-
Notifications
You must be signed in to change notification settings - Fork 0
/
logic.spad
4314 lines (3810 loc) · 155 KB
/
logic.spad
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
)if false
\documentclass{article}
\usepackage{axiom}
\usepackage{url}
\begin{document}
\title{lattice related mathematical structures}
\author{Martin J Baker}
\maketitle
\begin{abstract}
In this pamphlet are partial order, lattice structures and logic operations based on
them. Logic operations based on lattice structures
Finite lattices may be based on a poset (partial order)
I have put a fuller explanation of this code here:
\url{http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/index.htm}
\end{abstract}
\section{Related Code}
See Package 'UserDefinedPartialOrdering' in setorder.spad
See Domain: 'PartialOrder' in catdef.spad
\section{Introduction}
I am using Steven Vickers book [ref 1] as a reference.
There are a common set of lattice-like structures that occur in various branches
of mathematics such as orders, logic and sets. I would like to represent these
structures in FriCAS.
\begin{table}[]
\label{Poset and Lattice Structures}
\begin{tabular}{lll}
Order & Logic & Set\\
T (top) & true & universe\\
_|_ (bottom) & false & empty\\
greatest lower bound & meet & intersection \\
least upper bound & join & union
\end{tabular}
\end{table}
\section{Poset Code}
What I have done so far seems to be applicable to finite lattices but a lot of my
interest in this subject would be infinite structures. Especially structures
from Topology such as a 'frame' which is a complete lattice with infinite meets.
I am also interested in structures from computer science such as domain theory.
\section{Posets and Lattices}
A Partially Ordered Set (POSET) is a structure with an operator '<=' with a binary
output:
<=(a:%,b:%) -> Boolean
This structure has the following axioms:
\begin{itemize}
\item reflexivity \forall(x): x<=x
\item antisymmetry \forall(x,y): x<=y and y<=x iff x=y
\item transitivity \forall(x,y,z): x<=y and y<=z implies x<=z
\end{itemize}
A lattice is the same structure (every lattice is a poset, not every poset is a
lattice) but it is an algebra (in the universal algebra sense) which has binary
operations:
\begin{itemize}
\item x \vee y
\item x \wedge y
\end{itemize}
Which obey the following axioms:
\begin{table}[]
\label{Lattice Axioms}
\begin{tabular}{lll}
commutativity \forall(x,y): & x \vee y=y \vee x & x \wedge y=y \wedge x\\
associativity \forall(x,y,z): & (x \vee y) \vee z=y \vee (x \vee z) &
(x \wedge y) \wedge z=y \wedge (x \wedge z)\\
idempotence \forall x: & x \vee x=x & x \wedge x=x\\
\end{tabular}
\end{table}
Both of these forms could probably be crunched together in the same FriCAS
category/domain. The approved Axiom/FriCAS style seems to be to include as
many functions as possible in categories/domains rather than separating them
out.
However we need to use these structures differently so my strategy so far is
to have two sorts of domains:
\begin{itemize}
\item posets - here the representation is the whole structure.
\item lattices - here the representation is an element of the structure.
\end{itemize}
So for the poset, the representation would be the whole structure, like this:
\begin{verbatim}
Rep := Record(set:List S,struct:List List Boolean)
\end{verbatim}
The lattice is an algebraicizing of this. The lattice constructor would take the poset
as a parameter. So corresponding poset and lattice categories are shown in the following table:
\begin{table}[]
\label{Poset and Lattice Structures}
\begin{tabular}{ll}
Poset Categories & Lattice Categories\\
Poset & \\
Dcpo & JoinSemilattice\\
CoDcpo & MeetSemilattice\\
BiCPO & Lattice
\end{tabular}
\end{table}
\section{Utilities}
Before the code for posets here are some utilities that they use.
ListPackage code is written by Franz Lehner but these notes are written by
me (Martin Baker) so apologies if if have misinterpreted anything.
ListPackage does topological sort/splitting of lists. Should this code
belong with other list code or should it be defined in terms of graphs?
For an explanation of 'topological sorting' see this wikipedia page:
\url{https://en.wikipedia.org/wiki/Topological_sorting}
Topological sorting applies, in the most general case, to DAGs (Directed Acyclic
Graph). We can define a poset from a DAG, alternative methods are transitive
closure and transitive reduction.
In the context of partial orders they are also closely related to the concept of a
linear extension of a partial order.
)endif
)abbrev package LISTPKG ListPackage
++ Author: Franz Lehner
++ Date Created: 24.04.2008
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ splitting lists
ListPackage(T:BasicType): Exports == Implementation where
NNI==> NonNegativeInteger
Exports ==> with
splitList:(T->Boolean,List T)->Record(yes:List T,no:List T)
++ \spad{splitList(f,x)} splits the list x into a
++ yes part and a no part according to the boolean function f
topologicalSort!: ((T,T) -> Boolean, List T) -> List T
++ \spad{topologicalSort(xx)} returns a rearrangement of the elements
++ which is compatible with the partial order.
++ The argument list xx is destroyed.
topologicalSort: ((T,T) -> Boolean, List T) -> List T
++ \spad{topologicalSort(xx)} returns a rearrangement of the elements
++ which is compatible with the partial order.
topologicalSort: (List(List(Boolean)), List T) -> List T
++ \spad{topologicalSort(xx)} returns a rearrangement of the elements
++ which is compatible with the partial order.
++ (Martin Baker) I added this version because predicate function can
++ be difficult to work with so use table instead.
shiftLeft : List T -> List T
++ \spad{leftShift(l)} rotates the list l to the left and inserts the
++ first element at the end
cartesian:List List T -> List List T
++ \spad{cartesian([S1,S2,...])} returns the set of lists
++ [s1,s2,...] with si in Si
cartesianPower:(List T, NonNegativeInteger) -> List List T
++ \spad{cartesianPower(S,n)} returns the n-th cartesian power of the list S
if T has OrderedSet then
minShift : List T -> List T
++ \spad{minShift(l)} returns the lexicographically minimal cyclic
++ rotation of the list l
Implementation ==> add
splitList(f:T->Boolean, l:List T):Record(yes:List T, no:List T) ==
empty? l => [empty(),empty()]
-- fill the lists to make concat! work
resyes:List T := empty()
resno:List T := empty()
for t in l repeat
if test f(t) then
resyes:=cons(t,resyes)
else
resno:=cons(t,resno)
[reverse! resyes, reverse! resno]
topologicalSort!(f, xx) ==
bucket:List T := empty()
res:List List T := empty()
while not empty? xx repeat
x0:= first xx
xx:=rest xx
bucket:= [x0]
xx1:List T := empty()
for x in xx repeat
if f(x0, x) then
bucket:=cons(x,bucket)
else
xx1:=cons(x,xx1)
res:=cons(reverse bucket, res)
xx:=reverse xx1
concat res
topologicalSort(f, xx) ==
xx1:= copy xx
topologicalSort!(f, xx1)
-- \spad{topologicalSort(xx)} returns a rearrangement of the elements
-- which is compatible with the partial order.
-- (Martin Baker) I added this version because predicate function can
-- be difficult to work with so use table instead.
topologicalSort(adjacency:List(List(Boolean)), xx:List(T)) ==
-- concert to with indexes to work with
xi:List(NNI) := [n for n in 1..(#xx)]
bucket:List NNI := empty()
res:List(List(NNI)) := empty()
while not empty? xi repeat
x0:= first xi
xi:=rest xi
bucket:= [x0]
xx1:List NNI := empty()
for x in xi repeat
if adjacency.x0.x then
bucket:=cons(x,bucket)
else
xx1:=cons(x,xx1)
res:=cons(reverse bucket, res)
xi:=reverse xx1
r:List(NNI) := concat res
-- convert back to values from indexes
[xx.p for p in r]
shiftLeft(xx) ==
empty? xx => return xx
concat (rest xx, first xx)
if T has OrderedSet then
minShift(xx) ==
empty? xx => return xx
empty? rest xx => return xx
res := xx
xx1 := xx
for k in 2..#xx repeat
xx1 := shiftLeft xx1
if xx1 < res then
res := xx1
res
cartesian(SS:List List T):List List T ==
one? (# SS) => return [[s] for s in first SS]
res:List List T := empty()
for x in cartesian rest SS repeat
for s in first SS repeat
res:=cons(cons(s,x),res)
res
cartesianPower(S: List T, n:NonNegativeInteger):List List T ==
empty? S or zero? n => return empty()
one? n => return [[s] for s in S]
res:List List T := empty()
for x in cartesianPower(S, qcoerce(n-1)) repeat
for s in S repeat
res := cons(cons(s,x),res)
res
)if false
\section{domain INCMAT IncidenceAlgebra}
At the moment my (Martin Baker) poset code uses an adjacency matrix for the Rep
of a poset (with entries being boolean values - so an adjacency array).
See FinitePoset below.
The code here implements the incidence algebra of posets.
Franz Lehner originally used the name IncidenceMatrix for this. I changed this
because it tends to be used for matrix where: rows are vertices and
columns are edges as described here:
\url{https://en.wikipedia.org/wiki/Incidence_matrix}
So I changed the name IncidenceMatrix to IncidenceAlgebra.
From \url{http://wiki.axiom-developer.org/SandBoxCategoryOfGraphs2}.
Notes: \axiom{S:Type} does not work because
\verb|position(i,V)$OneDimensionalArray S|
requires \axiom{SetCategory}.
)endif
)abbrev domain INCMAT IncidenceAlgebra
++ Author: Franz Lehner [email protected]
++ Date Created: 30 April 2013
++ Fix History: Martin Baker - changed name from IncidenceMatrix to IncidenceAlgebra
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ A domain for incidence matrices of finite posets.
IncidenceAlgebra(R:Ring, S:SetCategory): Decl == Impl where
IND ==> OneDimensionalArray S
Decl ==> SetCategory with
-- IncidenceAlgebra declarations
--constructor
incidenceAlgebra:(Matrix R, List S) -> %
++ \spad{incidenceAlgebra(A, ss)}
++ constructs an adjacency matrix with with indices ss and Matrix A
incidenceAlgebra:(Matrix R, OneDimensionalArray S) -> %
++ \spad{incidenceAlgebra(A, ss)}
++ constructs an adjacency matrix with with indices ss and Matrix A
--access
indices:% -> OneDimensionalArray S
++ \spad{indices(A)} returns the indices of the incidence matrix A
matrix:% -> Matrix R
++ \spad{matrix(A)} returns the underlying matrix
++ of the incidence matrix A
apply:(%,Integer,Integer)-> R
++ \spad{A(i,j)} returns $A_{i,j}$
apply:(%,S,S)-> R
++ \spad{A(s,t)} returns $A_{i,j}$, where $i$, $j$ are the positions
++ of $s$ and $t$ in the index list.
-- output
coerce:% -> OutputForm
-- manipulations
_*:(Permutation Integer,%)->%
++ \spad{\pi * A} permutes the indices and the matrix according to the
++ permutation \spad{\pi}.
-- _*:(Permutation S,%)->%;
-- arithmetics
"+": (%,%) -> %
++ \spad{x + y} is the sum of the matrices x and y.
++ Error: if the dimensions are incompatible.
"*": (%,%) -> %
++ \spad{x * y} is the product of the matrices x and y.
++ Error: if the dimensions are incompatible.
"*": (R,%) -> %
++ \spad{r*x} is the left scalar multiple of the scalar r and the
++ matrix x.
"*": (%,R) -> %
++ \spad{r*x} is the left scalar multiple of the scalar r and the
++ matrix x.
"^": (%, NonNegativeInteger) -> %
++ \spad{x ^ n} computes a non-negative integral power of the
++ matrix x. Error: if the matrix is not square.
Impl ==> add
Rep := Record(matrix:Matrix R, indices:IND)
Ai,Bi,Ci:Matrix R
r: R
A,B: %
ss: List S
i,j: Integer
u,v: S
-- IncidenceAlgebra implementation
incidenceAlgebra(Ai:Matrix R, ssa:OneDimensionalArray S):% ==
if (nrows Ai ~= #ssa) or (ncols Ai ~= #ssa) then
error "Sizes not compatible"
[Ai, ssa]
incidenceAlgebra(Ai, ss) == incidenceAlgebra(Ai, oneDimensionalArray ss)
-- if (nrows Ai ~= #ss) or (ncols Ai ~= #ss) then
-- error "Sizes not compatible"
-- [Ai,oneDimensionalArray ss]
indices A == A.indices
matrix A == A.matrix
apply(A, i, j) == (A.matrix)(i,j)
apply(A,u,v) ==
i := position(u,indices A)
zero? i => error "First index is not a vertex"
j := position(v,indices A)
zero? j => error "Second index is not a vertex"
(A.matrix)(i,j)
(p:Permutation Integer) * (A) ==
mp:Set Integer:= movedPoints p
n:Integer := # indices A
if (min mp) < 1 or (max mp) > n then
error "Permutation out of range"
-- permute the indices
newindices:OneDimensionalArray S := oneDimensionalArray [ (indices A)(eval(p,i)) for i in 1..n]
-- permutation matrix
indic:List Integer := [eval(p,i) for i in 1..n]
newA:Matrix R:= (matrix A)(indic,indic)
[newA, newindices]
coerce(A):OutputForm ==
bracket commaSeparate [(matrix A)::OutputForm , (indices A)::OutputForm]
_=(A1:%,A2:%):Boolean == (indices A1 = indices A2) and (matrix A1 = matrix A2)
-- Arithmetics
A + B ==
Aind := indices A
Bind := indices B
if Aind ~= Bind then
error "incompatible indices"
Ci := matrix A + matrix B
incidenceAlgebra(Ci, Aind)
A * B ==
Aind := indices A
Bind := indices B
if Aind ~= Bind then
error "incompatible indices"
Ci := matrix A * matrix B
incidenceAlgebra(Ci, Aind)
r * A ==
Aind := indices A
Ci := r*matrix A
incidenceAlgebra(Ci, Aind)
A * r ==
Aind := indices A
Ci := (matrix A) * r
incidenceAlgebra(Ci, Aind)
A^n ==
Aind := indices A
Ci := (matrix A)^n
incidenceAlgebra(Ci, Aind)
)if false
\section{domain FMOEBF FiniteMoebiusFunction}
Code for FiniteMoebiusFunction by Franz Lehner. Notes by Martin Baker are here:
\url{http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/moebius/}
This domain computes Moebius functions of finite subposets
of infinite posets given by lists of elements.
It computes the zeta matrix and stores its inverse.
)endif
)abbrev domain FMOEBF FiniteMoebiusFunction
++ Author: Franz Lehner
++ Date Created: 06.03.2011
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ A domain for Moebius functions of explicit subposets
++ of infinite posets.
FiniteMoebiusFunction(P:Join(PartialOrder, SetCategory)):Exports == Implementation where
R ==> Integer
NNI ==> NonNegativeInteger
MATL ==> Record(matrix:Matrix R, indices:List P)
TRIMATI==> TriangularMatrixOperations(R, Vector R, Vector R, Matrix R)
Exports ==> SetCategory with
moebiusFunction:List P -> %
++ \spad{moebiusFunction(pp)} creates the canonical
++ zeta matrix and inverts it.
moebiusMu:(mf:%, pi:P, si:P) -> R
++ \spad{moebiusMu(mf, pi, si)} evaluates the Moebius function
apply:(mf:%, pi:P, si:P) -> R
++ \spad{mf(pi, si)} evaluates the Moebius function mf at pi and si
members:% -> List P
++ \spad{members(mf)} returns the elements of the subposet
moebiusMatrix:% -> Matrix R
++ \spad{moebiusMatrix(P)} returns the Moebius matrix
Implementation ==> add
Rep:= MATL
rep(x:%):Rep == x :: Rep
per(r:Rep):% == r :: %
members(mf:%):List P == rep(mf).indices
moebiusFunction(xx:List P):% ==
xxo:List P:= removeDuplicates topologicalSort("<=", xx)$(ListPackage P)
zf:Matrix R:= matrix [[(if x <= y then 1 else 0) for y in xxo] _
for x in xxo]
mf:Matrix R:= UpTriBddDenomInv(zf, 1)$TRIMATI
per ([mf, xxo]$Rep)
canonicalZeta:(P, P) -> R
canonicalZeta(pi, si) ==
if pi <= si then
return 1
0
moebiusMu(mf:%, x:P, y:P) ==
mfn:Matrix R:= (rep mf) matrix
kx:=position(x, members mf)
ky:=position(y, members mf)
zero? kx or zero? ky =>
error "not members"
return (mfn)(kx, ky)
apply(mf:%, x:P, y:P) ==
mfn:Matrix R:= (rep mf) matrix
kx:=position(x, members mf)
ky:=position(y, members mf)
zero? kx or zero? ky =>
error "not members"
return (mfn)(kx, ky)
moebiusMatrix(mf:%):Matrix R == rep(mf) matrix
coerce(mf:%):OutputForm == hconcat("Moebius Function"::OutputForm, coerce(members(mf)))
)if false
\section{domain GENMOEBF GeneralizedFiniteMoebiusFunction}
Code for GeneralizedFiniteMoebiusFunction by Franz Lehner. Notes by Martin Baker are here:
\url{http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/moebius/}
A \emph{generalized Moebius function} is the inverse
of an upper triangular matrix on a poset
which is not necessarily the zeta matrix.
It works similar to the domain \axiom{FiniteMoebiusFunction}.
)endif
)abbrev domain GENMOEBF GeneralizedFiniteMoebiusFunction
++ Author: Franz Lehner
++ Date Created: 06.03.2011
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ A domain for generalized Moebius functions of explicit subposets.
GeneralizedFiniteMoebiusFunction(P:Join(PartialOrder, SetCategory), R: Field):Exports == Implementation where
NNI ==> NonNegativeInteger
MATL ==> Record(zmatrix:Matrix R, mmatrix:Matrix R, indices:List P)
TRIMATI==> TriangularMatrixOperations(R, Vector R, Vector R, Matrix R)
Exports ==> with
generalizedMoebiusFunction:(List P, (P, P) -> R) -> %
++ \spad{generalizedMoebiusFunction(pp, zeta)} inverts the given zeta function
canonicalMoebiusFunction:(List P) -> %
++ \spad{canonicalMoebiusFunction(pp)} inverts the canonical zeta function
apply:(mf:%, pi:P, si:P) -> R
++ \spad{mf(pi, si)} evaluates the Moebius function mf at pi and si
members:% -> List P
++ \spad{members(mf)} returns the elements of the subposet
moebiusMatrix:% -> Matrix R
++ \spad{moebiusMatrix()} returns the Moebius matrix
Implementation ==> add
Rep:= MATL
rep(x:%):Rep == x :: Rep
per(r:Rep):% == r :: %
members(mf:%):List P == rep(mf).indices
generalizedMoebiusFunction(xx:List P, z:(P, P) -> R):% ==
xxo:List P:= removeDuplicates topologicalSort("<=", xx)$(ListPackage P)
zf:Matrix R:= matrix [[(if y<=x then z(x, y) else 0) for x in xxo] _
for y in xxo]
mf:Union(Matrix R, "failed"):=inverse zf
mf case "failed" => error "zeta not invertible"
return per ([zf, mf, xxo]$Rep)
canonicalZeta:(P, P) -> R
canonicalZeta(pi, si) ==
if pi <= si then
return 1
0
apply(mf:%, x:P, y:P) ==
mfn:Matrix R:= (rep mf) mmatrix
kx:=position(x, members mf)
ky:=position(y, members mf)
zero? kx or zero? ky =>
error "not members"
return (mfn)(ky, kx)
moebiusMatrix(mf:%):Matrix R == rep(mf) mmatrix
zetaMatrix(mf:%):Matrix R == rep(mf) zmatrix
coerce(mf:%):OutputForm == "m"::OutputForm
)if false
\section{Poset Code}
As already described, the representation in the following categories contains
the whole order and not just one element (unlike PartialOrder in catdef.spad).
)endif
)abbrev category PREORD Preorder
++ Author: Martin Baker
++ Description: implies operation with reflexivity and transitivity
++ for more documentation see:
++ http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/index.htm
++ Related Domains: PartialOrder in catdef.spad
++ Axiom: reflexivity forall(x): x<=x
++ Axiom: transitivity forall(x,y,z): x<=y and y<=z implies x<=z
++ Date Created: Aug 2015
Preorder(S) : Category == Definition where
S : SetCategory
NNI==> NonNegativeInteger
Definition ==> FiniteGraph(S) with
le:(s : %,NNI, NNI) -> Boolean
++ less than or equal
++ I would have liked to have used: "<=" instead of "le"
++ "<=" compiles but when called gives:
++ Internal Error: The function <= with signature hashcode is
++ missing from domain
)abbrev category POSET Poset
++ Author: Martin Baker
++ Description: holds a complete set together with a structure to codify
++ the partial order.
++ for more documentation see:
++ http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/index.htm
++ Date Created: Aug 2015
++ Basic Operations:
++ Related packages: UserDefinedPartialOrdering in setorder.spad
++ Related categories: PartialOrder in catdef.spad
++ Related Domains: DirectedGraph in graph.spad
++ Also See:
++ AMS Classifications:
++ Keywords: poset partial order
++ Examples: power set structure
++ References:
++ Axiom: reflexivity forall(x): x<=x
++ Axiom: antisymmetry forall(x,y): x<=y and y<=x iff x=y
++ Axiom: transitivity forall(x,y,z): x<=y and y<=z implies x<=z
Poset(S) : Category == Definition where
S : SetCategory
PI ==> PositiveInteger
NNI==> NonNegativeInteger
SINT==> SingleInteger
OBJT ==> Record(value : S, posX : NNI, posY : NNI)
ARROW ==> Record(name : String, arrType : NNI, fromOb : NNI, _
toOb : NNI, xOffset : Integer, yOffset : Integer, map : List NNI)
x<<y ==> hconcat(x::OutputForm,y::OutputForm)
Definition ==> Preorder(S) with
finitePoset : (carrier:List S,struct1:List List Boolean) -> %
++ constructor where the set and structure is supplied.
finitePoset : (carrier:List S,pred:((S, S) -> Boolean)) -> %
++ constructor where the set and structure is supplied.
++ The structure is supplied as a predicate function.
getVert : (s : %) -> List S
++ getVert(s) returns a list of all the vertices (or objects)
++ of the graph s.
++ Note: different from getVertices(s) which is inherited from FiniteGraph(S)
getArr : (s : %) -> List List Boolean
++ getArr(s) returns a list of all the arrows (or edges)
++ Note: different from getArrows(s) which is inherited from FiniteGraph(S)
setVert:(s : %,v:List S) -> Void
++ sets the list of all vertices (or objects)
setArr:(s : %,v:List List Boolean) -> Void
++ sets the list of all arrows (or edges)
addObject : (s : %, n : S) -> %
++ addObject!(s, n) adds object with coordinates n to the
++ graph s.
++ This is done in a non-mutable way, that is, the original
++ poset is not changed instead a new one is constructed.
addArrow : (s : %, n1 : NNI, n2 : NNI) -> %
++ addArrow!(s, nm, n1, n2) adds an arrow to the graph s, where:
++ n1 is the index of the start object
++ n2 is the index of the end object
++ This is done in a non-mutable way, that is, the original
++ poset is not changed instead a new one is constructed.
opposite : (s : %) -> %
++ constructs the opposite in the category theory sense of reversing
++ all the arrows
powerSetStructure : (objs : S) -> %
++ powerSetStructure(set) is a constructor for a Poset
++ where each element is a set (implemented as a list)
++ and with a subset structure.
++ requires S to be a list.
implies:(s : %,NNI, NNI) -> Boolean
meetIfCan:(s : %,a:NNI,b:NNI) -> Union(NNI,"failed")
++ returns the meet of 'a' and 'b'
++ In this version of meet nodes are represented as index values.
++ In the general case, not every poset will have a meet in which case
++ "failed" will be returned as an error indication.
joinIfCan:(s : %,a:NNI,b:NNI) -> Union(NNI,"failed")
++ returns the join of 'a' and 'b'
++ In this version of join nodes are represented as index values.
++ In the general case, not every poset will have a join in which case
++ "failed" will be returned as an error indication.
meetIfCan:(s : %,elements:List(NNI)) -> Union(NNI,"failed")
++ returns the meet of a subset of lattice given by list of elements
joinIfCan:(s : %,elements:List(NNI)) -> Union(NNI,"failed")
++ returns the join of a subset of lattice given by list of elements
glb:(s : %,a:List NNI) -> Union(NNI,"failed")
++ 'greatest lower bound' or 'infimum'
++ In this version of glb nodes are represented as index values.
++ Not every subset of a poset will have a glb in which case
++ "failed" will be returned as an error indication.
lub:(s : %,a:List NNI) -> Union(NNI,"failed")
++ 'least upper bound' or 'supremum'
++ In this version of lub nodes are represented as index values.
++ Not every subset of a poset will have a lub in which case
++ "failed" will be returned as an error indication.
upperSet:(s:%) -> %
++ a subset U with the property that, if x is in U and x<=y, then y is in U
lowerSet:(s:%) -> %
++ a subset U with the property that, if x is in U and x>=y, then y is in U
indexToObject:(s : %,index:NNI) -> S
++ returns the object at a given index
objectToIndex:(s : %,obj:S) -> NNI
++ returns the index of a given object
completeReflexivity:(s:%) -> %
++ Reflexivity requires forall(x): x<=x
++ This function enforces this by making sure that every element has
++ arrow to itself. That is, the leading diagonal is true.
completeTransitivity:(s:%) -> %
++ Transitivity requires forall(x,y,z): x<=y and y<=z implies x<=z
++ This function enforces this by making sure that the composition
++ of any two arrows is also an arrow.
isAntisymmetric?:(s:%) -> Boolean
++ Antisymmetric requires forall(x,y): x<=y and y<=x iff x=y
++ Returns true if this is the case for every element.
isChain?:(s:%) -> Boolean
++ is a subset of a partially ordered set such that any two elements
++ in the subset are comparable
isAntiChain?:(s:%) -> Boolean
++ is a subset of a partially ordered set such that any two elements
++ in the subset are incomparable
moebius:(s:%) -> IncidenceAlgebra(Integer,S)
++ moebius incidence matrix for this poset
++ This function is based on code by Franz Lehner.
++ Notes by Martin Baker on the webpage here:
++ \url{http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/moebius/}
zetaMatrix:(s:%) -> IncidenceAlgebra(Integer,S)
++ \spad{zetaMatrix(P)} returns the matrix of the zeta function
++ This function is based on code by Franz Lehner.
++ Notes by Martin Baker on the webpage here:
++ \url{http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/moebius/}
coverMatrix:(s:%) -> IncidenceAlgebra(Integer,S)
++ the covering matrix of a list of elements from a comparison function
++ the list is assumed to be topologically sorted (i.e., w.r. to
++ a linear extension of the comparison function f
++ This function is based on code by Franz Lehner.
++ Notes by Martin Baker on the webpage here:
++ \url{http://www.euclideanspace.com/prog/scratchpad/mycode/discrete/logic/moebius/}
add
-- adds an object to this poset
addObject(s : %, n : S) : % ==
dim : NNI := #(getVert(s)) + 1
obs : List S := concat(getVert(s),n)
arrows : List(List(Boolean)) := nil()$List(List(Boolean))
for a in getArr(s) repeat
width:NNI := #a
padding:Union(NNI,"failed") := subtractIfCan(dim,width)
if padding ~= "failed" then
diff:NNI := padding::NNI
--print(("addObject diff=",string(diff))$String)])
for x in 1..diff repeat
a := concat(a,false)
if empty?(arrows)
then arrows := [a]
else arrows := concat(arrows,a)
emptyRow:List Boolean := [false for x in 1..dim]
arrows := concat(arrows,emptyRow)
finitePoset(obs,arrows)
-- TODO - make this non-mutable
-- adds an arrow to this graph, where:
-- s is the graph where the arrow is to be added
-- n1 is the index of the start object
-- n2 is the index of the end object
addArrow(s : %, n1 : NNI, n2 : NNI) : % ==
a : List Boolean := qelt(getArr(s),n1)
setelt!(a,n2,true)
setelt!(getArr(s),n1,a)
finitePoset(getVert(s),getArr(s))
-- local function to test a single value in the arrow matrix
isArrow?(arr:List(List(Boolean)),a:NNI,b:NNI):Boolean ==
row:NNI := 1
for x in arr repeat
if row=a then
val:Boolean := qelt(x,b)
return val
row=row+1
false
le(s : %,a:NNI,b:NNI):Boolean == isArrow?(getArr(s),a,b)
-- local function to set a single value in the arrow matrix
setArrow!(arr:List(List(Boolean)),a:NNI,b:NNI,c:Boolean):Void ==
row:NNI := 1
for x in arr repeat
if row=a then
setelt!(x,b,c)
return void
row=row+1
void
-- start of FiniteGraph implementation
-- addObject!(s, n) adds object n to the graph s.
-- mutable version of addObject.
addObject!(s : %, n : S):% ==
dim : NNI := #(getVert(s)) + 1
obs : List S := concat(getVert(s),n)
arrows : List(List(Boolean)) := nil()$List(List(Boolean))
for a in getArr(s) repeat
width:NNI := #a
padding:Union(NNI,"failed") := subtractIfCan(dim,width)
if padding ~= "failed" then
diff:NNI := padding::NNI
--print("addObject! diff="::Symbol << string(diff))
for x in 1..diff repeat
a := concat(a,false)
if empty?(arrows)
then arrows := [a]
else arrows := concat(arrows,a)
emptyRow:List Boolean := [false for x in 1..dim]
arrows := concat(arrows,emptyRow)
setVert(s,obs)
setArr(s,arrows)
s
-- addObject!(s, n) adds object with coordinates n to the
-- graph s.
addObject!(s : %, n : OBJT):% ==
ob:S := n.value
addObject!(s,ob)
-- addArrow!(s, nm, n1, n2) adds an arrow to the graph s, where:
-- nm is the name of the arrow
-- n1 is the index of the start object
-- n2 is the index of the end object
addArrow!(s : %, name : String, n1 : NNI, n2 : NNI):% ==
a : List Boolean := qelt(getArr(s),n1)
setelt!(a,n2,true)
setelt!(getArr(s),n1,a)
finitePoset(getVert(s),getArr(s))
-- addArrow!(s, nm, n1, n2, mp) adds an arrow to the graph s, where:
-- nm is the name of the arrow
-- n1 is the index of the start object
-- n2 is the index of the end object
-- mp is a map represented by this arrow
addArrow!(s : %, name : String, n1 : NNI, n2 : NNI, mp : List NNI):% ==
addArrow!(s,name,n1,n2)
-- getVertices(s) returns a list of all the vertices (or objects)
-- of the graph s.
getVertices(s : %):List(OBJT) ==
[[x,0::NNI,0::NNI] for x in getVert(s)]
-- getArrows(s) returns a list of all the arrows (or edges)
getArrows(s : %):List(ARROW) ==
res:List(ARROW) := nil()
dim:NNI := #getArr(s)
for x in 1..dim for row in getArr(s) repeat
for y in 1..dim for val in row repeat
if val then
arr:ARROW := ["x", 0::NNI,x pretend NNI,y pretend NNI,0::Integer,0::Integer,nil()$List(NNI)]
res := concat(res,arr)
res
-- flatten(n) takes a second order graph, we don't really need
-- this here so return an empty poset.
flatten(n : DirectedGraph(%)):% ==
finitePoset([],[nil()$List(Boolean)])
-- initial constructs a graph without vertices or edges
initial():% ==
finitePoset([],nil()$List(List(Boolean)))
-- terminal(a) constructs a graph over a with a single vertex
-- and a single loop
terminal(a : S):% ==
finitePoset([a],[[true]])
-- cycleOpen(objs, arrowName) constructs a graph with vertices
-- (from objs) connected in a cycle but with one gap. The last
-- vertex in the sequence loops back to itself so all vertices
-- have one outgoing arrow.
-- arrowName is a prefix for all arrow names, this will be
-- followed by a number starting at 1 and incremented for each
-- arrow
cycleOpen(objs : List S, arrowName : String):% ==
finitePoset([],[nil()$List(Boolean)])
-- cycleClosed: (objs: List S, arrowName: String) constructs a graph
-- with vertices (from objs) connected in a cycle.
-- arrowName is a prefix for all arrow names, this will be
-- followed by a number starting at 1 and incremented for each
-- arrow
cycleClosed(objs : List S, arrowName : String):% ==
finitePoset([],[nil()$List(Boolean)])
-- unit(objs, arrowName) constructs a graph with vertices
-- (from objs) and arrows from each object to itself.
-- arrowName is a prefix for all arrow names, this will be
-- followed by a number starting at 1 and incremented for each
-- arrow
unit(objs : List(S), arrowName : String):% ==
dim:NNI := #objs
arrs:List(List(Boolean)) := [nil()$List(Boolean)]
for x in 1..dim repeat
row:List Boolean := nil()
for y in 1..dim repeat
val:Boolean := (x=y)
row := concat(row,val)
arrs := concat(arrs,row)
finitePoset(objs,arrs)
-- kgraph(objs, arrowName)
-- constructs a graph with vertices (from objs) and fully
-- connected arrows, that is, each object has an arrow to
-- every other object except itself.
-- arrowName is a prefix for all arrow names, this will be
-- followed by a number starting at 1 and incremented for each
-- arrow
kgraph(objs : List S, arrowName : String):% ==
finitePoset([],[[false]])
-- isDirectSuccessor?(s, a, b) is
-- true if 'b' is a direct successor of 'a'
-- that is, if there is a direct arrow from 'a' to 'b'
isDirectSuccessor?(s : %, a : NNI, b : NNI):Boolean ==
row : List Boolean := qelt(getArr(s),a)
qelt(row,b)
-- isGreaterThan?((s, a, b) is
-- true if we can get from vertex 'a' to 'b' through a
-- sequence of arrows but we can't go in the opposite
-- direction from 'b' to 'a'
isGreaterThan?(s : %, a : NNI, b : NNI):Boolean ==
row : List Boolean := qelt(getArr(s),a)
qelt(row,b)
-- max(s) returns index of the vertex which can be reached
-- from all other vertices. Gives 0 if no such node exists
-- or if it is not unique, if there is a loop for instance.
max(s : %) : NNI ==
arr:List(NNI) := nil()
index:NNI := 1::NNI
for x in getArr(s) repeat
arr := concat(arr,index)
index := index+1
res:Union(NNI,"failed") := meetIfCan(s,arr)
if res = "failed" then return 0::NNI
res::NNI
-- max(s, sub) returns index of the vertex which
-- can be reached from a given subset of the vertices. Gives
-- 0 if no such node exists or if it is not unique, if there
-- is a loop for instance.
max(s : %, sub : List NNI):NNI ==
res:Union(NNI,"failed") := meetIfCan(s,sub)
if res = "failed" then return 0::NNI
res::NNI
-- min(s) returns index of the vertex which can reach to all
-- other vertices. Gives 0 if no such node exists or if it is
-- not unique, if there is a loop for instance.
min(s : %) : NNI ==
arr:List(NNI) := nil()
index:NNI := 1::NNI
for x in getArr(s) repeat
arr := concat(arr,index)
index := index+1
res:Union(NNI,"failed") := joinIfCan(s,arr)
if res = "failed" then return 0::NNI
res::NNI
-- min(s, sub) returns index of the vertex which can reach
-- to a given subset of the vertices. Gives 0 if no such node
-- exists or if it is not unique, if there is a loop for instance.
min(s : %, sub : List NNI):NNI ==
res:Union(NNI,"failed") := joinIfCan(s,sub)
if res = "failed" then return 0::NNI
res::NNI
-- isFixPoint?(s, a) is
-- true if 'a' has an arrow to itself
-- should always be true due to reflexivity law
isFixPoint?(s : %, a : NNI):Boolean ==
true
-- arrowName(s, a, b) retrieves
-- the name of arrow a->b