Controller program generation method based on semantic planning and quality optimization
By employing a multi-stage PLC program generation and optimization method, the problems of poor flexibility and uncontrollable quality in existing PLC code generation technologies have been solved. This method enables efficient and verifiable PLC program generation, thereby improving the development efficiency and quality of industrial automation control.
Patent Information
- Application Number
- CN202511534272.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-26
- Publication Date
- 2026-01-09
AI Technical Summary
Existing PLC code automatic generation technologies suffer from poor flexibility, difficulty in meeting complex industrial needs, inability to guarantee the quality of generated code, and lack of effective code reuse mechanisms. Furthermore, existing tools cannot effectively integrate user feedback or automatic evaluation results for code repair and optimization, resulting in low iteration efficiency.
A multi-stage PLC program generation and optimization method is adopted, which combines semantic retrieval-enhanced task planning, structured code synthesis, and feedback-based quality closed-loop optimization mechanism. Through semantic indexing, inference scheduling, and intermediate representation structure, natural language tasks are transformed into verifiable plans with logical constraints. Through module clustering and multi-round prompt-guided logic reconstruction, high-quality PLC programs conforming to the IEC61131-3 standard are generated.
It significantly improves development efficiency, program robustness, and feasibility for industrial deployment. The generated PLC program has clear logic, standardized structure, good predictability and maintainability, supports modular combination and multi-scenario reuse, and reduces the development threshold and the risk of human error.
Smart Images

Figure CN121300221A_ABST
Abstract
Description
Technical Field
[0001] This invention provides a controller program generation method based on semantic planning and quality optimization, belonging to the field of automation technology. Background Technology
[0002] With the continuous development of industrial automation and intelligent manufacturing, control systems based on programmable logic controllers (PLCs) are widely used in various industrial processes, becoming a core technology for the execution and control of critical tasks on the production floor. Especially driven by the Industrial Internet of Things (IIoT) and Industry 4.0, manufacturing enterprises are placing higher demands on the complexity, response speed, security, and adaptability of control programs. Traditional PLC programming methods heavily rely on human experience, resulting in low programming efficiency, high error rates, and difficulty in meeting the rapid deployment and diverse customization needs of complex dynamic tasks. Therefore, researching the automatic generation and optimization of PLC code using artificial intelligence methods such as Large Language Models (LLM) has become one of the important development directions for industrial intelligent upgrading.
[0003] Although some research has attempted to introduce natural language processing (NLP) technology into PLC code generation, existing methods generally suffer from problems such as uncontrollable code quality, low efficiency in utilizing error feedback, and poor adaptation to industry standards, making it difficult to meet the stringent requirements of industrial-grade executability. On the one hand, the generated control programs lack systematic semantic planning and logical constraints, leading to frequent syntax errors and functional defects; on the other hand, existing tools cannot effectively integrate user feedback or automatic evaluation results for code repair and optimization, resulting in low iteration efficiency.
[0004] The aforementioned issues limit the implementation and application of large-scale models in the field of industrial control. There is an urgent need to build a collaborative system with planning capabilities, code synthesis capabilities, and quality self-optimization capabilities to support a PLC code generation process with high reliability, verifiability, and low human dependence. Summary of the Invention
[0005] This invention provides a controller program generation method based on semantic planning and quality optimization, which solves the following technical problems:
[0006] (1) This invention aims to solve the problems in existing PLC code automatic generation technology, including the challenges of poor flexibility, difficulty in meeting complex industrial needs, inability to guarantee the quality of generated code, and lack of effective code reuse mechanisms in large-scale systems. A multi-stage PLC program generation and optimization method for natural language task description is proposed, which integrates semantic retrieval-enhanced task planning, structured code synthesis, and feedback-based quality closed-loop optimization mechanism.
[0007] (2) This invention automatically transforms natural language tasks into verifiable plans with logical constraints by constructing semantic indexes, inference scheduling and intermediate representation structures; it achieves high-quality PLC program generation that conforms to the IEC61131-3 standard through module clustering and multi-round prompt-guided logic reconstruction; and it combines static analysis and test feedback, adopts iterative optimization and scoring mechanisms to evaluate and enhance code quality, thereby systematically solving the problems of full-process intelligence, structuring and verification of "natural language → PLC program", significantly improving development efficiency, program robustness and feasibility of industrial deployment.
[0008] The specific technical solution of this invention is as follows:
[0009] A controller program generation method based on semantic planning and quality optimization includes the following steps:
[0010] (1) Input Natural Language Task Description Dataset Each of them This represents an automated control task.
[0011] (2) Perform semantic preprocessing on each task tᵢ, including:
[0012] Task text classification: ,in The results of classifying the task text;
[0013] Embedded representation generation: ,in For the task Embedded representation;
[0014] The system pre-builds a structured knowledge base Includes function block definitions, interface specifications, and control semantics;
[0015] (3) Use vector similarity to perform semantic retrieval on tᵢ to obtain a set of matching fragments:
[0016]
[0017] in Representing a knowledge base Matching fragments in Represents the vector similarity function. Representing a knowledge base In and the task The embedded representation of the matched fragment, To set a threshold;
[0018] (4) Generate task context representation structure It includes control objectives, candidate function blocks, boundary conditions, and semantic label information.
[0019] (5) Dynamically schedule the inference submodule and select which module to call based on the task complexity:
[0020] State machine synthesis module: ;
[0021] Constraint propagation module: ;
[0022] Security logic verification module: ;
[0023] Semantic path extension module: ;
[0024] (6) Generate a structured task plan from the results of combined reasoning:
[0025]
[0026] in: Indicates the control objective. This represents logic and state transitions. Mapping function blocks and signal actions.
[0027] (7) The input to the code synthesis module is a triple:
[0028]
[0029] in: For task description, For structured task planning, For constraint set;
[0030] (8) Formal definition of the synthesized function:
[0031]
[0032] in: For automatic code generation functions, To output the ST program.
[0033] (9) Based on the ST code skeleton, the variable declaration section, initialization logic and control structure are automatically extracted and defined with explicit identifiers to support subsequent refactoring and combination.
[0034] (10) Set of submodules Clustering is performed using a lightweight structure embedding and K-means clustering, a representative control structure is selected, and redundant modules are removed.
[0035] (11) Perform multi-round guided refactoring (CoT) for each representative submodule. Each refactoring process is as follows:
[0036]
[0037] in: Indicates the first The refactored submodules Indicates the first The refactored submodules This indicates a task description. For context constraints, This is a semantically based logic optimization function.
[0038] (12) The code synthesis process is as follows:
[0039] (12.1) Parse the ST skeleton and extract semantic submodules;
[0040] (12.2) Clustering and redundancy removal, selecting representative modules;
[0041] (12.3) CoT multi-round reconstruction to maintain semantic consistency;
[0042] (12.4) Merge the declaration area, initialization logic and refactor the module;
[0043] (12.5) Verify the syntax and semantics of the generated code;
[0044] (12.6) Return to the executable structured PLC program.
[0045] (13) The quality optimization module is based on structured error context and incorporates the following feedback:
[0046] Static analysis: Compiler diagnostic results;
[0047] Dynamic testing: test case execution and attribute verification;
[0048] (14) Let the diagnostic feedback set be:
[0049]
[0050] in: Indicates the first The static analysis results are as follows: Indicates the first Item dynamic feedback.
[0051] (15) Construct a multidimensional error context and perform selective repair. Formalized as:
[0052]
[0053] in: Indicates the logical location where the corresponding error occurred. The semantic region representing the impact of the error. This indicates the weight of the error's impact on the overall functionality.
[0054] (16) In selective repair, errors that meet the following conditions are given priority:
[0055]
[0056] in: This is an indicator function that takes a value of 1 when the error is located in a critical control path and 0 otherwise, ensuring that the part that has the greatest impact on the control objective is repaired first.
[0057] (17) Perform a quality assessment after repair, using Round-by-round scoring, scoring function definition:
[0058]
[0059] in: For the first The evaluation score is evaluated in rounds, with the weights decreasing linearly to emphasize the effects of previous optimizations.
[0060] (18) If the model output format is abnormal, the system will assign a default score. And record rollback information to ensure process robustness.
[0061] (19) If ,in If the score threshold is specified, then the iterative optimization process is executed:
[0062] (19.1) Analysis and feedback;
[0063] (19.2) Modeling error context;
[0064] (19.3) Apply targeted repair strategies;
[0065] (19.4) Recalculate Q;
[0066] (20) The feedback from multiple rounds of evaluation will be summarized by the large model to track persistent problems and assist in fine-tuning.
[0067] (21) When The output PLC code is the final version.
[0068] The technical effects of the present invention are as follows:
[0069] (1) This invention significantly improves the development efficiency and quality of industrial automation control programs by constructing a full-process automated technology system from natural language task description to structured PLC programs. Compared with the traditional development method that relies on human experience and templates, this invention introduces intelligent reasoning mechanisms and structured intermediate representations in semantic understanding, logic planning, code synthesis and verification optimization, etc. It can automatically parse complex task intentions, generate control logic structures that conform to industrial standards, and effectively support modular combination and multi-scenario reuse, reducing the development threshold and the risk of human error.
[0070] (2) This invention introduces a closed-loop quality optimization mechanism, integrating static diagnosis and dynamic feedback into a multi-round iterative repair and evaluation process, systematically improving the robustness, correctness, and maintainability of the program. The generated PLC program is not only logically clear and structurally standardized, but also capable of performance optimization and boundary verification under constraint-driven conditions, possessing good predictability and industrial deployment capabilities. The overall solution breaks through the bottlenecks of existing automatic generation systems in task understanding, semantic consistency maintenance, and code quality assurance, providing key technical support for the development of highly reliable control programs in intelligent manufacturing and industrial internet environments. Attached Figure Description
[0071] Figure 1 This is a flowchart of the present invention. Detailed Implementation
[0072] The specific technical solution of the present invention will be described in conjunction with the accompanying drawings and embodiments. The process of the present invention is as follows: Figure 1 As shown.
[0073] Example 1: Three-station sorting and safety interlock control on an automobile assembly line
[0074] Implementation steps:
[0075] (1) The production line consists of three conveyor sections and two buffer positions; the requirements are "stop upon arrival, yield at full capacity, emergency stop interlock, and adjacent sections cannot be fed simultaneously". The input consists of the operator's natural language process description and I / O point table.
[0076] (2) Classify and vectorize the task text, and combine the structured knowledge of function blocks and interface specifications to retrieve relevant fragments of "state machine / interlock / cycle control" to form a context: control target, candidate function blocks (timer, rising edge trigger, interlock logic), boundary conditions (adjacent mutual exclusion, full position yield), etc.
[0077] (3) Dynamic scheduling reasoning submodule: state machine synthesis (Idle / FeedIn / Sort / Transfer / Fault), constraint propagation (adjacent interlocking), security verification (E-Stop covers all drivers), semantic path extension (abnormal rollback).
[0078] (4) The triplet of "task description - task plan - constraint set" is fed into the synthesis function to generate the ST skeleton conforming to IEC61131-3, and the variable segment, initialization segment and control structure are automatically separated. Lightweight structure embedding and K-means clustering (k=3) are performed on the 8 semantic sub-modules to select three representative modules: "adjacent interlock", "full position yield", and "emergency stop coverage". Then, multiple rounds of CoT reconstruction are carried out while maintaining semantic consistency. Finally, the modules are merged and the syntax-semantic verification is performed.
[0079] (5) The feedback set is composed of 12 compilation diagnostic and simulation test cases. The error context (error location / affected area / weight) is constructed. The critical path is repaired first (such as "emergency stop does not cover a branch road") and scored by round. Iterate to the threshold .
[0080] (6) After two rounds of repairs Convergence is achieved when the value is ≥0.90; in the abnormal use case of "adjacent simultaneous feed", the interlock is successfully blocked; when an emergency stop is triggered, each segment is immediately de-energized and transferred to Fault, and can be restored by pressing Idle→FeedIn after reset.
[0081] Example 2: Level-Temperature Coordinated Control in Chemical Mixing Tanks
[0082] Implementation steps:
[0083] (1) Objective: "Maintain liquid level of 60%±2% and temperature of 70℃±1℃; prohibit heating when liquid level is <40%; cut off heating and alarm when temperature exceeds 40%; pump and drain valve are mutually exclusive." Input is natural language process and sensor, actuator I / O.
[0084] (2) Perform semantic preprocessing and retrieval on the text to locate the knowledge of "formulation segment / process status / interlock / safety strategy" and form the context: control target (liquid level, temperature), candidate function block (PID, timer, comparator), boundary conditions (valve-pump mutual exclusion, over-temperature cut-off), etc.
[0085] (3) Dynamically call state machine synthesis (Fill→HeatMix→Hold→Drain→Fault), constraint propagation (liquid level <40% ⇒ prohibit heating), safety verification (over-temperature, over-liquid level), semantic path extension (return to Hold bandwidth under disturbance).
[0086] (4) Generate the ST skeleton and extract 10 semantic sub-modules; K-means dynamically takes k=4, and the representative modules are "liquid level regulation", "temperature control PID", "interlock (pump / valve / heater)" and "over-temperature emergency handling". Perform 2 to 3 rounds of CoT reconstruction on the representative modules to maintain the consistency of constraints; perform syntax and semantic verification after merging.
[0087] (5) Static diagnosis eliminates uninitialized variables; dynamic testing introduces ±5% level disturbance and ±2℃ measurement noise, constructs error contexts, and prioritizes the repair of "interlock omission" and "boundary jitter" problems; according to the scoring function Iteration to .
[0088] (6) After the third round ≥0.88: Liquid level steady-state error ≤±1.5%, over-temperature triggers cut-off and alarm, pump / valve mutual exclusion is effective in all scenarios; meets convergence and output conditions.
[0089] The core technology of this invention lies in proposing a complete process system for automatically generating structured PLC control programs from natural language task descriptions, encompassing three major stages: semantic planning, code synthesis, and quality optimization. In the semantic planning stage, the system constructs a task representation structure with contextual understanding capabilities through vectorization processing of the task text and semantic retrieval enhancement mechanisms. Based on dynamic reasoning modules (such as state machine synthesis and constraint propagation), it generates a formalized intermediate task plan, bridging the semantic gap between natural language and automated control logic. This structured task plan not only carries the task objectives and control intentions but also provides clear and verifiable semantic input for subsequent automatic code generation.
[0090] This invention uses a standardized ST code skeleton as its foundation, introducing module clustering and prompt-guided refactoring strategies to achieve automatic mapping of structured task plans. Through lightweight embedding, representative module selection, and "chain-of-thought" prompting, the system can achieve fine-grained refactoring and redundancy elimination of control logic while maintaining semantic consistency, thereby automatically synthesizing PLC programs that conform to the IEC 61131-3 standard, have a clear structure, and correct logic. The generated results possess good scalability and module independence, and can be directly applied to industrial-grade deployments, significantly reducing manual intervention and development time.
[0091] This invention designs a closed-loop feedback mechanism that unifies static analysis results and dynamic simulation feedback into a multi-dimensional error context. Combined with a weighted scoring mechanism and an iterative enhancement process, it automatically evaluates and targets program quality for improvement. This mechanism can automatically attempt semantically conservative reconstruction upon error detection and dynamically adjust the repair strategy across multiple rounds of evaluation until a control program meeting a set quality threshold is generated.
[0092] This embodiment can also employ the following methods:
[0093] (1) A code generation system driven by a fixed template library. This approach generates PLC code by constructing a large code template library for typical control tasks and performing template matching and fill-in-the-blank replacement based on natural language keywords or task types. Although this method has low implementation costs and can be quickly deployed in specific domains, it suffers from severe limitations in scalability and generalization. The template method struggles to handle the control intent and boundary constraints implicit in the task description, cannot adapt to dynamic combinations and non-standard control logic, and the generated results lack structural consistency and verifiable intermediate representations. Furthermore, it has poor support for complex semantics, which is not conducive to industrial-grade automation development in highly complex scenarios.
[0094] (2) Direct code generation based on Large Language Model (LLM) involves end-to-end encoding of natural language task descriptions using a pre-trained model and directly outputting PLC code snippets. While this method offers advantages in language understanding, it lacks a structured intermediate expression mechanism and a controllable planning stage, resulting in generated code that is often uninterpretable, unstable, and fails to meet industry standards (such as IEC 61131-3) requirements for structural standardization, verifiability, and deployability. Furthermore, this method lacks code-level semantic constraints and quality assessment feedback mechanisms, making it prone to generating semantically drifting errors when faced with complex tasks. Therefore, although this approach offers the convenience of end-to-end generation, it cannot achieve the verifiable link and closed-loop optimization control between the task and code emphasized in this invention.
Claims
1. A controller program generation method based on semantic planning and quality optimization, characterized in that, Includes the following steps: (1) Input Natural Language Task Description Dataset Each of them This represents an automated control task; (2) Perform semantic preprocessing on each task tᵢ, including: Task text classification: ,in The results of classifying the task text; Embedded representation generation: ,in For the task Embedded representation; The system pre-builds a structured knowledge base Includes function block definitions, interface specifications, and control semantics; (3) Using vector similarity pairs Perform semantic retrieval to obtain a set of matching fragments: ; in Representing a knowledge base Matching fragments in Represents the vector similarity function. Representing a knowledge base In and the task The embedded representation of the matched fragment, To set a threshold; (4) Generate task context representation structure ; (5) Dynamically schedule the inference submodule and select the module to be called based on the task complexity; (6) Generate a structured task plan from the results of combined reasoning: ; in: Indicates the control objective. This represents logic and state transitions. Mapping function blocks and signal actions; (7) The input to the code synthesis module is a triple: ; in: For task description, For structured task planning, For constraint set; (8) Formal definition of the synthesized function: ; in: For automatic code generation functions, To output the ST program; (9) Based on the ST code skeleton, the variable declaration section, initialization logic and control structure are automatically extracted and delimited with clear identifiers to support subsequent refactoring and combination; (10) Set of submodules Perform clustering by embedding a lightweight structure and performing K-means clustering, selecting a representative control structure and removing redundant modules; (11) Perform multi-round prompt-guided refactoring (CoT) for each representative submodule; (12) The code synthesis process is as follows: (12.1) Parse the ST skeleton and extract semantic submodules; (12.2) Clustering and redundancy removal, selecting representative modules; (12.3) CoT multi-round reconstruction to maintain semantic consistency; (12.4) Merge the declaration area, initialization logic and refactor the module; (12.5) Verify the syntax and semantics of the generated code; (12.6) Return to the executable structured PLC program; (13) The quality optimization module is based on structured error context and incorporates the following feedback: Static analysis: Compiler diagnostic results; Dynamic testing: test case execution and attribute verification; (14) Define the diagnostic feedback set; (15) Construct a multidimensional error context and perform selective repair. Formalized as: ; in: Indicates the logical location where the corresponding error occurred. The semantic region representing the impact of the error. This indicates the weight of the error's impact on the overall functionality. (16) In selective repair, errors that meet the following conditions are given priority: ; in: This is an indicator function that takes a value of 1 when the error is located in a critical control path and 0 otherwise, ensuring that the part that has the greatest impact on the control objective is repaired first. (17) Perform a quality assessment after repair, using Round-by-round scoring, scoring function definition: ; in: For the first The evaluation scores are evaluated in rounds, with the weights decreasing linearly to emphasize the effectiveness of earlier optimizations. (18) If the model output format is abnormal, the system will assign a default score. And record rollback information to ensure process robustness; (19) If ,in If the score threshold is indicated, then an iterative optimization process is executed; (20) The feedback from multiple rounds of evaluation will be summarized by the large model to track persistent problems and assist in fine-tuning; (21) When The output PLC code is the final version.
2. The controller program generation method based on semantic planning and quality optimization according to claim 1, characterized in that, Step (4) Generate the task context representation structure It includes control objectives, candidate function blocks, boundary conditions, and semantic label information.
3. The controller program generation method based on semantic planning and quality optimization according to claim 1, characterized in that, Step (5) involves calling the module, including: State machine synthesis module: ; Constraint propagation module: ; Security logic verification module: ; Semantic path extension module: .
4. The controller program generation method based on semantic planning and quality optimization according to claim 1, characterized in that, Step (11) Each reconstruction process is as follows: ; in: Indicates the first The refactored submodules Indicates the first The refactored submodules This indicates a task description. For context constraints, It is a semantic-based logic optimization function.
5. The controller program generation method based on semantic planning and quality optimization according to claim 1, characterized in that, The diagnostic feedback set in step (14) is as follows: ; in: Indicates the first The static analysis results are as follows: Indicates the first Item dynamic feedback.
6. The controller program generation method based on semantic planning and quality optimization according to claim 1, characterized in that, The iterative optimization process in step (19) includes: a. Analysis and feedback; b. Model the error context; c. Apply targeted repair strategies; d. Recalculate Q.
Citation Information
Cited By
Code generation method and device, equipment and storage medium
CN121477769A