"""Pretty-printing (pprint()), the 'Print' Op, debugprint() and pydotprint(). They all allow different way to print a graph or the result of an Op in a graph(Print Op) """ from __future__ import absolute_import, print_function, division from copy import copy import logging import os import sys import hashlib import numpy as np from six import string_types, integer_types, iteritems from six.moves import StringIO, reduce import theano from theano import gof from theano import config from theano.gof import Op, Apply from theano.compile import Function, debugmode, SharedVariable pydot_imported = False pydot_imported_msg = "" try: # pydot-ng is a fork of pydot that is better maintained import pydot_ng as pd if pd.find_graphviz(): pydot_imported = True else: pydot_imported_msg = "pydot-ng can't find graphviz. Install graphviz." except ImportError: try: # fall back on pydot if necessary import pydot as pd if hasattr(pd, 'find_graphviz'): if pd.find_graphviz(): pydot_imported = True else: pydot_imported_msg = "pydot can't find graphviz" else: pd.Dot.create(pd.Dot()) pydot_imported = True except ImportError: # tests should not fail on optional dependency pydot_imported_msg = ("Install the python package pydot or pydot-ng." " Install graphviz.") except Exception as e: pydot_imported_msg = "An error happened while importing/trying pydot: " pydot_imported_msg += str(e.args) _logger = logging.getLogger("theano.printing") VALID_ASSOC = set(['left', 'right', 'either']) def debugprint(obj, depth=-1, print_type=False, file=None, ids='CHAR', stop_on_name=False, done=None, print_storage=False, print_clients=False, used_ids=None): """Print a computation graph as text to stdout or a file. :type obj: :class:`~theano.gof.Variable`, Apply, or Function instance :param obj: symbolic thing to print :type depth: integer :param depth: print graph to this depth (-1 for unlimited) :type print_type: boolean :param print_type: whether to print the type of printed objects :type file: None, 'str', or file-like object :param file: print to this file ('str' means to return a string) :type ids: str :param ids: How do we print the identifier of the variable id - print the python id value int - print integer character CHAR - print capital character "" - don't print an identifier :param stop_on_name: When True, if a node in the graph has a name, we don't print anything below it. :type done: None or dict :param done: A dict where we store the ids of printed node. Useful to have multiple call to debugprint share the same ids. :type print_storage: bool :param print_storage: If True, this will print the storage map for Theano functions. Combined with allow_gc=False, after the execution of a Theano function, we see the intermediate result. :type print_clients: bool :param print_clients: If True, this will print for Apply node that have more then 1 clients its clients. This help find who use an Apply node. :type used_ids: dict or None :param used_ids: the id to use for some object, but maybe we only referred to it yet. :returns: string if `file` == 'str', else file arg Each line printed represents a Variable in the graph. The indentation of lines corresponds to its depth in the symbolic graph. The first part of the text identifies whether it is an input (if a name or type is printed) or the output of some Apply (in which case the Op is printed). The second part of the text is an identifier of the Variable. If print_type is True, we add a part containing the type of the Variable If a Variable is encountered multiple times in the depth-first search, it is only printed recursively the first time. Later, just the Variable identifier is printed. If an Apply has multiple outputs, then a '.N' suffix will be appended to the Apply's identifier, to indicate which output a line corresponds to. """ if not isinstance(depth, integer_types): raise Exception("depth parameter must be an int") if file == 'str': _file = StringIO() elif file is None: _file = sys.stdout else: _file = file if done is None: done = dict() if used_ids is None: used_ids = dict() used_ids = dict() results_to_print = [] profile_list = [] order = [] # Toposort smap = [] # storage_map if isinstance(obj, (list, tuple, set)): lobj = obj else: lobj = [obj] for obj in lobj: if isinstance(obj, gof.Variable): results_to_print.append(obj) profile_list.append(None) smap.append(None) order.append(None) elif isinstance(obj, gof.Apply): results_to_print.extend(obj.outputs) profile_list.extend([None for item in obj.outputs]) smap.extend([None for item in obj.outputs]) order.extend([None for item in obj.outputs]) elif isinstance(obj, Function): results_to_print.extend(obj.maker.fgraph.outputs) profile_list.extend( [obj.profile for item in obj.maker.fgraph.outputs]) if print_storage: smap.extend( [obj.fn.storage_map for item in obj.maker.fgraph.outputs]) else: smap.extend( [None for item in obj.maker.fgraph.outputs]) topo = obj.maker.fgraph.toposort() order.extend( [topo for item in obj.maker.fgraph.outputs]) elif isinstance(obj, gof.FunctionGraph): results_to_print.extend(obj.outputs) profile_list.extend([getattr(obj, 'profile', None) for item in obj.outputs]) smap.extend([getattr(obj, 'storage_map', None) for item in obj.outputs]) topo = obj.toposort() order.extend([topo for item in obj.outputs]) elif isinstance(obj, (integer_types, float, np.ndarray)): print(obj, file=_file) elif isinstance(obj, (theano.In, theano.Out)): results_to_print.append(obj.variable) profile_list.append(None) smap.append(None) order.append(None) else: raise TypeError("debugprint cannot print an object of this type", obj) scan_ops = [] if any([p for p in profile_list if p is not None and p.fct_callcount > 0]): print(""" Timing Info ----------- -->