def plotPackedBeam(coordinates, angle, axis1, axis2, boresight, equaltorial_range, pixel_range, beamRadius, fileName='pack.png', scope=1., transparency = 1., index = False, HD = True): #angle = 180 - angle # print("tiling angle: %.2f" % angle) # angle = angle - 90 thisDpi = 96 matplotlib.rcParams.update({'font.size': 8}) plt.clf() if HD == True: fig = plt.figure(figsize=(1600./thisDpi, 1200./thisDpi), dpi=thisDpi) else: fig = plt.figure(figsize=(400./thisDpi, 300./thisDpi), dpi=thisDpi) # plt.axes().set_aspect('equal', 'datalim') axis = fig.add_subplot(111, aspect='equal') # center = coordinates[0] for idx in range(len(coordinates)): coord = coordinates[idx] ellipse = Ellipse(xy=coord, width=2*axis1, height=2*axis2, angle=angle, alpha = transparency) ellipse.fill = False axis.add_artist(ellipse) if index == True: axis.text(coord[0], coord[1], idx, size=6, ha='center', va='center') gridCenter = [0,0] circle = Ellipse(xy=gridCenter, width=2*beamRadius, height=2*beamRadius, angle=0) circle.fill = False axis.add_artist(circle) margin = beamRadius*1.3*scope axis.set_xlim(gridCenter[0]-2*margin, gridCenter[0]+2*margin) axis.set_ylim(gridCenter[1]-2*margin, gridCenter[1]+2*margin) beamNum = len(coordinates) xTicks = FixedLocator([pixel_range[0], 0, pixel_range[1]]) xTicksLabel = FixedFormatter(["{:.2f}".format(equaltorial_range[0]), "{:.2f}".format(boresight[0]), "{:.2f}".format(equaltorial_range[1])]) axis.xaxis.set_major_formatter(xTicksLabel) axis.xaxis.set_major_locator(xTicks) axis.set_xlabel("RA") yTicks = FixedLocator([pixel_range[2], 0, pixel_range[3]]) yTicksLabel = FixedFormatter(["{:.2f}".format(equaltorial_range[2]), "{:.2f}".format(boresight[1]), "{:.2f}".format(equaltorial_range[3])]) axis.yaxis.set_major_formatter(yTicksLabel) axis.yaxis.set_major_locator(yTicks) axis.yaxis.set_tick_params(rotation=90) axis.set_ylabel("DEC") fig.tight_layout() plt.savefig(fileName, dpi=thisDpi) plt.close()
def plotBeamFit(sideLength, center, ellipseCenter, angle, axis1, axis2, fileName='fit.png'): halfSideLength = sideLength/2.0 xMin = center[0] - halfSideLength xMax = center[0] + halfSideLength yMin = center[1] - halfSideLength yMax = center[1] + halfSideLength thisDpi = 96 matplotlib.rcParams.update({'font.size': 8}) plt.clf() fig = plt.figure(figsize=(400./thisDpi, 300./thisDpi), dpi=thisDpi) plt.subplots_adjust(right=0.92) ax = fig.add_subplot(111, aspect='equal') # step=sideLength/20.0 # trueCenter = [center[0] + step/2., center[1] - step/2.] ellipse = Ellipse(xy=ellipseCenter, width=2*axis1, height=2*axis2, angle=angle) ellipse.fill = False ax.add_artist(ellipse) radius = max(axis1, axis2) ax.set_xlim(xMin, xMax) ax.set_ylim(yMin, yMax) # ax.get_xaxis().set_visible(False) # ax.get_yaxis().set_visible(False) # ax.patch.set_visible(False) # fig.patch.set_visible(False) ax.axis('off') plt.savefig(fileName, transparent=True, dpi=thisDpi) plt.close()
def plotBeamWithFit(array, center, sideLength, widthH, widthV, angle, fileName='contourfit.png', interpolation = True): thisDpi = 96. matplotlib.rcParams.update({'font.size': 8}) fig = plt.figure(figsize=(400./thisDpi, 300./thisDpi), dpi=thisDpi) axis = fig.gca() if type(sideLength) == list: plotRange = sideLength else: halfSideLength = sideLength/2.0 xStart = (center[0] - halfSideLength) xEnd = (center[0] + halfSideLength) yStart = (center[1] - halfSideLength) yEnd = (center[1] + halfSideLength) plotRange = [xStart, xEnd, yStart, yEnd] interpolateOption = 'bicubic' if interpolation == True else 'nearest' ims = axis.imshow(np.fliplr(array), cmap=plt.cm.jet, vmin=0, vmax=1, # interpolation=interpolateOption, extent=plotRange) interpolation=interpolateOption, aspect = 'equal', origin='bottom') imageShape = array.shape gridCenter = ((imageShape[1]/2.0 - 1), (imageShape[0]/2.0)) # print("plot angle: %.2f" % angle) ellipse = Ellipse(gridCenter, width=2*widthH, height=2*widthV, angle= angle) ellipse.fill = False axis.add_artist(ellipse) fig.colorbar(ims) axis.set_aspect('auto') xTicks = FixedLocator([0, gridCenter[0], imageShape[1]-1]) xTicksLabel = FixedFormatter(["{:.2f}".format(plotRange[0]), "{:.2f}".format(center[0]), "{:.2f}".format(plotRange[1])]) axis.xaxis.set_major_formatter(xTicksLabel) axis.xaxis.set_major_locator(xTicks) axis.set_xlabel("RA") yTicks = FixedLocator([0, gridCenter[1], imageShape[0]-1]) yTicksLabel = FixedFormatter(["{:.2f}".format(plotRange[3]), "{:.2f}".format(center[1]), "{:.2f}".format(plotRange[2])]) axis.yaxis.set_major_formatter(yTicksLabel) axis.yaxis.set_major_locator(yTicks) axis.yaxis.set_tick_params(rotation=90) axis.set_ylabel("DEC") # plt.subplots_adjust(left=0.20, right=1.00) # axes = plt.gca() # axes.set_xlim([x.min(),x.max()]) # axes.set_ylim([y.min(),y.max()]) # plt.xlabel('Right Ascension') # plt.ylabel('Declination') plt.savefig(fileName, dpi=thisDpi) plt.close()
def plot_beam_shape(array, center, sideLength, ellipseCenter, axis1, axis2, angle, fileName='contour.png', interpolation = True): thisDpi = 96. matplotlib.rcParams.update({'font.size': 8}) fig = plt.figure(figsize=(400./thisDpi, 300./thisDpi), dpi=thisDpi) halfSideLength = sideLength/2.0 xStart = (center[0] - halfSideLength) xEnd = (center[0] + halfSideLength) yStart = (center[1] - halfSideLength) yEnd = (center[1] + halfSideLength) plotRange = [xStart, xEnd, yStart, yEnd] interpolateOption = 'bicubic' if interpolation == True else 'nearest' plt.imshow(array,cmap=plt.cm.jet, vmin=0, vmax=1, interpolation=interpolateOption, extent=plotRange) plt.colorbar() ax = fig.gca() ax.set_aspect('equal', 'datalim') ellipse = Ellipse(xy=ellipseCenter, width=2*axis1, height=2*axis2, angle=angle) ellipse.fill = False ax.add_artist(ellipse) plt.savefig(fileName, dpi=thisDpi) plt.close()
def plot_poincare(working_data, measures, show=True, title='Poincare plot'): # pragma: no cover '''visualize poincare plot function that visualises poincare plot. Parameters ---------- working_data : dict dictionary object that contains all heartpy's working data (temp) objects. will be created if not passed to function measures : dict dictionary object used by heartpy to store computed measures. Will be created if not passed to function title : str the title used in the plot Returns ------- out : matplotlib plot object only returned if show == False. Examples -------- This function has no examples. See documentation of heartpy for more info. ''' #get color palette colorpalette = config.get_colorpalette_poincare() #get values from dict x_plus = working_data['poincare']['x_plus'] x_minus = working_data['poincare']['x_minus'] sd1 = measures['sd1'] sd2 = measures['sd2'] #define figure fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}) #plot scatter plt.scatter(x_plus, x_minus, color=colorpalette[0], alpha='0.75', label='peak-peak intervals') #plot identity line mins = np.min([x_plus, x_minus]) maxs = np.max([x_plus, x_minus]) identity_line = np.linspace(np.min(mins), np.max(maxs)) plt.plot(identity_line, identity_line, color='black', alpha=0.5, label='identity line') #rotate SD1, SD2 vectors 45 degrees counterclockwise sd1_xrot, sd1_yrot = rotate_vec(0, sd1, 45) sd2_xrot, sd2_yrot = rotate_vec(0, sd2, 45) #plot rotated SD1, SD2 lines plt.plot([np.mean(x_plus), np.mean(x_plus) + sd1_xrot], [np.mean(x_minus), np.mean(x_minus) + sd1_yrot], color=colorpalette[1], label='SD1') plt.plot([np.mean(x_plus), np.mean(x_plus) - sd2_xrot], [np.mean(x_minus), np.mean(x_minus) + sd2_yrot], color=colorpalette[2], label='SD2') #plot ellipse xmn = np.mean(x_plus) ymn = np.mean(x_minus) el = Ellipse((xmn, ymn), width=sd2 * 2, height=sd1 * 2, angle=45.0) ax.add_artist(el) el.set_edgecolor((0, 0, 0)) el.fill = False plt.legend(loc=4, framealpha=0.6) plt.title(title) if show: plt.show() else: return plt
plt.plot(xvert,yvert,'ro') plt.plot(np.array([xvert,fpx]),np.array([yvert,fpy]),'r') # Extreme rays s = np.linspace(0,1000,num=1000) ang = (ytop - fpy)/(xtop-fpx) plt.plot([xtop,fpx],[ytop,fpy],'g--') plt.plot([xbot,fpx],[ybot,fpy],'g--') # Figure out how tipped my viewing angle is skew_ang = np.radians(1.4) view_skew_ell = Ellipse(xy=(xtop+D_pri_pix*np.cos(tilt)/2,ytop+D_pri_pix*np.sin(tilt)/2), width=D_pri_pix, height=D_pri_pix*np.sin(skew_ang), angle=tilt_pri) view_skew_ell.fill=False ax.add_artist(view_skew_ell) plt.plot(xe,ye,'c') plt.plot(f1x,f1y,'co') plt.plot(f2x,f2y,'co') if True: plt.xlim([0,xmax]) plt.ylim([ymax,0]) else: plt.xlim([1200,2200]) plt.ylim([1500,500])
def plot_all(interferometry, beamshape, overlap, retile, fileName): thisDpi = 96 matplotlib.rcParams.update({'font.size': 8}) fig = plt.figure(figsize=(1024. / thisDpi, 1024. / thisDpi), dpi=thisDpi) fig, axs = plt.subplots(2, 2) """ array configuraton parameters: interferometry """ def angleToCartesian(angleDeg, radius): angle = np.deg2rad(angleDeg) if angle <= np.pi / 2: x = np.sin(angle) * radius y = np.cos(angle) * radius elif angle > np.pi / 2 and angle <= np.pi: x = np.sin(angle) * radius y = np.cos(angle) * radius elif angle > np.pi and angle <= np.pi * 1.5: x = np.sin(angle) * radius y = np.cos(angle) * radius elif angle > np.pi * 1.5 and angle <= np.pi * 2: x = np.sin(angle) * radius y = np.cos(angle) * radius return x, y antennas = interferometry[0] center = interferometry[1] horizons = interferometry[2] antennas = np.array(antennas) antX = antennas[:, 1] - center[1] antY = antennas[:, 0] - center[0] antXMax = np.abs(antX).max() antYMax = np.abs(antY).max() radius = antXMax * 1.2 if antXMax > antYMax else antYMax * 1.2 pointSize = 3 thisDpi = 96 ax = axs[0, 0] ax.set_title("Array and Source") "cartisian" ax.plot([-radius, radius, 0, 0, 0], [0, 0, 0, radius, -radius], c="k", alpha=0.1) "antennas" ants = ax.scatter(antX, antY, s=pointSize) "horizon" horizon = plt.Circle((0, 0), radius, fill=False) ax.add_artist(horizon) horizons = np.array(horizons) if isinstance(horizons[0], np.ndarray): azi0, alt0 = horizons[0] else: azi0, alt0 = horizons lineStyle = '--' if alt0 < 0 else '-' "altitude" altRadius = (90 - np.abs(alt0)) / 90. * radius altCircle = plt.Circle((0, 0), altRadius, fill=False, alpha=0.1, ls=lineStyle) ax.add_artist(altCircle) "azimuth" x, y = angleToCartesian(azi0, radius) aziLine, = ax.plot([0, x], [0, y], ls=lineStyle, alpha=0.1) "source" starColor = 'black' if alt0 < 0 else 'blue' starX, starY = angleToCartesian(azi0, altRadius) star, = ax.plot(starX, starY, marker='*') star.set_color(starColor) ax.set_aspect('equal', 'datalim') ax.set_xlim([-radius * 1.3, +radius * 1.3]) ax.set_ylim([-radius * 1.3, +radius * 1.3]) ax.legend([star, ants, horizon], ["source", "antennas", "horizon"], loc="upper right") """ beam shape with fit parameters: beamshape """ axis = axs[0, 1] axis.set_title("Beam shape simulation") array, center, sideLength, widthH, widthV, angle, drop, interpolation = beamshape if type(sideLength) == list: plotRange = sideLength else: halfSideLength = sideLength / 2.0 xStart = (center[0] - halfSideLength) xEnd = (center[0] + halfSideLength) yStart = (center[1] - halfSideLength) yEnd = (center[1] + halfSideLength) plotRange = [xStart, xEnd, yStart, yEnd] interpolateOption = 'bicubic' if interpolation == True else 'nearest' ims = axis.imshow( array, cmap=plt.cm.jet, vmin=0, vmax=1, # interpolation=interpolateOption, extent=plotRange) interpolation=interpolateOption, aspect='equal', origin='lower') imageShape = array.shape # gridCenter = ((imageShape[1]/2.0 - 1), (imageShape[0]/2.0)) gridCenter = ((imageShape[1] / 2.0), (imageShape[0] / 2.0)) # print("plot angle: %.2f" % angle) ellipse = Ellipse(gridCenter, width=2 * widthH, height=2 * widthV, angle=angle) ellipse.fill = False axis.add_artist(ellipse) # fig.colorbar(ims) axis.set_aspect('equal') xTicks = FixedLocator([0, gridCenter[0], imageShape[1] - 1]) xTicksLabel = FixedFormatter([ "{:.2f}".format(plotRange[0]), "{:.2f}".format(center[0]), "{:.2f}".format(plotRange[1]) ]) axis.xaxis.set_major_locator(xTicks) axis.xaxis.set_major_formatter(xTicksLabel) axis.xaxis.set_tick_params(tickdir="out", tick2On=False) axis.set_xlabel("Right Ascension") yTicks = FixedLocator([0, gridCenter[1], imageShape[0] - 1]) yTicksLabel = FixedFormatter([ "{:.2f}".format(plotRange[3]), "{:.2f}".format(center[1]), "{:.2f}".format(plotRange[2]) ]) axis.yaxis.set_major_locator(yTicks) axis.yaxis.set_major_formatter(yTicksLabel) axis.yaxis.set_tick_params(tickdir="out", tick2On=False) axis.set_ylabel("Declination") # plt.yticks(axis.get_yticks(), visible=True, rotation="vertical") """ overlap parameters: overlap """ axis = axs[1, 0] axis.set_title("Tiling Overlap") overlapTables, mode, drop, title = overlap overlapTables = np.array(overlapTables) if isinstance(overlapTables[0][0], np.ndarray): animate = True else: animate = False pointSize = 10 thisDpi = 96 if title != None: pass # plt.title(title) else: pass overlapTable0 = overlapTables if mode == "counter": image = axis.imshow(overlapTable0, cmap=plt.cm.jet, vmin=0, vmax=2) else: image = axis.imshow(overlapTable0, cmap=plt.cm.jet, vmin=0) axis.set_aspect('equal', 'datalim') # fig.tight_layout() """ reitle parameters: retile """ axis = axs[1, 1] axis.set_title("Tiling Efficiency") counter, x, xMax, threshold = retile counter = np.array(counter) axis.set_xlim([x[0], xMax]) axis.set_ylim([-0.05, 1.05]) axis.plot(x, counter[:, 0], c='r', ls='-', label='overlap') axis.plot(x, counter[:, 1], c='g', ls='-', label='non-overlap') axis.plot(x, counter[:, 2], c='b', ls='-', label='empty') axis.axhline(threshold, ls='--', lw=0.5) axis.legend(loc="center right") # axis.ylabel('overlap fraction') fig.tight_layout() plt.savefig(fileName) fig.clf() plt.close(fig) plt.clf() plt.close()
for idx in range(len(beam_coordinate)): coord = beam_coordinate[idx] if index == True: num = indice[idx].split('cfbf')[-1] axis.text(coord[0], coord[1], int(num), size=6, ha='center', va='center') ellipse = Ellipse(xy=coord, width=2. * axis1 / resolution, height=2. * axis2 / resolution, angle=angle) ellipse.fill = False if inner > 0 and idx < inner: ellipse.fill = True ellipse.edgecolor = 'auto' inner_idx.append(int(num)) if idx == 0: ellipse.facecolor = '#4169E1' else: ellipse.facecolor = '#0F52BA' axis.add_artist(ellipse) margin = 1.1 * max(np.sqrt(np.sum(np.square(beam_coordinate), axis=1))) axis.set_xlim(center[0] - margin, center[0] + margin) axis.set_ylim(center[1] - margin, center[1] + margin) if args.extra_source is not None: extra_coords = np.genfromtxt(args.extra_source[0], dtype=None)
def plotPackedBeam2(coordinates, angle, axis1, axis2, boresight, equaltorial_range, pixel_range, tiling_meta, fileName='pack.png', scope=1., show_axis=True, extra_coordinates=[], extra_coordinates_text=[], subGroup=[], transparency=1., edge=True, index=False, HD=True, raw=False): #angle = 180 - angle # print("tiling angle: %.2f" % angle) # angle = angle - 90 thisDpi = 96 matplotlib.rcParams.update({'font.size': 8}) plt.clf() if HD == True: fig = plt.figure(figsize=(1600. / thisDpi, 1600. / thisDpi), dpi=thisDpi) else: fig = plt.figure(figsize=(400. / thisDpi, 400. / thisDpi), dpi=thisDpi) # plt.axes().set_aspect('equal', 'datalim') axis = fig.add_subplot(111, aspect='equal') center = coordinates[0] for idx in range(len(coordinates)): coord = coordinates[idx] ellipse = Ellipse(xy=coord, width=2 * axis1, height=2 * axis2, angle=angle, alpha=transparency) ellipse.fill = False axis.add_artist(ellipse) if index == True: axis.text(coord[0], coord[1], idx, size=6, ha='center', va='center') for group in subGroup: subCoordinates, subAngle, subAxis1, subAxis2 = group for idx in range(len(subCoordinates)): coord = subCoordinates[idx] ellipse = Ellipse(xy=coord, width=2 * subAxis1, height=2 * subAxis2, angle=subAngle, alpha=transparency) ellipse.fill = False axis.add_artist(ellipse) for idx in range(len(extra_coordinates)): coord = extra_coordinates[idx] circle = Circle(xy=coord, radius=0.0006) axis.add_artist(circle) if extra_coordinates_text != []: axis.text(coord[0], coord[1], extra_coordinates_text[idx], size=5, ha='center', va='center') gridCenter = [0, 0] tilingScale = tiling_meta["scale"] if edge == True: shape = tiling_meta["shape"] if shape == "circle": edge = Circle(xy=gridCenter, radius=tilingScale, alpha=0.1, linewidth=3) elif shape == "ellipse": a, b, angle = tiling_meta["parameter"] edge = Ellipse(xy=gridCenter, width=2 * a, height=2 * b, angle=angle, alpha=0.1, linewidth=3) elif shape == "hexagon": angle = tiling_meta["parameter"][1] edge = RegularPolygon(xy=gridCenter, numVertices=6, radius=tilingScale, orientation=angle, alpha=0.1, linewidth=3) elif shape == "polygon": vertices = tiling_meta["parameter"] edge = Polygon(xy=vertices, closed=True, alpha=0.1, linewidth=3) if shape == "annulus": for annulus in tiling_meta["parameter"]: annulus_type = annulus[0] if annulus_type == "polygon": vertices = annulus[1] edge = Polygon(xy=vertices, closed=True, alpha=0.1, linewidth=3) elif annulus_type == "ellipse": a, b, angle = annulus[1] edge = Ellipse(xy=gridCenter, width=2 * a, height=2 * b, angle=angle, alpha=0.1, linewidth=3) edge.fill = False axis.add_artist(edge) else: edge.fill = False axis.add_artist(edge) margin = tilingScale * 1.3 * scope axis.set_xlim(gridCenter[0] - margin, gridCenter[0] + margin) axis.set_ylim(gridCenter[1] - margin, gridCenter[1] + margin) beamNum = len(coordinates) if show_axis != True: plt.xticks([]) plt.yticks([]) else: xTicks = FixedLocator([pixel_range[0], 0, pixel_range[1]]) xTicksLabel = FixedFormatter([ "{:.2f}".format(equaltorial_range[0]), "{:.2f}".format(boresight[0]), "{:.2f}".format(equaltorial_range[1]) ]) axis.xaxis.set_major_locator(xTicks) axis.xaxis.set_major_formatter(xTicksLabel) axis.xaxis.set_tick_params(tickdir="out", tick2On=False) axis.set_xlabel("RA", size=20) plt.xticks(axis.get_xticks(), visible=True, size=20) yTicks = FixedLocator([pixel_range[2], 0, pixel_range[3]]) yTicksLabel = FixedFormatter([ "{:.2f}".format(equaltorial_range[2]), "{:.2f}".format(boresight[1]), "{:.2f}".format(equaltorial_range[3]) ]) axis.yaxis.set_major_locator(yTicks) axis.yaxis.set_major_formatter(yTicksLabel) axis.yaxis.set_tick_params(tickdir="out", tick2On=False) axis.set_ylabel("DEC", size=20) plt.yticks(axis.get_yticks(), visible=True, rotation="vertical", size=20) fig.tight_layout() plt.savefig(fileName, dpi=thisDpi) plt.close()
def plotBeamWithFit(array, center, sideLength, widthH, widthV, angle, resolution, fileName='contourfit.png', colormap=False, interpolation=True, shapeOverlay=False): thisDpi = 96. matplotlib.rcParams.update({'font.size': 8}) shape = np.array(array).shape step = resolution wcs_properties = wcs.WCS(naxis=2) wcs_properties.wcs.crpix = [shape[1] / 2. - 0.5, shape[0] / 2. - 0.5] wcs_properties.wcs.cdelt = [-step, step] wcs_properties.wcs.crval = center wcs_properties.wcs.ctype = ["RA---TAN", "DEC--TAN"] if (colormap == True): fig = plt.figure(figsize=(400. / thisDpi, 300. / thisDpi), dpi=thisDpi) else: fig = plt.figure(figsize=(400. / thisDpi, 400. / thisDpi), dpi=thisDpi) axis = fig.add_subplot(111, aspect='equal', projection=wcs_properties) interpolateOption = 'bicubic' if interpolation == True else 'nearest' ims = axis.imshow(array, cmap=plt.cm.jet, vmin=0, vmax=1, interpolation=interpolateOption, aspect='equal', origin='lower') imageShape = array.shape if shapeOverlay == True: gridCenter = ((imageShape[1] / 2.0), (imageShape[0] / 2.0)) ellipse = Ellipse(gridCenter, width=2 * widthH / resolution, height=2 * widthV / resolution, angle=angle) ellipse.fill = False axis.add_artist(ellipse) if (colormap == True): fig.colorbar(ims) fig.tight_layout() axis.set_aspect('auto') ra = axis.coords[0] dec = axis.coords[1] ra.set_major_formatter('hh:mm:ss') ra.set_ticklabel(size=8) dec.set_ticklabel(size=8, rotation="vertical") dec.set_ticks_position('l') ra.set_ticks_position('b') ra.set_axislabel("RA", size=8) dec.set_major_formatter('dd:mm:ss') dec.set_axislabel("DEC", size=8) plt.subplots_adjust(left=0.10, bottom=0.10, right=0.98, top=0.96, wspace=0, hspace=0) plt.savefig(fileName, dpi=thisDpi) plt.close()
def plotPackedBeam(coordinates, angle, axis1, axis2, boresight, tiling_meta, fileName='pack.png', scope=1., show_axis=True, extra_coordinates=[], extra_coordinates_text=[], subGroup=[], transparency=1., edge=True, index=False, HD=True, raw=False): step = 1 / 10000000000. wcs_properties = wcs.WCS(naxis=2) wcs_properties.wcs.crpix = [0, 0] wcs_properties.wcs.cdelt = [-step, step] wcs_properties.wcs.crval = boresight wcs_properties.wcs.ctype = ["RA---TAN", "DEC--TAN"] center = boresight resolution = step thisDpi = 96 matplotlib.rcParams.update({'font.size': 8}) plt.clf() if HD == True: fig = plt.figure(figsize=(1600. / thisDpi, 1600. / thisDpi), dpi=thisDpi) else: fig = plt.figure(figsize=(400. / thisDpi, 400. / thisDpi), dpi=thisDpi) axis = fig.add_subplot(111, aspect='equal', projection=wcs_properties) beam_coordinate = np.array(coordinates) / resolution # beam_coordinate += [center[0] - 1, 0] # beam_coordinate = [0, center[1] - 1] + [1, -1]*beam_coordinate for idx in range(len(beam_coordinate)): coord = beam_coordinate[idx] ellipse = Ellipse(xy=coord, width=2. * axis1 / resolution, height=2. * axis2 / resolution, angle=angle, alpha=transparency) ellipse.fill = False axis.add_artist(ellipse) if index == True: axis.text(coord[0], coord[1], idx, size=6, ha='center', va='center') for group in subGroup: subCoordinates, subAngle, subAxis1, subAxis2 = group for idx in range(len(subCoordinates)): coord = subCoordinates[idx] / resolution ellipse = Ellipse(xy=coord, width=2 * subAxis1 / resolution, height=2 * subAxis2 / resolution, angle=subAngle, alpha=transparency) ellipse.fill = False axis.add_artist(ellipse) for idx in range(len(extra_coordinates)): coord = extra_coordinates[idx] / resolution circle = Circle(xy=coord, radius=0.0006) axis.add_artist(circle) if extra_coordinates_text != []: axis.text(coord[0], coord[1], extra_coordinates_text[idx], size=5, ha='center', va='center') gridCenter = center tilingScale = tiling_meta["scale"] if edge == True: shape = tiling_meta["shape"] if shape == "circle": edge = Circle(xy=gridCenter, radius=tilingScale / resolution, alpha=0.1, linewidth=3) elif shape == "ellipse": a, b, angle = tiling_meta["parameter"] edge = Ellipse(xy=gridCenter, width=2 * a / resolution, height=2 * b / resolution, angle=angle, alpha=0.1, linewidth=3) elif shape == "hexagon": if tiling_meta["parameter"] is not None: angle = tiling_meta["parameter"][1] else: angle = 0 edge = RegularPolygon(xy=gridCenter, numVertices=6, radius=tilingScale / resolution, orientation=np.deg2rad(60. - angle), alpha=0.1, linewidth=3) elif shape == "polygon": vertices = tiling_meta["parameter"] edge = Polygon(xy=np.array(vertices) / resolution, closed=True, alpha=0.1, linewidth=3) if shape == "annulus": for annulus in tiling_meta["parameter"]: annulus_type = annulus[0] if annulus_type == "polygon": vertices = annulus[1] edge = Polygon(xy=np.array(vertices) / resolution, closed=True, alpha=0.1, linewidth=3) elif annulus_type == "ellipse": a, b, angle = annulus[1] edge = Ellipse(xy=gridCenter, width=2 * a / resolution, height=2 * b / resolution, angle=angle, alpha=0.1, linewidth=3) edge.fill = False axis.add_artist(edge) else: edge.fill = False axis.add_artist(edge) margin = tilingScale / step * 1.3 * scope axis.set_xlim(gridCenter[0] - margin, gridCenter[0] + margin) axis.set_ylim(gridCenter[1] - margin, gridCenter[1] + margin) fig.tight_layout() if show_axis != True: plt.xticks([]) plt.yticks([]) else: ra = axis.coords[0] dec = axis.coords[1] ra.set_ticklabel(size=20) dec.set_ticklabel(size=20, rotation="vertical") dec.set_ticks_position('l') ra.set_major_formatter('hh:mm:ss') ra.set_ticks_position('b') ra.set_axislabel("RA", size=20) dec.set_major_formatter('dd:mm:ss') dec.set_axislabel("DEC", size=20) plt.subplots_adjust(left=0.04, bottom=0.05, right=0.98, top=0.96, wspace=0, hspace=0) plt.savefig(fileName, dpi=thisDpi) plt.close()
def createBeamshapeModel(originalImage, density, windowLength, interpolatedLength = 800): interpolater = interpolate.interp2d(range(density), range(density), originalImage, kind='cubic') image = interpolater(np.linspace(0, density, interpolatedLength, endpoint = False), np.linspace(0, density, interpolatedLength, endpoint = False)) samples = [] # levels = np.arange(0.1, 0.9 + 0.025, 0.025).tolist() levels = np.linspace(0.1, 0.9, 1 + int((0.9 - 0.1)/0.025)).tolist() # print(levels) # levels = [0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.975] # levels = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8] plot = False if plot == True: thisDpi = 96 fig = plt.figure(figsize=(1200./thisDpi,1200./thisDpi), dpi=thisDpi) ax0 = plt.subplot2grid((6, 6), (3, 0), colspan=3, rowspan=3) ax1 = plt.subplot2grid((6, 6), (3, 3), colspan=3, rowspan=3) ax2 = plt.subplot2grid((6, 6), (0, 0), colspan=6) ax3 = plt.subplot2grid((6, 6), (1, 0), colspan=6) ax4 = plt.subplot2grid((6, 6), (2, 0), colspan=6) ax0.imshow(image, cmap="jet") ax0.title.set_text('Contour') ax1.imshow(image, cmap="jet") ax1.title.set_text('Fit') else: fig, ax0 = plt.subplots() contour = ax0.contour(image, levels) dataShape = image.shape center = np.unravel_index(image.argmax(), dataShape) count = 0.1 for segs, coll in zip(contour.allsegs, contour.collections): count += 0.025 powerline = None fulllength = 0 segLength = len(segs) if segLength > 1: for seg in segs: fulllength += len(seg) minimalLength = int(fulllength * 0.2) paths = coll.get_paths() pathIndexToDel = [] for segIndex, seg in enumerate(segs): if len(seg) < minimalLength: pathIndexToDel.append(segIndex) continue if powerline is None: powerline = seg else: powerline = np.concatenate((powerline, seg)) pathIndexToDel.reverse() for index in pathIndexToDel: del(paths[index]) # print("small contour of length {} at level {} delelted".format( # len(segs[index]), levels[len(samples)])) elif segLength == 1: powerline = np.array(segs[0]) else: powerline = None if powerline is None: if count > 0.2: logger.warning('level {} countour is None!'.format(count)) para = [np.nan, np.nan, 0, 0, np.nan] else: para = fitContour(powerline) samples.append(para) if plot == True: ellipse = Ellipse(center, width=2*para[0], height=2*para[1], angle=np.rad2deg(para[4])) ellipse.fill = False ax1.add_artist(ellipse) ### check NaN ## samples = np.array(samples).T for sampleIndex in np.arange(len(samples)): nans = np.isnan(samples[sampleIndex]) if np.any(nans): levelNumber = levels[np.squeeze(np.argwhere(nans)[0][0])] if levelNumber > 0.2: logger.warning('level {} have NaN value!'.format(levelNumber)) sample = samples[sampleIndex] sample[nans]= np.interp(np.array(levels)[nans], np.array(levels)[~nans], sample[~nans]) samples[sampleIndex] = sample samples = samples.T ## extrapolate the overlap ratio of 1 # levels.append(1.0) # samples.append([0, 0, samples[-1][2], samples[-1][3], samples[-1][4]]) ## extrapolate the overlap ratio of 0 # levels.insert(0, 0.0) # samples.insert(0, samples[0]) # samples = np.array(samples) # samples[:, 0] = (1.*windowLength/interpolatedLength*samples[:, 0]) # samples[:, 1] = (1.*windowLength/interpolatedLength*samples[:, 1]) # samples[:, 4] = np.rad2deg(samples[:, 4]) # samples[0, 0:2] = [0.89/2, 0.89/2] # samples = np.array(samples) samples[:, 0] = (1.*windowLength/interpolatedLength*samples[:, 0]) samples[:, 1] = (1.*windowLength/interpolatedLength*samples[:, 1]) angles = samples[:, 4] for i in range(1, len(angles)): if angles[i] - angles[i-1] > np.pi * 0.8: angles[i] -= np.pi elif angles[i] - angles[i-1] < -np.pi * 0.8: angles[i] += np.pi samples[:, 4] = np.rad2deg(angles) interpMethod ="cubic" # "quadratic, slinear, cubic" majorInterp = interpolate.interp1d(levels, samples[:, 0], kind=interpMethod) minorInterp = interpolate.interp1d(levels, samples[:, 1], kind=interpMethod) angleInterp = interpolate.interp1d(levels, samples[:, 4], kind=interpMethod) interval = 0.001 # levelInterp = np.arange(levels[0], levels[-1]+interval, interval).tolist() levelInterp = np.linspace(levels[0], levels[-1], 1 + int((levels[-1] - levels[0])/interval)).tolist() # levelInterp[-1] = np.round(levelInterp[-1], 7) majorInterped = majorInterp(levelInterp).tolist() minorInterped = minorInterp(levelInterp).tolist() angleInterped = angleInterp(levelInterp).tolist() # angleInterped = interpolate.splev(levelInterp, tck, der=0) ### extrapolate the overlap ratio of 1 levelInterp.append(1.0) majorInterped.append(0) minorInterped.append(0) angleInterped.append(angleInterped[-1]) ### extrapolate the overlap ratio of 0 levelInterp.insert(0, 0.0) majorInterped.insert(0, 0.89/2) minorInterped.insert(0, 0.89/2) angleInterped.insert(0, angleInterped[0]) interval = 0.00001 levelLinearInterp = np.arange(levelInterp[0], levelInterp[-1]+interval, interval) majorInterped = np.interp(levelLinearInterp, levelInterp, majorInterped) minorInterped = np.interp(levelLinearInterp, levelInterp, minorInterped) angleInterped = np.interp(levelLinearInterp, levelInterp, angleInterped) # print(len(levelInterp), len(levelLinearInterp)) if plot == True: ax2.plot(levels, samples[:, 0]) ax3.plot(levels, samples[:, 1]) ax4.plot(levels, samples[:, 4]) ax2.plot(levelLinearInterp, majorInterped) ax3.plot(levelLinearInterp, minorInterped ) # ax4.plot(levelInterp, np.rad2deg(angleInterp(levelInterp))) ax4.plot(levelLinearInterp, angleInterped) ax2.set_ylabel('Major', size=15) ax2.set_xticklabels([]) ax2.tick_params(axis='y', labelsize=15 ) ax2.set_ylim(0, max(samples[1:, 0])*1.2) ax3.set_ylabel('Minor', size=15) ax3.tick_params(axis='y', labelsize=15 ) ax3.set_xticklabels([]) ax3.set_ylim(0, max(samples[1:, 1])*1.2) ax4.set_ylabel('Orientation', size=15) ax4.set_xlabel('Overlap ratio', size=15) ax4.tick_params(axis='x', labelsize=15 ) fig.subplots_adjust(hspace=0) fig.tight_layout() fig.savefig("plots/levels.png") plt.close() beamshapeModel = np.array([levelLinearInterp, majorInterped, minorInterped, angleInterped]).T return beamshapeModel
# Extreme rays s = np.linspace(0, 1000, num=1000) ang = (ytop - fpy) / (xtop - fpx) plt.plot([xtop, fpx], [ytop, fpy], 'g--') plt.plot([xbot, fpx], [ybot, fpy], 'g--') # Figure out how tipped my viewing angle is skew_ang = np.radians(1.4) view_skew_ell = Ellipse(xy=(xtop + D_pri_pix * np.cos(tilt) / 2, ytop + D_pri_pix * np.sin(tilt) / 2), width=D_pri_pix, height=D_pri_pix * np.sin(skew_ang), angle=tilt_pri) view_skew_ell.fill = False ax.add_artist(view_skew_ell) plt.plot(xe, ye, 'c') plt.plot(f1x, f1y, 'co') plt.plot(f2x, f2y, 'co') if True: plt.xlim([0, xmax]) plt.ylim([ymax, 0]) else: plt.xlim([1200, 2200]) plt.ylim([1500, 500]) plt.show()