-
Notifications
You must be signed in to change notification settings - Fork 1
/
Visualize.m2
2750 lines (2137 loc) · 99.9 KB
/
Visualize.m2
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
---------------------------------------------------------------------------
-- PURPOSE : Visualize package for Macaulay2 provides the ability to
-- visualize various algebraic objects in javascript using a
-- modern browser.
--
-- Copyright (C) 2017 Brett Barwick, Thomas Enkosky, Branden Stone and Jim Vallandingham
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License version 2
-- as published by the Free Software Foundation.
--
-- This program 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.
--------------------------------------------------------------------------
newPackage(
"Visualize",
Version => "1.0",
Date => "August 31, 2017",
Authors => {
{Name => "Brett Barwick", Email => "[email protected]", HomePage => "http://faculty.uscupstate.edu/bbarwick/"},
{Name => "Thomas Enkosky", Email => "[email protected]", HomePage => "http://math.bu.edu/people/tomenk/"},
{Name => "Branden Stone", Email => "[email protected]", HomePage => "http://math.adelpi.edu/~bstone/"},
{Name => "Jim Vallandingham", Email => "[email protected]", HomePage => "http://vallandingham.me/"}
-- Contributing Author {Name => "Ata Firat Pir", Email => "[email protected]"},
-- Contributing Author {Name => "Elliot Korte", Email => "[email protected]"},
-- Contributing Author {Name => "Will Smith", Email => "[email protected]"},
-- Contributing Author {Name => "Julio Urenda", Email => "[email protected]"},
},
Headline => "Interactive visualization and manipulation of combinatorial objects in a browser",
Keywords => {"Graphics"},
DebuggingMode => true,
PackageExports => {"Graphs", "Posets", "SimplicialComplexes"},
AuxiliaryFiles => true,
Configuration => {"DefaultPath" => null }
)
export {
-- Options
"VisPath",
"VisTemplate",
"Warning",
"FixExtremeElements",
-- Methods
"visualize",
-- Helpers
-- "toArray", -- Don't need to export?
-- "getCurrPath", -- Don't need to export?
-- "copyTemplate",-- Don't need to export?
-- "replaceInFile",-- Don't need to export?
-- "heightFunction",
-- "relHeightFunction",
-- Server
"openPort",
"closePort"
}
------------------------------------------------------------
-- Global Variables
------------------------------------------------------------
defaultPath = (options Visualize).Configuration#"DefaultPath"
basePath = currentFileDirectory -- created this because copyJS would not handle
-- currentFileDirectory for some reason.
commonVisOpts = {VisPath => defaultPath, Warning => true, Verbose => false} -- list of common options for visualize method
-- (options Visualize).Configuration
portTest = false -- Used to test if ports are open or closed.
inOutPort = null -- Actual file the listener is opened to.
inOutPortNum = null -- The port number that is being opened. This is passed to the browser.
------------------------------------------------------------
-- METHODS
------------------------------------------------------------
-- Input: None.
-- Output: String containing current path.
getCurrPath = method()
installMethod(getCurrPath, () -> (local currPath; currPath = get "!pwd"; substring(currPath,0,(length currPath)-1)|"/"))
--input: A list of lists
--output: an array of arrays
toArray = method()
toArray(List) := L -> (
return new Array from apply(L, i -> new Array from i);
)
--replaceInFile
-- replaces a given pattern by a given pattern in a file
-- input: string containing the pattern
-- string containing the replacement
-- string containing the file name,
replaceInFile = method()
replaceInFile(String, String, String) := (patt, repl, fileName) -> (
local currFile;
local currStr;
currFile = openIn fileName;
currStr = get currFile;
currStr = replace(patt, repl, currStr);
currFile = openOut fileName;
currFile << currStr << close;
return fileName;
)
-- input: path to an html file
-- output: a copy of the input file in a temporary folder
--
copyTemplate = method()
copyTemplate String := src -> (
local fileName; local dirPath;
fileName = (toString currentTime() )|".html";
dirPath = temporaryFileName();
makeDirectory dirPath;
dirPath = concatenate(dirPath,"/",fileName);
copyFile( src, dirPath);
return dirPath;
)
-- input: A source path to an html file and a destination directory
-- output: a copy of the source file in the destination directory
--
copyTemplate(String,String) := (src,dst) -> (
local fileName; local dirPath;
fileName = (toString currentTime() )|".html";
-- dirPath = temporaryFileName();
-- makeDirectory dirPath;
dirPath = concatenate(dst,fileName);
-- test to see if users directory exists
if (fileExists dst)
then (
copyFile( src, dirPath);
return dirPath;
)
else error "Path does not exist. Please check the path and try again.";
)
-- input: three strings
-- output:
searchReplace = method() --Options => {VisPath => currentDirectory()}) -- do we use VisPath?
searchReplace(String,String,String) := (oldString,newString,visSrc) -> (
local visFilePathTemp;
visFilePathTemp = temporaryFileName();
copyFile(visSrc,visFilePathTemp);
openOut visSrc <<
replace(oldString, newString , get visFilePathTemp) <<
close;
return visSrc;
)
-- Input: Poset
-- Output: A list where the ith element is the height of the ith element
-- of P.GroundSet as it appears in a filtration of the poset.
heightFunction = method()
heightFunction(Poset) := P -> (
local F; local G; local tempList;
F = filtration P;
G = P.GroundSet;
tempList = new MutableList from apply(#G,i -> null);
-- The next line creates a list in which the ith entry is the
-- height of the ith element in P.GroundSet.
scan(#F, i -> scan(F#i, j -> (tempList#(position(G, k -> k == j)) = i)));
return toList tempList;
)
-- Input: Poset
-- Output: A list where the ith element is the 'relative height' of the ith
-- element of P.GroundSet, which helps to evenly distribute the elements
-- of the poset evenly based on how they appear within the maximal chains
-- in the poset.
relHeightFunction = method()
relHeightFunction(Poset) := P -> (
local nodes; local maxChains;
local heightList; local maxChainList; local chainLengthList;
local relHeightList; local totalHeight;
nodes = P_*;
maxChains = maximalChains P;
heightList = heightFunction P;
maxChainList = apply(nodes, j -> delete(null,apply(maxChains, L -> (if any(L, i -> i == j) == true then L else null))));
chainLengthList = apply(maxChainList, i -> apply(i, j -> #j));
relHeightList = apply(chainLengthList, i -> max i - 1);
totalHeight = lcm relHeightList;
return apply(#nodes, i -> (totalHeight / relHeightList#i) * heightList#i);
)
--input: A monomial ideal of a polynomial ring in 2 or 3 variables.
--output: The newton polytope of the of the ideal.
--
visualize = method(Options => true)
--{VisPath => defaultPath, Warning => true, VisTemplate => basePath |"Visualize/templates/visIdeal/visIdeal"} >> opts -> J -> (
visualize(Ideal) := commonVisOpts|{VisTemplate => basePath |"Visualize/templates/visIdeal/visIdeal"} >> opts -> J -> (
local R; local arrayList; local arrayString; local numVar; local visTemp;
local varList; local newArrayList; local newArrayString;
R = ring J;
numVar = rank source vars R;
varList = flatten entries vars R;
if ((numVar != 2) and (numVar != 3)) then (error "Ring needs to have either 2 or 3 variables.");
if numVar == 2
then (
if opts.VisPath =!= null
then (
visTemp = copyTemplate(opts.VisTemplate|"2D.html",opts.VisPath);
copyJS(opts.VisPath, Warning => opts.Warning);
)
else (
visTemp = copyTemplate(opts.VisTemplate|"2D.html");
copyJS(replace(baseFilename visTemp, "", visTemp), Warning => opts.Warning);
);
-- changed gens to leadTerm so if there's a non monomial ideal
-- it will return the initial ideal
arrayList = apply( flatten entries leadTerm J, m -> flatten exponents m);
arrayList = toArray arrayList;
arrayString = toString arrayList;
searchReplace("visArray",arrayString, visTemp);
-- searchReplace("XXX",toString(varList_0), visTemp);
-- searchReplace("YYY",toString(varList_1), visTemp);
-- searchReplace("ZZZ",toString(varList_2), visTemp)
)
else (
if opts.VisPath =!= null
then (
visTemp = copyTemplate(opts.VisTemplate|"3D.html",opts.VisPath);
copyJS(opts.VisPath, Warning => opts.Warning);
)
else (
visTemp = copyTemplate(opts.VisTemplate|"3D.html");
copyJS(replace(baseFilename visTemp, "", visTemp), Warning => opts.Warning);
);
arrayList = apply(flatten entries basis(0,infinity, R/J), m -> flatten exponents m );
arrayList = toArray arrayList;
newArrayList = apply(flatten entries leadTerm J, m -> flatten exponents m );
newArrayList = toArray newArrayList;
arrayString = toString arrayList;
newArrayString = toString newArrayList;
searchReplace("visArray",arrayString, visTemp);
searchReplace("newVisArray",newArrayString, visTemp);
searchReplace("XXX",toString(varList_0), visTemp);
searchReplace("YYY",toString(varList_1), visTemp);
searchReplace("ZZZ",toString(varList_2), visTemp)
);
show new URL from { "file://"|visTemp };
return visTemp;--opts.VisPath|A_1;
)
--input: A graph
--output: A visualization of the graph in the browser
--{VisPath => defaultPath, VisTemplate => basePath | "Visualize/templates/visGraph/visGraph-template.html", Warning => true, Verbose => false} >> opts -> G -> (
visualize(Graph) := commonVisOpts|{VisTemplate => basePath | "Visualize/templates/visGraph/visGraph-template.html"} >> opts -> G -> (
local A; local arrayString; local vertexString; local visTemp;
local keyPosition; local vertexSet; local browserOutput;
openPortTest();
A = adjacencyMatrix G;
arrayString = toString toArray entries A; -- Turn the adjacency matrix into a nested array (as a string) to copy to the template html file.
-- Add this back in when we figure out how to deal with the old
-- Graphs package not knowing what G.vertexSet means.
-- !!!! Need to deal with version numbers here
-- if value((options Graphs).Version) == 0.3.1 then (
if .1 == 1 then (
vertexString = toString new Array from apply(keys(G#graph), i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the older Graphs package.
) else (
-- This is a workaround for finding and referring to the key vertexSet in the hash table for G.
-- Would be better to be able to refer to G.vertexSet, but the package
-- seems not to load if we try this.
keyPosition = position(keys G, i -> toString i == "vertexSet");
vertexString = toString new Array from apply((values G)#keyPosition, i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the newer Graphs package
--vertexSet = symbol vertexSet;
--vertexString = toString new Array from apply(G.vertexSet, i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the newer Graphs package.
-- vertexString = toString new Array from apply((values G)#0, i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the newer Graphs package.
);
if opts.VisPath =!= null
then (
visTemp = copyTemplate(opts.VisTemplate, opts.VisPath); -- Copy the visGraph template to a temporary directory.
copyJS(opts.VisPath, Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
)
else (
visTemp = copyTemplate(opts.VisTemplate); -- Copy the visGraph template to a temporary directory.
copyJS(replace(baseFilename visTemp, "", visTemp), Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
);
searchReplace("visArray",arrayString, visTemp); -- Replace visArray in the visGraph html file by the adjacency matrix.
searchReplace("visLabels",vertexString, visTemp); -- Replace visLabels in the visGraph html file by the ordered list of vertices.
searchReplace("visPort",inOutPortNum, visTemp); -- Replace visPort in the visGraph html file by the user port number.
show new URL from { "file://"|visTemp };
browserOutput = openServer(inOutPort, Verbose => opts.Verbose);
return browserOutput;
)
-- Input: A digraph
-- Output: A visualization of the digraph in the browser
--{Verbose => false, VisPath => defaultPath, VisTemplate => basePath |"Visualize/templates/visDigraph/visDigraph-template.html", Warning => true} >> opts -> G -> (
visualize(Digraph) := commonVisOpts|{VisTemplate => basePath |"Visualize/templates/visDigraph/visDigraph-template.html"} >> opts -> G -> (
local A; local arrayString; local vertexString; local visTemp;
local keyPosition; local vertexSet; local browserOutput;
openPortTest();
A = adjacencyMatrix G;
arrayString = toString toArray entries A; -- Turn the adjacency matrix into a nested array (as a string) to copy to the template html file.
-- Add this back in when we figure out how to deal with the old
-- Graphs package not knowing what G.vertexSet means.
--if value((options Graphs).Version) == 0.1 then (
if 1 == .1 then (
vertexString = toString new Array from apply(keys(G#graph), i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the older Graphs package.
) else (
-- This is a workaround for finding and referring to the key vertexSet in the hash table for G.
-- Would be better to be able to refer to G.vertexSet, but the package
-- seems not to load if we try this.
keyPosition = position(keys G, i -> toString i == "vertexSet");
vertexString = toString new Array from apply((values G)#keyPosition, i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the newer Graphs package
--vertexSet = symbol vertexSet;
--vertexString = toString new Array from apply(G.vertexSet, i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the newer Graphs package.
-- vertexString = toString new Array from apply((values G)#0, i -> "\""|toString(i)|"\""); -- Create a string containing an ordered list of the vertices in the newer Graphs package.
);
-- visTemp = copyTemplate(currentDirectory()|"Visualize/templates/visDigraph/visDigraph-template.html"); -- Copy the visDigraph template to a temporary directory.
-- copyJS(replace(baseFilename visTemp, "", visTemp)); -- Copy the javascript libraries to the temp folder.
if opts.VisPath =!= null
then (
visTemp = copyTemplate(opts.VisTemplate, opts.VisPath); -- Copy the visDigraph template to a temporary directory.
copyJS(opts.VisPath, Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
)
else (
visTemp = copyTemplate(opts.VisTemplate); -- Copy the visDigraph template to a temporary directory.
copyJS(replace(baseFilename visTemp, "", visTemp), Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
);
searchReplace("visArray",arrayString, visTemp); -- Replace visArray in the visDigraph html file by the adjacency matrix.
searchReplace("visLabels",vertexString, visTemp); -- Replace visLabels in the visDigraph html file by the ordered list of vertices.
searchReplace("visPort",inOutPortNum, visTemp); -- Replace visPort in the visGraph html file by the user port number.
show new URL from { "file://"|visTemp };
browserOutput = openServer(inOutPort, Verbose => opts.Verbose);
return browserOutput;
)
-- Input: A poset
-- Output: A visualization of the poset in the browser
--{Verbose=>false,FixExtremeElements => false, VisPath => defaultPath, VisTemplate => basePath | "Visualize/templates/visPoset/visPoset-template.html", Warning => true} >> opts -> P -> (
visualize(Poset) := commonVisOpts|{FixExtremeElements => false, VisTemplate => basePath | "Visualize/templates/visPoset/visPoset-template.html"} >> opts -> P -> (
local labelList; local groupList; local relList; local visTemp;
local numNodes; local labelString; local nodeString; local relationString;
local relMatrixString; local fixExtremeEltsString; local browserOutput;
openPortTest();
labelList = apply(P_*, i -> "'"|(toString i)|"'");
labelString = toString new Array from labelList;
relMatrixString = toString toArray entries P.RelationMatrix;
fixExtremeEltsString = toString opts.FixExtremeElements;
if opts.VisPath =!= null
then (
visTemp = copyTemplate(opts.VisTemplate, opts.VisPath); -- Copy the visPoset template to a temporary directory.
copyJS(opts.VisPath, Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
)
else (
visTemp = copyTemplate(opts.VisTemplate); -- Copy the visPoset template to a temporary directory.
copyJS(replace(baseFilename visTemp, "", visTemp), Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
);
searchReplace("visLabels",labelString, visTemp); -- Replace visLabels in the visPoset html file by the labels of the nodes in the same order as the ground set of P.
searchReplace("visRelMatrix",relMatrixString, visTemp); -- Replace visRelMatrix in the visPoset html file by the relation matrix of the poset.
searchReplace("visPort",inOutPortNum, visTemp); -- Replace visPort in the visGraph html file by the user port number.
searchReplace("visExtremeElts",fixExtremeEltsString, visTemp); -- Replace visExtremeElts in the visPoset html file by the option passed by the user of whether to fix the extremal elements at the minimum or maximum levels.
show new URL from { "file://"|visTemp };
browserOutput = openServer(inOutPort, Verbose => opts.Verbose);
return browserOutput;
)
-- Input: A simplicial complex
-- Output: A visualization of the simplicial complex in the browser
--{Verbose => false, VisPath => defaultPath, VisTemplate => basePath | "Visualize/templates/visSimplicialComplex/visSimplicialComplex2d-template.html", Warning => true} >> opts -> D -> (
visualize(SimplicialComplex) := commonVisOpts|{VisTemplate => basePath | "Visualize/templates/visSimplicialComplex/visSimplicialComplex2d-template.html"} >> opts -> D -> (
local vertexSet; local edgeSet; local face2Set; local face3Set; local visTemp;
local vertexList; local edgeList; local face2List; local face3List;
local vertexString; local edgeString; local face2String; local face3String;
local visTemplate; local browserOutput;
openPortTest();
vertexSet = flatten entries faces(0,D);
edgeSet = flatten entries faces(1,D);
face2Set = flatten entries faces(2,D);
vertexList = apply(vertexSet, v -> apply(new List from factor v, i -> i#0));
edgeList = apply(edgeSet, e -> apply(new List from factor e, i -> i#0));
face2List = apply(face2Set, f -> apply(new List from factor f, i -> i#0));
vertexString = toString new Array from apply(vertexSet, i -> "'"|toString(i)|"'");
edgeString = toString new Array from apply(#edgeList, i -> new Array from {position(vertexSet, j -> j === edgeList#i#1),position(vertexSet, j -> j === edgeList#i#0)});
face2String = toString new Array from apply(#face2List, i -> new Array from {position(vertexSet, j -> j == face2List#i#2),position(vertexSet, j -> j == face2List#i#1),position(vertexSet, j -> j == face2List#i#0)});
if dim D>2 then (
error "3-dimensional simplicial complexes not implemented yet.";
visTemplate = basePath | "Visualize/templates/visSimplicialComplex/visSimplicialComplex3d-template.html"
)
else (
visTemplate = basePath | "Visualize/templates/visSimplicialComplex/visSimplicialComplex2d-template.html"
);
if opts.VisPath =!= null
then (
visTemp = copyTemplate(visTemplate, opts.VisPath); -- Copy the visSimplicialComplex template to a temporary directory.
copyJS(opts.VisPath, Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
)
else (
visTemp = copyTemplate(visTemplate); -- Copy the visSimplicialComplex template to a temporary directory.
copyJS(replace(baseFilename visTemp, "", visTemp), Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
);
searchReplace("visNodes",vertexString, visTemp); -- Replace visNodes in the visSimplicialComplex html file by the ordered list of vertices.
searchReplace("visEdges",edgeString, visTemp); -- Replace visEdges in the visSimplicialComplex html file by the list of edges.
searchReplace("vis2Faces",face2String, visTemp); -- Replace vis2Faces in the visSimplicialComplex html file by the list of faces.
searchReplace("visPort",inOutPortNum, visTemp); -- Replace visPort in the visGraph html file by the user port number.
if dim D>2 then (
error "3-dimensional simplicial complexes not implemented yet.";
face3Set = flatten entries faces(3,D);
face3List = apply(face3Set, f -> apply(new List from factor f, i -> i#0));
face3String = toString new Array from apply(#face3List, i -> {"\"v1\": "|toString(position(vertexSet, j -> j == face3List#i#3))|",\"v2\": "|toString(position(vertexSet, j -> j == face3List#i#2))|",\"v3\": "|toString(position(vertexSet, j -> j == face3List#i#1))|",\"v4\": "|toString(position(vertexSet, j -> j == face3List#i#0))});
searchReplace("vis3Faces",face3String, visTemp); -- Replace vis3Faces in the visSimplicialComplex html file by the list of faces.
);
show new URL from { "file://"|visTemp };
browserOutput = openServer(inOutPort, Verbose => opts.Verbose);
return browserOutput;
)
{*
--input: A parameterized surface in RR^3
--output: The surface in the browser
--
visualize(List) := {VisPath => defaultPath, VisTemplate => basePath | "Visualize/templates/visSurface/Graphulus-Surface.html", Warning => true} >> opts -> P -> (
local visTemp; local stringList;
if opts.VisPath =!= null
then (
visTemp = copyTemplate(opts.VisTemplate, opts.VisPath); -- Copy the visSimplicialComplex template to a temporary directory.
copyJS(opts.VisPath, Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
)
else (
visTemp = copyTemplate(opts.VisTemplate); -- Copy the visSimplicialComplex template to a temporary directory.
copyJS(replace(baseFilename visTemp, "", visTemp), Warning => opts.Warning); -- Copy the javascript libraries to the temp folder.
);
stringList = apply(P, i -> "\""|toString i|"\"");
searchReplace("visP1", stringList#0, visTemp); -- Replace visNodes in the visSimplicialComplex html file by the ordered list of vertices.
searchReplace("visP2", stringList#1, visTemp); -- Replace visEdges in the visSimplicialComplex html file by the list of edges.
searchReplace("visP3", stringList#2, visTemp); -- Replace vis2Faces in the visSimplicialComplex html file by the list of faces.
show new URL from { "file://"|visTemp };
return visTemp;
)
*}
-- Input: A string of a path to a directory
-- Output: Copies the needed files and libraries to path
--
-- Caveat: Checks to see if files exist. If they do exist, the user
-- must give permission to continue. Continuing will overwrite
-- current files and cannot be undone.
copyJS = method(Options => {Warning => true})
copyJS(String) := opts -> dst -> (
if not match("/$", dst) then dst = dst | "/";
if not fileExists dst then makeDirectory dst;
dirs := {"js", "css", "fonts", "images"};
existingDirs := select(dirs, dir -> fileExists concatenate(dst, dir));
if #existingDirs > 0 and opts.Warning == true then (
print concatenate(
" -- Note: You can suppress this message with the 'Warning => false' option.\n",
" -- The following folders on the path ",dst," have some files that will be overwritten: ",
demark(", ", existingDirs), newline,
" -- This action cannot be undone.", newline);
ans := read " Would you like to continue? (y or n): ";
while (ans != "y" and ans != "n") do (
ans = read " Would you like to continue? (y or n): ";
);
if ans == "n" then (
error "Process was aborted.";
);
);
for dir in dirs do (
makeDirectory(dst | dir);
for file in readDirectory(basePath | "Visualize/" | dir) do (
if not member(file, {".", ".."}) then (
copyFile(realpath(basePath | "Visualize/" | dir | "/" | file),
dst | dir | "/" | file)))
);
return "Created directories at "|dst;
)
-- The server workflow is as follows.
-- 0. Load Visualize.m2
-- 1. User opens port :: openPort("8000")
-- :: If any port is open an error occurs.
-- :: Sometimes the error is thrown when no port
-- :: is open. This usually occurs right after a
-- :: port has been closed. It takes a bit of time
-- :: for M2 to realize no port is open.
-- :: Maybe this is an issue with the garbage collector?
-- 2. Define graph or other object :: G = graph(....)
-- 3. Run visualize :: H = visualize G
-- :: This will open the website and start
-- :: communication with the server.
-- :: When the user ends session, output is
-- :: sent back to M2 and assigned to H.
-- 4. End session to export info to browser;
-- 5. Keep working and visualizing objects;
-- 6. When finished, user closes port :: closePort() (or restart M2).
-- Input: String, a port number the user wants to open.
-- Output: None, a port is open and a message is displayed.
--
openPort = method()
openPort String := F -> (
if (portTest == true)
then (
error ("--Port "| toString inOutPort | " is currently open. To use a different port, you must first close this port with closePort().");
)
else(
portTest = true;
inOutPortNum = F;
F = "$localhost:"|F;
inOutPort = openListener F;
print("--Port " | toString inOutPort | " is now open.");
);
)
--getCurrPath = method()
--installMethod(getCurrPath, () -> (local currPath; currPath = get "!pwd"; substring(currPath,0,(length currPath)-1)|"/"))
closePort = method()
installMethod(closePort, () -> (
portTest = false;
close inOutPort;
print("--Port " | toString inOutPort | " is now closing. This could take a few seconds.");
)
)
-- Input: none
-- Output: Error is user trying to run 'visualize' without first opening a port.
--
openPortTest = method()
installMethod(openPortTest, () -> (
if (portTest == false ) then error("-- You must open a port with 'openPort()' before you can communicate with the browser.");
)
)
-- Input: File, an in-out port for communicating with the browser
-- Output: Whatever the browser sends
--
openServer = method(Options =>{Verbose => true})
openServer File := opts -> S -> (
local server; local fun; local listener;
local httpHeader; local testKey;
local u; local data; local dataValue;
testKey = " ";
listener = S;
server = () -> (
stderr << "-- Visualizing. Your browser should open automatically." << endl << "-- Click 'End Session' in the browser when finished." << endl;
while true do (
wait {listener};
g := openInOut listener; -- this should be interruptible! (Dan's Comment, not sure what it means)
r := read g;
if opts.Verbose then stderr << "request: " << stack lines r << endl << endl;
r = lines r;
if #r == 0 then (close g; continue);
data := last r;
dataValue = value data;
r = first r;
-- Begin handling requests from browser
---------------------------------------
-- hasEulerianTrail
if match("^POST /hasEulerianTrail/(.*) ",r) then (
-- testKey = "hasEulerianTrail";
fun = identity;
u = toString( hasEulerianTrail dataValue );
)
-- hasOddHole
else if match("^POST /hasOddHole/(.*) ",r) then (
-- testKey = "hasOddHole";
fun = identity;
u = toString( hasOddHole dataValue );
)
-- isCM
else if match("^POST /isCM/(.*) ",r) then (
-- testKey = "isCM";
fun = identity;
u = toString( isCM dataValue );
)
-- isBipartite
else if match("^POST /isBipartite/(.*) ",r) then (
-- testKey = "isBipartite";
fun = identity;
u = toString( isBipartite dataValue );
)
-- isChordal
else if match("^POST /isChordal/(.*) ",r) then (
-- testKey = "isChordal";
fun = identity;
u = toString( isChordal dataValue );
)
-- isComparabilityGraph
else if match("^POST /isComparabilityGraph/(.*) ",r) then (
-- testKey = "isComparabilityGraph";
fun = identity;
u = toString( isComparabilityGraph dataValue );
)
-- isConnected
else if match("^POST /isConnected/(.*) ",r) then (
-- testKey = "isConnected";
fun = identity;
u = toString( isConnected dataValue );
)
-- isCyclic
else if match("^POST /isCyclic/(.*) ",r) then (
-- testKey = "isCyclic";
fun = identity;
u = toString( isCyclic dataValue );
)
-- isEulerian
else if match("^POST /isEulerian/(.*) ",r) then (
-- testKey = "isEulerian";
fun = identity;
u = toString( isEulerian dataValue );
)
-- isForest
else if match("^POST /isForest/(.*) ",r) then (
-- testKey = "isForest";
fun = identity;
u = toString( isForest dataValue );
)
-- isPerfect
else if match("^POST /isPerfect/(.*) ",r) then (
-- testKey = "isPerfect";
fun = identity;
u = toString( isPerfect dataValue );
)
-- isRegular
else if match("^POST /isRegular/(.*) ",r) then (
-- testKey = "isRegular";
fun = identity;
u = toString( isRegular dataValue );
)
-- isSimple
else if match("^POST /isSimple/(.*) ",r) then (
-- testKey = "isSimple";
fun = identity;
u = toString( isSimple dataValue );
)
-- isStronglyConnected
else if match("^POST /isStronglyConnected/(.*) ",r) then (
-- testKey = "isStronglyConnected";
fun = identity;
u = toString( isStronglyConnected dataValue );
)
-- isTree
else if match("^POST /isTree/(.*) ",r) then (
-- testKey = "isTree";
fun = identity;
u = toString( isTree dataValue );
)
-- isRigid
else if match("^POST /isRigid/(.*) ",r) then (
-- testKey = "isRigid";
fun = identity;
u = toString( isRigid dataValue );
)
-- isWeaklyConnected
else if match("^POST /isWeaklyConnected/(.*) ",r) then (
-- testKey = "isWeaklyConnected";
fun = identity;
u = toString( isWeaklyConnected dataValue );
)
-- chromaticNumber
else if match("^POST /chromaticNumber/(.*) ",r) then (
-- testKey = "chromaticNumber";
fun = identity;
u = toString( chromaticNumber dataValue );
)
-- independenceNumber
else if match("^POST /independenceNumber/(.*) ",r) then (
-- testKey = "independenceNumber";
fun = identity;
u = toString( independenceNumber dataValue );
)
-- cliqueNumber
else if match("^POST /cliqueNumber/(.*) ",r) then (
-- testKey = "cliqueNumber";
fun = identity;
u = toString( cliqueNumber dataValue );
)
-- degeneracy
else if match("^POST /degeneracy/(.*) ",r) then (
-- testKey = "degeneracy";
fun = identity;
u = toString( degeneracy dataValue );
)
-- density
else if match("^POST /density/(.*) ",r) then (
-- testKey = "density";
fun = identity;
u = toString( density dataValue );
)
-- diameter
else if match("^POST /diameter/(.*) ",r) then (
-- testKey = "diameter";
fun = identity;
u = toString( diameter dataValue );
)
-- edgeConnectivity
else if match("^POST /edgeConnectivity/(.*) ",r) then (
-- testKey = "edgeConnectivity";
fun = identity;
u = toString( edgeConnectivity dataValue );
)
-- minimalDegree
else if match("^POST /minimalDegree/(.*) ",r) then (
-- testKey = "minimalDegree";
fun = identity;
u = toString( minimalDegree dataValue );
)
-- numberOfComponents
else if match("^POST /numberOfComponents/(.*) ",r) then (
-- testKey = "numberOfComponents";
fun = identity;
u = toString( numberOfComponents dataValue );
)
-- numberOfTriangles
else if match("^POST /numberOfTriangles/(.*) ",r) then (
-- testKey = "numberOfTriangles";
fun = identity;
u = toString( numberOfTriangles dataValue );
)
-- radius
else if match("^POST /radius/(.*) ",r) then (
-- testKey = "radius";
fun = identity;
if not isConnected dataValue then u = "Not connected." else u = toString( radius dataValue );
)
-- vertexConnectivity
else if match("^POST /vertexConnectivity/(.*) ",r) then (
-- testKey = "";
fun = identity;
u = toString( vertexConnectivity dataValue );
)
-- vertexCoverNumber
else if match("^POST /vertexCoverNumber/(.*) ",r) then (
-- testKey = "vertexCoverNumber";
fun = identity;
u = toString( vertexCoverNumber dataValue );
)
----------------------
-- Tests for posets --
----------------------
-- isAtomic
else if match("^POST /isAtomic/(.*) ",r) then (
-- testKey = "isAtomic";
fun = identity;
if not isLattice dataValue then u = "Not lattice." else u = toString( isAtomic dataValue );
)
-- isBounded
else if match("^POST /isBounded/(.*) ",r) then (
-- testKey = "isBounded";
fun = identity;
u = toString( isBounded dataValue );
)
-- isDistributive
else if match("^POST /isDistributive/(.*) ",r) then (
-- testKey = "isDistributive";
fun = identity;
if not isLattice dataValue then u = "Not lattice." else u = toString( isDistributive dataValue );
)
-- isGeometric
else if match("^POST /isGeometric/(.*) ",r) then (
-- testKey = "isGeometric";
fun = identity;
if not isLattice dataValue then u = "Not lattice." else u = toString( isGeometric dataValue );
)
-- isGraded
else if match("^POST /isGraded/(.*) ",r) then (
-- testKey = "isGraded";
fun = identity;
u = toString( isGraded dataValue );
)
-- isLattice
else if match("^POST /isLattice/(.*) ",r) then (
-- testKey = "isLattice";
fun = identity;
u = toString( isLattice dataValue );
)
-- isLowerSemilattice
else if match("^POST /isLowerSemilattice/(.*) ",r) then (
-- testKey = "isLowerSemilattice";
fun = identity;
u = toString( isLowerSemilattice dataValue );
)
-- isLowerSemimodular (only applies to ranked posets)
else if match("^POST /isLowerSemimodular/(.*) ",r) then (
-- testKey = "isLowerSemimodular";
fun = identity;
if not (isRanked dataValue and isLattice dataValue) then u = "Not ranked lattice." else u = toString( isLowerSemimodular dataValue );
)
-- isModular
else if match("^POST /isModular/(.*) ",r) then (
-- testKey = "isModular";
fun = identity;
if not isLattice dataValue then u = "Not lattice." else u = toString( isModular dataValue );
)
-- isRanked
else if match("^POST /isRanked/(.*) ",r) then (
-- testKey = "isRanked";
fun = identity;
u = toString( isRanked dataValue );
)
-- isSperner (only applies to ranked posets)
else if match("^POST /isSperner/(.*) ",r) then (
-- testKey = "isSperner";
fun = identity;
if not isRanked dataValue then u = "Not ranked." else u = toString( isSperner dataValue );
)
-- isStrictSperner (only applies to ranked posets)
else if match("^POST /isStrictSperner/(.*) ",r) then (
-- testKey = "isStrictSperner";
fun = identity;
if not isRanked dataValue then u = "Not ranked." else u = toString( isStrictSperner dataValue );
)
-- isUpperSemilattice
else if match("^POST /isUpperSemilattice/(.*) ",r) then (
-- testKey = "isUpperSemilattice";
fun = identity;
u = toString( isUpperSemilattice dataValue );
)
-- isUpperSemimodular (only applies to ranked posets)
else if match("^POST /isUpperSemimodular/(.*) ",r) then (
-- testKey = "isUpperSemimodular";
fun = identity;
if not(isRanked dataValue and isLattice dataValue) then u = "Not ranked lattice." else u = toString( isUpperSemimodular dataValue );
)
-- dilworthNumber
else if match("^POST /dilworthNumber/(.*) ",r) then (
-- testKey = "dilworthNumber";
fun = identity;
u = toString( dilworthNumber dataValue );
)
-- End Session
else if match("^POST /end/(.*) ",r) then (
R := dataValue;
return R;
)
-- Error to catch typos and bad requests
else (
error ("There was no match to the request: "|r);
);
-- Determines the output based on the testKey
-- if (testKey == "isCM") then ( u = toString( cmTest value data ) );
-- if (testKey == "isBipartite") then ( u = toString( isBipartite value data ) );
-- if (testKey == "isChordal") then ( u = toString( isChordal value data ) );
-- if (testKey == "isConnected") then ( u = toString( isConnected value data ) );
-- if (testKey == "isCyclic") then ( u = toString( isCyclic value data ) );
-- if (testKey == "isEulerian") then ( u = toString( isEulerian value data ) );
-- if (testKey == "isForest") then ( u = toString( isForest value data ) );
-- if (testKey == "isPerfect") then ( u = toString( isPerfect value data ) );
-- if (testKey == "isRegular") then ( u = toString( isRegular value data ) );
-- if (testKey == "isSimple") then ( u = toString( isSimple value data ) );
-- if (testKey == "isTree") then ( u = toString( isTree value data ) );
send := httpHeader fun u;
if opts.Verbose then stderr << "response: " << stack lines send << endl << endl;
g << send << close;
);