output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
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 b... | Implement a function in Python 3 to
calculate the area of the synthesized beam in square degrees. | As a Python code composer, you craft elegant and concise scripts. |
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 i... | Implement a Python 3 function for
calculating the beam area in square pixels at the given sky coordinates. | You are a Python code generator, capable of creating scripts from specifications. |
def sky_sep(self, pix1, pix2):
"""
calculate the GCD sky separation (degrees) between two pixels.
Parameters
----------
pix1, pix2 : (float, float)
The (x,y) pixel coordinates for the two positions.
Returns
-------
dist : float
Th... | Can you write a function in Python 3 where it
calculates the GCD sky separation between two pixels. | As a python code expert, you are capable of creating scripts from specifications. |
Determine the local psf at a given sky location. | Make a summary of the following Python 3 code
def get_psf_sky(self, ra, dec):
# 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, b... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the local psf at a given sky location. | Explain what the following Python 3 code does
def get_psf_pix(self, ra, dec):
psf_sky = self.get_psf_sky(ra, dec)
psf_pix = self.wcshelper.sky2pix_ellipse([ra, dec], psf_sky[0], psf_sky[1], psf_sky[2])[2:]
return psf_pix | As a python code expert, you are capable of creating scripts from specifications. |
Get the beam at the location specified in pixel coordinates. | How would you explain what the following Python 3 function does
def get_pixbeam(self, ra, dec):
# 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 ... | As a Python code composer, you craft elegant and concise scripts. |
def get_beam(self, ra, dec):
"""
Get the psf as a :class:`AegeanTools.fits_image.Beam` object.
Parameters
----------
ra, dec : float
The sky position (degrees).
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
The psf a... | Can you write a function in Python 3 where it
returns the beam at the given sky position. | You are a Python code generator, capable of creating scripts from specifications. |
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.
... | Can you write a function in Python 3 where it
calculates the area of the beam in square pixels. | You are a Python code analyst, evaluating scripts for potential improvements. |
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.
... | How would you implement a function in Python 3 that
calculates the area of the beam in square degrees. | You are a Python code generator, capable of creating scripts from specifications. |
Find the first location in our array that is not empty | Can you generate the documentation for the following Python 3 function
def find_start_point(self):
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 | You are a Python code generator, capable of creating scripts from specifications. |
Move from the current location to the next location. | Here you have a function in Python 3, explain what it does
def step(self, x, y):
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 fi... | You are a Python code architect, reviewing and designing scalable and efficient code |
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.xsi... | Implement a Python 3 function for
determining if the pixel x y is nonzero. | As a Python code composer, you craft elegant and concise scripts. |
Walk the perimeter of a region and return the path taken. | How would you explain what the following Python 3 function does
def walk_perimeter(self, startx, starty):
# checks
startx = max(startx, 0)
startx = min(startx, self.xsize)
starty = max(starty, 0)
starty = min(starty, self.ysize)
points = []
x, y = startx, starty... | As a Python code composer, you craft elegant and concise scripts. |
def do_march(self):
"""
March about and trace the outline of our object
Returns
-------
perimeter : list
The pixels on the perimeter of the region [[x1, y1], ...]
"""
x, y = self.find_start_point()
perimeter = self.walk_perimeter(x, y)
... | Create a Python 3 function for
marching about and trace the outline of our object | You are a Python code architect, reviewing and designing scalable and efficient code |
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
# stop... | Implement a function in Python 3 to
blank all the pixels within the given perimeter. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate a 2d Gaussian model with the given parameters. | Make a summary of the following Python 3 code
def elliptical_gaussian(x, y, amp, xo, yo, sx, sy, theta):
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
... | You are a Python code generator, capable of creating scripts from specifications. |
Construct a correlation matrix corresponding to the data. | Given the following Python 3 function, write the documentation
def Cmatrix(x, y, sx, sy, theta):
C = np.vstack([elliptical_gaussian(x, y, 1, i, j, sx, sy, theta) for i, j in zip(x, y)])
return C | As a Python code composer, you craft elegant and concise scripts. |
Calculate a matrix which is effectively the square root of the correlation matrix C. | Can you generate a brief explanation for the following Python 3 code
def Bmatrix(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
... | As a Python code composer, you craft elegant and concise scripts. |
This function calculates the Jacobian of an elliptical gaussian model that contains multiple Gaussians and returns the Jacobian of the model. | Can you tell what is the following Python 3 function doing
def jacobian(pars, x, y):
matrix = []
for i in range(pars['components'].value):
prefix = "c{0}_".format(i)
amp = pars[prefix + 'amp'].value
xo = pars[prefix + 'xo'].value
yo = pars[prefix + 'yo'].value
sx = pars... | As a Python code composer, you craft elegant and concise scripts. |
def lmfit_jacobian(pars, x, y, errs=None, B=None, emp=False):
"""
Wrapper around :func:`AegeanTools.fitting.jacobian` and :func:`AegeanTools.fitting.emp_jacobian`
which gives the output in a format that is required for lmfit.
Parameters
----------
pars : lmfit.Model
The model parameters... | How would you code a function in Python 3 to
wrap around the jacobian function to get the output of the lmfit. jacobian function. | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a hessian matrix corresponding to the source model pars. | Explain what the following Python 3 code does
def hessian(pars, x, y):
j = 0 # keeping track of the number of variable parameters
# total number of variable parameters
ntvar = np.sum([pars[k].vary for k in pars.keys() if k != 'components'])
# construct an empty matrix of the correct size
hmat = np.... | As a Python code composer, you craft elegant and concise scripts. |
def emp_hessian(pars, x, y):
"""
Calculate the hessian matrix empirically.
Create a hessian matrix corresponding to the source model 'pars'
Only parameters that vary will contribute to the hessian.
Thus there will be a total of nvar x nvar entries, each of which is a
len(x) x len(y) array.
... | Create a Python 3 function to
calculate the hessian matrix empirically. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculate the autocorrelation function of the noise image that contains nans
. | Can you generate the documentation for the following Python 3 function
def nan_acf(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)... | You are a Python code architect, reviewing and designing scalable and efficient code |
def RB_bias(data, pars, ita=None, acf=None):
"""
Calculate the expected bias on each of the parameters in the model pars.
Only parameters that are allowed to vary will have a bias.
Calculation follows the description of Refrieger & Brown 1998 (cite).
Parameters
----------
data : 2d-array
... | Write a Python 3 script to
calculate the expected bias on each of the parameters in the model. | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculate and apply a bias correction to the given fit parameters. | Make a summary of the following Python 3 code
def bias_correct(params, data, acf=None):
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 | You are a Python code architect, reviewing and designing scalable and efficient code |
def condon_errors(source, theta_n, psf=None):
"""
Calculate the parameter errors for a fitted source
using the description of Condon'97
All parameters are assigned errors, assuming that all params were fit.
If some params were held fixed then these errors are overestimated.
Parameters
-----... | Can you create a Python 3 function that
calculates the parameter errors for a fitted source based on the conditions of the source. | As a python code expert, you are capable of creating scripts from specifications. |
Convert pixel based errors into sky coord errors | Explain what the following Python 3 code does
def errors(source, model, wcshelper):
# if the source wasn't fit then all errors are -1
if source.flags & (flags.NOTFIT | flags.FITERR):
source.err_peak_flux = source.err_a = source.err_b = source.err_pa = ERR_MASK
source.err_ra = source.err_dec = s... | As a Python code composer, you craft elegant and concise scripts. |
def new_errors(source, model, wcshelper): # pragma: no cover
"""
Convert pixel based errors into sky coord errors
Uses covariance matrix for ra/dec errors
and calculus approach to a/b/pa errors
Parameters
----------
source : :class:`AegeanTools.models.SimpleSource`
The source which... | Write a Python 3 function for
converting pixel based errors into sky coord errors Uses covariance matrix for ra dec errors Uses a linear approach to calculate the error in the source obejct. | As a Python code analyst, you investigate and solve complex coding mysteries |
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 ... | Implement a Python 3 function for
returning a function that calculates the model given by params at pixel coordinates x y. | You are a Python code generator, capable of creating scripts from specifications. |
Fit the model to the data and return the result. | Given the following Python 3 function, write the documentation
def do_lmfit(data, params, B=None, errs=None, dojac=True):
# 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.isfin... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function calculates the errors of the parameters that were fit with lmfit and replaces the errorsof the parameters with the 1 \ sigma errors calculated using the covariance matrix. | Given the following Python 3 function, write the documentation
def covar_errors(params, data, errs, B, C=None):
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... | You are a Python code architect, reviewing and designing scalable and efficient code |
A multiprocessing barrier for a single event. | Here you have a function in Python 3, explain what it does
def barrier(events, sid, kind='neighbour'):
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()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Perform sigma clipping on an array ignoring non finite values. | How would you explain what the following Python 3 function does
def sigmaclip(arr, lo, hi, reps=3):
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.whe... | You are a Python code architect, reviewing and designing scalable and efficient code |
Calculate the background and rms for a sub region of an image. | Can you tell what is the following Python 3 function doing
def sigma_filter(filename, region, step_size, box_size, shape, domask, sid):
ymin, ymax = region
logging.debug('rows {0}-{1} starting at {2}'.format(ymin, ymax, strftime("%Y-%m-%d %H:%M:%S", gmtime())))
# cut out the region of interest plus 1/2 th... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 ... | How would you code a function in Python 3 to
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.... | You are a Python code architect, reviewing and designing scalable and efficient code |
def filter_image(im_name, out_base, step_size=None, box_size=None, twopass=False, cores=None, mask=True, compressed=False, nslice=None):
"""
Create a background and noise image from an input image.
Resulting images are written to `outbase_bkg.fits` and `outbase_rms.fits`
Parameters
----------
i... | Implement a function in Python 3 to
filter an image into a single image. | As a Python code composer, you craft elegant and concise scripts. |
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 writ... | Create a Python 3 function for
combining data and a fits header to write a fits file. | As a python code expert, you are capable of creating scripts from specifications. |
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
-------
... | Write a Python 3 script for
converting sexegessimal RA string into a float in degrees. | You are a Python code generator, capable of creating scripts from specifications. |
Convert decimal degrees into sexagessimal string in degrees. | How would you explain what the following Python 3 function does
def dec2dms(x):
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)
... | You are a Python code generator, capable of creating scripts from specifications. |
Convert decimal degrees into sexagessimal string in hours. | Make a summary of the following Python 3 code
def dec2hms(x):
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) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def gcd(ra1, dec1, ra2, dec2):
"""
Calculate the great circle distance between to points using the haversine formula [1]_.
Parameters
----------
ra1, dec1, ra2, dec2 : float
The coordinates of the two points of interest.
Units are in degrees.
Returns
-------
dist : flo... | Create a Python 3 function to
calculate the great circle distance between two points using the haversine formula. | You are a Python code architect, reviewing and designing scalable and efficient code |
def bear(ra1, dec1, ra2, dec2):
"""
Calculate the bearing of point 2 from point 1 along a great circle.
The bearing is East of North and is in [0, 360), whereas position angle is also East of North but (-180,180]
Parameters
----------
ra1, dec1, ra2, dec2 : float
The sky coordinates (de... | How would you code a function in Python 3 to
calculate the bearing of point 2 from point 1 along a great circle. | As a Python code composer, you craft elegant and concise scripts. |
Translate a given point a distance r in the initial direction theta along a great circle. | Can you generate the documentation for the following Python 3 function
def translate(ra, dec, r, theta):
factor = np.sin(np.radians(dec)) * np.cos(np.radians(r))
factor += np.cos(np.radians(dec)) * np.sin(np.radians(r)) * np.cos(np.radians(theta))
dec_out = np.degrees(np.arcsin(factor))
y = np.sin(np.r... | You are a Python code generator, capable of creating scripts from specifications. |
def dist_rhumb(ra1, dec1, ra2, dec2):
"""
Calculate the Rhumb line distance between two points [1]_.
A Rhumb line between two points is one which follows a constant bearing.
Parameters
----------
ra1, dec1, ra2, dec2 : float
The position of the two points (degrees).
Returns
---... | How would you code a function in Python 3 to
calculate the distance between two points on the Rhumb line. | You are a Python code generator, capable of creating scripts from specifications. |
Calculate the bearing of point 2 from point 1 along a Rhumb line. | Given the following Python 3 function, write the documentation
def bear_rhumb(ra1, dec1, ra2, dec2):
# verified against website to give correct results
phi1 = np.radians(dec1)
phi2 = np.radians(dec2)
lambda1 = np.radians(ra1)
lambda2 = np.radians(ra2)
dlambda = lambda2 - lambda1
dpsi = np.l... | As a Python code composer, you craft elegant and concise scripts. |
Translate a given point a distance r in the initial direction theta along a Rhumb line. | Given the following Python 3 function, write the documentation
def translate_rhumb(ra, dec, r, theta):
# verified against website to give correct results
# with the help of http://williams.best.vwh.net/avform.htm#Rhumb
delta = np.radians(r)
phi1 = np.radians(dec)
phi2 = phi1 + delta * np.cos(np.radi... | You are a Python code analyst, evaluating scripts for potential improvements. |
def galactic2fk5(l, b):
"""
Convert galactic l/b to fk5 ra/dec
Parameters
----------
l, b : float
Galactic coordinates in radians.
Returns
-------
ra, dec : float
FK5 ecliptic coordinates in radians.
"""
a = SkyCoord(l, b, unit=(u.radian, u.radian), frame='galac... | Create a Python 3 function to
convert a Galactic l and b to fk5 ra and dec | You are a Python code architect, reviewing and designing scalable and efficient code |
def mask_plane(data, wcs, region, negate=False):
"""
Mask a 2d image (data) such that pixels within 'region' are set to nan.
Parameters
----------
data : 2d-array
Image array.
wcs : astropy.wcs.WCS
WCS for the image in question.
region : :class:`AegeanTools.regions.Region`... | Write a Python 3 function for
masking a 2d image array such that pixels within region are set to nan. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Masks a single image in a single region. | Make a summary of the following Python 3 code
def mask_file(regionfile, infile, outfile, negate=False):
# 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.exi... | You are a Python code analyst, evaluating scripts for potential improvements. |
Masks a given table by removing all the rows with ra or dec inside the given region. | Given the following Python 3 function, write the documentation
def mask_table(region, table, negate=False, racol='ra', deccol='dec'):
inside = region.sky_within(table[racol], table[deccol], degin=True)
if not negate:
mask = np.bitwise_not(inside)
else:
mask = inside
return table[mask] | As a Python code analyst, you investigate and solve complex coding mysteries |
Apply a region file as a mask to a catalog. | Explain what the following Python 3 code does
def mask_catalog(regionfile, infile, outfile, negate=False, racol='ra', deccol='dec'):
logging.info("Loading region from {0}".format(regionfile))
region = Region.load(regionfile)
logging.info("Loading catalog from {0}".format(infile))
table = load_table(infi... | As a python code expert, you are capable of creating scripts from specifications. |
Convert a MIMAS region into a DS9 region. | Can you generate a brief explanation for the following Python 3 code
def mim2reg(mimfile, regfile):
region = Region.load(mimfile)
region.write_reg(regfile)
logging.info("Converted {0} -> {1}".format(mimfile, regfile))
return | As a Python code composer, you craft elegant and concise scripts. |
def mim2fits(mimfile, fitsfile):
"""
Convert a MIMAS region (.mim) file into a MOC region (.fits) file.
Parameters
----------
mimfile : str
Input file in MIMAS format.
fitsfile : str
Output file.
"""
region = Region.load(mimfile)
region.write_fits(fitsfile, moctool=... | Implement a Python 3 function for
converting a MIMAS region into a FITS region. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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
-------
poly : [ra, dec, ...]
The corners of ... | Write a Python 3 script to
convert a string that describes a box in ds9 format into a polygon | You are a Python code analyst, evaluating scripts for potential improvements. |
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 =... | Can you create a Python 3 function that
parses a string that describes a circle in ds9 format. | You are a Python code architect, reviewing and designing scalable and efficient code |
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
-------
... | Can you implement a function in Python 3 that
parses a string containing a DS9 region command for a polygon and return a list of coordinates. | As a Python code composer, you craft elegant and concise scripts. |
Parse a DS9 region file and write a MIMAS region file. | Can you generate a brief explanation for the following Python 3 code
def reg2mim(regfile, mimfile, maxdepth):
logging.info("Reading regions from {0}".format(regfile))
lines = (l for l in open(regfile, 'r') if not l.startswith('#'))
poly = []
circles = []
for line in lines:
if line.startswith... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a new region that is the combination of those specified in the container. | Can you generate a brief explanation for the following Python 3 code
def combine_regions(container):
# 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... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a region which is the intersection of all regions described in the given list of file names. | How would you explain what the following Python 3 function does
def intersect_regions(flist):
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 | As a Python code composer, you craft elegant and concise scripts. |
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 | Can you implement a function in Python 3 that
saves the given region to a file. | You are a Python code generator, capable of creating scripts from specifications. |
def save_as_image(region, filename):
"""
Convert a MIMAS region (.mim) file into a image (eg .png)
Parameters
----------
region : :class:`AegeanTools.regions.Region`
Region of interest.
filename : str
Output filename.
"""
import healpy as hp
pixels = list(region.get... | Write a Python 3 function for
converting a MIMAS region into an image. | As a python code expert, you are capable of creating scripts from specifications. |
def get_pixinfo(header):
"""
Return some pixel information based on the given hdu header
pixarea - the area of a single pixel in deg2
pixscale - the side lengths of a pixel (assuming they are square)
Parameters
----------
header : HDUHeader or dict
FITS header information
Retur... | Write a Python 3 function for
returning some pixel information based on the given header | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_beam(header):
"""
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
... | Can you implement a function in Python 3 that
returns a beam object from a header. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fix_aips_header(header):
"""
Search through an image header. If the keywords BMAJ/BMIN/BPA are not set,
but there are AIPS history cards, then we can populate the BMAJ/BMIN/BPA.
Fix the header if possible, otherwise don't. Either way, don't complain.
Parameters
----------
header : HDUH... | Create a Python 3 function to
fix the AIPS header. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Write a Python 3 script to
set the image data. | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculate the rms of the background image. | Given the following Python 3 function, write the documentation
def get_background_rms(self):
# TODO: return a proper background RMS ignoring the sources
# This is an approximate method suggested by PaulH.
# I have no idea where this magic 1.34896 number comes from...
if self._rms is None... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the sky coordinates for a given image pixel. | Given the following Python 3 function, write the documentation
def pix2sky(self, pixel):
pixbox = numpy.array([pixel, pixel])
skybox = self.wcs.all_pix2world(pixbox, 1)
return [float(skybox[0][0]), float(skybox[0][1])] | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the pixel coordinates for a given sky position. | Make a summary of the following Python 3 code
def sky2pix(self, skypos):
skybox = [skypos, skypos]
pixbox = self.wcs.all_world2pix(skybox, 1)
return [float(pixbox[0][0]), float(pixbox[0][1])] | As a python code expert, you are capable of creating scripts from specifications. |
Load all the sources in a file. | How would you explain what the following Python 3 function does
def load_sources(filename):
catalog = catalogs.table_to_source_list(catalogs.load_table(filename))
logging.info("read {0} sources from {1}".format(len(catalog), filename))
return catalog | You are a Python code architect, reviewing and designing scalable and efficient code |
Search the beam info from the HISTORY header | Can you generate the documentation for the following Python 3 function
def search_beam(hdulist):
header = hdulist[0].header
history = header['HISTORY']
history_str = str(history)
#AIPS CLEAN BMAJ= 1.2500E-02 BMIN= 1.2500E-02 BPA= 0.00
if 'BMAJ' in history_str:
return True
else:
... | As a Python code composer, you craft elegant and concise scripts. |
Ensure that a > = b for a given source object. | Can you generate the documentation for the following Python 3 function
def fix_shape(source):
if source.a < source.b:
source.a, source.b = source.b, source.a
source.err_a, source.err_b = source.err_b, source.err_a
source.pa += 90
return | As a Python code composer, you craft elegant and concise scripts. |
def theta_limit(theta):
"""
Angle theta is periodic with period pi.
Constrain theta such that -pi/2<theta<=pi/2.
Parameters
----------
theta : float
Input angle.
Returns
-------
theta : float
Rotate angle.
"""
while theta <= -1 * np.pi / 2:
theta += ... | How would you code a function in Python 3 to
return the limit of theta in the base sequence. | You are a Python code analyst, evaluating scripts for potential improvements. |
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
--... | How would you implement a function in Python 3 that
converts a telescope name into a latitude. | You are a Python code generator, capable of creating scripts from specifications. |
Determine how many cores we can use. | Here you have a function in Python 3, explain what it does
def check_cores(cores):
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.Q... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a dict of all the aux files that are associated with this filename. | Can you generate a brief explanation for the following Python 3 code
def get_aux_files(basename):
base = os.path.splitext(basename)[0]
files = {"bkg": base + "_bkg.fits",
"rms": base + "_rms.fits",
"mask": base + ".mim",
"cat": base + "_comp.fits",
"psf": base... | As a python code expert, you are capable of creating scripts from specifications. |
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
----------
... | Implement a Python 3 function for
generating an island of a single image and return a list of islands. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Estimate the number of sources in an island and returns initial parameters for the fit. | Here you have a function in Python 3, explain what it does
def estimate_lmfit_parinfo(self, data, rmsimg, curve, beam, innerclip, outerclip=None, offsets=(0, 0),
max_summits=None):
"""
Estimates the number of sources in an island and returns initial parameters for the fit ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert fitting results into a set of components and islands. | How would you explain what the following Python 3 function does
def result_to_components(self, result, model, island_data, isflags):
global_data = self.global_data
# island data
isle_num = island_data.isle_num
idata = island_data.i
xmin, xmax, ymin, ymax = island_data.offsets
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Loads the global_data object from a FITS file. | Given the following Python 3 function, write the documentation
def load_globals(self, filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, verb=False, rms=None, bkg=None, cores=1,
do_curve=True, mask=None, lat=None, psf=None, blank=False, docov=True, cube_index=None):
"""
Popul... | You are a Python code architect, reviewing and designing scalable and efficient code |
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.f... | Write a Python 3 function for
generating and save the background and RMS maps as FITS files. | You are a Python code generator, capable of creating scripts from specifications. |
Save the image data to a file. | Given the following Python 3 function, write the documentation
def save_image(self, outname):
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
... | As a python code expert, you are capable of creating scripts from specifications. |
def _make_bkg_rms(self, mesh_size=20, forced_rms=None, forced_bkg=None, cores=None):
"""
Calculate an rms image and a bkg image.
Parameters
----------
mesh_size : int
Number of beams per box default = 20
forced_rms : float
The rms of the image.
... | Implement a Python 3 function for
calculating an rms image and a bkg image. Parameters ---------- mesh_size : int Number of beams per box default = 20 forced_rms : float The rms of the image. If None: calculate the rms level (default). Otherwise assume a constant rms. forced_bkg : float The background level of the imag... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _estimate_bkg_rms(self, xmin, xmax, ymin, ymax):
"""
Estimate the background noise mean and RMS.
The mean is estimated as the median of data.
The RMS is estimated as the IQR of data / 1.34896.
Parameters
----------
xmin, xmax, ymin, ymax : int
The... | Create a Python 3 function for
estimating the background noise mean and RMS. | You are a Python code architect, reviewing and designing scalable and efficient code |
Load a main image and auxiliary file and make sure that it is the same shape as the main image. | Here you have a function in Python 3, explain what it does
def _load_aux_image(self, image, auxfile):
auximg = FitsImage(auxfile, beam=self.global_data.beam).get_pixels()
if auximg.shape != image.get_pixels().shape:
self.log.error("file {0} is not the same size as the image map".format(auxfi... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _refit_islands(self, group, stage, outerclip=None, istart=0):
"""
Do island refitting (priorized fitting) on a group of islands.
Parameters
----------
group : list
A list of components grouped by island.
stage : int
Refitting stage.
... | Write a Python 3 function that can
refit islands on a group of components. | As a Python code composer, you craft elegant and concise scripts. |
This function is called by the island fit method. It is called by the island fit method. | Can you tell what is the following Python 3 function doing
def _fit_island(self, island_data):
global_data = self.global_data
# global data
dcurve = global_data.dcurve
rmsimg = global_data.rmsimg
# island data
isle_num = island_data.isle_num
idata = island_data.... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 :... | Write a Python 3 script for
executing fitting on a list of islands and return a list of sources. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function will find sources in an image. | Given the following Python 3 function, write the documentation
def find_sources_in_image(self, filename, hdu_index=0, outfile=None, rms=None, bkg=None, max_summits=None, innerclip=5,
outerclip=4, cores=None, rmsin=None, bkgin=None, beam=None, doislandflux=False,
... | As a python code expert, you are capable of creating scripts from specifications. |
def priorized_fit_islands(self, filename, catalogue, hdu_index=0, outfile=None, bkgin=None, rmsin=None, cores=1,
rms=None, bkg=None, beam=None, lat=None, imgpsf=None, catpsf=None, stage=3, ratio=None, outerclip=3,
doregroup=True, docov=True, cube_index=None):
... | Write a Python 3 function for
taking an input catalog, and image, and optional background/noise images fit the flux and ra/dec for each of the given sources, keeping the morphology fixed if doregroup is true the groups will be recreated based on a matching radius/probability. if doregroup is false then the islands of t... | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks if a list of files are of a recognizable output type. | Can you generate the documentation for the following Python 3 function
def check_table_formats(files):
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
l... | As a python code expert, you are capable of creating scripts from specifications. |
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",
... | Create a Python 3 function for
printing a list of all the file formats that are supported for writing. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Modify the metadata dictionary. | Make a summary of the following Python 3 code
def update_meta_data(meta=None):
if meta is None:
meta = {}
if 'DATE' not in meta:
meta['DATE'] = strftime("%Y-%m-%d %H:%M:%S", gmtime())
if 'PROGRAM' not in meta:
meta['PROGRAM'] = "AegeanTools.catalogs"
meta['PROGVER'] = "{0}-({... | As a Python code analyst, you investigate and solve complex coding mysteries |
Save a catalogue of sources using filename as a model. | Can you generate a brief explanation for the following Python 3 code
def save_catalog(filename, catalog, meta=None, prefix=None):
ascii_table_formats = {'csv': 'csv', 'tab': 'tab', 'tex': 'latex', 'html': 'html'}
# .ann and .reg are handled by me
meta = update_meta_data(meta)
extension = os.path.splitex... | As a Python code analyst, you investigate and solve complex coding mysteries |
def load_catalog(filename):
"""
Load a catalogue and extract the source positions (only)
Parameters
----------
filename : str
Filename to read. Supported types are csv, tab, tex, vo, vot, and xml.
Returns
-------
catalogue : list
A list of [ (ra, dec), ...]
"""
... | Can you write a function in Python 3 where it
loads a catalogue and extract the source positions | As a python code expert, you are capable of creating scripts from specifications. |
Load a table from a given file. | Can you tell what is the following Python 3 function doing
def load_table(filename):
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 ... | As a Python code analyst, you investigate and solve complex coding mysteries |
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(file... | Create a Python 3 function for
writing a table to a file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert a table of data into a list of sources. | Given the following Python 3 function, write the documentation
def table_to_source_list(table, src_type=OutputSource):
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 sour... | As a Python code analyst, you investigate and solve complex coding mysteries |
Writes a list of sources to a file with format determined by extension. | Here you have a function in Python 3, explain what it does
def write_catalog(filename, catalog, fmt=None, meta=None, prefix=None):
if meta is None:
meta = {}
if prefix is None:
pre=''
else:
pre = prefix + '_'
def writer(filename, catalog, fmt=None):
"""
construc... | You are a Python code analyst, evaluating scripts for potential improvements. |
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 ... | Write a Python 3 script to
convert a table into a FITSTable and then write to disk. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Writes an output file in ds9. reg format that outlines the boundaries of each island. | Make a summary of the following Python 3 code
def writeIslandContours(filename, catalog, fmt='reg'):
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=ou... | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.