/**
   * Perform a two-dimensional interpolation
   *
   * @param oldx an IDataset containing a 1D array of X-values, sorted in increasing order,
   *     corresponding to the first dimension of <code>oldxy</code>
   * @param oldy an IDataset containing a 1D array of Y-values, sorted in increasing order,
   *     corresponding to the second dimension of <code>oldxy</code>
   * @param oldxy an IDataset containing a 2D grid of interpolation points
   * @param newx an IDataset containing a 1D array of X-values that will be sent to the
   *     interpolating function
   * @param newy an IDataset containing a 1D array of Y-values that will be sent to the
   *     interpolating function
   * @param interpolator an instance of {@link
   *     org.apache.commons.math3.analysis.interpolation.BivariateGridInterpolator}
   * @param output_type an {@link BicubicInterpolationOutput} that will determine how <code>newx
   *     </code> and <code>newy</code> will be interpreted, and therefore whether a 1D or 2D Dataset
   *     will be returned.
   * @return rank 1 or 2 Dataset, depending on <code>output_type}</code>
   * @throws NonMonotonicSequenceException
   * @throws NumberIsTooSmallException
   */
  public static Dataset interpolate(
      IDataset oldx,
      IDataset oldy,
      IDataset oldxy,
      IDataset newx,
      IDataset newy,
      BivariateGridInterpolator interpolator,
      BicubicInterpolationOutput output_type)
      throws NonMonotonicSequenceException, NumberIsTooSmallException {

    // check shapes
    if (oldx.getRank() != 1) throw new IllegalArgumentException("oldx Shape must be 1D");
    if (oldy.getRank() != 1) throw new IllegalArgumentException("oldy Shape must be 1D");
    if (oldxy.getRank() != 2) throw new IllegalArgumentException("oldxy Shape must be 2D");
    if (oldx.getShape()[0] != oldxy.getShape()[0])
      throw new IllegalArgumentException("oldx Shape must match oldxy Shape[0]");
    if (oldy.getShape()[0] != oldxy.getShape()[1])
      throw new IllegalArgumentException("oldy Shape must match oldxy Shape[1]");
    if (newx.getRank() != 1) throw new IllegalArgumentException("newx Shape must be 1D");
    if (newy.getRank() != 1) throw new IllegalArgumentException("newx Shape must be 1D");
    if (output_type == BicubicInterpolationOutput.ONED && newy.getSize() != newx.getSize())
      throw new IllegalArgumentException(
          "newx and newy Size must be identical when expecting a rank 1 dataset result");

    DoubleDataset oldx_dd = (DoubleDataset) DatasetUtils.cast(oldx, Dataset.FLOAT64);
    DoubleDataset oldy_dd = (DoubleDataset) DatasetUtils.cast(oldy, Dataset.FLOAT64);
    DoubleDataset oldxy_dd = (DoubleDataset) DatasetUtils.cast(oldxy, Dataset.FLOAT64);

    // unlike in Interpolation1D, we will not be sorting here, as it just too complicated
    // the user will be responsible for ensuring the arrays are properly sorted

    // oldxy_dd needs to be transformed into a double[][] array
    // this call may throw an exception that needs handling by the calling method
    BivariateFunction func =
        interpolator.interpolate(
            oldx_dd.getData(), oldy_dd.getData(), convertDoubleDataset2DtoPrimitive(oldxy_dd));

    Dataset rv = null;

    if (output_type == BicubicInterpolationOutput.ONED) {
      rv = DatasetFactory.zeros(new int[] {newx.getSize()}, Dataset.FLOAT64);

      for (int i = 0; i < newx.getSize(); i++) {
        double val = 0.0;
        try {
          val = func.value(newx.getDouble(i), newy.getDouble(i));
          rv.set(val, i);
        } catch (OutOfRangeException e) {
          rv.set(0.0, i);
        }
      }
    } else if (output_type == BicubicInterpolationOutput.TWOD) {
      rv = DatasetFactory.zeros(new int[] {newx.getSize(), newy.getSize()}, Dataset.FLOAT64);

      for (int i = 0; i < newx.getSize(); i++) {
        for (int j = 0; j < newy.getSize(); j++) {
          double val = 0.0;
          try {
            val = func.value(newx.getDouble(i), newy.getDouble(j));
            rv.set(val, i, j);
          } catch (OutOfRangeException e) {
            rv.set(0.0, i, j);
          }
        }
      }
    }

    rv.setName(oldxy.getName() + "_interpolated");

    return rv;
  }
  private void checkNexusFile(
      IRunnableDevice<ScanModel> scanner, List<ScanMetadata> scanMetadata, int... sizes)
      throws Exception {

    final ScanModel scanModel = ((AbstractRunnableDevice<ScanModel>) scanner).getModel();
    assertEquals(DeviceState.READY, scanner.getDeviceState());

    NXroot rootNode = getNexusRoot(scanner);
    NXentry entry = rootNode.getEntry();
    checkMetadata(entry, scanMetadata);
    // check that the scan points have been written correctly
    assertScanPointsGroup(entry, sizes);

    NXinstrument instrument = entry.getInstrument();

    LinkedHashMap<String, List<String>> signalFieldAxes = new LinkedHashMap<>();
    // axis for additional dimensions of a datafield, e.g. image
    signalFieldAxes.put(NXdetector.NX_DATA, Arrays.asList("real", "imaginary"));
    signalFieldAxes.put("spectrum", Arrays.asList("spectrum_axis"));
    signalFieldAxes.put("value", Collections.emptyList());

    String detectorName = scanModel.getDetectors().get(0).getName();
    NXdetector detector = instrument.getDetector(detectorName);
    // map of detector data field to name of nxData group where that field
    // is the @signal field
    Map<String, String> expectedDataGroupNames =
        signalFieldAxes
            .keySet()
            .stream()
            .collect(
                Collectors.toMap(
                    Function.identity(),
                    x -> detectorName + (x.equals(NXdetector.NX_DATA) ? "" : "_" + x)));

    // validate the main NXdata generated by the NexusDataBuilder
    Map<String, NXdata> nxDataGroups = entry.getChildren(NXdata.class);
    assertEquals(signalFieldAxes.size(), nxDataGroups.size());
    assertTrue(nxDataGroups.keySet().containsAll(expectedDataGroupNames.values()));
    for (String nxDataGroupName : nxDataGroups.keySet()) {
      NXdata nxData = entry.getData(nxDataGroupName);

      String sourceFieldName =
          nxDataGroupName.equals(detectorName)
              ? NXdetector.NX_DATA
              : nxDataGroupName.substring(nxDataGroupName.indexOf('_') + 1);
      assertSignal(nxData, sourceFieldName);
      // check the nxData's signal field is a link to the appropriate source data node of the
      // detector
      DataNode dataNode = detector.getDataNode(sourceFieldName);
      IDataset dataset = dataNode.getDataset().getSlice();
      assertSame(dataNode, nxData.getDataNode(sourceFieldName));
      assertTarget(
          nxData,
          sourceFieldName,
          rootNode,
          "/entry/instrument/" + detectorName + "/" + sourceFieldName);

      // check that the other primary data fields of the detector haven't been added to this NXdata
      for (String primaryDataFieldName : signalFieldAxes.keySet()) {
        if (!primaryDataFieldName.equals(sourceFieldName)) {
          assertNull(nxData.getDataNode(primaryDataFieldName));
        }
      }

      int[] shape = dataset.getShape();
      for (int i = 0; i < sizes.length; i++) assertEquals(sizes[i], shape[i]);

      // Make sure none of the numbers are NaNs. The detector
      // is expected to fill this scan with non-nulls.
      final PositionIterator it = new PositionIterator(shape);
      while (it.hasNext()) {
        int[] next = it.getPos();
        assertFalse(Double.isNaN(dataset.getDouble(next)));
      }

      // Check axes
      final IPosition pos = scanModel.getPositionIterable().iterator().next();
      final Collection<String> scannableNames = pos.getNames();

      // Append _value_demand to each name in list, then add detector axis fields to result
      List<String> expectedAxesNames =
          Stream.concat(
                  scannableNames.stream().map(x -> x + "_value_set"),
                  signalFieldAxes.get(sourceFieldName).stream())
              .collect(Collectors.toList());
      assertAxes(nxData, expectedAxesNames.toArray(new String[expectedAxesNames.size()]));

      int[] defaultDimensionMappings = IntStream.range(0, sizes.length).toArray();
      int i = -1;
      for (String scannableName : scannableNames) {

        i++;
        NXpositioner positioner = instrument.getPositioner(scannableName);
        assertNotNull(positioner);

        dataNode = positioner.getDataNode("value_set");
        dataset = dataNode.getDataset().getSlice();
        shape = dataset.getShape();
        assertEquals(1, shape.length);
        assertEquals(sizes[i], shape[0]);

        String nxDataFieldName = scannableName + "_value_set";
        assertSame(dataNode, nxData.getDataNode(nxDataFieldName));
        assertIndices(nxData, nxDataFieldName, i);
        assertTarget(
            nxData, nxDataFieldName, rootNode, "/entry/instrument/" + scannableName + "/value_set");

        // Actual values should be scanD
        dataNode = positioner.getDataNode(NXpositioner.NX_VALUE);
        dataset = dataNode.getDataset().getSlice();
        shape = dataset.getShape();
        assertArrayEquals(sizes, shape);

        nxDataFieldName = scannableName + "_" + NXpositioner.NX_VALUE;
        assertSame(dataNode, nxData.getDataNode(nxDataFieldName));
        assertIndices(nxData, nxDataFieldName, defaultDimensionMappings);
        assertTarget(
            nxData,
            nxDataFieldName,
            rootNode,
            "/entry/instrument/" + scannableName + "/" + NXpositioner.NX_VALUE);
      }
    }
  }