How to create complex Matrix by using PETSc.Mat()

Issue #83 closed
fredcool112 created an issue

After A.creator, I try to put numpy.matrix HH in PETSc.Mat(), like the following:

opts = PETSc.Options()
n = opts.getInt('n', 2**N)
A = PETSc.Mat()
A.create()
A.setSizes([n, n])
A.setFromOptions()
A.setUp()
for i in range(2**N):
        for j in range(2**N):
                A[i,j] = HH[i,j]
A.assemble()

Then it shows

test.py:171: ComplexWarning: Casting complex values to real discards the imaginary part
  A[i,j] = HH[i,j]

Please help me to put the complex number into PETSc.Mat()

Thank you

Comments (10)

  1. Lisandro Dalcin

    Have you built PETSc and SLEPc with complex numbers (PETSc configure option --with-scalar-type=complex)?

  2. Lisandro Dalcin

    BTW, you should use A.setType(PETSc.Mat.Type.DENSE) after creation if you intend to store a dense matrix.

  3. Wu

    @dalcinl Hello, I have the same problem, but I install petsc and also petsc4py with conda python. It is only the following command:

    conda install petsc4py

    I would like to ask you here, how can I specify this complex configuration? Thanks

  4. Lisandro Dalcin

    The conda-forge builds do not yet support complex numbers. I'm planning to eventually add a complex variant of the PETSc package, but right now my efforts are directed towards supporting MPI variants.

  5. Ganesh Diwan

    @dalcinl I am trying to import complex matrices from Matlab in Python and use PETSc solvers with the help of petsc4py. I built my PETSc (libpetsc-complex-3.7.3) with the Synaptic and installed petsc4py with pip, both without any issues. I still end up with TypeError when using PETSc.Mat().createAIJ() or PETSc.Vec().createWithArray

    TypeError: Cannot cast array data from dtype('complex128') to dtype('float64') according to the rule 'safe'
    

    Do you reckon my PETSc or petsc4py is not properly configured or if I need to use a specific PETSc branch to be able to work with complex matrices/vectors. Tia.

  6. Lisandro Dalcin

    It seems that your petsc4py is not built with the right petsc-complex build. Please double check this way:

    from petsc4py import PETSc
    print(PETSc.ScalarType)
    

    If PETSc.ScalarType is not a complex type, then you have to rebuild and reinstall petsc4py with the right PETSc build using complex numbers.

  7. Lisandro Dalcin

    You can also check using ldd on the PETSc.so extension module within the petsc4py installation.

  8. Lisandro Dalcin

    This issue tracker is intended to report issues, not general questions or help. A more appropriate place with much more visibility and chances of getting good advice is the petsc-users mailing list.

  9. Log in to comment