MPh-py / MPh

Pythonic scripting interface for Comsol Multiphysics
https://mph.readthedocs.io
MIT License
274 stars 70 forks source link

Overloaded Java method with boolean and integer arguments #79

Closed banduser closed 2 years ago

banduser commented 2 years ago

I'm currrently using MPH to access the Java Layer of COMSOL directly in order to change the parameters of a model.

So far, in order to change my model I've been saving my COMSOL model as a .java file and copying lines of code, then adding '.java' after 'model' and running the code in python.

So for example:

model.param().set("box_width", "100 [mm]");

becomes

model.java.param().set("box_width", "100 [mm]");

This works great for changing Geometry Parameters, however, I've run into a seemingly minor issue when attempting to change certain Options in Comsol:

grafik

Lets say I check the box marked 'Selections' in the image above and then copy the java code into my python script, I get

model.component("comp1").mesh("mesh1").export().set("selection", true);

which I can change to

model.java.component("comp1").mesh("mesh1").export().set("selection", true);

but get an error when running the code in python:

Because the boolean operators for python are capitalized ('True' instead of 'true'), this leads to python reading 'true' as an unnamed variable and results in an error. Changing the boolean operator to python Syntax results in a COMSOL error however:

model.java.component("comp1").mesh("mesh1").export().set("selection", true);

Traceback (most recent call last):

  File "C:\Users\me\Desktop\Mph_Test_Param.py", line 53, in <module>
    model.java.component("comp1").mesh("mesh1").export().set("selection", True);

TypeError: Ambiguous overloads found for com.comsol.model.impl.PropFeatureImpl.set(str,bool) between:
    public com.comsol.model.PropFeature com.comsol.model.impl.PropFeatureImpl.set(java.lang.String,boolean)
    public com.comsol.model.PropFeature com.comsol.model.impl.PropFeatureImpl.set(java.lang.String,int)

I've found a fix for this using JPype with the argumentjpype.java.lang.Boolean(True):

model.java.component("comp1").mesh("mesh1").export().set("selection", jpype.java.lang.Boolean(True);

Just wanted to include this here incase anyone runs into the same issue.

john-hen commented 2 years ago

Thanks for documenting this here. It happens because in Python bool is a subclass of int, and JPype treats them the same and then cannot decide which of the two overloaded methods to call. Instead of jpype.java.lang.Boolean you can also use jpype.JBoolean to cast to a Java bool.