]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network/src/org/simantics/district/network/DistrictNetworkUtil.java
Support searching nearby vertices in network diagram
[simantics/district.git] / org.simantics.district.network / src / org / simantics / district / network / DistrictNetworkUtil.java
1 package org.simantics.district.network;
2
3 import java.awt.geom.Rectangle2D;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.stream.Collectors;
9 import java.util.stream.Stream;
10
11 import org.simantics.Simantics;
12 import org.simantics.databoard.Bindings;
13 import org.simantics.datatypes.literal.RGB;
14 import org.simantics.datatypes.literal.RGB.Integer;
15 import org.simantics.db.ReadGraph;
16 import org.simantics.db.Resource;
17 import org.simantics.db.WriteGraph;
18 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
19 import org.simantics.db.common.request.BinaryRead;
20 import org.simantics.db.common.request.IndexRoot;
21 import org.simantics.db.common.request.ObjectsWithType;
22 import org.simantics.db.common.request.ResourceRead;
23 import org.simantics.db.common.utils.OrderedSetUtils;
24 import org.simantics.db.exception.BindingException;
25 import org.simantics.db.exception.DatabaseException;
26 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
27 import org.simantics.db.exception.ServiceException;
28 import org.simantics.db.indexing.IndexUtils;
29 import org.simantics.db.layer0.request.PossibleVariable;
30 import org.simantics.db.layer0.variable.Variable;
31 import org.simantics.diagram.stubs.DiagramResource;
32 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
33 import org.simantics.diagram.synchronization.graph.layer.GraphLayer;
34 import org.simantics.diagram.synchronization.graph.layer.IGraphLayerUtil;
35 import org.simantics.district.network.ontology.DistrictNetworkResource;
36 import org.simantics.layer0.Layer0;
37 import org.simantics.maps.elevation.server.SingletonTiffTileInterface;
38 import org.simantics.maps.elevation.server.prefs.MapsElevationServerPreferences;
39 import org.simantics.modeling.ModelingResources;
40 import org.simantics.modeling.adapters.NewCompositeActionFactory;
41 import org.simantics.operation.Layer0X;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import com.vividsolutions.jts.geom.Envelope;
46 import com.vividsolutions.jts.index.quadtree.Quadtree;
47
48 public class DistrictNetworkUtil {
49
50     private static final Logger LOGGER = LoggerFactory.getLogger(DistrictNetworkUtil.class);
51
52     public static Resource createEdge(WriteGraph graph, Resource composite, double[] detailedGeometryCoords) throws DatabaseException {
53         return createEdge(graph, composite, graph.getPossibleObject(composite, DistrictNetworkResource.getInstance(graph).EdgeDefaultMapping), detailedGeometryCoords);
54     }
55
56     public static Resource createEdge(WriteGraph graph, Resource composite, Resource mapping, double[] detailedGeometryCoords) throws DatabaseException {
57         Layer0 L0 = Layer0.getInstance(graph);
58         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
59         if (mapping == null) {
60             mapping = graph.getSingleObject(composite, DN.EdgeDefaultMapping);
61         }
62         
63         Resource edge = graph.newResource();
64         graph.claim(edge, L0.InstanceOf, DN.Edge);
65         
66         graph.claim(edge, DN.HasMapping, null, mapping);
67         
68         OrderedSetUtils.addFirst(graph, composite, edge);
69         graph.claim(composite, L0.ConsistsOf, L0.PartOf, edge);
70         
71         claimFreshElementName(graph, composite, edge);
72         
73         // We need to put GraphLayer to newLayers so...
74         for (Resource layer : graph.getObjects(composite, DiagramResource.getInstance(graph).HasLayer)) {
75             IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
76             
77             GraphLayer gl = layerUtil.loadLayer(graph, layer);
78             gl.forEachTag(tag -> {
79                 DiagramGraphUtil.tag(graph, edge, tag, true);
80             });
81         }
82         
83         // add detailed geometry (if any)
84         graph.claimLiteral(edge, DN.Edge_HasGeometry, detailedGeometryCoords, Bindings.DOUBLE_ARRAY);
85         return edge;
86     }
87
88     /**
89      * @param graph
90      * @param composite
91      * @param coords
92      * @param elevation Double.MAX_VALUE to fetch elevation from elevation server (if enabled and has data)
93      * @return
94      * @throws DatabaseException
95      */
96     public static Resource createVertex(WriteGraph graph, Resource composite, double[] coords, double elevation) throws DatabaseException {
97         Resource defaultVertexMapping = graph.getPossibleObject(composite, DistrictNetworkResource.getInstance(graph).VertexDefaultMapping);
98         return createVertex(graph, composite, coords, elevation, defaultVertexMapping);
99     }
100
101     /**
102      * @param graph
103      * @param composite
104      * @param coords
105      * @param elevation Double.MAX_VALUE to fetch elevation from elevation server (if enabled and has data)
106      * @param mapping
107      * @return
108      * @throws DatabaseException
109      */
110     public static Resource createVertex(WriteGraph graph, Resource composite, double[] coords, double elevation, Resource mapping) throws DatabaseException {
111         // Double.MAX_VALUE is our secret to lookup elevation from elevation server
112         if (elevation == Double.MAX_VALUE) {
113             // ok, resolve from server or default to 0
114             if (MapsElevationServerPreferences.useElevationServer()) {
115                 // ok! we use new elevation API to resolve possible elevations for the starting points
116                 try {
117                     elevation = SingletonTiffTileInterface.lookup(coords[1], coords[0]).doubleValue();
118                 } catch (Exception ee) {
119                     LOGGER.error("Could not get elevation from tiff interface", ee);
120                 }
121             } else {
122                 elevation = 0;
123             }
124         }
125         
126         Layer0 L0 = Layer0.getInstance(graph);
127         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
128         DiagramResource DIA = DiagramResource.getInstance(graph);
129         Resource vertex = graph.newResource();
130         graph.claim(vertex, L0.InstanceOf, DN.Vertex);
131         graph.claimLiteral(vertex, DIA.HasLocation, coords);
132         graph.claimLiteral(vertex, DN.Vertex_HasElevation, elevation, Bindings.DOUBLE);
133         
134         graph.claim(vertex, DN.HasMapping, null, mapping);
135         
136         OrderedSetUtils.add(graph, composite, vertex);
137         graph.claim(composite, L0.ConsistsOf, L0.PartOf, vertex);
138         
139         claimFreshElementName(graph, composite, vertex);
140         
141         // We need to put GraphLayer to newLayers so...
142         for (Resource layer : graph.getObjects(composite, DiagramResource.getInstance(graph).HasLayer)) {
143             IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
144             
145             GraphLayer gl = layerUtil.loadLayer(graph, layer);
146             gl.forEachTag(tag -> {
147                 DiagramGraphUtil.tag(graph, vertex, tag, true);
148             });
149         }
150         
151         return vertex;
152     }
153     
154     public static Resource joinVertices(WriteGraph graph, Collection<Resource> vertices) throws DatabaseException {
155         if (vertices.isEmpty())
156             throw new IllegalArgumentException("vertices-collection should not be empty for joining vertices!");
157         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
158         Iterator<Resource> verticeIterator = vertices.iterator();
159         Resource master = verticeIterator.next();
160         while (verticeIterator.hasNext()) {
161             Resource slave = verticeIterator.next();
162             Resource composite = graph.getSingleObject(slave, Layer0.getInstance(graph).PartOf);
163             Collection<Resource> startVertexEdges = graph.getObjects(slave, DN.HasStartVertex_Inverse);
164             for (Resource startVertexEdge : startVertexEdges) {
165                 graph.deny(startVertexEdge, DN.HasStartVertex);
166                 graph.claim(startVertexEdge, DN.HasStartVertex, master);
167             }
168             Collection<Resource> endVertexEdges = graph.getObjects(slave, DN.HasEndVertex_Inverse);
169             for (Resource endVertexEdge : endVertexEdges) {
170                 graph.deny(endVertexEdge, DN.HasEndVertex);
171                 graph.claim(endVertexEdge, DN.HasEndVertex, master);
172             }
173             OrderedSetUtils.remove(graph, composite, slave);
174             // Remove ConsistsOf statement
175             graph.deny(composite, Layer0.getInstance(graph).ConsistsOf, slave);
176         }
177         return master;
178     }
179     
180     public static double calculateDistance(ReadGraph graph, Resource startVertex, Resource endVertex) throws DatabaseException {
181         Layer0 L0 = Layer0.getInstance(graph);
182         Resource startComposite = graph.getSingleObject(startVertex, L0.PartOf);
183         Resource endComposite = graph.getSingleObject(endVertex, L0.PartOf);
184         if (!startComposite.equalsResource(endComposite)) {
185             throw new DatabaseException("Can not calculate distance between vertices on different composites! " + startVertex + " -> " + endVertex);
186         }
187         Resource crs = graph.getSingleObject(startComposite, DistrictNetworkResource.getInstance(graph).HasSpatialRefSystem);
188         
189         CRS crsClass = graph.adapt(crs, CRS.class);
190         
191         double[] startCoords = graph.getRelatedValue2(startVertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
192         double[] endCoords = graph.getRelatedValue2(endVertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
193         
194         return crsClass.calculateDistance(startCoords, endCoords);
195     }
196     
197     public static final String claimFreshElementName(WriteGraph graph, Resource diagram, Resource element) throws DatabaseException {
198         Layer0 L0 = Layer0.getInstance(graph);
199         DiagramResource DIA = DiagramResource.getInstance(graph);
200         // Get name prefix from diagram
201         String namePrefix = graph.getPossibleRelatedValue2(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix);
202         if (namePrefix == null)
203             namePrefix = "";
204         // Give running name to element and increment the counter attached to the diagram.
205         Long l = graph.getPossibleRelatedValue(diagram, DIA.HasModCount, Bindings.LONG);
206         if (l == null)
207             l = Long.valueOf(0L);
208         String name = namePrefix + l.toString();
209         graph.claimLiteral(element, L0.HasName, name, Bindings.STRING);
210         graph.claimLiteral(diagram, DIA.HasModCount, ++l, Bindings.LONG);
211         return name;
212     }
213
214     public static Resource getDiagramElement(ReadGraph graph, Resource component) throws DatabaseException {
215         if (component == null)
216             return null;
217         DiagramResource DIA = DiagramResource.getInstance(graph);
218         if (graph.isInstanceOf(component, DIA.Element))
219             return component;
220         ModelingResources MOD = ModelingResources.getInstance(graph);
221         Resource element = graph.getPossibleObject(component, MOD.ComponentToElement);
222         return element != null && graph.isInstanceOf(element, DIA.Element) ? element : null;
223     }
224
225     public static Resource getMappedElement(ReadGraph graph, Resource element) throws DatabaseException {
226         if (element == null)
227             return null;
228         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
229         return graph.getPossibleObject(element, DN.MappedComponent);
230     }
231
232     public static Resource getMappedComponent(ReadGraph graph, Resource element) throws DatabaseException {
233         if (element == null)
234             return null;
235         Resource mappedElement = getMappedElement(graph, element);
236         if (mappedElement == null)
237             return null;
238         ModelingResources MOD = ModelingResources.getInstance(graph);
239         return graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
240     }
241     
242     public static Resource getMappedComponentCached(ReadGraph graph, Resource vertex) throws DatabaseException {
243         return graph.syncRequest(new MappedComponentRequest(vertex), TransientCacheListener.instance());
244     }
245
246     public static Resource getMappedDNElement(ReadGraph graph, Resource element) throws DatabaseException {
247         if (element == null)
248             return null;
249         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
250         return graph.getPossibleObject(element, DN.MappedFromElement);
251     }
252
253     public static Variable toMappedConfigurationModule(ReadGraph graph, Resource input) throws DatabaseException {
254         if (input == null)
255             return null;
256
257         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
258         if (graph.isInstanceOf(input, DN.Element)) {
259             Resource mappedElement = getMappedElement(graph, input);
260             if (mappedElement == null)
261                 return null;
262
263             ModelingResources MOD = ModelingResources.getInstance(graph);
264             Resource mappedComponent = graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
265             if (mappedComponent == null)
266                 return null;
267
268             return graph.syncRequest(new PossibleVariable(mappedComponent));
269         }
270         return null;
271     }
272
273     public static void toggleDrawMap(WriteGraph graph, Resource diagram) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
274         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
275         Boolean current = graph.getPossibleRelatedValue(diagram, DN.Diagram_drawMapEnabled, Bindings.BOOLEAN);
276         if (current == null)
277             current = true;
278         graph.claimLiteral(diagram, DN.Diagram_drawMapEnabled, !current, Bindings.BOOLEAN);
279     }
280
281     public static Boolean drawMapEnabled(ReadGraph graph, Resource diagram) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
282         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
283         Boolean current = graph.getPossibleRelatedValue(diagram, DN.Diagram_drawMapEnabled, Bindings.BOOLEAN);
284         return current != null ? current : true;
285     }
286
287     public static void changeMapBackgroundColor(WriteGraph graph, Resource diagram, Integer integer) throws DatabaseException {
288         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
289         graph.claimLiteral(diagram, DN.Diagram_backgroundColor, integer, Bindings.getBindingUnchecked(RGB.Integer.class));
290     }
291     
292     public static Boolean trackChangesEnabled(ReadGraph graph, Resource diagram) throws DatabaseException {
293         if (diagram != null && graph.hasStatement(diagram)) {
294             return Boolean.TRUE.equals(graph.getPossibleRelatedValue(diagram,
295                 DistrictNetworkResource.getInstance(graph).Diagram_trackChangesEnabled));
296         } else {
297             return false;
298         }
299     }
300
301     public static RGB.Integer backgroundColor(ReadGraph graph, Resource diagram) throws DatabaseException {
302         return graph.getPossibleRelatedValue(diagram,
303                 DistrictNetworkResource.getInstance(graph).Diagram_backgroundColor,
304                 Bindings.getBindingUnchecked(RGB.Integer.class));
305     }
306     
307     public static Resource createNetworkDiagram(WriteGraph graph, Resource target, Resource compositeType, String defaultName, Resource defaultEdgeMapping, Resource defaultVertexMapping, Resource rightClickVertexMapping, Resource leftClickVertexMapping, Resource crs) throws DatabaseException {
308         Resource composite = NewCompositeActionFactory.createComposite(graph, target, defaultName, compositeType);
309
310         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
311         Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
312         graph.claim(diagram, DN.EdgeDefaultMapping, defaultEdgeMapping);
313         graph.claim(diagram, DN.VertexDefaultMapping, defaultVertexMapping);
314         graph.claim(diagram, DN.RightClickDefaultMapping, rightClickVertexMapping);
315         graph.claim(diagram, DN.LeftClickDefaultMapping, leftClickVertexMapping);
316         graph.claim(diagram, DN.HasSpatialRefSystem, crs);
317         
318         // Generated name prefix from composite name
319         String compositeName = graph.getRelatedValue2(composite, Layer0.getInstance(graph).HasName, Bindings.STRING);
320         graph.claimLiteral(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix, "N" + compositeName.substring(compositeName.length() - 1, compositeName.length()));
321         
322         return composite;
323     }
324
325     public static final class MappedComponentRequest extends ResourceRead<Resource> {
326         public MappedComponentRequest(Resource element) {
327             super(element);
328         }
329
330         @Override
331         public Resource perform(ReadGraph graph) throws DatabaseException {
332             return getMappedComponent(graph, resource);
333         }
334     }
335
336     public static class ResourceVertex {
337         
338         public final boolean isConsumer;
339         public final Resource vertex;
340         public final double[] coords;
341         
342         public ResourceVertex(Resource vertex, double[] coords, boolean isConsumer) {
343             this.vertex = vertex;
344             this.coords = coords;
345             this.isConsumer = isConsumer;
346         }
347     }
348     
349     public static void changeMappingType(WriteGraph graph, Resource newMapping, List<Resource> elements) throws DatabaseException {
350         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
351         for (Resource element : elements) {
352             graph.deny(element, DN.HasMapping);
353             graph.claim(element, DN.HasMapping, newMapping);
354         }
355     }
356
357     public static Stream<Resource> findDNElementsById(ReadGraph graph, Resource context, String idToFind) throws DatabaseException {
358         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph); 
359         return IndexUtils.findByType(graph,
360             graph.syncRequest(new IndexRoot(context)),
361             DN.Element
362         ).stream().filter(element -> {
363             try {
364                 String id = graph.getPossibleRelatedValue(element, DN.HasId, Bindings.STRING);
365                 return id != null && id.contains(idToFind);
366             } catch (DatabaseException e) {
367                 LOGGER.error("Could not read id for element {]", element, e);
368                 return false;
369             }
370         });
371     }
372     
373     public static Resource findDNElementById(ReadGraph graph, Resource context, String idToFind) throws DatabaseException {
374         List<Resource> elements = findDNElementsById(graph, context, idToFind).collect(Collectors.toList());
375         if (elements.size() == 1) {
376             return elements.iterator().next();
377         }
378         return null;
379     }
380     
381     public static List<Resource> findDNElementByXYCoordinates(ReadGraph graph, Resource context, double lat, double lon, double padding) throws DatabaseException {
382         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
383         DiagramResource DIA = DiagramResource.getInstance(graph);
384         List<Resource> results = new ArrayList<>();
385         Collection<Resource> vertices = IndexUtils.findByType(graph, graph.syncRequest(new IndexRoot(context)), DN.Vertex);
386         Rectangle2D rect = new Rectangle2D.Double(lat, lon, padding, padding);
387         for (Resource vertex : vertices) {
388             double[] location = graph.getRelatedValue(vertex, DIA.HasLocation, Bindings.DOUBLE_ARRAY);
389             if (rect.contains(location[0], location[1])) {
390                 results.add(vertex);
391             }
392         }
393         return results;
394     }
395
396     public static List<ResourceVertex> nearbyResourceVertices(ReadGraph graph, Resource diagramResource, Resource vertex, Double padding) throws DatabaseException {
397         double halfPadding = padding / 2;
398         
399         Quadtree existingVertices = graph.syncRequest(new ExistingVerticesRead(diagramResource, halfPadding), TransientCacheListener.instance());
400         double[] coords = graph.getRelatedValue(vertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
401         double x1 = coords[0] - halfPadding;
402         double y1= coords[1] - halfPadding;
403         double x2 = coords[0] + halfPadding;
404         double y2= coords[1] + halfPadding;
405         Envelope e = new Envelope(x1, x2, y1, y2);
406         
407         List<?> result = existingVertices.query(e);
408         @SuppressWarnings("unchecked")
409         List<ResourceVertex> vertices = (List<ResourceVertex>) result;
410         
411         Rectangle2D vertexRectangle = new Rectangle2D.Double(coords[0] - halfPadding, coords[1] - halfPadding, padding, padding);
412         
413         // let's sort by distance
414         List<ResourceVertex> sortedVertices = vertices.stream().filter(rv -> {
415             if (rv.vertex.equals(vertex))
416                 return false;
417             
418             Rectangle2D nearbyRectangle = new Rectangle2D.Double(rv.coords[0] - halfPadding, rv.coords[1] - halfPadding, padding, padding);
419             return vertexRectangle.intersects(nearbyRectangle);
420         }).sorted((o1, o2) -> {
421             double disto1 = Math.sqrt((Math.pow(coords[0] - o1.coords[0], 2) + (Math.pow(coords[1] - o1.coords[1], 2))));
422             double disto2 = Math.sqrt((Math.pow(coords[0] - o2.coords[0], 2) + (Math.pow(coords[1] - o2.coords[1], 2))));
423             
424             if (o1.vertex.getResourceId() == 2554883) {
425                 System.err.println("here we are");
426             }
427             
428             return Double.compare(disto1, disto2);
429         }).collect(Collectors.toList());
430         return sortedVertices;
431     }
432
433     public static List<Resource> nearbyVertices(ReadGraph graph, Resource vertex, double padding) throws DatabaseException {
434         Resource diagramResource = graph.getSingleObject(vertex, Layer0.getInstance(graph).PartOf);
435         return nearbyResourceVertices(graph, diagramResource, vertex, padding)
436                 .stream()
437                 .map(rv -> rv.vertex)
438                 .collect(Collectors.toList());
439     }
440
441     public static Quadtree existingVertices(Resource diagramResource, Double padding) throws DatabaseException {
442         Quadtree vv = Simantics.getSession().syncRequest(new ExistingVerticesRead(diagramResource, padding));
443         return vv;
444     }
445
446     public static class ExistingVerticesRead extends BinaryRead<Resource, Double, Quadtree> {
447
448         public ExistingVerticesRead(Resource diagramResource, Double padding) {
449             super(diagramResource, padding);
450         }
451
452         @Override
453         public Quadtree perform(ReadGraph graph) throws DatabaseException {
454             Collection<Resource> vertices = graph.syncRequest(new ObjectsWithType(parameter, Layer0.getInstance(graph).ConsistsOf, DistrictNetworkResource.getInstance(graph).Vertex));
455             Quadtree vv = new Quadtree();
456             for (Resource vertex : vertices) {
457                 double[] coords = graph.getRelatedValue2(vertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
458                 double x1 = coords[0] - parameter2;
459                 double y1= coords[1] - parameter2;
460                 double x2 = coords[0] + parameter2;
461                 double y2= coords[1] + parameter2;
462                 Envelope e = new Envelope(x1, x2, y1, y2);
463                 vv.insert(e, new ResourceVertex(vertex, coords, true));
464             }
465             return vv;
466         }
467     }
468
469 }