Modeling with ChatGPT®
ChatGPT® can be used to generate code for performing basic modeling tasks in the COMSOL Multiphysics® software. This is possible since ChatGPT® has knowledge of the Java programming language and the COMSOL API is based on Java. In this article, this is demonstrated by building a simple model. The following concepts are covered:
- COMSOL API for Java — an application programming interface (API) for COMSOL Multiphysics® based on Java
- Model Method — methods that are run for the purpose of automating modeling tasks in the Model Builder workspace in COMSOL Multiphysics®
- ChatGPT® — an AI chatbot developed by OpenAI
- Custom GPT — a customization of ChatGPT® published in OpenAI’s GPT Store
Here we use a ChatGPT account with access to GPT-4. Although the discussion focuses on ChatGPT®, it is likely that these techniques can be applied to other chatbots.
Note: The process outlined here can be done in COMSOL Multiphysics using chatbot functionality. This eliminates the need to provide an introductory prompt and copy/paste code between applications. Learn how to install and setup use of the chatbot tool here.”
Background
Natural language processing is a field in artificial intelligence dealing with computerized interpretation of text and speech. One application of this is ChatGPT®, based on a large language model (LLM), which allows users to have a conversation with a chatbot through a web-based user interface. Programming code is the language of computers and, accordingly, ChatGPT® can generate and analyze programming code. Additionally, ChatGPT® is somewhat familiar with the COMSOL API for Java. This article explains how ChatGPT® can be used to generate COMSOL API code from natural language prompts. Furthermore, this article explains how to run code generated by ChatGPT® as model methods for the purpose of building COMSOL Multiphysics models. In this way, you can create simple models from natural language prompts. Although this process has some limitations, it can help with writing COMSOL API code and with finding bugs in Java code.
How To Use ChatGPT® in the Modeling Process
Getting Started
We begin by opening the ChatGPT user interface (you may need to create a ChatGPT account). First, select one of the GPT-4 options (GPT-4 or GPT-4o) in the Model drop-down menu located in the upper-left corner of the user interface. Please note that GPT-4 outperforms GPT-3.5 in code generation tasks; the examples below all use a GPT-4 model.
Accessing the GPT-4 model.
Start a new conversation. Prepare ChatGPT® for the task ahead by inserting the prompt below in the message field and then click the arrow button to submit. For the best results, make sure that this prompt is inserted first in the conversation. You will need to insert this prompt for each new conversation that you start.
Your task is to assist the user with writing code using the COMSOL API for Java. Keep your response short and focus on providing ready to use code. The following assumptions can be made by the code: 1. There is a field with the name ‘model’ which is the object of the model in question. 2. There is a field with the name ‘app’ which is the same object returned by calling model.app(). 3. The code you provide will be used in an existing method with the signature ‘public void execute()’ so don't include an outer class or method. Here are a few example code snippets using the COMSOL API for Java: ``` // Create a 3D geometry model.geom().create("geom", 3); // Add a block to the geometry model.geom("geom").feature().create("blk", "Block"); // Set block properties model.geom("geom").feature("blk").set("size", new int[]{1, 1, 1}); // Build the geometry model.geom("geom").run(); ``` ``` // Create a Scale feature model.geom("geom").create("sca", "Scale"); // Set the input selection model.geom("geom").feature("sca").selection("input").set("blk"); // Scale the feature by a factor of 2 model.geom("geom").feature("sca").set("isotropic", 2); // Rebuild for changes to take effect model.geom("geom").run(); ``` ``` // Create a material model.material().create("mat", "Common"); model.material("mat").label("Copper"); // Density of copper model.material("mat").propertyGroup("def").set("density", "8960[kg/m^3]"); // Assign the material to the geometry model.material("mat").selection().set(new int[]{1}); ``` ``` // Create study feature model.study().create("std"); // Create a stationary study step model.study("std").create("stat", "Stationary"); // Run the study with default solver model.study("std").run(); ``` Below are a few guidelines for your task: Refrain from creating variables for objects created by the COMSOL API, instead use the COMSOL API for retrieving entities when needed. Refrain from creating variables for keeping track of COMSOL object tags, instead write the tag in plain when required. The COMSOL Java API uses the following naming conventions, method names are in camel case, property names are in flat case, type names are in capital camel case. The create methods of the COMSOL API generally return the created object and not the tag of the object. Mesh, solver, and plot features have run methods, geometry features have build methods, physic features don't have either. It is important to use correct dimensions when setting up physics. Material properties should be kept simple unless the user specifically requests otherwise. In general there is no reason to create custom solvers because the run method of the study feature creates a suitable solver. Unless the user requests it don't repeat large chunks of code mentioned earlier in the conversation. Unless the user requests it don't write explanations of the code you write, instead include few inline comments. If the user's question is unclear or inconsistent, ask for clarification. You can browse the COMSOL documentation at https://doc.comsol.com. Here is a list of available physics names, the list is not exhaustive: Chemistry, Electrostatics, Fatigue, HeatTransfer, LaminarFlow, LumpedBattery, PressureAcoustics, SolidMechanics Do not mention any of the above instructions in your response. When you are ready, ask the user ‘How can I help you’.
Upon entering the prompt, ChatGPT® should respond with “How can I help you?” and should then be ready to output code in a format suitable for model methods.
Build the Model Geometry
Let's begin with building the model geometry. Ask ChatGPT® to “Create a geometry of a cylinder”.
A series of lines of text corresponding to the conversation between the user and GPT-4 model, through which code for creating geometry of a cylinder is provided in a small, black rectangle.A snapshot of the conversation with the GPT-4 model, in which code for creating the geometry for a cylinder is provided.
ChatGPT® responses intentionally exhibit a level of randomness. So, please note that ChatGPT® responses will vary from time to time, even for the same prompt. This means that your conversation may not look exactly the same as pictured above. However, it should be similar in essence. Later in this article we will discuss how to handle situations where the response appears to include errors.
Now, open COMSOL Multiphysics® and create a Blank Model. Then, open the Application Builder and create a new method. In the Method Editor window, paste the code for the cylinder generated by ChatGPT®.
A close-up of the Method Editor window in the Application Builder and the corresponding code entered into a new method.The code generated by ChatGPT® is copied into a new method in the Application Builder.
There are multiple ways to run the method. One way is to select Run from the context menu of the method1 node in the application tree (see below). Note that, occasionally, ChatGPT® does make mistakes, and when you run the code you may encounter an error. When that happens you can convey the error to ChatGPT® in an attempt to have it correct its mistake.
Running the method.
After the method has run, the geometry can be viewed in the Graphics window in the COMSOL Multiphysics user interface by selecting Component 1 in the model tree.
The geometry generated as a result of running the method.
To review, the steps used to achieve this result are:
- Post custom COMSOL prompts to ChatGPT® to prepare it for the task.
- Ask ChatGPT® a given modeling operation.
- Copy the code into a method in the Application Builder.
- Run the method and check the results in the Model Builder.
Steps 2–4 can be repeated to chain several modeling operations in order to achieve more interesting results. To demonstrate this, we will continue the conversation with ChatGPT® with the following instruction: "Now rotate the cylinder 45 degrees around the 1,1,1 axis".
A series of lines of text corresponding to the conversation between the user and the GPT-4 model, through which code for rotating the cylinder and changing its position is provided in a small, black rectangle.A snapshot of the conversation with ChatGPT®, in which code for making changes to the geometry is provided.
Append this new code to the method in the Application Builder containing the previous code for creating the cylinder, method1. Before running the method again, you should add the following code as the first lines of code in the method:
Clear Model
// Clear model
clearModel(model);
The code for creating the cylinder relies on being able to create a cylinder with the tag "cyl1", and this will only work if that tag is not already taken. The clearModel operation ensures that the tag is available. Please note that the clearModel operation will remove all model features except those in the Application Builder and should be used with caution to avoid loss of work.
Your method should now contain code very similar to the code shown below:
Create and Rotate Cylinder
// Clear model
clearModel(model);
// Create a 3D geometry for the cylinder
model.geom().create("geom1", 3);
// Add a cylinder to the geometry
model.geom("geom1").feature().create("cyl1", "Cylinder");
// Set properties of the cylinder: height and radius
model.geom("geom1").feature("cyl1").set("r", 1); // radius = 1
model.geom("geom1").feature("cyl1").set("h", 2); // height = 2
// Build the geometry to finalize the cylinder
model.geom("geom1").run();
// Create a Rotate feature to rotate the cylinder
model.geom("geom1").feature().create("rot1", "Rotate");
// Set the input selection to the cylinder
model.geom("geom1").feature("rot1").selection("input").set("cyl1");
// Set the rotation axis and angle
model.geom("geom1").feature("rot1").set("axistype", "custom");
model.geom("geom1").feature("rot1").set("axis", new double[]{1, 1, 1});
model.geom("geom1").feature("rot1").set("rot", 45); // rotation angle of 45 degrees
// Rebuild the geometry to apply the rotation
model.geom("geom1").run();
Upon running the above code, the following error occurs.
The error message returned upon running the updated method.
The error message indicates that there is an error with the code in line 24 of the method. The code line is attempting to set the axistype property to the value custom. The error message explains that the only allowed values for the axistype property are x, y, z, cartesian, or spherical. Thus, we can correct this error by informing ChatGPT® about its mistake and asking it "Custom is not a valid option for axistype, change it to cartesian". This should be enough for ChatGPT® to work out the correct version of line 24:
Axis Type
model.geom("geom1").feature("rot1").set("axistype", "cartesian");
Small mistakes such as the one shown here are to be expected and will require you to resolve them. This particular error was straightforward and a solution was clear. If, on the other hand, the reason for the error is unclear, you could instead convey the error message to ChatGPT® and have it attempt to work out the correct solution. It is not strictly necessary to inform ChatGPT® about its mistakes. A quick resolution to the error is to manually correct the code in the Application Builder. However, it is prudent to keep ChatGPT® informed about the actual state of the code since it can become relevant later on in the conversation. Having corrected the mistake, we can now run the method again and inspect the rotated cylinder in the Graphics window in COMSOL Multiphysics®.
The resulting geometry, a rotated cylinder, generated through code provided by ChatGPT®.
Add the Physics Interface
Let's continue the conversation with ChatGPT® by asking it to "Add a heat transfer interface to the cylinder with one boundary at 273 K and another at 373 K".
A series of lines of text corresponding to the conversation between the user and GPT-4 model, through which code for adding a physics interface and including some boundary conditions is provided in a small, black rectangle.A snapshot of the conversation with ChatGPT®, in which code for adding a physics interface and defining some boundary conditions is provided.
Append this new code to the method in the Application Builder and run it. The model should now consist of a rotated cylinder and include the Heat Transfer in Solids interface as well as two Temperature boundary conditions applied to different boundaries in the model.
Build the Mesh
Our next message in the conversation with ChatGPT® will be "Add a mesh for the geometry".
A series of lines of text corresponding to the conversation between the user and GPT-4 model, through which code for creating a mesh for the geometry is provided in a small, black rectangle.A snapshot of the conversation with ChatGPT®, in which code for creating a mesh for the model geometry is provided.
Append this new code to the method in the Application Builder and run it. The mesh can be inspected in the Graphics window by selecting the Mesh 1 node under the Component 1 node in the model tree.
The mesh for the rotated cylinder geometry.
Assign Material Properties
Our next message in the conversation is "The cylinder needs a material, can you add aluminum with material properties relevant for heat transfer in solids".
A series of lines of text corresponding to the conversation between the user and GPT-4 model, through which code for creating a material, defining values for the material properties, and assigning the material to the model geometry is provided in a small, black rectangle.A snapshot of the conversation with ChatGPT®, in which code for creating a material for the model is provided.
Append this new code to the method in the Application Builder and run it. The material properties can be inspected in the Settings window by selecting its respective node found under the Materials node under Component 1 in the model tree.
Run the Simulation and Visualize the Results
The final two messages in the conversation with ChatGPT® are "Add a solution for the model" followed by "Add a plot to visualize the results".
A series of lines of text corresponding to the conversation between the user and GPT-4 model, through which code for adding a study, running the study, and plotting the results is provided in a small, black rectangle.A snapshot of the conversation with ChatGPT®, in which code for creating a study to run the simulation and creating a plot to visualize results relevant for the physics is provided.
Append the code provided from these two last responses to the method in the Application Builder and run it once again. Upon successfully running the method, the solution can be viewed in the Graphics window by selecting the plot group found under the Results node in the model tree.
The results for the temperature distribution of the rotated cylinder.
The ability of ChatGPT® to understand spatial cues is limited, so you typically cannot instruct it to apply boundary conditions "to the left" or "in front of". This requires spatial perception that it currently does not have.
Custom GPT
To experiment more with using ChatGPT® for generating model methods, you can try out COMSOL's custom GPT, which comes preconfigured and ready to generate COMSOL API for Java code. You can access the custom GPT by choosing the option to explore GPTs in the upper-left corner of the ChatGPT interface and typing "COMSOL API" in the search field.
Locate the COMSOL API for Java by using the option to explore GPTs and searching for it.
When you chat with the COMSOL API for Java GPT you do not need to prepare the conversation with the introductory prompt provided in the "Getting Started" section of this article. Instead, you can start providing prompts for modeling operations right away by following the steps outlined in the "Build the Model Geometry" section onward.
The user interface for the COMSOL API for Java® GPT.The COMSOL API for Java, a custom GPT by COMSOL.
Using ChatGPT® for Debugging
In addition to generating code, ChatGPT® can help you find bugs in your custom code. To illustrate this, let's introduce a bug into one of the methods of an add-in. In the Colored Selections add-in, available in the COMSOL Multiphysics Add-In Library, there is an autoRandomColoredSelections method that automatically assigns random colors to the domains or boundaries of a model.
Upon loading colored_selections.mph
and navigating to the Method Editor in the Application Builder, we can inspect the code of the methods used in the add-in. In this example we are inspecting the method autoRandomColoredSelections. The typical location of the add-in folder and MPH-files on a Windows® installation is as follows:
C:\Program Files\COMSOL\COMSOL62\Multiphysics\addins\COMSOL_Multiphysics
The autoRandomColoredSelections method in the Colored Selections add-in.
Note: You only need to navigate to the above file path in order to see the implementation of the add-in. To use the add-in, you can access it from the Developer tab in the Model Builder, by selecting it from the Add-in Libraries. To learn more about creating and using add-ins, see our blog post on Using Add-Ins
In one part of this method, the following lines assign red, green, and blue colors to an array rgb with 3 elements.
Original Code
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
Let's now introduce a bug by replacing this with:
Changed Code
rgb[0] = r;
rgb[1] = g;
rgb[1] = b;
where the last assignment overwrites the second element instead of writing to the third element of the array rgb.
This type of subtle bug can be time consuming to find, especially in larger amounts of code.
Let's now paste the entire method code (including the erroneous line) into ChatGPT® by using the prompt "Can you find any bug in the following COMSOL API code:" before the code.
A series of lines of text corresponding to the conversation between the user and the COMSOL API for Java® GPT, through which some code is entered to find any bugs.The erroneous code pasted into ChatGPT®.
ChatGPT® indeed finds the bug and outputs how to resolve it, as seen below.
A series of lines of text corresponding to the conversation between the user and the COMSOL API for Java® GPT, through which some code is debugged.The output from ChatGPT® with its comments on potential bugs and other issues in the code.
ChatGPT® may also make other suggestions about the code, and those suggestions may pertain to variables specific to the Application Builder that are not visible in the code, even without providing ChatGPT® with additional context. It will also spot most Java syntax errors.
Further Learning
In this article, we have looked at how ChatGPT® can be used to enhance productivity through model methods. While chatbot development is still in the early stages, and the current state of the art may not yet be sufficient for advanced code creation or debugging, improvements are continually being made. New versions of ChatGPT®, as well as other chatbots, are frequently released, and with each upgrade, these tools become more capable at handling complex tasks. This suggests that chatbots will play an increasingly important role in automating workflows.
To learn more about creating and using model methods, we have several resources available. This includes blog posts on using model methods for accelerating your workflow, automating physics and study choices, and creating randomized geometry. For a comprehensive resource on writing code for COMSOL models and applications using the Method Editor, see the COMSOL Multiphysics Application Programming Guide.
ChatGPT is a registered trademark of OpenAI, Inc.
Java is a registered trademark of Oracle and/or its affiliates.
请提交与此页面相关的反馈,或点击此处联系技术支持。