Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update/visualise #5

Merged
merged 3 commits into from
Mar 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ dependencies:
- python-graphviz
- pyyaml
- ase
- ipycytoscape
63 changes: 31 additions & 32 deletions example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -178,29 +178,6 @@
"g = StructureGraph()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "e7e17888-8da4-4618-9eb9-c599a83ababf",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"<Graph identifier=N304404e3864e4aef8d79731c1ae06af1 (<class 'rdflib.graph.Graph'>)>"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"g.graph.parse(\"pyscal_rdf/data/cmso.owl\", format='xml')"
]
},
{
"cell_type": "markdown",
"id": "0065555c-d343-4d1b-a05a-69ddac61a4c5",
Expand All @@ -211,39 +188,61 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 7,
"id": "3c50dba0-50a6-436f-9044-9105d93a6cb1",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"g.add_structure_to_graph(struct_l12)\n",
"g.add_structure_to_graph(struct_Fe)\n",
"g.add_structure_to_graph(struct_Si)"
"g.add_structure_to_graph(struct_l12)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "3ee82cb2-7566-4749-963c-80f2040361d4",
"execution_count": 12,
"id": "43e6adf0-b33d-4d86-84b1-2a40cf1fc726",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "411c7ddfa5c1492ca1f610885725d667",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"<Graph identifier=N304404e3864e4aef8d79731c1ae06af1 (<class 'rdflib.graph.Graph'>)>"
"CytoscapeWidget(cytoscape_layout={'name': 'cola', 'avoidOverlap': True, 'animate': True}, cytoscape_style=[{'s…"
]
},
"execution_count": 9,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"g.graph.serialize(\"map.ttl\", format='turtle')"
"g.visualise()"
]
},
{
"cell_type": "markdown",
"id": "d18fa37f-ff9f-4b40-8bf0-c8851e0dd145",
"metadata": {},
"source": [
"Add the rest of the structures"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55e4827c-714f-4caf-ba82-195499bf2fc6",
"metadata": {},
"outputs": [],
"source": [
"g.add_structure_to_graph(struct_Fe)\n",
"g.add_structure_to_graph(struct_Si)"
]
},
{
Expand Down
24 changes: 20 additions & 4 deletions pyscal_rdf/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ def _replace_keys(refdict, indict):
class StructureGraph:
def __init__(self, graph_file=None):
self.graph = Graph()
#owlfile = os.path.join(os.path.dirname(__file__), "data/cmso.owl")
#self.graph.parse(owlfile, format='xml')

self.graph.bind("cmso", CMSO)
if graph_file is not None:
if os.path.exists(graph_file):
Expand Down Expand Up @@ -242,13 +245,21 @@ def add_atoms(self, name=None):



def visualise(self, edge_color="#37474F",
styledict=None, graph_attr ={'rankdir': 'BT'},):
def visualise(self, backend='ipycytoscape',
edge_color="#37474F",
styledict=None,
graph_attr ={'rankdir': 'BT'},
layoutname='cola'):

sdict = defstyledict.copy()
if styledict is not None:
sdict = _replace_keys(sdict, styledict)
return visualize_graph(self.graph, edge_color=edge_color,
styledict=sdict, graph_attr=graph_attr)
return visualize_graph(self.graph,
backend=backend,
edge_color=edge_color,
styledict=sdict,
graph_attr=graph_attr,
layoutname=layoutname)

def write(self, filename, format="json-ld"):
with open(filename, "w") as fout:
Expand Down Expand Up @@ -295,4 +306,9 @@ def to_file(self, sample, filename=None, format="lammps-dump"):
return sys.to_ase()
else:
sys.to_file(filename, format=format)

def serialize(self, filename, format='turtle'):
owlfile = os.path.join(os.path.dirname(__file__), "data/cmso.owl")
self.graph.parse(owlfile, format='xml')


127 changes: 124 additions & 3 deletions pyscal_rdf/visualize.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
import os
from rdflib import BNode, URIRef, Literal
import uuid
import json
import ipycytoscape

def get_title_from_BNode(x):
return x.toPython()

def get_string_from_URI(x):
def get_string_from_URI(x, ):
raw = x.toPython().split("#")
if len(raw)>1:
return raw[-1]
Expand All @@ -24,10 +26,129 @@ def parse_object(x):
styledict = {
"BNode": {"color": "#ffe6ff", "shape": "box", "style": "filled"},
"URIRef": {"color": "#ffffcc", "shape": "box", "style": "filled"},
"Literal": {"color": "#e6ffcc", "shape": "parallelogram", "style": "filled"},
"Literal": {"color": "#e6ffcc", "shape": "ellipse", "style": "filled"},
}

def visualize_graph(g,
def _switch_box(box):
if box == "box":
return 'rectangle'
#remember that only boxes will be used, circles no!

def _fix_id(string1, istype1):
if istype1 == 'Literal':
id1 = str(uuid.uuid4())
else:
id1 = string1
return id1

def visualize_graph(g,
backend="ipycytoscape",
edge_color="#37474F",
styledict=styledict,
graph_attr ={'rankdir': 'LR'},
layoutname='cola'):
if backend=='ipycytoscape':
return _visualize_graph_ipycytoscape_backend(g,
edge_color=edge_color,
styledict=styledict,
layoutname=layoutname)
else:
return _visualize_graph_graphviz_backend(g,
edge_color=edge_color,
styledict=styledict,
graph_attr=graph_attr)

def _visualize_graph_ipycytoscape_backend(g,
edge_color="#37474F",
styledict=styledict,
layoutname='cola'):
#first step is to create the json file
# we can start with a dict
gdict = {}
gdict["nodes"] = []
gdict["edges"] = []
for k in g:
string1, istype1 = parse_object(k[0])
id1 = _fix_id(string1, istype1)
d = {"data": {"id": str(id1),
"label": str(string1),
"classes": str(istype1),
"shape": _switch_box(styledict[istype1]['shape']),
"width": len(string1)*7,
"fontsize": styledict[istype1]['fontsize']}}
gdict["nodes"].append(d)

string2, istype2 = parse_object(k[2])
id2 = _fix_id(string2, istype2)
d = {"data": {"id": str(id2),
"label": str(string2),
"classes": str(istype2),
"shape": _switch_box(styledict[istype2]['shape']),
"width": len(string2)*7,
"fontsize": styledict[istype1]['fontsize']}}
gdict["nodes"].append(d)

string3, istype3 = parse_object(k[1])
id3 = str(uuid.uuid4())
d = {"data": {"id": str(id3),
"label": str(string3),
"source": id1,
"target": id2,
"fontsize": styledict[istype1]['fontsize']}}
gdict["edges"].append(d)

#graph is complete
#lets try without any customisation
my_style = [
{'selector': 'node',
'style': {
'font-family': 'arial',
'font-size': '10px',
'label': 'data(label)',
'shape': 'data(shape)',
"text-valign": "center",
"text-halign": "center",
"width": 'data(width)',
"font-size": 'data(fontsize)',
}},
{'selector':
'edge',
'style': {
'font-family': 'arial',
'label': 'data(label)',
"font-size": 'data(fontsize)',
"target-arrow-shape": "triangle",
"target-arrow-color": edge_color,
"curve-style": "bezier",
}},
{'selector':
'node[classes="BNode"]',
'style': {
'background-color': styledict['BNode']['color'],
}},
{'selector':
'node[classes="URIRef"]',
'style': {
'background-color': styledict['URIRef']['color'],
}},
{'selector':
'node[classes="Literal"]',
'style': {
'background-color': styledict['Literal']['color']
}},
]

ipycyobj = ipycytoscape.CytoscapeWidget()
ipycyobj.set_layout(
name=layoutname,
avoidOverlap=True,
animate=True,)
ipycyobj.graph.add_graph_from_json(gdict, directed=True)
ipycyobj.set_style(my_style)
return ipycyobj


def _visualize_graph_graphviz_backend(g,
edge_color="#37474F",
styledict=styledict,
graph_attr ={'rankdir': 'LR'},
Expand Down