text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_traceback(text): """Receive a list of strings representing the input from stdin and return the restructured backtrace. This iterates over the output and once it identifies a hopefully genuine identifier, it will start parsing output. In the case the input includes a reraise (a Python 3 case), the primary traceback isn't handled, only the reraise. Each of the traceback lines are then handled two lines at a time for each stack object. Note that all parts of each stack object are stripped from newlines and spaces to keep the output clean. """
capture = False entries = [] all_else = [] ignore_trace = False # In python 3, a traceback may includes output from a reraise. # e.g, an exception is captured and reraised with another exception. # This marks that we should ignore if text.count(TRACEBACK_IDENTIFIER) == 2: ignore_trace = True for index, line in enumerate(text): if TRACEBACK_IDENTIFIER in line: if ignore_trace: ignore_trace = False continue capture = True # We're not capturing and making sure we only read lines # with spaces since, after the initial identifier, all traceback lines # contain a prefix spacing. elif capture and line.startswith(' '): if index % 2 == 0: # Line containing a file, line and module. line = line.strip().strip('\n') next_line = text[index + 1].strip('\n') entries.append(line + ', ' + next_line) elif capture: # Line containing the module call. entries.append(line) break else: # Add everything else after the traceback. all_else.append(line) traceback_entries = [] # Build the traceback structure later passed for formatting. for index, line in enumerate(entries[:-2]): # TODO: This should be done in a _parse_entry function element = line.split(',') element[0] = element[0].strip().lstrip('File').strip(' "') element[1] = element[1].strip().lstrip('line').strip() element[2] = element[2].strip().lstrip('in').strip() traceback_entries.append(tuple(element)) return traceback_entries, all_else
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classify_catalog(catalog): """ Look at a list of sources and split them according to their class. Parameters catalog : iterable A list or iterable object of {SimpleSource, IslandSource, OutputSource} objects, possibly mixed. Any other objects will be silently ignored. Returns ------- components : list List of sources of type OutputSource islands : list List of sources of type IslandSource simples : list List of source of type SimpleSource """
components = [] islands = [] simples = [] for source in catalog: if isinstance(source, OutputSource): components.append(source) elif isinstance(source, IslandSource): islands.append(source) elif isinstance(source, SimpleSource): simples.append(source) return components, islands, simples
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def island_itergen(catalog): """ Iterate over a catalog of sources, and return an island worth of sources at a time. Yields a list of components, one island at a time Parameters catalog : iterable A list or iterable of :class:`AegeanTools.models.OutputSource` objects. Yields ------ group : list A list of all sources within an island, one island at a time. """
# reverse sort so that we can pop the last elements and get an increasing island number catalog = sorted(catalog) catalog.reverse() group = [] # using pop and keeping track of the list length ourselves is faster than # constantly asking for len(catalog) src = catalog.pop() c_len = len(catalog) isle_num = src.island while c_len >= 0: if src.island == isle_num: group.append(src) c_len -= 1 if c_len <0: # we have just added the last item from the catalog # and there are no more to pop yield group else: src = catalog.pop() else: isle_num += 1 # maybe there are no sources in this island so skip it if group == []: continue yield group group = [] return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sanitise(self): """ Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly. """
for k in self.__dict__: if isinstance(self.__dict__[k], np.float32): # np.float32 has a broken __str__ method self.__dict__[k] = np.float64(self.__dict__[k])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_circles(self, ra_cen, dec_cen, radius, depth=None): """ Add one or more circles to this region Parameters ra_cen, dec_cen, radius : float or list The center and radius of the circle or circles to add to this region. depth : int The depth at which the given circles will be inserted. """
if depth is None or depth > self.maxdepth: depth = self.maxdepth try: sky = list(zip(ra_cen, dec_cen)) rad = radius except TypeError: sky = [[ra_cen, dec_cen]] rad = [radius] sky = np.array(sky) rad = np.array(rad) vectors = self.sky2vec(sky) for vec, r in zip(vectors, rad): pix = hp.query_disc(2**depth, vec, r, inclusive=True, nest=True) self.add_pixels(pix, depth) self._renorm() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_poly(self, positions, depth=None): """ Add a single polygon to this region. Parameters Positions for the vertices of the polygon. The polygon needs to be convex and non-intersecting. depth : int The deepth at which the polygon will be inserted. """
if not (len(positions) >= 3): raise AssertionError("A minimum of three coordinate pairs are required") if depth is None or depth > self.maxdepth: depth = self.maxdepth ras, decs = np.array(list(zip(*positions))) sky = self.radec2sky(ras, decs) pix = hp.query_polygon(2**depth, self.sky2vec(sky), inclusive=True, nest=True) self.add_pixels(pix, depth) self._renorm() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_pixels(self, pix, depth): """ Add one or more HEALPix pixels to this region. Parameters pix : int or iterable The pixels to be added depth : int The depth at which the pixels are added. """
if depth not in self.pixeldict: self.pixeldict[depth] = set() self.pixeldict[depth].update(set(pix))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_area(self, degrees=True): """ Calculate the total area represented by this region. Parameters degrees : bool If True then return the area in square degrees, otherwise use steradians. Default = True. Returns ------- area : float The area of the region. """
area = 0 for d in range(1, self.maxdepth+1): area += len(self.pixeldict[d])*hp.nside2pixarea(2**d, degrees=degrees) return area
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _demote_all(self): """ Convert the multi-depth pixeldict into a single set of pixels at the deepest layer. The result is cached, and reset when any changes are made to this region. """
# only do the calculations if the demoted list is empty if len(self.demoted) == 0: pd = self.pixeldict for d in range(1, self.maxdepth): for p in pd[d]: pd[d+1].update(set((4*p, 4*p+1, 4*p+2, 4*p+3))) pd[d] = set() # clear the pixels from this level self.demoted = pd[d+1] return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _renorm(self): """ Remake the pixel dictionary, merging groups of pixels at level N into a single pixel at level N-1 """
self.demoted = set() # convert all to lowest level self._demote_all() # now promote as needed for d in range(self.maxdepth, 2, -1): plist = self.pixeldict[d].copy() for p in plist: if p % 4 == 0: nset = set((p, p+1, p+2, p+3)) if p+1 in plist and p+2 in plist and p+3 in plist: # remove the four pixels from this level self.pixeldict[d].difference_update(nset) # add a new pixel to the next level up self.pixeldict[d-1].add(p/4) self.demoted = set() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky_within(self, ra, dec, degin=False): """ Test whether a sky position is within this region Parameters ra, dec : float Sky position. degin : bool If True the ra/dec is interpreted as degrees, otherwise as radians. Default = False. Returns ------- within : bool True if the given position is within one of the region's pixels. """
sky = self.radec2sky(ra, dec) if degin: sky = np.radians(sky) theta_phi = self.sky2ang(sky) # Set values that are nan to be zero and record a mask mask = np.bitwise_not(np.logical_and.reduce(np.isfinite(theta_phi), axis=1)) theta_phi[mask, :] = 0 theta, phi = theta_phi.transpose() pix = hp.ang2pix(2**self.maxdepth, theta, phi, nest=True) pixelset = self.get_demoted() result = np.in1d(pix, list(pixelset)) # apply the mask and set the shonky values to False result[mask] = False return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union(self, other, renorm=True): """ Add another Region by performing union on their pixlists. Parameters other : :class:`AegeanTools.regions.Region` The region to be combined. renorm : bool Perform renormalisation after the operation? Default = True. """
# merge the pixels that are common to both for d in range(1, min(self.maxdepth, other.maxdepth)+1): self.add_pixels(other.pixeldict[d], d) # if the other region is at higher resolution, then include a degraded version of the remaining pixels. if self.maxdepth < other.maxdepth: for d in range(self.maxdepth+1, other.maxdepth+1): for p in other.pixeldict[d]: # promote this pixel to self.maxdepth pp = p/4**(d-self.maxdepth) self.pixeldict[self.maxdepth].add(pp) if renorm: self._renorm() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def without(self, other): """ Subtract another Region by performing a difference operation on their pixlists. Requires both regions to have the same maxdepth. Parameters other : :class:`AegeanTools.regions.Region` The region to be combined. """
# work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].difference_update(opd) self._renorm() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersect(self, other): """ Combine with another Region by performing intersection on their pixlists. Requires both regions to have the same maxdepth. Parameters other : :class:`AegeanTools.regions.Region` The region to be combined. """
# work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].intersection_update(opd) self._renorm() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symmetric_difference(self, other): """ Combine with another Region by performing the symmetric difference of their pixlists. Requires both regions to have the same maxdepth. Parameters other : :class:`AegeanTools.regions.Region` The region to be combined. """
# work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].symmetric_difference_update(opd) self._renorm() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_reg(self, filename): """ Write a ds9 region file that represents this region as a set of diamonds. Parameters filename : str File to write """
with open(filename, 'w') as out: for d in range(1, self.maxdepth+1): for p in self.pixeldict[d]: line = "fk5; polygon(" # the following int() gets around some problems with np.int64 that exist prior to numpy v 1.8.1 vectors = list(zip(*hp.boundaries(2**d, int(p), step=1, nest=True))) positions = [] for sky in self.vec2sky(np.array(vectors), degrees=True): ra, dec = sky pos = SkyCoord(ra/15, dec, unit=(u.degree, u.degree)) positions.append(pos.ra.to_string(sep=':', precision=2)) positions.append(pos.dec.to_string(sep=':', precision=2)) line += ','.join(positions) line += ")" print(line, file=out) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_fits(self, filename, moctool=''): """ Write a fits file representing the MOC of this region. Parameters filename : str File to write moctool : str String to be written to fits header with key "MOCTOOL". Default = '' """
datafile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'MOC.fits') hdulist = fits.open(datafile) cols = fits.Column(name='NPIX', array=self._uniq(), format='1K') tbhdu = fits.BinTableHDU.from_columns([cols]) hdulist[1] = tbhdu hdulist[1].header['PIXTYPE'] = ('HEALPIX ', 'HEALPix magic code') hdulist[1].header['ORDERING'] = ('NUNIQ ', 'NUNIQ coding method') hdulist[1].header['COORDSYS'] = ('C ', 'ICRS reference frame') hdulist[1].header['MOCORDER'] = (self.maxdepth, 'MOC resolution (best order)') hdulist[1].header['MOCTOOL'] = (moctool, 'Name of the MOC generator') hdulist[1].header['MOCTYPE'] = ('CATALOG', 'Source type (IMAGE or CATALOG)') hdulist[1].header['MOCID'] = (' ', 'Identifier of the collection') hdulist[1].header['ORIGIN'] = (' ', 'MOC origin') time = datetime.datetime.utcnow() hdulist[1].header['DATE'] = (datetime.datetime.strftime(time, format="%Y-%m-%dT%H:%m:%SZ"), 'MOC creation date') hdulist.writeto(filename, overwrite=True) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _uniq(self): """ Create a list of all the pixels that cover this region. This list contains overlapping pixels of different orders. Returns ------- pix : list A list of HEALPix pixel numbers. """
pd = [] for d in range(1, self.maxdepth): pd.extend(map(lambda x: int(4**(d+1) + x), self.pixeldict[d])) return sorted(pd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky2ang(sky): """ Convert ra,dec coordinates to theta,phi coordinates ra -> phi dec -> theta Parameters sky : numpy.array Array of (ra,dec) coordinates. See :func:`AegeanTools.regions.Region.radec2sky` Returns ------- theta_phi : numpy.array Array of (theta,phi) coordinates. """
try: theta_phi = sky.copy() except AttributeError as _: theta_phi = np.array(sky) theta_phi[:, [1, 0]] = theta_phi[:, [0, 1]] theta_phi[:, 0] = np.pi/2 - theta_phi[:, 0] # # force 0<=theta<=2pi # theta_phi[:, 0] -= 2*np.pi*(theta_phi[:, 0]//(2*np.pi)) # # and now -pi<=theta<=pi # theta_phi[:, 0] -= (theta_phi[:, 0] > np.pi)*2*np.pi return theta_phi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky2vec(cls, sky): """ Convert sky positions in to 3d-vectors on the unit sphere. Parameters sky : numpy.array Sky coordinates as an array of (ra,dec) Returns ------- vec : numpy.array Unit vectors as an array of (x,y,z) See Also -------- :func:`AegeanTools.regions.Region.vec2sky` """
theta_phi = cls.sky2ang(sky) theta, phi = map(np.array, list(zip(*theta_phi))) vec = hp.ang2vec(theta, phi) return vec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_header(cls, header, beam=None, lat=None): """ Create a new WCSHelper class from the given header. Parameters header : `astropy.fits.HDUHeader` or string The header to be used to create the WCS helper beam : :class:`AegeanTools.fits_image.Beam` or None The synthesized beam. If the supplied beam is None then one is constructed form the header. lat : float The latitude of the telescope. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object. """
try: wcs = pywcs.WCS(header, naxis=2) except: # TODO: figure out what error is being thrown wcs = pywcs.WCS(str(header), naxis=2) if beam is None: beam = get_beam(header) else: beam = beam if beam is None: logging.critical("Cannot determine beam information") _, pixscale = get_pixinfo(header) refpix = (header['CRPIX1'], header['CRPIX2']) return cls(wcs, beam, pixscale, refpix, lat)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_file(cls, filename, beam=None): """ Create a new WCSHelper class from a given fits file. Parameters filename : string The file to be read beam : :class:`AegeanTools.fits_image.Beam` or None The synthesized beam. If the supplied beam is None then one is constructed form the header. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object """
header = fits.getheader(filename) return cls.from_header(header, beam)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pix2sky(self, pixel): """ Convert pixel coordinates into sky coordinates. Parameters pixel : (float, float) The (x,y) pixel coordinates Returns ------- sky : (float, float) The (ra,dec) sky coordinates in degrees """
x, y = pixel # wcs and pyfits have oposite ideas of x/y return self.wcs.wcs_pix2world([[y, x]], 1)[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky2pix(self, pos): """ Convert sky coordinates into pixel coordinates. Parameters pos : (float, float) The (ra, dec) sky coordinates (degrees) Returns ------- pixel : (float, float) The (x,y) pixel coordinates """
pixel = self.wcs.wcs_world2pix([pos], 1) # wcs and pyfits have oposite ideas of x/y return [pixel[0][1], pixel[0][0]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky2pix_vec(self, pos, r, pa): """ Convert a vector from sky to pixel coords. The vector has a magnitude, angle, and an origin on the sky. Parameters pos : (float, float) The (ra, dec) of the origin of the vector (degrees). r : float The magnitude or length of the vector (degrees). pa : float The position angle of the vector (degrees). Returns ------- x, y : float The pixel coordinates of the origin. r, theta : float The magnitude (pixels) and angle (degrees) of the vector. """
ra, dec = pos x, y = self.sky2pix(pos) a = translate(ra, dec, r, pa) locations = self.sky2pix(a) x_off, y_off = locations a = np.sqrt((x - x_off) ** 2 + (y - y_off) ** 2) theta = np.degrees(np.arctan2((y_off - y), (x_off - x))) return x, y, a, theta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pix2sky_vec(self, pixel, r, theta): """ Given and input position and vector in pixel coordinates, calculate the equivalent position and vector in sky coordinates. Parameters pixel : (int,int) origin of vector in pixel coordinates r : float magnitude of vector in pixels theta : float angle of vector in degrees Returns ------- ra, dec : float The (ra, dec) of the origin point (degrees). r, pa : float The magnitude and position angle of the vector (degrees). """
ra1, dec1 = self.pix2sky(pixel) x, y = pixel a = [x + r * np.cos(np.radians(theta)), y + r * np.sin(np.radians(theta))] locations = self.pix2sky(a) ra2, dec2 = locations a = gcd(ra1, dec1, ra2, dec2) pa = bear(ra1, dec1, ra2, dec2) return ra1, dec1, a, pa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky2pix_ellipse(self, pos, a, b, pa): """ Convert an ellipse from sky to pixel coordinates. Parameters pos : (float, float) The (ra, dec) of the ellipse center (degrees). a, b, pa: float The semi-major axis, semi-minor axis and position angle of the ellipse (degrees). Returns ------- x,y : float The (x, y) pixel coordinates of the ellipse center. sx, sy : float The major and minor axes (FWHM) in pixels. theta : float The rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis. """
ra, dec = pos x, y = self.sky2pix(pos) x_off, y_off = self.sky2pix(translate(ra, dec, a, pa)) sx = np.hypot((x - x_off), (y - y_off)) theta = np.arctan2((y_off - y), (x_off - x)) x_off, y_off = self.sky2pix(translate(ra, dec, b, pa - 90)) sy = np.hypot((x - x_off), (y - y_off)) theta2 = np.arctan2((y_off - y), (x_off - x)) - np.pi / 2 # The a/b vectors are perpendicular in sky space, but not always in pixel space # so we have to account for this by calculating the angle between the two vectors # and modifying the minor axis length defect = theta - theta2 sy *= abs(np.cos(defect)) return x, y, sx, sy, np.degrees(theta)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pix2sky_ellipse(self, pixel, sx, sy, theta): """ Convert an ellipse from pixel to sky coordinates. Parameters pixel : (float, float) The (x, y) coordinates of the center of the ellipse. sx, sy : float The major and minor axes (FHWM) of the ellipse, in pixels. theta : float The rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis. Returns ------- ra, dec : float The (ra, dec) coordinates of the center of the ellipse (degrees). a, b : float The semi-major and semi-minor axis of the ellipse (degrees). pa : float The position angle of the ellipse (degrees). """
ra, dec = self.pix2sky(pixel) x, y = pixel v_sx = [x + sx * np.cos(np.radians(theta)), y + sx * np.sin(np.radians(theta))] ra2, dec2 = self.pix2sky(v_sx) major = gcd(ra, dec, ra2, dec2) pa = bear(ra, dec, ra2, dec2) v_sy = [x + sy * np.cos(np.radians(theta - 90)), y + sy * np.sin(np.radians(theta - 90))] ra2, dec2 = self.pix2sky(v_sy) minor = gcd(ra, dec, ra2, dec2) pa2 = bear(ra, dec, ra2, dec2) - 90 # The a/b vectors are perpendicular in sky space, but not always in pixel space # so we have to account for this by calculating the angle between the two vectors # and modifying the minor axis length defect = pa - pa2 minor *= abs(np.cos(np.radians(defect))) return ra, dec, major, minor, pa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pixbeam_pixel(self, x, y): """ Determine the beam in pixels at the given location in pixel coordinates. Parameters x , y : float The pixel coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` A beam object, with a/b/pa in pixel coordinates. """
ra, dec = self.pix2sky((x, y)) return self.get_pixbeam(ra, dec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_beam(self, ra, dec): """ Determine the beam at the given sky location. Parameters ra, dec : float The sky coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` A beam object, with a/b/pa in sky coordinates """
# check to see if we need to scale the major axis based on the declination if self.lat is None: factor = 1 else: # this works if the pa is zero. For non-zero pa it's a little more difficult factor = np.cos(np.radians(dec - self.lat)) return Beam(self.beam.a / factor, self.beam.b, self.beam.pa)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pixbeam(self, ra, dec): """ Determine the beam in pixels at the given location in sky coordinates. Parameters ra , dec : float The sly coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` A beam object, with a/b/pa in pixel coordinates. """
if ra is None: ra, dec = self.pix2sky(self.refpix) pos = [ra, dec] beam = self.get_beam(ra, dec) _, _, major, minor, theta = self.sky2pix_ellipse(pos, beam.a, beam.b, beam.pa) if major < minor: major, minor = minor, major theta -= 90 if theta < -180: theta += 180 if not np.isfinite(theta): theta = 0 if not all(np.isfinite([major, minor, theta])): beam = None else: beam = Beam(major, minor, theta) return beam
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_beamarea_deg2(self, ra, dec): """ Calculate the area of the synthesized beam in square degrees. Parameters ra, dec : float The sky coordinates at which the calculation is made. Returns ------- area : float The beam area in square degrees. """
barea = abs(self.beam.a * self.beam.b * np.pi) # in deg**2 at reference coords if self.lat is not None: barea /= np.cos(np.radians(dec - self.lat)) return barea
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_beamarea_pix(self, ra, dec): """ Calculate the beam area in square pixels. Parameters ra, dec : float The sky coordinates at which the calculation is made dec Returns ------- area : float The beam area in square pixels. """
parea = abs(self.pixscale[0] * self.pixscale[1]) # in deg**2 at reference coords barea = self.get_beamarea_deg2(ra, dec) return barea / parea
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_psf_sky(self, ra, dec): """ Determine the local psf at a given sky location. The psf is returned in degrees. Parameters ra, dec : float The sky position (degrees). Returns ------- a, b, pa : float The psf semi-major axis, semi-minor axis, and position angle in (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned. """
# If we don't have a psf map then we just fall back to using the beam # from the fits header (including ZA scaling) if self.data is None: beam = self.wcshelper.get_beam(ra, dec) return beam.a, beam.b, beam.pa x, y = self.sky2pix([ra, dec]) # We leave the interpolation in the hands of whoever is making these images # clamping the x,y coords at the image boundaries just makes sense x = int(np.clip(x, 0, self.data.shape[1] - 1)) y = int(np.clip(y, 0, self.data.shape[2] - 1)) psf_sky = self.data[:, x, y] return psf_sky
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pixbeam(self, ra, dec): """ Get the psf at the location specified in pixel coordinates. The psf is also in pixel coordinates. Parameters ra, dec : float The sky position (degrees). Returns ------- a, b, pa : float The psf semi-major axis (pixels), semi-minor axis (pixels), and rotation angle (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned. """
# If there is no psf image then just use the fits header (plus lat scaling) from the wcshelper if self.data is None: return self.wcshelper.get_pixbeam(ra, dec) # get the beam from the psf image data psf = self.get_psf_pix(ra, dec) if not np.all(np.isfinite(psf)): log.warn("PSF requested, returned Null") return None return Beam(psf[0], psf[1], psf[2])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_beamarea_pix(self, ra, dec): """ Calculate the area of the beam in square pixels. Parameters ra, dec : float The sky position (degrees). Returns ------- area : float The area of the beam in square pixels. """
beam = self.get_pixbeam(ra, dec) if beam is None: return 0 return beam.a * beam.b * np.pi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_beamarea_deg2(self, ra, dec): """ Calculate the area of the beam in square degrees. Parameters ra, dec : float The sky position (degrees). Returns ------- area : float The area of the beam in square degrees. """
beam = self.get_beam(ra, dec) if beam is None: return 0 return beam.a * beam.b * np.pi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_start_point(self): """ Find the first location in our array that is not empty """
for i, row in enumerate(self.data): for j, _ in enumerate(row): if self.data[i, j] != 0: # or not np.isfinite(self.data[i,j]): return i, j
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step(self, x, y): """ Move from the current location to the next Parameters x, y : int The current location """
up_left = self.solid(x - 1, y - 1) up_right = self.solid(x, y - 1) down_left = self.solid(x - 1, y) down_right = self.solid(x, y) state = 0 self.prev = self.next # which cells are filled? if up_left: state |= 1 if up_right: state |= 2 if down_left: state |= 4 if down_right: state |= 8 # what is the next step? if state in [1, 5, 13]: self.next = self.UP elif state in [2, 3, 7]: self.next = self.RIGHT elif state in [4, 12, 14]: self.next = self.LEFT elif state in [8, 10, 11]: self.next = self.DOWN elif state == 6: if self.prev == self.UP: self.next = self.LEFT else: self.next = self.RIGHT elif state == 9: if self.prev == self.RIGHT: self.next = self.UP else: self.next = self.DOWN else: self.next = self.NOWHERE return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solid(self, x, y): """ Determine whether the pixel x,y is nonzero Parameters x, y : int The pixel of interest. Returns ------- solid : bool True if the pixel is not zero. """
if not(0 <= x < self.xsize) or not(0 <= y < self.ysize): return False if self.data[x, y] == 0: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk_perimeter(self, startx, starty): """ Starting at a point on the perimeter of a region, 'walk' the perimeter to return to the starting point. Record the path taken. Parameters startx, starty : int The starting location. Assumed to be on the perimeter of a region. Returns ------- perimeter : list """
# checks startx = max(startx, 0) startx = min(startx, self.xsize) starty = max(starty, 0) starty = min(starty, self.ysize) points = [] x, y = startx, starty while True: self.step(x, y) if 0 <= x <= self.xsize and 0 <= y <= self.ysize: points.append((x, y)) if self.next == self.UP: y -= 1 elif self.next == self.LEFT: x -= 1 elif self.next == self.DOWN: y += 1 elif self.next == self.RIGHT: x += 1 # stop if we meet some kind of error elif self.next == self.NOWHERE: break # stop when we return to the starting location if x == startx and y == starty: break return points
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_march(self): """ March about and trace the outline of our object Returns ------- perimeter : list """
x, y = self.find_start_point() perimeter = self.walk_perimeter(x, y) return perimeter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _blank_within(self, perimeter): """ Blank all the pixels within the given perimeter. Parameters perimeter : list The perimeter of the region. """
# Method: # scan around the perimeter filling 'up' from each pixel # stopping when we reach the other boundary for p in perimeter: # if we are on the edge of the data then there is nothing to fill if p[0] >= self.data.shape[0] or p[1] >= self.data.shape[1]: continue # if this pixel is blank then don't fill if self.data[p] == 0: continue # blank this pixel self.data[p] = 0 # blank until we reach the other perimeter for i in range(p[1]+1, self.data.shape[1]): q = p[0], i # stop when we reach another part of the perimeter if q in perimeter: break # fill everything in between, even inclusions self.data[q] = 0 return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_march_all(self): """ Recursive march in the case that we have a fragmented shape. Returns ------- The perimeters of all the regions in the image. See Also -------- :func:`AegeanTools.msq2.MarchingSquares.do_march` """
# copy the data since we are going to be modifying it data_copy = copy(self.data) # iterate through finding an island, creating a perimeter, # and then blanking the island perimeters = [] p = self.find_start_point() while p is not None: x, y = p perim = self.walk_perimeter(x, y) perimeters.append(perim) self._blank_within(perim) p = self.find_start_point() # restore the data self.data = data_copy return perimeters
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def elliptical_gaussian(x, y, amp, xo, yo, sx, sy, theta): """ Generate a model 2d Gaussian with the given parameters. Evaluate this model at the given locations x,y. Parameters x, y : numeric or array-like locations at which to evaluate the gaussian amp : float Peak value. xo, yo : float Center of the gaussian. sx, sy : float major/minor axes in sigmas theta : float position angle (degrees) CCW from x-axis Returns ------- data : numeric or array-like Gaussian function evaluated at the x,y locations. """
try: sint, cost = math.sin(np.radians(theta)), math.cos(np.radians(theta)) except ValueError as e: if 'math domain error' in e.args: sint, cost = np.nan, np.nan xxo = x - xo yyo = y - yo exp = (xxo * cost + yyo * sint) ** 2 / sx ** 2 \ + (xxo * sint - yyo * cost) ** 2 / sy ** 2 exp *= -1. / 2 return amp * np.exp(exp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Cmatrix(x, y, sx, sy, theta): """ Construct a correlation matrix corresponding to the data. The matrix assumes a gaussian correlation function. Parameters x, y : array-like locations at which to evaluate the correlation matirx sx, sy : float major/minor axes of the gaussian correlation function (sigmas) theta : float position angle of the gaussian correlation function (degrees) Returns ------- data : array-like The C-matrix. """
C = np.vstack([elliptical_gaussian(x, y, 1, i, j, sx, sy, theta) for i, j in zip(x, y)]) return C
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Bmatrix(C): """ Calculate a matrix which is effectively the square root of the correlation matrix C Parameters C : 2d array A covariance matrix Returns ------- B : 2d array A matrix B such the B.dot(B') = inv(C) """
# this version of finding the square root of the inverse matrix # suggested by Cath Trott L, Q = eigh(C) # force very small eigenvalues to have some minimum non-zero value minL = 1e-9*L[-1] L[L < minL] = minL S = np.diag(1 / np.sqrt(L)) B = Q.dot(S) return B
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nan_acf(noise): """ Calculate the autocorrelation function of the noise where the noise is a 2d array that may contain nans Parameters noise : 2d-array Noise image. Returns ------- acf : 2d-array The ACF. """
corr = np.zeros(noise.shape) ix,jx = noise.shape for i in range(ix): si_min = slice(i, None, None) si_max = slice(None, ix-i, None) for j in range(jx): sj_min = slice(j, None, None) sj_max = slice(None, jx-j, None) if np.all(np.isnan(noise[si_min, sj_min])) or np.all(np.isnan(noise[si_max, sj_max])): corr[i, j] = np.nan else: corr[i, j] = np.nansum(noise[si_min, sj_min] * noise[si_max, sj_max]) # return the normalised acf return corr / np.nanmax(corr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bias_correct(params, data, acf=None): """ Calculate and apply a bias correction to the given fit parameters Parameters params : lmfit.Parameters The model parameters. These will be modified. data : 2d-array The data which was used in the fitting acf : 2d-array ACF of the data. Default = None. Returns ------- None See Also -------- :func:`AegeanTools.fitting.RB_bias` """
bias = RB_bias(data, params, acf=acf) i = 0 for p in params: if 'theta' in p: continue if params[p].vary: params[p].value -= bias[i] i += 1 return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ntwodgaussian_lmfit(params): """ Convert an lmfit.Parameters object into a function which calculates the model. Parameters params : lmfit.Parameters Model parameters, can have multiple components. Returns ------- model : func A function f(x,y) that will compute the model. """
def rfunc(x, y): """ Compute the model given by params, at pixel coordinates x,y Parameters ---------- x, y : numpy.ndarray The x/y pixel coordinates at which the model is being evaluated Returns ------- result : numpy.ndarray Model """ result = None for i in range(params['components'].value): prefix = "c{0}_".format(i) # I hope this doesn't kill our run time amp = np.nan_to_num(params[prefix + 'amp'].value) xo = params[prefix + 'xo'].value yo = params[prefix + 'yo'].value sx = params[prefix + 'sx'].value sy = params[prefix + 'sy'].value theta = params[prefix + 'theta'].value if result is not None: result += elliptical_gaussian(x, y, amp, xo, yo, sx, sy, theta) else: result = elliptical_gaussian(x, y, amp, xo, yo, sx, sy, theta) return result return rfunc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_lmfit(data, params, B=None, errs=None, dojac=True): """ Fit the model to the data data may contain 'flagged' or 'masked' data with the value of np.NaN Parameters data : 2d-array Image data params : lmfit.Parameters Initial model guess. B : 2d-array B matrix to be used in residual calculations. Default = None. errs : 1d-array dojac : bool If true then an analytic jacobian will be passed to the fitting routine. Returns ------- result : ? lmfit.minimize result. params : lmfit.Params Fitted model. See Also -------- :func:`AegeanTools.fitting.lmfit_jacobian` """
# copy the params so as not to change the initial conditions # in case we want to use them elsewhere params = copy.deepcopy(params) data = np.array(data) mask = np.where(np.isfinite(data)) def residual(params, **kwargs): """ The residual function required by lmfit Parameters ---------- params: lmfit.Params The parameters of the model being fit Returns ------- result : numpy.ndarray Model - Data """ f = ntwodgaussian_lmfit(params) # A function describing the model model = f(*mask) # The actual model if B is None: return model - data[mask] else: return (model - data[mask]).dot(B) if dojac: result = lmfit.minimize(residual, params, kws={'x': mask[0], 'y': mask[1], 'B': B, 'errs': errs}, Dfun=lmfit_jacobian) else: result = lmfit.minimize(residual, params, kws={'x': mask[0], 'y': mask[1], 'B': B, 'errs': errs}) # Remake the residual so that it is once again (model - data) if B is not None: result.residual = result.residual.dot(inv(B)) return result, params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def covar_errors(params, data, errs, B, C=None): """ Take a set of parameters that were fit with lmfit, and replace the errors with the 1\sigma errors calculated using the covariance matrix. Parameters params : lmfit.Parameters Model data : 2d-array Image data errs : 2d-array ? Image noise. B : 2d-array B matrix. C : 2d-array C matrix. Optional. If supplied then Bmatrix will not be used. Returns ------- params : lmfit.Parameters Modified model. """
mask = np.where(np.isfinite(data)) # calculate the proper parameter errors and copy them across. if C is not None: try: J = lmfit_jacobian(params, mask[0], mask[1], errs=errs) covar = np.transpose(J).dot(inv(C)).dot(J) onesigma = np.sqrt(np.diag(inv(covar))) except (np.linalg.linalg.LinAlgError, ValueError) as _: C = None if C is None: try: J = lmfit_jacobian(params, mask[0], mask[1], B=B, errs=errs) covar = np.transpose(J).dot(J) onesigma = np.sqrt(np.diag(inv(covar))) except (np.linalg.linalg.LinAlgError, ValueError) as _: onesigma = [-2] * len(mask[0]) for i in range(params['components'].value): prefix = "c{0}_".format(i) j = 0 for p in ['amp', 'xo', 'yo', 'sx', 'sy', 'theta']: if params[prefix + p].vary: params[prefix + p].stderr = onesigma[j] j += 1 return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def barrier(events, sid, kind='neighbour'): """ act as a multiprocessing barrier """
events[sid].set() # only wait for the neighbours if kind=='neighbour': if sid > 0: logging.debug("{0} is waiting for {1}".format(sid, sid - 1)) events[sid - 1].wait() if sid < len(bkg_events) - 1: logging.debug("{0} is waiting for {1}".format(sid, sid + 1)) events[sid + 1].wait() # wait for all else: [e.wait() for e in events] return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sigmaclip(arr, lo, hi, reps=3): """ Perform sigma clipping on an array, ignoring non finite values. During each iteration return an array whose elements c obey: mean -std*lo < c < mean + std*hi where mean/std are the mean std of the input array. Parameters arr : iterable An iterable array of numeric types. lo : float The negative clipping level. hi : float The positive clipping level. reps : int The number of iterations to perform. Default = 3. Returns ------- mean : float The mean of the array, possibly nan std : float The std of the array, possibly nan Notes ----- Scipy v0.16 now contains a comparable method that will ignore nan/inf values. """
clipped = np.array(arr)[np.isfinite(arr)] if len(clipped) < 1: return np.nan, np.nan std = np.std(clipped) mean = np.mean(clipped) for _ in range(int(reps)): clipped = clipped[np.where(clipped > mean-std*lo)] clipped = clipped[np.where(clipped < mean+std*hi)] pstd = std if len(clipped) < 1: break std = np.std(clipped) mean = np.mean(clipped) if 2*abs(pstd-std)/(pstd+std) < 0.2: break return mean, std
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sf2(args): """ A shallow wrapper for sigma_filter. Parameters args : list A list of arguments for sigma_filter Returns ------- None """
# an easier to debug traceback when multiprocessing # thanks to https://stackoverflow.com/a/16618842/1710603 try: return sigma_filter(*args) except: import traceback raise Exception("".join(traceback.format_exception(*sys.exc_info())))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_mc_sharemem(filename, step_size, box_size, cores, shape, nslice=None, domask=True): """ Calculate the background and noise images corresponding to the input file. The calculation is done via a box-car approach and uses multiple cores and shared memory. Parameters filename : str Filename to be filtered. step_size : (int, int) Step size for the filter. box_size : (int, int) Box size for the filter. cores : int Number of cores to use. If None then use all available. nslice : int The image will be divided into this many horizontal stripes for processing. Default = None = equal to cores shape : (int, int) The shape of the image in the given file. domask : bool True(Default) = copy data mask to output. Returns ------- bkg, rms : numpy.ndarray The interpolated background and noise images. """
if cores is None: cores = multiprocessing.cpu_count() if (nslice is None) or (cores==1): nslice = cores img_y, img_x = shape # initialise some shared memory global ibkg # bkg = np.ctypeslib.as_ctypes(np.empty(shape, dtype=np.float32)) # ibkg = multiprocessing.sharedctypes.Array(bkg._type_, bkg, lock=True) ibkg = multiprocessing.Array('f', img_y*img_x) global irms #rms = np.ctypeslib.as_ctypes(np.empty(shape, dtype=np.float32)) #irms = multiprocessing.sharedctypes.Array(rms._type_, rms, lock=True) irms = multiprocessing.Array('f', img_y * img_x) logging.info("using {0} cores".format(cores)) logging.info("using {0} stripes".format(nslice)) if nslice > 1: # box widths should be multiples of the step_size, and not zero width_y = int(max(img_y/nslice/step_size[1], 1) * step_size[1]) # locations of the box edges ymins = list(range(0, img_y, width_y)) ymaxs = list(range(width_y, img_y, width_y)) ymaxs.append(img_y) else: ymins = [0] ymaxs = [img_y] logging.debug("ymins {0}".format(ymins)) logging.debug("ymaxs {0}".format(ymaxs)) # create an event per stripe global bkg_events, mask_events bkg_events = [multiprocessing.Event() for _ in range(len(ymaxs))] mask_events = [multiprocessing.Event() for _ in range(len(ymaxs))] args = [] for i, region in enumerate(zip(ymins, ymaxs)): args.append((filename, region, step_size, box_size, shape, domask, i)) # start a new process for each task, hopefully to reduce residual memory use pool = multiprocessing.Pool(processes=cores, maxtasksperchild=1) try: # chunksize=1 ensures that we only send a single task to each process pool.map_async(_sf2, args, chunksize=1).get(timeout=10000000) except KeyboardInterrupt: logging.error("Caught keyboard interrupt") pool.close() sys.exit(1) pool.close() pool.join() bkg = np.reshape(np.array(ibkg[:], dtype=np.float32), shape) rms = np.reshape(np.array(irms[:], dtype=np.float32), shape) del ibkg, irms return bkg, rms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_fits(data, header, file_name): """ Combine data and a fits header to write a fits file. Parameters data : numpy.ndarray The data to be written. header : astropy.io.fits.hduheader The header for the fits file. file_name : string The file to write Returns ------- None """
hdu = fits.PrimaryHDU(data) hdu.header = header hdulist = fits.HDUList([hdu]) hdulist.writeto(file_name, overwrite=True) logging.info("Wrote {0}".format(file_name)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dec2dec(dec): """ Convert sexegessimal RA string into a float in degrees. Parameters dec : string A string separated representing the Dec. Expected format is `[+- ]hh:mm[:ss.s]` Colons can be replaced with any whit space character. Returns ------- dec : float The Dec in degrees. """
d = dec.replace(':', ' ').split() if len(d) == 2: d.append(0.0) if d[0].startswith('-') or float(d[0]) < 0: return float(d[0]) - float(d[1]) / 60.0 - float(d[2]) / 3600.0 return float(d[0]) + float(d[1]) / 60.0 + float(d[2]) / 3600.0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dec2dms(x): """ Convert decimal degrees into a sexagessimal string in degrees. Parameters x : float Angle in degrees Returns ------- dms : string String of format [+-]DD:MM:SS.SS or XX:XX:XX.XX if x is not finite. """
if not np.isfinite(x): return 'XX:XX:XX.XX' if x < 0: sign = '-' else: sign = '+' x = abs(x) d = int(math.floor(x)) m = int(math.floor((x - d) * 60)) s = float(( (x - d) * 60 - m) * 60) return '{0}{1:02d}:{2:02d}:{3:05.2f}'.format(sign, d, m, s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dec2hms(x): """ Convert decimal degrees into a sexagessimal string in hours. Parameters x : float Angle in degrees Returns ------- dms : string String of format HH:MM:SS.SS or XX:XX:XX.XX if x is not finite. """
if not np.isfinite(x): return 'XX:XX:XX.XX' # wrap negative RA's if x < 0: x += 360 x /= 15.0 h = int(x) x = (x - h) * 60 m = int(x) s = (x - m) * 60 return '{0:02d}:{1:02d}:{2:05.2f}'.format(h, m, s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mask_file(regionfile, infile, outfile, negate=False): """ Created a masked version of file, using a region. Parameters regionfile : str A file which can be loaded as a :class:`AegeanTools.regions.Region`. The image will be masked according to this region. infile : str Input FITS image. outfile : str Output FITS image. negate : bool If True then pixels *outside* the region are masked. Default = False. See Also -------- :func:`AegeanTools.MIMAS.mask_plane` """
# Check that the input file is accessible and then open it if not os.path.exists(infile): raise AssertionError("Cannot locate fits file {0}".format(infile)) im = pyfits.open(infile) if not os.path.exists(regionfile): raise AssertionError("Cannot locate region file {0}".format(regionfile)) region = Region.load(regionfile) try: wcs = pywcs.WCS(im[0].header, naxis=2) except: # TODO: figure out what error is being thrown wcs = pywcs.WCS(str(im[0].header), naxis=2) if len(im[0].data.shape) > 2: data = np.squeeze(im[0].data) else: data = im[0].data print(data.shape) if len(data.shape) == 3: for plane in range(data.shape[0]): mask_plane(data[plane], wcs, region, negate) else: mask_plane(data, wcs, region, negate) im[0].data = data im.writeto(outfile, overwrite=True) logging.info("Wrote {0}".format(outfile)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def box2poly(line): """ Convert a string that describes a box in ds9 format, into a polygon that is given by the corners of the box Parameters line : str A string containing a DS9 region command for a box. Returns ------- The corners of the box in clockwise order from top left. """
words = re.split('[(\s,)]', line) ra = words[1] dec = words[2] width = words[3] height = words[4] if ":" in ra: ra = Angle(ra, unit=u.hour) else: ra = Angle(ra, unit=u.degree) dec = Angle(dec, unit=u.degree) width = Angle(float(width[:-1])/2, unit=u.arcsecond) # strip the " height = Angle(float(height[:-1])/2, unit=u.arcsecond) # strip the " center = SkyCoord(ra, dec) tl = center.ra.degree+width.degree, center.dec.degree+height.degree tr = center.ra.degree-width.degree, center.dec.degree+height.degree bl = center.ra.degree+width.degree, center.dec.degree-height.degree br = center.ra.degree-width.degree, center.dec.degree-height.degree return np.ravel([tl, tr, br, bl]).tolist()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circle2circle(line): """ Parse a string that describes a circle in ds9 format. Parameters line : str A string containing a DS9 region command for a circle. Returns ------- circle : [ra, dec, radius] The center and radius of the circle. """
words = re.split('[(,\s)]', line) ra = words[1] dec = words[2] radius = words[3][:-1] # strip the " if ":" in ra: ra = Angle(ra, unit=u.hour) else: ra = Angle(ra, unit=u.degree) dec = Angle(dec, unit=u.degree) radius = Angle(radius, unit=u.arcsecond) return [ra.degree, dec.degree, radius.degree]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poly2poly(line): """ Parse a string of text containing a DS9 description of a polygon. This function works but is not very robust due to the constraints of healpy. Parameters line : str A string containing a DS9 region command for a polygon. Returns ------- The coordinates of the polygon. """
words = re.split('[(\s,)]', line) ras = np.array(words[1::2]) decs = np.array(words[2::2]) coords = [] for ra, dec in zip(ras, decs): if ra.strip() == '' or dec.strip() == '': continue if ":" in ra: pos = SkyCoord(Angle(ra, unit=u.hour), Angle(dec, unit=u.degree)) else: pos = SkyCoord(Angle(ra, unit=u.degree), Angle(dec, unit=u.degree)) # only add this point if it is some distance from the previous one coords.extend([pos.ra.degree, pos.dec.degree]) return coords
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_regions(container): """ Return a region that is the combination of those specified in the container. The container is typically a results instance that comes from argparse. Order of construction is: add regions, subtract regions, add circles, subtract circles, add polygons, subtract polygons. Parameters container : :class:`AegeanTools.MIMAS.Dummy` The regions to be combined. Returns ------- region : :class:`AegeanTools.regions.Region` The constructed region. """
# create empty region region = Region(container.maxdepth) # add/rem all the regions from files for r in container.add_region: logging.info("adding region from {0}".format(r)) r2 = Region.load(r[0]) region.union(r2) for r in container.rem_region: logging.info("removing region from {0}".format(r)) r2 = Region.load(r[0]) region.without(r2) # add circles if len(container.include_circles) > 0: for c in container.include_circles: circles = np.radians(np.array(c)) if container.galactic: l, b, radii = circles.reshape(3, circles.shape[0]//3) ras, decs = galactic2fk5(l, b) else: ras, decs, radii = circles.reshape(3, circles.shape[0]//3) region.add_circles(ras, decs, radii) # remove circles if len(container.exclude_circles) > 0: for c in container.exclude_circles: r2 = Region(container.maxdepth) circles = np.radians(np.array(c)) if container.galactic: l, b, radii = circles.reshape(3, circles.shape[0]//3) ras, decs = galactic2fk5(l, b) else: ras, decs, radii = circles.reshape(3, circles.shape[0]//3) r2.add_circles(ras, decs, radii) region.without(r2) # add polygons if len(container.include_polygons) > 0: for p in container.include_polygons: poly = np.radians(np.array(p)) poly = poly.reshape((poly.shape[0]//2, 2)) region.add_poly(poly) # remove polygons if len(container.exclude_polygons) > 0: for p in container.include_polygons: poly = np.array(np.radians(p)) r2 = Region(container.maxdepth) r2.add_poly(poly) region.without(r2) return region
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersect_regions(flist): """ Construct a region which is the intersection of all regions described in the given list of file names. Parameters flist : list A list of region filenames. Returns ------- region : :class:`AegeanTools.regions.Region` The intersection of all regions, possibly empty. """
if len(flist) < 2: raise Exception("Require at least two regions to perform intersection") a = Region.load(flist[0]) for b in [Region.load(f) for f in flist[1:]]: a.intersect(b) return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_region(region, filename): """ Save the given region to a file Parameters region : :class:`AegeanTools.regions.Region` A region. filename : str Output file name. """
region.save(filename) logging.info("Wrote {0}".format(filename)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_pixels(self, pixels): """ Set the image data. Will not work if the new image has a different shape than the current image. Parameters pixels : numpy.ndarray New image data Returns ------- None """
if not (pixels.shape == self._pixels.shape): raise AssertionError("Shape mismatch between pixels supplied {0} and existing image pixels {1}".format(pixels.shape,self._pixels.shape)) self._pixels = pixels # reset this so that it is calculated next time the function is called self._rms = None return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pix2sky(self, pixel): """ Get the sky coordinates for a given image pixel. Parameters pixel : (float, float) Image coordinates. Returns ------- ra,dec : float Sky coordinates (degrees) """
pixbox = numpy.array([pixel, pixel]) skybox = self.wcs.all_pix2world(pixbox, 1) return [float(skybox[0][0]), float(skybox[0][1])]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_sources(filename): """ Open a file, read contents, return a list of all the sources in that file. @param filename: @return: list of OutputSource objects """
catalog = catalogs.table_to_source_list(catalogs.load_table(filename)) logging.info("read {0} sources from {1}".format(len(catalog), filename)) return catalog
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scope2lat(telescope): """ Convert a telescope name into a latitude returns None when the telescope is unknown. Parameters telescope : str Acronym (name) of telescope, eg MWA. Returns ------- lat : float The latitude of the telescope. Notes ----- These values were taken from wikipedia so have varying precision/accuracy """
scopes = {'MWA': -26.703319, "ATCA": -30.3128, "VLA": 34.0790, "LOFAR": 52.9088, "KAT7": -30.721, "MEERKAT": -30.721, "PAPER": -30.7224, "GMRT": 19.096516666667, "OOTY": 11.383404, "ASKAP": -26.7, "MOST": -35.3707, "PARKES": -32.999944, "WSRT": 52.914722, "AMILA": 52.16977, "AMISA": 52.164303, "ATA": 40.817, "CHIME": 49.321, "CARMA": 37.28044, "DRAO": 49.321, "GBT": 38.433056, "LWA": 34.07, "ALMA": -23.019283, "FAST": 25.6525 } if telescope.upper() in scopes: return scopes[telescope.upper()] else: log = logging.getLogger("Aegean") log.warn("Telescope {0} is unknown".format(telescope)) log.warn("integrated fluxes may be incorrect") return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_cores(cores): """ Determine how many cores we are able to use. Return 1 if we are not able to make a queue via pprocess. Parameters cores : int The number of cores that are requested. Returns ------- cores : int The number of cores available. """
cores = min(multiprocessing.cpu_count(), cores) if six.PY3: log = logging.getLogger("Aegean") log.info("Multi-cores not supported in python 3+, using one core") return 1 try: queue = pprocess.Queue(limit=cores, reuse=1) except: # TODO: figure out what error is being thrown cores = 1 else: try: _ = queue.manage(pprocess.MakeReusable(fix_shape)) except: cores = 1 return cores
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_flood_wrap(self, data, rmsimg, innerclip, outerclip=None, domask=False): """ Generator function. Segment an image into islands and return one island at a time. Needs to work for entire image, and also for components within an island. Parameters data : 2d-array Image array. rmsimg : 2d-array Noise image. innerclip, outerclip :float Seed (inner) and flood (outer) clipping values. domask : bool If True then look for a region mask in globals, only return islands that are within the region. Default = False. Yields ------ data_box : 2d-array A island of sources with subthreshold values masked. xmin, xmax, ymin, ymax : int The corners of the data_box within the initial data array. """
if outerclip is None: outerclip = innerclip # compute SNR image (data has already been background subtracted) snr = abs(data) / rmsimg # mask of pixles that are above the outerclip a = snr >= outerclip # segmentation a la scipy l, n = label(a) f = find_objects(l) if n == 0: self.log.debug("There are no pixels above the clipping limit") return self.log.debug("{1} Found {0} islands total above flood limit".format(n, data.shape)) # Yield values as before, though they are not sorted by flux for i in range(n): xmin, xmax = f[i][0].start, f[i][0].stop ymin, ymax = f[i][1].start, f[i][1].stop if np.any(snr[xmin:xmax, ymin:ymax] > innerclip): # obey inner clip constraint # self.log.info("{1} Island {0} is above the inner clip limit".format(i, data.shape)) data_box = copy.copy(data[xmin:xmax, ymin:ymax]) # copy so that we don't blank the master data data_box[np.where( snr[xmin:xmax, ymin:ymax] < outerclip)] = np.nan # blank pixels that are outside the outerclip data_box[np.where(l[xmin:xmax, ymin:ymax] != i + 1)] = np.nan # blank out other summits # check if there are any pixels left unmasked if not np.any(np.isfinite(data_box)): # self.log.info("{1} Island {0} has no non-masked pixels".format(i,data.shape)) continue if domask and (self.global_data.region is not None): y, x = np.where(snr[xmin:xmax, ymin:ymax] >= outerclip) # convert indices of this sub region to indices in the greater image yx = list(zip(y + ymin, x + xmin)) ra, dec = self.global_data.wcshelper.wcs.wcs_pix2world(yx, 1).transpose() mask = self.global_data.region.sky_within(ra, dec, degin=True) # if there are no un-masked pixels within the region then we skip this island. if not np.any(mask): continue self.log.debug("Mask {0}".format(mask)) # self.log.info("{1} Island {0} will be fit".format(i, data.shape)) yield data_box, xmin, xmax, ymin, ymax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_background_files(self, image_filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, rms=None, bkg=None, cores=1, outbase=None): """ Generate and save the background and RMS maps as FITS files. They are saved in the current directly as aegean-background.fits and aegean-rms.fits. Parameters image_filename : str or HDUList Input image. hdu_index : int If fits file has more than one hdu, it can be specified here. Default = 0. bkgin, rmsin : str or HDUList Background and noise image filename or HDUList beam : :class:`AegeanTools.fits_image.Beam` Beam object representing the synthsized beam. Will replace what is in the FITS header. rms, bkg : float A float that represents a constant rms/bkg level for the entire image. Default = None, which causes the rms/bkg to be loaded or calculated. cores : int Number of cores to use if different from what is autodetected. outbase : str Basename for output files. """
self.log.info("Saving background / RMS maps") # load image, and load/create background/rms images self.load_globals(image_filename, hdu_index=hdu_index, bkgin=bkgin, rmsin=rmsin, beam=beam, verb=True, rms=rms, bkg=bkg, cores=cores, do_curve=True) img = self.global_data.img bkgimg, rmsimg = self.global_data.bkgimg, self.global_data.rmsimg curve = np.array(self.global_data.dcurve, dtype=bkgimg.dtype) # mask these arrays have the same mask the same as the data mask = np.where(np.isnan(self.global_data.data_pix)) bkgimg[mask] = np.NaN rmsimg[mask] = np.NaN curve[mask] = np.NaN # Generate the new FITS files by copying the existing HDU and assigning new data. # This gives the new files the same WCS projection and other header fields. new_hdu = img.hdu # Set the ORIGIN to indicate Aegean made this file new_hdu.header["ORIGIN"] = "Aegean {0}-({1})".format(__version__, __date__) for c in ['CRPIX3', 'CRPIX4', 'CDELT3', 'CDELT4', 'CRVAL3', 'CRVAL4', 'CTYPE3', 'CTYPE4']: if c in new_hdu.header: del new_hdu.header[c] if outbase is None: outbase, _ = os.path.splitext(os.path.basename(image_filename)) noise_out = outbase + '_rms.fits' background_out = outbase + '_bkg.fits' curve_out = outbase + '_crv.fits' snr_out = outbase + '_snr.fits' new_hdu.data = bkgimg new_hdu.writeto(background_out, overwrite=True) self.log.info("Wrote {0}".format(background_out)) new_hdu.data = rmsimg new_hdu.writeto(noise_out, overwrite=True) self.log.info("Wrote {0}".format(noise_out)) new_hdu.data = curve new_hdu.writeto(curve_out, overwrite=True) self.log.info("Wrote {0}".format(curve_out)) new_hdu.data = self.global_data.data_pix / rmsimg new_hdu.writeto(snr_out, overwrite=True) self.log.info("Wrote {0}".format(snr_out)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_image(self, outname): """ Save the image data. This is probably only useful if the image data has been blanked. Parameters outname : str Name for the output file. """
hdu = self.global_data.img.hdu hdu.data = self.global_data.img._pixels hdu.header["ORIGIN"] = "Aegean {0}-({1})".format(__version__, __date__) # delete some axes that we aren't going to need for c in ['CRPIX3', 'CRPIX4', 'CDELT3', 'CDELT4', 'CRVAL3', 'CRVAL4', 'CTYPE3', 'CTYPE4']: if c in hdu.header: del hdu.header[c] hdu.writeto(outname, overwrite=True) self.log.info("Wrote {0}".format(outname)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fit_islands(self, islands): """ Execute fitting on a list of islands This function just wraps around fit_island, so that when we do multiprocesing a single process will fit multiple islands before returning results. Parameters islands : list of :class:`AegeanTools.models.IslandFittingData` The islands to be fit. Returns ------- sources : list The sources that were fit. """
self.log.debug("Fitting group of {0} islands".format(len(islands))) sources = [] for island in islands: res = self._fit_island(island) sources.extend(res) return sources
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_table_formats(files): """ Determine whether a list of files are of a recognizable output type. Parameters files : str A list of file names Returns ------- result : bool True if *all* the file names are supported """
cont = True formats = get_table_formats() for t in files.split(','): _, ext = os.path.splitext(t) ext = ext[1:].lower() if ext not in formats: cont = False log.warn("Format not supported for {0} ({1})".format(t, ext)) if not cont: log.error("Invalid table format specified.") return cont
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_formats(): """ Print a list of all the file formats that are supported for writing. The file formats are determined by their extensions. Returns ------- None """
fmts = { "ann": "Kvis annotation", "reg": "DS9 regions file", "fits": "FITS Binary Table", "csv": "Comma separated values", "tab": "tabe separated values", "tex": "LaTeX table format", "html": "HTML table", "vot": "VO-Table", "xml": "VO-Table", "db": "Sqlite3 database", "sqlite": "Sqlite3 database"} supported = get_table_formats() print("Extension | Description | Supported?") for k in sorted(fmts.keys()): print("{0:10s} {1:24s} {2}".format(k, fmts[k], k in supported)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_table(filename): """ Load a table from a given file. Supports csv, tab, tex, vo, vot, xml, fits, and hdf5. Parameters filename : str File to read Returns ------- table : Table Table of data. """
supported = get_table_formats() fmt = os.path.splitext(filename)[-1][1:].lower() # extension sans '.' if fmt in ['csv', 'tab', 'tex'] and fmt in supported: log.info("Reading file {0}".format(filename)) t = ascii.read(filename) elif fmt in ['vo', 'vot', 'xml', 'fits', 'hdf5'] and fmt in supported: log.info("Reading file {0}".format(filename)) t = Table.read(filename) else: log.error("Table format not recognized or supported") log.error("{0} [{1}]".format(filename, fmt)) raise Exception("Table format not recognized or supported") return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_table(table, filename): """ Write a table to a file. Parameters table : Table Table to be written filename : str Destination for saving table. Returns ------- None """
try: if os.path.exists(filename): os.remove(filename) table.write(filename) log.info("Wrote {0}".format(filename)) except Exception as e: if "Format could not be identified" not in e.message: raise e else: fmt = os.path.splitext(filename)[-1][1:].lower() # extension sans '.' raise Exception("Cannot auto-determine format for {0}".format(fmt)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_to_source_list(table, src_type=OutputSource): """ Convert a table of data into a list of sources. A single table must have consistent source types given by src_type. src_type should be one of :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. Parameters table : Table Table of sources src_type : class Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. Returns ------- sources : list A list of objects of the given type. """
source_list = [] if table is None: return source_list for row in table: # Initialise our object src = src_type() # look for the columns required by our source object for param in src_type.names: if param in table.colnames: # copy the value to our object val = row[param] # hack around float32's broken-ness if isinstance(val, np.float32): val = np.float64(val) setattr(src, param, val) # save this object to our list of sources source_list.append(src) return source_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeFITSTable(filename, table): """ Convert a table into a FITSTable and then write to disk. Parameters filename : str Filename to write. table : Table Table to write. Returns ------- None Notes ----- Due to a bug in numpy, `int32` and `float32` are converted to `int64` and `float64` before writing. """
def FITSTableType(val): """ Return the FITSTable type corresponding to each named parameter in obj """ if isinstance(val, bool): types = "L" elif isinstance(val, (int, np.int64, np.int32)): types = "J" elif isinstance(val, (float, np.float64, np.float32)): types = "E" elif isinstance(val, six.string_types): types = "{0}A".format(len(val)) else: log.warning("Column {0} is of unknown type {1}".format(val, type(val))) log.warning("Using 5A") types = "5A" return types cols = [] for name in table.colnames: cols.append(fits.Column(name=name, format=FITSTableType(table[name][0]), array=table[name])) cols = fits.ColDefs(cols) tbhdu = fits.BinTableHDU.from_columns(cols) for k in table.meta: tbhdu.header['HISTORY'] = ':'.join((k, table.meta[k])) tbhdu.writeto(filename, overwrite=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeIslandContours(filename, catalog, fmt='reg'): """ Write an output file in ds9 .reg format that outlines the boundaries of each island. Parameters filename : str Filename to write. catalog : list List of sources. Only those of type :class:`AegeanTools.models.IslandSource` will have contours drawn. fmt : str Output format type. Currently only 'reg' is supported (default) Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandBoxes` """
if fmt != 'reg': log.warning("Format {0} not yet supported".format(fmt)) log.warning("not writing anything") return out = open(filename, 'w') print("#Aegean island contours", file=out) print("#AegeanTools.catalogs version {0}-({1})".format(__version__, __date__), file=out) line_fmt = 'image;line({0},{1},{2},{3})' text_fmt = 'fk5; text({0},{1}) # text={{{2}}}' mas_fmt = 'image; line({1},{0},{3},{2}) #color = yellow' x_fmt = 'image; point({1},{0}) # point=x' for c in catalog: contour = c.contour if len(contour) > 1: for p1, p2 in zip(contour[:-1], contour[1:]): print(line_fmt.format(p1[1] + 0.5, p1[0] + 0.5, p2[1] + 0.5, p2[0] + 0.5), file=out) print(line_fmt.format(contour[-1][1] + 0.5, contour[-1][0] + 0.5, contour[0][1] + 0.5, contour[0][0] + 0.5), file=out) # comment out lines that have invalid ra/dec (WCS problems) if np.nan in [c.ra, c.dec]: print('#', end=' ', file=out) # some islands may not have anchors because they don't have any contours if len(c.max_angular_size_anchors) == 4: print(text_fmt.format(c.ra, c.dec, c.island), file=out) print(mas_fmt.format(*[a + 0.5 for a in c.max_angular_size_anchors]), file=out) for p1, p2 in c.pix_mask: # DS9 uses 1-based instead of 0-based indexing print(x_fmt.format(p1 + 1, p2 + 1), file=out) out.close() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeIslandBoxes(filename, catalog, fmt): """ Write an output file in ds9 .reg, or kvis .ann format that contains bounding boxes for all the islands. Parameters filename : str Filename to write. catalog : list List of sources. Only those of type :class:`AegeanTools.models.IslandSource` will have contours drawn. fmt : str Output format type. Currently only 'reg' and 'ann' are supported. Default = 'reg'. Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandContours` """
if fmt not in ['reg', 'ann']: log.warning("Format not supported for island boxes{0}".format(fmt)) return # fmt not supported out = open(filename, 'w') print("#Aegean Islands", file=out) print("#Aegean version {0}-({1})".format(__version__, __date__), file=out) if fmt == 'reg': print("IMAGE", file=out) box_fmt = 'box({0},{1},{2},{3}) #{4}' else: print("COORD P", file=out) box_fmt = 'box P {0} {1} {2} {3} #{4}' for c in catalog: # x/y swap for pyfits/numpy translation ymin, ymax, xmin, xmax = c.extent # +1 for array/image offset xcen = (xmin + xmax) / 2.0 + 1 # + 0.5 in each direction to make lines run 'between' DS9 pixels xwidth = xmax - xmin + 1 ycen = (ymin + ymax) / 2.0 + 1 ywidth = ymax - ymin + 1 print(box_fmt.format(xcen, ycen, xwidth, ywidth, c.island), file=out) out.close() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeDB(filename, catalog, meta=None): """ Output an sqlite3 database containing one table for each source type Parameters filename : str Output filename catalog : list List of sources of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. meta : dict Meta data to be written to table `meta` Returns ------- None """
def sqlTypes(obj, names): """ Return the sql type corresponding to each named parameter in obj """ types = [] for n in names: val = getattr(obj, n) if isinstance(val, bool): types.append("BOOL") elif isinstance(val, (int, np.int64, np.int32)): types.append("INT") elif isinstance(val, (float, np.float64, np.float32)): # float32 is bugged and claims not to be a float types.append("FLOAT") elif isinstance(val, six.string_types): types.append("VARCHAR") else: log.warning("Column {0} is of unknown type {1}".format(n, type(n))) log.warning("Using VARCHAR") types.append("VARCHAR") return types if os.path.exists(filename): log.warning("overwriting {0}".format(filename)) os.remove(filename) conn = sqlite3.connect(filename) db = conn.cursor() # determine the column names by inspecting the catalog class for t, tn in zip(classify_catalog(catalog), ["components", "islands", "simples"]): if len(t) < 1: continue #don't write empty tables col_names = t[0].names col_types = sqlTypes(t[0], col_names) stmnt = ','.join(["{0} {1}".format(a, b) for a, b in zip(col_names, col_types)]) db.execute('CREATE TABLE {0} ({1})'.format(tn, stmnt)) stmnt = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(tn, ','.join(col_names), ','.join(['?' for i in col_names])) # expend the iterators that are created by python 3+ data = list(map(nulls, list(r.as_list() for r in t))) db.executemany(stmnt, data) log.info("Created table {0}".format(tn)) # metadata add some meta data db.execute("CREATE TABLE meta (key VARCHAR, val VARCHAR)") for k in meta: db.execute("INSERT INTO meta (key, val) VALUES (?,?)", (k, meta[k])) conn.commit() log.info(db.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()) conn.close() log.info("Wrote file {0}".format(filename)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def norm_dist(src1, src2): """ Calculate the normalised distance between two sources. Sources are elliptical Gaussians. The normalised distance is calculated as the GCD distance between the centers, divided by quadrature sum of the radius of each ellipse along a line joining the two ellipses. For ellipses that touch at a single point, the normalized distance will be 1/sqrt(2). Parameters src1, src2 : object The two positions to compare. Objects must have the following parameters: (ra, dec, a, b, pa). Returns ------- dist: float The normalised distance. """
if np.all(src1 == src2): return 0 dist = gcd(src1.ra, src1.dec, src2.ra, src2.dec) # degrees # the angle between the ellipse centers phi = bear(src1.ra, src1.dec, src2.ra, src2.dec) # Degrees # Calculate the radius of each ellipse along a line that joins their centers. r1 = src1.a*src1.b / np.hypot(src1.a * np.sin(np.radians(phi - src1.pa)), src1.b * np.cos(np.radians(phi - src1.pa))) r2 = src2.a*src2.b / np.hypot(src2.a * np.sin(np.radians(180 + phi - src2.pa)), src2.b * np.cos(np.radians(180 + phi - src2.pa))) R = dist / (np.hypot(r1, r2) / 3600) return R
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky_dist(src1, src2): """ Great circle distance between two sources. A check is made to determine if the two sources are the same object, in this case the distance is zero. Parameters src1, src2 : object Two sources to check. Objects must have parameters (ra,dec) in degrees. Returns ------- distance : float The distance between the two sources. See Also -------- :func:`AegeanTools.angle_tools.gcd` """
if np.all(src1 == src2): return 0 return gcd(src1.ra, src1.dec, src2.ra, src2.dec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pairwise_ellpitical_binary(sources, eps, far=None): """ Do a pairwise comparison of all sources and determine if they have a normalized distance within eps. Form this into a matrix of shape NxN. Parameters sources : list A list of sources (objects with parameters: ra,dec,a,b,pa) eps : float Normalised distance constraint. far : float If sources have a dec that differs by more than this amount then they are considered to be not matched. This is a short-cut around performing GCD calculations. Returns ------- prob : numpy.ndarray A 2d array of True/False. See Also -------- :func:`AegeanTools.cluster.norm_dist` """
if far is None: far = max(a.a/3600 for a in sources) l = len(sources) distances = np.zeros((l, l), dtype=bool) for i in range(l): for j in range(i, l): if i == j: distances[i, j] = False continue src1 = sources[i] src2 = sources[j] if src2.dec - src1.dec > far: break if abs(src2.ra - src1.ra)*np.cos(np.radians(src1.dec)) > far: continue distances[i, j] = norm_dist(src1, src2) > eps distances[j, i] = distances[i, j] return distances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regroup_vectorized(srccat, eps, far=None, dist=norm_dist): """ Regroup the islands of a catalog according to their normalised distance. Assumes srccat is recarray-like for efficiency. Return a list of island groups. Parameters srccat : np.rec.arry or pd.DataFrame Should have the following fields[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any] eps : float maximum normalised distance within which sources are considered to be grouped far : float (degrees) sources that are further than this distance apart will not be grouped, and will not be tested. Default = 0.5. dist : func a function that calculates the distance between a source and each element of an array of sources. Default = :func:`AegeanTools.cluster.norm_dist` Returns ------- islands : list of lists Each island contians integer indices for members from srccat (in descending dec order). """
if far is None: far = 0.5 # 10*max(a.a/3600 for a in srccat) # most negative declination first # XXX: kind='mergesort' ensures stable sorting for determinism. # Do we need this? order = np.argsort(srccat.dec, kind='mergesort')[::-1] # TODO: is it better to store groups as arrays even if appends are more # costly? groups = [[order[0]]] for idx in order[1:]: rec = srccat[idx] # TODO: Find out if groups are big enough for this to give us a speed # gain. If not, get distance to all entries in groups above # decmin simultaneously. decmin = rec.dec - far for group in reversed(groups): # when an island's largest (last) declination is smaller than # decmin, we don't need to look at any more islands if srccat.dec[group[-1]] < decmin: # new group groups.append([idx]) rafar = far / np.cos(np.radians(rec.dec)) group_recs = np.take(srccat, group, mode='clip') group_recs = group_recs[abs(rec.ra - group_recs.ra) <= rafar] if len(group_recs) and dist(rec, group_recs).min() < eps: group.append(idx) break else: # new group groups.append([idx]) # TODO?: a more numpy-like interface would return only an array providing # the mapping: # group_idx = np.empty(len(srccat), dtype=int) # for i, group in enumerate(groups): # group_idx[group] = i # return group_idx return groups
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_file_or_hdu(filename): """ Load a file from disk and return an HDUList If filename is already an HDUList return that instead Parameters filename : str or HDUList File or HDU to be loaded Returns ------- hdulist : HDUList """
if isinstance(filename, fits.HDUList): hdulist = filename else: hdulist = fits.open(filename, ignore_missing_end=True) return hdulist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compress(datafile, factor, outfile=None): """ Compress a file using decimation. Parameters datafile : str or HDUList Input data to be loaded. (HDUList will be modified if passed). factor : int Decimation factor. outfile : str File to be written. Default = None, which means don't write a file. Returns ------- hdulist : HDUList A decimated HDUList See Also -------- :func:`AegeanTools.fits_interp.expand` """
if not (factor > 0 and isinstance(factor, int)): logging.error("factor must be a positive integer") return None hdulist = load_file_or_hdu(datafile) header = hdulist[0].header data = np.squeeze(hdulist[0].data) cx, cy = data.shape[0], data.shape[1] nx = cx // factor ny = cy // factor # check to see if we will have some residual data points lcx = cx % factor lcy = cy % factor if lcx > 0: nx += 1 if lcy > 0: ny += 1 # decimate the data new_data = np.empty((nx + 1, ny + 1)) new_data[:nx, :ny] = data[::factor, ::factor] # copy the last row/col across new_data[-1, :ny] = data[-1, ::factor] new_data[:nx, -1] = data[::factor, -1] new_data[-1, -1] = data[-1, -1] # TODO: Figure out what to do when CD2_1 and CD1_2 are non-zero if 'CDELT1' in header: header['CDELT1'] *= factor elif 'CD1_1' in header: header['CD1_1'] *= factor else: logging.error("Error: Can't find CDELT1 or CD1_1") return None if 'CDELT2' in header: header['CDELT2'] *= factor elif "CD2_2" in header: header['CD2_2'] *= factor else: logging.error("Error: Can't find CDELT2 or CD2_2") return None # Move the reference pixel so that the WCS is correct header['CRPIX1'] = (header['CRPIX1'] + factor - 1) / factor header['CRPIX2'] = (header['CRPIX2'] + factor - 1) / factor # Update the header so that we can do the correct interpolation later on header['BN_CFAC'] = (factor, "Compression factor (grid size) used by BANE") header['BN_NPX1'] = (header['NAXIS1'], 'original NAXIS1 value') header['BN_NPX2'] = (header['NAXIS2'], 'original NAXIS2 value') header['BN_RPX1'] = (lcx, 'Residual on axis 1') header['BN_RPX2'] = (lcy, 'Residual on axis 2') header['HISTORY'] = "Compressed by a factor of {0}".format(factor) # save the changes hdulist[0].data = np.array(new_data, dtype=np.float32) hdulist[0].header = header if outfile is not None: hdulist.writeto(outfile, overwrite=True) logging.info("Wrote: {0}".format(outfile)) return hdulist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(datafile, outfile=None): """ Expand and interpolate the given data file using the given method. Datafile can be a filename or an HDUList It is assumed that the file has been compressed and that there are `BN_?` keywords in the fits header that describe how the compression was done. Parameters datafile : str or HDUList filename or HDUList of file to work on outfile : str filename to write to (default = None) Returns ------- hdulist : HDUList HDUList of the expanded data. See Also -------- :func:`AegeanTools.fits_interp.compress` """
hdulist = load_file_or_hdu(datafile) header = hdulist[0].header data = hdulist[0].data # Check for the required key words, only expand if they exist if not all(a in header for a in ['BN_CFAC', 'BN_NPX1', 'BN_NPX2', 'BN_RPX1', 'BN_RPX2']): return hdulist factor = header['BN_CFAC'] (gx, gy) = np.mgrid[0:header['BN_NPX2'], 0:header['BN_NPX1']] # fix the last column of the grid to account for residuals lcx = header['BN_RPX2'] lcy = header['BN_RPX1'] rows = (np.arange(data.shape[0]) + int(lcx/factor))*factor cols = (np.arange(data.shape[1]) + int(lcy/factor))*factor # Do the interpolation hdulist[0].data = np.array(RegularGridInterpolator((rows,cols), data)((gx, gy)), dtype=np.float32) # update the fits keywords so that the WCS is correct header['CRPIX1'] = (header['CRPIX1'] - 1) * factor + 1 header['CRPIX2'] = (header['CRPIX2'] - 1) * factor + 1 if 'CDELT1' in header: header['CDELT1'] /= factor elif 'CD1_1' in header: header['CD1_1'] /= factor else: logging.error("Error: Can't find CD1_1 or CDELT1") return None if 'CDELT2' in header: header['CDELT2'] /= factor elif "CD2_2" in header: header['CD2_2'] /= factor else: logging.error("Error: Can't find CDELT2 or CD2_2") return None header['HISTORY'] = 'Expanded by factor {0}'.format(factor) # don't need these any more so delete them. del header['BN_CFAC'], header['BN_NPX1'], header['BN_NPX2'], header['BN_RPX1'], header['BN_RPX2'] hdulist[0].header = header if outfile is not None: hdulist.writeto(outfile, overwrite=True) logging.info("Wrote: {0}".format(outfile)) return hdulist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_autocommit_mode(self, switch): """ Strip and make a string case insensitive and ensure it is either 'true' or 'false'. If neither, prompt user for either value. When 'true', return True, and when 'false' return False. """
parsed_switch = switch.strip().lower() if not parsed_switch in ['true', 'false']: self.send_response( self.iopub_socket, 'stream', { 'name': 'stderr', 'text': 'autocommit must be true or false.\n\n' } ) switch_bool = (parsed_switch == 'true') committed = self.switch_autocommit(switch_bool) message = ( 'committed current transaction & ' if committed else '' + 'switched autocommit mode to ' + str(self._autocommit) ) self.send_response( self.iopub_socket, 'stream', { 'name': 'stderr', 'text': message, } )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deconstruct(self): """ Deconstruct the field for Django 1.7+ migrations. """
name, path, args, kwargs = super(BaseEncryptedField, self).deconstruct() kwargs.update({ #'key': self.cipher_key, 'cipher': self.cipher_name, 'charset': self.charset, 'check_armor': self.check_armor, 'versioned': self.versioned, }) return name, path, args, kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_packages_by_root_package(where): """Better than excluding everything that is not needed, collect only what is needed. """
root_package = os.path.basename(where) packages = [ "%s.%s" % (root_package, sub_package) for sub_package in find_packages(where)] packages.insert(0, root_package) return packages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_long_description(marker=None, intro=None): """ click_ is a framework to simplify writing composable commands for command-line tools. This package extends the click_ functionality by adding support for commands that use configuration files. .. _click: https://click.pocoo.org/ EXAMPLE: A configuration file, like: .. code-block:: INI # -- FILE: foo.ini [foo] flag = yes name = Alice and Bob numbers = 1 4 9 16 25 filenames = foo/xxx.txt bar/baz/zzz.txt [person.alice] name = Alice birthyear = 1995 [person.bob] name = Bob birthyear = 2001 can be processed with: .. code-block:: python # EXAMPLE: """
if intro is None: intro = inspect.getdoc(make_long_description) with open("README.rst", "r") as infile: line = infile.readline() while not line.strip().startswith(marker): line = infile.readline() # -- COLLECT REMAINING: Usage example contents = infile.read() text = intro +"\n" + contents return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pubsub_pop_message(self, deadline=None): """Pops a message for a subscribed client. Args: deadline (int): max number of seconds to wait (None => no timeout) Returns: Future with the popped message as result (or None if timeout or ConnectionError object in case of connection errors or ClientError object if you are not subscribed) """
if not self.subscribed: excep = ClientError("you must subscribe before using " "pubsub_pop_message") raise tornado.gen.Return(excep) reply = None try: reply = self._reply_list.pop(0) raise tornado.gen.Return(reply) except IndexError: pass if deadline is not None: td = timedelta(seconds=deadline) yield self._condition.wait(timeout=td) else: yield self._condition.wait() try: reply = self._reply_list.pop(0) except IndexError: pass raise tornado.gen.Return(reply)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_flat_ids(assigned): """ This is a helper function to recover the coordinates of regions that have been labeled within an image. This function efficiently computes the coordinate of all regions and returns the information in a memory-efficient manner. Parameters assigned : ndarray[ndim=2, dtype=int] The labeled image. For example, the result of calling scipy.ndimage.label on a binary image Returns -------- I : ndarray[ndim=1, dtype=int] Array of 1d coordinate indices of all regions in the image region_ids : ndarray[shape=[n_features + 1], dtype=int] Indexing array used to separate the coordinates of the different regions. For example, region k has xy coordinates of xy[region_ids[k]:region_ids[k+1], :] labels : ndarray[ndim=1, dtype=int] The labels of the regions in the image corresponding to the coordinates For example, assigned.ravel()[I[k]] == labels[k] """
# MPU optimization: # Let's segment the regions and store in a sparse format # First, let's use where once to find all the information we want ids_labels = np.arange(len(assigned.ravel()), 'int64') I = ids_labels[assigned.ravel().astype(bool)] labels = assigned.ravel()[I] # Now sort these arrays by the label to figure out where to segment sort_id = np.argsort(labels) labels = labels[sort_id] I = I[sort_id] # this should be of size n_features-1 region_ids = np.where(labels[1:] - labels[:-1] > 0)[0] + 1 # This should be of size n_features + 1 region_ids = np.concatenate(([0], region_ids, [len(labels)])) return [I, region_ids, labels]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2): """ This function gives the magnitude and direction of the slope based on Tarboton's D_\infty method. This is a helper-function to _tarboton_slopes_directions """
data0 = data[slc0] data1 = data[slc1] data2 = data[slc2] s1 = (data0 - data1) / d1 s2 = (data1 - data2) / d2 s1_2 = s1**2 sd = (data0 - data2) / np.sqrt(d1**2 + d2**2) r = np.arctan2(s2, s1) rad2 = s1_2 + s2**2 # Handle special cases # should be on diagonal b_s1_lte0 = s1 <= 0 b_s2_lte0 = s2 <= 0 b_s1_gt0 = s1 > 0 b_s2_gt0 = s2 > 0 I1 = (b_s1_lte0 & b_s2_gt0) | (r > theta) if I1.any(): rad2[I1] = sd[I1] ** 2 r[I1] = theta.repeat(I1.shape[1], 1)[I1] I2 = (b_s1_gt0 & b_s2_lte0) | (r < 0) # should be on straight section if I2.any(): rad2[I2] = s1_2[I2] r[I2] = 0 I3 = b_s1_lte0 & (b_s2_lte0 | (b_s2_gt0 & (sd <= 0))) # upslope or flat rad2[I3] = -1 I4 = rad2 > mag[slc0] if I4.any(): mag[slc0][I4] = rad2[I4] direction[slc0][I4] = r[I4] * ang[1] + ang[0] * np.pi/2 return mag, direction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_i(self, i, data, field, side): """ Assigns data on the i'th tile to the data 'field' of the 'side' edge of that tile """
edge = self.get_i(i, side) setattr(edge, field, data[edge.slice])