|
| 1 | +importos |
| 2 | +importsubprocess |
| 3 | +importsys |
| 4 | +importtempfile |
| 5 | +fromtypingimportList,Optional,Tuple,Union |
| 6 | +importnumpyasnp |
| 7 | +fromonnximportModelProto |
| 8 | + |
| 9 | + |
| 10 | +def_find_in_PATH(prog:str)->Optional[str]: |
| 11 | +""" |
| 12 | + Looks into every path mentioned in ``%PATH%`` a specific file, |
| 13 | + it raises an exception if not found. |
| 14 | +
|
| 15 | + :param prog: program to look for |
| 16 | + :return: path |
| 17 | + """ |
| 18 | +sep=";"ifsys.platform.startswith("win")else":" |
| 19 | +path=os.environ["PATH"] |
| 20 | +forpinpath.split(sep): |
| 21 | +f=os.path.join(p,prog) |
| 22 | +ifos.path.exists(f): |
| 23 | +returnp |
| 24 | +returnNone |
| 25 | + |
| 26 | + |
| 27 | +def_find_graphviz_dot(exc:bool=True)->str: |
| 28 | +""" |
| 29 | + Determines the path to graphviz (on Windows), |
| 30 | + the function tests the existence of versions 34 to 45 |
| 31 | + assuming it was installed in a standard folder: |
| 32 | + ``C:\\Program Files\\MiKTeX 2.9\\miktex\\bin\\x64``. |
| 33 | +
|
| 34 | + :param exc: raise exception of be silent |
| 35 | + :return: path to dot |
| 36 | + :raises FileNotFoundError: if graphviz not found |
| 37 | + """ |
| 38 | +ifsys.platform.startswith("win"): |
| 39 | +version=list(range(34,60)) |
| 40 | +version.extend([f"{v}.1"forvinversion]) |
| 41 | +forvinversion: |
| 42 | +graphviz_dot=f"C:\\Program Files (x86)\\Graphviz2.{v}\\bin\\dot.exe" |
| 43 | +ifos.path.exists(graphviz_dot): |
| 44 | +returngraphviz_dot |
| 45 | +extra= ["build/update_modules/Graphviz/bin"] |
| 46 | +forextinextra: |
| 47 | +graphviz_dot=os.path.join(ext,"dot.exe") |
| 48 | +ifos.path.exists(graphviz_dot): |
| 49 | +returngraphviz_dot |
| 50 | +p=_find_in_PATH("dot.exe") |
| 51 | +ifpisNone: |
| 52 | +ifexc: |
| 53 | +raiseFileNotFoundError( |
| 54 | +f"Unable to find graphviz, look into paths such as{graphviz_dot}." |
| 55 | + ) |
| 56 | +returnNone |
| 57 | +returnos.path.join(p,"dot.exe") |
| 58 | +# linux |
| 59 | +return"dot" |
| 60 | + |
| 61 | + |
| 62 | +def_run_subprocess( |
| 63 | +args:List[str], |
| 64 | +cwd:Optional[str]=None, |
| 65 | +): |
| 66 | +assertnotisinstance( |
| 67 | +args,str |
| 68 | + ),"args should be a sequence of strings, not a string." |
| 69 | + |
| 70 | +p=subprocess.Popen( |
| 71 | +args, |
| 72 | +cwd=cwd, |
| 73 | +shell=False, |
| 74 | +env=os.environ, |
| 75 | +stdout=subprocess.PIPE, |
| 76 | +stderr=subprocess.STDOUT, |
| 77 | + ) |
| 78 | +raise_exception=False |
| 79 | +output="" |
| 80 | +whileTrue: |
| 81 | +output=p.stdout.readline().decode(errors="ignore") |
| 82 | +ifoutput==""andp.poll()isnotNone: |
| 83 | +break |
| 84 | +ifoutput: |
| 85 | +if ( |
| 86 | +"fatal error"inoutput |
| 87 | +or"CMake Error"inoutput |
| 88 | +or"gmake: ***"inoutput |
| 89 | +or"): error C"inoutput |
| 90 | +or": error: "inoutput |
| 91 | + ): |
| 92 | +raise_exception=True |
| 93 | +p.poll() |
| 94 | +p.stdout.close() |
| 95 | +ifraise_exception: |
| 96 | +raiseRuntimeError( |
| 97 | +"An error was found in the output. The build is stopped.\n{output}" |
| 98 | + ) |
| 99 | +returnoutput |
| 100 | + |
| 101 | + |
| 102 | +def_run_graphviz(filename:str,image:str,engine:str="dot")->str: |
| 103 | +""" |
| 104 | + Run :epkg:`Graphviz`. |
| 105 | +
|
| 106 | + :param filename: filename which contains the graph definition |
| 107 | + :param image: output image |
| 108 | + :param engine: *dot* or *neato* |
| 109 | + :return: output of graphviz |
| 110 | + """ |
| 111 | +ext=os.path.splitext(image)[-1] |
| 112 | +assertextin { |
| 113 | +".png", |
| 114 | +".bmp", |
| 115 | +".fig", |
| 116 | +".gif", |
| 117 | +".ico", |
| 118 | +".jpg", |
| 119 | +".jpeg", |
| 120 | +".pdf", |
| 121 | +".ps", |
| 122 | +".svg", |
| 123 | +".vrml", |
| 124 | +".tif", |
| 125 | +".tiff", |
| 126 | +".wbmp", |
| 127 | + },f"Unexpected extension{ext!r} for{image!r}." |
| 128 | +ifsys.platform.startswith("win"): |
| 129 | +bin_=os.path.dirname(_find_graphviz_dot()) |
| 130 | +# if bin not in os.environ["PATH"]: |
| 131 | +# os.environ["PATH"] = os.environ["PATH"] + ";" + bin |
| 132 | +exe=os.path.join(bin_,engine) |
| 133 | +else: |
| 134 | +exe=engine |
| 135 | +ifos.path.exists(image): |
| 136 | +os.remove(image) |
| 137 | +output=_run_subprocess([exe,f"-T{ext[1:]}",filename,"-o",image]) |
| 138 | +assertos.path.exists(image),f"Graphviz failed due to{output}" |
| 139 | +returnoutput |
| 140 | + |
| 141 | + |
| 142 | +defdraw_graph_graphviz( |
| 143 | +dot:Union[str,ModelProto], |
| 144 | +image:str, |
| 145 | +engine:str="dot", |
| 146 | +)->str: |
| 147 | +""" |
| 148 | + Draws a graph using :epkg:`Graphviz`. |
| 149 | +
|
| 150 | + :param dot: dot graph or ModelProto |
| 151 | + :param image: output image, None, just returns the output |
| 152 | + :param engine: *dot* or *neato* |
| 153 | + :return: :epkg:`Graphviz` output or |
| 154 | + the dot text if *image* is None |
| 155 | +
|
| 156 | + The function creates a temporary file to store the dot file if *image* is not None. |
| 157 | + """ |
| 158 | +ifisinstance(dot,ModelProto): |
| 159 | +from .dot_plotimportto_dot |
| 160 | + |
| 161 | +sdot=to_dot(dot) |
| 162 | +else: |
| 163 | +sdot=dot |
| 164 | +withtempfile.NamedTemporaryFile(delete=False)asfp: |
| 165 | +fp.write(sdot.encode("utf-8")) |
| 166 | +fp.close() |
| 167 | + |
| 168 | +filename=fp.name |
| 169 | +assertos.path.exists( |
| 170 | +filename |
| 171 | + ),f"File{filename!r} cannot be created to store the graph." |
| 172 | +out=_run_graphviz(filename,image,engine=engine) |
| 173 | +assertos.path.exists( |
| 174 | +image |
| 175 | + ),f"Graphviz failed with no reason,{image!r} not found, output is{out}." |
| 176 | +os.remove(filename) |
| 177 | +returnout |
| 178 | + |
| 179 | + |
| 180 | +defplot_dot( |
| 181 | +dot:Union[str,ModelProto], |
| 182 | +ax:Optional["matplotlib.axis.Axis"]=None,# noqa: F821 |
| 183 | +engine:str="dot", |
| 184 | +figsize:Optional[Tuple[int,int]]=None, |
| 185 | +)->"matplotlib.axis.Axis":# noqa: F821 |
| 186 | +""" |
| 187 | + Draws a dot graph into a matplotlib graph. |
| 188 | +
|
| 189 | + :param dot: dot graph or ModelProto |
| 190 | + :param image: output image, None, just returns the output |
| 191 | + :param engine: *dot* or *neato* |
| 192 | + :param figsize: figsize of ax is None |
| 193 | + :return: :epkg:`Graphviz` output or |
| 194 | + the dot text if *image* is None |
| 195 | +
|
| 196 | + .. plot:: |
| 197 | +
|
| 198 | + import matplotlib.pyplot as plt |
| 199 | + import onnx.parser |
| 200 | +
|
| 201 | + model = onnx.parser.parse_model( |
| 202 | + ''' |
| 203 | + <ir_version: 8, opset_import: [ "": 18]> |
| 204 | + agraph (float[N] x) => (float[N] z) { |
| 205 | + two = Constant <value_float=2.0> () |
| 206 | + four = Add(two, two) |
| 207 | + z = Mul(four, four) |
| 208 | + }''') |
| 209 | + ax = plot_dot(dot) |
| 210 | + ax.set_title("Dummy graph") |
| 211 | + plt.show() |
| 212 | + """ |
| 213 | +ifaxisNone: |
| 214 | +importmatplotlib.pyplotasplt |
| 215 | + |
| 216 | +_,ax=plt.subplots(1,1,figsize=figsize) |
| 217 | +clean=True |
| 218 | +else: |
| 219 | +clean=False |
| 220 | + |
| 221 | +fromPILimportImage |
| 222 | + |
| 223 | +withtempfile.NamedTemporaryFile(suffix=".png",delete=False)asfp: |
| 224 | +fp.close() |
| 225 | + |
| 226 | +draw_graph_graphviz(dot,fp.name,engine=engine) |
| 227 | +img=np.asarray(Image.open(fp.name)) |
| 228 | +os.remove(fp.name) |
| 229 | + |
| 230 | +ax.imshow(img) |
| 231 | + |
| 232 | +ifclean: |
| 233 | +ax.get_xaxis().set_visible(False) |
| 234 | +ax.get_yaxis().set_visible(False) |
| 235 | +ax.get_figure().tight_layout() |
| 236 | +returnax |