Method and system for modelica model parsing and semantic reconstruction based on metamodel
Patent Information
- Application Number
- CN202611165249.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-03
- Publication Date
- 2026-10-30
AI Technical Summary
[0009]有鉴于此,本发明提供了一种基于元模型的Modelica模型解析与语义重构方法及系统,以解决现有技术中Modelica模型解析与具体语法强耦合、缺乏统一语义表达标准、跨工具互操作性不足以及本体语义支撑薄弱的问题
[0024]本发明与现有技术相比存在的有益效果包括以下五个方面:
Smart Images

Figure CN123011241A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the intersection of Model-Based Systems Engineering (MBSE) and Semantic Web technology, specifically to a method and system for Modelica model parsing and semantic reconstruction based on metamodels. Background Technology
[0002] The Modelica language has been developed and maintained by the Modelica Association since 1997, with the current mainstream version being Modelica 3.6 (released in 2023). It has been recommended by the International Federation of Automatic Control (IFAC) and the International Electrotechnical Commission (IEC) as a standard language for modeling physical systems in multiple fields, and is widely used in system-level modeling in aerospace, automotive, energy systems, robotics control, and building energy conservation. With the increasing adoption of Model-Based Systems Engineering (MBSE) methodologies in the development of complex products, the traceability, verifiability, and cross-tool interoperability of system models have become essential industry requirements.
[0003] The Modelica language has complex syntax features, including multiple inheritance, generic types, array dimensions, conditional expressions, and variable structure parameters, making the parsing and understanding of its model files technically challenging. Current technologies face the following main challenges when processing Modelica models:
[0004] First, the syntax is tightly coupled. Traditional parsing methods are usually strongly coupled with the specific syntax of Modelica. When the language specification is upgraded or there are dialect extensions from different simulation vendors, the parser often needs to be modified extensively, resulting in high maintenance costs.
[0005] Second, there is a lack of unified standards for semantic representation. Different simulation tools (such as Dymola, OpenModelica, SimulationX, etc.) may produce different internal data representations for the same Modelica model, making it difficult to align the model semantics across different toolchains.
[0006] Third, interoperability needs improvement. Existing solutions mostly focus on model management for single tools and lack technical means for cross-tool semantic reasoning, making it difficult to support requirement traceability, design verification, and change impact analysis throughout the MBSE lifecycle.
[0007] Fourth, there is insufficient support for ontology semantics. Currently, there is a lack of proprietary meta-model definitions for the Modelica language, as well as a complete automated technical solution for parsing syntax and mapping OWL ontology semantics. Some existing solutions rely on manual modeling, which is difficult to adapt to large-scale model library scenarios.
[0008] Patent application CN202411834875 discloses a Modelica parsing method based on ANTLR4. However, this method only implements parsing at the grammatical level, without establishing a meta-model abstraction layer independent of grammar, nor does it achieve automated mapping from model objects to OWL ontologies. While the Modelica-to-OWL solution in the VTT technical report involves semantic transformation, it relies on manual modeling and lacks automated processing capabilities. None of the aforementioned existing technologies form a complete automated technical chain of "meta-model definition—syntax parsing—semantic mapping—standardization release," leaving room for improvement in semantic interoperability. Summary of the Invention
[0009] In view of this, the present invention provides a method and system for Modelica model parsing and semantic reconstruction based on metamodel, in order to solve the problems of strong coupling between Modelica model parsing and specific syntax, lack of unified semantic expression standards, insufficient cross-tool interoperability, and weak ontology semantic support in the prior art.
[0010] According to a first aspect of the present invention, a method for parsing and semantic reconstruction of Modelica models based on meta-models is provided, comprising the following steps:
[0011] Step S101: Define the abstract metamodel of the Modelica language. The abstract metamodel includes model classes, package classes, linker classes, block classes, parameter classes, component classes, and inheritance relationship classes. It expresses the core semantic concepts of the Modelica language in an object-oriented manner, forming an intermediate representation layer that is independent of specific syntax.
[0012] Step S102: Using the ANTLR4 tool, write lexical rule files and syntax rule files based on the Modelica language specification to generate corresponding lexical analyzers and syntax analyzers; input the Modelica source file into the lexical analyzer for lexical analysis, converting the character stream into a token stream; then input the token stream into the syntax analyzer for syntax analysis, generating an abstract syntax tree (AST);
[0013] Step S103: Traverse the abstract syntax tree, and according to the preset syntax node recognition rules and mapping rules, convert the AST nodes that conform to the rules into instance objects of the metamodel class defined in step S1, and construct a hierarchical metamodel object graph.
[0014] The preset syntax node identification rules include: starting from the root node of the AST, recursively traversing all class definition nodes; extracting the class prefix field to determine the type of the current model element; extracting the class body field to obtain the class body element list; traversing the element list and processing inheritance clauses, component parameter declarations, and nested class definitions respectively; for inheritance clauses, extracting the inheritance target path to establish an ExtendsRelationship record; for component parameter declarations, extracting the type prefix, type specifier, array subscript, modifier, and comment fields.
[0015] Step S104: Based on the preset OWL ontology mapping rules, the metamodel object graph constructed in step S103 is converted into OWL / RDF semantic assertions to generate an OWL ontology with unified semantics.
[0016] In a second aspect, the present invention provides a Modelica model parsing and semantic reconstruction system based on a meta-model, comprising:
[0017] The metamodel definition module is used to define and store the abstract metamodel of the Modelica language;
[0018] The parsing module is used to perform lexical and syntactic analysis on Modelica source files using the ANTLR4 tool to generate an AST;
[0019] The metamodel construction module recursively traverses all class definition nodes starting from the root node of the AST, extracts class prefix fields to determine the model element type, and extracts class body fields to obtain a list of class body elements. It then iterates through each element, processing inheritance clauses (establishing ExtendsRelationship and filtering Modelica standard library inheritance), component parameter declarations (extracting type prefixes, type specifiers, array indices, modifiers, and comment fields, and performing parameter tri-classification), and nested class definitions (recursively processing) to form a hierarchical metamodel object graph.
[0020] The OWL refactoring module is used to convert the metamodel object graph into OWL / RDF semantic assertions based on OWL ontology mapping rules.
[0021] The storage module is used to persistently store the metamodel object graph and OWL / RDF semantic assertions.
[0022] In a third aspect, the present invention provides an electronic device, including a memory, a processor, and a computer program stored in the memory, wherein when the computer program is executed by the processor, it implements the steps of the Modelica model parsing and semantic reconstruction method based on the meta-model as described in any of the preceding claims.
[0023] In a fourth aspect, the present invention provides a computer-readable storage medium having a computer program stored thereon, wherein when the computer program is executed by a processor, it implements the steps of the Modelica model parsing and semantic reconstruction method based on the meta-model as described in any of the preceding claims.
[0024] The advantages of this invention compared to the prior art include the following five aspects:
[0025] First, it features syntactic decoupling and strong scalability. By introducing a metamodel abstraction layer, the specific Modelica syntax (AST generated by ANTLR4) is completely separated from the model semantic expression (metamodel objects). There is no inheritance or dependency relationship between the definition of the metamodel class and the syntax tree node classes generated by the parser. When the Modelica language specification is upgraded or needs to be adapted to dialect extensions of different simulation vendors, only the ANTLR4 .g4 syntax rule file needs to be adjusted and the parser regenerated; there is no need to modify the metamodel definition and the downstream OWL refactoring logic.
[0026] Second, it unifies semantic expression and supports intelligent reasoning. Based on the W3C standard OWL ontology, it expresses the semantic information of the Modelica model, enabling the model's type relationships, parameter constraints, inheritance structure, and physical units to be logically reasoned by standard RDF inference engines (such as Apache Jena, Pellet, and HermiT) and semantically retrieved by the SPARQL query language, thus realizing the leap from "syntactic-level model management" to "semantic-level model management".
[0027] Third, cross-tool interoperability supports the entire MBSE lifecycle. By exposing the OWL ontology through the OSLC standard interface, different simulation tools such as Dymola, OpenModelica, and SimulationX can access and query model semantic information through a unified RESTful API, realizing model semantic interoperability between simulation toolchains. This is of great value for requirement tracing, design verification, and change impact analysis throughout the MBSE lifecycle.
[0028] Fourth, it boasts high parsing accuracy and covers complex scenarios. The parameter tri-classification mechanism resolves semantic ambiguity in model parameters, protected code filtering eliminates interference from non-semantic information, standard library filtering and automatic transfer processing of inheritance relationships ensure the integrity of inheritance semantics and the simplicity of the ontology, and package.order sorting and array dimension processing guarantee compatibility with mainstream modeling tools. Experimental verification shows that in the parsing of an aero-engine control system (EngineControl.mo, containing 47 model classes and 312 parameters), the method of this application achieves a 100% complete extraction rate, a parameter tri-classification accuracy of 98.7%, and an OWL ontology generation time of approximately 2.3 seconds, representing an efficiency improvement of approximately 40 times compared to manual modeling methods.
[0029] Fifth, the technical solution is complete and can be directly engineered. This application provides clear technical means and implementation methods covering the entire technical chain, from metamodel definition, ANTLR4 parsing, AST mapping, OWL semantic reconstruction to OSLC service exposure. Each step is based on mature open-source frameworks (ANTLR4, Apache Jena, Eclipse Lyo), which can directly guide engineering implementation. Attached Figure Description
[0030] To more clearly illustrate the technical solutions in the embodiments of this application, the accompanying drawings used in the description of the embodiments will be briefly introduced below.
[0031] Figure 1 This is a flowchart illustrating the Modelica model parsing and semantic reconstruction method based on the meta-model according to the present invention.
[0032] Figure 2 This is a flowchart illustrating the process of defining the Modelica language abstract metamodel provided in this application embodiment.
[0033] Figure 3 This is a schematic diagram of the lexical and syntactic analysis process based on ANTLR4 provided in the embodiments of this application.
[0034] Figure 4 This is a schematic diagram of the AST traversal and metamodel object mapping construction process provided in the embodiments of this application.
[0035] Figure 5 This is a schematic diagram of the parameter three-classification mechanism determination process provided in the embodiments of this application.
[0036] Figure 6 This is a schematic diagram of the filtering process provided in the embodiments of this application.
[0037] Figure 7 This is a schematic diagram of the inheritance relationship transfer process provided in the embodiments of this application.
[0038] Figure 8 This is a schematic diagram of the sorting process provided in the embodiments of this application.
[0039] Figure 9 This is a schematic diagram of the dimension processing flow provided in the embodiments of this application.
[0040] Figure 10 This is a schematic diagram of the mapping process from metamodel objects to OWL ontology semantic reconstruction provided in the embodiments of this application.
[0041] Figure 11 This is a schematic diagram of the OWL class hierarchy mapping relationship provided in the embodiments of this application.
[0042] Figure 12 This is a schematic diagram illustrating the mapping relationship between parameters and OWL attributes and annotations provided in the embodiments of this application.
[0043] Figure 13 This is a schematic diagram of the OSLC service exposure architecture based on the Eclipse Lyo framework provided in the embodiments of this application.
[0044] Figure 14 This is a schematic diagram of the semantic query processing flow provided in the embodiments of this application.
[0045] Figure 15 This is the UML class diagram of the Modelica abstract metamodel provided in this application embodiment.
[0046] Figure 16 This is a schematic diagram of the overall architecture of the Modelica model parsing and semantic reconstruction system based on the meta-model provided in this application embodiment.
[0047] Figure 17 This is a complete data flow diagram of the Modelica model analysis of the aircraft engine control system, which is an embodiment of this application.
[0048] Figure 18 This is a schematic diagram of the data flow for analyzing the battery model of an electric vehicle BMS, which is an embodiment of this application.
[0049] Figure 19 This is a schematic diagram of the hardware and software architecture of the electronic device provided in the embodiments of this application. Detailed Implementation
[0050] In the following description, specific details such as particular system architectures and techniques are set forth for illustrative purposes and not for limiting purposes, in order to provide a thorough understanding of the embodiments of this application. However, those skilled in the art will understand that this application may also be implemented in other embodiments without these specific details.
[0051] Figure 1This is a flowchart illustrating a Modelica model parsing and semantic reconstruction method based on a meta-model according to the present invention. Figure 1 As shown, the method includes the following steps:
[0052] S101 defines the abstract metamodel of the Modelica language. This abstract metamodel includes a metamodel class (ModelicaModel), a package class (ModelicaPackage), a connector class (ModelicaConnector), a block class (ModelicaBlock), a parameter class (ModelicaParameter), a component class (ModelicaComponent), and an inheritance relationship class (ExtendsRelationship). It expresses the core semantic concepts of the Modelica language in an object-oriented manner, forming an intermediate representation layer independent of specific syntax. It defines ModelicaElement as the abstract base class for all model elements, using the UUIDv4 standard to automatically generate a globally unique identifier as id. This metamodel provides a unified data model foundation for subsequent AST node mapping. For detailed procedures on metamodel definition, see [link to documentation]. Figure 2 And its explanation. There is no inheritance or dependency relationship between the definition of the metamodel class and the syntax tree node class generated by the parser. The inheritance relationship class (ExtendsRelationship) is used to record the association information of one model element inheriting from another model element through the extends clause, including the source model ID and the target model name.
[0053] It should be noted that all custom fields in this article will be described separately, while all other fields are existing fields defined by the Modelica language specification or automatically generated by the syntax parsing tool.
[0054] In step S102, using the ANTLR4 tool, lexical and grammatical rule files are written based on the Modelica language specification, generating corresponding lexical and parsing analyzers. The Modelica source files are read as a character stream using ANTLRInputStream and input into the lexical analyzer for lexical analysis, identifying keywords, identifiers, operators, and literals, converting the character stream into a token stream. The token stream is then input into the parser for grammatical analysis, parsing the token sequence into an Abstract Syntax Tree (AST) starting with the root node context according to the grammatical rules. The root node of the AST corresponds to the definition context stored in the file, and its child nodes are all class definition contexts defined in the file. This AST serves as the input for the meta-model construction in step S103. For a detailed flowchart of lexical and grammatical analysis, please refer to [link to relevant documentation]. Figure 3 And its explanation.
[0055] S103, traverse the abstract syntax tree (AST), and according to the preset syntax node identification and mapping rules, convert AST nodes that conform to the rules into instance objects of the metamodel class defined in step S101, constructing a hierarchical metamodel object graph. The preset syntax node identification and mapping rules include: starting from the AST root node, recursively traversing all class definition nodes, extracting class prefix fields to determine the model element type, and extracting class body fields to obtain a list of class body elements. Traverse each element, and process the inheritance clause (establish ExtendsRelationship and filter Modelica standard library inheritance), component parameter declaration (extract type prefix, type specifier, array subscript, modifier, and comment fields, and perform parameter three-classification judgment), and nested class definition (recursively processed).
[0056] For component parameter declarations, the enumeration type definition and its enumeration value list contained in the annotation are also identified, and the enumeration item identifier and annotation information are extracted.
[0057] Step S103 also includes parsing error tolerance handling:
[0058] When an AST node cannot be identified according to the preset rules, a warning log is recorded, the current node is skipped, and subsequent nodes are processed. After the parsing is completed, the warning logs are summarized into a parsing report.
[0059] During the traversal, the `isProtected` flag is maintained to filter protected code. `isProtected` is a boolean flag used to indicate whether the current region is protected, determining whether to skip elements within that region. Finally, a hierarchical metamodel object graph is constructed. For a detailed process of AST traversal mapping, see [link to documentation]. Figures 4 to 9 And its explanation.
[0060] S104, based on the preset OWL (Web Ontology Language) ontology mapping rules, converts the metamodel object graph constructed in step S103 into OWL / RDF (Resource Description Framework) semantic assertions, thus reconstructing the semantics of the OWL ontology. The mapping rules include: class hierarchy mapping (metamodel instance → OWL individual), inheritance relationship mapping (ExtendsRelationship → rdfs:subClassOf assertion), parameter type mapping (basic types → owl:DatatypeProperty, composite types → owl:ObjectProperty), and parameter metadata mapping (8 properties including unit → owl:AnnotationProperty). For a detailed process of OWL ontology semantic reconstruction, please refer to [link to relevant documentation]. Figures 10 to 12 And its explanation.
[0061] S105, based on the OSLC ServiceProvider mechanism of the Eclipse Lyo framework, registers the OWL ontology generated in step S104 as a ServiceProvider. Resource types are defined using ResourceShape, and the ontology is exposed externally via a RESTful interface in RDF / XML or Turtle format, providing three API endpoints: model semantic retrieval, parameter detail query, and SPARQL semantic query. External systems (Dymola, OpenModelica, MBSE platform, etc.) retrieve model semantics or perform cross-model searches via standard HTTP GET requests. For a detailed architecture of OSLC service exposure, see [link to OSLC service exposure architecture]. Figures 13 to 14 And its explanation.
[0062] In some embodiments of this application, the method can be executed by an integrated model management and semantic analysis platform, which includes at least a parsing engine, a metamodel manager, an OWL refactoring engine, and an OSLC service framework, deployed on a server side, receiving Modelica source files or zip-compressed project packages uploaded by users via a web interface. When parsing a compressed Modelica project, the parser locates the package.order file in the compressed package, sorts the list of model elements according to the order defined in the file, and then performs parsing. For zip-compressed Modelica projects, the parser first decompresses the package and locates the package.order file to determine the parsing order, and then traverses all .mo files in the compressed package in this order for batch parsing.
[0063] According to the technical solution provided in the embodiments of this application, by defining an abstract meta-model of the Modelica language as an intermediate representation layer, using the ANTLR4 tool for syntax-driven parsing, mapping the parsing results to meta-model objects and performing OWL semantic reconstruction, and finally exposing them to the outside world through the OSLC standard interface, the complete technical link of meta-model + ANTLR4 + OWL + OSLC is used to realize the transformation of the Modelica model from syntactic text to inferable semantic knowledge, effectively solving the problems of severe syntactic coupling, inconsistent semantic expression and poor cross-tool interoperability in the prior art.
[0064] Figure 2 This is a schematic diagram of the metamodel definition process provided in an embodiment of this application. For example... Figure 2 As shown, defining a metamodel involves the following steps:
[0065] S201 defines the ModelicaElement abstract base class, which includes three common attributes: id (set as a custom field id, String type, UUIDv4 format), name (set as a custom field name, String type, corresponding to the class name or component name in the Modelica source file), and description (set as a custom field description, String type, corresponding to the comment information in the Modelica source code).
[0066] S202 defines four core classes that inherit from ModelicaElement: ModelicaModel (containing an inheritance list (set as a custom field extends), a parameter list (set as a custom field parameters), and a component list (set as a custom field components)), ModelicaPackage (containing a child element list (set as a custom field children) and sorting information (set as a custom field packageOrder), with the data type (set as a custom field dataType) attribute value set to folder (set as a custom field folder)), ModelicaConnector (containing an interface parameter list (set as a custom field interfaceParams)), and ModelicaBlock (containing an input parameter list (set as a custom field inputs) and an output parameter list (set as a custom field outputs)).
[0067] S203 defines three helper classes: ModelicaParameter (containing an enumeration field (set as a custom field parameterType), with values of parameter, interface, or real number (set as a custom enumeration value PARAMETER / INTERFACE / REAL), type name (set as a custom field valueType), default value (set as a custom field defaultValue), and eight annotation properties: unit, displayUnit, min, max, fixed, start, nominal, and quantity), ModelicaComponent (containing a component type name (set as a custom field componentType) and a modifier parameter field (set as a custom field modifiers)), and ExtendsRelationship (containing two association properties: source model ID (custom field sourceModelId) and target model name (targetModelName), which are not inherited from ModelicaElement).
[0068] S204, Establish inter-class relationships: ModelicaModel, ModelicaPackage, ModelicaConnector, and ModelicaBlock are derived from ModelicaElement through inheritance; ModelicaParameter and ModelicaComponent are associated with their corresponding parent elements through composition; ExtendsRelationship connects the source model and the target model through association.
[0069] All classes in the metamodel are implemented in Java POJO form, using the standard JavaBean specification, and can be directly processed by JSON serialization libraries such as Jackson, facilitating persistent storage and network transmission. Figure 15 It is a complete meta-model hierarchy displayed in the form of a UML class diagram.
[0070] Figure 3 This is a schematic diagram of the lexical and syntactic analysis process based on ANTLR4 provided in an embodiment of this application. For example... Figure 3 As shown, the process includes the following steps:
[0071] S301 reads the Modelica source files as a character stream using ANTLRInputStream. For zip-compressed project packages, it first decompresses the package.order file to determine the parsing order, and then reads each .mo file sequentially.
[0072] S302, the ModelicaLexer lexical analyzer identifies character sequences as corresponding token sequences based on the lexical rules defined in the lexical rule file (such as ModelicaLexer.g4). The identified tokens are categorized into four types: keyword tokens, identifier tokens, operator tokens, and literal tokens. All tokens are buffered and organized into CommonTokenStream objects.
[0073] In step S303, the ModelicaParser parser receives the CommonTokenStream as input and, according to the grammar rules defined in the grammar rule file (e.g., ModelicaParser.g4), uses a top-down recursive descent parsing strategy to parse the token sequence into a hierarchical syntax tree. The root node of the syntax tree stores the definition context, and its children include all class definition context child nodes defined in the file. This syntax tree serves as the input for the metamodel construction in step S103.
[0074] Figure 4 This is a schematic diagram illustrating the AST traversal and metamodel object mapping construction process provided in an embodiment of this application. For example... Figure 4 As shown, the process includes the following steps:
[0075] S401, starting from the root node of the AST, recursively traverse each class definition node;
[0076] Extract the first value of the class prefix field, determine the model element type based on its specific value, and create the corresponding metamodel instance: create a ModelicaModel instance when the value is 'model', a ModelicaPackage instance when the value is 'package', a ModelicaBlock instance when the value is 'block', and a ModelicaConnector instance when the value is 'connector'. Simultaneously, extract the class name and set its 'name' attribute, and extract the comment information and set its 'description' attribute.
[0077] S402, extract the class body field from the long class specifier and obtain the list of elements of the class body.
[0078] For each inheritance clause node in the element list, process it as follows: extract its type attribute (the target path of inheritance). If the path is prefixed with "Modelica", skip it and do not record "ExtendsRelationship"; otherwise, create an "ExtendsRelationship" record. If the path contains a "." separator, it indicates that it is referencing a type nested within a file; extract the type name after the last "." as the target model name (targetModelName). For detailed processing of inheritance relationship propagation, see [link to relevant documentation]. Figure 7 .
[0079] S403 processes each component parameter declaration node in the element list: extracting the type prefix, type specifier, array index, modifiers (including attribute values such as start, unit, fixed, min, max, nominal, etc.) and comment fields.
[0080] S404 performs a three-category parameter classification: if the type prefix is "parameter," it is classified as a parameter (PARAMETER); if the type name matches a predefined interface type regular expression, it is classified as an interface (INTERFACE); and if the type name exists in a predefined SI physical unit property file, it is classified as a result (REAL). The predefined SI physical unit property file, such as SIUNITS.properties, maintains a mapping between Modelica standard type names and physical quantity names (e.g., Position → length). This file can be expanded during system deployment according to project needs. Construct a ModelicaParameter instance and set the corresponding properties and annotation properties. For detailed explanations of parameter classification and array dimension handling, see [link to documentation]. Figure 5 and Figure 9 Array dimension handling: For parameters whose declarations contain array subscripts, append the array dimension information to the parameter value type name; for declarations whose names contain array indices, append the index expression to the parameter name.
[0081] Inheritance relationship passing: For each identified inheritance clause, firstly filter the inheritance relationships from the Modelica standard library, and only retain the inheritance of custom parent types; then search the interface type parameters contained in the parent interface in the global scope, and inject a copy of the interface type parameters into the child model that inherits the interface.
[0082] S405, for nested class definition nodes in the element list, recursively call this process to process nested class definitions.
[0083] S406, Protected Code Filtering: When traversing the class body element list, identify the location of the `protected` keyword and mark the code block immediately following it as protected code for exclusion, retaining only elements in the public area. A boolean flag `isProtected` can be maintained (default is false), set to true when the `protected` keyword is encountered, and reset to false when the `public` keyword is encountered. All component parameter declarations and nested class definitions encountered while `isProtected` is true are marked as protected code, and no corresponding metamodel instance is created. For detailed processing of protected filtering, see [link to documentation]. Figure 6 .
[0084] Figure 5 This is a further explanation of the parametric three-class classification mechanism. For example... Figure 5 As shown, the process includes the following steps:
[0085] Retrieve the type prefix and type specifier fields from the component parameter declaration node. If the type prefix value is "parameter", it is determined to be of type "PARAMETER", and annotation attributes such as "defaultValue", "unit", and "start" are extracted.
[0086] When the type name matches the preset interface type regular expression (such as (?i). Interface. When the parameter is of type INTERFACE, it is determined to be an external connector interface.
[0087] When the type name exists in the SIUNITS.properties file, it is determined to be of type REAL. The corresponding physical quantity name is retrieved from this file and set as the `quantity` annotation property. If none of the three conditions are met, the current declaration is marked as a normal component. The SIUNITS.properties file maintains the mapping relationship between Modelica standard type names and physical quantity names (such as Position→length). This file can be extended according to project needs during system deployment.
[0088] Figure 6 This is a further explanation of protected code filtering. For example... Figure 6 As shown, the isProtected flag is initialized to false. The element list is traversed element by element. When the protected keyword is encountered, isProtected is set to true, and subsequent elements are marked as protected.
[0089] When `isProtected` is false, the current element is processed normally, and a metamodel instance is created. When `isProtected` is true, creation is skipped. For inheritance clause nodes, processing is always normal regardless of the `isProtected` state, because inheritance defines the type hierarchy of the model.
[0090] Figure 7 This is a further explanation of how inheritance relationships are passed on. For example... Figure 7 As shown, the type attribute of the inheritance clause is extracted to obtain the inheritance target path. It is then determined whether the path is prefixed with "Modelica". If so, the inheritance relationship belongs to the Modelica standard library and is excluded, and ExtendsRelationship is not recorded. If not, it is further determined whether the path contains a "." separator. If it does, it means that the type is referenced within the file, and the type name after the last "." is extracted as the target model name (targetModelName). If it does not contain it, the path is directly used as the target model name (targetModelName). Then, ExtendsRelationship is recorded, its source model ID (sourceModelId) is set to the current model's id, and its target model name (targetModelName) is set to the target name obtained above. Then, the list of interface parameters with parameterType set to INTERFACE in the parent connector is searched globally, and deep copies of these interface parameters are injected into the parameter list (parameters) of the current child model, so that the child model fully obtains the parameters agreed upon by the parent interface.
[0091] The two key design features of this mechanism are: standard library filtering—inheritance paths prefixed with Modelica are automatically excluded to prevent the massive inheritance hierarchy of the standard library from being introduced into the user's semantic ontology; and deep copying of interface parameters—a copy is injected instead of a reference, ensuring that the child model can independently modify the inherited parameters without affecting the original definition of the parent interface.
[0092] Figure 8 This is a further explanation of the sorting process handled by package.order. Figure 8 As shown, search for the `package.order` file within the zip archive. If the file exists, read its contents and parse them into a sorted list.
[0093] The model elements are reordered according to the sorted list before parsing. The package.order file is a common convention file for mainstream Modelica modeling tools such as Dymola. This embodiment of the application ensures that the parsing results are consistent with the element arrangement in the modeling tool by reading this file.
[0094] Figure 9 This is a further explanation of how array dimensions are handled. For example... Figure 9 As shown, iterate through the declaration list. If a declaration contains an array index, extract the array dimension information and concatenate it to valueType (that is, record Real as Real[3,3]).
[0095] If the parameter name contains an array index (such as x[generator.nState]), the index expression is appended to the parameter name to form the complete identifier. In addition, for parameters containing enumeration types, a complete list of enumeration values and comment information are recorded; for declarations containing redeclare, the type information before and after the redeclare is recorded.
[0096] Figure 10 This is a schematic diagram illustrating the mapping process from metamodel objects to OWL ontology semantic reconstruction provided in this application embodiment. For example... Figure 10 As shown, the semantic reconstruction process follows four mapping rules:
[0097] S1001, Perform class hierarchy mapping: Each metamodel class instance is mapped to an OWL individual, whose rdf:type points to the corresponding OWL class. ModelicaModel instance → rdf:type modelica:Model, ModelicaPackage instance → rdf:type modelica:Package, ModelicaConnector instance → rdf:type modelica:Connector, ModelicaBlock instance → rdf:type modelica:Block. Simultaneously, generate the corresponding OWL class hierarchy assertion. modelica: is the OWL namespace prefix defined in this application. For detailed information on class hierarchy mapping, see [link to documentation]. Figure 11 .
[0098] S1002, Perform inheritance relationship mapping: ExtendsRelationship is directly mapped to the rdfs:subClassOf semantic assertion. For example, if engineModel inherits sensorInterface through extends, then the triple assertion <#engineModel> rdfs:subClassOf <#sensorInterface> is generated. rdfs:subClassOf is transitive, and the RDF inference engine can automatically deduce all attribute constraints in a multi-level inheritance chain.
[0099] S1003, Execution parameter type mapping: Basic physical types (Real→xsd:double, Integer→xsd:integer, Boolean→xsd:boolean, String→xsd:string) are mapped to owl:DatatypeProperty, with the domain being the individual model to which it belongs and the value domain being the corresponding XML Schema data type. Composite types (custom Connector type names) are mapped to owl:ObjectProperty.
[0100] S1004, execution parameter metadata mapping: The eight properties—unit, displayUnit, min, max, fixed, start, nominal, and quantity—are mapped to their corresponding owl:AnnotationProperty. AnnotationProperty does not participate in the OWL inference engine's logical reasoning but is fully preserved for external applications to read. For detailed explanations of parameter mapping, see [link to documentation]. Figure 12 .
[0101] Figure 11 This is a further elaboration on class hierarchy mapping. For example... Figure 11 As shown, the metamodel instances on the left (PackageEngineControl, Connector sensorInterface, Model engineModel) are mapped to OWL individuals on the right. The engineModel inherits from sensorInterface via the extends property, which is mapped to the rdfs:subClassOf assertion. The URIs of OWL individuals use the format <#individual name>, and the namespace prefix modelica maps to the Modelica ontology namespace IRI defined in this application.
[0102] Figure 12 This is a further explanation of parameter mapping. For example... Figure 12As shown, taking the Modelica parameter declaration `parameterReal p_start(start=0.1, unit=Pa, fixed=false)` as an example, the parameter declaration is input, generating an OWL individual `<#engineModel_p_start>(rdf:type modelica:RealParameter)`, creating data attribute assertions (`modelica:defaultValue 0.1`, `modelica:hasParameter`) and annotation attribute assertions (`modelica:unitPa`, `modelica:start 0.1`, `modelica:fixed false`), and finally representing the complete semantics as RDF triples (Turtle format). Semantic reconstruction is implemented based on the Apache Jena framework. `modelica:defaultValue`, `modelica:hasParameter`, `modelica:unit`, `modelica:start`, and `modelica:fixed` are custom OWL attributes defined in this application under the `modelica:` namespace.
[0103] Figure 13 This is a schematic diagram of the OSLC service exposure architecture based on the Eclipse Lyo framework provided in an embodiment of this application. Figure 13 As shown, the architecture consists of four layers:
[0104] Storage layer: The OWL / RDF semantic assertions generated in step S104 are persisted to the Apache Jena TDB triple database, supporting cross-model semantic retrieval based on the SPARQL query language.
[0105] The OSLC framework layer inherits from the ServiceProviderFactory abstract class of the Lyo framework, implements DataManageServiceProviderFactory, creates ServiceProvider instances and sets their titles and descriptions, and defines a set of attributes for queryable resources (including rdf:type, modelica:hasParameter, modelica:unit, modelica:defaultValue, etc.) through ResourceShape. DataManageServiceProviderFactory is a custom service provider factory class defined in this application; rdf:type is a type attribute defined by the W3C RDF standard, used to represent the OWL class to which an OWL individual belongs; modelica:hasParameter, modelica:unit, and modelica:defaultValue are custom OWL attributes defined in this application under the modelica: namespace, where modelica:hasParameter represents the containment relationship between a model individual and its parameter individual, modelica:unit represents the physical unit of the parameter, and modelica:defaultValue represents the default value of the parameter.
[0106] Interface layer: Three API endpoints are exposed to the outside world through RESTful interfaces in RDF / XML or Turtle format: model semantic retrieval (GET / api / oslc / model / {modelId}), parameter detail query (GET / api / oslc / parameter / {parameterId}), and SPARQL semantic query endpoint (GET / api / oslc / sparql?query={SPARQL_QUERY}). GET / api / oslc / model / {modelId} represents the model semantic retrieval endpoint, where {modelId} is the unique identifier of the model to be queried. The client obtains the complete OWL semantic description of the specified model through this endpoint. GET / api / oslc / parameter / {parameterId} represents the parameter details query endpoint, where {parameterId} is the unique identifier of the parameter to be queried. The client obtains the type, default value, and annotation attributes of the specified parameter through this endpoint. GET / api / oslc / sparql?query={SPARQL_QUERY} represents the SPARQL semantic query endpoint, where {SPARQL_QUERY} is the SPARQL query statement submitted by the client. The system executes the query statement in the triple database and returns the matching results.
[0107] Client layer: External systems (Dymola, OpenModelica, MBSE platform and custom tools) access the system via standard HTTP GET requests.
[0108] Figure 14 This is a further explanation of the SPARQL semantic query processing flow. For example... Figure 14 As shown, the client sends a SPARQL query request, and the system parses the query statement to extract the SELECT / FROM / WHERE pattern.
[0109] Perform RDF triple matching in the Triple Store and return results in JSON / XML format. Typical query examples include: querying all models that inherit from a certain interface, querying parameters in Pa, and querying models that meet certain constraints.
[0110] Figure 15 This is a UML class diagram of the Modelica abstract metamodel provided in this application embodiment, which shows the complete class hierarchy of the metamodel using standard UML class diagram representation. For example... Figure 15 As shown, ModelicaElement serves as the abstract base class, while ModelicaModel, ModelicaPackage, ModelicaConnector, and ModelicaBlock are derived from ModelicaElement through inheritance. ModelicaParameter and ModelicaComponent are associated with their corresponding parent elements through composition. ExtendsRelationship connects ModelicaModel through association. Key properties of each class are represented using UML attribute tables.
[0111] Figure 16 This is a schematic diagram of the overall architecture of the Modelica model parsing and semantic reconstruction system based on a meta-model provided in this application embodiment. For example... Figure 16 As shown, the system includes:
[0112] The metamodel definition module is used to define the abstract metamodel of the Modelica language. The abstract metamodel includes model classes (ModelicaModel), package classes (ModelicaPackage), connector classes (ModelicaConnector), block classes (ModelicaBlock), parameter classes (ModelicaParameter), component classes (ModelicaComponent), and inheritance relationship classes (ExtendsRelationship). It expresses the core semantic concepts of the Modelica language in an object-oriented manner, forming an intermediate representation layer that is independent of specific syntax. It defines ModelicaElement as the abstract base class for all model elements and uses the UUIDv4 standard to automatically generate a globally unique identifier as id.
[0113] The parsing module is used to perform lexical and syntactic analysis on Modelica source files using the ANTLR4 engine to generate an AST.
[0114] The metamodel construction module recursively traverses all class definition nodes starting from the root node of the AST, extracts class prefix fields to determine the model element type, and extracts class body fields to obtain a list of class body elements. Each element is traversed, processing inheritance clauses (establishing ExtendsRelationship and filtering Modelica standard library inheritance), component parameter declarations (extracting type prefixes, type specifiers, array indices, modifiers, and comment fields, and performing parameter tri-classification), and nested class definitions (recursively processing), forming a hierarchical metamodel object graph.
[0115] The metamodel building module can include: a parameter classification submodule, used to automatically classify parameters in the model based on syntactic features; a protected code filtering submodule, used to identify and exclude code blocks after the `protected` keyword, retaining only public area element information; an inheritance transitive submodule, used to filter Modelica standard library inheritance relationships and globally search for parent interface type parameters to inject into child models; an array processing submodule, used to handle array dimension information concatenation; a sorting submodule, used to sort the model element list according to the order defined in the `package.order` file; and a fault tolerance submodule, used to log warnings and skip the current node when AST node matching fails.
[0116] The OWL refactoring module is used to convert the metamodel object graph into OWL / RDF semantic assertions based on preset OWL (Web Ontology Language) ontology mapping rules.
[0117] The storage module is responsible for the persistence of the metamodel object graph and RDF semantic assertions.
[0118] It may also include: an OSLC service module, which is used for the OSLC ServiceProvider mechanism based on the Eclipse Lyo framework. It registers the OWL ontology generated in step S104 as a ServiceProvider, defines the resource form through ResourceShape, exposes it to the outside world through a RESTful interface in RDF / XML or Turtle format, and provides three API endpoints: model semantic acquisition, parameter detail query, and SPARQL semantic query.
[0119] The implementation process of this application is further described in detail below with two specific embodiments, and experimental verification data is provided.
[0120] Example 1: Modelica model analysis of aircraft engine control system. Figure 17 This is a complete data flow diagram of this embodiment. (See diagram below.) Figure 17 As shown, the input is the EngineControl.mo file. After reading the source file, ANTLR4 lexical and syntactic analysis is performed. The meta-model is constructed: p_start is determined to be of type PARAMETER due to the type prefix "parameter"; Real is also marked as type REAL because it exists in SIUNITS; defaultValue=0.1 and unit=Pa are extracted; isActive is determined to be PARAMETER; the inheritance relationship of extends sensorInterface is preserved; the sensorValue parameter in sensorInterface is deep-copied and injected into engineModel; internalGain in the protected region is excluded. The OWL ontology is generated. EngineControl, engineModel, p_start, isActive, sensorInterface, sensorValue, and internalGain are custom model element names in this embodiment, where EngineControl is the package name, engineModel is the model name, p_start and isActive are parameter names, sensorInterface is the connector name, sensorValue is the interface parameter name, and internalGain is the parameter name in the protected region.
[0121] Example 2: Modelica model analysis of electric vehicle battery management system (BMS). Figure 18 This is a schematic diagram of the data flow in this embodiment. Figure 18As shown, the input is the BatteryPack.mo file. After reading the source file, ANTLR4 parses and filters standard library inheritance—extends PartialTwoPort is automatically excluded because the path starts with Modelica, avoiding the introduction of a large standard library inheritance hierarchy such as PartialTwoPort→TwoPort→ElectricalNode into the semantic ontology. The capacity is determined to be of type PARAMETER, and start=50, unit=kWh, min=0, max=200 are extracted; internalResistance in the protected region is excluded. An OWL ontology is generated, supporting SPARQL queries for all battery models with capacities between 50 and 100kWh. BatteryPack, capacity, and internalResistance are custom model element names in this embodiment, where BatteryPack is the model name, capacity is the parameter name, and internalResistance is the parameter name in the protected region. It should be noted that PartialTwoPort, TwoPort, and ElectricalNode are existing classes in the Modelica standard library and are not part of the custom content defined in this application.
[0122] The two embodiments described above represent the two core application areas of Modelica: aviation and automotive, demonstrating the versatility of the technical solution presented in this application across different scenarios. In particular, in Embodiment 2, the correct operation of the Modelica standard library inheritance filtering mechanism verifies the effectiveness of the inheritance relationship processing steps.
[0123] Experimental verification data:
[0124] To verify the technical effectiveness of the proposed solution, tests were conducted in the following experimental environment:
[0125] Hardware environment: Intel Xeon E5-2680 v4 processor (2.4GHz, 14 cores and 28 threads), 64GB DDR4 memory, SSD solid-state drive;
[0126] Software environment: Ubuntu 22.04 LTS operating system, OpenJDK 17, ANTLR4 4.13.1, Apache Jena 4.9.0, Eclipse Lyo 5.0.0;
[0127] Test objects: Aircraft engine control system model library (EngineControl.mo, containing 47 model classes, 312 parameters, file size approximately 180KB) and electric vehicle BMS model library (BatteryPack.mo, containing 23 model classes, 156 parameters, file size approximately 95KB).
[0128] Test items and results:
[0129] 1. Complete extraction rate: The completeness of the extraction of all model classes, parameters, components, and inheritance relationships in the test object was manually verified, and the complete extraction rate was 100%.
[0130] 2. Parameter classification accuracy: Based on 312 manually labeled parameters, the automatic classification results were consistent with the manual labeling for 308 parameters, with an accuracy of 98.7% (308 / 312). The four misclassified parameters were all boundary cases (such as custom type names containing the word "Interface" and existing in the SI unit file).
[0131] 3. OWL ontology generation time: From the completion of AST traversal to the writing of all OWL / RDF semantic assertions into the triple database, EngineControl.mo took 2.3 seconds, and BatteryPack.mo took 1.1 seconds;
[0132] 4. Efficiency Comparison: For the EngineControl.mo model, the traditional manual modeling method (where an engineer with more than 3 years of Modelica modeling experience manually builds an equivalent OWL ontology using the Protégé tool) takes about 92 minutes, while the automated method in this application takes only 2.3 seconds, improving efficiency by about 40 times.
[0133] 5. Cross-tool compatibility: After exposing the generated OWL ontology through the OSLC interface, it was accessed using Dymola2023x, OpenModelica 1.22.0 and the self-developed MBSE platform client respectively. All of them successfully obtained the model semantics and executed SPARQL queries, and the query response time was less than 200ms.
[0134] Figure 19 This is a schematic diagram of the hardware and software architecture of the electronic device provided in the embodiments of this application. For example... Figure 19 As shown, the electronic device includes a hardware layer (processor, memory, storage medium, and network interface) and a software layer (operating system, Java Virtual Machine, and application). The application includes a metamodel definition module, a parsing module, a metamodel building module, an OWL refactoring module, an OSLC service module, and a storage module.
[0135] Therefore, the present invention also provides an electronic device, including a memory, a processor, and a computer program stored in the memory, wherein when the computer program is executed by the processor, it implements the aforementioned meta-model-based Modelica model parsing and semantic reconstruction method.
[0136] The present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein when the computer program is executed by a processor, it implements the aforementioned meta-model-based Modelica model parsing and semantic reconstruction method.
[0137] The above description is merely an optional embodiment of this application and is not intended to limit this application. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of this application should be included within the protection scope of this application.
Claims
1. A method for parsing and semantic reconstruction of Modelica models based on meta-models, characterized in that, Includes the following steps: Step S101: Define the abstract metamodel of the Modelica language. The abstract metamodel includes metamodel classes, package classes, linker classes, block classes, parameter classes, component classes, and inheritance relationship classes. It expresses the core semantic concepts of the Modelica language in an object-oriented manner, forming an intermediate representation layer that is independent of specific syntax. Step S102: Using the ANTLR4 tool, write lexical rule files and syntax rule files based on the Modelica language specification to generate the corresponding lexical analyzer and syntax analyzer; The Modelica source file is input into the lexical analyzer for lexical analysis, and the character stream is converted into a token stream. The token stream is then input into the parser for parsing to generate an abstract syntax tree (AST). Step S103: Traverse the abstract syntax tree, and according to the preset syntax node identification rules and mapping rules, convert the AST nodes that conform to the rules into instance objects of the metamodel class defined in step S101, and construct a hierarchical metamodel object graph. The preset syntax node identification rules include: starting from the root node of the AST, recursively traversing all class definition nodes; extracting the class prefix field to determine the type of the current model element; extracting the class body field to obtain the class body element list; traversing the element list and processing inheritance clauses, component parameter declarations, and nested class definitions respectively; for inheritance clauses, extracting the inheritance target path to establish an ExtendsRelationship record; for component parameter declarations, extracting the type prefix, type specifier, array subscript, modifier, and comment fields. Step S104: Based on the preset OWL ontology mapping rules, the metamodel object graph constructed in step S103 is converted into OWL / RDF semantic assertions to generate an OWL ontology with unified semantics.
2. The Modelica model parsing and semantic reconstruction method based on meta-model as described in claim 1, characterized in that, In step S103, During the traversal, the following processing is performed according to the node type: Parameter three-classification processing: The parameters in the model are automatically classified according to syntactic features. When the value of the type prefix field is "parameter", the parameter is determined to be a parameter type. When the parameter type name matches the preset interface type regular expression, the parameter is determined to be an interface type. When the parameter type name exists in the preset SI physical unit attribute file, the parameter is determined to be a result parameter type. Protected code filtering: When traversing the list of class body elements, identify the location where the protected keyword appears, mark the code block that immediately follows as protected code and exclude it, and only retain the element information of the public area; Inheritance relationship transitive processing: For each identified inheritance clause, firstly filter the inheritance relationships from the Modelica standard library, and only retain the inheritance of custom parent types; then search the interface type parameters contained in the parent interface in the global scope, and inject a copy of the interface type parameters into the child model that inherits the interface; Array dimension handling: For parameters whose declarations contain array subscripts, append the array dimension information to the parameter value type name; for declarations whose names contain array indices, append the index expression to the parameter name.
3. The Modelica model parsing and semantic reconstruction method based on meta-model according to claim 1, characterized in that, Step S102 also includes a package.order sorting step: When parsing a compressed Modelica project, the package.order file in the compressed package is located, and the list of model elements is sorted according to the order defined in the file before parsing is performed.
4. The Modelica model parsing and semantic reconstruction method based on meta-model according to claim 1, characterized in that, The OWL ontology mapping rules mentioned in step S104 include: Class hierarchy mapping: Each metamodel class instance is mapped to an OWL individual, whose rdf:type points to the corresponding OWL class; Inheritance mapping: The inheritance relationship class ExtendsRelationship is mapped to the rdfs:subClassOf semantic assertion; Parameter type mapping: Basic physical type parameters are mapped to owl:DatatypeProperty, and composite type parameters are mapped to owl:ObjectProperty; Parameter metadata mapping: unit, displayUnit, min, max, fixed, start, nominal, and quantity are mapped to their respective owl:AnnotationProperty.
5. The Modelica model parsing and semantic reconstruction method based on meta-model according to claim 1, characterized in that, Step S104 is followed by step S105: Based on the OSLC ServiceProvider mechanism of the Eclipse Lyo framework, the generated OWL ontology is registered as a ServiceProvider and exposed to the outside world through a RESTful interface, supporting SPARQL semantic queries.
6. The Modelica model parsing and semantic reconstruction method based on meta-model according to claim 1, characterized in that, The method further includes: The generated OWL / RDF semantic assertions are persistently stored in a triple database, supporting cross-model semantic retrieval based on the SPARQL query language.
7. The Modelica model parsing and semantic reconstruction method based on meta-model according to claim 1, characterized in that, In step S103, for component parameter declarations, the enumeration type definition and its enumeration value list contained in the annotation are identified, and the enumeration item identifier and annotation information are extracted.
8. The Modelica model parsing and semantic reconstruction method based on meta-model according to claim 1, characterized in that, Step S103 also includes parsing error tolerance handling: When an AST node cannot be identified according to the preset rules, a warning log is recorded, the current node is skipped, and subsequent nodes are processed. After the parsing is completed, the warning logs are summarized into a parsing report.
9. A Modelica model parsing and semantic reconstruction system based on a meta-model, characterized in that, include: The metamodel definition module is used to define and store the abstract metamodel of the Modelica language; The parsing module is used to perform lexical and syntactic analysis on Modelica source files using the ANTLR4 tool to generate an AST; The metamodel construction module is used to recursively traverse all class definition nodes starting from the root node of the AST, extract class prefix fields to determine the model element type, extract class body fields to obtain the class body element list, traverse each element, and process inheritance clauses (establish ExtendsRelationship and filter Modelica standard library inheritance), component parameter declarations (extract type prefix, type specifier, array subscript, modifier and comment fields, and perform parameter three-class classification judgment) and nested class definitions (recursively process), forming a hierarchical metamodel object graph; The OWL refactoring module is used to convert the metamodel object graph into OWL / RDF semantic assertions based on OWL ontology mapping rules. The storage module is used to persistently store the metamodel object graph and OWL / RDF semantic assertions.
10. The system according to claim 9, characterized in that, It also includes the OSLC service module, which is used to register the OWL ontology as a ServiceProvider and expose it to the outside world through a RESTful interface.
11. An electronic device comprising a memory, a processor, and a computer program stored in the memory, characterized in that, When the computer program is executed by the processor, it implements the Modelica model parsing and semantic reconstruction method based on the meta-model as described in any one of claims 1 to 8.
12. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the Modelica model parsing and semantic reconstruction method based on the meta-model as described in any one of claims 1 to 8.
Citation Information
Patent Citations
Grammar analysis system and method for Modelica language
CN119918534A
