Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96144
License: OTHER
1
2
# coding: utf-8
3
4
# # Importing modules, setting options and defining custom functions for use in other worksheets
5
# To import into another worksheet:
6
#
7
# ```
8
# fun_include_ipynb('Worksheet_setup')
9
# ```
10
# or
11
# ```
12
# load('Worksheet_setup.sage')
13
# ```
14
# Note: This worksheet is prepared for the open source software [sage](http://www.sagemath.org). In sage 7.3, nbconvert is missing dependencies. To rectify, enter the following commands in a terminal:
15
#
16
# ```
17
# sage --sh
18
# pip install entrypoints
19
# pip install configparser
20
# ```
21
#
22
23
# In[1]:
24
25
get_ipython().magic(u'matplotlib inline')
26
import numpy as np # for data array operations
27
import pylab # for plotting
28
import json # for reading notebook metadata
29
30
list_plot.options["frame"]=True
31
list_plot.options["axes"]=False
32
plot.options["frame"]=True
33
plot.options["axes"]=False
34
35
try:
36
for s in units.amount_of_substance.trait_names():
37
globals()[s] = getattr(units.amount_of_substance,s)
38
for s in units.energy.trait_names():
39
globals()[s] = getattr(units.energy,s)
40
for s in units.length.trait_names():
41
globals()[s] = getattr(units.length,s)
42
for s in units.mass.trait_names():
43
globals()[s] = getattr(units.mass,s)
44
for s in units.pressure.trait_names():
45
globals()[s] = getattr(units.pressure,s)
46
for s in units.temperature.trait_names():
47
globals()[s] = getattr(units.temperature,s)
48
for s in units.time.trait_names():
49
globals()[s] = getattr(units.time,s)
50
for s in units.power.trait_names():
51
globals()[s] = getattr(units.power,s)
52
except: # in newer versions of sage, need to use _tab_completion() instead of trait_names()
53
for s in units.amount_of_substance._tab_completion():
54
globals()[s] = getattr(units.amount_of_substance,s)
55
for s in units.energy._tab_completion():
56
globals()[s] = getattr(units.energy,s)
57
for s in units.length._tab_completion():
58
globals()[s] = getattr(units.length,s)
59
for s in units.mass._tab_completion():
60
globals()[s] = getattr(units.mass,s)
61
for s in units.pressure._tab_completion():
62
globals()[s] = getattr(units.pressure,s)
63
for s in units.temperature._tab_completion():
64
globals()[s] = getattr(units.temperature,s)
65
for s in units.time._tab_completion():
66
globals()[s] = getattr(units.time,s)
67
for s in units.power._tab_completion():
68
globals()[s] = getattr(units.power,s)
69
70
71
udict = {}
72
cdict = {}
73
docdict = {}
74
dict_latex = {}
75
dict_domain = {}
76
dict_vars ={}
77
78
79
def var2(name, doc='', units=1, domain1='real', latexname='', value = False):
80
'''
81
Creates a symbolic variable in the given domain (standard:'real') and with the given
82
latexname. Further, it adds the string doc to docdict, the units to udict and the value
83
to cdict. All entries are optional except for name. Note that the information passed as
84
domain1 is saved as an assumption, e.g. 'a is read'. All assumptions can be viewed as a
85
list, using the command assumptions().
86
Usage example:
87
sage: var2('x', 'Distance' , units=meter, domain1 = 'positive', latexname = 'x_{1-2}', value = 1.0)
88
'''
89
if len(latexname)>0:
90
z = var(name,domain = domain1,latex_name = latexname)
91
else:
92
z = var(name,domain = domain1)
93
var1 = eval(name)
94
dict_domain[var1] = domain1
95
dict_latex[var1] = var1._latex_()
96
docdict[var1] = doc
97
udict[var1] = units
98
dict_vars[var1] = {'doc': doc, 'units': units, 'domain1': domain1, 'latexname': latexname, 'value': value}
99
if value:
100
cdict[var1] = value
101
return z
102
103
def fun_loadvars(vardict = False):
104
'''
105
Loads all information related to symbolic variables defined using var2.
106
Usage example:
107
sage: allvars = fun_loadvars()
108
'''
109
if vardict:
110
variables = vardict.keys()
111
for var1 in variables:
112
var2(str(var1), doc = vardict[var1]['doc'], units = vardict[var1]['units'], domain1 = vardict[var1]['domain1'], latexname = vardict[var1]['latexname'], value = vardict[var1]['value'])
113
114
else:
115
variables = docdict.keys()
116
for var1 in variables:
117
if var1 in cdict.keys():
118
var2(str(var1), doc=docdict[var1], units=udict[var1], domain1 = dict_domain[var1], latexname=dict_latex[var1], value=cdict[var1])
119
else:
120
var2(str(var1), doc=docdict[var1], units=udict[var1], domain1 = dict_domain[var1], latexname=dict_latex[var1])
121
122
# Workaround from http://ask.sagemath.org/question/10260/convert-derived-si-units-to-base-units/
123
def convert(expr):
124
op = expr.operator()
125
ops = expr.operands()
126
if op:
127
if len(ops) == 2:
128
return op(*map(convert, ops))
129
else:
130
return op(convert(ops[0]), reduce(op, map(convert, ops[1:])))
131
else:
132
return expr.convert() if hasattr(expr, 'convert') else expr
133
134
def units_check(eq, sfull = True):
135
'''
136
Checks whether all arguments are keys in udict and returns simplified units
137
'''
138
global udict, dict_units
139
udict1 = {}
140
# Need to multiply units with variable, so that we can devide by the symbolic equation later:
141
for key1 in udict.keys():
142
udict1[key1] = key1*udict[key1]
143
for blah in eq.arguments():
144
udict[blah]
145
eq.show()
146
if sfull:
147
return convert(eq.subs(udict1)/eq).simplify_full()
148
else:
149
return convert(eq.subs(udict1)/eq)
150
151
def fun_units_formatted(variable):
152
'''
153
Returns units of variable expanded to exponential notation.
154
155
'''
156
global udict, subsdict
157
units1 = (eval(variable)*udict[eval(variable)]/eval(variable)).subs(subsdict) # multiplication and division by the variable ensures that units1 is a symbolic expression, even if udict[var] = 1
158
facs = units1.factor_list()
159
str1 = ''
160
for term1 in facs:
161
op1 = term1[1]
162
if op1==1:
163
str1 = str(term1[0]) + ' ' + str1
164
if op1!=1:
165
str1 = str1 +' ' + str(term1[0])
166
str1 = str1 + '$^{' + str(op1) + '}$ '
167
return str1
168
169
170
171
def plot_fit(xdata, ydata, model, initial_guess = None, parameters = None, variables = None):
172
'''Fits the parameters of model to lists of xdata and ydata and plots the results
173
Example:
174
#linear regression through origin
175
var('x m')
176
model(x) = m*x
177
plot_fit(xdata,ydata,model)
178
'''
179
data = zip(xdata,ydata)
180
xdata1 = vector(xdata)
181
ydata1 = vector(ydata)
182
p1 = find_fit(data, model,solution_dict=True)
183
pkeys = p1.keys()
184
p2 = {}
185
for i in pkeys: p2[i] = n(p1[i],digits=3)
186
fitvals = vector([n(model(x1).subs(p1)) for x1 in xdata])
187
# root mean square deviation
188
rmsd = sqrt(mean(ydata1 - fitvals)^2)
189
nrmsd = rmsd/(max(ydata) - min(ydata))
190
blah = text("y="+str(model(x).subs(p2)),(0,0),fontsize=10,rgbcolor=(1,0,0))
191
print "y="+str(model(x).subs(p2))
192
print "NRMSD = "+str(n(nrmsd,digits=5))
193
lentext = blah.xmax() - blah.xmin()
194
# plot
195
P = list_plot(data, frame=True, axes = False, faceted=True, color = "white")
196
P += plot(model.subs(p1),(x,min(xdata),max(xdata)),color = 'black', legend_label = "y="+str(model(x).subs(p2)) + '\n ' + "NRMSD = "+str(n(nrmsd,digits=5)))
197
return P
198
199
def dict_print(vdict1, list_names = None):
200
dtype1 = [('name', 'S10'), ('val', object)]
201
vdict2 = vdict1.copy()
202
if list_names:
203
vdict2 = {}
204
for name1 in list_names:
205
vdict2[name1] = vdict1[name1]
206
list1 = np.array(vdict2.items(), dtype = dtype1)
207
list2 = np.sort(list1,order = 'name')
208
for k, v in list2:
209
print "{:<15} {:<15}".format(k,v)
210
211
def fun_dict_print(vdict1):
212
dtype1 = [('name', 'S10'), ('val', object)]
213
list1 = np.array(vdict1.items(), dtype = dtype1)
214
list2 = np.sort(list1,order = 'name')
215
for k, v in list2:
216
print "{:<15} {:<15}".format(k,v)
217
218
def fun_dict(dict1,dict2):
219
'''
220
Updates all entries of dict1 with entries co-occurring in dict2
221
and returns the udated dict1.
222
'''
223
dict1.update(dict2)
224
return dict1
225
226
def fun_comp_array(expr1, nparray):
227
"""
228
Returns list of values for expr1
229
corresponding to each row of nparray
230
where all arguments in expr1 are substituted
231
by the corresponding values in nparray.
232
"""
233
list_args = expr1.args()
234
return [expr1.subs(dict(zip(list_args, [nparray[str(dummy)][i] for dummy in list_args]))) for i in srange(len(nparray))]
235
236
def fun_printvar(varname):
237
pstring = str(varname)+': ' + docdict[varname]
238
try:
239
value = cdict[varname]
240
pstring1 = pstring + ', ' + str(n(value, prec = 16)) + ' ' + str(udict[varname]/varname)
241
except: pstring1 = pstring + ', ' + str(udict[varname]/varname)
242
print pstring1
243
return
244
245
def fun_eq(eq, sfull = True):
246
print units_check(eq)
247
return eq
248
249
def fun_export_ipynb(worksheet, folder):
250
'''
251
Exports worksheet.ipynb to a .py or .sage depending on kernel.
252
Example:
253
fun_export_ipynb('Worksheet_setup', 'temp/')
254
Need to import json before using this function. Unless option output=True is given,
255
each line of text has a semicolon added in the .py file, preventing any output.
256
'''
257
str1 = 'jupyter nbconvert --to=python \'' + worksheet+'.ipynb\''
258
print str1
259
print 'Exporting specified worksheet to .py file...'
260
261
try:
262
retcode = os.system(str1)
263
if retcode < 0:
264
print >>sys.stderr, "nbconvert was terminated by signal", -retcode
265
else:
266
print >>sys.stderr, "nbconvert returned", retcode
267
except OSError as e:
268
print >>sys.stderr, "Execution failed:", e
269
print >>sys.stderr, "Trying ipython nbconvert instead..."
270
str1 = 'ipython nbconvert --to script \'' + worksheet+'.ipynb\'' # for new version of python
271
try:
272
retcode = os.system(str1)
273
if retcode < 0:
274
print >>sys.stderr, "nbconvert was terminated by signal", -retcode
275
else:
276
print >>sys.stderr, "nbconvert returned", retcode
277
except OSError as e:
278
print >>sys.stderr, "Execution failed:", e
279
280
str1 = worksheet + '.py'
281
282
print 'Checking if specified ipynb file was run with sage kernel...'
283
with open(worksheet+'.ipynb') as data_file:
284
data = json.load(data_file)
285
286
if data['metadata']['kernelspec']['name'][0:4] == 'sage':
287
print 'Renaming .py file to .sage if notebook kernel was sage (to avoid exponent error)'
288
str2 = folder + worksheet + '.sage'
289
os.rename(str1, str2)
290
291
292
def fun_include_ipynb(worksheet, del1 = True, output = True):
293
'''
294
Exports worksheet.ipynb to a sage file and loads it into current worksheet.
295
Example:
296
fun_include_ipynb('Worksheet_setup')
297
Need to import json before using this function. Unless option output=True is given,
298
each line of text has a semicolon added in the .py file, preventing any output.
299
'''
300
str1 = 'jupyter nbconvert --to=python \'' + worksheet+'.ipynb\''
301
print str1
302
print 'Exporting specified worksheet to .py file...'
303
304
try:
305
retcode = os.system(str1)
306
if retcode < 0:
307
print >>sys.stderr, "nbconvert was terminated by signal", -retcode
308
else:
309
print >>sys.stderr, "nbconvert returned", retcode
310
except OSError as e:
311
print >>sys.stderr, "Execution failed:", e
312
print >>sys.stderr, "Trying ipython nbconvert instead..."
313
str1 = 'ipython nbconvert --to script \'' + worksheet+'.ipynb\'' # for new version of python
314
try:
315
retcode = os.system(str1)
316
if retcode < 0:
317
print >>sys.stderr, "nbconvert was terminated by signal", -retcode
318
else:
319
print >>sys.stderr, "nbconvert returned", retcode
320
except OSError as e:
321
print >>sys.stderr, "Execution failed:", e
322
323
str1 = worksheet + '.py'
324
325
print 'Checking if specified ipynb file was run with sage kernel...'
326
with open(worksheet+'.ipynb') as data_file:
327
data = json.load(data_file)
328
329
if data['metadata']['kernelspec']['name'][0:4] == 'sage':
330
print 'Renaming .py file to .sage if notebook kernel was sage (to avoid exponent error)'
331
str2 = worksheet + '.sage'
332
os.rename(str1, str2)
333
str1 = str2
334
if output == False:
335
input_file = open(str1, "r")
336
str2 = '0_'+ str1
337
output_file = open(str2, "w")
338
for line in input_file:
339
line = line.strip() # remove line end marks
340
final = line+'\n'
341
if len(line)>0:
342
if line[-1] != ';':
343
final= line+';\n'
344
output_file.write(final)
345
input_file.close()
346
os.remove(str1)
347
output_file.close()
348
str1 = str2
349
350
351
print 'Loading file into current worksheet...'
352
load(str1)
353
if del1:
354
print 'Removing file generated above...'
355
os.remove(str1)
356
357
358
# Below, we export the above commands to a file called Worksheet_setup.sage in the temp folder, which can be loaded in other worksheets by typing:
359
#
360
# `load('temp/Worksheet_setup.sage')`
361
# However, to avoid re-exporting the file every time it is loaded, we will comment out the command and instead execute it from a different worksheet, Worksheet_update.ipynb.
362
363
# In[2]:
364
365
#fun_export_ipynb('Worksheet_setup', 'temp/')
366
367
368
# In[ ]:
369
370
371
372
373