]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network/src/org/simantics/district/network/DistrictNetworkUtil.java
Make it possible to import CSV data via SCL & create models
[simantics/district.git] / org.simantics.district.network / src / org / simantics / district / network / DistrictNetworkUtil.java
1 package org.simantics.district.network;
2
3 import java.util.Collection;
4 import java.util.Iterator;
5
6 import org.simantics.databoard.Bindings;
7 import org.simantics.datatypes.literal.RGB;
8 import org.simantics.datatypes.literal.RGB.Integer;
9 import org.simantics.db.ReadGraph;
10 import org.simantics.db.Resource;
11 import org.simantics.db.WriteGraph;
12 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
13 import org.simantics.db.common.request.ResourceRead;
14 import org.simantics.db.common.utils.OrderedSetUtils;
15 import org.simantics.db.exception.BindingException;
16 import org.simantics.db.exception.DatabaseException;
17 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
18 import org.simantics.db.exception.ServiceException;
19 import org.simantics.db.layer0.request.PossibleVariable;
20 import org.simantics.db.layer0.variable.Variable;
21 import org.simantics.diagram.stubs.DiagramResource;
22 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
23 import org.simantics.diagram.synchronization.graph.layer.GraphLayer;
24 import org.simantics.diagram.synchronization.graph.layer.IGraphLayerUtil;
25 import org.simantics.district.network.ontology.DistrictNetworkResource;
26 import org.simantics.layer0.Layer0;
27 import org.simantics.modeling.ModelingResources;
28 import org.simantics.modeling.adapters.NewCompositeActionFactory;
29 import org.simantics.operation.Layer0X;
30
31 public class DistrictNetworkUtil {
32
33     public static Resource createEdge(WriteGraph graph, Resource composite, double[] detailedGeometryCoords) throws DatabaseException {
34         return createEdge(graph, composite, graph.getPossibleObject(composite, DistrictNetworkResource.getInstance(graph).EdgeDefaultMapping), detailedGeometryCoords);
35     }
36
37     public static Resource createEdge(WriteGraph graph, Resource composite, Resource mapping, double[] detailedGeometryCoords) throws DatabaseException {
38         Layer0 L0 = Layer0.getInstance(graph);
39         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
40         if (mapping == null) {
41             mapping = graph.getSingleObject(composite, DN.EdgeDefaultMapping);
42         }
43         
44         Resource edge = graph.newResource();
45         graph.claim(edge, L0.InstanceOf, DN.Edge);
46         
47         graph.claim(edge, DN.HasMapping, null, mapping);
48         
49         OrderedSetUtils.addFirst(graph, composite, edge);
50         graph.claim(composite, L0.ConsistsOf, L0.PartOf, edge);
51         
52         claimFreshElementName(graph, composite, edge);
53         
54         // We need to put GraphLayer to newLayers so...
55         for (Resource layer : graph.getObjects(composite, DiagramResource.getInstance(graph).HasLayer)) {
56             IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
57             
58             GraphLayer gl = layerUtil.loadLayer(graph, layer);
59             gl.forEachTag(tag -> {
60                 DiagramGraphUtil.tag(graph, edge, tag, true);
61             });
62         }
63         
64         // add detailed geometry (if any)
65         graph.claimLiteral(edge, DN.Edge_HasGeometry, detailedGeometryCoords, Bindings.DOUBLE_ARRAY);
66         return edge;
67     }
68
69     public static Resource createVertex(WriteGraph graph, Resource composite, double[] coords, double elevation) throws DatabaseException {
70         Resource defaultVertexMapping = graph.getPossibleObject(composite, DistrictNetworkResource.getInstance(graph).VertexDefaultMapping);
71         return createVertex(graph, composite, coords, elevation, defaultVertexMapping);
72     }
73
74     public static Resource createVertex(WriteGraph graph, Resource composite, double[] coords, double elevation, Resource mapping) throws DatabaseException {
75         Layer0 L0 = Layer0.getInstance(graph);
76         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
77         DiagramResource DIA = DiagramResource.getInstance(graph);
78         Resource vertex = graph.newResource();
79         graph.claim(vertex, L0.InstanceOf, DN.Vertex);
80         graph.claimLiteral(vertex, DIA.HasLocation, coords);
81         graph.claimLiteral(vertex, DN.Vertex_HasElevation, elevation, Bindings.DOUBLE);
82         
83         graph.claim(vertex, DN.HasMapping, null, mapping);
84         
85         OrderedSetUtils.add(graph, composite, vertex);
86         graph.claim(composite, L0.ConsistsOf, L0.PartOf, vertex);
87         
88         claimFreshElementName(graph, composite, vertex);
89         
90         // We need to put GraphLayer to newLayers so...
91         for (Resource layer : graph.getObjects(composite, DiagramResource.getInstance(graph).HasLayer)) {
92             IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
93             
94             GraphLayer gl = layerUtil.loadLayer(graph, layer);
95             gl.forEachTag(tag -> {
96                 DiagramGraphUtil.tag(graph, vertex, tag, true);
97             });
98         }
99         
100         return vertex;
101     }
102     
103     public static Resource joinVertices(WriteGraph graph, Collection<Resource> vertices) throws DatabaseException {
104         if (vertices.isEmpty())
105             throw new IllegalArgumentException("vertices-collection should not be empty for joining vertices!");
106         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
107         Iterator<Resource> verticeIterator = vertices.iterator();
108         Resource master = verticeIterator.next();
109         while (verticeIterator.hasNext()) {
110             Resource slave = verticeIterator.next();
111             Resource composite = graph.getSingleObject(slave, Layer0.getInstance(graph).PartOf);
112             Collection<Resource> startVertexEdges = graph.getObjects(slave, DN.HasStartVertex_Inverse);
113             for (Resource startVertexEdge : startVertexEdges) {
114                 graph.deny(startVertexEdge, DN.HasStartVertex);
115                 graph.claim(startVertexEdge, DN.HasStartVertex, master);
116             }
117             Collection<Resource> endVertexEdges = graph.getObjects(slave, DN.HasEndVertex_Inverse);
118             for (Resource endVertexEdge : endVertexEdges) {
119                 graph.deny(endVertexEdge, DN.HasEndVertex);
120                 graph.claim(endVertexEdge, DN.HasEndVertex, master);
121             }
122             OrderedSetUtils.remove(graph, composite, slave);
123             // Remove ConsistsOf statement
124             graph.deny(composite, Layer0.getInstance(graph).ConsistsOf, slave);
125         }
126         return master;
127     }
128     
129     public static double calculateDistance(ReadGraph graph, Resource startVertex, Resource endVertex) throws DatabaseException {
130         Layer0 L0 = Layer0.getInstance(graph);
131         Resource startComposite = graph.getSingleObject(startVertex, L0.PartOf);
132         Resource endComposite = graph.getSingleObject(endVertex, L0.PartOf);
133         if (!startComposite.equalsResource(endComposite)) {
134             throw new DatabaseException("Can not calculate distance between vertices on different composites! " + startVertex + " -> " + endVertex);
135         }
136         Resource crs = graph.getSingleObject(startComposite, DistrictNetworkResource.getInstance(graph).HasSpatialRefSystem);
137         
138         CRS crsClass = graph.adapt(crs, CRS.class);
139         
140         double[] startCoords = graph.getRelatedValue2(startVertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
141         double[] endCoords = graph.getRelatedValue2(endVertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
142         
143         return crsClass.calculateDistance(startCoords, endCoords);
144     }
145     
146     public static final String claimFreshElementName(WriteGraph graph, Resource diagram, Resource element) throws DatabaseException {
147         Layer0 L0 = Layer0.getInstance(graph);
148         DiagramResource DIA = DiagramResource.getInstance(graph);
149         // Get name prefix from diagram
150         String namePrefix = graph.getPossibleRelatedValue2(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix);
151         if (namePrefix == null)
152             namePrefix = "";
153         // Give running name to element and increment the counter attached to the diagram.
154         Long l = graph.getPossibleRelatedValue(diagram, DIA.HasModCount, Bindings.LONG);
155         if (l == null)
156             l = Long.valueOf(0L);
157         String name = namePrefix + l.toString();
158         graph.claimLiteral(element, L0.HasName, name, Bindings.STRING);
159         graph.claimLiteral(diagram, DIA.HasModCount, ++l, Bindings.LONG);
160         return name;
161     }
162
163     public static Resource getDiagramElement(ReadGraph graph, Resource component) throws DatabaseException {
164         if (component == null)
165             return null;
166         DiagramResource DIA = DiagramResource.getInstance(graph);
167         if (graph.isInstanceOf(component, DIA.Element))
168             return component;
169         ModelingResources MOD = ModelingResources.getInstance(graph);
170         Resource element = graph.getPossibleObject(component, MOD.ComponentToElement);
171         return element != null && graph.isInstanceOf(element, DIA.Element) ? element : null;
172     }
173
174     public static Resource getMappedElement(ReadGraph graph, Resource element) throws DatabaseException {
175         if (element == null)
176             return null;
177         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
178         return graph.getPossibleObject(element, DN.MappedComponent);
179     }
180
181     public static Resource getMappedComponent(ReadGraph graph, Resource element) throws DatabaseException {
182         if (element == null)
183             return null;
184         Resource mappedElement = getMappedElement(graph, element);
185         if (mappedElement == null)
186             return null;
187         ModelingResources MOD = ModelingResources.getInstance(graph);
188         return graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
189     }
190     
191     public static Resource getMappedComponentCached(ReadGraph graph, Resource vertex) throws DatabaseException {
192         return graph.syncRequest(new MappedComponentRequest(vertex), TransientCacheListener.instance());
193     }
194
195     public static Resource getMappedDNElement(ReadGraph graph, Resource element) throws DatabaseException {
196         if (element == null)
197             return null;
198         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
199         return graph.getPossibleObject(element, DN.MappedFromElement);
200     }
201
202     public static Variable toMappedConfigurationModule(ReadGraph graph, Resource input) throws DatabaseException {
203         if (input == null)
204             return null;
205
206         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
207         if (graph.isInstanceOf(input, DN.Element)) {
208             Resource mappedElement = getMappedElement(graph, input);
209             if (mappedElement == null)
210                 return null;
211
212             ModelingResources MOD = ModelingResources.getInstance(graph);
213             Resource mappedComponent = graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
214             if (mappedComponent == null)
215                 return null;
216
217             return graph.syncRequest(new PossibleVariable(mappedComponent));
218         }
219         return null;
220     }
221
222     public static void toggleDrawMap(WriteGraph graph, Resource diagram) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
223         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
224         Boolean current = graph.getPossibleRelatedValue(diagram, DN.Diagram_drawMapEnabled, Bindings.BOOLEAN);
225         if (current == null)
226             current = true;
227         graph.claimLiteral(diagram, DN.Diagram_drawMapEnabled, !current, Bindings.BOOLEAN);
228     }
229
230     public static Boolean drawMapEnabled(ReadGraph graph, Resource diagram) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
231         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
232         Boolean current = graph.getPossibleRelatedValue(diagram, DN.Diagram_drawMapEnabled, Bindings.BOOLEAN);
233         return current != null ? current : true;
234     }
235
236     public static void changeMapBackgroundColor(WriteGraph graph, Resource diagram, Integer integer) throws DatabaseException {
237         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
238         graph.claimLiteral(diagram, DN.Diagram_backgroundColor, integer, Bindings.getBindingUnchecked(RGB.Integer.class));
239     }
240     
241     public static Boolean trackChangesEnabled(ReadGraph graph, Resource diagram) throws DatabaseException {
242         if (diagram != null && graph.hasStatement(diagram)) {
243             return Boolean.TRUE.equals(graph.getPossibleRelatedValue(diagram,
244                 DistrictNetworkResource.getInstance(graph).Diagram_trackChangesEnabled));
245         } else {
246             return false;
247         }
248     }
249
250     public static RGB.Integer backgroundColor(ReadGraph graph, Resource diagram) throws DatabaseException {
251         return graph.getPossibleRelatedValue(diagram,
252                 DistrictNetworkResource.getInstance(graph).Diagram_backgroundColor,
253                 Bindings.getBindingUnchecked(RGB.Integer.class));
254     }
255     
256     public static Resource createNetworkDiagram(WriteGraph graph, Resource target, Resource compositeType, String defaultName, Resource defaultEdgeMapping, Resource defaultVertexMapping, Resource rightClickVertexMapping, Resource leftClickVertexMapping, Resource crs) throws DatabaseException {
257         Resource composite = NewCompositeActionFactory.createComposite(graph, target, defaultName, compositeType);
258
259         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
260         Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
261         graph.claim(diagram, DN.EdgeDefaultMapping, defaultEdgeMapping);
262         graph.claim(diagram, DN.VertexDefaultMapping, defaultVertexMapping);
263         graph.claim(diagram, DN.RightClickDefaultMapping, rightClickVertexMapping);
264         graph.claim(diagram, DN.LeftClickDefaultMapping, leftClickVertexMapping);
265         graph.claim(diagram, DN.HasSpatialRefSystem, crs);
266         
267         // Generated name prefix from composite name
268         String compositeName = graph.getRelatedValue2(composite, Layer0.getInstance(graph).HasName, Bindings.STRING);
269         graph.claimLiteral(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix, "N" + compositeName.substring(compositeName.length() - 1, compositeName.length()));
270         
271         return composite;
272     }
273
274     public static final class MappedComponentRequest extends ResourceRead<Resource> {
275         public MappedComponentRequest(Resource element) {
276             super(element);
277         }
278
279         @Override
280         public Resource perform(ReadGraph graph) throws DatabaseException {
281             return getMappedComponent(graph, resource);
282         }
283     }
284
285     public static class ResourceVertex {
286         
287         public final boolean isConsumer;
288         public final Resource vertex;
289         public final double[] coords;
290         
291         public ResourceVertex(Resource vertex, double[] coords, boolean isConsumer) {
292             this.vertex = vertex;
293             this.coords = coords;
294             this.isConsumer = isConsumer;
295         }
296     }
297 }