{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Flybase Learner Notebook" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "ename": "", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31mCannot execute code, session has been disposed. Please try restarting the Kernel." ] } ], "source": [ "# Install a conda package in the current Jupyter kernel\n", "import sys\n", "!pip install .\n", "\n", "from hyperon import MeTTa\n", "\n", "from pathlib import Path\n", "program = '''\n", " (isa red color)\n", " (isa green color)\n", " (isa blue color)\n", " ;(isa comment color)\n", "\n", "!(extend-py! metta_learner)\n", "\n", "!(let $space (new-fly-space)\n", " (add-atom &self (= (my-nspace) $space)))\n", "\n", "!(add-atom (my-nspace) (The user name is William))\n", "!(add-atom (my-nspace) (William is 26 years old))\n", "!(add-atom (my-nspace) (William has 2 brothers))\n", "!(add-atom (my-nspace) (Brothers names are Mike and Nick))\n", "!(add-atom (my-nspace) (Nick is 3 years older than William))\n", "!(add-atom (my-nspace) (Mike is 5 years younger than Nick))\n", "\n", "\n", "; !(match (my-nspace) (What is the user name $x) $x)\n", "; !(match (my-nspace) (How old $x is William) $x)\n", "!(match (my-nspace) (How old ($x) is Mike) $x)\n", "; !(match (my-nspace) (What $x is father name) $x)\n", "; !(match (my-nspace) (What $x is Mike age) $x)\n", "\n", " !(match &self (isa $color color) $color)\n", "\n", " (= (f) (+ 2 3))\n", " !(f)\n", "'''\n", "\n", "metta = MeTTa()\n", "[metta.run(program), metta.parse_all('red green blue'), metta.parse_all('5')]\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'PWD': '/opt/logicmoo_workspace/packs_sys/logicmoo_opencog/MeTTa/flybase-learner/'}\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "ERROR: /opt/logicmoo_workspace/packs_sys/logicmoo_opencog/MeTTa/flybase-learner/swi_flybase.pl:4:\n", "ERROR: set_pySwip_flag/2: Type error: `integer' expected, found `inf' (an atom)\n", "Warning: /opt/logicmoo_workspace/packs_sys/logicmoo_opencog/MeTTa/flybase-learner/swi_flybase.pl:4:\n", "Warning: Goal (directive) failed: user:set_pySwip_flag(table_max,inf)\n", "Warning: /opt/logicmoo_workspace/packs_sys/logicmoo_opencog/MeTTa/flybase-learner/swi_flybase.pl:62:\n", "Warning: Singleton variables: [N]\n", "% init_phase(after_load).\n", "current_pySwip_flag(argv,['--libonly'])\n", "echo_option(libonly,true)\n", "%~ /opt/logicmoo_workspace/packs_sys/logicmoo_agi/pySwip/pfc_3_0/pfc_3_0_0.pl:209 \n", "%~ call_in_thread('user:wdmsg(call_in_thread)',user,wdmsg(call_in_thread))\n", "%~ call_in_thread.\n", "%~ call_in_thread\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "program=[ grid_size(In,InH,InV), \n", " grid_size(Out,OutH,OutV), \n", " InArea is InH*InV, \n", " OutArea is OutH*OutV, \n", " ratio_for(RatioArea,OutArea,InArea), \n", " max_min(OutArea,InArea,BothMaxArea,BothMinArea), \n", " mass(In,InMass), \n", " mass(Out,OutMass), \n", " ratio_for(DeltaMass,OutMass,InMass), \n", " unique_color_count(In,InColorLen), \n", " unique_color_count(Out,OutColorLen), \n", " ratio_for(RatioColorLen,OutColorLen,InColorLen), \n", " unique_colors(In,InColors), \n", " unique_colors(Out,OutColors), \n", " intersection( InColors, \n", " OutColors, SharedColors,InSpecificColors, \n", " OutSpecificColors), \n", " append( [InSpecificColors,SharedColors,OutSpecificColors], \n", " Include_Append_AllColors), \n", " nop(dont_include(Include_Append_AllColors)), \n", " sort_safe(Include_Append_AllColors,AllColors), \n", " my_maplist( length, \n", " [ InColors, OutColors,SharedColors, \n", " InSpecificColors, OutSpecificColors, AllColors], \n", " [ InColorsLen, OutColorsLen,SharedColorsLen, \n", " InSpecificColorsLen, OutSpecificColorsLen, AllColorsLen]), \n", " ratio_for(RescaleH,OutH,InH), \n", " ratio_for(RescaleV,OutV,InV), \n", " ratio_for(InDensity,InMass,InArea), \n", " ratio_for(OutDensity,OutMass,OutArea), \n", " ratio_for(DeltaDensity,OutDensity,InDensity), \n", " max_min(OutH,OutV,OutMaxHV,Min_OutMaxHV), \n", " max_min(InH,InV,InMaxHV,Min_MaxHV), \n", " OutMaxHVArea is OutMaxHV*OutMaxHV, \n", " InMaxHVArea is InMaxHV*InMaxHV, \n", " ratio_for(RatioMaxHVArea,OutMaxHVArea,InMaxHVArea), \n", " max_min(InMaxHVArea,OutMaxHVArea,BothMaxHVAreaMax,BothMaxHVAreaMin), \n", " ratio_for(RatioBothMaxHVArea,BothMaxHVAreaMax,BothMaxHVAreaMin)]\n", "\t\tin=In\n", "\t\tin_h=InH\n", "\t\tin_v=InV\n", "\t\tout=Out\n", "\t\tout_h=OutH\n", "\t\tout_v=OutV\n", "\t\tin_area=InArea\n", "\t\tout_area=OutArea\n", "\t\tratio_area=RatioArea\n", "\t\tboth_max_area=BothMaxArea\n", "\t\tboth_min_area=BothMinArea\n", "\t\tin_mass=InMass\n", "\t\tout_mass=OutMass\n", "\t\tdelta_mass=DeltaMass\n", "\t\tin_color_len=InColorLen\n", "\t\tout_color_len=OutColorLen\n", "\t\tratio_color_len=RatioColorLen\n", "\t\tin_colors=InColors\n", "\t\tout_colors=OutColors\n", "\t\tshared_colors=SharedColors\n", "\t\tin_specific_colors=InSpecificColors\n", "\t\tout_specific_colors=OutSpecificColors\n", "\t\tall_colors=AllColors\n", "\t\tin_colors_len=InColorsLen\n", "\t\tout_colors_len=OutColorsLen\n", "\t\tshared_colors_len=SharedColorsLen\n", "\t\tin_specific_colors_len=InSpecificColorsLen\n", "\t\tout_specific_colors_len=OutSpecificColorsLen\n", "\t\tall_colors_len=AllColorsLen\n", "\t\trescale_h=RescaleH\n", "\t\trescale_v=RescaleV\n", "\t\tin_density=InDensity\n", "\t\tout_density=OutDensity\n", "\t\tdelta_density=DeltaDensity\n", "\t\tout_max_hv=OutMaxHV\n", "\t\tin_max_hv=InMaxHV\n", "\t\tout_max_hv_area=OutMaxHVArea\n", "\t\tin_max_hv_area=InMaxHVArea\n", "\t\tratio_max_hv_area=RatioMaxHVArea\n", "\t\tboth_max_hv_area_max=BothMaxHVAreaMax\n", "\t\tboth_max_hv_area_min=BothMaxHVAreaMin\n", "\t\tratio_both_max_hv_area=RatioBothMaxHVArea\n", "synthesized(user:save_test_hints)\n", "synthesized(user:parcCmt)\n", "synthesized(user:print_whole_test)\n", "synthesized(user:each_ndividuator)\n", "synthesized(user:show_task_pairs)\n", "synthesized(user:test_encoders_mining)\n", "synthesized(user:invoke_n_v)\n", "synthesized(user:clear_saveable_test_info)\n", "synthesized(user:ndividuator)\n", "synthesized(user:test_encoder_for_simple_output)\n", "synthesized(user:print_test_file_hints)\n", "synthesized(user:is_encode_tst)\n", "synthesized(user:clear_saveable_test_info_now)\n", "synthesized(user:test_encoders)\n", "synthesized(user:print_test_hints)\n", "synthesized(user:clear_test_now)\n", "synthesized(user:whole_ndividuator)\n", "synthesized(user:ndividuator_logicmoo)\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "%~ /opt/logicmoo_workspace/packs_sys/logicmoo_agi/pySwip/kaggle_arc/kaggle_arc_footer.pl:27 \n", "%~ default.\n", "%~ 'removed check:list_undefined and list_void_declarations use: ?- real_list_undefined([]),real_list_void_declarations. '.\n", "%~ /opt/logicmoo_workspace/packs_sys/logicmoo_opencog/MeTTa/flybase-learner/swi_support.pl:11 \n", "%~ main_file.\n", "% 102,902 inferences, 0.016 CPU in 0.016 seconds (100% CPU, 6320490 Lips)\n", "%~ main_file_complete.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "synthesized(user:detect_pair_hints)\n", "synthesized(user:show_reduced_io)\n", "synthesized(user:pairification_propmpt)\n", "synthesized(user:show_filtered_groups)\n", "synthesized(user:test_example_grid)\n", "synthesized(user:cache_grid_objs)\n", "synthesized(user:show_reduced_io_fav)\n", "synthesized(user:compute_and_show_test_hints)\n", "synthesized(user:ensure_individuals1)\n", "synthesized(user:learn_grid_size)\n", "synthesized(user:test_predict_grid_size)\n", "synthesized(user:test_show_grid_objs)\n", "synthesized(user:test_abstracted_recall)\n", "synthesized(user:ensure_scene_change_rules)\n", "synthesized(user:show_reduced_inputs)\n", "synthesized(user:compute_and_show_test_hints_fresh)\n", "synthesized(user:task_io_mono_diag)\n", "synthesized(user:show_assumed_mapped)\n", "synthesized(user:show_reduced_outputs)\n", "synthesized(user:detect_all_training_hints)\n", "synthesized(user:compute_scene_change)\n", "synthesized(user:calc_all_individuals)\n", "synthesized(user:print_best_individuals)\n", "synthesized(user:compile_and_save_hints_now)\n", "synthesized(user:ensure_propcounts)\n", "synthesized(user:show_pair_groups)\n", "synthesized(user:print_hybrid_set)\n", "synthesized(user:deduce_shapes)\n", "synthesized(user:print_individuals)\n", "synthesized(user:show_all_test_reductions)\n", "synthesized(user:show_reduced_pairs)\n", "synthesized(user:learn_ilp)\n", "synthesized(user:show_groups)\n", "synthesized(user:show_object_dependancy)\n", "synthesized(user:clear_object_dependancy)\n", "\n", "% Type ?- \n", " load_from_main ,\n", " catch_log(load_json_files) ,\n", " catch_log(load_task_states) ,\n", " catch_log(devaluation) ,\n", " catch_log(gen_gids) ,\n", " catch_log(create_group_dmiles) ,\n", " catch_log(test_show_colors) , \n", " demo. % or press up arrow\n", "show_time_gt_duration(0.8838648796081543>0.3,create_points_plus_now)\n", "\u001b[0m\u001b[0m\u001b[33mmaybe_report_time(0.8838648796081543>0.3,create_points_plus_now)\n", "\u001b[0m\u001b[0m\u001b[0m" ] } ], "source": [ "from __future__ import print_function\n", "from collections import deque\n", "\n", "import hyperonpy as hp\n", "from hyperon.atoms import V, S, E, ValueAtom, GroundedAtom, ExpressionAtom, G, AtomType, MatchableObject, OperationAtom, OperationObject, BindingsSet, Atom\n", "from hyperon.runner import MeTTa\n", "from hyperon.ext import register_atoms, register_tokens\n", "from hyperon.base import AbstractSpace, SpaceRef, GroundingSpace, interpret\n", "# Avoid conflict for \"Atom\"\n", "from pyswip import Atom as PySwipAtom\n", "from pyswip import Term\n", "from hyperon.atoms import Atom as MeTTaAtom\n", "from pyswip import Functor, registerForeign, PL_PRUNED, PL_retry, PL_FA_NONDETERMINISTIC, PL_foreign_control, PL_foreign_context, PL_FIRST_CALL, PL_REDO, Variable, Prolog as PySwip\n", "from pyswip.easy import newModule, Query\n", "from hyperon.atoms import *\n", "import openai\n", "import hyperon\n", "\n", "pySwip = PySwip()\n", "for l in pySwip.query(\"working_directory(PWD,PWD)\"):\n", " print(l)\n", "pySwip.consult(\"swi_flybase.pl\")\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 3, "metadata": { "scrolled": true }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (272713009.py, line 5)", "output_type": "error", "traceback": [ "\u001b[0;36m Input \u001b[0;32mIn [3]\u001b[0;36m\u001b[0m\n\u001b[0;31m pySwip = PySwip()for l in pySwip.query(\"load_flybase\"):\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "from pyswip.pySwip import PySwip\n", "#from pyswip import getList, registerForeigns\n", "from pyswip_notebook import IsolatedPySwip\n", "\n", "pySwip = PySwip()\n", "\n", "for l in pySwip.query(\"load_flybase\"):\n", " print(l)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'N': 'encoding', 'V': 'octet'}\n", "{'N': 'stream_type_check', 'V': 'loose'}\n", "{'N': 'message_context', 'V': ['thread']}\n", "{'N': 'quasi_quotations', 'V': 'true'}\n", "{'N': 'unknown', 'V': 'error'}\n", "{'N': 'allow_variable_name_as_functor', 'V': 'false'}\n", "{'N': 'agc_margin', 'V': 10000}\n", "{'N': 'protect_static_code', 'V': 'false'}\n", "{'N': 'xref', 'V': 'false'}\n", "{'N': 'verbose_load', 'V': 'silent'}\n", "{'N': 'verbose_file_search', 'V': 'false'}\n", "{'N': 'shift_check', 'V': 'false'}\n", "{'N': 'traditional', 'V': 'false'}\n", "{'N': 'toplevel_prompt', 'V': '~m~d~l~! ?- '}\n", "{'N': 'fileerrors', 'V': 'true'}\n", "{'N': 'xpce', 'V': 'true'}\n", "{'N': 'allow_dot_in_atom', 'V': 'false'}\n", "{'N': 'argv', 'V': []}\n", "{'N': 'write_attributes', 'V': 'ignore'}\n", "{'N': 'toplevel_print_anon', 'V': 'true'}\n", "{'N': 'error_ambiguous_stream_pair', 'V': 'false'}\n", "{'N': 'table_space', 'V': 1073741824}\n", "{'N': 'emulated_dialect', 'V': 'swi'}\n", "{'N': 'signals', 'V': 'false'}\n", "{'N': 'system_thread_id', 'V': 49047}\n", "{'N': 'compiled_at', 'V': 'Mar 31 2023, 08:09:42'}\n", "{'N': 'rational_syntax', 'V': 'compatibility'}\n", "{'N': 'var_prefix', 'V': 'false'}\n", "{'N': 'cmake_build_type', 'V': 'DEB'}\n", "{'N': 'table_subsumptive', 'V': 'false'}\n", "{'N': 'cpu_count', 'V': 8}\n", "{'N': 'optimise_debug', 'V': 'default'}\n", "{'N': 'tmp_dir', 'V': '/tmp'}\n", "{'N': 'pid', 'V': 49047}\n", "{'N': 'autoload', 'V': 'true'}\n", "{'N': 'warn_override_implicit_import', 'V': 'true'}\n", "{'N': 'debugger_show_context', 'V': 'false'}\n", "{'N': 'last_call_optimisation', 'V': 'true'}\n", "{'N': 'optimise', 'V': 'false'}\n", "{'N': 'libswipl', 'V': '/lib/x86_64-linux-gnu/libswipl.so.9'}\n", "{'N': 'debug', 'V': 'false'}\n", "{'N': 'shared_home', 'V': '/usr/share/swi-pySwip'}\n", "{'N': 'debug_on_interrupt', 'V': 'false'}\n", "{'N': 'executable', 'V': './'}\n", "{'N': 'file_name_variables', 'V': 'false'}\n", "{'N': 'executable_format', 'V': 'elf'}\n", "{'N': 'float_overflow', 'V': 'error'}\n", "{'N': 'path_max', 'V': 4096}\n", "{'N': 'threads', 'V': 'true'}\n", "{'N': 'arch', 'V': 'x86_64-linux'}\n", "{'N': 'occurs_check', 'V': 'false'}\n", "{'N': 'home', 'V': '/usr/lib/swi-pySwip'}\n", "{'N': 'float_undefined', 'V': 'error'}\n", "{'N': 'dialect', 'V': 'swi'}\n", "{'N': 'toplevel_extra_white_line', 'V': 'true'}\n", "{'N': 'qcompile', 'V': 'false'}\n", "{'N': 'answer_write_options', 'V': ['quoted(true)', 'portray(true)', 'max_depth(10)', 'spacing(next_argument)']}\n", "{'N': 'emacs_inferior_process', 'V': 'false'}\n", "{'N': 'on_warning', 'V': 'print'}\n", "{'N': 'float_zero_div', 'V': 'error'}\n", "{'N': 'compile_meta_arguments', 'V': 'false'}\n", "{'N': 'print_write_options', 'V': ['portray(true)', 'quoted(true)', 'numbervars(true)']}\n", "{'N': 'max_procedure_arity', 'V': 1024}\n", "{'N': 'char_conversion', 'V': 'false'}\n", "{'N': 'float_max_integer', 'V': 9007199254740992.0}\n", "{'N': 'message_language', 'V': 'en_US'}\n", "{'N': 'max_tagged_integer', 'V': 72057594037927935}\n", "{'N': 'gc_thread', 'V': 'false'}\n", "{'N': 'gmp_version', 'V': 6}\n", "{'N': 'toplevel_residue_vars', 'V': 'false'}\n", "{'N': 'bounded', 'V': 'false'}\n", "{'N': 'trace_gc', 'V': 'false'}\n", "{'N': 'shared_table_space', 'V': 1073741824}\n", "{'N': 'c_libs', 'V': ''}\n", "{'N': 'c_cc', 'V': '/usr/bin/cc'}\n", "{'N': 'pipe', 'V': 'true'}\n", "{'N': 'double_quotes', 'V': 'string'}\n", "{'N': 'max_table_subgoal_size_action', 'V': 'error'}\n", "{'N': 'c_ldflags', 'V': ''}\n", "{'N': 'posix_shell', 'V': '/bin/sh'}\n", "{'N': 'agc_close_streams', 'V': 'false'}\n", "{'N': 'float_min', 'V': 2.2250738585072014e-308}\n", "{'N': 'large_files', 'V': 'true'}\n", "{'N': 'max_rational_size_action', 'V': 'error'}\n", "{'N': 'shared_object_search_path', 'V': 'LD_LIBRARY_PATH'}\n", "{'N': 'character_escapes', 'V': 'true'}\n", "{'N': 'shared_object_extension', 'V': 'so'}\n", "{'N': 'max_table_answer_size_action', 'V': 'error'}\n", "{'N': 'heartbeat', 'V': 0}\n", "{'N': 'max_answers_for_subgoal_action', 'V': 'error'}\n", "{'N': 'os_argv', 'V': ['./', '-q', '--nosignals', '--home=/usr/lib/swi-pySwip']}\n", "{'N': 'access_level', 'V': 'user'}\n", "{'N': 'user_flags', 'V': 'silent'}\n", "{'N': 'stack_limit', 'V': 1073741824}\n", "{'N': 'verbose_autoload', 'V': 'false'}\n", "{'N': 'sandboxed_load', 'V': 'false'}\n", "{'N': 'portable_vmi', 'V': 'true'}\n", "{'N': 'verbose', 'V': 'silent'}\n", "{'N': 'query_debug_settings', 'V': 'debug(false, false)'}\n", "{'N': 'unix', 'V': 'true'}\n", "{'N': 'toplevel_var_size', 'V': 1000}\n", "{'N': 'toplevel_name_variables', 'V': 'true'}\n", "{'N': 'iso', 'V': 'false'}\n", "{'N': 'mitigate_spectre', 'V': 'false'}\n", "{'N': 'table_incremental', 'V': 'false'}\n", "{'N': 'table_monotonic', 'V': 'eager'}\n", "{'N': 'packs', 'V': 'true'}\n", "{'N': 'file_search_cache_time', 'V': 10}\n", "{'N': 'table_shared', 'V': 'false'}\n", "{'N': 'version_data', 'V': 'swi(9, 0, 4, [])'}\n", "{'N': 'back_quotes', 'V': 'codes'}\n", "{'N': 'optimise_unify', 'V': 'true'}\n", "{'N': 'timezone', 'V': 28800}\n", "{'N': 'float_underflow', 'V': 'ignore'}\n", "{'N': 'float_rounding', 'V': 'to_nearest'}\n", "{'N': 'vmi_builtin', 'V': 'true'}\n", "{'N': 'generate_debug_info', 'V': 'true'}\n", "{'N': 'debug_on_error', 'V': 'true'}\n", "{'N': 'toplevel_mode', 'V': 'backtracking'}\n", "{'N': 'debugger_write_options', 'V': ['quoted(true)', 'portray(true)', 'max_depth(10)', 'attributes(portray)', 'spacing(next_argument)']}\n", "{'N': 'toplevel_list_wfs_residual_program', 'V': 'true'}\n", "{'N': 'file_name_case_handling', 'V': 'case_preserving'}\n", "{'N': 'report_error', 'V': 'true'}\n", "{'N': 'version', 'V': 90004}\n", "{'N': 'debug_term_position', 'V': 'false'}\n", "{'N': 'on_error', 'V': 'print'}\n", "{'N': 'determinism_error', 'V': 'error'}\n", "{'N': 'max_char_code', 'V': 1114111}\n", "{'N': 'integer_rounding_function', 'V': 'toward_zero'}\n", "{'N': 'gc', 'V': 'true'}\n", "{'N': 'max_arity', 'V': 'unbounded'}\n", "{'N': 'colon_sets_calling_context', 'V': 'true'}\n", "{'N': 'answer_format', 'V': '~p'}\n", "{'N': 'tty_control', 'V': 'false'}\n", "{'N': 'editor', 'V': 'default'}\n", "{'N': 'abi_version', 'V': {'built_in': 2757966453, 'foreign_interface': 2, 'qlf': 68, 'qlf_min_load': 68, 'record': 3, 'vmi': 2678345669}}\n", "{'N': 'address_bits', 'V': 64}\n", "{'N': 'resource_database', 'V': '/usr/lib/swi-pySwip/boot.prc'}\n", "{'N': 'prefer_rationals', 'V': 'false'}\n", "{'N': 'toplevel_goal', 'V': 'default'}\n", "{'N': 'min_tagged_integer', 'V': -72057594037927936}\n", "{'N': 'prompt_alternatives_on', 'V': 'determinism'}\n", "{'N': 'toplevel_print_factorized', 'V': 'false'}\n", "{'N': 'c_cflags', 'V': '-fPIC -pthread'}\n", "{'N': 'c_libplso', 'V': ''}\n", "{'N': 'unload_foreign_libraries', 'V': 'false'}\n", "{'N': 'float_max', 'V': 1.7976931348623157e+308}\n", "{'N': 'malloc', 'V': 'ptmalloc'}\n", "{'N': 'open_shared_object', 'V': 'true'}\n", "{'N': 'character_escapes_unicode', 'V': 'true'}\n", "{}\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "% Started at Tue Aug 22 07:12:37 2023\n", "% 1.333 seconds cpu time for 444,978 inferences\n", "% 7,856 atoms, 4,612 functors, 3,215 predicates, 37 modules, 132,243 VM-codes\n", "% \n", "% Limit Allocated In use\n", "% Local stack: - 116 Kb 1,384 b\n", "% Global stack: - 128 Kb 50 Kb\n", "% Trail stack: - 34 Kb 24 b\n", "% Total: 1,024 Mb 278 Kb 51 Kb\n", "% \n", "% 4 garbage collections gained 344,920 bytes in 0.000 seconds.\n", "% 5 clause garbage collections gained 124 clauses in 0.000 seconds.\n", "% Stack shifts: 2 local, 1 global, 0 trail in 0.000 seconds\n" ] } ], "source": [ " for l in pySwip.query(\"current_pySwip_flag(N,V)\"):\n", " print(l)\n", " \n", "for l in pySwip.query(\"statistics\"):\n", " print(l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Print all facts in the knowledge base." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "male(cronus).\n", "male(pluto).\n", "male(poseidon).\n", "male(zeus).\n", "male(ares).\n", "male(hephaestus).\n", "\n", "female(rhea).\n", "female(hestia).\n", "female(hera).\n", "female(demeter).\n", "female(athena).\n", "female(hebe).\n", "female(persephone).\n", "\n", "parent(cronus, hestia).\n", "parent(cronus, pluto).\n", "parent(cronus, poseidon).\n", "parent(cronus, zeus).\n", "parent(cronus, hera).\n", "parent(cronus, demeter).\n", "parent(rhea, hestia).\n", "parent(rhea, pluto).\n", "parent(rhea, poseidon).\n", "parent(rhea, zeus).\n", "parent(rhea, hera).\n", "parent(rhea, demeter).\n", "parent(zeus, athena).\n", "parent(zeus, ares).\n", "parent(zeus, hebe).\n", "parent(zeus, hephaestus).\n", "parent(hera, ares).\n", "parent(hera, hebe).\n", "parent(hera, hephaestus).\n", "parent(zeus, persephone).\n", "parent(demeter, persephone).\n", "{}\n" ] } ], "source": [ "# \n", "for l in pySwip.query(\"listing\"):\n", " print(l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next we add a few more complext rules." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "pySwip.assertz(\"isFather(X, Y) :- male(X), parent(X, Y)\")\n", "\n", "pySwip.assertz(\"isMother(X, Y) :- female(X), parent(X, Y)\")\n", "\n", "pySwip.assertz(\"isDaughter(X, Y) :- female(X), parent(Y, X)\")\n", "\n", "pySwip.assertz(\"isSon(X, Y) :- male(X), parent(Y, X)\")\n", "\n", "pySwip.assertz(\"isAncestor(X, Y) :- parent(X, Y)\")\n", "\n", "pySwip.assertz(\"isAncestor(X, Y) :- parent(X, T), parent(T, Y)\")" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('TAXRANK:0000001', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000002', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000003', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000004', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000005', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000006', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000007', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000008', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000009', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000010', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000011', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000012', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000013', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000014', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000015', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000016', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000017', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000018', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000019', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000020', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000021', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000022', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000023', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000024', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000025', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000026', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000027', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000028', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000029', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000030', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000031', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000032', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000033', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000034', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000035', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000036', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000037', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000038', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000039', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000040', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000041', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000042', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000043', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000044', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000045', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000046', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000047', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000048', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000049', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000050', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000051', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000052', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000053', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000054', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000055', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000056', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000057', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000058', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000059', 'TAXRANK:0000000', 'is_a'), ('TAXRANK:0000060', 'TAXRANK:0000000', 'is_a')]\n", "['TAXRANK:0000000', 'TAXRANK:0000001', 'TAXRANK:0000002', 'TAXRANK:0000003', 'TAXRANK:0000004', 'TAXRANK:0000005', 'TAXRANK:0000006', 'TAXRANK:0000007', 'TAXRANK:0000008', 'TAXRANK:0000009', 'TAXRANK:0000010', 'TAXRANK:0000011', 'TAXRANK:0000012', 'TAXRANK:0000013', 'TAXRANK:0000014', 'TAXRANK:0000015', 'TAXRANK:0000016', 'TAXRANK:0000017', 'TAXRANK:0000018', 'TAXRANK:0000019', 'TAXRANK:0000020', 'TAXRANK:0000021', 'TAXRANK:0000022', 'TAXRANK:0000023', 'TAXRANK:0000024', 'TAXRANK:0000025', 'TAXRANK:0000026', 'TAXRANK:0000027', 'TAXRANK:0000028', 'TAXRANK:0000029', 'TAXRANK:0000030', 'TAXRANK:0000031', 'TAXRANK:0000032', 'TAXRANK:0000033', 'TAXRANK:0000034', 'TAXRANK:0000035', 'TAXRANK:0000036', 'TAXRANK:0000037', 'TAXRANK:0000038', 'TAXRANK:0000039', 'TAXRANK:0000040', 'TAXRANK:0000041', 'TAXRANK:0000042', 'TAXRANK:0000043', 'TAXRANK:0000044', 'TAXRANK:0000045', 'TAXRANK:0000046', 'TAXRANK:0000047', 'TAXRANK:0000048', 'TAXRANK:0000049', 'TAXRANK:0000050', 'TAXRANK:0000051', 'TAXRANK:0000052', 'TAXRANK:0000053', 'TAXRANK:0000054', 'TAXRANK:0000055', 'TAXRANK:0000056', 'TAXRANK:0000057', 'TAXRANK:0000058', 'TAXRANK:0000059', 'TAXRANK:0000060']\n", "61\n", "60\n", "True\n", "species\n" ] }, { "data": { "text/plain": [ "{'TAXRANK:0000000'}" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import networkx\n", "import obonet\n", "\n", "# Read the taxrank ontology\n", "url = 'https://github.com/dhimmel/obonet/raw/main/tests/data/taxrank.obo'\n", "graph = obonet.read_obo(url)\n", "\n", "# Or read the xz-compressed taxrank ontology\n", "url = 'https://github.com/dhimmel/obonet/raw/main/tests/data/taxrank.obo.xz'\n", "graph = obonet.read_obo(url)\n", "\n", "print(graph.edges)\n", "\n", "print(graph.nodes)\n", "\n", "# Number of nodes\n", "print(len(graph))\n", "\n", "# Number of edges\n", "print(graph.number_of_edges())\n", "\n", "# Check if the ontology is a DAG\n", "print(networkx.is_directed_acyclic_graph(graph))\n", "\n", "# Mapping from term ID to name\n", "id_to_name = {id_: data.get('name') for id_, data in graph.nodes(data=True)}\n", "print(id_to_name['TAXRANK:0000006']) # TAXRANK:0000006 is species\n", "\n", "# Find all superterms of species. Note that networkx.descendants gets\n", "# superterms, while networkx.ancestors returns subterms.\n", "networkx.descendants(graph, 'TAXRANK:0000006')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can query the knowledge base." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "true\n" ] } ], "source": [ "# \n", "res = list(pySwip.query(\"isAncestor(rhea, persephone)\"))\n", "print(\"false\" if len(res) == 0 else \"true\")" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Y': 'athena'}\n", "{'Y': 'ares'}\n", "{'Y': 'hebe'}\n", "{'Y': 'hephaestus'}\n", "{'Y': 'persephone'}\n" ] } ], "source": [ "# a more complext query with a variable\n", "for res in pySwip.query(\"isFather(zeus, Y)\"):\n", " print(res)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multiple instances of `IsolatedPySwip` do not interfere with each other." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{}\n", "\n", ":- dynamic is_empty/1.\n", "\n", "is_empty(another_pySwip).\n" ] } ], "source": [ "# \n", "\n", "another_pySwip = IsolatedPySwip()\n", "\n", "another_pySwip.assertz(\"is_empty(another_pySwip)\")\n", "\n", "for l in another_pySwip.query(\"listing\"):\n", " print(l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Foreign functions from `pyswip` work as well" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, john\n", "Hello, gina\n", "[{'X': 'john'}, {'X': 'gina'}]\n" ] } ], "source": [ "from pyswip import registerForeign\n", "\n", "def hello(t):\n", " print(\"Hello,\", t)\n", "hello.arity = 1\n", "\n", "registerForeign(hello)\n", "\n", "pySwip = IsolatedPySwip()\n", "pySwip.assertz(\"father(michael,john)\")\n", "pySwip.assertz(\"father(michael,gina)\")\n", "print(list(pySwip.query(\"father(michael,X), hello(X)\")))" ] } ], "metadata": { "interpreter": { "hash": "ac3e2752b8d3c7ac594336078a1da4fa888e9a385f6933a16a4c4965994955e7" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.5" } }, "nbformat": 4, "nbformat_minor": 2 }