def plot_function_and_solution(func, area, first_point, solution, meshgrid): fig = plt.figure(figsize=(14, 8)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122, projection="3d") fig.suptitle("My Function", size=24) # Color mesh ax1.set_axis_bgcolor("white") # ax1.pcolormesh(X, Y, Z, cmap=cm.jet, norm=LogNorm()) ax1.contour(*meshgrid, zdir='z', offset=0, stride=0.1, cmap=cm.coolwarm) ax1.scatter(*first_point, color="k") ax1.annotate('First Point', xy=first_point, xytext=(-0.5, 1.25), arrowprops=dict(facecolor='black', shrink=0.05)) ax1.scatter(solution[0], solution[1], color="g") ax1.annotate('Solution', xy=(solution[0], solution[1]), xytext=(-1, -3), arrowprops=dict(facecolor='blue', shrink=0.05)) # Surface plot ax2.set_axis_bgcolor("white") ax2.plot_surface(*meshgrid, norm = LogNorm(), cmap=cm.jet, linewidth=1) first_point_3d = (first_point[0], first_point[1], func(first_point)) ax2.view_init(azim=65, elev=25) ax2.scatter(*first_point_3d, color="k") xa, ya, _ = proj3d.proj_transform(first_point_3d[0], first_point_3d[1], first_point_3d[2], ax2.get_proj()) ax2.annotate("First Point", xy = (xa, ya), xytext = (20, 120), textcoords = 'offset points', ha = 'right', va = 'bottom', arrowprops=dict(facecolor='black', shrink=0.05)) ax2.scatter(*solution, color="k") xa, ya, _ = proj3d.proj_transform(solution[0], solution[1], solution[2], ax2.get_proj()) ax2.annotate("Solution", xy = (xa, ya), xytext = (0, 100), textcoords = 'offset points', ha = 'right', va = 'bottom', arrowprops=dict(facecolor='blue', shrink=0.05))
def update_position(e): x2, y2, _ = proj3d.proj_transform(xposition[0], yposition[0], zposition[0], ax.get_proj()) start_label.xy = x2,y2 start_label.update_positions(fig.canvas.renderer) x2, y2, _ = proj3d.proj_transform(xposition[len(xposition)-1], yposition[len(yposition)-1], zposition[len(zposition)-1], ax.get_proj()) end_label.xy = x2,y2 end_label.update_positions(fig.canvas.renderer) fig.canvas.draw()
def refresh(self): for l in self._labs: x, y, _ = proj3d.proj_transform(l[1][0], l[1][1], l[1][2], self.ax1.get_proj()) x2, y2, _ = proj3d.proj_transform(l[2][0], l[2][1], l[2][2], self.ax1.get_proj()) l[0].xytext = self._midp(x, y, x2, y2) for l in self._alabs: x, y, _ = proj3d.proj_transform(l[1][0], l[1][1], l[1][2], self.ax1.get_proj()) l[0].xytext = (x+0.002,y+0.002) self.canvas.draw()
def plot_surface(ax, m, start, goal, title): t1 = np.arange(181) t2 = np.arange(361) X, Y = np.meshgrid(t1, t2, indexing='ij') surf = ax.plot_surface(X, Y, m, cmap=cm.jet) ax.set_title(title) ax.set_xlabel('theta1') ax.set_ylabel('theta2') x, y, _ = proj3d.proj_transform(start[0],start[1],m[start[0], start[1]], ax.get_proj()) x2, y2, _ = proj3d.proj_transform(goal[0],goal[1],m[goal[0], goal[1]], ax.get_proj()) l1 = ax.annotate('start', xy=(x, y)) l2 = ax.annotate('goal', xy=(x2, y2))
def draw(self, renderer): #xs3d, ys3d, zs3d = self._verts3d for coords in self._verts3d: xs3d, ys3d, zs3d = coords[0], coords[1], coords[2] xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer)
def plot_emotions(emotions, X, Y, Z, plot_labels = True): emos = emotions import matplotlib matplotlib.use('TkAgg') from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(X, Y, Z) ax.set_xlabel('Serotonin') ax.set_ylabel('Noradrenaline') ax.set_zlabel('Dopamine') if plot_labels: labels = [] for i in range(len(X)): x2, y2, _ = proj3d.proj_transform(X[i],Y[i],Z[i], ax.get_proj()) label = plt.annotate( emos[i], xy = (x2, y2), xytext = (-5, 5), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.1', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) labels.append(label) def update_position(e): for i in range(len(X)): x2, y2, _ = proj3d.proj_transform(X[i],Y[i],Z[i], ax.get_proj()) labels[i].xy = (x2, y2) labels[i].update_positions(fig.canvas.renderer) fig.canvas.draw() fig.canvas.mpl_connect('button_release_event', update_position) plt.tight_layout() plt.show()
def annotatePlot(X, index, annotes, button): """Create popover label in 3d chart Args: X (np.array) - array of points, of shape (numPoints, 3) index (int) - index (into points array X) of item which should be printed Returns: None """ # If we have previously displayed another label, remove it first if hasattr(annotatePlot, 'label'): annotatePlot.label.remove() if button == 2: # Get data point from array of points X, at position index x2, y2, _ = proj3d.proj_transform(X[index, 0], X[index, 1], X[index, 2], ax.get_proj()) annote = annotes[index] annotatePlot.label = plt.annotate(annote, xy=(x2, y2), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')) # if we press another button (i.e. to pan the axis we need to create a dummy (blank) annotate # this is because the annotePlot still has an attribute (it has previously been called elif button != 2: annotatePlot.label = plt.annotate('', xy=(0, 0), xytext=(0, 0)) fig.canvas.draw()
def draw(self, renderer): with warnings.catch_warnings(): warnings.simplefilter("ignore") xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer)
def update_position(e): for a in range(len(all_position)): x2, y2, _ = proj3d.proj_transform(all_position[a][0],all_position[a][1],all_position[a][2], ax.get_proj()) all_label[a].xy = x2,y2 label.update_positions(fig.canvas.renderer) fig.canvas.draw()
def update_position(e): for i, x, y, z, l in zip(i_s, xs, ys, zs, labels): x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) l.xy = x2,y2 l.update_positions(fig.canvas.renderer) fig.canvas.draw()
def LabelEvent(self, GraphicsObject, PlotOptions): EventTypeFormatted = self.EventType if EventTypeFormatted == 'upwr_flyby': EventTypeFormatted = 'unpowered flyby' elif EventTypeFormatted == 'pwr_flyby': EventTypeFormatted = 'powered flyby' elif EventTypeFormatted == 'chem_burn': EventTypeFormatted = 'chemical burn' elif EventTypeFormatted == 'LT_rndzvs': EventTypeFormatted = 'LT rendezvous' elif EventTypeFormatted == 'begin_spiral': EventTypeFormatted = 'begin spiral' elif EventTypeFormatted == 'end_spiral': EventTypeFormatted = 'end spiral' description = EventTypeFormatted + '\n' + self.Location + '\n' + self.GregorianDate #for launches a C3 and DLA are needed if self.EventType == 'launch': description += '\nC3 = ' + "{0:.3f}".format(self.C3) + ' $km^2/s^2$' #add the LV to the description? description += '\nDLA = ' + "{0:.1f}".format(self.Declination) + '$^{\circ}$' #for non-launch departures only the C3 is needed if self.EventType == 'departure': description += '\nC3 = ' + "{0:.3f}".format(self.C3) + ' $km^2/s^2$' #for spirals output only the delta-v if self.EventType == 'begin_spiral' or self.EventType == 'end_spiral': description += '\n$\Delta v$ = ' + "{0:.3f}".format(self.DVmagorThrottle) + ' $km/s$' #for other events, output v-infinity and DLA if self.EventType == 'upwr_flyby' or self.EventType == 'pwr_flyby' or self.EventType == 'intercept' or self.EventType == 'interface' or self.EventType == 'insertion': description += '\n$v_\infty$ = ' + "{0:.3f}".format(math.sqrt(self.C3)) + ' $km/s$' description += '\nDEC = ' + "{0:.1f}".format(self.Declination) + '$^{\circ}$' #for flybys, altitude should be outputed if self.EventType == 'upwr_flyby' or self.EventType == 'pwr_flyby': description += '\naltitude = ' + "{0:.0f}".format(self.Altitude) + ' $km$' #for propulsive events, a deltaV is needed if self.EventType == 'departure' or self.EventType == 'pwr_flyby' or self.EventType == 'insertion' or self.EventType == 'chem_burn' or self.EventType == 'rendezvous': description += '\n$\Delta v$ = ' + "{0:.3f}".format(self.DVmagorThrottle) + ' $km/s$' #always append the spacecraft Mass description += '\nm = ' + "{0:.0f}".format(self.Mass) + ' $kg$' #draw the text #note, do not draw anything for chemical burns below 10 m/s if not (self.EventType == "chem_burn" and self.DVmagorThrottle < 0.001): x2D, y2D, _ = proj3d.proj_transform(self.SpacecraftState[0],self.SpacecraftState[1],self.SpacecraftState[2], GraphicsObject.get_proj()) self.eventlabel = plt.annotate(description, xycoords = 'data', xy = (x2D, y2D), xytext = (20, 20), textcoords = 'offset points', ha = 'left', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'white', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'), size=PlotOptions.FontSize) self.AnnotationHelper = self.eventlabel.draggable(use_blit=True) self.pcid = GraphicsObject.figure.canvas.mpl_connect('button_press_event', self.ClickAnnotation) self.rcid = GraphicsObject.figure.canvas.mpl_connect('button_release_event', self.ReleaseAnnotation)
def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) mp.FancyArrowPatch.draw(self, renderer)
def annotatedScatter3d(labels,xs,ys,zs): """3d scatter plot, sadly rotating breaks the association of dots and annotations""" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') sc = ax.scatter(xs,ys,zs) for txt, x, y, z in zip(labels, xs, ys, zs): x2, y2, _ = proj3d.proj_transform(x,y,z, ax.get_proj()) label = plt.annotate(txt, xy = (x2, y2))
def update_position(e): global fig global ax global labels_and_points for label, x, y, z in labels_and_points: x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) label.xy = x2,y2 label.update_positions(fig.canvas.renderer) fig.canvas.draw()
def update_position(e): print "In update" x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) for i in range(0, np.size(z)): if i % 800 == 0: labels[(i / 800)].xy = x2[i], y2[i] labels[(i / 800)].update_positions(fig.canvas.renderer) fig.canvas.draw()
def update_position(e): x2, y2, _ = proj3d.proj_transform(data3N[:, 0], data3N[:, 1], data3N[:, 2], ax.get_proj()) for i in range(len(data3N[:, 0])): label = Labels[i] label.xy = x2[i],y2[i] label.update_positions(fig.canvas.renderer) fig.canvas.draw()
def update_position(e): print('update') #Transform co-ordinates to get new 2D projection Tx, Ty, _ = proj3d.proj_transform(xp, yp, zp, ax.get_proj()) for i in range(len(xp)): label = label_list[i] label.xy = Tx[i],Ty[i] label.update_positions(fig.canvas.renderer) fig.canvas.draw() return
def flatten3DPoint(self, px, py, pz): """project a point in 3D space onto a 2D screen""" # convert 3D spave to 2D space x2, y2, _ = proj3d.proj_transform(px, py, pz, self.threeDAx.get_proj()) # convert 2d space to screen space [x2,y2] = self.threeDAx.transData.transform((x2, y2)) # adjust for image dimensions x2 = x2/self.twoDImgWidth y2 = y2/self.twoDImgHeight return [x2, y2]
def _load_residue(self, event): r = self._ligands[self.res_type.GetValue()] self.ax1.cla() self.ax1.mouse_init() self.ax1.set_frame_on(False) self.ax1.set_axis_off() for a in (self.ax1.w_xaxis, self.ax1.w_yaxis, self.ax1.w_zaxis): a.line.set_visible(False) a.pane.set_visible(False) a.set_major_locator(ticker.NullLocator()) self.ax1.scatter3D(r['c'][:,0], r['c'][:,1], r['c'][:,2], c=r['col'], s=400) m = max([max(r['c'][:,i])-min(r['c'][:,i]) for i in range(3)]) for i,ax in enumerate(['set_xlim', 'set_ylim', 'set_zlim']): mid = min(r['c'][:,i])+((max(r['c'][:,i]) - min(r['c'][:,i]))/2) getattr(self.ax1, ax)(mid-(m/2), mid+(m/2)) self._labs = [] self._alabs = [] for i,a in enumerate(r['at']): ac = r['c'][i] x2, y2, _ = proj3d.proj_transform(ac[0],ac[1],ac[2], self.ax1.get_proj()) for j,b in enumerate(r['at']): if a is not b: bc = r['c'][j] if a.distance(b) < 1.8: std = '' n = a.name.strip()+'-'+b.name.strip() if n in r['stdevs']: std = ' (' + str(r['stdevs'][n]) + ')' self.ax1.plot([ac[0], bc[0]], [ac[1], bc[1]], [ac[2], bc[2]], 'k-') x3, y3, _ = proj3d.proj_transform(bc[0],bc[1],bc[2], self.ax1.get_proj()) self._labs.append([self.ax1.annotate('%.2f' % a.distance(b) + std, xy=self._midp(x2,y2,x3,y3), size=6), ac, bc]) self._alabs.append([self.ax1.annotate(a.name.strip(), xy=(x2+0.002,y2+0.002), size=7), ac]) self.canvas.draw()
def update_position(e): print "From update position" #Transform co-ordinates to get new 2D projection tX, tY, _ = proj3d.proj_transform(dataX, dataY, dataZ, ax.get_proj()) for i in range(len(dataX)): label = labels[i] label.xy = tX[i],tY[i] label.update_positions(fig.canvas.renderer) fig.canvas.draw() return
def update_position(e): """ A callback handler to update positions of the labels projected into 2d space when the graph is rotated """ for k in LABELS_MAP: x1, y1, z1 = LABELS_MAP[k][0:3] x2, y2, _ = proj3d.proj_transform(x1, y1, z1, AXES.get_proj()) annotation = LABELS_MAP[k][3] annotation.xy = x2, y2 annotation.update_positions(FIG.canvas.renderer) FIG.canvas.draw()
def update_position(self, e): labels = self.labels for ii, c in enumerate(self.points): x_proj, y_proj, _ = proj3d.proj_transform(c[0], c[1], c[2], self.ax.get_proj()) labels[ii].xy = x_proj, y_proj labels[ii].update_positions(self.fig.canvas.renderer) self.fig.canvas.draw()
def test_proj_transform(): M = _test_proj_make_M() xs = np.array([0, 1, 1, 0, 0, 0, 1, 1, 0, 0]) * 300.0 ys = np.array([0, 0, 1, 1, 0, 0, 0, 1, 1, 0]) * 300.0 zs = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) * 300.0 txs, tys, tzs = proj3d.proj_transform(xs, ys, zs, M) ixs, iys, izs = proj3d.inv_transform(txs, tys, tzs, M) np.testing.assert_almost_equal(ixs, xs) np.testing.assert_almost_equal(iys, ys) np.testing.assert_almost_equal(izs, zs)
def plotFeatures(features, wordBidict, dims): """ Plot the desired points. Will draw all points if that is requested. Will draw labels for added words. """ if (FIG == None and AXES == None): setupPlot() AXES.clear() xs, ys, zs = None, None, None if not PLOT_ALL_POINTS: # iterate LABELS_MAP and get features for words xs = np.empty((len(LABELS_MAP),)) ys = np.empty((len(LABELS_MAP),)) zs = np.empty((len(LABELS_MAP),)) c = 0 for w in LABELS_MAP: x, y, z, _ = LABELS_MAP[w] xs[c] = x ys[c] = y zs[c] = z c = c + 1 else: xs = features[:,dims[0]] # dim 0 ys = features[:,dims[1]] # 1 zs = features[:,dims[2]] # 2 AXES.scatter(xs, ys, zs, c='r', marker='o') for k in LABELS_MAP: x1, y1, z1 = LABELS_MAP[k][0:3] x2, y2, _ = proj3d.proj_transform(x1, y1, z1, AXES.get_proj()) annotation = pylab.annotate(k, xy=(x2,y2), textcoords="offset points", xytext=(0, 0)) #annotation = pylab.annotate(k, xy = (x2, y2), xytext = (-15, 15), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) LABELS_MAP[k][3] = annotation AXES.set_xlabel('X='+str(dims[0])) AXES.set_ylabel('Y='+str(dims[1])) AXES.set_zlabel('Z='+str(dims[2])) global CALLBACK_ADDED if not CALLBACK_ADDED: FIG.canvas.mpl_connect('button_release_event', update_position) #FIG.canvas.mpl_connect('motion_notify_event', update_position) CALLBACK_ADDED = True plt.show() plt.draw()
def distance(point, event): """Return distance between mouse position and given data point Args: point (np.array): np.array of shape (3,), with x,y,z in data coords event (MouseEvent): mouse event (which contains mouse position in .x and .xdata) Returns: distance (np.float64): distance (in screen coords) between mouse pos and data point """ assert point.shape == (3,), "distance: point.shape is wrong: %s, must be (3,)" % point.shape # Project 3d data space to 2d data space x2, y2, _ = proj3d.proj_transform(point[0], point[1], point[2], plt.gca().get_proj()) # Convert 2d data space to 2d screen space x3, y3 = ax.transData.transform((x2, y2)) return np.sqrt ((x3 - event.x)**2 + (y3 - event.y)**2)
def _test_proj_draw_axes(M, s=1, *args, **kwargs): xs = [0, s, 0, 0] ys = [0, 0, s, 0] zs = [0, 0, 0, s] txs, tys, tzs = proj3d.proj_transform(xs, ys, zs, M) o, ax, ay, az = zip(txs, tys) lines = [(o, ax), (o, ay), (o, az)] fig, ax = plt.subplots(*args, **kwargs) linec = LineCollection(lines) ax.add_collection(linec) for x, y, t in zip(txs, tys, ['o', 'x', 'y', 'z']): ax.text(x, y, t) return fig, ax
def annotate_point(figure, axes, x, y, z, color): xp1, yp1, _ = proj3d.proj_transform(x, y, z, axes.get_proj()) label = axes.annotate( '{:.5g}'.format(z), xy=(xp1, yp1), xytext = (-20, 40), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle='round,pad=0.5', fc=color, alpha=0.5), arrowprops = dict(arrowstyle='->', connectionstyle='arc3,rad=0', color=color)) def update_position(_): xp2, yp2, _ = proj3d.proj_transform(x, y, z, axes.get_proj()) label.xy = xp2, yp2 label.update_positions(figure.canvas.renderer) figure.canvas.draw() figure.canvas.mpl_connect('button_release_event', update_position)
def draw(self, renderer, rasterized=True): """ Drawing actually happens here """ # Draws only when the dragging finished if self.leftdown: return xs3d, ys3d, zs3d = self._verts3d for i in xrange(len(xs3d)): xs, ys, _ = proj3d.proj_transform(xs3d[i], ys3d[i], zs3d[i], renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) self.set_color(self.colors[i]) FancyArrowPatch.draw(self, renderer) self.leftdown = False
def test_proj_axes_cube(): M = _test_proj_make_M() ts = '0 1 2 3 0 4 5 6 7 4'.split() xs = np.array([0, 1, 1, 0, 0, 0, 1, 1, 0, 0]) * 300.0 ys = np.array([0, 0, 1, 1, 0, 0, 0, 1, 1, 0]) * 300.0 zs = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) * 300.0 txs, tys, tzs = proj3d.proj_transform(xs, ys, zs, M) fig, ax = _test_proj_draw_axes(M, s=400) ax.scatter(txs, tys, c=tzs) ax.plot(txs, tys, c='r') for x, y, t in zip(txs, tys, ts): ax.text(x, y, t) ax.set_xlim(-0.2, 0.2) ax.set_ylim(-0.2, 0.2)
def annotatePlot(X, index): """Create popover label in 3d chart Args: X (np.array) - array of points, of shape (numPoints, 3) index (int) - index (into points array X) of item which should be printed Returns: None """ # If we have previously displayed another label, remove it first if hasattr(annotatePlot, 'label'): annotatePlot.label.remove() # Get data point from array of points X, at position index x2, y2,_ = proj3d.proj_transform(X[index, 0], X[index, 1], X[index, 2], ax.get_proj()) annotatePlot.label = plt.annotate("index: %d" % index, xy = (x2, y2), xytext = (-20,20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) fig.canvas.draw()
def plot_throttle_table(self, create_fit_line=False, referencepoint=[], neighbors=[], MakeLabels=False,trajectory_mdot=[],trajectory_thrust=[],trajectory_power=[]): import matplotlib from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d PPUpower = [] Isp = [] Thrust = [] Voltage = [] Mdot = [] PointLabels = [] Efficiency = [] Current = [] ScaledCurrent = [] for setting in self.ThrottleSettings: if not (referencepoint == setting or setting in neighbors): PPUpower.append(setting.ThrusterPower / self.PPUefficiency) Isp.append(setting.Isp) Thrust.append(setting.Thrust) Voltage.append(setting.BeamVoltage) Mdot.append(setting.Mdot) Efficiency.append(setting.efficiency) Current.append(setting.BeamCurrent) ScaledCurrent.append(Efficiency[-1]*Current[-1]) PointLabels.append(setting.TL) ThrottleFigure = matplotlib.pyplot.figure() ThrottleFigure.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99) ThrottleAxes = ThrottleFigure.add_subplot(111, projection='3d') ThrottleAxes.view_init(elev=90, azim=-90) ThrottleAxes.scatter(numpy.array(PPUpower), numpy.array(Mdot), numpy.array(Thrust), color='blue', s=50, alpha=1.0, label='throttle settings') if MakeLabels: for i, txt in enumerate(PointLabels): x2D, y2D, _ = proj3d.proj_transform(PPUpower[i],Mdot[i],Thrust[i], ThrottleAxes.get_proj()) ThrottleAxes.annotate(PointLabels[i], (x2D,y2D)) if create_fit_line: Voltage_polynomial = numpy.poly1d(numpy.polyfit(PPUpower, Voltage, 4)) Isp_polynomial = numpy.poly1d(numpy.polyfit(PPUpower, Isp, 4)) Mdot_polynomial = numpy.poly1d(numpy.polyfit(PPUpower, Mdot, 4)) Thrust_polynomial = numpy.poly1d(numpy.polyfit(PPUpower, Thrust, 4)) Current_polynomial = numpy.poly1d(numpy.polyfit(PPUpower, Current, 4)) powerlinepoints = numpy.linspace(min(PPUpower), max(PPUpower), 100) ThrottleAxes.plot(powerlinepoints, Mdot_polynomial(powerlinepoints), Thrust(powerlinepoints)) if referencepoint: ThrottleAxes.scatter(referencepoint.ThrusterPower / self.PPUefficiency, referencepoint.Mdot, referencepoint.Thrust, color='crimson', s=50, alpha=1.0, label='reference throttle setting') if MakeLabels: x2D, y2D, _ = proj3d.proj_transform(referencepoint.ThrusterPower / self.PPUefficiency, referencepoint.Mdot, referencepoint.Thrust, ThrottleAxes.get_proj()) ThrottleAxes.annotate(referencepoint.TL, (x2D, y2D)) if neighbors: NPPUpower = [] NVoltage = [] NIsp = [] NThrust = [] NPointLabels = [] NMdot = [] for neighbor in neighbors: print(neighbor.TL) NPPUpower.append(neighbor.ThrusterPower / self.PPUefficiency) NMdot.append(neighbor.Mdot) NIsp.append(neighbor.Isp) NThrust.append(neighbor.Thrust) NVoltage.append(neighbor.BeamVoltage) NPointLabels.append(neighbor.TL) ThrottleAxes.scatter(numpy.array(NPPUpower), numpy.array(NMdot), numpy.array(NThrust), color='orange', s=50, alpha=1.0, label='neighbors of reference throttle setting') if MakeLabels: for i, txt in enumerate(NPointLabels): x2D, y2D, _ = proj3d.proj_transform(NPPUpower[i],NMdot[i],NThrust[i], ThrottleAxes.get_proj()) ThrottleAxes.annotate(NPointLabels[i], (x2D,y2D)) if len(trajectory_mdot) and len(trajectory_thrust) and len(trajectory_power): ThrottleAxes.scatter(numpy.array(trajectory_power),numpy.array(trajectory_mdot),numpy.array(trajectory_thrust), marker='x',c='black',s=100,alpha=1.0,label='Throttle outputs used in trajectory') ThrottleAxes.view_init(elev=0, azim=0) ThrottleAxes.set_xlabel('PPU input power (kW)') ThrottleAxes.set_ylabel('Mass flow rate (mg/s)') ThrottleAxes.set_zlabel('Thrust (mN)') ThrottleAxes.set_title(self.FileName) leg = ThrottleAxes.legend() leg.draggable() ThrottleFigure.show() if create_fit_line: return Voltage_polynomial, Thrust_polynomial, Mdot_polynomial, Isp_polynomial
def pcaSubplot(self, X_r, dim, PCs_round, labels, template_list, dpiVal): """ Get the Principal Component Analysis data for this set of coordinates The value of 'dim' specifies the number of dimensions to diplay Then plot the PCA data """ # Set some figure parameters plt.rcParams['xtick.major.pad'] = '8' plt.rcParams['ytick.major.pad'] = '8' # Plot either PCA data on 2D or 3D if dim == 2: fig = plt.figure(figsize=(15, 13), dpi=dpiVal) fig.set_facecolor('white') fig.canvas.set_window_title("PCA 2D") ax = fig.add_subplot(111) # Scatter conformations. Designated by circles, colored based on # IFP similarity to a defined template scat = ax.scatter(X_r[:, 0], X_r[:, 1], s=600, marker="v", color="black") # Setting labels for both conformations and templates for label, x, y in zip(labels, X_r[:, 0], X_r[:, 1]): ax.annotate(label, xy=(x, y + 0.06), fontsize=30, ha='center', va='bottom') if dim == 3: fig = plt.figure() fig.set_facecolor('white') fig.canvas.set_window_title("PCA 3D") ax = fig.add_subplot(111, projection='3d') # Conformations scat = Axes3D.scatter(ax, X_r[:, 0], X_r[:, 1], X_r[:, 2], size=600, marker="o") # Scatter plot labels for label, x, y, z in zip(labels, X_r[:, 0], X_r[:, 1], X_r[:, 2]): if label != "": x2D, y2D, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) ax.annotate(label, xy=(x2D, y2D), fontsize=30, ha='left', va='bottom') # Setting axes and labels ax.set_xlabel("PC1 ({} %)".format(PCs_round[0])) ax.xaxis.label.set_size(25) ax.set_ylabel("PC2 ({} %)".format(PCs_round[1])) ax.yaxis.label.set_size(25) if dim == 3: ax.set_zlabel("PC3 ({0} %)".format(PCs_round[2])) ax.zaxis.label.set_size(25) ax.tick_params(axis="both", which="major", labelsize=25)
def draw(self, renderer): """Starts as 2-d,g ets projected into 3-d""" xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) FancyArrowPatch.draw(self, renderer)
X = np.array(Xt) Y = np.array(Yt) Z = np.array(Zt) max_range = np.array([X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min()]).max() / 2.0 mid_x = (X.max() + X.min()) * 0.5 mid_y = (Y.max() + Y.min()) * 0.5 mid_z = (Z.max() + Z.min()) * 0.5 ax2.set_xlim3d(mid_x - max_range, mid_x + max_range) ax2.set_ylim3d(mid_y - max_range, mid_y + max_range) ax2.set_zlim3d(mid_z - max_range, mid_z + max_range) # Create Annotation ax2.annotate(s=r'$x$', xy=tuple(proj3d.proj_transform(*px, M=ax2.get_proj()))[:2], fontsize=14, bbox={ 'pad': 8, 'fill': None, 'edgecolor': 'None' }, va='top', ha='left') ax2.annotate(s=r'$y$', xy=tuple(proj3d.proj_transform(*pcbl, M=ax2.get_proj()))[:2], fontsize=14, bbox={ 'pad': 8, 'fill': None, 'edgecolor': 'None'
def plot_bloch_vector(bloch, title=""): """Plot a Bloch vector. Plot a sphere, axes, the Bloch vector, and its projections onto each axis. bloch is a 3-tuple (x, y, z) title is a string, the plot title """ # Set arrow lengths arlen = 1.3 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_aspect("equal") # Plot semi-transparent sphere u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, color="b", alpha=0.1) # Plot arrows (axes, Bloch vector, its projections) xa = Arrow3D([0, arlen], [0, 0], [0, 0], mutation_scale=20, lw=1, arrowstyle="-|>", color="k") ya = Arrow3D([0, 0], [0, arlen], [0, 0], mutation_scale=20, lw=1, arrowstyle="-|>", color="k") za = Arrow3D([0, 0], [0, 0], [0, arlen], mutation_scale=20, lw=1, arrowstyle="-|>", color="k") a = Arrow3D([0, bloch[0]], [0, bloch[1]], [0, bloch[2]], mutation_scale=20, lw=2, arrowstyle="simple", color="k") bax = Arrow3D([0, bloch[0]], [0, 0], [0, 0], mutation_scale=20, lw=2, arrowstyle="-", color="r") bay = Arrow3D([0, 0], [0, bloch[1]], [0, 0], mutation_scale=20, lw=2, arrowstyle="-", color="g") baz = Arrow3D([0, 0], [0, 0], [0, bloch[2]], mutation_scale=20, lw=2, arrowstyle="-", color="b") arrowlist = [xa, ya, za, a, bax, bay, baz] for arr in arrowlist: ax.add_artist(arr) # Rotate the view ax.view_init(30, 30) # Annotate the axes, shifts are ad-hoc for this (30, 30) view xp, yp, _ = proj3d.proj_transform(arlen, 0, 0, ax.get_proj()) plt.annotate("x", xy=(xp, yp), xytext=(-3, -8), textcoords='offset points', ha='right', va='bottom') xp, yp, _ = proj3d.proj_transform(0, arlen, 0, ax.get_proj()) plt.annotate("y", xy=(xp, yp), xytext=(6, -5), textcoords='offset points', ha='right', va='bottom') xp, yp, _ = proj3d.proj_transform(0, 0, arlen, ax.get_proj()) plt.annotate("z", xy=(xp, yp), xytext=(2, 0), textcoords='offset points', ha='right', va='bottom') plt.title(title) plt.show()
ax.text(P_0[0], P_0[1] - 0.15 * r, P_0[2] + 0.035 * r, r"$P_0$", color='darkblue', size=14) # P_0 ax.text(r * sin(phi_0 + 0.13) * cos(-0.2 * pi), r * sin(phi_0 + 0.13) * sin(-0.2 * pi), r * cos(phi_0 + 0.13), r"$ \theta=\theta_0$", color='darkblue', size=14) # theta x2, y2, _ = proj3d.proj_transform(0, r * sin(pi - 0.2), r * cos(pi - 0.2), ax.get_proj()) label = pylab.annotate( r"$ \phi=0$", color='darkblue', xy=(x2, y2), xytext=(-15, 10), size=14, textcoords='offset points', ha='right', va='bottom', # bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0', color='darkblue')) #Vetores
def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer)
def plotData(self): # Plot the hand position self.axisPos.set_title('Hand Position', fontweight='bold', fontsize=16) self.axisPos.set_xlabel('x [mm]', fontsize=10) self.axisPos.set_ylabel('y [mm]', fontsize=10) self.axisPos.set_zlabel('z [mm]', fontsize=10) self.axisPos.set_xlim( [max(self.handPos[0]) + 5, min(self.handPos[0]) - 5]) self.axisPos.set_ylim( [max(self.handPos[1]) + 5, min(self.handPos[1]) - 5]) self.axisPos.set_zlim( [min(self.handPos[2]) - 5, max(self.handPos[2]) + 5]) for i in range(0, len(self.handPos[0])): if i == 0: # Plot the start position self.axisPos.scatter(self.handPos[0][i], self.handPos[1][i], self.handPos[2][i], color='yellowgreen', marker='o', s=200, alpha=0.75) x2D, y2D, _ = proj3d.proj_transform(self.handPos[0][i], self.handPos[1][i], self.handPos[2][i], self.axisPos.get_proj()) self.annStart = self.axisPos.annotate( 'Start', xy=(x2D, y2D), xytext=(-30, 0), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round, pad = 0.5', fc='yellowgreen', alpha=0.65), arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad = 0')) elif i == len(self.handPos[0]) - 1: # Plot the target position self.axisPos.scatter(self.handPos[0][i], self.handPos[1][i], self.handPos[2][i], color='gold', marker='o', s=200, alpha=0.75, label='Target') x2D, y2D, _ = proj3d.proj_transform(self.handPos[0][i], self.handPos[1][i], self.handPos[2][i], self.axisPos.get_proj()) self.annTarget = self.axisPos.annotate( 'Target', xy=(x2D, y2D), xytext=(80, 0), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round, pad = 0.5', fc='gold', alpha=0.65), arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad = 0')) else: # Plot the remaining trajectory self.axisPos.scatter(self.handPos[0][i], self.handPos[1][i], self.handPos[2][i], color='firebrick', marker='.', s=170, alpha=0.50) # Plot the hand velocity self.axisVel.set_title('Hand Velocity Norm', fontweight='bold', fontsize=16) self.axisVel.set_xlabel('Time [s]', fontsize=11) self.axisVel.set_ylabel('[mm/s]', fontsize=11) self.axisVel.set_xlim(min(self.t), max(self.t)) self.axisVel.set_ylim(0.0, max(self.handVel) + 5) self.axisVel.spines['left'].set_color('teal') self.axisVel.spines['left'].set_linewidth(3) self.axisVel.plot(self.t, self.handVel, color='teal', linewidth=1.65, label='Vel [mm/s]') # ************************** # # FUNCTION: update # # ************************** # def update(i): # Plot the start position annotation oldAnnStart = self.annStart x2D, y2D, _ = proj3d.proj_transform(self.handPos[0][0], self.handPos[1][0], self.handPos[2][0], self.axisPos.get_proj()) self.annStart = self.axisPos.annotate( 'Start', xy=(x2D, y2D), xytext=(-30, 0), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round, pad = 0.5', fc='yellowgreen', alpha=0.65), arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad = 0')) oldAnnStart.remove() # Plot the target position annotation oldAnnTarget = self.annTarget l = len(self.handPos[0]) - 1 x2D, y2D, _ = proj3d.proj_transform(self.handPos[0][l], self.handPos[1][l], self.handPos[2][l], self.axisPos.get_proj()) self.annTarget = self.axisPos.annotate( 'Target', xy=(x2D, y2D), xytext=(80, 0), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round, pad = 0.5', fc='gold', alpha=0.65), arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad = 0')) oldAnnTarget.remove() # Updates the annotations of start and target positions, when the view is changed a = anim.FuncAnimation(self.fig, update, frames=1000) self.handWindow.mainloop()
def main(): start_time = time.time() conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.cursor() ax = plt.axes() cur.execute( 'SELECT "Tower Density (Km2 per Cell)" FROM public.altice_statsmunicipals' ) fetched = cur.fetchall() towerDensities = parseDBColumns(fetched, 0, float) print("Statistics of Tower Density Values") plt.title("Different Tower Density Values for the Various Municipals") plt.xlabel("municipal") plt.ylabel("Tower Density (Km2 per Cell)") plt.plot(towerDensities, 'gx') plt.grid(True) plt.show() print(stats(towerDensities)) # ---------------------------------------------------------------------------------------------- classes = [0, 1, 2, 4, 8, 16, 32, 64, 128, 277] classNames = [ "[0 to 1[", "]1 to 2]", "]2 to 4]", "]4 to 8]", "]8, 16]", "]16, 32]", "]32, 64]", "]64, 128]", "]128, 277]" ] out = pd.cut(list(towerDensities), bins=classes, include_lowest=True) ax = out.value_counts().plot.bar(rot=0, color="g", figsize=(30, 20), fontsize=25) ax.set_xticklabels(classNames) ax.margins(y=0.0, tight=True) plt.ylim(0, 80) plt.grid(True) rects = ax.patches values = [] allInfo = str(pd.Categorical.value_counts(out)) lines = allInfo.split("\n") for i in range(len(lines) - 1): line = lines[i].split("]") values.append(int(line[1].strip())) for rect, label in zip(rects, values): height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2, height, round(label, 2), ha='center', va='bottom', fontsize=19) plt.title("Different Tower Density Values for the Various Municipals", fontsize=40) plt.ylabel("Number of Users", fontsize=30) plt.xlabel("Range of Travells Distance (in Kms)", fontsize=30) plt.grid(True) plt.show() # ---------------------------------------------------------------------------------------------- cur.execute( 'SELECT "Average Calls Per Day", "Average of Days Until Call","Nº Active Days" FROM public.altice_region_users_characterization' ) fetched = cur.fetchall() averageCallsPerDay = parseDBColumns(fetched, 0, float) regularity = parseDBColumns(fetched, 1, float) numberActiveDays = parseDBColumns(fetched, 2, int) print("Statistics of Average Calls Per Day Values") plt.title( "Different Average Calls Per Day Values for the Various User") plt.xlabel("user") plt.ylabel("Average Calls Per Day") plt.plot(averageCallsPerDay, 'bx') plt.grid(True) plt.show() print(stats(averageCallsPerDay)) # ---------------------------------------------------------------------------------------------- classes = [0, 1, 2, 4, 8, 16, 32, 64, 128, 236] classNames = [ "[0 to 1[", "]1 to 2]", "]2 to 4]", "]4 to 8]", "]8, 16]", "]16, 32]", "]32, 64]", "]64, 128]", "]128, 236]" ] out = pd.cut(list(averageCallsPerDay), bins=classes, include_lowest=True) ax = out.value_counts().plot.bar(rot=0, color="b", figsize=(30, 20), fontsize=25) ax.set_xticklabels(classNames) ax.margins(y=0.0, tight=True) plt.ylim(0, 190000) plt.grid(True) rects = ax.patches values = [] allInfo = str(pd.Categorical.value_counts(out)) lines = allInfo.split("\n") for i in range(len(lines) - 1): line = lines[i].split("]") values.append(int(line[1].strip())) for rect, label in zip(rects, values): height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2, height, round(label, 2), ha='center', va='bottom', fontsize=19) plt.title( "Different Average Calls Per Day Values for the Various User", fontsize=40) plt.ylabel("user", fontsize=30) plt.xlabel("Average Calls Per Day", fontsize=30) plt.grid(True) plt.show() # ---------------------------------------------------------------------------------------------- print("Statistics of Average of Days Until Call Values") plt.title( "Different Average of Days Until Call Values for the Various Users" ) plt.xlabel("user") plt.ylabel("Average of Days Until Call") plt.plot(regularity, 'rx') plt.grid(True) plt.show() print(stats(regularity)) # ---------------------------------------------------------------------------------------------- classes = [0, 1, 2, 4, 8, 16, 32, 64, 128, 226] classNames = [ "[0 to 1[", "]1 to 2]", "]2 to 4]", "]4 to 8]", "]8, 16]", "]16, 32]", "]32, 64]", "]64, 128]", "]128, 226]" ] out = pd.cut(list(regularity), bins=classes, include_lowest=True) ax = out.value_counts().plot.bar(rot=0, color="r", figsize=(30, 20), fontsize=25) ax.set_xticklabels(classNames) ax.margins(y=0.0, tight=True) plt.ylim(0, 250000) plt.grid(True) rects = ax.patches values = [] allInfo = str(pd.Categorical.value_counts(out)) lines = allInfo.split("\n") for i in range(len(lines) - 1): line = lines[i].split("]") values.append(int(line[1].strip())) for rect, label in zip(rects, values): height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2, height, round(label, 2), ha='center', va='bottom', fontsize=19) plt.title( "Different Average of Days Until Call Values for the Various Users", fontsize=40) plt.ylabel("user", fontsize=30) plt.xlabel("Average of Days Until Call", fontsize=30) plt.grid(True) plt.show() # ---------------------------------------------------------------------------------------------- print("Statistics of Nº Active Days Values Values") plt.title("Different Nº Active Days Values for the Various Users") plt.xlabel("user") plt.ylabel("Nº Active Days") plt.plot(numberActiveDays, 'yx') plt.grid(True) plt.show() print(stats(numberActiveDays)) # ---------------------------------------------------------------------------------------------- classes = [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 405] classNames = [ "[0 to 1[", "]1 to 2]", "]2 to 4]", "]4 to 8]", "]8, 16]", "]16, 32]", "]32, 64]", "]64, 128]", "]128, 256]", "]256, 405]" ] out = pd.cut(list(numberActiveDays), bins=classes, include_lowest=True) ax = out.value_counts().plot.bar(rot=0, color="y", figsize=(30, 20), fontsize=25) ax.set_xticklabels(classNames) ax.margins(y=0.0, tight=True) plt.ylim(0, 160000) plt.grid(True) rects = ax.patches values = [] allInfo = str(pd.Categorical.value_counts(out)) lines = allInfo.split("\n") for i in range(len(lines) - 1): line = lines[i].split("]") values.append(int(line[1].strip())) for rect, label in zip(rects, values): height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2, height, round(label, 2), ha='center', va='bottom', fontsize=19) plt.title("Different Nº Active Days Values for the Various Users", fontsize=40) plt.ylabel("user", fontsize=30) plt.xlabel("Nº Active Days", fontsize=30) plt.grid(True) plt.show() # -------------------------------------------------------- cur.execute('SELECT * FROM public.altice_experiment5') fetched = cur.fetchall() regularity = parseDBColumns(fetched, 0, float) averageCalls = parseDBColumns(fetched, 1, float) numberDays = parseDBColumns(fetched, 2, float) fig = plt.figure(figsize=(16, 12)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) ax = fig.add_subplot(111, projection='3d') theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = 25 * r * np.sin(theta) y = 350 * r * np.cos(theta) plt.rcParams['agg.path.chunksize'] = 10000 print("Drawing the Chart...") # ran plt.grid(True) ax.set_xlim(-1, 75) ax.set_ylim(-1, 100) ax.set_zlim(-1, 400) plt.gca().invert_xaxis() ax.plot(averageCalls, regularity, numberDays, "gx") ax.set_xlabel('Call Activity Every x Days', fontsize=18, labelpad=14) ax.set_ylabel('Average Calls Per Day', fontsize=18, labelpad=14) ax.set_zlabel('Nº of Active Days', fontsize=18, labelpad=14) f = lambda x, y, z: proj3d.proj_transform(x, y, z, ax.get_proj())[:2] ax.legend(loc="upper left", bbox_transform=ax.transData, prop={'size': 13}) plt.show() # -------------------------------------------------------- cur.execute('SELECT * FROM public.altice_experiment_3_1') fetched = cur.fetchall() numberDays = parseDBColumns(fetched, 0, float) numberDays_questao1 = [1] * len(numberDays) numberDays_racioHome = parseDBColumns(fetched, 1, float) numberDays_racioWorkplace = parseDBColumns(fetched, 2, float) numberDays_racioHome_Workplace = parseDBColumns(fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_3_2') fetched = cur.fetchall() numberDays_questao2 = [2] * len(numberDays) numberDays_racioHome_Morning = parseDBColumns(fetched, 1, float) numberDays_racioWorkplace_Morning = parseDBColumns(fetched, 2, float) numberDays_racioHome_Workplace_Morning = parseDBColumns( fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_3_3') fetched = cur.fetchall() numberDays_questao3 = [3] * len(numberDays) numberDays_racioHome_Evening = parseDBColumns(fetched, 1, float) numberDays_racioWorkplace_Evening = parseDBColumns(fetched, 2, float) numberDays_racioHome_Workplace_Evening = parseDBColumns( fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_3_4') fetched = cur.fetchall() numberDays_questao4 = [4] * len(numberDays) numberDays_racioH_W = parseDBColumns(fetched, 1, float) numberDays_racioW_H = parseDBColumns(fetched, 2, float) numberDays_racioH_W_or_W_H = parseDBColumns(fetched, 3, float) numberDays_racioH_W_and_W_H = parseDBColumns(fetched, 4, float) cur.execute('SELECT * FROM public.altice_experiment_3_5') fetched = cur.fetchall() numberDays_questao5 = [5] * len(numberDays) numberDays_racioWeekdays = parseDBColumns(fetched, 1, float) fig = plt.figure(figsize=(12, 8)) ax = plt.axes() plt.xlabel("Number of Days", fontsize=18) plt.ylabel("Percentage of Users", fontsize=18) ax.set_xlim(-1, 420) ax.set_ylim(-1, 100) plt.xticks(np.arange(min(numberDays) - 1, 420, 20), fontsize=14) plt.yticks(np.arange(0, 100, 5), fontsize=14) ax.plot(numberDays, numberDays_racioWeekdays, color="#663300", linewidth=4, label="Call Activity on Weekdays") ax.plot(numberDays, numberDays_racioHome_Workplace, 'y', linewidth=4, label="Indentified Home and Workplace") f = lambda x, y, z: proj3d.proj_transform(x, y, z, ax.get_proj())[:2] ax.legend(loc="upper right", bbox_transform=ax.transData, prop={'size': 14}) plt.grid(True) plt.show() # -------------------------------------------------------- cur.execute('SELECT * FROM public.altice_experiment_2_1') fetched = cur.fetchall() regularity = parseDBColumns(fetched, 0, float) regularity_questao1 = [1] * len(regularity) regularity_racioHome = parseDBColumns(fetched, 1, float) regularity_racioWorkplace = parseDBColumns(fetched, 2, float) regularity_racioHome_Workplace = parseDBColumns(fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_2_2') fetched = cur.fetchall() regularity_questao2 = [2] * len(regularity) regularity_racioHome_Morning = parseDBColumns(fetched, 1, float) regularity_racioWorkplace_Morning = parseDBColumns(fetched, 2, float) regularity_racioHome_Workplace_Morning = parseDBColumns( fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_2_3') fetched = cur.fetchall() regularity_questao3 = [3] * len(regularity) regularity_racioHome_Evening = parseDBColumns(fetched, 1, float) regularity_racioWorkplace_Evening = parseDBColumns(fetched, 2, float) regularity_racioHome_Workplace_Evening = parseDBColumns( fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_2_4') fetched = cur.fetchall() regularity_questao4 = [4] * len(regularity) regularity_racioH_W = parseDBColumns(fetched, 1, float) regularity_racioW_H = parseDBColumns(fetched, 2, float) regularity_racioH_W_or_W_H = parseDBColumns(fetched, 3, float) regularity_racioH_W_and_W_H = parseDBColumns(fetched, 4, float) cur.execute('SELECT * FROM public.altice_experiment_2_5') fetched = cur.fetchall() regularity_questao5 = [5] * len(regularity) regularity_racioWeekdays = parseDBColumns(fetched, 1, float) fig = plt.figure(figsize=(14, 10)) ax = plt.axes() plt.xlabel("Regularity (Call Activity in Every x Days)", fontsize=18) plt.ylabel("Percentage of Users", fontsize=18) ax.set_xlim(-1, 210) ax.set_ylim(-1, 100) # plt.xticks(np.arange(min(regularity)-1, 210, 10), fontsize=14) # plt.yticks(np.arange(0, 100, 2.5), fontsize=14) ax.plot(regularity[:-42], regularity_racioWeekdays[:-42], "k", linewidth=3, label="Call Activity on Weekdays") ax.plot(regularity[:-42], regularity_racioHome_Workplace[:-42], 'r', linewidth=3, label="Indentified Home and Workplace") ax.plot(regularity[:-42], regularity_racioHome_Workplace_Morning[:-42], 'k', linewidth=3, label="Activity at Home and Workplace in the Morning") ax.plot(regularity[:-42], regularity_racioHome_Workplace_Evening[:-42], 'b', linewidth=3, label="Activity at Home and Workplace in the Morning") ax.plot(regularity[:-42], regularity_racioH_W_or_W_H[:-42], 'g', linewidth=3, label="Call Activity During Home->Work or Vice-Versa") ax.plot(regularity[:-42], regularity_racioH_W_and_W_H[:-42], 'c', linewidth=3, label="Call Activity During Home->to Work and Vice-Versa") ax.legend(loc="right", bbox_transform=ax.transData, fontsize=14, labelspacing=2, prop={'size': 14}) plt.grid(True) plt.show() stats1 = stats(regularity_racioWeekdays[:-42]) stats2 = stats(regularity_racioHome_Workplace[:-42]) stats3 = stats(regularity_racioHome_Workplace_Morning[:-42]) stats4 = stats(regularity_racioHome_Workplace_Evening[:-42]) stats5 = stats(regularity_racioH_W_or_W_H[:-42]) stats6 = stats(regularity_racioH_W_and_W_H[:-42]) res1 = next(x for x, val in enumerate(regularity_racioWeekdays[:-42]) if val < stats1["mean"]) res2 = next( x for x, val in enumerate(regularity_racioHome_Workplace[:-42]) if val < stats2["mean"]) res3 = next(x for x, val in enumerate( regularity_racioHome_Workplace_Morning[:-42]) if val < stats3["mean"]) res4 = next(x for x, val in enumerate( regularity_racioHome_Workplace_Evening[:-42]) if val < stats4["mean"]) res5 = next(x for x, val in enumerate(regularity_racioH_W_or_W_H[:-42]) if val < stats5["mean"]) res6 = next(x for x, val in enumerate(regularity_racioH_W_and_W_H[:-42]) if val < stats6["mean"]) print(regularity[res1]) print(regularity[res2]) print(regularity[res3]) print(regularity[res4]) print(regularity[res5]) print(stats5["mean"]) print(regularity[res6]) print(stats6["mean"]) print(regularity) # -------------------------------------------------------- cur.execute('SELECT * FROM public.altice_experiment_1_1') fetched = cur.fetchall() averageCalls = parseDBColumns(fetched, 0, float) averageCalls_racioHome = parseDBColumns(fetched, 1, float) averageCalls_racioWorkplace = parseDBColumns(fetched, 2, float) averageCalls_racioHome_Workplace = parseDBColumns(fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_1_2') fetched = cur.fetchall() averageCalls_racioHome_Morning = parseDBColumns(fetched, 1, float) averageCalls_racioWorkplace_Morning = parseDBColumns(fetched, 2, float) averageCalls_racioHome_Workplace_Morning = parseDBColumns( fetched, 3, float) cur.execute('SELECT * FROM public.altice_experiment_1_3') fetched = cur.fetchall() averageCalls_racioHome_Evening = parseDBColumns(fetched, 1, float) averageCalls_racioWorkplace_Evening = parseDBColumns(fetched, 2, float) averageCalls_racioHome_Workplace_Evening = parseDBColumns( fetched, 3, float) cur.execute('SELECT * FROM public.experiment_1_4') fetched = cur.fetchall() averageCalls_racioH_W = parseDBColumns(fetched, 1, float) averageCalls_racioW_H = parseDBColumns(fetched, 2, float) averageCalls_racioH_W_or_W_H = parseDBColumns(fetched, 3, float) averageCalls_racioH_W_and_W_H = parseDBColumns(fetched, 4, float) cur.execute('SELECT * FROM public.altice_experiment_1_5') fetched = cur.fetchall() averageCalls_racioWeekdays = parseDBColumns(fetched, 1, float) fig = plt.figure(figsize=(12, 8)) ax = plt.axes() plt.xlabel("Average Number of CallsMade/Received Per Day", fontsize=18) plt.ylabel("Percentage of Users", fontsize=18) ax.set_xlim(-1, 42) ax.set_ylim(-1, 100) plt.xticks(np.arange(min(averageCalls), 42, 2), fontsize=14) plt.yticks(np.arange(0, 100, 5), fontsize=14) ax.plot(averageCalls[:400], averageCalls_racioWeekdays[:400], color='#000000', linewidth=3, label="Call Activity on Weekdays") ax.plot(averageCalls[:400], averageCalls_racioHome_Workplace[:400], color='#003300', linewidth=3, label="Indentified Home and Workplace") ax.plot(averageCalls[:400], averageCalls_racioHome_Workplace_Morning[:400], color='#ffb3b3', linewidth=3, label="Activity at Home and Workplace in the Morning") ax.plot(averageCalls[:400], averageCalls_racioHome_Workplace_Evening[:400], color='#ff1a1a', linewidth=3, label="Activity at Home and Workplace in the Evening") ax.plot(averageCalls[:400], averageCalls_racioH_W_or_W_H[:400], color='#ff6600', linewidth=3, label="Call Activity During Home->Work or Vice-Versa") ax.plot(averageCalls[:400], averageCalls_racioH_W_and_W_H[:400], color='#009973', linewidth=3, label="Call Activity During Home->to Work and Vice-Versa") plt.grid(True) plt.show() stats1 = stats(averageCalls_racioWeekdays[:400]) stats2 = stats(averageCalls_racioHome_Workplace[:400]) stats3 = stats(averageCalls_racioHome_Workplace_Morning[:400]) stats4 = stats(averageCalls_racioHome_Workplace_Evening[:400]) stats5 = stats(averageCalls_racioH_W_or_W_H[:400]) stats6 = stats(averageCalls_racioH_W_and_W_H[:400]) res1 = next(x for x, val in enumerate(averageCalls_racioWeekdays[:400]) if val > stats1["mean"]) res2 = next( x for x, val in enumerate(averageCalls_racioHome_Workplace[:400]) if val > stats2["mean"]) res3 = next(x for x, val in enumerate( averageCalls_racioHome_Workplace_Morning[:400]) if val > stats3["mean"]) res4 = next(x for x, val in enumerate( averageCalls_racioHome_Workplace_Evening[:400]) if val > stats4["mean"]) res5 = next(x for x, val in enumerate(averageCalls_racioH_W_or_W_H[:400]) if val > stats5["mean"]) res6 = next( x for x, val in enumerate(averageCalls_racioH_W_and_W_H[:400]) if val > stats6["mean"]) print(averageCalls[res1]) print(averageCalls[res2]) print(averageCalls[res3]) print(averageCalls[res4]) print(averageCalls[res5]) print(stats5["mean"]) print(averageCalls[res6]) print(stats6["mean"]) # EXPERIMENT 5 -------------------------------------------------------------------------------------------------------------------- cur.execute('SELECT * FROM public.altice_experiment5') fetched = cur.fetchall() regularity = parseDBColumns(fetched, 0, float) averageCalls = parseDBColumns(fetched, 1, float) numberDays = parseDBColumns(fetched, 2, float) fig = plt.figure(figsize=(16, 12)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) ax = fig.add_subplot(111, projection='3d') plt.rcParams['agg.path.chunksize'] = 10000 print("Drawing the Chart...") ax.set_xlim(0, 400) ax.set_ylim(-1, 210) ax.set_zlim(-1, 45) plt.gca().invert_xaxis() ax.plot(numberDays, regularity, averageCalls, '*') ax.set_xlabel('Nº of Active Days', fontsize=18, labelpad=14) ax.set_ylabel('Regularity', fontsize=18, labelpad=14) ax.set_zlabel('Average Number of calls', fontsize=18, labelpad=14) f = lambda x, y, z: proj3d.proj_transform(x, y, z, ax.get_proj())[:2] ax.legend(loc="upper left", bbox_transform=ax.transData, prop={'size': 13}) plt.show() # EXPERIMENT 4_2 cur.execute('SELECT * FROM public.altice_experiment_4_2') fetched = cur.fetchall() towerdensities = parseDBColumns(fetched, 1, float) racioH_W = parseDBColumns(fetched, 2, float) racioW_H = parseDBColumns(fetched, 3, float) racioH_W_or_W_H = parseDBColumns(fetched, 4, float) racioH_W_and_W_H = parseDBColumns(fetched, 5, float) fig = plt.figure(figsize=(12, 8)) ax = plt.axes() plt.xlabel("Tower Density (Km2 per cell)") plt.ylabel("Percentage of Users") plt.xticks(np.arange(0, 607, 20)) plt.yticks(np.arange(0, 100, 10)) ax.plot(towerdensities, racioH_W, "*", label="Intermediate Towers Home->Work") ax.plot(towerdensities, racioW_H, "*", label="Intermediate Towers Work->Home") ax.plot(towerdensities, racioH_W_or_W_H, "*", label="Intermediate Towers Home->Work or Work->Home") ax.plot(towerdensities, racioH_W_and_W_H, "*", label="Intermediate Towers Home->Work and Work->Home") f = lambda x, y, z: proj3d.proj_transform(x, y, z, ax.get_proj())[:2] ax.legend(loc="upper right", bbox_transform=ax.transData, prop={'size': 13}) plt.grid(True) plt.show() fig = plt.figure(figsize=(16, 12)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) ax = fig.add_subplot(111, projection='3d') plt.rcParams['agg.path.chunksize'] = 10000 print("Drawing the Chart...") ax.set_yticks(np.arange(0, 600, 40)) plt.gca().invert_yaxis() plt.xticks(np.arange(4), ('Home->Work', 'Work->Home', 'Home->Work \nor Work->Home', 'Home->Work \nand Work->Home'), fontsize=14) ax.plot([0] * len(towerdensities), towerdensities, racioH_W, '*') ax.plot([1] * len(towerdensities), towerdensities, racioW_H, '*') ax.plot([2] * len(towerdensities), towerdensities, racioH_W_or_W_H, '*') ax.plot([3] * len(towerdensities), towerdensities, racioH_W_and_W_H, '*') ax.set_ylabel('Tower Density (Km2 Per Cell)', fontsize=18, labelpad=14) ax.set_zlabel('Percentage of Users', fontsize=18, labelpad=14) f = lambda x, y, z: proj3d.proj_transform(x, y, z, ax.get_proj())[:2] ax.legend(loc="upper left", bbox_transform=ax.transData, prop={'size': 13}) plt.show() elapsed_time = time.time() - start_time print("EXECUTION TIME: " + str(elapsed_time / 60) + " MINUTES") # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.')
ax.set_yticks([]) ax._axis3don = False box = ax.get_position() # create color bar axColor = plt.axes( [box.x0 * 1.00 + box.width * 1.00, box.y0, 0.01, box.height]) cb = plt.colorbar(sm, cax=axColor) cb.set_label("Air density (kg/m^3)") cb.ax.invert_yaxis() labels = [] ax.set_xlim(25, 50) ax.set_ylim(np.min(y), np.max(y)) ax.set_zlim(np.min(z), np.max(z)) x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) print x2 ax.scatter(x, y, z, t, cmap=green_red, lw=0, s=1) for i in range(1, np.size(z), 500): name = "Altitude: " + np.str(z[i]) + " m\n" + "Distance: " + np.str( dist[i]) + " m" label = ax.annotate(name, xy=(x2[i], y2[i]), xytext=(-150.0, -10.0), textcoords='offset points', fontsize=10, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) labels.append(label)
def dataspace(point): if point.shape == (3,): x2, y2, _ = proj3d.proj_transform(point[0], point[1], point[2], plt.gca().get_proj()) else: x2, y2 = point[0], point[1] return x2, y2
zorder=10) # pontos O-Q-R-S plt.plot(x_11, y_11, z_11, color="darkblue", alpha=0.8, zorder=0) plt.plot(x_21, y_21, z_21, color="darkblue", alpha=0.8, zorder=0) plt.plot(x_12, y_12, z_12, color="darkblue", alpha=0.8, zorder=0) plt.plot(x_22, y_22, z_22, color="darkblue", alpha=0.8, zorder=0) plt.plot(xx_21, yy_21, zz_21, color="darkblue", alpha=0.2, zorder=0, ls='--') plt.plot(xx_22, yy_22, zz_22, color="darkblue", alpha=0.2, zorder=0, ls='--') # #Setas step_arrow = 0.007 # O Q x_seta, y_seta, z_seta = [ 0.5 * (Q_0[0] + O_0[0]), 0.5 * (Q_0[1] + O_0[1]), 0.5 * (Q_0[2] + O_0[2]) ] x2, y2, _ = proj3d.proj_transform(x_seta, y_seta, z_seta, ax.get_proj()) plt.arrow(x2, y2, 0.05 * step_arrow, -0.5 * step_arrow, shape='full', length_includes_head=True, head_width=.0035, color='darkblue', zorder=0, alpha=0.8) # Q R x_seta, y_seta, z_seta = [ 0.5 * (Q_0[0] + R_0[0]), 0.5 * (Q_0[1] + R_0[1]), 0.5 * (Q_0[2] + R_0[2]) ] x2, y2, _ = proj3d.proj_transform(x_seta, y_seta, z_seta, ax.get_proj())
def draw(self, renderer): xp, yp, zp = self._v x, y, z = proj3d.proj_transform(xp, yp, zp, renderer.M) self.set_positions((x[0], y[0]), (x[1], y[1])) FancyArrowPatch.draw(self, renderer)
def LabelEvent(self, GraphicsObject, PlotOptions, labelString = None): import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d description = '' if labelString == None: if PlotOptions.ShowTextDescriptions: EventTypeFormatted = self.EventType if EventTypeFormatted == 'upwr_flyby': EventTypeFormatted = 'unpowered flyby' elif EventTypeFormatted == 'pwr_flyby': EventTypeFormatted = 'powered flyby' elif EventTypeFormatted == 'chem_burn': EventTypeFormatted = 'chemical burn' elif EventTypeFormatted == 'LT_rndzvs': EventTypeFormatted = 'rendezvous' elif EventTypeFormatted == 'begin_spiral': EventTypeFormatted = 'begin spiral' elif EventTypeFormatted == 'end_spiral': EventTypeFormatted = 'end spiral' elif EventTypeFormatted == 'mission_end': EventTypeFormatted = 'end of mission' elif EventTypeFormatted == 'momtransfer': EventTypeFormatted = 'momentum transfer' if PlotOptions.NumberEventLabels: EventNumber = 'Event # ' + str(PlotOptions.EventCounter) + ':\n' else: EventNumber = '' description = EventNumber + EventTypeFormatted.capitalize() + '\n' + self.Location if PlotOptions.DisplayEventDates: description += '\n' + self.GregorianDate if PlotOptions.DisplayEventSpecs: #for launches a C3 and DLA are needed if self.EventType == 'launch': description += '\n$C_3$ = ' + "{0:.3f}".format(self.C3) + ' $km^2/s^2$' #add the LV to the description? description += '\nDLA = ' + "{0:.1f}".format(self.Declination) + '$^{\circ}$' #for non-launch departures only the C3 is needed if self.EventType == 'departure' and self.C3 > 0.0: description += '\n$C_3$ = ' + "{0:.3f}".format(self.C3) + ' $km^2/s^2$' #for other events, output v-infinity and DLA if self.EventType in ['upwr_flyby', 'pwr_flyby', 'intercept', 'interface', 'insertion', 'momtransfer']: description += '\n$v_\infty$ = ' + "{0:.3f}".format(math.sqrt(self.C3)) + ' $km/s$' description += '\nDEC = ' + "{0:.1f}".format(self.Declination) + '$^{\circ}$' #for flybys, altitude should be outputed if self.EventType in ['upwr_flyby', 'pwr_flyby', 'periapse']: description += '\naltitude = ' + "{0:.0f}".format(self.Altitude) + ' $km$' #for propulsive events, a deltaV is needed if (self.EventType == 'departure' or self.EventType == 'pwr_flyby' or self.EventType == 'insertion' or self.EventType == 'chem_burn' or self.EventType == 'rendezvous') and self.DVmagorThrottle > 0.0: description += '\n$\Delta v$ = ' + "{0:.3f}".format(self.DVmagorThrottle) + ' $km/s$' #always append the spacecraft Mass if PlotOptions.DisplayEventMass: if self.Mass < 1.0e+5: description += '\nm = ' + "{0:.0f}".format(self.Mass) + ' $kg$' else: description += '\nm = ' + "{0:.4e}".format(self.Mass) + ' $kg$' if PlotOptions.DisplayArrivalPhaseAngle and self.EventType == 'intercept': R = self.SpacecraftState[0:3] V = self.DeltaVorThrustVectorControl r = math.sqrt(R[0]*R[0] + R[1]*R[1] + R[2]*R[2]) v = math.sqrt(V[0]*V[0] + V[1]*V[1] + V[2]*V[2]) try: PhaseAngle = math.acos(-(R[0]*V[0] + R[1]*V[1] + R[2]*V[2]) / (r * v)) * 180.0 / math.pi description += '\n' + r'$\beta $' + ' = ' + "{0:.1f}".format(PhaseAngle) + ' degrees' except: print("Bad velocity vector while calculating phase angle, event" + str(self.EventNumber)) else: description = str(PlotOptions.EventCounter) else: description = labelString #draw the text #note, do not draw anything for chemical burns below 10 m/s if not (self.EventType == "chem_burn" and self.DVmagorThrottle < 0.0001): x2D, y2D, _ = proj3d.proj_transform(self.SpacecraftState[0],self.SpacecraftState[1],self.SpacecraftState[2], GraphicsObject.get_proj()) if PlotOptions.ShowTextDescriptions: self.eventlabel = plt.annotate(description, xycoords = 'data', xy = (x2D, y2D), xytext = (20, (PlotOptions.EventCounter + 20)), textcoords = 'offset points', ha = 'left', va = 'bottom', #self.eventlabel = plt.annotate(description, xycoords = 'data', xy = (self.SpacecraftState[0],self.SpacecraftState[1]), xytext = (20, (PlotOptions.EventCounter + 20)), textcoords = 'offset points', ha = 'left', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'white', alpha = 1.0), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'), size=PlotOptions.FontSize, family='serif') # changed to usurp drag-fu else: self.eventlabel = plt.annotate(description, xycoords = 'data', xy = (x2D, y2D), ha = 'left', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'white', alpha = 1.0), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'), size=PlotOptions.FontSize, family='serif') # changed to usurp drag-fu self.AnnotationHelper = self.eventlabel.draggable(use_blit=True) self.pcid = GraphicsObject.figure.canvas.mpl_connect('button_press_event', self.ClickAnnotation) self.rcid = GraphicsObject.figure.canvas.mpl_connect('button_release_event', self.ReleaseAnnotation) #update the event counter only if the event is printable PlotOptions.EventCounter += 1
def animate(self, vessel, periapsis, eccentricity, ecc_anom, incl, argPe): # Calculate data used in both modes pr = vessel.orbit.body.equatorial_radius inclination = incl + np.pi q = periapsis + pr # periapsis radius a = q / (1 - eccentricity) # semi major axis ap = 2 * a - q # aperiapsis radius theta = np.linspace(0, 2 * np.pi, 181) r = (a * (1 - eccentricity ** 2)) / (1 + eccentricity * np.cos(theta)) true_anom = 2 * np.arctan2(np.sqrt(1 + eccentricity) * np.sin(ecc_anom / 2), np.sqrt(1 - eccentricity) * np.cos(ecc_anom / 2)) r_vess = (a * (1 - eccentricity ** 2)) / (1 + eccentricity * np.cos(true_anom)) # Plot 1 if self.mode is not 1: # clear the plot and reset its properties self.ax1.clear() self.ax1.set_theta_offset(np.pi) self.ax1.axis("off") self.ax1.set_title("Orbit - Planar View", fontsize=24, color="blue", fontweight="bold") # plot the planet circle = plt.Circle((0, 0), pr, transform=self.ax1.transData._b, color="grey", alpha=1) self.ax1.add_artist(circle) self.ax1.annotate(vessel.orbit.body.name, xy=(.5, .5), xycoords='axes fraction', horizontalalignment='center', verticalalignment='center', color="white", size=24 ) # set the plot axis limits self.ax1.set_rlim(ap * 1.25) # plot the orbit self.ax1.plot(theta, r, color="blue", lw=3) # plot PE and AP self.ax1.plot([0], [q], "D", color="white", markersize=7) self.ax1.annotate("Pe = " + si_val(periapsis, 2) + "m", xy=(0, q), # theta, radius xytext=(-5, -5), # fraction, fraction textcoords='offset points', horizontalalignment='right', verticalalignment='bottom', color="white" ) self.ax1.plot([np.pi], [ap], "D", color="white", markersize=7) self.ax1.annotate("Ap = " + si_val(ap - pr, 2) + "m", xy=(np.pi, ap), # theta, radius xytext=(5, 5), # fraction, fraction textcoords='offset points', horizontalalignment='left', verticalalignment='bottom', color="white" ) # plot the current position self.ax1.plot([true_anom], [r_vess], ".", color="red", markersize=20) # plot 2 if self.mode is not 0: self.ax2.clear() self.ax2.axis("off") self.ax2.set_title("Orbit - Oblique View", fontsize=24, color="blue", fontweight="bold") # Adjustment of the axes, so that they all have the same span: for axis in 'xyz': getattr(self.ax2, 'set_{}lim'.format(axis))((-a, a)) r2 = (a * (1 - eccentricity ** 2)) / (1 + eccentricity * np.cos(theta + np.asanyarray(argPe) - np.pi / 2)) xo = r2 * np.cos(theta) y2 = r2 * np.sin(theta) zo = np.zeros(181) inclination = incl x2 = xo * np.cos(inclination) + zo * np.sin(inclination) # y2 = yo z2 = -xo * np.sin(inclination) + zo * np.cos(inclination) # Set up marker points # coord index, label, marker, colours (in RGBA) and sizes # AN and Dn # These are simple as we have rotated our orbit so the An is at +Y node_label = [(45, "An", "^", [0, 1, 0, 1], 10), (135, "Dn", "v", [0, 1, 0, 1], 10)] # Pe and Ap # These are then calculated from An using argPe, and opposite to that point. i_pe = (45 + int(degrees(argPe) / 2)) % 180 i_ap = (i_pe + 90) % 180 node_label.append((i_pe, "Pe", "D", [1, 1, 1, 1], 10)) node_label.append((i_ap, "Ap", "D", [1, 1, 1, 1], 10)) # Vessel i_ve = (i_pe + int(degrees(true_anom) / 2)) % 180 node_label.append((i_ve, "", "o", [1, 0, 0, 1], 10)) self.ax2.plot(x2, y2, z2) for i in range(len(node_label)): xl, yl, _ = proj3d.proj_transform(x2[node_label[i][0]], y2[node_label[i][0]], z2[node_label[i][0]], self.ax2.get_proj()) self.ax2.plot([x2[node_label[i][0]]], [y2[node_label[i][0]]], [z2[node_label[i][0]]], node_label[i][2], c=node_label[i][3], markersize=node_label[i][4]) self.ax2.annotate(node_label[i][1], xy=(xl, yl), xytext=(5, 5), # fraction, fraction textcoords='offset points', horizontalalignment='left', verticalalignment='bottom', color="white" ) # add the planet t1, t2 = np.mgrid[0.0:np.pi:150j, 0.0:2.0 * np.pi:150j] xp = pr * np.sin(t1) * np.cos(t2) yp = pr * np.sin(t1) * np.sin(t2) zp = pr * np.cos(t1) self.ax2.plot_surface(xp, yp, zp, color="grey", edgecolor="none") self.fig.canvas.draw()
def plotLatticeSpacing(self, text): """adds lattice spacing to plot""" # create tranfsromation of cube dimensions to 2D x_shift = .3 # width shift y_shift = 0. # depth shift z_shift = 0. # upwards shift l = 2. # length of arrow a = 1 # axis the arrow will extend along (0,1,2) = (x,y,z) i = np.asarray( # the initial field position [1 + x_shift, -1 + y_shift, -1 + z_shift]) mask = np.in1d(np.arange(i.size), a) # mask is true on only the axis f = i + mask * l # the final arrow point m = i + .5 * mask * l # the mid point # lambda function to get the position from a different matrix projection getPos = lambda xyz: proj3d.proj_transform(*tuple(xyz), M=self.ax.get_proj()) # get points of the arrow x1, y1, _ = getPos(i) # initial points x2, y2, _ = getPos(f) # final point xm, ym, _ = getPos(m) # mid point arrow = self.ax.annotate( '', # draw the arrow xy=(x1, y1), # start of arrow xytext=(x2, y2), # end of arrow arrowprops={'arrowstyle': '<->'}) label = self.ax.annotate( # draw the text text, # text to annotate with xy=(xm, ym), # location of text xytext=(10, -10), # specify the offset of the text xycoords='data', textcoords='offset points') # add to list of labels self.labels['spacing_arrow'] = arrow self.labels['spacing_label'] = label def update_position_arrow(e): """click and the labels snap the correct place http://stackoverflow.com/a/10394128/4013571 """ # get points of the arrow x1, y1, _ = getPos(i) # initial points x2, y2, _ = getPos(f) # final point self.labels['spacing_arrow'].xy = x1, y1 # redef start point self.labels['spacing_arrow'].xyann = x2, y2 # redef final point self.labels['spacing_arrow'].update_positions( self.fig.canvas.renderer) self.fig.canvas.draw() pass def update_position_text(e): """click and the labels snap the correct place http://stackoverflow.com/a/10394128/4013571 """ # get points of the arrow xm, ym, _ = getPos(m) # initial points self.labels['spacing_label'].xy = xm, ym # redef start point self.labels['spacing_label'].update_positions( self.fig.canvas.renderer) self.fig.canvas.draw() pass # enable the updated position self.fig.canvas.mpl_connect('button_release_event', update_position_arrow) self.fig.canvas.mpl_connect('button_release_event', update_position_text) plt.draw() pass
""" First transformation repositions the points so that the points with weight 1 are positioned at the barycentric coordinates. The second transformation will need to scale the points to the the realtive distances befor the transformations are preserved. """ x1s = [] y1s = [] x2s = [] y2s = [] baryPoints = [] for optPoint in T: # one point of interest x1, y1, _ = proj3d.proj_transform(optPoint[0], optPoint[1], optPoint[2], ax1.get_proj()) [x1,y1] = ax1.transData.transform((x1, y1)) # convert 2d space to screen space # put them in screen space relative to ax0 x1s.append(x1/width) y1s.append(y1/height) length = ( optPoint[0] + optPoint[1] + optPoint[2] ) baryPoint = [optPoint[0] / length, optPoint[1] / length, 0] baryPoints.append(baryPoint) # another point of interest x2, y2, _ = proj3d.proj_transform(baryPoint[0], baryPoint[1], baryPoint[2], ax2.get_proj()) [x2,y2] = ax2.transData.transform((x2, y2)) # convert 2d space to screen space x2s.append(x2/width) y2s.append(y2/height)
def draw(self, renderer): """Draw the patch.""" xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) super(Arrow3D, self).draw(renderer)
Y = np.array(Yt) Z = np.array(Zt) max_range = 0.5 * np.array([ X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min() ]).max() / 2.0 mid_x = (X.max() + X.min()) * 0.5 - 0.25 mid_y = (Y.max() + Y.min()) * 0.5 - 0.35 mid_z = (Z.max() + Z.min()) * 0.5 ax2.set_xlim3d(mid_x - max_range, mid_x + max_range) ax2.set_ylim3d(mid_y - max_range, mid_y + max_range) ax2.set_zlim3d(mid_z - max_range, mid_z + max_range) # Create Annotation ax2.annotate(s=r'$x$', xy=tuple(proj3d.proj_transform(*px, M=ax2.get_proj()))[:2], fontsize=14, bbox={ 'pad': 8, 'fill': None, 'edgecolor': 'None' }, va='top', ha='left') ax2.annotate(s=r'$y$', xy=tuple(proj3d.proj_transform(*py, M=ax2.get_proj()))[:2], fontsize=14, bbox={ 'pad': 8, 'fill': None, 'edgecolor': 'None'
def update_position(e): for label, x, y, z in labels_and_points: x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) label.xy = x2,y2 label.update_positions(fig.canvas.renderer) fig.canvas.draw()
def LabelEvent(self, GraphicsObject, PlotOptions): EventTypeFormatted = self.EventType if EventTypeFormatted == 'upwr_flyby': EventTypeFormatted = 'unpowered flyby' elif EventTypeFormatted == 'pwr_flyby': EventTypeFormatted = 'powered flyby' elif EventTypeFormatted == 'chem_burn': EventTypeFormatted = 'chemical burn' elif EventTypeFormatted == 'LT_rndzvs': EventTypeFormatted = 'LT rendezvous' elif EventTypeFormatted == 'begin_spiral': EventTypeFormatted = 'begin spiral' elif EventTypeFormatted == 'end_spiral': EventTypeFormatted = 'end spiral' description = EventTypeFormatted + '\n' + self.Location + '\n' + self.GregorianDate #for launches a C3 and DLA are needed if self.EventType == 'launch': description += '\nC3 = ' + "{0:.3f}".format( self.C3) + ' $km^2/s^2$' #add the LV to the description? description += '\nDLA = ' + "{0:.1f}".format( self.Declination) + '$^{\circ}$' #for non-launch departures only the C3 is needed if self.EventType == 'departure': description += '\nC3 = ' + "{0:.3f}".format( self.C3) + ' $km^2/s^2$' #for spirals output only the delta-v if self.EventType == 'begin_spiral' or self.EventType == 'end_spiral': description += '\n$\Delta v$ = ' + "{0:.3f}".format( self.DVmagorThrottle) + ' $km/s$' #for other events, output v-infinity and DLA if self.EventType == 'upwr_flyby' or self.EventType == 'pwr_flyby' or self.EventType == 'intercept' or self.EventType == 'interface' or self.EventType == 'insertion': description += '\n$v_\infty$ = ' + "{0:.3f}".format( math.sqrt(self.C3)) + ' $km/s$' description += '\nDEC = ' + "{0:.1f}".format( self.Declination) + '$^{\circ}$' #for flybys, altitude should be outputed if self.EventType == 'upwr_flyby' or self.EventType == 'pwr_flyby': description += '\naltitude = ' + "{0:.0f}".format( self.Altitude) + ' $km$' #for propulsive events, a deltaV is needed if self.EventType == 'departure' or self.EventType == 'pwr_flyby' or self.EventType == 'insertion' or self.EventType == 'chem_burn' or self.EventType == 'rendezvous': description += '\n$\Delta v$ = ' + "{0:.3f}".format( self.DVmagorThrottle) + ' $km/s$' #always append the spacecraft Mass description += '\nm = ' + "{0:.0f}".format(self.Mass) + ' $kg$' #draw the text #note, do not draw anything for chemical burns below 10 m/s if not (self.EventType == "chem_burn" and self.DVmagorThrottle < 0.001): x2D, y2D, _ = proj3d.proj_transform(self.SpacecraftState[0], self.SpacecraftState[1], self.SpacecraftState[2], GraphicsObject.get_proj()) self.eventlabel = plt.annotate(description, xycoords='data', xy=(x2D, y2D), xytext=(20, 20), textcoords='offset points', ha='left', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='white', alpha=0.5), arrowprops=dict( arrowstyle='->', connectionstyle='arc3,rad=0'), size=PlotOptions.FontSize) self.AnnotationHelper = self.eventlabel.draggable(use_blit=True) self.pcid = GraphicsObject.figure.canvas.mpl_connect( 'button_press_event', self.ClickAnnotation) self.rcid = GraphicsObject.figure.canvas.mpl_connect( 'button_release_event', self.ReleaseAnnotation)
def do_3d_projection(self, render=None): from mpl_toolkits.mplot3d import proj3d xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) return np.min(zs)
# -*- coding: utf-8 -*- """ Created on Sat Jun 16 13:06:57 2018 @author: Otm """ import pylab from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d fig = pylab.figure() ax = fig.add_subplot(111, projection='3d') x = y = z = [1, 2, 3] sc = ax.scatter(x, y, z) # now try to get the display coordinates of the first point x2, y2, _ = proj3d.proj_transform(1, 1, 1, ax.get_proj())
def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M) self.xy = (xs, ys) Annotation.draw(self, renderer)
def __init__(self, groups): points = [g['center'] for g in groups] self.points = points self.groups = groups # color = iter(plt.cm.rainbow(np.linspace(0, 1, len(set(deals))))) colors = get_colors(len(groups)) self.fig = plt.figure(1) plt.rcParams['figure.figsize'] = 9, 9 self.fig_text = plt.figure(2) self.fig_buttons = plt.figure(3) # Doing some layout with subplots: # fig = plt.figure() self.ax = self.fig.gca(projection='3d') self.ax.set_xlabel('x') self.ax.set_ylabel('y') self.ax.set_zlabel('z') # plot main figure labels = [] buttons = [] # cursors = [] for i_col, group in enumerate(self.groups): ax_button = self.fig_buttons.add_subplot(len(groups), 1, i_col + 1) # cursor = Cursor(ax_button, useblit=True, color='black', linewidth=2) c = group['center'] r = group['radius'] self.ax.scatter(c[0], c[1], c[2], s=1e3 * r, c=colors[i_col]) group_button = ButtonClickProcessor(ax_button, label=i_col, color=colors[i_col], viewer=self) x_proj, y_proj, _ = proj3d.proj_transform(c[0], c[1], c[1], self.ax.get_proj()) label = self.ax.annotate(str(i_col), xy=(x_proj, y_proj), xytext=(-20, 20), textcoords='offset points', ha='right', va='top', fontsize=12, bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops = dict(arrowstyle='->', connectionstyle='arc3,rad=0')) labels.append(label) buttons.append(group_button) # cursors.append(cursor) self.labels = labels # self.buttons = buttons # self.cursors = cursors # lgd = self.ax.legend(loc=9, bbox_to_anchor=(0.5,0)) # self.ax.legend() self.fig_buttons.canvas.draw() #connect events self.fig.canvas.mpl_connect('button_release_event', self.update_position)
def draw(self, renderer): from mpl_toolkits.mplot3d import proj3d xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) FancyArrowPatch.draw(self, renderer)
def pcaSubplot_vars(self, X_r, dim, varData, varName, PCs_round, labels, template_list, dpiVal): """ Get the Principal Component Analysis data for this set of coordinates The value of 'dim' specifies the number of dimensions to diplay Then plot the PCA data """ # Set some figure parameters plt.rcParams['xtick.major.pad'] = '8' plt.rcParams['ytick.major.pad'] = '8' # Divide up the data to plot into general conformations and templates. # The colormap data is not used for the templates, and a different # marker is used. templatePosition = [] confData = [] confPosition = [] for l, d, x in zip(labels, varData, X_r): if l in template_list: templatePosition.append(x) else: confData.append(d) confPosition.append(x) templatePosition = np.array(templatePosition) confPosition = np.array(confPosition) # Plot either PCA data on 2D or 3D if dim == 2: # Create figure and subplot fig = plt.figure(figsize=(17, 13), dpi=dpiVal) fig.set_facecolor('white') fig.canvas.set_window_title("PCA 2D") ax = fig.add_subplot(111) # Scatter conformations. Designated by circles, colored based on # IFP similarity to a defined template scat = ax.scatter(confPosition[:, 0], confPosition[:, 1], s=600, marker="o", cmap=plt.cm.magma, c=confData, vmin=0.0, vmax=1.0) # Scatter the template conformation(s). Designated by arrows. ax.scatter(templatePosition[:, 0], templatePosition[:, 1], s=600, marker="v", color="black") # Setting labels for both conformations and templates for label, x, y in zip(labels, X_r[:, 0], X_r[:, 1]): ax.annotate(label, xy=(x, y + 0.05), fontsize=30, ha='center', va='bottom') # Settin axis and labels ax.set_xlabel("PC1 ({} %)".format(PCs_round[0]), fontsize=30) ax.set_ylabel("PC2 ({} %)".format(PCs_round[1]), fontsize=30) ax.tick_params(axis="both", which="major", labelsize=25) # Plot the colorbar cb = plt.colorbar(scat) cb.set_label(varName, size=30) cb.ax.tick_params(labelsize=25) # 3D figure if dim == 3: # Create figure and subplot fig = plt.figure() fig.set_facecolor('white') fig.canvas.set_window_title("PCA 3D") ax = fig.add_subplot(111, projection='3d') # Conformations scat = ax.scatter(confPosition[:, 0], confPosition[:, 1], confPosition[:, 2], s=200, marker="o", cmap=plt.cm.magma, c=confData, vmin=0.0, vmax=1.0) # Templates ax.scatter(templatePosition[:, 0], templatePosition[:, 1], templatePosition[:, 2], c="black", s=200, marker="v") # Scatter plot labels for label, x, y, z in zip(labels, X_r[:, 0], X_r[:, 1], X_r[:, 2]): if label != "": x2D, y2D, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) ax.annotate(label, xy=(x2D, y2D), fontsize=10, ha='left', va='top') # Setting axis and labelsize ax.set_xlabel("PC1 ({} %)".format(PCs_round[0]), fontsize=10) ax.set_ylabel("PC2 ({} %)".format(PCs_round[1]), fontsize=10) ax.set_zlabel("PC3 ({} %)".format(PCs_round[2]), fontsize=10) ax.tick_params(axis="both", which="major", labelsize=10) # Plot the colorbar cb = plt.colorbar(scat) cb.set_label(varName, size=10) cb.ax.tick_params(labelsize=10)
def do_3d_projection(self, renderer=None): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) return np.min(zs)
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection from mpl_toolkits.mplot3d import proj3d fig = plt.figure() ax = fig.add_subplot(111, projection='3d') vertices = vv #colors = colors = "bgrcmykw" for i, poly in enumerate(parsed): ax.add_collection3d(Poly3DCollection([poly[1]], alpha=0.5)) #ax.scatter([x[0] for i,x in enumerate(vertices)],[x[1] for x in vertices],[x[2] for x in vertices]) ax.scatter([x[0] for x in vv], [x[1] for x in vv], [x[2] for x in vv]) ax.scatter(vertices_np[:, 0], vertices_np[:, 1], vertices_np[:, 2]) ax.auto_scale_xyz([-a, a], [-a, a], [-a, a]) for a, p in vdict.iteritems(): tr = proj3d.proj_transform(p[0], p[1], p[2], ax.get_proj()) ax.annotate(str(a), (tr[0], tr[1])) a = 0.6 plt.show() exit() print output_np fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(output_np, interpolation='none') numrows, numcols = output_np.shape def format_coord(x, y): col = int(x + 0.5) row = int(y + 0.5)
def draw(self, renderer): x3d, y3d, z3d = self._verts3d x, y, z = proj3d.proj_transform(x3d, y3d, z3d, renderer.M) self.center = x, y Circle.draw(self, renderer)