def write2file(filename, string, verbosity=0): output = open(filename, 'w') output.write(string) output.write('\n') output.close() if verbosity > 0: mout.out("Line written to " + mcol.file + filename)
def showAll(verbosity=1): if (verbosity > 0): mout.out("showing all graphs"+" ... ", printScript=True, end='') plt.show() if (verbosity > 0): mout.out("Done.")
def closeAll(verbosity=1): if (verbosity > 0): mout.out("closing all graphs"+" ... ", printScript=True, end='') plt.close(fig='all') if (verbosity > 0): mout.out("Done.")
def hist2D(xdata, ydata, bins=10, xlab='x', ylab='y', title=None, filename=None, show=True, verbosity=2, density=False, printScript=False, xmin=None, xmax=None, ymin=None, ymax=None, dpi=100, figsize=[4.8, 6.4]): if (verbosity > 0): if title is not None: mout.out("graphing " + mcol.varName + title + mcol.clear + " ... ", printScript=printScript, end='') else: mout.out("graphing ... ", printScript=printScript, end='') many = any(isinstance(el, list) for el in ydata) assert not many if not any([thing is None for thing in [xmin, xmax, ymin, ymax]]): range = [[xmin, xmax], [ymin, ymax]] else: range = None graph, axis = plt.subplots(dpi=dpi, figsize=figsize) plt.hist2d(xdata, ydata, bins=bins, range=range, density=density) plt.xlabel(xlab) plt.ylabel(ylab) plt.suptitle(title) if show: plt.show() if filename is not None: if (verbosity > 0): mout.out("saving as " + mcol.file + filename + mcol.clear + " ... ", end='') plt.savefig(filename) plt.close() if (verbosity > 0): mout.out("Done.")
def array2file(filename, list_of_things, append=False, verbosity=1): if append: output = open(filename, 'a') else: output = open(filename, 'w') many = any(isinstance(el, list) for el in list_of_things) if many: counter = 0 for many_things in list_of_things: string = "" for thing in many_things: string += str(thing) string += " " output.write(string) output.write('\n') counter += 1 output.close() # mout.errorOut("Nested Lists Unsupported",fatal=True,code="mout.array2file") else: counter = 0 for thing in list_of_things: try: string = str(thing) except: mout.errorOut("Could not convert item to string.", code=counter, fatal=True) output.write(string) output.write('\n') counter += 1 output.close() if verbosity > 0: mout.out(str(counter) + " lines written to " + mcol.file + filename)
def hist1D(ydata, bins=10, xlab='x', ylab='y', title=None, filename=None, show=True, verbosity=2, density=False, printScript=False, range=None): if (verbosity > 0): if title is not None: mout.out("graphing " + mcol.varName + title + mcol.clear + " ... ", printScript=printScript, end='') else: mout.out("graphing ... ", printScript=printScript, end='') many = any(isinstance(el, list) for el in ydata) assert not many plt.hist(ydata, bins=bins, range=range, density=density) plt.xlabel(xlab) plt.ylabel(ylab) plt.suptitle(title) if show: plt.show() if filename is not None: if (verbosity > 0): mout.out("saving as " + mcol.file + filename + mcol.clear + " ... ", end='') plt.savefig(filename) plt.close() if (verbosity > 0): mout.out("Done.")
def fit(xdata, ydata, rank=0, verbosity=1, printScript=False, title="", fitMin=None, fitMax=None, precision=4, errorPrecision=2, xUnit="", yUnit="", dataFile=None): # if there are nested ydatas: many = any(isinstance(el, list) for el in ydata) if xdata is None: if many: xdata = [i for i in range(len(ydata[0]))] else: xdata = [i for i in range(len(ydata))] if title is None: title = "" # initialise arrays combined_xdata = [] combined_ydata = [] combined_data = [] # check if multiple ydata sets if not many: # if just one set of data for index, xpoint in enumerate(xdata): if fitMin is not None and xpoint < fitMin: continue if fitMax is not None and xpoint > fitMax: break combined_xdata.append(xpoint) combined_ydata.append(ydata[index]) else: # loop over ydata sets for data in ydata: for index, ypoint in enumerate(data): if fitMin is not None and xdata[index] < fitMin: continue if fitMax is not None and xdata[index] > fitMax: break combined_xdata.append(xdata[index]) combined_ydata.append(ypoint) # get the number of datapoints num_points = len(combined_ydata) # user output if verbosity > 0: mout.out("fitting " + mcol.varName + title + mcol.clear + " (rank " + str(rank) + ", " + str(num_points) + " points) " + mcol.clear + "...", printScript=printScript, end=' ') if fitMin is not None or fitMax is not None: mout.out("fitrange=[" + str(fitMin) + ":" + str(fitMax) + "]", printScript=False, end=' ') # the actual fitting: coeffs, variance = np.polyfit(combined_xdata, combined_ydata, rank, cov=True) # user output if verbosity > 0: mout.out("Done.") # get list of letters in the alphabet alphabet_string = string.ascii_uppercase # alphabet_string = string.ascii_lowercase alphabet_list = list(alphabet_string) # write out the function type: if verbosity > 1: mout.out(mcol.func + "f" + mcol.clear + "(" + mcol.arg + "x" + mcol.clear + ") = ", end='') for i in range(rank, -1, -1): if i == 0: x_string = " " elif i == 1: x_string = mcol.arg + "x" + mcol.clear + " + " else: x_string = mcol.arg + "x^" + str(i) + mcol.clear + " + " mout.out(mcol.varName + alphabet_list[rank - i] + x_string + mcol.clear, end='') mout.out("") # initialise arrays vals = [] errs = [] # process the coefficients for i in range(rank, -1, -1): # append the current coefficient vals.append(coeffs[i]) errs.append(np.sqrt(variance[i, i])) if yUnit != "" and xUnit != "": for i in range(rank, -1, -1): # write out the results unitString = yUnit if i == 1: unitString = unitString + "/(" + xUnit + ")" elif i > 1: unitString = unitString + "/(" + xUnit + "^" + str(i) + ")" mout.varOut(alphabet_list[rank - i], vals[i], unit=unitString, error=errs[i], valCol=mcol.result, precision=precision, errorPrecision=errorPrecision, printScript=printScript, dataFile=dataFile, verbosity=verbosity) # get the resulting fit function fit_func = np.poly1d(coeffs) if rank == 0: vals = vals[0] errs = errs[0] # return the necessary return vals, errs, fit_func
def graph2D(xdata, ydata, fitFunc=None, printScript=False, ytitles=None, fitTitle=None, style=None, filename=None, show=True, xmin=None, xmax=None, ymin=None, ymax=None, xlab='x', ylab='y', title=None, subtitle=None, verbosity=2, colour=None, yerrors=None, xerrors=None, alpha=1.0, xticrot=None, xticsize=None, xSci=False, ySci=False, xLog=False, yLog=False, xtics=None, ytics=None, dpi=100, figsize=[6.4, 4.8], bar_width=0.8, zeroaxis=False, points=None): # graph = plt.figure(dpi=dpi,figsize=figsize) graph, axis = plt.subplots(dpi=dpi, figsize=figsize) if (verbosity > 0): if title is not None: mout.out("graphing " + mcol.varName + title + mcol.clear + " ... ", printScript=printScript, end='') else: mout.out("graphing ... ", printScript=printScript, end='') y_many = any(isinstance(el, list) for el in ydata) if xdata is not None: x_many = any(isinstance(el, list) for el in xdata) else: x_many = False style_many = isinstance(style, list) if xdata is None: if y_many: xdata = [i for i in range(len(ydata[0]))] else: xdata = [i for i in range(len(ydata))] # plot the normal data if y_many: # ydata is a list of lists! if ytitles is not None: # for curve, label in zip(ydata,ytitles): for index, curve in enumerate(ydata): if x_many: this_xdata = xdata[index] else: this_xdata = xdata if style_many: this_style = style[index] else: this_style = style if ytitles[index] is None: label = "ydata[" + str(index) + "]" else: label = ytitles[index] if style is None: if colour is None or colour[index] is None: plt.plot(this_xdata, curve, label=label) else: plt.plot(this_xdata, curve, colour[index], label=label) elif this_style == "bar": if colour is None or colour[index] is None: plt.bar(this_xdata, curve, align='center', label=label, alpha=alpha) else: plt.bar(this_xdata, curve, align='center', label=label, color=colour[index], alpha=alpha) else: if colour is None or colour[index] is None: plt.plot(this_xdata, curve, this_style, label=label) else: plt.plot(this_xdata, curve, colour[index] + this_style, label=label) else: for index, curve in enumerate(ydata): if x_many: this_xdata = xdata[index] else: this_xdata = xdata if style_many: this_style = style[index] else: this_style = style if this_style is None: if colour is None or colour[index] is None: plt.plot(this_xdata, curve, label="ydata[" + str(index) + "]") else: plt.plot(this_xdata, curve, colour[index], label="ydata[" + str(index) + "]") elif this_style == "bar": if colour is None or colour[index] is None: plt.bar(this_xdata, curve, align='center', label="ydata[" + str(index) + "]", alpha=alpha) else: plt.bar(this_xdata, curve, colour[index], align='center', label="ydata[" + str(index) + "]", alpha=alpha) else: if colour is None or colour[index] is None: plt.plot(this_xdata, curve, this_style, label="ydata[" + str(index) + "]") else: plt.plot(this_xdata, curve, colour[index] + this_style, label="ydata[" + str(index) + "]") else: if ytitles is not None: label = ytitles print(label) else: label = None if colour is None: colour = "k" alpha = 0.5 # ydata is just a list! if label is not None: if style is None: plt.plot(xdata, ydata, colour, label=label) elif style == "bar": plt.bar(xdata, ydata, color=colour, label=label, align='center', alpha=alpha, width=bar_width) else: plt.plot(xdata, ydata, colour + style, label=label) else: if style is None: plt.plot(xdata, ydata, colour) elif style == "bar": plt.bar(xdata, ydata, color=colour, align='center', alpha=alpha, width=bar_width) else: plt.plot(xdata, ydata, colour + style) if xSci: plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 0)) if ySci: plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0)) # plot the yerrorbars if yerrors is not None: if y_many: for index, curve in enumerate(ydata): if yerrors[index] is not None: if style == "bar": this_colour = "k" if colour is None or colour[index] is None: this_colour = None else: this_colour = colour[index] if colour is None or colour[index] is None: plt.errorbar(xdata, curve, yerrors[index], fmt='none', capsize=3, capthick=2, color='C' + str(index)) else: plt.errorbar(xdata, curve, yerrors[index], fmt='none', capsize=3, capthick=2, color=colour[index]) else: if style == "bar": colour = "k" if colour is None: plt.errorbar(xdata, ydata, yerrors, fmt='none', capsize=3, capthick=2, color='C' + str(index), colour="k") else: plt.errorbar(xdata, ydata, yerrors, fmt='none', color=colour, capsize=3, capthick=2) # plot the xerrorbars if xerrors is not None: if y_many: for index, curve in enumerate(ydata): if xerrors[index] is not None: if style == "bar": this_colour = "k" if colour is None or colour[index] is None: this_colour = None else: this_colour = colour[index] if colour is None or colour[index] is None: plt.errorbar(xdata, curve, xerr=xerrors[index], fmt='none', capsize=3, capthick=2, color='C' + str(index)) else: plt.errorbar(xdata, curve, xerr=xerrors[index], fmt='none', capsize=3, capthick=2, color=colour[index]) else: if style == "bar": colour = "k" if colour is None: plt.errorbar(xdata, ydata, xerr=xerrors, fmt='none', capsize=3, capthick=2, color='C' + str(index)) else: plt.errorbar(xdata, ydata, xerr=xerrors, fmt='none', color=colour, capsize=3, capthick=2) # plot extra points: if points is not None: y_many_points = any(isinstance(el, list) for el in points) if y_many_points: for pair in points: plt.plot(pair[0], pair[1], 'ko') else: plt.plot(points[0], points[1], 'ko') # plot the fitting function if x_many: this_xdata = xdata[0] else: this_xdata = xdata if fitFunc is not None: if fitTitle is None or fitTitle == "": if ytitles is None or fitTitle == "": plt.plot(this_xdata, fitFunc(this_xdata), 'k--') else: plt.plot(this_xdata, fitFunc(this_xdata), 'k--', label="f(x) " + str(fitFunc)) else: plt.plot(this_xdata, fitFunc(this_xdata), 'k--', label=fitTitle) plt.axis([xmin, xmax, ymin, ymax]) plt.xlabel(xlab) plt.ylabel(ylab) plt.suptitle(title) if zeroaxis: axis.axhline(y=0, color='k') axis.axvline(x=0, color='k') if xLog: plt.xscale('log') if yLog: plt.yscale('log') if xticrot is not None: plt.xticks(rotation=xticrot) if xticsize is not None: plt.xticks(fontsize=xticsize) if xtics is not None: start, end = axis.get_xlim() # print(start, end, xtics) xtics = round((end - start) / xtics) axis.xaxis.set_ticks(np.arange(start, end, xtics)) if ytics is not None: start, end = axis.get_xlim() ytics = round((end - start) / ytics) axis.yaxis.set_ticks(np.arange(start, end, ytics)) if subtitle is not None: plt.figtext(0.5, 0.91, subtitle, horizontalalignment='center') if y_many or ytitles is not None: plt.legend() if show: if (verbosity > 1): mout.out("showing ... ", end='') plt.show() if filename is not None: if (verbosity > 0): mout.out("saving as " + mcol.file + filename + mcol.clear + " ... ", end='') plt.savefig(filename) plt.close(fig=graph) if (verbosity > 0): mout.out("Done.")