kbs 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +68 -1
- data/README.md +52 -25
- data/lib/kbs/agenda.rb +208 -0
- data/lib/kbs/alpha_memory.rb +55 -7
- data/lib/kbs/alpha_network.rb +83 -0
- data/lib/kbs/beta_memory.rb +54 -19
- data/lib/kbs/blackboard/audit_log.rb +26 -25
- data/lib/kbs/blackboard/engine.rb +49 -40
- data/lib/kbs/blackboard/fact.rb +17 -21
- data/lib/kbs/blackboard/memory.rb +116 -40
- data/lib/kbs/blackboard/message_queue.rb +39 -28
- data/lib/kbs/blackboard/persistence/hybrid_store.rb +20 -9
- data/lib/kbs/blackboard/persistence/redis_store.rb +59 -51
- data/lib/kbs/blackboard/persistence/sqlite_store.rb +29 -32
- data/lib/kbs/blackboard/persistence/store.rb +11 -1
- data/lib/kbs/blackboard/redis_message_queue.rb +16 -7
- data/lib/kbs/condition.rb +39 -2
- data/lib/kbs/decompiler.rb +300 -124
- data/lib/kbs/dsl/condition_helpers.rb +8 -6
- data/lib/kbs/dsl/knowledge_base.rb +73 -93
- data/lib/kbs/dsl/pattern_evaluator.rb +38 -15
- data/lib/kbs/dsl/rule_builder.rb +118 -40
- data/lib/kbs/dsl/variable.rb +51 -6
- data/lib/kbs/dsl.rb +10 -3
- data/lib/kbs/engine.rb +395 -77
- data/lib/kbs/errors.rb +38 -0
- data/lib/kbs/exists_node.rb +12 -0
- data/lib/kbs/fact.rb +5 -19
- data/lib/kbs/fact_registry.rb +51 -0
- data/lib/kbs/introspection.rb +93 -0
- data/lib/kbs/join_indexing.rb +104 -0
- data/lib/kbs/join_node.rb +93 -57
- data/lib/kbs/join_test_builder.rb +80 -0
- data/lib/kbs/join_tests.rb +66 -0
- data/lib/kbs/memory_index.rb +75 -0
- data/lib/kbs/negation_node.rb +6 -82
- data/lib/kbs/network_node.rb +31 -0
- data/lib/kbs/pattern_matching.rb +27 -0
- data/lib/kbs/production_node.rb +50 -6
- data/lib/kbs/quantifier_node.rb +140 -0
- data/lib/kbs/rule.rb +26 -13
- data/lib/kbs/rule_source.rb +74 -0
- data/lib/kbs/rule_step.rb +27 -0
- data/lib/kbs/token.rb +60 -10
- data/lib/kbs/tracer.rb +80 -0
- data/lib/kbs/truth_maintenance.rb +82 -0
- data/lib/kbs/version.rb +1 -1
- data/lib/kbs/working_memory.rb +25 -3
- data/lib/kbs.rb +17 -4
- metadata +22 -129
- data/.envrc +0 -3
- data/.github/workflows/deploy-github-pages.yml +0 -52
- data/COMMITS.md +0 -196
- data/Rakefile +0 -8
- data/docs/advanced/custom-persistence.md +0 -775
- data/docs/advanced/debugging.md +0 -726
- data/docs/advanced/index.md +0 -8
- data/docs/advanced/performance.md +0 -865
- data/docs/advanced/testing.md +0 -827
- data/docs/api/blackboard.md +0 -1157
- data/docs/api/engine.md +0 -1047
- data/docs/api/facts.md +0 -1212
- data/docs/api/index.md +0 -12
- data/docs/api/rules.md +0 -1104
- data/docs/architecture/blackboard.md +0 -544
- data/docs/architecture/index.md +0 -277
- data/docs/architecture/network-structure.md +0 -343
- data/docs/architecture/rete-algorithm.md +0 -737
- data/docs/assets/css/custom.css +0 -83
- data/docs/assets/images/blackboard-architecture.svg +0 -136
- data/docs/assets/images/compiled-network.svg +0 -101
- data/docs/assets/images/fact-assertion-flow.svg +0 -117
- data/docs/assets/images/fact-rule-relationship.svg +0 -65
- data/docs/assets/images/fact-structure.svg +0 -42
- data/docs/assets/images/inference-cycle.svg +0 -47
- data/docs/assets/images/kb-components.svg +0 -43
- data/docs/assets/images/kbs.jpg +0 -0
- data/docs/assets/images/pattern-matching-trace.svg +0 -136
- data/docs/assets/images/rete-network-layers.svg +0 -96
- data/docs/assets/images/rule-structure.svg +0 -44
- data/docs/assets/images/system-layers.svg +0 -69
- data/docs/assets/images/trading-signal-network.svg +0 -139
- data/docs/assets/js/mathjax.js +0 -17
- data/docs/examples/index.md +0 -223
- data/docs/guides/blackboard-memory.md +0 -589
- data/docs/guides/dsl.md +0 -1321
- data/docs/guides/facts.md +0 -652
- data/docs/guides/getting-started.md +0 -385
- data/docs/guides/index.md +0 -23
- data/docs/guides/negation.md +0 -529
- data/docs/guides/pattern-matching.md +0 -561
- data/docs/guides/persistence.md +0 -451
- data/docs/guides/variable-binding.md +0 -491
- data/docs/guides/writing-rules.md +0 -914
- data/docs/index.md +0 -155
- data/docs/installation.md +0 -156
- data/docs/quick-start.md +0 -221
- data/docs/what-is-a-fact.md +0 -694
- data/docs/what-is-a-knowledge-base.md +0 -350
- data/docs/what-is-a-rule.md +0 -833
- data/examples/.gitignore +0 -1
- data/examples/README.md +0 -531
- data/examples/advanced_example.rb +0 -270
- data/examples/advanced_example_dsl.rb +0 -224
- data/examples/ai_enhanced_kbs.rb +0 -523
- data/examples/ai_enhanced_kbs_dsl.rb +0 -538
- data/examples/blackboard_demo.rb +0 -50
- data/examples/blackboard_demo_dsl.rb +0 -50
- data/examples/car_diagnostic.rb +0 -64
- data/examples/car_diagnostic_dsl.rb +0 -54
- data/examples/concurrent_inference_demo.rb +0 -362
- data/examples/concurrent_inference_demo_dsl.rb +0 -362
- data/examples/csv_trading_system.rb +0 -559
- data/examples/csv_trading_system_dsl.rb +0 -525
- data/examples/iot_demo_using_dsl.rb +0 -83
- data/examples/portfolio_rebalancing_system.rb +0 -651
- data/examples/portfolio_rebalancing_system_dsl.rb +0 -613
- data/examples/redis_trading_demo.rb +0 -177
- data/examples/redis_trading_demo_dsl.rb +0 -177
- data/examples/rule_source_demo.rb +0 -123
- data/examples/run_all.rb +0 -50
- data/examples/run_all_dsl.rb +0 -49
- data/examples/sample_stock_data.csv +0 -46
- data/examples/stock_trading_advanced.rb +0 -469
- data/examples/stock_trading_advanced_dsl.rb +0 -404
- data/examples/temp_dsl.txt +0 -9392
- data/examples/timestamped_trading.rb +0 -286
- data/examples/timestamped_trading_dsl.rb +0 -258
- data/examples/trading_demo.rb +0 -334
- data/examples/trading_demo_dsl.rb +0 -322
- data/examples/working_demo.rb +0 -176
- data/examples/working_demo_dsl.rb +0 -160
- data/mkdocs.yml +0 -181
data/lib/kbs/engine.rb
CHANGED
|
@@ -1,13 +1,34 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module KBS
|
|
4
|
+
# The RETE rule engine: builds the network for each rule, matches facts
|
|
5
|
+
# as they are added and removed, and fires the activated rules.
|
|
4
6
|
class Engine
|
|
5
|
-
|
|
7
|
+
include Introspection
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
attr_reader :working_memory, :rules, :alpha_memories, :production_nodes, :agenda, :tracer
|
|
10
|
+
|
|
11
|
+
# @param strategy [Symbol] conflict resolution strategy; see KBS::Agenda
|
|
12
|
+
# @param fact_duplication [Boolean] whether working memory may hold two
|
|
13
|
+
# facts with the same type and attributes; see #fact_duplication=
|
|
14
|
+
def initialize(strategy: :definition, fact_duplication: true)
|
|
15
|
+
@fact_duplication = fact_duplication
|
|
16
|
+
@fact_registry = FactRegistry.new
|
|
17
|
+
@matching = false
|
|
18
|
+
@truth_maintenance = TruthMaintenance.new
|
|
19
|
+
@pending_retractions = []
|
|
20
|
+
@retracting = false
|
|
21
|
+
@firing = nil
|
|
22
|
+
@agenda = Agenda.new(strategy: strategy)
|
|
23
|
+
@tracer = Tracer.new
|
|
24
|
+
@rule_paths = {}
|
|
25
|
+
@halted = false
|
|
8
26
|
@working_memory = WorkingMemory.new
|
|
9
27
|
@rules = []
|
|
10
|
-
@
|
|
28
|
+
@alpha_network = AlphaNetwork.new
|
|
29
|
+
@alpha_memories = @alpha_network.memories
|
|
30
|
+
@fact_memories = {}
|
|
31
|
+
@beta_nodes = []
|
|
11
32
|
@production_nodes = {}
|
|
12
33
|
@root_beta_memory = BetaMemory.new
|
|
13
34
|
|
|
@@ -19,38 +40,283 @@ module KBS
|
|
|
19
40
|
end
|
|
20
41
|
|
|
21
42
|
def add_rule(rule)
|
|
43
|
+
unless rule.logical_conditions_first?
|
|
44
|
+
raise ArgumentError, "rule #{rule.name.inspect}: logical conditions must come before the other conditions"
|
|
45
|
+
end
|
|
46
|
+
|
|
22
47
|
@rules << rule
|
|
23
48
|
build_network_for_rule(rule)
|
|
24
49
|
end
|
|
25
50
|
|
|
51
|
+
# Adds a fact to working memory and matches it against the rules.
|
|
52
|
+
#
|
|
53
|
+
# With fact duplication off, a fact equal to one already in working
|
|
54
|
+
# memory is not added and the existing fact is returned.
|
|
55
|
+
#
|
|
56
|
+
# A fact added by the action of a rule with logical conditions is
|
|
57
|
+
# supported by the match of those conditions and is retracted when
|
|
58
|
+
# that match goes away. If the match is already gone, because an
|
|
59
|
+
# earlier step of the same action removed it, the fact is not added
|
|
60
|
+
# and nil is returned.
|
|
26
61
|
def add_fact(type, attributes = {})
|
|
62
|
+
ensure_not_matching!
|
|
63
|
+
support = current_support
|
|
64
|
+
return nil if support&.retracted?
|
|
65
|
+
|
|
66
|
+
existing = duplicate_of(type, attributes)
|
|
67
|
+
if existing
|
|
68
|
+
reinforce(existing, support)
|
|
69
|
+
return existing
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
fact = create_fact(type, attributes)
|
|
73
|
+
attach_support(fact, support) if support
|
|
74
|
+
fact
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Makes the fact and puts it in working memory, which matches it.
|
|
78
|
+
def create_fact(type, attributes)
|
|
27
79
|
fact = Fact.new(type, attributes)
|
|
28
80
|
@working_memory.add_fact(fact)
|
|
29
81
|
fact
|
|
30
82
|
end
|
|
31
83
|
|
|
32
84
|
def remove_fact(fact)
|
|
85
|
+
ensure_not_matching!
|
|
33
86
|
@working_memory.remove_fact(fact)
|
|
34
87
|
end
|
|
35
88
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
89
|
+
# Changes a fact's attributes and matches it again, as a retraction
|
|
90
|
+
# followed by an assertion: matches that depended on the old values
|
|
91
|
+
# go away, and rules the new values satisfy are activated, including
|
|
92
|
+
# rules that already fired for this fact.
|
|
93
|
+
#
|
|
94
|
+
# Setting an attribute with fact[:key] = value does not do this; the
|
|
95
|
+
# network keeps matching the values the fact had when it was added.
|
|
96
|
+
#
|
|
97
|
+
# @param changes [Hash] attributes to merge into the fact's
|
|
98
|
+
# @return [KBS::Fact, nil] the fact; the existing equal fact when
|
|
99
|
+
# duplication is off and the change makes this fact a duplicate (this
|
|
100
|
+
# fact is then removed); nil when the fact is not in working memory
|
|
101
|
+
def modify(fact, changes)
|
|
102
|
+
ensure_not_matching!
|
|
103
|
+
return nil unless @working_memory.include?(fact)
|
|
104
|
+
|
|
105
|
+
@working_memory.remove_fact(fact)
|
|
106
|
+
existing = duplicate_of(fact.type, fact.attributes.merge(changes))
|
|
107
|
+
return existing if existing
|
|
108
|
+
|
|
109
|
+
fact.attributes.merge!(changes)
|
|
110
|
+
@working_memory.add_fact(fact)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# Whether working memory may hold two facts with the same type and
|
|
114
|
+
# attributes. True by default.
|
|
115
|
+
attr_reader :fact_duplication
|
|
116
|
+
|
|
117
|
+
# Turning duplication off makes add_fact return the existing fact
|
|
118
|
+
# instead of adding an equal one. Duplicates already in working
|
|
119
|
+
# memory stay.
|
|
120
|
+
def fact_duplication=(allowed)
|
|
121
|
+
@fact_duplication = allowed
|
|
122
|
+
@fact_registry.clear
|
|
123
|
+
@working_memory.facts.each { |fact| @fact_registry.add(fact) } unless allowed
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# The fact in working memory with this type and attributes, when
|
|
127
|
+
# duplication is off; nil otherwise.
|
|
128
|
+
def duplicate_of(type, attributes)
|
|
129
|
+
return nil if @fact_duplication
|
|
130
|
+
|
|
131
|
+
@fact_registry.find(type, attributes)
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# Whether `fact` was asserted under logical conditions and will be
|
|
135
|
+
# retracted when the matches that support it are gone.
|
|
136
|
+
def logically_supported?(fact)
|
|
137
|
+
@truth_maintenance.supported?(fact)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# The matches that support `fact`, each as the facts that matched the
|
|
141
|
+
# rule's logical conditions. Empty for an unconditional fact.
|
|
142
|
+
def dependencies(fact)
|
|
143
|
+
@truth_maintenance.supports_of(fact).map(&:facts)
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# The facts that will lose a support if `fact` is retracted.
|
|
147
|
+
def dependents(fact)
|
|
148
|
+
@truth_maintenance.facts_depending_on(fact)
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# A beta memory calls this when a token that can support facts
|
|
152
|
+
# leaves it. Facts left without support are retracted once the
|
|
153
|
+
# current match is done.
|
|
154
|
+
def token_removed(token)
|
|
155
|
+
token.mark_retracted!
|
|
156
|
+
@pending_retractions.concat(@truth_maintenance.withdraw(token))
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# The token that supports facts asserted right now: the match of the
|
|
160
|
+
# firing rule's logical conditions. nil outside such a rule.
|
|
161
|
+
def current_support
|
|
162
|
+
return nil unless @firing
|
|
163
|
+
|
|
164
|
+
rule = @firing.rule
|
|
165
|
+
logical = rule.logical_count
|
|
166
|
+
return nil if logical.zero?
|
|
167
|
+
|
|
168
|
+
token = @firing.token
|
|
169
|
+
(rule.conditions.size - logical).times { token = token.parent }
|
|
170
|
+
token
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# A fact that already exists was asserted again. From a logical rule
|
|
174
|
+
# it gains a support, unless it is unconditional. From anywhere else
|
|
175
|
+
# it becomes unconditional.
|
|
176
|
+
def reinforce(fact, support)
|
|
177
|
+
if support.nil?
|
|
178
|
+
@truth_maintenance.release(fact)
|
|
179
|
+
elsif @truth_maintenance.supported?(fact)
|
|
180
|
+
@truth_maintenance.support(fact, support)
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# Records the support of a new fact. Matching the fact may itself
|
|
185
|
+
# have removed the support, in which case the fact goes straight
|
|
186
|
+
# back out.
|
|
187
|
+
def attach_support(fact, support)
|
|
188
|
+
if support.retracted?
|
|
189
|
+
@pending_retractions << fact
|
|
190
|
+
else
|
|
191
|
+
@truth_maintenance.support(fact, support)
|
|
192
|
+
end
|
|
193
|
+
retract_unsupported_facts
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
# Retracts the facts whose last support was withdrawn. Retracting
|
|
197
|
+
# one can withdraw the support of others; the loop takes those too.
|
|
198
|
+
def retract_unsupported_facts
|
|
199
|
+
return if @matching || @retracting
|
|
200
|
+
|
|
201
|
+
@retracting = true
|
|
202
|
+
begin
|
|
203
|
+
while (fact = @pending_retractions.shift)
|
|
204
|
+
remove_fact(fact)
|
|
44
205
|
end
|
|
206
|
+
ensure
|
|
207
|
+
@retracting = false
|
|
45
208
|
end
|
|
46
209
|
end
|
|
47
210
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
211
|
+
# Whether the engine is matching a fact right now.
|
|
212
|
+
def matching?
|
|
213
|
+
@matching
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
def ensure_not_matching!
|
|
217
|
+
raise MatchInProgressError if @matching
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def facts
|
|
221
|
+
@working_memory.facts
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
# Working memory calls this when a fact is added or removed.
|
|
225
|
+
def update(action, fact)
|
|
226
|
+
ensure_not_matching!
|
|
227
|
+
@matching = true
|
|
228
|
+
begin
|
|
229
|
+
if action == :add
|
|
230
|
+
@tracer.fact_added(fact)
|
|
231
|
+
@fact_registry.add(fact) unless @fact_duplication
|
|
232
|
+
match_fact(fact)
|
|
233
|
+
elsif action == :remove
|
|
234
|
+
@tracer.fact_removed(fact)
|
|
235
|
+
@fact_registry.remove(fact)
|
|
236
|
+
@truth_maintenance.release(fact)
|
|
237
|
+
unmatch_fact(fact)
|
|
52
238
|
end
|
|
239
|
+
ensure
|
|
240
|
+
@matching = false
|
|
53
241
|
end
|
|
242
|
+
retract_unsupported_facts
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
# Sends a new fact to every alpha memory whose pattern it matches,
|
|
246
|
+
# and remembers which ones, so that retracting it needs no matching.
|
|
247
|
+
def match_fact(fact)
|
|
248
|
+
memories = matching_alpha_memories(fact)
|
|
249
|
+
return if memories.empty?
|
|
250
|
+
|
|
251
|
+
@fact_memories[fact] = memories
|
|
252
|
+
memories.each { |memory| memory.activate(fact) }
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
# Takes a fact out of the alpha memories it went into. The fact is
|
|
256
|
+
# not matched again, so this works even if its attributes changed.
|
|
257
|
+
def unmatch_fact(fact)
|
|
258
|
+
memories = @fact_memories.delete(fact)
|
|
259
|
+
memories&.each { |memory| memory.deactivate(fact) }
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
# The alpha memories whose pattern `fact` matches.
|
|
263
|
+
def matching_alpha_memories(fact)
|
|
264
|
+
@alpha_network.memories_for(fact)
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
# The alpha memories that hold `fact`.
|
|
268
|
+
def alpha_memories_for(fact)
|
|
269
|
+
@fact_memories.fetch(fact, []).dup
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
# Fires activations from the agenda until it is empty: the highest
|
|
273
|
+
# priority first, then by the agenda's strategy. Facts that a rule
|
|
274
|
+
# asserts or retracts change the agenda before the next firing, so
|
|
275
|
+
# rules chain within one run. An activation fires once.
|
|
276
|
+
#
|
|
277
|
+
# @param limit [Integer, nil] stop after this many firings
|
|
278
|
+
# @return [Integer] the number of rules fired
|
|
279
|
+
def run(limit = nil)
|
|
280
|
+
@halted = false
|
|
281
|
+
fired = 0
|
|
282
|
+
|
|
283
|
+
until @halted || (limit && fired >= limit)
|
|
284
|
+
activation = @agenda.pop
|
|
285
|
+
break unless activation
|
|
286
|
+
|
|
287
|
+
@tracer.rule_fired(activation)
|
|
288
|
+
fire_activation(activation)
|
|
289
|
+
fired += 1
|
|
290
|
+
end
|
|
291
|
+
|
|
292
|
+
fired
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
# Stops the current run after the rule that is firing. Call it from a
|
|
296
|
+
# rule action.
|
|
297
|
+
def halt
|
|
298
|
+
@halted = true
|
|
299
|
+
end
|
|
300
|
+
|
|
301
|
+
def strategy
|
|
302
|
+
@agenda.strategy
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def strategy=(strategy)
|
|
306
|
+
@agenda.strategy = strategy
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
def fire_activation(activation)
|
|
310
|
+
@firing = activation
|
|
311
|
+
activation.node.fire_rule(activation.token)
|
|
312
|
+
ensure
|
|
313
|
+
@firing = nil
|
|
314
|
+
end
|
|
315
|
+
|
|
316
|
+
# Production nodes in firing order: higher rule priority first, and
|
|
317
|
+
# definition order among rules of equal priority.
|
|
318
|
+
def prioritized_production_nodes
|
|
319
|
+
@production_nodes.values.sort_by.with_index { |node, index| [-node.rule.priority, index] }
|
|
54
320
|
end
|
|
55
321
|
|
|
56
322
|
# Clear all transient RETE state while preserving the compiled rule network.
|
|
@@ -68,82 +334,134 @@ module KBS
|
|
|
68
334
|
# This method clears all four levels directly while preserving the
|
|
69
335
|
# root beta memory's dummy token (needed for first-condition joins).
|
|
70
336
|
def reset
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
@
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
# Their successors are intermediate BetaMemory nodes.
|
|
80
|
-
# The root beta memory is never a join node successor, so
|
|
81
|
-
# its dummy token is preserved.
|
|
82
|
-
alpha_mem.successors.each do |join_node|
|
|
83
|
-
next unless join_node.respond_to?(:successors)
|
|
84
|
-
join_node.successors.each do |beta_or_prod|
|
|
85
|
-
beta_or_prod.tokens.clear if beta_or_prod.respond_to?(:tokens)
|
|
86
|
-
end
|
|
87
|
-
end
|
|
88
|
-
end
|
|
337
|
+
clear_working_memory
|
|
338
|
+
clear_fact_records
|
|
339
|
+
clear_network_memories
|
|
340
|
+
@production_nodes.each_value(&:reset)
|
|
341
|
+
@agenda.clear
|
|
342
|
+
@root_beta_memory.each_token(&:clear_children)
|
|
343
|
+
restore_leading_negations
|
|
344
|
+
end
|
|
89
345
|
|
|
90
|
-
|
|
91
|
-
|
|
346
|
+
# Releases what the engine holds open. An in-memory engine holds
|
|
347
|
+
# nothing; an engine with a store closes it.
|
|
348
|
+
def close; end
|
|
349
|
+
|
|
350
|
+
private
|
|
92
351
|
|
|
93
|
-
|
|
94
|
-
|
|
352
|
+
# Empties working memory directly, without telling the observers:
|
|
353
|
+
# everything is being cleared.
|
|
354
|
+
def clear_working_memory
|
|
355
|
+
@working_memory.clear
|
|
95
356
|
end
|
|
96
357
|
|
|
97
|
-
|
|
358
|
+
# Forgets what the engine records about each fact.
|
|
359
|
+
def clear_fact_records
|
|
360
|
+
@fact_memories.clear
|
|
361
|
+
@fact_registry.clear
|
|
362
|
+
@truth_maintenance.clear
|
|
363
|
+
@pending_retractions.clear
|
|
364
|
+
end
|
|
98
365
|
|
|
99
|
-
|
|
100
|
-
|
|
366
|
+
# Empties every alpha memory, every node's own records and the beta
|
|
367
|
+
# memory below each node. The root beta memory is below no node, so
|
|
368
|
+
# its dummy token stays.
|
|
369
|
+
def clear_network_memories
|
|
370
|
+
@alpha_memories.each_value(&:clear)
|
|
371
|
+
@alpha_memories.each_value.flat_map(&:successors).uniq.each { |node| clear_node(node) }
|
|
372
|
+
end
|
|
101
373
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
# Build join tests - if pattern has :type that differs from condition.type,
|
|
108
|
-
# add it as an attribute test since it was overwritten in the merge
|
|
109
|
-
tests = []
|
|
110
|
-
if condition.pattern[:type] && condition.pattern[:type] != condition.type
|
|
111
|
-
# The pattern's :type should be checked as an attribute constraint
|
|
112
|
-
tests << {
|
|
113
|
-
token_field_index: index,
|
|
114
|
-
token_field: :type,
|
|
115
|
-
fact_field: :type,
|
|
116
|
-
operation: :eq,
|
|
117
|
-
expected_value: condition.pattern[:type]
|
|
118
|
-
}
|
|
119
|
-
end
|
|
374
|
+
def clear_node(node)
|
|
375
|
+
node.reset
|
|
376
|
+
node.successors.grep(BetaMemory).each(&:clear)
|
|
377
|
+
end
|
|
120
378
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
379
|
+
# A rule that starts with a negated condition matches while working
|
|
380
|
+
# memory is empty, so its match is rebuilt after a reset.
|
|
381
|
+
def restore_leading_negations
|
|
382
|
+
@root_beta_memory.successors.grep(NegationNode).each { |node| replay_tokens(@root_beta_memory, node) }
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
# Hands a node every token already in the memory above it.
|
|
386
|
+
def replay_tokens(beta_memory, node)
|
|
387
|
+
beta_memory.tokens.each { |token| node.left_activate(token) }
|
|
388
|
+
end
|
|
389
|
+
|
|
390
|
+
def build_network_for_rule(rule)
|
|
391
|
+
join_tests = JoinTestBuilder.new(rule.conditions).tests
|
|
392
|
+
last_logical = rule.logical_count - 1
|
|
393
|
+
path = @rule_paths[rule.name] = []
|
|
394
|
+
beta_memory = @root_beta_memory
|
|
395
|
+
rule.conditions.each_with_index do |condition, index|
|
|
396
|
+
node = add_condition_node(beta_memory, condition, join_tests[index])
|
|
397
|
+
beta_memory = node.successors.grep(BetaMemory).first
|
|
398
|
+
beta_memory.listener = self if index == last_logical
|
|
399
|
+
path << RuleStep.new(condition, node.alpha_memory, node, beta_memory)
|
|
132
400
|
end
|
|
401
|
+
add_production_node(rule, beta_memory)
|
|
402
|
+
end
|
|
403
|
+
|
|
404
|
+
# The node for `condition` below `beta_memory`: one that is already
|
|
405
|
+
# there doing the same work, or a new one brought up to date.
|
|
406
|
+
#
|
|
407
|
+
# @return [KBS::JoinNode, KBS::QuantifierNode]
|
|
408
|
+
def add_condition_node(beta_memory, condition, tests)
|
|
409
|
+
alpha_memory = get_or_create_alpha_memory(condition.pattern.merge(type: condition.type))
|
|
410
|
+
node_class = node_class_for(condition)
|
|
411
|
+
shareable_node(beta_memory, node_class, alpha_memory, tests) ||
|
|
412
|
+
build_node(beta_memory, node_class, alpha_memory, tests)
|
|
413
|
+
end
|
|
133
414
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
415
|
+
# Ends the rule's path with its production node. A rule with no
|
|
416
|
+
# conditions never matches.
|
|
417
|
+
def add_production_node(rule, beta_memory)
|
|
418
|
+
node = ProductionNode.new(rule, @agenda, order: @rules.size)
|
|
419
|
+
beta_memory.successors << node
|
|
420
|
+
@production_nodes[rule.name] = node
|
|
421
|
+
replay_tokens(beta_memory, node) unless rule.conditions.empty?
|
|
422
|
+
end
|
|
137
423
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
424
|
+
# A node already below `beta_memory` that does the same work: the
|
|
425
|
+
# same kind of node, on the same alpha memory, with the same tests.
|
|
426
|
+
# Rules that start with the same conditions share those nodes and
|
|
427
|
+
# the partial matches in their beta memories.
|
|
428
|
+
def shareable_node(beta_memory, node_class, alpha_memory, tests)
|
|
429
|
+
beta_memory.successors.find do |node|
|
|
430
|
+
node.instance_of?(node_class) && node.alpha_memory.equal?(alpha_memory) && node.tests == tests
|
|
142
431
|
end
|
|
143
432
|
end
|
|
144
433
|
|
|
434
|
+
# A new node with its beta memory, brought up to date with the
|
|
435
|
+
# tokens already in `beta_memory`.
|
|
436
|
+
def build_node(beta_memory, node_class, alpha_memory, tests)
|
|
437
|
+
node = node_class.new(alpha_memory, beta_memory, tests)
|
|
438
|
+
node.successors << BetaMemory.new
|
|
439
|
+
@beta_nodes << node
|
|
440
|
+
replay_tokens(beta_memory, node)
|
|
441
|
+
node
|
|
442
|
+
end
|
|
443
|
+
|
|
444
|
+
def node_class_for(condition)
|
|
445
|
+
return NegationNode if condition.negated
|
|
446
|
+
return ExistsNode if condition.exists
|
|
447
|
+
|
|
448
|
+
JoinNode
|
|
449
|
+
end
|
|
450
|
+
|
|
451
|
+
# A new alpha memory starts with the facts already in working memory.
|
|
452
|
+
# Facts go straight into its items: the memory has no successors yet,
|
|
453
|
+
# and existing alpha memories already hold their facts.
|
|
145
454
|
def get_or_create_alpha_memory(pattern)
|
|
146
|
-
@
|
|
455
|
+
@alpha_network.fetch(pattern) { |memory| seed_alpha_memory(memory, pattern) }
|
|
456
|
+
end
|
|
457
|
+
|
|
458
|
+
def seed_alpha_memory(memory, pattern)
|
|
459
|
+
@working_memory.facts.each do |fact|
|
|
460
|
+
next unless fact.matches?(pattern)
|
|
461
|
+
|
|
462
|
+
memory.add_item(fact)
|
|
463
|
+
(@fact_memories[fact] ||= []) << memory
|
|
464
|
+
end
|
|
147
465
|
end
|
|
148
466
|
end
|
|
149
467
|
end
|
data/lib/kbs/errors.rb
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module KBS
|
|
4
|
+
# Base class of the errors this gem raises.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# Raised when a fact is added, removed or modified while the engine is
|
|
8
|
+
# in the middle of matching another fact. This happens when a pattern
|
|
9
|
+
# predicate changes facts. A working-memory observer added with
|
|
10
|
+
# add_observer runs after the engine has matched the fact, so it does
|
|
11
|
+
# not raise. Change facts from rule actions instead, which run between
|
|
12
|
+
# matches.
|
|
13
|
+
class MatchInProgressError < Error
|
|
14
|
+
def initialize(message = "facts cannot be added, removed or modified while a fact is being matched")
|
|
15
|
+
super
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Raised when a DSL condition keyword such as `on`, `without` or
|
|
20
|
+
# `perform` is called on a rule builder whose rule has already been
|
|
21
|
+
# built, for example from inside the rule's `perform` block. The call
|
|
22
|
+
# could no longer change the rule.
|
|
23
|
+
class RuleBuiltError < Error
|
|
24
|
+
def initialize(rule_name, keyword)
|
|
25
|
+
super("rule #{rule_name.inspect} is already built; `#{keyword}` cannot change it " \
|
|
26
|
+
"(inside perform, use fact/assert/retract/modify/query to change working memory)")
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Raised when a DSL rule builder is asked to change working memory
|
|
31
|
+
# (fact, assert, retract, modify, query, ...) but was created without a
|
|
32
|
+
# knowledge base to forward the call to.
|
|
33
|
+
class NoKnowledgeBaseError < Error
|
|
34
|
+
def initialize(rule_name, method)
|
|
35
|
+
super("rule #{rule_name.inspect} has no knowledge base, so `#{method}` cannot reach working memory")
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module KBS
|
|
4
|
+
# An `exists` condition: passes a token on once, while at least one
|
|
5
|
+
# fact matches it, however many do. It binds no variables for later
|
|
6
|
+
# conditions and adds no fact to the match.
|
|
7
|
+
class ExistsNode < QuantifierNode
|
|
8
|
+
def passes_when_matched?
|
|
9
|
+
true
|
|
10
|
+
end
|
|
11
|
+
end
|
|
12
|
+
end
|
data/lib/kbs/fact.rb
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module KBS
|
|
4
|
+
# A typed set of attributes in working memory.
|
|
4
5
|
class Fact
|
|
6
|
+
include PatternMatching
|
|
7
|
+
|
|
5
8
|
attr_reader :id, :type, :attributes
|
|
6
9
|
|
|
7
10
|
def initialize(type, attributes = {})
|
|
@@ -18,26 +21,9 @@ module KBS
|
|
|
18
21
|
@attributes[key] = value
|
|
19
22
|
end
|
|
20
23
|
|
|
21
|
-
def matches?(pattern)
|
|
22
|
-
return false if pattern[:type] && pattern[:type] != @type
|
|
23
|
-
|
|
24
|
-
pattern.each do |key, value|
|
|
25
|
-
next if key == :type
|
|
26
|
-
|
|
27
|
-
if value.is_a?(Proc)
|
|
28
|
-
return false unless @attributes[key] && value.call(@attributes[key])
|
|
29
|
-
elsif value.is_a?(Symbol) && value.to_s.end_with?('?')
|
|
30
|
-
next
|
|
31
|
-
else
|
|
32
|
-
return false unless @attributes[key] == value
|
|
33
|
-
end
|
|
34
|
-
end
|
|
35
|
-
|
|
36
|
-
true
|
|
37
|
-
end
|
|
38
|
-
|
|
39
24
|
def to_s
|
|
40
|
-
|
|
25
|
+
attributes = @attributes.map { |key, value| "#{key}: #{value.inspect}" }.join(", ")
|
|
26
|
+
"fact #{@type.inspect}#{", #{attributes}" unless attributes.empty?}"
|
|
41
27
|
end
|
|
42
28
|
end
|
|
43
29
|
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module KBS
|
|
4
|
+
# Finds the fact in working memory that has a given type and attributes,
|
|
5
|
+
# so an engine can refuse to hold the same fact twice.
|
|
6
|
+
#
|
|
7
|
+
# A fact is filed under a copy of its attributes taken when it is
|
|
8
|
+
# added, so it is still found, and still removed, after its attributes
|
|
9
|
+
# change.
|
|
10
|
+
class FactRegistry
|
|
11
|
+
def initialize
|
|
12
|
+
@facts = {}
|
|
13
|
+
@keys = {}
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Files `fact` unless an equal fact is already filed.
|
|
17
|
+
#
|
|
18
|
+
# @return [Boolean] whether the fact was filed
|
|
19
|
+
def add(fact)
|
|
20
|
+
key = self.class.key(fact.type, fact.attributes)
|
|
21
|
+
return false if @facts.key?(key)
|
|
22
|
+
|
|
23
|
+
@facts[key] = fact
|
|
24
|
+
@keys[fact] = key
|
|
25
|
+
true
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def remove(fact)
|
|
29
|
+
key = @keys.delete(fact)
|
|
30
|
+
@facts.delete(key) if key
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# @return [Object, nil] the filed fact with this type and attributes
|
|
34
|
+
def find(type, attributes)
|
|
35
|
+
@facts[self.class.key(type, attributes)]
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def size
|
|
39
|
+
@facts.size
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def clear
|
|
43
|
+
@facts.clear
|
|
44
|
+
@keys.clear
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def self.key(type, attributes)
|
|
48
|
+
[type, attributes.dup.freeze]
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|