How to Integrate External Data Files with Your COMSOL® App

August 30, 2016

Have you ever wanted to integrate your COMSOL® software apps with external data files? These files can contain material properties, geometric dimensions, or other model inputs, and such data can derive from internal company standards or be provided by a vendor. Built-in methods in the Application Builder simplify reading from these files and displaying options read. To show this procedure, we will build an app that populates a combo box with material properties from a comma-separated values (CSV) file.

A Brief Introduction to Using External Files in Apps

To begin, let’s consider the needs of an app that uses external files:

  1. A user interface (UI) object for users to browse to file locations
  2. A UI object to let users choose between options read from the files
  3. Code to change relevant model object settings according to users’ selections

For the first and second items, theFile Importobject and aCombo Boxin the Application Builder are good options. Meanwhile, there are a number of tools available that make the third task quite simple. One such tool is theRecord Codefeature, which generates equivalent Java® code for the tasks we perform using the user interface in the COMSOL Multiphysics® software.

When building apps, we often need more code than the methods that set the model inputs. Such auxiliary methods can convert data, manipulate arrays, or interact with the operating system, among other tasks. Again, the Application Builder includes built-in methods for such tasks, allowing you to add features to your apps with minimal coding.

Here, we will demonstrate these ideas by extending the functionality of a tuning fork app. First, we will add a combo box to select between tuning forks made of aluminum, brass, or steel. Then, we will add a File Import object to read materials from a data file.

Extending the Functionality of a Tuning Fork App

Tuning forks are used to calibrate musical instruments to a standard pitch. Tuning fork-like structures, however, are also used in industrial applications such as MEMS gyroscopes.

In an earlier blog post, we presented atuning fork appthat calculates the natural frequency of a steel tuning fork given its length. The app does the reverse as well, determining the length to achieve a target frequency. In our original demonstration, we fixed the prong radius to one commercially available size. As such, users could only adjust the prong length.

Image highlighting a tuning fork simulation app.
The original tuning fork application. The prong length can be changed, while other inputs are fixed.

Say that you now want users to change the material or prong radius. One way to do so is to insertInput FieldorSliderobjects. These UI objects allow users to specify any values. On the other hand, the tuning fork market has only certain materials and prong radii. When you want an app to offer choices between discrete options, a Combo Box is one suitable object.

These options could be hardcoded if all of the available choices are known when the app is created. But what if new choices become available on the market after the app is distributed? Hardcoding the new options and redistributing the app is not ideal. A better plan is to design an app that allows users to point to a data file and make the app populate combo boxes and other UI objects. Whenever the available choices change, users can simply provide a new data file containing the updated options. This way you make the app enforce market or company standards, without presumptively setting the standards in stone.

Combo Boxes and Recording Code

A Combo Box helps users select from a predefined list and sets the value of a variable according to their choice. The available choices are specified in aChoice List, which features aValueandDisplay name. TheDisplay nameis a description that users see in the UI, while theValueis what the variable will contain. Such variables associated with input objects in the UI are called the input object’ssource. An app programmer can, for example, use a variable in a conditional statement to execute a set of actions based on the selected entry.

The series of screenshots below show how to add a combo box for a material selection in the tuning fork app.Aluminum, Brass,andSteelare the predefined choices. Notice that we write full names forDisplay namebut use shorter versions forValue. The source, the stringmat, takes eitheralm, brs,orstlwhen the user clicks onAluminum, Brass,orSteel.

Screenshot depicting how to add a Combo Box.
Adding a Combo Box.

Image illustrating how to add a Choice List.
Adding a Choice List.

Figure displaying how to associate a Combo Box with a Choice List.
Associating a Choice List with a Combo Box.

If we run the application now, clicking the combo box sets the stringmatto eitheralm, brs,orstl; and that is all. The material properties in the model do not change yet. To achieve this, we have to write a Java® method and associate the method with the combo box.

Let’s name this new methodchange_material. In the method, we need to include Java® code for updating the density, Young’s modulus, and Poisson’s ratio. To this end, we perform the following steps:

  1. ClickRecord Code
  2. Switch to the Model Builder and change the material properties to some numerical values
  3. ClickStop Recording

The software will give us the Java® code corresponding to the set of actions we performed in the Model Builder. This is more efficient and less prone to error than looking for object names and methods in theCOMSOL Programming Reference Manual.

Screen capture demonstrating how to add a new method and use the Record Code feature.
Adding a new method and using record code to obtain the code for changing density, Young’s modulus, and Poisson’s ratio.

The Java® code above, obtained using the Record Code feature, fixes the material properties to one set of values. Next, we add a conditional block to choose material properties based on the string mat. Don’t want to have to remember the Java® code syntax for an if-else statement? Use theLanguage Elementsfeature! Finally, we associate the method with theOn data changeevent of the combo box, as shown below.

Image depicting how to get Java syntax with the Language Elements feature.
The Language Elements feature can be used to get Java® code syntax, if needed.

Note that even when you are only interested in scripting, with no plan to make an app, you can utilize the Record Code feature to quickly and easily generate code. To learn more, read our blog post “Apps: How to Use the Editor Tools and Record Code Features“.

Reading from a File and Dynamically Changing a Choice List

To incorporate external files, the app has to enable users to browse to such files. The Application Builder has a File Import object for this purpose. As when adding any input object, we take the following two steps:

  1. Associate the File Import object with an item in the model or a declaration
  2. Code a method that runs when the data in the input object changes

The first task is mandatory. In the current example, we will associate the File Import object with a File declaration. A File Import object stores a file path and generates an alias to the path.

The second task, which has a method run right after an input object’s data change, is optional. For instance, the value might only be used later when computing the solution. But the app we are creating has to execute the following actions when the file name in the File Import object changes:

  1. Read the file and store its content in a string matrix
  2. Store the labels for all of the rows in a string array
  3. Update the values and display names of the combo box based on the contents of the data file just read

To this end, we will create a new method,read_materials_file, and link it with the File Import object’sOn data changeevent, as illustrated in the following screenshot.

Screenshot highlighting three steps for associating a File Import object with an On data change event and File declaration.
Adding a File Import object and associating it with a File declaration andOn data changeevent.

Let’s now write the code for this method. In the Application Builder, methods are written using the Java® programming language. We could write such codes from scratch but the Application Builder’s Method Library contains several built-in methods for file input/output and other actions, making the process more efficient.

Reading a File

For reading comma-separated values (CSV file), we can use thereadCSVFilemethod. The argument to this method is a string for the file path and the output is a string matrix.

String[][] readCSVFile(String name)

Getting Labels

For the purpose of this demonstration, we assume that the first column of the data file contains material labels, such asAluminumandSteel from supplier 1. We want to extract this column and display it in the combo box. To extract a column from an array, we can use the built-ingetColumnmethod. The arguments are a string matrix and the column number. The column index starts from zero, as is the case with Java® code array indices.

String[] getColumn(String[][] matrix, int column)

Dynamically Changing Choice List Values and Display Names

To change values in a Choice List, we can use the built-insetListmethod. This method changes the values and display names of a Choice List to the strings in the argument.

setList(String[] value, String[] displayNames)

Using the above built-in methods, we obtain the following short code for reading a CSV file, storing the contents, and updating the combo box’s Choice List.

Image displaying a read_materials_file in the Application Builder.
The built-in Method Library in the Application Builder contains several methods for manipulating data or UI objects, file reading/writing, and interacting with the operating system.

Let’s clarify the stringupload:///file_matCSVand the integer arraymatindexin the above method. The stringupload:///file_matCSVrepresents the file path. Go to theAccess usingsection in the File declaration settings window to find this alias. The integer arraymatindexmakes up values for the combo box’s Choice List.

In the method, we assume the first column in the CSV file to be material labels. These labels, extracted using the built-in methodgetColumn, are displayed in the combo box. The values, on the other hand, are internal tags for programming. As such, we should not expect an app user to supply them. Since we can not foresee the number of rows in the data file, we can not hardcode thevaluestring either.

What we can do instead is get the number of rows in the file and store as many integers in an integer array. This entails changing the source data of the combo box from a string to an integer (see the integerimatin the screenshot below). Finally, make the built-intoStringmethod convert the integer array to a string array for thesetListmethod. That way, when a user clicks on the combo box, the integer changes to the index number of the selected row. The app can then use this number to go to the relevant row in the string matrix holding the file’s content.

The above modifications result in the following method.

Visual displaying how to use strings or integers as sources in combo boxes.
Combo boxes can use strings or integers as sources.

Notice the old code for hardcoded material options is still around. Our goal is to let users incorporate their own material data file, if they have one. Otherwise, they need alternate options. To that end, we make a new method out of the commented section and have it called when users prefer the built-in choices to external data files. This preference can be expressed, for example, by checking on/off within a check box. The resulting implementation is highlighted below.

Screenshots showing a read_materials_file, change_material, and default_material.

Simulation app with the option to use data from CSV file highlighted.
A Boolean variable associated with a check box can be used to switch between a material data file and alternate hardcoded options.

A method local to the check box object is used to enable the file browser or disable the browser and populate the combo box with default options, based on the value of the check box. The Record Code feature is again used to get the Java® code for enabling and disabling the file browser.

Screen capture illustrating a local method.
A user interface object can have a local method that runs when a user interacts with that particular object. Local methods can not be called from elsewhere in the app.

Now let’s utilize our app with the following sample CSV file.

Image displaying a user-specified data file.
Apps can be linked to a user-specified data file.

Here’s a look at the final version of the app in action.

Screenshot of a tuning fork app with the File import window open.
Image showing the final version of a tuning fork app.

Possible Further Refinement of the Tuning Fork App

The main purpose of today’s blog post is to demonstrate how to link apps to external data files. Note that some auxiliary refinements have been left out.

File Structure

We assumed that the data file contains labels, densities, Young’s moduli, and Poisson ratios in columns in that order. It is possible that the data file is not in that order or contains some columns that are unnecessary for the app’s purpose. Rather than asking users to restructure their file to conform to our assumptions, we can add input fields or dialog boxes in the app to ask the user which column contains what information.

Consider the case where a user has more than one data file, say from different suppliers and possibly with different formats. Instead of reading just one file at a time, we may want to make the app append the Choice List every time a new file is read. The Application Builder has built-in methods for appending arrays, finding unique values when there are duplicates, writing the appended data to an output file for future use, and more.

Geometry Parameters

In this app, the mechanical properties and length of the tuning fork can be edited while the radius is fixed. If the radius needs to be read from a data file as well, we just need to use the Record Code feature to get the Java® code for changing the radius and add it to the methods above. This is true for any model input.

Input Units

We have taken for granted that the data will be in the right units. If this is not certain, we can use the Application Builder’s built-in methods for string manipulation and data validation to take care of that.

Concluding Thoughts on Using an External Data File with an App

We have shown you how to use an external data file with an app. This feature helps you design apps that cater to evolving company or market standards, without the need for modifying the code when such changes happen. The same techniques for file reading and manipulation may come in handy if your app needs a lengthy list of inputs. App users can easily store their frequently used sets of values in a data file.

To effectively and efficiently create apps, we encourage you to utilize the Application Builder’s Method Library. It contains several methods that can enhance the functionality and usability of apps. For more details, you can refer to theIntroduction to Application Buildermanual, particularly theBuilt-in Method Libraryappendix.

For further information on the basics of building COMSOL apps, be sure to check out ourIntro to Application Builder Videos seriesas well as this blog post onautomating model preprocessing with the Application Builder.

If you have any questions about this blog post or building simulation apps, please do not hesitate tocontact us.

Oracle and Java are registered trademarks of Oracle and/or its affiliates.


Comments (0)

Leave a Comment
Log In | Registration
Loading...
EXPLORE COMSOL BLOG
Baidu
map