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