def fitAndPlotLinear(x, y, rngt, ax, alfa, showPlot, labelAlfa, p): markers=["o", "s","D","^","d","h","p","o"] labelRange = ['low', 'med', 'high'] labelRange = labelRange+list([str(i) for i in rngt]) cm = plt.get_cmap('Set1') cm1 = plt.get_cmap('Set3') slopes = [] if showPlot: inf.smallerFont(ax, 8) ax.scatter(x, y, color=cm(abs(alfa/9)), alpha=0.75, edgecolors='none', marker=markers[alfa])#, "o", lw=0.5) arrow = dict(arrowstyle="-", connectionstyle="arc3", ls="--", color="gray") putLabels(ax, p.calc, alfa) for i in range(0,len(rngt)-1): a, b = fun.linearFit(x, y, rngt[i], rngt[i+1]) slopes.append(b) if showPlot: ax.semilogy(x[rngt[i]:rngt[i+1]+1], np.exp(fun.linear(x[rngt[i]:rngt[i+1]+1], a, b)), ls="-", color=cm1((i+abs(alfa)*3)/12)) xHalf = (x[rngt[i]]+x[rngt[i+1]]+1)/2 text = "{:03.3f}".format(-b) yHalf = np.exp(fun.linear(xHalf, a, b)) if alfa == -1: ax.text(xHalf, 2e1, r"$"+roman.toRoman(i+1)+r"$", color="gray", ha="right", va="center")#, transform=axarr[i].transAxes) xHalf *= 1.15 yHalf *= 5 text = r"$E_a="+text+r"$" bbox_props = dict(boxstyle="round", fc="w", ec="1", alpha=0.6) ax.text(xHalf,yHalf, text, color=cm(abs(alfa/9)), bbox=bbox_props, ha="center", va="center", size=6) if showPlot and alfa > -1: locator = LogLocator(100,[1e-1]) ax.yaxis.set_major_locator(locator) return slopes
def linear_act_forward(A, W, b, act): """ Implements the linear and activation functions of a single node Also, returns the original values for storage in cache """ if act == "sigmoid": Z, lin_cache = linear(A, W, b) A, act_cache = sigmoid(Z) elif act == "relu": Z, lin_cache = linear(A, W, b) A, act_cache = relu(Z) elif act == "softmax": Z, lin_cache = linear(A, W, b) A, act_cache = softmax(Z) cache = (lin_cache, act_cache) return A, cache
def get_value(self, onset): elapsed = (float(onset) + self.shift) % self.length if self.interp == 'linear': val = float(linear(elapsed / self.length, self.arr)) elif self.interp == 'nearest': val = float(nearest(elapsed / self.length, self.arr)) if self.bounds: ymin, ymax = self.bounds s, y, n = rescale(self.arr, ymin, ymax) val = (val - y) * s + n inv_qnt = 1.0 / self.quantize val = floor(val * inv_qnt) / inv_qnt return val
def fitAndPlotLinear(x, y, rngt, axis, alfa, showPlot, labelAlfa): labelRange = ['low', 'med', 'high'] labelRange = labelRange+list([str(i) for i in rngt]) cm = plt.get_cmap('Set1') slopes = [] if showPlot: axis.scatter(x, y, color=cm(abs(alfa/9)), alpha=0.75, edgecolors='none')#, "o", lw=0.5) for i in range(0,len(rngt)-1): a, b = fun.linearFit(x, y, rngt[i], rngt[i+1]) slopes.append(b) if showPlot: axis.semilogy(x[rngt[i]:rngt[i+1]+1], np.exp(fun.linear(x[rngt[i]:rngt[i+1]+1], a, b)), ls="-", label="{} {} {:03.3f} ".format(labelAlfa[alfa],labelRange[i],b)) if i == len(rngt)-2: if alfa == -1: axis.legend(prop={'size': 8}, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) else: axis.legend(prop={'size': 5.1}, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., ncol=2) return slopes
def localAvgAndPlotLinear(x, y, ax, alfa, sp, co2, first=False, total=False, verbose=False): showPlot = sp # and (alfa == 4 or alfa == 5) markers = ["o", "s", "D", "^", "d", "h", "p"] cm = plt.get_cmap('tab20') cm1 = plt.get_cmap('hsv') slopes = [] l = 1 if showPlot: #inf.smallerFont(ax, 8) y = [float("NaN") if v < 1e-50 else v for v in y] # remove almost 0 multiplicities ax.scatter(x, y, color=cm(abs((alfa % 20) / 20)), alpha=0.75, edgecolors=getMec(alfa), marker=markers[alfa % 7]) arrow = dict(arrowstyle="-", connectionstyle="arc3", ls="--", color="gray") a = alfa if first: a = 0 putLabels(ax, co2 + 1, a, total) # all s = allSlopes(x, y) if verbose and (any(np.isinf(s)) or any(np.isnan(s))): print("error fitting", alfa) for i in range(0, len(x)): a, b = fitA(x, y, s, i) slopes.append(b) if showPlot: ax.set_yscale("log") ax.plot(x[i - 1:i + 2], np.exp(fun.linear(x[i - 1:i + 2], a, b)), ls="-", color="gray", alpha=0) xHalf = x[i] text = "{:03.3f}".format(-b) yHalf = np.exp(fun.linear(xHalf, a, b)) if alfa == -1: xHalf *= 1 yHalf *= 5 text = r"$E_a=" + text + r"$" bbox_props = dict(boxstyle="round", fc="w", ec="1", alpha=0.6) if alfa == -10: ax.text(xHalf, yHalf, text, color=cm(abs(alfa / 9)), bbox=bbox_props, ha="center", va="center", size=6) return slopes
def forward(self, input): """Applies the forward pass by returning a linear function wx + b, where x is the input, w the weights and b the bias and saves the input for the backward pass to compute its computations.""" self.input = input return functions.linear(self.input, self.weight, self.bias)
def plot(ax, ax2, data, i, alp=1): marker = ["o", "s", "H", "D", "^", "d", "h", "p", "o"] cm = plt.get_cmap("Accent") alpha = 0.5 mew = 0 data = np.array(data) try: flux = data[0, 0] except IndexError: raise factor = data[0, 6] x = 1 / kb / data[:, 1] + np.log(flux**factor) lw = 3 lg1, = ax.plot(x, data[:, 3], label=r"$F=$" + fun.base10(flux), lw=lw, marker="", ls="-", mew=mew, ms=12, alpha=alpha, color=cm(i / 8)) ax.plot(x, data[:, 4], label=r"$N_h$" + fun.base10(flux), lw=lw + 1, ls="-.", mew=1, color=cm(i / 8), ms=7, alpha=1) ax2.plot(x, data[:, 3] / data[:, 4], label="aa", color=cm(i / 8), ls="", marker="o", ms=2, mec=cm(i / 8), mfc=cm(i / 8), alpha=alp) arrow = dict(arrowstyle="->", connectionstyle="arc3", ls="-", color=cm(i / 8)) if str(flux)[0] == "5": ax.annotate(fun.base10(flux), xy=(x[2], data[:, 4][2]), color=cm(i / 8), xytext=(0.9, 0.52 - 0.05 * i), textcoords="axes fraction", arrowprops=arrow) if flux == 5e4: #Fit rngt = inf.defineRanges("AgUc", "simple", data[:, 1]) for i in range(len(rngt) - 2, -1, -1): y = data[:, 4] a, b = fun.linearFit(x, y, rngt[i], rngt[i + 1]) ax.semilogy(x[rngt[i]:rngt[i + 1] + 1], np.exp(fun.linear(x[rngt[i]:rngt[i + 1] + 1], a, b)), ls="-", color="lightgray", zorder=+200) xHalf = (x[rngt[i]] + x[rngt[i + 1]] + 1) / 2 text = "{:03.3f}".format(-b) yHalf = np.exp(fun.linear(xHalf, a, b)) * 10 text = r"$" + text + r"$" ax.text(xHalf, yHalf, text, color="black", ha="center", va="center", size=10, zorder=+400) i = 0 # print "interpolation" to the rest of lower x values ax.semilogy(x[0:rngt[i + 1] + 1], np.exp(fun.linear(x[0:rngt[i + 1] + 1], a, b)), ls=":", color="lightgray", zorder=+300) #Fit f for i in range(len(rngt) - 2, -1, -1): y = data[:, 3] / data[:, 4] a, b = fun.linearFit(x, y, rngt[i], rngt[i + 1]) ax2.plot(x[rngt[i]:rngt[i + 1] + 1], np.exp(fun.linear(x[rngt[i]:rngt[i + 1] + 1], a, b)), ls="-", color="lightgray", zorder=+200) xHalf = (x[rngt[i]] + x[rngt[i + 1]] + 1) / 2 text = "{:03.3f}".format(-b) yHalf = np.exp(fun.linear(xHalf, a, b)) * 1.02 text = r"$" + text + r"$" ax2.text(xHalf, yHalf, text, color="gray", ha="center", va="center", size=10, zorder=+400) i = 0 # print "interpolation" to the rest of lower x values ax2.plot(x[0:rngt[i + 1] + 1], np.exp(fun.linear(x[0:rngt[i + 1] + 1], a, b)), ls=":", color="lightgray", zorder=+300) if flux == 3.5e0: rngt = inf.defineRanges("basic", "simple", data[:, 1]) for i in range(len(rngt) - 2, -1, -1): #reverse iteration y = data[:, 4] a, b = fun.linearFit(x, y, rngt[i], rngt[i + 1]) ax.semilogy(x[rngt[i]:rngt[i + 1] + 1], np.exp(fun.linear(x[rngt[i]:rngt[i + 1] + 1], a, b)), ls="-", color="lightgray", zorder=+200) xHalf = (x[rngt[i]] + x[rngt[i + 1]] + 1) / 2 text = "{:03.3f}".format(-b) yHalf = np.exp(fun.linear(xHalf, a, b)) * 10 text = r"$" + text + r"$" ax.text(xHalf, yHalf, text, color="black", ha="center", va="center", size=10, zorder=+400) # print "interpolation" to the rest of lower x values ax.semilogy(np.arange(120, 70, -1), np.exp(fun.linear(np.arange(120, 70, -1), a, b)), ls=":", color="lightgray", zorder=+300) #Fit f for i in range(len(rngt) - 2, -1, -1): #reverse iteration y = data[:, 3] / data[:, 4] a, b = fun.linearFit(x, y, rngt[i], rngt[i + 1]) ax2.plot(x[rngt[i]:rngt[i + 1] + 1], np.exp(fun.linear(x[rngt[i]:rngt[i + 1] + 1], a, b)), ls="-", color="lightgray", zorder=+200) xHalf = (x[rngt[i]] + x[rngt[i + 1]] + 1) / 2 text = "{:03.3f}".format(-b) yHalf = np.exp(fun.linear(xHalf, a, b)) * 1.02 text = r"$" + text + r"$" ax2.text(xHalf, yHalf, text, color="gray", ha="center", va="center", size=7, zorder=+400) return lg1
def forward(self, x): if self.unified: return linearUnified(self.k)(x, self.w, self.b) else: return linear(self.k)(x, self.w, self.b)
]) plt.errorbar(x, mag, yerr=err, ls='', marker='.', markersize=1, color='r', elinewidth=0.5, capsize=2.5, ecolor='r', label='Without Accept/Reject') # Linear fit best, covar = curve_fit(f.linear, x, mag, sigma=err, p0=(0.375, -1.0)) plt.plot(x, f.linear(x, *best), ls='--', c='red', linewidth=0.65) deg = len(mag) - len(best) #Here and below: degrees of freedom for the #reduced chi-squared #Saving the value of the parameter so that it can be used as an estimate in the following fit mag_no_AR = best[0] #Print the results of the fit print("WITHOUT ACCEPT/REJECT") print('Parameters: ', best) print("Parameters' Std Error: ", np.sqrt(np.diag(covar))) print('Covariance: ', covar) print('Reduced chi-squared: ', f.red_chi_sq(mag, f.linear(x, *best), err, dof=deg)) print('\n')
dist_lidar_data = [] for sensor in dist_lidar_sense: i = 0 data_buff = [] while i < 20: data_buff.append(str(functions.constant(100, 0))) i += 1 dist_lidar_data.append([sensor] + data_buff) ####linear pressure_brake_data = [] for sensor in pressure_brake_sense: i = 0 data_buff = [] while i < 20: data_buff.append(str(functions.linear(1, 0, i, 0.3))) i += 1 pressure_brake_data.append([sensor] + data_buff) thermo_brake_data = [] for sensor in thermo_brake_sense: i = 0 data_buff = [] while i < 20: data_buff.append(str(functions.linear(2, 0, i, 0.4))) i += 1 thermo_brake_data.append([sensor] + data_buff) ####exponential pressure_sense_data = []
import functions print("This is the test for the linear function") print("\n") #This is the test for the function of solving linear equations. print('x =', functions.linear()) print("\n") #This is the test for the function of solving quadratic equations. print("This is the test for the function of quadratic equations") print("\n") print(functions.quadratic()) #This is the test for graphing a 2D equation. functions.graph(4, 8, 50)
print("CORRELATORS") print("Parameters: ", best) print("Errors of the parameters: ", np.sqrt(np.diag(c))) print("Covariance: ", c) fig2 = plt.figure(2) plt.errorbar(N, t_metr, yerr=err_m, ls='', marker='.', markersize=1, elinewidth=0.5, capsize=2.5, mec='red', ecolor='red') best, c = curve_fit(f.linear, N, t_metr, p0=(1, 1), sigma=err_m) plt.plot(x, f.linear(x, *best), ls='-', color='b', linewidth=0.9) plt.grid(linestyle=':') plt.title("Behavior of the computational times of the Metropolis") plt.xlabel("N") plt.ylabel(r"$t_{metr}$ (s)") print("\nMETROPOLIS") print("Parameters: ", best) print("Errors of the parameters: ", np.sqrt(np.diag(c))) print("Covariance: ", c) fig1.savefig("graphs/correlators_times.png", dpi=(200), bbox_inches='tight') fig2.savefig("graphs/metropolis_times.png", dpi=(200), bbox_inches='tight')