code stringlengths 1 18.2k |
|---|
must be used, otherwise an error will be thrown.''' fai_files = {ref_fai, qry_fai} if None in fai_files and len(fai_files) != 1: print(fai_files) raise Error('Error in convert_to_msp_crunch. Must use both of ref_fai and qry_fai, or neither of them') if ref_fai is not None: assert qry_fai is not None ref_offsets = pyfas... |
ref_fai is not None: aln.ref_start += ref_offsets[aln.ref_name] aln.ref_end += ref_offsets[aln.ref_name] aln.qry_start += qry_offsets[aln.qry_name] aln.qry_end += qry_offsets[aln.qry_name] print(aln.to_msp_crunch(), file=f_out) pyfastaq.utils.close(f_out) |
def _request(self, method, url, params=None, headers=None, data=None): """Common handler for all the HTTP requests.""" if not params: params = {} # set default headers if not headers: headers = { 'accept': '*/*' } if method == 'POST' or method == 'PUT': headers.update({'Content-Type': 'application/json'}) try: response... |
response_code // 100 == 2 else False if response.text: try: data = response.json() except ValueError: data = response.content else: data = '' response_headers = response.headers return BurpResponse(success=success, response_code=response_code, data=data, response_headers=response_headers) except ValueError as e: return... |
handling the request. {}'.format(response.content), success=False) except Exception as e: return BurpResponse(success=False, message='Eerror is %s' % e) |
def user_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text also works: :: :user:`Steven Lor... |
title = utils.unescape(title).strip() config = inliner.document.settings.env.app.config if config.issues_user_uri: ref = config.issues_user_uri.format(user=target) else: ref = "https://github.com/{0}".format(target) if has_explicit_title: text = title else: text = "@{0}".format(target) link = nodes.reference(text=text,... |
def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a CVE on https://cve.mitre.org. Examples: :: :cve:`CVE-2018-17175` """ options = options or {} content = content or [] has_explicit_title, title, target = split_explicit_title(text) target = utils.unescape(targ... |
def list_line(self, line): """ Write the given iterable of values (line) to the file as items on the same line. Any argument that stringifies to a string legal as a TSV data item can be written. Does not copy the line or build a big string in memory. """ if len(line) == 0: return self.stream.write(str(line[0])) for ite... |
def prepare(doc): """ Parse metadata to obtain list of mustache templates, then load those templates. """ doc.mustache_files = doc.get_metadata('mustache') if isinstance(doc.mustache_files, basestring): # process single YAML value stored as string if not doc.mustache_files: doc.mustache_files = None # switch empty stri... |
the_file.write('\n') if doc.mustache_files is not None: doc.mustache_hashes = [yaml.load(open(file, 'r').read()) for file in doc.mustache_files] doc.mhash = { k: v for mdict in doc.mustache_hashes for k, v in mdict.items() } # combine list of dicts into a single dict doc.mrenderer = pystache.Renderer(escape=lambda u: u... |
def action(elem, doc): """ Apply combined mustache template to all strings in document. """ if type(elem) == Str and doc.mhash is not None: elem.text = doc.mrenderer.render(elem.text, doc.mhash) return elem |
def get_callback(self, renderer_context): """ Determine the name of the callback to wrap around the json output. """ request = renderer_context.get('request', None) params = request and get_query_params(request) or {} return params.get(self.callback_parameter, self.default_callback) |
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders into jsonp, wrapping the json output in a callback function. Clients may set the callback function name using a query parameter on the URL, for example: ?callback=exampleCallbackName """ renderer_context = renderer_context or {} callba... |
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Loading raw data for ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE) if measurement is not None: if measurement.infl... |
} } for name, data in measurement.data.items() } return data, 200 else: return None, 404 else: return None, 404 |
def to_jd(year, week, day): '''Return Julian day count of given ISO year, week, and day''' return day + n_weeks(SUN, gregorian.to_jd(year - 1, 12, 28), week) |
def from_jd(jd): '''Return tuple of ISO (year, week, day) for Julian day''' year = gregorian.from_jd(jd)[0] day = jwday(jd) + 1 dayofyear = ordinal.from_jd(jd)[1] week = trunc((dayofyear - day + 10) / 7) # Reset year if week < 1: week = weeks_per_year(year - 1) year = year - 1 # Check that year actually has 53 weeks el... |
53: week = 1 year = year + 1 return year, week, day |
def weeks_per_year(year): '''Number of ISO weeks in a year''' # 53 weeks: any year starting on Thursday and any leap year starting on Wednesday jan1 = jwday(gregorian.to_jd(year, 1, 1)) if jan1 == THU or (jan1 == WED and isleap(year)): return 53 else: return 52 |
def stsci(hdulist): """For STScI GEIS files, need to do extra steps.""" instrument = hdulist[0].header.get('INSTRUME', '') # Update extension header keywords if instrument in ("WFPC2", "FOC"): rootname = hdulist[0].header.get('ROOTNAME', '') filetype = hdulist[0].header.get('FILETYPE', '') for i in range(1, len(hdulist... |
hdulist[i].header['EXPNAME'] = (rootname, "9 character exposure identifier") hdulist[i].header['EXTVER']= (i, "extension version number") hdulist[i].header['EXTNAME'] = (filetype, "extension name") hdulist[i].header['INHERIT'] = (True, "inherit the primary header") hdulist[i].header['ROOTNAME'] = (rootname, "rootname o... |
def stsci2(hdulist, filename): """For STScI GEIS files, need to do extra steps.""" # Write output file name to the primary header instrument = hdulist[0].header.get('INSTRUME', '') if instrument in ("WFPC2", "FOC"): hdulist[0].header['FILENAME'] = filename |
def readgeis(input): """Input GEIS files "input" will be read and a HDUList object will be returned. The user can use the writeto method to write the HDUList object to a FITS file. """ global dat cardLen = fits.Card.length # input file(s) must be of the form *.??h and *.??d if input[-1] != 'h' or input[-4] != '.': rais... |
% input data_file = input[:-1]+'d' _os = sys.platform if _os[:5] == 'linux' or _os[:5] == 'win32' or _os[:5] == 'sunos' or _os[:3] == 'osf' or _os[:6] == 'darwin': bytes_per_line = cardLen+1 else: raise "Platform %s is not supported (yet)." % _os geis_fmt = {'REAL':'f', 'INTEGER':'i', 'LOGICAL':'i','CHARACTER':'S'} end... |
= [] while 1: line = im.read(bytes_per_line)[:cardLen] line = line[:8].upper() + line[8:] if line == end_card: break cards.append(fits.Card.fromstring(line)) phdr = fits.Header(cards) im.close() _naxis0 = phdr.get('NAXIS', 0) _naxis = [phdr['NAXIS'+str(j)] for j in range(1, _naxis0+1)] _naxis.insert(0, _naxis0) _bitpix... |
8 else: data_size = 0 group_size = data_size + _psize // 8 # decode the group parameter definitions, # group parameters will become extension header groups = phdr['GROUPS'] gcount = phdr['GCOUNT'] pcount = phdr['PCOUNT'] formats = [] bools = [] floats = [] _range = range(1, pcount+1) key = [phdr['PTYPE'+str(j)] for j i... |
parameter definition header keywords _list = ['PTYPE'+str(j) for j in _range] + \ ['PDTYPE'+str(j) for j in _range] + \ ['PSIZE'+str(j) for j in _range] + \ ['DATATYPE', 'PSIZE', 'GCOUNT', 'PCOUNT', 'BSCALE', 'BZERO'] # Construct record array formats for the group parameters # as interpreted from the Primary header fil... |
_type = pdtype[:star] _bytes = pdtype[star+1:] # collect boolean keywords since they need special attention later if _type == 'LOGICAL': bools.append(i) if pdtype == 'REAL*4': floats.append(i) fmt = geis_fmt[_type] + _bytes formats.append((ptype,fmt)) _shape = _naxis[1:] _shape.reverse() _code = fits.BITPIX2DTYPE[_bitp... |
the end, so it will not conflict with previous delete for i in range(len(phdr)-1, -1, -1): if phdr.cards[i].keyword in _list: del phdr[i] # clean up other primary header keywords phdr['SIMPLE'] = True phdr['BITPIX'] = 16 phdr['GROUPS'] = False _after = 'NAXIS' if _naxis0 > 0: _after += str(_naxis0) phdr.set('EXTEND', v... |
fits.HDUList([fits.PrimaryHDU(header=phdr, data=None)]) # Use copy-on-write for all data types since byteswap may be needed # in some platforms. f1 = open(data_file, mode='rb') dat = f1.read() # dat = memmap(data_file, mode='c') hdulist.mmobject = dat errormsg = "" loc = 0 for k in range(gcount): ext_dat = numpy.fromst... |
or infs which might indicate # a byte-swapping problem, such as being written out on little-endian # and being read in on big-endian or vice-versa. if _code.find('float') >= 0 and \ (numpy.any(numpy.isnan(ext_dat)) or numpy.any(numpy.isinf(ext_dat))): errormsg += "===================================\n" errormsg += "= W... |
NaN and/or Inf. =\n" errormsg += "===================================\n" elif _code.find('int') >= 0: # Check INT data for max values ext_dat_frac,ext_dat_exp = numpy.frexp(ext_dat) if ext_dat_exp.max() == int(_bitpix) - 1: # Potential problems with byteswapping errormsg += "===================================\n" error... |
errormsg += "===================================\n" ext_hdu = fits.ImageHDU(data=ext_dat) rec = numpy.fromstring(dat[loc+data_size:loc+group_size], dtype=formats) loc += group_size # Create separate PyFITS Card objects for each entry in 'rec' for i in range(1, pcount+1): #val = rec.field(i-1)[0] val = rec[0][i-1] if va... |
Card is deprecated in pyfits 0.9 _str = '%-8s= %20.7G / %s' % (key[i-1], val, comm[i-1]) _card = fits.Card.fromstring(_str) else: _card = fits.Card(keyword=key[i-1], value=val, comment=comm[i-1]) ext_hdu.header.append(_card) # deal with bscale/bzero if (_bscale != 1 or _bzero != 0): ext_hdu.header['BSCALE'] = _bscale e... |
written out on a platform =\n" errormsg += "= with a different byte-order. =\n" errormsg += "= =\n" errormsg += "= Please verify that the values =\n" errormsg += "= are correct or apply the =\n" errormsg += "= '.byteswap()' method. =\n" errormsg += "===================================\n" print(errormsg) f1.close() stsc... |
def parse_path(f1, f2): """Parse two input arguments and return two lists of file names""" import glob # if second argument is missing or is a wild card, point it # to the current directory f2 = f2.strip() if f2 == '' or f2 == '*': f2 = './' # if the first argument is a directory, use all GEIS files if os.path.isdir(f1... |
os.path.join(f1, '*.??h') list1 = glob.glob(f1) list1 = [name for name in list1 if name[-1] == 'h' and name[-4] == '.'] # if the second argument is a directory, use file names in the # first argument to construct file names, i.e. # abc.xyh will be converted to abc_xyf.fits if os.path.isdir(f2): list2 = [] for file in l... |
'_' + name[-3:-1] + 'f.fits' list2.append(os.path.join(f2, fitsname)) else: list2 = [s.strip() for s in f2.split(",")] if list1 == [] or list2 == []: err_msg = "" if list1 == []: err_msg += "Input files `{:s}` not usable/available. ".format(f1) if list2 == []: err_msg += "Input files `{:s}` not usable/available. ".form... |
def parseinput(inputlist,outputname=None, atfile=None): """ Recursively parse user input based upon the irafglob program and construct a list of files that need to be processed. This program addresses the following deficiencies of the irafglob program:: parseinput can extract filenames from association tables Returns -... |
any outfiles specified in an association table. Parameters ---------- inputlist - string specification of input files using either wild-cards, @-file or comma-separated list of filenames outputname - string desired name for output product to be created from the input files atfile - object function to use in interpretin... |
of output files to be processed newoutputname - string name of output file to be created. See Also -------- stsci.tools.irafglob """ # Initalize some variables files = [] # list used to store names of input files newoutputname = outputname # Outputname returned to calling program. # The value of outputname is only chan... |
# We can use irafglob to parse the input. If the input wasn't # an association table, it needs to be either a wildcard, '@' file, # or comma seperated list. files = irafglob(inputlist, atfile=atfile) # Now that we have expanded the inputlist into a python list # containing the list of input files, it is necessary to ex... |
to make sure none of them are association tables. # # If an association table is found, the entries should be read # Determine if the input is an association table for file in files: if (checkASN(file) == True): # Create a list to store the files extracted from the # association tiable assoclist = [] # The input is an ... |
# Open the association table assocdict = readASNTable(file, None, prodonly=False) except: errorstr = "###################################\n" errorstr += "# #\n" errorstr += "# UNABLE TO READ ASSOCIATION FILE,#\n" errorstr += str(file)+'\n' errorstr += "# DURING FILE PARSING. #\n" errorstr += "# #\n" errorstr += "# Plea... |
has been properly #\n" errorstr += "# formatted. #\n" errorstr += "# #\n" errorstr += "# This error message is being #\n" errorstr += "# generated from within the #\n" errorstr += "# parseinput.py module. #\n" errorstr += "# #\n" errorstr += "###################################\n" raise ValueError(errorstr) # Extract t... |
None: newoutputname = assocdict['output'] # Loop over the association dictionary to extract the input # file names. for f in assocdict['order']: assoclist.append(fileutil.buildRootname(f)) # Remove the name of the association table from the list of files files.remove(file) # Append the list of filenames generated from ... |
and the output name if provided in an association. return files, newoutputname |
def checkASN(filename): """ Determine if the filename provided to the function belongs to an association. Parameters ---------- filename: string Returns ------- validASN : boolean value """ # Extract the file extn type: extnType = filename[filename.rfind('_')+1:filename.rfind('.')] # Determine if this extn name is vali... |
def countinputs(inputlist): """ Determine the number of inputfiles provided by the user and the number of those files that are association tables Parameters ---------- inputlist : string the user input Returns ------- numInputs: int number of inputs provided by the user numASNfiles: int number of association files prov... |
to count the number of inputfiles files = irafglob(inputlist, atfile=None) # Use the "len" ufunc to count the number of entries in the list numInputs = len(files) # Loop over the list and see if any of the entries are association files for file in files: if (checkASN(file) == True): numASNfiles += 1 return numInputs,nu... |
def summary(logfile, time_format): "show a summary of all projects" def output(summary): width = max([len(p[0]) for p in summary]) + 3 print '\n'.join([ "%s%s%s" % (p[0], ' ' * (width - len(p[0])), colored(minutes_to_txt(p[1]), 'red')) for p in summary]) output(server.summarize(read(logfile, time_format, only_elapsed=T... |
def status(logfile, time_format): "show current status" try: r = read(logfile, time_format)[-1] if r[1][1]: return summary(logfile, time_format) else: print "working on %s" % colored(r[0], attrs=['bold']) print " since %s" % colored( server.date_to_txt(r[1][0], time_format), 'green') print " to now, %s" % colored( serv... |
def start(project, logfile, time_format): "start tracking for <project>" records = read(logfile, time_format) if records and not records[-1][1][1]: print "error: there is a project already active" return write(server.start(project, records), logfile, time_format) print "starting work on %s" % colored(project, attrs=['b... |
def stop(logfile, time_format): "stop tracking for the active project" def save_and_output(records): records = server.stop(records) write(records, logfile, time_format) def output(r): print "worked on %s" % colored(r[0], attrs=['bold']) print " from %s" % colored( server.date_to_txt(r[1][0], time_format), 'green') prin... |
def parse(logfile, time_format): "parses a stream with text formatted as a Timed logfile and shows a summary" records = [server.record_from_txt(line, only_elapsed=True, time_format=time_format) for line in sys.stdin.readlines()] # TODO: make this code better. def output(summary): width = max([len(p[0]) for p in summary... |
def projects(logfile, time_format): "prints a newline-separated list of all projects" print '\n'.join(server.list_projects(read(logfile, time_format))) |
def getLTime(): """Returns a formatted string with the current local time.""" _ltime = _time.localtime(_time.time()) tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime) return tlm_str |
def getDate(): """Returns a formatted string with the current date.""" _ltime = _time.localtime(_time.time()) date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime) return date_str |
def convertDate(date): """Convert DATE string into a decimal year.""" d, t = date.split('T') return decimal_date(d, timeobs=t) |
def decimal_date(dateobs, timeobs=None): """Convert DATE-OBS (and optional TIME-OBS) into a decimal year.""" year, month, day = dateobs.split('-') if timeobs is not None: hr, min, sec = timeobs.split(':') else: hr, min, sec = 0, 0, 0 rdate = datetime.datetime(int(year), int(month), int(day), int(hr), int(min), int(sec)... |
ddate = int(year) + dday return ddate |
def interpretDQvalue(input): """ Converts an integer 'input' into its component bit values as a list of power of 2 integers. For example, the bit value 1027 would return [1, 2, 1024] """ nbits = 16 # We will only support integer values up to 2**128 for iexp in [16, 32, 64, 128]: # Find out whether the input value is le... |
(input // (2 ** iexp)) == 0: # when it finally is, we have identified how many bits can be used to # describe this input bitvalue nbits = iexp break # Find out how 'dtype' values are described on this machine a = np.zeros(1, dtype='int16') atype_descr = a.dtype.descr[0][1] # Use this description to build the descriptio... |
= atype_descr[:2] + str(nbits // 8) result = np.zeros(nbits + 1, dtype=dtype_str) # For each bit, determine whether it has been set in the input value or not for n in range(nbits + 1): i = 2 ** n if input & i > 0: # record which bit has been set as the power-of-2 integer result[n] = i # Return the non-zero unique |
values as a Python list return np.delete(np.unique(result), 0).tolist() |
def isFits(input): """ Returns -------- isFits: tuple An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and ``fitstype`` are specified as: - ``isfits``: True|False - ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None Notes ----- Input images which do not have a valid FITS filename will auto... |
valid FITS filename but runs into some error upon opening, this routine will raise that exception for the calling routine/user to handle. """ isfits = False fitstype = None names = ['fits', 'fit', 'FITS', 'FIT'] #determine if input is a fits file based on extension # Only check type of FITS file if filename ends in val... |
False if isinstance(input, fits.HDUList): isfits = True f = input else: isfits = True in [input.endswith(l) for l in names] # if input is a fits file determine what kind of fits it is #waiver fits len(shape) == 3 if isfits: if f is None: try: f = fits.open(input, mode='readonly') fileclose = True except Exception: if f... |
f[0].data if data0 is not None: try: if isinstance(f[1], fits.TableHDU): fitstype = 'waiver' except IndexError: fitstype = 'simple' else: fitstype = 'mef' if fileclose: f.close() return isfits, fitstype |
def verifyWriteMode(files): """ Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out the list of names of affe... |
input is a list of filenames, # if only a single filename has been given as input, # convert it to a list with len == 1. if not isinstance(files, list): files = [files] # Keep track of the name of each file which is not writable not_writable = [] writable = True # Check each file in input list for fname in files: |
try: f = open(fname,'a') f.close() del f except: not_writable.append(fname) writable = False if not writable: print('The following file(s) do not have write permission!') for fname in not_writable: print(' ', fname) return writable |
def getFilterNames(header, filternames=None): """ Returns a comma-separated string of filter names extracted from the input header (PyFITS header object). This function has been hard-coded to support the following instruments: ACS, WFPC2, STIS This function relies on the 'INSTRUME' keyword to define what instrument has... |
their instrument, in the case their instrument is not supported. """ # Define the keyword names for each instrument _keydict = { 'ACS': ['FILTER1', 'FILTER2'], 'WFPC2': ['FILTNAM1', 'FILTNAM2'], 'STIS': ['OPT_ELEM', 'FILTER'], 'NICMOS': ['FILTER', 'FILTER2'], 'WFC3': ['FILTER', 'FILTER2'] } # Find out what instrument t... |
does not contain INSTRUME keyword.') # Check to make sure this instrument is supported in _keydict if instrument in _keydict: _filtlist = _keydict[instrument] else: _filtlist = filternames # At this point, we know what keywords correspond to the filter names # in the header. Now, get the values associated with those ke... |
of the # blank keywords. Values containing 'CLEAR' or 'N/A' are valid. _filter_values = [] for _key in _filtlist: if _key in header: _val = header[_key] else: _val = '' if _val.strip() != '': _filter_values.append(header[_key]) # Return the comma-separated list return ','.join(_filter_values) |
def buildNewRootname(filename, extn=None, extlist=None): """ Build rootname for a new file. Use 'extn' for new filename if given, does NOT append a suffix/extension at all. Does NOT check to see if it exists already. Will ALWAYS return a new filename. """ # Search known suffixes to replace ('_crj.fits',...) _extlist = ... |
('.fits','.c1h',...) #_extlist.append('.') # Also append any user-specified extensions... if extlist: _extlist += extlist if isinstance(filename, fits.HDUList): try: filename = filename.filename() except: raise ValueError("Can't determine the filename of an waivered HDUList object.") for suffix in _extlist: _indx = fil... |
+ extn |
def buildRootname(filename, ext=None): """ Build a new rootname for an existing file and given extension. Any user supplied extensions to use for searching for file need to be provided as a list of extensions. Examples -------- :: >>> rootname = buildRootname(filename, ext=['_dth.fits']) # doctest: +SKIP """ if filenam... |
and '_' in ext[0]: froot = os.path.splitext(fname)[0].split('_')[0] else: froot = fname if fpath in ['', ' ', None]: fpath = os.curdir # Get complete list of filenames from current directory flist = os.listdir(fpath) #First, assume given filename is complete and verify # it exists... rootname = None for name in flist: ... |
'.fits': rootname = froot + '.fits' break # If we have an incomplete filename, try building a default # name and seeing if it exists... # # Set up default list of suffix/extensions to add to rootname _extlist = [] for extn in EXTLIST: _extlist.append(extn) if rootname is None: # Add any user-specified extension to list... |
i in ext: _extlist.insert(0,i) # loop over all extensions looking for a filename that matches... for extn in _extlist: # Start by looking for filename with exactly # the same case a provided in ASN table... rname = froot + extn for name in flist: if rname == name: rootname = name break if rootname is None: # Try lookin... |
# instead of a mixed-case filename as required # by the pipeline. rname = froot.lower() + extn for name in flist: if rname == name: rootname = name break if rootname is not None: break # If we still haven't found the file, see if we have the # info to build one... if rootname is None and ext is not None: # Check |
to see if we have a full filename to start with... _indx = froot.find('.') if _indx > 0: rootname = froot[:_indx] + ext[0] else: rootname = froot + ext[0] if fpath not in ['.', '', ' ', None]: rootname = os.path.join(fpath, rootname) # It will be up to the calling routine to verify # that a valid rootname, rather than ... |
rootname |
def getKeyword(filename, keyword, default=None, handle=None): """ General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string. """ # Insure that there is at least 1 extension specified... if filename.find('[') < 0: filename += '[0]' _fname, _extn = ... |
openImage(_fname) else: # Use what the user provides, after insuring # that it is a proper PyFITS object. if isinstance(handle, fits.HDUList): _fimg = handle else: raise ValueError('Handle must be %r object!' % fits.HDUList) # Address the correct header _hdr = getExtn(_fimg, _extn).header try: value = _hdr[keyword] exc... |
_fimg.close() del _fimg if value == '': if default is None: value = None else: value = default # NOTE: Need to clean up the keyword.. Occasionally the keyword value # goes right up to the "/" FITS delimiter, and iraf.keypar is incapable # of realizing this, so it incorporates "/" along with the keyword value. # For exa... |
image "j8e601bkq_flt.fits", # the CD keywords look like this: # # CD1_1 = 9.221627430999639E-06/ partial of first axis coordinate w.r.t. x # CD1_2 = -1.0346992614799E-05 / partial of first axis coordinate w.r.t. y # # so for CD1_1, iraf.keypar returns: # "9.221627430999639E-06/" # # So, the following piece of code CHEC... |
character if it is a "/". # This fix courtesy of Anton Koekemoer, 2002. elif isinstance(value, string_types): if value[-1:] == '/': value = value[:-1] return value |
def getHeader(filename, handle=None): """ Return a copy of the PRIMARY header, along with any group/extension header for this filename specification. """ _fname, _extn = parseFilename(filename) # Allow the user to provide an already opened PyFITS object # to derive the header from... # if not handle: # Open image wheth... |
user provides, after insuring # that it is a proper PyFITS object. if isinstance(handle, fits.HDUList): _fimg = handle else: raise ValueError('Handle must be a %r object!' % fits.HDUList) _hdr = _fimg['PRIMARY'].header.copy() # if the data is not in the primary array delete NAXIS # so that the correct value is read fro... |
is None or (_extn.isdigit() and int(_extn) == 0)): # Append correct extension/chip/group header to PRIMARY... #for _card in getExtn(_fimg,_extn).header.ascard: #_hdr.ascard.append(_card) for _card in getExtn(_fimg, _extn).header.cards: _hdr.append(_card) if not handle: # Close file handle now... _fimg.close() del _fimg... |
def updateKeyword(filename, key, value,show=yes): """Add/update keyword to header with given value.""" _fname, _extn = parseFilename(filename) # Open image whether it is FITS or GEIS _fimg = openImage(_fname, mode='update') # Address the correct header _hdr = getExtn(_fimg, _extn).header # Assign a new value or add new... |
value # Close image _fimg.close() del _fimg |
def buildFITSName(geisname): """Build a new FITS filename for a GEIS input image.""" # User wants to make a FITS copy and update it... _indx = geisname.rfind('.') _fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits' return _fitsname |
def openImage(filename, mode='readonly', memmap=False, writefits=True, clobber=True, fitsname=None): """ Opens file and returns PyFITS object. Works on both FITS and GEIS formatted images. Notes ----- If a GEIS or waivered FITS image is used as input, it will convert it to a MEF object and only if ``writefits = True`` ... |
write out the new MEF file will be created using `buildFITSName`. Parameters ---------- filename: str name of input file mode: str mode for opening file based on PyFITS `mode` parameter values memmap: bool switch for using memory mapping, `False` for no, `True` for yes writefits: bool if `True`, will write out GEIS as ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.