1 package org.simantics.district.network;
3 import java.awt.geom.Rectangle2D;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Iterator;
8 import java.util.stream.Collectors;
9 import java.util.stream.Stream;
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;
45 import com.vividsolutions.jts.geom.Envelope;
46 import com.vividsolutions.jts.index.quadtree.Quadtree;
48 public class DistrictNetworkUtil {
50 private static final Logger LOGGER = LoggerFactory.getLogger(DistrictNetworkUtil.class);
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);
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);
63 Resource edge = graph.newResource();
64 graph.claim(edge, L0.InstanceOf, DN.Edge);
66 graph.claim(edge, DN.HasMapping, null, mapping);
68 OrderedSetUtils.addFirst(graph, composite, edge);
69 graph.claim(composite, L0.ConsistsOf, L0.PartOf, edge);
71 claimFreshElementName(graph, composite, edge);
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);
77 GraphLayer gl = layerUtil.loadLayer(graph, layer);
78 gl.forEachTag(tag -> {
79 DiagramGraphUtil.tag(graph, edge, tag, true);
83 // add detailed geometry (if any)
84 graph.claimLiteral(edge, DN.Edge_HasGeometry, detailedGeometryCoords, Bindings.DOUBLE_ARRAY);
92 * @param elevation Double.MAX_VALUE to fetch elevation from elevation server (if enabled and has data)
94 * @throws DatabaseException
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);
105 * @param elevation Double.MAX_VALUE to fetch elevation from elevation server (if enabled and has data)
108 * @throws DatabaseException
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
117 elevation = SingletonTiffTileInterface.lookup(coords[1], coords[0]).doubleValue();
118 } catch (Exception ee) {
119 LOGGER.error("Could not get elevation from tiff interface", ee);
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);
134 graph.claim(vertex, DN.HasMapping, null, mapping);
136 OrderedSetUtils.add(graph, composite, vertex);
137 graph.claim(composite, L0.ConsistsOf, L0.PartOf, vertex);
139 claimFreshElementName(graph, composite, vertex);
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);
145 GraphLayer gl = layerUtil.loadLayer(graph, layer);
146 gl.forEachTag(tag -> {
147 DiagramGraphUtil.tag(graph, vertex, tag, true);
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);
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);
173 OrderedSetUtils.remove(graph, composite, slave);
174 // Remove ConsistsOf statement
175 graph.deny(composite, Layer0.getInstance(graph).ConsistsOf, slave);
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);
187 Resource crs = graph.getSingleObject(startComposite, DistrictNetworkResource.getInstance(graph).HasSpatialRefSystem);
189 CRS crsClass = graph.adapt(crs, CRS.class);
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);
194 return crsClass.calculateDistance(startCoords, endCoords);
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)
204 // Give running name to element and increment the counter attached to the diagram.
205 Long l = graph.getPossibleRelatedValue(diagram, DIA.HasModCount, Bindings.LONG);
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);
214 public static Resource getDiagramElement(ReadGraph graph, Resource component) throws DatabaseException {
215 if (component == null)
217 DiagramResource DIA = DiagramResource.getInstance(graph);
218 if (graph.isInstanceOf(component, DIA.Element))
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;
225 public static Resource getMappedElement(ReadGraph graph, Resource element) throws DatabaseException {
228 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
229 return graph.getPossibleObject(element, DN.MappedComponent);
232 public static Resource getMappedComponent(ReadGraph graph, Resource element) throws DatabaseException {
235 Resource mappedElement = getMappedElement(graph, element);
236 if (mappedElement == null)
238 ModelingResources MOD = ModelingResources.getInstance(graph);
239 return graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
242 public static Resource getMappedComponentCached(ReadGraph graph, Resource vertex) throws DatabaseException {
243 return graph.syncRequest(new MappedComponentRequest(vertex), TransientCacheListener.instance());
246 public static Resource getMappedDNElement(ReadGraph graph, Resource element) throws DatabaseException {
249 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
250 return graph.getPossibleObject(element, DN.MappedFromElement);
253 public static Variable toMappedConfigurationModule(ReadGraph graph, Resource input) throws DatabaseException {
257 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
258 if (graph.isInstanceOf(input, DN.Element)) {
259 Resource mappedElement = getMappedElement(graph, input);
260 if (mappedElement == null)
263 ModelingResources MOD = ModelingResources.getInstance(graph);
264 Resource mappedComponent = graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
265 if (mappedComponent == null)
268 return graph.syncRequest(new PossibleVariable(mappedComponent));
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);
278 graph.claimLiteral(diagram, DN.Diagram_drawMapEnabled, !current, Bindings.BOOLEAN);
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;
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));
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));
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));
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);
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);
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()));
325 public static final class MappedComponentRequest extends ResourceRead<Resource> {
326 public MappedComponentRequest(Resource element) {
331 public Resource perform(ReadGraph graph) throws DatabaseException {
332 return getMappedComponent(graph, resource);
336 public static class ResourceVertex {
338 public final boolean isConsumer;
339 public final Resource vertex;
340 public final double[] coords;
342 public ResourceVertex(Resource vertex, double[] coords, boolean isConsumer) {
343 this.vertex = vertex;
344 this.coords = coords;
345 this.isConsumer = isConsumer;
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);
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)),
362 ).stream().filter(element -> {
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);
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();
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])) {
396 public static List<ResourceVertex> nearbyResourceVertices(ReadGraph graph, Resource diagramResource, Resource vertex, Double padding) throws DatabaseException {
397 double halfPadding = padding / 2;
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);
407 List<?> result = existingVertices.query(e);
408 @SuppressWarnings("unchecked")
409 List<ResourceVertex> vertices = (List<ResourceVertex>) result;
411 Rectangle2D vertexRectangle = new Rectangle2D.Double(coords[0] - halfPadding, coords[1] - halfPadding, padding, padding);
413 // let's sort by distance
414 List<ResourceVertex> sortedVertices = vertices.stream().filter(rv -> {
415 if (rv.vertex.equals(vertex))
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))));
424 if (o1.vertex.getResourceId() == 2554883) {
425 System.err.println("here we are");
428 return Double.compare(disto1, disto2);
429 }).collect(Collectors.toList());
430 return sortedVertices;
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)
437 .map(rv -> rv.vertex)
438 .collect(Collectors.toList());
441 public static Quadtree existingVertices(Resource diagramResource, Double padding) throws DatabaseException {
442 Quadtree vv = Simantics.getSession().syncRequest(new ExistingVerticesRead(diagramResource, padding));
446 public static class ExistingVerticesRead extends BinaryRead<Resource, Double, Quadtree> {
448 public ExistingVerticesRead(Resource diagramResource, Double padding) {
449 super(diagramResource, padding);
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));