Java Code Examples for org.opengis.parameter.ParameterValue#setValue()

The following examples show how to use org.opengis.parameter.ParameterValue#setValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnmodifiableParameterValueTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that {@link UnmodifiableParameterValue#getValue()} can clone the value.
 */
@Test
@DependsOnMethod("testCreate")
public void testGetValue() {
    final ParameterValue<Date> modifiable = DefaultParameterDescriptorTest
            .createSimpleOptional("Time reference", Date.class).createValue();
    modifiable.setValue(date("1994-01-01 00:00:00"));
    /*
     * Create and validate an unmodifiable parameter,
     * then verify that the values are not the same.
     */
    final DefaultParameterValue<Date> unmodifiable = assertEquivalent(modifiable);
    final Date t1 =   modifiable.getValue();
    final Date t2 = unmodifiable.getValue();
    assertNotSame("Date should be cloned.", t1, t2);
    assertEquals(t1, t2);
    /*
     * Verify that cloning the parameter also clone its value.
     */
    final DefaultParameterValue<Date> clone = unmodifiable.clone();
    assertEquals(DefaultParameterValue.class, clone.getClass());
    final Date t3 = clone.getValue();
    assertNotSame(t1, t3);
    assertNotSame(t2, t3);
    assertEquals (t1, t3);
}
 
Example 2
Source File: DefaultParameterValueGroupTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@code DefaultParameterValueGroup.values().set(…)}.
 */
@Test
@DependsOnMethod("testValuesGet")
public void testValuesSet() {
    final DefaultParameterValueGroup  group  = new DefaultParameterValueGroup(descriptor);
    final List<GeneralParameterValue> values = group.values();
    assertEquals("Initial size", 2, values.size());
    final ParameterValue<?> p0 = (ParameterValue<?>) descriptor.descriptors().get(0).createValue();
    final ParameterValue<?> p1 = (ParameterValue<?>) descriptor.descriptors().get(1).createValue();
    p0.setValue(4);
    p1.setValue(5);
    assertEquals("Mandatory 1", values.set(0, p0).getDescriptor().getName().toString());
    assertEquals("Mandatory 2", values.set(1, p1).getDescriptor().getName().toString());
    try {
        values.set(2, p1);
        fail("Index 2 shall be out of bounds.");
    } catch (IndexOutOfBoundsException e) {
        assertNotNull(e.getMessage());
    }
    assertEquals("size", 2, values.size()); // Size should be unchanged.
    assertEquals(4, ((ParameterValue<?>) values.get(0)).intValue());
    assertEquals(5, ((ParameterValue<?>) values.get(1)).intValue());
}
 
Example 3
Source File: Proj4Parser.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the parameter value group filled from the {@literal Proj.4} parameters.
 *
 * @throws IllegalArgumentException if a Proj.4 parameter can not be converted to the expected type.
 */
final ParameterValueGroup parameters() throws IllegalArgumentException {
    final ParameterValueGroup pg = method.getParameters().createValue();
    for (final Map.Entry<String,String> entry : parameters.entrySet()) {
        final String keyword = entry.getKey();
        if (!EXCLUDES.contains(keyword)) {
            final ParameterValue<?> value = pg.parameter(keyword);
            value.setValue(Double.parseDouble(entry.getValue()));
        }
    }
    return pg;
}
 
Example 4
Source File: TensorValues.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets all parameter values to the element value in the specified matrix.
 * After this method call, {@link #values} will returns only the elements
 * different from the default value.
 *
 * @param  matrix  the matrix to copy in this group of parameters.
 */
final void setMatrix(final Matrix matrix) {
    final int numRow = matrix.getNumRow();
    final int numCol = matrix.getNumCol();
    dimensions[0].setValue(numRow);
    dimensions[1].setValue(numCol);
    values = null;
    final int[] indices = new int[2];
    for (int j=0; j<numRow; j++) {
        indices[0] = j;
        ParameterValue<?>[] row = null;
        for (int i=0; i<numCol; i++) {
            indices[1] = i;
            ParameterDescriptor<E> descriptor = descriptors.getElementDescriptor(indices);
            final E def = descriptor.getDefaultValue();
            final double element = matrix.getElement(j,i);
            if (!(def instanceof Number) || !Numerics.equalsIgnoreZeroSign(element, ((Number) def).doubleValue())) {
                final ParameterValue<?> value = descriptor.createValue();
                value.setValue(element);
                if (row == null) {
                    row = new ParameterValue<?>[numCol];
                    if (values == null) {
                        values = new ParameterValue<?>[numRow][];
                    }
                    values[j] = row;
                }
                row[i] = value;
            }
        }
    }
}
 
Example 5
Source File: UnmodifiableParameterValueTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the value returned by {@link DefaultParameterValue#unmodifiable(ParameterValue)}.
 */
@Test
public void testCreate() {
    final ParameterValue<Double> modifiable = DefaultParameterDescriptorTest
            .createSimpleOptional("Scale factor", Double.class).createValue();
    modifiable.setValue(0.9996); // Scale factor of all UTM projections.
    /*
     * Create and validate an unmodifiable parameter,
     * then verify that we can not modify its value.
     */
    final DefaultParameterValue<Double> unmodifiable = assertEquivalent(modifiable);
    assertSame("Double instances do not need to be cloned.", modifiable.getValue(), unmodifiable.getValue());
    modifiable.setValue(1.0);
    try {
        unmodifiable.setValue(1.0);
        fail("UnmodifiableParameterValue shall not allow modification.");
    } catch (UnsupportedOperationException e) {
        final String message = e.getMessage();
        assertTrue(message, message.contains("DefaultParameterValue"));
    }
    assertEquals(1.0,      modifiable.doubleValue(), STRICT);
    assertEquals(0.9996, unmodifiable.doubleValue(), STRICT);
    /*
     * Verify that invoking again DefaultParameterValue.unmodifiable(…) return the same instance.
     * Opportunistically verify that we detect null value and instances already unmodifiable.
     */
    assertNull   (              DefaultParameterValue.unmodifiable(null));
    assertSame   (unmodifiable, DefaultParameterValue.unmodifiable(unmodifiable));
    assertNotSame(unmodifiable, assertEquivalent(modifiable));
    modifiable.setValue(0.9996); // Restore our original value.
    assertSame   (unmodifiable, assertEquivalent(modifiable));
}
 
Example 6
Source File: ParameterFormatTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the formatting of a parameter value group with a cardinality
 * invalid according ISO 19111, but allowed by Apache SIS implementation.
 * ISO 19111 restricts {@link ParameterValue} cardinality to the [0 … 1] range,
 * but SIS can handle arbitrary number of occurrences (2 in this test).
 */
@Test
@DependsOnMethod("testExtendedCardinality")
public void testMultiOccurrence() {
    final ParameterValueGroup group = DefaultParameterDescriptorGroupTest.M1_M1_O1_O2.createValue();
    group.parameter("Mandatory 2").setValue(20);
    final ParameterValue<?> value = group.parameter("Optional 4");
    value.setValue(40);
    /*
     * Adding a second occurrence of the same parameter.
     * Not straightforward because not allowed by ISO 19111.
     */
    final ParameterValue<?> secondOccurrence = value.getDescriptor().createValue();
    group.values().add(secondOccurrence);
    secondOccurrence.setValue(50);

    final ParameterFormat format = new ParameterFormat(null, null);
    format.setContentLevel(ParameterFormat.ContentLevel.BRIEF);
    final String text = format.format(group);
    assertMultilinesEquals(
            "Test group\n" +
            "┌─────────────┬─────────┬──────────────┬───────┐\n" +
            "│ Name        │ Type    │ Value domain │ Value │\n" +
            "├─────────────┼─────────┼──────────────┼───────┤\n" +
            "│ Mandatory 1 │ Integer │              │    10 │\n" +
            "│ Mandatory 2 │ Integer │              │    20 │\n" +
            "│ Optional 4  │ Integer │              │    40 │\n" +
            "│      ″      │    ″    │      ″       │    50 │\n" +
            "└─────────────┴─────────┴──────────────┴───────┘\n", text);
}
 
Example 7
Source File: MapProjectionParametersTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the standard parallel dynamic parameter.
 */
@Test
public void testStandardParallel() {
    final MapProjectionDescriptor descriptor = createDescriptor(2);
    final ParameterValueGroup parameters = descriptor.createValue();
    final ParameterValue<?> p  = parameters.parameter(STANDARD_PARALLEL);
    final ParameterValue<?> p1 = parameters.parameter(STANDARD_PARALLEL_1);
    final ParameterValue<?> p2 = parameters.parameter(STANDARD_PARALLEL_2);
    assertSame(p,  parameters.parameter(STANDARD_PARALLEL));
    assertSame(p1, parameters.parameter(STANDARD_PARALLEL_1));
    assertSame(p2, parameters.parameter(STANDARD_PARALLEL_2));
    assertNotSame(p1, p2);
    assertNotSame(p1, p);
    assertNotSame(p2, p);

    /* Empty */      assertArrayEquals(new double[] {     }, p.doubleValueList(), 0.0);
    p1.setValue(40); assertArrayEquals(new double[] {40   }, p.doubleValueList(), 0.0);
    p2.setValue(60); assertArrayEquals(new double[] {40,60}, p.doubleValueList(), 0.0);

    p.setValue(new double[] {30,40});
    assertEquals(30, p1.doubleValue(), 0.0);
    assertEquals(40, p2.doubleValue(), 0.0);

    p.setValue(new double[] {45});
    assertEquals(45,         p1.doubleValue(), 0.0);
    assertEquals(Double.NaN, p2.doubleValue(), 0.0);
}
 
Example 8
Source File: OmsMapsViewer.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void addImageMosaic( MapContent map ) throws Exception {
    if (inImageMosaics != null) {
        RasterSymbolizer sym = sf.getDefaultRasterSymbolizer();
        Style style = SLD.wrapSymbolizers(sym);

        final ParameterValue<Color> inTransp = AbstractGridFormat.INPUT_TRANSPARENT_COLOR.createValue();
        inTransp.setValue(Color.white);

        final ParameterValue<Color> outTransp = ImageMosaicFormat.OUTPUT_TRANSPARENT_COLOR.createValue();
        outTransp.setValue(Color.white);
        final ParameterValue<Color> backColor = ImageMosaicFormat.BACKGROUND_COLOR.createValue();
        backColor.setValue(Color.RED);
        final ParameterValue<Boolean> fading = ImageMosaicFormat.FADING.createValue();
        fading.setValue(true);

        final ParameterValue<Interpolation> interpol = ImageMosaicFormat.INTERPOLATION.createValue();
        interpol.setValue(new javax.media.jai.InterpolationBilinear());

        final ParameterValue<Boolean> resol = ImageMosaicFormat.ACCURATE_RESOLUTION.createValue();
        resol.setValue(true);

        
        final ParameterValue<Boolean> multiThread= ImageMosaicFormat.ALLOW_MULTITHREADING.createValue();
        multiThread.setValue(true);

        final ParameterValue<Boolean> usejai = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue();
        usejai.setValue(false);

        final ParameterValue<double[]> bkg = ImageMosaicFormat.BACKGROUND_VALUES.createValue();
        bkg.setValue(new double[]{0});

        GeneralParameterValue[] gp = new GeneralParameterValue[]{inTransp, multiThread};

        for( String imageMosaicPath : inImageMosaics ) {
            ImageMosaicReader imr = new ImageMosaicReader(new File(imageMosaicPath));
            GridReaderLayer layer = new GridReaderLayer(imr, style, gp);
            map.addLayer(layer);
        }
    }

}
 
Example 9
Source File: CustomCrsPanel.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private static PropertyContainer createValueContainer(ParameterValueGroup valueGroup) {
    final PropertyContainer vc = new PropertyContainer();
    List<GeneralParameterDescriptor> descriptors = valueGroup.getDescriptor().descriptors();
    for (GeneralParameterDescriptor descriptor : descriptors) {
        final Class valueType;
        Set validValues = null;
        Comparable minValue = null;
        Comparable maxValue = null;
        if (descriptor instanceof ParameterDescriptor) {
            ParameterDescriptor parameterDescriptor = (ParameterDescriptor) descriptor;
            valueType = parameterDescriptor.getValueClass();
            validValues = parameterDescriptor.getValidValues();
            minValue = parameterDescriptor.getMinimumValue();
            maxValue = parameterDescriptor.getMaximumValue();
        } else {
            valueType = Double.TYPE;
        }

        final String paramName = descriptor.getName().getCode();
        final PropertyDescriptor vd = new PropertyDescriptor(paramName, valueType);
        final ParameterValue<?> parameterValue = valueGroup.parameter(paramName);
        if (parameterValue.getUnit() != null) {
            vd.setUnit(String.valueOf(parameterValue.getUnit()));
        }
        if (validValues != null) {
            vd.setValueSet(new ValueSet(validValues.toArray()));
        }
        if ( minValue instanceof Double && maxValue instanceof Double) {
            Double min = (Double) minValue;
            Double max = (Double) maxValue;
            vd.setValueRange(new ValueRange(min, max));
            if(parameterValue.getValue() == null) {
                parameterValue.setValue((min + max) / 2);
            }
        }

        vd.setDefaultConverter();
        final Property property = new Property(vd, new PropertyAccessor() {
            @Override
            public Object getValue() {
                return parameterValue.getValue();
            }

            @Override
            public void setValue(Object value) {
                parameterValue.setValue(value);
            }
        });
        vc.addProperty(property);
    }
    return vc;
}
 
Example 10
Source File: DefaultMathTransformFactory.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Completes the parameter group with information about source and target ellipsoid axis lengths,
 * if available. This method writes semi-major and semi-minor parameter values only if they do not
 * already exists in the given parameters.
 *
 * <p>The given method and parameters are stored in the {@link #provider} and {@link #parameters}
 * fields respectively. The actual stored values may differ from the values given to this method.</p>
 *
 * @param  factory  the enclosing factory.
 * @param  method   description of the transform to be created, or {@code null} if unknown.
 * @return the exception if the operation failed, or {@code null} if none. This exception is not thrown now
 *         because the caller may succeed in creating the transform anyway, or otherwise may produce a more
 *         informative exception.
 * @throws IllegalArgumentException if the operation fails because a parameter has a unrecognized name or an
 *         illegal value.
 *
 * @see #getCompletedParameters()
 */
@SuppressWarnings("null")
final RuntimeException completeParameters(final DefaultMathTransformFactory factory, OperationMethod method,
        final ParameterValueGroup userParams) throws FactoryException, IllegalArgumentException
{
    /*
     * The "Geographic/geocentric conversions" conversion (EPSG:9602) can be either:
     *
     *    - "Ellipsoid_To_Geocentric"
     *    - "Geocentric_To_Ellipsoid"
     *
     * EPSG defines both by a single operation, but Apache SIS needs to distinguish them.
     */
    if (method instanceof AbstractProvider) {
        final String alt = ((AbstractProvider) method).resolveAmbiguity(this);
        if (alt != null) {
            method = factory.getOperationMethod(alt);
        }
    }
    provider   = method;
    parameters = userParams;
    /*
     * Get the operation method for the appropriate number of dimensions. For example the default Molodensky
     * operation expects two-dimensional source and target CRS. If a given CRS is three-dimensional, we need
     * a provider variant which will not concatenate a "geographic 3D to 2D" operation before the Molodensky
     * one. It is worth to perform this check only if the provider is a subclass of DefaultOperationMethod,
     * since it needs to override the 'redimension(int, int)' method.
     */
    if (method instanceof DefaultOperationMethod && method.getClass() != DefaultOperationMethod.class) {
        final Integer sourceDim = (sourceCS != null) ? sourceCS.getDimension() : method.getSourceDimensions();
        final Integer targetDim = (targetCS != null) ? targetCS.getDimension() : method.getTargetDimensions();
        if (sourceDim != null && targetDim != null) {
            method = ((DefaultOperationMethod) method).redimension(sourceDim, targetDim);
            if (method instanceof MathTransformProvider) {
                provider = method;
            }
        }
    }
    ensureCompatibleParameters(false);      // Invoke only after we set 'provider' to its final instance.
    /*
     * Get a mask telling us if we need to set parameters for the source and/or target ellipsoid.
     * This information should preferably be given by the provider. But if the given provider is
     * not a SIS implementation, use as a fallback whether ellipsoids are provided. This fallback
     * may be less reliable.
     */
    int n;
    if (provider instanceof AbstractProvider) {
        n = ((AbstractProvider) provider).getEllipsoidsMask();
    } else {
        n = 0;
        if (sourceEllipsoid != null) n  = 1;
        if (targetEllipsoid != null) n |= 2;
    }
    /*
     * Set the ellipsoid axis-length parameter values. Those parameters may appear in the source ellipsoid,
     * in the target ellipsoid or in both ellipsoids.
     */
    switch (n) {
        case 0: return null;
        case 1: return setEllipsoid(getSourceEllipsoid(), Constants.SEMI_MAJOR, Constants.SEMI_MINOR, true, null);
        case 2: return setEllipsoid(getTargetEllipsoid(), Constants.SEMI_MAJOR, Constants.SEMI_MINOR, true, null);
        case 3: {
            RuntimeException failure = null;
            if (sourceCS != null) try {
                ensureCompatibleParameters(true);
                final ParameterValue<?> p = parameters.parameter("dim");    // Really 'parameters', not 'userParams'.
                if (p.getValue() == null) {
                    p.setValue(sourceCS.getDimension());
                }
            } catch (IllegalArgumentException | IllegalStateException e) {
                failure = e;
            }
            failure = setEllipsoid(getSourceEllipsoid(), "src_semi_major", "src_semi_minor", false, failure);
            failure = setEllipsoid(getTargetEllipsoid(), "tgt_semi_major", "tgt_semi_minor", false, failure);
            return failure;
        }
        default: throw new AssertionError(n);
    }
}
 
Example 11
Source File: InverseOperationMethod.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Infers the properties to give to an inverse coordinate operation.
 * The returned map will contain three kind of information:
 *
 * <ul>
 *   <li>Metadata (domain of validity, accuracy)</li>
 *   <li>Parameter values, if possible</li>
 * </ul>
 *
 * This method copies accuracy and domain of validity metadata from the given operation.
 * We presume that the inverse operation has the same accuracy than the direct operation.
 *
 * <div class="note"><b>Note:</b>
 * in many cases, the inverse operation is numerically less accurate than the direct operation because it
 * uses approximations like series expansions or iterative methods. However the numerical errors caused by
 * those approximations are not of interest here, because they are usually much smaller than the inaccuracy
 * due to the stochastic nature of coordinate transformations (not to be confused with coordinate conversions;
 * see ISO 19111 for more information).</div>
 *
 * If the inverse of the given operation can be represented by inverting the sign of all numerical
 * parameter values, then this method copies also those parameters in a {@code "parameters"} entry.
 *
 * @param source  the operation for which to get the inverse parameters.
 * @param target  where to store the inverse parameters.
 */
static void properties(final SingleOperation source, final Map<String,Object> target) {
    target.put(SingleOperation.DOMAIN_OF_VALIDITY_KEY, source.getDomainOfValidity());
    final Collection<PositionalAccuracy> accuracy = source.getCoordinateOperationAccuracy();
    if (!Containers.isNullOrEmpty(accuracy)) {
        target.put(SingleOperation.COORDINATE_OPERATION_ACCURACY_KEY,
                accuracy.toArray(new PositionalAccuracy[accuracy.size()]));
    }
    /*
     * If the inverse of the given operation can be represented by inverting the sign of all numerical
     * parameter values, copies those parameters in a "parameters" entry in the properties map.
     * Otherwise does nothing.
     */
    final ParameterValueGroup parameters = source.getParameterValues();
    final ParameterValueGroup copy = parameters.getDescriptor().createValue();
    for (final GeneralParameterValue gp : parameters.values()) {
        if (gp instanceof ParameterValue<?>) {
            final ParameterValue<?> src = (ParameterValue<?>) gp;
            final Object value = src.getValue();
            if (value instanceof Number) {
                final ParameterDescriptor<?> descriptor = src.getDescriptor();
                final InternationalString remarks = descriptor.getRemarks();
                if (remarks != SignReversalComment.SAME) {
                    if (remarks != SignReversalComment.OPPOSITE) {
                        /*
                         * The parameter descriptor does not specify whether the values for the inverse operation
                         * have the same sign or opposite sign. We could heuristically presume that we can invert
                         * the sign if the minimum value has the opposite sign than the maximum value  (as in the
                         * [-10 … 10] range), but such assumption is dangerous. For example the values in a matrix
                         * could be bounded to a range like [-1 … 1], which would mislead above heuristic rule.
                         *
                         * Note that abandoning here does not mean that we will never know the parameter values.
                         * As a fallback, AbstractCoordinateOperation will try to get the parameter values from
                         * the MathTransform. This is the appropriate thing to do at least for Affine operation.
                         */
                        return;
                    }
                    /*
                     * The parameter value of the inverse operation is (or is presumed to be) the negative of
                     * the parameter value of the source operation.  We need to preserve units of measurement
                     * if they were specified.
                     */
                    final ParameterValue<?> tgt = copy.parameter(descriptor.getName().getCode());
                    final Unit<?> unit = src.getUnit();
                    if (unit != null) {
                        tgt.setValue(-src.doubleValue(), unit);
                    } else if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
                        tgt.setValue(-src.intValue());
                    } else {
                        tgt.setValue(-src.doubleValue());
                    }
                    // No need to add 'tgt' to 'copy' since it was done by the call to copy.parameter(…).
                    continue;
                }
            }
        }
        copy.values().add(gp);
    }
    target.put(CoordinateOperations.PARAMETERS_KEY, copy);
}
 
Example 12
Source File: DefaultParameterValueGroupTest.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Tests {@code DefaultParameterValueGroup.values().addAll(…)} with subgroups.
 *
 * @since 0.6
 */
@Test
@DependsOnMethod({"testValuesAddAll", "testAddGroup", "testEqualsAndHashCode"})
public void testValuesAddAllWithSubgroups() {
    final DefaultParameterDescriptorGroup group, subGroup;
    final List<GeneralParameterDescriptor> descriptors = new ArrayList<>(descriptor.descriptors());
    subGroup = new DefaultParameterDescriptorGroup(singletonMap(NAME_KEY, "theSubGroup"),
            2, 4, descriptors.toArray(new GeneralParameterDescriptor[descriptors.size()]));
    descriptors.add(subGroup);
    group = new DefaultParameterDescriptorGroup(singletonMap(NAME_KEY, "theGroup"),
            descriptors.toArray(new GeneralParameterDescriptor[descriptors.size()]));
    /*
     * Prepare the GeneralParameterValue instances that we are going to add in the above group.
     * We assign arbitrary integer values to each instance if order to be able to differentiate
     * them, but the purpose of this test is not to verify those integer values.
     *
     * We intentionally:
     *   - Omit the creation of a mandatory parameter value
     *   - Create more sub-groups than the minimum required.
     */
    final ParameterValue<?>   v2 = (ParameterValue<?>) descriptor.descriptor("Mandatory 2").createValue();
    final ParameterValue<?>   v3 = (ParameterValue<?>) descriptor.descriptor( "Optional 3").createValue();
    final ParameterValueGroup g1 = subGroup.createValue();
    final ParameterValueGroup g2 = subGroup.createValue();
    final ParameterValueGroup g3 = subGroup.createValue();
    v2.setValue(4);
    v3.setValue(8);
    g1.parameter("Mandatory 1").setValue(3);
    g2.parameter( "Optional 4").setValue(7);
    g3.parameter("Mandatory 2").setValue(5);
    final List<GeneralParameterValue> expected = new ArrayList<>(6);
    assertTrue(expected.add(v2));
    assertTrue(expected.add(v3));
    assertTrue(expected.add(g1));
    assertTrue(expected.add(g2));
    assertTrue(expected.add(g3));
    /*
     * A newly created group should be initialized with 4 GeneralParameterValue instances because of
     * the mandatory ones. After we added our own instances created above, the group should contains
     * 6 instances (one more than what we added) because of the "Mandatory 1" parameter that we did
     * not provided. Note that the element order in the 'values' collection does not need to be the
     * order in which we provided our GeneralParameterValue instances.
     */
    final List<GeneralParameterValue> values = group.createValue().values();
    assertEquals("Initial size", 4,         values.size());
    assertTrue  ("List shall be modified",  values.addAll(expected));
    assertEquals("Size after addAll(…)", 6, values.size());
    final ParameterValue<?> v1 = (ParameterValue<?>) values.get(0);
    assertEquals("Default value", DefaultParameterDescriptorGroupTest.DEFAULT_VALUE, v1.getValue());
    assertTrue(expected.add(v1));
    assertSetEquals(expected, values);
}
 
Example 13
Source File: ParametersTest.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Tests {@link Parameters#copy(ParameterValueGroup, ParameterValueGroup)}.
 *
 * @see <a href="https://issues.apache.org/jira/browse/SIS-202">SIS-202</a>
 */
@Test
public void testCopy() {
    /*
     * The descriptor to be used for this test. This descriptor contain at least
     * one subgroup, for testing the Parameters.copy(...) method recursivity.
     */
    final String subgroupName = DefaultParameterDescriptorGroupTest.M1_M1_O1_O2.getName().getCode();
    final DefaultParameterDescriptorGroup descriptor = new DefaultParameterDescriptorGroup(
            Collections.singletonMap(DefaultParameterDescriptorGroup.NAME_KEY, "parent"), 1, 1,
            DefaultParameterDescriptorTest.createSimpleOptional("A parent parameter", String.class),
            DefaultParameterDescriptorGroupTest.M1_M1_O1_O2);
    /*
     * Create the parameter value to copy. We set some values, but intentionally not all of them.
     * The unset values will be used for verifying that they do not overwrite destination values.
     */
    final ParameterValueGroup source = descriptor.createValue();
    final ParameterValueGroup sourceSubgroup = source.addGroup(subgroupName);
    final ParameterValue<?> o1 = sourceSubgroup.parameter("Optional 4");
    final ParameterValue<?> o2 = o1.getDescriptor().createValue();      // See ParameterFormatTest.testMultiOccurrence()
    sourceSubgroup.parameter("Mandatory 2").setValue(20);
    sourceSubgroup.values().add(o2);
    o1.setValue(40);
    o2.setValue(50);
    source.parameter("A parent parameter").setValue("A value from the source");
    /*
     * Create the parameter to use as the destination. We put some value in those parameters in order to
     * verify that those values are overwritten (only those for which the value is set in the source).
     */
    final ParameterValueGroup target = descriptor.createValue();
    final ParameterValueGroup targetSubgroup = target.addGroup(subgroupName);
    targetSubgroup.parameter("Mandatory 1").setValue(-10);      // We expect this value to be overwritten.
    targetSubgroup.parameter("Optional 3") .setValue( 30);      // We expect this value to be preserved.
    target.parameter("A parent parameter") .setValue("A value to be overwritten");
    /*
     * The actual test.
     */
    Parameters.copy(source, target);
    assertSame(sourceSubgroup, TestUtilities.getSingleton(source.groups(subgroupName)));
    assertSame(targetSubgroup, TestUtilities.getSingleton(target.groups(subgroupName)));
    assertEquals("A value from the source", target.parameter("A parent parameter").getValue());
    assertEquals("Mandatory 1",    10, targetSubgroup.parameter("Mandatory 1").intValue());
    assertEquals("Mandatory 2",    20, targetSubgroup.parameter("Mandatory 2").intValue());
    assertEquals("Optional 3",     30, targetSubgroup.parameter("Optional 3") .intValue());
    assertEquals("Optional 4",     40, ((ParameterValue<?>) targetSubgroup.values().get(3)).intValue());
    assertEquals("Optional 4 bis", 50, ((ParameterValue<?>) targetSubgroup.values().get(4)).intValue());
}
 
Example 14
Source File: DefaultMathTransformFactory.java    From sis with Apache License 2.0 3 votes vote down vote up
/**
 * Ensures that a value is set in the given parameter.
 *
 * <ul>
 *   <li>If the parameter has no value, then it is set to the given value.<li>
 *   <li>If the parameter already has a value, then the parameter is left unchanged
 *       but its value is compared to the given one for consistency.</li>
 * </ul>
 *
 * @param  parameter  the parameter which must have a value.
 * @param  actual     the current parameter value, or {@code NaN} if none.
 * @param  expected   the expected parameter value, derived from the ellipsoid.
 * @param  unit       the unit of {@code value}.
 * @param  tolerance  maximal difference (in unit of {@code unit}) for considering the two values as equivalent.
 * @return {@code true} if there is a mismatch between the actual value and the expected one.
 */
private static boolean ensureSet(final ParameterValue<?> parameter, final double actual,
        final double expected, final Unit<?> unit, final double tolerance)
{
    if (Math.abs(actual - expected) <= tolerance) {
        return false;
    }
    if (Double.isNaN(actual)) {
        parameter.setValue(expected, unit);
        return false;
    }
    return true;
}