kbs 0.2.1 → 0.4.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.
Files changed (134) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +87 -1
  3. data/README.md +66 -25
  4. data/lib/kbs/agenda.rb +301 -0
  5. data/lib/kbs/alpha_memory.rb +80 -9
  6. data/lib/kbs/alpha_network.rb +95 -0
  7. data/lib/kbs/beta_memory.rb +54 -19
  8. data/lib/kbs/blackboard/audit_log.rb +26 -25
  9. data/lib/kbs/blackboard/engine.rb +49 -40
  10. data/lib/kbs/blackboard/fact.rb +17 -21
  11. data/lib/kbs/blackboard/memory.rb +116 -40
  12. data/lib/kbs/blackboard/message_queue.rb +39 -28
  13. data/lib/kbs/blackboard/persistence/hybrid_store.rb +20 -9
  14. data/lib/kbs/blackboard/persistence/redis_store.rb +59 -51
  15. data/lib/kbs/blackboard/persistence/sqlite_store.rb +29 -32
  16. data/lib/kbs/blackboard/persistence/store.rb +11 -1
  17. data/lib/kbs/blackboard/redis_message_queue.rb +16 -7
  18. data/lib/kbs/condition.rb +42 -2
  19. data/lib/kbs/decompiler.rb +300 -124
  20. data/lib/kbs/dsl/condition_helpers.rb +8 -6
  21. data/lib/kbs/dsl/knowledge_base.rb +73 -93
  22. data/lib/kbs/dsl/pattern_evaluator.rb +38 -15
  23. data/lib/kbs/dsl/rule_builder.rb +118 -40
  24. data/lib/kbs/dsl/variable.rb +51 -6
  25. data/lib/kbs/dsl.rb +10 -3
  26. data/lib/kbs/engine.rb +395 -77
  27. data/lib/kbs/errors.rb +38 -0
  28. data/lib/kbs/exists_node.rb +12 -0
  29. data/lib/kbs/fact.rb +5 -19
  30. data/lib/kbs/fact_registry.rb +51 -0
  31. data/lib/kbs/introspection.rb +93 -0
  32. data/lib/kbs/join_indexing.rb +106 -0
  33. data/lib/kbs/join_node.rb +93 -57
  34. data/lib/kbs/join_test_builder.rb +80 -0
  35. data/lib/kbs/join_tests.rb +66 -0
  36. data/lib/kbs/memory_index.rb +104 -0
  37. data/lib/kbs/negation_node.rb +6 -82
  38. data/lib/kbs/network_node.rb +31 -0
  39. data/lib/kbs/pattern_matching.rb +52 -0
  40. data/lib/kbs/production_node.rb +50 -6
  41. data/lib/kbs/quantifier_node.rb +140 -0
  42. data/lib/kbs/rule.rb +26 -13
  43. data/lib/kbs/rule_source.rb +74 -0
  44. data/lib/kbs/rule_step.rb +27 -0
  45. data/lib/kbs/token.rb +76 -10
  46. data/lib/kbs/tracer.rb +80 -0
  47. data/lib/kbs/truth_maintenance.rb +82 -0
  48. data/lib/kbs/version.rb +1 -1
  49. data/lib/kbs/working_memory.rb +25 -3
  50. data/lib/kbs.rb +17 -4
  51. metadata +22 -129
  52. data/.envrc +0 -3
  53. data/.github/workflows/deploy-github-pages.yml +0 -52
  54. data/COMMITS.md +0 -196
  55. data/Rakefile +0 -8
  56. data/docs/advanced/custom-persistence.md +0 -775
  57. data/docs/advanced/debugging.md +0 -726
  58. data/docs/advanced/index.md +0 -8
  59. data/docs/advanced/performance.md +0 -865
  60. data/docs/advanced/testing.md +0 -827
  61. data/docs/api/blackboard.md +0 -1157
  62. data/docs/api/engine.md +0 -1047
  63. data/docs/api/facts.md +0 -1212
  64. data/docs/api/index.md +0 -12
  65. data/docs/api/rules.md +0 -1104
  66. data/docs/architecture/blackboard.md +0 -544
  67. data/docs/architecture/index.md +0 -277
  68. data/docs/architecture/network-structure.md +0 -343
  69. data/docs/architecture/rete-algorithm.md +0 -737
  70. data/docs/assets/css/custom.css +0 -83
  71. data/docs/assets/images/blackboard-architecture.svg +0 -136
  72. data/docs/assets/images/compiled-network.svg +0 -101
  73. data/docs/assets/images/fact-assertion-flow.svg +0 -117
  74. data/docs/assets/images/fact-rule-relationship.svg +0 -65
  75. data/docs/assets/images/fact-structure.svg +0 -42
  76. data/docs/assets/images/inference-cycle.svg +0 -47
  77. data/docs/assets/images/kb-components.svg +0 -43
  78. data/docs/assets/images/kbs.jpg +0 -0
  79. data/docs/assets/images/pattern-matching-trace.svg +0 -136
  80. data/docs/assets/images/rete-network-layers.svg +0 -96
  81. data/docs/assets/images/rule-structure.svg +0 -44
  82. data/docs/assets/images/system-layers.svg +0 -69
  83. data/docs/assets/images/trading-signal-network.svg +0 -139
  84. data/docs/assets/js/mathjax.js +0 -17
  85. data/docs/examples/index.md +0 -223
  86. data/docs/guides/blackboard-memory.md +0 -589
  87. data/docs/guides/dsl.md +0 -1321
  88. data/docs/guides/facts.md +0 -652
  89. data/docs/guides/getting-started.md +0 -385
  90. data/docs/guides/index.md +0 -23
  91. data/docs/guides/negation.md +0 -529
  92. data/docs/guides/pattern-matching.md +0 -561
  93. data/docs/guides/persistence.md +0 -451
  94. data/docs/guides/variable-binding.md +0 -491
  95. data/docs/guides/writing-rules.md +0 -914
  96. data/docs/index.md +0 -155
  97. data/docs/installation.md +0 -156
  98. data/docs/quick-start.md +0 -221
  99. data/docs/what-is-a-fact.md +0 -694
  100. data/docs/what-is-a-knowledge-base.md +0 -350
  101. data/docs/what-is-a-rule.md +0 -833
  102. data/examples/.gitignore +0 -1
  103. data/examples/README.md +0 -531
  104. data/examples/advanced_example.rb +0 -270
  105. data/examples/advanced_example_dsl.rb +0 -224
  106. data/examples/ai_enhanced_kbs.rb +0 -523
  107. data/examples/ai_enhanced_kbs_dsl.rb +0 -538
  108. data/examples/blackboard_demo.rb +0 -50
  109. data/examples/blackboard_demo_dsl.rb +0 -50
  110. data/examples/car_diagnostic.rb +0 -64
  111. data/examples/car_diagnostic_dsl.rb +0 -54
  112. data/examples/concurrent_inference_demo.rb +0 -362
  113. data/examples/concurrent_inference_demo_dsl.rb +0 -362
  114. data/examples/csv_trading_system.rb +0 -559
  115. data/examples/csv_trading_system_dsl.rb +0 -525
  116. data/examples/iot_demo_using_dsl.rb +0 -83
  117. data/examples/portfolio_rebalancing_system.rb +0 -651
  118. data/examples/portfolio_rebalancing_system_dsl.rb +0 -613
  119. data/examples/redis_trading_demo.rb +0 -177
  120. data/examples/redis_trading_demo_dsl.rb +0 -177
  121. data/examples/rule_source_demo.rb +0 -123
  122. data/examples/run_all.rb +0 -50
  123. data/examples/run_all_dsl.rb +0 -49
  124. data/examples/sample_stock_data.csv +0 -46
  125. data/examples/stock_trading_advanced.rb +0 -469
  126. data/examples/stock_trading_advanced_dsl.rb +0 -404
  127. data/examples/temp_dsl.txt +0 -9392
  128. data/examples/timestamped_trading.rb +0 -286
  129. data/examples/timestamped_trading_dsl.rb +0 -258
  130. data/examples/trading_demo.rb +0 -334
  131. data/examples/trading_demo_dsl.rb +0 -322
  132. data/examples/working_demo.rb +0 -176
  133. data/examples/working_demo_dsl.rb +0 -160
  134. data/mkdocs.yml +0 -181
@@ -1,88 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KBS
4
- class NegationNode
5
- attr_accessor :alpha_memory, :beta_memory, :successors, :tests
6
-
7
- def initialize(alpha_memory, beta_memory, tests = [])
8
- @alpha_memory = alpha_memory
9
- @beta_memory = beta_memory
10
- @successors = []
11
- @tests = tests
12
- @tokens_with_matches = Hash.new { |h, k| h[k] = [] }
13
-
14
- alpha_memory.successors << self if alpha_memory
15
- beta_memory.successors << self if beta_memory
16
- end
17
-
18
- def left_activate(token)
19
- matches = @alpha_memory.items.select { |fact| perform_join_tests(token, fact) }
20
-
21
- if matches.empty?
22
- new_token = Token.new(token, nil, self)
23
- token.children << new_token
24
- @successors.each { |s| s.activate(new_token) }
25
- else
26
- @tokens_with_matches[token] = matches
27
- end
28
- end
29
-
30
- def right_activate(fact)
31
- @beta_memory.tokens.each do |token|
32
- if perform_join_tests(token, fact)
33
- if @tokens_with_matches[token].empty?
34
- token.children.each do |child|
35
- @successors.each { |s| s.deactivate(child) if s.respond_to?(:deactivate) }
36
- end
37
- token.children.clear
38
- end
39
- @tokens_with_matches[token] << fact
40
- end
41
- end
42
- end
43
-
44
- def right_deactivate(fact)
45
- @beta_memory.tokens.each do |token|
46
- if @tokens_with_matches[token].include?(fact)
47
- @tokens_with_matches[token].delete(fact)
48
-
49
- if @tokens_with_matches[token].empty?
50
- new_token = Token.new(token, nil, self)
51
- token.children << new_token
52
- @successors.each { |s| s.activate(new_token) }
53
- end
54
- end
55
- end
56
- end
57
-
58
- private
59
-
60
- def perform_join_tests(token, fact)
61
- @tests.all? do |test|
62
- fact_value = fact.attributes[test[:fact_field]]
63
-
64
- # If test has expected_value, compare against that constant
65
- if test.key?(:expected_value)
66
- if test[:operation] == :eq
67
- fact_value == test[:expected_value]
68
- elsif test[:operation] == :ne
69
- fact_value != test[:expected_value]
70
- else
71
- true
72
- end
73
- else
74
- # Otherwise compare with token value
75
- token_value = token.facts[test[:token_field_index]]&.attributes&.[](test[:token_field])
76
-
77
- if test[:operation] == :eq
78
- token_value == fact_value
79
- elsif test[:operation] == :ne
80
- token_value != fact_value
81
- else
82
- true
83
- end
84
- end
85
- end
4
+ # A `without` condition: passes a token on while no fact matches it.
5
+ # A fact that matches the token blocks it; the token passes again when
6
+ # its last blocker is retracted.
7
+ class NegationNode < QuantifierNode
8
+ def passes_when_matched?
9
+ false
86
10
  end
87
11
  end
88
12
  end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KBS
4
+ # What a memory may ask of any node below it. A node overrides the
5
+ # calls it acts on; the rest do nothing, so a memory can tell every
6
+ # successor the same thing without asking what kind of node it is.
7
+ module NetworkNode
8
+ def left_unlink!; end
9
+
10
+ def left_relink!; end
11
+
12
+ def right_unlink!; end
13
+
14
+ def right_relink!; end
15
+
16
+ # A fact left the node's alpha memory.
17
+ def right_deactivate(_fact); end
18
+
19
+ private
20
+
21
+ # Passes a new token on to the memories below this node.
22
+ def activate_successors(token)
23
+ @successors.each { |successor| successor.activate(token) }
24
+ end
25
+
26
+ # Takes a token back from the memories below this node.
27
+ def deactivate_successors(token)
28
+ @successors.each { |successor| successor.deactivate(token) }
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KBS
4
+ # Fact#matches? for both kinds of fact. The including class has @type
5
+ # and @attributes.
6
+ module PatternMatching
7
+ # Whether the fact's type and attributes fit `pattern`. A Proc is
8
+ # called with the attribute's value, a ?variable fits anything, and
9
+ # any other value has to be equal. Walks the pattern with each_pair,
10
+ # since Hash#all? builds a [key, value] Array for every entry.
11
+ def matches?(pattern)
12
+ type = pattern[:type]
13
+ return false if type && type != @type
14
+
15
+ attributes = @attributes
16
+ pattern.each_pair do |key, expected|
17
+ next if key == :type
18
+ return false unless PatternMatching.value_matches?(attributes[key], expected)
19
+ end
20
+ true
21
+ end
22
+
23
+ def self.value_matches?(actual, expected)
24
+ if expected.is_a?(Proc)
25
+ actual && expected.call(actual)
26
+ elsif variable?(expected)
27
+ true
28
+ else
29
+ actual == expected
30
+ end
31
+ end
32
+
33
+ # A ?variable, which fits any value.
34
+ def self.variable?(expected)
35
+ expected.is_a?(Symbol) && expected.end_with?('?')
36
+ end
37
+
38
+ # The [attribute, expected value] pairs of `pattern` that can fail: all
39
+ # but the type and the ?variables. Frozen.
40
+ def self.tests_for(pattern)
41
+ pattern.reject { |key, expected| key == :type || variable?(expected) }.to_a.freeze
42
+ end
43
+
44
+ # Whether `attributes` pass every test from #tests_for.
45
+ def self.passes?(tests, attributes)
46
+ tests.each do |key, expected|
47
+ return false unless value_matches?(attributes[key], expected)
48
+ end
49
+ true
50
+ end
51
+ end
52
+ end
@@ -1,28 +1,72 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KBS
4
+ # The end of a rule's path through the network: puts each complete
5
+ # match on the agenda and fires the rule for it.
4
6
  class ProductionNode
5
- attr_accessor :rule, :tokens
7
+ include NetworkNode
6
8
 
7
- def initialize(rule)
9
+ attr_accessor :rule
10
+ attr_reader :order
11
+
12
+ # @param agenda [KBS::Agenda, nil] where matches wait to fire; without
13
+ # one the node only collects tokens
14
+ # @param order [Integer] the rule's position among the engine's rules
15
+ def initialize(rule, agenda = nil, order: 0)
8
16
  @rule = rule
9
- @tokens = []
17
+ @tokens = Set.new.compare_by_identity
18
+ @agenda = agenda
19
+ @order = order
20
+ @activations = {}.compare_by_identity
21
+ @fired = Set.new.compare_by_identity
22
+ end
23
+
24
+ # @return [Array<KBS::Token>] the rule's current matches, fired or
25
+ # not, in the order they arrived. A copy.
26
+ def tokens
27
+ @tokens.to_a
10
28
  end
11
29
 
30
+ # A complete match. The rule does not fire here: the activation waits
31
+ # on the agenda until Engine#run, so a later retraction can still
32
+ # take it back.
12
33
  def activate(token)
13
34
  @tokens << token
14
- # Don't fire immediately - wait for run() to fire rules
15
- # This allows negation nodes to deactivate tokens before they fire
35
+ @activations[token] = @agenda.add(self, token, rule_order: @order) if @agenda
16
36
  end
17
37
 
38
+ # Fires the rule for `token` unless this rule already fired for it.
39
+ # Rules with the same conditions share their tokens, so the record is
40
+ # kept here, per rule, and not only on the token.
18
41
  def fire_rule(token)
19
- return if token.fired?
42
+ return if fired?(token)
43
+
44
+ @fired << token
20
45
  @rule.fire(token.facts)
21
46
  token.mark_fired!
22
47
  end
23
48
 
49
+ # Whether this rule has fired for `token`.
50
+ def fired?(token)
51
+ @fired.include?(token)
52
+ end
53
+
24
54
  def deactivate(token)
25
55
  @tokens.delete(token)
56
+ @fired.delete(token)
57
+ @agenda&.remove(@activations.delete(token))
58
+ end
59
+
60
+ # A beta memory tells its successors of tokens through these.
61
+ alias left_activate activate
62
+ alias left_deactivate deactivate
63
+
64
+ # Forgets every match, fired or pending.
65
+ def reset
66
+ @activations.each_value { |activation| @agenda&.remove(activation) }
67
+ @activations.clear
68
+ @fired.clear
69
+ @tokens.clear
26
70
  end
27
71
  end
28
72
  end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KBS
4
+ # Base for the nodes that test whether a token has any matching fact
5
+ # rather than joining it with each one: NegationNode passes a token on
6
+ # while it has no match, ExistsNode while it has at least one. The
7
+ # token passed on carries no fact.
8
+ #
9
+ # Each token is linked to the facts that match it, and each fact to the
10
+ # tokens it matches. Adding or removing a fact follows those links to
11
+ # the affected tokens, so neither memory is searched.
12
+ class QuantifierNode
13
+ include NetworkNode
14
+ include JoinTests
15
+ include JoinIndexing
16
+
17
+ attr_accessor :successors
18
+ attr_reader :alpha_memory, :beta_memory, :tests
19
+
20
+ def initialize(alpha_memory, beta_memory, tests = [])
21
+ @alpha_memory = alpha_memory
22
+ @beta_memory = beta_memory
23
+ @successors = []
24
+ @tests = tests
25
+ @facts_matching = {}.compare_by_identity
26
+ @tokens_matched_by = {}
27
+
28
+ alpha_memory.successors << self if alpha_memory
29
+ beta_memory.successors << self if beta_memory
30
+ build_join_indexes
31
+ end
32
+
33
+ def tests=(tests)
34
+ @tests = tests
35
+ build_join_indexes
36
+ end
37
+
38
+ def alpha_memory=(memory)
39
+ @alpha_memory = memory
40
+ build_join_indexes
41
+ end
42
+
43
+ def beta_memory=(memory)
44
+ @beta_memory = memory
45
+ build_join_indexes
46
+ end
47
+
48
+ # Subclasses answer whether a token is passed on while it has a
49
+ # matching fact (exists) or while it has none (negation).
50
+ def passes_when_matched?
51
+ raise NotImplementedError, "#{self.class} must define passes_when_matched?"
52
+ end
53
+
54
+ def left_activate(token)
55
+ matching_facts(token).each { |fact| link(token, fact) }
56
+ emit(token) if matched?(token) == passes_when_matched?
57
+ end
58
+
59
+ def right_activate(fact)
60
+ matching_tokens(fact).each do |token|
61
+ already_matched = matched?(token)
62
+ link(token, fact)
63
+ next if already_matched
64
+
65
+ passes_when_matched? ? emit(token) : retract(token)
66
+ end
67
+ end
68
+
69
+ def right_deactivate(fact)
70
+ tokens = @tokens_matched_by.delete(fact)
71
+ return unless tokens
72
+
73
+ tokens.each do |token|
74
+ facts = @facts_matching[token]
75
+ facts.delete(fact)
76
+ next unless facts.empty?
77
+
78
+ @facts_matching.delete(token)
79
+ passes_when_matched? ? retract(token) : emit(token)
80
+ end
81
+ end
82
+
83
+ def left_deactivate(token)
84
+ retract(token)
85
+ facts = @facts_matching.delete(token)
86
+ facts&.each { |fact| unlink_token(fact, token) }
87
+ end
88
+
89
+ # Whether `token` has at least one matching fact.
90
+ def matched?(token)
91
+ @facts_matching.key?(token)
92
+ end
93
+
94
+ # The facts that match `token`.
95
+ def facts_matching(token)
96
+ @facts_matching[token].to_a
97
+ end
98
+
99
+ # The tokens that `fact` matches.
100
+ def tokens_matched_by(fact)
101
+ @tokens_matched_by[fact].to_a
102
+ end
103
+
104
+ # Forgets every link, without telling the successors.
105
+ def reset
106
+ @facts_matching.clear
107
+ @tokens_matched_by.clear
108
+ end
109
+
110
+ private
111
+
112
+ def link(token, fact)
113
+ (@facts_matching[token] ||= Set.new) << fact
114
+ (@tokens_matched_by[fact] ||= Set.new.compare_by_identity) << token
115
+ end
116
+
117
+ def unlink_token(fact, token)
118
+ tokens = @tokens_matched_by[fact]
119
+ return unless tokens
120
+
121
+ tokens.delete(token)
122
+ @tokens_matched_by.delete(fact) if tokens.empty?
123
+ end
124
+
125
+ # Passes `token` on, extended by a position that holds no fact.
126
+ def emit(token)
127
+ new_token = Token.new(token, nil, self)
128
+ token.add_child(new_token)
129
+ activate_successors(new_token)
130
+ end
131
+
132
+ # Takes back what this node passed on for `token`.
133
+ def retract(token)
134
+ token.children.select { |child| child.node.equal?(self) }.each do |child|
135
+ token.remove_child(child)
136
+ deactivate_successors(child)
137
+ end
138
+ end
139
+ end
140
+ end
data/lib/kbs/rule.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KBS
4
+ # A named set of conditions and the action to run for each match.
4
5
  class Rule
5
6
  attr_reader :name, :priority
6
7
  attr_accessor :conditions, :action
@@ -19,28 +20,40 @@ module KBS
19
20
  @fired_count += 1
20
21
  return unless @action
21
22
 
22
- bindings = extract_bindings(facts)
23
+ bindings = bindings_for(facts)
23
24
 
24
- # Support both 1-parameter and 2-parameter actions
25
- if @action.arity == 1 || @action.arity == -1
25
+ # Support 0-parameter, 1-parameter and 2-parameter actions
26
+ if @action.arity.zero?
27
+ @action.call
28
+ elsif [1, -1].include?(@action.arity)
26
29
  @action.call(facts)
27
30
  else
28
31
  @action.call(facts, bindings)
29
32
  end
30
33
  end
31
34
 
32
- private
35
+ # The number of leading conditions that are logical. Facts the rule
36
+ # asserts are supported by the match of those conditions.
37
+ def logical_count
38
+ @conditions.take_while(&:logical).size
39
+ end
40
+
41
+ # Logical conditions have to come before every other condition.
42
+ def logical_conditions_first?
43
+ @conditions.drop(logical_count).none?(&:logical)
44
+ end
33
45
 
34
- def extract_bindings(facts)
35
- bindings = {}
36
- @conditions.each_with_index do |condition, index|
37
- next if condition.negated
38
- fact = facts[index]
39
- condition.variable_bindings.each do |var, field|
40
- bindings[var] = fact.attributes[field] if fact
41
- end
46
+ # Maps each variable to its value in the matched facts. The facts
47
+ # line up with the conditions that bind a fact; negated and exists
48
+ # conditions contribute none.
49
+ def bindings_for(facts)
50
+ @conditions.select(&:binds_fact?).zip(facts).each_with_object({}) do |(condition, fact), bindings|
51
+ bindings.merge!(condition.bindings_from(fact)) if fact
42
52
  end
43
- bindings
53
+ end
54
+
55
+ def to_s
56
+ RuleSource.new(name: @name, conditions: @conditions, action: @action, priority: @priority).to_s
44
57
  end
45
58
  end
46
59
  end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KBS
4
+ # Writes a rule as DSL source, from its parts. Procs in patterns and the
5
+ # action are decompiled; one that can't be is replaced by a placeholder.
6
+ #
7
+ # KBS::RuleSource.new(name: "hot", conditions: rule.conditions).to_s
8
+ # # => "rule \"hot\" do\n on :sensor\nend"
9
+ class RuleSource
10
+ def initialize(name:, conditions:, action: nil, priority: 0, description: nil)
11
+ @name = name
12
+ @conditions = conditions
13
+ @action = action
14
+ @priority = priority
15
+ @description = description
16
+ end
17
+
18
+ def to_s
19
+ ["rule #{@name.inspect} do", *header_lines, *condition_lines, *action_lines, "end"].join("\n")
20
+ end
21
+
22
+ # The desc and priority lines, when the rule has them.
23
+ def header_lines
24
+ lines = []
25
+ lines << " desc #{@description.inspect}" if @description
26
+ lines << " priority #{@priority}" unless @priority.zero?
27
+ lines
28
+ end
29
+
30
+ # One line per condition, the leading logical ones inside a
31
+ # `logical do ... end` block.
32
+ def condition_lines
33
+ count = @conditions.take_while(&:logical).size
34
+ lines = @conditions.each_with_index.map do |condition, index|
35
+ RuleSource.condition_line(condition, index < count ? " " : " ")
36
+ end
37
+ return lines if count.zero?
38
+
39
+ lines.insert(count, " end").unshift(" logical do")
40
+ end
41
+
42
+ def action_lines
43
+ @action ? [" perform #{RuleSource.block_source(@action)}"] : []
44
+ end
45
+
46
+ class << self
47
+ def condition_line(condition, indent)
48
+ pattern = pattern_source(condition.pattern)
49
+ line = "#{indent}#{condition.keyword} #{condition.type.inspect}"
50
+ pattern.empty? ? line : "#{line}, #{pattern}"
51
+ end
52
+
53
+ # A pattern as the keyword arguments of a condition.
54
+ def pattern_source(pattern)
55
+ pattern.map { |key, value| "#{key}: #{value_source(value)}" }.join(", ")
56
+ end
57
+
58
+ def value_source(value)
59
+ return value.inspect unless value.is_a?(Proc)
60
+
61
+ Decompiler.new(value).decompile
62
+ rescue StandardError => e
63
+ "<decompilation failed: #{e.message}>"
64
+ end
65
+
66
+ # A proc as a block literal: { |params| body }
67
+ def block_source(block)
68
+ Decompiler.new(block).decompile_block
69
+ rescue StandardError => e
70
+ "{ <decompilation failed: #{e.message}> }"
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KBS
4
+ # One condition of a rule as built into the network: the condition, the
5
+ # alpha memory of the facts that fit it, the node that joins it, and the
6
+ # beta memory of the partial matches up to and including it. The engine
7
+ # keeps one per condition of each rule for Engine#matches and
8
+ # Engine#join_activity.
9
+ RuleStep = Data.define(:condition, :alpha_memory, :node, :beta_memory) do
10
+ # How far the rule has matched at this condition.
11
+ def matches
12
+ { **label, alpha_matches: alpha_memory.size, partial_matches: beta_memory.size }
13
+ end
14
+
15
+ # The work this condition's node has done. Rules that share the node
16
+ # report the same counts.
17
+ def activity
18
+ { **label, indexed: node.indexed?, **node.activity.to_h }
19
+ end
20
+
21
+ private
22
+
23
+ def label
24
+ { keyword: condition.keyword, type: condition.type }
25
+ end
26
+ end
27
+ end
data/lib/kbs/token.rb CHANGED
@@ -1,29 +1,75 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KBS
4
+ # A partial match: the facts matched so far, as a chain of tokens with
5
+ # one link per condition.
4
6
  class Token
5
- attr_accessor :parent, :fact, :node, :children
7
+ attr_accessor :parent, :fact, :node
8
+
9
+ EMPTY_CHILDREN = Set.new.freeze
6
10
 
7
11
  def initialize(parent, fact, node)
8
12
  @parent = parent
9
13
  @fact = fact
10
14
  @node = node
11
- @children = []
15
+ @children = nil
12
16
  @fired = false
17
+ @retracted = false
18
+ @slots = build_slots
13
19
  end
14
20
 
15
- def facts
16
- facts = []
17
- token = self
18
- while token
19
- facts.unshift(token.fact) if token.fact
20
- token = token.parent
21
+ # @return [Set<KBS::Token>] the tokens that extend this one, so that
22
+ # removing this token can remove them without a search. Frozen and
23
+ # empty while there are none. Use #add_child and #remove_child to
24
+ # change them.
25
+ def children
26
+ case @children
27
+ when nil then EMPTY_CHILDREN
28
+ when Set then @children
29
+ else Set[@children].freeze
30
+ end
31
+ end
32
+
33
+ # Most tokens have one child or none, so @children holds a lone child
34
+ # itself and becomes a Set only for the second.
35
+ def add_child(token)
36
+ case @children
37
+ when nil then @children = token
38
+ when Set then @children << token
39
+ else @children = Set.new.compare_by_identity << @children << token unless @children.equal?(token)
40
+ end
41
+ end
42
+
43
+ def remove_child(token)
44
+ case @children
45
+ when Set then @children.delete(token)
46
+ when token then @children = nil
21
47
  end
22
- facts
48
+ end
49
+
50
+ def clear_children
51
+ @children = nil
52
+ end
53
+
54
+ # The matched facts, one per positive condition. Frozen: the slots
55
+ # themselves when every condition matched a fact, so that firing a
56
+ # rule allocates nothing for them.
57
+ def facts
58
+ @slots.include?(nil) ? @slots.compact.freeze : @slots
59
+ end
60
+
61
+ # One entry per condition matched so far: the matched fact, or nil
62
+ # for a negated or exists condition. Frozen.
63
+ attr_reader :slots
64
+
65
+ # The fact matched by the condition at `index` in the rule, or nil
66
+ # when that condition is negated.
67
+ def fact_at(index)
68
+ @slots[index]
23
69
  end
24
70
 
25
71
  def to_s
26
- "Token(#{facts.map(&:to_s).join(', ')})"
72
+ "Token(#{facts.join(', ')})"
27
73
  end
28
74
 
29
75
  def fired?
@@ -33,5 +79,25 @@ module KBS
33
79
  def mark_fired!
34
80
  @fired = true
35
81
  end
82
+
83
+ # Whether the engine has seen this token leave its beta memory. Only
84
+ # recorded for tokens that can logically support facts.
85
+ def retracted?
86
+ @retracted
87
+ end
88
+
89
+ def mark_retracted!
90
+ @retracted = true
91
+ end
92
+
93
+ private
94
+
95
+ # One entry per condition matched so far, nil for a negated one. The
96
+ # root dummy token (no parent, no fact) matches no condition.
97
+ def build_slots
98
+ return (@fact ? [@fact] : []).freeze unless @parent
99
+
100
+ [*@parent.slots, @fact].freeze
101
+ end
36
102
  end
37
103
  end