Skip to content

Commit

Permalink
Keep 'ci/dependabot-updates' up-to-date with 'master'
Browse files Browse the repository at this point in the history
  • Loading branch information
TEAM4-0 committed Mar 15, 2023
2 parents e024138 + 269239e commit 8d87231
Show file tree
Hide file tree
Showing 7 changed files with 209 additions and 173 deletions.
5 changes: 3 additions & 2 deletions docs/tools-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,13 @@ optional arguments:

### Examples

The figure below is generated with the following command:

```console
ontograph --relations=all --legend --format=pdf emmo-inferred emmo.pdf # complete ontology
ontograph --root=Holistic --relations=hasInput,hasOutput,hasTemporaryParticipant,hasAgent --parents=2 --legend --leaves=Measurement,Manufacturing,CompleteManufacturing,ManufacturedProduct,CommercialProduct,Manufacturer --format=png --exclude=Task,Workflow,Computation,MaterialTreatment emmo-inferred measurement.png
ontograph --root=Material --relations=all --legend --format=png emmo-inferred material.png
```

The figure below is generated with the last command in the list above.
![Graph generated with the ontograph tool.](images/material.png)

---
Expand Down
47 changes: 32 additions & 15 deletions ontopy/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from ontopy.utils import asstring, get_label
from ontopy.ontology import Ontology
from ontopy.utils import EMMOntoPyException
from ontopy.utils import EMMOntoPyException, get_format

if TYPE_CHECKING:
from ipywidgets.widgets.widget_templates import GridspecLayout
Expand Down Expand Up @@ -102,10 +102,13 @@
"hasSpatialDirectPart": {"color": "darkgreen", "style": "dashed"},
"hasTemporalPart": {"color": "magenta"},
"hasTemporalDirectPart": {"color": "magenta", "style": "dashed"},
"hasReferenceUnit": {"color": "darkgreen", "style": "dashed"},
"hasReferenceUnit": {"color": "cornflowerblue", "style": "dashed"},
"hasSign": {"color": "orange"},
"hasConvention": {"color": "orange", "style": "dashed"},
"hasProperty": {"color": "orange", "style": "dotted"},
"hasOutput": {"color": "darkviolet", "style": "dotted"},
"hasInput": {"color": "darkviolet"},
"hasTemporaryParticipant": {"color": "darkviolet", "style": "dashed"},
},
"inverse": {"arrowhead": "inv"},
"default_dataprop": {"color": "green", "constraint": "false"},
Expand Down Expand Up @@ -206,7 +209,7 @@ class OntoGraph: # pylint: disable=too-many-instance-attributes
Whether to add labels to the edges of the generated graph.
It is also possible to provide a dict mapping the
full labels (with cardinality stripped off for restrictions)
to some abbriviations.
to some abbreviations.
addnodes : bool
Whether to add missing target nodes in relations.
addconstructs : bool
Expand Down Expand Up @@ -480,27 +483,31 @@ def add_edge(self, subject, predicate, obj, edgelabel=None, **attrs):
raise RuntimeError(f'`object` "{obj}" must have been added')
key = (subject, predicate, obj)
if key not in self.edges:
if edgelabel is None:
relations = self.style.get("relations", {})
rels = set(
self.ontology[_] for _ in relations if _ in self.ontology
)
if (edgelabel is None) and (
(predicate in rels) or (predicate == "isA")
):
edgelabel = self.edgelabels

label = None
if edgelabel is None:
tokens = predicate.split()
if len(tokens) == 2 and tokens[1] in ("some", "only"):
label = tokens[1]
label = f"{tokens[0]} {tokens[1]}"
elif len(tokens) == 3 and tokens[1] in (
"exactly",
"min",
"max",
):
label = f"{tokens[1]} {tokens[2]}"
label = f"{tokens[0]} {tokens[1]} {tokens[2]}"
elif isinstance(edgelabel, str):
label = edgelabel
elif isinstance(edgelabel, dict):
label = edgelabel.get(predicate, predicate)
elif edgelabel:
label = predicate

kwargs = self.get_edge_attrs(predicate, attrs=attrs)
self.dot.edge(subject, obj, label=label, **kwargs)
self.edges.add(key)
Expand Down Expand Up @@ -780,6 +787,10 @@ def add_legend(self, relations=None):
Hence, you usually want to call add_legend() as the last method
before saving or displaying.
Relations with defined style will be bold in legend.
Relations that have inherited style from parent relation
will not be bold.
"""
rels = self.style.get("relations", {})
if relations is None:
Expand All @@ -799,9 +810,16 @@ def add_legend(self, relations=None):
label1 = [table]
label2 = [table]
for index, relation in enumerate(relations):
label1.append(
f'<tr><td align="right" port="i{index}">{relation}</td></tr>'
)
if (relation in rels) or (relation == "isA"):
label1.append(
f'<tr><td align="right" '
f'port="i{index}"><b>{relation}</b></td></tr>'
)
else:
label1.append(
f'<tr><td align="right" '
f'port="i{index}">{relation}</td></tr>'
)
label2.append(f'<tr><td port="i{index}">&nbsp;</td></tr>')
label1.append("</table>>")
label2.append("</table>>")
Expand Down Expand Up @@ -865,9 +883,8 @@ def get_relations(self, sort=True):
def save(self, filename, fmt=None, **kwargs):
"""Saves graph to `filename`. If format is not given, it is
inferred from `filename`."""
base, ext = os.path.splitext(filename)
if fmt is None:
fmt = ext.lstrip(".")
base = os.path.splitext(filename)[0]
fmt = get_format(filename, default="svg", fmt=fmt)
kwargs.setdefault("cleanup", True)
if fmt in ("graphviz", "gv"):
if "dictionary" in kwargs:
Expand Down Expand Up @@ -1092,7 +1109,7 @@ def cytoscapegraph(
onto: ontology to be used for mouse actions.
infobox: "left" or "right". Placement of infbox with
respect to graph.
force: force generate graph withour correct edgelabels.
force: force generate graph without correct edgelabels.
Returns:
cytoscapewidget with graph and infobox to be visualized
in jupyter lab.
Expand Down
15 changes: 2 additions & 13 deletions ontopy/ontodoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import yaml
import owlready2

from ontopy.utils import asstring, camelsplit, get_label
from ontopy.utils import asstring, camelsplit, get_label, get_format
from ontopy.graph import OntoGraph, filter_classes

if TYPE_CHECKING:
Expand Down Expand Up @@ -1177,7 +1177,7 @@ def write( # pylint: disable=too-many-arguments
for reg, sub in substitutions:
content = re.sub(reg, sub, content)

fmt = get_format(outfile, fmt)
fmt = get_format(outfile, default="html", fmt=fmt)
if fmt not in ("simple-html", "markdown", "md"): # Run pandoc
if not genfile:
with NamedTemporaryFile(mode="w+t", suffix=".md") as temp_file:
Expand Down Expand Up @@ -1410,17 +1410,6 @@ def run_pandoc_pdf(latex_dir, pdf_engine, outfile, args, verbose=True):
shutil.move(pdffile, outfile)


def get_format(outfile, fmt=None):
"""Infer format from outfile and format."""
if fmt is None:
fmt = os.path.splitext(outfile)[1]
if not fmt:
fmt = "html"
if fmt.startswith("."):
fmt = fmt[1:]
return fmt


def get_style(fmt):
"""Infer style from output format."""
if fmt == "simple-html":
Expand Down
9 changes: 9 additions & 0 deletions ontopy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,3 +724,12 @@ def normalise_url(url):
components = list(splitted)
components[2] = os.path.normpath(splitted.path)
return urllib.parse.urlunsplit(components)


def get_format(outfile: str, default: str, fmt: str = None):
"""Infer format from outfile and format."""
if fmt is None:
fmt = os.path.splitext(outfile)[1]
if not fmt:
fmt = default
return fmt.lstrip(".")
Loading

0 comments on commit 8d87231

Please sign in to comment.