Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 288
Image: ubuntu2004
1
2
3
# This file was *autogenerated* from the file scripts/generator.sage
4
from sage.all_cmdline import * # import sage library
5
6
_sage_const_100000 = Integer(100000); _sage_const_999999 = Integer(999999); _sage_const_0 = Integer(0); _sage_const_1 = Integer(1); _sage_const_3 = Integer(3); _sage_const_2 = Integer(2); _sage_const_1000 = Integer(1000); _sage_const_10000 = Integer(10000)# Generator helpers
7
def mi_vars(*latex_names, random_order=True):
8
"""
9
Given one or more `latex_names` of strings, returns a tuple
10
of Sage variables. `random_order` names them so that they appear
11
in expressions in a random order.
12
"""
13
stamp = randrange(_sage_const_100000 ,_sage_const_999999 )
14
indices = list(range(len(latex_names)))
15
if random_order:
16
shuffle(indices)
17
import string
18
random_letter = choice(list(string.ascii_lowercase))
19
return (var(f"{random_letter}_mi_var_{stamp}_{indices[i]}", latex_name=name) for i, name in enumerate(latex_names))
20
21
def shuffled_equation(*terms):
22
"""
23
Represents the equation sum(terms)==0, but with terms shuffled randomly
24
to each side.
25
"""
26
new_equation = (SR(_sage_const_0 )==_sage_const_0 )
27
for term in terms:
28
if choice([True,False]):
29
new_equation += (SR(term)==_sage_const_0 )
30
else:
31
new_equation += (_sage_const_0 ==-SR(term))
32
return new_equation*choice([-_sage_const_1 ,_sage_const_1 ])
33
34
def base64_graphic(obj, file_format="svg"):
35
"""
36
Generates Base64 encoding of the graphic in the requested file_format.
37
"""
38
if not isinstance(obj,Graphics):
39
raise TypeError("Only graphics may be encoded as base64")
40
if file_format not in ["svg", "png"]:
41
raise ValueError("Invalid file format")
42
filename = tmp_filename(ext=f'.{file_format}')
43
obj.save(filename)
44
with open(filename, 'rb') as f:
45
from base64 import b64encode
46
b64 = b64encode(f.read())
47
return b64
48
49
def data_url_graphic(obj, file_format="svg"):
50
"""
51
Generates Data URL representing the graphic in the requested file_format.
52
"""
53
b64 = base64_graphic(obj, file_format=file_format).decode('utf-8')
54
if file_format=="svg":
55
file_format = "svg+xml"
56
return f"data:image/{file_format};base64,{b64}"
57
58
def latex_system_from_matrix(matrix, variables="x", alpha_mode=False, variable_list=[]):
59
# Augment with zero vector if not already augmented
60
if not matrix.subdivisions()[_sage_const_1 ]:
61
matrix=matrix.augment(zero_vector(ZZ, len(matrix.rows())), subdivide=true)
62
num_vars = matrix.subdivisions()[_sage_const_1 ][_sage_const_0 ]
63
# Start using requested variables
64
system_vars = variable_list
65
# Conveniently add xyzwv if requested
66
if alpha_mode:
67
system_vars += list(var("x y z w v"))
68
# Finally fall back to x_n as needed
69
system_vars += [var(f"{variables}_{n+1}") for n in range(num_vars)]
70
# Build matrix
71
latex_output = "\\begin{matrix}\n"
72
for row in matrix.rows():
73
if row[_sage_const_0 ]!= _sage_const_0 :
74
latex_output += latex(row[_sage_const_0 ]*system_vars[_sage_const_0 ])
75
previous_terms = True
76
else:
77
previous_terms = False
78
for n,cell in enumerate(row[_sage_const_1 :num_vars]):
79
latex_output += " & "
80
if cell < _sage_const_0 and previous_terms:
81
latex_output += " - "
82
elif cell > _sage_const_0 and previous_terms:
83
latex_output += " + "
84
latex_output += " & "
85
if cell != _sage_const_0 :
86
latex_output += latex(cell.abs()*system_vars[n+_sage_const_1 ])
87
if not previous_terms:
88
previous_terms = bool(cell!=_sage_const_0 )
89
if not previous_terms:
90
latex_output += " 0 "
91
latex_output += " & = & "
92
latex_output += latex(row[num_vars])
93
latex_output += "\\\\\n"
94
latex_output += "\\end{matrix}"
95
return latex_output
96
97
def latexify(obj):
98
if isinstance(obj,str):
99
return obj
100
elif isinstance(obj,list):
101
return [latexify(item) for item in obj]
102
elif isinstance(obj,dict):
103
return {key:latexify(obj[key]) for key in obj.keys()}
104
else:
105
return str(latex(obj))
106
107
import sys,json
108
if sys.argv[_sage_const_3 ]:
109
generator_path = sys.argv[_sage_const_1 ]
110
amount = int(sys.argv[_sage_const_2 ])
111
public = (sys.argv[_sage_const_3 ]=="PUBLIC")
112
load(generator_path) # provides generator() function
113
seeds = []
114
for i in range(amount):
115
if public:
116
seed = i % _sage_const_1000
117
else:
118
set_random_seed()
119
seed = randrange(_sage_const_1000 ,_sage_const_10000 )
120
set_random_seed(seed)
121
seeds.append({"seed":int(seed),"values":latexify(generator())})
122
print(json.dumps(seeds))
123
124
125