def checkOverwrite(path): if not os.path.exists(path): return if os.path.isfile(path): err.error( "Failed to create the output file:\n\n" " " + str(path) + "\n\n" "The file already exists. You can do one of the following:\n\n" "1) Enable automatic overwrite in the GUI or parameter file\n" "2) Change base name and/or output directory in the GUI or\n" " parameter file\n" "3) Delete or rename the existing file", fatal=True, frame=True) elif os.path.isdir(path) and os.listdir(path): err.error( "Failed to create the output directory:\n\n" " " + str(path) + "\n\n" "The directory already exists and is not empty. You can do one\n" "of the following:\n\n" "1) Enable automatic overwrite in the GUI or parameter file\n" "2) Change base name and/or output directory in the GUI or\n" " parameter file\n" "3) Delete or rename the existing directory", fatal=True, frame=True) return
def apply_weights_file(data, weightsFile, subcube): # Load weights cube err.message("Applying weights cube:\n " + str(weightsFile)) try: f = fits.open(weightsFile, memmap=False) header_weights = f[0].header except: err.error("Failed to read weights cube.") # Extract axis sizes and types n_axes_weights, axis_size_weights, axis_type_weights = extract_axis_size(header_weights) # Ensure correct dimensionality check_cube_dimensions(n_axes_weights, axis_size_weights, cube_name="weights cube", min_dim=1, max_dim=4) # Multiply data by weights # 1-D spectrum if n_axes_weights == 1: err.warning("Weights cube has 1 axis; interpreted as spectrum.\nAdding first and second axis.") if len(subcube): err.ensure(len(subcube) == 6, "Subcube list must have 6 entries ({0:d} given).".format(len(subcube))) data *= np.reshape(f[0].section[subcube[4]:subcube[5]], (-1, 1, 1)) else: data *= reshape(f[0].data, (-1, 1, 1)) # 2-D image elif n_axes_weights == 2: if len(subcube) == 6 or len(subcube) == 4: data *= np.array([f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]]]) else: data *= np.array([f[0].data]) # 3-D cube elif n_axes_weights == 3: if len(subcube) == 6: data *= f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: data *= f[0].data # 4-D hypercube else: if len(subcube) == 6: data *= f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: data *= f[0].section[0] f.close() err.message(" Weights cube applied.") return data
def writeMask(cube, header, dictionary, filename, compress, flagOverwrite): header.add_history("SoFiA source finding") optionsList = [] optionsDepth = [] dictionary = removeOptions(dictionary) recursion(dictionary, optionsList, optionsDepth) headerList = [] for i in range(0, len(optionsList)): if len(optionsList[i].split("=")) > 1: tmpString = optionsList[i] depthNumber = optionsDepth[i] j = i - 1 while depthNumber > 0: if optionsDepth[i] > optionsDepth[j]: tmpString = optionsList[j] + "." + tmpString depthNumber = optionsDepth[j] j -= 1 headerList.append(tmpString) for option in headerList: header.add_history(option) if cube.max() < 32767: cube = cube.astype("int16") # add axes required to make the shape of the mask cube equal to the shape of the input datacube while header["naxis"] > len(cube.shape): cube.resize(tuple([ 1, ] + list(cube.shape))) hdu = fits.PrimaryHDU(data=cube, header=header) hdu.header["BUNIT"] = "source_ID" hdu.header["DATAMIN"] = cube.min() hdu.header["DATAMAX"] = cube.max() hdu.header["ORIGIN"] = sofia_version_full name = filename if compress: name += ".gz" # Check for overwrite flag: if not flagOverwrite and os.path.exists(name): err.error("Output file exists: " + name + ".", fatal=False) return else: hdu.writeto(name, output_verify="warn", **__astropy_arg_overwrite__) return
def apply_weights_function(data, weightsFunction): err.message("Applying weights function:\n " + str(weightsFunction)) # Define whitelist of allowed character sequences and import relevant Numpy functions whitelist = [ "x", "y", "z", "e", "E", "sin", "cos", "tan", "arcsin", "arccos", "arctan", "arctan2", "sinh", "cosh", "tanh", "arcsinh", "arccosh", "arctanh", "exp", "log", "sqrt", "square", "power", "absolute", "fabs", "sign" ] from numpy import sin, cos, tan, arcsin, arccos, arctan, arctan2, sinh, cosh, tanh, arcsinh, arccosh, arctanh, exp, log, sqrt, square, power, absolute, fabs, sign # Search for all keywords consisting of consecutive sequences of alphabetical characters keywordsFound = filter(None, re.split("[^a-zA-Z]+", str(weightsFunction))) # Check for non-whitelisted sequences for keyword in keywordsFound: err.ensure( keyword in whitelist, "Unknown keyword '" + str(keyword) + "' found in weights function:\n" " " + str(weightsFunction) + "\n" "Please check your input.") # Loop over all channels for i in range(data.shape[0]): # Create index arrays over 2-D planes (i.e. of width dz = 1) z, y, x = np.indices((1, data.shape[1], data.shape[2])) z += i # Multiply each plane by weights function try: data[z, y, x] *= eval(str(weightsFunction)) # NOTE: eval() should be safe now as we don't allow for non-whitelisted keywords. except: err.error("Failed to evaluate weights function:\n" " " + str(weightsFunction) + "\n" "Please check your input.") err.message(" Weights function applied.") return data
def checkOverwrite(path): if not os.path.exists(path): return if os.path.isfile(path): err.error( "Failed to create the output file:\n\n" " " + str(path) + "\n\n" "The file already exists. You can do one of the following:\n\n" "1) Enable automatic overwrite in the GUI or parameter file\n" "2) Change base name and/or output directory in the GUI or\n" " parameter file\n" "3) Delete or rename the existing file", fatal=True, frame=True) elif os.path.isdir(path) and os.listdir(path): err.error( "Failed to create the output directory:\n\n" " " + str(path) + "\n\n" "The directory already exists and is not empty. You can do one\n" "of the following:\n\n" "1) Enable automatic overwrite in the GUI or parameter file\n" "2) Change base name and/or output directory in the GUI or\n" " parameter file\n" "3) Delete or rename the existing directory", fatal=True, frame=True) return
def apply_weights_function(data, weightsFunction): err.message("Applying weights function:\n " + str(weightsFunction)) # Define whitelist of allowed character sequences and import relevant Numpy functions whitelist = ["x", "y", "z", "e", "E", "sin", "cos", "tan", "arcsin", "arccos", "arctan", "arctan2", "sinh", "cosh", "tanh", "arcsinh", "arccosh", "arctanh", "exp", "log", "sqrt", "square", "power", "absolute", "fabs", "sign"] from numpy import sin, cos, tan, arcsin, arccos, arctan, arctan2, sinh, cosh, tanh, arcsinh, arccosh, arctanh, exp, log, sqrt, square, power, absolute, fabs, sign # Search for all keywords consisting of consecutive sequences of alphabetical characters keywordsFound = filter(None, re.split("[^a-zA-Z]+", str(weightsFunction))) # Check for non-whitelisted sequences for keyword in keywordsFound: err.ensure(keyword in whitelist, "Unknown keyword '" + str(keyword) + "' found in weights function:\n" " " + str(weightsFunction) + "\n" "Please check your input.") # Loop over all channels for i in range(data.shape[0]): # Create index arrays over 2-D planes (i.e. of width dz = 1) z, y, x = np.indices((1, data.shape[1], data.shape[2])) z += i # Multiply each plane by weights function try: data[z, y, x] *= eval(str(weightsFunction)) # NOTE: eval() should be safe now as we don't allow for non-whitelisted keywords. except: err.error( "Failed to evaluate weights function:\n" " " + str(weightsFunction) + "\n" "Please check your input.") err.message(" Weights function applied.") return data
def check_overwrite(filename, flagOverwrite, fatal=False): if not flagOverwrite and os.path.exists(filename): err.error("Output file exists: " + filename + ".", fatal=fatal) return False return True
default_file = os.getenv("SOFIA_PIPELINE_PATH").replace( "sofia_pipeline.py", "SoFiA_default_input.txt") Parameters = readoptions.readPipelineOptions(default_file) # ------------------------------ # ---- READ USER PARAMETERS ---- # ------------------------------ err.print_progress_message("Reading user parameters", t0) # This reads in a file with parameters and creates a dictionary: parameter_file = sys.argv[1] err.message("Parameters extracted from: " + str(parameter_file)) User_Parameters = readoptions.readPipelineOptions(parameter_file) if not User_Parameters: err.error("No valid parameter settings found in parameter file.", fatal=True) # Overwrite default parameters with user parameters (if exist): for task in iter(User_Parameters): if task in Parameters: for key in iter(User_Parameters[task]): if key in Parameters[task]: Parameters[task][key] = User_Parameters[task][key] # Define the base and output directory name used for output files (defaults to input file # name if writeCat.basename is found to be invalid): outputBase = Parameters["writeCat"]["basename"] outputDir = Parameters["writeCat"]["outputDir"] if outputDir and not os.path.isdir(outputDir): err.error("The specified output directory does not exist:\n" +
default_file = os.getenv("SOFIA_PIPELINE_PATH").replace("sofia_pipeline.py", "SoFiA_default_input.txt") Parameters = readoptions.readPipelineOptions(default_file) # ------------------------------ # ---- READ USER PARAMETERS ---- # ------------------------------ err.print_progress_message("Reading user parameters", t0) # This reads in a file with parameters and creates a dictionary: parameter_file = sys.argv[1] err.message("Parameters extracted from: " + str(parameter_file)) User_Parameters = readoptions.readPipelineOptions(parameter_file) if not User_Parameters: err.error("No valid parameter settings found in parameter file.", fatal=True) # Overwrite default parameters with user parameters (if exist): for task in iter(User_Parameters): if task in Parameters: for key in iter(User_Parameters[task]): if key in Parameters[task]: Parameters[task][key] = User_Parameters[task][key] # Define the base and output directory name used for output files (defaults to input file # name if writeCat.basename is found to be invalid): outputBase = Parameters["writeCat"]["basename"] outputDir = Parameters["writeCat"]["outputDir"] if outputDir and not os.path.isdir(outputDir): err.error("The specified output directory does not exist:\n" + str(outputDir), fatal=True)
def readPipelineOptions(filename = "pipeline.options"): # Try to open parameter file try: f = open(filename, "r") except IOError as e: err.error("Failed to read parameter file: " + str(filename) + "\n" + str(e), fatal=True) # Extract lines from parameter file lines = f.readlines() f.close() # Remove leading/trailing whitespace and empty lines lines = [line.strip() for line in lines] # Check for version number for line in lines: if "# Creator: SoFiA" in line: par_file_version = line[17:] if par_file_version != sofia_version: err.warning( "The parameter file was created with a different version of SoFiA\n" "(" + str(par_file_version) + ") than the one you are currently using (" + str(sofia_version) + ").\n" "Some settings defined in the parameter file may not be recognised\n" "by SoFiA, which could lead to unexpected results.", frame=True) # Remove comments lines = [line for line in lines if len(line) > 0 and line[0] != "#"] # Some additional setup datatypes = allowedDataTypes() tasks = {} pedantic = True # Controls whether to exit on unrecognised or redefined parameters pedantic_counter = 0 # Loop over all lines: for line in lines: # Extract parameter name and value try: parameter, value = tuple(line.split("=", 1)) parameter = parameter.strip() value = value.split("#")[0].strip() module, parname = tuple(parameter.split(".", 1)) except: err.error("Failed to read parameter: " + str(line) + "\nExpected format: module.parameter = value", fatal=True) # Ensure that module and parameter names are not empty if len(module) < 1 or len(parname) < 1: err.error("Failed to read parameter: " + str(line) + "\nExpected format: module.parameter = value", fatal=True) subtasks = tasks if module not in subtasks: subtasks[module] = {} subtasks = subtasks[module] if parname in subtasks: err.warning("Multiple definitions of parameter " + str(parameter) + " encountered.\nIgnoring all additional definitions.") pedantic_counter += 1 continue if parameter in datatypes: try: if datatypes[parameter] == "bool": subtasks[parname] = str2bool(value) elif datatypes[parameter] == "float": subtasks[parname] = float(value) elif datatypes[parameter] == "int": subtasks[parname] = int(value) elif datatypes[parameter] == "array": subtasks[parname] = literal_eval(value) else: subtasks[parname] = str(value) except: err.error("Failed to parse parameter value:\n" + str(line) + "\nExpected data type: " + str(datatypes[parameter]), fatal=True) if parameter == "pipeline.pedantic": pedantic = subtasks[parname] # Update 'pedantic' setting else: err.warning("Ignoring unknown parameter: " + str(parameter) + " = " + str(value)) pedantic_counter += 1 continue if pedantic and pedantic_counter: err.error("Multiply-defined or unrecognised parameter(s) encountered.\nPlease check your parameter file or set pipeline.pedantic = false\nto ignore unknown or already defined parameters.", fatal=True) return tasks
def import_mask(maskFile, header, axis_size, subcube): err.message("Loading mask cube:\n " + str(maskFile)) try: f = fits.open(maskFile, memmap=False) header_mask = f[0].header except: err.error("Failed to read mask cube.") # Extract axis sizes and types n_axes_mask, axis_size_mask, axis_type_mask = extract_axis_size( header_mask) # Ensure correct dimensionality check_cube_dimensions(n_axes_mask, axis_size_mask, cube_name="mask cube", min_dim=1, max_dim=4) # 1-D spectrum if n_axes_mask == 1: err.warning( "Mask cube has 1 axis; interpreted as spectrum.\nAdding first and second axis." ) ensure(header_mask['CRVAL1'] == header['CRVAL1'], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6: if header_mask["NAXIS1"] == axis_size[2]: err.message( " Input mask cube already matches size of data subcube.\n No subcube selection applied." ) mask = np.reshape(f[0].data, (-1, 1, 1)) elif header_mask["NAXIS1"] == fullshape[0]: err.message(" Subcube selection applied to input mask cube.") mask = np.reshape(f[0].section[subcube[4]:subcube[5]], (-1, 1, 1)) else: err.error( "Data subcube does not match size of mask subcube or full mask." ) elif not len(subcube): mask = np.reshape(f[0].data, (-1, 1, 1)) else: err.error( "The subcube list must have 6 entries ({0:d} given).".format( len(subcube))) # 2-D image elif n_axes_mask == 2: err.ensure( header_mask["CRVAL1"] == header["CRVAL1"] and header_mask["CRVAL2"] == header["CRVAL2"], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6 or len(subcube) == 4: if header_mask["NAXIS1"] == axis_size[0] and header_mask[ "NAXIS2"] == axis_size[1]: err.message( " Input mask cube already matches size of data subcube.\n No subcube selection applied." ) mask = np.array([f[0].data]) elif header_mask["NAXIS1"] == fullshape[2] and header_mask[ "NAXIS2"] == fullshape[1]: err.message(" Subcube selection applied to input mask cube.") mask = np.array([ f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]] ]) else: err.error( "Data subcube does not match size of mask subcube or full mask." ) else: mask = np.array([f[0].data]) # 3-D cube elif n_axes_mask == 3: err.ensure( header_mask["CRVAL1"] == header["CRVAL1"] and header_mask["CRVAL2"] == header["CRVAL2"] and header_mask["CRVAL3"] == header["CRVAL3"], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6: if header_mask["NAXIS1"] == axis_size[0] and header_mask[ "NAXIS2"] == axis_size[1] and header_mask[ "NAXIS3"] == axis_size[2]: err.message( " Input mask cube already matches size of data subcube.\n No subcube selection applied." ) mask = f[0].data elif header_mask["NAXIS1"] == fullshape[2] and header_mask[ "NAXIS2"] == fullshape[1] and header_mask[ "NAXIS3"] == fullshape[0]: err.message(" Subcube selection applied to input mask cube.") mask = f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: err.error( "Data subcube does not match size of mask subcube or full mask." ) else: mask = f[0].data # 4-D hypercube else: err.ensure( header_mask["CRVAL1"] == header["CRVAL1"] and header_mask["CRVAL2"] == header["CRVAL2"] and header_mask["CRVAL3"] == header["CRVAL3"], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6: if header_mask["NAXIS1"] == axis_size[0] and header_mask[ "NAXIS2"] == axis_size[1] and header_mask[ "NAXIS3"] == axis_size[2]: err.message( " Input mask cube already matches size of data subcube.\n No subcube selection applied." ) mask = f[0].section[0] elif header_mask["NAXIS1"] == fullshape[2] and header_mask[ "NAXIS2"] == fullshape[1] and header_mask[ "NAXIS3"] == fullshape[0]: err.message(" Subcube selection applied to input mask cube.") mask = f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: err.error( "Data subcube does not match size of mask subcube or full mask." ) else: mask = f[0].section[0] mask[mask > 0] = 1 f.close() err.message("Mask cube loaded.") # In all cases, convert mask to Boolean with masked pixels set to 1. return (mask > 0).astype(bool)
def get_subcube_range(header, n_axes, axis_size, subcube, subcubeMode): # Basic sanity checks err.ensure(subcubeMode in {"pixel", "world"}, "Subcube mode must be 'pixel' or 'world'.") err.ensure((len(subcube) == 4 and n_axes == 2) or (len(subcube) == 6 and n_axes > 2), "Subcube range must contain 4 values for 2-D cubes\n" "or 6 values for 3-D/4-D cubes.") # ----------------- # World coordinates # ----------------- if subcubeMode == "world": # Read WCS information try: wcsin = wcs.WCS(header) except: err.error("Failed to read WCS information from data cube header.") # Calculate cos(dec) correction for RA range: if wcsin.wcs.cunit[0] == "deg" and wcsin.wcs.cunit[1] == "deg": corrfact = math.cos(math.radians(subcube[1])) if n_axes == 4: subcube = wcsin.wcs_world2pix( np.array([[ subcube[0] - subcube[3] / corrfact, subcube[1] - subcube[4], subcube[2] - subcube[5], 0 ], [ subcube[0] + subcube[3] / corrfact, subcube[1] + subcube[4], subcube[2] + subcube[5], 0 ]]), 0)[:, :3] elif n_axes == 3: subcube = wcsin.wcs_world2pix( np.array([[ subcube[0] - subcube[3] / corrfact, subcube[1] - subcube[4], subcube[2] - subcube[5] ], [ subcube[0] + subcube[3] / corrfact, subcube[1] + subcube[4], subcube[2] + subcube[5] ]]), 0) elif n_axes == 2: subcube = wcsin.wcs_world2pix( np.array([[ subcube[0] - subcube[2] / corrfact, subcube[1] - subcube[3] ], [ subcube[0] + subcube[2] / corrfact, subcube[1] + subcube[3] ]]), 0) else: err.error("Unsupported number of axes.") # Flatten array subcube = np.ravel(subcube, order="F") # Ensure that min pix coord < max pix coord for all axes. # This operation is meaningful because wcs_world2pix returns negative pixel coordinates # only for pixels located before an axis' start (i.e., negative pixel coordinates should # not be interpreted as counting backward from an axis' end). subcube[0], subcube[1] = correct_order(subcube[0], subcube[1]) subcube[2], subcube[3] = correct_order(subcube[2], subcube[3]) if len(subcube) == 6: subcube[4], subcube[5] = correct_order(subcube[4], subcube[5]) # Convert to integer subcube = list(subcube.astype(int)) # Constrain subcube to be within cube boundaries for axis in range(min(3, n_axes)): err.ensure( subcube[2 * axis + 1] >= 0 and subcube[2 * axis] < axis_size[axis], "Subcube outside input cube range for axis {0:d}.".format( axis)) subcube[2 * axis] = max(subcube[2 * axis], 0) subcube[2 * axis + 1] = min(subcube[2 * axis + 1] + 1, axis_size[axis]) # ----------------- # Pixel coordinates # ----------------- else: # Ensure that pixel coordinates are integers for value in subcube: err.ensure( type(value) == int, "Subcube boundaries must be integer values.") # Sanity checks on boundaries for axis in range(min(3, n_axes)): # Ensure correct order err.ensure( subcube[2 * axis] < subcube[2 * axis + 1], "Lower subcube boundary greater than upper boundary.\nPlease check your input." ) # Adjust lower boundary subcube[2 * axis] = max(subcube[2 * axis], 0) subcube[2 * axis] = min(subcube[2 * axis], axis_size[axis] - 1) # Adjust upper boundary: subcube[2 * axis + 1] = max(subcube[2 * axis + 1], 1) subcube[2 * axis + 1] = min(subcube[2 * axis + 1], axis_size[axis]) # Report final subcube boundaries err.message(" Loading subcube of range " + str(subcube) + '.') return subcube
def EstimateRel(data, pdfoutname, parNames, parSpace=["snr_sum", "snr_max", "n_pix"], logPars=[1, 1, 1], autoKernel=True, scaleKernel=1, negPerBin=1, skellamTol=-0.5, kernel=[0.15, 0.05, 0.1], usecov=False, doscatter=1, docontour=1, doskellam=1, dostats=0, saverel=1, threshold=0.99, fMin=0, verb=0, makePlot=False): # Always work on logarithmic parameter values; the reliability.logPars parameter should be removed if 0 in logPars: err.warning( " Setting all reliability.logPars entries to 1. This parameter is no longer editable by users." ) logPars = [1 for pp in parSpace] # Import Matplotlib if diagnostic plots requested if makePlot: import matplotlib # The following line is necessary to run SoFiA remotely matplotlib.use("Agg") import matplotlib.pyplot as plt # -------------------------------- # Build array of source parameters # -------------------------------- idCOL = parNames.index("id") ftotCOL = parNames.index("snr_sum") fmaxCOL = parNames.index("snr_max") fminCOL = parNames.index("snr_min") # Get columns of requested parameters parCol = [] for ii in range(len(parSpace)): parCol.append(parNames.index(parSpace[ii])) # Get position and number of positive and negative sources pos = data[:, ftotCOL] > 0 neg = data[:, ftotCOL] <= 0 Npos = pos.sum() Nneg = neg.sum() err.ensure(Npos, "No positive sources found; cannot proceed.") err.ensure(Nneg, "No negative sources found; cannot proceed.") # Get array of relevant source parameters (and take log of them if requested) ids = data[:, idCOL] pars = np.empty((data.shape[0], 0)) for ii in range(len(parSpace)): if parSpace[ii] == "snr_max": parsTmp = data[:, fmaxCOL] * pos - data[:, fminCOL] * neg if logPars[ii]: parsTmp = np.log10(parsTmp) pars = np.concatenate((pars, parsTmp.reshape(-1, 1)), axis=1) elif parSpace[ii] == "snr_sum" or parSpace[ii] == "snr_mean": parsTmp = abs(data[:, parCol[ii]].reshape(-1, 1)) if logPars[ii]: parsTmp = np.log10(parsTmp) pars = np.concatenate((pars, parsTmp), axis=1) else: parsTmp = data[:, parCol[ii]].reshape(-1, 1) if logPars[ii]: parsTmp = np.log10(parsTmp) pars = np.concatenate((pars, parsTmp), axis=1) err.message(" Working in parameter space {0:}".format(str(parSpace))) err.message( " Will convolve the distribution of positive and negative sources in this space to derive the P and N density fields" ) pars = np.transpose(pars) # ---------------------------------------------------------- # Set parameters to work with and gridding/plotting for each # ---------------------------------------------------------- # Axis labels when plotting labs = [] for ii in range(len(parSpace)): labs.append("") if logPars[ii]: labs[ii] += "log " labs[ii] += parSpace[ii] # Axis limits when plotting pmin, pmax = pars.min(axis=1), pars.max(axis=1) pmin, pmax = pmin - 0.1 * (pmax - pmin), pmax + 0.1 * (pmax - pmin) lims = [[pmin[i], pmax[i]] for i in range(len(parSpace))] # Grid on which to evaluate Np and Nn in order to plot contours grid = [[pmin[i], pmax[i], 0.02 * (pmax[i] - pmin[i])] for i in range(len(parSpace))] # Calculate the number of rows and columns in figure projections = [subset for subset in combinations(range(len(parSpace)), 2)] nr = int(np.floor(np.sqrt(len(projections)))) nc = int(np.ceil(float(len(projections)) / nr)) # --------------------------------------- # Set smoothing kernel in parameter space # --------------------------------------- # If autoKernel is True, then the initial kernel is taken as a scaled version of the covariance matrix # of the negative sources. The kernel size along each axis is such that the number of sources per kernel # width (sigma**2) is equal to "negPerBin". Optionally, the user can decide to use only the diagonal # terms of the covariance matrix. The kernel is then grown until convergence is reached on the Skellam # plot. If autoKernel is False, then use the kernel given by "kernel" parameter (argument of EstimateRel); # this is sigma, and is squared to be consistent with the auto kernel above. if autoKernel: # Set the kernel shape to that of the variance or covariance matrix kernel = np.cov(pars[:, neg]) kernelType = "covariance" # Check if kernel matrix can be inverted try: np.linalg.inv(kernel) except: err.error( "The reliability cannot be calculated because the smoothing kernel\n" "derived from " + str(pars[:, neg].shape[1]) + " negative sources cannot be inverted.\n" "This is likely due to an insufficient number of negative sources.\n" "Try to increase the number of negative sources by changing the\n" "source finding and/or filtering settings.", fatal=True, frame=True) if np.isnan(kernel).sum(): err.error( "The reliability cannot be calculated because the smoothing kernel\n" "derived from " + str(pars[:, neg].shape[1]) + " negative sources contains NaNs.\n" "A good kernel is required to calculate the density field of positive\n" "and negative sources in parameter space.\n" "Try to increase the number of negative sources by changing the\n" "source finding and/or filtering settings.", fatal=True, frame=True) if not usecov: kernel = np.diag(np.diag(kernel)) kernelType = "variance" kernelIter = 0.0 deltplot = [] # Scale the kernel size as requested by the user (scaleKernel>0) or use the autoscale algorithm (scaleKernel=0) if scaleKernel > 0: # Scale kernel size as requested by the user # Note that the scale factor is squared because users are asked to give a factor to apply to sqrt(kernel) kernel *= scaleKernel**2 err.message( " Using the {0:s} matrix scaled by a factor {1:.2f} as convolution kernel" .format(kernelType, scaleKernel)) err.message(" The sqrt(kernel) size is:") err.message(" " + str(np.sqrt(np.abs(kernel)))) elif scaleKernel == 0: # Scale kernel size to get started the kernel-growing loop # The scale factor for sqrt(kernel) is elevated to the power of 1.0 / len(parCol) err.message( " Will search for the best convolution kernel by scaling the {0:s} matrix" .format(kernelType)) err.message(" The {0:s} matrix has sqrt:".format(kernelType)) err.message(" " + str(np.sqrt(np.abs(kernel)))) # negPerBin must be >=1 err.ensure( negPerBin >= 1, "The parameter reliability.negPerBin used to start the convolution kernel search was set to {0:.1f} but must be >= 1. Please change your settings." .format(negPerBin)) kernel *= ((negPerBin + kernelIter) / Nneg)**(2.0 / len(parCol)) err.message(" Search starting from the kernel with sqrt:") err.message(" " + str(np.sqrt(np.abs(kernel)))) err.message( " Iteratively growing kernel until the distribution of (P-N)/sqrt(P+N) reaches median/width = {0:.2f} ..." .format(skellamTol)) err.ensure( skellamTol <= 0, "The parameter reliability.skellamTol was set to {0:.2f} but must be <= 0. Please change your settings." .format(skellamTol)) else: err.ensure(scaleKernel>=0,\ "The reliability.scaleKernel parameter cannot be negative.\n"\ "It should be = 0 if you want SoFiA to find the optimal kernel scaling\n"\ "or > 0 if you want to set the scaling yourself.\n"\ "Please change your settings.") #deltOLD=-1e+9 # Used to stop kernel growth if P-N stops moving closer to zero [NOT USED CURRENTLY] if doskellam and makePlot: fig0 = plt.figure() else: # Note that the user must give sigma, which then gets squared err.message( " Using user-defined variance kernel with sqrt(kernel) size: {0}". format(kernel)) err.ensure( len(parSpace) == len(kernel), "The number of entries in the kernel above does not match the number of parameters you requested for the reliability calculation." ) kernel = np.identity(len(kernel)) * np.array(kernel)**2 # Set grow_kernel to 1 to start the kernel growing loop below. grow_kernel = 1 # This loop will estimate the reliability, check whether the kernel is large enough, # and if not pick a larger kernel. If autoKernel = 0 or scaleKernel = 0, we will do # just one pass (i.e., we will not grow the kernel). while grow_kernel: # ------------------------ # Evaluate N-d reliability # ------------------------ if verb: err.message( " estimate normalised positive and negative density fields ..." ) Np = gaussian_kde_set_covariance(pars[:, pos], kernel) Nn = gaussian_kde_set_covariance(pars[:, neg], kernel) # Calculate the number of positive and negative sources at the location of positive sources Nps = Np(pars[:, pos]) * Npos Nns = Nn(pars[:, pos]) * Nneg # Calculate the number of positive and negative sources at the location of negative sources nNps = Np(pars[:, neg]) * Npos nNns = Nn(pars[:, neg]) * Nneg # Calculate the reliability at the location of positive sources Rs = (Nps - Nns) / Nps # The reliability must be <= 1. If not, something is wrong. err.ensure( Rs.max() <= 1, "Maximum reliability greater than 1; something is wrong.\nPlease ensure that enough negative sources are detected\nand decrease your source finding threshold if necessary.", frame=True) # Find pseudo-reliable sources (taking maximum(Rs, 0) in order to include objects with Rs < 0 # if threshold == 0; Rs may be < 0 because of insufficient statistics) # These are called pseudo-reliable because some objects may be discarded later based on additional criteria below pseudoreliable = np.maximum(Rs, 0) >= threshold # Find reliable sources (taking maximum(Rs, 0) in order to include objects with Rs < 0 if # threshold == 0; Rs may be < 0 because of insufficient statistics) #reliable=(np.maximum(Rs, 0)>=threshold) * (data[pos, ftotCOL].reshape(-1,) > fMin) * (data[pos, fmaxCOL].reshape(-1,) > 4) reliable = (np.maximum(Rs, 0) >= threshold) * ( (data[pos, ftotCOL] / np.sqrt(data[pos, parNames.index("n_pix")])).reshape(-1, ) > fMin) if autoKernel: # Calculate quantities needed for comparison to Skellam distribution delt = (nNps - nNns) / np.sqrt(nNps + nNns) deltstd = delt.std() deltmed = np.median(delt) deltmin = delt.min() deltmax = delt.max() if deltmed / deltstd > -100 and doskellam and makePlot: plt.hist(delt / deltstd, bins=np.arange(deltmin / deltstd, max(5.1, deltmax / deltstd), 0.01), cumulative=True, histtype="step", color=(min( 1, float(max(1., negPerBin) + kernelIter) / Nneg), 0, 0), density=True) deltplot.append([((max(1., negPerBin) + kernelIter) / Nneg)**(1.0 / len(parCol)), deltmed / deltstd]) if scaleKernel: grow_kernel = 0 else: err.message( " iteration, median, width, median/width = %3i, %9.2e, %9.2e, %9.2e" % (kernelIter, deltmed, deltstd, deltmed / deltstd)) if deltmed / deltstd > skellamTol or negPerBin + kernelIter >= Nneg: grow_kernel = 0 err.message( " Found good kernel after %i kernel growth iterations. The sqrt(kernel) size is:" % kernelIter) err.message(np.sqrt(np.abs(kernel))) elif deltmed / deltstd < 5 * skellamTol: kernel *= (float(negPerBin + kernelIter + 20) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 20 elif deltmed / deltstd < 2 * skellamTol: kernel *= (float(negPerBin + kernelIter + 10) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 10 elif deltmed / deltstd < 1.5 * skellamTol: kernel *= (float(negPerBin + kernelIter + 3) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 3 else: kernel *= (float(negPerBin + kernelIter + 1) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 1 else: grow_kernel = 0 # ------------ # Skellam plot # ------------ if autoKernel and deltmed / deltstd > -100 and doskellam and makePlot: plt.plot(np.arange(-10, 10, 0.01), stats.norm().cdf(np.arange(-10, 10, 0.01)), "k-") plt.plot(np.arange(-10, 10, 0.01), stats.norm(scale=0.4).cdf(np.arange(-10, 10, 0.01)), "k:") plt.legend(("Gaussian (sigma=1)", "Gaussian (sigma=0.4)"), loc="lower right", prop={"size": 13}) plt.hist(delt / deltstd, bins=np.arange(deltmin / deltstd, max(5.1, deltmax / deltstd), 0.01), cumulative=True, histtype="step", color="r", density=True) plt.xlim(-5, 5) plt.ylim(0, 1) plt.xlabel("(P-N)/sqrt(N+P)") plt.ylabel("cumulative distribution") plt.plot([0, 0], [0, 1], "k--") fig0.savefig("%s_rel_skellam.pdf" % pdfoutname, rasterized=True) if not scaleKernel: fig3 = plt.figure() deltplot = np.array(deltplot) plt.plot(deltplot[:, 0], deltplot[:, 1], "ko-") plt.xlabel("kernel size (1D-sigma, aribtrary units)") plt.ylabel("median/std of (P-N)/sqrt(P+N)") plt.axhline(y=skellamTol, linestyle="--", color="r") fig3.savefig("%s_rel_skellam-delta.pdf" % pdfoutname, rasterized=True) # ----------------------- # Scatter plot of sources # ----------------------- specialids = [] if doscatter and makePlot: if verb: err.message(" plotting sources ...") fig1 = plt.figure(figsize=(18, 4.5 * nr)) plt.subplots_adjust(left=0.06, bottom=0.15 / nr, right=0.97, top=1 - 0.08 / nr, wspace=0.35, hspace=0.25) n_p = 0 for jj in projections: if verb: err.message(" projection %i/%i" % (projections.index(jj) + 1, len(projections))) n_p, p1, p2 = n_p + 1, jj[0], jj[1] plt.subplot(nr, nc, n_p) plt.scatter(pars[p1, pos], pars[p2, pos], marker="o", c="b", s=10, edgecolor="face", alpha=0.5) plt.scatter(pars[p1, neg], pars[p2, neg], marker="o", c="r", s=10, edgecolor="face", alpha=0.5) for si in specialids: plt.plot(pars[p1, ids == si], pars[p2, ids == si], "kd", zorder=10000, ms=7, mfc="none", mew=2) # Plot Integrated SNR threshold if fMin > 0 and (parSpace[jj[0]], parSpace[jj[1]]) == ("snr_sum", "snr_mean"): xArray = np.arange( lims[p1][0], lims[p1][1] + (lims[p1][1] - lims[p1][0]) / 100, (lims[p1][1] - lims[p1][0]) / 100) plt.plot(xArray, np.log10(fMin) * 2 - xArray, 'k:') elif fMin > 0 and (parSpace[jj[0]], parSpace[jj[1]]) == ("snr_mean", "snr_sum"): yArray = np.arange( lims[p2][0], lims[p2][1] + (lims[p2][1] - lims[p2][0]) / 100, (lims[p2][1] - lims[p2][0]) / 100) plt.plot(np.log10(fMin) * 2 - yArray, yArray, 'k:') plt.xlim(lims[p1][0], lims[p1][1]) plt.ylim(lims[p2][0], lims[p2][1]) plt.xlabel(labs[p1]) plt.ylabel(labs[p2]) plt.grid(color='k', linestyle='-', linewidth=0.2) fig1.savefig("%s_rel_scatter.pdf" % pdfoutname, rasterized=True) # ------------- # Plot contours # ------------- if docontour and makePlot: levs = 10**np.arange(-1.5, 2, 0.5) if verb: err.message(" plotting contours ...") fig2 = plt.figure(figsize=(18, 4.5 * nr)) plt.subplots_adjust(left=0.06, bottom=0.15 / nr, right=0.97, top=1 - 0.08 / nr, wspace=0.35, hspace=0.25) n_p = 0 for jj in projections: if verb: err.message(" projection %i/%i" % (projections.index(jj) + 1, len(projections))) n_p, p1, p2 = n_p + 1, jj[0], jj[1] g1, g2 = grid[p1], grid[p2] x1 = np.arange(g1[0], g1[1], g1[2]) x2 = np.arange(g2[0], g2[1], g2[2]) pshape = (x2.shape[0], x1.shape[0]) # Get array of source parameters on current projection parsp = np.concatenate((pars[p1:p1 + 1], pars[p2:p2 + 1]), axis=0) # Derive Np and Nn density fields on the current projection setcov = kernel[p1:p2 + 1:p2 - p1, p1:p2 + 1:p2 - p1] try: Np = gaussian_kde_set_covariance(parsp[:, pos], setcov) Nn = gaussian_kde_set_covariance(parsp[:, neg], setcov) except: err.error( "Reliability determination failed because of issues with the\n" "smoothing kernel. This is likely due to an insufficient number\n" "of negative detections. Please review your filtering and source\n" "finding settings to ensure that a sufficient number of negative\n" "detections is found.", fatal=True, frame=True) # Evaluate density fields on grid on current projection g = np.transpose( np.transpose(np.mgrid[slice(g1[0], g1[1], g1[2]), slice(g2[0], g2[1], g2[2])]).reshape( -1, 2)) Np = Np(g) Nn = Nn(g) Np = Np / Np.sum() * Npos Nn = Nn / Nn.sum() * Nneg Np.resize(pshape) Nn.resize(pshape) plt.subplot(nr, nc, n_p) plt.contour(x1, x2, Np, origin="lower", colors="b", levels=levs, zorder=2) plt.contour(x1, x2, Nn, origin="lower", colors="r", levels=levs, zorder=1) # Plot Integrated SNR threshold if fMin > 0 and (parSpace[jj[0]], parSpace[jj[1]]) == ("snr_sum", "snr_mean"): xArray = np.arange( lims[p1][0], lims[p1][1] + (lims[p1][1] - lims[p1][0]) / 100, (lims[p1][1] - lims[p1][0]) / 100) plt.plot(xArray, np.log10(fMin) * 2 - xArray, 'k:') elif fMin > 0 and (parSpace[jj[0]], parSpace[jj[1]]) == ("snr_mean", "snr_sum"): yArray = np.arange( lims[p2][0], lims[p2][1] + (lims[p2][1] - lims[p2][0]) / 100, (lims[p2][1] - lims[p2][0]) / 100) plt.plot(np.log10(fMin) * 2 - yArray, yArray, 'k:') if reliable.sum(): plt.scatter(pars[p1, pos][reliable], pars[p2, pos][reliable], marker="o", s=10, edgecolor="k", facecolor="k", zorder=4) if (pseudoreliable * (reliable == False)).sum(): plt.scatter(pars[p1, pos][pseudoreliable * (reliable == False)], pars[p2, pos][pseudoreliable * (reliable == False)], marker="x", s=40, edgecolor="0.5", facecolor="0.5", zorder=3) for si in specialids: plt.plot(pars[p1, ids == si], pars[p2, ids == si], "kd", zorder=10000, ms=7, mfc="none", mew=2) plt.xlim(lims[p1][0], lims[p1][1]) plt.ylim(lims[p2][0], lims[p2][1]) plt.xlabel(labs[p1]) plt.ylabel(labs[p2]) plt.grid(color='k', linestyle='-', linewidth=0.2) fig2.savefig("%s_rel_contour.pdf" % pdfoutname, rasterized=True) # ------------------------- # Add Np, Nn and R to table # ------------------------- # This allows me not to calculate R every time I want to do some plot analysis, # but just read it from the file if saverel: if not (docontour or dostats): Nps = Np(pars[:, pos]) * Npos Nns = Nn(pars[:, pos]) * Nneg Np = np.zeros((data.shape[0], )) Np[pos] = Nps Nn = np.zeros((data.shape[0], )) Nn[pos] = Nns R = -np.ones((data.shape[0], )) # R will be -1 for negative sources # Set R to zero for positive sources if R < 0 because of Nn > Np R[pos] = np.maximum(0, (Np[pos] - Nn[pos]) / Np[pos]) data = np.concatenate( (data, Np.reshape(-1, 1), Nn.reshape(-1, 1), R.reshape(-1, 1)), axis=1) data = [list(jj) for jj in list(data)] return data, ids[pos][reliable].astype(int)
def write_catalog_from_array(mode, objects, catHeader, catUnits, catFormat, parList, outName, flagCompress, flagOverwrite, flagUncertainties): # Check output format and compression availableModes = ["ASCII", "XML", "SQL"] if mode not in availableModes: err.warning("Unknown catalogue format: " + str(mode) + ". Defaulting to ASCII.") mode = "ASCII" modeIndex = availableModes.index(mode) if flagCompress: outName += ".gz" err.message("Writing " + availableModes[modeIndex] + " catalogue: " + outName + ".") # Exit if file exists and overwrite flag is set to false func.check_overwrite(outName, flagOverwrite, fatal=True) # Do we need to write all parameters? if parList == ["*"] or not parList: parList = list(catHeader) # Remove undefined parameters parList = [item for item in parList if item in catHeader] # Remove statistical uncertainties if not requested if not flagUncertainties: for item in ["err_x", "err_y", "err_z", "err_w20", "err_w50"]: while item in parList: parList.remove(item) # Check whether there is anything left if not len(parList): err.error("No valid output parameters selected. No output catalogue written.", fatal=False) return # Create and write catalogue in requested format # ------------------------------------------------------------------------- if mode == "XML": # Define basic XML header information votable = Element("VOTABLE") resource = SubElement(votable, "RESOURCE", name="SoFiA catalogue (version %s)" % sofia_version) description = SubElement(resource, "DESCRIPTION") description.text = "Source catalogue from the Source Finding Application (SoFiA) version %s" % sofia_version coosys = SubElement(resource, "COOSYS", ID="J2000") table = SubElement(resource, "TABLE", ID="sofia_cat", name="sofia_cat") # Load list of parameters and unified content descriptors (UCDs) ucdList = {} fileUcdPath = os.environ["SOFIA_PIPELINE_PATH"] fileUcdPath = fileUcdPath.replace("sofia_pipeline.py", "SoFiA_source_parameters.dat") try: with open(fileUcdPath) as fileUcd: for line in fileUcd: (key, value) = line.split() ucdList[key] = value except: err.warning("Failed to read UCD file.") # Create parameter fields for par in parList: ucdEntity = ucdList[par] if par in ucdList else "" index = list(catHeader).index(par) if catFormat[index] == "%30s": field = SubElement(table, "FIELD", name=par, ucd=ucdEntity, datatype="char", arraysize="30", unit=catUnits[index]) else: field = SubElement(table, "FIELD", name=par, ucd=ucdEntity, datatype="float", unit=catUnits[index]) # Create data table entries data = SubElement(table, "DATA") tabledata = SubElement(data, "TABLEDATA") for obj in objects: tr = SubElement(tabledata, "TR") for par in parList: td = SubElement(tr, "TD") index = list(catHeader).index(par) td.text = (catFormat[index] % obj[index]).strip() # Write XML catalogue: try: f1 = gzopen(outName, "wb") if flagCompress else open(outName, "w") except: err.error("Failed to write to XML catalogue: " + outName + ".", fatal=False) return f1.write(prettify(votable)) #f1.write(tostring(votable, "utf-8")) // without prettifying, which is faster and uses much less memory f1.close # -----------------------------------------------------------------End-XML- elif mode == "SQL": # Record if there is an ID column in the catalogue # (if no ID is present, we will later create one for use as primary key) noID = "id" not in parList # Write some header information: content = "-- SoFiA catalogue (version %s)\n\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n\n" % sofia_version # Construct and write table structure: flagProgress = False content += "CREATE TABLE IF NOT EXISTS `SoFiA-Catalogue` (\n" if noID: content += " `id` INT NOT NULL,\n" for par in parList: index = list(catHeader).index(par) if flagProgress: content += ",\n" content += " " + sqlHeaderItem(par) + sqlFormat(catFormat[index]) flagProgress = True content += ",\n PRIMARY KEY (`id`),\n KEY (`id`)\n) DEFAULT CHARSET=utf8 COMMENT=\'SoFiA source catalogue\';\n\n" # Insert data: flagProgress = False content += "INSERT INTO `SoFiA-Catalogue` (" if noID: content += "`id`, " for par in parList: if flagProgress: content += ", " content += sqlHeaderItem(par) flagProgress = True content += ") VALUES\n" source_count = 0 for obj in objects: flagProgress = False source_count += 1 content += "(" if noID: content += str(source_count) + ", " for par in parList: index = list(catHeader).index(par) if flagProgress: content += ", " content += sqlDataItem(obj[index], catFormat[index]) flagProgress = True if(source_count < len(objects)): content += "),\n" else: content += ");\n" # Write catalogue try: fp = gzopen(outName, "wb") if flagCompress else open(outName, "w") except: err.error("Failed to write to SQL catalogue: " + outName + ".", fatal=False) return fp.write(content) fp.close() # -----------------------------------------------------------------End-SQL- else: # mode == "ASCII" by default # Determine header sizes based on variable-length formatting lenCathead = [] for j in catFormat: lenCathead.append(int(j.split("%")[1].split("e")[0].split("f")[0].split("i")[0].split("d")[0].split(".")[0].split("s")[0]) + 1) # Create header headerName = "" headerUnit = "" headerCol = "" outFormat = "" colCount = 0 header = "SoFiA catalogue (version %s)\n" % sofia_version for par in parList: index = list(catHeader).index(par) headerName += catHeader[index].rjust(lenCathead[index]) headerUnit += catUnits[index].rjust(lenCathead[index]) headerCol += ("(%i)" % (colCount + 1)).rjust(lenCathead[index]) outFormat += catFormat[index] + " " colCount += 1 header += headerName[3:] + '\n' + headerUnit[3:] + '\n' + headerCol[3:] # Create catalogue outObjects = [] for obj in objects: outObjects.append([]) for par in parList: outObjects[-1].append(obj[list(catHeader).index(par)]) # Write ASCII catalogue try: np.savetxt(outName, np.array(outObjects, dtype=object), fmt=outFormat, header=header) except: err.error("Failed to write to ASCII catalogue: " + outName + ".", fatal=False) return # ---------------------------------------------------------------End-ASCII- return
def import_mask(maskFile, header, axis_size, subcube): err.message("Loading mask cube:\n " + str(maskFile)) try: f = fits.open(maskFile, memmap=False) header_mask = f[0].header except: err.error("Failed to read mask cube.") # Extract axis sizes and types n_axes_mask, axis_size_mask, axis_type_mask = extract_axis_size(header_mask) # Ensure correct dimensionality check_cube_dimensions(n_axes_mask, axis_size_mask, cube_name="mask cube", min_dim = 1, max_dim = 4) # 1-D spectrum if n_axes_mask == 1: err.warning("Mask cube has 1 axis; interpreted as spectrum.\nAdding first and second axis.") ensure(header_mask['CRVAL1'] == header['CRVAL1'], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6: if header_mask["NAXIS1"] == axis_size[2]: err.message(" Input mask cube already matches size of data subcube.\n No subcube selection applied.") mask = np.reshape(f[0].data, (-1, 1, 1)) elif header_mask["NAXIS1"] == fullshape[0]: err.message(" Subcube selection applied to input mask cube.") mask = np.reshape(f[0].section[subcube[4]:subcube[5]], (-1, 1, 1)) else: err.error("Data subcube does not match size of mask subcube or full mask.") elif not len(subcube): mask = np.reshape(f[0].data, (-1, 1, 1)) else: err.error("The subcube list must have 6 entries ({0:d} given).".format(len(subcube))) # 2-D image elif n_axes_mask == 2: err.ensure(header_mask["CRVAL1"] == header["CRVAL1"] and header_mask["CRVAL2"] == header["CRVAL2"], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6 or len(subcube) == 4: if header_mask["NAXIS1"] == axis_size[0] and header_mask["NAXIS2"] == axis_size[1]: err.message(" Input mask cube already matches size of data subcube.\n No subcube selection applied.") mask = np.array([f[0].data]) elif header_mask["NAXIS1"] == fullshape[2] and header_mask["NAXIS2"] == fullshape[1]: err.message(" Subcube selection applied to input mask cube.") mask = np.array([f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]]]) else: err.error("Data subcube does not match size of mask subcube or full mask.") else: mask = np.array([f[0].data]) # 3-D cube elif n_axes_mask == 3: err.ensure(header_mask["CRVAL1"] == header["CRVAL1"] and header_mask["CRVAL2"] == header["CRVAL2"] and header_mask["CRVAL3"] == header["CRVAL3"], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6: if header_mask["NAXIS1"] == axis_size[0] and header_mask["NAXIS2"] == axis_size[1] and header_mask["NAXIS3"] == axis_size[2]: err.message(" Input mask cube already matches size of data subcube.\n No subcube selection applied.") mask = f[0].data elif header_mask["NAXIS1"] == fullshape[2] and header_mask["NAXIS2"] == fullshape[1] and header_mask["NAXIS3"] == fullshape[0]: err.message(" Subcube selection applied to input mask cube.") mask = f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: err.error("Data subcube does not match size of mask subcube or full mask.") else: mask = f[0].data # 4-D hypercube else: err.ensure(header_mask["CRVAL1"] == header["CRVAL1"] and header_mask["CRVAL2"] == header["CRVAL2"] and header_mask["CRVAL3"] == header["CRVAL3"], "Input cube and mask are not on the same WCS grid.") if len(subcube) == 6: if header_mask["NAXIS1"] == axis_size[0] and header_mask["NAXIS2"] == axis_size[1] and header_mask["NAXIS3"] == axis_size[2]: err.message(" Input mask cube already matches size of data subcube.\n No subcube selection applied.") mask = f[0].section[0] elif header_mask["NAXIS1"] == fullshape[2] and header_mask["NAXIS2"] == fullshape[1] and header_mask["NAXIS3"] == fullshape[0]: err.message(" Subcube selection applied to input mask cube.") mask = f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: err.error("Data subcube does not match size of mask subcube or full mask.") else: mask = f[0].section[0] mask[mask > 0] = 1 f.close() err.message("Mask cube loaded.") # In all cases, convert mask to Boolean with masked pixels set to 1. return (mask > 0).astype(bool)
def apply_flagging(data, flagFile, flagRegions, subcube): # ------------------------------- # Apply flagging cube if provided # ------------------------------- if flagFile: err.message("Applying flagging cube:\n " + str(flagFile)) try: f = fits.open(flagFile, memmap=False) header_flags = f[0].header except: err.error("Failed to read flagging cube.") # Extract axis sizes and types n_axes_flags, axis_size_flags, axis_type_flags = extract_axis_size(header_flags) # Ensure correct dimensionality check_cube_dimensions(n_axes_flags, axis_size_flags, cube_name="flagging cube") # Apply flagging # 2-D image if n_axes_flags == 2: for chan in range(data.shape[0]): if len(subcube) == 6 or len(subcube) == 4: data[chan][np.isnan(f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]])] = np.nan else: data[chan][np.isnan(np.array([f[0].data]))] = np.nan # 3-D cube elif n_axes_flags == 3: if len(subcube) == 6: data[np.isnan(f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]])] = np.nan else: data[np.isnan(f[0].data)] = np.nan # 4-D hypercube else: if len(subcube) == 6: data[np.isnan(f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]])] = np.nan else: data[np.isnan(f[0].section[0])] = np.nan f.close() err.message("Flagging cube applied.") # ---------------------------------- # Apply flagging regions if provided # ---------------------------------- if flagRegions: err.message("Applying flagging regions:\n " + str(flagRegions)) dim = len(data.shape) try: for region in flagRegions: for i in range(0, len(region) / 2): if region[2 * i + 1] == "": region[2 * i + 1] = data.shape[dim - i - 1] if len(region) == 2: data[0, region[2]:region[3], region[0]:region[1]] = np.nan else: data[region[4]:region[5], region[2]:region[3], region[0]:region[1]] = np.nan err.message("Flagging regions applied.") except: err.error("Flagging did not succeed. Please check the dimensions\nof your data cube and flagging regions.") return data
def get_subcube_range(header, n_axes, axis_size, subcube, subcubeMode): # Basic sanity checks err.ensure( subcubeMode in {"pixel", "world"}, "Subcube mode must be 'pixel' or 'world'.") err.ensure( (len(subcube) == 4 and n_axes == 2) or (len(subcube) == 6 and n_axes > 2), "Subcube range must contain 4 values for 2-D cubes\n" "or 6 values for 3-D/4-D cubes.") # ----------------- # World coordinates # ----------------- if subcubeMode == "world": # Read WCS information try: wcsin = wcs.WCS(header) except: err.error("Failed to read WCS information from data cube header.") # Calculate cos(dec) correction for RA range: if wcsin.wcs.cunit[0] == "deg" and wcsin.wcs.cunit[1] == "deg": corrfact = math.cos(math.radians(subcube[1])) if n_axes == 4: subcube = wcsin.wcs_world2pix(np.array([[subcube[0] - subcube[3] / corrfact, subcube[1] - subcube[4], subcube[2] - subcube[5], 0], [subcube[0] + subcube[3] / corrfact, subcube[1] + subcube[4], subcube[2] + subcube[5], 0]]), 0)[:, :3] elif n_axes == 3: subcube = wcsin.wcs_world2pix(np.array([[subcube[0] - subcube[3] / corrfact, subcube[1] - subcube[4], subcube[2] - subcube[5]], [subcube[0] + subcube[3] / corrfact, subcube[1] + subcube[4], subcube[2] + subcube[5]]]), 0) elif n_axes == 2: subcube = wcsin.wcs_world2pix(np.array([[subcube[0] - subcube[2] / corrfact, subcube[1] - subcube[3]], [subcube[0] + subcube[2] / corrfact, subcube[1] + subcube[3]]]), 0) else: err.error("Unsupported number of axes.") # Flatten array subcube = np.ravel(subcube, order="F") # Ensure that min pix coord < max pix coord for all axes. # This operation is meaningful because wcs_world2pix returns negative pixel coordinates # only for pixels located before an axis' start (i.e., negative pixel coordinates should # not be interpreted as counting backward from an axis' end). subcube[0], subcube[1] = correct_order(subcube[0], subcube[1]) subcube[2], subcube[3] = correct_order(subcube[2], subcube[3]) if len(subcube) == 6: subcube[4], subcube[5] = correct_order(subcube[4], subcube[5]) # Convert to integer subcube = list(subcube.astype(int)) # Constrain subcube to be within cube boundaries for axis in range(min(3, n_axes)): err.ensure(subcube[2 * axis + 1] >= 0 and subcube[2 * axis] < axis_size[axis], "Subcube outside input cube range for axis {0:d}.".format(axis)) subcube[2 * axis] = max(subcube[2 * axis], 0) subcube[2 * axis + 1] = min(subcube[2 * axis + 1] + 1, axis_size[axis]) # ----------------- # Pixel coordinates # ----------------- else: # Ensure that pixel coordinates are integers for value in subcube: err.ensure(type(value) == int, "Subcube boundaries must be integer values.") # Sanity checks on boundaries for axis in range(min(3, n_axes)): # Ensure correct order err.ensure(subcube[2 * axis] < subcube[2 * axis + 1], "Lower subcube boundary greater than upper boundary.\nPlease check your input.") # Adjust lower boundary subcube[2 * axis] = max(subcube[2 * axis], 0) subcube[2 * axis] = min(subcube[2 * axis], axis_size[axis] - 1) # Adjust upper boundary: subcube[2 * axis + 1] = max(subcube[2 * axis + 1], 1) subcube[2 * axis + 1] = min(subcube[2 * axis + 1], axis_size[axis]) # Report final subcube boundaries err.message(" Loading subcube of range " + str(subcube) + '.') return subcube
def import_data(doSubcube, inFile, weightsFile, maskFile, weightsFunction=None, subcube=[], subcubeMode="pixel", doFlag=False, flagRegions=False, flagFile="", cubeOnly=False): # Basic sanity checks on user input err.ensure( os.path.isfile(inFile), "Data file not found:\n " + str(inFile)) # ------------------------------- # Open input cube and read header # ------------------------------- err.message("Loading input data cube.") try: f = fits.open(inFile, mode="readonly", memmap=False, do_not_scale_image_data=False) header = f[0].header except: err.error("Failed to load primary HDU of data file:\n " + str(inFile)) # Extract axis sizes and types n_axes, axis_size, axis_type = extract_axis_size(header) # Check dimensionality of data cube check_cube_dimensions(n_axes, axis_size, cube_name="data cube") # Print some information err.message(" Data cube has {0:d} axes.".format(header["NAXIS"])) err.message(" Types: " + str(axis_type)) err.message(" Sizes: " + str(axis_size)) # Extract subcube boundaries if requested if len(subcube): subcube = get_subcube_range(header, n_axes, axis_size, subcube, subcubeMode) else: subcube = [] # -------------------------------- # Read requested subregion of data # -------------------------------- # 2-D image if n_axes == 2: fullshape = [axis_size[1], axis_size[0]] if len(subcube): data = np.array([f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]]]) header["CRPIX1"] -= subcube[0] header["CRPIX2"] -= subcube[2] header["NAXIS1"] = subcube[1] - subcube[0] header["NAXIS2"] = subcube[3] - subcube[2] else: data = np.array([f[0].data]) # 3-D cube elif n_axes == 3: fullshape = [axis_size[2], axis_size[1], axis_size[0]] if len(subcube): data = f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] header["CRPIX1"] -= subcube[0] header["CRPIX2"] -= subcube[2] header["CRPIX3"] -= subcube[4] header["NAXIS1"] = subcube[1] - subcube[0] header["NAXIS2"] = subcube[3] - subcube[2] header["NAXIS3"] = subcube[5] - subcube[4] else: data = f[0].data #4-D hypercube else: fullshape = [axis_size[2], axis_size[1], axis_size[0]] if len(subcube): data = f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] header["CRPIX1"] -= subcube[0] header["CRPIX2"] -= subcube[2] header["CRPIX3"] -= subcube[4] header["NAXIS1"] = subcube[1] - subcube[0] header["NAXIS2"] = subcube[3] - subcube[2] header["NAXIS3"] = subcube[5] - subcube[4] else: data = f[0].section[0] # Close input cube f.close() err.message("Input data cube loaded.") # --------------------------------------------------------- # If no additional actions required, return data and header # --------------------------------------------------------- if cubeOnly: return data, header # --------------------------------------------------- # Otherwise carry out additional actions as requested # --------------------------------------------------- # Weighting if weightsFile: data = apply_weights_file(data, weightsFile, subcube) elif weightsFunction: data = apply_weights_function(data, weightsFunction) # Flagging if doFlag: data = apply_flagging(data, flagFile, flagRegions, subcube) # Masking if maskFile: mask = import_mask(maskFile, header, axis_size, subcube) else: # Create an empty mask if none is provided. mask = np.zeros(data.shape, dtype=bool) return data, header, mask, subcube
def import_data(doSubcube, inFile, weightsFile, maskFile, weightsFunction=None, subcube=[], subcubeMode="pixel", doFlag=False, flagRegions=False, flagFile="", cubeOnly=False): # Basic sanity checks on user input err.ensure(os.path.isfile(inFile), "Data file not found:\n " + str(inFile)) # ------------------------------- # Open input cube and read header # ------------------------------- err.message("Loading input data cube.") try: f = fits.open(inFile, mode="readonly", memmap=False, do_not_scale_image_data=False) header = f[0].header except: err.error("Failed to load primary HDU of data file:\n " + str(inFile)) # Extract axis sizes and types n_axes, axis_size, axis_type = extract_axis_size(header) # Check dimensionality of data cube check_cube_dimensions(n_axes, axis_size, cube_name="data cube") # Print some information err.message(" Data cube has {0:d} axes.".format(header["NAXIS"])) err.message(" Types: " + str(axis_type)) err.message(" Sizes: " + str(axis_size)) # Extract subcube boundaries if requested if len(subcube): subcube = get_subcube_range(header, n_axes, axis_size, subcube, subcubeMode) else: subcube = [] # -------------------------------- # Read requested subregion of data # -------------------------------- # 2-D image if n_axes == 2: fullshape = [axis_size[1], axis_size[0]] if len(subcube): data = np.array( [f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]]]) header["CRPIX1"] -= subcube[0] header["CRPIX2"] -= subcube[2] header["NAXIS1"] = subcube[1] - subcube[0] header["NAXIS2"] = subcube[3] - subcube[2] else: data = np.array([f[0].data]) # 3-D cube elif n_axes == 3: fullshape = [axis_size[2], axis_size[1], axis_size[0]] if len(subcube): data = f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] header["CRPIX1"] -= subcube[0] header["CRPIX2"] -= subcube[2] header["CRPIX3"] -= subcube[4] header["NAXIS1"] = subcube[1] - subcube[0] header["NAXIS2"] = subcube[3] - subcube[2] header["NAXIS3"] = subcube[5] - subcube[4] else: data = f[0].data #4-D hypercube else: fullshape = [axis_size[2], axis_size[1], axis_size[0]] if len(subcube): data = f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] header["CRPIX1"] -= subcube[0] header["CRPIX2"] -= subcube[2] header["CRPIX3"] -= subcube[4] header["NAXIS1"] = subcube[1] - subcube[0] header["NAXIS2"] = subcube[3] - subcube[2] header["NAXIS3"] = subcube[5] - subcube[4] else: data = f[0].section[0] # Close input cube f.close() err.message("Input data cube loaded.") # --------------------------------------------------------- # If no additional actions required, return data and header # --------------------------------------------------------- if cubeOnly: return data, header # --------------------------------------------------- # Otherwise carry out additional actions as requested # --------------------------------------------------- # Weighting if weightsFile: data = apply_weights_file(data, weightsFile, subcube) elif weightsFunction: data = apply_weights_function(data, weightsFunction) # Flagging if doFlag: data = apply_flagging(data, flagFile, flagRegions, subcube) # Masking if maskFile: mask = import_mask(maskFile, header, axis_size, subcube) else: # Create an empty mask if none is provided. mask = np.zeros(data.shape, dtype=bool) return data, header, mask, subcube
def writeMoments(datacube, maskcube, filename, debug, header, compress, write_mom, flagOverwrite): # Exit if nothing is to be done if not any(write_mom): err.warning("No moment maps requested; skipping moment map generation.") return # --------------------------- # Number of detected channels # --------------------------- nrdetchan = (maskcube > 0).sum(axis=0) if np.nanmax(nrdetchan) < 65535: nrdetchan = nrdetchan.astype("int16") else: nrdetchan = nrdetchan.astype("int32") hdu = pyfits.PrimaryHDU(data=nrdetchan, header=header) hdu.header["BUNIT"] = "Nchan" hdu.header["DATAMIN"] = np.nanmin(nrdetchan) hdu.header["DATAMAX"] = np.nanmax(nrdetchan) hdu.header["ORIGIN"] = sofia_version_full glob.delete_header(hdu.header, "CTYPE3") glob.delete_header(hdu.header, "CRPIX3") glob.delete_header(hdu.header, "CRVAL3") glob.delete_header(hdu.header, "CDELT3") name = str(filename) + "_nrch.fits" if compress: name += ".gz" # Check for overwrite flag if not flagOverwrite and os.path.exists(name): err.error("Output file exists: " + str(name) + ".", fatal=False) else: hdu.writeto(name, output_verify="warn", **__astropy_arg_overwrite__) # ---------------------- # Moment 0, 1 and 2 maps # ---------------------- # WARNING: The generation of moment maps will mask the copy of the data cube held # in memory by SoFiA. If you wish to use the original data cube after # this point, please reload it first! datacube[maskcube == 0] = 0 # Regrid cube if necessary if "CELLSCAL" in header and header["CELLSCAL"] == "1/F": err.warning( "CELLSCAL keyword with value of 1/F found.\n" "Will regrid data cube before creating moment images.") datacube = glob.regridMaskedChannels(datacube, maskcube, header) # ALERT: Why are we doing this? #datacube = np.array(datacube, dtype=np.single) # Extract relevant WCS parameters if glob.check_wcs_info(header): width = header["CDELT3"] chan0 = header["CRPIX3"] freq0 = header["CRVAL3"] mom_scale_factor = 1.0 # Velocity if glob.check_header_keywords(glob.KEYWORDS_VELO, header["CTYPE3"]): if not "CUNIT3" in header or header["CUNIT3"].lower() == "m/s": # Assuming m/s and converting to km/s mom_scale_factor = 1.0e-3 unit_spec = "km/s" elif header["CUNIT3"].lower() == "km/s": # Assuming km/s unit_spec = "km/s" else: # Working with whatever velocity units the cube has unit_spec = str(header["CUNIT3"]) # Frequency elif glob.check_header_keywords(glob.KEYWORDS_FREQ, header["CTYPE3"]): if not "CUNIT3" in header or header["CUNIT3"].lower() == "hz": # Assuming Hz unit_spec = "Hz" elif header["CUNIT3"].lower() == "khz": # Assuming kHz and converting to Hz mom_scale_factor = 1.0e+3 unit_spec = "Hz" else: # Working with whatever frequency units the cube has unit_spec = str(header["CUNIT3"]) else: err.warning("Axis descriptors missing from FITS file header.\nMoment maps will not be scaled!") width = 1.0 chan0 = 0.0 freq0 = 0.0 mom_scale_factor = 1.0 unit_spec = "chan" # Prepare moment maps # NOTE: We are making use of NumPy's array broadcasting rules here to avoid # having to cast array sizes to the full 3-D data cube size! moments = [None, None, None] with np.errstate(invalid="ignore"): if any(write_mom): # Definition of moment 0 moments[0] = np.nansum(datacube, axis=0) if write_mom[1] or write_mom[2]: # Definition of moment 1 velArr = ((np.arange(datacube.shape[0]) + 1.0 - chan0) * width + freq0).reshape((datacube.shape[0], 1, 1)) moments[1] = np.divide(np.nansum(velArr * datacube, axis=0), moments[0]) if write_mom[2]: # Definition of moment 2 velArr = velArr - moments[1] moments[2] = np.sqrt(np.divide(np.nansum(velArr * velArr * datacube, axis=0), moments[0])) # Multiply moment 0 by channel width moments[0] *= abs(width) # Set up unit strings if "BUNIT" in header: unit_flux = str(header["BUNIT"]) # Correct for common misspellings of "Jy[/beam]" if unit_flux.lower() == "jy": unit_flux = "Jy." + unit_spec elif unit_flux.lower() == "jy/beam": unit_flux = "Jy/beam." + unit_spec else: unit_flux += "." + unit_spec else: err.warning("Cannot determine flux unit; BUNIT missing from header.") unit_flux = "" unit_mom = [unit_flux, unit_spec, unit_spec] # Writing moment maps to disk for i in range(3): if write_mom[i] and moments[i] is not None: err.message("Writing moment {0:d} image.".format(i)) moments[i] *= mom_scale_factor hdu = pyfits.PrimaryHDU(data=moments[i], header=header) hdu.header["BUNIT"] = unit_mom[i] hdu.header["DATAMIN"] = np.nanmin(moments[i]) hdu.header["DATAMAX"] = np.nanmax(moments[i]) hdu.header["ORIGIN"] = sofia_version_full hdu.header["CELLSCAL"] = "CONSTANT" glob.delete_header(hdu.header, "CRPIX3") glob.delete_header(hdu.header, "CRVAL3") glob.delete_header(hdu.header, "CDELT3") glob.delete_header(hdu.header, "CTYPE3") if debug: hdu.writeto(str(filename) + "_mom{0:d}.debug.fits".format(i), output_verify="warn", **__astropy_arg_overwrite__) else: name = str(filename) + "_mom{0:d}.fits".format(i) if compress: name += ".gz" # Check for overwrite flag if not flagOverwrite and os.path.exists(name): err.error("Output file exists: " + str(name) + ".", fatal=False) else: hdu.writeto(name, output_verify="warn", **__astropy_arg_overwrite__) return
def apply_weights_file(data, weightsFile, subcube): # Load weights cube err.message("Applying weights cube:\n " + str(weightsFile)) try: f = fits.open(weightsFile, memmap=False) header_weights = f[0].header except: err.error("Failed to read weights cube.") # Extract axis sizes and types n_axes_weights, axis_size_weights, axis_type_weights = extract_axis_size( header_weights) # Ensure correct dimensionality check_cube_dimensions(n_axes_weights, axis_size_weights, cube_name="weights cube", min_dim=1, max_dim=4) # Multiply data by weights # 1-D spectrum if n_axes_weights == 1: err.warning( "Weights cube has 1 axis; interpreted as spectrum.\nAdding first and second axis." ) if len(subcube): err.ensure( len(subcube) == 6, "Subcube list must have 6 entries ({0:d} given).".format( len(subcube))) data *= np.reshape(f[0].section[subcube[4]:subcube[5]], (-1, 1, 1)) else: data *= reshape(f[0].data, (-1, 1, 1)) # 2-D image elif n_axes_weights == 2: if len(subcube) == 6 or len(subcube) == 4: data *= np.array( [f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]]]) else: data *= np.array([f[0].data]) # 3-D cube elif n_axes_weights == 3: if len(subcube) == 6: data *= f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: data *= f[0].data # 4-D hypercube else: if len(subcube) == 6: data *= f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]] else: data *= f[0].section[0] f.close() err.message(" Weights cube applied.") return data
def readPipelineOptions(filename="pipeline.options"): # Try to open parameter file try: f = open(filename, "r") except IOError as e: err.error("Failed to read parameter file: " + str(filename) + "\n" + str(e), fatal=True) # Extract lines from parameter file lines = f.readlines() f.close() # Remove leading/trailing whitespace and empty lines lines = [line.strip() for line in lines] # Check for version number for line in lines: if "# Creator: SoFiA" in line: par_file_version = line[17:] sof_file_version = getVersion() if par_file_version != sof_file_version: err.warning( "The parameter file was created with a different version of SoFiA\n" "(" + str(par_file_version) + ") than the one you are currently using (" + str(sof_file_version) + ").\n" "Some settings defined in the parameter file may not be recognised\n" "by SoFiA, which could lead to unexpected results.", frame=True) # Remove comments lines = [line for line in lines if len(line) > 0 and line[0] != "#"] # Some additional setup datatypes = allowedDataTypes() tasks = {} pedantic = True # Controls whether to exit on unrecognised or redefined parameters pedantic_counter = 0 # Loop over all lines: for line in lines: # Extract parameter name and value try: parameter, value = tuple(line.split("=", 1)) parameter = parameter.strip() value = value.split("#")[0].strip() module, parname = tuple(parameter.split(".", 1)) except: err.error("Failed to read parameter: " + str(line) + "\nExpected format: module.parameter = value", fatal=True) # Ensure that module and parameter names are not empty if len(module) < 1 or len(parname) < 1: err.error("Failed to read parameter: " + str(line) + "\nExpected format: module.parameter = value", fatal=True) subtasks = tasks if module not in subtasks: subtasks[module] = {} subtasks = subtasks[module] if parname in subtasks: err.warning("Multiple definitions of parameter " + str(parameter) + " encountered.\nIgnoring all additional definitions.") pedantic_counter += 1 continue if parameter in datatypes: try: if datatypes[parameter] == "bool": subtasks[parname] = str2bool(value) elif datatypes[parameter] == "float": subtasks[parname] = float(value) elif datatypes[parameter] == "int": subtasks[parname] = int(value) elif datatypes[parameter] == "array": subtasks[parname] = literal_eval(value) else: subtasks[parname] = str(value) except: err.error("Failed to parse parameter value:\n" + str(line) + "\nExpected data type: " + str(datatypes[parameter]), fatal=True) if parameter == "pipeline.pedantic": pedantic = subtasks[parname] # Update 'pedantic' setting else: err.warning("Ignoring unknown parameter: " + str(parameter) + " = " + str(value)) pedantic_counter += 1 continue if pedantic and pedantic_counter: err.error( "Multiply-defined or unrecognised parameter(s) encountered.\nPlease check your parameter file or set pipeline.pedantic = false\nto ignore unknown or already defined parameters.", fatal=True) return tasks
def apply_flagging(data, flagFile, flagRegions, subcube): # ------------------------------- # Apply flagging cube if provided # ------------------------------- if flagFile: err.message("Applying flagging cube:\n " + str(flagFile)) try: f = fits.open(flagFile, memmap=False) header_flags = f[0].header except: err.error("Failed to read flagging cube.") # Extract axis sizes and types n_axes_flags, axis_size_flags, axis_type_flags = extract_axis_size( header_flags) # Ensure correct dimensionality check_cube_dimensions(n_axes_flags, axis_size_flags, cube_name="flagging cube") # Apply flagging # 2-D image if n_axes_flags == 2: for chan in range(data.shape[0]): if len(subcube) == 6 or len(subcube) == 4: data[chan][np.isnan( f[0].section[subcube[2]:subcube[3], subcube[0]:subcube[1]])] = np.nan else: data[chan][np.isnan(np.array([f[0].data]))] = np.nan # 3-D cube elif n_axes_flags == 3: if len(subcube) == 6: data[np.isnan(f[0].section[subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]])] = np.nan else: data[np.isnan(f[0].data)] = np.nan # 4-D hypercube else: if len(subcube) == 6: data[np.isnan(f[0].section[0, subcube[4]:subcube[5], subcube[2]:subcube[3], subcube[0]:subcube[1]])] = np.nan else: data[np.isnan(f[0].section[0])] = np.nan f.close() err.message("Flagging cube applied.") # ---------------------------------- # Apply flagging regions if provided # ---------------------------------- if flagRegions: err.message("Applying flagging regions:\n " + str(flagRegions)) dim = len(data.shape) try: for region in flagRegions: for i in range(0, len(region) / 2): if region[2 * i + 1] == "": region[2 * i + 1] = data.shape[dim - i - 1] if len(region) == 2: data[0, region[2]:region[3], region[0]:region[1]] = np.nan else: data[region[4]:region[5], region[2]:region[3], region[0]:region[1]] = np.nan err.message("Flagging regions applied.") except: err.error( "Flagging did not succeed. Please check the dimensions\nof your data cube and flagging regions." ) return data
def EstimateRel(data, pdfoutname, parNames, parSpace=["snr_sum", "snr_max", "n_pix"], logPars=[1, 1, 1], autoKernel=True, scaleKernel=1, negPerBin=1, skellamTol=-0.5, kernel=[0.15, 0.05, 0.1], usecov=False, doscatter=1, docontour=1, doskellam=1, dostats=0, saverel=1, threshold=0.99, fMin=0, verb=0, makePlot=False): # Always work on logarithmic parameter values; the reliability.logPars parameter should be removed if 0 in logPars: err.warning(" Setting all reliability.logPars entries to 1. This parameter is no longer editable by users.") logPars=[1 for pp in parSpace] # Import Matplotlib if diagnostic plots requested if makePlot: import matplotlib # The following line is necessary to run SoFiA remotely matplotlib.use("Agg") import matplotlib.pyplot as plt # -------------------------------- # Build array of source parameters # -------------------------------- idCOL = parNames.index("id") ftotCOL = parNames.index("snr_sum") fmaxCOL = parNames.index("snr_max") fminCOL = parNames.index("snr_min") # Get columns of requested parameters parCol = [] for ii in range(len(parSpace)): parCol.append(parNames.index(parSpace[ii])) # Get position and number of positive and negative sources pos = data[:, ftotCOL] > 0 neg = data[:, ftotCOL] <= 0 Npos = pos.sum() Nneg = neg.sum() err.ensure(Npos, "No positive sources found; cannot proceed.") err.ensure(Nneg, "No negative sources found; cannot proceed.") # Get array of relevant source parameters (and take log of them if requested) ids = data[:,idCOL] pars = np.empty((data.shape[0], 0)) for ii in range(len(parSpace)): if parSpace[ii] == "snr_max": parsTmp = data[:,fmaxCOL] * pos - data[:,fminCOL] * neg if logPars[ii]: parsTmp = np.log10(parsTmp) pars = np.concatenate((pars, parsTmp.reshape(-1, 1)), axis=1) elif parSpace[ii] == "snr_sum" or parSpace[ii] == "snr_mean": parsTmp = abs(data[:,parCol[ii]].reshape(-1, 1)) if logPars[ii]: parsTmp = np.log10(parsTmp) pars = np.concatenate((pars, parsTmp), axis=1) else: parsTmp = data[:,parCol[ii]].reshape(-1, 1) if logPars[ii]: parsTmp = np.log10(parsTmp) pars = np.concatenate((pars, parsTmp), axis=1) err.message(" Working in parameter space {0:}".format(str(parSpace))) err.message(" Will convolve the distribution of positive and negative sources in this space to derive the P and N density fields") pars = np.transpose(pars) # ---------------------------------------------------------- # Set parameters to work with and gridding/plotting for each # ---------------------------------------------------------- # Axis labels when plotting labs = [] for ii in range(len(parSpace)): labs.append("") if logPars[ii]: labs[ii] += "log " labs[ii] += parSpace[ii] # Axis limits when plotting pmin, pmax = pars.min(axis=1), pars.max(axis=1) pmin, pmax = pmin - 0.1 * (pmax - pmin), pmax + 0.1 * (pmax - pmin) lims = [[pmin[i], pmax[i]] for i in range(len(parSpace))] # Grid on which to evaluate Np and Nn in order to plot contours grid = [[pmin[i], pmax[i], 0.02 * (pmax[i] - pmin[i])] for i in range(len(parSpace))] # Calculate the number of rows and columns in figure projections = [subset for subset in combinations(range(len(parSpace)), 2)] nr = int(np.floor(np.sqrt(len(projections)))) nc = int(np.ceil(float(len(projections)) / nr)) # --------------------------------------- # Set smoothing kernel in parameter space # --------------------------------------- # If autoKernel is True, then the initial kernel is taken as a scaled version of the covariance matrix # of the negative sources. The kernel size along each axis is such that the number of sources per kernel # width (sigma**2) is equal to "negPerBin". Optionally, the user can decide to use only the diagonal # terms of the covariance matrix. The kernel is then grown until convergence is reached on the Skellam # plot. If autoKernel is False, then use the kernel given by "kernel" parameter (argument of EstimateRel); # this is sigma, and is squared to be consistent with the auto kernel above. if autoKernel: # Set the kernel shape to that of the variance or covariance matrix kernel = np.cov(pars[:, neg]) kernelType = "covariance" # Check if kernel matrix can be inverted try: np.linalg.inv(kernel) except: err.error( "The reliability cannot be calculated because the smoothing kernel\n" "derived from " + str(pars[:,neg].shape[1]) + " negative sources cannot be inverted.\n" "This is likely due to an insufficient number of negative sources.\n" "Try to increase the number of negative sources by changing the\n" "source finding and/or filtering settings.", fatal=True, frame=True) if np.isnan(kernel).sum(): err.error( "The reliability cannot be calculated because the smoothing kernel\n" "derived from " + str(pars[:,neg].shape[1]) + " negative sources contains NaNs.\n" "A good kernel is required to calculate the density field of positive\n" "and negative sources in parameter space.\n" "Try to increase the number of negative sources by changing the\n" "source finding and/or filtering settings.", fatal=True, frame=True) if not usecov: kernel = np.diag(np.diag(kernel)) kernelType = "variance" kernelIter = 0.0 deltplot = [] # Scale the kernel size as requested by the user (scaleKernel>0) or use the autoscale algorithm (scaleKernel=0) if scaleKernel>0: # Scale kernel size as requested by the user # Note that the scale factor is squared because users are asked to give a factor to apply to sqrt(kernel) kernel *= scaleKernel**2 err.message(" Using the {0:s} matrix scaled by a factor {1:.2f} as convolution kernel".format(kernelType, scaleKernel)) err.message(" The sqrt(kernel) size is:") err.message(" " + str(np.sqrt(np.abs(kernel)))) elif scaleKernel==0: # Scale kernel size to get started the kernel-growing loop # The scale factor for sqrt(kernel) is elevated to the power of 1.0 / len(parCol) err.message(" Will search for the best convolution kernel by scaling the {0:s} matrix".format(kernelType)) err.message(" The {0:s} matrix has sqrt:".format(kernelType)) err.message(" " + str(np.sqrt(np.abs(kernel)))) # negPerBin must be >=1 err.ensure(negPerBin>=1,"The parameter reliability.negPerBin used to start the convolution kernel search was set to {0:.1f} but must be >= 1. Please change your settings.".format(negPerBin)) kernel *= ((negPerBin + kernelIter) / Nneg)**(2.0 / len(parCol)) err.message(" Search starting from the kernel with sqrt:") err.message(" " + str(np.sqrt(np.abs(kernel)))) err.message(" Iteratively growing kernel until the distribution of (P-N)/sqrt(P+N) reaches median/width = {0:.2f} ...".format(skellamTol)) err.ensure(skellamTol<=0,"The parameter reliability.skellamTol was set to {0:.2f} but must be <= 0. Please change your settings.".format(skellamTol)) else: err.ensure(scaleKernel>=0,\ "The reliability.scaleKernel parameter cannot be negative.\n"\ "It should be = 0 if you want SoFiA to find the optimal kernel scaling\n"\ "or > 0 if you want to set the scaling yourself.\n"\ "Please change your settings.") #deltOLD=-1e+9 # Used to stop kernel growth if P-N stops moving closer to zero [NOT USED CURRENTLY] if doskellam and makePlot: fig0 = plt.figure() else: # Note that the user must give sigma, which then gets squared err.message(" Using user-defined variance kernel with sqrt(kernel) size: {0}".format(kernel)) err.ensure(len(parSpace)==len(kernel),"The number of entries in the kernel above does not match the number of parameters you requested for the reliability calculation.") kernel = np.identity(len(kernel)) * np.array(kernel)**2 # Set grow_kernel to 1 to start the kernel growing loop below. grow_kernel = 1 # This loop will estimate the reliability, check whether the kernel is large enough, # and if not pick a larger kernel. If autoKernel = 0 or scaleKernel = 0, we will do # just one pass (i.e., we will not grow the kernel). while grow_kernel: # ------------------------ # Evaluate N-d reliability # ------------------------ if verb: err.message(" estimate normalised positive and negative density fields ...") Np = gaussian_kde_set_covariance(pars[:,pos], kernel) Nn = gaussian_kde_set_covariance(pars[:,neg], kernel) # Calculate the number of positive and negative sources at the location of positive sources Nps = Np(pars[:,pos]) * Npos Nns = Nn(pars[:,pos]) * Nneg # Calculate the number of positive and negative sources at the location of negative sources nNps = Np(pars[:,neg]) * Npos nNns = Nn(pars[:,neg]) * Nneg # Calculate the reliability at the location of positive sources Rs = (Nps - Nns) / Nps # The reliability must be <= 1. If not, something is wrong. err.ensure(Rs.max() <= 1, "Maximum reliability greater than 1; something is wrong.\nPlease ensure that enough negative sources are detected\nand decrease your source finding threshold if necessary.", frame=True) # Find pseudo-reliable sources (taking maximum(Rs, 0) in order to include objects with Rs < 0 # if threshold == 0; Rs may be < 0 because of insufficient statistics) # These are called pseudo-reliable because some objects may be discarded later based on additional criteria below pseudoreliable = np.maximum(Rs, 0) >= threshold # Find reliable sources (taking maximum(Rs, 0) in order to include objects with Rs < 0 if # threshold == 0; Rs may be < 0 because of insufficient statistics) #reliable=(np.maximum(Rs, 0)>=threshold) * (data[pos, ftotCOL].reshape(-1,) > fMin) * (data[pos, fmaxCOL].reshape(-1,) > 4) reliable = (np.maximum(Rs, 0) >= threshold) * ((data[pos, ftotCOL] / np.sqrt(data[pos, parNames.index("n_pix")])).reshape(-1,) > fMin) if autoKernel: # Calculate quantities needed for comparison to Skellam distribution delt = (nNps - nNns) / np.sqrt(nNps + nNns) deltstd = delt.std() deltmed = np.median(delt) deltmin = delt.min() deltmax = delt.max() if deltmed / deltstd > -100 and doskellam and makePlot: plt.hist(delt / deltstd, bins=np.arange(deltmin / deltstd, max(5.1, deltmax / deltstd), 0.01), cumulative=True, histtype="step", color=(min(1, float(max(1.,negPerBin) + kernelIter) / Nneg), 0,0), normed=True) deltplot.append([((max(1.,negPerBin) + kernelIter) / Nneg)**(1.0 / len(parCol)), deltmed / deltstd]) if scaleKernel: grow_kernel = 0 else: err.message(" iteration, median, width, median/width = %3i, %9.2e, %9.2e, %9.2e" % (kernelIter, deltmed, deltstd, deltmed / deltstd)) if deltmed / deltstd > skellamTol or negPerBin + kernelIter >= Nneg: grow_kernel = 0 err.message(" Found good kernel after %i kernel growth iterations. The sqrt(kernel) size is:" % kernelIter) err.message(np.sqrt(np.abs(kernel))) elif deltmed / deltstd < 5 * skellamTol: kernel *= (float(negPerBin + kernelIter + 20) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 20 elif deltmed / deltstd < 2 * skellamTol: kernel *= (float(negPerBin + kernelIter + 10) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 10 elif deltmed / deltstd < 1.5 * skellamTol: kernel *= (float(negPerBin + kernelIter + 3) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 3 else: kernel *= (float(negPerBin + kernelIter + 1) / (negPerBin + kernelIter))**(2.0 / len(parCol)) kernelIter += 1 else: grow_kernel = 0 # ------------ # Skellam plot # ------------ if autoKernel and deltmed / deltstd > -100 and doskellam and makePlot: plt.plot(np.arange(-10, 10, 0.01), stats.norm().cdf(np.arange(-10, 10, 0.01)), "k-") plt.plot(np.arange(-10, 10, 0.01), stats.norm(scale=0.4).cdf(np.arange(-10, 10, 0.01)), "k:") plt.legend(("Gaussian (sigma=1)", "Gaussian (sigma=0.4)"), loc="lower right", prop={"size":13}) plt.hist(delt / deltstd, bins=np.arange(deltmin / deltstd, max(5.1, deltmax / deltstd), 0.01), cumulative=True, histtype="step", color="r", normed=True) plt.xlim(-5, 5) plt.ylim(0, 1) plt.xlabel("(P-N)/sqrt(N+P)") plt.ylabel("cumulative distribution") plt.plot([0, 0], [0, 1], "k--") fig0.savefig("%s_rel_skellam.pdf" % pdfoutname, rasterized=True) if not scaleKernel: fig3 = plt.figure() deltplot = np.array(deltplot) plt.plot(deltplot[:,0], deltplot[:,1], "ko-") plt.xlabel("kernel size (1D-sigma, aribtrary units)") plt.ylabel("median/std of (P-N)/sqrt(P+N)") plt.axhline(y=skellamTol, linestyle="--", color="r") fig3.savefig("%s_rel_skellam-delta.pdf" % pdfoutname, rasterized=True) # ----------------------- # Scatter plot of sources # ----------------------- specialids = [] if doscatter and makePlot: if verb: err.message(" plotting sources ...") fig1 = plt.figure(figsize=(18, 4.5 * nr)) plt.subplots_adjust(left=0.06, bottom=0.15/nr, right = 0.97, top=1-0.08/nr, wspace=0.35, hspace=0.25) n_p = 0 for jj in projections: if verb: err.message(" projection %i/%i" % (projections.index(jj) + 1, len(projections))) n_p, p1, p2 = n_p + 1, jj[0], jj[1] plt.subplot(nr, nc, n_p) plt.scatter(pars[p1,pos], pars[p2,pos], marker="o", c="b", s=10, edgecolor="face", alpha=0.5) plt.scatter(pars[p1,neg], pars[p2,neg], marker="o", c="r", s=10, edgecolor="face", alpha=0.5) for si in specialids: plt.plot(pars[p1, ids==si], pars[p2, ids==si], "kd", zorder=10000, ms=7, mfc="none", mew=2) # Plot Integrated SNR threshold if fMin>0 and (parSpace[jj[0]],parSpace[jj[1]])==("snr_sum","snr_mean"): xArray=np.arange(lims[p1][0],lims[p1][1]+(lims[p1][1]-lims[p1][0])/100,(lims[p1][1]-lims[p1][0])/100) plt.plot(xArray,np.log10(fMin)*2-xArray,'k:') elif fMin>0 and (parSpace[jj[0]],parSpace[jj[1]])==("snr_mean","snr_sum"): yArray=np.arange(lims[p2][0],lims[p2][1]+(lims[p2][1]-lims[p2][0])/100,(lims[p2][1]-lims[p2][0])/100) plt.plot(np.log10(fMin)*2-yArray,yArray,'k:') plt.xlim(lims[p1][0], lims[p1][1]) plt.ylim(lims[p2][0], lims[p2][1]) plt.xlabel(labs[p1]) plt.ylabel(labs[p2]) plt.grid(color='k',linestyle='-',linewidth=0.2) fig1.savefig("%s_rel_scatter.pdf" % pdfoutname, rasterized=True) # ------------- # Plot contours # ------------- if docontour and makePlot: levs = 10**np.arange(-1.5, 2, 0.5) if verb: err.message(" plotting contours ...") fig2 = plt.figure(figsize=(18, 4.5 * nr)) plt.subplots_adjust(left=0.06, bottom=0.15/nr, right=0.97, top=1-0.08/nr, wspace=0.35, hspace=0.25) n_p = 0 for jj in projections: if verb: err.message(" projection %i/%i" % (projections.index(jj) + 1, len(projections))) n_p, p1, p2 = n_p + 1, jj[0], jj[1] g1, g2 = grid[p1], grid[p2] x1 = np.arange(g1[0], g1[1], g1[2]) x2 = np.arange(g2[0], g2[1], g2[2]) pshape = (x2.shape[0], x1.shape[0]) # Get array of source parameters on current projection parsp = np.concatenate((pars[p1:p1+1], pars[p2:p2+1]), axis=0) # Derive Np and Nn density fields on the current projection setcov = kernel[p1:p2+1:p2-p1,p1:p2+1:p2-p1] try: Np = gaussian_kde_set_covariance(parsp[:,pos], setcov) Nn = gaussian_kde_set_covariance(parsp[:,neg], setcov) except: err.error( "Reliability determination failed because of issues with the\n" "smoothing kernel. This is likely due to an insufficient number\n" "of negative detections. Please review your filtering and source\n" "finding settings to ensure that a sufficient number of negative\n" "detections is found.", fatal=True, frame=True) # Evaluate density fields on grid on current projection g = np.transpose(np.transpose(np.mgrid[slice(g1[0], g1[1], g1[2]), slice(g2[0], g2[1], g2[2])]).reshape(-1, 2)) Np = Np(g) Nn = Nn(g) Np = Np / Np.sum() * Npos Nn = Nn / Nn.sum() * Nneg Np.resize(pshape) Nn.resize(pshape) plt.subplot(nr, nc, n_p) plt.contour(x1, x2, Np, origin="lower", colors="b", levels=levs, zorder=2) plt.contour(x1, x2, Nn, origin="lower", colors="r", levels=levs, zorder=1) # Plot Integrated SNR threshold if fMin>0 and (parSpace[jj[0]],parSpace[jj[1]])==("snr_sum","snr_mean"): xArray=np.arange(lims[p1][0],lims[p1][1]+(lims[p1][1]-lims[p1][0])/100,(lims[p1][1]-lims[p1][0])/100) plt.plot(xArray,np.log10(fMin)*2-xArray,'k:') elif fMin>0 and (parSpace[jj[0]],parSpace[jj[1]])==("snr_mean","snr_sum"): yArray=np.arange(lims[p2][0],lims[p2][1]+(lims[p2][1]-lims[p2][0])/100,(lims[p2][1]-lims[p2][0])/100) plt.plot(np.log10(fMin)*2-yArray,yArray,'k:') if reliable.sum(): plt.scatter(pars[p1,pos][reliable], pars[p2,pos][reliable], marker="o", s=10, edgecolor="k", facecolor="k", zorder=4) if (pseudoreliable * (reliable == False)).sum(): plt.scatter(pars[p1,pos][pseudoreliable * (reliable == False)], pars[p2,pos][pseudoreliable * (reliable == False)], marker="x", s=40, edgecolor="0.5", facecolor="0.5", zorder=3) for si in specialids: plt.plot(pars[p1,ids==si], pars[p2,ids==si], "kd", zorder=10000, ms=7, mfc="none", mew=2) plt.xlim(lims[p1][0], lims[p1][1]) plt.ylim(lims[p2][0], lims[p2][1]) plt.xlabel(labs[p1]) plt.ylabel(labs[p2]) plt.grid(color='k',linestyle='-',linewidth=0.2) fig2.savefig("%s_rel_contour.pdf" % pdfoutname, rasterized=True) # ------------------------- # Add Np, Nn and R to table # ------------------------- # This allows me not to calculate R every time I want to do some plot analysis, # but just read it from the file if saverel: if not (docontour or dostats): Nps = Np(pars[:,pos]) * Npos Nns = Nn(pars[:,pos]) * Nneg Np = np.zeros((data.shape[0],)) Np[pos] = Nps Nn = np.zeros((data.shape[0],)) Nn[pos] = Nns R = -np.ones((data.shape[0],)) # R will be -1 for negative sources # Set R to zero for positive sources if R < 0 because of Nn > Np R[pos] = np.maximum(0, (Np[pos] - Nn[pos]) / Np[pos]) data = np.concatenate((data, Np.reshape(-1, 1), Nn.reshape(-1, 1), R.reshape(-1, 1)), axis=1) data = [list(jj) for jj in list(data)] return data, ids[pos][reliable].astype(int)
def write_catalog_from_array(mode, objects, catHeader, catUnits, catFormat, parList, outName, flagCompress, flagOverwrite, flagUncertainties): # Check output format and compression availableModes = ["ASCII", "XML", "SQL"] if mode not in availableModes: err.warning("Unknown catalogue format: " + str(mode) + ". Defaulting to ASCII.") mode = "ASCII" modeIndex = availableModes.index(mode) if flagCompress: outName += ".gz" err.message("Writing " + availableModes[modeIndex] + " catalogue: " + outName + ".") # Exit if file exists and overwrite flag is set to false func.check_overwrite(outName, flagOverwrite, fatal=True) # Do we need to write all parameters? if parList == ["*"] or not parList: parList = list(catHeader) # Remove undefined parameters parList = [item for item in parList if item in catHeader] # Remove statistical uncertainties if not requested if not flagUncertainties: for item in ["err_x", "err_y", "err_z", "err_w20", "err_w50"]: while item in parList: parList.remove(item) # Check whether there is anything left if not len(parList): err.error( "No valid output parameters selected. No output catalogue written.", fatal=False) return # Create and write catalogue in requested format # ------------------------------------------------------------------------- if mode == "XML": # Define basic XML header information votable = Element("VOTABLE") resource = SubElement(votable, "RESOURCE", name="SoFiA catalogue (version %s)" % sofia_version) description = SubElement(resource, "DESCRIPTION") description.text = "Source catalogue from the Source Finding Application (SoFiA) version %s" % sofia_version coosys = SubElement(resource, "COOSYS", ID="J2000") table = SubElement(resource, "TABLE", ID="sofia_cat", name="sofia_cat") # Load list of parameters and unified content descriptors (UCDs) ucdList = {} fileUcdPath = os.environ["SOFIA_PIPELINE_PATH"] fileUcdPath = fileUcdPath.replace("sofia_pipeline.py", "SoFiA_source_parameters.dat") try: with open(fileUcdPath) as fileUcd: for line in fileUcd: (key, value) = line.split() ucdList[key] = value except: err.warning("Failed to read UCD file.") # Create parameter fields for par in parList: ucdEntity = ucdList[par] if par in ucdList else "" index = list(catHeader).index(par) if catFormat[index] == "%30s": field = SubElement(table, "FIELD", name=par, ucd=ucdEntity, datatype="char", arraysize="30", unit=catUnits[index]) else: field = SubElement(table, "FIELD", name=par, ucd=ucdEntity, datatype="float", unit=catUnits[index]) # Create data table entries data = SubElement(table, "DATA") tabledata = SubElement(data, "TABLEDATA") for obj in objects: tr = SubElement(tabledata, "TR") for par in parList: td = SubElement(tr, "TD") index = list(catHeader).index(par) td.text = (catFormat[index] % obj[index]).strip() # Write XML catalogue: try: f1 = gzopen(outName, "wb") if flagCompress else open(outName, "w") except: err.error("Failed to write to XML catalogue: " + outName + ".", fatal=False) return f1.write(prettify(votable)) #f1.write(tostring(votable, "utf-8")) // without prettifying, which is faster and uses much less memory f1.close # -----------------------------------------------------------------End-XML- elif mode == "SQL": # Record if there is an ID column in the catalogue # (if no ID is present, we will later create one for use as primary key) noID = "id" not in parList # Write some header information: content = "-- SoFiA catalogue (version %s)\n\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n\n" % sofia_version # Construct and write table structure: flagProgress = False content += "CREATE TABLE IF NOT EXISTS `SoFiA-Catalogue` (\n" if noID: content += " `id` INT NOT NULL,\n" for par in parList: index = list(catHeader).index(par) if flagProgress: content += ",\n" content += " " + sqlHeaderItem(par) + sqlFormat(catFormat[index]) flagProgress = True content += ",\n PRIMARY KEY (`id`),\n KEY (`id`)\n) DEFAULT CHARSET=utf8 COMMENT=\'SoFiA source catalogue\';\n\n" # Insert data: flagProgress = False content += "INSERT INTO `SoFiA-Catalogue` (" if noID: content += "`id`, " for par in parList: if flagProgress: content += ", " content += sqlHeaderItem(par) flagProgress = True content += ") VALUES\n" source_count = 0 for obj in objects: flagProgress = False source_count += 1 content += "(" if noID: content += str(source_count) + ", " for par in parList: index = list(catHeader).index(par) if flagProgress: content += ", " content += sqlDataItem(obj[index], catFormat[index]) flagProgress = True if (source_count < len(objects)): content += "),\n" else: content += ");\n" # Write catalogue try: fp = gzopen(outName, "wb") if flagCompress else open(outName, "w") except: err.error("Failed to write to SQL catalogue: " + outName + ".", fatal=False) return fp.write(content) fp.close() # -----------------------------------------------------------------End-SQL- else: # mode == "ASCII" by default # Determine header sizes based on variable-length formatting lenCathead = [] for j in catFormat: lenCathead.append( int( j.split("%")[1].split("e")[0].split("f")[0].split("i") [0].split("d")[0].split(".")[0].split("s")[0]) + 1) # Create header headerName = "" headerUnit = "" headerCol = "" outFormat = "" colCount = 0 header = "SoFiA catalogue (version %s)\n" % sofia_version for par in parList: index = list(catHeader).index(par) headerName += catHeader[index].rjust(lenCathead[index]) headerUnit += catUnits[index].rjust(lenCathead[index]) headerCol += ("(%i)" % (colCount + 1)).rjust(lenCathead[index]) outFormat += catFormat[index] + " " colCount += 1 header += headerName[3:] + '\n' + headerUnit[3:] + '\n' + headerCol[3:] # Create catalogue outObjects = [] for obj in objects: outObjects.append([]) for par in parList: outObjects[-1].append(obj[list(catHeader).index(par)]) # Write ASCII catalogue try: np.savetxt(outName, np.array(outObjects, dtype=object), fmt=outFormat, header=header) except: err.error("Failed to write to ASCII catalogue: " + outName + ".", fatal=False) return # ---------------------------------------------------------------End-ASCII- return
def check_overwrite(filename, flagOverwrite, fatal=False): if not flagOverwrite and os.path.exists(filename): err.error("Output file exists: " + filename + ".", fatal=fatal) return False return True