Python Forum

Full Version: Extend my __init__ method by an extra parameter Tol
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to extend my __init__ method by an extra parameter Tol (tolerance) which serves as a threshold for converting a given matrix to a sparse matrix. All elements of the original matrix which have an absolute value less than Tol should be considered as zeros. Give Tol a default value 0

this is my code


import numpy as np


class SparseMatrix:
 
    def __init__(self,matrix):
        self.matrix=np.asarray(matrix)
        self.intern_represent = 'CSR'
        self.intern_represent = 'CSC'
    
    @property   
    def values (self):
        return self.matrix [np.nonzero(self.matrix)]
         
      
    def __repr__(self):
        return (' A= '+ str(self.values) +
                '\nIA= ' + str(self.IA) +
                '\nJA= '+ str(self.JA))
 
    @property
    def IA (self):
        IA =[]
        IA.append (0)
        for i in range (1,np.shape(self.matrix)[0]+1):
            num=IA [i-1] + np.count_nonzero(self.matrix [i-1])
            IA.append(num)
        IA=np.asarray (IA)
        return IA
         
    @property
    def JA (self):
        index=np.nonzero(self.matrix)
        return index [1]
      
    @property   
    def number_of_nonzero(self):
        return len (self.values)
          
    def change (self,i,j,new):
        self.matrix [i][j]=new
        return new

    def ConvertCSC(self):
        return np.transpose(self.matrix)


    def CSReqaulCSC(self):
      if (self.matrix==np.transpose(self.matrix)).all():
          return True
      else:
          return False
      all
def __init__(self,matrix, tol=0):
That part I got, but how can i use it when i want to run the code. Lets say i have this matrix
a = SparseMatrix([[1,3,0,0,0],
                  [0,2,0,3,0],
                  [0,1,1,0,0],
                  [3,0,0,0,2],
                  [0,1,0,0,0]])
    
and I want my tolerance to filter all my numbers higher than 1. Do I change in "def value" or my "IA"?
thx for replying!
class SparseMatrix:
  
    def __init__(self,matrix, tol=0):
        self.matrix=np.asarray(matrix)
        self.intern_represent = 'CSR'
        self.intern_represent = 'CSC'
        self.tol = tol
then use self.tol anywhere you need to use it in the class



class SparseMatrix:
   
    def __init__(self,matrix, tol=0):
        self.matrix=np.asarray(matrix)
        self.intern_represent = 'CSR'
        self.intern_represent = 'CSC'
        self.tol = tol

    def show_tol_value(self):
        print(self.tol)


use_default_tol = SparseMatrix(matrix)
use_default_tol.show_tol_value()
change_default_tol = SparseMatrix(matrix, 1)
change_default_tol.show_tol_value()
Output:
0 1
"All elements of the original matrix which have an absolute value less than Tol should be considered as zeros"

what do you think he(my teacher) means by that quote?
If a value is greater then tol use the value, but if a value is less then tol, 0 should be used instead of the value.
Missing the issue of negative numbers. If a value's absolute value is less than tol, change the value to zero.
If you use numpy, it's easier:

In [1]: import numpy as np                                                                                                            

In [2]: np.random.randint(1, 100, (3,3))                                                                                              
Out[2]: 
array([[58, 13,  8],
       [16, 41, 76],
       [44, 22, 32]])

In [3]: np.random.randint(1, 10, (3,3))                                                                                               
Out[3]: 
array([[9, 9, 4],
       [6, 7, 6],
       [5, 9, 9]])

In [4]: matrix = np.random.randint(1, 10, (3,3))                                                                                      

In [5]: matrix                                                                                                                        
Out[5]: 
array([[9, 6, 3],
       [6, 7, 4],
       [7, 4, 2]])

In [6]: matrix[matrix < 5]                                                                                                            
Out[6]: array([3, 4, 4, 2])

In [7]: matrix[matrix < 5] = 0                                                                                                        

In [8]: matrix                                                                                                                        
Out[8]: 
array([[9, 6, 0],
       [6, 7, 0],
       [7, 0, 0]])
If you want to do this in Python, you can nest loops.

def set_zero(matrix, tolerance):
    result = []
    for row in matrix:
        cols = []
        for value in row:
            if value < tolerance:
                cols.append(0)
            else:
                cols.append(value)
        result.append(cols)
    return result
def set_zero(matrix, tolerance):
    result = []
    for row in matrix:
        cols = []
        for value in row:
            if abs(value) < tolerance:
                cols.append(0)
            else:
                cols.append(value)
        result.append(cols)
    return result
One correction - use abs()