prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  Changing the order of plotting and file load seems to cause netcdf errors
  For some reason it seems that changing the order of plotting and loading data causes failures, not entirely sure why yet. This is only occurring for me on Ubuntu 16.04 with the latest version of arviz. It does not occur on my osx laptop
  
  
  Load, Load, Plot, Plot doesn't work. Stack trace attached
  [stack_trace.txt](https://github.com/arviz-devs/arviz/files/2349232/stack_trace.txt)
  
  ```
  import arviz as az
  az.style.use('arviz-darkgrid')
  
  non_centered = az.load_arviz_data('non_centered_eight')
  centered = az.load_arviz_data('centered_eight')
  az.violintraceplot(non_centered, var_names=["mu", "tau"], textsize=8)
  az.violintraceplot(centered, var_names=["mu", "tau"], textsize=8)
  ```
  
  Load, Plot, Load, Plot works
  
  ```
  import arviz as az
  az.style.use('arviz-darkgrid')
  
  non_centered = az.load_arviz_data('non_centered_eight')
  az.violintraceplot(non_centered, var_names=["mu", "tau"], textsize=8)
  
  centered = az.load_arviz_data('centered_eight')
  az.violintraceplot(centered, var_names=["mu", "tau"], textsize=8)
  ```
  
  </issue>
  <code>
  [start of arviz/inference_data.py]
  1 """Data structure for using netcdf groups with xarray."""
  2 import netCDF4 as nc
  3 import xarray as xr
  4 
  5 
  6 class InferenceData():
  7     """Container for accessing netCDF files using xarray."""
  8 
  9     def __init__(self, *_, **kwargs):
  10         """Initialize InferenceData object from keyword xarray datasets.
  11 
  12         Examples
  13         --------
  14         InferenceData(posterior=posterior, prior=prior)
  15 
  16         Parameters
  17         ----------
  18         kwargs :
  19             Keyword arguments of xarray datasets
  20         """
  21         self._groups = []
  22         for key, dataset in kwargs.items():
  23             if dataset is None:
  24                 continue
  25             elif not isinstance(dataset, xr.Dataset):
  26                 raise ValueError('Arguments to InferenceData must be xarray Datasets '
  27                                  '(argument "{}" was type "{}")'.format(key, type(dataset)))
  28             setattr(self, key, dataset)
  29             self._groups.append(key)
  30 
  31     def __repr__(self):
  32         """Make string representation of object."""
  33         return 'Inference data with groups:\n\t> {options}'.format(
  34             options='\n\t> '.join(self._groups)
  35         )
  36 
  37     @staticmethod
  38     def from_netcdf(filename):
  39         """Initialize object from a netcdf file.
  40 
  41         Expects that the file will have groups, each of which can be loaded by xarray.
  42 
  43         Parameters
  44         ----------
  45         filename : str
  46             location of netcdf file
  47 
  48         Returns
  49         -------
  50         InferenceData object
  51         """
  52         groups = {}
  53         for group in nc.Dataset(filename, mode='r').groups:
  54             groups[group] = xr.open_dataset(filename, group=group, autoclose=True)
  55         return InferenceData(**groups)
  56 
  57     def to_netcdf(self, filename):
  58         """Write InferenceData to file using netcdf4.
  59 
  60         Parameters
  61         ----------
  62         filename : str
  63             Location to write to
  64 
  65         Returns
  66         -------
  67         str
  68             Location of netcdf file
  69         """
  70         mode = 'w' # overwrite first, then append
  71         for group in self._groups:
  72             data = getattr(self, group)
  73             data.to_netcdf(filename, mode=mode, group=group)
  74             data.close()
  75             mode = 'a'
  76         return filename
  77
  [end of arviz/inference_data.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/arviz/inference_data.py b/arviz/inference_data.py
  --- a/arviz/inference_data.py
  +++ b/arviz/inference_data.py
  @@ -50,8 +50,12 @@
           InferenceData object
           """
           groups = {}
  -        for group in nc.Dataset(filename, mode='r').groups:
  -            groups[group] = xr.open_dataset(filename, group=group, autoclose=True)
  +        with nc.Dataset(filename, mode='r') as data:
  +            data_groups = list(data.groups)
  +
  +        for group in data_groups:
  +            with xr.open_dataset(filename, group=group) as data:
  +                groups[group] = data
           return InferenceData(**groups)
   
       def to_netcdf(self, filename):
  
verification_info: {"golden_diff": "diff --git a/arviz/inference_data.py b/arviz/inference_data.py\n--- a/arviz/inference_data.py\n+++ b/arviz/inference_data.py\n@@ -50,8 +50,12 @@\n         InferenceData object\n         \"\"\"\n         groups = {}\n-        for group in nc.Dataset(filename, mode='r').groups:\n-            groups[group] = xr.open_dataset(filename, group=group, autoclose=True)\n+        with nc.Dataset(filename, mode='r') as data:\n+            data_groups = list(data.groups)\n+\n+        for group in data_groups:\n+            with xr.open_dataset(filename, group=group) as data:\n+                groups[group] = data\n         return InferenceData(**groups)\n \n     def to_netcdf(self, filename):\n", "issue": "Changing the order of plotting and file load seems to cause netcdf errors\nFor some reason it seems that changing the order of plotting and loading data causes failures, not entirely sure why yet. This is only occurring for me on Ubuntu 16.04 with the latest version of arviz. It does not occur on my osx laptop\r\n\r\n\r\nLoad, Load, Plot, Plot doesn't work. Stack trace attached\r\n[stack_trace.txt](https://github.com/arviz-devs/arviz/files/2349232/stack_trace.txt)\r\n\r\n```\r\nimport arviz as az\r\naz.style.use('arviz-darkgrid')\r\n\r\nnon_centered = az.load_arviz_data('non_centered_eight')\r\ncentered = az.load_arviz_data('centered_eight')\r\naz.violintraceplot(non_centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\naz.violintraceplot(centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\n```\r\n\r\nLoad, Plot, Load, Plot works\r\n\r\n```\r\nimport arviz as az\r\naz.style.use('arviz-darkgrid')\r\n\r\nnon_centered = az.load_arviz_data('non_centered_eight')\r\naz.violintraceplot(non_centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\n\r\ncentered = az.load_arviz_data('centered_eight')\r\naz.violintraceplot(centered, var_names=[\"mu\", \"tau\"], textsize=8)\r\n```\n", "before_files": [{"content": "\"\"\"Data structure for using netcdf groups with xarray.\"\"\"\nimport netCDF4 as nc\nimport xarray as xr\n\n\nclass InferenceData():\n    \"\"\"Container for accessing netCDF files using xarray.\"\"\"\n\n    def __init__(self, *_, **kwargs):\n        \"\"\"Initialize InferenceData object from keyword xarray datasets.\n\n        Examples\n        --------\n        InferenceData(posterior=posterior, prior=prior)\n\n        Parameters\n        ----------\n        kwargs :\n            Keyword arguments of xarray datasets\n        \"\"\"\n        self._groups = []\n        for key, dataset in kwargs.items():\n            if dataset is None:\n                continue\n            elif not isinstance(dataset, xr.Dataset):\n                raise ValueError('Arguments to InferenceData must be xarray Datasets '\n                                 '(argument \"{}\" was type \"{}\")'.format(key, type(dataset)))\n            setattr(self, key, dataset)\n            self._groups.append(key)\n\n    def __repr__(self):\n        \"\"\"Make string representation of object.\"\"\"\n        return 'Inference data with groups:\\n\\t> {options}'.format(\n            options='\\n\\t> '.join(self._groups)\n        )\n\n    @staticmethod\n    def from_netcdf(filename):\n        \"\"\"Initialize object from a netcdf file.\n\n        Expects that the file will have groups, each of which can be loaded by xarray.\n\n        Parameters\n        ----------\n        filename : str\n            location of netcdf file\n\n        Returns\n        -------\n        InferenceData object\n        \"\"\"\n        groups = {}\n        for group in nc.Dataset(filename, mode='r').groups:\n            groups[group] = xr.open_dataset(filename, group=group, autoclose=True)\n        return InferenceData(**groups)\n\n    def to_netcdf(self, filename):\n        \"\"\"Write InferenceData to file using netcdf4.\n\n        Parameters\n        ----------\n        filename : str\n            Location to write to\n\n        Returns\n        -------\n        str\n            Location of netcdf file\n        \"\"\"\n        mode = 'w' # overwrite first, then append\n        for group in self._groups:\n            data = getattr(self, group)\n            data.to_netcdf(filename, mode=mode, group=group)\n            data.close()\n            mode = 'a'\n        return filename\n", "path": "arviz/inference_data.py"}]}