public void Test(string sourceResourceName, string targetResourceName, double projectDelta, double unprojectDelta)
        {
            var sourceData = GoldData.GetReadyReader(sourceResourceName);
            var targetData = GoldData.GetReadyReader(targetResourceName);
            var sourceCrs = GoldData.GetCrs(sourceData);
            var targetCrs = GoldData.GetCrs(targetData);

            Assert.IsNotNull(sourceCrs);
            Assert.IsNotNull(targetCrs);

            var operationGenerator = new HelmertCrsCoordinateOperationPathGenerator();
            var operationPath = operationGenerator.Generate(sourceCrs, targetCrs).First();
            Assert.IsNotNull(operationPath);
            var compiler = new StaticCoordinateOperationCompiler();
            var forward = new CompiledConcatenatedTransformation<GeographicCoordinate, Point2>(compiler.Compile(operationPath) as IEnumerable<ITransformation>);
            var inverse = forward.GetInverse();

            while (sourceData.Read() && targetData.Read()) {
                var geogreaphicExpected = sourceData.CurrentLatLon();
                var projectedExpected = targetData.CurrentPoint2D();

                var projected = forward.TransformValue(geogreaphicExpected);
                Assert.AreEqual(projectedExpected.X, projected.X, projectDelta);
                Assert.AreEqual(projectedExpected.Y, projected.Y, projectDelta);

                var geographic = inverse.TransformValue(projectedExpected);
                Assert.AreEqual(geogreaphicExpected.Latitude, geographic.Latitude, unprojectDelta);
                Assert.AreEqual(geogreaphicExpected.Longitude, geographic.Longitude, unprojectDelta);
            }
        }
 public StaticCoordinateOperationCompiler.StepCompilationResult Compile(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
 {
     if(stepParameters == null) throw new ArgumentNullException("stepParameters");
     Contract.EndContractBlock();
     return CompileInverse(stepParameters)
         ?? CompileForwards(stepParameters);
 }
        public void epsg3140_to_wgs()
        {
            var crs = EpsgMicroDatabase.Default.GetCrs(3140);
            var wgs = EpsgMicroDatabase.Default.GetCrs(4326);

            // source for coordinates is http://epsg.io/3140/map
            var ptWgs = new GeographicCoordinate(-17.785, 177.97);
            var pt3140 = new Point2(530138.52663372, 821498.68898981); // units in links

            var gen = new EpsgCrsCoordinateOperationPathGenerator();
            var paths = gen.Generate(wgs, crs);
            var compiler = new StaticCoordinateOperationCompiler();
            var txs = paths
                .Select(p => compiler.Compile(p))
                .Where(p => p != null);

            var forward = txs.Single();
            var actualForward = (Point2)forward.TransformValue(ptWgs);
            Assert.AreEqual(pt3140.X, actualForward.X, 30);
            Assert.AreEqual(pt3140.Y, actualForward.Y, 30);

            var reverse = forward.GetInverse();
            var actualReverse = (GeographicCoordinate)reverse.TransformValue(pt3140);
            Assert.AreEqual(ptWgs.Longitude, actualReverse.Longitude, 0.01);
            Assert.AreEqual(ptWgs.Latitude, actualReverse.Latitude, 0.01);
        }
Example #4
0
        private static StaticCoordinateOperationCompiler.StepCompilationResult CreateHelmertStep(TransformationCompilationParams opData, Helmert7Transformation helmert)
        {
            Contract.Requires(opData != null);
            Contract.Requires(helmert != null);
            if (opData.StepParams.RelatedInputCrs is ICrsGeocentric && opData.StepParams.RelatedOutputCrs is ICrsGeocentric)
            {
                return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                           opData.StepParams,
                           opData.StepParams.RelatedOutputCrsUnit ?? opData.StepParams.RelatedInputCrsUnit ?? opData.StepParams.InputUnit,
                           helmert));
            }

            var spheroidFrom = ExtractSpheroid(opData.StepParams.RelatedInputCrs) ?? ExtractSpheroid(opData.StepParams.RelatedOutputCrs);

            if (null == spheroidFrom)
            {
                return(null);
            }

            var spheroidTo = ExtractSpheroid(opData.StepParams.RelatedOutputCrs) ?? spheroidFrom;

            ITransformation transformation = new GeocentricTransformationGeographicWrapper(spheroidFrom, spheroidTo, helmert);
            var             unitConversion = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(opData.StepParams.InputUnit, OgcAngularUnit.DefaultRadians);

            if (null != unitConversion)
            {
                transformation = new ConcatenatedTransformation(new[] { unitConversion, transformation });
            }

            return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                       opData.StepParams,
                       OgcAngularUnit.DefaultRadians,
                       transformation));
        }
Example #5
0
        private static StaticCoordinateOperationCompiler.StepCompilationResult CreateGeographicTopocentric(TransformationCompilationParams opData)
        {
            Contract.Requires(opData != null);
            var outputUnit = opData.StepParams.RelatedOutputCrsUnit;

            if (null == outputUnit)
            {
                return(null);
            }

            var latParam = new KeywordNamedParameterSelector("LAT");
            var lonParam = new KeywordNamedParameterSelector("LON");
            var hParam   = new KeywordNamedParameterSelector("H");

            opData.ParameterLookup.Assign(latParam, lonParam, hParam);

            GeographicHeightCoordinate origin;

            if (!TryCreateGeographicHeightCoordinate(latParam.Selection, lonParam.Selection, hParam.Selection, OgcAngularUnit.DefaultRadians, opData.StepParams.RelatedOutputCrsUnit, out origin))
            {
                origin = GeographicHeightCoordinate.Zero;
            }

            var spheroidIn = opData.StepParams.ConvertRelatedInputSpheroidUnit(outputUnit);

            if (null == spheroidIn)
            {
                return(null);
            }

            var spheroidOut = opData.StepParams.ConvertRelatedOutputSpheroidUnit(outputUnit);

            if (null == spheroidOut)
            {
                return(null);
            }

            var geographicGeocentric = new GeographicGeocentricTransformation(spheroidIn);
            var topocentricOrigin    = geographicGeocentric.TransformValue(origin);

            var transformations = new List <ITransformation>()
            {
                geographicGeocentric,
                new GeocentricTopocentricTransformation(topocentricOrigin, spheroidOut)
            };

            var inputUnitConversion = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(opData.StepParams.InputUnit, OgcAngularUnit.DefaultRadians);

            if (null != inputUnitConversion)
            {
                transformations.Insert(0, inputUnitConversion);
            }

            return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                       opData.StepParams,
                       outputUnit,
                       new ConcatenatedTransformation(transformations)
                       ));
        }
Example #6
0
        private static StaticCoordinateOperationCompiler.StepCompilationResult CreateGeocentricTranslation(TransformationCompilationParams opData)
        {
            Contract.Requires(opData != null);
            var xParam = new KeywordNamedParameterSelector("XAXIS", "X");
            var yParam = new KeywordNamedParameterSelector("YAXIS", "Y");
            var zParam = new KeywordNamedParameterSelector("ZAXIS", "Z");

            opData.ParameterLookup.Assign(xParam, yParam, zParam);

            Vector3 delta;

            if (!TryCreateVector3(xParam.Selection, yParam.Selection, zParam.Selection, out delta))
            {
                return(null);
            }

            if (opData.StepParams.RelatedInputCrs is ICrsGeocentric && opData.StepParams.RelatedOutputCrs is ICrsGeocentric)
            {
                // assume the units are correct
                return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                           opData.StepParams,
                           opData.StepParams.RelatedOutputCrsUnit ?? opData.StepParams.RelatedInputCrsUnit ?? opData.StepParams.InputUnit,
                           new GeocentricTranslation(delta)));
            }

            // TODO: need to handle unit here
            var inputSpheroid = opData.StepParams.RelatedInputSpheroid;

            if (null == inputSpheroid)
            {
                return(null);
            }

            // TODO: may even need to convert units while translating

            // TODO: need to handle unit here
            var outputSpheroid = opData.StepParams.RelatedOutputSpheroid;

            if (null == outputSpheroid)
            {
                return(null);
            }

            ITransformation transformation = new GeographicGeocentricTranslation(inputSpheroid, delta, outputSpheroid);
            var             conv           = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(opData.StepParams.InputUnit, OgcAngularUnit.DefaultRadians);

            if (null != conv)
            {
                transformation = new ConcatenatedTransformation(new[] { conv, transformation });
            }
            return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                       opData.StepParams,
                       OgcAngularUnit.DefaultRadians,
                       transformation));
        }
Example #7
0
        private StaticCoordinateOperationCompiler.StepCompilationResult CompileInverse(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
        {
            Contract.Requires(stepParameters != null);
            if (!stepParameters.CoordinateOperationInfo.IsInverseOfDefinition || !stepParameters.CoordinateOperationInfo.HasInverse)
            {
                return(null);
            }

            var inverseOperationInfo = stepParameters.CoordinateOperationInfo.GetInverse();

            if (null == inverseOperationInfo)
            {
                return(null);
            }

            var expectedOutputUnits = stepParameters.RelatedOutputCrsUnit
                                      ?? stepParameters.RelatedInputCrsUnit
                                      ?? stepParameters.InputUnit;

            var forwardCompiledStep = CompileForwardToTransform(new StaticCoordinateOperationCompiler.StepCompilationParameters(
                                                                    inverseOperationInfo,
                                                                    expectedOutputUnits,
                                                                    stepParameters.RelatedOutputCrs,
                                                                    stepParameters.RelatedInputCrs
                                                                    ));

            if (null == forwardCompiledStep)
            {
                return(null);
            }

            var forwardCompiledOperation = forwardCompiledStep.Transformation;

            if (!forwardCompiledOperation.HasInverse)
            {
                return(null);
            }

            var inverseCompiledOperation = forwardCompiledOperation.GetInverse();
            var resultTransformation     = inverseCompiledOperation;

            // make sure that the input units are correct
            var unitConversion = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(stepParameters.InputUnit, forwardCompiledStep.OutputUnit);

            if (null != unitConversion)
            {
                resultTransformation = new ConcatenatedTransformation(new[] { unitConversion, resultTransformation });
            }

            return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                       stepParameters,
                       expectedOutputUnits,
                       resultTransformation
                       ));
        }
Example #8
0
 public TestRunner()
 {
     _epsgPathGenerator = new EpsgCrsCoordinateOperationPathGenerator();
     _epsgPathGenerator.CrsFilters = new List<Predicate<EpsgCrs>> {
         IsNotDeprecated
     };
     _epsgPathGenerator.OpFilters = new List<Predicate<ICoordinateOperationInfo>>{
         IsNotDeprecated,
         IsNotRestricted
     };
     _coordinateOperationCompiler = new StaticCoordinateOperationCompiler();
 }
Example #9
0
        private static StaticCoordinateOperationCompiler.StepCompilationResult CreateTunisiaMiningGrid(TransformationCompilationParams opData)
        {
            Contract.Requires(opData != null);
            ITransformation transformation = new TunisiaMiningGrid();
            var             conv           = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(opData.StepParams.InputUnit, OgcAngularUnit.DefaultGrads);

            if (null != conv)
            {
                transformation = new ConcatenatedTransformation(new[] { conv, transformation });
            }

            return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                       opData.StepParams,
                       OgcLinearUnit.DefaultKilometer,
                       transformation));
        }
Example #10
0
        private static StaticCoordinateOperationCompiler.StepCompilationResult CreateMadridToEd50Polynomial(TransformationCompilationParams opData)
        {
            Contract.Requires(opData != null);
            var a0Param  = new FullMatchParameterSelector("A0");
            var a1Param  = new FullMatchParameterSelector("A1");
            var a2Param  = new FullMatchParameterSelector("A2");
            var a3Param  = new FullMatchParameterSelector("A3");
            var b00Param = new FullMatchParameterSelector("B00");
            var b0Param  = new FullMatchParameterSelector("B0");
            var b1Param  = new FullMatchParameterSelector("B1");
            var b2Param  = new FullMatchParameterSelector("B2");
            var b3Param  = new FullMatchParameterSelector("B3");

            opData.ParameterLookup.Assign(a0Param, a1Param, a2Param, a3Param, b00Param, b0Param, b1Param, b2Param, b3Param);

            double a0, a1, a2, a3, b00, b0, b1, b2, b3;

            TryGetCoefficientValue(a0Param.Selection, out a0);
            TryGetCoefficientValue(a1Param.Selection, out a1);
            TryGetCoefficientValue(a2Param.Selection, out a2);
            TryGetCoefficientValue(a3Param.Selection, out a3);
            TryGetCoefficientValue(b00Param.Selection, out b00);
            TryGetCoefficientValue(b0Param.Selection, out b0);
            TryGetCoefficientValue(b1Param.Selection, out b1);
            TryGetCoefficientValue(b2Param.Selection, out b2);
            TryGetCoefficientValue(b3Param.Selection, out b3);

            ITransformation transformation = new MadridEd50Polynomial(a0, a1, a2, a3, b00, b0, b1, b2, b3);

            var conv = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(opData.StepParams.InputUnit, OgcAngularUnit.DefaultDegrees);

            if (null != conv)
            {
                transformation = new ConcatenatedTransformation(new[] { conv, transformation });
            }

            return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                       opData.StepParams,
                       OgcAngularUnit.DefaultDegrees,
                       transformation));
        }
        public void epsg3079_to_epsg3575()
        {
            var from = EpsgMicroDatabase.Default.GetCrs(3079);
            var to = EpsgMicroDatabase.Default.GetCrs(3575);
            var wgs = EpsgMicroDatabase.Default.GetCrs(4326);

            var somePlaceInMichigan = new GeographicCoordinate(40.4, -91.8);
            var expected3079 = new Point2(6992.885640195105, -644.956855237484);
            var expected3575 = new Point2(-5244224.354585549, 1095575.5476152631);

            var gen = new EpsgCrsCoordinateOperationPathGenerator();
            var fromPath = gen.Generate(from, wgs).First();
            var toPath = gen.Generate(to, wgs).First();

            var compiler = new StaticCoordinateOperationCompiler();

            var fromTx = compiler.Compile(fromPath);
            var toTx = compiler.Compile(toPath);

            var a = (GeographicCoordinate)fromTx.TransformValue(expected3079);
            Assert.AreEqual(somePlaceInMichigan.Latitude, a.Latitude, 0.01);
            Assert.AreEqual(somePlaceInMichigan.Longitude, a.Longitude, 0.01);
            var b = (Point2)fromTx.GetInverse().TransformValue(somePlaceInMichigan);
            Assert.AreEqual(expected3079.X, b.X, 0.01);
            Assert.AreEqual(expected3079.Y, b.Y, 0.01);
            var d = (Point2)toTx.GetInverse().TransformValue(somePlaceInMichigan);
            Assert.AreEqual(expected3575.X, d.X, 0.01);
            Assert.AreEqual(expected3575.Y, d.Y, 0.01);
            var c = (GeographicCoordinate)toTx.TransformValue(expected3575);
            Assert.AreEqual(somePlaceInMichigan.Latitude, c.Latitude, 0.01);
            Assert.AreEqual(somePlaceInMichigan.Longitude, c.Longitude, 0.01);

            var allTotalPaths = gen.Generate(from, to).ToList();
            var totalPath = allTotalPaths.First();
            var totalTx = compiler.Compile(totalPath);
            var actual3575 = (Point2)totalTx.TransformValue(expected3079);

            Assert.AreEqual(expected3575.X, actual3575.X, 1);
            Assert.AreEqual(expected3575.Y, actual3575.Y, 1);
        }
        private StaticCoordinateOperationCompiler.StepCompilationResult CompileForwards(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
        {
            Contract.Requires(stepParameters != null);
            var forwardCompiledOperation = CompileForwardToTransform(stepParameters);
            if (null == forwardCompiledOperation)
                return null;

            ITransformation resultTransformation = forwardCompiledOperation;

            // make sure that the input units are correct
            var actualInputUnits = stepParameters.InputUnit;
            var desiredInputUnits = OgcAngularUnit.DefaultRadians;
            if (null != desiredInputUnits && !UnitEqualityComparer.Default.Equals(actualInputUnits, desiredInputUnits)) {
                var conv = SimpleUnitConversionGenerator.FindConversion(actualInputUnits, desiredInputUnits);
                if (null != conv) {
                    var conversionTransformation = new AngularElementTransformation(conv);
                    resultTransformation = new ConcatenatedTransformation(new[] { conversionTransformation, resultTransformation });
                }
            }

            var outputUnits = stepParameters.RelatedOutputCrsUnit ?? stepParameters.RelatedInputCrsUnit ?? OgcLinearUnit.DefaultMeter;

            return new StaticCoordinateOperationCompiler.StepCompilationResult(
                stepParameters,
                outputUnits,
                resultTransformation
            );
        }
Example #13
0
        private ConversionResult ExecuteStaticEpsg(TestCase testCase)
        {
            var result = new ConversionResult();
            try {

                var paths = _epsgPathGenerator.Generate(testCase.Source, testCase.Target)
                    .OrderBy(x => GetEpsgAccuracy(x) ?? 999);

                var compiler = new StaticCoordinateOperationCompiler();
                var compiledPaths = paths
                    .Select(x => compiler.Compile(x));

                var bestCompiledPath = compiledPaths.FirstOrDefault(x => x != null);

                var transformation = bestCompiledPath;
                if (transformation == null)
                    throw new InvalidOperationException("No compiled transformation");

                result.ResultData = transformation.TransformValues(testCase.InputCoordinates).ToArray();
            }
            catch (Exception ex) {
                result.Exception = ex;
            }

            return result;
        }
        public void epsg3857_to_wgs()
        {
            var crs = EpsgMicroDatabase.Default.GetCrs(3857);
            var wgs = EpsgMicroDatabase.Default.GetCrs(4326);

            var ptWgs = new GeographicCoordinate(45,10);
            var pt3857 = new Point2(1113194, 5621521);

            var gen = new EpsgCrsCoordinateOperationPathGenerator();
            var paths = gen.Generate(wgs, crs);
            var compiler = new StaticCoordinateOperationCompiler();
            var txs = paths.Select(p => compiler.Compile(p)).Where(p => p != null);

            var forward = txs.Single();

            var actualZeroMeters = (Point2)forward.TransformValue(GeographicCoordinate.Zero);
            Assert.AreEqual(0, actualZeroMeters.X);
            Assert.AreEqual(0, actualZeroMeters.Y, 0.0000001);

            var actualForward = (Point2)forward.TransformValue(ptWgs);
            Assert.AreEqual(pt3857.X, actualForward.X, 30);
            Assert.AreEqual(pt3857.Y, actualForward.Y, 30);

            var reverse = forward.GetInverse();

            var actualZeroDegrees = (GeographicCoordinate)reverse.TransformValue(Point2.Zero);
            Assert.AreEqual(0, actualZeroDegrees.Longitude);
            Assert.AreEqual(0, actualZeroDegrees.Latitude);

            var actualReverse = (GeographicCoordinate)reverse.TransformValue(pt3857);
            Assert.AreEqual(ptWgs.Longitude, actualReverse.Longitude, 0.0001);
            Assert.AreEqual(ptWgs.Latitude, actualReverse.Latitude, 0.0001);
        }
        private StaticCoordinateOperationCompiler.StepCompilationResult CompileInverse(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
        {
            Contract.Requires(stepParameters != null);
            if (!stepParameters.CoordinateOperationInfo.IsInverseOfDefinition || !stepParameters.CoordinateOperationInfo.HasInverse)
                return null;

            var inverseOperationInfo = stepParameters.CoordinateOperationInfo.GetInverse();
            if (null == inverseOperationInfo)
                return null;

            var forwardCompiledOperation = CompileForwardToTransform(new StaticCoordinateOperationCompiler.StepCompilationParameters(
                inverseOperationInfo,
                OgcAngularUnit.DefaultRadians,
                stepParameters.RelatedOutputCrs,
                stepParameters.RelatedInputCrs
            ));

            if (null == forwardCompiledOperation || !forwardCompiledOperation.HasInverse)
                return null;

            var inverseCompiledOperation = forwardCompiledOperation.GetInverse();
            ITransformation resultTransformation = inverseCompiledOperation;

            // make sure that the input units are correct
            var actualInputUnits = stepParameters.InputUnit;
            /*var projectionSpheroid = stepParameters.RelatedInputSpheroid as ISpheroidInfo;
            var desiredInputUnits = null == projectionSpheroid
                ? stepParameters.RelatedInputCrsUnit
                : projectionSpheroid.AxisUnit;*/
            var desiredInputUnits = stepParameters.RelatedInputCrsUnit;
            if (null != desiredInputUnits && !UnitEqualityComparer.Default.Equals(actualInputUnits, desiredInputUnits)) {
                var conv = SimpleUnitConversionGenerator.FindConversion(actualInputUnits, desiredInputUnits);
                if (null != conv) {
                    var conversionTransformation = new LinearElementTransformation(conv);
                    resultTransformation = new ConcatenatedTransformation(new[] { conversionTransformation, resultTransformation });
                }
            }

            // the result units will be radians
            return new StaticCoordinateOperationCompiler.StepCompilationResult(
                stepParameters,
                OgcAngularUnit.DefaultRadians,
                resultTransformation
            );
        }
        public void epsg4326_to_5072()
        {
            var wgs = EpsgMicroDatabase.Default.GetCrs(4326);
            var nad83Albers = EpsgMicroDatabase.Default.GetCrs(5072);
            var gen = new EpsgCrsCoordinateOperationPathGenerator();
            var paths = gen.Generate(wgs, nad83Albers);
            var compiler = new StaticCoordinateOperationCompiler();
            var txs = paths.Select(p => compiler.Compile(p)).Where(p => p != null);
            var forward = txs.Single();

            var transformed = (Point2)forward.TransformValue(new GeographicCoordinate(39, -105));
            Assert.AreEqual(-771063, transformed.X, 1);
            Assert.AreEqual(1811448, transformed.Y, 1);
        }
        private StaticCoordinateOperationCompiler.StepCompilationResult CompileForwards(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
        {
            Contract.Requires(stepParameters != null);
            var forwardCompiledStep = CompileForwardToTransform(stepParameters);
            if (null == forwardCompiledStep)
                return null;

            return new StaticCoordinateOperationCompiler.StepCompilationResult(
                stepParameters,
                forwardCompiledStep.OutputUnit,
                forwardCompiledStep.Transformation
            );
        }
        public HttpResponseMessage Draw(double? minLon, double? maxLon, double? minLat, double? maxLat, int? maxImgWidth, int? maxImgHeight)
        {
            var shapefilePath = HostingEnvironment.MapPath("~/App_Data/builtupp_usa/builtupp_usa.shp");

            ITransformation<GeographicCoordinate, Point2> transformation = null;
            var targetCrs = EpsgMicroDatabase.Default.GetCrs(3005);
            LongitudeDegreeRange dataLongitudeRange;
            Range dataLatitudeRange;
            using (var shapeFile = Shapefile.Open(shapefilePath)) {
                dataLongitudeRange = new LongitudeDegreeRange(shapeFile.Extent.MinX, shapeFile.Extent.MaxX);
                dataLatitudeRange = new Range(shapeFile.Extent.MinY, shapeFile.Extent.MaxY);

                var dataCrs = EpsgMicroDatabase.Default.GetCrs(4326);
                var pathGenerator = new EpsgCrsCoordinateOperationPathGenerator();
                var paths = pathGenerator.Generate(dataCrs, targetCrs);
                var compiler = new StaticCoordinateOperationCompiler();
                var firstTransfom = paths.Select(p => {
                    return compiler.Compile(p);
                }).First(x => x != null);

                transformation = firstTransfom as ITransformation<GeographicCoordinate, Point2>;
                if (transformation == null && firstTransfom is IEnumerable<ITransformation>)
                    transformation = new CompiledConcatenatedTransformation<GeographicCoordinate, Point2>((IEnumerable<ITransformation>)firstTransfom);

            }

            var geoMbrMin = new GeographicCoordinate(minLat ?? dataLatitudeRange.Low, minLon ?? dataLongitudeRange.Start);
            var geoMbrMax = new GeographicCoordinate(maxLat ?? dataLatitudeRange.High, maxLon ?? dataLongitudeRange.End);
            var geoMbrTL = new GeographicCoordinate(geoMbrMax.Latitude, geoMbrMin.Longitude);
            var geoMbrTR = new GeographicCoordinate(geoMbrMin.Latitude, geoMbrMax.Longitude);

            var projectedMbrPoints = new[] {
                    geoMbrMin,
                    geoMbrMax,
                    geoMbrTL,
                    geoMbrTR,
                    new GeographicCoordinate(geoMbrMin.Latitude, Math.Abs(geoMbrMin.Longitude + geoMbrMax.Longitude) / 2.0)
                }
                .Select(transformation.TransformValue)
                .ToArray();

            var projectedExtent = new Mbr(
                new Point2(projectedMbrPoints.Min(x => x.X), projectedMbrPoints.Min(x => x.Y)),
                new Point2(projectedMbrPoints.Max(x => x.X), projectedMbrPoints.Max(x => x.Y))
            );

            var geogMapOrigin = new GeographicCoordinate(dataLatitudeRange.Mid, dataLongitudeRange.Mid);
            var mapOrigin = transformation.TransformValue(geogMapOrigin);

            var mapOffset = new Vector2(0/*-(mapOrigin.X - projectedExtent.X.Mid)*/, projectedExtent.Height / 2.0);

            var imageSizeLimits = new Vector2(maxImgWidth ?? 300, maxImgHeight ?? 300);
            if (imageSizeLimits.X > 4096 || imageSizeLimits.Y > 4096)
                throw new ArgumentException("Image size too large");

            var dataRatio = new Vector2(projectedExtent.Width / imageSizeLimits.X, projectedExtent.Height / imageSizeLimits.Y);
            var lowCorner = projectedExtent.Min;
            Vector2 desiredImageSize;
            double imageScaleFactor;
            if (dataRatio.Y < dataRatio.X) {
                imageScaleFactor = imageSizeLimits.X / projectedExtent.Width;
                desiredImageSize = new Vector2(imageSizeLimits.X, (int)(projectedExtent.Height * imageScaleFactor));
            }
            else {
                imageScaleFactor = imageSizeLimits.Y / projectedExtent.Height;
                desiredImageSize = new Vector2((int)(projectedExtent.Width * imageScaleFactor), imageSizeLimits.Y);
            }

            using (var image = new System.Drawing.Bitmap((int)desiredImageSize.X, (int)desiredImageSize.Y))
            using (var graphics = Graphics.FromImage(image)) {
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                var shapeSource = new PointShapefileShapeSource(shapefilePath);
                var shapeReader = new ShapeReader(shapeSource);
                using (var shapeEnumerator = shapeReader.GetEnumerator()) {
                    var sourceCoordinates = ReadPagesToGeographicCoordinate(shapeEnumerator).SelectMany(x => x);
                    var pointColor = Color.Black;
                    var circleFillBrush = new SolidBrush(Color.FromArgb(64,16,64,128));
                    var featureRadius = 3.0;
                    var featureDiameter = featureRadius * 2;
                    var featureDiameterFloat = (float)featureDiameter;
                    var topLeftOffset = new Vector2(-featureRadius,-featureRadius);

                    foreach (var transformedPoint in transformation.TransformValues(sourceCoordinates)) {
                        var offsetPoint = transformedPoint.Difference(lowCorner).Add(mapOffset);

                        var scaledPoint = offsetPoint.GetScaled(imageScaleFactor);
                        var screenPoint = new Point2(scaledPoint.X, image.Height - scaledPoint.Y);
                        var drawTopLeft = screenPoint.Add(topLeftOffset);

                        graphics.FillEllipse(circleFillBrush, (float)drawTopLeft.X, (float)drawTopLeft.Y, featureDiameterFloat, featureDiameterFloat);
                    }
                }
                var result = new HttpResponseMessage(HttpStatusCode.OK);
                byte[] imageBytes;
                using (var memoryStream = new MemoryStream()) {
                    image.Save(memoryStream, ImageFormat.Png);
                    imageBytes = memoryStream.ToArray();
                }
                result.Content = new ByteArrayContent(imageBytes);
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                return result;
            }
        }
Example #19
0
        private Helmert7Transformation ExtractHelmert7Transformation(EpsgCoordinateTransformInfo transform)
        {
            var method = transform.Method;
            Contract.Assume(method != null);

            var compiler = new StaticCoordinateOperationCompiler();
            var compileRequest = new CoordinateOperationCrsPathInfo(
                new[] { transform.SourceCrs, transform.TargetCrs },
                new[] { transform });
            var compileResult = compiler.Compile(compileRequest);
            if (compileResult == null)
                return null;
            var transformSteps = (compileResult as IEnumerable<ITransformation>) ?? ArrayUtil.CreateSingleElementArray(compileResult);
            var exposedSteps = transformSteps.Select(step => {
                if (step is GeocentricTransformationGeographicWrapper) {
                    return ((GeocentricTransformationGeographicWrapper)step).GeocentricCore;
                }
                return step;
            });

            foreach (var step in exposedSteps) {
                if (step is Helmert7Transformation) {
                    return step as Helmert7Transformation;
                }
                if (step is GeocentricTranslation) {
                    return new Helmert7Transformation(((GeocentricTranslation)step).Delta);
                }
                if (step is GeographicGeocentricTranslation) {
                    return new Helmert7Transformation(((GeographicGeocentricTranslation)step).Delta);
                }
            }

            return null;
        }
        private StaticCoordinateOperationCompiler.StepCompilationResult CompileForwardToTransform(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
        {
            Contract.Requires(stepParameters != null);
            string operationName = null;
            IEnumerable<INamedParameter> parameters = null;

            var parameterizedOperation = stepParameters.CoordinateOperationInfo as IParameterizedCoordinateOperationInfo;
            if (null != parameterizedOperation) {
                if (null != parameterizedOperation.Method)
                    operationName = parameterizedOperation.Method.Name;
                parameters = parameterizedOperation.Parameters;
            }

            if (String.IsNullOrEmpty(operationName))
                operationName = stepParameters.CoordinateOperationInfo.Name;
            if (String.IsNullOrEmpty(operationName))
                return null;

            var parameterLookup = new NamedParameterLookup(parameters ?? Enumerable.Empty<INamedParameter>());
            var compilationParams = new TransformationCompilationParams(stepParameters, parameterLookup, operationName);

            var normalizedName = _coordinateOperationNameComparer.Normalize(compilationParams.OperationName);
            if (normalizedName.StartsWith("POSITIONVECTORTRANSFORMATION"))
                return CreatePositionVectorTransformation(compilationParams);
            if (normalizedName.StartsWith("COORDINATEFRAMEROTATION"))
                return CreateCoordinateFrameRotationTransformation(compilationParams);
            if (normalizedName.StartsWith("MOLODENSKYBADEKAS"))
                return CreateMolodenskyBadekas(compilationParams);
            if (normalizedName.Equals("GEOGRAPHICOFFSET") || (normalizedName.StartsWith("GEOGRAPHIC") && normalizedName.EndsWith("OFFSET")))
                return CreateGeographicOffset(compilationParams);
            if (normalizedName.StartsWith("GEOCENTRICTRANSLATION"))
                return CreateGeocentricTranslation(compilationParams);
            if (normalizedName.Equals("VERTICALOFFSET"))
                return CreateVerticalOffset(compilationParams);
            if (normalizedName.Equals("MADRIDTOED50POLYNOMIAL"))
                return CreateMadridToEd50Polynomial(compilationParams);
            if (normalizedName.Equals("SIMILARITYTRANSFORMATION"))
                return CreateSimilarityTransformation(compilationParams);
            if (normalizedName.Equals("AFFINEPARAMETRICTRANSFORMATION"))
                return CreateAffineParametricTransformation(compilationParams);
            if (normalizedName.Equals("GEOGRAPHIC3DTO2DCONVERSION") || normalizedName.Equals("GEOGRAPHIC2DTO3DCONVERSION"))
                return CreateGeographicDimensionChange(compilationParams);
            if (normalizedName.Equals("TUNISIAMININGGRID"))
                return CreateTunisiaMiningGrid(compilationParams);
            if (normalizedName.StartsWith("GEOCENTRICTOPOCENTRIC"))
                return CreateGeocentricTopocentric(compilationParams);
            if (normalizedName.StartsWith("GEOGRAPHICTOPOCENTRIC"))
                return CreateGeographicTopocentric(compilationParams);
            if (normalizedName.StartsWith("VERTICALPERSPECTIVE")) {
                return CreateVerticalPerspective(compilationParams);
            }
            return null;
        }
Example #21
0
        private static StaticCoordinateOperationCompiler.StepCompilationResult CreateMolodenskyBadekas(TransformationCompilationParams opData)
        {
            Contract.Requires(opData != null);
            var xTransParam = new KeywordNamedParameterSelector("XAXIS", "TRANS");
            var yTransParam = new KeywordNamedParameterSelector("YAXIS", "TRANS");
            var zTransParam = new KeywordNamedParameterSelector("ZAXIS", "TRANS");
            var xRotParam   = new KeywordNamedParameterSelector("XAXIS", "ROT");
            var yRotParam   = new KeywordNamedParameterSelector("YAXIS", "ROT");
            var zRotParam   = new KeywordNamedParameterSelector("ZAXIS", "ROT");
            var scaleParam  = new KeywordNamedParameterSelector("SCALE");
            var ord1Param   = new KeywordNamedParameterSelector("ORDINATE1");
            var ord2Param   = new KeywordNamedParameterSelector("ORDINATE2");
            var ord3Param   = new KeywordNamedParameterSelector("ORDINATE3");

            if (!opData.ParameterLookup.Assign(xTransParam, yTransParam, zTransParam, xRotParam, yRotParam, zRotParam, scaleParam, ord1Param, ord2Param, ord3Param))
            {
                return(null);
            }

            Vector3 translation, rotation;
            Point3  ordinate;
            double  scale;

            if (!TryCreateVector3(xTransParam.Selection, yTransParam.Selection, zTransParam.Selection, out translation))
            {
                return(null);
            }
            if (!TryCreateVector3(xRotParam.Selection, yRotParam.Selection, zRotParam.Selection, OgcAngularUnit.DefaultRadians, out rotation))
            {
                return(null);
            }
            if (!TryCreatePoint3(ord1Param.Selection, ord2Param.Selection, ord3Param.Selection, out ordinate))
            {
                return(null);
            }
            if (!NamedParameter.TryGetDouble(scaleParam.Selection, out scale))
            {
                return(null);
            }

            var molodensky = new MolodenskyBadekasTransformation(translation, rotation, ordinate, scale);

            if (opData.StepParams.RelatedInputCrs is ICrsGeocentric && opData.StepParams.RelatedOutputCrs is ICrsGeocentric)
            {
                return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                           opData.StepParams,
                           opData.StepParams.RelatedOutputCrsUnit ?? opData.StepParams.RelatedInputCrsUnit ?? opData.StepParams.InputUnit,
                           molodensky));
            }

            // TODO: need to handle units here
            var spheroidFrom = opData.StepParams.RelatedInputSpheroid;

            if (null == spheroidFrom)
            {
                return(null);
            }

            // TODO: need to handle units here
            var spheroidTo = opData.StepParams.RelatedOutputSpheroid;

            if (null == spheroidTo)
            {
                return(null);
            }

            ITransformation transformation = new GeocentricTransformationGeographicWrapper(spheroidFrom, spheroidTo, molodensky);
            var             conv           = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(opData.StepParams.InputUnit, OgcAngularUnit.DefaultRadians);

            if (null != conv)
            {
                transformation = new ConcatenatedTransformation(new[] { conv, transformation });
            }

            return(new StaticCoordinateOperationCompiler.StepCompilationResult(
                       opData.StepParams,
                       OgcAngularUnit.DefaultRadians,
                       transformation));
        }
        private ITransformation<GeographicCoordinate, Point2> CompileForwardToTransform(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
        {
            Contract.Requires(stepParameters != null);
            string operationName = null;
            IEnumerable<INamedParameter> parameters = null;

            var parameterizedOperation = stepParameters.CoordinateOperationInfo as IParameterizedCoordinateOperationInfo;
            if (null != parameterizedOperation) {
                if (null != parameterizedOperation.Method)
                    operationName = parameterizedOperation.Method.Name;
                parameters = parameterizedOperation.Parameters;
            }

            if (null == operationName)
                operationName = stepParameters.CoordinateOperationInfo.Name;

            Func<ProjectionCompilationParams, ITransformation<GeographicCoordinate, Point2>> projectionCompiler;
            if (String.IsNullOrEmpty(operationName) || !_transformationCreatorLookup.TryGetValue(operationName, out projectionCompiler) || null == projectionCompiler)
                return null;

            var parameterLookup = new NamedParameterLookup(parameters ?? Enumerable.Empty<INamedParameter>());
            var projectionCompilationParams = new ProjectionCompilationParams(stepParameters, parameterLookup, operationName);

            return projectionCompiler(projectionCompilationParams);
        }
        private StaticCoordinateOperationCompiler.StepCompilationResult CompileInverse(StaticCoordinateOperationCompiler.StepCompilationParameters stepParameters)
        {
            Contract.Requires(stepParameters != null);
            if (!stepParameters.CoordinateOperationInfo.IsInverseOfDefinition || !stepParameters.CoordinateOperationInfo.HasInverse)
                return null;

            var inverseOperationInfo = stepParameters.CoordinateOperationInfo.GetInverse();
            if (null == inverseOperationInfo)
                return null;

            var expectedOutputUnits = stepParameters.RelatedOutputCrsUnit
                ?? stepParameters.RelatedInputCrsUnit
                ?? stepParameters.InputUnit;

            var forwardCompiledStep = CompileForwardToTransform(new StaticCoordinateOperationCompiler.StepCompilationParameters(
                inverseOperationInfo,
                expectedOutputUnits,
                stepParameters.RelatedOutputCrs,
                stepParameters.RelatedInputCrs
            ));

            if (null == forwardCompiledStep)
                return null;

            var forwardCompiledOperation = forwardCompiledStep.Transformation;
            if (!forwardCompiledOperation.HasInverse)
                return null;

            var inverseCompiledOperation = forwardCompiledOperation.GetInverse();
            var resultTransformation = inverseCompiledOperation;

            // make sure that the input units are correct
            var unitConversion = StaticCoordinateOperationCompiler.CreateCoordinateUnitConversion(stepParameters.InputUnit, forwardCompiledStep.OutputUnit);
            if (null != unitConversion)
                resultTransformation = new ConcatenatedTransformation(new[] { unitConversion, resultTransformation });

            return new StaticCoordinateOperationCompiler.StepCompilationResult(
                stepParameters,
                expectedOutputUnits,
                resultTransformation
            );
        }
 public TransformationCompilationParams(
     StaticCoordinateOperationCompiler.StepCompilationParameters stepParams,
     NamedParameterLookup parameterLookup,
     string operationName
 )
 {
     Contract.Requires(stepParams != null);
     Contract.Requires(parameterLookup != null);
     Contract.Requires(!String.IsNullOrEmpty(operationName));
     StepParams = stepParams;
     ParameterLookup = parameterLookup;
     OperationName = operationName;
 }