Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MVT Writer Geometry shift #29

Closed
megedsh opened this issue Mar 18, 2024 · 10 comments · Fixed by #30
Closed

MVT Writer Geometry shift #29

megedsh opened this issue Mar 18, 2024 · 10 comments · Fixed by #30
Assignees
Labels
bug Something isn't working

Comments

@megedsh
Copy link

megedsh commented Mar 18, 2024

Encountered an issue when writing an mvt where some of the geometries are shifted to a wrong location.
for the same geometry, higher and lower zoom display different behaviours.
In low zoom (4) the some of the polygons are not where they should be.
in high zoom (6) the issue is not reproduced.

Geometry used in test:
Italy.txt

`

    [Test]
    public void MvtWriterGeometryIssue()
    {
        writeTile(8, 6, 4);
        writeTile(34,24,6);
    }

    private static void writeTile(int x, int y, int z)
    {
        string italyTxt = getItalyText();
        Geometry geometry = new WKTReader().Read(italyTxt);
        Feature feature = new Feature(geometry, new AttributesTable(new Dictionary<string, object>()
        {
            { "id", 1 }
        }));
        Tile tileDefinition = new Tile(x, y, z);
        VectorTile vectorTile = new VectorTile { TileId = tileDefinition.Id };
        Layer layer = new Layer { Name = "layer1" };
        vectorTile.Layers.Add(layer);
        layer.Features.Add(feature);

        byte[] result;
        MemoryStream? ms;
        using (ms = new MemoryStream(1024 * 32))
        {
            vectorTile.Write(ms);
            result = ms.ToArray();
        }

        File.WriteAllBytes($"{x}_{y}_{z}.mvt", result);
    }

    private static string getItalyText() => File.ReadAllText("Italy.wkt");

Opend the tiles in QGIS, with an OSM layer in background to see the shift.

Original geometry:
2024-03-18_11h00_48

Tile x=8,y=6,z=4

2024-03-18_11h24_14

Tile x=34,y=24,z=6

2024-03-18_11h29_28

FObermaier added a commit that referenced this issue Mar 18, 2024
Add provided unit test slightly modified

refers to #29
@FObermaier FObermaier self-assigned this Mar 18, 2024
@FObermaier FObermaier added the bug Something isn't working label Mar 18, 2024
@FObermaier
Copy link
Member

FObermaier commented Mar 18, 2024

The parts of the input polygon are not sorted by their area (descending). This might cause the MapBoxTileWriter to encode CoordinateSequences and later decide not to write them. At that point, the current x- and y- ordinates have already been updated so the next starting point of a sequence that is actually written is incorrect.

Could you verify that 8_6_4.zip is what you expect.

@megedsh
Copy link
Author

megedsh commented Mar 18, 2024

I think it looks good..
I need to do some more testing..
Thanks !!

2024-03-18_18h17_35

@megedsh
Copy link
Author

megedsh commented Mar 18, 2024

so sorting the polygons by area will solve this without a fix ?
the source is a shp file that I also read with your lib, so I guess I can recreate the topology with sorting.

@FObermaier
Copy link
Member

so sorting the polygons by area will solve this without a fix ?

I suppose so. Geometry.Normalize() should do.

@megedsh
Copy link
Author

megedsh commented Mar 18, 2024

Sorry, Geometry.Normalize() dosent seem to work..

@FObermaier
Copy link
Member

Sorry for the misleading suggestion. Geometry.Normalize does not sort items in a MultiPolygon by their area. Sorting does not help either, because the issue here arises from the interior ring that excludes San Marino.

I'll improve the fix.

@megedsh
Copy link
Author

megedsh commented Mar 19, 2024

Thanks, Ill take the branch later and test it.
maybe ill create a better unit test by reading the tile and than compare the geometries

@megedsh
Copy link
Author

megedsh commented Mar 19, 2024

Tested with the branch.. looks good on several zoom levels
2024-03-19_11h36_29

I wrote a unit test that reads the features back from the tile, with the thought of asserting the original features
only to see that the tile writer distorts the the feature differently for every zoom level..
I dont know how to compare the similarity of the distorted polygon..
test is below, maybe you can alter it.

`

    [Test]
    public void MvtWriterGeometryIssue()
    {
        string italyTxt = getItalyText();
        MultiPolygon a = new WKTReader().Read(italyTxt) as MultiPolygon;
        //byte[] tile1 = writeTile(8, 6, 4, a);
        //IFeature[] features = readTile(8, 6, 4, tile1);

        byte[] tile1 = writeTile(4401, 3077, 13, a);
        IFeature[] features = readTile(4401, 3077, 13, tile1);

        Assert.AreEqual(1, features.Length);
        MultiPolygon b = features[0].Geometry as MultiPolygon;

        Assert.AreEqual(a.Count,b.Count);

        Geometry[] a_polygons = a.OrderBy(p => p.Area).ThenBy(p => p.Coordinates.Length).ToArray();
        Geometry[] b_polygons = b.OrderBy(p => p.Area).ThenBy(p => p.Coordinates.Length).ToArray();

        for (int i = 0; i < a_polygons.Length; i++)
        {
            Geometry pa = a_polygons[i].Normalized();
            Geometry pb = b_polygons[i].Normalized();
            

            //Geometries are distorted for different zoom levels, cant asser't similarity

            IntersectionMatrix intersectionMatrix = pa.Relate(pb);
            
        }
    }
    
    private static byte[] writeTile(int x, int y, int z, Geometry geometry)
    {
        Feature feature = new Feature(geometry, new AttributesTable(new Dictionary<string, object>
        {
            { "id", 1 }
        }));
        Tile tileDefinition = new Tile(x, y, z);
        VectorTile vectorTile = new VectorTile { TileId = tileDefinition.Id };
        Layer layer = new Layer { Name = "layer1" };
        vectorTile.Layers.Add(layer);
        layer.Features.Add(feature);

        byte[] result;
        MemoryStream? fs;
        using (fs = new MemoryStream(1024 * 32))
        {
            vectorTile.Write(fs);
            result = fs.ToArray();
        }

        return result;
    }

    private static IFeature[] readTile(int x, int y, int z, byte[] tile)
    {
        MapboxTileReader reader = new MapboxTileReader();

        Tile tileDefinition = new Tile(x, y, z);

        List<IFeature> res = new List<IFeature>();
        using (MemoryStream ms = new MemoryStream(tile))
        {
            VectorTile? vt = reader.Read(ms, tileDefinition, "id");

            //Loop through each layer.
            foreach (Layer l in vt.Layers)
            {
                IList<IFeature> features = l.Features;
                res.AddRange(features);
            }
        }

        return res.ToArray();
    }

`

@FObermaier
Copy link
Member

FObermaier commented Mar 19, 2024

I dont know how to compare the similarity of the distorted polygon..

Try one or combine any of NetTopologySuite.Algorithm.Match.[Hausdorff|Area|Frechet]SimilarityMeasure.
They implement ISimilarityMeasure an interface that describes functions that compute a value describing the similarity of two geometries.

@megedsh
Copy link
Author

megedsh commented Mar 19, 2024

Like you said.
used HausdorffSimilarityMeasure, and allowed 0.05 deveiation
Develop branch fails (similarity ~0.85), Fix branch 0.96

`

    [Test]
    public void MvtWriterGeometryIssue()
    {
        string italyTxt = getItalyText();
        Geometry? geom = new WKTReader().Read(italyTxt);

        assertSimilarityAfterExportImportTile(geom, 8, 6, 4, 0.05);
    }

    private static void assertSimilarityAfterExportImportTile(Geometry g, int x, int y, int zoom, double threashold)
    {
        byte[] tile1 = writeTile(x, y, zoom, g);
        IFeature[] features = readTile(x, y, zoom, tile1);
        Assert.NotNull(features);
        Assert.AreEqual(1, features.Length);

        Geometry geomFromTile = features[0].Geometry;
        if (geomFromTile is GeometryCollection gca && g is GeometryCollection gcb)
        {
            Assert.AreEqual(gca.Count, gcb.Count);
        }

        double similarity = new HausdorffSimilarityMeasure().Measure(geomFromTile, g);
        if (similarity >= 1)
        {
            Assert.Pass();
        }
        else
        {
            Assert.AreEqual(1, similarity, threashold, $"Geometry from tile not similar to original. Threashold = ({threashold})" );
        }
    }

    private static byte[] writeTile(int x, int y, int z, Geometry geometry)
    {
        Feature feature = new Feature(geometry, new AttributesTable(new Dictionary<string, object>
        {
            { "id", 1 }
        }));
        Tile tileDefinition = new Tile(x, y, z);
        VectorTile vectorTile = new VectorTile { TileId = tileDefinition.Id };
        Layer layer = new Layer { Name = "layer1" };
        vectorTile.Layers.Add(layer);
        layer.Features.Add(feature);

        byte[] result;
        MemoryStream? fs;
        using (fs = new MemoryStream(1024 * 32))
        {
            vectorTile.Write(fs);
            result = fs.ToArray();
        }

        return result;
    }

    private static IFeature[] readTile(int x, int y, int z, byte[] tile)
    {
        MapboxTileReader reader = new MapboxTileReader();

        Tile tileDefinition = new Tile(x, y, z);

        List<IFeature> res = new List<IFeature>();
        using (MemoryStream ms = new MemoryStream(tile))
        {
            VectorTile? vt = reader.Read(ms, tileDefinition, "id");

            //Loop through each layer.
            foreach (Layer l in vt.Layers)
            {
                IList<IFeature> features = l.Features;
                res.AddRange(features);
            }
        }

        return res.ToArray();
    }

`

FObermaier added a commit that referenced this issue Aug 13, 2024
Add provided unit test slightly modified

refers to #29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants