matpy
API¶
Matrix multiplication¶
This is a sample module that defines a bunch of matrix multiplication function and puts them together in a class. So you it’s easier to understand how to actually use classes.
- author
Lucas Sawade (lsawade@princeton.edu, 2019)
- license
GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lgpl.html)
-
class
matpy.matrixmultiplication.
MatrixMultiplication
(a, b, method='matmul')[source]¶ Bases:
object
Class to handle 2D matrix multiplication.
- Usage:
Assume that a and b are 2D numpy arrays that match in size for multiplication.
>>> from matpy.matrixmultiplication import MatrixMultiplication >>> MM = MatrixMultiplication(a, b, method="matmul") >>> c = MM() >>> print(c)
Or using the other method
>>> from matpy.matrixmultiplication import MatrixMultiplication >>> MM = MatrixMultiplication(a, b, method="dotprod") >>> c = MM() >>> print(c)
- Math:
Different ways to compute the dot product of two matrices.
\[A_{ij}B_{jk} = C_{ik}\]
This function initializes the MatrixMultiplication class.
- Parameters
a (numpy.ndarray) – matrix A
b (numpy.ndarray) – matrix B
-
matpy.matrixmultiplication.
dotprod
(a: numpy.array, b: numpy.array) → numpy.ndarray[source]¶ Standard wrapper around numpy’s function.
- Parameters
a (numpy.ndarray) – matrix A
b (numpy.ndarray) – matrix B
- Returns
multiplied matrix
- Usage:
Assume that a and b are 2D numpy arrays that match in size for multiplication.
Example
from matpy.matrixmultiplication import dotprod c = dotprod(a, b) print(c)
-
matpy.matrixmultiplication.
matmul
(a: numpy.array, b: numpy.array) → numpy.ndarray[source]¶ Standard wrapper around numnpy’s function.
- Parameters
a (numpy.ndarray) – matrix A
b (numpy.ndarray) – matrix B
- Returns
multiplied matrix
- Usage:
Assume that a and b are 2D numpy arrays that match in size for multiplication.
from matpy.matrixmultiplication import matmul c = matmul(a, b) print(c)
Logging Utility¶
This module includes a custom logger to make it easier to identify errors and debug etc.
The module adds both another level to the logger and the corresponding formatter. If you want to remove or add any logging level make sure to edit both the CustomLogger and the CustomFormatter to accommodate your changes!
- author
Lucas Sawade (lsawade@princeton.edu, 2019)
- license
GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lgpl.html)
-
class
matpy.log_util.
CustomFormatter
[source]¶ Bases:
logging.Formatter
Logging Formatter to add colors and count warning / errors
This class organizes the customization of the logging output. The formatter as of now outputs the logs in the following manner in order of Loglevel:
Example Output
[2020-04-03 14:17:18] -- matpy.matrixmultiplication ----- [INFO]: Initializing matrices... [2020-04-03 14:17:18] -- matpy.matrixmultiplication ---- [ERROR]: Test Error Level (matrixmultiplication.py:60) [2020-04-03 14:17:18] -- matpy.matrixmultiplication - [CRITICAL]: Test Critical Level (matrixmultiplication.py:61) [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [VERBOSE]: Test Verbose Level [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [VERBOSE]: A: [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [VERBOSE]: [1 2] [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [VERBOSE]: [3 4] [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [VERBOSE]: B: [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [VERBOSE]: [2 3 5] [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [VERBOSE]: [4 5 6] [2020-04-03 14:17:18] -- matpy.matrixmultiplication -- [WARNING]: Matrix size exceeds 4 elements.
These outputs are colored in the actual output but the formatting is just as shown above. VERBOSE is an extra added LogLevel formatting. More can be added below the comment EXTRA LEVELS in the same way the VERBOSE is added.
The variable VERBOSE is given at the top of the module. That way it can be changed for all depending function
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.
Use a style parameter of ‘%’, ‘{‘ or ‘$’ to specify that you want to use one of %-formatting,
str.format()
({}
) formatting orstring.Template
formatting in your format string.Changed in version 3.2: Added the
style
parameter.-
format
(record)[source]¶ Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
-
-
class
matpy.log_util.
CustomLogger
(name, level=0)[source]¶ Bases:
logging.Logger
This class is just created ot add the VERBOSE level. More level could be added to this class to accommodate other levels.
The variable VERBOSE is given at the top of the module. That way it can be changed for all depending function
The class makes it possible to add extra levels to the classic logger The line addLoggingLevel(“VERBOSE”, VERBOSE) in the initalization is an example on how to add a level using the addLoggingLevel function located in this module.
Don’t forget to edit the CustomFormatter to accommodate for your introduced levels if you are using the CustomFormatter. An example is given in the class under # EXTRA LEVELS for the VERBOSE level.
Initialize the logger with a name and an optional level.
-
matpy.log_util.
addLoggingLevel
(levelName, levelNum, methodName=None)[source]¶ Comprehensively adds a new logging level to the logging module and the currently configured logging class.
levelName becomes an attribute of the logging module with the value levelNum. methodName becomes a convenience method for both logging itself and the class returned by logging.getLoggerClass() (usually just logging.Logger). If methodName is not specified, levelName.lower() is used.
To avoid accidental clobberings of existing attributes, this method will raise an AttributeError if the level name is already an attribute of the logging module or if the method name is already present
Example
addLoggingLevel('TRACE', logging.DEBUG - 5) logging.getLogger(__name__).setLevel("TRACE") logging.getLogger(__name__).trace('that worked') logging.trace('so did this') logging.TRACE 5
Taken from StackOverflow because the code was beautifully simple. Author: Mad Physicist (Mar 4, 2016)
Testing¶
Matrix Multiplication¶
This is a small script that shows how to simply create a tests class. The reason why a tests class is the superior choice over a function is that it can set up a testing environment, e.g. a tests directory structure needed to check existing files. The unittest testclass also contains an easy way to check whether your function throws an error, when it should.
- author
Lucas Sawade (lsawade@princeton.edu, 2019)
- license
GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lgpl.html)
-
class
tests.test_matmul_and_dot.
TestDot
(methodName='runTest')[source]¶ Bases:
unittest.case.TestCase
“A sample tests class to check if your modules’ functions ar functioning.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
-
class
tests.test_matmul_and_dot.
TestMM
(methodName='runTest')[source]¶ Bases:
unittest.case.TestCase
“A sample tests class to check if your modules’ functions are functioning.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
-
class
tests.test_matmul_and_dot.
TestMatMul
(methodName='runTest')[source]¶ Bases:
unittest.case.TestCase
“A sample tests class to check if your modules’ functions ar functioning.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
-
setUp
()[source]¶ The setUp command is used to reduce the need for large amounts of redudandant code. This will be executed and setup once before every of your test-class’ method. Very useful if you want to load and setup a certain object.
-