Generating a random sparse hermitian matrix in Python












1














I'd like to find a way to generate random sparse hermitian matrices in Python, but don't really know how to do so efficiently. How would I go about doing this?



Obviously, there are slow, ugly ways to do this, but since I'm going to be doing this a lot, I'd like if there was a faster way to do it.



Is there an easy way to calculate the density of the matrix? It's the parameter that I'd be using to compare two factorisation algorithms. It's defined as
$$ d = frac{mathrm{nnz}}{n^2} $$
where $mathrm{nnz}$ is defined as the number of nonzero entries in the matrix and $n$ is its number of rows or columns (hence $n^2$ is the number of elements in the matrix).



EDIT



Calculating the density should be easy:



density = np.count_nonzero(A)/n**2


should do the trick.










share|cite|improve this question





























    1














    I'd like to find a way to generate random sparse hermitian matrices in Python, but don't really know how to do so efficiently. How would I go about doing this?



    Obviously, there are slow, ugly ways to do this, but since I'm going to be doing this a lot, I'd like if there was a faster way to do it.



    Is there an easy way to calculate the density of the matrix? It's the parameter that I'd be using to compare two factorisation algorithms. It's defined as
    $$ d = frac{mathrm{nnz}}{n^2} $$
    where $mathrm{nnz}$ is defined as the number of nonzero entries in the matrix and $n$ is its number of rows or columns (hence $n^2$ is the number of elements in the matrix).



    EDIT



    Calculating the density should be easy:



    density = np.count_nonzero(A)/n**2


    should do the trick.










    share|cite|improve this question



























      1












      1








      1







      I'd like to find a way to generate random sparse hermitian matrices in Python, but don't really know how to do so efficiently. How would I go about doing this?



      Obviously, there are slow, ugly ways to do this, but since I'm going to be doing this a lot, I'd like if there was a faster way to do it.



      Is there an easy way to calculate the density of the matrix? It's the parameter that I'd be using to compare two factorisation algorithms. It's defined as
      $$ d = frac{mathrm{nnz}}{n^2} $$
      where $mathrm{nnz}$ is defined as the number of nonzero entries in the matrix and $n$ is its number of rows or columns (hence $n^2$ is the number of elements in the matrix).



      EDIT



      Calculating the density should be easy:



      density = np.count_nonzero(A)/n**2


      should do the trick.










      share|cite|improve this question















      I'd like to find a way to generate random sparse hermitian matrices in Python, but don't really know how to do so efficiently. How would I go about doing this?



      Obviously, there are slow, ugly ways to do this, but since I'm going to be doing this a lot, I'd like if there was a faster way to do it.



      Is there an easy way to calculate the density of the matrix? It's the parameter that I'd be using to compare two factorisation algorithms. It's defined as
      $$ d = frac{mathrm{nnz}}{n^2} $$
      where $mathrm{nnz}$ is defined as the number of nonzero entries in the matrix and $n$ is its number of rows or columns (hence $n^2$ is the number of elements in the matrix).



      EDIT



      Calculating the density should be easy:



      density = np.count_nonzero(A)/n**2


      should do the trick.







      matrices numerical-linear-algebra random python sparse-matrices






      share|cite|improve this question















      share|cite|improve this question













      share|cite|improve this question




      share|cite|improve this question








      edited Nov 30 at 8:33

























      asked Nov 30 at 8:27









      Peiffap

      367




      367






















          2 Answers
          2






          active

          oldest

          votes


















          1














          This generates a random mask with of a given size n and density dens, you just need to apply it to a dense matrix of your choice



          import numpy as np
          np.random.seed(0)

          n = 300
          dens = 0.2
          mask = np.array([np.random.choice([True, False], n, p = [dens, 1 - dens]) for i in range(n)])

          print(np.count_nonzero(mask) / n**2)


          The result of this is



          >>> 0.20224444444444445


          To force the result to be Hermitian just use



          $$
          H = frac{1}{2}(A + A^*)
          $$






          share|cite|improve this answer





















          • Alright, I see how this works but how do I apply the mask to a matrix?
            – Peiffap
            Nov 30 at 10:08










          • @Peiffap Define the matrix M and then run A = M[mask]
            – caverac
            Nov 30 at 10:09












          • M[mask], no? Thanks!
            – Peiffap
            Nov 30 at 10:11



















          0














          When I apply the $M[$mask$]$, I only get the values of $M$ where True is defined in mask. How do I get the sparse matrix $M$ (where false$=0$, True=real value).



          (I think we are following the same course ;))






          share|cite|improve this answer























          • I found it ! M[mask]=0 if you swap the True with probability = 1-dens and False with probability = dens.
            – emanuelPaul
            Dec 5 at 21:25










          • If you have an easier way please feel free to contact me! And if you are from UCL, and you got ideas about LUcsr... contact me as well please!
            – emanuelPaul
            Dec 5 at 21:26











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "69"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          noCode: true, onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmath.stackexchange.com%2fquestions%2f3019821%2fgenerating-a-random-sparse-hermitian-matrix-in-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          This generates a random mask with of a given size n and density dens, you just need to apply it to a dense matrix of your choice



          import numpy as np
          np.random.seed(0)

          n = 300
          dens = 0.2
          mask = np.array([np.random.choice([True, False], n, p = [dens, 1 - dens]) for i in range(n)])

          print(np.count_nonzero(mask) / n**2)


          The result of this is



          >>> 0.20224444444444445


          To force the result to be Hermitian just use



          $$
          H = frac{1}{2}(A + A^*)
          $$






          share|cite|improve this answer





















          • Alright, I see how this works but how do I apply the mask to a matrix?
            – Peiffap
            Nov 30 at 10:08










          • @Peiffap Define the matrix M and then run A = M[mask]
            – caverac
            Nov 30 at 10:09












          • M[mask], no? Thanks!
            – Peiffap
            Nov 30 at 10:11
















          1














          This generates a random mask with of a given size n and density dens, you just need to apply it to a dense matrix of your choice



          import numpy as np
          np.random.seed(0)

          n = 300
          dens = 0.2
          mask = np.array([np.random.choice([True, False], n, p = [dens, 1 - dens]) for i in range(n)])

          print(np.count_nonzero(mask) / n**2)


          The result of this is



          >>> 0.20224444444444445


          To force the result to be Hermitian just use



          $$
          H = frac{1}{2}(A + A^*)
          $$






          share|cite|improve this answer





















          • Alright, I see how this works but how do I apply the mask to a matrix?
            – Peiffap
            Nov 30 at 10:08










          • @Peiffap Define the matrix M and then run A = M[mask]
            – caverac
            Nov 30 at 10:09












          • M[mask], no? Thanks!
            – Peiffap
            Nov 30 at 10:11














          1












          1








          1






          This generates a random mask with of a given size n and density dens, you just need to apply it to a dense matrix of your choice



          import numpy as np
          np.random.seed(0)

          n = 300
          dens = 0.2
          mask = np.array([np.random.choice([True, False], n, p = [dens, 1 - dens]) for i in range(n)])

          print(np.count_nonzero(mask) / n**2)


          The result of this is



          >>> 0.20224444444444445


          To force the result to be Hermitian just use



          $$
          H = frac{1}{2}(A + A^*)
          $$






          share|cite|improve this answer












          This generates a random mask with of a given size n and density dens, you just need to apply it to a dense matrix of your choice



          import numpy as np
          np.random.seed(0)

          n = 300
          dens = 0.2
          mask = np.array([np.random.choice([True, False], n, p = [dens, 1 - dens]) for i in range(n)])

          print(np.count_nonzero(mask) / n**2)


          The result of this is



          >>> 0.20224444444444445


          To force the result to be Hermitian just use



          $$
          H = frac{1}{2}(A + A^*)
          $$







          share|cite|improve this answer












          share|cite|improve this answer



          share|cite|improve this answer










          answered Nov 30 at 9:58









          caverac

          13k21028




          13k21028












          • Alright, I see how this works but how do I apply the mask to a matrix?
            – Peiffap
            Nov 30 at 10:08










          • @Peiffap Define the matrix M and then run A = M[mask]
            – caverac
            Nov 30 at 10:09












          • M[mask], no? Thanks!
            – Peiffap
            Nov 30 at 10:11


















          • Alright, I see how this works but how do I apply the mask to a matrix?
            – Peiffap
            Nov 30 at 10:08










          • @Peiffap Define the matrix M and then run A = M[mask]
            – caverac
            Nov 30 at 10:09












          • M[mask], no? Thanks!
            – Peiffap
            Nov 30 at 10:11
















          Alright, I see how this works but how do I apply the mask to a matrix?
          – Peiffap
          Nov 30 at 10:08




          Alright, I see how this works but how do I apply the mask to a matrix?
          – Peiffap
          Nov 30 at 10:08












          @Peiffap Define the matrix M and then run A = M[mask]
          – caverac
          Nov 30 at 10:09






          @Peiffap Define the matrix M and then run A = M[mask]
          – caverac
          Nov 30 at 10:09














          M[mask], no? Thanks!
          – Peiffap
          Nov 30 at 10:11




          M[mask], no? Thanks!
          – Peiffap
          Nov 30 at 10:11











          0














          When I apply the $M[$mask$]$, I only get the values of $M$ where True is defined in mask. How do I get the sparse matrix $M$ (where false$=0$, True=real value).



          (I think we are following the same course ;))






          share|cite|improve this answer























          • I found it ! M[mask]=0 if you swap the True with probability = 1-dens and False with probability = dens.
            – emanuelPaul
            Dec 5 at 21:25










          • If you have an easier way please feel free to contact me! And if you are from UCL, and you got ideas about LUcsr... contact me as well please!
            – emanuelPaul
            Dec 5 at 21:26
















          0














          When I apply the $M[$mask$]$, I only get the values of $M$ where True is defined in mask. How do I get the sparse matrix $M$ (where false$=0$, True=real value).



          (I think we are following the same course ;))






          share|cite|improve this answer























          • I found it ! M[mask]=0 if you swap the True with probability = 1-dens and False with probability = dens.
            – emanuelPaul
            Dec 5 at 21:25










          • If you have an easier way please feel free to contact me! And if you are from UCL, and you got ideas about LUcsr... contact me as well please!
            – emanuelPaul
            Dec 5 at 21:26














          0












          0








          0






          When I apply the $M[$mask$]$, I only get the values of $M$ where True is defined in mask. How do I get the sparse matrix $M$ (where false$=0$, True=real value).



          (I think we are following the same course ;))






          share|cite|improve this answer














          When I apply the $M[$mask$]$, I only get the values of $M$ where True is defined in mask. How do I get the sparse matrix $M$ (where false$=0$, True=real value).



          (I think we are following the same course ;))







          share|cite|improve this answer














          share|cite|improve this answer



          share|cite|improve this answer








          edited Dec 8 at 0:11









          dantopa

          6,41132042




          6,41132042










          answered Dec 5 at 21:08









          emanuelPaul

          1




          1












          • I found it ! M[mask]=0 if you swap the True with probability = 1-dens and False with probability = dens.
            – emanuelPaul
            Dec 5 at 21:25










          • If you have an easier way please feel free to contact me! And if you are from UCL, and you got ideas about LUcsr... contact me as well please!
            – emanuelPaul
            Dec 5 at 21:26


















          • I found it ! M[mask]=0 if you swap the True with probability = 1-dens and False with probability = dens.
            – emanuelPaul
            Dec 5 at 21:25










          • If you have an easier way please feel free to contact me! And if you are from UCL, and you got ideas about LUcsr... contact me as well please!
            – emanuelPaul
            Dec 5 at 21:26
















          I found it ! M[mask]=0 if you swap the True with probability = 1-dens and False with probability = dens.
          – emanuelPaul
          Dec 5 at 21:25




          I found it ! M[mask]=0 if you swap the True with probability = 1-dens and False with probability = dens.
          – emanuelPaul
          Dec 5 at 21:25












          If you have an easier way please feel free to contact me! And if you are from UCL, and you got ideas about LUcsr... contact me as well please!
          – emanuelPaul
          Dec 5 at 21:26




          If you have an easier way please feel free to contact me! And if you are from UCL, and you got ideas about LUcsr... contact me as well please!
          – emanuelPaul
          Dec 5 at 21:26


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Mathematics Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmath.stackexchange.com%2fquestions%2f3019821%2fgenerating-a-random-sparse-hermitian-matrix-in-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Sphinx de Gizeh

          Dijon

          Équipe cycliste