Last active
March 17, 2025 12:31
-
-
Save ruihangdu/57fa2e18a2c4b950e13d90522d59ad95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| # For simplicity we assume no change of basis and use basis | |
| # [1, 0, 0, ..], [0, 1, 0, ...] ... as the default basis | |
| class Tensor: | |
| def __init__(self, p, q, n, data): | |
| self.data = data | |
| self.cotravariantRank = p | |
| self.covariantRank = q | |
| self.dimension = n | |
| def get_coordinate_for_index(self, index, index_type): | |
| if index_type == "contravariant": | |
| # we are slicing the data in row-wise fashion | |
| return Tensor( | |
| self.cotravariantRank - 1, | |
| self.covariantRank, | |
| self.dimension, | |
| self.data[index] | |
| ) | |
| else: | |
| # slice in column-wise fashion | |
| return Tensor( | |
| self.cotravariantRank, | |
| self.covariantRank - 1, | |
| self.dimension, | |
| self.data[:, index] | |
| ) | |
| def get_contravariant_coordinates(self): | |
| if self.cotravariantRank == 0: | |
| return None | |
| else: | |
| return [self.get_coordinate_for_index(i, "contravariant") for i in range(self.dimension)] | |
| def get_covariant_coordinates(self): | |
| if self.covariantRank == 0: | |
| return None | |
| else: | |
| return [self.get_coordinate_for_index(i, "covariant") for i in range(self.dimension)] | |
| def __repr__(self): | |
| return str(self.data) | |
| scalar = Tensor(0, 0, 1, 1.23) | |
| vector = Tensor(1, 0, 3, np.array([[1.2], [2], [7.8]])) | |
| covector = Tensor(0, 1, 2, np.array([[3.5, 7.2]])) | |
| matrix = Tensor(1, 1, 3, np.array([[1.5, 2, 3.7], [4.2, 3, 8], [3.9, 23, 2]])) | |
| print(vector.get_contravariant_coordinates()) # [[1.2], [2.], [7.8]] | |
| print(vector.get_covariant_coordinates()) # None | |
| print(covector.get_contravariant_coordinates()) # None | |
| print(covector.get_covariant_coordinates()) # [[3.5], [7.2]] | |
| print(matrix.get_contravariant_coordinates()) # [[1.5 2. 3.7], [4.2 3. 8. ], [ 3.9 23. 2. ]] | |
| print(matrix.get_covariant_coordinates()) # [[1.5 4.2 3.9], [ 2. 3. 23.], [3.7 8. 2. ]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment