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 gaussfill(dem, size=3, newmask=None): """Gaussian filter with filling """
smooth = gauss_fltr_astropy(dem, size=size) smooth[~dem.mask] = dem[~dem.mask] if newmask is not None: smooth = np.ma.array(smooth, mask=newmask) return smooth
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def median_fltr(dem, fsize=7, origmask=False): """Scipy.ndimage median filter Does not properly handle NaN """
print("Applying median filter with size %s" % fsize) from scipy.ndimage.filters import median_filter dem_filt_med = median_filter(dem.filled(np.nan), fsize) #Now mask all nans out = np.ma.fix_invalid(dem_filt_med, copy=False, fill_value=dem.fill_value) if origmask: out = np.ma.array(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 median_fltr_opencv(dem, size=3, iterations=1): """OpenCV median filter """
import cv2 dem = malib.checkma(dem) if size > 5: print("Need to implement iteration") n = 0 out = dem while n <= iterations: dem_cv = cv2.medianBlur(out.astype(np.float32).filled(np.nan), size) out = np.ma.fix_invalid(dem_cv) out.set_fill_value(dem.fill_value) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circular_mask(size): """Create a circular mask for an array Useful when sampling rasters for a laser shot """
r = size/2 c = (r,r) y,x = np.ogrid[-c[0]:size-c[0], -c[1]:size-c[1]] mask = ~(x*x + y*y <= r*r) return mask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def median_fltr_skimage(dem, radius=3, erode=1, origmask=False): """ Older skimage.filter.median_filter This smooths, removes noise and fills in nodata areas wit...
#Note, ndimage doesn't properly handle ma - convert to nan dem = malib.checkma(dem) dem = dem.astype(np.float64) #Mask islands if erode > 0: print("Eroding islands smaller than %s pixels" % (erode * 2)) dem = malib.mask_islands(dem, iterations=erode) print("Applying median filt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dz_fltr(dem_fn, refdem_fn, perc=None, rangelim=(0,30), smooth=False): """Absolute elevation difference range filter using values from a source raster file an...
try: open(refdem_fn) except IOError: sys.exit('Unable to open reference DEM: %s' % refdem_fn) from pygeotools.lib import warplib dem_ds, refdem_ds = warplib.memwarp_multi_fn([dem_fn, refdem_fn], res='first', extent='first', t_srs='first') dem = iolib.ds_getma(dem_ds) refdem = i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dz_fltr_ma(dem, refdem, perc=None, rangelim=(0,30), smooth=False): """Absolute elevation difference range filter using values from a source array and a refer...
if smooth: refdem = gauss_fltr_astropy(refdem) dem = gauss_fltr_astropy(dem) dz = refdem - dem #This is True for invalid values in DEM, and should be masked demmask = np.ma.getmaskarray(dem) if perc: dz_perc = malib.calcperc(dz, perc) print("Applying dz percentile...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erode_edge(dem, iterations=1): """Erode pixels near nodata """
import scipy.ndimage as ndimage print('Eroding pixels near nodata: %i iterations' % iterations) mask = np.ma.getmaskarray(dem) mask_dilate = ndimage.morphology.binary_dilation(mask, iterations=iterations) out = np.ma.array(dem, mask=mask_dilate) return 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 butter(dt_list, val, lowpass=1.0): """This is framework for a butterworth bandpass for 1D data Needs to be cleaned up and generalized """
import scipy.signal import matplotlib.pyplot as plt #dt is 300 s, 5 min dt_diff = np.diff(dt_list) dt_diff = np.array([dt.total_seconds() for dt in dt_diff]) dt = malib.fast_median(dt_diff) #f is 0.00333 Hz #288 samples/day fs = 1./dt nyq = fs/2. if False: #psd, f =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freq_filt(bma): """ This is a framework for 2D FFT filtering. It has not be tested or finished - might be a dead end See separate utility freq_analysis.py ""...
""" Want to fit linear function to artifact line in freq space, Then mask everything near that line at distances of ~5-200 pixels, Or whatever the maximum CCD artifact dimension happens to be, This will depend on scaling - consult CCD map for interval """ #Fill ndv with random data 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 stack_smooth(s_orig, size=7, save=False): """Run Gaussian smoothing filter on exising stack object """
from copy import deepcopy from pygeotools.lib import filtlib print("Copying original DEMStack") s = deepcopy(s_orig) s.stack_fn = os.path.splitext(s_orig.stack_fn)[0]+'_smooth%ipx.npz' % size #Loop through each array and smooth print("Smoothing all arrays in stack with %i px gaussian filte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack_clip(s_orig, extent, out_stack_fn=None, copy=True, save=False): """Create a new stack object with limited extent from an exising stack object """
#Should check for valid extent #This is not memory efficient, but is much simpler #To be safe, if we are saving out, create a copy to avoid overwriting if copy or save: from copy import deepcopy print("Copying original DEMStack") s = deepcopy(s_orig) else: #Want to ...
<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_stack_subset(s_orig, idx, out_stack_fn=None, copy=True, save=False): """Create a new stack object as a subset of an exising stack object """
#This must be a numpy boolean array idx = np.array(idx) if np.any(idx): #This is not memory efficient, but is much simpler #To be safe, if we are saving out, create a copy to avoid overwriting if copy or save: from copy import deepcopy print("Copying original...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack_merge(s1, s2, out_stack_fn=None, sort=True, save=False): """Merge two stack objects """
from pygeotools.lib import geolib from copy import deepcopy #Assumes input stacks have identical extent, resolution, and projection if s1.ma_stack.shape[1:3] != s2.ma_stack.shape[1:3]: print(s1.ma_stack.shape) print(s2.ma_stack.shape) sys.exit('Input stacks must have identical 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 randomfill(a): """Fill masked areas with random noise This is needed for any fft-based operations """
a = checkma(a) #For data that have already been normalized, #This provides a proper normal distribution with mean=0 and std=1 #a = (a - a.mean()) / a.std() #noise = a.mask * (np.random.randn(*a.shape)) noise = a.mask * np.random.normal(a.mean(), a.std(), a.shape) #Add the noise b = a.fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nanfill(a, f_a, *args, **kwargs): """Fill masked areas with np.nan Wrapper for functions that can't handle ma (e.g. scipy.ndimage) This will force filters to...
a = checkma(a) ndv = a.fill_value #Note: The following fails for arrays that are not float (np.nan is float) b = f_a(a.filled(np.nan), *args, **kwargs) #the fix_invalid fill_value parameter doesn't seem to work out = np.ma.fix_invalid(b, copy=False) out.set_fill_value(ndv) return 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 fast_median(a): """Fast median operation for masked array using 50th-percentile """
a = checkma(a) #return scoreatpercentile(a.compressed(), 50) if a.count() > 0: out = np.percentile(a.compressed(), 50) else: out = np.ma.masked return 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 mad(a, axis=None, c=1.4826, return_med=False): """Compute normalized median absolute difference Can also return median array, as this can be expensive, and o...
a = checkma(a) #return np.ma.median(np.fabs(a - np.ma.median(a))) / c if a.count() > 0: if axis is None: med = fast_median(a) out = fast_median(np.fabs(a - med)) * c else: med = np.ma.median(a, axis=axis) #This is necessary for broadcasting ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calcperc(b, perc=(0.1,99.9)): """Calculate values at specified percentiles """
b = checkma(b) if b.count() > 0: #low = scoreatpercentile(b.compressed(), perc[0]) #high = scoreatpercentile(b.compressed(), perc[1]) low = np.percentile(b.compressed(), perc[0]) high = np.percentile(b.compressed(), perc[1]) else: low = 0 high = 0 #low =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calcperc_sym(b, perc=(0.1,99.9)): """ Get symmetrical percentile values Useful for determining clim centered on 0 for difference maps """
clim = np.max(np.abs(calcperc(b, perc))) #clim = (-clim, clim) return -clim, clim
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iqr(b, perc=(25, 75)): """Inter-quartile range """
b = checkma(b) low, high = calcperc(b, perc) return low, high, high - low
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iv(b, **kwargs): """Quick access to imview for interactive sessions """
import matplotlib.pyplot as plt import imview.imviewer as imview b = checkma(b) #if hasattr(kwargs,'imshow_kwargs'): # kwargs['imshow_kwargs']['interpolation'] = 'bicubic' #else: # kwargs['imshow_kwargs'] = {'interpolation': 'bicubic'} #bma_fig(fig, bma, cmap='gist_rainbow_r', cl...
<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_shape(shape): ''' Normalize numpy array shapes so they're always expressed as a tuple, even for one-dimensional shapes. Parameters shape - an int, or a tuple of ints Returns a shape tuple ''' try: i = int(shape) return (i,) except Type...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def localortho(lon, lat): """Create srs for local orthographic projection centered at lat, lon """
local_srs = osr.SpatialReference() local_proj = '+proj=ortho +lat_0=%0.7f +lon_0=%0.7f +datum=WGS84 +units=m +no_defs ' % (lat, lon) local_srs.ImportFromProj4(local_proj) return local_srs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geom2localortho(geom): """Convert existing geom to local orthographic projection Useful for local cartesian distance/area calculations """
cx, cy = geom.Centroid().GetPoint_2D() lon, lat, z = cT_helper(cx, cy, 0, geom.GetSpatialReference(), wgs_srs) local_srs = localortho(lon,lat) local_geom = geom_dup(geom) geom_transform(local_geom, local_srs) return local_geom
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dd2dms(dd): """Convert decimal degrees to degrees, minutes, seconds """
n = dd < 0 dd = abs(dd) m,s = divmod(dd*3600,60) d,m = divmod(m,60) if n: d = -d return 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 dms2dd(d,m,s): """Convert degrees, minutes, seconds to decimal degrees """
if d < 0: sign = -1 else: sign = 1 dd = sign * (int(abs(d)) + float(m) / 60 + float(s) / 3600) return dd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dd2dm(dd): """Convert decimal to degrees, decimal minutes """
d,m,s = dd2dms(dd) m = m + float(s)/3600 return 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 mapToPixel(mX, mY, geoTransform): """Convert map coordinates to pixel coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - ...
mX = np.asarray(mX) mY = np.asarray(mY) if geoTransform[2] + geoTransform[4] == 0: pX = ((mX - geoTransform[0]) / geoTransform[1]) - 0.5 pY = ((mY - geoTransform[3]) / geoTransform[5]) - 0.5 else: pX, pY = applyGeoTransform(mX, mY, invertGeoTransform(geoTransform)) #return i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pixelToMap(pX, pY, geoTransform): """Convert pixel coordinates to map coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - ...
pX = np.asarray(pX, dtype=float) pY = np.asarray(pY, dtype=float) pX += 0.5 pY += 0.5 mX, mY = applyGeoTransform(pX, pY, geoTransform) return mX, mY
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mem_ds(res, extent, srs=None, dtype=gdal.GDT_Float32): """Create a new GDAL Dataset in memory Useful for various applications that require a Dataset """
#These round down to int #dst_ns = int((extent[2] - extent[0])/res) #dst_nl = int((extent[3] - extent[1])/res) #This should pad by 1 pixel, but not if extent and res were calculated together to give whole int dst_ns = int((extent[2] - extent[0])/res + 0.99) dst_nl = int((extent[3] - extent[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 copyproj(src_fn, dst_fn, gt=True): """Copy projection and geotransform from one raster file to another """
src_ds = gdal.Open(src_fn, gdal.GA_ReadOnly) dst_ds = gdal.Open(dst_fn, gdal.GA_Update) dst_ds.SetProjection(src_ds.GetProjection()) if gt: src_gt = np.array(src_ds.GetGeoTransform()) src_dim = np.array([src_ds.RasterXSize, src_ds.RasterYSize]) dst_dim = np.array([dst_ds.RasterX...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geom_transform(geom, t_srs): """Transform a geometry in place """
s_srs = geom.GetSpatialReference() if not s_srs.IsSame(t_srs): ct = osr.CoordinateTransformation(s_srs, t_srs) geom.Transform(ct) geom.AssignSpatialReference(t_srs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shp_dict(shp_fn, fields=None, geom=True): """Get a dictionary for all features in a shapefile Optionally, specify fields """
from pygeotools.lib import timelib ds = ogr.Open(shp_fn) lyr = ds.GetLayer() nfeat = lyr.GetFeatureCount() print('%i input features\n' % nfeat) if fields is None: fields = shp_fieldnames(lyr) d_list = [] for n,feat in enumerate(lyr): d = {} if geom: g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lyr_proj(lyr, t_srs, preserve_fields=True): """Reproject an OGR layer """
#Need to check t_srs s_srs = lyr.GetSpatialRef() cT = osr.CoordinateTransformation(s_srs, t_srs) #Do everything in memory drv = ogr.GetDriverByName('Memory') #Might want to save clipped, warped shp to disk? # create the output layer #drv = ogr.GetDriverByName('ESRI Shapefile') #ou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raster_shpclip(r_fn, shp_fn, extent='raster', bbox=False, pad=None, invert=False, verbose=False): """Clip an input raster by input polygon shapefile for give...
from pygeotools.lib import iolib from pygeotools.lib import warplib r_ds = iolib.fn_getds(r_fn) r_srs = get_ds_srs(r_ds) r_extent = ds_extent(r_ds) r_extent_geom = bbox2geom(r_extent) #NOTE: want to add spatial filter here to avoid reprojeting global RGI polygons, for example shp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geom2shp(geom, out_fn, fields=False): """Write out a new shapefile for input geometry """
from pygeotools.lib import timelib driverName = "ESRI Shapefile" drv = ogr.GetDriverByName(driverName) if os.path.exists(out_fn): drv.DeleteDataSource(out_fn) out_ds = drv.CreateDataSource(out_fn) out_lyrname = os.path.splitext(os.path.split(out_fn)[1])[0] geom_srs = geom.GetSpatial...
<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_outline(ds, t_srs=None, scale=1.0, simplify=False, convex=False): """Generate outline of unmasked values in input raster get_outline is an attempt to rep...
gt = np.array(ds.GetGeoTransform()) from pygeotools.lib import iolib a = iolib.ds_getma_sub(ds, scale=scale) #Create empty geometry geom = ogr.Geometry(ogr.wkbPolygon) #Check to make sure we have unmasked data if a.count() != 0: #Scale the gt for reduced resolution #The UL 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 ds_cT(ds, x, y, xy_srs=wgs_srs): """Convert input point coordinates to map coordinates that match input dataset """
#Convert lat/lon to projected srs ds_srs = get_ds_srs(ds) #If xy_srs is undefined, assume it is the same as ds_srs mX = x mY = y if xy_srs is not None: if not ds_srs.IsSame(xy_srs): mX, mY, mZ = cT_helper(x, y, 0, xy_srs, ds_srs) return mX, mY
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def line2pts(geom, dl=None): """Given an input line geom, generate points at fixed interval Useful for extracting profile data from raster """
#Extract list of (x,y) tuples at nodes nodes = geom.GetPoints() #print "%i nodes" % len(nodes) #Point spacing in map units if dl is None: nsteps=1000 dl = geom.Length()/nsteps #This only works for equidistant projection! #l = np.arange(0, geom.Length(), dl) #Initia...
<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_res_stats(ds_list, t_srs=None): """Return resolution stats for an input dataset list """
if t_srs is None: t_srs = get_ds_srs(ds_list[0]) res = np.array([get_res(ds, t_srs=t_srs) for ds in ds_list]) #Check that all projections are identical #gt_array = np.array([ds.GetGeoTransform() for ds in args]) #xres = gt_array[:,1] #yres = -gt_array[:,5] #if xres == yres: #re...
<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_res(ds, t_srs=None, square=False): """Get GDAL Dataset raster resolution """
gt = ds.GetGeoTransform() ds_srs = get_ds_srs(ds) #This is Xres, Yres res = [gt[1], np.abs(gt[5])] if square: res = [np.mean(res), np.mean(res)] if t_srs is not None and not ds_srs.IsSame(t_srs): if True: #This diagonal approach is similar to the approach in gdaltran...
<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_center(ds, t_srs=None): """Get center coordinates of GDAL Dataset """
gt = ds.GetGeoTransform() ds_srs = get_ds_srs(ds) #Note: this is center of center pixel, not ul corner of center pixel center = [gt[0] + (gt[1] * ds.RasterXSize/2.0), gt[3] + (gt[5] * ds.RasterYSize/2.0)] #include t_srs.Validate() and t_srs.Fixup() if t_srs is not None and not ds_srs.IsSame(t_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 get_ds_srs(ds): """Get srs object for GDAL Datset """
ds_srs = osr.SpatialReference() ds_srs.ImportFromWkt(ds.GetProjectionRef()) return ds_srs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def srs_check(ds): """Check validitiy of Dataset srs Return True if srs is properly defined """
# ds_srs = get_ds_srs(ds) gt = np.array(ds.GetGeoTransform()) gt_check = ~np.all(gt == np.array((0.0, 1.0, 0.0, 0.0, 0.0, 1.0))) proj_check = (ds.GetProjection() != '') #proj_check = ds_srs.IsProjected() out = False if gt_check and proj_check: out = True return 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 ds_IsEmpty(ds): """Check to see if dataset is empty after warp """
out = False b = ds.GetRasterBand(1) #Looks like this throws: #ERROR 1: Failed to compute min/max, no valid pixels found in sampling. #Should just catch this rater than bothering with logic below try: mm = b.ComputeRasterMinMax() if (mm[0] == mm[1]): ndv = b.GetNoDa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gt_corners(gt, nx, ny): """Get corner coordinates based on input geotransform and raster dimensions """
ul = [gt[0], gt[3]] ll = [gt[0], gt[3] + (gt[5] * ny)] ur = [gt[0] + (gt[1] * nx), gt[3]] lr = [gt[0] + (gt[1] * nx), gt[3] + (gt[5] * ny)] return ul, ll, ur, lr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ds_geom(ds, t_srs=None): """Return dataset bbox envelope as geom """
gt = ds.GetGeoTransform() ds_srs = get_ds_srs(ds) if t_srs is None: t_srs = ds_srs ns = ds.RasterXSize nl = ds.RasterYSize x = np.array([0, ns, ns, 0, 0], dtype=float) y = np.array([0, 0, nl, nl, 0], dtype=float) #Note: pixelToMap adds 0.5 to input coords, need to account for th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geom_wh(geom): """Compute width and height of geometry in projected units """
e = geom.GetEnvelope() h = e[1] - e[0] w = e[3] - e[2] return w, h
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gdaldem_mem_ma(ma, ds=None, res=None, extent=None, srs=None, processing='hillshade', returnma=False, computeEdges=False): """ Wrapper to allow gdaldem calcul...
if ds is None: ds = mem_ds(res, extent, srs=None, dtype=gdal.GDT_Float32) else: ds = mem_ds_copy(ds) b = ds.GetRasterBand(1) b.WriteArray(ma) out = gdaldem_mem_ds(ds, processing=processing, returnma=returnma) return 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 get_xy_ma(bma, gt, stride=1, origmask=True, newmask=None): """Return arrays of x and y map coordinates for input array and geotransform """
pX = np.arange(0, bma.shape[1], stride) pY = np.arange(0, bma.shape[0], stride) psamp = np.meshgrid(pX, pY) #if origmask: # psamp = np.ma.array(psamp, mask=np.ma.getmaskarray(bma), fill_value=0) mX, mY = pixelToMap(psamp[0], psamp[1], gt) mask = None if origmask: mask = np.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 get_xy_1D(ds, stride=1, getval=False): """Return 1D arrays of x and y map coordinates for input GDAL Dataset """
gt = ds.GetGeoTransform() #stride = stride_m/gt[1] pX = np.arange(0, ds.RasterXSize, stride) pY = np.arange(0, ds.RasterYSize, stride) mX, dummy = pixelToMap(pX, pY[0], gt) dummy, mY = pixelToMap(pX[0], pY, gt) return mX, mY
<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_xy_grids(ds, stride=1, getval=False): """Return 2D arrays of x and y map coordinates for input GDAL Dataset """
gt = ds.GetGeoTransform() #stride = stride_m/gt[1] pX = np.arange(0, ds.RasterXSize, stride) pY = np.arange(0, ds.RasterYSize, stride) psamp = np.meshgrid(pX, pY) mX, mY = pixelToMap(psamp[0], psamp[1], gt) return mX, mY
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitPlaneSVD(XYZ): """Fit a plane to input point data using SVD """
[rows,cols] = XYZ.shape # Set up constraint equations of the form AB = 0, # where B is a column vector of the plane coefficients # in the form b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0. p = (np.ones((rows,1))) AB = np.hstack([XYZ,p]) [u, d, v] = np.linalg.svd(AB,0) # Solution is last ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitPlaneLSQ(XYZ): """Fit a plane to input point data using LSQ """
[rows,cols] = XYZ.shape G = np.ones((rows,3)) G[:,0] = XYZ[:,0] #X G[:,1] = XYZ[:,1] #Y Z = XYZ[:,2] coeff,resid,rank,s = np.linalg.lstsq(G,Z,rcond=None) return coeff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ds_fitplane(ds): """Fit a plane to values in GDAL Dataset """
from pygeotools.lib import iolib bma = iolib.ds_getma(ds) gt = ds.GetGeoTransform() return ma_fitplane(bma, gt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getUTMzone(geom): """Determine UTM Zone for input geometry """
#If geom has srs properly defined, can do this #geom.TransformTo(wgs_srs) #Get centroid lat/lon lon, lat = geom.Centroid().GetPoint_2D() #Make sure we're -180 to 180 lon180 = (lon+180) - np.floor((lon+180)/360)*360 - 180 zonenum = int(np.floor((lon180 + 180)/6) + 1) #Determine N/S hemis...
<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_proj(geom, proj_list=None): """Determine best projection for input geometry """
out_srs = None if proj_list is None: proj_list = gen_proj_list() #Go through user-defined projeciton list for projbox in proj_list: if projbox.geom.Intersects(geom): out_srs = projbox.srs break #If geom doesn't fall in any of the user projection bbox, use UTM...
<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_proj_list(): """Create list of projections with cascading preference """
#Eventually, just read this in from a text file proj_list = [] #Alaska #Note, this spans -180/180 proj_list.append(ProjBox([-180, -130, 51.35, 71.35], 3338)) #proj_list.append(ProjBox([-130, 172.4, 51.35, 71.35], 3338)) #Transantarctic Mountains proj_list.append(ProjBox([150, 175, -80, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xy2geom(x, y, t_srs=None): """Convert x and y point coordinates to geom """
geom_wkt = 'POINT({0} {1})'.format(x, y) geom = ogr.CreateGeometryFromWkt(geom_wkt) if t_srs is not None and not wgs_srs.IsSame(t_srs): ct = osr.CoordinateTransformation(t_srs, wgs_srs) geom.Transform(ct) geom.AssignSpatialReference(t_srs) return geom
<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_dem_mosaic_cmd(fn_list, o, fn_list_txt=None, tr=None, t_srs=None, t_projwin=None, georef_tile_size=None, threads=None, tile=None, stat=None): """ Create ...
cmd = ['dem_mosaic',] if o is None: o = 'mos' cmd.extend(['-o', o]) if threads is None: from pygeotools.lib import iolib threads = iolib.cpu_count() cmd.extend(['--threads', threads]) if tr is not None: cmd.extend(['--tr', tr]) if t_srs is not None: #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_rs_alg(r): """Parse resampling algorithm """
#Note:GRA_CubicSpline created huge block artifacts for the St. Helen's compute_dh WV cases #Stick with CubicSpline for both upsampling/downsampling for now if r == 'near': #Note: Nearest respects nodata when downsampling gra = gdal.GRA_NearestNeighbour elif r == 'bilinear': gra ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_srs(t_srs, src_ds_list=None): """Parse arbitrary input t_srs Parameters t_srs : str or gdal.Dataset or filename Arbitrary input t_srs src_ds_list : lis...
if t_srs is None and src_ds_list is None: print("Input t_srs and src_ds_list are both None") else: if t_srs is None: t_srs = 'first' if t_srs == 'first' and src_ds_list is not None: t_srs = geolib.get_ds_srs(src_ds_list[0]) elif t_srs == 'last' and src_ds...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_res(res, src_ds_list=None, t_srs=None): """Parse arbitrary input res Parameters res : str or gdal.Dataset or filename or float Arbitrary input res src_...
#Default to using first t_srs for res calculations #Assumes src_ds_list is not None t_srs = parse_srs(t_srs, src_ds_list) #Valid options for res res_str_list = ['first', 'last', 'min', 'max', 'mean', 'med', 'common_scale_factor'] #Compute output resolution in t_srs if res in res_str_list ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_extent(extent, src_ds_list=None, t_srs=None): """Parse arbitrary input extent Parameters extent : str or gdal.Dataset or filename or list of float Arbi...
#Default to using first t_srs for extent calculations if t_srs is not None: t_srs = parse_srs(t_srs, src_ds_list) #Valid strings extent_str_list = ['first', 'last', 'intersection', 'union'] if extent in extent_str_list and src_ds_list is not None: if len(src_ds_list) == 1 and (ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0): """Helper function for memwarp of multiple...
return warp_multi(src_ds_list, res, extent, t_srs, r, warptype=memwarp, verbose=verbose, dst_ndv=dst_ndv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0): """Helper function for memwarp of multi...
#Should implement proper error handling here if not iolib.fn_list_check(src_fn_list): sys.exit('Missing input file(s)') src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list] return memwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, dst_ndv=dst_ndv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diskwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None): """Helper function for di...
return warp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, warptype=diskwarp, outdir=outdir, dst_ndv=dst_ndv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diskwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None): """Helper function for...
#Should implement proper error handling here if not iolib.fn_list_check(src_fn_list): sys.exit('Missing input file(s)') src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list] return diskwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, outdir=outdir, dst_ndv=dst_ndv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeout(ds, outfn): """Write ds to disk Note: Depreciated function - use diskwarp functions when writing to disk to avoid unnecessary CreateCopy """
print("Writing out %s" % outfn) #Use outfn extension to get driver #This may have issues if outfn already exists and the mem ds has different dimensions/res out_ds = iolib.gtif_drv.CreateCopy(outfn, ds, 0, options=iolib.gdal_opt) out_ds = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLocalTime(utc_dt, tz): """Return local timezone time """
import pytz local_tz = pytz.timezone(tz) local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) return local_dt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strptime_fuzzy(s): """Fuzzy date string parsing Note: this returns current date if not found. If only year is provided, will return current month, day """
import dateutil.parser dt = dateutil.parser.parse(str(s), fuzzy=True) return dt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fn_getdatetime_list(fn): """Extract all datetime strings from input filename """
#Want to split last component fn = os.path.split(os.path.splitext(fn)[0])[-1] import re #WV01_12JUN152223255-P1BS_R1C1-102001001B3B9800__WV01_12JUN152224050-P1BS_R1C1-102001001C555C00-DEM_4x.tif #Need to parse above with month name #Note: made this more restrictive to avoid false matches: ...
<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_t_factor(t1, t2): """Time difference between two datetimes, expressed as decimal year """
t_factor = None if t1 is not None and t2 is not None and t1 != t2: dt = t2 - t1 year = timedelta(days=365.25) t_factor = abs(dt.total_seconds() / year.total_seconds()) return t_factor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_fn_list(fn_list): """Sort input filename list by datetime """
dt_list = get_dt_list(fn_list) fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))] return fn_list_sort
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_repeat_dt(dt_list, offset_s=0.001): """Add some small offset to remove duplicate times Needed for xarray interp, which expects monotonically increasing t...
idx = (np.diff(dt_list) == timedelta(0)) while np.any(idx): dt_list[idx.nonzero()[0] + 1] += timedelta(seconds=offset_s) idx = (np.diff(dt_list) == timedelta(0)) return dt_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dt_list(fn_list): """Get list of datetime objects, extracted from a filename """
dt_list = np.array([fn_getdatetime(fn) for fn in fn_list]) return dt_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_closest_dt_idx(dt, dt_list): """Get indices of dt_list that is closest to input dt """
from pygeotools.lib import malib dt_list = malib.checkma(dt_list, fix=False) dt_diff = np.abs(dt - dt_list) return dt_diff.argmin()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean_date(dt_list): """Calcuate mean datetime from datetime list """
dt_list_sort = sorted(dt_list) dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort] avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel) return dt_list_sort[0] + avg_timedelta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def median_date(dt_list): """Calcuate median datetime from datetime list """
#dt_list_sort = sorted(dt_list) idx = len(dt_list)/2 if len(dt_list) % 2 == 0: md = mean_date([dt_list[idx-1], dt_list[idx]]) else: md = dt_list[idx] return md
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dt_cluster(dt_list, dt_thresh=16.0): """Find clusters of similar datetimes within datetime list """
if not isinstance(dt_list[0], float): o_list = dt2o(dt_list) else: o_list = dt_list o_list_sort = np.sort(o_list) o_list_sort_idx = np.argsort(o_list) d = np.diff(o_list_sort) #These are indices of breaks #Add one so each b starts a cluster b = np.nonzero(d > dt_thresh)[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dt2decyear(dt): """Convert datetime to decimal year """
year = dt.year startOfThisYear = datetime(year=year, month=1, day=1) startOfNextYear = datetime(year=year+1, month=1, day=1) yearElapsed = sinceEpoch(dt) - sinceEpoch(startOfThisYear) yearDuration = sinceEpoch(startOfNextYear) - sinceEpoch(startOfThisYear) fraction = yearElapsed/yearDuration ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decyear2dt(t): """Convert decimal year to datetime """
year = int(t) rem = t - year base = datetime(year, 1, 1) dt = base + timedelta(seconds=(base.replace(year=base.year+1) - base).total_seconds() * rem) #This works for np array input #year = t.astype(int) #rem = t - year #base = np.array([datetime(y, 1, 1) for y in year]) return dt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dt2jd(dt): """Convert datetime to julian date """
a = (14 - dt.month)//12 y = dt.year + 4800 - a m = dt.month + 12*a - 3 return dt.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jd2dt(jd): """Convert julian date to datetime """
n = int(round(float(jd))) a = n + 32044 b = (4*a + 3)//146097 c = a - (146097*b)//4 d = (4*c + 3)//1461 e = c - (1461*d)//4 m = (5*e + 2)//153 day = e + 1 - (153*m + 2)//5 month = m + 3 - 12*(m//10) year = 100*b + d - 4800 + m/10 tfrac = 0.5 + float(jd) - n tfrac_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 gps2dt(gps_week, gps_ms): """Convert GPS week and ms to a datetime """
gps_epoch = datetime(1980,1,6,0,0,0) gps_week_s = timedelta(seconds=gps_week*7*24*60*60) gps_ms_s = timedelta(milliseconds=gps_ms) return gps_epoch + gps_week_s + gps_ms_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 disco_loop(opc, version, queue, real_out, dup_lines=False, show_bytes=False): """Disassembles a queue of code objects. If we discover another code object whi...
while len(queue) > 0: co = queue.popleft() if co.co_name not in ('<module>', '?'): real_out.write("\n" + format_code_info(co, version) + "\n") bytecode = Bytecode(co, opc, dup_lines=dup_lines) real_out.write(bytecode.dis(show_bytes=show_bytes) + "\n") for c in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disco_loop_asm_format(opc, version, co, real_out, fn_name_map, all_fns): """Produces disassembly in a format more conducive to automatic assembly by producin...
if version < 3.0: co = code2compat(co) else: co = code3compat(co) co_name = co.co_name mapped_name = fn_name_map.get(co_name, co_name) new_consts = [] for c in co.co_consts: if iscode(c): if version < 3.0: c_compat = code2compat(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 wr_long(f, x): """Internal; write a 32-bit int to a file in little-endian order."""
if PYTHON3: f.write(bytes([x & 0xff])) f.write(bytes([(x >> 8) & 0xff])) f.write(bytes([(x >> 16) & 0xff])) f.write(bytes([(x >> 24) & 0xff])) else: f.write(chr( x & 0xff)) f.write(chr((x >> 8) & 0xff)) f.write(chr((x >> 16) & 0xff)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_compile(codeobject, filename, timestamp, magic): """Write code object as a byte-compiled file Arguments: codeobject: code object filefile: bytecode file...
# Atomically write the pyc/pyo file. Issue #13146. # id() is used to generate a pseudo-random filename. path_tmp = '%s.%s' % (filename, id(filename)) fc = None try: fc = open(path_tmp, 'wb') if PYTHON3: fc.write(bytes([0, 0, 0, 0])) else: fc.write('\...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int2magic(magic_int): """Given a magic int like 62211, compute the corresponding magic byte string b'\x03\xf3\r\n' using the conversion method that does this...
if (sys.version_info >= (3, 0)): return struct.pack('<Hcc', magic_int, bytes('\r', 'utf-8'), bytes('\n', 'utf-8')) else: return struct.pack('<Hcc', magic_int, '\r', '\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 sysinfo2float(version_info=sys.version_info): """Convert a sys.versions_info-compatible list into a 'canonic' floating-point number which that can then be us...
vers_str = '.'.join([str(v) for v in version_info[0:3]]) if version_info[3] != 'final': vers_str += '.' + ''.join([str(i) for i in version_info[3:]]) if IS_PYPY: vers_str += 'pypy' else: try: import platform platform = platform.python_implementation() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sysinfo2magic(version_info=sys.version_info): """Convert a list sys.versions_info compatible list into a 'canonic' floating-point number which that can then ...
# FIXME: DRY with sysinfo2float() vers_str = '.'.join([str(v) for v in version_info[0:3]]) if version_info[3] != 'final': vers_str += ''.join([str(v) for v in version_info[3:]]) if IS_PYPY: vers_str += 'pypy' else: try: import platform platform = pl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_opdata(l, from_mod, version=None, is_pypy=False): """Sets up a number of the structures found in Python's opcode.py. Python opcode.py routines assign at...
if version: l['python_version'] = version l['is_pypy'] = is_pypy l['cmp_op'] = cmp_op l['HAVE_ARGUMENT'] = HAVE_ARGUMENT if version <= 3.5: l['findlinestarts'] = findlinestarts l['findlabels'] = findlabels l['get_jump_targets'] = get_jump_targets l['get_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rm_op(l, name, op): """Remove an opcode. This is used when basing a new Python release off of another one, and there is an opcode that is in the old release ...
# opname is an array, so we need to keep the position in there. l['opname'][op] = '<%s>' % op if op in l['hasconst']: l['hasconst'].remove(op) if op in l['hascompare']: l['hascompare'].remove(op) if op in l['hascondition']: l['hascondition'].remove(op) if op in l['hasfree...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def opcode_check(l): """When the version of Python we are running happens to have the same opcode set as the opcode we are importing, we perform checks to make s...
# Python 2.6 reports 2.6000000000000001 if (abs(PYTHON_VERSION - l['python_version']) <= 0.01 and IS_PYPY == l['is_pypy']): try: import dis opmap = fix_opcode_names(dis.opmap) # print(set(opmap.items()) - set(l['opmap'].items())) # print(set(l['op...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_opcodes(opmap): """Utility for dumping opcodes"""
op2name = {} for k in opmap.keys(): op2name[opmap[k]] = k for i in sorted(op2name.keys()): print("%-3s %s" % (str(i), op2name[i]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pretty_flags(flags): """Return pretty representation of code flags."""
names = [] result = "0x%08x" % flags for i in range(32): flag = 1 << i if flags & flag: names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag))) flags ^= flag if not flags: break else: names.append(hex(flags)) names.reverse()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _try_compile(source, name): """Attempts to compile the given source, first as an expression and then as a statement if the first approach fails. Utility func...
try: c = compile(source, name, 'eval') except SyntaxError: c = compile(source, name, 'exec') 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 get_code_object(x): """Helper to handle methods, functions, generators, strings and raw code objects"""
if hasattr(x, '__func__'): # Method x = x.__func__ if hasattr(x, '__code__'): # Function x = x.__code__ if hasattr(x, 'gi_code'): # Generator x = x.gi_code if isinstance(x, str): # Source code x = _try_compile(x, "<disassembly>") if hasattr(x, 'co_code'): # Cod...