private SimpleMatchList generateMatches(SimpleMatchSettings settings) {
    JosmTaskMonitor monitor = new JosmTaskMonitor();
    monitor.beginTask("Generating matches");

    // create Features and collections from primitive selections
    Set<OsmPrimitive> allPrimitives = new HashSet<>();
    allPrimitives.addAll(settings.getReferenceSelection());
    allPrimitives.addAll(settings.getSubjectSelection());
    FeatureCollection allFeatures = createFeatureCollection(allPrimitives);
    FeatureCollection refColl = new FeatureDataset(allFeatures.getFeatureSchema());
    FeatureCollection subColl = new FeatureDataset(allFeatures.getFeatureSchema());
    for (Feature f : allFeatures.getFeatures()) {
      OsmFeature osmFeature = (OsmFeature) f;
      if (settings.getReferenceSelection().contains(osmFeature.getPrimitive()))
        refColl.add(osmFeature);
      if (settings.getSubjectSelection().contains(osmFeature.getPrimitive()))
        subColl.add(osmFeature);
    }

    // TODO: pass to MatchFinderPanel to use as hint/default for DistanceMatchers
    // get maximum possible distance so scores can be scaled (FIXME: not quite accurate)
    //        Envelope envelope = refColl.getEnvelope();
    //        envelope.expandToInclude(subColl.getEnvelope());
    //        double maxDistance = Point2D.distance(
    //            envelope.getMinX(),
    //            envelope.getMinY(),
    //            envelope.getMaxX(),
    //            envelope.getMaxY());

    // build matcher
    FCMatchFinder finder = settings.getMatchFinder();

    // FIXME: ignore/filter duplicate objects (i.e. same object in both sets)
    // FIXME: fix match functions to work on point/linestring features as well
    // find matches
    Map<Feature, Matches> map = finder.match(refColl, subColl, monitor);

    monitor.subTask("Finishing match list");

    // convert to simple one-to-one match
    SimpleMatchList list = new SimpleMatchList();
    for (Map.Entry<Feature, Matches> entry : map.entrySet()) {
      OsmFeature target = (OsmFeature) entry.getKey();
      OsmFeature subject = (OsmFeature) entry.getValue().getTopMatch();
      if (target != null && subject != null)
        list.add(
            new SimpleMatch(
                target.getPrimitive(), subject.getPrimitive(), entry.getValue().getTopScore()));
    }

    monitor.finishTask();
    monitor.close();
    return list;
  }
예제 #2
0
  /**
   * Write a dbf file with the information from the featureCollection.
   *
   * @param featureCollection column data from collection
   * @param fname name of the dbf file to write to
   */
  void writeDbf(FeatureCollection featureCollection, String fname) throws Exception {
    DbfFileWriter dbf;
    FeatureSchema fs;
    int t;
    int f;
    int u;
    int num;

    fs = featureCollection.getFeatureSchema();

    // -1 because one of the columns is geometry
    DbfFieldDef[] fields = new DbfFieldDef[fs.getAttributeCount() - 1];

    // dbf column type and size
    f = 0;

    for (t = 0; t < fs.getAttributeCount(); t++) {
      AttributeType columnType = fs.getAttributeType(t);
      String columnName = fs.getAttributeName(t);

      if (columnType == AttributeType.INTEGER) {
        fields[f] = new DbfFieldDef(columnName, 'N', 16, 0);
        f++;
      } else if (columnType == AttributeType.DOUBLE) {
        fields[f] = new DbfFieldDef(columnName, 'N', 33, 16);
        f++;
      } else if (columnType == AttributeType.STRING) {
        int maxlength = findMaxStringLength(featureCollection, t);

        if (maxlength > 255) {
          throw new Exception(
              "ShapefileWriter does not support strings longer than 255 characters");
        }

        fields[f] = new DbfFieldDef(columnName, 'C', maxlength, 0);
        f++;
      } else if (columnType == AttributeType.DATE) {
        fields[f] = new DbfFieldDef(columnName, 'D', 8, 0);
        f++;
      } else if (columnType == AttributeType.GEOMETRY) {
        // do nothing - the .shp file handles this
      } else {
        throw new Exception("Shapewriter: unsupported AttributeType found in featurecollection.");
      }
    }

    // write header
    dbf = new DbfFileWriter(fname);
    dbf.writeHeader(fields, featureCollection.size());

    // write rows
    num = featureCollection.size();

    List features = featureCollection.getFeatures();

    for (t = 0; t < num; t++) {
      // System.out.println("dbf: record "+t);
      Feature feature = (Feature) features.get(t);
      Vector DBFrow = new Vector();

      // make data for each column in this feature (row)
      for (u = 0; u < fs.getAttributeCount(); u++) {
        AttributeType columnType = fs.getAttributeType(u);

        if (columnType == AttributeType.INTEGER) {
          Object a = feature.getAttribute(u);

          if (a == null) {
            DBFrow.add(new Integer(0));
          } else {
            DBFrow.add((Integer) a);
          }
        } else if (columnType == AttributeType.DOUBLE) {
          Object a = feature.getAttribute(u);

          if (a == null) {
            DBFrow.add(new Double(0.0));
          } else {
            DBFrow.add((Double) a);
          }
        } else if (columnType == AttributeType.DATE) {
          Object a = feature.getAttribute(u);
          if (a == null) {
            DBFrow.add("");
          } else {
            DBFrow.add(DbfFile.DATE_PARSER.format((Date) a));
          }
        } else if (columnType == AttributeType.STRING) {
          Object a = feature.getAttribute(u);

          if (a == null) {
            DBFrow.add(new String(""));
          } else {
            // MD 16 jan 03 - added some defensive programming
            if (a instanceof String) {
              DBFrow.add(a);
            } else {
              DBFrow.add(a.toString());
            }
          }
        }
      }

      dbf.writeRecord(DBFrow);
    }

    dbf.close();
  }
예제 #3
0
  /**
   * return a single geometry collection <br>
   * result.GeometryN(i) = the i-th feature in the FeatureCollection<br>
   * All the geometry types will be the same type (ie. all polygons) - or they will be set to<br>
   * NULL geometries<br>
   * <br>
   * GeometryN(i) = {Multipoint,Multilinestring, or Multipolygon)<br>
   *
   * @param fc feature collection to make homogeneous
   */
  public GeometryCollection makeSHAPEGeometryCollection(FeatureCollection fc) throws Exception {
    GeometryCollection result;
    Geometry[] allGeoms = new Geometry[fc.size()];

    int geomtype = findBestGeometryType(fc);

    if (geomtype == 0) {
      throw new Exception(
          "Could not determine shapefile type - data is either all GeometryCollections or empty");
    }

    List features = fc.getFeatures();

    for (int t = 0; t < features.size(); t++) {
      Geometry geom;
      geom = ((Feature) features.get(t)).getGeometry();

      switch (geomtype) {
        case 1: // point
          if ((geom instanceof Point)) {
            // good!
            Point[] p = new Point[1];
            p[0] = (Point) geom;

            allGeoms[t] = new MultiPoint(p, new PrecisionModel(), 0);
          } else if (geom instanceof MultiPoint) {
            allGeoms[t] = geom;
          } else {
            allGeoms[t] = new MultiPoint(null, new PrecisionModel(), 0);
          }

          break;

        case 2: // line
          if ((geom instanceof LineString)) {
            LineString[] l = new LineString[1];
            l[0] = (LineString) geom;

            allGeoms[t] = new MultiLineString(l, new PrecisionModel(), 0);
          } else if (geom instanceof MultiLineString) {
            allGeoms[t] = geom;
          } else {
            allGeoms[t] = new MultiLineString(null, new PrecisionModel(), 0);
          }

          break;

        case 3: // polygon
          if (geom instanceof Polygon) {
            // good!
            Polygon[] p = new Polygon[1];
            p[0] = (Polygon) geom;

            allGeoms[t] = makeGoodSHAPEMultiPolygon(new MultiPolygon(p, new PrecisionModel(), 0));
          } else if (geom instanceof MultiPolygon) {
            allGeoms[t] = makeGoodSHAPEMultiPolygon((MultiPolygon) geom);
          } else {
            allGeoms[t] = new MultiPolygon(null, new PrecisionModel(), 0);
          }

          break;
      }
    }

    result = new GeometryCollection(allGeoms, new PrecisionModel(), 0);

    return result;
  }
예제 #4
0
  public static Geometry obtenerGeometriaParcela(String dxf, WorkbenchContext context) {

    Geometry geometryParcela = null;

    GeopistaLoadDxfQueryChooser dxfLoad =
        new GeopistaLoadDxfQueryChooser(Dxf.class, "GEOPISTA dxf", extensions(Dxf.class), context);

    InputStream fileDXF = ImportarUtils_LCGIII.parseStringToIS(dxf);

    try {
      Assert.isTrue(!dxfLoad.getDataSourceQueries(fileDXF).isEmpty());
    } catch (AssertionFailedException e) {
      throw new AssertionFailedException(I18N.get("FileEmpty"));
    }

    fileDXF = ImportarUtils_LCGIII.parseStringToIS(dxf);

    boolean exceptionsEncountered = false;
    for (Iterator i = dxfLoad.getDataSourceQueries(fileDXF).iterator(); i.hasNext(); ) {
      DataSourceQuery dataSourceQuery = (DataSourceQuery) i.next();

      ArrayList exceptions = new ArrayList();
      Assert.isTrue(dataSourceQuery.getDataSource().isReadable());

      Connection connection = dataSourceQuery.getDataSource().getConnection();
      try {
        FeatureCollection dataset =
            dataSourceQuery
                .getDataSource()
                .installCoordinateSystem(
                    connection.executeQuery(dataSourceQuery.getQuery(), exceptions, null), null);
        if (dataset != null) {

          String layerName = dataSourceQuery.toString();
          Geometry geometriaInicial = null;
          GeopistaFeature featureInicial = null;

          if (layerName.startsWith("PG-LP")) {
            // Obtener el borde con las features de la capa
            ArrayList lstFeatures = new ArrayList();
            for (Iterator features = dataset.getFeatures().iterator(); features.hasNext(); ) {
              GeopistaFeature feature = (GeopistaFeature) features.next();
              lstFeatures.add(feature);
            }
            ArrayList coordenadas = new ArrayList();

            if (lstFeatures != null && lstFeatures.size() > 0) {

              featureInicial = (GeopistaFeature) lstFeatures.iterator().next();
              lstFeatures.remove(featureInicial);
              geometriaInicial = featureInicial.getGeometry();
              for (int indice = 0; indice < geometriaInicial.getCoordinates().length; indice++)
                coordenadas.add(geometriaInicial.getCoordinates()[indice]);

              if (geometriaInicial instanceof LineString) {

                Point puntoFinal = ((LineString) geometriaInicial).getEndPoint();
                GeopistaFeature feature = null;
                Geometry geometria = null;
                int indice;

                while (lstFeatures.size() > 0) {
                  boolean encontrado = false;
                  Iterator features = lstFeatures.iterator();
                  while (features.hasNext() && !encontrado) {

                    feature = (GeopistaFeature) features.next();
                    geometria = feature.getGeometry();
                    if (geometria instanceof LineString) {

                      if (puntoFinal.distance(((LineString) geometria).getStartPoint()) == 0) {

                        for (indice = 1; indice < geometria.getCoordinates().length; indice++)
                          coordenadas.add(geometria.getCoordinates()[indice]);
                        puntoFinal = ((LineString) geometria).getEndPoint();
                        encontrado = true;

                      } else if (puntoFinal.distance(((LineString) geometria).getEndPoint()) == 0) {
                        for (indice = geometria.getCoordinates().length - 2; indice >= 0; indice--)
                          coordenadas.add(geometria.getCoordinates()[indice]);

                        puntoFinal = ((LineString) geometria).getStartPoint();
                        encontrado = true;
                      }
                    }
                  }
                  if (encontrado) {
                    lstFeatures.remove(feature);
                  }
                }
                Coordinate[] coordenadasParcela = new Coordinate[coordenadas.size()];
                indice = 0;
                for (Iterator coordenada = coordenadas.iterator(); coordenada.hasNext(); ) {
                  coordenadasParcela[indice] = (Coordinate) coordenada.next();
                  indice++;
                }

                if (coordenadasParcela[0].equals3D(
                    coordenadasParcela[coordenadasParcela.length - 1])) {
                  LinearRing lineaParcela =
                      geometriaInicial.getFactory().createLinearRing(coordenadasParcela);
                  Polygon poligonoParcela = null;
                  poligonoParcela = geometriaInicial.getFactory().createPolygon(lineaParcela, null);
                  geometryParcela = poligonoParcela;
                }
              }
            }
          }
        }
      } finally {
        connection.close();
      }
      if (!exceptions.isEmpty()) {
        if (!exceptionsEncountered) {
          context.getIWorkbench().getFrame().getOutputFrame().createNewDocument();
          exceptionsEncountered = true;
        }
        reportExceptions(exceptions, dataSourceQuery, context);
      }
    }
    if (exceptionsEncountered) {
      context
          .getIWorkbench()
          .getGuiComponent()
          .warnUser("Problems were encountered. See Output Window for details.");
    }

    return geometryParcela;
  }