<jupyter_start><jupyter_text>Solar System **Setting up the environment**Initialization of the Ontology editor in Jupyter Notebook<jupyter_code>from cognipy.ontology import Ontology #the ontology processing class
from cognipy.ontology import CQL #SPARQL format tailored for Contolled Natural Language
from cognipy.ontology import encode_string_for_graph_label #complex datatypes encoder for the graph labels in graph visualisation
import textwrap

def graph_attribute_formatter(val):
    if isinstance(val,list) or isinstance(val,set):
        return " | ".join(list(map(lambda i:encode_string_for_graph_label(graph_attribute_formatter(i)),val)))
    elif isinstance(val,dict):
        return " | ".join(list(map(lambda i:i[0]+" : "+encode_string_for_graph_label(graph_attribute_formatter(i[1])),val.items())))
    else:
        return encode_string_for_graph_label(textwrap.fill(str(val),40))<jupyter_output><empty_output><jupyter_text>Scraping data and building CNL<jupyter_code>import pandas as pd
import os
if os.path.exists('orbits.pkl'):
    raw_orbit_data=pd.read_pickle('orbits.pkl')
else:
    raw_orbit_data=pd.read_html('http://nineplanets.org/data.html')[0]
    pd.to_pickle(raw_orbit_data,'orbits.pkl')
raw_orbit_data
def renum(x):
    x=str(x)
    x=x.strip().replace(' ','')
    x='0'+x if x[0]=='.' else x
    x=x+'0' if x[-1]=='.' else x
    return x
def orbits_to_cnl(row):
    lines = []
    if row.Name==row.Name: #Nan check
        if row.Orbits!='-':
            lines.append(f"{row.Name} orbits {row.Orbits}.")
            lines.append(f"{row.Name} has-index equal-to '{row['#']}'.")
            if row['Distance (000 km)']==row['Distance (000 km)']:
                lines.append(f"{row.Name} has-semimajor-axis-1000-km equal-to {renum(row['Distance (000 km)'])}.")
            if row['O_Period (days)']==row['O_Period (days)']:
                lines.append(f"{row.Name} has-period equal-to {renum(row['O_Period (days)'])}.")
            if row['Eccen']==row['Eccen']:
                lines.append(f"{row.Name} has-eccentricity equal-to {renum(row['Eccen'])}.")
            if row.Discoverer!='-':
                lines.append(f"{row.Name} has-discoverer equal-to '{row.Discoverer.split('(')[0]}'.")
                lines.append(f"{row.Name} has-discovery-year equal-to {row.Date}.")
    return '\n'.join(lines)
orbit_cnl='\n'.join(line for line in raw_orbit_data.apply(orbits_to_cnl,axis=1) if line!='')
print(orbit_cnl[:1000]+"...")
if os.path.exists('physics.pkl'):
    raw_physical_data=pd.read_pickle('physics.pkl')
else:
    raw_physical_data= pd.read_html('https://nineplanets.org/physical-solar-system-data/',header=[0,1])[0]
    raw_physical_data.columns=["Name","Radius","Mass","Dens","Abo","Vo","Rotate","Dimensions"]
    pd.to_pickle(raw_physical_data,'physics.pkl')
raw_physical_data
def physics_to_cnl(row):
    lines = []
    if row.Name==row.Name: #Nan check
        lines.append(f"{row.Name} has-radius equal-to {renum(row.Radius)}.")
        if row.Mass!='?' and row.Mass==row.Mass:
            if row.Mass[0]=='<':
                lines.append(f"{row.Name} has-mass-kg lower-than {renum(row.Mass[1:])}.")
            else:
                lines.append(f"{row.Name} has-mass-kg equal-to {renum(row.Mass)}.")
        if row.Dens!='?' and row.Dens==row.Dens:
            lines.append(f"{row.Name} has-density equal-to {renum(row.Dens)}.")
        if row.Abo!='?':
            lines.append(f"{row.Name} has-abo equal-to {renum(row.Abo)}.")
        if row.Vo!='-' and row.Vo!='?':
            lines.append(f"{row.Name} has-vo equal-to {renum(row.Vo)}.")
        if row.Rotate!='?' and row.Rotate==row.Rotate:
            if row.Rotate=='S':
                lines.append(f"{row.Name} has-rotate equal-to 'Stable'.")
            elif row.Rotate=='chaotic':
                lines.append(f"{row.Name} has-rotate equal-to 'Chaotic'.")
            else:
                lines.append(f"{row.Name} has-rotate equal-to {renum(row.Rotate)}.")
    return '\n'.join(lines)
physics_cnl = '\n'.join(line for line in raw_physical_data.apply(physics_to_cnl,axis=1) if line!='')
print(physics_cnl[:1000]+"...")<jupyter_output>Sun has-radius equal-to 695000.0.
Sun has-mass-kg equal-to 1.99e30.
Sun has-density equal-to 1.41.
Sun has-vo equal-to -26.
Sun has-rotate equal-to 24.6.
Mercury has-radius equal-to 2440.0.
Mercury has-mass-kg equal-to 3.30e23.
Mercury has-density equal-to 5.43.
Mercury has-abo equal-to 0.11.
Mercury has-vo equal-to -1.9.
Mercury has-rotate equal-to 58.6.
Venus has-radius equal-to 6052.0.
Venus has-mass-kg equal-to 4.87e24.
Venus has-density equal-to 5.24.
Venus has-abo equal-to 0.65.
Venus has-vo equal-to -4.4.
Venus has-rotate equal-to -243.
Earth has-radius equal-to 6378.0.
Earth has-mass-kg equal-to 5.97e24.
Earth has-density equal-to 5.52.
Earth has-abo equal-to 0.3.
Earth has-rotate equal-to 0.99.
Mars has-radius equal-to 3397.0.
Mars has-mass-kg equal-to 6.42e23.
Mars has-density equal-to 3.93.
Mars has-abo equal-to 0.15.
Mars has-vo equal-to -2.0.
Mars has-rotate equal-to 1.03.
Jupiter has-radius equal-to 71492.0.
Jupiter has-mass-kg equal-to 1.90e27.
Jupiter has-density equal-[...]<jupyter_text>Constructing few rules that will merge all the things together<jupyter_code>%%writefile solarsystem.encnl

Comment: 'Definition of a planet'.
If a thing orbits a star and the thing has-mass-kg greater-than 1.0e23 then the thing is a planet.

Comment: 'Definition of a dwarf-planet'.
If a thing orbits a star and the thing has-mass-kg greater-than 1.0e21 and the thing has-mass-kg lower-than 1.0e23 then the thing is a dwarf-planet.

Comment: 'Definition of the moon'.
If a thing(1) orbits a thing(2) and the thing(2) orbits a star then the thing(1) is a moon.

Comment: 'All starts with the Sun'.
Sun is a star.<jupyter_output>Overwriting solarsystem.encnl<jupyter_text>Loading the ontology<jupyter_code>onto=Ontology("cnl/string",'\n'.join([open("solarsystem.encnl","rt").read(), physics_cnl,orbit_cnl]), 
                    evaluator = lambda e:eval(e,globals(),locals()), 
                    graph_attribute_formatter = graph_attribute_formatter)<jupyter_output><empty_output><jupyter_text>Exploring the ontology<jupyter_code>onto.select_instances_of("a star")
onto.select_instances_of("a dwarf-planet")
onto.select_instances_of("a planet")
onto.select_instances_of("a moon that orbits Jupiter")<jupyter_output><empty_output><jupyter_text>Draw the ontology<jupyter_code>onto.draw_graph(layout='force directed',show={"relations"})<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15749961697563966, 'fraction_numerical': 0.02543281752719473, 'mean_word_length': 3.7031700288184437, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 23, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '544307', 'license': 'Apache-2.0', 'n_tokens_mistral': 2529, 'n_tokens_neox': 2361, 'n_words': 490, 'path': 'docsrc/jupyter_notebooks/SolarSystem/SolarSystem.ipynb', 'repo_name': 'jswiatkowski/cognipy', 'size': '6527'}