Help with KeyError: 0 in Material Assignment Using FenicsX

Help with KeyError: 0 in Material Assignment Using FenicsX

Dear FenicsX Community,

I’m encountering a KeyError: 0 when trying to assign material properties in my FenicsX simulation, and I’m hoping someone can help me troubleshoot the issue. Here’s a simplified version of my code and the problem context:

Code Snippet

materials = {
    1: n_GaAs,
    2: n_AlGaAs,
    3: n_GaAs,
    4: n_AlGaAs,
    5: n_AlOx,
    6: n_AlAs,
    7: n_AlGaAs,
    8: n_GaAs,
    9: n_GaAs + 1j * ni,
    10: n_GaAs,
    11: n_GaAs,
    12: n_GaAs,
    13: n_AlGaAs,
    14: n_GaAs
}

# Assuming 'values' is a list of material tags corresponding to the keys in 'materials'
material_values = np.array([materials[tag] for tag in values], dtype=np.complex128)

material = fem.Function(domain, ufl.FunctionSpace(domain, ("DG", 0)))
material.x.array[:] = material_values

Error Message

Traceback (most recent call last):  File "/home/mjz_77/program/111.py", line 223, in <module>    material_values = np.array([materials[tag] for tag in values], dtype=np.complex128)                                ~~~~~~~~~^^^^^KeyError: 0

The error occurs at the list comprehension where I'm trying to create material_values by indexing into the materials dictionary. The KeyError: 0 indicates that the code is trying to access materials[0], but my dictionary keys start from 1 and go up to 14.

Any guidance on debugging the source of the 0 key access or best practices for material property assignment in FenicsX would be greatly appreciated. Let me know if you need more context about how values is defined or the structure of my domain.

Thank you!

This is a Python issue and unrelated to FEniCS.

The way in which you create values will tell you why you have a 0 to be used as a key. And you’ve not shown us how that’s initialised.

1 Like