From e0fd8dbec268515f24495cdbe996a204e96ef4e1 Mon Sep 17 00:00:00 2001
From: Lionel GUEZ <guez@lmd.ens.fr>
Date: Thu, 23 Feb 2023 17:02:14 +0100
Subject: [PATCH] Accept more general input

Accept input graph of segments without cost functions and accept
absence of file `traj_segm.json`.
---
 Trajectories/draw_segments.py | 33 ++++++++++++++++++++++-----------
 1 file changed, 22 insertions(+), 11 deletions(-)

diff --git a/Trajectories/draw_segments.py b/Trajectories/draw_segments.py
index b157003f..0ba8906b 100755
--- a/Trajectories/draw_segments.py
+++ b/Trajectories/draw_segments.py
@@ -1,7 +1,11 @@
 #!/usr/bin/env python3
 
-"""Reads a graph of segments with cost functions and creates the
-corresponding Graphviz file, coloring the segments in red."""
+"""This script reads a graph of segments and creates the corresponding
+Graphviz file. If the segments have cost functions then the width of
+an edge is inversely proportionnal to the cost function. If the file
+traj_segm.json is found then the trajectories are colored in red.
+
+"""
 
 import graph_tool
 import sys
@@ -20,15 +24,22 @@ for v in g_in.vertices():
 for e in g_in.edges():
     source  = e.source()
     target = e.target()
-    g_out.add_edge(g_in.vp.name[source], g_in.vp.name[target],
-               penwidth = 10 / g_in.ep.cost_function[e])
-
-with open("traj_segm.json") as f: traj_segm = json.load(f)
-
-for segment_list in traj_segm:
-    for i in range(len(segment_list) - 1):
-        e = g_out.get_edge(segment_list[i], segment_list[i + 1])
-        e.attr["color"] = "red"
+    try:
+        g_out.add_edge(g_in.vp.name[source], g_in.vp.name[target],
+                       penwidth = 10 / g_in.ep.cost_function[e])
+    except AttributeError:
+        g_out.add_edge(g_in.vp.name[source], g_in.vp.name[target])
+
+try:
+    with open("traj_segm.json") as f: traj_segm = json.load(f)
+except FileNotFoundError:
+    print("traj_segm.json not found")
+    print("Will not color trajectories.")
+else:
+    for segment_list in traj_segm:
+        for i in range(len(segment_list) - 1):
+            e = g_out.get_edge(segment_list[i], segment_list[i + 1])
+            e.attr["color"] = "red"
 
 g_out.write(sys.argv[2])
 
-- 
GitLab