14-linear-algebra/03-complex-and-shapes.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
16123c3cb770968e1ec35e5b94ccee6909b8295e
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

// Elements are ordinary Protos Numbers, so exact Fractions and Complex values
// keep their usual arithmetic. Shapes must match exactly.

LA: import("std:math/linear_algebra")
Vector: LA.Vector
Matrix: LA.Matrix

// Fractions stay exact: 1/2 * 2 + 1/3 * 3 is exactly 2.
exact: Vector(1 / 2, 1 / 3).dot(Vector(2, 3))
print(exact)

// dot is Hermitian: it conjugates the receiver's elements only.
i: Complex(0, 1)
hermitian: Vector(i).dot(Vector(i))                   // conj(i) * i == 1
// matvec and matmul conjugate nothing.
plain: Matrix(1, 1, i).matvec(Vector(i))[0]           // i * i == -1
print(hermitian)
print(plain)

// A shape mismatch signals an Error; nothing is broadcast or padded. The
// guarded block contains only the mismatched add, so an Error here is that
// shape rejection; if add unexpectedly succeeds, the block answers
// "accepted" and the final check below fails the program.
mismatch: Error.handle(
    () => {
        Vector(1, 2).add(Vector(1))
        "accepted"
    },
    (error) => {
        "rejected"
    }
)
print(mismatch)

// An empty contraction is the exact Integer 0, not 0.0.
empty: Vector().dot(Vector())
print(empty)

verified: (exact === 2) &&
    (hermitian === 1) &&
    (plain === -1) &&
    (mismatch == "rejected") &&
    (empty === 0)
// A wrong result must fail the program, not print false.
if(!verified) {
    Error().signal()
}
print(verified)