/
manifold.cljc
1381 lines (1208 loc) · 54.1 KB
/
manifold.cljc
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
;;
;; Copyright © 2017 Colin Smith.
;; This work is based on the Scmutils system of MIT/GNU Scheme:
;; Copyright © 2002 Massachusetts Institute of Technology
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or (at
;; your option) any later version.
;;
;; This software is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this code; if not, see <http://www.gnu.org/licenses/>.
;;
(ns sicmutils.calculus.manifold
"This namespace defines a functional API for:
- differentiable manifolds (both manifold families like [[Rn]] and manifolds
specialized to a concrete dimension)
- manifold points
- coordinate patches
As well as a whole bunch of defined manifolds and coordinate systems for
exploration and fun!"
(:refer-clojure :exclude [uuid])
(:require #?(:cljs [goog.string :refer [format]])
[sicmutils.abstract.function :as af]
[sicmutils.abstract.number :refer [simplify-numerical-expression]]
[sicmutils.calculus.frame :as cf]
[sicmutils.function :as f]
[sicmutils.generic :as g]
[sicmutils.matrix :as matrix]
[sicmutils.mechanics.rotation
:refer [rotate-x-matrix rotate-y-matrix rotate-z-matrix]]
[sicmutils.structure :as s]
[sicmutils.util :as u]
[sicmutils.value :as v]
[taoensso.timbre :as log]))
;; # Disclaimer (from @sritchie)
;;
;; I'm convinced that the scmutils code used to implement the ideas
;; in "Functional Differential Geometry" doesn't have the final say on the best
;; API for differential geometry. I'm going to leave notes throughout the
;; namespace suggesting ways that we might make it better; please take these as
;; challenges and erase the notes as you make improvements!
;;
;; Big TODO items:
;;
;; - `manifold` and `patch` should be protocols, so that manifolds, patches and
;; coordinate systems can report their manifold, and patches and coordinate
;; systems can report their patch. `point` can report its manifold too. Once
;; this change is made, `transfer-point` should use the `manifold` protocol to
;; simplify its implementation. (NOTE that `manifold` now works on coordsys
;; and manifolds, but not yet on patches.)
;;
;; - `patch`, `manifold` and `point` should be defrecords, so that they can
;; implement the protocols above in different ways. We can also implement
;; `dimension` correctly.
;;
;; - `make-patch` should return a patch template; only when you specialize the
;; manifold, or retrieve the patch FROM the specialized manifold with
;; `get-patch` should you actually build the defrecord.
;;
;; - the original codebase assigns a UUID to each manifold specialized off a
;; family. Is this a good idea?
;;
;; - coordinate systems now use a UUID in the protocol; this feels like a code
;; smell. This exists so that coordinate prototypes can live in metadata, and
;; can be changed without affecting equality of coordinate systems. BUT
;; reconsider this design!
;;
;; - coordinate systems have many more functions like `access-chains`,
;; `dual-chains`, `coordinate-basis` and friends. These are missing, and SHOULD
;; go into `coordinate.cljc.` Basically caching functions that can do these
;; transformations for a coordinate system should live in one spot.
;;
;; - it feels like `ICoordinateSystem` WANTS to live in `coordinate.cljc`... but
;; maybe not. I have a sense that we're a bit tangled.
;;
;; - keeping caches inside the points feels wrong. Can we just cache the
;; function itself?
;;
;; - There is a huge amount of repetition between the different coordinate
;; system definitions! There is clearly a smaller protocol that would work,
;; like `point->coords` and `coords->point`, plus maybe the validator.
;; `my-manifold-point?` does all the work for point checking, and we can
;; compose with a coordinate system defrecord to return `manifold`, `patch`
;; and `prototype.`
;;
;; If we do this it'll make it easier to memoize just these smaller functions,
;; and keep an outer `point->coords` that can memoize the internal thing.
;;
;; - TODO: document all of the coordinate systems at the bottom of the page!
;;
;; - TODO: more tests of all of the new accessor functions. See Codecov for what
;; - to do here.
;;
;; Okay, on to the business.
;;
;;
;; ## Manifold Families
;;
;; Manifolds like R1, R2, S1, S2 etc are specialized versions of "manifold
;; templates" like Rn and Sn. We call these "manifold families", while scmutils
;; calls these "manifold types".
;;
;; NOTE: rather than taking a `name-format` string, `make-manifold-family`
;; should take a function of the single dimension argument.
;;
;; NOTE: the original scmutils codebase keeps a `:distinguished-points` list
;; inside the manifold family. This isn't used anywhere in the book or codebase.
;; Keep an eye out and either implement or delete this note.
(defn make-manifold-family
"Generates a manifold family (a template for building manifolds) from the
supplied `name-format`.
Generated manifolds locally resemble Euclidean space (Rn) by default. You can
optionally pass `'Complex` or `'Quaternion` to `over` to customize the field
of the vector space that the manifold locally resembles at each point.
NOTE: only `'Real` does anything as of 3.15.2021."
([name-format]
(make-manifold-family name-format 'Real))
([name-format over]
{:pre [(contains? #{'Real 'Complex 'Quaternion} over)]}
{:over over
:name-format name-format
:patch-templates {}
:type ::manifold-family}))
(defn manifold-family?
"Returns `true` if `m` is a dictionary representing a manifold family, false
otherwise."
[m]
(= (v/kind m) ::manifold-family))
(defn make-manifold
"Returns a concrete manifold generated by specializing the supplied manifold
`family` into a concrete manifold of dimension `n`. `n` must be a positive
integer.
Optionally takes an `embedding-dimension`; this must be >= the value of `n`.
Use this in cases like an n-sphere embedded in a euclidean space of dimension
n+1.
A [manifold](https://en.wikipedia.org/wiki/Manifold) is a topological space
that locally resembles Euclidean space near each point."
([family n]
(make-manifold family n n))
([family n embedding-dimension]
{:pre [(integer? n)
(> n 0)
(>= embedding-dimension n)]}
{:family family
:name (format (:name-format family) n)
:dimension n
:embedding-dimension embedding-dimension
:type ::manifold}))
(defn manifold?
"Returns `true` if `m` is a dictionary representing a manifold, false
otherwise."
[m]
(= (v/kind m) ::manifold))
(defn manifold-type
"The supplied manifold `m` locally resembles some vector space; this function
returns the field over which that vector space was specified."
[manifold]
(get-in manifold [:family :over]))
(defn manifold
"If `m` is a manifold, acts as identity. Else, if given some structure
associated with a manifold (like a coordinate system), returns the associated
manifold."
[m]
(if (manifold? m)
m
(::manifold (meta m))))
;; ## Coordinate Patches
(defn- make-patch
"Returns a bare `patch` with no manifold attached."
[name]
{:name name
:coordinate-systems {}})
(defn attach-patch
"Takes a manifold `family` and attaches a patch template with the supplied
`patch-name`. Returns a new manifold family.
All manifolds generated from the returned family will have this coordinate
patch attached."
[family patch-name]
(let [patch (make-patch patch-name)]
(assoc-in family [:patch-templates patch-name] patch)))
(defn patch-names
"Returns a set of patch names registered in the supplied manifold."
[manifold]
(u/keyset
(get-in manifold [:family :patch-templates])))
(defn get-patch
"Returns the patch named by `patch-name` within the supplied `manifold` if
registered. Throws otherwise.
NOTE that the returned patch will keep a reference to the supplied `manifold`
under a `:manifold` key.
A coordinate patch is a simply-connected open set around a point in the
manifold. A manifold might have many patches. Coordinate systems are defined
on patches; these allow the parameterization of any point on the patch in
terms of a tuple of real numbers (the coordinates)."
[manifold patch-name]
(if-let [gen (get-in manifold [:family :patch-templates patch-name])]
(assoc gen :manifold manifold)
(throw
(ex-info "Unknown patch."
{:patch-name patch-name
:manifold manifold}))))
;; ## Coordinate Systems
;;
;; Coordinate systems are added to coordinate patches. A coordinate system is an
;; invertible map from the space to R^n (or C^n or H^n, depending on the field
;; over which the manifold's defined!)
(defn attach-coordinate-system
"Returns a new manifold family generated by attaching the supplied coordinate
system constructor to `family`, indexed by the supplied patch and coordinate
system names."
[family coordinate-system-name patch-name coordinate-system-ctor]
(let [ks [:patch-templates patch-name
:coordinate-systems coordinate-system-name]
v coordinate-system-ctor]
(assoc-in family ks v)))
(defn coordinate-system-names
"Returns a set of names of all coordinate system constructors registered in the
supplied patch."
[patch]
(u/keyset
(:coordinate-systems patch)))
(defn- get-coordinate-system
"If a coordinate system constructor registered at `system-name` exists in the
supplied `patch`, return it. Else, error.
NOTE for FDG-goers: This is called `coordinate-system` in scmutils."
[patch system-name]
(or (get-in patch [:coordinate-systems system-name])
(throw
(ex-info "Unknown coordinate system."
{:coordinate-system-name system-name
:patch patch}))))
(defn coordinate-system-at
"Returns an [[ICoordinateSystem]] instance specialized to the patch named
`patch-name` on `manifold`."
[manifold coordinate-system-name patch-name]
(let [patch (get-patch manifold patch-name)
ctor (get-coordinate-system patch coordinate-system-name)]
(ctor manifold)))
;; ## Manifold Points
;;
;; This section defines constructors and accessors for
;; non-coordinate-constrained points on some manifold.
(declare uuid)
(defn- make-manifold-point
"Returns a point in `manifold` specified by its Euclidean coordinates `spec`.
Mathematically, a point is defined in the manifold in a coordinate-free way.
To compute with the point, you'll need to get it into a coordinate
representation using `((chart coord-system) point)`.
Optionally, you can pass a `coordinate-system` and a
representation (`coordinate-rep`) of the point in that coordinate system. The
returned point keeps a mutable cache of its coordinate representations, keyed
by `:coordinate-representations`; passing these values will seed the cache."
([spec manifold]
{:type ::manifold-point
:spec spec
:manifold manifold
:coordinate-representations (atom {})})
([spec manifold coordinate-system coordinate-rep]
(let [point (make-manifold-point spec manifold)
reps (:coordinate-representations point)]
(swap! reps assoc (uuid coordinate-system) coordinate-rep)
point)))
(defn manifold-point-representation
"Returns the backing Euclidean space representation of the supplied manifold
point."
[point]
(:spec point))
(defn point->manifold
"Return the manifold upon which this `point` was defined."
[point]
(:manifold point))
(defn manifold-point?
"Returns true if `p` is a manifold point, false otherwise."
[p]
(= (v/kind p) ::manifold-point))
(defn- my-manifold-point?
"Returns true if `point` was created under the aegis of `manifold`, false
otherwise."
[point manifold]
(and (manifold-point? point)
(= (point->manifold point)
manifold)))
(defn get-coordinates
"Returns the representation of `manifold-point` in `coordinate-system`.
If an entry for the given `coordinate-system` is not found, `thunk` is called
to produce the representation. The representation is cached in the point."
[manifold-point coordinate-system thunk]
(let [reps (:coordinate-representations manifold-point)
coordsys-id (uuid coordinate-system)]
(or (@reps coordsys-id)
(let [rep (s/mapr simplify-numerical-expression (thunk))]
(swap! reps assoc coordsys-id rep)
rep))))
;; ## Coordinate System Protocol
(defprotocol ICoordinateSystem
(check-coordinates [this coords]
"Returns true if the supplied coordinates `coords` can be converted into a
point by this [[ICoordinateSystem]], false otherwise.")
(check-point [this point]
"Returns true if the supplied `point` can be converted into coordinates by
this [[ICoordinateSystem]], false otherwise.")
(coords->point [this coords]
"Returns the manifold point on this [[ICoordinateSystem]]'s manifold
corresponding to the supplied `coords`." )
(point->coords [this point]
"Returns a coordinate representation of the supplied manifold point `point`,
as specified by this [[ICoordinateSystem]].")
(uuid [this]
"Returns a unique identifier for this instance of [[ICoordinateSystem]].
(This is an internal implementation detail to allow us to attach coordinate
prototypes and other items as metadata to an [[ICoordinateSystem]] without
affecting equality.)"))
(defn coordinate-system?
"Returns true if `x` implements [[ICoordinateSystem]], false otherwise."
[x]
(satisfies? ICoordinateSystem x))
(defn coordinate-prototype
"Returns the symbolic coordinate prototype associated with `coordsys`. This is
a structure of the correct dimension for this coordinate system, with all
symbolic entries.
Returns nil for non-valid inputs."
[coordsys]
(::coord-prototype (meta coordsys)))
(defn with-coordinate-prototype
"Returns an identical `coordsys` with the new `coordinate-prototype` installed."
[coordsys prototype]
(let [current-proto (coordinate-prototype coordsys)]
(if (= current-proto prototype)
coordsys
(vary-meta coordsys assoc ::coord-prototype prototype))))
(defn chart
"Given an [[ICoordinateSystem]], returns a function from a point on the
coordinate system's manifold to the coordinate representation specified by the
supplied `coordinate-system`."
[coordinate-system]
(if (cf/frame? coordinate-system)
(fn [event]
(cf/event->coords coordinate-system event))
(fn [point]
(point->coords coordinate-system point))))
(defn point
"Given an [[ICoordinateSystem]], returns a function from coordinates in
`coordinate-system`'s repesentation to the matching point on the manifold
associated with `coordinate-system`."
[coordinate-system]
(if (cf/frame? coordinate-system)
(fn [coords]
(cf/coords->event coordinate-system coords))
(fn [coords]
(coords->point coordinate-system coords))))
(defn typical-coords
"Given an [[ICoordinateSystem]], returns a structure that matches
the [[coordinate-prototype]] of `coordinate-system`, with all unique,
gensym-ed entries.
Use [[typical-coords]] if you require a unique symbolic coordinate
representation compatible with `coordinate-system`.
See [[typical-point]] for a coordinate-free version of this function."
[coordinate-system]
(s/mapr gensym (coordinate-prototype coordinate-system)))
(defn typical-point
"Given an [[ICoordinateSystem]], returns a unique, symbolically-represented
point on the manifold associated with `coordinate-system`.
See [[typical-coords]] for a coordinate-based version of this function."
[coordinate-system]
(let [coords (typical-coords coordinate-system)]
(coords->point coordinate-system coords)))
(defn transfer-point
"Returns a function that takes a single manifold `point` embedded in the
manifold `embedded` and transfers the point to the supplied `embedding`
manifold.
The embedding dimension must be the same for both manifolds.
NOTE that `embedded` and `embedding` can be either manifolds, or instances
of [[ICoordinateSystem]]. In the latter case `embedded` and `embedding` will
bind to the manifold associated with the supplied [[ICoordinateSystem]]."
[embedded embedding]
(let [embedded-m (manifold embedded)
embedding-m (manifold embedding)]
(assert (= (:embedding-dimension embedded-m)
(:embedding-dimension embedding-m)))
(fn [point]
(assert (= embedded-m (point->manifold point)))
(make-manifold-point
(manifold-point-representation point)
embedding-m))))
(defn corresponding-velocities
"Takes a coordinate representation `coords` of a manifold point with all
symbolic entries, and returns a structure of the same shape with `v:`
prepended to all symbols.
This structure is appropriate for representing the velocities associated with
each coordinate."
[coords]
(s/mapr (fn [x]
(symbol (str "v:" x)))
coords))
(defn literal-manifold-function
"Given a symbolic name `sym` and an [[ICoordinateSystem]], returns a literal
function that maps coordinate-free manifold points to a scalar output.
Also aliased as [[literal-manifold-function]]."
[sym coordinate-system]
(let [n (:dimension (manifold coordinate-system))
domain (s/up* (repeat n 0))
range 0]
(vary-meta
(f/compose (af/literal-function sym domain range)
(chart coordinate-system))
assoc
:name name
:coordinate-system coordinate-system
:type ::manifold-function)))
(def ^{:doc "Alias for [[literal-manifold-function]], present for scmutils
codebase compatibility."}
literal-scalar-field
literal-manifold-function)
(defn zero-manifold-function
"Manifold function that maps every input manifold `point` to the scalar value 0."
[point]
{:pre [(manifold-point? point)]}
0)
(defn one-manifold-function
"Manifold function that maps every input manifold `point` to the scalar value 1."
[point]
{:pre [(manifold-point? point)]}
1)
(defn constant-manifold-function
"Takes some constant `c` and returns a manifold function that maps every input
manifold `point` to `c.`"
[c]
(fn [point]
{:pre [(manifold-point? point)]}
c))
;; ## Explicit Coordinate Systems
;;
;; This section defines many instances of [[ICoordinateSystem]].
(defn c:generate
"Generates a coordinate structure of the supplied dimension `n`, and
`orientation` using the supplied function `f` for entries. See the very
similar [[sicmutils.structure/generate]] for more details.
NOTE from GJS: this is a kludge introduced only to allow a coordinate of
dimension 1 to automatically unwrap itself."
[n orientation f]
(if (= n 1)
(f 0)
(s/generate n orientation f)))
(defn- default-coordinate-prototype
"Takes a `manifold` and returns a [[sicmutils.structure/up]] instance of the
same dimension as `manifold`, with symbolic entries in each position. "
[manifold]
(let [k (:dimension manifold)]
(c:generate
k ::s/up (fn [i] (symbol (str "x" i))))))
(defn- ->Rectangular
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points in Rn (where `n` is the dimension of `manifold`) to an explicit Rn
structure.
This is as close to an identity coordinate transformation as the system gets!"
([manifold]
(let [proto (default-coordinate-prototype manifold)]
(->Rectangular manifold proto)))
([manifold coordinate-prototype]
(let [id (u/uuid)]
(-> (reify ICoordinateSystem
(check-coordinates [_ coords]
(= (s/dimension coords)
(:dimension manifold)))
(check-point [_ point]
(my-manifold-point? point manifold))
(coords->point [this coords]
(assert (check-coordinates this coords))
(make-manifold-point coords manifold this coords))
(point->coords [this point]
(assert (check-point this point))
(get-coordinates
point this
(fn []
(let [rep (manifold-point-representation point)]
(assert (= (s/dimension rep)
(:embedding-dimension manifold)))
rep))))
(uuid [_] id))
(with-meta {::coord-prototype coordinate-prototype
::manifold manifold})))))
(defn- ->PolarCylindrical
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points in Rn (where `n` is the dimension of `manifold`) to [cylindrical
coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
The first two Rn coordinates in the manifold point become `r` and `theta`, and
all other points are untouched."
([manifold]
(let [proto (default-coordinate-prototype manifold)]
(->PolarCylindrical manifold proto)))
([manifold coordinate-prototype]
(let [id (u/uuid)]
(-> (reify ICoordinateSystem
(check-coordinates [_ coords]
(and (s/up? coords)
(= (s/dimension coords)
(:dimension manifold))
(> (s/dimension coords) 1)
(let [c0 (nth coords 0)]
(or (not (v/number? c0))
(>= c0 0)))))
(check-point [_ point]
(my-manifold-point? point manifold))
(coords->point [this coords]
(assert (check-coordinates this coords))
(let [[r theta] coords]
(-> coords
(assoc 0 (g/* r (g/cos theta)))
(assoc 1 (g/* r (g/sin theta)))
(make-manifold-point manifold this coords))))
(point->coords [this point]
(assert (check-point this point))
(get-coordinates
point this
(fn []
(let [rep (manifold-point-representation point)]
(when-not (and (s/up? rep)
(= (s/dimension rep)
(:embedding-dimension manifold)))
(u/illegal "PolarCylindrical bad point"))
(let [[x y] rep
rsq (g/+ (g/square x)
(g/square y))]
(when (v/zero? rsq)
(u/illegal-state "PolarCylindrical singular"))
(-> rep
(assoc 0 (g/sqrt rsq))
(assoc 1 (g/atan y x))))))))
(uuid [_] id))
(with-meta {::coord-prototype coordinate-prototype
::manifold manifold})))))
(defn- ->SphericalCylindrical
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points in Rn (where `n` is the dimension of `manifold`) to
generalized [spherical
coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
The first three Rn coordinates in the manifold point become `r` and `theta`,
`phi` (radius, colatitude and longitude) and all other points are untouched.
This last bit allows us to use spherical coordinates for manifolds with higher
than three dimensions."
([manifold]
(let [proto (default-coordinate-prototype manifold)]
(->SphericalCylindrical manifold proto)))
([manifold coordinate-prototype]
(let [id (u/uuid)]
(-> (reify ICoordinateSystem
(check-coordinates [_ coords]
(and (s/up? coords)
(= (g/dimension coords)
(:dimension manifold))
(or (not (v/number? coords))
(>= (nth coords 0) 0))))
(check-point [_ point]
(my-manifold-point? point manifold))
(coords->point [this coords]
(assert (check-coordinates this coords))
(let [[r theta phi] coords]
(-> coords
(assoc 0 (g/* r (g/sin theta) (g/cos phi)))
(assoc 1 (g/* r (g/sin theta) (g/sin phi)))
(assoc 2 (g/* r (g/cos theta)))
(make-manifold-point manifold this coords))))
(point->coords [this point]
(assert (check-point this point))
(get-coordinates
point this
(fn []
(let [rep (manifold-point-representation point)]
(when-not (and (s/up? rep)
(= (g/dimension rep)
(:embedding-dimension manifold)))
(u/illegal "SphericalCylindrical bad point"))
(let [[x y z] rep
r (g/sqrt
(g/+ (g/square x)
(g/square y)
(g/square z)))]
(when (v/zero? r)
(u/illegal-state "SphericalCylindrical singular"))
(-> rep
(assoc 0 r)
(assoc 1 (g/acos (g/divide z r)))
(assoc 2 (g/atan y x))))))))
(uuid [_] id))
(with-meta {::coord-prototype coordinate-prototype
::manifold manifold})))))
(defn- ->SpacetimeSpherical
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points in R4 to 'spacetime spherical coordinates'. The first coordinate is
time, and the remaining three coordinates are [spherical spatial
coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
The spatial coordinates are `r` and `theta`, `phi` (radius, colatitude and
longitude)."
([manifold]
(let [proto (default-coordinate-prototype manifold)]
(->SpacetimeSpherical manifold proto)))
([manifold coordinate-prototype]
(let [id (u/uuid)]
(-> (reify ICoordinateSystem
(check-coordinates [_ coords]
(and (s/up? coords)
(= (g/dimension coords) 4)))
(check-point [_ point]
(my-manifold-point? point manifold))
(coords->point [this coords]
(assert (check-coordinates this coords))
(let [[t r theta phi] coords]
(make-manifold-point
(s/up t
(g/* r (g/sin theta) (g/cos phi))
(g/* r (g/sin theta) (g/sin phi))
(g/* r (g/cos theta)))
manifold this coords)))
(point->coords [this point]
(assert (check-point this point))
(get-coordinates
point this
(fn []
(let [rep (manifold-point-representation point)]
(if-not (check-coordinates this rep)
(throw
(ex-info "bad ->SpacetimeSpherical point: "
{:point point
:coordinate-system this}))
(let [[t x y z] rep
r (g/sqrt
(g/+ (g/square x)
(g/square y)
(g/square z)))]
(when (and (v/number? r)
(v/zero? r))
(throw
(ex-info "->SpacetimeSpherical singular: "
{:point point
:coordinate-system this})))
(s/up t
r
(g/acos (g// z r))
(g/atan y x))))))))
(uuid [_] id))
(with-meta {::coord-prototype coordinate-prototype
::manifold manifold})))))
(defn- ->S2-coordinates
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points and colatitude-longitude coordinates for the surface of the sphere
S(2).
Also accepts a unitary `orientation` matrix (2-tensor, technically, a down of
ups, dimension 3 each, since S(2) is embedded in 3-space) used to reposition
the north pole of the spherical coordinate system.
See [n-sphere: Spherical
Coordinates](https://en.wikipedia.org/wiki/N-sphere#Spherical_coordinates) for
notes about the generalized versions of these coordinates, for S(n)."
([orientation]
(let [inverse-orientation (g/invert orientation)]
(fn ctor
([manifold]
(let [proto (default-coordinate-prototype manifold)]
(ctor manifold proto)))
([manifold coordinate-prototype]
(let [id (u/uuid)]
(-> (reify ICoordinateSystem
(check-coordinates [_ coords]
(and (s/up? coords)
(= (g/dimension coords) 2)
(or (not (v/number? coords))
(>= (nth coords 0) 0))))
(check-point [_ point]
(my-manifold-point? point manifold))
(coords->point [this coords]
(assert (check-coordinates this coords))
(let [[colatitude longitude] coords]
(make-manifold-point
(g/* orientation
(s/up (g/* (g/sin colatitude) (g/cos longitude))
(g/* (g/sin colatitude) (g/sin longitude))
(g/cos colatitude)))
manifold this coords)))
(point->coords [this point]
(assert (check-point this point))
(get-coordinates
point this
(fn []
(let [rep (g/* inverse-orientation
(manifold-point-representation point))]
(if (and (s/up? rep)
(= (g/dimension rep)
(:embedding-dimension manifold)))
(let [[x y z] rep]
(s/up (g/acos z) (g/atan y x)))
(u/illegal "S2-coordinates bad point"))))))
(uuid [_] id))
(with-meta {::coord-prototype coordinate-prototype
::manifold manifold}))))))))
(defn- ->Sn-coordinates
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points and spherical on the
unit [n-sphere](https://en.wikipedia.org/wiki/N-sphere#Spherical_coordinates),
ie, S(n). The sphere is embedded in a space of dimension n+1.
Also accepts an `orientation-function` from dimension `(+ n 1)` to a unitary
`orientation` matrix (2-tensor, technically, a down of ups, dimension `n+1`
each, since S(n) is embedded in n+1 dimensional-space). This 2-tensor is used
to reposition the north pole of the spherical coordinate system.
See [n-sphere: Spherical
Coordinates](https://en.wikipedia.org/wiki/N-sphere#Spherical_coordinates) for
notes about these coordinates."
[orientation-function]
(letfn [(rotate-left [l]
(lazy-cat (rest l) [(first l)]))]
(fn ctor
([manifold]
(let [proto (default-coordinate-prototype manifold)]
(ctor manifold proto)))
([manifold coordinate-prototype]
(let [n (:dimension manifold)
orientation-matrix (orientation-function (+ n 1))
orientation-inverse-matrix (g/invert orientation-matrix)
id (u/uuid)]
(-> (reify ICoordinateSystem
(check-coordinates [_ coords]
(let [dim (g/dimension coords)]
(or (and (= n 1)
(= dim 1))
(and (s/up? coords)
(= dim n)
;; check that every coordinate but the final one is
;; positive, if it's a number.
(every? (map-indexed
(fn [i coord]
(or (= (inc i) n)
(not (v/number? coord))
(not (g/negative? coord)))))
coords)))))
(check-point [_ point]
(my-manifold-point? point manifold))
(coords->point [this coords]
(assert (check-coordinates this coords))
(if (= n 1)
(let [pt (s/up (g/cos coords)
(g/sin coords))]
(make-manifold-point
(g/* orientation-matrix pt)
manifold this coords))
(let [sines (map g/sin coords)
cosines (map g/cos coords)
pt (s/up*
(rotate-left
(map (fn [i]
(if (= i n)
(apply g/* sines)
(apply g/* (cons (nth cosines i)
(take i sines)))))
(range (inc n)))))]
(make-manifold-point
(g/* orientation-matrix pt)
manifold this coords))))
(point->coords [this point]
(assert (check-point this point))
(get-coordinates
point this
(fn []
(letfn [(safe-atan [y x]
(when (and (number? y) (number? x)
(v/zero? y) (v/zero? x))
(log/warn "Sn-coordinates singular!"))
(g/atan y x))]
(let [pt (rotate-left
(reverse
(g/* orientation-inverse-matrix
(manifold-point-representation point))))]
(if (= n 1)
(safe-atan (nth pt 1) (nth pt 0))
(loop [r (first pt)
more (rest pt)
ans [(safe-atan (first pt) (second pt))]]
;; There is almost certainly a more efficient way to do
;; this. Study the transformation here, and see how many
;; times we're taking square roots and then squaring again.
;; https://en.wikipedia.org/wiki/N-sphere#Spherical_coordinates
(if-not (next more)
(s/up* ans)
(let [r' (g/sqrt (g/+ (g/square (first more))
(g/square r)))]
(recur r'
(rest more)
(cons (safe-atan r' (second more))
ans)))))))))))
(uuid [_] id))
(with-meta {::coord-prototype coordinate-prototype
::manifold manifold})))))))
(defn- ->Sn-stereographic
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points and a [stereographic
projection]((https://en.wikipedia.org/wiki/N-sphere#Stereographic_projection))
of the
unit [n-sphere](https://en.wikipedia.org/wiki/N-sphere#Stereographic_projection)
S(n) from the final coordinate.
Also accepts an `orientation-function` from dimension `(+ n 1)` to a unitary
`orientation` matrix (2-tensor, technically, a down of ups, dimension `n+1`
each, since S(n) is embedded in n+1 dimensional-space). This 2-tensor is used
to reposition the north pole of the spherical coordinate system.
Notes from scmutils:
The `orientation-function` should return an orthogonal (n+1)-by-(n+1) matrix.
It can be interpreted as moving the pole / plane of projection and possibly
reflecting.
The default pole is (0 0 ... 1).
We fire a ray through m = (m_0 ... m_n)
x(t) = p + t(m - p)
x(0) = p, x(1) = m
x_n(t) = 1-t(1+m_n), 0 = x_n(1/(1+m_n))"
[orientation-function]
(fn ctor
([manifold]
(let [proto (default-coordinate-prototype manifold)]
(ctor manifold proto)))
([manifold coordinate-prototype]
(let [n (:dimension manifold)
orientation-matrix (orientation-function (+ n 1))
orientation-inverse-matrix (g/invert orientation-matrix)
id (u/uuid)]
(-> (reify ICoordinateSystem
(check-coordinates [_ coords]
(or (and (= n 1) (= (g/dimension coords) 1))
(and (s/up? coords) (= (g/dimension coords) n))))
(check-point [_ point]
(my-manifold-point? point manifold))
(coords->point [this coords]
(assert (check-coordinates this coords))
(let [coords' (if (= n 1) (s/up coords) coords)
delta (g/dot-product coords' coords')
xn (g/divide (g/- delta 1)
(g/+ 1 delta))
pt (s/generate (+ n 1)
::s/up
#(if (= % n) xn
(g/divide (g/* 2 (nth coords' %))
(g/+ 1 delta))))]
(make-manifold-point
(g/* orientation-matrix pt)
manifold this coords)))
(point->coords [this point]
(assert (check-point this point))
(get-coordinates
point this
(fn []
(let [pt (g/* orientation-inverse-matrix
(manifold-point-representation point))]
(when (and (v/number? (nth pt n))
(= (nth pt n) 1))
(u/illegal-state "S^n stereographic singular"))
(let [coords (s/generate
n ::s/up
#(g/divide (nth pt %)
(g/- 1 (nth pt n))))]
(if (= n 1)
(first coords)
coords))))))
(uuid [_] id))
(with-meta {::coord-prototype coordinate-prototype
::manifold manifold}))))))
(defn- ->Sn-gnomonic
"Returns an [[ICoordinateSystem]] instance that converts between `manifold`
points and a [Gnomonic
Projection](https://en.wikipedia.org/wiki/Gnomonic_projection) of the [unit
n-sphere](https://en.wikipedia.org/wiki/N-sphere).
We map the nothern hemisphere to the plane by firing a ray from the origin.
The coordinates are given by the intersection with the z = 1 plane.
x(t) = t*m
x_n(t) = t*m_n, 1 = x_n(1/m_n)
`orientation-function` should should return an n+1-by-n+1 orthogonal matrix.