title: Python: How to interpolate angles on a grid?
body: <p>I have a grid with some given data. This data is given by its angle (from <code>0</code> to <code>π</code>).
  Within this grid I have another smaller grid.</p>
  
  <p>This might look like this:</p>
  
  <p><a href="https://i.stack.imgur.com/0Rqpn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Rqpn.png" alt="enter image description here"></a></p>
  
  <p>Now I want to interpolate the angles on that grid.</p>
  
  <p>I tried this by using <code>scipy.interpolate.griddata</code> what gives a good result. But there is a problem when the angles change from almost <code>0</code> to almost <code>π</code> (because the middle is <code>π/2</code> ...)</p>
  
  <p>Here is the result and it is easy to see what's going wrong.</p>
  
  <p><a href="https://i.stack.imgur.com/nLrPB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nLrPB.png" alt="enter image description here"></a></p>
  
  <p>How can I deal with that problem? Thank you! :)</p>
  
  <p>Here is the code to reproduce:</p>
  
  <pre><code>import numpy as np
  from matplotlib import pyplot as plt
  from scipy.interpolate import griddata
  
  ax = plt.subplot()
  ax.set_aspect(1)
  
  # Simulate some given data.
  x, y = np.meshgrid(np.linspace(-10, 10, 20), np.linspace(-10, 10, 20))
  data = np.arctan(y / 10) % np.pi
  u = np.cos(data)
  v = np.sin(data)
  
  ax.quiver(x, y, u, v, headlength=0.01, headaxislength=0, pivot='middle', units='xy')
  
  # Create a smaller grid within.
  x1, y1 = np.meshgrid(np.linspace(-1, 5, 15), np.linspace(-6, 2, 20))
  # ax.plot(x1, y1, '.', color='red', markersize=2)
  
  # Interpolate data on grid.
  interpolation = griddata((x.flatten(), y.flatten()), data.flatten(), (x1.flatten(), y1.flatten()))
  u1 = np.cos(interpolation)
  v1 = np.sin(interpolation)
  ax.quiver(x1, y1, u1, v1, headlength=0.01, headaxislength=0, pivot='middle', units='xy',
            color='red', scale=3, width=0.03)
  
  plt.show()
  </code></pre>
  
  <hr>
  
  <p>Edit:</p>
  
  <p>Thanks to @bubble, there is a way to adjust the given angles before interpolation such that the result will be as desired.
  Therefore:</p>
  
  <ol>
  <li><p>Define a rectifying function:</p>
  
  <pre><code>def RectifyData(data):
      for j in range(len(data)):
          step = data[j] - data[j - 1]
          if abs(step) &gt; np.pi / 2:
              data[j] += np.pi * (2 * (step &lt; 0) - 1)
      return data
  </code></pre></li>
  <li><p>Interpolate as follows:</p>
  
  <pre><code>interpolation = griddata((x.flatten(), y.flatten()),
                           RectifyData(data.flatten()),
                           (x1.flatten(), y1.flatten()))
  u1 = np.cos(interpolation)
  v1 = np.sin(interpolation)
  </code></pre></li>
  </ol>