学习中心

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

Note that 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.

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 theModeldrop-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.

A checkmark shows GPT-4 is selected in the model menu as the model to use in the ChatGPT user interface.
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 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 aBlank Model. Then, open the Application Builder and create a new method. In theMethod Editorwindow, 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. 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 selectRunfrom the context menu of themethod1node 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.

A close-up of the application tree with a method selected and the corresponding options.
Running the method.

After the method has run, the geometry can be viewed in theGraphicswindow in the COMSOL Multiphysics user interface by selectingComponent 1in the model tree.

The model geometry for the cylinder in the Graphics window.
The geometry generated as a result of running the method.

To review, the steps used to achieve this result are:

  1. Post custom COMSOL prompts to ChatGPT® to prepare it for the task.
  2. Ask ChatGPT® a given modeling operation.
  3. Copy the code into a method in the Application Builder.
  4. 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 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. TheclearModeloperation ensures that the tag is available. Please note that theclearModeloperation 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 window, which includes a brief description of why the method failed to run and where in the code the failure 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 theaxistypeproperty to the valuecustom. The error message explains that the only allowed values for theaxistypeproperty arex,y,z,cartesian, orspherical. 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 theGraphicswindow in COMSOL Multiphysics®.

The geometry for the rotated cylinder in the Graphics window.
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 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 theHeat Transfer in Solidsinterface as well as twoTemperatureboundary 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 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 theGraphicswindow by selecting theMesh 1node under theComponent 1node in the model tree.

The mesh for the rotated cylinder in the Graphics window.
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 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 theSettingswindow by selecting its respective node found under theMaterialsnode underComponent 1in 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 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 theGraphicswindow by selecting the plot group found under theResultsnode in the model tree.

A plot of the temperature distribution for the rotated cylinder, which uses a rainbow color distribution showing shades of blue, cyan, green, yellow, orange, and red.
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.

The ChatGPT user interface with the option to explore GPTs.
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 user interface for the COMSOL API for Java® GPT.

The COMSOL API for Java®, a custom GPT

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 theColored Selectionsadd-in, available in the COMSOL Multiphysics Add-In Library, there is anautoRandomColoredSelectionsmethod that automatically assigns random colors to the domains or boundaries of a model.

Upon loadingcolored_selections.mphand 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 methodautoRandomColoredSelections. 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 Method Editor window in the Application Builder with a method for the Colored Selections add-in highlighted and showing the corresponding code. The Method Editor window in the Application Builder with a method for the Colored Selections add-in highlighted and showing the corresponding code.

TheautoRandomColoredSelectionsmethod in theColored Selectionsadd-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 theDevelopertab 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 onUsing Add-Ins

In one part of this method, the following lines assign red, green, and blue colors to an arrayrgbwith 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 arrayrgb.

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. 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. 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 throughmodel 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 usingmodel methods, we have several resources available. This includes blog posts on usingmodel methodsforaccelerating your workflow,automating physics and study choices, andcreating randomized geometry. For a comprehensive resource on writing code for COMSOL models and applications using theMethod Editor, see theCOMSOL Multiphysics Application Programming Guide.

ChatGPT is a registered trademark of OpenAI, Inc.

Java is a registered trademark of Oracle and/or its affiliates.


请提交与此页面相关的反馈,或点击此处联系技术支持

Baidu
map