Constraint to make sure a matrix inverse exists

In reply to DK87:

You can try this (and please check my dot-product math)

module top;
  class matrix;
    rand bit signed [3:0]  A[][], AI[][];
    
    constraint c_size { A.size inside {[2:4]}; A.size == AI.size; }
    constraint c_square { foreach (A[D1]) {A.size == A[D1].size;
                                           A.size == AI[D1].size; } 
                        }
    constraint c_inverse { foreach ( A[D1,D2] )
      A[D1].sum() with (int'(A[item.index][D1] * AI[D2][item.index])) == (D1 == D2); }
  endclass
      
  matrix m = new;
  initial begin
    assert(m.randomize());
    foreach (m.A[i,j]) begin
      if (j==0) $display;
      $write(m.A[i][j],,);
    end
    $write("\n-------");
    foreach (m.AI[i,j]) begin
      if (j==0) $display;
       $write(m.AI[i][j],,);
    end
    $display;
  end
      
endmodule : top

Do realize these constraints explode as you increase the number of bits and the size of the array. A 4X4X4 array is randomizing a 128 bit variable with constraints between every combination of bits.

1 Like