📚 The CoCalc Library - books, templates and other resources
License: OTHER
1# coding: utf-823# # Importing modules, setting options and defining custom functions for use in other worksheets4# To import into another worksheet:5#6# ```7# fun_include_ipynb('Worksheet_setup')8# ```9# or10# ```11# load('Worksheet_setup.sage')12# ```13# 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:14#15# ```16# sage --sh17# pip install entrypoints18# pip install configparser19# ```20#2122# In[1]:2324get_ipython().magic(u'matplotlib inline')25import numpy as np # for data array operations26import pylab # for plotting27import json # for reading notebook metadata2829list_plot.options["frame"]=True30list_plot.options["axes"]=False31plot.options["frame"]=True32plot.options["axes"]=False3334try:35for s in units.amount_of_substance.trait_names():36globals()[s] = getattr(units.amount_of_substance,s)37for s in units.energy.trait_names():38globals()[s] = getattr(units.energy,s)39for s in units.length.trait_names():40globals()[s] = getattr(units.length,s)41for s in units.mass.trait_names():42globals()[s] = getattr(units.mass,s)43for s in units.pressure.trait_names():44globals()[s] = getattr(units.pressure,s)45for s in units.temperature.trait_names():46globals()[s] = getattr(units.temperature,s)47for s in units.time.trait_names():48globals()[s] = getattr(units.time,s)49for s in units.power.trait_names():50globals()[s] = getattr(units.power,s)51except: # in newer versions of sage, need to use _tab_completion() instead of trait_names()52for s in units.amount_of_substance._tab_completion():53globals()[s] = getattr(units.amount_of_substance,s)54for s in units.energy._tab_completion():55globals()[s] = getattr(units.energy,s)56for s in units.length._tab_completion():57globals()[s] = getattr(units.length,s)58for s in units.mass._tab_completion():59globals()[s] = getattr(units.mass,s)60for s in units.pressure._tab_completion():61globals()[s] = getattr(units.pressure,s)62for s in units.temperature._tab_completion():63globals()[s] = getattr(units.temperature,s)64for s in units.time._tab_completion():65globals()[s] = getattr(units.time,s)66for s in units.power._tab_completion():67globals()[s] = getattr(units.power,s)686970udict = {}71cdict = {}72docdict = {}73dict_latex = {}74dict_domain = {}75dict_vars ={}767778def var2(name, doc='', units=1, domain1='real', latexname='', value = False):79'''80Creates a symbolic variable in the given domain (standard:'real') and with the given81latexname. Further, it adds the string doc to docdict, the units to udict and the value82to cdict. All entries are optional except for name. Note that the information passed as83domain1 is saved as an assumption, e.g. 'a is read'. All assumptions can be viewed as a84list, using the command assumptions().85Usage example:86sage: var2('x', 'Distance' , units=meter, domain1 = 'positive', latexname = 'x_{1-2}', value = 1.0)87'''88if len(latexname)>0:89z = var(name,domain = domain1,latex_name = latexname)90else:91z = var(name,domain = domain1)92var1 = eval(name)93dict_domain[var1] = domain194dict_latex[var1] = var1._latex_()95docdict[var1] = doc96udict[var1] = units97dict_vars[var1] = {'doc': doc, 'units': units, 'domain1': domain1, 'latexname': latexname, 'value': value}98if value:99cdict[var1] = value100return z101102def fun_loadvars(vardict = False):103'''104Loads all information related to symbolic variables defined using var2.105Usage example:106sage: allvars = fun_loadvars()107'''108if vardict:109variables = vardict.keys()110for var1 in variables:111var2(str(var1), doc = vardict[var1]['doc'], units = vardict[var1]['units'], domain1 = vardict[var1]['domain1'], latexname = vardict[var1]['latexname'], value = vardict[var1]['value'])112113else:114variables = docdict.keys()115for var1 in variables:116if var1 in cdict.keys():117var2(str(var1), doc=docdict[var1], units=udict[var1], domain1 = dict_domain[var1], latexname=dict_latex[var1], value=cdict[var1])118else:119var2(str(var1), doc=docdict[var1], units=udict[var1], domain1 = dict_domain[var1], latexname=dict_latex[var1])120121# Workaround from http://ask.sagemath.org/question/10260/convert-derived-si-units-to-base-units/122def convert(expr):123op = expr.operator()124ops = expr.operands()125if op:126if len(ops) == 2:127return op(*map(convert, ops))128else:129return op(convert(ops[0]), reduce(op, map(convert, ops[1:])))130else:131return expr.convert() if hasattr(expr, 'convert') else expr132133def units_check(eq, sfull = True):134'''135Checks whether all arguments are keys in udict and returns simplified units136'''137global udict, dict_units138udict1 = {}139# Need to multiply units with variable, so that we can devide by the symbolic equation later:140for key1 in udict.keys():141udict1[key1] = key1*udict[key1]142for blah in eq.arguments():143udict[blah]144eq.show()145if sfull:146return convert(eq.subs(udict1)/eq).simplify_full()147else:148return convert(eq.subs(udict1)/eq)149150def fun_units_formatted(variable):151'''152Returns units of variable expanded to exponential notation.153154'''155global udict, subsdict156units1 = (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] = 1157facs = units1.factor_list()158str1 = ''159for term1 in facs:160op1 = term1[1]161if op1==1:162str1 = str(term1[0]) + ' ' + str1163if op1!=1:164str1 = str1 +' ' + str(term1[0])165str1 = str1 + '$^{' + str(op1) + '}$ '166return str1167168169170def plot_fit(xdata, ydata, model, initial_guess = None, parameters = None, variables = None):171'''Fits the parameters of model to lists of xdata and ydata and plots the results172Example:173#linear regression through origin174var('x m')175model(x) = m*x176plot_fit(xdata,ydata,model)177'''178data = zip(xdata,ydata)179xdata1 = vector(xdata)180ydata1 = vector(ydata)181p1 = find_fit(data, model,solution_dict=True)182pkeys = p1.keys()183p2 = {}184for i in pkeys: p2[i] = n(p1[i],digits=3)185fitvals = vector([n(model(x1).subs(p1)) for x1 in xdata])186# root mean square deviation187rmsd = sqrt(mean(ydata1 - fitvals)^2)188nrmsd = rmsd/(max(ydata) - min(ydata))189blah = text("y="+str(model(x).subs(p2)),(0,0),fontsize=10,rgbcolor=(1,0,0))190print "y="+str(model(x).subs(p2))191print "NRMSD = "+str(n(nrmsd,digits=5))192lentext = blah.xmax() - blah.xmin()193# plot194P = list_plot(data, frame=True, axes = False, faceted=True, color = "white")195P += 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)))196return P197198def dict_print(vdict1, list_names = None):199dtype1 = [('name', 'S10'), ('val', object)]200vdict2 = vdict1.copy()201if list_names:202vdict2 = {}203for name1 in list_names:204vdict2[name1] = vdict1[name1]205list1 = np.array(vdict2.items(), dtype = dtype1)206list2 = np.sort(list1,order = 'name')207for k, v in list2:208print "{:<15} {:<15}".format(k,v)209210def fun_dict_print(vdict1):211dtype1 = [('name', 'S10'), ('val', object)]212list1 = np.array(vdict1.items(), dtype = dtype1)213list2 = np.sort(list1,order = 'name')214for k, v in list2:215print "{:<15} {:<15}".format(k,v)216217def fun_dict(dict1,dict2):218'''219Updates all entries of dict1 with entries co-occurring in dict2220and returns the udated dict1.221'''222dict1.update(dict2)223return dict1224225def fun_comp_array(expr1, nparray):226"""227Returns list of values for expr1228corresponding to each row of nparray229where all arguments in expr1 are substituted230by the corresponding values in nparray.231"""232list_args = expr1.args()233return [expr1.subs(dict(zip(list_args, [nparray[str(dummy)][i] for dummy in list_args]))) for i in srange(len(nparray))]234235def fun_printvar(varname):236pstring = str(varname)+': ' + docdict[varname]237try:238value = cdict[varname]239pstring1 = pstring + ', ' + str(n(value, prec = 16)) + ' ' + str(udict[varname]/varname)240except: pstring1 = pstring + ', ' + str(udict[varname]/varname)241print pstring1242return243244def fun_eq(eq, sfull = True):245print units_check(eq)246return eq247248def fun_export_ipynb(worksheet, folder):249'''250Exports worksheet.ipynb to a .py or .sage depending on kernel.251Example:252fun_export_ipynb('Worksheet_setup', 'temp/')253Need to import json before using this function. Unless option output=True is given,254each line of text has a semicolon added in the .py file, preventing any output.255'''256str1 = 'jupyter nbconvert --to=python \'' + worksheet+'.ipynb\''257print str1258print 'Exporting specified worksheet to .py file...'259260try:261retcode = os.system(str1)262if retcode < 0:263print >>sys.stderr, "nbconvert was terminated by signal", -retcode264else:265print >>sys.stderr, "nbconvert returned", retcode266except OSError as e:267print >>sys.stderr, "Execution failed:", e268print >>sys.stderr, "Trying ipython nbconvert instead..."269str1 = 'ipython nbconvert --to script \'' + worksheet+'.ipynb\'' # for new version of python270try:271retcode = os.system(str1)272if retcode < 0:273print >>sys.stderr, "nbconvert was terminated by signal", -retcode274else:275print >>sys.stderr, "nbconvert returned", retcode276except OSError as e:277print >>sys.stderr, "Execution failed:", e278279str1 = worksheet + '.py'280281print 'Checking if specified ipynb file was run with sage kernel...'282with open(worksheet+'.ipynb') as data_file:283data = json.load(data_file)284285if data['metadata']['kernelspec']['name'][0:4] == 'sage':286print 'Renaming .py file to .sage if notebook kernel was sage (to avoid exponent error)'287str2 = folder + worksheet + '.sage'288os.rename(str1, str2)289290291def fun_include_ipynb(worksheet, del1 = True, output = True):292'''293Exports worksheet.ipynb to a sage file and loads it into current worksheet.294Example:295fun_include_ipynb('Worksheet_setup')296Need to import json before using this function. Unless option output=True is given,297each line of text has a semicolon added in the .py file, preventing any output.298'''299str1 = 'jupyter nbconvert --to=python \'' + worksheet+'.ipynb\''300print str1301print 'Exporting specified worksheet to .py file...'302303try:304retcode = os.system(str1)305if retcode < 0:306print >>sys.stderr, "nbconvert was terminated by signal", -retcode307else:308print >>sys.stderr, "nbconvert returned", retcode309except OSError as e:310print >>sys.stderr, "Execution failed:", e311print >>sys.stderr, "Trying ipython nbconvert instead..."312str1 = 'ipython nbconvert --to script \'' + worksheet+'.ipynb\'' # for new version of python313try:314retcode = os.system(str1)315if retcode < 0:316print >>sys.stderr, "nbconvert was terminated by signal", -retcode317else:318print >>sys.stderr, "nbconvert returned", retcode319except OSError as e:320print >>sys.stderr, "Execution failed:", e321322str1 = worksheet + '.py'323324print 'Checking if specified ipynb file was run with sage kernel...'325with open(worksheet+'.ipynb') as data_file:326data = json.load(data_file)327328if data['metadata']['kernelspec']['name'][0:4] == 'sage':329print 'Renaming .py file to .sage if notebook kernel was sage (to avoid exponent error)'330str2 = worksheet + '.sage'331os.rename(str1, str2)332str1 = str2333if output == False:334input_file = open(str1, "r")335str2 = '0_'+ str1336output_file = open(str2, "w")337for line in input_file:338line = line.strip() # remove line end marks339final = line+'\n'340if len(line)>0:341if line[-1] != ';':342final= line+';\n'343output_file.write(final)344input_file.close()345os.remove(str1)346output_file.close()347str1 = str2348349350print 'Loading file into current worksheet...'351load(str1)352if del1:353print 'Removing file generated above...'354os.remove(str1)355356357# 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:358#359# `load('temp/Worksheet_setup.sage')`360# 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.361362# In[2]:363364#fun_export_ipynb('Worksheet_setup', 'temp/')365366367# In[ ]:368369370371372373