-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmetta_learner_no_panda.py
executable file
·3998 lines (3262 loc) · 139 KB
/
metta_learner_no_panda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
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
784
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
print(";; ...doing...",__name__)
# Version Space Candidate Elimination inside of MeTTa
# This implementation focuses on bringing this machine learning algorithm into the MeTTa relational programming environment.
# Douglas R. Miles 2023
# Standard Library Imports
import atexit, io, inspect, json, os, re, subprocess, sys, traceback
from collections import Counter
from glob import glob
from time import monotonic_ns, time
# Global Variables
VSPACE_VERBOSE = os.environ.get("VSPACE_VERBOSE")
# 0 = for scripts/demos
# 1 = developer
# 2 = debugger
verbose = 1
if VSPACE_VERBOSE is not None:
try: verbose = int(VSPACE_VERBOSE) # Convert it to an integer
except ValueError: ""
# Third-Party Imports
try: from pyswip import (Atom as PySwipAtom, Term, call, Functor, PL_discard_foreign_frame, PL_new_term_ref, PL_open_foreign_frame,
registerForeign, PL_PRUNED, PL_retry, PL_FA_NONDETERMINISTIC, PL_foreign_control, PL_foreign_context, PL_FIRST_CALL, PL_REDO, Variable, Prolog as PySwip)
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
try: from pyswip.easy import newModule, Query
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
try: import hyperonpy as hp
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
try: from hyperon.atoms import *
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
try: from hyperon.base import AbstractSpace, SpaceRef, GroundingSpace, interpret
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
try: from hyperon.base import *
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
try: from hyperon.ext import register_atoms, register_tokens
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
try: from hyperon.runner import MeTTa
except ImportError as e:
if verbose>0: print(f"; Error: {e}")
# Readline Imports (Platform Specific)
try: import readline
except ImportError: import pyreadline3 as readline
# Error Handling for Janus
try: from janus import *
except Exception as e:
if verbose>0: print(f"; Error: {e}")
# Error Handling for OpenAI
try:
import openai
try: openai.api_key = os.environ["OPENAI_API_KEY"]
except KeyError: ""
except Exception as e:
if verbose>0: print(f"; Error: {e}")
histfile = os.path.join(os.path.expanduser("~"), ".metta_history")
is_init = True
oper_dict = {}
janus_dict = {}
syms_dict = {}
def parent_space():
return the_python_runner.parent.space()
def child_space():
return the_python_runner.space()
def self_space():
return the_new_runner_space
space_refs = {
#'&vspace': lambda: the_verspace,
'&gptspace': lambda: the_gptspace,
#'&flybase': lambda: the_flybase,
'&parent': lambda: parent_space(),
'&child': lambda: child_space(),
'&self': self_space}
try:
readline.set_history_length(300)
readline.read_history_file(histfile)
readline.set_history_length(300)
h_len = readline.get_current_history_length()
except FileNotFoundError:
open(histfile, 'wb').close()
h_len = 0
def add_to_history_if_unique(item, position_from_last=1):
for i in range(1, readline.get_current_history_length() + 1):
if readline.get_history_item(i) == item: return
insert_to_history(item, position_from_last)
def insert_to_history(item, position_from_last=5):
hist = [readline.get_history_item(i) for i in range(1, readline.get_current_history_length() + 1)]
# Remove the item from the list if it already exists before the insertion position
insertion_position = max(0, len(hist) - position_from_last)
if item in hist[:insertion_position]:
hist.remove(item)
# Insert the item at the desired position
hist.insert(insertion_position, item)
# Clear and repopulate the history
readline.clear_history()
for h in hist:
readline.add_history(h)
def readline_add_history(t):
readline.add_history(t)
insert_to_history('!(get-by-key &my-dict "A")')
insert_to_history("@metta !")
insert_to_history("!(mine-overlaps)")
insert_to_history("!(try-overlaps)")
insert_to_history("!(load-flybase-full)")
insert_to_history("!(load-flybase-tiny)")
#insert_to_history("!(load-vspace)")
insert_to_history("!(learn-vspace)")
insert_to_history('!(match &parent (gene_map_table $Dmel $abo $G $C $D $E) (gene_map_table $Dmel $abo $G $C $D $E) )')
insert_to_history('!(match &parent (gene_map_table $Dmel $abo (GeneValueNode "FBgn0000018") $C $D $E) (gene_map_table $Dmel $abo (GeneValueNode "FBgn0000018") $C $D $E))')
insert_to_history('!(add-atom &parent (gene_map_table (ConceptNode "Dmel") (ConceptNode "abo") (GeneValueNode "FBgn0000018") (ConceptNode "2-44") (ConceptNode "32C1-32C1") (StringValue "2L:10973443..10975293(-1)")))')
insert_to_history("!(match &parent $ $)")
insert_to_history("!(match &flybase $ $)")
insert_to_history('!(match &flybase (gene_map_table $Dmel $abo $G $C $D $E) (gene_map_table $Dmel $abo $G $C $D $E) )')
insert_to_history('!(match &flybase (gene_map_table $Dmel $abo (GeneValueNode "FBgn0000018") $C $D $E) (gene_map_table $Dmel $abo (GeneValueNode "FBgn0000018") $C $D $E))')
insert_to_history('!(add-atom &flybase (gene_map_table (ConceptNode "Dmel") (ConceptNode "abo") (GeneValueNode "FBgn0000018") (ConceptNode "2-44") (ConceptNode "32C1-32C1") (StringValue "2L:10973443..10975293(-1)")))')
insert_to_history('!(match &flybase (gene_map_table $Dmel $abo FBgn0000018 $C $D $E) (gene_map_table $Dmel $abo FBgn0000018 $C $D $E))')
insert_to_history('!(test_custom_v_space)', position_from_last=1)
OPTIONS = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# The completer function
def completer(text, state):
options = [i for i in OPTIONS if i.startswith(text)]
if state < len(options):
return options[state]
else:
return None
# Register the completer function
readline.set_completer(completer)
# Use the tab key for completion
readline.parse_and_bind('tab: complete')
def save(prev_h_len, histfile):
new_h_len = readline.get_current_history_length()
readline.set_history_length(400)
readline.append_history_file(new_h_len - prev_h_len, histfile)
atexit.register(save, h_len, histfile)
def export_to_metta(func):
setattr(func, 'metta', True)
if verbose>3: print_cmt(f"{func}={getattr(func, 'export_to_metta', False)}")
return func
def export_flags(**kwargs):
def decorator(func):
if verbose > 1: print(f"; export_flags({repr(func)})", end=" ")
for n in kwargs:
setattr(func, n, kwargs[n])
if verbose > 1:
for n in kwargs:
print(f"{repr(n)}={repr(getattr(func, n, None))}", end=" ")
print()
return func
return decorator
def get_call_parts(func):
sig = inspect.signature(func)
params = sig.parameters
# Constructing full parameter strings
param_parts = []
params_call_parts = []
var_args = var_kwargs = None
for param_name, param in params.items():
part = param_name
call_part = param_name
if param.kind == inspect.Parameter.VAR_POSITIONAL:
var_args = f'*{param_name}'
part = var_args
call_part = var_args
elif param.kind == inspect.Parameter.VAR_KEYWORD:
var_kwargs = f'**{param_name}'
part = var_kwargs
call_part = var_kwargs
elif param.default != inspect.Parameter.empty and isinstance(param.default, (int, str)):
part += f'={repr(param.default)}'
param_parts.append(part)
params_call_parts.append(call_part)
return param_parts, params_call_parts
def add_janus_methods(module, dict = janus_dict):
for name, func in inspect.getmembers(module):
if inspect.isfunction(func):
if getattr(func, "Janus", False) or getattr(func, "MeTTa", False):
use_name = getattr(func, 'name', name)
non_underscore_attrs = {attr: getattr(func, attr) for attr in dir(func) if not attr.startswith('_')}
if len(non_underscore_attrs)==0: continue
param_parts, params_call_parts = get_call_parts(func)
add_to_janus(use_name, param_parts, params_call_parts, func,non_underscore_attrs, janus_dict)
@export_flags(MeTTa=True)
def add_python_module(module, dict=oper_dict):
for name, func in inspect.getmembers(module):
if inspect.isfunction(func):
add_python_function(name, func, dict)
def add_python_function(name, func, dict):
use_name = getattr(func, 'name', name)
non_underscore_attrs = {attr: getattr(func, attr) for attr in dir(func) if not attr.startswith('_')}
if len(non_underscore_attrs)==0: return False
param_parts, params_call_parts = get_call_parts(func)
added = False
if getattr(func, "Janus", False):
added = add_to_janus(use_name, param_parts, params_call_parts,
func, non_underscore_attrs, janus_dict) or added
if getattr(func, 'MeTTa', False):
added = add_to_metta(use_name, param_parts, params_call_parts,
getattr(func, 'op', "OperationAtom"), getattr(func, 'unwrap', False),
func, non_underscore_attrs, dict) or added
if not added and verbose > 3:
print_cmt(f"unused({name}({param_parts})) attributes: {non_underscore_attrs}")
return added
@export_flags(MeTTa=True)
def add_to_metta(name, param_parts, params_call_parts, op_kind, unwrap, func, non_underscore_attrs, dict=oper_dict):
hyphens, underscores = name.replace('_', '-'), name.replace('-', '_')
# Construct the param_str from param_parts
metta_params_str = ' '.join(param_parts)
s = f"!({hyphens})" if metta_params_str == "" else f"!({hyphens} {metta_params_str})"
add_to_history_if_unique(s)
if hyphens in dict:
return True
# Construct the param_str from param_parts
param_str = ', '.join(param_parts)
# Using params_call_parts in the function call inside lambda
params_for_call = ', '.join(params_call_parts)
# Constructing the source code to execute
src = f'op = {op_kind}("{hyphens}", lambda {param_str}: [{underscores}({params_for_call})], unwrap={unwrap})'
local_vars = {}
if verbose > 1:
print_cmt(f"{src} # {non_underscore_attrs}"[5:])
try:
exec(src, globals(), local_vars)
dict[hyphens] = local_vars['op']
dict[underscores] = local_vars['op']
return True
except SyntaxError as e:
print_cmt(f"Syntax error in executing: {src}")
print_cmt(f"Error details: {e}")
return False
def add_to_janus(name, param_parts, params_call_parts, func, non_underscore_attrs, dict = janus_dict):
if getattr(func, 'CallsVSpace', False): return False
#if not getattr(func, "Janus", False): return False
suggestedName = getattr(func, 'name', name)
if suggestedName is not None:
use_name = suggestedName
else: use_name = name
for key, item in dict.items():
if key==use_name:
return True
suggestedFlags = getattr(func, 'flags', None)
if suggestedFlags is None:
suggestedFlags = 0
suggestedArity = getattr(func, 'arity', None)
if suggestedArity is None:
num_args = len(param_parts)
suggestedArity = num_args
func.arity = suggestedArity
#if verbose > 1:
print_cmt(f"registerForeign({use_name}, arity = {param_parts}/{suggestedArity}, flags = {suggestedFlags} ) {non_underscore_attrs}")
#if not getattr(func, "Janus", False): return False
dict[use_name]=func
registerForeign(func, arity = suggestedArity, flags = suggestedFlags )
return True
#############################################################################################################################
# @export_flags(MeTTa=True)
# def add_python_module(module, dict = oper_dict):
#
# for name, func in inspect.getmembers(module):
# if inspect.isfunction(func):
# if getattr(func, 'MeTTa', False):
# suggestedName = getattr(func, 'name', None)
# if suggestedName is not None:
# use_name = suggestedName
# else: use_name = name
# suggestedArity = getattr(func, 'arity', None)
# sig = inspect.signature(func)
# params = sig.parameters
#
# num_args = len([p for p in params.values() if p.default == p.empty and p.kind == p.POSITIONAL_OR_KEYWORD])
# # Check for varargs
# has_varargs = any(p.kind == p.VAR_POSITIONAL for p in params.values())
# if suggestedArity is None: suggestedArity = num_args
#
# keyword_arg_names = []
# # Iterate through parameters
# for name, param in params.items():
# # Check if the parameter is either VAR_KEYWORD or has a default value
# if param.kind == inspect.Parameter.VAR_KEYWORD or param.default != inspect.Parameter.empty:
# keyword_arg_names.append(name)
#
# if is_varargs==True or has_varargs:
# suggestedArity = -1
# add_to_metta(use_name, suggestedArity,
# getattr(func, 'op', "OperationAtom"),
# getattr(func, 'unwrap', False), func, dict)
#
# @export_flags(MeTTa=True)
# def add_to_metta(name, length, op_kind, unwrap, funct, dict = oper_dict):
# hyphens, underscores = name.replace('_', '-'), name.replace('-', '_')
# mettavars = ' '.join(f"${chr(97 + i)}" for i in range(length)).strip()
# pyvars = ', '.join(chr(97 + i) for i in range(length)).strip()
#
# if length == -1: #varargs
# pyvars = "*args"
# mettavars = "..."
#
# s = f"!({hyphens})" if mettavars == "" else f"!({hyphens} {mettavars})"
# add_to_history_if_unique(s); #print(s)
# if hyphens not in dict:
# src, local_vars = f'op = {op_kind}( "{hyphens}", lambda {pyvars}: [{underscores}({pyvars})], unwrap={unwrap})', {}
# if verbose>1: print_cmt(f"add_to_metta={src}")
# if verbose>8: print_cmt(f"funct={dir(funct)}")
# exec(src, globals(), local_vars)
# dict[hyphens] = local_vars['op']
# dict[underscores] = local_vars['op']
#
#############################################################################################################################
# Function to find subclasses of clazz in a module
def find_subclasses_of(module, clazz):
subclasses = {}
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and issubclass(obj, clazz) and obj is not clazz:
subclasses[name]=obj
return subclasses.items()
for name, claz in find_subclasses_of(module,AbstractSpace):
print(f"found class {claz} with name {name}")
# inspect the constructor and syntesize a function that will create an object
@export_flags(MeTTa=True)
def add_to_swip(name, dict = oper_dict):
hyphens, underscores = name.replace('_', '-'), name.replace('-', '_')
add_to_history_if_unique(f"!({hyphens})")
if hyphens not in dict:
src, local_vars = f'op = lambda : [swip_exec("{underscores}")]', {}
exec(src, {}, local_vars)
if verbose>1: print_cmt(f"swip: {hyphens}")
dict[hyphens] = OperationAtom(hyphens, local_vars['op'], unwrap=False)
def addSpaceName(name, space):
global syms_dict, space_refs
prev = getSpaceByName(name)
name = str(name)
if not name.startswith("&"):
name = "&" + name
syms_dict[name] = lambda _: G(asSpaceRef(space))
if prev is None:
space_refs[name] = lambda : space
def getSpaceByName(name):
global space_refs
if name is ValueAtom:
name = name.get_value()
if name is GroundingSpace:
return name
name = str(name)
if not name.startswith("&"):
name = "&" + name
found = space_refs.get(name, None)
if found is None: return None
return found()
def getNameBySpace(target_space):
if target_space is None:
return None
global space_refs, syms_dict
# Search in space_refs
for name, space_func in space_refs.items():
S = space_func()
if S is target_space:
return name
if S:
if id(S) == id(target_space):
return name
# Search in syms_dict
for name, space_func in syms_dict.items():
GR = space_func(None)
if GR:
if id(GR) == id(target_space):
return name
if id(GR.get_object()) == id(target_space):
return name
return None
vspace_ordinal = 0
# Mainly a sanity loading test class
class MettaLearner:
""
class Circles:
def __init__(self, initial_data=None):
self.data = {}
if initial_data:
for key, value in initial_data.items():
self.__setitem__(key, value)
def _get_key(self, key):
try:
hash_key = hash(key)
return ('hash', hash_key)
except TypeError:
id_key = id(key)
return ('id', id_key)
def __getitem__(self, key):
key_type, key_value = self._get_key(key)
return self.data[(key_type, key_value)][1]
def __setitem__(self, key, value):
key_type, key_value = self._get_key(key)
self.data[(key_type, key_value)] = (key, value)
def __delitem__(self, key):
key_type, key_value = self._get_key(key)
del self.data[(key_type, key_value)]
def __contains__(self, key):
key_type, key_value = self._get_key(key)
return (key_type, key_value) in self.data
def __len__(self):
return len(self.data)
def __iter__(self):
for key_tuple in self.data.keys():
yield key_tuple
def original_keys(self):
for key, _ in self.data.values():
yield key
def get(self, key, default=None):
key_type, key_value = self._get_key(key)
if (key_type, key_value) in self.data:
return self.data[(key_type, key_value)][1]
else:
return default
def items(self):
return [(key, value) for key, value in self.data.values()]
def keys(self):
return [key for key, _ in self.data.values()]
def values(self):
return [value for _, value in self.data.values()]
def clear(self):
self.data.clear()
def pop(self, key, default=None):
key_type, key_value = self._get_key(key)
return self.data.pop((key_type, key_value), (None, default))[1]
def popitem(self):
_, (key, value) = self.data.popitem()
return (key, value)
def setdefault(self, key, default=None):
key_type, key_value = self._get_key(key)
return self.data.setdefault((key_type, key_value), (key, default))[1]
def update(self, other):
for key, value in other.items():
self.__setitem__(key, value)
# subclass to later capture any utility we can add to 'subst'
def asSpaceRef(obj):
if isinstance(obj, (VSpaceRef, SpaceRef)):
return obj
return VSpaceRef(obj)
try:
class VSpaceRef(SpaceRef):
"""
A reference to a Space, which may be accessed directly, wrapped in a grounded atom,
or passed to a MeTTa interpreter.
"""
def __init__(self, space_obj):
"""
Initialize a new SpaceRef based on the given space object, either a CSpace
or a custom Python object.
"""
super().__init__(space_obj)
self.py_space_obj = space_obj
#if type(space_obj) is hp.CSpace:
# self.cspace = space_obj
#else:
# self.cspace = hp.space_new_custom(space_obj)
def is_VSpace(self):
return isinstance(self.py_space_obj,VSpace)
def get_atoms(self):
"""
Returns a list of all Atoms in the Space, or None if that is impossible
"""
if self.is_VSpace():
return self.py_space_obj.get_atoms()
res = hp.space_list(self.cspace)
if res == None:
return None
result = []
for r in res:
result.append(Atom._from_catom(r))
return result
def __del__(self):
"""Free the underlying CSpace object """
return
if self.is_VSpace(): self.py_space_obj.__del__()
else: hp.space_free(self.cspace)
def __eq__(self, other):
"""Compare two SpaceRef objects for equality, based on their underlying spaces."""
if not isinstance(other,SpaceRef): return False
if self.is_VSpace(): return get_payload(self) is other.get_payload(self)
else: return hp.space_eq(self.cspace, other.cspace)
@staticmethod
def _from_cspace(cspace):
"""
Create a new SpaceRef based on the given CSpace object.
"""
return asSpaceRef(cspace)
def copy(self):
"""
Returns a new copy of the SpaceRef, referencing the same underlying Space.
"""
return self
def add_atom(self, atom):
"""
Add an Atom to the Space.
"""
if self.is_VSpace():
return self.py_space_obj.add(atom)
hp.space_add(self.cspace, atom.catom)
def remove_atom(self, atom):
"""
Delete the specified Atom from the Space.
"""
if self.is_VSpace():
return self.py_space_obj.remove(atom)
return hp.space_remove(self.cspace, atom.catom)
def replace_atom(self, atom, replacement):
"""
Replaces the specified Atom, if it exists in the Space, with the supplied replacement.
"""
if self.is_VSpace():
return self.py_space_obj.replace(atom, replacement)
return hp.space_replace(self.cspace, atom.catom, replacement.catom)
def atom_count(self):
"""
Returns the number of Atoms in the Space, or -1 if it cannot be readily computed.
"""
if self.is_VSpace():
return self.py_space_obj.atom_count()
return hp.space_atom_count(self.cspace)
def get_payload(self):
"""
Returns the Space object referenced by the SpaceRef, or None if the object does not have a
direct Python interface.
"""
if self.is_VSpace():
return self.py_space_obj;
return hp.space_get_payload(self.cspace)
def query(self, pattern):
"""
Performs the specified query on the Space, and returns the result as a BindingsSet.
"""
if self.is_VSpace():
return self.py_space_obj.query(pattern);
result = hp.space_query(self.cspace, pattern.catom)
return BindingsSet(result)
def subst(self, pattern, templ):
"""
Performs a substitution within the Space
"""
if self.is_VSpace():
return self.py_space_obj.subst(pattern, templ);
cspace = super().cspace
return [Atom._from_catom(catom) for catom in
hp.space_subst(cspace, pattern.catom,
templ.catom)]
@export_flags(MeTTa=True)
class VSpace(AbstractSpace):
def from_space(self, cspace):
self.gspace = GroundingSpaceRef(cspace)
def __init__(self, space_name=None, unwrap=False):
super().__init__()
#addSpaceName(ispace_name,self)
if space_name is None:
global vspace_ordinal
ispace_name = f"&vspace_{vspace_ordinal}"
vspace_ordinal=vspace_ordinal+1
space_name = ispace_name
self.sp_name = PySwipAtom(space_name)
swip.assertz(f"was_asserted_space('{space_name}')")
#swip.assertz(f"was_space_type('{space_name}',asserted_space)")
self.sp_module = newModule("user")
self.unwrap = unwrap
addSpaceName(space_name,self)
def __del__(self):
return
pass
def swip_space_name(self):
return swipRef(self.sp_name)
#return self.sp_name
@foreign_framed
def query(self, query_atom):
new_bindings_set = BindingsSet.empty()
#swipl_load = PL_new_term_ref()
metta_vars = [atom for atom in query_atom.iterate() if atom.get_type() == AtomKind.VARIABLE]
metaVarNames = [str(atom) for atom in metta_vars]
circles = Circles()
swivars = [m2s(circles,item,1) for item in metta_vars]
varsList = Variable()
varsList.unify(swivars)
varNames = Variable()
varNames.unify(metaVarNames)
swip_obj = m2s(circles,query_atom)
if verbose>1: print_cmt(f"circles={circles}")
#if verbose>1: print_cmt(f"metta_vars={metta_vars}, swivars={swivars}")
q = PySwipQ(Functor('metta_iter_bind',4)
(self.swip_space_name(), swip_obj, varsList, varNames), module=self.sp_module)
while q.nextSolution():
swivars = varsList.value
bindings = Bindings()
vn = 0
for mv in metta_vars:
svar = swivars[vn]
sval = svar
if verbose>1: pt(f"svar({vn})=",svar, " ")
if isinstance(svar, Variable):
sval = sval.value
else: sval = svar
if verbose>1: pt(f"sval({vn})=",sval, " ")
mval = s2m(circles,sval)
if verbose>1: pt(f"mval({vn})=",mval, " ")
bindings.add_var_binding(mv, mval)
vn = vn + 1
new_bindings_set.push(bindings)
q.closeQuery()
return new_bindings_set
def _call(self, functor_name, *args):
q = PySwipQ(Functor(functor_name, len(args) + 1)(self.swip_space_name(), *args), module=self.sp_module)
try: return q.nextSolution()
except Exception as e:
if verbose>0: print_cmt(f"Error: {e}")
if verbose>0: traceback.print_exc()
finally: q.closeQuery()
@foreign_framed
def add(self, atom):
circles = Circles()
return self._call("add-atom", m2s(circles,atom))
@foreign_framed
def add_atom(self, atom):
circles = Circles()
return self._call("add-atom", m2s(circles,atom))
@foreign_framed
def remove_atom(self, atom):
circles = Circles()
return self._call("remove-atom", m2s(circles,atom))
@foreign_framed
def remove(self, atom):
circles = Circles()
return self._call("remove-atom", m2s(circles,atom))
@foreign_framed
def replace(self, from_atom, to_atom):
circles = Circles()
return self._call("replace-atom", m2s(circles,from_atom), m2s(circles,to_atom))
@foreign_framed
def subst(self, pattern, templ):
"""
Performs a substitution within the Space
"""
circles = Circles()
return self._call("subst_pattern_template", m2s(circles,pattern), m2s(circles,templ))
@foreign_framed
def atom_count(self):
result = list(swip.query(f"'atom-count'('{self.sp_name}',AtomCount)"))
if verbose>1: print_cmt(result)
if result is None: return 0
if len(result)==0: return 0
CB = result[0]
if CB is None: return 0
C = CB['AtomCount']
if not isinstance(C,int):
C = C.value
return C
@foreign_framed
def get_atoms(self):
circles = Circles()
result = list(swip.query(f"'get-atoms'('{self.sp_name}',AtomsList)"))
if result is None: return []
if len(result)==0: return []
CB = result[0]
if CB is None: return []
C = CB['AtomsList']
if verbose>1: print_cmt(f"get_atoms={type(C)}")
R = s2m(circles,C)
return R
def atoms_iter(self):
swipl_fid = PL_open_foreign_frame()
Atoms = Variable("Iter")
q = PySwipQ(Functor("atoms_iter", 2)(self.swip_space_name(), Atoms), module=self.sp_module)
def closeff():
nonlocal swipl_fid
ff = swipl_fid
swipl_fid = None
if ff is not None:
PL_discard_foreign_frame(ff)
class LazyIter:
circles = Circles()
def __init__(self, q, v):
self.q, self.v = q, v
def __iter__(self):
return self
def __next__(self):
if self.q.nextSolution():
return s2m(circles,self.v.value.value)
closeff()
raise StopIteration
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.q.closeQuery()
closeff()
return LazyIter(q, Atoms)
def copy(self):
return self
class VSpaceCallRust(VSpace):
def __init__(self, space_name=None, unwrap=False):
super().__init__()
#def eval_in_rust_mettaf():
@export_flags(MeTTa=True)
class FederatedSpace(VSpace):
def __init__(self, space_name, unwrap=False):
super().__init__(space_name, unwrap)
def _checked_impl(self, method_name, *args):
if access_error:
raise Exception(f"Error in FederatedSpace.{method_name}: Implementation for {method_name}({', '.join(map(str, args))}) is not complete.")
return super()
def query(self, query_atom):
return self._checked_impl("query", query_atom).query(query_atom)
def add(self, atom):
return self._checked_impl("add", atom).add(atom)
def remove(self, atom):
return self._checked_impl("remove", atom).remove(atom)
def replace(self, from_atom, to_atom):
return self._checked_impl("replace", from_atom, to_atom).replace(from_atom, to_atom)
def atom_count(self):
return self._checked_impl("atom_count").atom_count()
def atoms_iter(self):
return self._checked_impl("atoms_iter").atoms_iter()
def copy(self):
return self
import numpy as np
class VSNumpyValue(MatchableObject):
def __eq__(self, metta_obj):
return isinstance(metta_obj, VSNumpyValue) and\
(self.content.shape == metta_obj.content.shape) and\
(self.content == metta_obj.content).all()
def match_(self, metta_obj):
sh = self.content.shape
bindings = {}
if isinstance(metta_obj, GroundedAtom):
metta_obj = metta_obj.get_object()
# Match by equality with another VSNumpyValue
if isinstance(metta_obj, VSNumpyValue):
return [{}] if metta_obj == self else []
# if isinstance(metta_obj, VSPatternValue):
# metta_obj = metta_obj.to_expr()
if isinstance(metta_obj, ExpressionAtom):
ch = metta_obj.get_children()
# TODO: constructors and operations
if len(ch) != sh[0]:
return []
for i in range(len(ch)):
res = self.content[i]
typ = _np_atom_type(res)
res = VSNumpyValue(res)
if isinstance(ch[i], VariableAtom):
bindings[ch[i].get_name()] = G(res, typ)
elif isinstance(ch[i], ExpressionAtom):
bind_add = res.match_(ch[i])
if bind_add == []:
return []
bindings.update(bind_add[0])
return [] if len(bindings) == 0 else [bindings]
class VSPatternValue(MatchableObject):
def match_(self, orig_metta_obj):
metta_obj = orig_metta_obj
if isinstance(metta_obj, GroundedAtom):
metta_obj = metta_obj.get_object().content
#if not isinstance(metta_obj, VSPatternValue):
# return metta_obj.match_(self)
# TODO: match to patterns
#return []
metta_obj = orig_metta_obj
bindings = {}
if isinstance(metta_obj, GroundedAtom):
metta_obj = metta_obj.get_object()
# Match by equality with another VSNumpyValue
if isinstance(metta_obj, VSNumpyValue):
return [{}] if metta_obj == self else []
# if isinstance(metta_obj, VSPatternValue):
# metta_obj = metta_obj.to_expr()
if isinstance(metta_obj, ExpressionAtom):
ch = metta_obj.get_children()
# TODO: constructors and operations
if len(ch) != sh[0]:
return []
for i in range(len(ch)):
res = self.content[i]
typ = _np_atom_type(res)
res = VSNumpyValue(res)
if isinstance(ch[i], VariableAtom):
bindings[ch[i].get_name()] = G(res, typ)
elif isinstance(ch[i], ExpressionAtom):
bind_add = res.match_(ch[i])
if bind_add == []:
return []
bindings.update(bind_add[0])
return [] if len(bindings) == 0 else [bindings]
class VSPatternOperation(OperationObject):
def __init__(self, name, op, unwrap=False, rec=False):
super().__init__(name, op, unwrap)
self.rec = rec
def execute(self, *args, res_typ=AtomType.UNDEFINED):
print(f"args={args}")
if self.rec and isinstance(args[0], ExpressionAtom):
args = args[0].get_children()
args = [self.execute(arg)[0]\
if isinstance(arg, ExpressionAtom) else arg for arg in args]
# If there is a variable or VSPatternValue in arguments, create VSPatternValue
# instead of executing the operation
for arg in args:
if isinstance(arg, GroundedAtom) and\
isinstance(arg.get_object(), VSPatternValue) or\
isinstance(arg, VariableAtom):
return [G(VSPatternValue([self, args]))]
return super().execute(*args, res_typ=res_typ)
class VSpacePatternOperation(OperationObject):
def __init__(self, name, op, unwrap=False, rec=False):
super().__init__(name, op, unwrap)
self.rec = rec
self._catom = None
@property
def catom(self):
return self.get_catom()
@catom.setter
def catom(self, value):
self.set_catom(value)