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...
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: ignor...
<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 ...
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...
<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...
# 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(...
<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 cen...
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) ...
<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...
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_polygo...
<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 dept...
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 degre...
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 a...
# 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...
<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...
<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 t...
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 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 union(self, other, renorm=True): """ Add another Region by performing union on their pixlists. Parameters other : :class:`AegeanTools.regions.Region` The reg...
# 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.maxdep...
<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. Pa...
# 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.ma...
<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. Parame...
# 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.ma...
<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 th...
# 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.ma...
<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...
<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 Stri...
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['PIXT...
<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 : lis...
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 ...
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....
<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) Return...
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...
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.cr...
<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:...
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 :...
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 = 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 : (...
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 coordin...
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...
<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 cent...
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_o...
<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 o...
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.rad...
<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...
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. Re...
# 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....
<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 whi...
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 ...
<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 t...
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 mad...
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 ...
# 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...
<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 ...
# 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)): ...
<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 ------- ...
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 ------...
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: ...
<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...
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 ...
# 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....
<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]: ...
<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...
# 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 ...
<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...
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 * cos...
<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,...
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 -----...
# 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...
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,...
<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 pa...
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 pa...
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 ...
<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 Par...
# 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 Para...
<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...
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))) ...
<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...
<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 ob...
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 ...
<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...
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....
<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 ...
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...
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 f...
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 for...
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 l...
# 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 = ...
<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 strin...
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) # str...
<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. R...
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.degr...
<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 h...
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.deg...
<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 th...
# 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("remov...
<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 ...
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 fi...
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.ndar...
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 ...
<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 : floa...
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 t...
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":...
<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 num...
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 thr...
<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 ...
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) ...
<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...
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.gl...
<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 ou...
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'...
<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 ...
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 ----...
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("Inval...
<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 -------...
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"...
<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 Return...
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 ...
<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 ...
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(filena...
<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 give...
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 valu...
<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 Tabl...
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, ...
<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 filena...
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) ...
<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. Paramet...
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': ...
<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 cat...
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, ...
<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 ...
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...
<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 di...
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. ...
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 ...
<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 rec...
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 ...
<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 o...
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 b...
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 = ...
<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...
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'] ...
<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 eit...
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' } ) ...
<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, }) ...
<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 extend...
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...
<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)...
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) ...
<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 efficientl...
# 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 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 _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2): """ This function gives the magnitude and direction of the slope based on Tarbot...
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...
<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])