org.opengis.parameter.ParameterValue Java Examples

The following examples show how to use org.opengis.parameter.ParameterValue. 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: CC_GeneralParameterValue.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked by JAXB at marshalling time for getting the actual element to write
 * inside the {@code <gml:parameterValue>} XML element.
 * This is the value or a copy of the value given in argument to the {@code wrap} method.
 *
 * @return the element to be marshalled.
 *
 * @see CC_GeneralOperationParameter#getElement()
 */
@XmlElements({  // We can not use @XmlElementRef because we have no public AbstractParameterValue parent class.
    @XmlElement(name = "ParameterValue",      type = DefaultParameterValue.class),
    @XmlElement(name = "ParameterValueGroup", type = DefaultParameterValueGroup.class)
})
public GeneralParameterValue getElement() {
    final GeneralParameterValue metadata = this.metadata;
    if (metadata instanceof DefaultParameterValue<?>) {
        return (DefaultParameterValue<?>) metadata;
    }
    if (metadata instanceof DefaultParameterValueGroup) {
        return (DefaultParameterValueGroup) metadata;
    }
    if (metadata instanceof ParameterValue) {
        return new DefaultParameterValue<>((ParameterValue<?>) metadata);
    }
    if (metadata instanceof ParameterValueGroup) {
        return new DefaultParameterValueGroup((ParameterValueGroup) metadata);
    }
    return null;    // Unknown types are currently not marshalled (we may revisit that in a future SIS version).
}
 
Example #3
Source File: DefaultConversionTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that at least some of the properties of the given {@code op} instance have the expected values
 * for an instance created by {@link #createLongitudeRotation(GeographicCRS, GeographicCRS, TemporalCRS)}.
 */
@SuppressWarnings("SuspiciousToArrayCall")
private static void verifyProperties(final DefaultConversion op, final boolean swapSourceAxes) {
    assertEquals("name",       "Paris to Greenwich", op.getName().getCode());
    assertEquals("sourceCRS",  "NTF (Paris)",        op.getSourceCRS().getName().getCode());
    assertEquals("targetCRS",  "Back to Greenwich",  op.getTargetCRS().getName().getCode());
    assertEquals("method",     "Longitude rotation", op.getMethod().getName().getCode());
    assertEquals("parameters", "Longitude rotation", op.getParameterDescriptors().getName().getCode());

    final ParameterValueGroup parameters = op.getParameterValues();
    final ParameterValue<?>[] values = parameters.values().toArray(new ParameterValue<?>[1]);
    assertEquals("parameters",    "Longitude rotation", parameters.getDescriptor().getName().getCode());
    assertEquals("parameters[0]", "Longitude offset",    values[0].getDescriptor().getName().getCode());
    assertEquals("parameters[0]", OFFSET, values[0].doubleValue(), STRICT);
    assertEquals(1, values.length);

    final Matrix3 expected = new Matrix3();
    expected.m02 = OFFSET;
    if (swapSourceAxes) {
        expected.m00 = expected.m11 = 0;
        expected.m01 = expected.m10 = 1;
    }
    assertMatrixEquals("Longitude rotation of a two-dimensional CRS", expected,
            MathTransforms.getMatrix(op.getMathTransform()), STRICT);
}
 
Example #4
Source File: UnmodifiableParameterValueGroup.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new unmodifiable parameter group.
 *
 * @param group  the group of values to copy.
 * @param done   an initially empty map used for protection against circular references.
 *
 * @see #create(ParameterValueGroup)
 */
private UnmodifiableParameterValueGroup(final ParameterValueGroup group, final Map<ParameterValueGroup,Boolean> done) {
    if (done.put(group, Boolean.TRUE) != null) {
        throw new IllegalArgumentException(Errors.format(Errors.Keys.CircularReference));
    }
    descriptor = group.getDescriptor();
    final List<GeneralParameterValue> values = group.values();
    final GeneralParameterValue[] array = new GeneralParameterValue[values.size()];
    for (int i=0; i<array.length; i++) {
        GeneralParameterValue value = values.get(i);
        ArgumentChecks.ensureNonNullElement("values", i, value);
        if (value instanceof ParameterValue<?>) {
            value = UnmodifiableParameterValue.create((ParameterValue<?>) value);
        } else if (value instanceof ParameterValueGroup) {
            value = new UnmodifiableParameterValueGroup((ParameterValueGroup) value, done);
        }
        array[i] = value;
    }
    this.values = UnmodifiableArrayList.wrap(array);
}
 
Example #5
Source File: TensorValues.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a matrix from this group of parameters.
 * This operation is allowed only for tensors of {@linkplain TensorParameters#rank() rank} 2.
 *
 * @return a matrix created from this group of parameters.
 */
final Matrix toMatrix() {
    final int numRow = dimensions[0].intValue();
    final int numCol = dimensions[1].intValue();
    final Matrix matrix = Matrices.createDiagonal(numRow, numCol);
    if (values != null) {
        for (int j=0; j<numRow; j++) {
            final ParameterValue<?>[] row = (ParameterValue<?>[]) values[j];
            if (row != null) {
                for (int i=0; i<numCol; i++) {
                    final ParameterValue<?> element = row[i];
                    if (element != null) {
                        matrix.setElement(j, i, element.doubleValue());
                    }
                }
            }
        }
    }
    return matrix;
}
 
Example #6
Source File: TensorValues.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Implementation of {@link #values()} which adds parameter values to the given list.
 * This method invokes itself recursively.
 */
private static void addValues(final Object[] values, final int[] actualSize, int j,
        final List<GeneralParameterValue> addTo)
{
    if (values != null) {
        final int length = Math.min(values.length, actualSize[j]);
        if (++j != actualSize.length) {
            for (int i=0; i<length; i++) {
                addValues((Object[]) values[i], actualSize, j, addTo);
            }
        } else {
            for (int i=0; i<length; i++) {
                final ParameterValue<?> parameter = (ParameterValue<?>) values[i];
                if (parameter != null && !isOmitted(parameter)) {
                    addTo.add(parameter);
                }
            }
        }
    }
}
 
Example #7
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public static RegionMap generalParameterValues2RegionParamsMap( GeneralParameterValue[] params ) {
    GridGeometry2D gg = null;
    if (params != null) {
        for( int i = 0; i < params.length; i++ ) {
            final ParameterValue< ? > param = (ParameterValue< ? >) params[i];
            final String name = param.getDescriptor().getName().getCode();
            if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString())) {
                gg = (GridGeometry2D) param.getValue();
                break;
            }
        }
    }
    if (gg == null) {
        throw new IllegalArgumentException("No gridgeometry present"); //$NON-NLS-1$
    }
    RegionMap regionParams = gridGeometry2RegionParamsMap(gg);
    return regionParams;
}
 
Example #8
Source File: ParametersTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Implementation of {@link #testValueDomain()} on a single descriptor instance.
 * This method test two paths:
 *
 * <ul>
 *   <li>The special case for {@link DefaultParameterDescriptor} instances.</li>
 *   <li>The fallback for generic cases. For that test, we wrap the descriptor in an anonymous class
 *       for hiding the fact that the descriptor is an instance of {@code DefaultParameterDescriptor}.</li>
 * </ul>
 */
private static <T extends Comparable<? super T>> void verifyValueDomain(
        final Range<T> valueDomain, final ParameterDescriptor<T> descriptor)
{
    assertEquals(valueDomain, Parameters.getValueDomain(descriptor));
    assertEquals(valueDomain, Parameters.getValueDomain(new ParameterDescriptor<T>() {
        @Override public ReferenceIdentifier      getName()          {return descriptor.getName();}
        @Override public Collection<GenericName>  getAlias()         {return descriptor.getAlias();}
        @Override public Set<ReferenceIdentifier> getIdentifiers()   {return descriptor.getIdentifiers();}
        @Override public InternationalString      getRemarks()       {return descriptor.getRemarks();}
        @Override public int                      getMinimumOccurs() {return descriptor.getMinimumOccurs();}
        @Override public int                      getMaximumOccurs() {return descriptor.getMaximumOccurs();}
        @Override public Class<T>                 getValueClass()    {return descriptor.getValueClass();}
        @Override public Set<T>                   getValidValues()   {return descriptor.getValidValues();}
        @Override public Comparable<T>            getMinimumValue()  {return descriptor.getMinimumValue();}
        @Override public Comparable<T>            getMaximumValue()  {return descriptor.getMaximumValue();}
        @Override public T                        getDefaultValue()  {return descriptor.getDefaultValue();}
        @Override public Unit<?>                  getUnit()          {return descriptor.getUnit();}
        @Override public ParameterValue<T>        createValue()      {return descriptor.createValue();}
        @Override public String                   toWKT()            {return descriptor.toWKT();}
    }));
}
 
Example #9
Source File: DefaultParameterValueGroupTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that attempts to add an invalid parameter cause an {@link InvalidParameterNameException} to be thrown.
 */
@Test
@DependsOnMethod("testValuesAdd")
public void testValuesAddWrongParameter() {
    final DefaultParameterValueGroup    group = createGroup(10);
    final List<GeneralParameterValue>  values = group.values();
    final ParameterValue<Integer> nonExistent = new DefaultParameterDescriptor<>(
            singletonMap(NAME_KEY, "Optional 5"), 0, 1, Integer.class, null, null, null).createValue();
    try {
        values.add(nonExistent);
        fail("“Optional 5” is not a parameter for this group.");
    } catch (InvalidParameterNameException e) {
        assertEquals("Optional 5", e.getParameterName());
        final String message = e.getMessage();
        assertTrue(message, message.contains("Optional 5"));
        assertTrue(message, message.contains("Test group"));
    }
}
 
Example #10
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 #11
Source File: DefaultParameterValueGroupTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@code DefaultParameterValueGroup.values().get(…)} on a group expected to be pre-filled
 * with mandatory parameters.
 */
@Test
public void testValuesGet() {
    final DefaultParameterValueGroup  group  = new DefaultParameterValueGroup(descriptor);
    final List<GeneralParameterValue> values = group.values();
    assertEquals("Initial size", 2, values.size());
    assertEquals(descriptor.descriptors().get(0).createValue(), values.get(0));
    assertEquals(descriptor.descriptors().get(1).createValue(), values.get(1));
    try {
        values.get(2);
        fail("Index 2 shall be out of bounds.");
    } catch (IndexOutOfBoundsException e) {
        assertNotNull(e.getMessage());
    }
    assertEquals(DefaultParameterDescriptorGroupTest.DEFAULT_VALUE, ((ParameterValue<?>) values.get(0)).getValue());
    assertEquals(DefaultParameterDescriptorGroupTest.DEFAULT_VALUE, ((ParameterValue<?>) values.get(1)).getValue());
}
 
Example #12
Source File: WKTUtilities.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Appends a {@linkplain ParameterValue parameter} in a {@code PARAMETER[…]} element.
 * If the supplied parameter is actually a {@linkplain ParameterValueGroup parameter group},
 * all contained parameters will be flattened in a single list.
 *
 * @param  parameter  the parameter to append to the WKT, or {@code null} if none.
 * @param  formatter  the formatter where to append the parameter.
 */
public static void append(GeneralParameterValue parameter, final Formatter formatter) {
    if (parameter instanceof ParameterValueGroup) {
        boolean first = true;
        for (final GeneralParameterValue param : ((ParameterValueGroup) parameter).values()) {
            if (first) {
                formatter.newLine();
                first = false;
            }
            append(param, formatter);
        }
    }
    if (parameter instanceof ParameterValue<?>) {
        if (!(parameter instanceof FormattableObject)) {
            parameter = new DefaultParameterValue<>((ParameterValue<?>) parameter);
        }
        formatter.append((FormattableObject) parameter);
        formatter.newLine();
    }
}
 
Example #13
Source File: UnmodifiableParameterValueTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an {@link UnmodifiableParameterValue} implementation for the given parameter
 * and asserts that we got a new instance equivalent to the original one.
 */
private static <T> DefaultParameterValue<T> assertEquivalent(final ParameterValue<T> modifiable) {
    final DefaultParameterValue<T> unmodifiable = DefaultParameterValue.unmodifiable(modifiable);
    assertNotSame("Expected a new instance.", modifiable, unmodifiable);
    assertTrue("New instance shall be equal to the original one.",
            unmodifiable.equals(modifiable, ComparisonMode.BY_CONTRACT));
    return unmodifiable;
}
 
Example #14
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 #15
Source File: GeographicToGeocentric.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of {@link #createMathTransform(MathTransformFactory, ParameterValueGroup)}
 * shared with {@link GeocentricToGeographic}.
 */
static MathTransform create(final MathTransformFactory factory, final Parameters values)
        throws FactoryException
{
    final ParameterValue<?> semiMajor = values.parameter(Constants.SEMI_MAJOR);
    final Unit<Length> unit = semiMajor.getUnit().asType(Length.class);
    return EllipsoidToCentricTransform.createGeodeticConversion(factory, semiMajor.doubleValue(),
            values.parameter(Constants.SEMI_MINOR).doubleValue(unit), unit, values.intValue(DIMENSION) >= 3,
            EllipsoidToCentricTransform.TargetType.CARTESIAN);
}
 
Example #16
Source File: EllipsoidToCentricTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a transform with the same parameters than this transform,
 * but expecting two-dimensional inputs instead than three-dimensional.
 */
final EllipsoidToCentricTransform create2D() {
    final ParameterValue<Double> p = context.getOrCreate(SEMI_MAJOR);
    final Unit<Length> unit = p.getUnit().asType(Length.class);
    return new EllipsoidToCentricTransform(p.doubleValue(),
            context.getOrCreate(SEMI_MINOR).doubleValue(unit), unit, false, getTargetType());
}
 
Example #17
Source File: TensorValues.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the parameter value in this group for the specified name.
 *
 * @param  name  the name of the parameter to search for.
 * @return the parameter value for the given name.
 * @throws ParameterNotFoundException if there is no parameter for the given name.
 */
@Override
public ParameterValue<?> parameter(String name) throws ParameterNotFoundException {
    name = CharSequences.trimWhitespaces(name);
    ArgumentChecks.ensureNonEmpty("name", name);
    IllegalArgumentException cause = null;
    int[] indices = null;
    try {
        indices = descriptors.nameToIndices(name);
    } catch (IllegalArgumentException exception) {
        cause = exception;
    }
    if (indices != null) {
        final int[] actualSize = size();
        if (TensorParameters.isInBounds(indices, actualSize)) {
            return parameter(indices, actualSize);
        }
    }
    /*
     * The given name is not a matrix (or tensor) element name.
     * Verify if the requested parameters is one of those that
     * specify the matrix/tensor size ("num_row" or "num_col").
     */
    final int rank = descriptors.rank();
    for (int i=0; i<rank; i++) {
        final ParameterDescriptor<Integer> param = descriptors.getDimensionDescriptor(i);
        if (IdentifiedObjects.isHeuristicMatchForName(param, name)) {
            return dimensions[i];
        }
    }
    throw (ParameterNotFoundException) new ParameterNotFoundException(Resources.format(
            Resources.Keys.ParameterNotFound_2, getName(), name), name).initCause(cause);
}
 
Example #18
Source File: TensorValues.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a copy of the given matrix parameters.
 * If {@code clone} is true, the new group will be a clone of the given group.
 * If {@code clone} is false, the new group will be initialized to default values.
 */
TensorValues(final TensorValues<E> other, final boolean clone) {
    super(other);
    descriptors = other.descriptors;
    dimensions = other.dimensions.clone();
    for (int i=0; i<dimensions.length; i++) {
        final ParameterValue<Integer> dim = dimensions[i];
        dimensions[i] = clone ? dim.clone() : dim.getDescriptor().createValue();
    }
    if (clone) {
        values = clone(other.values);
    }
}
 
Example #19
Source File: MapProjectionParameters.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new parameter.
 */
InverseFlattening(final ParameterValue<?> semiMajor, final ParameterValue<?> semiMinor) {
    super(DESCRIPTOR);
    this.semiMajor = semiMajor;
    this.semiMinor = semiMinor;
    invalidate();
}
 
Example #20
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 #21
Source File: ParameterMarshallingTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the given parameter value has the expected value and descriptor properties.
 *
 * @param  code        the expected EPSG code.
 * @param  name        the expected EPSG name.
 * @param  alias       the expected OGC alias.
 * @param  value       the expected value.
 * @param  unit        the expected unit of measurement for both the value and the descriptor.
 * @param  descriptor  the expected parameter descriptor associated to the parameter value.
 * @param  parameter   the parameter value to verify.
 */
private static void verifyParameter(final int code, final String name, final String alias,
        final double value, final Unit<?> unit, final GeneralParameterDescriptor descriptor,
        final GeneralParameterValue parameter)
{
    assertInstanceOf(name, ParameterValue.class, parameter);
    final ParameterValue<?> p = (ParameterValue<?>) parameter;
    final ParameterDescriptor<?> d = p.getDescriptor();
    verifyDescriptor(code, name, alias, true, d);
    assertSame  ("descriptor", descriptor,   d);
    assertEquals("value",      value,        p.doubleValue(), STRICT);
    assertEquals("unit",       unit,         p.getUnit());
    assertEquals("valueClass", Double.class, d.getValueClass());
    assertEquals("unit",       unit,         d.getUnit());
}
 
Example #22
Source File: ContextualParameters.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the parameter value of the given name.
 * Before the call to {@link #completeTransform completeTransform(…)},
 * this method can be used for setting parameter values like below:
 *
 * {@preformat java
 *   parameter("Scale factor").setValue(0.9996);   // Scale factor of Universal Transverse Mercator (UTM) projections.
 * }
 *
 * After the call to {@code completeTransform(…)}, the returned parameters are read-only.
 *
 * @param  name  the name of the parameter to search.
 * @return the parameter value for the given name.
 * @throws ParameterNotFoundException if there is no parameter of the given name.
 */
@Override
public synchronized ParameterValue<?> parameter(final String name) throws ParameterNotFoundException {
    final GeneralParameterDescriptor desc = descriptor.descriptor(name);
    if (!(desc instanceof ParameterDescriptor<?>)) {
        throw parameterNotFound(name);
    }
    /*
     * Search for existing parameter instance. This implementation does not scale, but should be okay since
     * the amount of parameters is typically very small (rarely more than 6 parameters in map projections).
     */
    for (int i=0; i < values.length; i++) {
        ParameterValue<?> p = values[i];
        if (p == null) {
            values[i] = p = new ContextualParameter<>((ParameterDescriptor<?>) desc);
            return p;
        }
        if (p.getDescriptor() == desc) {                    // Identity comparison should be okay here.
            return p;
        }
    }
    /*
     * We may reach this point if map projection construction is completed (i.e. 'completeTransform(…)' has
     * been invoked) and the user asks for a parameter which is not one of the parameters that we retained.
     * Returns a parameter initialized to the default value, which is the actual value (otherwise we would
     * have stored that parameter).  Note: we do not bother making the parameter immutable for performance
     * reason. If the user invokes a setter method on the returned parameter, he may get a false impression
     * that this ContextualParameters is still modifiable. We presume that such scenario would be rare.
     */
    if (isFrozen) {
        return ((ParameterDescriptor<?>) desc).createValue();
    }
    /*
     * Should never reach this point. If it happen anyway, this means that the descriptor now accepts
     * more parameters than what it declared at ContextualParameteres construction time, or that some
     * ParameterDescriptor instances changed.
     */
    throw new ParameterNotFoundException(Errors.format(Errors.Keys.UnexpectedChange_1, descriptor.getName()), name);
}
 
Example #23
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 #24
Source File: ContextualParametersTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link ContextualParameters#parameter(String)} and {@link ContextualParameters#values()}.
 */
@Test
public void testParameters() {
    final ContextualParameters p = create(1, 1);
    assertTrue("values().isEmpty()",       p.values().isEmpty());
    assertTrue("normalize.isIdentity()",   p.getMatrix(ContextualParameters.MatrixRole.NORMALIZATION).isIdentity());
    assertTrue("denormalize.isIdentity()", p.getMatrix(ContextualParameters.MatrixRole.DENORMALIZATION).isIdentity());
    assertTrue("normalize.isIdentity()",   p.getMatrix(ContextualParameters.MatrixRole.INVERSE_NORMALIZATION).isIdentity());
    assertTrue("denormalize.isIdentity()", p.getMatrix(ContextualParameters.MatrixRole.INVERSE_DENORMALIZATION).isIdentity());

    final ParameterValue<?> p1 = p.parameter("Mandatory 1");
    final ParameterValue<?> p2 = p.parameter("Mandatory 2");
    try {
        p.parameter("Mandatory 3");
        fail("Shall not find a non-existent parameter.");
    } catch (ParameterNotFoundException e) {
        // This is the expected exception.
        final String message = e.getMessage();
        assertTrue(message, message.contains("Mandatory 3"));
    }

    assertNotSame(p1, p2);
    assertSame(p1, p.parameter("Mandatory 1"));
    assertSame(p2, p.parameter("Mandatory 2"));
    assertEquals("values().size()", 2, p.values().size());
    assertArrayEquals("values.toArray()", new ParameterValue<?>[] {p1, p2}, p.values().toArray());
}
 
Example #25
Source File: DefaultTransformationTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that at least some of the properties of the given {@code op} instance have the expected values
 * for an instance created by {@link #createGeocentricTranslation()}.
 */
@SuppressWarnings("SuspiciousToArrayCall")
private static void verifyProperties(final DefaultTransformation op) {
    assertEquals("name",       "Tokyo to JGD2000 (GSI)",  op.getName().getCode());
    assertEquals("sourceCRS",  "Tokyo 1918",              op.getSourceCRS().getName().getCode());
    assertEquals("targetCRS",  "JGD2000",                 op.getTargetCRS().getName().getCode());
    assertEquals("method",     "Geocentric translations", op.getMethod().getName().getCode());
    assertEquals("parameters", "Geocentric translations", op.getParameterDescriptors().getName().getCode());

    final ParameterValueGroup parameters = op.getParameterValues();
    final ParameterValue<?>[] values = parameters.values().toArray(new ParameterValue<?>[3]);
    assertEquals("parameters",    "Geocentric translations", parameters.getDescriptor().getName().getCode());
    assertEquals("parameters[0]", "X-axis translation",      values[0] .getDescriptor().getName().getCode());
    assertEquals("parameters[1]", "Y-axis translation",      values[1] .getDescriptor().getName().getCode());
    assertEquals("parameters[2]", "Z-axis translation",      values[2] .getDescriptor().getName().getCode());
    assertEquals("parameters[0]", -146.414, values[0].doubleValue(), STRICT);
    assertEquals("parameters[1]",  507.337, values[1].doubleValue(), STRICT);
    assertEquals("parameters[2]",  680.507, values[2].doubleValue(), STRICT);
    assertEquals(3, values.length);

    final Matrix m = MathTransforms.getMatrix(op.getMathTransform());
    assertNotNull("transform", m);
    for (int j=m.getNumRow(); --j >= 0;) {
        for (int i=m.getNumCol(); --i >= 0;) {
            double expected = (i == j) ? 1 : 0;
            if (i == 2) switch (j) {
                case 0: expected = -146.414; break;
                case 1: expected =  507.337; break;
                case 2: expected =  680.507; break;
            }
            assertEquals(expected, m.getElement(j,i), STRICT);
        }
    }
}
 
Example #26
Source File: SingleOperationMarshallingTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests unmarshalling of a defining conversion.
 *
 * @throws JAXBException if an error occurred during marshalling or unmarshalling.
 */
@Test
@DependsOnMethod("testOperationMethod")
public void testConversionUnmarshalling() throws JAXBException {
    final DefaultConversion c = unmarshalFile(DefaultConversion.class, "Conversion.xml");
    assertEquals("name", "World Mercator", c.getName().getCode());
    assertEquals("identifier", "3395", getSingleton(c.getIdentifiers()).getCode());
    assertEquals("scope", "Very small scale mapping.", String.valueOf(c.getScope()));
    assertNull  ("operationVersion", c.getOperationVersion());

    final GeographicBoundingBox e = (GeographicBoundingBox) getSingleton(c.getDomainOfValidity().getGeographicElements());
    assertEquals("eastBoundLongitude", +180, e.getEastBoundLongitude(), STRICT);
    assertEquals("westBoundLongitude", -180, e.getWestBoundLongitude(), STRICT);
    assertEquals("northBoundLatitude",   84, e.getNorthBoundLatitude(), STRICT);
    assertEquals("southBoundLatitude",  -80, e.getSouthBoundLatitude(), STRICT);

    // This is a defining conversion, so we do not expect CRS.
    assertNull("sourceCRS",        c.getSourceCRS());
    assertNull("targetCRS",        c.getTargetCRS());
    assertNull("interpolationCRS", c.getInterpolationCRS());
    assertNull("mathTransform",    c.getMathTransform());

    // The most difficult part.
    final OperationMethod method = c.getMethod();
    assertNotNull("method", method);
    verifyMethod(method);

    final ParameterValueGroup parameters = c.getParameterValues();
    assertNotNull("parameters", parameters);
    final Iterator<GeneralParameterValue> it = parameters.values().iterator();
    verifyParameter(method, parameters,  -0.0, (ParameterValue<?>) it.next());
    verifyParameter(method, parameters, -90.0, (ParameterValue<?>) it.next());
    assertFalse("Unexpected parameter.", it.hasNext());

    Validators.validate(c);
}
 
Example #27
Source File: SingleOperationMarshallingTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verify a parameter value. The descriptor is expected to be the same instance than the descriptors
 * defined in the {@link ParameterValueGroup} and in the {@link OperationMethod}.
 *
 * @param  method         the method of the enclosing operation.
 * @param  group          the group which contain the given parameter.
 * @param  expectedValue  the expected parameter value.
 * @param  parameter      the parameter to verify.
 */
private static void verifyParameter(final OperationMethod method, final ParameterValueGroup group,
        final double expectedValue, final ParameterValue<?> parameter)
{
    final ParameterDescriptor<?> descriptor = parameter.getDescriptor();
    final String name = descriptor.getName().getCode();
    assertSame("parameterValues.descriptor", descriptor,  group.getDescriptor().descriptor(name));
    assertSame("method.descriptor",          descriptor, method.getParameters().descriptor(name));
    assertEquals("value", expectedValue, parameter.doubleValue(), STRICT);
}
 
Example #28
Source File: GeodeticObjectParserTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the parsing of a projected CRS using angular values in grads instead than degrees
 * and in lengths in kilometres instead than metres.
 *
 * @throws ParseException if the parsing failed.
 */
@Test
@DependsOnMethod({"testGeographicWithParisMeridian", "testProjectedCRS"})
public void testProjectedWithGradUnits() throws ParseException {
    String wkt = "PROJCS[“NTF (Paris) / Lambert zone II”," +
                 "  GEOGCS[“NTF (Paris)”," +
                 "    DATUM[“Nouvelle Triangulation Française (Paris)”," +
                 "      SPHEROID[“Clarke 1880 (IGN)”, 6378249.2, 293.4660212936269]," +
                 "      TOWGS84[-168,-60,320,0,0,0,0]]," +
                 "    PRIMEM[“Paris”, 2.5969213, AUTHORITY[“EPSG”, “8903”]]," +     // In grads.
                 "    UNIT[“grad”, 0.01570796326794897]]," +
                 "  PROJECTION[“Lambert Conformal Conic (1SP)”]," +  // Intentional swapping of "Conformal" and "Conic".
                 "  PARAMETER[“latitude_of_origin”, 52.0]," +        // In grads.
                 "  PARAMETER[“scale_factor”, 0.99987742]," +
                 "  PARAMETER[“false_easting”, 600.0]," +
                 "  PARAMETER[“false_northing”, 2200.0]," +
                 "  UNIT[“km”,1000]]";

    validateParisFranceII(parse(ProjectedCRS.class, wkt), 0, true);
    /*
     * Parse again using Convention.WKT1_COMMON_UNITS and ignoring AXIS[…] elements.
     * See the comment in 'testGeographicWithParisMeridian' method for a discussion.
     * The new aspect tested by this method is that the unit should be ignored
     * for the parameters in addition to the prime meridian.
     */
    wkt = wkt.replace("2.5969213", "2.33722917");       // Convert unit in prime meridian.
    wkt = wkt.replace("52.0",      "46.8");             // Convert unit in “latitude_of_origin” parameter.
    wkt = wkt.replace("600.0",     "600000");           // Convert unit in “false_easting” parameter.
    wkt = wkt.replace("2200.0",    "2200000");          // Convert unit in “false_northing” parameter.
    newParser(Convention.WKT1_IGNORE_AXES);
    final ProjectedCRS crs = parse(ProjectedCRS.class, wkt);
    assertNameAndIdentifierEqual("NTF (Paris) / Lambert zone II", 0, crs);
    verifyProjectedCS(crs.getCoordinateSystem(), Units.KILOMETRE);
    final PrimeMeridian pm = verifyNTF(crs.getDatum(), true);
    assertEquals("angularUnit", Units.DEGREE, pm.getAngularUnit());
    assertEquals("greenwichLongitude", 2.33722917, pm.getGreenwichLongitude(), STRICT);
    final ParameterValue<?> param = verifyNTF(crs.getConversionFromBase().getParameterValues());
    assertEquals("angularUnit", Units.DEGREE, param.getUnit());
    assertEquals("latitude_of_origin",  46.8, param.doubleValue(), STRICT);
}
 
Example #29
Source File: GeodeticObjectParserTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the parameters of a “NTF (Paris) / Lambert zone II” projection.
 */
private static void validateParisFranceII(final ProjectedCRS crs, final int identifier, final boolean hasToWGS84) {
    assertNameAndIdentifierEqual("NTF (Paris) / Lambert zone II", identifier, crs);
    verifyProjectedCS(crs.getCoordinateSystem(), Units.KILOMETRE);
    final PrimeMeridian pm = verifyNTF(crs.getDatum(), hasToWGS84);
    assertEquals("angularUnit", Units.GRAD, pm.getAngularUnit());
    assertEquals("greenwichLongitude", 2.5969213, pm.getGreenwichLongitude(), STRICT);
    final ParameterValue<?> param = verifyNTF(crs.getConversionFromBase().getParameterValues());
    assertEquals("angularUnit", Units.GRAD, param.getUnit());
    assertEquals("latitude_of_origin",  52.0, param.doubleValue(), STRICT);
}
 
Example #30
Source File: GeodeticObjectParserTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the parameter values for a projected CRS which is expected to be “NTF (Paris) / Lambert zone II”.
 * This is used by the methods in this class which test a CRS using less frequently used units and prime meridian.
 *
 * @return the latitude of origin, to be verified by the caller because the unit of measurement depends on the test.
 */
private static ParameterValue<?> verifyNTF(final ParameterValueGroup param) {
    assertEquals("Lambert Conic Conformal (1SP)", param.getDescriptor().getName().getCode());
    assertEquals("semi_major",     6378249.2, param.parameter("semi_major"      ).doubleValue(Units.METRE),  STRICT);
    assertEquals("semi_minor",     6356515.0, param.parameter("semi_minor"      ).doubleValue(Units.METRE),  1E-12);
    assertEquals("central_meridian",     0.0, param.parameter("central_meridian").doubleValue(Units.DEGREE), STRICT);
    assertEquals("scale_factor",  0.99987742, param.parameter("scale_factor"    ).doubleValue(Units.UNITY),    STRICT);
    assertEquals("false_easting",   600000.0, param.parameter("false_easting"   ).doubleValue(Units.METRE),  STRICT);
    assertEquals("false_northing", 2200000.0, param.parameter("false_northing"  ).doubleValue(Units.METRE),  STRICT);
    return param.parameter("latitude_of_origin");
}