Class: Graphomaton

Inherits:
Object
  • Object
show all
Defined in:
lib/graphomaton.rb,
lib/graphomaton/cli.rb,
lib/graphomaton/model.rb,
lib/graphomaton/errors.rb,
lib/graphomaton/version.rb,
lib/graphomaton/exporters.rb,
lib/graphomaton/cli/config.rb,
lib/graphomaton/url_policy.rb,
lib/graphomaton/atomic_file.rb,
lib/graphomaton/input_policy.rb,
lib/graphomaton/exporters/dot.rb,
lib/graphomaton/exporters/pdf.rb,
lib/graphomaton/exporters/png.rb,
lib/graphomaton/exporters/svg.rb,
lib/graphomaton/exporters/webp.rb,
lib/graphomaton/process_runner.rb,
lib/graphomaton/exporter_registry.rb,
lib/graphomaton/exporters/mermaid.rb,
lib/graphomaton/layout/force_tree.rb,
lib/graphomaton/exporters/plantuml.rb,
lib/graphomaton/identifier_allocator.rb,
sig/graphomaton.rbs

Defined Under Namespace

Modules: ExporterCapabilities, ExporterIntrospection, Exporters, Layout Classes: AtomicFile, CLI, ConversionError, Diagnostic, Error, ExportError, ExporterRegistry, IdentifierAllocator, InputPolicy, Label, LayoutError, ParseError, ProcessRunner, RenderOptions, RenderResult, SecurityError, State, SvgOptions, Theme, Transition, UrlPolicy, ValidationError

Constant Summary collapse

STATE_RADIUS =
40
DEFAULT_STATE_RADIUS =
STATE_RADIUS
DEFAULT_PADDING =
80
DEFAULT_NODE_SPACING =
120
DEFAULT_RANK_SPACING =
120
DEFAULT_FORCE_ITERATIONS =
120
DEFAULT_GRAPHVIZ_COMMAND =
'dot'
DEFAULT_PRESERVE_MANUAL_POSITIONS =
true
DEFAULT_FIT =
:none
LAYOUT_OPTIONS =
i[linear circle grid layered bfs force graphviz dot manual].freeze
DIRECTION_OPTIONS =
i[lr tb rl bt].freeze
FIT_OPTIONS =
i[none contain cover].freeze
STATE_KIND_OPTIONS =
i[normal choice fork join].freeze
INITIAL_POSITION_OPTIONS =
i[auto start].freeze
FINAL_POSITION_OPTIONS =
i[auto end].freeze
FORMAT_OPTIONS =
i[svg png pdf webp html mermaid mmd dot plantuml puml].freeze
FORMAT_ALIASES =
{
  mmd: :mermaid,
  puml: :plantuml
}.freeze
ALL_EXPORT_CAPABILITIES =
i[
  state_style transition_style url state_tooltip transition_tooltip group parent pseudostate bundle line_style
].freeze
RASTER_EXPORT_CAPABILITIES =
(ALL_EXPORT_CAPABILITIES - i[url state_tooltip transition_tooltip]).freeze
EXPORTERS =
ExporterRegistry.new.tap do |registry|
  registry.register(:svg, extensions: %w[svg], capabilities: ALL_EXPORT_CAPABILITIES) { Exporters::Svg }
  registry.register(:png, extensions: %w[png], binary: true, capabilities: RASTER_EXPORT_CAPABILITIES) { Exporters::Png }
  registry.register(:pdf, extensions: %w[pdf], binary: true, capabilities: RASTER_EXPORT_CAPABILITIES) { Exporters::Pdf }
  registry.register(:webp, extensions: %w[webp], binary: true, capabilities: RASTER_EXPORT_CAPABILITIES) { Exporters::Webp }
  registry.register(:html, extensions: %w[html], capabilities: i[group parent pseudostate]) { Exporters::Mermaid }
  registry.register(:mermaid, aliases: i[mmd], extensions: %w[mermaid mmd], capabilities: i[group parent pseudostate]) { Exporters::Mermaid }
  registry.register(:dot, aliases: i[gv], extensions: %w[dot gv], capabilities: i[url state_tooltip transition_tooltip group pseudostate bundle line_style]) { Exporters::Dot }
  registry.register(:plantuml, aliases: i[puml], extensions: %w[plantuml puml], capabilities: i[group parent pseudostate]) { Exporters::Plantuml }
end
DEFAULT_INITIAL_POSITION =
:auto
DEFAULT_FINAL_POSITION =
:auto
DEFAULT_EPSILON_LABEL =
"\u03b5"
DEFAULT_MAX_INPUT_BYTES =
10 * 1024 * 1024
DEFAULT_MAX_STATES =
10_000
DEFAULT_MAX_TRANSITIONS =
100_000
DEFAULT_MAX_METADATA_DEPTH =
64
DEFAULT_MAX_LABEL_LENGTH =
64 * 1024
DEFAULT_MAX_GROUP_DEPTH =
64
DEFAULT_MAX_CANVAS_AREA =
100_000_000
DEFAULT_MAX_CANVAS_DIMENSION =
100_000
DEFAULT_MAX_LAYOUT_ITERATIONS =
10_000
FORCE_TREE_THRESHOLD =
128
VALIDATION_MODES =
i[deferred strict].freeze
VALIDATION_PROFILES =
i[references fsm_semantics dfa].freeze
UNSET =
Object.new.freeze
EMPTY_TRANSITIONS =
[].freeze
VERSION =

Returns:

  • (String)
'1.2.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(validation: :deferred) ⇒ Graphomaton

Returns a new instance of Graphomaton.

Parameters:

  • validation: (Symbol) (defaults to: :deferred)


577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/graphomaton.rb', line 577

def initialize(validation: :deferred)
  @validation_mode = validation.to_sym
  unless VALIDATION_MODES.include?(@validation_mode)
    raise ArgumentError, "Unknown validation mode: #{validation.inspect}. Available modes: #{VALIDATION_MODES.join(', ')}"
  end

  @states = {}
  @transitions = []
  @initial_state = nil
  @final_states = []
  @final_state_set = Set.new
  @state_positions = {}
  @manual_states = {}
  @revision = 0
  @next_transition_id = 0
  @layout_cache = {}
end

Instance Attribute Details

#initial_state ⇒ Object (readonly)

Returns the value of attribute initial_state.

Returns:

  • (Object)


247
248
249
# File 'lib/graphomaton.rb', line 247

def initial_state
  @initial_state
end

#revision ⇒ Integer (readonly)

Returns the value of attribute revision.

Returns:

  • (Integer)


247
248
249
# File 'lib/graphomaton.rb', line 247

def revision
  @revision
end

Class Method Details

.exporter_capabilities(format) ⇒ Object



265
266
267
# File 'lib/graphomaton.rb', line 265

def self.exporter_capabilities(format)
  EXPORTERS.fetch(format).capabilities
end

.from_hash(data = nil, max_states: DEFAULT_MAX_STATES, max_transitions: DEFAULT_MAX_TRANSITIONS, max_metadata_depth: DEFAULT_MAX_METADATA_DEPTH, max_label_length: DEFAULT_MAX_LABEL_LENGTH, max_group_depth: DEFAULT_MAX_GROUP_DEPTH, strict_schema: true, **input) ⇒ Graphomaton

Parameters:

  • data (Hash[untyped, untyped]) (defaults to: nil)
  • (Object)

Returns:

Raises:

  • (ArgumentError)


269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/graphomaton.rb', line 269

def self.from_hash(data = nil, max_states: DEFAULT_MAX_STATES, max_transitions: DEFAULT_MAX_TRANSITIONS,
                   max_metadata_depth: , max_label_length: DEFAULT_MAX_LABEL_LENGTH,
                   max_group_depth: DEFAULT_MAX_GROUP_DEPTH, strict_schema: true, **input)
  if data.nil? && !input.empty?
    data = input
  elsif !input.empty?
    raise ArgumentError, "Unknown input keywords: #{input.keys.join(', ')}"
  end
  raise ArgumentError, 'Graphomaton input must be a Hash' unless data.is_a?(Hash)

  enforce_positive_limit(, 'max_metadata_depth')
  enforce_positive_limit(max_label_length, 'max_label_length')
  enforce_positive_limit(max_group_depth, 'max_group_depth')

  InputPolicy.known_keys!(data, InputPolicy::TOP_LEVEL_KEYS, context: 'top-level', strict: strict_schema)
  ensure_alias_values_agree!(data, :initial, :initial_state, context: 'top-level initial state')
  ensure_alias_values_agree!(data, :final, :final_states, context: 'top-level final states')
  version = input_value(data, :version)
  raise ArgumentError, "Unsupported Graphomaton schema version: #{version.inspect}" unless version.nil? || version == 1

  automaton = new
  states = state_inputs(input_value(data, :states))
  transitions = transition_inputs(input_value(data, :transitions))
  enforce_collection_limit(states, max_states, 'states')
  enforce_collection_limit(transitions, max_transitions, 'transitions')

  states.each do |state|
    add_state_from_input(
      automaton,
      state,
      max_metadata_depth: ,
      max_label_length: max_label_length,
      strict_schema: strict_schema
    )
  end

  initial_state = input_value(data, :initial, :initial_state)
  assign_initial_from_input(automaton, initial_state) unless initial_state.nil?

  Array(input_value(data, :final, :final_states)).each do |state|
    automaton.add_final(state)
  end

  transitions.each do |transition|
    add_transition_from_input(
      automaton,
      transition,
      max_metadata_depth: ,
      max_label_length: max_label_length,
      strict_schema: strict_schema
    )
  end

  enforce_group_depth(automaton, max_group_depth)

  automaton
end

.from_json(source, max_input_bytes: DEFAULT_MAX_INPUT_BYTES, **limits) ⇒ Graphomaton

Parameters:

  • source (String, _Reader)
  • (Object)

Returns:



327
328
329
# File 'lib/graphomaton.rb', line 327

def self.from_json(source, max_input_bytes: DEFAULT_MAX_INPUT_BYTES, **limits)
  from_hash(JSON.parse(bounded_source(source, max_input_bytes)), **limits)
end

.from_yaml(source, aliases: false, max_input_bytes: DEFAULT_MAX_INPUT_BYTES, **limits) ⇒ Graphomaton

Parameters:

  • source (String, _Reader)
  • (Object)

Returns:



331
332
333
334
# File 'lib/graphomaton.rb', line 331

def self.from_yaml(source, aliases: false, max_input_bytes: DEFAULT_MAX_INPUT_BYTES, **limits)
  yaml = YAML.safe_load(bounded_source(source, max_input_bytes), permitted_classes: [Symbol], aliases: aliases)
  from_hash(yaml || {}, **limits)
end

.pdf_available?(converter: Exporters::Pdf::DEFAULT_CONVERTER) ⇒ Boolean

Returns:

  • (Boolean)


253
254
255
# File 'lib/graphomaton.rb', line 253

def self.pdf_available?(converter: Exporters::Pdf::DEFAULT_CONVERTER)
  Exporters::Pdf.available?(converter: converter)
end

.png_available?(converter: Exporters::Png::DEFAULT_CONVERTER) ⇒ Boolean

Returns:

  • (Boolean)


249
250
251
# File 'lib/graphomaton.rb', line 249

def self.png_available?(converter: Exporters::Png::DEFAULT_CONVERTER)
  Exporters::Png.available?(converter: converter)
end

.register_exporter(name, arg1) ⇒ Object .register_exporter(name, arg1) ⇒ Object

Overloads:

  • .register_exporter(name, arg1) ⇒ Object

    Parameters:

    • name (Symbol, String)
    • arg1 (Object)

    Returns:

    • (Object)
  • .register_exporter(name, arg1) ⇒ Object

    Parameters:

    • name (Symbol, String)
    • arg1 (Object)

    Returns:

    • (Object)

Yields:

Yield Returns:

  • (Object)


261
262
263
# File 'lib/graphomaton.rb', line 261

def self.register_exporter(name, **options, &loader)
  EXPORTERS.register(name, **options, &loader)
end

.theme_from_hash(data) ⇒ Object

Raises:

  • (ArgumentError)


336
337
338
339
340
341
# File 'lib/graphomaton.rb', line 336

def self.theme_from_hash(data)
  raise ArgumentError, 'Graphomaton theme input must be a Hash' unless data.is_a?(Hash)

  theme = input_value(data, :theme) || data
  Theme.normalize(theme, context: 'Graphomaton theme')
end

.theme_from_json(source, max_input_bytes: DEFAULT_MAX_INPUT_BYTES) ⇒ Object



343
344
345
# File 'lib/graphomaton.rb', line 343

def self.theme_from_json(source, max_input_bytes: DEFAULT_MAX_INPUT_BYTES)
  theme_from_hash(JSON.parse(bounded_source(source, max_input_bytes)))
end

.theme_from_yaml(source, aliases: false, max_input_bytes: DEFAULT_MAX_INPUT_BYTES) ⇒ Object



347
348
349
350
# File 'lib/graphomaton.rb', line 347

def self.theme_from_yaml(source, aliases: false, max_input_bytes: DEFAULT_MAX_INPUT_BYTES)
  yaml = YAML.safe_load(bounded_source(source, max_input_bytes), permitted_classes: [Symbol], aliases: aliases)
  theme_from_hash(yaml || {})
end

.validate_canvas_dimensions!(width, height) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/graphomaton.rb', line 232

def self.validate_canvas_dimensions!(width, height)
  { width: width, height: height }.each do |name, value|
    unless value.is_a?(Numeric) && value.real? && value.to_f.finite? && value.positive?
      raise ArgumentError, "#{name} must be a positive finite number"
    end
  end
  if width.to_f * height.to_f > DEFAULT_MAX_CANVAS_AREA
    raise ArgumentError, "canvas area exceeds max_canvas_area (#{DEFAULT_MAX_CANVAS_AREA})"
  end
  if width.to_f > DEFAULT_MAX_CANVAS_DIMENSION || height.to_f > DEFAULT_MAX_CANVAS_DIMENSION
    raise ArgumentError, "canvas dimension exceeds max_canvas_dimension (#{DEFAULT_MAX_CANVAS_DIMENSION})"
  end

  true
end

.webp_available?(converter: Exporters::Webp::DEFAULT_CONVERTER) ⇒ Boolean

Returns:

  • (Boolean)


257
258
259
# File 'lib/graphomaton.rb', line 257

def self.webp_available?(converter: Exporters::Webp::DEFAULT_CONVERTER)
  Exporters::Webp.available?(converter: converter)
end

Instance Method Details

#==(other) ⇒ Object



2015
2016
2017
# File 'lib/graphomaton.rb', line 2015

def ==(other)
  other.is_a?(Graphomaton) && to_h == other.to_h
end

#add_final(state) ⇒ self

Parameters:

  • state (Object)

Returns:

  • (self)

Raises:



856
857
858
859
860
861
862
863
864
865
866
# File 'lib/graphomaton.rb', line 856

def add_final(state)
  InputPolicy.identifier!(state, context: 'Final state id')
  raise ValidationError, "Final state #{state.inspect} is not defined" if @validation_mode == :strict && !@states.key?(state)
  return self if @final_state_set.include?(state)

  stable_state = immutable_copy(state)
  @final_states << stable_state
  @final_state_set << stable_state
  graph_changed!
  self
end

#add_state(name, x = nil, y = nil, label: nil, style: nil, metadata: nil, shape: nil, kind: nil, max_metadata_depth: DEFAULT_MAX_METADATA_DEPTH, max_label_length: DEFAULT_MAX_LABEL_LENGTH) ⇒ self

Parameters:

  • name (Object)
  • x (Numeric, nil) (defaults to: nil)
  • y (Numeric, nil) (defaults to: nil)
  • (Object)

Returns:

  • (self)

Raises:

  • (ArgumentError)


615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/graphomaton.rb', line 615

def add_state(name, x = nil, y = nil, label: nil, style: nil, metadata: nil, shape: nil, kind: nil,
              max_metadata_depth: , max_label_length: DEFAULT_MAX_LABEL_LENGTH)
  InputPolicy.identifier!(name, context: 'State id')
  label = label.to_s if label.is_a?(Label)
  InputPolicy.label!(label, context: "State #{name.inspect} label", max_bytes: max_label_length)
  InputPolicy.mapping!(style, context: "State #{name.inspect} style")
  InputPolicy.mapping!(, context: "State #{name.inspect} metadata")
  if 
    InputPolicy.nested_depth!(
      ,
      maximum: ,
      context: "State #{name.inspect} metadata",
      max_string_bytes: max_label_length
    )
  end
  raise ArgumentError, "Duplicate state id: #{name.inspect}" if @states.key?(name)
  if x.nil? != y.nil?
    raise ArgumentError, 'State coordinates require both x and y'
  end
  unless x.nil?
    validate_finite_number!(x, 'state x coordinate')
    validate_finite_number!(y, 'state y coordinate')
  end

  stable_name = immutable_copy(name)
  @manual_states[stable_name] = !x.nil? && !y.nil?
  @states[stable_name] = State.new(
    id: stable_name,
    x: x,
    y: y,
    label: immutable_copy(label),
    style: immutable_copy(style),
    metadata: immutable_copy(),
    shape: immutable_copy(shape),
    kind: resolve_state_kind(kind)
  )
  graph_changed!
  self
end

#add_transition(from, to, label, style: nil, metadata: nil, line_style: nil, epsilon_label: DEFAULT_EPSILON_LABEL, sort_labels: false, max_metadata_depth: DEFAULT_MAX_METADATA_DEPTH, max_label_length: DEFAULT_MAX_LABEL_LENGTH) ⇒ self

Parameters:

  • from (Object)
  • to (Object)
  • label (Object)
  • (Object)

Returns:

  • (self)

Raises:

  • (ArgumentError)


745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/graphomaton.rb', line 745

def add_transition(from, to, label, style: nil, metadata: nil, line_style: nil,
                   epsilon_label: DEFAULT_EPSILON_LABEL, sort_labels: false,
                   max_metadata_depth: , max_label_length: DEFAULT_MAX_LABEL_LENGTH)
  InputPolicy.identifier!(from, context: 'Transition source')
  InputPolicy.identifier!(to, context: 'Transition target')
  raise ArgumentError, 'Transition label cannot be nil' if label.nil?
  labels = label.is_a?(Array) ? label : [label]
  raise ArgumentError, 'Transition labels cannot be empty' if labels.empty?
  raise ArgumentError, 'Transition labels cannot contain nil' if labels.any?(&:nil?)
  labels.each do |item|
    InputPolicy.label!(item, context: 'Transition label', max_bytes: max_label_length)
  end
  InputPolicy.mapping!(style, context: 'Transition style')
  InputPolicy.mapping!(, context: 'Transition metadata')
  if 
    InputPolicy.nested_depth!(
      ,
      maximum: ,
      context: 'Transition metadata',
      max_string_bytes: max_label_length
    )
  end
  if @validation_mode == :strict
    raise ValidationError, "Transition source #{from.inspect} is not defined" unless @states.key?(from)
    raise ValidationError, "Transition target #{to.inspect} is not defined" unless @states.key?(to)
  end
  @next_transition_id += 1
  @transitions << Transition.new(
    id: @next_transition_id,
    from: immutable_copy(from),
    to: immutable_copy(to),
    label: immutable_copy(normalize_transition_label(label, epsilon_label: epsilon_label, sort_labels: sort_labels)),
    style: immutable_copy(style),
    metadata: immutable_copy(),
    line_style: immutable_copy(line_style)
  )
  graph_changed!
  self
end

#analysis_warnings ⇒ Object



896
897
898
899
900
# File 'lib/graphomaton.rb', line 896

def analysis_warnings
  validation_diagnostics(profile: :fsm_semantics)
    .select { |diagnostic| diagnostic.severity == :warning }
    .map(&:message)
end

#auto_layout(width = 800, height = 600, layout: :linear, direction: :lr, state_radius: DEFAULT_STATE_RADIUS, padding: DEFAULT_PADDING, node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING, force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil, graphviz_command: DEFAULT_GRAPHVIZ_COMMAND, initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION, preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS, fit: DEFAULT_FIT) ⇒ Object



1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
# File 'lib/graphomaton.rb', line 1264

def auto_layout(width = 800, height = 600, layout: :linear, direction: :lr,
               state_radius: DEFAULT_STATE_RADIUS, padding: DEFAULT_PADDING,
               node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING,
               force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil,
               graphviz_command: DEFAULT_GRAPHVIZ_COMMAND,
               initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION,
               preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS,
               fit: DEFAULT_FIT)
  return self if @states.empty?

  resolved_layout = resolve_layout(layout)
  effective_preserve_manual_positions = preserve_manual_positions || resolved_layout == :manual

  layout_positions(
    width,
    height,
    layout: resolved_layout,
    direction: direction,
    state_radius: state_radius,
    padding: padding,
    node_spacing: node_spacing,
    rank_spacing: rank_spacing,
    force_iterations: force_iterations,
    layout_seed: layout_seed,
    graphviz_command: graphviz_command,
    initial_position: initial_position,
    final_position: final_position,
    preserve_manual_positions: effective_preserve_manual_positions,
    fit: fit
  ).each do |name, position|
    state = @states[name]
    next if effective_preserve_manual_positions && manual_position?(name) && resolve_fit(fit) == :none

    @states[name] = State.new(
      id: state.id,
      x: position[:x],
      y: position[:y],
      label: state.label,
      style: state.style,
      metadata: state.,
      shape: state.shape,
      kind: state.kind
    )
  end
  graph_changed!
  self
end

#bottom_sccs ⇒ Array[Array[untyped]]

Returns:

  • (Array[Array[untyped]])


1007
1008
1009
1010
1011
1012
1013
# File 'lib/graphomaton.rb', line 1007

def bottom_sccs
  ensure_analysis_index!
  strongly_connected_components.select do |component|
    members = component.to_set
    component.all? { |state| @outgoing_by_state[state].all? { |transition| members.include?(transition.to) } }
  end
end

#clear_initial ⇒ self

Returns:

  • (self)


848
849
850
851
852
853
854
# File 'lib/graphomaton.rb', line 848

def clear_initial
  return self if @initial_state.nil?

  @initial_state = nil
  graph_changed!
  self
end

#count_parallel_transitions(from, to) ⇒ Object



1956
1957
1958
1959
# File 'lib/graphomaton.rb', line 1956

def count_parallel_transitions(from, to)
  ensure_analysis_index!
  @transitions_by_undirected_pair.fetch(Set[from, to].freeze, EMPTY_TRANSITIONS).size
end

#dead_states ⇒ Object



977
978
979
980
981
982
# File 'lib/graphomaton.rb', line 977

def dead_states
  reaching_final = states_reaching_final
  return [] if reaching_final.empty?

  @states.keys - reaching_final
end

#final_states ⇒ Array[untyped]

Returns:

  • (Array[untyped])


603
604
605
# File 'lib/graphomaton.rb', line 603

def final_states
  immutable_snapshot(@final_states)
end

#get_transition_index(from, to, label) ⇒ Object



1961
1962
1963
1964
1965
# File 'lib/graphomaton.rb', line 1961

def get_transition_index(from, to, label)
  ensure_analysis_index!
  transitions = @transitions_by_undirected_pair.fetch(Set[from, to].freeze, EMPTY_TRANSITIONS)
  transitions.index { |transition| transition.from == from && transition.to == to && transition.label == label } || transitions.size
end

#graph_roots ⇒ Array[untyped]

Returns:

  • (Array[untyped])


940
941
942
943
# File 'lib/graphomaton.rb', line 940

def graph_roots
  ensure_analysis_index!
  ordered_state_names.select { |state| @incoming_by_state[state].empty? }
end

#incoming_by_state ⇒ Object



1972
1973
1974
1975
# File 'lib/graphomaton.rb', line 1972

def incoming_by_state
  ensure_analysis_index!
  @incoming_by_state.transform_values { |transitions| transitions.map(&:to_h).freeze }.freeze
end

#layout_diagnostics_for(positions, width, height, state_radius, x: 0, y: 0) ⇒ Object



1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'lib/graphomaton.rb', line 1093

def layout_diagnostics_for(positions, width, height, state_radius, x: 0, y: 0)
  radius = state_radius.to_f
  left = x.to_f
  top = y.to_f
  right = left + width.to_f
  bottom = top + height.to_f
  positions.each_with_object([]) do |(name, position), diagnostics|
    state_x = position[:x].to_f
    state_y = position[:y].to_f
    if state_x - radius < left || state_x + radius > right
      diagnostics << Diagnostic.new(
        code: 'state-clipped-horizontal',
        severity: :warning,
        path: ['states', name, 'x'],
        message: "State #{name.inspect} may be clipped horizontally",
        hint: 'Increase the canvas width or use fit: :contain'
      )
    end
    if state_y - radius < top || state_y + radius > bottom
      diagnostics << Diagnostic.new(
        code: 'state-clipped-vertical',
        severity: :warning,
        path: ['states', name, 'y'],
        message: "State #{name.inspect} may be clipped vertically",
        hint: 'Increase the canvas height or use fit: :contain'
      )
    end
  end.freeze
end

#layout_positions(width = 800, height = 600, layout: :linear, direction: :lr, state_radius: DEFAULT_STATE_RADIUS, padding: DEFAULT_PADDING, node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING, force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil, graphviz_command: DEFAULT_GRAPHVIZ_COMMAND, initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION, preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS, fit: DEFAULT_FIT) ⇒ Object



1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
# File 'lib/graphomaton.rb', line 1123

def layout_positions(width = 800, height = 600, layout: :linear, direction: :lr,
                    state_radius: DEFAULT_STATE_RADIUS, padding: DEFAULT_PADDING,
                    node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING,
                    force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil,
                    graphviz_command: DEFAULT_GRAPHVIZ_COMMAND,
                    initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION,
                    preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS,
                    fit: DEFAULT_FIT)
  self.class.validate_canvas_dimensions!(width, height)
  validate_finite_number!(state_radius, 'state_radius', positive: true)
  validate_finite_number!(padding, 'padding', nonnegative: true)
  validate_finite_number!(node_spacing, 'node_spacing', nonnegative: true)
  validate_finite_number!(rank_spacing, 'rank_spacing', nonnegative: true)
  unless force_iterations.is_a?(Integer) && force_iterations >= 0
    raise ArgumentError, 'force_iterations must be a non-negative Integer'
  end
  if force_iterations > DEFAULT_MAX_LAYOUT_ITERATIONS
    raise ArgumentError, "force_iterations exceeds max_layout_iterations (#{DEFAULT_MAX_LAYOUT_ITERATIONS})"
  end
  unless layout_seed.nil? || layout_seed.is_a?(Integer)
    raise ArgumentError, 'layout_seed must be an Integer or nil'
  end

  return {} if @states.empty?

  resolved_layout = resolve_layout(layout)
  resolved_direction = resolve_direction(direction)
  resolved_fit = resolve_fit(fit)
  resolved_initial_position = resolve_initial_position(initial_position)
  resolved_final_position = resolve_final_position(final_position)
  resolved_padding = [padding.to_f, 0].max
  resolved_node_spacing = [node_spacing.to_f, (state_radius * 2.5)].max
  resolved_rank_spacing = [rank_spacing.to_f, (state_radius * 2.5)].max
  effective_preserve_manual_positions = preserve_manual_positions || resolved_layout == :manual
  cache_key = [
    width.to_f, height.to_f, resolved_layout, resolved_direction, state_radius.to_f, resolved_padding,
    resolved_node_spacing, resolved_rank_spacing, force_iterations, layout_seed,
    Array(graphviz_command), resolved_initial_position, resolved_final_position,
    effective_preserve_manual_positions, resolved_fit
  ].freeze
  if (cached = @layout_cache[cache_key])
    positions = deep_copy(cached)
    @state_positions = positions
    return positions
  end
  ordered_states = ordered_state_names

  manual_positions = {}
  auto_states = []

  ordered_states.each do |name|
    state = @states[name]
    if effective_preserve_manual_positions && manual_position?(name)
      validate_finite_number!(state[:x], "state #{name.inspect} x coordinate")
      validate_finite_number!(state[:y], "state #{name.inspect} y coordinate")
      manual_positions[name] = { x: state[:x], y: state[:y] }
    else
      auto_states << name
    end
  end

  auto_states = arrange_auto_states(
    auto_states,
    initial_position: resolved_initial_position,
    final_position: resolved_final_position
  )

  auto_positions = case resolved_layout
                  when :linear
                    layout_linear_positions(auto_states, width, height, resolved_direction, state_radius,
                                           resolved_padding, resolved_node_spacing)
                  when :circle
                    layout_circle_positions(auto_states, width, height, resolved_direction, state_radius, resolved_padding)
                  when :grid
                    layout_grid_positions(auto_states, width, height, resolved_direction, state_radius,
                                         resolved_padding, resolved_node_spacing)
                  when :layered, :bfs
                    layout_layered_positions(auto_states, width, height, resolved_direction, state_radius,
                                            resolved_padding, resolved_node_spacing, resolved_rank_spacing,
                                            final_position: resolved_final_position)
                  when :manual
                    if auto_states.empty?
                      {}
                    else
                      raise ArgumentError, "Manual layout requires explicit coordinates for: #{auto_states.join(', ')}"
                    end
                  when :force
                    layout_force_positions(
                      auto_states,
                      width,
                      height,
                      resolved_direction,
                      state_radius,
                      resolved_padding,
                      resolved_node_spacing,
                      force_iterations,
                      layout_seed,
                      fixed_positions: manual_positions
                    )
                  when :graphviz, :dot
                    layout_graphviz_positions(
                      auto_states,
                      width,
                      height,
                      resolved_direction,
                      state_radius,
                      resolved_padding,
                      command: graphviz_command
                    )
                  else
                    raise ArgumentError, "Unknown SVG layout: #{layout.inspect}. Available layouts: #{LAYOUT_OPTIONS.join(', ')}"
                  end

  if resolved_layout != :force
    auto_positions = avoid_fixed_position_collisions(
      auto_positions,
      manual_positions,
      width,
      height,
      state_radius,
      resolved_padding,
      resolved_node_spacing,
      resolved_direction
    )
  end
  positions = manual_positions.merge(auto_positions)
  positions = fit_positions(positions, width, height, state_radius, resolved_padding, resolved_fit) unless resolved_fit == :none
  @state_positions = positions
  @layout_cache.shift if @layout_cache.size >= 16
  @layout_cache[cache_key] = immutable_copy(positions)
  positions
end

#layout_warnings(width = 800, height = 600, layout: :linear, direction: :lr, state_radius: DEFAULT_STATE_RADIUS, padding: DEFAULT_PADDING, node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING, force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil, graphviz_command: DEFAULT_GRAPHVIZ_COMMAND, initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION, preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS, fit: DEFAULT_FIT) ⇒ Object



1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
# File 'lib/graphomaton.rb', line 1064

def layout_warnings(width = 800, height = 600, layout: :linear, direction: :lr,
                    state_radius: DEFAULT_STATE_RADIUS, padding: DEFAULT_PADDING,
                    node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING,
                    force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil,
                    graphviz_command: DEFAULT_GRAPHVIZ_COMMAND,
                    initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION,
                    preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS,
                    fit: DEFAULT_FIT)
  positions = layout_positions(
    width,
    height,
    layout: layout,
    direction: direction,
    state_radius: state_radius,
    padding: padding,
    node_spacing: node_spacing,
    rank_spacing: rank_spacing,
    force_iterations: force_iterations,
    layout_seed: layout_seed,
    graphviz_command: graphviz_command,
    initial_position: initial_position,
    final_position: final_position,
    preserve_manual_positions: preserve_manual_positions,
    fit: fit
  )

  layout_diagnostics_for(positions, width, height, state_radius).map(&:message)
end

#live_states ⇒ Object



984
985
986
# File 'lib/graphomaton.rb', line 984

def live_states
  states_reaching_final
end

#outgoing_by_state ⇒ Object



1967
1968
1969
1970
# File 'lib/graphomaton.rb', line 1967

def outgoing_by_state
  ensure_analysis_index!
  @outgoing_by_state.transform_values { |transitions| transitions.map(&:to_h).freeze }.freeze
end

#reachable_from(state) ⇒ Array[untyped]

Parameters:

  • state (Object)

Returns:

  • (Array[untyped])

Raises:

  • (ArgumentError)


917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
# File 'lib/graphomaton.rb', line 917

def reachable_from(state)
  raise ArgumentError, "State is not defined: #{state.inspect}" unless @states.key?(state)

  ensure_analysis_index!
  visited = { state => true }
  queue = [state]
  head = 0
  while head < queue.length
    current = queue[head]
    head += 1
    @outgoing_by_state[current].each do |transition|
      target = transition.to
      next if visited[target]

      visited[target] = true
      queue << target
    end
  end
  ordered_state_names.select { |name| visited[name] }
end

#reachable_states ⇒ Array[untyped] Also known as: reachable_from_initial

Returns:

  • (Array[untyped])


913
914
915
# File 'lib/graphomaton.rb', line 913

def reachable_states
  layered_distances.keys
end

#remove_final(state) ⇒ self

Parameters:

  • state (Object)

Returns:

  • (self)


868
869
870
871
872
873
874
# File 'lib/graphomaton.rb', line 868

def remove_final(state)
  return self unless @final_state_set.delete?(state)

  @final_states.delete(state)
  graph_changed!
  self
end

#remove_state(name, cascade: false) ⇒ self

Parameters:

  • name (Object)
  • cascade: (Boolean) (defaults to: false)

Returns:

  • (self)

Raises:

  • (ArgumentError)


725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'lib/graphomaton.rb', line 725

def remove_state(name, cascade: false)
  raise ArgumentError, "State is not defined: #{name.inspect}" unless @states.key?(name)

  connected = @transitions.select { |transition| transition.from == name || transition.to == name }
  if connected.any? && !cascade
    raise ArgumentError, "State #{name.inspect} has transitions; pass cascade: true to remove them"
  end

  @states.delete(name)
  @manual_states.delete(name)
  @state_positions.delete(name)
  @transitions -= connected
  @initial_state = nil if @initial_state == name
  if @final_state_set.delete?(name)
    @final_states.delete(name)
  end
  graph_changed!
  self
end

#remove_transition(identifier) ⇒ self

Parameters:

  • identifier (Object)

Returns:

  • (self)


830
831
832
833
834
# File 'lib/graphomaton.rb', line 830

def remove_transition(identifier)
  @transitions.delete_at(transition_index(identifier))
  graph_changed!
  self
end

#render(format: :svg, width: 800, height: 600, strict_semantics: false, **options) ⇒ String

Parameters:

  • format: (Symbol, String) (defaults to: :svg)
  • width: (Numeric) (defaults to: 800)
  • height: (Numeric) (defaults to: 600)
  • strict_semantics: (Boolean) (defaults to: false)
  • (Object)

Returns:

  • (String)


2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
# File 'lib/graphomaton.rb', line 2041

def render(format: :svg, width: 800, height: 600, strict_semantics: false, **options)
  resolved_format = resolve_format(format)
  losses = semantic_diagnostics(resolved_format, **options)
  if strict_semantics && losses.any?
    raise ExportError, losses.map(&:message).join("\n")
  end

  case resolved_format
  when :svg
    to_svg(width, height, **options)
  when :png
    to_png(width, height, **options)
  when :pdf
    to_pdf(width, height, **options)
  when :webp
    to_webp(width, height, **options)
  when :html
    to_html(**options)
  when :mermaid
    to_mermaid(**options)
  when :dot
    to_dot(**options)
  when :plantuml
    to_plantuml(**options)
  else
    exporter = self.class::EXPORTERS.fetch(resolved_format).exporter.new(self)
    exporter.export(width, height, **options)
  end
end

#render_result(format: :svg, width: 800, height: 600, strict_semantics: false, **options) ⇒ RenderResult

Parameters:

  • format: (Symbol, String) (defaults to: :svg)
  • width: (Numeric) (defaults to: 800)
  • height: (Numeric) (defaults to: 600)
  • strict_semantics: (Boolean) (defaults to: false)
  • (Object)

Returns:



2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
# File 'lib/graphomaton.rb', line 2077

def render_result(format: :svg, width: 800, height: 600, strict_semantics: false, **options)
  resolved = resolve_format(format)
  losses = semantic_diagnostics(resolved, **options)
  if strict_semantics && losses.any?
    raise ExportError, losses.map(&:message).join("\n")
  end

  exporter = case resolved
             when :svg then Exporters::Svg
             when :png then Exporters::Png
             when :pdf then Exporters::Pdf
             when :webp then Exporters::Webp
             end
  if exporter
    result = exporter.new(self).export_result(width, height, **options)
    return result if losses.empty?

    return RenderResult.new(
      output: result.output,
      diagnostics: (losses + result.diagnostics).freeze,
      bounds: result.bounds,
      layout: result.layout
    )
  end

  output = render(
    format: resolved,
    width: width,
    height: height,
    strict_semantics: strict_semantics,
    **options
  )
  RenderResult.new(
    output: output,
    diagnostics: losses,
    bounds: nil,
    layout: nil
  )
end

#render_with(options) ⇒ String

Parameters:

Returns:

  • (String)

Raises:

  • (ArgumentError)


2071
2072
2073
2074
2075
# File 'lib/graphomaton.rb', line 2071

def render_with(options)
  raise ArgumentError, 'options must be a Graphomaton::RenderOptions' unless options.is_a?(RenderOptions)

  render(format: options.format, width: options.width, height: options.height, **options.options)
end

#save(filename, format: nil, width: 800, height: 600, **options) ⇒ Object



2117
2118
2119
2120
2121
# File 'lib/graphomaton.rb', line 2117

def save(filename, format: nil, width: 800, height: 600, **options)
  resolved_format = resolve_format(format || File.extname(filename).delete_prefix('.'))
  output = render(format: resolved_format, width: width, height: height, **options)
  AtomicFile.write(filename, output, binary: self.class::EXPORTERS.fetch(resolved_format).binary)
end

#save_dot(filename, direction: Exporters::Dot::DEFAULT_DIRECTION, theme: nil, rank_constraints: Exporters::Dot::DEFAULT_RANK_CONSTRAINTS) ⇒ Object



2480
2481
2482
2483
# File 'lib/graphomaton.rb', line 2480

def save_dot(filename, direction: Exporters::Dot::DEFAULT_DIRECTION, theme: nil,
             rank_constraints: Exporters::Dot::DEFAULT_RANK_CONSTRAINTS)
  AtomicFile.write(filename, to_dot(direction: direction, theme: theme, rank_constraints: rank_constraints))
end

#save_html(filename, direction: Exporters::Mermaid::DEFAULT_DIRECTION, theme: Exporters::Mermaid::DEFAULT_THEME, cdn: Exporters::Mermaid::DEFAULT_CDN, inline_mermaid: false, offline: false, title: nil, lang: Exporters::Mermaid::DEFAULT_LANG, show_source: Exporters::Mermaid::DEFAULT_SHOW_SOURCE, pan_zoom: Exporters::Mermaid::DEFAULT_PAN_ZOOM, mathjax: Exporters::Mermaid::DEFAULT_MATHJAX, mathjax_cdn: Exporters::Mermaid::DEFAULT_MATHJAX_CDN, inline_mathjax: false, self_contained: false, nonce: nil, csp: false, mermaid_sha256: nil, mathjax_sha256: nil, notes: Exporters::Mermaid::DEFAULT_NOTES, class_defs: Exporters::Mermaid::DEFAULT_CLASS_DEFS) ⇒ Object



2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
# File 'lib/graphomaton.rb', line 2439

def save_html(filename, direction: Exporters::Mermaid::DEFAULT_DIRECTION, theme: Exporters::Mermaid::DEFAULT_THEME,
              cdn: Exporters::Mermaid::DEFAULT_CDN, inline_mermaid: false, offline: false, title: nil,
              lang: Exporters::Mermaid::DEFAULT_LANG, show_source: Exporters::Mermaid::DEFAULT_SHOW_SOURCE,
              pan_zoom: Exporters::Mermaid::DEFAULT_PAN_ZOOM,
              mathjax: Exporters::Mermaid::DEFAULT_MATHJAX,
              mathjax_cdn: Exporters::Mermaid::DEFAULT_MATHJAX_CDN,
              inline_mathjax: false, self_contained: false, nonce: nil, csp: false,
              mermaid_sha256: nil, mathjax_sha256: nil,
              notes: Exporters::Mermaid::DEFAULT_NOTES,
              class_defs: Exporters::Mermaid::DEFAULT_CLASS_DEFS)
  AtomicFile.write(
    filename,
    to_html(
      direction: direction,
      theme: theme,
      cdn: cdn,
      inline_mermaid: inline_mermaid,
      offline: offline,
      title: title,
      lang: lang,
      show_source: show_source,
      pan_zoom: pan_zoom,
      mathjax: mathjax,
      mathjax_cdn: mathjax_cdn,
      inline_mathjax: inline_mathjax,
      self_contained: self_contained,
      nonce: nonce,
      csp: csp,
      mermaid_sha256: mermaid_sha256,
      mathjax_sha256: mathjax_sha256,
      notes: notes,
      class_defs: class_defs
    )
  )
end

#save_pdf(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, converter: Exporters::Pdf::DEFAULT_CONVERTER, **svg_options) ⇒ Object



2389
2390
2391
2392
# File 'lib/graphomaton.rb', line 2389

def save_pdf(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
             converter: Exporters::Pdf::DEFAULT_CONVERTER, **svg_options)
  AtomicFile.write(filename, to_pdf(width, height, theme: theme, converter: converter, **svg_options), binary: true)
end

#save_plantuml(filename, direction: Exporters::Plantuml::DEFAULT_DIRECTION, theme: nil, notes: Exporters::Plantuml::DEFAULT_NOTES) ⇒ Object



2490
2491
2492
2493
# File 'lib/graphomaton.rb', line 2490

def save_plantuml(filename, direction: Exporters::Plantuml::DEFAULT_DIRECTION, theme: nil,
                  notes: Exporters::Plantuml::DEFAULT_NOTES)
  AtomicFile.write(filename, to_plantuml(direction: direction, theme: theme, notes: notes))
end

#save_png(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, scale: Exporters::Png::DEFAULT_SCALE, converter: Exporters::Png::DEFAULT_CONVERTER, **svg_options) ⇒ Object



2379
2380
2381
2382
# File 'lib/graphomaton.rb', line 2379

def save_png(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
             scale: Exporters::Png::DEFAULT_SCALE, converter: Exporters::Png::DEFAULT_CONVERTER, **svg_options)
  AtomicFile.write(filename, to_png(width, height, theme: theme, scale: scale, converter: converter, **svg_options), binary: true)
end

#save_svg(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, layout: :linear, direction: :lr, responsive: false, state_radius: DEFAULT_STATE_RADIUS, auto_state_radius: Exporters::Svg::DEFAULT_AUTO_STATE_RADIUS, min_state_radius: Exporters::Svg::DEFAULT_MIN_STATE_RADIUS, max_state_radius: Exporters::Svg::DEFAULT_MAX_STATE_RADIUS, state_shape: Exporters::Svg::DEFAULT_STATE_SHAPE, state_stroke_width: Exporters::Svg::DEFAULT_STATE_STROKE_WIDTH, transition_stroke_width: Exporters::Svg::DEFAULT_TRANSITION_STROKE_WIDTH, padding: DEFAULT_PADDING, node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING, force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil, auto_size: false, graphviz_command: DEFAULT_GRAPHVIZ_COMMAND, auto_density_spacing: Exporters::Svg::DEFAULT_AUTO_DENSITY_SPACING, arrow_size: Exporters::Svg::DEFAULT_ARROW_SIZE, arrow_shape: Exporters::Svg::DEFAULT_ARROW_SHAPE, initial_arrow_length: Exporters::Svg::DEFAULT_INITIAL_ARROW_LENGTH, initial_arrow_label: Exporters::Svg::DEFAULT_INITIAL_ARROW_LABEL, final_arrow_length: Exporters::Svg::DEFAULT_FINAL_ARROW_LENGTH, final_arrow_label: Exporters::Svg::DEFAULT_FINAL_ARROW_LABEL, initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION, merge_parallel_transitions: true, wrap: Exporters::Svg::DEFAULT_WRAP, max_transition_label_width: Exporters::Svg::DEFAULT_MAX_LABEL_WIDTH, state_wrap: false, max_state_label_width: Exporters::Svg::DEFAULT_MAX_STATE_LABEL_WIDTH, sort_labels: Exporters::Svg::DEFAULT_SORT_LABELS, label_tooltips: Exporters::Svg::DEFAULT_LABEL_TOOLTIPS, html_tooltips: Exporters::Svg::DEFAULT_HTML_TOOLTIPS, font_family: Exporters::Svg::DEFAULT_FONT_FAMILY, state_font_weight: Exporters::Svg::DEFAULT_STATE_FONT_WEIGHT, transition_font_weight: Exporters::Svg::DEFAULT_TRANSITION_FONT_WEIGHT, label_background: Exporters::Svg::DEFAULT_LABEL_BACKGROUND, label_border: Exporters::Svg::DEFAULT_LABEL_BORDER, label_padding: Exporters::Svg::DEFAULT_LABEL_PADDING, label_radius: Exporters::Svg::DEFAULT_LABEL_RADIUS, rotate_labels: Exporters::Svg::DEFAULT_ROTATE_LABELS, highlight_unreachable: false, highlight_dead_states: Exporters::Svg::DEFAULT_HIGHLIGHT_DEAD_STATES, highlight_initial_state: Exporters::Svg::DEFAULT_HIGHLIGHT_INITIAL_STATE, highlight_final_states: Exporters::Svg::DEFAULT_HIGHLIGHT_FINAL_STATES, highlight_transitions: Exporters::Svg::DEFAULT_HIGHLIGHT_TRANSITIONS, unreachable_zone: Exporters::Svg::DEFAULT_UNREACHABLE_ZONE, xml_declaration: Exporters::Svg::DEFAULT_XML_DECLARATION, css_variables: Exporters::Svg::DEFAULT_CSS_VARIABLES, embed_styles: Exporters::Svg::DEFAULT_EMBED_STYLES, pretty: Exporters::Svg::DEFAULT_PRETTY, minify: Exporters::Svg::DEFAULT_MINIFY, state_effect: Exporters::Svg::DEFAULT_STATE_EFFECT, loop_position: Exporters::Svg::DEFAULT_LOOP_POSITION, edge_style: Exporters::Svg::DEFAULT_EDGE_STYLE, show_final_arrows: Exporters::Svg::DEFAULT_SHOW_FINAL_ARROWS, scc_groups: Exporters::Svg::DEFAULT_SCC_GROUPS, fold_groups: Exporters::Svg::DEFAULT_FOLD_GROUPS, preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS, fit: DEFAULT_FIT, title: nil, description: nil, svg_id: nil) ⇒ Object



2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
# File 'lib/graphomaton.rb', line 2247

def save_svg(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
             layout: :linear, direction: :lr, responsive: false, state_radius: DEFAULT_STATE_RADIUS,
             auto_state_radius: Exporters::Svg::DEFAULT_AUTO_STATE_RADIUS,
             min_state_radius: Exporters::Svg::DEFAULT_MIN_STATE_RADIUS,
             max_state_radius: Exporters::Svg::DEFAULT_MAX_STATE_RADIUS,
             state_shape: Exporters::Svg::DEFAULT_STATE_SHAPE,
             state_stroke_width: Exporters::Svg::DEFAULT_STATE_STROKE_WIDTH,
             transition_stroke_width: Exporters::Svg::DEFAULT_TRANSITION_STROKE_WIDTH,
             padding: DEFAULT_PADDING, node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING,
             force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil, auto_size: false,
             graphviz_command: DEFAULT_GRAPHVIZ_COMMAND,
             auto_density_spacing: Exporters::Svg::DEFAULT_AUTO_DENSITY_SPACING,
             arrow_size: Exporters::Svg::DEFAULT_ARROW_SIZE,
             arrow_shape: Exporters::Svg::DEFAULT_ARROW_SHAPE,
             initial_arrow_length: Exporters::Svg::DEFAULT_INITIAL_ARROW_LENGTH,
             initial_arrow_label: Exporters::Svg::DEFAULT_INITIAL_ARROW_LABEL,
             final_arrow_length: Exporters::Svg::DEFAULT_FINAL_ARROW_LENGTH,
             final_arrow_label: Exporters::Svg::DEFAULT_FINAL_ARROW_LABEL,
             initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION,
             merge_parallel_transitions: true, wrap: Exporters::Svg::DEFAULT_WRAP,
             max_transition_label_width: Exporters::Svg::DEFAULT_MAX_LABEL_WIDTH, state_wrap: false,
             max_state_label_width: Exporters::Svg::DEFAULT_MAX_STATE_LABEL_WIDTH,
             sort_labels: Exporters::Svg::DEFAULT_SORT_LABELS,
             label_tooltips: Exporters::Svg::DEFAULT_LABEL_TOOLTIPS,
             html_tooltips: Exporters::Svg::DEFAULT_HTML_TOOLTIPS,
             font_family: Exporters::Svg::DEFAULT_FONT_FAMILY,
             state_font_weight: Exporters::Svg::DEFAULT_STATE_FONT_WEIGHT,
             transition_font_weight: Exporters::Svg::DEFAULT_TRANSITION_FONT_WEIGHT,
             label_background: Exporters::Svg::DEFAULT_LABEL_BACKGROUND,
             label_border: Exporters::Svg::DEFAULT_LABEL_BORDER,
             label_padding: Exporters::Svg::DEFAULT_LABEL_PADDING,
             label_radius: Exporters::Svg::DEFAULT_LABEL_RADIUS,
             rotate_labels: Exporters::Svg::DEFAULT_ROTATE_LABELS,
             highlight_unreachable: false,
             highlight_dead_states: Exporters::Svg::DEFAULT_HIGHLIGHT_DEAD_STATES,
             highlight_initial_state: Exporters::Svg::DEFAULT_HIGHLIGHT_INITIAL_STATE,
             highlight_final_states: Exporters::Svg::DEFAULT_HIGHLIGHT_FINAL_STATES,
             highlight_transitions: Exporters::Svg::DEFAULT_HIGHLIGHT_TRANSITIONS,
             unreachable_zone: Exporters::Svg::DEFAULT_UNREACHABLE_ZONE,
             xml_declaration: Exporters::Svg::DEFAULT_XML_DECLARATION,
             css_variables: Exporters::Svg::DEFAULT_CSS_VARIABLES,
             embed_styles: Exporters::Svg::DEFAULT_EMBED_STYLES,
             pretty: Exporters::Svg::DEFAULT_PRETTY,
             minify: Exporters::Svg::DEFAULT_MINIFY,
             state_effect: Exporters::Svg::DEFAULT_STATE_EFFECT,
             loop_position: Exporters::Svg::DEFAULT_LOOP_POSITION,
             edge_style: Exporters::Svg::DEFAULT_EDGE_STYLE,
             show_final_arrows: Exporters::Svg::DEFAULT_SHOW_FINAL_ARROWS,
             scc_groups: Exporters::Svg::DEFAULT_SCC_GROUPS,
             fold_groups: Exporters::Svg::DEFAULT_FOLD_GROUPS,
             preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS,
             fit: DEFAULT_FIT,
             title: nil, description: nil, svg_id: nil)
  AtomicFile.write(
    filename,
    to_svg(
      width,
      height,
      theme: theme,
      layout: layout,
      direction: direction,
      responsive: responsive,
      state_radius: state_radius,
      auto_state_radius: auto_state_radius,
      min_state_radius: min_state_radius,
      max_state_radius: max_state_radius,
      state_shape: state_shape,
      state_stroke_width: state_stroke_width,
      transition_stroke_width: transition_stroke_width,
      padding: padding,
      node_spacing: node_spacing,
      rank_spacing: rank_spacing,
      force_iterations: force_iterations,
      layout_seed: layout_seed,
      graphviz_command: graphviz_command,
      auto_size: auto_size,
      auto_density_spacing: auto_density_spacing,
      arrow_size: arrow_size,
      arrow_shape: arrow_shape,
      initial_arrow_length: initial_arrow_length,
      initial_arrow_label: initial_arrow_label,
      final_arrow_length: final_arrow_length,
      final_arrow_label: final_arrow_label,
      initial_position: initial_position,
      final_position: final_position,
      merge_parallel_transitions: merge_parallel_transitions,
      label_background: label_background,
      label_border: label_border,
      label_padding: label_padding,
      label_radius: label_radius,
      rotate_labels: rotate_labels,
      highlight_unreachable: highlight_unreachable,
      highlight_dead_states: highlight_dead_states,
      highlight_initial_state: highlight_initial_state,
      highlight_final_states: highlight_final_states,
      highlight_transitions: highlight_transitions,
      unreachable_zone: unreachable_zone,
      xml_declaration: xml_declaration,
      css_variables: css_variables,
      embed_styles: embed_styles,
      pretty: pretty,
      minify: minify,
      state_effect: state_effect,
      loop_position: loop_position,
      edge_style: edge_style,
      show_final_arrows: show_final_arrows,
      scc_groups: scc_groups,
      fold_groups: fold_groups,
      preserve_manual_positions: preserve_manual_positions,
      fit: fit,
      wrap: wrap,
      max_transition_label_width: max_transition_label_width,
      state_wrap: state_wrap,
      max_state_label_width: max_state_label_width,
      sort_labels: sort_labels,
      label_tooltips: label_tooltips,
      html_tooltips: html_tooltips,
      font_family: font_family,
      state_font_weight: state_font_weight,
      transition_font_weight: transition_font_weight,
      title: title,
      description: description,
      svg_id: svg_id
    )
  )
end

#save_webp(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, converter: Exporters::Webp::DEFAULT_CONVERTER, **svg_options) ⇒ Object



2399
2400
2401
2402
# File 'lib/graphomaton.rb', line 2399

def save_webp(filename, width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
              converter: Exporters::Webp::DEFAULT_CONVERTER, **svg_options)
  AtomicFile.write(filename, to_webp(width, height, theme: theme, converter: converter, **svg_options), binary: true)
end

#self_loop_traps ⇒ Array[untyped]

Returns:

  • (Array[untyped])


992
993
994
995
996
997
998
999
1000
# File 'lib/graphomaton.rb', line 992

def self_loop_traps
  ensure_analysis_index!
  ordered_state_names.select do |state|
    outgoing = @outgoing_by_state[state]
    next false if outgoing.empty?

    outgoing.all? { |transition| transition.to == state }
  end
end

#semantic_diagnostics(format, **options) ⇒ Array[Diagnostic]

Parameters:

  • format (Symbol, String)
  • (Object)

Returns:



2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
# File 'lib/graphomaton.rb', line 2026

def semantic_diagnostics(format, **options)
  resolved = resolve_format(format)
  capabilities = self.class.exporter_capabilities(resolved).dup
  capabilities << :state_tooltip if options[:notes] && i[html mermaid plantuml].include?(resolved)
  ExporterCapabilities.losses_for(self, capabilities).map do |feature|
    Diagnostic.new(
      code: 'unsupported-export-feature',
      severity: :warning,
      path: ['export', resolved.to_s],
      message: "#{resolved} output does not preserve #{feature}",
      hint: 'Choose SVG or remove the unsupported feature.'
    )
  end.freeze
end

#set_initial(state) ⇒ self

Parameters:

  • state (Object)

Returns:

  • (self)

Raises:



836
837
838
839
840
841
842
843
844
845
846
# File 'lib/graphomaton.rb', line 836

def set_initial(state)
  InputPolicy.identifier!(state, context: 'Initial state id')
  raise ValidationError, "Initial state #{state.inspect} is not defined" if @validation_mode == :strict && !@states.key?(state)

  stable_state = immutable_copy(state)
  return self if @initial_state == stable_state

  @initial_state = stable_state
  graph_changed!
  self
end

#sink_states ⇒ Array[untyped]

Returns:

  • (Array[untyped])


1002
1003
1004
1005
# File 'lib/graphomaton.rb', line 1002

def sink_states
  ensure_analysis_index!
  ordered_state_names.select { |state| @outgoing_by_state[state].empty? }
end

#state_records ⇒ Object



607
608
609
# File 'lib/graphomaton.rb', line 607

def state_records
  @states.dup.freeze
end

#states ⇒ Hash[untyped, Hash[Symbol, untyped]]

Returns:

  • (Hash[untyped, Hash[Symbol, untyped]])


595
596
597
# File 'lib/graphomaton.rb', line 595

def states
  immutable_snapshot(@states.transform_values(&:to_h))
end

#states_reaching_final ⇒ Object



953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
# File 'lib/graphomaton.rb', line 953

def states_reaching_final
  defined_final_states = @final_states.select { |state| @states.key?(state) }
  return [] if defined_final_states.empty?

  ensure_analysis_index!

  reachable = defined_final_states.to_h { |state| [state, true] }
  queue = reachable.keys
  head = 0
  while head < queue.length
    state = queue[head]
    head += 1
    @incoming_by_state[state].each do |transition|
      previous = transition.from
      next if reachable[previous]

      reachable[previous] = true
      queue << previous
    end
  end

  ordered_state_names.select { |state| reachable[state] }
end

#strongly_connected_components ⇒ Object



1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
# File 'lib/graphomaton.rb', line 1015

def strongly_connected_components
  ensure_analysis_index!
  adjacency = @outgoing_by_state.transform_values { |transitions| transitions.map(&:to) }
  reverse_adjacency = @incoming_by_state.transform_values { |transitions| transitions.map(&:from) }

  visited = {}
  finish_order = []
  @states.each_key do |state|
    next if visited[state]

    visited[state] = true
    stack = [[state, 0]]
    until stack.empty?
      current, next_index = stack.last
      if next_index < adjacency[current].length
        target = adjacency[current][next_index]
        stack.last[1] += 1
        next if visited[target]

        visited[target] = true
        stack << [target, 0]
      else
        finish_order << current
        stack.pop
      end
    end
  end

  assigned = {}
  finish_order.reverse_each.filter_map do |state|
    next if assigned[state]

    component = []
    stack = [state]
    assigned[state] = true
    until stack.empty?
      current = stack.pop
      component << current
      reverse_adjacency[current].reverse_each do |target|
        next if assigned[target]

        assigned[target] = true
        stack << target
      end
    end
    component
  end
end

#to_dot(direction: Exporters::Dot::DEFAULT_DIRECTION, theme: nil, rank_constraints: Exporters::Dot::DEFAULT_RANK_CONSTRAINTS) ⇒ Object



2475
2476
2477
2478
# File 'lib/graphomaton.rb', line 2475

def to_dot(direction: Exporters::Dot::DEFAULT_DIRECTION, theme: nil,
           rank_constraints: Exporters::Dot::DEFAULT_RANK_CONSTRAINTS)
  Exporters::Dot.new(self, direction: direction, theme: theme, rank_constraints: rank_constraints).export
end

#to_h ⇒ Hash[Symbol, untyped]

Returns:

  • (Hash[Symbol, untyped])


1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
# File 'lib/graphomaton.rb', line 1982

def to_h
  output = {
    version: 1,
    states: @states.values.map do |state|
      serialized = { id: state.id }
      serialized[:x] = state.x unless state.x.nil?
      serialized[:y] = state.y unless state.y.nil?
      serialized[:label] = state.label unless state.label.nil?
      serialized[:style] = state.style unless state.style.nil?
      serialized[:metadata] = state. unless state..nil?
      serialized[:shape] = state.shape unless state.shape.nil?
      serialized[:kind] = state.kind unless state.kind.nil?
      serialized
    end,
    transitions: @transitions.map do |transition|
      serialized = transition.to_h
      serialized[:label] = transition.label.to_h if transition.label.is_a?(Label)
      serialized
    end
  }
  output[:initial] = @initial_state unless @initial_state.nil?
  output[:final] = @final_states unless @final_states.empty?
  immutable_snapshot(output)
end

#to_html(direction: Exporters::Mermaid::DEFAULT_DIRECTION, theme: Exporters::Mermaid::DEFAULT_THEME, cdn: Exporters::Mermaid::DEFAULT_CDN, inline_mermaid: false, offline: false, title: nil, lang: Exporters::Mermaid::DEFAULT_LANG, show_source: Exporters::Mermaid::DEFAULT_SHOW_SOURCE, pan_zoom: Exporters::Mermaid::DEFAULT_PAN_ZOOM, mathjax: Exporters::Mermaid::DEFAULT_MATHJAX, mathjax_cdn: Exporters::Mermaid::DEFAULT_MATHJAX_CDN, inline_mathjax: false, self_contained: false, nonce: nil, csp: false, mermaid_sha256: nil, mathjax_sha256: nil, notes: Exporters::Mermaid::DEFAULT_NOTES, class_defs: Exporters::Mermaid::DEFAULT_CLASS_DEFS) ⇒ Object



2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
# File 'lib/graphomaton.rb', line 2409

def to_html(direction: Exporters::Mermaid::DEFAULT_DIRECTION, theme: Exporters::Mermaid::DEFAULT_THEME,
            cdn: Exporters::Mermaid::DEFAULT_CDN, inline_mermaid: false, offline: false, title: nil,
            lang: Exporters::Mermaid::DEFAULT_LANG, show_source: Exporters::Mermaid::DEFAULT_SHOW_SOURCE,
            pan_zoom: Exporters::Mermaid::DEFAULT_PAN_ZOOM,
            mathjax: Exporters::Mermaid::DEFAULT_MATHJAX,
            mathjax_cdn: Exporters::Mermaid::DEFAULT_MATHJAX_CDN,
            inline_mathjax: false, self_contained: false, nonce: nil, csp: false,
            mermaid_sha256: nil, mathjax_sha256: nil,
            notes: Exporters::Mermaid::DEFAULT_NOTES,
            class_defs: Exporters::Mermaid::DEFAULT_CLASS_DEFS)
  Exporters::Mermaid.new(self, direction: direction, notes: notes, class_defs: class_defs).export_html(
    theme: theme,
    cdn: cdn,
    inline_mermaid: inline_mermaid,
    offline: offline,
    title: title,
    lang: lang,
    show_source: show_source,
    pan_zoom: pan_zoom,
    mathjax: mathjax,
    mathjax_cdn: mathjax_cdn,
    inline_mathjax: inline_mathjax,
    self_contained: self_contained,
    nonce: nonce,
    csp: csp,
    mermaid_sha256: mermaid_sha256,
    mathjax_sha256: mathjax_sha256
  )
end

#to_json(*arguments) ⇒ String

Parameters:

  • (Object)

Returns:

  • (String)


2007
2008
2009
# File 'lib/graphomaton.rb', line 2007

def to_json(*arguments)
  JSON.generate(to_h, *arguments)
end

#to_mermaid(direction: Exporters::Mermaid::DEFAULT_DIRECTION, notes: Exporters::Mermaid::DEFAULT_NOTES, class_defs: Exporters::Mermaid::DEFAULT_CLASS_DEFS) ⇒ Object



2404
2405
2406
2407
# File 'lib/graphomaton.rb', line 2404

def to_mermaid(direction: Exporters::Mermaid::DEFAULT_DIRECTION, notes: Exporters::Mermaid::DEFAULT_NOTES,
               class_defs: Exporters::Mermaid::DEFAULT_CLASS_DEFS)
  Exporters::Mermaid.new(self, direction: direction, notes: notes, class_defs: class_defs).export
end

#to_pdf(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, converter: Exporters::Pdf::DEFAULT_CONVERTER, **svg_options) ⇒ Object



2384
2385
2386
2387
# File 'lib/graphomaton.rb', line 2384

def to_pdf(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
           converter: Exporters::Pdf::DEFAULT_CONVERTER, **svg_options)
  Exporters::Pdf.new(self).export(width, height, theme: theme, converter: converter, **svg_options)
end

#to_plantuml(direction: Exporters::Plantuml::DEFAULT_DIRECTION, theme: nil, notes: Exporters::Plantuml::DEFAULT_NOTES) ⇒ Object



2485
2486
2487
2488
# File 'lib/graphomaton.rb', line 2485

def to_plantuml(direction: Exporters::Plantuml::DEFAULT_DIRECTION, theme: nil,
                notes: Exporters::Plantuml::DEFAULT_NOTES)
  Exporters::Plantuml.new(self, direction: direction, theme: theme, notes: notes).export
end

#to_png(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, scale: Exporters::Png::DEFAULT_SCALE, converter: Exporters::Png::DEFAULT_CONVERTER, **svg_options) ⇒ Object



2374
2375
2376
2377
# File 'lib/graphomaton.rb', line 2374

def to_png(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
           scale: Exporters::Png::DEFAULT_SCALE, converter: Exporters::Png::DEFAULT_CONVERTER, **svg_options)
  Exporters::Png.new(self).export(width, height, theme: theme, scale: scale, converter: converter, **svg_options)
end

#to_svg(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, layout: :linear, direction: :lr, responsive: false, state_radius: DEFAULT_STATE_RADIUS, auto_state_radius: Exporters::Svg::DEFAULT_AUTO_STATE_RADIUS, min_state_radius: Exporters::Svg::DEFAULT_MIN_STATE_RADIUS, max_state_radius: Exporters::Svg::DEFAULT_MAX_STATE_RADIUS, state_shape: Exporters::Svg::DEFAULT_STATE_SHAPE, state_stroke_width: Exporters::Svg::DEFAULT_STATE_STROKE_WIDTH, transition_stroke_width: Exporters::Svg::DEFAULT_TRANSITION_STROKE_WIDTH, padding: DEFAULT_PADDING, node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING, force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil, auto_size: false, graphviz_command: DEFAULT_GRAPHVIZ_COMMAND, auto_density_spacing: Exporters::Svg::DEFAULT_AUTO_DENSITY_SPACING, arrow_size: Exporters::Svg::DEFAULT_ARROW_SIZE, arrow_shape: Exporters::Svg::DEFAULT_ARROW_SHAPE, initial_arrow_length: Exporters::Svg::DEFAULT_INITIAL_ARROW_LENGTH, initial_arrow_label: Exporters::Svg::DEFAULT_INITIAL_ARROW_LABEL, final_arrow_length: Exporters::Svg::DEFAULT_FINAL_ARROW_LENGTH, final_arrow_label: Exporters::Svg::DEFAULT_FINAL_ARROW_LABEL, initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION, merge_parallel_transitions: true, wrap: Exporters::Svg::DEFAULT_WRAP, max_transition_label_width: Exporters::Svg::DEFAULT_MAX_LABEL_WIDTH, state_wrap: false, max_state_label_width: Exporters::Svg::DEFAULT_MAX_STATE_LABEL_WIDTH, sort_labels: Exporters::Svg::DEFAULT_SORT_LABELS, label_tooltips: Exporters::Svg::DEFAULT_LABEL_TOOLTIPS, html_tooltips: Exporters::Svg::DEFAULT_HTML_TOOLTIPS, font_family: Exporters::Svg::DEFAULT_FONT_FAMILY, state_font_weight: Exporters::Svg::DEFAULT_STATE_FONT_WEIGHT, transition_font_weight: Exporters::Svg::DEFAULT_TRANSITION_FONT_WEIGHT, label_background: Exporters::Svg::DEFAULT_LABEL_BACKGROUND, label_border: Exporters::Svg::DEFAULT_LABEL_BORDER, label_padding: Exporters::Svg::DEFAULT_LABEL_PADDING, label_radius: Exporters::Svg::DEFAULT_LABEL_RADIUS, rotate_labels: Exporters::Svg::DEFAULT_ROTATE_LABELS, highlight_unreachable: false, highlight_dead_states: Exporters::Svg::DEFAULT_HIGHLIGHT_DEAD_STATES, highlight_initial_state: Exporters::Svg::DEFAULT_HIGHLIGHT_INITIAL_STATE, highlight_final_states: Exporters::Svg::DEFAULT_HIGHLIGHT_FINAL_STATES, highlight_transitions: Exporters::Svg::DEFAULT_HIGHLIGHT_TRANSITIONS, unreachable_zone: Exporters::Svg::DEFAULT_UNREACHABLE_ZONE, xml_declaration: Exporters::Svg::DEFAULT_XML_DECLARATION, css_variables: Exporters::Svg::DEFAULT_CSS_VARIABLES, embed_styles: Exporters::Svg::DEFAULT_EMBED_STYLES, pretty: Exporters::Svg::DEFAULT_PRETTY, minify: Exporters::Svg::DEFAULT_MINIFY, state_effect: Exporters::Svg::DEFAULT_STATE_EFFECT, loop_position: Exporters::Svg::DEFAULT_LOOP_POSITION, edge_style: Exporters::Svg::DEFAULT_EDGE_STYLE, show_final_arrows: Exporters::Svg::DEFAULT_SHOW_FINAL_ARROWS, scc_groups: Exporters::Svg::DEFAULT_SCC_GROUPS, fold_groups: Exporters::Svg::DEFAULT_FOLD_GROUPS, preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS, fit: DEFAULT_FIT, title: nil, description: nil, svg_id: nil) ⇒ Object



2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
# File 'lib/graphomaton.rb', line 2123

def to_svg(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
           layout: :linear, direction: :lr, responsive: false, state_radius: DEFAULT_STATE_RADIUS,
           auto_state_radius: Exporters::Svg::DEFAULT_AUTO_STATE_RADIUS,
           min_state_radius: Exporters::Svg::DEFAULT_MIN_STATE_RADIUS,
           max_state_radius: Exporters::Svg::DEFAULT_MAX_STATE_RADIUS,
           state_shape: Exporters::Svg::DEFAULT_STATE_SHAPE,
           state_stroke_width: Exporters::Svg::DEFAULT_STATE_STROKE_WIDTH,
           transition_stroke_width: Exporters::Svg::DEFAULT_TRANSITION_STROKE_WIDTH,
           padding: DEFAULT_PADDING, node_spacing: DEFAULT_NODE_SPACING, rank_spacing: DEFAULT_RANK_SPACING,
           force_iterations: DEFAULT_FORCE_ITERATIONS, layout_seed: nil, auto_size: false,
           graphviz_command: DEFAULT_GRAPHVIZ_COMMAND,
           auto_density_spacing: Exporters::Svg::DEFAULT_AUTO_DENSITY_SPACING,
           arrow_size: Exporters::Svg::DEFAULT_ARROW_SIZE,
           arrow_shape: Exporters::Svg::DEFAULT_ARROW_SHAPE,
           initial_arrow_length: Exporters::Svg::DEFAULT_INITIAL_ARROW_LENGTH,
           initial_arrow_label: Exporters::Svg::DEFAULT_INITIAL_ARROW_LABEL,
           final_arrow_length: Exporters::Svg::DEFAULT_FINAL_ARROW_LENGTH,
           final_arrow_label: Exporters::Svg::DEFAULT_FINAL_ARROW_LABEL,
           initial_position: DEFAULT_INITIAL_POSITION, final_position: DEFAULT_FINAL_POSITION,
           merge_parallel_transitions: true, wrap: Exporters::Svg::DEFAULT_WRAP,
           max_transition_label_width: Exporters::Svg::DEFAULT_MAX_LABEL_WIDTH, state_wrap: false,
           max_state_label_width: Exporters::Svg::DEFAULT_MAX_STATE_LABEL_WIDTH,
           sort_labels: Exporters::Svg::DEFAULT_SORT_LABELS,
           label_tooltips: Exporters::Svg::DEFAULT_LABEL_TOOLTIPS,
           html_tooltips: Exporters::Svg::DEFAULT_HTML_TOOLTIPS,
           font_family: Exporters::Svg::DEFAULT_FONT_FAMILY,
           state_font_weight: Exporters::Svg::DEFAULT_STATE_FONT_WEIGHT,
           transition_font_weight: Exporters::Svg::DEFAULT_TRANSITION_FONT_WEIGHT,
           label_background: Exporters::Svg::DEFAULT_LABEL_BACKGROUND,
           label_border: Exporters::Svg::DEFAULT_LABEL_BORDER,
           label_padding: Exporters::Svg::DEFAULT_LABEL_PADDING,
           label_radius: Exporters::Svg::DEFAULT_LABEL_RADIUS,
           rotate_labels: Exporters::Svg::DEFAULT_ROTATE_LABELS,
           highlight_unreachable: false,
           highlight_dead_states: Exporters::Svg::DEFAULT_HIGHLIGHT_DEAD_STATES,
           highlight_initial_state: Exporters::Svg::DEFAULT_HIGHLIGHT_INITIAL_STATE,
           highlight_final_states: Exporters::Svg::DEFAULT_HIGHLIGHT_FINAL_STATES,
           highlight_transitions: Exporters::Svg::DEFAULT_HIGHLIGHT_TRANSITIONS,
           unreachable_zone: Exporters::Svg::DEFAULT_UNREACHABLE_ZONE,
           xml_declaration: Exporters::Svg::DEFAULT_XML_DECLARATION,
           css_variables: Exporters::Svg::DEFAULT_CSS_VARIABLES,
           embed_styles: Exporters::Svg::DEFAULT_EMBED_STYLES,
           pretty: Exporters::Svg::DEFAULT_PRETTY,
           minify: Exporters::Svg::DEFAULT_MINIFY,
           state_effect: Exporters::Svg::DEFAULT_STATE_EFFECT,
           loop_position: Exporters::Svg::DEFAULT_LOOP_POSITION,
           edge_style: Exporters::Svg::DEFAULT_EDGE_STYLE,
           show_final_arrows: Exporters::Svg::DEFAULT_SHOW_FINAL_ARROWS,
           scc_groups: Exporters::Svg::DEFAULT_SCC_GROUPS,
           fold_groups: Exporters::Svg::DEFAULT_FOLD_GROUPS,
           preserve_manual_positions: DEFAULT_PRESERVE_MANUAL_POSITIONS,
           fit: DEFAULT_FIT,
           title: nil, description: nil, svg_id: nil)
  Exporters::Svg.new(self).export(
    width,
    height,
    theme: theme,
    layout: layout,
    direction: direction,
    responsive: responsive,
    state_radius: state_radius,
    auto_state_radius: auto_state_radius,
    min_state_radius: min_state_radius,
    max_state_radius: max_state_radius,
    state_shape: state_shape,
    state_stroke_width: state_stroke_width,
    transition_stroke_width: transition_stroke_width,
    padding: padding,
    node_spacing: node_spacing,
    rank_spacing: rank_spacing,
    force_iterations: force_iterations,
    layout_seed: layout_seed,
    graphviz_command: graphviz_command,
    auto_size: auto_size,
    auto_density_spacing: auto_density_spacing,
    arrow_size: arrow_size,
    arrow_shape: arrow_shape,
    initial_arrow_length: initial_arrow_length,
    initial_arrow_label: initial_arrow_label,
    final_arrow_length: final_arrow_length,
    final_arrow_label: final_arrow_label,
    initial_position: initial_position,
    final_position: final_position,
    merge_parallel_transitions: merge_parallel_transitions,
    label_background: label_background,
    label_border: label_border,
    label_padding: label_padding,
    label_radius: label_radius,
    rotate_labels: rotate_labels,
    highlight_unreachable: highlight_unreachable,
    highlight_dead_states: highlight_dead_states,
    highlight_initial_state: highlight_initial_state,
    highlight_final_states: highlight_final_states,
    highlight_transitions: highlight_transitions,
    unreachable_zone: unreachable_zone,
    xml_declaration: xml_declaration,
    css_variables: css_variables,
    embed_styles: embed_styles,
    pretty: pretty,
    minify: minify,
    state_effect: state_effect,
    loop_position: loop_position,
    edge_style: edge_style,
    show_final_arrows: show_final_arrows,
    scc_groups: scc_groups,
    fold_groups: fold_groups,
    preserve_manual_positions: preserve_manual_positions,
    fit: fit,
    wrap: wrap,
    max_transition_label_width: max_transition_label_width,
    state_wrap: state_wrap,
    max_state_label_width: max_state_label_width,
    sort_labels: sort_labels,
    label_tooltips: label_tooltips,
    html_tooltips: html_tooltips,
    font_family: font_family,
    state_font_weight: state_font_weight,
    transition_font_weight: transition_font_weight,
    title: title,
    description: description,
    svg_id: svg_id
  )
end

#to_webp(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME, converter: Exporters::Webp::DEFAULT_CONVERTER, **svg_options) ⇒ Object



2394
2395
2396
2397
# File 'lib/graphomaton.rb', line 2394

def to_webp(width = 800, height = 600, theme: Exporters::Svg::DEFAULT_THEME,
            converter: Exporters::Webp::DEFAULT_CONVERTER, **svg_options)
  Exporters::Webp.new(self).export(width, height, theme: theme, converter: converter, **svg_options)
end

#to_yaml(**options) ⇒ String

Parameters:

  • (Object)

Returns:

  • (String)


2011
2012
2013
# File 'lib/graphomaton.rb', line 2011

def to_yaml(**options)
  to_h.to_yaml(**options)
end

#transition_records ⇒ Object



611
612
613
# File 'lib/graphomaton.rb', line 611

def transition_records
  @transitions.dup.freeze
end

#transitions ⇒ Array[Hash[Symbol, untyped]]

Returns:

  • (Array[Hash[Symbol, untyped]])


599
600
601
# File 'lib/graphomaton.rb', line 599

def transitions
  immutable_snapshot(@transitions.map(&:to_h))
end

#transitions_by_pair ⇒ Object



1977
1978
1979
1980
# File 'lib/graphomaton.rb', line 1977

def transitions_by_pair
  ensure_analysis_index!
  @transitions_by_directed_pair.transform_values { |transitions| transitions.map(&:to_h).freeze }.freeze
end

#trap_states ⇒ Object



988
989
990
# File 'lib/graphomaton.rb', line 988

def trap_states
  self_loop_traps
end

#unreachable_states ⇒ Object



949
950
951
# File 'lib/graphomaton.rb', line 949

def unreachable_states
  @states.keys - reachable_states
end

#update_state(name, **attributes) ⇒ self

Parameters:

  • name (Object)
  • (Object)

Returns:

  • (self)

Raises:

  • (ArgumentError)


670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/graphomaton.rb', line 670

def update_state(name, **attributes)
  state = @states.fetch(name) { raise ArgumentError, "State is not defined: #{name.inspect}" }
  allowed = i[x y label style  shape kind]
  unknown = attributes.keys - allowed
  raise ArgumentError, "Unknown state attributes: #{unknown.join(', ')}" unless unknown.empty?
  if attributes.key?(:x) != attributes.key?(:y)
    raise ArgumentError, 'State coordinates require both x and y'
  end

  x = attributes.fetch(:x, state.x)
  y = attributes.fetch(:y, state.y)
  if x.nil? != y.nil?
    raise ArgumentError, 'State coordinates require both x and y'
  end
  unless x.nil?
    validate_finite_number!(x, 'state x coordinate')
    validate_finite_number!(y, 'state y coordinate')
  end
  label = attributes.fetch(:label, state.label)
  label = label.to_s if label.is_a?(Label)
  style = attributes.fetch(:style, state.style)
   = attributes.fetch(:metadata, state.)
  InputPolicy.label!(label, context: "State #{name.inspect} label", max_bytes: DEFAULT_MAX_LABEL_LENGTH)
  InputPolicy.mapping!(style, context: "State #{name.inspect} style")
  InputPolicy.mapping!(, context: "State #{name.inspect} metadata")
  if 
    InputPolicy.nested_depth!(
      ,
      maximum: ,
      context: "State #{name.inspect} metadata",
      max_string_bytes: DEFAULT_MAX_LABEL_LENGTH
    )
  end

  updated_state = State.new(
    id: state.id,
    x: x,
    y: y,
    label: immutable_copy(label),
    style: immutable_copy(style),
    metadata: immutable_copy(),
    shape: immutable_copy(attributes.fetch(:shape, state.shape)),
    kind: resolve_state_kind(attributes.fetch(:kind, state.kind))
  )
  coordinates_updated = attributes.key?(:x)
  manual = !x.nil? && !y.nil?
  manual_changed = coordinates_updated && @manual_states[name] != manual
  return self if updated_state == state && !manual_changed

  @states[name] = updated_state
  @manual_states[name] = manual if coordinates_updated
  graph_changed!
  self
end

#update_transition(identifier, **attributes) ⇒ self

Parameters:

  • identifier (Object)
  • (Object)

Returns:

  • (self)

Raises:

  • (ArgumentError)


785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
# File 'lib/graphomaton.rb', line 785

def update_transition(identifier, **attributes)
  index = transition_index(identifier)
  transition = @transitions.fetch(index)
  allowed = i[from to label style  line_style]
  unknown = attributes.keys - allowed
  raise ArgumentError, "Unknown transition attributes: #{unknown.join(', ')}" unless unknown.empty?

  from = attributes.fetch(:from, transition.from)
  to = attributes.fetch(:to, transition.to)
  label = attributes.fetch(:label, transition.label)
  InputPolicy.identifier!(from, context: 'Transition source')
  InputPolicy.identifier!(to, context: 'Transition target')
  raise ArgumentError, 'Transition label cannot be nil' if label.nil?
  labels = label.is_a?(Array) ? label : [label]
  raise ArgumentError, 'Transition labels cannot be empty' if labels.empty?
  raise ArgumentError, 'Transition labels cannot contain nil' if labels.any?(&:nil?)
  labels.each do |item|
    InputPolicy.label!(item, context: 'Transition label', max_bytes: DEFAULT_MAX_LABEL_LENGTH)
  end
  if @validation_mode == :strict
    raise ValidationError, "Transition source #{from.inspect} is not defined" unless @states.key?(from)
    raise ValidationError, "Transition target #{to.inspect} is not defined" unless @states.key?(to)
  end
   = attributes.fetch(:metadata, transition.)
  style = attributes.fetch(:style, transition.style)
  InputPolicy.mapping!(style, context: 'Transition style')
  InputPolicy.mapping!(, context: 'Transition metadata')
  InputPolicy.nested_depth!(, maximum: , context: 'Transition metadata') if 

  updated_transition = Transition.new(
    id: transition.id,
    from: immutable_copy(from),
    to: immutable_copy(to),
    label: immutable_copy(normalize_transition_label(label)),
    style: immutable_copy(style),
    metadata: immutable_copy(),
    line_style: immutable_copy(attributes.fetch(:line_style, transition.line_style))
  )
  return self if updated_transition == transition

  @transitions[index] = updated_transition
  graph_changed!
  self
end

#upsert_state(name, x = UNSET, y = UNSET, **attributes) ⇒ self

Parameters:

  • name (Object)
  • x (Numeric, nil) (defaults to: UNSET)
  • y (Numeric, nil) (defaults to: UNSET)
  • (Object)

Returns:

  • (self)


655
656
657
658
659
660
661
662
663
664
665
666
667
668
# File 'lib/graphomaton.rb', line 655

def upsert_state(name, x = UNSET, y = UNSET, **attributes)
  unless @states.key?(name)
    new_x = x.equal?(UNSET) ? nil : x
    new_y = y.equal?(UNSET) ? nil : y
    return add_state(name, new_x, new_y, **attributes)
  end

  return update_state(name, **attributes) if x.equal?(UNSET) && y.equal?(UNSET)
  if x.equal?(UNSET) || y.equal?(UNSET)
    raise ArgumentError, 'State coordinates require both x and y'
  end

  update_state(name, x: x, y: y, **attributes)
end

#valid?(profile: :references) ⇒ Boolean

Parameters:

  • profile: (Symbol, Array[Symbol]) (defaults to: :references)

Returns:

  • (Boolean)


902
903
904
# File 'lib/graphomaton.rb', line 902

def valid?(profile: :references)
  validation_errors(profile: profile).empty?
end

#validate!(profile: :references) ⇒ true

Parameters:

  • profile: (Symbol, Array[Symbol]) (defaults to: :references)

Returns:

  • (true)

Raises:



906
907
908
909
910
911
# File 'lib/graphomaton.rb', line 906

def validate!(profile: :references)
  errors = validation_errors(profile: profile)
  return true if errors.empty?

  raise ValidationError, errors.join("\n")
end

#validation_diagnostics(profile: :references) ⇒ Array[Diagnostic]

Parameters:

  • profile: (Symbol, Array[Symbol]) (defaults to: :references)

Returns:



876
877
878
879
880
881
882
883
884
885
886
887
888
# File 'lib/graphomaton.rb', line 876

def validation_diagnostics(profile: :references)
  profiles = Array(profile).map(&:to_sym)
  profiles = profiles.flat_map { |name| name == :all ? VALIDATION_PROFILES : name }.uniq
  unknown = profiles - VALIDATION_PROFILES
  unless unknown.empty?
    raise ArgumentError, "Unknown validation profiles: #{unknown.join(', ')}. Available profiles: #{VALIDATION_PROFILES.join(', ')}"
  end
  diagnostics = reference_diagnostics if profiles.include?(:references)
  diagnostics ||= []
  diagnostics.concat(fsm_semantic_diagnostics) if profiles.include?(:fsm_semantics)
  diagnostics.concat(dfa_diagnostics) if profiles.include?(:dfa)
  diagnostics.freeze
end

#validation_errors(profile: :references) ⇒ Array[String]

Parameters:

  • profile: (Symbol, Array[Symbol]) (defaults to: :references)

Returns:

  • (Array[String])


890
891
892
893
894
# File 'lib/graphomaton.rb', line 890

def validation_errors(profile: :references)
  validation_diagnostics(profile: profile)
    .select { |diagnostic| diagnostic.severity == :error }
    .map(&:message)
end

#weakly_connected_components ⇒ Array[Array[untyped]]

Returns:

  • (Array[Array[untyped]])


945
946
947
# File 'lib/graphomaton.rb', line 945

def weakly_connected_components
  weak_components(ordered_state_names)
end

#write(io, format: :svg, width: 800, height: 600, **options) ⇒ Integer

Parameters:

  • io (_Writer)
  • format: (Symbol, String) (defaults to: :svg)
  • width: (Numeric) (defaults to: 800)
  • height: (Numeric) (defaults to: 600)
  • (Object)

Returns:

  • (Integer)


2019
2020
2021
2022
2023
2024
# File 'lib/graphomaton.rb', line 2019

def write(io, format: :svg, width: 800, height: 600, **options)
  resolved = resolve_format(format)
  output = render(format: resolved, width: width, height: height, **options)
  io.binmode if io.respond_to?(:binmode) && self.class::EXPORTERS.fetch(resolved).binary
  io.write(output)
end