def extract_single_dimension(self, variable, t_max): print("Extracting variable '{}'.".format(variable.name)) if self.folders is None: self.get_folders() # noinspection PyUnusedLocal data = [[] for i in range(t_max)] for i in tqdm(self.stats.data["idx"]): results = Results(economy_folder=self.folders[i]) for t in range(t_max): data[t].append(results.data[variable.name][t]) print("Convert in array.") variable.data = dict() variable.data["mean"] = np.array( [np.mean(data[t]) for t in range(t_max)]) variable.data["std"] = np.array( [np.std(data[t]) for t in range(t_max)]) print("Write in pickle.") variable.write() print("Done.")
def drawC(ps, img, v=0, r=10): ps = np.array(ps) if ps.ndim == 1: ps = np.array([ps]) rrcc = [sk.draw.circle(p[0], p[1], r) for p in ps] rr, cc = [rr for rr, cc in rrcc], [cc for rr, cc in rrcc] rr, cc = np.array(reduce(np.append, rr)), np.array(reduce(np.append, cc)) rr, cc = setMaxMin(rr, img.shape[0], 0), setMaxMin(cc, img.shape[1], 0) img[rr, cc] = v
def ek(alpha, betas): ca = np.cos(alpha) sa = np.sin(alpha) cbs = np.cos(betas) sbs = np.sin(betas) return np.array([[ca * cbs, -sbs, sa * cbs], [ca * sbs, cbs, sa * sbs], [-sa, 0, ca]])
def rK(lK, beta): cb = np.cos(beta) sb = np.sin(beta) rKx = cb * lK rKy = 0 rKz = sb * lK return np.array([rKx, rKy, rKz])
def reflection(xvals, p): #position=p[0]; intensity=p[1]; slit=p[2]; stth=p[3]; background=p[4]; thickness=p[5]; absorption=p[6] x0 = p[0] i0 = p[1] w = p[2] theta = p[3] ib = p[4] thick = p[5] u = p[6] th = np.deg2rad(theta) p0 = w * np.sin(th) / np.sin(2 * th) out = [] for x in xvals: if x < (x0 - p0): val = ib elif ((x >= (x0 - p0)) and (x < x0)): val = i0 * ((x - x0 + p0) / u) - i0 * (np.sin(th) / (2 * u * u)) * (1 - np.exp( (-2 * u / np.sin(th)) * (x - x0 + p0))) + ib elif ((x >= x0) and (x < (x0 + p0))): val = i0 * (np.sin(th) / (2 * u * u)) * (np.exp( (-2 * u / np.sin(th)) * (x - x0 + p0)) - 2 * np.exp( (-2 * u / np.sin(th)) * (x - x0)) + 1) + i0 * ((x0 + p0 - x) / u) + ib elif (x >= (x0 + p0)): val = i0 * np.sin(th) / ( 2 * u * u) * (np.exp(-2 * u * (x - x0 + p0) / np.sin(th)) - 2 * np.exp(-2 * u * (x - x0) / np.sin(th)) + np.exp(-2 * u * (x - x0 - p0) / np.sin(th))) + ib out = out + [val] return np.array(out)
def orthogonal_proj(zfront, zback): a = (zfront + zback) / (zfront - zback) b = -2 * (zfront * zback) / (zfront - zback) # -0.0001 added for numerical stability as suggested in: # http://stackoverflow.com/questions/23840756 return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, -0.0001, zback]])
def rB(R, omegat): cot = np.cos(np.radians(omegat)) sot = np.sin(np.radians(omegat)) rBx = cot * R rBy = sot * R rBz = 0 return np.array([rBx, rBy, rBz])
def walldirect(xvals, p, mode='eval'): """ From Wang et al. """ try: if mode == 'eval': out = wall(xvals, p) True elif mode == 'params': #out = ['cent', 'sigma', 'amp', 'const', 'slope'] out = [ 'position', 'intensity', 'slit', 'theta', 'background', 'thickness', 'absorption' ] elif mode == 'name': out = "Wall_Direct" elif mode == 'guess': xmin, xmax, ymin, ymax = [ xvals.min(), xvals.max(), p.min(), p.max() ] out = [ xmin + (xmax - xmin) / 2.0, ymax - ymin, (xmax - xmin) / 6.0, 45.0, ymin, (xmax - xmin) / 3.0, 0.01 ] True else: out = [] except: out = np.array([0] * len(p)) return out
def drawArc(self, centerxy, startxy, endxy): v1 = np.array([startxy[0] - centerxy[0], startxy[1] - centerxy[1]]) v2 = np.array([endxy[0] - centerxy[0], endxy[1] - centerxy[1]]) cos夹角 = (v1[0] * v2[0] + v1[1] * v2[1]) / (np.sqrt(v1.dot(v1)) * np.sqrt(v2.dot(v2))) angle_between = np.arccos(cos夹角) radius = np.sqrt(v1.dot(v1)) angle_start = np.arctan2(v1[1], v1[0]) angle_end = angle_start + angle_between self.ctx.move_to(startxy[0], startxy[1]) self.ctx.arc(centerxy[0], centerxy[1], radius, angle_start, angle_end) # self.ctx.arc_negative(centerxy[0], centerxy[1], radius, angle_start, angle_end) return []
def voigt(x, p, mode='eval'): """Pearson Type VII From Hutchings et al. 2005. Introduction to the characterisation of residual stress by neutron diffraction.2005. Page 160 Function: :math:`f(x) = k + m*x + p_2 \exp\left(\\frac{-(x - p_0)^2}{2p_1^2}\\right)` """ try: if mode == 'eval': #cent=p[0];wid=p[1];amp=p[2];const=p[3];slope=p[4] x0 = p[0] ux = p[1] H0 = p[2] const = p[3] slope = p[4] m = p[5] out = H0 * (1 + (x - x0)**2.0 / ((1.0 / m) * (0.5 * ux)**2))**-(1.0 / m) + const + slope * x elif mode == 'params': out = ['cent', 'sigma', 'amp', 'const', 'slope', 'shape'] elif mode == 'name': out = "Voigt" elif mode == 'guess': g = fitfuncs.peakguess(x, p) out = [g[0], g[1], g[3], g[5], g[4], 0.5] else: out = [] except: out = [0, 0, 0, 0, 0, 0] return np.array(out)
def transmissionreverse(xvals, p, mode='eval'): """ From Brand et al. """ try: if mode == 'eval': xvals = xvals * -1.0 prms = p.copy() prms[0] = -prms[0] out = transmission(xvals, prms) True elif mode == 'params': #out = ['cent', 'sigma', 'amp', 'const', 'slope'] out = [ 'position', 'intensity', 'slit', 'theta', 'background', 'thickness', 'absorption' ] elif mode == 'name': out = "Transmission_Reverse" elif mode == 'guess': xmin, xmax, ymin, ymax = [ xvals.min(), xvals.max(), p.min(), p.max() ] out = [ xmin + (xmax - xmin) / 2.0, ymax - ymin, (xmax - xmin) / 3.0, 45.0, ymin, 0.0, 0.01 ] True else: out = [] except: out = np.array([0] * len(p)) return out
def getSkeletonPositions(player): l = [getXyzw(player.SkeletonPositions[idd]) for idd in range(20)]+\ [getXyzw(player.get_position())] sp = np.array(l) sp[-1, -1] = 0 x = np.mean(sp[[jo.shoulderCenter, jo.hipCenter, jo.spine]], 0) sp[:-1] -= x return sp
def Marzmean(lK, Rg, alpha, betas, beta, delta): pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi]) omegat = np.arange(0, 360, 1) alpha, betas = orientation(lK, Rg, alpha, betas, beta, delta, omegat, pos) return alpha, np.mean( Marzsum(lK, Rg, alpha, betas, beta, delta, omegat, pos)), Ftrminmax(lK, Rg, alpha, betas, beta, delta, omegat, pos)
def Marzmean(lK, Rg, alpha, betas, beta, delta): pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi]) omegat = np.arange(0, 360, 1) a, b = orientation(lK, Rg, alpha, betas, beta, delta, omegat, pos) alpha = a betas = b Ma = np.mean(Marzsum(lK, Rg, a, b, beta, delta, omegat, pos)) Mg = np.mean(Marzsum(lK, Rg, a, b, beta, delta, omegat, pos)) return alpha, betas, Ma, Mg
def getYx(player, img): xy = [ skeleton_to_depth_image(sp, img.shape[1], img.shape[0]) for sp in player.SkeletonPositions ] yx = np.array(xy)[..., [1, 0]].astype(int) setMaxMin(yx[:, 0], VIDEO_WINSIZE[1], 0) setMaxMin(yx[:, 1], VIDEO_WINSIZE[0], 0) return yx
def show_prediction_result(image, label_image, clf): size = (8, 8) plt.figure(figsize=(15, 10)) plt.imshow(image, cmap='gray_r') candidates = [] predictions = [] for region in regionprops(label_image): # skip small images # if region.area < 100: # continue # draw rectangle around segmented coins minr, minc, maxr, maxc = region.bbox # make regions square maxwidth = np.max([maxr - minr, maxc - minc]) minr, maxr = int(0.5 * ((maxr + minr) - maxwidth)) - 3, int(0.5 * ((maxr + minr) + maxwidth)) + 3 minc, maxc = int(0.5 * ((maxc + minc) - maxwidth)) - 3, int(0.5 * ((maxc + minc) + maxwidth)) + 3 rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2, alpha=0.2) plt.gca().add_patch(rect) # predict digit candidate = image[minr:maxr, minc:maxc] candidate = np.array(imresize(candidate, size), dtype=float) # invert # candidate = np.max(candidate) - candidate # print im # rescale to 16 in integer candidate = (candidate - np.min(candidate)) if np.max(candidate) == 0: continue candidate /= np.max(candidate) candidate[candidate < 0.2] = 0.0 candidate *= 16 candidate = np.array(candidate, dtype=int) prediction = clf.predict(candidate.reshape(-1)) candidates.append(candidate) predictions.append(prediction) plt.text(minc - 10, minr - 10, "{}".format(prediction), fontsize=50) plt.xticks([], []) plt.yticks([], []) plt.tight_layout() plt.show() return candidates, predictions
def plot_ui_curve(ax1, ax2, *arg, **kwarg): u_data = voltage_data[kwarg['label']] i_data = current_data[kwarg['label']] ax1.plot(i_data, u_data, *arg, **kwarg) ax1.set_xlabel('Current [A]') ax1.set_ylabel('Voltage [V]') voltage_to_compensate = np.array(u_data) - np.array(i_data) * R ax2.plot(i_data, voltage_to_compensate, *arg, **kwarg) ax2.set_xlabel('Current [A]') ax2.set_ylabel('Voltage [V]') print('#define LENGTH_OF_LUT ', len(i_data)) print('REAL lut_current_ctrl[LENGTH_OF_LUT] = {' + ', '.join(f'{el:g}' for el in i_data[::-1]) + '};') print('REAL lut_voltage_ctrl[LENGTH_OF_LUT] = {' + ', '.join(f'{el:g}' for el in voltage_to_compensate[::-1]) + '};') print()
def wall(xvals, parms): #position=p[0]; intensity=p[1]; slit=p[2]; stth=p[3]; background=p[4]; thickness=p[5]; absorption=p[6] midpoint = parms[0] i0 = parms[1] w = parms[2] theta = parms[3] ib = parms[4] thick = parms[5] u = parms[6] midpoint = parms[0] x0 = midpoint - thick / 2.0 th = np.deg2rad(theta) p = w * np.cos(th) Atot = w * w / np.sin(2.0 * th) out = [] for x in xvals: if (x <= (x0 - p)): val = ib #elif ((x0-p) >= (x-thick)) and ((x0+p) >= x): #Gauge volume is smaller than thickness if ((x > (x0 - p)) and (x0 - p > (x - thick)) and (x <= x0)): val = ib + i0 * ((x - (x0 - p)) * ((x - (x0 - p)) * np.tan(th))) / Atot elif ((x > x0) and (x <= x0 + p) and (x0 - p > (x - thick))): val = ib + i0 * (Atot - (x0 + p - x) * (x0 + p - x) * np.tan(th)) / Atot elif (x0 - p > (x - thick) and (x0 + p < x)): #Gauge volume is smaller than thickness val = ib + i0 elif (x0 - p < (x - thick) and (x0 + p > x)): #Gauge volume is larger than thickness A2 = (x0 + p - x) * (x0 + p - x) * np.tan(th) A3 = ((x - thick) - (x0 - p)) * (((x - thick) - (x0 - p)) * np.tan(th)) val = ib + i0 * (Atot - A2 - A3) / Atot elif ((x0 - p) < (x - thick)) and ((x0 + p) < x) and (x0 >= (x - thick)): A3 = ((x - thick) - (x0 - p)) * (((x - thick) - (x0 - p)) * np.tan(th)) val = ib + i0 * (Atot - A3) / Atot elif (x0 < (x - thick) and ((x0 + p >= (x - thick)))): A2 = (x0 + p - (x - thick)) * ((x0 + p) - (x - thick)) * np.tan(th) val = ib + i0 * (A2 / Atot) elif (x0 + p < (x - thick)): val = ib #elif ((x0-p) < (x-thick)) and ((x0+p) >= x): #Gauge volume is larger than thickness # A2 = (x0+p-x)*(x0+p-x)*np.tan(th) # A3 = ((x-thick)-(x0-p))*(((x-thick)-(x0-p))*np.tan(th)) # val = ib + i0*(Atot-A2-A3)/Atot out = out + [val] return np.array(out)
def rA(lK, R, alpha, betas, beta, delta, omegat): cb = np.cos(beta) sb = np.sin(beta) ca = np.cos(alpha) sa = np.sin(alpha) cbs = np.cos(betas) sbs = np.sin(betas) cotd = np.cos(np.radians(omegat) + delta) sotd = np.sin(np.radians(omegat) + delta) rAx = (ca * cbs * cotd - sbs * sotd) * R + cb * lK rAy = (ca * sbs * cotd + cbs * sotd) * R rAz = (-sa * cotd) * R + sb * lK return np.array([rAx, rAy, rAz])
def __init__(self,colorname='red'): self.id=1 self.start = self.stop = int(0) self.position = self.fwhm = self.intensity = self.background = self.intensity_sum = self.intensity_area = self.counts = self.errustrain = float(0.0) self.bgndfitparms = [0,0] self.bgndyvals = np.array([]) #will contain the y values of the calculated background over the fit range self.position_fix = self.fwhm_fix = self.intensity_fix = self.background_fix = False self.position_stdev = self.fwhm_stdev = self.intensity_stdev = self.background_stdev = float(0.0) self.chi2 = self.r2 = self.time = float(0.0) self.position_valid = self.fwhm_valid = self.intensity_valid = self.background_valid = self.chi2_valid = self.r2_valid = True #Red for invalid, Black for valid self.niter = int(0) self.color = colorname self.line = Line2D([], [], color = colorname, antialiased = False, alpha = 0.5, linestyle=":") self.fittedline = Line2D([], [], color = colorname, antialiased = False) self.bgrngline = Line2D([], [], color = colorname, antialiased = False, alpha = 0.5, linestyle=" ", marker='.', markersize=2.5) self.bgline = Line2D([], [], color = colorname, antialiased = False, alpha = 0.5, linewidth = 0.5, linestyle="-") self.diffline = Line2D([], [], color = colorname, antialiased = False, alpha = 0.9, linewidth = 0.2)
def transformCoords(self, points, deg_addTheta=0): # This function takes in an nx2 array of coordinates of the form # [x,y] and returns rotated and translated coordinates. The # translation and rotation are described by obj.anchor_xy and # obj.theta. The optional "addTheta" argument adds an # additional angle of "addTheta" to the obj.theta attribute. transCoords = [] for point in points: # 旋转方向和eMach是反一下的,我是Park变换。 cosT = np.cos(self.theta + (deg_addTheta * np.pi / 180)) sinT = np.sin(self.theta + (deg_addTheta * np.pi / 180)) transCoords.append([ points[0] * cosT + points[1] * sinT, points[0] * -sinT + points[1] * cosT ]) return np.array(transCoords)
def wallzscan(xvals, p): #position=p[0]; intensity=p[1]; slit=p[2]; stth=p[3]; background=p[4]; thickness=p[5]; absorption=p[6] midpoint = p[0] i0 = p[1] w = p[2] theta = p[3] ib = p[4] thick = p[5] u = p[6] p0 = w / 2.0 x0 = midpoint - thick / 2.0 out = [] if w > thick: maxbeam = thick else: maxbeam = w for x in xvals: x1 = x x2 = x - thick if (x1 <= (x0 - p0)) and (x1 <= (x0 + p0)) and (x2 <= (x0 - p0)) and (x2 <= (x0 + p0)): val = ib elif ((x0 - p0) <= x1) and ( (x0 - p0) >= x2) and (x0 + p0) >= x1 and (x0 + p0) >= x2: val = ib + i0 * (x1 - (x0 - p0)) / maxbeam elif (x0 - p0) >= x2 and (x0 + p0) <= x1 and (x0 - p0) <= x1 and ( x0 + p0) >= x2: val = ib + i0 elif (x0 - p0) <= x2 and (x0 + p0) >= x2 and (x0 + p0 <= x1) and (x0 - p0) <= x1: val = ib + i0 * ((x0 + p0) - x2) / maxbeam elif (x0 - p0) <= x2 and (x0 + p0) <= x2 and (x0 - p0) <= x1 and ( x0 + p0) <= x1: val = ib elif (x0 - p0) <= x2 and (x0 + p0) >= x1 and (x0 - p0) <= x1 and ( x0 + p0) >= x2: val = ib + i0 out = out + [val] return np.array(out)
def transmission(xvals, parms): #position=p[0]; intensity=p[1]; slit=p[2]; stth=p[3]; background=p[4]; thickness=p[5]; absorption=p[6] #x0=p[0]; i0=p[1]; w=p[2]; theta=p[3]; ib=p[4]; thick=p[5]; u=p[6]; #th = np.deg2rad(theta) #p0 = w * np.cos(th)/np.cos(2*th) #out = [] #for x in xvals: # if x < (x0 - p0): # val = ib # elif ((x>=x0-p0) and (x < x0)): # val = i0*(x-x0+p0)*(x-x0+p0)+ib # elif ((x>=x0) and (x<(x0+p0))): # val = i0*(2.0*p0*p0-(x0+p0-x)*(x0+p0-x))+ib # elif (x>=x0+p0): # val=2*i0*p0*p0 +ib # out = out + [val] x0 = parms[0] i0 = parms[1] w = parms[2] theta = parms[3] ib = parms[4] thick = parms[5] u = parms[6] th = np.deg2rad(theta) p = w * np.cos(th) Atot = w * w / np.sin(2.0 * th) out = [] for x in xvals: if (x <= (x0 - p)): val = ib elif ((x > (x0 - p)) and (x <= x0)): val = ib + i0 * ((x - (x0 - p)) * ((x - (x0 - p)) * np.tan(th))) / Atot elif ((x > x0) and (x <= x0 + p)): val = ib + i0 * (Atot - (x0 + p - x) * (x0 + p - x) * np.tan(th)) / Atot elif (x > x0 + p): val = ib + i0 out = out + [val] return np.array(out)
def zscan(xvals, p): #position=p[0]; intensity=p[1]; slit=p[2]; stth=p[3]; background=p[4]; thickness=p[5]; absorption=p[6] x0 = p[0] i0 = p[1] w = p[2] theta = p[3] ib = p[4] thick = p[5] u = p[6] p0 = w / 2.0 #b=p[4]; m=p[1]; a=p[2]; x0=p[0] #out = b+(m-b)/(1+np.exp(-a*(xvals-x0))) out = [] for x in xvals: if x < (x0 - p0): val = ib elif (x > (x0 - p0)) and (x < (x0 + p0)): val = ib + i0 * (x - (x0 - p0)) / (2 * p0) else: val = ib + i0 out = out + [val] return np.array(out)
def Gauss(x, p, mode='eval'): """Gaussian defined by amplitide Function: :math:`f(x) = k + m*x + p_2 \exp\left(\\frac{-(x - p_0)^2}{2p_1^2}\\right)` """ try: if mode == 'eval': cent = p[0] wid = p[1] amp = p[2] const = p[3] slope = p[4] #out = const + amp * np.exp(-1.0 * (x - cent)**2 / (2 * wid**2)) #Inserted the 0.5* because we want FWHM out, not HWHM #out = const + slope*x + amp * np.exp(-1.0 * (x - cent)**2 / (2 * (0.5*wid)**2)) conversion = 2.0 * np.sqrt( 2.0 * np.log(2) ) #Hutchings et al. Introduction to the characterisation of residual stress by neutron diffraction.2005. Page 159 #conversion = 2.0 out = const + slope * x + amp * np.exp(-1.0 * (x - cent)**2 / (2 * (wid / conversion)**2)) elif mode == 'params': out = ['cent', 'sigma', 'amp', 'const', 'slope'] elif mode == 'name': out = "Gaussian" elif mode == 'guess': g = fitfuncs.peakguess(x, p) out = [g[0], g[1] / (4 * np.log(2)), g[3], g[4], g[5]] else: out = [] except: out = [0, 0, 0, 0, 0] return np.array(out)
def get_sharp_rate(done_exp): cap_list = [float(x[0]) for x in done_exp] return_list = [] base_cap = float(done_exp[0][0]) for i in range(len(cap_list)): if i == 0: return_list.append(float(1.00)) else: ri = (float(done_exp[i][0]) - float(done_exp[0][0])) / float( done_exp[0][0]) return_list.append(ri) std = float(np.array(return_list).std()) exp_portfolio = (float(done_exp[-1][0]) - float(done_exp[0][0])) / float( done_exp[0][0]) exp_norisk = 0.04 * (5.0 / 12.0) sharp_rate = (exp_portfolio - exp_norisk) / (std) return sharp_rate, std
def __new__(cls, array_like, culture): self = np.array(array_like).view(cls) return self
def __new__(cls, convictions): self = np.array(np.zeros(len(convictions), dtype=int)).view(cls) return self
def get_matrix_of_agents_convictions(self): return np.array([a.culture.convictions for a in self.agents])
def Marzmean0(lK, Rg, alpha, betas, beta, delta): pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi]) omegat = np.arange(0, 360, 1) return np.mean(Marzsum(lK, Rg, alpha, betas, beta, delta, omegat, pos))
from pylab import np with open('ML Sample Data/RL 1k/TIME/Gaussian F=0.400 DC=50 A=0.50 TIME [2019-01-18 13_58_52.56].csv') as f: arr = np.array([float(item) for item in f.readlines()]) print(arr)