-
Notifications
You must be signed in to change notification settings - Fork 1
/
vector.ts
1009 lines (955 loc) · 38.1 KB
/
vector.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Token, Evaluable, Constant as _Constant, Variable as _Variable, Expression as _Expression, Operator, isConstant, isVariable, Numerical } from "./core/definitions";
import { BinaryOperator, isBinaryOperator } from "./core/operators/binary";
import { UnaryOperator, isUnaryOperator } from "./core/operators/unary";
import { ExpressionBuilder } from "./core/expression";
import { Scalar } from "./scalar";
import { InvalidIndex, Overwrite } from "./core/errors";
import { MathContext } from "./core/math/context";
import { mathenv } from "./core/env";
import { BigNum } from "./core/math/bignum";
import { hyper_cross } from "./core/math/numerical";
import { trimZeroes } from "./core/math/parsers";
/**
* The double underscore.
*
* Represents any unknown value. When passed in along with other known values
* this gets interpreted as an unknown or a {@link Variable}.
* @see {@link Vector.variable} for a use case example.
*/
export const __ = undefined;
/**
* Base class to work with vector quantities. Vectors can be represented as a
* list of numbers, the vector components. The current implementation of this
* class work only with Cartesian vector systems and therefore, Cartesian coordinates.
* Any particular vector object has a pre-assigned value for dimension. The
* dimensionality of vectors which are results of vector operations are
* calculated depending on the dimension of the vectors being operated upon.
* @abstract
*/
export abstract class Vector extends Numerical implements Token, Evaluable {
readonly abstract type: "constant" | "variable" | "expression";
readonly quantity = "vector";
/**
* Returns the components of `this` vector. The index values start
* from `1` instead of the commonly used starting index `0`.
* @param i The index of the desired component.
* @return The {@link Scalar} element at given index.
*/
readonly abstract X: (i: number) => Scalar;
/**
* The number of components `this` has.
*/
readonly abstract dimension: number;
/**
* Evaluates and returns the negated value of a vector constant. A
* negative vector \\( - \overrightarrow{A} \\) is defined such that
*
* \\[ \overrightarrow{A} + \left( - \overrightarrow{A} \right) = \overrightarrow{0} \\].
*
* Component wise, if \\( \overrightarrow{A} = a_i \hat{e_i} \\), it can
* be expressed as
*
* \\[ - \overrightarrow{A} = -a_i \hat{e_i} \\].
*/
readonly abstract neg: Vector;
/**
* Adds two {@link Vector}s together. If `this` and `that` are both constants
* then vectorially adds the two and returns a new {@link Vector.Constant} object
* otherwise creates an {@link Expression} out of them and returns the same.
* @param that The scalar to add `this` with.
* @return The result of algebraic addition.
*/
public abstract add(that: Vector): Vector;
/**
* Subtracts `that` from `this`. If `this` and `that` are both constants
* then vectorially subtracts one from the other and returns a new
* {@link Vector.Constant} object otherwise creates an {@link Expression} out of them
* and returns the same.
* @param that The scalar to subtract from `this`.
* @return The result of algebraic subtraction.
*/
public abstract sub(that: Vector): Vector;
/**
* Evaluates the scalar product of `this` and `that`. If both are constants
* then numerically computes the product and returns a {@link Scalar.Constant} object
* otherwise creates an {@link Expression} out of them and returns the same.
* @param that The scalar to subtract from `this`.
* @return The inner product of `this` and `that`.
*/
public abstract dot(that: Vector): Scalar;
/**
* Evaluates the vector product of `this` and `that`. If both are constants
* then numerically computes the product and returns a {@link Vector.Constant} object
* otherwise creates an {@link Expression} out of them and returns the same.
* @param that The scalar to subtract from `this`.
* @return The vector product of `this` and `that`.
*/
public abstract cross(that: Vector): Vector;
/**
* Scales, or multiplies the "size" (magnitude) of, `this` vector by given
* amount. If `this` and `k` are both constants then numerically calculates
* the scaled vector otherwise creates an {@link Expression} out of them and
* returns the same.
* @param k The scale factor.
* @return The scaled vector.
*/
public abstract scale(k: Scalar): Vector;
/**
* Computes the magnitude of a constant vector numerically.
* @param A The {@link Vector} whose magnitude is to be calculated.
* @return The {@link Scalar} magnitude of the given {@link Vector}.
*/
public static mag(A: Vector.Constant): Scalar.Constant;
/**
* Computes the magnitude of a given vector. If `A` vector is a constant
* vector then numerically calculates the magnitude otherwise creates a
* scalar {@link Expression} and returns the same.
* @param A The {@link Vector} whose magnitude is to be calculated.
* @return The {@link Scalar} magnitude of the given {@link Vector}.
*/
public static mag(A: Vector): Scalar.Expression;
public static mag(A: Vector) {
if(A instanceof Vector.Constant) {
let m = BigNum.real(0);
for(let i = 1; i <= A.value.length; i++)
m = m.add(A.X(i).value.mul(A.X(i).value));
return Scalar.constant(m.pow(BigNum.real("0.5")));
}
return new Scalar.Expression(UnaryOperator.MAG, A);
}
/**
* For a given constant vector `A`, numerically evaluates the unit vector along `A`.
* @param A The {@link Vector.Constant} along which the unit vector is to be calculated.
* @return The unit vector along the given {@link Vector} `A`.
*/
public static unit(A: Vector.Constant): Vector.Constant;
/**
* For a given variable vector `A`, creates an {@link Expression} for the unit vector along `A`.
* @param A The {@link Vector.Constant} along which the unit vector is to be calculated.
* @return The unit vector along the given {@link Vector} `A`.
*/
public static unit(A: Vector): Vector.Expression;
public static unit(A: Vector) {
if(A instanceof Vector.Constant)
return A.scale(Scalar.constant(1).div(Vector.mag(A)));
const m = Vector.mag(A);
return new Vector.Expression(UnaryOperator.UNIT, A, (i: number) => A.X(i).div(m), A.dimension);
}
}
export namespace Vector {
/**
* A mapping from named vector constants to {@link Vector.Constant} objects.
* @ignore
*/
const NAMED_CONSTANTS = new Map<string, Vector.Constant>();
/**
* A mapping from name of vector variables to {@link Vector.Variable} objects.
* @ignore
*/
const VARIABLES = new Map<string, Vector.Variable>();
/**
* Represents constant vectors. That is, all the vector components are
* {@link Scalar.Constant}s. All the components are interpreted as in the
* Cartesian system.
* @extends {@link Vector}
*/
export class Constant extends Vector implements _Constant {
readonly type = "constant";
readonly classRef = Vector.Constant;
readonly value: Scalar.Constant[] = [];
/**
* The name by which `this` is identified. This is optional and defaults
* to the empty string `""`.
*/
readonly name: string;
/**
* Creates a {@link Vector.Constant} object from a list of {@link Scalar.Constant}
* objects. One may optionally pass in a string by which `this` object
* may be identified by.
*
* Using the constructor directly for creating vector objects is
* not recommended.
*
* @see {@link Vector.constant}
* @param value The fixed value `this` should represent.
* @param name The name by which `this` is identified.
*/
constructor(value: Scalar.Constant[], name?: string);
constructor(value: Scalar.Constant[], name = "") {
super();
this.name = name;
for(const x of value)
this.value.push(x);
}
/**
* Returns the components of `this` vector. The index values start
* from `1` instead of the commonly used starting index `0`.
* @param i The index of the desired component.
* @return The {@link Scalar} element at given index.
*/
public get X() {
const value = this.value;
return function(i: number) {
if(i <= 0)
throw new InvalidIndex(i, 0);
return (i <= value.length)?value[i - 1]: Scalar.constant(0);
};
}
public get dimension() {
return this.value.length;
}
/**
* Checks for equality of two vector constants. The equality check
* for floating point numbers becomes problematic in the decimal system.
* The binary representation is finite and therefore even if two values
* are in fact equal they may not return true by using the `==` or `===`
* equality. To tackle this problem we use a tolerance value, if the
* difference of the two numerical values is less than that tolerance
* value then we can assume the values to be practically equal. Smaller
* tolerance values will result in more accurate checks.
* This function allows a default tolerance of `1e-14` for floating point numbers.
* @param that The value to check equality with.
*/
public equals(that: Vector.Constant): boolean;
/**
* Checks for equality of two vector constants. The equality check
* for floating point numbers becomes problematic in the decimal system.
* The binary representation is finite and therefore even if two values
* are in fact equal they may not return true by using the `==` or `===`
* equality. To tackle this problem we use a tolerance value, if the
* difference of the two numerical values is less than that tolerance
* value then we can assume the values to be practically equal. Smaller
* tolerance values will result in more accurate checks.
* @param that The value to check equality with.
* @param tolerance The tolerance permitted for floating point numbers.
*/
public equals(that: Vector.Constant, context: MathContext): boolean;
public equals(that: Vector.Constant, context=mathenv.mode) {
const m = Math.max(this.value.length, that.value.length);
for(let i = 1; i <= m; i++)
if(!this.X(i).value.equals(that.X(i).value, context))
return false;
return true;
}
/**
* Evaluates and returns the negated value of a vector constant. A
* negative vector \\( - \overrightarrow{A} \\) is defined such that
*
* \\[ \overrightarrow{A} + \left( - \overrightarrow{A} \right) = \overrightarrow{0} \\].
*
* Component wise, if \\( \overrightarrow{A} = a_i \hat{e_i} \\), it can
* be expressed as
*
* \\[ - \overrightarrow{A} = -a_i \hat{e_i} \\].
*/
public get neg() {
return Vector.constant(this.value.map(x => x.neg));
}
/**
* Adds two {@link Vector.Constant} objects numerically.
* @param that The {@link Vector.Constant} to add to `this`.
* @return The vector sum of `this` and `that`.
*/
public add(that: Vector.Constant): Vector.Constant;
/**
* Creates and returns a {@link Vector.Expression} for the addition of
* two {@link Vector} objects. The {@link type} of `this` does not matter because
* adding a variable vector to another vector always results in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for sum of `this` and `that`.
*/
public add(that: Vector.Variable | Vector.Expression): Vector.Expression;
public add(that: Vector) {
if(that instanceof Vector.Constant) {
const m = Math.max(this.value.length, that.value.length);
const vec: Scalar.Constant[] = [];
for(let i = 1; i <= m; i++)
vec.push(this.X(i).add(that.X(i)));
return Vector.constant(vec);
}
return new Vector.Expression(BinaryOperator.ADD, this, that, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return (<Scalar>this.X(i)).add(that.X(i));
}, Math.max(this.dimension, that.dimension));
}
/**
* Subtracts one {@link Vector.Constant} object from another numerically.
* @param that The {@link Vector.Constant} to subtract from `this`.
* @return The vector difference of `this` from `that`.
*/
public sub(that: Vector.Constant): Vector.Constant;
/**
* Creates and returns a {@link Vector.Expression} for the subtraction of
* two {@link Vector} objects. The {@link type} of `this` does not matter because
* subtracting a variable vector from another vector always results in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for subtracting `that` from `this`.
*/
public sub(that: Vector.Variable | Vector.Expression): Vector.Expression;
public sub(that: Vector) {
if(that instanceof Vector.Constant) {
const m = Math.max(this.value.length, that.value.length);
const vec: Scalar.Constant[] = [];
for(let i = 1; i <= m; i++)
vec.push(this.X(i).sub(that.X(i)));
return Vector.constant(vec);
}
return new Vector.Expression(BinaryOperator.SUB, this, that, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return (<Scalar>this.X(i)).sub(that.X(i));
}, Math.max(this.dimension, that.dimension));
}
/**
* Calculates the scalar product of two {@link Vector.Constant} objects
* numerically.
* @param that The {@link Vector.Constant} to compute scalar product with `this`.
* @return The inner product of `this` and `that`.
*/
public dot(that: Vector.Constant): Scalar.Constant;
/**
* Creates and returns a {@link Vector.Expression} for the dot product of
* two {@link Vector} objects. The {@link type} of `this` does not matter because
* dot multiplying a variable vector with another vector always results
* in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for inner product of `this` and `that`.
*/
public dot(that: Vector.Variable | Vector.Expression): Scalar.Expression;
public dot(that: Vector) {
if(that instanceof Vector.Constant) {
let parallel = BigNum.real(0);
const m = Math.max(this.value.length, that.value.length);
for(let i = 1; i <= m; i++)
parallel = parallel.add(this.X(i).value.mul(that.X(i).value));
return Scalar.constant(parallel);
}
return new Scalar.Expression(BinaryOperator.DOT, this, that);
}
/**
* Calculates the vector product of two {@link Vector.Constant} objects numerically.
* @param that The {@link Vector.Constant} to compute cross product with `this`.
* @return The vector product of `this` and `that`.
*/
public cross(that: Vector.Constant): Vector.Constant;
/**
* Creates and returns a {@link Vector.Expression} for the cross product of
* two {@link Vector} objects. The {@link type} of `this` does not matter because
* cross multiplying a variable vector to another vector always results
* in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for vector product of `this` and `that`.
*/
public cross(that: Vector.Variable | Vector.Expression): Vector.Expression;
public cross(that: Vector) {
if(!(that instanceof Vector.Constant)) {
const N = Math.max(this.dimension, that.dimension);
const properDimension = properVectorDimension(N);
return new Vector.Expression(
BinaryOperator.CROSS,
this, that,
cross_index(this, that), properDimension);
}
const n = Math.max(this.value.length, that.value.length);
const resLength = properVectorDimension(n);
const res = new Array(resLength).fill(0).map(() => Scalar.ZERO);
for(let i = 1; i <= n; i++) {
for(let j = 1; j <= n; j++) {
if(i === j) continue;
const signedBase = hyper_cross(i, j);
const Ai = this.X(i), Bj = that.X(j);
const sign = Math.sign(signedBase);
const e3 = sign * signedBase;
const resComp = Ai.mul(Bj);
res[e3 - 1] = res[e3 - 1].add(sign === 1? resComp: resComp.neg);
}
}
return Vector.constant(res);
}
/**
* Scales `this` {@link Vector.Constant} object numerically.
* @param k The scale factor.
* @return The scaled vector.
*/
public scale(k: Scalar.Constant): Vector.Constant;
/**
* Creates and returns a {@link Vector.Expression} for the scaling of
* `this` {@link Vector} object. The {@link type} of `this` does not matter because
* scaling a variable vector always results in an expression.
* @param k The scale factor.
* @return Expression for scaling `this`.
*/
public scale(k: Scalar.Variable | Scalar.Expression): Vector.Expression;
public scale(k: Scalar) {
if(k instanceof Scalar.Constant)
return Vector.constant(this.value.map(x => k.mul(x)));
return new Vector.Expression(BinaryOperator.SCALE, this, k, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return (<Scalar>this.X(i)).mul(k);
}, this.dimension);
}
}
/**
* Represents vector variables. That is, all the vector components are
* either {@link Scalar.Constant}s or {@link Scalar.Variable}s. All the
* components are interpreted as in the Cartesian system.
* @extends {@link Vector}
*/
export class Variable extends Vector implements _Variable {
readonly type = "variable";
readonly classRef = Vector.Variable;
readonly name: string;
readonly dimension: number;
readonly value: (Scalar.Variable | Scalar.Constant)[];
/**
* Creates a {@link Vector.Variable} object.
*
* Using the constructor directly for creating vector objects is
* not recommended.
*
* @see {@link Vector.variable}
* @param name The name with which the {@link Vector.Variable} is going to be identified.
*/
constructor(name: string, dimension?: number);
/**
* Creates a {@link Vector.Variable} object from an array. The array may
* contain known {@link Scalar.Constants} and, for the components yet unknown,
* {@link Scalar.Variable}. This allows for creation of vectors whose few
* components are known before hand and the rest are not.
*
* Using the constructor directly for creating vector objects is
* not recommended.
*
* @see {@link Vector.variable}
* @param name The name with which the {@link Vector.Variable} is going to be identified.
* @param value The array containing the values with which to initialise the vector variable object.
*/
constructor(name: string, value: (Scalar.Variable | Scalar.Constant)[]);
constructor(a: string, b: undefined | number | (Scalar.Variable | Scalar.Constant)[]) {
super();
this.name = a;
if(b === undefined) {
this.value = [];
this.dimension = 3;
} else if(typeof b === "number") {
this.value = [];
this.dimension = b;
} else {
this.value = b;
this.dimension = this.value.length;
}
}
/**
* Returns the components of `this` vector. The index values start
* from `1` instead of the commonly used starting index `0`.
* @param i The index of the desired component.
* @return The {@link Scalar} element at given index.
*/
public get X() {
return (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
if(this.value.length === 0)
return Scalar.variable(this.name + "_" + i);
return (i <= this.value.length)? this.value[i - 1]: Scalar.constant(0);
};
}
/**
* Evaluates and returns the negated value of a vector constant. A
* negative vector \\( - \overrightarrow{A} \\) is defined such that
*
* \\[ \overrightarrow{A} + \left( - \overrightarrow{A} \right) = \overrightarrow{0} \\].
*
* Component wise, if \\( \overrightarrow{A} = a_i \hat{e_i} \\), it can
* be expressed as
*
* \\[ - \overrightarrow{A} = -a_i \hat{e_i} \\].
*/
public get neg() {
return new Vector.Expression(UnaryOperator.NEG, this, i => this.X(i).neg, this.dimension);
}
/**
* Creates and returns a {@link Vector.Expression} for the addition of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* adding a variable vector to another vector always results in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for sum of `this` and `that`.
*/
public add(that: Vector) {
return new Vector.Expression(BinaryOperator.ADD, this, that, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return (<Scalar>this.X(i)).add(that.X(i));
}, Math.max(this.dimension, that.dimension));
}
/**
* Creates and returns a {@link Vector.Expression} for the subtraction of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* subtracting a variable vector from another vector always results in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for subtracting `that` from `this`.
*/
public sub(that: Vector) {
return new Vector.Expression(BinaryOperator.SUB, this, that, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return (<Scalar>this.X(i)).sub(that.X(i));
}, Math.max(this.dimension, that.dimension));
}
/**
* Creates and returns a {@link Vector.Expression} for the dot product of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* dot multiplying a variable vector with another vector always results
* in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for inner product of `this` and `that`.
*/
public dot(that: Vector) {
return new Scalar.Expression(BinaryOperator.DOT, this, that);
}
/**
* Creates and returns a {@link Vector.Expression} for the cross product of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* cross multiplying a variable vector to another vector always results
* in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for vector product of `this` and `that`.
*/
public cross(that: Vector) {
const N = Math.max(this.dimension, that.dimension);
const properDimension = properVectorDimension(N);
return new Vector.Expression(
BinaryOperator.CROSS,
this, that,
cross_index(this, that), properDimension);
}
/**
* Creates and returns a {@link Vector.Expression} for the scaling of
* `this` {@link Vector} object. The {@link type} of `that` does not matter because
* scaling a variable vector always results in an expression.
* @param k The scale factor.
* @return Expression for scaling `this`.
*/
public scale(k: Scalar) {
return new Vector.Expression(BinaryOperator.SCALE, this, k, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return (<Scalar>this.X(i)).mul(k);
}, this.dimension);
}
}
/**
* Represents vector expressions. That is, all the vector components are
* either {@link Scalar.Constant}s or {@link Scalar.Variable}s or
* {@link Scalar.Variable}s or {@link Scalar.Expression}s. All the components
* are interpreted as in the Cartesian system.
* @extends {@link Vector}
*/
export class Expression extends Vector implements _Expression {
readonly type = "expression";
readonly classRef = Vector.Expression;
readonly arg_list: Set<_Variable>;
readonly rest: any[];
readonly dimension: number;
readonly op: Operator;
readonly operands: Evaluable[] = [];
/**
* Returns the components of `this` vector. The index values start
* from `1` instead of the commonly used starting index `0`.
* @param i The index of the desired component.
* @return The {@link Scalar} element at given index.
*/
readonly X: (i: number) => Scalar;
/**
* Creates a vector expression for a binary operator with left and right
* hand side arguments.
* @param op The root binary operator.
* @param lhs The left hand side argument for the root operator.
* @param rhs The right hand side argument for the root operator.
* @param X The accessor function which defines what the `i`th element should be.
*/
constructor(op: BinaryOperator, lhs: Evaluable, rhs: Evaluable, X: (i: number) => Scalar, dimension: number, ...args: any[]);
/**
* Creates a vector expression for a binary operator with left and right
* hand side arguments.
* @param op The root unary operator.
* @param arg The argument for the root operator.
* @param X The accessor function which defines what the `i`th element should be.
*/
constructor(op: UnaryOperator, arg: Evaluable, X: (i: number) => Scalar, dimension: number, ...args: any[]);
constructor(op: Operator, ...args: any[]) {
super();
this.op = op;
let a, b = undefined;
if(isBinaryOperator(op)) {
[a, b] = args.slice(0, 2);
this.operands.push(a, b);
this.X = args[2];
this.dimension = args[3];
this.rest = args.slice(4);
} else if(isUnaryOperator(op)) {
a = args[0];
this.operands.push(a);
this.X = args[1];
this.dimension = args[2];
this.rest = args.slice(2);
} else throw new Error("Illegal argument.");
this.arg_list = ExpressionBuilder.createArgList(a, b);
}
/**
* The left hand side operand for `this.op`.
* @throws If `this.op` is a `UnaryOperator`.
*/
public get lhs() {
if(isBinaryOperator(this.op))
return this.operands[0];
throw new Error("Unary operators have no left hand argument.");
}
/**
* The right hand side operand for `this.op`.
* @throws If `this.op` is a `UnaryOperator`.
*/
public get rhs() {
if(isBinaryOperator(this.op))
return this.operands[1];
throw new Error("Unary operators have no right hand argument.");
}
/**
* The argument for `this.op`.
* @throws If `this.op` is a `BinaryOperator`.
*/
public get arg() {
if(isUnaryOperator(this.op))
return this.operands[0];
throw new Error("Binary operators have two arguments.");
}
/**
* Evaluates and returns the negated value of a vector constant. A
* negative vector \\( - \overrightarrow{A} \\) is defined such that
*
* \\[ \overrightarrow{A} + \left( - \overrightarrow{A} \right) = \overrightarrow{0} \\].
*
* Component wise, if \\( \overrightarrow{A} = a_i \hat{e_i} \\), it can
* be expressed as
*
* \\[ - \overrightarrow{A} = -a_i \hat{e_i} \\].
*/
public get neg() {
return new Vector.Expression(UnaryOperator.NEG, this, i => this.X(i).neg, this.dimension);
}
/**
* Creates and returns a {@link Vector.Expression} for the addition of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* adding an unknown vector/vector expression to another vector always
* results in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for sum of `this` and `that`.
*/
public add(that: Vector) {
return new Vector.Expression(BinaryOperator.ADD, this, that, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return this.X(i).add(that.X(i));
}, Math.max(this.dimension, that.dimension));
}
/**
* Creates and returns a {@link Vector.Expression} for the subtraction of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* subtracting an unknown vector/vector expression from another vector
* always results in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for subtracting `that` from `this`.
*/
public sub(that: Vector) {
return new Vector.Expression(BinaryOperator.SUB, this, that, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return this.X(i).sub(that.X(i));
}, Math.max(this.dimension, that.dimension));
}
/**
* Creates and returns a {@link Vector.Expression} for the dot product of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* dot multiplying an unknown vector/vector expression with another vector
* always results
* in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for inner product of `this` and `that`.
*/
public dot(that: Vector) {
return new Scalar.Expression(BinaryOperator.DOT, this, that);
}
/**
* Creates and returns a {@link Vector.Expression} for the cross product of
* two {@link Vector} objects. The {@link type} of `that` does not matter because
* cross multiplying an unknown vector/vector expression to another vector
* always results
* in an expression.
* @param that The {@link Vector} to add to `this`.
* @return Expression for vector product of `this` and `that`.
*/
public cross(that: Vector) {
const N = Math.max(this.dimension, that.dimension);
const properDimension = properVectorDimension(N);
return new Vector.Expression(
BinaryOperator.CROSS,
this, that,
cross_index(this, that), properDimension);
}
/**
* Creates and returns a {@link Vector.Expression} for the scaling of
* `this` {@link Vector} object. The {@link type} of `that` does not matter because
* scaling an unknown vector/vector expression always results in an expression.
* @param k The scale factor.
* @return Expression for scaling `this`.
*/
public scale(k: Scalar) {
return new Vector.Expression(BinaryOperator.SCALE, this, k, (i: number) => {
if(i <= 0)
throw new InvalidIndex(i, 0);
return this.X(i).mul(k);
}, this.dimension);
}
/**
* Checks whether `this` {@link Vector.Expression} depends on a given
* {@link Variable}.
* @param v The {@link Variable} to check against.
*/
public isFunctionOf(v: _Variable) {
return this.arg_list.has(v);
}
/**
* Evaluates this {@link Vector.Expression} at the given values for the
* {@link Variable} objects `this` depends on. In case `this` is not a
* function of any of the variables in the mapping then `this` is returned
* as is.
* @param values A map from the {@link Variable} quantities to {@link Constant} quantities.
* @return The result after evaluating `this` at the given values.
*/
public at(values: Map<_Variable, _Constant>) {
const res = ExpressionBuilder.evaluateAt(this, values);
if(isConstant(res))
return <Vector.Constant>res;
if(isVariable(res))
return <Vector.Variable>res;
return <Vector.Expression>res;
}
}
/**
* Creates a new {@link Vector.Constant} object from a list of numbers
* if it has not been created before.
* Otherwise just returns the previously created object.
*
* This is the recommended way of creating {@link Vector.Constant} objects instead of
* using the constructor.
* @param value The fixed value the {@link Vector.Constant} is supposed to represent.
*/
export function constant(value: number[]): Vector.Constant;
/**
* Defines a named {@link Vector.Constant} object from a list of numbers
* if it has not been created before.
* Otherwise just returns the previously created object.
*
* This is the recommended way of creating named {@link Vector.Constant} objects instead of
* using the constructor.
* @param value The fixed value the {@link Vector.Constant} is supposed to represent.
* @param name The string with which `this` object is identified.
* @throws Throws an error if a {@link Vector.Constant} with the same name has been defined previously.
*/
export function constant(value: number[], name: string): Vector.Constant;
/**
* Creates a new {@link Vector.Constant} object from a list of {@link Scalar.Constant} objects
* if it has not been created before.
* Otherwise just returns the previously created object.
*
* This is the recommended way of creating {@link Vector.Constant} objects instead of
* using the constructor.
* @param value The fixed value the {@link Vector.Constant} is supposed to represent.
*/
export function constant(value: Scalar.Constant[]): Vector.Constant;
/**
* Defines a named {@link Vector.Constant} object from a list of {@link Scalar.Constant} objects
* if it has not been created before.
* Otherwise just returns the previously created object.
*
* This is the recommended way of creating named {@link Vector.Constant} objects instead of
* using the constructor.
* @param value The fixed value the {@link Vector.Constant} is supposed to represent.
* @param name The string with which `this` object is identified.
*
* @throws Throws an error if a {@link Vector.Constant} with the same name has been defined previously.
*/
export function constant(value: Scalar.Constant[], name: string): Vector.Constant;
/**
* Returns a previously declared named {@link Vector.Constant} object.
* @param name The name of the named {@link Vector.Constant} object to be retrieved.
*/
export function constant(name: string): Vector.Constant;
export function constant(a: number[] | Scalar.Constant[] | string, b?: string) {
if(typeof a === "string") {
const value = NAMED_CONSTANTS.get(a);
if(value === undefined) throw new Error("No such constant defined.");
return value;
}
let scalars: Scalar.Constant[];
let name = "";
if(b !== undefined) {
if(NAMED_CONSTANTS.get(b) !== undefined)
throw new Overwrite(b);
name = b;
}
if(typeof a[0] === "number") scalars = constantFromNumbers(<Array<number>>a);
else scalars = constantFromScalars(<Array<Scalar.Constant>>a);
const value = name === ""? new Vector.Constant(scalars): new Vector.Constant(scalars, name);
if(name !== "") NAMED_CONSTANTS.set(name, value);
return value;
}
/**
* Creates a new {@link Vector.Variable} object if it has not been created before.
* Otherwise just returns the previously created object.
*
* This is the recommended way of creating {@link Vector.Variable} objects instead of
* using the constructor.
* @param name The string with which `this` object will be identified.
*/
export function variable(name: string): Vector.Variable;
/**
* Creates a new {@link Vector.Variable} object if it has not been created before.
* Otherwise just returns the previously created object.
*
* This is the recommended way of creating {@link Vector.Variable} objects instead of
* using the constructor.
* @param name The string with which `this` object will be identified.
*/
export function variable(name: string, dimension: number): Vector.Variable;
/**
* Creates a {@link Vector.Variable} object from an array. The array may
* contain known scalar constants and, for the components yet unknown,
* [\_\_](../globals.html#__). Passing ``__`` as an element of the `value` array automatically
* gets interpreted as having a variable at that index. This allows for
* creation of vectors whose few components are known before hand and
* the rest are not. For example,
* ```javascript
* const A = Vector.variable("A", [1, __, 4, __, 2]);
* console.log(A);
* ```
* This line of code will create a vector whose 2nd and 4th components are
* {@link Scalar.Variable} objects and the remaining will be {@link Scalar.Constant}
* objects.
*
* This is the recommended way of creating {@link Vector.Variable} objects instead of
* using the constructor.
* @param name The name with which the {@link Vector.Variable} is going to be identified.
* @param value The array containing the values with which to initialise the vector variable object.
*/
export function variable(name: string, value: (Scalar.Constant | undefined | number)[]): Vector.Variable;
export function variable(name: string, b?: number | (Scalar.Constant | undefined | number)[]) {
let v = VARIABLES.get(name);
if(v !== undefined)
return v;
if(b === undefined)
v = new Vector.Variable(name);
else if(typeof b === "number")
v = new Vector.Variable(name, b);
else {
const arr: (Scalar.Constant | Scalar.Variable)[] = [];
let i = b.length - 1;
for(; i >= 0; i--)
if(b[i] !== Scalar.constant(0) || b[i] !== 0)
break;
for(let j = 0; j <= i; j++) {
const x = b[j];
if(x === undefined) arr.push(Scalar.variable(name + "_" + (j+1)));
else if(x instanceof Scalar.Constant) arr.push(x);
else arr.push(Scalar.constant(x));
}
v = new Vector.Variable(name, arr);
}
VARIABLES.set(name, v);
return v;
}
/**
* Returns a single cartesian vector unit corresponding to a given index.
* The indexing starts from 1. With \\( \hat{e_1} = \hat{i} \\) and so on
* (for \\( i>0 \\)) are the orthogonal cartesian vector units.
* @param i The index.
*/
export function e(i: number) {
if(i <= 0)
throw TypeError("Non-positive indices not allowed for basis.");
const values = new Array(i).fill(0).map(() => Scalar.ZERO);
values[i - 1] = Scalar.constant(1);
return Vector.constant(values);
}
}
/**
* Calculates the minimum dimension for an algebra, closed under cross product
* using The Cayley-Dickson construction, in which the vector exists.
* @param n The number of components in said vector.
* @internal
*/
function properVectorDimension(n: number) {
return n === 2 ? 3 : Math.pow(2, Math.ceil(Math.log2(n - 1)) + 1) - 1;
}
/**
* Returns an indexing function for the components of the cross product of 2
* vectors.
* @param A
* @param B
* @internal
*/
function cross_index(A: Vector, B: Vector) {
const N = Math.max(A.dimension, B.dimension);
return (i: number) => {
if(i <= 0)
throw new Error("Indexing starts from `1`.");
if(i > properVectorDimension(N)) return Scalar.ZERO;
let sum: Scalar = Scalar.ZERO;
for(let j = 1; j <= N; j++)
for(let k = 1; k <= N; k++) {
if(j === k) continue;
const signedIndex = hyper_cross(j, k);
if(Math.abs(signedIndex) !== i) continue;
const sign = Math.sign(signedIndex);
const prod = (A.X(j) as Scalar).mul(B.X(k));
sum = sign === 1? sum.add(prod): sum.sub(prod);
}
return sum;
};
}
/**
* Creates an array of {@link Scalar.Constant} as expected by the {@link Vector.Constant}
* constructor. Trims out the trailing zeroes in the array.
* @param value List of constant scalars.
* @internal
*/
function constantFromScalars(value: Scalar.Constant[]) {
return trimZeroes(value, "end", x => x.equals(Scalar.ZERO));
}
/**
* Creates an array of {@link Scalar.Constant} as expected by the {@link Vector.Constant}
* constructor from an array of numbers. Trims out the trailing zeroes in the array.
* @param value List of numbers.
* @internal
*/
function constantFromNumbers(value: number[]): Scalar.Constant[];
/**
* Creates an array of {@link Scalar.Constant} as expected by the {@link Vector.Constant}
* constructor from an array of {@link BigNum}. Trims out the trailing zeroes in the array.
* @param value List of numbers.
* @internal
*/
function constantFromNumbers(value: BigNum[]): Scalar.Constant[];
/**
* Creates an array of {@link Scalar.Constant} as expected by the {@link Vector.Constant}