prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  matplotlib.use('Agg') fail
  It result in plot fail 
  ```
  _tkinter.TclError: no display name and no $DISPLAY environment variable
  ```
  I fixed this by applying a patch on `espnet/nets/pytorch_backend/transformer/plot.py`
  ```
  @@ -1,5 +1,6 @@
   import logging
  -
  +import matplotlib
  +matplotlib.use('Agg')
   import matplotlib.pyplot as plt
  
   from espnet.asr import asr_utils
  ```
  
  </issue>
  <code>
  [start of espnet/nets/pytorch_backend/transformer/plot.py]
  1 import logging
  2 
  3 import matplotlib.pyplot as plt
  4 
  5 from espnet.asr import asr_utils
  6 
  7 
  8 def _plot_and_save_attention(att_w, filename):
  9     # dynamically import matplotlib due to not found error
  10     from matplotlib.ticker import MaxNLocator
  11     import os
  12     d = os.path.dirname(filename)
  13     if not os.path.exists(d):
  14         os.makedirs(d)
  15     w, h = plt.figaspect(1.0 / len(att_w))
  16     fig = plt.Figure(figsize=(w * 2, h * 2))
  17     axes = fig.subplots(1, len(att_w))
  18     if len(att_w) == 1:
  19         axes = [axes]
  20     for ax, aw in zip(axes, att_w):
  21         # plt.subplot(1, len(att_w), h)
  22         ax.imshow(aw, aspect="auto")
  23         ax.set_xlabel("Input")
  24         ax.set_ylabel("Output")
  25         ax.xaxis.set_major_locator(MaxNLocator(integer=True))
  26         ax.yaxis.set_major_locator(MaxNLocator(integer=True))
  27     fig.tight_layout()
  28     return fig
  29 
  30 
  31 def savefig(plot, filename):
  32     plot.savefig(filename)
  33     plt.clf()
  34 
  35 
  36 def plot_multi_head_attention(data, attn_dict, outdir, suffix="png", savefn=savefig):
  37     """Plot multi head attentions
  38 
  39     :param dict data: utts info from json file
  40     :param dict[str, torch.Tensor] attn_dict: multi head attention dict.
  41         values should be torch.Tensor (head, input_length, output_length)
  42     :param str outdir: dir to save fig
  43     :param str suffix: filename suffix including image type (e.g., png)
  44     :param savefn: function to save
  45     """
  46     for name, att_ws in attn_dict.items():
  47         for idx, att_w in enumerate(att_ws):
  48             filename = "%s/%s.%s.%s" % (
  49                 outdir, data[idx][0], name, suffix)
  50             dec_len = int(data[idx][1]['output'][0]['shape'][0])
  51             enc_len = int(data[idx][1]['input'][0]['shape'][0])
  52             if "encoder" in name:
  53                 att_w = att_w[:, :enc_len, :enc_len]
  54             elif "decoder" in name:
  55                 if "self" in name:
  56                     att_w = att_w[:, :dec_len, :dec_len]
  57                 else:
  58                     att_w = att_w[:, :dec_len, :enc_len]
  59             else:
  60                 logging.warning("unknown name for shaping attention")
  61             fig = _plot_and_save_attention(att_w, filename)
  62             savefn(fig, filename)
  63 
  64 
  65 class PlotAttentionReport(asr_utils.PlotAttentionReport):
  66     def plotfn(self, *args, **kwargs):
  67         plot_multi_head_attention(*args, **kwargs)
  68 
  69     def __call__(self, trainer):
  70         attn_dict = self.get_attention_weights()
  71         suffix = "ep.{.updater.epoch}.png".format(trainer)
  72         self.plotfn(self.data, attn_dict, self.outdir, suffix, savefig)
  73 
  74     def get_attention_weights(self):
  75         batch = self.converter([self.transform(self.data)], self.device)
  76         if isinstance(batch, tuple):
  77             att_ws = self.att_vis_fn(*batch)
  78         elif isinstance(batch, dict):
  79             att_ws = self.att_vis_fn(**batch)
  80         return att_ws
  81 
  82     def log_attentions(self, logger, step):
  83         def log_fig(plot, filename):
  84             from os.path import basename
  85             logger.add_figure(basename(filename), plot, step)
  86             plt.clf()
  87 
  88         attn_dict = self.get_attention_weights()
  89         self.plotfn(self.data, attn_dict, self.outdir, "", log_fig)
  90
  [end of espnet/nets/pytorch_backend/transformer/plot.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/espnet/nets/pytorch_backend/transformer/plot.py b/espnet/nets/pytorch_backend/transformer/plot.py
  --- a/espnet/nets/pytorch_backend/transformer/plot.py
  +++ b/espnet/nets/pytorch_backend/transformer/plot.py
  @@ -1,8 +1,7 @@
   import logging
   
  -import matplotlib.pyplot as plt
  -
   from espnet.asr import asr_utils
  +import matplotlib.pyplot as plt
   
   
   def _plot_and_save_attention(att_w, filename):
  
verification_info: {"golden_diff": "diff --git a/espnet/nets/pytorch_backend/transformer/plot.py b/espnet/nets/pytorch_backend/transformer/plot.py\n--- a/espnet/nets/pytorch_backend/transformer/plot.py\n+++ b/espnet/nets/pytorch_backend/transformer/plot.py\n@@ -1,8 +1,7 @@\n import logging\n \n-import matplotlib.pyplot as plt\n-\n from espnet.asr import asr_utils\n+import matplotlib.pyplot as plt\n \n \n def _plot_and_save_attention(att_w, filename):\n", "issue": "matplotlib.use('Agg') fail\nIt result in plot fail \r\n```\r\n_tkinter.TclError: no display name and no $DISPLAY environment variable\r\n```\r\nI fixed this by applying a patch on `espnet/nets/pytorch_backend/transformer/plot.py`\r\n```\r\n@@ -1,5 +1,6 @@\r\n import logging\r\n-\r\n+import matplotlib\r\n+matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n\r\n from espnet.asr import asr_utils\r\n```\n", "before_files": [{"content": "import logging\n\nimport matplotlib.pyplot as plt\n\nfrom espnet.asr import asr_utils\n\n\ndef _plot_and_save_attention(att_w, filename):\n    # dynamically import matplotlib due to not found error\n    from matplotlib.ticker import MaxNLocator\n    import os\n    d = os.path.dirname(filename)\n    if not os.path.exists(d):\n        os.makedirs(d)\n    w, h = plt.figaspect(1.0 / len(att_w))\n    fig = plt.Figure(figsize=(w * 2, h * 2))\n    axes = fig.subplots(1, len(att_w))\n    if len(att_w) == 1:\n        axes = [axes]\n    for ax, aw in zip(axes, att_w):\n        # plt.subplot(1, len(att_w), h)\n        ax.imshow(aw, aspect=\"auto\")\n        ax.set_xlabel(\"Input\")\n        ax.set_ylabel(\"Output\")\n        ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n        ax.yaxis.set_major_locator(MaxNLocator(integer=True))\n    fig.tight_layout()\n    return fig\n\n\ndef savefig(plot, filename):\n    plot.savefig(filename)\n    plt.clf()\n\n\ndef plot_multi_head_attention(data, attn_dict, outdir, suffix=\"png\", savefn=savefig):\n    \"\"\"Plot multi head attentions\n\n    :param dict data: utts info from json file\n    :param dict[str, torch.Tensor] attn_dict: multi head attention dict.\n        values should be torch.Tensor (head, input_length, output_length)\n    :param str outdir: dir to save fig\n    :param str suffix: filename suffix including image type (e.g., png)\n    :param savefn: function to save\n    \"\"\"\n    for name, att_ws in attn_dict.items():\n        for idx, att_w in enumerate(att_ws):\n            filename = \"%s/%s.%s.%s\" % (\n                outdir, data[idx][0], name, suffix)\n            dec_len = int(data[idx][1]['output'][0]['shape'][0])\n            enc_len = int(data[idx][1]['input'][0]['shape'][0])\n            if \"encoder\" in name:\n                att_w = att_w[:, :enc_len, :enc_len]\n            elif \"decoder\" in name:\n                if \"self\" in name:\n                    att_w = att_w[:, :dec_len, :dec_len]\n                else:\n                    att_w = att_w[:, :dec_len, :enc_len]\n            else:\n                logging.warning(\"unknown name for shaping attention\")\n            fig = _plot_and_save_attention(att_w, filename)\n            savefn(fig, filename)\n\n\nclass PlotAttentionReport(asr_utils.PlotAttentionReport):\n    def plotfn(self, *args, **kwargs):\n        plot_multi_head_attention(*args, **kwargs)\n\n    def __call__(self, trainer):\n        attn_dict = self.get_attention_weights()\n        suffix = \"ep.{.updater.epoch}.png\".format(trainer)\n        self.plotfn(self.data, attn_dict, self.outdir, suffix, savefig)\n\n    def get_attention_weights(self):\n        batch = self.converter([self.transform(self.data)], self.device)\n        if isinstance(batch, tuple):\n            att_ws = self.att_vis_fn(*batch)\n        elif isinstance(batch, dict):\n            att_ws = self.att_vis_fn(**batch)\n        return att_ws\n\n    def log_attentions(self, logger, step):\n        def log_fig(plot, filename):\n            from os.path import basename\n            logger.add_figure(basename(filename), plot, step)\n            plt.clf()\n\n        attn_dict = self.get_attention_weights()\n        self.plotfn(self.data, attn_dict, self.outdir, \"\", log_fig)\n", "path": "espnet/nets/pytorch_backend/transformer/plot.py"}]}