Returning an array using the LAMMPS python+variable commands?

I am using the version from 3 November, 2022 (built with the PYTHON module).

I want to obtain an array from Python, using the LAMMPS python and variable commands. It seems that the python command wants you to hardcode how many characters an inline defined Python function returns. For example:

python 		fxn input 1 v_ntypz return v_fac format ii here """
def fxn(ntypz):
	return 10

This works, because 10 has two digits, and format ii specifies two digits. However, I`m wondering if there is a way to return an array. I’ve tried the following (as a VERY basic trial):

python 		fxn input 1 v_ntypz return v_fac format ss here """
def fxn(ntypz):
	ap = []
	for i in range(3):
	return ap

variable fac python fxn

print "${fac}"                         #TEST CASE 1 (and comment out test case 2)
variable i loop 3                   #TEST CASE 2 (and comment out test case 1)
	print "${fac[i]}"
next i

I try here format ss and format ii (since list ‘ab’ being returned is a string-char string, but it is an array of integers… so decided to test with both). Now if I set format ss here with TEST CASE 2, or if I format ii here, for TEST CASE 2, I get the following error:

ERROR on proc 0: Substitution for illegal variable fac[i] (src/input.cpp:650)
Last command: ${fac[i]
application called MPI_Abort(MPI_COMM_WORLD, 1) - process 0
[unset]: write_line error; fd=-1 buf=:cmd=abort exitcode=1
system msg for write_line failure : Bad file descriptor

If I set format ss here and try TEST CASE 1, I get

Segmentation fault (core dumped)

If I set format ii here and try TEST CASE 1, I get


I’m (A) lost as to what is happening here (although something weird like “-1” for my ostensible list seems to be expected), and (B) in a pickle about how to proceed. My goal is to obtain an array using the python functionality of LAMMPS, and wondering the best way to proceed (and I want Python here, because I want to do some heavier manipulations).

I also noted the documentation suggests example suggests a format pf combo (p - SELF, f - floating point), and I`m unsure what exactly one might do with that (I guess floating point makes sense, but the combo ‘pf’?).

edit: cleaned typos

You cannot return an array from a python style variable, only a scalar.
For the use case that you describe, you have to make the array index a function argument.

Here is a minimal example:

region box block 0 1 0 1 0 1
create_box 1 box

python myfunc input 2 v_arg v_idx return v_fidx format iii here """
mydata = [0, 1, 2, 4, 8, 16]
def myfunc(arg,idx):
   return arg*mydata[idx-1]

variable arg index 10
variable idx loop 6
variable fidx python myfunc

label loop
    print "loop iteration ${idx}: ${fidx}"
next idx
jump SELF loop
1 Like

Thank you! I was able to get my script to run! :slight_smile: