├── .gitattributes ├── .github └── pull_request_template.md ├── .vscode ├── extensions.json ├── launch.json ├── tasks.json └── settings.json ├── ADTTools ├── RecreateAdtInstance │ ├── requirements.txt │ ├── Makefile │ ├── README.md │ ├── jlog.py │ └── main.py ├── ADTToolsLibrary │ ├── ADTToolsLibrary.csproj │ └── Log.cs ├── UploadModels │ ├── OrderedHashSet.cs │ ├── UploadModels.csproj │ ├── DTInterfaceInfoEqualityComparer.cs │ ├── Options.cs │ └── Program.cs ├── DeleteModels │ ├── DeleteModels.csproj │ ├── Options.cs │ └── Program.cs ├── ADTTools.sln └── Readme.md ├── DTDLValidator ├── global.json ├── DTDLValidator │ ├── Interactive │ │ ├── ExitCommand.cs │ │ ├── ListCommand.cs │ │ ├── ShowCommand.cs │ │ ├── DTDLParser.cs │ │ ├── ShowInfoCommand.cs │ │ ├── Interactive.cs │ │ ├── LoadCommand.cs │ │ └── CompareCommand.cs │ ├── DTDLValidator.csproj │ ├── Log.cs │ └── Program.cs ├── DTDLValidator.sln ├── .vscode │ ├── launch.json │ └── tasks.json └── .gitignore ├── OWL2DTDL ├── Properties │ └── launchSettings.json ├── Log.cs ├── OWL2DTDL.sln ├── OWL2DTDL.csproj ├── .vscode │ ├── launch.json │ └── tasks.json ├── RecIgnoredNames.csv ├── OntologyRestriction.cs ├── .gitignore ├── Relationship.cs ├── VocabularyHelper.cs ├── README.md └── DotNetRdfExtensions.cs ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── .devcontainer ├── scripts │ └── azure-cli.sh ├── devcontainer.json └── Dockerfile ├── README.md ├── SECURITY.md └── .gitignore /.gitattributes: -------------------------------------------------------------------------------- 1 | # Normalize line endings 2 | *.sh text eol=lf 3 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### What 2 | 3 | 4 | ### Why 5 | 6 | 7 | ### Tested 8 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["streetsidesoftware.code-spell-checker"] 3 | } 4 | -------------------------------------------------------------------------------- /ADTTools/RecreateAdtInstance/requirements.txt: -------------------------------------------------------------------------------- 1 | azure-mgmt-digitaltwins>=6.2.0 2 | azure-identity>=1.11.0 3 | tqdm>=4.64.1 4 | halo>=0.0.31 -------------------------------------------------------------------------------- /DTDLValidator/global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "7.0.102", 4 | "rollForward": "feature" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /ADTTools/ADTToolsLibrary/ADTToolsLibrary.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/ExitCommand.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using CommandLine; 4 | 5 | [Verb("exit", HelpText = "Exit CLI.")] 6 | internal class ExitCommand 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ADTTools/RecreateAdtInstance/Makefile: -------------------------------------------------------------------------------- 1 | ## 2 | # Recreate ADT Instance 3 | # 4 | # @file 5 | # @version 1.0 6 | makeFileDir := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) 7 | 8 | init: 9 | pip install -r requirements.txt 10 | clean: 11 | rm -r $(makeFileDir)__pycache__ 12 | # end 13 | -------------------------------------------------------------------------------- /OWL2DTDL/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "OWL2DTDL": { 4 | "commandName": "Project", 5 | "commandLineArgs": "-u https://w3id.org/rec/full/3.3/ -i ./RecIgnoredNames.csv -o C:\\Users\\karlh\\Scratch\\Git\\opendigitaltwins-building\\Ontology" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /ADTTools/UploadModels/OrderedHashSet.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | 4 | namespace UploadModels 5 | { 6 | internal class OrderedHashSet : KeyedCollection 7 | { 8 | public OrderedHashSet() 9 | { 10 | } 11 | 12 | public OrderedHashSet(IEqualityComparer comparer) 13 | : base(comparer) 14 | { 15 | } 16 | 17 | protected override T GetKeyForItem(T item) 18 | { 19 | return item; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ADTTools/DeleteModels/DeleteModels.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /ADTTools/DeleteModels/Options.cs: -------------------------------------------------------------------------------- 1 | using CommandLine; 2 | 3 | namespace DeleteModels 4 | { 5 | internal class Options 6 | { 7 | [Option('t', "tenantId", Required = true, HelpText = "The application's tenant id for connecting to Azure Digital Twins.")] 8 | public string TenantId { get; set; } 9 | 10 | [Option('c', "clientId", Required = true, HelpText = "The application's client id for connecting to Azure Digital Twins.")] 11 | public string ClientId { get; set; } 12 | 13 | [Option('h', "hostName", Required = true, HelpText = "The host name of your Azure Digital Twins instance.")] 14 | public string HostName { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /OWL2DTDL/Log.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace OWL2DTDL 4 | { 5 | public static class Log 6 | { 7 | static public void Out(string s, ConsoleColor col = ConsoleColor.White) 8 | { 9 | Console.ForegroundColor = col; 10 | Console.WriteLine(s); 11 | Console.ForegroundColor = ConsoleColor.White; 12 | } 13 | 14 | static public void Error(string s) 15 | { 16 | Out(s, ConsoleColor.DarkRed); 17 | } 18 | 19 | static public void Alert(string s) 20 | { 21 | Out(s, ConsoleColor.DarkYellow); 22 | } 23 | 24 | static public void Ok(string s) 25 | { 26 | Out(s, ConsoleColor.DarkGreen); 27 | } 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/DTDLValidator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | true 7 | dtdl-validator 8 | ./nupkg 9 | true 10 | win-x64 11 | true 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /ADTTools/ADTToolsLibrary/Log.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ADTToolsLibrary 4 | { 5 | public static class Log 6 | { 7 | static public void Write(string s, ConsoleColor col = ConsoleColor.White) 8 | { 9 | Console.ForegroundColor = col; 10 | Console.WriteLine(s); 11 | Console.ResetColor(); 12 | } 13 | 14 | static public void Error(string s) 15 | { 16 | Write(s, ConsoleColor.DarkRed); 17 | } 18 | 19 | static public void Warning(string s) 20 | { 21 | Write(s, ConsoleColor.DarkYellow); 22 | } 23 | 24 | static public void Ok(string s) 25 | { 26 | Write(s, ConsoleColor.DarkGreen); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ADTTools/UploadModels/UploadModels.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to 4 | agree to a Contributor License Agreement (CLA) declaring that you have the right to, 5 | and actually do, grant us the rights to use your contribution. For details, visit 6 | https://cla.microsoft.com. 7 | 8 | When you submit a pull request, a CLA-bot will automatically determine whether you need 9 | to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the 10 | instructions provided by the bot. You will only need to do this once across all repositories using our CLA. 11 | 12 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 13 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 14 | or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 15 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/ListCommand.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using CommandLine; 4 | using Microsoft.Azure.DigitalTwins.Parser.Models; 5 | using System; 6 | using System.Threading.Tasks; 7 | 8 | [Verb("list", HelpText = "List models.")] 9 | internal class ListCommand 10 | { 11 | public Task Run(Interactive p) 12 | { 13 | Console.WriteLine(listFormat, "Interface Id", "Display Name"); 14 | Console.WriteLine(listFormat, "------------", "------------"); 15 | foreach (DTInterfaceInfo @interface in p.Models.Values) 16 | { 17 | @interface.DisplayName.TryGetValue("en", out string displayName); 18 | Console.WriteLine(listFormat, @interface.Id.AbsoluteUri, displayName ?? ""); 19 | } 20 | 21 | return Task.FromResult(null); 22 | } 23 | 24 | private const string listFormat = "{0,-80}{1}"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Log.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator 2 | { 3 | using System; 4 | 5 | public static class Log 6 | { 7 | static public void Out(string s, ConsoleColor col = ConsoleColor.White) 8 | { 9 | Console.ForegroundColor = col; 10 | Console.WriteLine(s); 11 | Console.ForegroundColor = ConsoleColor.White; 12 | } 13 | 14 | static public void Error(string s) 15 | { 16 | Out(s, ConsoleColor.DarkRed); 17 | } 18 | 19 | static public void Alert(string s) 20 | { 21 | Out(s, ConsoleColor.DarkYellow); 22 | } 23 | 24 | static public void Ok(string s) 25 | { 26 | Out(s, ConsoleColor.DarkGreen); 27 | } 28 | 29 | static public void Error(Exception ex, string s) 30 | { 31 | var exception = s + "\n" + ex.ToString(); 32 | Out(exception, ConsoleColor.DarkRed); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ADTTools/UploadModels/DTInterfaceInfoEqualityComparer.cs: -------------------------------------------------------------------------------- 1 | using DTDLParser.Models; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.CodeAnalysis; 4 | 5 | namespace UploadModels 6 | { 7 | internal class DTInterfaceInfoEqualityComparer : IEqualityComparer 8 | { 9 | public bool Equals([AllowNull] DTInterfaceInfo x, [AllowNull] DTInterfaceInfo y) 10 | { 11 | if (ReferenceEquals(x, null) && ReferenceEquals(y, null)) 12 | { 13 | return true; 14 | } 15 | else if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) 16 | { 17 | return false; 18 | } 19 | else 20 | { 21 | return x.Id.Equals(y.Id); 22 | } 23 | } 24 | 25 | public int GetHashCode([DisallowNull] DTInterfaceInfo obj) 26 | { 27 | return obj.Id.GetHashCode(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) Microsoft Corporation. 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.devcontainer/scripts/azure-cli.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | # Copyright (c) Microsoft Corporation. 4 | # Licensed under the MIT license. 5 | 6 | CMD=az 7 | NAME="Azure CLI" 8 | 9 | echo -e "\e[34m»»» 📦 \e[32mInstalling \e[33m$NAME\e[0m ..." 10 | 11 | # https://docs.microsoft.com/cli/azure/install-azure-cli-linux?pivots=apt#option-2-step-by-step-installation-instructions 12 | 13 | sudo apt-get update 14 | sudo apt-get install ca-certificates curl apt-transport-https lsb-release gnupg 15 | 16 | curl -sL https://packages.microsoft.com/keys/microsoft.asc | 17 | gpg --dearmor | 18 | sudo tee /etc/apt/trusted.gpg.d/microsoft.gpg >/dev/null 19 | 20 | AZ_REPO=$(lsb_release -cs) 21 | echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | 22 | sudo tee /etc/apt/sources.list.d/azure-cli.list 23 | 24 | sudo apt-get update 25 | sudo apt-get install azure-cli 26 | 27 | # Install cli extension(s) 28 | echo -e "\n\e[34m»»» 🔐 \e[32mAdding webapp authV2 extension" 29 | az extension add --name authV2 --system 30 | 31 | echo -e "\n\e[34m»»» 💾 \e[32mInstalled to: \e[33m$(which $CMD)" 32 | echo -e "\e[34m»»» 💡 \e[32mVersion details: \e[39m$($CMD --version)" 33 | -------------------------------------------------------------------------------- /OWL2DTDL/OWL2DTDL.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30114.105 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OWL2DTDL", "OWL2DTDL.csproj", "{878ABCD8-CA64-4752-A601-75AE8FCAA695}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {878ABCD8-CA64-4752-A601-75AE8FCAA695}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {878ABCD8-CA64-4752-A601-75AE8FCAA695}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {878ABCD8-CA64-4752-A601-75AE8FCAA695}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {878ABCD8-CA64-4752-A601-75AE8FCAA695}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {6EAFFD29-25C7-4E0F-963A-0DD3D8F0BF30} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30011.22 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTDLValidator", "DTDLValidator\DTDLValidator.csproj", "{97A2EE2B-0FB4-4D61-A7BC-8A2FC166425E}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {97A2EE2B-0FB4-4D61-A7BC-8A2FC166425E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {97A2EE2B-0FB4-4D61-A7BC-8A2FC166425E}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {97A2EE2B-0FB4-4D61-A7BC-8A2FC166425E}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {97A2EE2B-0FB4-4D61-A7BC-8A2FC166425E}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {29693B31-2D04-4C59-99AD-12F65B833EF6} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /OWL2DTDL/OWL2DTDL.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | Project 10 | -u https://w3id.org/rec/full/3.3/ -i ./RecIgnoredNames.csv -s rec_3_3 -o /Users/karl/Documents/GitHub/Azure/opendigitaltwins-building/Ontology 11 | true 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Always 23 | 24 | 25 | Always 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /DTDLValidator/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/DTDLValidator/bin/Debug/netcoreapp3.1/DTDLValidator.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/DTDLValidator", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach", 24 | "processId": "${command:pickProcess}" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /OWL2DTDL/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/bin/Debug/net6.0/OWL2DTDL.dll", 14 | "args": ["-u", "https://w3id.org/rec/full/3.3/", "-o", "/Users/karl/Desktop/DTDL/"], 15 | "cwd": "${workspaceFolder}", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach", 24 | "processId": "${command:pickProcess}" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/ShowCommand.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using CommandLine; 4 | using Microsoft.Azure.DigitalTwins.Parser; 5 | using Microsoft.Azure.DigitalTwins.Parser.Models; 6 | using System; 7 | using System.Threading.Tasks; 8 | 9 | [Verb("show", HelpText = "Display model definition.")] 10 | internal class ShowCommand 11 | { 12 | [Value(0, HelpText = "Model id to show.")] 13 | public string ModelId { get; set; } 14 | 15 | public Task Run(Interactive p) 16 | { 17 | if (ModelId == null) 18 | { 19 | Log.Error("Please specify a valid model id"); 20 | return Task.FromResult(null); 21 | } 22 | 23 | try 24 | { 25 | Dtmi modelId = new Dtmi(ModelId); 26 | 27 | if (p.Models.TryGetValue(modelId, out DTInterfaceInfo @interface)) 28 | { 29 | Console.WriteLine(@interface.GetJsonLdText()); 30 | } 31 | } 32 | catch (Exception) 33 | { 34 | Log.Error($"{ModelId} is not a valid dtmi"); 35 | } 36 | 37 | return Task.FromResult(null); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/OWL2DTDL/bin/Debug/netcoreapp3.1/OWL2DTDL.dll", 14 | "args": ["-u","https://w3id.org/rec/full/3.3/","-o","${workspaceFolder}/../opendigitaltwins-building/Ontology","-i","RecIgnoredNames.csv","-s","rec_3_3"], 15 | "cwd": "${workspaceFolder}/OWL2DTDL", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach", 24 | "processId": "${command:pickProcess}" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /OWL2DTDL/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/OWL2DTDL.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/OWL2DTDL.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/OWL2DTDL.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/OWL2DTDL/OWL2DTDL.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/OWL2DTDL/OWL2DTDL.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/OWL2DTDL/OWL2DTDL.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /ADTTools/RecreateAdtInstance/README.md: -------------------------------------------------------------------------------- 1 | # Recreate Digital Twins Instance 2 | 3 | This project has been created to quickly delete and recreate ADT instance with the same instance name. This allows 4 | instances to be recreated without having the use a different host endpoint for the ADT instance. Additionally, this 5 | will also recreate endpoints. 6 | 7 | - **Note**: Endpoint Retention is based on the assumption that endpoints have originally been created using **identity** 8 | based authentication. 9 | 10 | ## Requirements 11 | - Currently, functionality has been verified only with Python **3.10** or higher. 12 | - On Windows, verify that the System PATH variable contains only one Python version. By going to `System Properties -> Advanced -> Environment`. If installing Python for the first time, a system restart may be required. 13 | 14 | ## Usage 15 | ### Install Dependencies 16 | Run: 17 | 18 | ```shell 19 | pip install -r requirements.txt 20 | ``` 21 | This will install required dependencies for this script. However, you can also simply just run `make` if you have **make** 22 | installed on your machine. 23 | 24 | ### Run Script 25 | Run: 26 | 27 | ```shell 28 | python main.py 29 | ``` 30 | 31 | The DigitalTwins instance name, subscription id, and resource groups are required arguments for use. 32 | - **Note**: The instance name refers to the name of the ADT instance, not the host name. -------------------------------------------------------------------------------- /DTDLValidator/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/DTDLValidator/DTDLValidator.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/DTDLValidator/DTDLValidator.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/DTDLValidator/DTDLValidator.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /ADTTools/RecreateAdtInstance/jlog.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from tqdm import tqdm 4 | from halo import Halo 5 | 6 | 7 | class ProgressBar: 8 | @staticmethod 9 | def new(total, msg): 10 | return tqdm(total=total, 11 | desc=msg, 12 | leave=False, 13 | bar_format="{l_bar}{bar}", 14 | colour="yellow") 15 | 16 | 17 | class Spinner: 18 | @staticmethod 19 | def new(msg): 20 | return Halo(text=msg, spinner="dots", placement="right") 21 | 22 | 23 | class LogFormat(logging.Formatter): 24 | grey = "\x1b[38;20m" 25 | green = "\x1b[32;20m" 26 | yellow = "\x1b[33;20m" 27 | red = "\x1b[31;20m" 28 | bold_red = "\x1b[31;1m" 29 | reset = "\x1b[0m" 30 | format = "%(levelname)s - %(asctime)s - %(name)s: %(message)s" 31 | 32 | FORMATS = { 33 | logging.DEBUG: green + format + reset, 34 | logging.INFO: green + format + reset, 35 | logging.WARNING: yellow + format + reset, 36 | logging.ERROR: red + format + reset, 37 | logging.CRITICAL: bold_red + format + reset 38 | } 39 | 40 | def format(self, record): 41 | log_fmt = self.FORMATS.get(record.levelno) 42 | formatter = logging.Formatter(log_fmt) 43 | return formatter.format(record) 44 | 45 | 46 | logger = logging.getLogger("RecreateAdtInstance") 47 | logger.setLevel(logging.DEBUG) 48 | 49 | console_handler = logging.StreamHandler() 50 | console_handler.setLevel(logging.DEBUG) 51 | console_handler.setFormatter(LogFormat()) 52 | 53 | logger.addHandler(console_handler) 54 | -------------------------------------------------------------------------------- /OWL2DTDL/RecIgnoredNames.csv: -------------------------------------------------------------------------------- 1 | https://w3id.org/rec/actuation/;Actuations are handled through creating Command objects from instance graphs 2 | https://w3id.org/rec/dataschemas/;Data schema logic is handled when creating Command and Telemetry objects 3 | https://w3id.org/rec/device/SensorInterface;Sensor interfaces are handled through creating Telemetry objects from instance graphs 4 | https://w3id.org/rec/core/MeasurementUnit;Measurement units and quantity kinds are handled through mapping to DTDL semantic types when creating Telemetry objects 5 | https://w3id.org/rec/core/QuantityKind; 6 | https://w3id.org/rec/core/DataSchema;Data schemas will be handled through Telemetry and Command generation 7 | http://qudt.org/;QUDT-based datatypes are used to generate DTDL Semantic Types; they are not themselves translated to interfaces 8 | https://w3id.org/rec/analytics/;REC analytics are out-of-scope for DTDL models 9 | https://w3id.org/rec/device/Communication;REC device communications are out-of-scope for DTDL models 10 | https://w3id.org/rec/device/DeviceEvents;The REC observation and device event models are out-of-scope for DTDL models 11 | https://w3id.org/rec/core/Observation;The REC observation and device event models are out-of-scope for DTDL models 12 | https://w3id.org/rec/device/PlacementContext;REC placement contexts should probably be expressed as properties in DTDL 13 | https://w3id.org/rec/core/SensorInterface;Sensor interface relates to the sensor schema, which is a DTDL language feature 14 | http://www.opengis.net/ont/geosparql#Geometry; 15 | https://w3id.org/rec/core/Software; 16 | https://w3id.org/rec/core/Service; 17 | https://w3id.org/rec/asset/ElectricalCircuit;Filtered out for v1.0 of DTDL model set, at Willow's request, until we figure out where it belongs. 18 | https://w3id.org/rec/agents/name;Filtered out in preference of generic top-level name property added by OWL2DTDL. -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "autopep8.args": ["--max-line-length=120"], 3 | "debug.internalConsoleOptions": "neverOpen", 4 | "cSpell.words": [ 5 | "autobuild", 6 | "azcli", 7 | "codespaces", 8 | "devcontainer", 9 | "digitaltwins", 10 | "dtdl", 11 | "dtmi", 12 | "entra", 13 | "historize", 14 | "localtime", 15 | "opendigitaltwins", 16 | "tflint" 17 | ], 18 | "editor.defaultFormatter": "esbenp.prettier-vscode", 19 | "editor.insertSpaces": true, 20 | "editor.formatOnSave": true, 21 | "editor.formatOnSaveMode": "modifications", 22 | "files.associations": { 23 | "*.workbook": "jsonc", 24 | ".git*": "shellscript" 25 | }, 26 | "files.watcherExclude": { 27 | "**/.git/objects/**": true, 28 | "**/.git/subtree-cache/**": true, 29 | "**/node_modules/*/**": true, 30 | "**/.python_packages/*/**": true, 31 | "**/bin/**": true, 32 | "**/obj/**": true 33 | }, 34 | "python.languageServer": "Pylance", 35 | "[dockerfile]": { 36 | "editor.defaultFormatter": "ms-azuretools.vscode-docker" 37 | }, 38 | "[dotenv]": { 39 | "editor.defaultFormatter": "foxundermoon.shell-format" 40 | }, 41 | "[ignore]": { 42 | "editor.defaultFormatter": "foxundermoon.shell-format" 43 | }, 44 | "[json]": { 45 | "editor.tabSize": 2 46 | }, 47 | "[jsonc]": { 48 | "editor.tabSize": 2 49 | }, 50 | "[markdown]": { 51 | "editor.wordWrap": "on" 52 | }, 53 | "[powershell]": { 54 | "editor.defaultFormatter": "ms-vscode.powershell", 55 | "editor.tabSize": 2 56 | }, 57 | "[python]": { 58 | "editor.defaultFormatter": "ms-python.autopep8" 59 | }, 60 | "[shellscript]": { 61 | "editor.defaultFormatter": "foxundermoon.shell-format" 62 | }, 63 | "markdown.updateLinksOnFileMove.enabled": "prompt", 64 | "markdown.updateLinksOnFileMove.enableForDirectories": true, 65 | "prettier.tabWidth": 2, 66 | "prettier.printWidth": 120, 67 | "prettier.arrowParens": "avoid", 68 | "prettier.trailingComma": "es5" 69 | } 70 | -------------------------------------------------------------------------------- /ADTTools/UploadModels/Options.cs: -------------------------------------------------------------------------------- 1 | using CommandLine; 2 | using System.Collections.Generic; 3 | 4 | namespace UploadModels 5 | { 6 | internal class Options 7 | { 8 | [Option('d', "useDefaultAzureCredentials", SetName = "upload", Required = false, HelpText = "If this flag is set to true, DefaultAzureCredentials will be used.")] 9 | public bool UseDefaultAzureCredentials { get; set; } = false; 10 | 11 | [Option('e', "allowUndefinedExtensions", SetName = "upload", Required = false, HelpText = "If this flag is set to true, the parser will allow Undefined Extensions in the DTDL.")] 12 | public bool AllowUndefinedExtensions { get; set; } = false; 13 | 14 | [Option('t', "tenantId", SetName = "upload", Required = false, HelpText = "The application's tenant id for connecting to Azure Digital Twins.")] 15 | public string TenantId { get; set; } 16 | 17 | [Option('c', "clientId", SetName = "upload", Required = false, HelpText = "The application's client id for connecting to Azure Digital Twins.")] 18 | public string ClientId { get; set; } 19 | 20 | [Option('s', "clientSecret", SetName = "upload", Required = false, HelpText = "The application's client secret for connecting to Azure Digital Twins.")] 21 | public string ClientSecret { get; set; } 22 | 23 | [Option('h', "hostName", SetName = "upload", Required = true, HelpText = "The host name of your Azure Digital Twins instance.")] 24 | public string HostName { get; set; } 25 | 26 | [Option('b', "batchSize", SetName = "upload", Default = 100, HelpText = "The maximum number of models uploaded in each batch (default 100).")] 27 | public int BatchSize { get; set; } 28 | 29 | [Option('w', "whatIf", SetName = "whatif", Required = true, Default = false, HelpText = "Display the order of the models that would be uploaded, but do not upload.")] 30 | public bool WhatIf { get; set; } 31 | 32 | [Value(0, Required = true, HelpText = "Model file names to upload (supports globs).")] 33 | public IEnumerable FileSpecs { get; set; } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ADTTools/DeleteModels/Program.cs: -------------------------------------------------------------------------------- 1 | using ADTToolsLibrary; 2 | using Azure; 3 | using Azure.DigitalTwins.Core; 4 | using Azure.Identity; 5 | using CommandLine; 6 | using System; 7 | using System.Linq; 8 | using System.Net; 9 | 10 | namespace DeleteModels 11 | { 12 | class Program 13 | { 14 | private readonly Options options; 15 | 16 | static void Main(string[] args) 17 | { 18 | Parser.Default.ParseArguments(args).WithParsed(options => new Program(options).Run()); 19 | } 20 | 21 | private Program(Options options) 22 | { 23 | this.options = options; 24 | } 25 | 26 | private void Run() 27 | { 28 | try 29 | { 30 | var credential = new InteractiveBrowserCredential(options.TenantId, options.ClientId); 31 | var client = new DigitalTwinsClient(new UriBuilder("https", options.HostName).Uri, credential); 32 | DeleteAllModels(client, 1); 33 | } 34 | catch (Exception ex) 35 | { 36 | Log.Error($"Deleting models failed."); 37 | Log.Error(ex.Message); 38 | } 39 | } 40 | 41 | private void DeleteAllModels(DigitalTwinsClient client, int iteration) 42 | { 43 | foreach (DigitalTwinsModelData modelData in client.GetModels()) 44 | { 45 | try 46 | { 47 | client.DeleteModel(modelData.Id); 48 | Log.Ok($"Deleted model '{modelData.Id}' (Iteration {iteration})"); 49 | } 50 | catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict) 51 | { 52 | // This model is a dependent and will be deleted in the next iteration. 53 | } 54 | catch (Exception ex) 55 | { 56 | Log.Error($"Failed to delete model '{modelData.Id}': {ex.Message}"); 57 | } 58 | } 59 | 60 | if (client.GetModels().Any()) 61 | { 62 | DeleteAllModels(client, iteration + 1); 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/DTDLParser.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using Microsoft.Azure.DigitalTwins.Parser; 4 | using Microsoft.Azure.DigitalTwins.Parser.Models; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | 8 | internal class DTDLParser 9 | { 10 | public DTDLParser(IDictionary modelStore) 11 | { 12 | this.modelStore = modelStore; 13 | } 14 | 15 | public async Task<(IReadOnlyDictionary, IEnumerable)> ParseAsync(IEnumerable jsonTexts) 16 | { 17 | // Create resolver state per call to ParseAsync so that multiple calls to ParseAsync can run concurrently. 18 | DTDLResolver dtdlResolver = new DTDLResolver(modelStore); 19 | parser.DtmiResolver = new DtmiResolver(dtdlResolver.Resolver); 20 | IReadOnlyDictionary entities = await parser.ParseAsync(jsonTexts); 21 | return (entities, dtdlResolver.ResolvedInterfaces); 22 | } 23 | 24 | private class DTDLResolver 25 | { 26 | public DTDLResolver(IDictionary modelStore) 27 | { 28 | this.modelStore = modelStore; 29 | } 30 | 31 | public IEnumerable Resolver(IReadOnlyCollection dtmis) 32 | { 33 | List texts = new List(); 34 | foreach (Dtmi dtmi in dtmis) 35 | { 36 | if (modelStore.TryGetValue(dtmi, out DTInterfaceInfo @interface)) 37 | { 38 | ResolvedInterfaces.Add(@interface); 39 | texts.Add(@interface.GetJsonLdText()); 40 | } 41 | } 42 | 43 | return texts; 44 | } 45 | 46 | public IList ResolvedInterfaces { get; private set; } = new List(); 47 | 48 | private readonly IDictionary modelStore; 49 | } 50 | 51 | private readonly ModelParser parser = new ModelParser(); 52 | private readonly IDictionary modelStore; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tools for Open Digital Twins Definition Language (DTDL) Based Ontologies 2 | 3 | ## Overview 4 | 5 | [Azure Digital Twins (ADT)](https://azure.microsoft.com/en-us/services/digital-twins/), and its underlying [Digital Twins Definition Language (DTDL)](https://github.com/Azure/opendigitaltwins-dtdl), enable modeling of your world in terms aligning to others in your industry vertical, or with a custom definition of your own making. The ability to historize, visualize and interact in near real time unlocks many possibilities creating a better tomorrow. 6 | 7 | This open-source set of tools can operate on any DTDL ontology, including, as an example, the [Real Estate Core](https://github.com/RealEstateCore/rec) ontology. 8 | 9 | ## ADT Tools 10 | 11 | The [ADTTools](./ADTTools/Readme.md) solution is a collection of tools to aid the creation and deletion of an ADT instance. 12 | 13 | ### Uploading Models to Azure Digital Twins 14 | 15 | The `UploadModels` tool is to add an ontology to your own ADT instance. Follow [these instructions](./ADTTools/Readme.md#uploadmodels) for details and refer to [this article](https://docs.microsoft.com/en-us/azure/digital-twins/how-to-manage-model) on managing models for more details. 16 | 17 | ### Deleting Models in Bulk 18 | 19 | The `DeleteModels` tool is if you want to remove models from an ADT instance for a clean start without having to recreate your ADT instance. Instructions are available [here](./ADTTools/Readme.md#deletemodels). 20 | 21 | ### Recreating an Azure Digital Twins Instance 22 | 23 | The `RecreateAdtInstance` tool is if you want to tear down and rebuild your ADT instance as an exact replica of what it was before deletion (excluding history). Refer to the [readme](./ADTTools/RecreateAdtInstance/README.md) for more information. 24 | 25 | ## Validating the Models 26 | 27 | The `DTDLValidator` tool aids in the creation of manually crafting DTDL models ensuring compatible formatting with Azure Digital Twins and the DTDL specification. You can lear more about model validation [here.](https://learn.microsoft.com/en-us/azure/digital-twins/concepts-models#validate-models). 28 | 29 | ## OWL to DTDL Conversion 30 | 31 | The `OWL2DTDL` tool is a converter between an OWL ontology or an ontology network (one root ontology reusing other ontologies through `owl:imports` declarations) into a set of DTDL Interface declarations for use with Azure Digital Twins. Learn more in this [readme](./OWL2DTDL/README.md) 32 | -------------------------------------------------------------------------------- /ADTTools/ADTTools.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31229.75 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UploadModels", "UploadModels\UploadModels.csproj", "{147FC65A-1653-4E66-982E-CC524523AE29}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ADTToolsLibrary", "ADTToolsLibrary\ADTToolsLibrary.csproj", "{D51B20C1-F002-457F-9E20-D37146181723}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeleteModels", "DeleteModels\DeleteModels.csproj", "{B4F2A68B-11DC-48F2-A489-9F75D46EDD55}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{639464E5-56C0-4C27-BDEC-B23007B04118}" 13 | ProjectSection(SolutionItems) = preProject 14 | Readme.md = Readme.md 15 | EndProjectSection 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {147FC65A-1653-4E66-982E-CC524523AE29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {147FC65A-1653-4E66-982E-CC524523AE29}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {147FC65A-1653-4E66-982E-CC524523AE29}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {147FC65A-1653-4E66-982E-CC524523AE29}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {D51B20C1-F002-457F-9E20-D37146181723}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {D51B20C1-F002-457F-9E20-D37146181723}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {D51B20C1-F002-457F-9E20-D37146181723}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {D51B20C1-F002-457F-9E20-D37146181723}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {B4F2A68B-11DC-48F2-A489-9F75D46EDD55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {B4F2A68B-11DC-48F2-A489-9F75D46EDD55}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {B4F2A68B-11DC-48F2-A489-9F75D46EDD55}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {B4F2A68B-11DC-48F2-A489-9F75D46EDD55}.Release|Any CPU.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(SolutionProperties) = preSolution 37 | HideSolutionNode = FALSE 38 | EndGlobalSection 39 | GlobalSection(ExtensibilityGlobals) = postSolution 40 | SolutionGuid = {ABEE0472-7C22-45EE-9899-C93C741A12C4} 41 | EndGlobalSection 42 | EndGlobal 43 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd). 40 | 41 | -------------------------------------------------------------------------------- /ADTTools/Readme.md: -------------------------------------------------------------------------------- 1 | # Azure Digital Twins tools 2 | 3 | This set of tools is designed to make it easy to manage DTDL ontologies with the Azure Digital Twins service. 4 | 5 | ## UploadModels 6 | 7 | UploadModels is used to upload an ontology (set of models) into an Azure Digital Twins service instance. The tool accepts a list of models (including wildcard and glob support), validates the models using the digital twins parser, orders the models so that "root" models are uploaded first, and then uploads models in batches for fast uploading. 8 | 9 | ### Usage 10 | 11 | `UploadModels [options] ` 12 | 13 | ### Options 14 | 15 | Upload 16 | - `-t` or `--tenantId`: The id (GUID) of your tenant or directory in Azure. 17 | - `-c` or `--clientId`: The id (GUID) of an Azure Active Directory app registration. See [Create an app registration to use with Azure Digital Twins](https://docs.microsoft.com/en-us/azure/digital-twins/how-to-create-app-registration) for more information. 18 | - `-h` or `--hostName`: The host name of your Azure Digital Twins service instance (no https prefix needed). 19 | 20 | Test 21 | - `-w` or `--whatIf`: When set, without the upload options, displays an ordered list of the models that would be uploaded. 22 | 23 | ### File list 24 | 25 | - fileList: A list of model file names that supports wildcards and globs. 26 | 27 | ### Example usage 28 | 29 | - Upload one model: `UploadModels -t 42a9ff5e-dd3a-4a89-8d92-2a7eaadbfcaa -c 198783fb-4301-4983-a12f-4eefb696282d -h briancr-ms.api.wcus.digitaltwins.azure.net .\MyModel.json` 30 | - Upload an ontology: `UploadModels -t 42a9ff5e-dd3a-4a89-8d92-2a7eaadbfcaa -c 198783fb-4301-4983-a12f-4eefb696282d -h briancr-ms.api.wcus.digitaltwins.azure.net \Ontology\**\*.json` 31 | - Display an ordered list of models that would be uploaded: `UploadModels -w \Ontology\**\*.json` 32 | 33 | ## DeleteModels 34 | 35 | DeleteModels is used to delete all the models in an Azure Digital Twins service instance. The tool deletes the models recursively so that "leaf" models are deleted first and "root" models are deleted last. 36 | 37 | ### Usage 38 | 39 | `DeleteModels [options]` 40 | 41 | ### Options 42 | 43 | - `-t` or `--tenantId`: The id (GUID) of your tenant or directory in Azure. 44 | - `-c` or `--clientId`: The id (GUID) of an Azure Active Directory app registration. See [Create an app registration to use with Azure Digital Twins](https://docs.microsoft.com/en-us/azure/digital-twins/how-to-create-app-registration) for more information. 45 | - `-h` or `--hostName`: The host name of your Azure Digital Twins service instance (no https prefix needed). 46 | 47 | ### Example usage 48 | 49 | - Delete all models: `DeleteModels -t 42a9ff5e-dd3a-4a89-8d92-2a7eaadbfcaa -c 198783fb-4301-4983-a12f-4eefb696282d -h briancr-ms.api.wcus.digitaltwins.azure.net` 50 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/ShowInfoCommand.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using CommandLine; 4 | using Microsoft.Azure.DigitalTwins.Parser; 5 | using Microsoft.Azure.DigitalTwins.Parser.Models; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | 11 | [Verb("showinfo", HelpText = "Display parent interfaces, properties and relationships defined in a model, taking inheritance into account")] 12 | internal class ShowInfoCommand 13 | { 14 | [Value(0, HelpText = "Model id to show.")] 15 | public string ModelId { get; set; } 16 | 17 | public Task Run(Interactive p) 18 | { 19 | if (ModelId == null) 20 | { 21 | Log.Error("Please specify a valid model id"); 22 | return Task.FromResult(null); 23 | } 24 | 25 | try 26 | { 27 | Dtmi modelId = new Dtmi(ModelId); 28 | 29 | if (p.Models.TryGetValue(modelId, out DTInterfaceInfo dti)) 30 | { 31 | Log.Ok("Inherited interfaces:"); 32 | foreach (DTInterfaceInfo parent in dti.Extends) 33 | { 34 | Log.Ok($" {parent.Id}"); 35 | } 36 | 37 | IReadOnlyDictionary contents = dti.Contents; 38 | Log.Alert($" Properties:"); 39 | var props = contents 40 | .Where(p => p.Value.EntityKind == DTEntityKind.Property) 41 | .Select(p => p.Value); 42 | foreach (DTPropertyInfo pi in props) 43 | { 44 | pi.Schema.DisplayName.TryGetValue("en", out string displayName); 45 | Log.Out($" {pi.Name}: {displayName ?? pi.Schema.ToString()}"); 46 | } 47 | 48 | Log.Out($" Relationships:", ConsoleColor.DarkMagenta); 49 | var rels = contents 50 | .Where(p => p.Value.EntityKind == DTEntityKind.Relationship) 51 | .Select(p => p.Value); 52 | foreach (DTRelationshipInfo ri in rels) 53 | { 54 | string target = ""; 55 | if (ri.Target != null) 56 | target = ri.Target.ToString(); 57 | Log.Out($" {ri.Name} -> {target}"); 58 | } 59 | } 60 | } 61 | catch (Exception) 62 | { 63 | Log.Error($"{ModelId} is not a valid dtmi"); 64 | } 65 | 66 | return Task.FromResult(null); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/dotnet 3 | { 4 | "name": "opendigitaltwins-tools", 5 | "build": { 6 | "dockerfile": "Dockerfile" 7 | }, 8 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 9 | "forwardPorts": [5000, 5001], 10 | "portsAttributes": { 11 | "5001": { 12 | "protocol": "https" 13 | } 14 | }, 15 | "runArgs": [ 16 | "--network", "host", "--cap-add", "NET_ADMIN" // use host networking so that the dev container can access the API when running the container locally 17 | ], 18 | 19 | "mounts": [ 20 | // Keep command history 21 | "type=volume,source=opendigitaltwins-tools-bashhistory,target=/home/codespace/commandhistory", 22 | // Mounts the login details from the host machine to azcli works in the container 23 | "type=bind,source=${env:HOME}${env:USERPROFILE}/.azure,target=/home/codespace/.azure", 24 | // Mount docker socket for docker builds 25 | "type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock" 26 | ], 27 | "customizations": { 28 | "vscode": { 29 | "settings": { 30 | // Only place settings here to enable devcontainer functionality. 31 | // Settings for both local and devcontainer should be placed 32 | // in .vscode/settings.json to enable identical behavior. 33 | "python.pythonPath": "/opt/conda/envs/development/bin/python", 34 | "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", 35 | "python.formatting.blackPath": "/usr/local/py-utils/bin/black", 36 | "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf" 37 | }, 38 | // Add extensions you want installed when the container is created into this array 39 | "extensions": [ 40 | "DavidAnson.vscode-markdownlint", 41 | "eamodio.gitlens", 42 | "esbenp.prettier-vscode", 43 | "foxundermoon.shell-format", 44 | "GitHub.copilot-chat", 45 | "GitHub.copilot", 46 | "github.vscode-github-actions", 47 | "hediet.vscode-drawio", 48 | "mechatroner.rainbow-csv", 49 | "mhutchie.git-graph", 50 | "ms-azure-devops.azure-pipelines", 51 | "ms-azuretools.azure-dev", 52 | "ms-azuretools.vscode-azureresourcegroups", 53 | "ms-azuretools.vscode-azurestorage", 54 | "ms-azuretools.vscode-docker", 55 | "ms-dotnettools.csdevkit", 56 | "ms-dotnettools.csharp", 57 | "ms-python.autopep8", 58 | "ms-python.mypy", 59 | "ms-python.pylint", 60 | "ms-python.python", 61 | "ms-python.vscode-pylance", 62 | "ms-toolsai.jupyter", 63 | "ms-vscode.makefile-tools", 64 | "ms-vscode.powershell", 65 | "msazurermtools.azurerm-vscode-tools", 66 | "mutantdino.resourcemonitor", 67 | "redhat.vscode-yaml", 68 | "streetsidesoftware.code-spell-checker" 69 | ] 70 | } 71 | }, 72 | "remoteUser": "codespace" 73 | } 74 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/Interactive.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using CommandLine; 4 | using Microsoft.Azure.DigitalTwins.Parser; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Threading.Tasks; 8 | using System.Linq; 9 | using Microsoft.Azure.DigitalTwins.Parser.Models; 10 | 11 | class Interactive 12 | { 13 | public Interactive() 14 | { 15 | DTDLParser = new DTDLParser(Models); 16 | Task.WaitAll(Run()); 17 | } 18 | 19 | public IDictionary Models { get; private set; } = new Dictionary(); 20 | 21 | public DTDLParser DTDLParser { get; private set; } 22 | 23 | private async Task Run() 24 | { 25 | Console.WriteLine("DTDLValidator Interactive Mode"); 26 | bool exit = false; 27 | while (!exit) 28 | { 29 | Console.WriteLine(); 30 | Console.Write("> "); 31 | string commandLine = Console.ReadLine(); 32 | Task commandTask = Task.FromResult(null); 33 | Parser.Default.ParseArguments< 34 | CompareCommand, 35 | ListCommand, 36 | LoadCommand, 37 | ShowCommand, 38 | ShowInfoCommand, 39 | ExitCommand>(SplitArgs(commandLine)) 40 | .WithParsed(command => commandTask = command.Run(this)) 41 | .WithParsed(command => commandTask = command.Run(this)) 42 | .WithParsed(command => commandTask = command.Run(this)) 43 | .WithParsed(command => commandTask = command.Run(this)) 44 | .WithParsed(command => commandTask = command.Run(this)) 45 | .WithParsed(command => exit = true); 46 | await commandTask; 47 | } 48 | } 49 | 50 | private string[] SplitArgs(string arg) 51 | { 52 | int quotecount = arg.Count(x => x == '"'); 53 | if (quotecount % 2 != 0) 54 | { 55 | Log.Alert("Your command contains an uneven number of quotes. Was that intended?"); 56 | } 57 | 58 | string[] segments = arg.Split('"', StringSplitOptions.RemoveEmptyEntries); 59 | List elements = new List(); 60 | for (int i = 0; i < segments.Length; i++) 61 | { 62 | if (i % 2 == 0) 63 | { 64 | string[] parts = segments[i].Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries); 65 | foreach (string ps in parts) 66 | elements.Add(ps.Trim()); 67 | } 68 | else 69 | { 70 | elements.Add(segments[i].Trim()); 71 | } 72 | } 73 | 74 | return elements.ToArray(); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | FROM mcr.microsoft.com/devcontainers/universal:linux 5 | 6 | # Avoid warnings by switching to noninteractive 7 | ENV DEBIAN_FRONTEND=noninteractive 8 | 9 | # Set env for tracking that we're running in a devcontainer 10 | ENV DEVCONTAINER=true 11 | 12 | # Save command line history 13 | RUN echo "export HISTFILE=/home/codespace/commandhistory/.bash_history" >> "/home/codespace/.bashrc" \ 14 | && echo "export PROMPT_COMMAND='history -a'" >> "/home/codespace/.bashrc" \ 15 | && mkdir -p /home/codespace/commandhistory \ 16 | && touch /home/codespace/commandhistory/.bash_history \ 17 | && chown -R codespace:codespace /home/codespace/commandhistory 18 | 19 | # Git command prompt 20 | RUN git clone https://github.com/magicmonty/bash-git-prompt.git /home/codespace/.bash-git-prompt --depth=1 \ 21 | && echo "if [ -f \"/home/codespace/.bash-git-prompt/gitprompt.sh\" ]; then GIT_PROMPT_ONLY_IN_REPO=1 && source /home/codespace/.bash-git-prompt/gitprompt.sh; fi" >> "/home/codespace/.bashrc" \ 22 | && chown -R codespace:codespace /home/codespace/.bash-git-prompt 23 | 24 | # terraform + tflint 25 | ARG TERRAFORM_VERSION=1.11.2 26 | ARG TFLINT_VERSION=0.55.1 27 | RUN mkdir -p /tmp/docker-downloads \ 28 | && curl -sSL -o /tmp/docker-downloads/terraform.zip https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip \ 29 | && unzip /tmp/docker-downloads/terraform.zip \ 30 | && mv terraform /usr/local/bin \ 31 | && rm /tmp/docker-downloads/terraform.zip \ 32 | && echo "alias tf=terraform" >> "/home/codespace/.bashrc" 33 | 34 | RUN curl -sSL -o /tmp/docker-downloads/tflint.zip https://github.com/wata727/tflint/releases/download/v${TFLINT_VERSION}/tflint_linux_amd64.zip \ 35 | && unzip /tmp/docker-downloads/tflint.zip \ 36 | && mv tflint /usr/local/bin \ 37 | && rm /tmp/docker-downloads/tflint.zip 38 | 39 | # azure-cli 40 | COPY ./scripts/azure-cli.sh /tmp/ 41 | RUN /tmp/azure-cli.sh 42 | 43 | # Install PowerShell 44 | RUN sudo apt-get update \ 45 | && sudo apt-get install -y wget apt-transport-https software-properties-common \ 46 | && wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb" -O packages-microsoft-prod.deb \ 47 | && sudo dpkg -i packages-microsoft-prod.deb \ 48 | && sudo apt-get update \ 49 | && sudo apt-get install -y powershell \ 50 | && sudo apt-get clean \ 51 | && rm -rf /var/lib/apt/lists/* 52 | 53 | # azure developer cli (azd) 54 | RUN curl -fsSL https://aka.ms/install-azd.sh | bash 55 | 56 | # Sync timezone (if TZ value not already present on host it defaults to America/Los_Angeles) 57 | # Note: if running on WSL (Windows) you can add the below to your $profile so your tz is automatically synced 58 | # $tz = [Windows.Globalization.Calendar,Windows.Globalization,ContentType=WindowsRuntime]::New().GetTimeZone() 59 | # [Environment]::SetEnvironmentVariable("TZ",$tz, "User") 60 | RUN if [ -z "$TZ" ]; then TZ="America/Los_Angeles"; fi && sudo ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ | sudo tee /etc/timezone > /dev/null 61 | 62 | # Install gettext-base so that we have envsubst 63 | RUN sudo apt-get update \ 64 | && sudo apt-get -y install gettext-base 65 | 66 | # Switch to the built-in non-root user 67 | USER codespace -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/LoadCommand.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using CommandLine; 4 | using Microsoft.Azure.DigitalTwins.Parser; 5 | using Microsoft.Azure.DigitalTwins.Parser.Models; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Diagnostics.CodeAnalysis; 9 | using System.IO; 10 | using System.Linq; 11 | using System.Threading.Tasks; 12 | 13 | [Verb("load", HelpText = "Load models.")] 14 | internal class LoadCommand 15 | { 16 | [Value(0, HelpText = "List of file names to load.")] 17 | public IEnumerable FileNames { get; set; } 18 | 19 | public async Task Run(Interactive p) 20 | { 21 | List modelTexts = new List(); 22 | foreach (string fileName in FileNames) 23 | { 24 | string directoryName = Path.GetDirectoryName(fileName); 25 | if (string.IsNullOrWhiteSpace(directoryName)) 26 | { 27 | directoryName = "."; 28 | } 29 | 30 | string[] expandedFileNames = Directory.GetFiles(directoryName, Path.GetFileName(fileName)); 31 | foreach (string expandedFileName in expandedFileNames) 32 | { 33 | modelTexts.Add(File.ReadAllText(expandedFileName)); 34 | Console.WriteLine($"Loaded {expandedFileName}"); 35 | } 36 | } 37 | 38 | // Parse the models. 39 | // The set of entities returned from ParseAsync includes entities loaded by the resolver. 40 | Console.WriteLine(); 41 | try 42 | { 43 | (IReadOnlyDictionary entities, IEnumerable resolvedInterfaces) = await p.DTDLParser.ParseAsync(modelTexts); 44 | foreach (Dtmi entityDtmi in entities.Keys) 45 | { 46 | Log.Ok($"Parsed {entityDtmi.AbsoluteUri}"); 47 | } 48 | 49 | // Store only the newly loaded interfaces. 50 | // Because the entities returned from ParseAsync contains 51 | // more than just interfaces and also any entities loaded by the resolver: 52 | // - Filter to just interfaces 53 | // - Exclude interfaces that were loaded by the resolver. 54 | // The above seems reasonable for a client to do, since the parser 55 | // doesn't/shouldn't know these details. 56 | Console.WriteLine(); 57 | IEnumerable interfaces = from entity in entities.Values 58 | where entity.EntityKind == DTEntityKind.Interface 59 | select entity as DTInterfaceInfo; 60 | interfaces = interfaces.Except(resolvedInterfaces, new DTInterfaceInfoComparer()); 61 | foreach (DTInterfaceInfo @interface in interfaces) 62 | { 63 | p.Models.Add(@interface.Id, @interface); 64 | Console.WriteLine($"Stored {@interface.Id.AbsoluteUri}"); 65 | } 66 | } 67 | catch (ParsingException pe) 68 | { 69 | Log.Error($"*** Error parsing models"); 70 | int derrcount = 1; 71 | foreach (ParsingError err in pe.Errors) 72 | { 73 | Log.Error($"Error {derrcount}:"); 74 | Log.Error($"{err.Message}"); 75 | Log.Error($"Primary ID: {err.PrimaryID}"); 76 | Log.Error($"Secondary ID: {err.SecondaryID}"); 77 | Log.Error($"Property: {err.Property}\n"); 78 | derrcount++; 79 | } 80 | } 81 | } 82 | 83 | private class DTInterfaceInfoComparer : IEqualityComparer 84 | { 85 | public bool Equals([AllowNull] DTInterfaceInfo x, [AllowNull] DTInterfaceInfo y) 86 | { 87 | if (ReferenceEquals(x, y)) 88 | { 89 | return true; 90 | } 91 | 92 | if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) 93 | { 94 | return false; 95 | } 96 | 97 | return x.Id == y.Id; 98 | } 99 | 100 | public int GetHashCode([DisallowNull] DTInterfaceInfo obj) 101 | { 102 | return obj.Id.GetHashCode(); 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /OWL2DTDL/OntologyRestriction.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Globalization; 3 | using System.Linq; 4 | using VDS.RDF; 5 | using VDS.RDF.Ontology; 6 | 7 | namespace OWL2DTDL 8 | { 9 | /// 10 | /// (Partial) representation of an owl:Restriction. 11 | /// 12 | public class OntologyRestriction 13 | { 14 | public OntologyProperty OnProperty 15 | { 16 | get 17 | { 18 | IUriNode onProperty = _graph.CreateUriNode(VocabularyHelper.OWL.onProperty); 19 | IEnumerable properties = _wrappedClass.GetNodesViaPredicate(onProperty).UriNodes(); 20 | if (properties.Count() != 1) 21 | { 22 | throw new RdfException("A restriction must be on exactly one property."); 23 | } 24 | return _graph.CreateOntologyProperty(properties.First()); 25 | } 26 | } 27 | 28 | public OntologyClass OnClass 29 | { 30 | get 31 | { 32 | IUriNode onClass = _graph.CreateUriNode(VocabularyHelper.OWL.onClass); 33 | IUriNode allValuesFrom = _graph.CreateUriNode(VocabularyHelper.OWL.allValuesFrom); 34 | IUriNode someValuesFrom = _graph.CreateUriNode(VocabularyHelper.OWL.someValuesFrom); 35 | IEnumerable classes = _wrappedClass.GetNodesViaPredicate(onClass) 36 | .Union(_wrappedClass.GetNodesViaPredicate(someValuesFrom)) 37 | .Union(_wrappedClass.GetNodesViaPredicate(allValuesFrom)); 38 | if (classes.Count() == 0) 39 | { 40 | if (OnProperty.IsObjectProperty()) 41 | { 42 | return _graph.CreateOntologyClass(VocabularyHelper.OWL.Thing); 43 | } 44 | else 45 | { 46 | return _graph.CreateOntologyClass(VocabularyHelper.RDFS.Literal); 47 | } 48 | } 49 | else if (classes.Count() == 1) 50 | { 51 | return _graph.CreateOntologyClass(classes.First()); 52 | } 53 | throw new RdfException("A restriction must be on at most one class."); 54 | } 55 | } 56 | 57 | public int MinimumCardinality 58 | { 59 | get 60 | { 61 | IUriNode someValuesFrom = _graph.CreateUriNode(VocabularyHelper.OWL.someValuesFrom); 62 | IUriNode minCardinality = _graph.CreateUriNode(VocabularyHelper.OWL.minCardinality); 63 | IUriNode minQualifiedCardinality = _graph.CreateUriNode(VocabularyHelper.OWL.minQualifiedCardinality); 64 | 65 | IEnumerable minCardinalities = _wrappedClass.GetNodesViaPredicate(minCardinality).Union(_wrappedClass.GetNodesViaPredicate(minQualifiedCardinality)); 66 | if (minCardinalities.LiteralNodes().Count() == 1 && 67 | minCardinalities.LiteralNodes().First().IsInteger()) 68 | { 69 | return int.Parse(minCardinalities.LiteralNodes().First().Value, CultureInfo.InvariantCulture); 70 | } 71 | 72 | if (_wrappedClass.GetNodesViaPredicate(someValuesFrom).Count() == 1) 73 | { 74 | return 1; 75 | } 76 | return 0; 77 | } 78 | } 79 | 80 | public int ExactCardinality 81 | { 82 | get 83 | { 84 | IUriNode cardinality = _graph.CreateUriNode(VocabularyHelper.OWL.cardinality); 85 | IUriNode qualifiedCardinality = _graph.CreateUriNode(VocabularyHelper.OWL.qualifiedCardinality); 86 | 87 | IEnumerable exactCardinalities = _wrappedClass.GetNodesViaPredicate(cardinality).Union(_wrappedClass.GetNodesViaPredicate(qualifiedCardinality)); 88 | if (exactCardinalities.LiteralNodes().Count() == 1 && 89 | exactCardinalities.LiteralNodes().First().IsInteger()) 90 | { 91 | return int.Parse(exactCardinalities.LiteralNodes().First().Value, CultureInfo.InvariantCulture); 92 | } 93 | return 0; 94 | } 95 | } 96 | 97 | public int MaximumCardinality 98 | { 99 | get 100 | { 101 | IUriNode maxCardinality = _graph.CreateUriNode(VocabularyHelper.OWL.maxCardinality); 102 | IUriNode maxQualifiedCardinality = _graph.CreateUriNode(VocabularyHelper.OWL.maxQualifiedCardinality); 103 | 104 | IEnumerable maxCardinalities = _wrappedClass.GetNodesViaPredicate(maxCardinality).Union(_wrappedClass.GetNodesViaPredicate(maxQualifiedCardinality)); 105 | if (maxCardinalities.LiteralNodes().Count() == 1 && 106 | maxCardinalities.LiteralNodes().First().IsInteger()) 107 | { 108 | return int.Parse(maxCardinalities.LiteralNodes().First().Value, CultureInfo.InvariantCulture); 109 | } 110 | return 0; 111 | } 112 | } 113 | 114 | public readonly OntologyGraph _graph; 115 | public readonly OntologyClass _wrappedClass; 116 | 117 | /// 118 | /// Wrapper around an ontology class that exposes some methods particular to ontology restrictions. 119 | /// 120 | /// 121 | public OntologyRestriction(OntologyClass wrappedClass) 122 | { 123 | _wrappedClass = wrappedClass; 124 | _graph = wrappedClass.Graph as OntologyGraph; 125 | } 126 | 127 | 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /ADTTools/RecreateAdtInstance/main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import time 3 | 4 | from jlog import logger 5 | from jlog import ProgressBar 6 | from jlog import Spinner 7 | from azure.mgmt.digitaltwins import AzureDigitalTwinsManagementClient 8 | from azure.core.exceptions import HttpResponseError 9 | from azure.core.exceptions import ClientAuthenticationError 10 | from azure.mgmt.digitaltwins.v2022_05_31.models import DigitalTwinsResource 11 | from azure.mgmt.digitaltwins.v2022_05_31.models import DigitalTwinsEndpointResource 12 | from azure.mgmt.digitaltwins.v2022_05_31.models import EventHub 13 | from azure.mgmt.digitaltwins.v2022_05_31.models import EventGrid 14 | from azure.mgmt.digitaltwins.v2022_05_31.models import ServiceBus 15 | from azure.identity import DefaultAzureCredential 16 | 17 | 18 | def map_endpoint(resource): 19 | props = resource.properties 20 | 21 | match props.endpoint_type: 22 | case "EventHub": 23 | return EventHub( 24 | authentication_type=props.authentication_type, 25 | endpoint_uri=props.endpoint_uri, 26 | entity_path=props.entity_path 27 | ) 28 | case "EventGrid": 29 | return EventGrid( 30 | topic_endpoint=props.topic_endpoint, 31 | access_key1=props.access_key1, 32 | authentication_type=props.authentication_type 33 | ) 34 | case "ServiceBus": 35 | return ServiceBus( 36 | authentication_type=props.authentication_type, 37 | endpoint_uri=props.endpoint_uri, 38 | entity_path=props.entity_path 39 | ) 40 | 41 | 42 | def delete_digital_twins_instance(): 43 | delete_start = round(time.time() * 1000) 44 | delete_instance = dt_resource_client.digital_twins.begin_delete(resource_group, instance_name) 45 | cycles = 0 46 | progress_bar = ProgressBar.new(total=10_000, msg="Deleting DigitalTwins Instance") 47 | 48 | while not delete_instance.done(): 49 | if cycles < 9_900: 50 | time.sleep(0.1) 51 | progress_bar.update(25) 52 | cycles += 25 53 | 54 | delete_end = round(time.time() * 1000) 55 | progress_bar.update(10_000 - cycles) 56 | progress_bar.close() 57 | 58 | return delete_end - delete_start 59 | 60 | 61 | def create_digital_twins_instance(): 62 | logger.info("Creating new DigitalTwins instance %s", instance_name) 63 | dt_resource = DigitalTwinsResource(location=instance.location, identity=instance.identity) 64 | 65 | create_start = round(time.time() * 1000) 66 | create_instance = dt_resource_client.digital_twins.begin_create_or_update(resource_group, instance_name, dt_resource) 67 | cycles = 0 68 | progress_bar = ProgressBar.new(total=15_000, msg="Creating DigitalTwins Instance") 69 | 70 | while not create_instance.done(): 71 | if cycles < 14_850: 72 | time.sleep(0.1) 73 | progress_bar.update(25) 74 | cycles += 25 75 | 76 | create_end = round(time.time() * 1000) 77 | progress_bar.update(15_000 - cycles) 78 | progress_bar.close() 79 | 80 | return create_end - create_start 81 | 82 | 83 | def create_endpoints(): 84 | num_endpoints = len(endpoints) 85 | logger.info("Recreating %d endpoint(s).", num_endpoints) 86 | start_time = round(time.time() * 1000) 87 | updated_endpoints = list() 88 | 89 | for endpoint in endpoints: 90 | updated_endpoint = dt_resource_client.digital_twins_endpoint.begin_create_or_update( 91 | resource_group_name=resource_group, 92 | resource_name=instance_name, 93 | endpoint_name=endpoint.name, 94 | endpoint_description=DigitalTwinsEndpointResource(properties=map_endpoint(endpoint)) 95 | ) 96 | 97 | updated_endpoints.append(updated_endpoint) 98 | 99 | spinner = Spinner.new("Creating Endpoints.") 100 | spinner.start() 101 | 102 | num_complete = 0 103 | while True: 104 | 105 | for index in range(0, num_endpoints): 106 | current_request = updated_endpoints[index] 107 | 108 | if current_request is None: 109 | continue 110 | 111 | if current_request.done(): 112 | updated_endpoints[index] = None 113 | num_complete += 1 114 | spinner.text = f"Creating Endpoints. {num_complete}/{num_endpoints}" 115 | 116 | if num_complete is num_endpoints: 117 | break 118 | 119 | time.sleep(0.1) 120 | 121 | end_time = round(time.time() * 1000) 122 | spinner.stop() 123 | return end_time - start_time 124 | 125 | 126 | if len(sys.argv) < 4: 127 | logger.error( 128 | 'ADT instance name must be provided as arg[1]. SubscriptionId must be provided as arg[2] Exiting. ResourceGroup as arg[3]') 129 | exit() 130 | 131 | instance_name = sys.argv[1] 132 | subscription_id = sys.argv[2] 133 | resource_group = sys.argv[3] 134 | 135 | api_version = "2022-05-31" 136 | credential_provider = DefaultAzureCredential() 137 | dt_resource_client = AzureDigitalTwinsManagementClient(credential_provider, subscription_id, api_version) 138 | 139 | instance = None 140 | 141 | try: 142 | instance = dt_resource_client.digital_twins.get(resource_group, instance_name) 143 | except (HttpResponseError, ClientAuthenticationError) as e: 144 | logger.exception(e) 145 | exit() 146 | 147 | logger.info("Successfully retrieved %s.", instance.name) 148 | 149 | endpoints = list(dt_resource_client.digital_twins_endpoint.list(resource_group, instance_name)) 150 | 151 | logger.info("Deleted DigitalTwins instance in %d milliseconds.", delete_digital_twins_instance()) 152 | 153 | logger.info("Created DigitalTwins instance in %d milliseconds", create_digital_twins_instance()) 154 | 155 | if len(endpoints) > 0: 156 | logger.info("Created endpoints in %d milliseconds", create_endpoints()) 157 | 158 | logger.info("Done.") 159 | dt_resource_client.close() 160 | -------------------------------------------------------------------------------- /DTDLValidator/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /OWL2DTDL/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Program.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator 2 | { 3 | using CommandLine; 4 | using Microsoft.Azure.DigitalTwins.Parser; 5 | using Microsoft.Azure.DigitalTwins.Parser.Models; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Reflection; 11 | using System.Text.Json; 12 | 13 | class Program 14 | { 15 | public class Options 16 | { 17 | [Option('e', "extension", Default = "json", SetName = "normal", HelpText = "File extension of files to be processed.")] 18 | public string Extension { get; set; } 19 | 20 | [Option('d', "directory", SetName = "normal", HelpText = "Directory to search files in.")] 21 | public string Directory { get; set; } 22 | 23 | [Option('r', "recursive", Default = false, SetName = "normal", HelpText = "Search given directory (option -d) only (false) or subdirectories too (true)")] 24 | public bool Recursive { get; set; } 25 | 26 | [Option('f', "files", HelpText = "Input files to be processed. If -d option is also specified, these files are read in addition.")] 27 | public IEnumerable InputFiles { get; set; } 28 | 29 | [Option('i', "interactive", Default = false, SetName = "interactive", HelpText = "Run in interactive mode")] 30 | public bool Interactive { get; set; } 31 | } 32 | 33 | static void Main(string[] args) 34 | { 35 | CommandLine.Parser.Default.ParseArguments(args) 36 | .WithParsed(RunOptions) 37 | .WithNotParsed(HandleParseError); 38 | } 39 | 40 | static void RunOptions(Options opts) 41 | { 42 | Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); 43 | string dtdlParserVersion = ""; 44 | foreach (Assembly a in assemblies) 45 | { 46 | if (a.GetName().Name.EndsWith("DigitalTwins.Parser")) 47 | dtdlParserVersion = a.GetName().Version.ToString(); 48 | } 49 | 50 | Log.Ok($"Simple DTDL Validator (dtdl parser library version {dtdlParserVersion})"); 51 | 52 | if (opts.Interactive == true) 53 | { 54 | Log.Alert("Entering interactive mode"); 55 | Interactive.Interactive i = new Interactive.Interactive(); 56 | return; 57 | } 58 | 59 | DirectoryInfo dinfo = null; 60 | try 61 | { 62 | if(opts.Directory != null && opts.Directory != string.Empty) 63 | { 64 | dinfo = new DirectoryInfo(opts.Directory); 65 | Log.Alert($"Validating *.{opts.Extension} files in folder '{dinfo.FullName}'.\nRecursive is set to {opts.Recursive}\n"); 66 | 67 | if (dinfo.Exists == false) 68 | { 69 | Log.Error($"Specified directory '{opts.Directory}' does not exist: Exiting..."); 70 | throw new Exception(); 71 | } 72 | } 73 | 74 | } catch (Exception e) 75 | { 76 | Log.Error($"Error accessing the target directory '{opts.Directory}': \n{e.Message}"); 77 | Environment.Exit(0); 78 | } 79 | 80 | SearchOption searchOpt = opts.Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; 81 | var files = opts.InputFiles.ToList(); 82 | 83 | if(dinfo!= null) 84 | { 85 | dinfo.EnumerateFiles($"*.{opts.Extension}", searchOpt).ToList().ForEach(file => files.Add(file.FullName)); 86 | } 87 | 88 | if (files.Count() == 0) 89 | { 90 | Log.Alert("No matching files found. Exiting."); 91 | return; 92 | } 93 | 94 | var modelDict = new Dictionary(); 95 | int count = 0; 96 | string lastFile = ""; 97 | try 98 | { 99 | foreach (var file in files) 100 | { 101 | StreamReader r = new StreamReader(file); 102 | string dtdl = r.ReadToEnd(); 103 | r.Close(); 104 | modelDict.Add(file, dtdl); 105 | lastFile = file; 106 | count++; 107 | } 108 | } catch (Exception e) 109 | { 110 | Log.Error($"Could not read files. \nLast file read: {lastFile}\nError: \n{e.Message}"); 111 | Environment.Exit(0); 112 | } 113 | 114 | Log.Ok($"Read {count} files from specified directory"); 115 | int errJson = 0; 116 | foreach (string file in modelDict.Keys) 117 | { 118 | modelDict.TryGetValue(file, out string dtdl); 119 | try 120 | { 121 | JsonDocument.Parse(dtdl); 122 | } catch (Exception e) 123 | { 124 | Log.Error($"Invalid json found in file {file}.\nJson parser error \n{e.Message}"); 125 | errJson++; 126 | } 127 | } 128 | 129 | if (errJson>0) 130 | { 131 | Log.Error($"\nFound {errJson} Json parsing errors"); 132 | Environment.Exit(0); 133 | } 134 | 135 | Log.Ok($"Validated JSON for all files - now validating DTDL"); 136 | List modelList = modelDict.Values.ToList(); 137 | ModelParser parser = new ModelParser(); 138 | parser.DtmiResolver = new DtmiResolver(Resolver); 139 | try 140 | { 141 | IReadOnlyDictionary om = parser.Parse(modelList); 142 | Log.Out(""); 143 | Log.Ok($"**********************************************"); 144 | Log.Ok($"** Validated all files - Your DTDL is valid **"); 145 | Log.Ok($"**********************************************"); 146 | Log.Out($"Found a total of {om.Keys.Count()} entities"); 147 | } 148 | catch (ParsingException pe) 149 | { 150 | Log.Error($"*** Error parsing models"); 151 | int derrcount = 1; 152 | foreach (ParsingError err in pe.Errors) 153 | { 154 | Log.Error($"Error {derrcount}:"); 155 | Log.Error($"{err.Message}"); 156 | Log.Error($"Primary ID: {err.PrimaryID}"); 157 | Log.Error($"Secondary ID: {err.SecondaryID}"); 158 | Log.Error($"Property: {err.Property}\n"); 159 | derrcount++; 160 | } 161 | 162 | Environment.Exit(0); 163 | } 164 | catch (ResolutionException ex) 165 | { 166 | Log.Error(ex, "Could not resolve required references"); 167 | Environment.Exit(0); 168 | } 169 | } 170 | 171 | static IEnumerable Resolver(IReadOnlyCollection dtmis) 172 | { 173 | Log.Error($"*** Error parsing models. Missing:"); 174 | foreach (Dtmi d in dtmis) 175 | { 176 | Log.Error($" {d}"); 177 | } 178 | 179 | return null; 180 | } 181 | 182 | static void HandleParseError(IEnumerable errs) 183 | { 184 | Log.Error($"Invalid command line."); 185 | foreach (Error e in errs) 186 | { 187 | Log.Error($"{e.Tag}: {e}"); 188 | } 189 | } 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /OWL2DTDL/Relationship.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using VDS.RDF; 5 | using VDS.RDF.Ontology; 6 | 7 | namespace OWL2DTDL 8 | { 9 | /// 10 | /// A representation of the relationships (data properties or object properties) that can be expressed on an OWL class. 11 | /// TODO Here be gremlins! Thid code is ugly and written in a hurry. It should probably be signficantly refactored and cleaned up, 12 | /// if not removed entirely. The relationship merge logic is particularly hairy. 13 | /// 14 | public class Relationship 15 | { 16 | public OntologyProperty Property 17 | { get; } 18 | 19 | public OntologyClass Target 20 | { get; set; } 21 | 22 | public int? MinimumCount 23 | { get; set; } 24 | 25 | public int? MaximumCount 26 | { get; set; } 27 | 28 | public int? ExactCount 29 | { 30 | get 31 | { 32 | if (MinimumCount.HasValue && MaximumCount.HasValue && MinimumCount == MaximumCount) 33 | { 34 | return MinimumCount; 35 | } 36 | return null; 37 | } 38 | set 39 | { 40 | MinimumCount = value; 41 | MaximumCount = value; 42 | } 43 | } 44 | 45 | public Relationship(OntologyProperty property, OntologyClass target) 46 | { 47 | if (!property.IsNamed() || !(target.IsNamed() || target.IsDatatype())) 48 | { 49 | throw new ArgumentException("Only named properties and named or datatype targets allowed."); 50 | } 51 | Property = property; 52 | Target = target; 53 | } 54 | 55 | /// 56 | /// Merge another Relationship into this one. 57 | /// This only works when the properties of the relationships are identical; else an exception is thrown. 58 | /// If the two relationships are to different target classes of which one subsumes the other, then the 59 | /// most specific relationship is kept. If the classes do not subsume one another, OWL thing is set as target. 60 | /// If the relationship targets are the same, then the narrower cardinality restrictions are kept. 61 | /// 62 | /// Another Relationship 63 | public void MergeWith(Relationship other) 64 | { 65 | if (!other.Property.Resource.Equals(this.Property.Resource)) 66 | { 67 | throw new Exception("Properties are not identical"); 68 | } 69 | 70 | // If target classes are not the same, then we need to keep the most specific one 71 | if (!other.Target.Resource.Equals(this.Target.Resource)) 72 | { 73 | // If both target classes are both datatypes, 74 | if (this.Target.IsDatatype() && other.Target.IsDatatype()) 75 | { 76 | // If the two targets are of same type but not the same, fall back to rdf:Literal 77 | if ( 78 | (this.Target.IsEnumerationDatatype() && other.Target.IsEnumerationDatatype()) || 79 | (this.Target.IsSimpleXsdWrapper() && other.Target.IsSimpleXsdWrapper()) || 80 | (this.Target.IsXsdDatatype() && other.Target.IsXsdDatatype())) 81 | { 82 | IGraph targetsGraph = this.Target.Graph; 83 | IUriNode rdfLiteral = targetsGraph.CreateUriNode(VocabularyHelper.RDFS.Literal); 84 | this.Target = new OntologyClass(rdfLiteral, targetsGraph); 85 | this.MinimumCount = null; 86 | this.MaximumCount = null; 87 | return; 88 | } 89 | else 90 | { 91 | // Preference order is enumeration, custom xsd wrapper type, built-in xsd type 92 | List relationshipCandidates = new List() { this, other }; 93 | relationshipCandidates.OrderBy(candidate => !candidate.Target.IsEnumerationDatatype()) 94 | .ThenBy(candidate => !candidate.Target.IsSimpleXsdWrapper()) 95 | .ThenBy(candidate => !candidate.Target.IsXsdDatatype()); 96 | if (relationshipCandidates.First() == this) 97 | { 98 | return; 99 | } 100 | else 101 | { 102 | this.Target = other.Target; 103 | this.MinimumCount = other.MinimumCount; 104 | this.MaximumCount = other.MaximumCount; 105 | return; 106 | } 107 | } 108 | } 109 | 110 | // If this relationship has the more specific target class, keep it as-is, i.e., return 111 | if (this.Target.SuperClassesWithOwlThing().Contains(other.Target)) 112 | { 113 | return; 114 | } 115 | // If the other relationhip has the more specific target class, keep it instead and return 116 | else if (other.Target.SuperClassesWithOwlThing().Contains(this.Target)) 117 | { 118 | this.Target = other.Target; 119 | this.MinimumCount = other.MinimumCount; 120 | this.MaximumCount = other.MaximumCount; 121 | return; 122 | } 123 | // The classes do not subsume one another; fall back to OWL:Thing as target class 124 | else 125 | { 126 | IGraph targetsGraph = this.Target.Graph; 127 | IUriNode owlThing = targetsGraph.CreateUriNode(VocabularyHelper.OWL.Thing); 128 | this.Target = new OntologyClass(owlThing, targetsGraph); 129 | this.MinimumCount = null; 130 | this.MaximumCount = null; 131 | return; 132 | } 133 | } 134 | 135 | // If either restriction has an exact count, then that is the most specific restriction possible and min/max need not be inspected 136 | if (ExactCount.HasValue || other.ExactCount.HasValue) 137 | { 138 | // If both restrictions have exact values they either diverge (e.g., caused by an inconsistent ontology) or they converge (no change is required) 139 | if (ExactCount.HasValue && other.ExactCount.HasValue) 140 | { 141 | if (ExactCount.Value != other.ExactCount.Value) 142 | { 143 | throw new Exception("Conflicting ExactCounts"); 144 | } 145 | // The exact value is identical; simply return 146 | return; 147 | } 148 | // Assign exact count from other only if our own is null, else keep our old exactcount 149 | ExactCount ??= other.ExactCount.Value; 150 | return; 151 | } 152 | 153 | int? newMinimum = new int?(); 154 | if (MinimumCount.HasValue || other.MinimumCount.HasValue) 155 | { 156 | // If both have minimum counts, keep the larger one 157 | if (MinimumCount.HasValue && other.MinimumCount.HasValue) 158 | { 159 | newMinimum = MinimumCount > other.MinimumCount ? MinimumCount : other.MinimumCount; 160 | } 161 | else 162 | { 163 | // Else, keep whichever is non-null 164 | newMinimum = MinimumCount.HasValue ? MinimumCount : other.MinimumCount; 165 | } 166 | } 167 | 168 | int? newMaximum = new int?(); 169 | if (MaximumCount.HasValue || other.MaximumCount.HasValue) 170 | { 171 | // If both have maximum counts, keep the smaller one 172 | if (MaximumCount.HasValue && other.MaximumCount.HasValue) 173 | { 174 | newMaximum = MaximumCount < other.MaximumCount ? MaximumCount : other.MaximumCount; 175 | } 176 | else 177 | { 178 | // Else, keep whichever is non-null 179 | newMaximum = MaximumCount.HasValue ? MaximumCount : other.MaximumCount; 180 | } 181 | } 182 | 183 | // At this point newMinimum is maximized or null and newMaximum is minimized or null 184 | // If they are inconsistent, i.e., newMinimum is larger than new Maximum, the model is inconsistent; 185 | // throw an error; else store 186 | if (newMinimum.HasValue && newMaximum.HasValue && newMinimum > newMaximum) 187 | { 188 | throw new Exception("Resulting min > resulting max"); 189 | } 190 | MinimumCount = newMinimum; 191 | MaximumCount = newMaximum; 192 | } 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /DTDLValidator/DTDLValidator/Interactive/CompareCommand.cs: -------------------------------------------------------------------------------- 1 | namespace DTDLValidator.Interactive 2 | { 3 | using CommandLine; 4 | using Microsoft.Azure.DigitalTwins.Parser; 5 | using Microsoft.Azure.DigitalTwins.Parser.Models; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | 11 | [Verb("compare", HelpText = "Compare two models.")] 12 | internal class CompareCommand 13 | { 14 | 15 | [Value(0, HelpText = "First model id to compare.")] 16 | public string FirstModelId { get; set; } 17 | 18 | [Value(1, HelpText = "Second model id to compare.")] 19 | public string SecondModelId { get; set; } 20 | 21 | public Task Run(Interactive p) 22 | { 23 | if (FirstModelId == null || SecondModelId == null) 24 | { 25 | Log.Error("Please specify two valid model ids as parameters"); 26 | return Task.FromResult(null); 27 | } 28 | 29 | bool firstValid = false; 30 | bool secondValid = false; 31 | 32 | Dtmi first = ValidateAndCreateDtmi(FirstModelId); 33 | Dtmi second = ValidateAndCreateDtmi(SecondModelId); 34 | DTInterfaceInfo dt1 = null; 35 | DTInterfaceInfo dt2 = null; 36 | 37 | if (first!=null && p.Models.TryGetValue(first, out dt1)) 38 | firstValid = true; 39 | if (second != null && p.Models.TryGetValue(second, out dt2)) 40 | secondValid = true; 41 | 42 | if (firstValid == false || secondValid == false) 43 | { 44 | if (first == null) 45 | Log.Error($"First model not a valid dtmi"); 46 | if (first!=null && firstValid == false) 47 | Log.Error($"First model not found in loaded models"); 48 | if (second == null) 49 | Log.Error($"Second model not a valid dtmi"); 50 | if (second != null && secondValid == false) 51 | Log.Error($"Second model not found in loaded models"); 52 | return Task.FromResult(null); 53 | } 54 | 55 | IReadOnlyDictionary con1 = dt1.Contents; 56 | IReadOnlyDictionary con2 = dt2.Contents; 57 | 58 | var props1 = con1 59 | .Where(p => p.Value.EntityKind == DTEntityKind.Property) 60 | .Select(p => p.Value as DTPropertyInfo); 61 | 62 | var props2 = con2 63 | .Where(p => p.Value.EntityKind == DTEntityKind.Property) 64 | .Select(p => p.Value as DTPropertyInfo); 65 | 66 | IEnumerable duplicates = props1.Intersect(props2, new DTPropertyInfoComparer()); 67 | IEnumerable diff1 = props1.Except(props2, new DTPropertyInfoComparer()); 68 | IEnumerable diff2 = props2.Except(props1, new DTPropertyInfoComparer()); 69 | 70 | Log.Alert("Common Properties (comparing name and schema, ignoring explicit ids)"); 71 | Console.WriteLine(listFormatBoth, "Property Name", "Schema"); 72 | Console.WriteLine(listFormatBoth, "-------------", "------"); 73 | foreach (var pi in duplicates) 74 | Console.WriteLine(listFormatBoth, pi.Name, pi.Schema); 75 | 76 | Console.WriteLine(); 77 | PrintDifference(dt1, diff1); 78 | Console.WriteLine(); 79 | PrintDifference(dt2, diff2); 80 | 81 | var rels1 = con1 82 | .Where(p => p.Value.EntityKind == DTEntityKind.Relationship) 83 | .Select(p => p.Value as DTRelationshipInfo); 84 | 85 | var rels2 = con2 86 | .Where(p => p.Value.EntityKind == DTEntityKind.Relationship) 87 | .Select(p => p.Value as DTRelationshipInfo); 88 | 89 | IEnumerable dupRels = rels1.Intersect(rels2, new DTRelationshipInfoComparer()); 90 | IEnumerable diffRels1 = rels1.Except(rels2, new DTRelationshipInfoComparer()); 91 | IEnumerable diffRels2 = rels2.Except(rels1, new DTRelationshipInfoComparer()); 92 | 93 | Console.WriteLine(); 94 | Log.Alert("Common Relationships (comparing name and target - not checking properties, ignoring explicit ids)"); 95 | Console.WriteLine(listFormatBoth, "Relationship Name", "Target"); 96 | Console.WriteLine(listFormatBoth, "-----------------", "------"); 97 | foreach (var pi in dupRels) 98 | { 99 | string target = ""; 100 | if (pi.Target != null) 101 | target = pi.Target.ToString(); 102 | Console.WriteLine(listFormatBoth, pi.Name, target); 103 | } 104 | 105 | Console.WriteLine(); 106 | PrintDifference(dt1, diffRels1); 107 | Console.WriteLine(); 108 | PrintDifference(dt2, diffRels2); 109 | 110 | return Task.FromResult(null); 111 | } 112 | 113 | private const string listFormatBoth = "{0,-30}{1}"; 114 | 115 | private void PrintDifference(DTInterfaceInfo dti, IEnumerable diffs) 116 | { 117 | Log.Alert($"Only in {dti.DisplayName.FirstOrDefault().Value ?? dti.Id.ToString()}"); 118 | Console.WriteLine(listFormatBoth, "Property Name", "Schema"); 119 | Console.WriteLine(listFormatBoth, "-------------", "------"); 120 | foreach (var pi in diffs) 121 | { 122 | Console.WriteLine(listFormatBoth, pi.Name, pi.Schema); 123 | } 124 | } 125 | 126 | private void PrintDifference(DTInterfaceInfo dti, IEnumerable diffs) 127 | { 128 | Log.Alert($"Only in {dti.DisplayName.FirstOrDefault().Value ?? dti.Id.ToString()}"); 129 | Console.WriteLine(listFormatBoth, "Relationship Name", "Schema"); 130 | Console.WriteLine(listFormatBoth, "-----------------", "------"); 131 | foreach (var pi in diffs) 132 | { 133 | Console.WriteLine(listFormatBoth, pi.Name, pi.Target); 134 | } 135 | } 136 | 137 | private Dtmi ValidateAndCreateDtmi(string dtmi) 138 | { 139 | try 140 | { 141 | Dtmi dt = new Dtmi(dtmi); 142 | return dt; 143 | } 144 | catch (Exception) 145 | { 146 | return null; 147 | } 148 | } 149 | } 150 | 151 | // This assumes that the DTProperties are *not* defined with explicit ids 152 | class DTPropertyInfoComparer : IEqualityComparer 153 | { 154 | // Products are equal if their names and product numbers are equal. 155 | public bool Equals(DTPropertyInfo x, DTPropertyInfo y) 156 | { 157 | 158 | //Check whether the compared objects reference the same data. 159 | if (Object.ReferenceEquals(x, y)) return true; 160 | 161 | //Check whether any of the compared objects is null. 162 | if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) 163 | return false; 164 | 165 | //Check whether the products' properties are equal. 166 | return x.Name == y.Name && x.Schema == y.Schema; 167 | } 168 | 169 | // If Equals() returns true for a pair of objects 170 | // then GetHashCode() must return the same value for these objects. 171 | 172 | public int GetHashCode(DTPropertyInfo pi) 173 | { 174 | //Check whether the object is null 175 | if (Object.ReferenceEquals(pi, null)) return 0; 176 | 177 | //Get hash code for the Name field if it is not null. 178 | int hashPIName = pi.Name == null ? 0 : pi.Name.GetHashCode(); 179 | 180 | //Get hash code for the Code field. 181 | int hashPISchema = pi.Schema.GetHashCode(); 182 | 183 | //Calculate the hash code for the product. 184 | return hashPIName ^ hashPISchema; 185 | } 186 | } 187 | 188 | // This assumes that the DTRelationships are *not* defined with explicit ids 189 | // Only compares name and target in this sample 190 | class DTRelationshipInfoComparer : IEqualityComparer 191 | { 192 | // Products are equal if their names and product numbers are equal. 193 | public bool Equals(DTRelationshipInfo x, DTRelationshipInfo y) 194 | { 195 | 196 | //Check whether the compared objects reference the same data. 197 | if (Object.ReferenceEquals(x, y)) return true; 198 | 199 | //Check whether any of the compared objects is null. 200 | if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) 201 | return false; 202 | 203 | //Check whether the products' properties are equal. 204 | return x.Name == y.Name && x.Target == y.Target; 205 | } 206 | 207 | // If Equals() returns true for a pair of objects 208 | // then GetHashCode() must return the same value for these objects. 209 | 210 | public int GetHashCode(DTRelationshipInfo pi) 211 | { 212 | //Check whether the object is null 213 | if (Object.ReferenceEquals(pi, null)) return 0; 214 | 215 | //Get hash code for the Name field if it is not null. 216 | int hashPIName = pi.Name == null ? 0 : pi.Name.GetHashCode(); 217 | 218 | //Get hash code for the Code field. 219 | if (pi.Target == null) 220 | return hashPIName; 221 | 222 | int hashPITarget = pi.Target.GetHashCode(); 223 | 224 | //Calculate the hash code for the product. 225 | return hashPIName ^ hashPITarget; 226 | } 227 | } 228 | 229 | } 230 | -------------------------------------------------------------------------------- /ADTTools/UploadModels/Program.cs: -------------------------------------------------------------------------------- 1 | using ADTToolsLibrary; 2 | using Azure; 3 | using Azure.DigitalTwins.Core; 4 | using Azure.Identity; 5 | using CommandLine; 6 | using Ganss.IO; 7 | using DTDLParser; 8 | using DTDLParser.Models; 9 | using System; 10 | using System.Collections.Generic; 11 | using System.IO; 12 | using System.Linq; 13 | using System.Text.Json; 14 | using System.Threading.Tasks; 15 | using Azure.Core; 16 | 17 | namespace UploadModels 18 | { 19 | class Program 20 | { 21 | private readonly Options options; 22 | 23 | static async Task Main(string[] args) 24 | { 25 | await Parser.Default.ParseArguments(args).WithParsedAsync(options => new Program(options).Run()); 26 | } 27 | 28 | private Program(Options options) 29 | { 30 | this.options = options; 31 | } 32 | 33 | private async Task Run() 34 | { 35 | // Expand globs and wildcards for all file specs. 36 | IEnumerable fileNames = GetFileNames(options.FileSpecs); 37 | 38 | // Load all the model text. 39 | var modelTexts = new Dictionary(); 40 | foreach (string fileName in fileNames) 41 | { 42 | modelTexts.Add(fileName, File.ReadAllText(fileName)); 43 | Log.Write($"Loaded: {fileName}"); 44 | } 45 | 46 | Log.Write(string.Empty); 47 | 48 | // Check that all model text is valid JSON (for better error reporting). 49 | if (!ParseModelJson(modelTexts)) 50 | { 51 | return; 52 | } 53 | 54 | // Parse models. 55 | IReadOnlyDictionary entities = await ParseModelsAsync(modelTexts); 56 | if (entities == null) 57 | { 58 | return; 59 | } 60 | 61 | // Get interfaces. 62 | IEnumerable interfaces = from entity in entities.Values 63 | where entity.EntityKind == DTEntityKind.Interface 64 | select (DTInterfaceInfo)entity; 65 | Log.Ok($"Parsed {interfaces.Count()} models successfully."); 66 | Log.Write(string.Empty); 67 | 68 | // Order interfaces for upload. 69 | IEnumerable orderedInterfaces = OrderInterfaces(interfaces); 70 | 71 | if (options.WhatIf) 72 | { 73 | DisplayOrderedInterfaces(orderedInterfaces); 74 | } 75 | else 76 | { 77 | await UploadOrderedInterfaces(orderedInterfaces); 78 | } 79 | } 80 | 81 | private async Task UploadOrderedInterfaces(IEnumerable orderedInterfaces) 82 | { 83 | Log.Write("Uploaded interfaces:"); 84 | try 85 | { 86 | TokenCredential credential; 87 | if (options.UseDefaultAzureCredentials) 88 | { 89 | credential = new DefaultAzureCredential(); 90 | } 91 | else 92 | { 93 | if (string.IsNullOrEmpty(options.ClientSecret)) 94 | { 95 | credential = new InteractiveBrowserCredential(options.TenantId, options.ClientId); 96 | } 97 | else 98 | { 99 | credential = new ClientSecretCredential(options.TenantId, options.ClientId, options.ClientSecret); 100 | } 101 | } 102 | 103 | var client = new DigitalTwinsClient(new UriBuilder("https", options.HostName).Uri, credential); 104 | 105 | for (int i = 0; i < (orderedInterfaces.Count() / options.BatchSize) + 1; i++) 106 | { 107 | IEnumerable batch = orderedInterfaces.Skip(i * options.BatchSize).Take(options.BatchSize); 108 | Response response = await client.CreateModelsAsync(batch.Select(i => i.GetJsonLdText())); 109 | foreach (DTInterfaceInfo @interface in batch) 110 | { 111 | Log.Ok(@interface.Id.AbsoluteUri); 112 | } 113 | } 114 | } 115 | catch (Exception ex) 116 | { 117 | Log.Error($"Upload failed."); 118 | Log.Error(ex.Message); 119 | } 120 | } 121 | 122 | private static void DisplayOrderedInterfaces(IEnumerable orderedInterfaces) 123 | { 124 | Log.Write("Ordered interfaces:"); 125 | foreach (DTInterfaceInfo orderedInterface in orderedInterfaces) 126 | { 127 | Log.Write(orderedInterface.Id.AbsoluteUri); 128 | } 129 | 130 | } 131 | 132 | private static bool ParseModelJson(Dictionary modelTexts) 133 | { 134 | var jsonErrors = new Dictionary(); 135 | foreach (string fileName in modelTexts.Keys) 136 | { 137 | try 138 | { 139 | JsonDocument jsonDoc = JsonDocument.Parse(modelTexts[fileName]); 140 | } 141 | catch (JsonException ex) 142 | { 143 | jsonErrors.Add(fileName, ex); 144 | } 145 | } 146 | 147 | if (jsonErrors.Count > 0) 148 | { 149 | Log.Error("Errors parsing models."); 150 | foreach (string fileName in jsonErrors.Keys) 151 | { 152 | Log.Error($"{fileName}: {jsonErrors[fileName].Message}"); 153 | } 154 | } 155 | 156 | return jsonErrors.Count == 0; 157 | } 158 | 159 | private async Task> ParseModelsAsync(Dictionary modelTexts) 160 | { 161 | IReadOnlyDictionary entities = null; 162 | try 163 | { 164 | var parser = new ModelParser(new ParsingOptions() { AllowUndefinedExtensions = options.AllowUndefinedExtensions }); 165 | entities = await parser.ParseAsync(modelTexts.Values.ToAsyncEnumerable()); 166 | } 167 | catch (ParsingException ex) 168 | { 169 | Log.Error("Errors parsing models."); 170 | foreach (ParsingError error in ex.Errors) 171 | { 172 | Log.Error(error.Message); 173 | } 174 | } 175 | catch (Exception ex) 176 | { 177 | Log.Error("Errors parsing models."); 178 | Log.Error(ex.Message); 179 | } 180 | 181 | return entities; 182 | } 183 | 184 | private static IEnumerable OrderInterfaces(IEnumerable interfaces) 185 | { 186 | // This function sorts interfaces from interfaces with no dependencies to interfaces with dependencies. 187 | // Using a depth-first search and post-order processing, we get an ordering from no dependencies to most dependencies. 188 | 189 | // Build the set of all referenced interfaces. 190 | HashSet referencedInterfaces = new HashSet(new DTInterfaceInfoEqualityComparer()); 191 | foreach (DTInterfaceInfo @interface in interfaces) 192 | { 193 | foreach (DTInterfaceInfo referencedInterface in @interface.Extends) 194 | { 195 | referencedInterfaces.Add(referencedInterface); 196 | } 197 | 198 | IEnumerable componentSchemas = from content in @interface.Contents.Values 199 | where content.EntityKind == DTEntityKind.Component 200 | select ((DTComponentInfo)content).Schema; 201 | foreach (DTInterfaceInfo referencedInterface in componentSchemas) 202 | { 203 | referencedInterfaces.Add(referencedInterface); 204 | } 205 | } 206 | 207 | // The roots of the trees are all the interfaces that are not referenced. 208 | IEnumerable rootInterfaces = interfaces.Except(referencedInterfaces, new DTInterfaceInfoEqualityComparer()); 209 | 210 | // For each root, perform depth-first, post-order processing to produce a sorted tree. 211 | OrderedHashSet orderedInterfaces = new OrderedHashSet(new DTInterfaceInfoEqualityComparer()); 212 | foreach (DTInterfaceInfo rootInterface in rootInterfaces) 213 | { 214 | OrderedHashSet rootInterfaceOrderedInterfaces = new OrderedHashSet(new DTInterfaceInfoEqualityComparer()); 215 | OrderInterface(rootInterfaceOrderedInterfaces, rootInterface); 216 | foreach (DTInterfaceInfo rootInterfaceOrderedInterface in rootInterfaceOrderedInterfaces) 217 | { 218 | if (!orderedInterfaces.Contains(rootInterfaceOrderedInterface)) 219 | { 220 | orderedInterfaces.Add(rootInterfaceOrderedInterface); 221 | } 222 | } 223 | } 224 | 225 | return orderedInterfaces; 226 | } 227 | 228 | private static void OrderInterface(OrderedHashSet orderedInterfaces, DTInterfaceInfo @interface) 229 | { 230 | // Order each extended interface. 231 | foreach (DTInterfaceInfo extendedInterface in @interface.Extends) 232 | { 233 | OrderInterface(orderedInterfaces, extendedInterface); 234 | } 235 | 236 | // Order each component schema interface. 237 | IEnumerable componentSchemas = from content in @interface.Contents.Values 238 | where content.EntityKind == DTEntityKind.Component 239 | select ((DTComponentInfo)content).Schema; 240 | foreach (DTInterfaceInfo componentSchemaInterface in componentSchemas) 241 | { 242 | OrderInterface(orderedInterfaces, componentSchemaInterface); 243 | } 244 | 245 | // Add this interface to the list of ordered interfaces. 246 | if (!orderedInterfaces.Contains(@interface)) 247 | { 248 | orderedInterfaces.Add(@interface); 249 | } 250 | } 251 | 252 | private static IEnumerable GetFileNames(IEnumerable fileSpecs) 253 | { 254 | IEnumerable fileNames = Enumerable.Empty(); 255 | foreach (string fileSpec in fileSpecs) 256 | { 257 | fileNames = fileNames.Concat(Glob.Expand(fileSpec).Select(fsi => fsi.FullName)); 258 | } 259 | 260 | return fileNames; 261 | } 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /OWL2DTDL/VocabularyHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | /// 4 | /// A set of often-used URIs, for easy reference. 5 | /// 6 | namespace OWL2DTDL.VocabularyHelper 7 | { 8 | public static class O2O 9 | { 10 | public static readonly Uri included = new Uri("https://karlhammar.com/owl2oas/o2o.owl#included"); 11 | public static readonly Uri endpoint = new Uri("https://karlhammar.com/owl2oas/o2o.owl#endpoint"); 12 | } 13 | 14 | public static class DC 15 | { 16 | public static readonly Uri title = new Uri("http://purl.org/dc/elements/1.1/title"); 17 | public static readonly Uri description = new Uri("http://purl.org/dc/elements/1.1/description"); 18 | } 19 | 20 | public static class CC 21 | { 22 | public static readonly Uri license = new Uri("http://creativecommons.org/ns#license"); 23 | } 24 | 25 | public static class RDFS 26 | { 27 | public static readonly Uri label = new Uri("http://www.w3.org/2000/01/rdf-schema#label"); 28 | public static readonly Uri subClassOf = new Uri("http://www.w3.org/2000/01/rdf-schema#subClassOf"); 29 | public static readonly Uri Datatype = new Uri("http://www.w3.org/2000/01/rdf-schema#Datatype"); 30 | public static readonly Uri Literal = new Uri("http://www.w3.org/2000/01/rdf-schema#Literal"); 31 | } 32 | 33 | public static class OWL 34 | { 35 | public static readonly Uri Thing = new Uri("http://www.w3.org/2002/07/owl#Thing"); 36 | public static readonly Uri Restriction = new Uri("http://www.w3.org/2002/07/owl#Restriction"); 37 | public static readonly Uri FunctionalProperty = new Uri("http://www.w3.org/2002/07/owl#FunctionalProperty"); 38 | public static readonly Uri versionIRI = new Uri("http://www.w3.org/2002/07/owl#versionIRI"); 39 | public static readonly Uri versionInfo = new Uri("http://www.w3.org/2002/07/owl#versionInfo"); 40 | public static readonly Uri deprecated = new Uri("http://www.w3.org/2002/07/owl#deprecated"); 41 | public static readonly Uri oneOf = new Uri("http://www.w3.org/2002/07/owl#oneOf"); 42 | 43 | public static readonly Uri annotatedSource = new Uri("http://www.w3.org/2002/07/owl#annotatedSource"); 44 | public static readonly Uri annotatedProperty = new Uri("http://www.w3.org/2002/07/owl#annotatedProperty"); 45 | public static readonly Uri annotatedTarget = new Uri("http://www.w3.org/2002/07/owl#annotatedTarget"); 46 | 47 | #region Restrictions 48 | public static readonly Uri onProperty = new Uri("http://www.w3.org/2002/07/owl#onProperty"); 49 | public static readonly Uri onClass = new Uri("http://www.w3.org/2002/07/owl#onClass"); 50 | public static readonly Uri cardinality = new Uri("http://www.w3.org/2002/07/owl#cardinality"); 51 | public static readonly Uri qualifiedCardinality = new Uri("http://www.w3.org/2002/07/owl#qualifiedCardinality"); 52 | public static readonly Uri allValuesFrom = new Uri("http://www.w3.org/2002/07/owl#allValuesFrom"); 53 | public static readonly Uri someValuesFrom = new Uri("http://www.w3.org/2002/07/owl#someValuesFrom"); 54 | public static readonly Uri minCardinality = new Uri("http://www.w3.org/2002/07/owl#minCardinality"); 55 | public static readonly Uri minQualifiedCardinality = new Uri("http://www.w3.org/2002/07/owl#minQualifiedCardinality"); 56 | public static readonly Uri maxCardinality = new Uri("http://www.w3.org/2002/07/owl#maxCardinality"); 57 | public static readonly Uri maxQualifiedCardinality = new Uri("http://www.w3.org/2002/07/owl#maxQualifiedCardinality"); 58 | #endregion 59 | } 60 | 61 | public static class QUDT 62 | { 63 | public static readonly Uri Unit = new Uri("http://qudt.org/schema/qudt/Unit"); 64 | public static readonly Uri hasQuantityKind = new Uri("http://qudt.org/schema/qudt/hasQuantityKind"); 65 | 66 | public static class UnitNS 67 | { 68 | public static readonly Uri A = new Uri("http://qudt.org/vocab/unit/A"); 69 | public static readonly Uri CentiM = new Uri("http://qudt.org/vocab/unit/CentiM"); 70 | public static readonly Uri DEG = new Uri("http://qudt.org/vocab/unit/DEG"); 71 | public static readonly Uri DEG_C = new Uri("http://qudt.org/vocab/unit/DEG_C"); 72 | public static readonly Uri HP = new Uri("http://qudt.org/vocab/unit/HP"); 73 | public static readonly Uri HR = new Uri("http://qudt.org/vocab/unit/HR"); 74 | public static readonly Uri KiloGM = new Uri("http://qudt.org/vocab/unit/KiloGM"); 75 | public static readonly Uri KiloGM_PER_HR = new Uri("http://qudt.org/vocab/unit/KiloGM-PER-HR"); 76 | public static readonly Uri KiloPA = new Uri("http://qudt.org/vocab/unit/KiloPA"); 77 | public static readonly Uri KiloW_HR = new Uri("http://qudt.org/vocab/unit/KiloW-HR"); 78 | public static readonly Uri KiloW = new Uri("http://qudt.org/vocab/unit/KiloW"); 79 | public static readonly Uri L = new Uri("http://qudt.org/vocab/unit/L"); 80 | public static readonly Uri L_PER_SEC = new Uri("http://qudt.org/vocab/unit/L-PER-SEC"); 81 | public static readonly Uri LUX = new Uri("http://qudt.org/vocab/unit/LUX"); 82 | public static readonly Uri M = new Uri("http://qudt.org/vocab/unit/M"); 83 | public static readonly Uri MilliM = new Uri("http://qudt.org/vocab/unit/MilliM"); 84 | public static readonly Uri MIN = new Uri("http://qudt.org/vocab/unit/MIN"); 85 | public static readonly Uri N = new Uri("http://qudt.org/vocab/unit/N"); 86 | public static readonly Uri M_PER_SEC = new Uri("http://qudt.org/vocab/unit/M-PER-SEC"); 87 | public static readonly Uri PSI = new Uri("http://qudt.org/vocab/unit/PSI"); 88 | public static readonly Uri REV_PER_MIN = new Uri("http://qudt.org/vocab/unit/REV-PER-MIN"); 89 | public static readonly Uri V = new Uri("http://qudt.org/vocab/unit/V"); 90 | public static readonly Uri W = new Uri("http://qudt.org/vocab/unit/W"); 91 | } 92 | 93 | public static class QuantityKindNS 94 | { 95 | public static readonly Uri AngularVelocity = new Uri("http://qudt.org/vocab/quantitykind/AngularVelocity"); 96 | public static readonly Uri ElectricCurrent = new Uri("http://qudt.org/vocab/quantitykind/ElectricCurrent"); 97 | public static readonly Uri Illuminance = new Uri("http://qudt.org/vocab/quantitykind/Illuminance"); 98 | public static readonly Uri Angle = new Uri("http://qudt.org/vocab/quantitykind/Angle"); 99 | public static readonly Uri Energy = new Uri("http://qudt.org/vocab/quantitykind/Energy"); 100 | public static readonly Uri Force = new Uri("http://qudt.org/vocab/quantitykind/Force"); 101 | public static readonly Uri Power = new Uri("http://qudt.org/vocab/quantitykind/Power"); 102 | public static readonly Uri Length = new Uri("http://qudt.org/vocab/quantitykind/Length"); 103 | public static readonly Uri Mass = new Uri("http://qudt.org/vocab/quantitykind/Mass"); 104 | public static readonly Uri MassFlowRate = new Uri("http://qudt.org/vocab/quantitykind/MassFlowRate"); 105 | public static readonly Uri Pressure = new Uri("http://qudt.org/vocab/quantitykind/Pressure"); 106 | public static readonly Uri Time = new Uri("http://qudt.org/vocab/quantitykind/Time"); 107 | public static readonly Uri Temperature = new Uri("http://qudt.org/vocab/quantitykind/Temperature"); 108 | public static readonly Uri Velocity = new Uri("http://qudt.org/vocab/quantitykind/Velocity"); 109 | public static readonly Uri Voltage = new Uri("http://qudt.org/vocab/quantitykind/Voltage"); 110 | public static readonly Uri Volume = new Uri("http://qudt.org/vocab/quantitykind/Volume"); 111 | public static readonly Uri VolumeFlowRate = new Uri("http://qudt.org/vocab/quantitykind/VolumeFlowRate"); 112 | } 113 | 114 | } 115 | 116 | 117 | public static class DTDL 118 | { 119 | public static readonly string dtdlContext = "dtmi:dtdl:context;2"; 120 | public static readonly Uri Interface = new Uri("dtmi:dtdl:class:Interface;2"); 121 | public static readonly Uri Property = new Uri("dtmi:dtdl:class:Property;2"); 122 | public static readonly Uri Relationship = new Uri("dtmi:dtdl:class:Relationship;2"); 123 | public static readonly Uri Telemetry = new Uri("dtmi:dtdl:class:Telemetry;2"); 124 | public static readonly Uri Component = new Uri("dtmi:dtdl:class:Component;2"); 125 | public static readonly Uri name = new Uri("dtmi:dtdl:property:name;2"); 126 | public static readonly Uri contents = new Uri("dtmi:dtdl:property:contents;2"); 127 | public static readonly Uri displayName = new Uri("dtmi:dtdl:property:displayName;2"); 128 | public static readonly Uri description = new Uri("dtmi:dtdl:property:description;2"); 129 | public static readonly Uri extends = new Uri("dtmi:dtdl:property:extends;2"); 130 | public static readonly Uri maxMultiplicity = new Uri("dtmi:dtdl:property:maxMultiplicity;2"); 131 | public static readonly Uri minMultiplicity = new Uri("dtmi:dtdl:property:minMultiplicity;2"); 132 | public static readonly Uri target = new Uri("dtmi:dtdl:property:target;2"); 133 | public static readonly Uri schema = new Uri("dtmi:dtdl:property:schema;2"); 134 | public static readonly Uri Map = new Uri("dtmi:dtdl:class:Map;2"); 135 | public static readonly Uri Enum = new Uri("dtmi:dtdl:class:Enum;2"); 136 | public static readonly Uri EnumValue = new Uri("dtmi:dtdl:class:EnumValue;2"); 137 | public static readonly Uri valueSchema = new Uri("dtmi:dtdl:property:valueSchema;2"); 138 | public static readonly Uri enumValue = new Uri("dtmi:dtdl:property:enumValue;2"); 139 | public static readonly Uri enumValues = new Uri("dtmi:dtdl:property:enumValues;2"); 140 | public static readonly Uri comment = new Uri("dtmi:dtdl:property:comment;2"); 141 | public static readonly Uri writable = new Uri("dtmi:dtdl:property:writable;2"); 142 | public static readonly Uri unit = new Uri("dtmi:dtdl:property:unit;2"); 143 | public static readonly Uri properties = new Uri("dtmi:dtdl:property:properties;2"); 144 | public static readonly Uri mapKey = new Uri("dtmi:dtdl:property:mapKey;2"); 145 | public static readonly Uri mapValue = new Uri("dtmi:dtdl:property:mapValue;2"); 146 | 147 | public static readonly Uri _string = new Uri("dtmi:dtdl:instance:Schema:string;2"); 148 | public static readonly Uri _boolean = new Uri("dtmi:dtdl:instance:Schema:boolean;2"); 149 | public static readonly Uri _integer = new Uri("dtmi:dtdl:instance:Schema:integer;2"); 150 | public static readonly Uri _date = new Uri("dtmi:dtdl:instance:Schema:date;2"); 151 | public static readonly Uri _dateTime = new Uri("dtmi:dtdl:instance:Schema:dateTime;2"); 152 | public static readonly Uri _double = new Uri("dtmi:dtdl:instance:Schema:double;2"); 153 | public static readonly Uri _duration = new Uri("dtmi:dtdl:instance:Schema:duration;2"); 154 | public static readonly Uri _float = new Uri("dtmi:dtdl:instance:Schema:float;2"); 155 | public static readonly Uri _long = new Uri("dtmi:dtdl:instance:Schema:long;2"); 156 | 157 | 158 | public static readonly Uri ampere = new Uri("dtmi:standard:unit:ampere;2"); 159 | public static readonly Uri volt = new Uri("dtmi:standard:unit:volt;2"); 160 | public static readonly Uri centimetre = new Uri("dtmi:standard:unit:centimetre;2"); 161 | public static readonly Uri degreeCelsius = new Uri("dtmi:standard:unit:degreeCelsius;2"); 162 | public static readonly Uri degreeOfArc = new Uri("dtmi:standard:unit:degreeOfArc;2"); 163 | public static readonly Uri horsepower = new Uri("dtmi:standard:unit:horsepower;2"); 164 | public static readonly Uri hour = new Uri("dtmi:standard:unit:hour;2"); 165 | public static readonly Uri kilogram = new Uri("dtmi:standard:unit:kilogram;2"); 166 | public static readonly Uri kilogramPerHour = new Uri("dtmi:standard:unit:kilogramPerHour;2"); 167 | public static readonly Uri kilopascal = new Uri("dtmi:standard:unit:kilopascal;2"); 168 | public static readonly Uri kilowattHour = new Uri("dtmi:standard:unit:kilowattHour;2"); 169 | public static readonly Uri kilowatt = new Uri("dtmi:standard:unit:kilowatt;2"); 170 | public static readonly Uri litre = new Uri("dtmi:standard:unit:litre;2"); 171 | public static readonly Uri litrePerSecond = new Uri("dtmi:standard:unit:litrePerSecond;2"); 172 | public static readonly Uri lux = new Uri("dtmi:standard:unit:lux;2"); 173 | public static readonly Uri metre = new Uri("dtmi:standard:unit:metre;2"); 174 | public static readonly Uri metrePerSecond = new Uri("dtmi:standard:unit:metrePerSecond;2"); 175 | public static readonly Uri millimetre = new Uri("dtmi:standard:unit:millimetre;2"); 176 | public static readonly Uri minute = new Uri("dtmi:standard:unit:minute;2"); 177 | public static readonly Uri newton = new Uri("dtmi:standard:unit:newton;2"); 178 | public static readonly Uri poundPerSquareInch = new Uri("dtmi:standard:unit:poundPerSquareInch;2"); 179 | public static readonly Uri revolutionPerMinute = new Uri("dtmi:standard:unit:revolutionPerMinute;2"); 180 | public static readonly Uri watt = new Uri("dtmi:standard:unit:watt;2"); 181 | 182 | public static readonly Uri Angle = new Uri("dtmi:standard:class:Angle;2"); 183 | public static readonly Uri AngularVelocity = new Uri("dtmi:standard:class:AngularVelocity;2"); 184 | public static readonly Uri Current = new Uri("dtmi:standard:class:Current;2"); 185 | public static readonly Uri Energy = new Uri("dtmi:standard:class:Energy;2"); 186 | public static readonly Uri Force = new Uri("dtmi:standard:class:Force;2"); 187 | public static readonly Uri Illuminance = new Uri("dtmi:standard:class:Illuminance;2"); 188 | public static readonly Uri Voltage = new Uri("dtmi:standard:class:Voltage;2"); 189 | public static readonly Uri Power = new Uri("dtmi:standard:class:Power;2"); 190 | public static readonly Uri Pressure = new Uri("dtmi:standard:class:Pressure;2"); 191 | public static readonly Uri Length = new Uri("dtmi:standard:class:Length;2"); 192 | public static readonly Uri Mass = new Uri("dtmi:standard:class:Mass;2"); 193 | public static readonly Uri MassFlowRate = new Uri("dtmi:standard:class:MassFlowRate;2"); 194 | public static readonly Uri Temperature = new Uri("dtmi:standard:class:Temperature;2"); 195 | public static readonly Uri TimeSpan = new Uri("dtmi:standard:class:TimeSpan;2"); 196 | public static readonly Uri Volume = new Uri("dtmi:standard:class:Volume;2"); 197 | public static readonly Uri Velocity = new Uri("dtmi:standard:class:Velocity;2"); 198 | public static readonly Uri VolumeFlowRate = new Uri("dtmi:standard:class:VolumeFlowRate;2"); 199 | 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /OWL2DTDL/README.md: -------------------------------------------------------------------------------- 1 | # The OWL2DTDL Converter 2 | 3 | **Author:** [Karl Hammar](https://hammar.dev) 4 | 5 | The OWL2DTDL converter is a tool that translates an OWL ontology or an ontology network (one root ontology reusing other ontologies through `owl:imports` declarations) into a set of DTDL Interface declarations for use, e.g., with the Azure Digital Twins service. This converter is a work-in-progress; if you find bugs, do not hesitate to contact the author. 6 | 7 | ## Example usage 8 | 9 | `./OWL2DTDL -u https://w3id.org/rec/full/3.3/ -i ./RecIgnoredNames.csv -o /Users/karl/Desktop/DTDL/` 10 | 11 | ## Options 12 | 13 | ``` 14 | -n, --no-imports Sets program to not follow owl:Imports declarations. 15 | 16 | -f, --file-path Required. The path to the on-disk root ontology file 17 | to translate. 18 | 19 | -u, --uri-path Required. The URI of the root ontology file to 20 | translate. 21 | 22 | -o, --outputPath Required. The directory in which to create DTDL 23 | models. 24 | 25 | -m, --merged-output Sets program to output one merged JSON-LD file for 26 | batch import into ADT. 27 | 28 | -i, --ignorefile Path to a CSV file, the first column of which lists 29 | (whole or partial) IRI:s that should be ignored by 30 | this tool and not translated into DTDL output. 31 | 32 | -s, --ontologySource An identifier for the ontology source; will be used to 33 | generate DTMI:s per the following design, where 34 | interfaceName is the local name of a translated OWL 35 | class, and ontologyName is the last segment of the 36 | translated class's namespace: 37 | . 39 | 40 | --help Display this help screen. 41 | 42 | --version Display version information. 43 | ``` 44 | 45 | **Note:** The `-f` and `-u` options are mutually exclusive; only one of the two should be provided. If both are given, `-f` takes priority. 46 | 47 | ## Supported OWL features 48 | 49 | ### owl:Class 50 | 51 | * Named OWL classes are translated into DTDL Interfaces. 52 | * Anonymous classes are ignored. 53 | 54 | ### owl:ObjectProperty 55 | 56 | * Object properties that are defined for a class (i.e., that are used in an OWL restriction on that class itself, or that have that class as defined rdfs:domain) are become DTDL Relationships on that Interface. 57 | * As DTDL only allows a single Target definition per Relationship, we only map such properties that have named singleton ranges (targets). More complex properties are ignored (for now). 58 | 59 | ### owl:DataProperty 60 | 61 | * Data Properties that are defined for a class (i.e., that are either used in a restriction on that class itself, or have that class as defined rdfs:domain) become DTDL Properties on that Interface. 62 | * Data properties that have ranges that are XSD base types are translated into corresponding DTDL primitive schemas per the table below. 63 | * Ranges that are custom data types that derive from exactly one built-in XSD base type gets translated the same way, with a comment added to the parent Property indicating the label of the derived type (e.g., "LitersPerMinute" for an int). 64 | 65 | ### owl:AnnotationProperty on owl:ObjectProperty 66 | 67 | OWL annotation properties that have an object property defined as their rdfs:domains are translated into DTDL Properties on the corresponding DTDL Relationships (see above). Per this approach, the property-graph behaviour of DTDL can be loosely emulated in OWL. 68 | 69 | ### Documentation and Deprecation 70 | 71 | * rdfs:labels become DTDL displayNames; language tags are maintained. 72 | * rdfs:comments become DTDL comments; language tags are maintained. 73 | * Entities that are marked as deprecated (i.e., are annotated with the property owl:deprecated and the boolean value true) are ignored in translation. 74 | 75 | ### DTMI Minting 76 | 77 | DTMI:s for named classes are minted based on the classes' URIs by concatenating five components: 78 | 79 | * The `"dtmi:digitaltwins:"` prefix 80 | * The `ontology source`, either given by a CLI option (`-s`), or generated by reverting the hostname and concatenating with the path segments excluding those that go into the `ontology name` or `local name`, see below 81 | * The `ontology name`: the last fragment of the URI before the `local name` 82 | * The `local name` of the class 83 | * The DTMI version identifier; for now hardcoded as `";1"` 84 | 85 | E.g., `https://w3id.org/rec/device/Actuator` becomes `dtmi:digitaltwins:org:w3id:rec:device:Actuator;1`. If the CLI option `-s rec_3_3` is given it becomes `dtmi:digitaltwins:rec_3_3:device:Actuator;1` 86 | 87 | ### Mapping OWL model to DTDL 88 | 89 | The following table maps key OWL constructs to DTDL. This map is used by the OWL2DTDL application to convert REC from OWL to DTDL. For detailed mappings, refer to the OWL2DTDL source code. 90 | 91 | | OWL Construct | | DTDL Construct | | 92 | |---------------------|----------------------|----------------------|------------------------------------| 93 | | Classes | owl:Class | Interface | @type:Interface | 94 | | | rdfs:label | | @id, displayName | 95 | | | rdfs:comment | | description | 96 | | Subclasses | owl:Class | Interface | @type:Interface | 97 | | | rdfs:label | | @id, displayName | 98 | | | rdfs:comment | | description | 99 | | | rdfs:subClassOf | | extends | 100 | | Datatype Properties | owl:DatatypeProperty | Interface Properties | @type:Property | 101 | | | rdfs:label | | displayName | 102 | | | rdfs:range | | schema | 103 | | Object Properties | owl:ObjectProperty | Relationship | @type:Relationship | 104 | | | rdfs:range | | target or omitted if no rdfs:range | 105 | | | rdfs:comment | | description | 106 | | | rdfs:label | | displayName | 107 | | Object Properties | rdfs:subClassOf + | Relationship | @type:Relationship | 108 | | | owl:Restriction | | | 109 | | | owl:onProperty | | name, description | 110 | | | owl:allValuesFrom | | target | 111 | 112 | 113 | ## Translation examples 114 | 115 | ### RealEstateCore Space 116 | 117 | The RealEstateCore 3.3 Space class is given below. Its translation into DTDL using this tool is provided in the subsequent listing. Note that the two restrictions on the property `hasGeometry` are filtered out of the DTDL translation, as the `Geometry` class is included in the file ignored classes listing passed in using the command line option `-i`. 118 | 119 | **Source OWL version of REC Space:** 120 | 121 | ```xml 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | A contiguous part of the physical world that has a 3D spatial extent and that contains or can contain sub-spaces. E.g., a Region can contain many pieces of Land, which in turn can contain many Buildings. 202 | Space 203 | 204 | ``` 205 | 206 | **Resulting DTDL version of REC Space:** 207 | 208 | ```yaml 209 | { 210 | "@id": "dtmi:digitaltwins:rec_3_3:core:Space;1", 211 | "@type": "Interface", 212 | "dtmi:dtdl:property:contents;2": [ 213 | { 214 | "@type": "Property", 215 | "description": { 216 | "en": "The number of people presently occupying a Space." 217 | }, 218 | "displayName": { 219 | "en": "person occupancy" 220 | }, 221 | "name": "personOccupancy", 222 | "schema": "integer", 223 | "writable": true 224 | }, 225 | { 226 | "@type": "Property", 227 | "description": { 228 | "en": "The number of people who can fit in a Space." 229 | }, 230 | "displayName": { 231 | "en": "person capacity" 232 | }, 233 | "name": "personCapacity", 234 | "schema": "integer", 235 | "writable": true 236 | }, 237 | { 238 | "@type": "Relationship", 239 | "description": { 240 | "en": "Indicates that a Space or Asset is served by some Sensor/Actuator or other Asset. For example: an entrance room might be served by (e.g., covered by) some camera equipment, or a conference room served by a CO2 sensor. Note that Assets can also service one another, e.g., an air-treatment Asset might serve an air diffuser Asset. Inverse of: serves" 241 | }, 242 | "displayName": { 243 | "en": "served by" 244 | }, 245 | "name": "servedBy" 246 | }, 247 | { 248 | "@type": "Relationship", 249 | "description": { 250 | "en": "Property that defines the legal owner(s) of a given entity. Inverse of: owns" 251 | }, 252 | "displayName": { 253 | "en": "owned by" 254 | }, 255 | "name": "ownedBy", 256 | "target": "dtmi:digitaltwins:rec_3_3:core:Agent;1" 257 | }, 258 | { 259 | "@type": "Relationship", 260 | "displayName": { 261 | "en": "operated by" 262 | }, 263 | "name": "operatedBy", 264 | "target": "dtmi:digitaltwins:rec_3_3:core:Agent;1" 265 | }, 266 | { 267 | "@type": "Relationship", 268 | "description": { 269 | "en": "Indicates a super-entity of the same base type (i.e., Spaces only have Spaces as parents, Organizations only have Organizations, etc). Inverse of: hasPart" 270 | }, 271 | "displayName": { 272 | "en": "is part of" 273 | }, 274 | "name": "isPartOf", 275 | "target": "dtmi:digitaltwins:rec_3_3:core:Space;1" 276 | }, 277 | { 278 | "@type": "Relationship", 279 | "description": { 280 | "en": "Indicates that an entity is included in some Collection, e.g., a Building is included in a RealEstate, or a Room is included in an Apartment. Inverse of: includes" 281 | }, 282 | "displayName": { 283 | "en": "included in" 284 | }, 285 | "name": "includedIn", 286 | "target": "dtmi:digitaltwins:rec_3_3:core:Collection;1" 287 | }, 288 | { 289 | "@type": "Relationship", 290 | "description": { 291 | "en": "Points to sub-entities that share the same base type (i.e., Spaces only have Spaces as parts, Assets only have Assets as parts, etc.). Inverse of: isPartOf" 292 | }, 293 | "displayName": { 294 | "en": "has part" 295 | }, 296 | "name": "hasPart", 297 | "target": "dtmi:digitaltwins:rec_3_3:core:Space;1" 298 | }, 299 | { 300 | "@type": "Relationship", 301 | "displayName": { 302 | "en": "has capability" 303 | }, 304 | "name": "hasCapability", 305 | "target": "dtmi:digitaltwins:rec_3_3:core:Capability;1" 306 | }, 307 | { 308 | "@type": "Relationship", 309 | "displayName": { 310 | "en": "constructed by" 311 | }, 312 | "name": "constructedBy", 313 | "target": "dtmi:digitaltwins:rec_3_3:core:Agent;1" 314 | }, 315 | { 316 | "@type": "Relationship", 317 | "displayName": { 318 | "en": "architected by" 319 | }, 320 | "name": "architectedBy", 321 | "target": "dtmi:digitaltwins:rec_3_3:core:Agent;1" 322 | } 323 | ], 324 | "description": { 325 | "en": "A contiguous part of the physical world that has a 3D spatial extent and that contains or can contain sub-spaces. E.g., a Region can contain many pieces of Land, which in turn can contain many Buildings." 326 | }, 327 | "displayName": { 328 | "en": "Space" 329 | }, 330 | "@context": "dtmi:dtdl:context;2" 331 | } 332 | ``` 333 | 334 | ### Equipment feeds/isFedBy Relationship with embedded Property 335 | 336 | The `substance` annotation property given below applies to two OWL object properties, `feeds` and `isFedBy`, which are in turn used in restrictions on the `Equipment` class. The range of `substance` range, reproduced below in abbreviated form, is a custom datatype based on an enumeration. When passed through OWL2DTDL, the two object properties become DTDL Relationship declarations on `Equipment`, with nested `substance` Properties on them, using an enumeration schema corresponding to the OWL custom datatype. 337 | 338 | **Properties**: 339 | 340 | ```xml 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | is fed by 349 | 350 | 351 | 352 | 353 | feeds 354 | 355 | ``` 356 | 357 | **Class that object properties apply to:** 358 | 359 | ```xml 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | Equipment that is permanently or semi-permanently mounted or installed in a building, e.g., HVAC systems, electrical systems, elevators, CC-TV-systems, etc. 375 | Equipment 376 | 377 | ``` 378 | 379 | **Annotation property range (custom datatype):** 380 | ```xml 381 | 382 | 383 | 384 | 385 | 386 | 387 | ACElec 388 | 389 | 390 | 391 | Air 392 | 393 | 394 | 395 | BlowdownWater 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | ``` 407 | 408 | **Resulting DTDL version of Equipment:** 409 | 410 | ```yaml 411 | { 412 | "@id": "dtmi:digitaltwins:rec_3_3:asset:Equipment;1", 413 | "@type": "Interface", 414 | "dtmi:dtdl:property:contents;2": [ 415 | { 416 | "@type": "Relationship", 417 | "displayName": { 418 | "en": "is fed by" 419 | }, 420 | "name": "isFedBy", 421 | "dtmi:dtdl:property:properties;2": { 422 | "@type": "Property", 423 | "name": "substance", 424 | "dtmi:dtdl:property:schema;2": { 425 | "@type": "Enum", 426 | "dtmi:dtdl:property:enumValues;2": [ 427 | { 428 | "enumValue": "ACElec", 429 | "name": "ACElec" 430 | }, 431 | { 432 | "enumValue": "Air", 433 | "name": "Air" 434 | }, 435 | { 436 | "enumValue": "BlowdownWater", 437 | "name": "BlowdownWater" 438 | } 439 | ], 440 | "valueSchema": "string" 441 | }, 442 | "writable": true 443 | } 444 | } 445 | ], 446 | "description": { 447 | "en": "Equipment that is permanently or semi-permanently mounted or installed in a building, e.g., HVAC systems, electrical systems, elevators, CC-TV-systems, etc." 448 | }, 449 | "displayName": { 450 | "en": "Equipment" 451 | }, 452 | "extends": "dtmi:digitaltwins:rec_3_3:core:Asset;1", 453 | "@context": "dtmi:dtdl:context;2" 454 | } 455 | ``` 456 | -------------------------------------------------------------------------------- /OWL2DTDL/DotNetRdfExtensions.cs: -------------------------------------------------------------------------------- 1 | using OWL2DTDL.VocabularyHelper; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Globalization; 5 | using System.IO; 6 | using System.Linq; 7 | using VDS.RDF; 8 | using VDS.RDF.Ontology; 9 | using VDS.RDF.Parsing; 10 | 11 | namespace OWL2DTDL 12 | { 13 | /// 14 | /// Various extensions to DotNetRdf, particularly relating to the VDS.RDF.Ontology functionality. 15 | /// 16 | public static class DotNetRdfExtensions 17 | { 18 | 19 | // Used in string handling etc 20 | private static readonly CultureInfo invariantCulture = CultureInfo.InvariantCulture; 21 | 22 | #region Shared 23 | /// 24 | /// Custom comparer for OntologyResource objects, that simply 25 | /// defers to comparison of nested INodes. 26 | /// 27 | class OntologyResourceComparer : IEqualityComparer 28 | { 29 | public bool Equals(OntologyResource x, OntologyResource y) 30 | { 31 | return x.Resource.Equals(y.Resource); 32 | } 33 | 34 | public int GetHashCode(OntologyResource obj) 35 | { 36 | return obj.Resource.GetHashCode(); 37 | } 38 | } 39 | #endregion 40 | 41 | #region INode/ILiteralNode/IUriNode extensions 42 | public static bool IsLiteral(this INode node) 43 | { 44 | return node.NodeType.Equals(NodeType.Literal); 45 | } 46 | 47 | public static bool IsUri(this INode node) 48 | { 49 | return node.NodeType.Equals(NodeType.Uri); 50 | } 51 | 52 | public static IUriNode AsUriNode(this INode node) 53 | { 54 | if (!node.IsUri()) 55 | { 56 | throw new RdfException($"Node {node} is not an URI node."); 57 | } 58 | return node as IUriNode; 59 | } 60 | 61 | public static string GetLocalName(this IUriNode node) 62 | { 63 | if (node.Uri.Fragment.Length > 0) 64 | { 65 | return node.Uri.Fragment.Trim('#'); 66 | } 67 | return Path.GetFileName(node.Uri.AbsolutePath); 68 | } 69 | 70 | public static IEnumerable DtdlTypes(this IUriNode node) 71 | { 72 | IGraph g = node.Graph; 73 | IUriNode dtdlType = g.CreateUriNode(new Uri("https://w3id.org/rec/metadata/dtdlType")); 74 | return g.GetTriplesWithSubjectPredicate(node, dtdlType).Select(trip => trip.Object).LiteralNodes().Select(litNode => litNode.Value); 75 | } 76 | 77 | // TODO This should probably be fixed to handle URN namespaces properly.. 78 | public static Uri GetNamespace(this IUriNode node) 79 | { 80 | if (node.Uri.Fragment.Length > 0) 81 | { 82 | return new Uri(node.Uri.GetLeftPart(UriPartial.Path) + "#"); 83 | } 84 | string nodeUriPath = node.Uri.GetLeftPart(UriPartial.Path); 85 | if (nodeUriPath.Count(x => x == '/') >= 3) 86 | { 87 | string nodeUriBase = nodeUriPath.Substring(0, nodeUriPath.LastIndexOf("/", StringComparison.Ordinal) + 1); 88 | return new Uri(nodeUriBase); 89 | } 90 | throw new UriFormatException($"The Uri {node.Uri} doesn't contain a namespace/local name separator."); 91 | } 92 | 93 | public static bool IsInteger(this ILiteralNode node) 94 | { 95 | Uri dataTypeUri = node.DataType; 96 | if (dataTypeUri == null) 97 | { 98 | return false; 99 | } 100 | string datatype = dataTypeUri.AbsoluteUri; 101 | return datatype.StartsWith(XmlSpecsHelper.NamespaceXmlSchema, StringComparison.Ordinal) 102 | && (datatype.EndsWith("Integer", StringComparison.Ordinal) || datatype.EndsWith("Int", StringComparison.Ordinal)); 103 | } 104 | #endregion 105 | 106 | #region OntologyResource extensions 107 | 108 | public static bool HasOwlVersionInfo(this OntologyResource resource) 109 | { 110 | INode owlVersionInfo = resource.Graph.CreateUriNode(VocabularyHelper.OWL.versionInfo); 111 | IEnumerable owlVersionInfos = resource.GetNodesViaPredicate(owlVersionInfo); 112 | if (owlVersionInfos.LiteralNodes().Any()) { 113 | return true; 114 | } 115 | return false; 116 | } 117 | 118 | public static string GetOwlVersionInfo(this OntologyResource resource) { 119 | 120 | if (!resource.HasOwlVersionInfo()) 121 | { 122 | throw new RdfException($"Resource {resource} does not have an owl:versionInfo annotation"); 123 | } 124 | 125 | INode owlVersionInfo = resource.Graph.CreateUriNode(VocabularyHelper.OWL.versionInfo); 126 | return resource.GetNodesViaPredicate(owlVersionInfo).LiteralNodes().First().Value; 127 | } 128 | 129 | public static bool IsNamed(this OntologyResource ontResource) 130 | { 131 | return ontResource.Resource.IsUri(); 132 | } 133 | 134 | public static bool IsBuiltIn(this OntologyResource ontologyResource) 135 | { 136 | if (!ontologyResource.IsNamed()) 137 | { 138 | return false; 139 | } 140 | 141 | HashSet builtIns = new HashSet() { 142 | "http://www.w3.org/1999/02/22-rdf-syntax-ns#", 143 | "http://www.w3.org/2000/01/rdf-schema#", 144 | "http://www.w3.org/2002/07/owl#", 145 | "http://www.w3.org/2001/XMLSchema#" 146 | }; 147 | return builtIns.Any(builtin => ontologyResource.GetUri().AbsoluteUri.Contains(builtin)); 148 | } 149 | 150 | public static IEnumerable GetNodesViaPredicate(this OntologyResource resource, INode predicate) 151 | { 152 | return resource.Graph.GetTriplesWithSubjectPredicate(resource.Resource, predicate).Select(triple => triple.Object); 153 | } 154 | 155 | public static IUriNode GetUriNode(this OntologyResource ontResource) 156 | { 157 | if (!ontResource.IsNamed()) 158 | { 159 | throw new RdfException($"Ontology resource {ontResource} does not have an IRI."); 160 | } 161 | return ontResource.Resource.AsUriNode(); 162 | } 163 | 164 | public static Uri GetUri(this OntologyResource ontResource) 165 | { 166 | return ontResource.GetUriNode().Uri; 167 | } 168 | 169 | public static Uri GetNamespace(this OntologyResource ontResource) 170 | { 171 | return ontResource.GetUriNode().GetNamespace(); 172 | } 173 | 174 | public static string GetLocalName(this OntologyResource ontResource) 175 | { 176 | return ontResource.GetUriNode().GetLocalName(); 177 | } 178 | 179 | public static bool IsDeprecated(this OntologyResource resource) 180 | { 181 | IUriNode deprecated = resource.Graph.CreateUriNode(OWL.deprecated); 182 | return resource.GetNodesViaPredicate(deprecated).LiteralNodes().Any(node => node.Value == "true"); 183 | } 184 | #endregion 185 | 186 | #region OntologyClass extensions 187 | 188 | public static int Depth(this OntologyClass oClass) 189 | { 190 | int largestParentDepth = 0; 191 | foreach (OntologyClass superClass in oClass.DirectSuperClasses) 192 | { 193 | int superClassDepth = superClass.Depth(); 194 | if (superClassDepth > largestParentDepth) 195 | { 196 | largestParentDepth = superClassDepth; 197 | } 198 | } 199 | return largestParentDepth + 1; 200 | } 201 | 202 | public static List LongestParentPathToOwlThing(this OntologyClass oClass) 203 | { 204 | IUriNode rdfsSubClassOf = oClass.Graph.CreateUriNode(RDFS.subClassOf); 205 | IEnumerable directSuperClasses = oClass.DirectSuperClasses.Where( 206 | parentClass => 207 | parentClass.IsNamed() && 208 | !parentClass.IsDeprecated() && 209 | !Program.PropertyAssertionIsDeprecated(oClass.GetUriNode(), rdfsSubClassOf, parentClass.GetUriNode()) 210 | ); 211 | 212 | // If we have no superclass or one of our superclasses is OWL:Thing, then we have reached the top level; return 213 | if (directSuperClasses.Count() < 1 || directSuperClasses.Any(superClass => superClass.IsOwlThing())) 214 | { 215 | return new List(); 216 | } 217 | else 218 | { 219 | // Assume the first parent has the longest path; if not, it will be replaced in subsequent foreach 220 | OntologyClass longestParent = directSuperClasses.First(); 221 | List longestParentPath = longestParent.LongestParentPathToOwlThing(); 222 | // Iterate through the other parents to see if any is longer 223 | foreach (OntologyClass possibleSuperClass in directSuperClasses.Skip(1)) 224 | { 225 | List possibleSuperClassParents = possibleSuperClass.LongestParentPathToOwlThing(); 226 | if (possibleSuperClassParents.Count() > longestParentPath.Count()) 227 | { 228 | longestParent = possibleSuperClass; 229 | longestParentPath = possibleSuperClassParents; 230 | } 231 | } 232 | 233 | // At this point shortestParentPath + shortestParent should together contain the shortest path to the root; return them 234 | longestParentPath.Add(longestParent.GetLocalName()); 235 | return longestParentPath; 236 | } 237 | } 238 | 239 | public static List ShortestParentPathToOwlThing(this OntologyClass oClass) 240 | { 241 | IUriNode rdfsSubClassOf = oClass.Graph.CreateUriNode(RDFS.subClassOf); 242 | IEnumerable directSuperClasses = oClass.DirectSuperClasses.Where( 243 | parentClass => 244 | parentClass.IsNamed() && 245 | !parentClass.IsDeprecated() && 246 | !Program.PropertyAssertionIsDeprecated(oClass.GetUriNode(), rdfsSubClassOf, parentClass.GetUriNode()) 247 | ); 248 | 249 | // If we have no superclass or one of our superclasses is OWL:Thing, then we have reached the top level; return 250 | if (directSuperClasses.Count() < 1 || directSuperClasses.Any(superClass => superClass.IsOwlThing())) 251 | { 252 | return new List(); 253 | } 254 | else 255 | { 256 | // Assume the first parent has the shortest path; if not, it will be replaced in subsequent foreach 257 | OntologyClass shortestParent = directSuperClasses.First(); 258 | List shortestParentPath = shortestParent.ShortestParentPathToOwlThing(); 259 | // Iterate through the other parents to see if any is shorter 260 | foreach (OntologyClass possibleSuperClass in directSuperClasses.Skip(1)) 261 | { 262 | List possibleSuperClassParents = possibleSuperClass.ShortestParentPathToOwlThing(); 263 | if (possibleSuperClassParents.Count() < shortestParentPath.Count()) 264 | { 265 | shortestParent = possibleSuperClass; 266 | shortestParentPath = possibleSuperClassParents; 267 | } 268 | } 269 | 270 | // At this point shortestParentPath + shortestParent should together contain the shortest path to the root; return them 271 | shortestParentPath.Add(shortestParent.GetLocalName()); 272 | return shortestParentPath; 273 | } 274 | } 275 | 276 | public static bool IsRestriction(this OntologyClass oClass) 277 | { 278 | return oClass.Types.UriNodes().Any(classType => classType.Uri.ToString().Equals(VocabularyHelper.OWL.Restriction.ToString())); 279 | } 280 | 281 | public static bool IsDatatype(this OntologyClass oClass) 282 | { 283 | return oClass.IsXsdDatatype() || oClass.Types.UriNodes().Any(classType => classType.Uri.AbsoluteUri.Equals(VocabularyHelper.RDFS.Datatype.AbsoluteUri)); 284 | } 285 | 286 | public static bool IsEnumerationDatatype(this OntologyClass oClass) 287 | { 288 | INode oneOf = oClass.Graph.CreateUriNode(VocabularyHelper.OWL.oneOf); 289 | if (oClass.IsDatatype()) { 290 | if (oClass.EquivalentClasses.Count() == 1) { 291 | return oClass.EquivalentClasses.Single().GetNodesViaPredicate(oneOf).Count() == 1; 292 | } 293 | else 294 | { 295 | return oClass.GetNodesViaPredicate(oneOf).Count() == 1; 296 | } 297 | } 298 | 299 | return false; 300 | } 301 | 302 | public static bool IsSimpleXsdWrapper(this OntologyClass oClass) 303 | { 304 | if (oClass.IsDatatype() && oClass.EquivalentClasses.Count() == 1) 305 | { 306 | return oClass.EquivalentClasses.Single().IsXsdDatatype(); 307 | } 308 | return false; 309 | } 310 | 311 | public static bool IsQudtUnit(this OntologyClass oClass) 312 | { 313 | return oClass.Types.UriNodes().Any(t => t.Uri.AbsoluteUri.Equals(VocabularyHelper.QUDT.Unit.AbsoluteUri)); 314 | } 315 | 316 | public static IEnumerable AsEnumeration(this OntologyClass oClass) 317 | { 318 | INode oneOf = oClass.Graph.CreateUriNode(VocabularyHelper.OWL.oneOf); 319 | INode list = oClass.EquivalentClasses.Append(oClass).SelectMany(equiv => equiv.GetNodesViaPredicate(oneOf)).First(); 320 | return oClass.Graph.GetListItems(list); 321 | } 322 | 323 | public static bool IsOwlThing(this OntologyClass oClass) 324 | { 325 | return oClass.IsNamed() && oClass.GetUri().AbsoluteUri.Equals(OWL.Thing.AbsoluteUri); 326 | } 327 | 328 | public static bool IsXsdDatatype(this OntologyClass oClass) 329 | { 330 | if (oClass.IsNamed()) 331 | { 332 | return oClass.GetUri().AbsoluteUri.StartsWith(XmlSpecsHelper.NamespaceXmlSchema, StringComparison.Ordinal); 333 | } 334 | return false; 335 | } 336 | 337 | public static IEnumerable GetRelationships(this OntologyClass cls) 338 | { 339 | List relationships = new List(); 340 | 341 | // Start w/ rdfs:domain declarations. At this time we only consider no-range (i.e., 342 | // range is owl:Thing) or named singleton ranges 343 | IEnumerable rdfsDomainProperties = cls.IsDomainOf.Where( 344 | property => 345 | property.Ranges.Count() == 0 || 346 | (property.Ranges.Count() == 1 && (property.Ranges.First().IsNamed() || property.Ranges.First().IsDatatype()))); 347 | foreach (OntologyProperty property in rdfsDomainProperties) 348 | { 349 | Relationship newRelationship; 350 | if (property.Ranges.Count() == 0) 351 | { 352 | OntologyGraph oGraph = cls.Graph as OntologyGraph; 353 | OntologyClass target; 354 | if (property.IsObjectProperty()) 355 | { 356 | target = oGraph.CreateOntologyClass(VocabularyHelper.OWL.Thing); 357 | } 358 | else 359 | { 360 | target = oGraph.CreateOntologyClass(VocabularyHelper.RDFS.Literal); 361 | } 362 | newRelationship = new Relationship(property, target); 363 | } 364 | else 365 | { 366 | OntologyClass range = property.Ranges.First(); 367 | newRelationship = new Relationship(property, range); 368 | } 369 | 370 | if (property.IsFunctional()) 371 | { 372 | newRelationship.ExactCount = 1; 373 | } 374 | 375 | relationships.Add(newRelationship); 376 | } 377 | 378 | // Continue w/ OWL restrictions on the class 379 | IEnumerable ontologyRestrictions = cls.DirectSuperClasses 380 | .Where(superClass => superClass.IsRestriction()) 381 | .Select(superClass => new OntologyRestriction(superClass)); 382 | foreach (OntologyRestriction ontologyRestriction in ontologyRestrictions) 383 | { 384 | 385 | 386 | OntologyProperty restrictionProperty = ontologyRestriction.OnProperty; 387 | OntologyClass restrictionClass = ontologyRestriction.OnClass; 388 | if (restrictionProperty.IsNamed() && (restrictionClass.IsNamed() || restrictionClass.IsDatatype())) 389 | { 390 | Relationship newRelationship = new Relationship(restrictionProperty, restrictionClass); 391 | 392 | int min = ontologyRestriction.MinimumCardinality; 393 | int exactly = ontologyRestriction.ExactCardinality; 394 | int max = ontologyRestriction.MaximumCardinality; 395 | 396 | if (min != 0) 397 | newRelationship.MinimumCount = min; 398 | if (exactly != 0) 399 | newRelationship.ExactCount = exactly; 400 | if (max != 0) 401 | newRelationship.MaximumCount = max; 402 | 403 | relationships.Add(newRelationship); 404 | } 405 | } 406 | 407 | // Iterate over the gathered list of Relationships and narrow down to the most specific ones, using a Dictionary for lookup and the MergeWith() method for in-place narrowing 408 | Dictionary relationshipsDict = new Dictionary(new OntologyResourceComparer()); 409 | foreach (Relationship relationship in relationships) 410 | { 411 | OntologyProperty property = relationship.Property; 412 | OntologyResource target = relationship.Target; 413 | // If we already have this property listed in the dictionary, first narrow down the relationship by combining it with the old copy 414 | if (relationshipsDict.ContainsKey(property)) 415 | { 416 | Relationship oldRelationship = relationshipsDict[property]; 417 | relationship.MergeWith(oldRelationship); 418 | } 419 | // Put relationship in the dictionary 420 | relationshipsDict[property] = relationship; 421 | } 422 | 423 | // Return the values 424 | return relationshipsDict.Values; 425 | } 426 | 427 | public static IEnumerable DtdlTypes(this OntologyClass oClass) 428 | { 429 | if (oClass.IsNamed()) 430 | { 431 | return oClass.GetUriNode().DtdlTypes(); 432 | } 433 | return new List(); 434 | } 435 | 436 | public static IEnumerable SuperClassesWithOwlThing(this OntologyClass cls) 437 | { 438 | IGraph graph = cls.Graph; 439 | IUriNode owlThing = graph.CreateUriNode(VocabularyHelper.OWL.Thing); 440 | OntologyClass owlThingClass = new OntologyClass(owlThing, graph); 441 | return cls.SuperClasses.Append(owlThingClass); 442 | } 443 | #endregion 444 | 445 | #region OntologyProperty extensions 446 | public static bool IsFunctional(this OntologyProperty property) 447 | { 448 | // Note the toString-based comparison; because .NET Uri class does not differentiate by Uri fragment! 449 | return property.Types.UriNodes().Any(propertyType => propertyType.Uri.ToString().Equals(VocabularyHelper.OWL.FunctionalProperty.ToString())); 450 | } 451 | 452 | public static bool IsObjectProperty(this OntologyProperty property) 453 | { 454 | return property.Types.UriNodes().Any(propertyType => propertyType.Uri.ToString().Equals(OntologyHelper.OwlObjectProperty, StringComparison.Ordinal)); 455 | } 456 | 457 | public static bool IsDataProperty(this OntologyProperty property) 458 | { 459 | return property.Types.UriNodes().Any(propertyType => propertyType.Uri.ToString().Equals(OntologyHelper.OwlDatatypeProperty, StringComparison.Ordinal)); 460 | } 461 | 462 | public static bool IsAnnotationProperty(this OntologyProperty property) 463 | { 464 | return property.Types.UriNodes().Any(propertyType => propertyType.Uri.ToString().Equals(OntologyHelper.OwlAnnotationProperty, StringComparison.Ordinal)); 465 | } 466 | #endregion 467 | 468 | #region OntologyGraph extensions 469 | public static Ontology GetOntology(this OntologyGraph graph) 470 | { 471 | IUriNode rdfType = graph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); 472 | IUriNode owlOntology = graph.CreateUriNode(new Uri(OntologyHelper.OwlOntology)); 473 | IEnumerable ontologyNodes = graph.GetTriplesWithPredicateObject(rdfType, owlOntology) 474 | .Select(triple => triple.Subject) 475 | .UriNodes(); 476 | 477 | switch (ontologyNodes.Count()) 478 | { 479 | case 0: 480 | throw new RdfException($"The graph {graph} doesn't contain any owl:Ontology declarations."); 481 | case 1: 482 | return new Ontology(ontologyNodes.Single(), graph); 483 | default: 484 | IUriNode ontologyNode = ontologyNodes.Where(node => node.Uri.AbsoluteUri.Equals(graph.BaseUri.AbsoluteUri)).DefaultIfEmpty(ontologyNodes.First()).First(); 485 | return new Ontology(ontologyNode, graph); 486 | } 487 | } 488 | 489 | public static IEnumerable GetIndividuals(this OntologyGraph graph, OntologyClass ontologyClass) 490 | { 491 | IUriNode classNode = ontologyClass.GetUriNode(); 492 | IUriNode rdfType = graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)); 493 | return graph.GetTriplesWithPredicateObject(rdfType, classNode) 494 | .Where(triple => triple.Subject.IsUri()) 495 | .Select(triple => new Individual(triple.Subject, graph)); 496 | } 497 | 498 | public static IEnumerable GetDatatypes(this OntologyGraph graph) 499 | { 500 | INode rdfsDatatype = graph.CreateUriNode(VocabularyHelper.RDFS.Datatype); 501 | return graph.GetClasses(rdfsDatatype); 502 | } 503 | #endregion 504 | 505 | #region Ontology extensions 506 | public static bool HasVersionUri(this Ontology ontology) 507 | { 508 | IUriNode versionIri = ontology.Graph.CreateUriNode(VocabularyHelper.OWL.versionIRI); 509 | return ontology.GetNodesViaPredicate(versionIri).UriNodes().Any(); 510 | } 511 | 512 | public static Uri GetVersionUri(this Ontology ontology) 513 | { 514 | if (!ontology.HasVersionUri()) 515 | { 516 | throw new RdfException($"Ontology {ontology} does not have an owl:versionIRI annotation"); 517 | } 518 | 519 | IUriNode versionIri = ontology.Graph.CreateUriNode(VocabularyHelper.OWL.versionIRI); 520 | return ontology.GetNodesViaPredicate(versionIri).UriNodes().First().Uri; 521 | } 522 | 523 | /// 524 | /// Gets a short name representation for an ontology, based on the last segment 525 | /// of the ontology IRI or (in the case of anonymous ontologies) the ontology hash. 526 | /// Useful for qname prefixes. 527 | /// 528 | /// 529 | /// 530 | public static string GetShortName(this Ontology ontology) 531 | { 532 | // Fallback way of getting a persistent short identifier in the 533 | // (unlikely?) case that we are dealing w/ an anonymous ontology 534 | if (!ontology.IsNamed()) 535 | { 536 | return ontology.GetHashCode().ToString(invariantCulture); 537 | } 538 | 539 | // This is a simple string handling thing 540 | string ontologyUriString = ontology.GetUri().AbsoluteUri; 541 | 542 | // Trim any occurences of entity separation characters 543 | if (ontologyUriString.EndsWith("/", StringComparison.Ordinal) || ontologyUriString.EndsWith("#", StringComparison.Ordinal)) 544 | { 545 | char[] trimChars = { '/', '#' }; 546 | ontologyUriString = ontologyUriString.Trim(trimChars); 547 | } 548 | 549 | // Get the last bit of the string, after the last slash 550 | ontologyUriString = ontologyUriString.Substring(ontologyUriString.LastIndexOf('/') + 1); 551 | 552 | // If the string contains dots, treat them as file ending delimiter and get rid of them 553 | // one at a time 554 | while (ontologyUriString.Contains('.', StringComparison.Ordinal)) 555 | { 556 | ontologyUriString = ontologyUriString.Substring(0, ontologyUriString.LastIndexOf('.')); 557 | } 558 | 559 | return ontologyUriString; 560 | } 561 | #endregion 562 | } 563 | } 564 | --------------------------------------------------------------------------------