code stringlengths 1 18.2k |
|---|
clobber: bool overwrite previously written out GEIS-derived MEF file fitsname: str name to use for GEIS-derived MEF file, if None and writefits==`True`, will use 'buildFITSName()' to generate one """ if not isinstance(filename, fits.HDUList): # Insure that the filename is always fully expanded # This will not affect fi... |
extension specification # from input image name _fname, _iextn = parseFilename(filename) else: _fname = filename # Check whether we have a FITS file and if so what type isfits, fitstype = isFits(_fname) if isfits: if fitstype != 'waiver': # Open the FITS file fimg = fits.open(_fname, mode=mode, memmap=memmap) return fi... |
= buildNewRootname(_fname, extn='_c1f.fits') dqexists = os.path.exists(_dqname) if dqexists: try: dqfile = convertwaiveredfits.convertwaiveredfits(_dqname) dqfitsname = buildNewRootname(_dqname, extn='_c1h.fits') except: print("Could not read data quality file %s" % _dqname) if writefits: # User wants to make a FITS co... |
FITS. fexists = os.path.exists(fitsname) if (fexists and clobber) or not fexists: print('Writing out WAIVERED as MEF to ', fitsname) if ASTROPY_VER_GE13: fimg.writeto(fitsname, overwrite=clobber) else: fimg.writeto(fitsname, clobber=clobber) if dqexists: print('Writing out WAIVERED as MEF to ', dqfitsname) if ASTROPY_V... |
re-written as MEF, now it needs its WCS updated #updatewcs.updatewcs(fitsname) fimg = fits.open(fitsname, mode=mode, memmap=memmap) # Return handle for use by user return fimg else: # Input was specified as a GEIS image, but no FITS copy # exists. Read it in with 'readgeis' and make a copy # then open the FITS copy... ... |
fimg = readgeis.readgeis(_fname) except: raise IOError("Could not open GEIS input: %s" % _fname) #check for the existence of a data quality file _dqname = buildNewRootname(_fname, extn='.c1h') dqexists = os.path.exists(_dqname) if dqexists: try: dqfile = readgeis.readgeis(_dqname) dqfitsname = buildFITSName(_dqname) ex... |
multi-extension FITS file and return a handle to it if writefits: # User wants to make a FITS copy and update it # using the filename they have provided if fitsname is None: fitsname = buildFITSName(_fname) # Write out GEIS image as multi-extension FITS. fexists = os.path.exists(fitsname) if (fexists and clobber) or no... |
fimg.writeto(fitsname, overwrite=clobber) else: fimg.writeto(fitsname, clobber=clobber) if dqexists: print('Writing out GEIS as MEF to ', dqfitsname) if ASTROPY_VER_GE13: dqfile.writeto(dqfitsname, overwrite=clobber) else: dqfile.writeto(dqfitsname, clobber=clobber) # Now close input GEIS image, and open writable # han... |
user return fimg |
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. """ # Parse out any extension specified in filename _indx = filename.find('[') if _indx > 0: # Read extension name provided _fname = filename[:_indx] _extn = filename[_indx + 1:-1] e... |
def parseExtn(extn=None): """ Parse a string representing a qualified fits extension name as in the output of `parseFilename` and return a tuple ``(str(extname), int(extver))``, which can be passed to `astropy.io.fits` functions using the 'ext' kw. Default return is the first extension in a fits file. Examples --------... |
extn: return ('', 0) try: lext = extn.split(',') except: return ('', 1) if len(lext) == 1 and lext[0].isdigit(): return ("", int(lext[0])) elif len(lext) == 2: return (lext[0], int(lext[1])) else: return (lext[0], 1) |
def countExtn(fimg, extname='SCI'): """ Return the number of 'extname' extensions, defaulting to counting the number of SCI extensions. """ closefits = False if isinstance(fimg, string_types): fimg = fits.open(fimg) closefits = True n = 0 for e in fimg: if 'extname' in e.header and e.header['extname'] == extname: n += ... |
def getExtn(fimg, extn=None): """ Returns the PyFITS extension corresponding to extension specified in filename. Defaults to returning the first extension with data or the primary extension, if none have data. If a non-existent extension has been specified, it raises a `KeyError` exception. """ # If no extension is pro... |
is None: # Set up default to point to PRIMARY extension. _extn = fimg[0] # then look for first extension with data. for _e in fimg: if _e.data is not None: _extn = _e break else: # An extension was provided, so parse it out... if repr(extn).find(',') > 1: if isinstance(extn, tuple): # We have a tuple possibly created b... |
it into a list for easier manipulation. _extns = list(extn) if '' in _extns: _extns.remove('') else: _extns = extn.split(',') # Two values given for extension: # for example, 'sci,1' or 'dq,1' try: _extn = fimg[_extns[0], int(_extns[1])] except KeyError: _extn = None for e in fimg: hdr = e.header if ('extname' in hdr a... |
elif repr(extn).find('/') > 1: # We are working with GEIS group syntax _indx = str(extn[:extn.find('/')]) _extn = fimg[int(_indx)] elif isinstance(extn, string_types): if extn.strip() == '': _extn = None # force error since invalid name was provided # Only one extension value specified... elif extn.isdigit(): # We only... |
specified... _nextn = None if extn.lower() == 'primary': _nextn = 0 else: i = 0 for hdu in fimg: isimg = 'extname' in hdu.header hdr = hdu.header if isimg and extn.lower() == hdr['extname'].lower(): _nextn = i break i += 1 if _nextn < len(fimg): _extn = fimg[_nextn] else: _extn = None else: # Only integer extension num... |
if int(extn) < len(fimg): _extn = fimg[int(extn)] else: _extn = None if _extn is None: raise KeyError('Extension %s not found' % extn) return _extn |
def findFile(input): """Search a directory for full filename with optional path.""" # If no input name is provided, default to returning 'no'(FALSE) if not input: return no # We use 'osfn' here to insure that any IRAF variables are # expanded out before splitting out the path... _fdir, _fname = os.path.split(osfn(input... |
# handle when requested file in on a disconnect network store return no _root, _extn = parseFilename(_fname) found = no for name in flist: if name == _root: # Check to see if given extension, if any, exists if _extn is None: found = yes continue else: _split = _extn.split(',') _extnum = None _extver = None if _split[0]... |
else: _extname = _split[0] if len(_split) > 1: _extver = int(_split[1]) else: _extver = 1 f = openImage(_root) f.close() if _extnum is not None: if _extnum < len(f): found = yes del f continue else: del f else: _fext = findExtname(f, _extname, extver=_extver) if _fext is not None: found = yes del f continue return foun... |
def checkFileExists(filename, directory=None): """ Checks to see if file specified exists in current or specified directory. Default is current directory. Returns 1 if it exists, 0 if not found. """ if directory is not None: fname = os.path.join(directory,filename) else: fname = filename _exist = os.path.exists(fname) ... |
def copyFile(input, output, replace=None): """Copy a file whole from input to output.""" _found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output) |
def removeFile(inlist): """ Utility function for deleting a list of files or a single file. This function will automatically delete both files of a GEIS image, just like 'iraf.imdelete'. """ if not isinstance(inlist, string_types): # We do have a list, so delete all filenames in list. # Treat like a list of full filena... |
to see if there are wildcards which need to be expanded if f.find('*') >= 0 or f.find('?') >= 0: # We have a wild card specification regpatt = f.replace('?', '.?') regpatt = regpatt.replace('*', '.*') _reg = re.compile(regpatt) for file in _ldir: if _reg.match(file): _remove(file) else: # This is just a single filename... |
a single filename _remove(inlist) |
def findKeywordExtn(ft, keyword, value=None): """ This function will return the index of the extension in a multi-extension FITS file which contains the desired keyword with the given value. """ i = 0 extnum = -1 # Search through all the extensions in the FITS object for chip in ft: hdr = chip.header # Check to make su... |
keyword in hdr: if value is not None: # If it does, then does the value match the desired value # MUST use 'str.strip' to match against any input string! if hdr[keyword].strip() == value: extnum = i break else: extnum = i break i += 1 # Return the index of the extension which contained the # desired EXTNAME value. retu... |
def findExtname(fimg, extname, extver=None): """ Returns the list number of the extension corresponding to EXTNAME given. """ i = 0 extnum = None for chip in fimg: hdr = chip.header if 'EXTNAME' in hdr: if hdr['EXTNAME'].strip() == extname.upper(): if extver is None or hdr['EXTVER'] == extver: extnum = i break i += 1 r... |
def rAsciiLine(ifile): """Returns the next non-blank line in an ASCII file.""" _line = ifile.readline().strip() while len(_line) == 0: _line = ifile.readline().strip() return _line |
def listVars(prefix="", equals="\t= ", **kw): """List IRAF variables.""" keylist = getVarList() if len(keylist) == 0: print('No IRAF variables defined') else: keylist.sort() for word in keylist: print("%s%s%s%s" % (prefix, word, equals, envget(word))) |
def untranslateName(s): """Undo Python conversion of CL parameter or variable name.""" s = s.replace('DOT', '.') s = s.replace('DOLLAR', '$') # delete 'PY' at start of name components if s[:2] == 'PY': s = s[2:] s = s.replace('.PY', '.') return s |
def envget(var, default=None): """Get value of IRAF or OS environment variable.""" if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf = None try: if iraf: return iraf.envget(var) ... |
return os.environ[var] except KeyError: if default is not None: return default elif var == 'TERM': # Return a default value for TERM # TERM gets caught as it is found in the default # login.cl file setup by IRAF. print("Using default TERM value for session.") return 'xterm' else: raise KeyError("Undefined environment v... |
def osfn(filename): """Convert IRAF virtual path name to OS pathname.""" # Try to emulate the CL version closely: # # - expands IRAF virtual file names # - strips blanks around path components # - if no slashes or relative paths, return relative pathname # - otherwise return absolute pathname if filename is None: retur... |
in ename.split(os.sep)] if len(dlist) == 1 and dlist[0] not in [os.curdir, os.pardir]: return dlist[0] # I use str.join instead of os.path.join here because # os.path.join("","") returns "" instead of "/" epath = os.sep.join(dlist) fname = os.path.abspath(epath) # append '/' if relative directory was at end or filename... |
os.sep return fname |
def defvar(varname): """Returns true if CL variable is defined.""" if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf = None if iraf: _irafdef = iraf.envget(varname) else: _irafde... |
_irafdef |
def set(*args, **kw): """Set IRAF environment variables.""" if len(args) == 0: if len(kw) != 0: # normal case is only keyword,value pairs for keyword, value in kw.items(): keyword = untranslateName(keyword) svalue = str(value) _varDict[keyword] = svalue else: # set with no arguments lists all variables (using same form... |
syntax # 'set @filename', which only gets used in the zzsetenv.def file, # where it reads extern.pkg. That file also gets read (in full cl # mode) by clpackage.cl. I get errors if I read this during # zzsetenv.def, so just ignore it here... # # Flag any other syntax as an error. if (len(args) != 1 or len(kw) != 0 or no... |
string_types) or args[0][:1] != '@'): raise SyntaxError("set requires name=value pairs") |
def show(*args, **kw): """Print value of IRAF or OS environment variables.""" if len(kw): raise TypeError('unexpected keyword argument: %r' % list(kw)) if args: for arg in args: print(envget(arg)) else: # print them all listVars(prefix=" ", equals="=") |
def unset(*args, **kw): """ Unset IRAF environment variables. This is not a standard IRAF task, but it is obviously useful. It makes the resulting variables undefined. It silently ignores variables that are not defined. It does not change the os environment variables. """ if len(kw) != 0: raise SyntaxError("unset requi... |
_varDict[arg] |
def Expand(instring, noerror=0): """ Expand a string with embedded IRAF variables (IRAF virtual filename). Allows comma-separated lists. Also uses os.path.expanduser to replace '~' symbols. Set the noerror flag to silently replace undefined variables with just the variable name or null (so Expand('abc$def') = 'abcdef' ... |
for each entry in comma-separated list wordlist = instring.split(",") outlist = [] for word in wordlist: outlist.append(os.path.expanduser(_expand1(word, noerror=noerror))) return ",".join(outlist) |
def _expand1(instring, noerror): """Expand a string with embedded IRAF variables (IRAF virtual filename).""" # first expand names in parentheses # note this works on nested names too, expanding from the # inside out (just like IRAF) mm = __re_var_paren.search(instring) while mm is not None: # remove embedded dollar sig... |
else: raise ValueError("Undefined variable `%s' in string `%s'" % (varname, instring)) instring = instring[:mm.start()] + varname + instring[mm.end():] mm = __re_var_paren.search(instring) # now expand variable name at start of string mm = __re_var_match.match(instring) if mm is None: return instring varname = mm.group... |
_expand1(envget(varname) + instring[mm.end():], noerror) elif noerror: return _expand1(varname + instring[mm.end():], noerror) else: raise ValueError("Undefined variable `%s' in string `%s'" % (varname, instring)) |
def legal_date(year, month, day): '''Check if this is a legal date in the Julian calendar''' daysinmonth = month_length(year, month) if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't have a day {}".format(month, day)) return True |
def from_jd(jd): '''Calculate Julian calendar date from Julian day''' jd += 0.5 z = trunc(jd) a = z b = a + 1524 c = trunc((b - 122.1) / 365.25) d = trunc(365.25 * c) e = trunc((b - d) / 30.6001) if trunc(e < 14): month = e - 1 else: month = e - 13 if trunc(month > 2): year = c |
- 4716 else: year = c - 4715 day = b - d - trunc(30.6001 * e) return (year, month, day) |
def to_jd(year, month, day): '''Convert to Julian day using astronomical years (0 = 1 BC, -1 = 2 BC)''' legal_date(year, month, day) # Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61 if month <= 2: year -= 1 month += 12 return (trunc((365.25 * (year + 4716))) + trunc((30.6001 * (month + 1))) + ... |
def delay_1(year): '''Test for delay of start of new year and to avoid''' # Sunday, Wednesday, and Friday as start of the new year. months = trunc(((235 * year) - 234) / 19) parts = 12084 + (13753 * months) day = trunc((months * 29) + parts / 25920) if ((3 * (day + 1)) % 7) < 3: day += 1 return day |
def delay_2(year): '''Check for delay in start of new year due to length of adjacent years''' last = delay_1(year - 1) present = delay_1(year) next_ = delay_1(year + 1) if next_ - present == 356: return 2 elif present - last == 382: return 1 else: return 0 |
def month_days(year, month): '''How many days are in a given month of a given year''' if month > 13: raise ValueError("Incorrect month index") # First of all, dispose of fixed-length 29 day months if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR): return 29 # If it's not a leap year, Adar has 29 days if month == ADAR a... |
If it's Heshvan, days depend on length of year if month == HESHVAN and (year_days(year) % 10) != 5: return 29 # Similarly, Kislev varies with the length of year if month == KISLEV and (year_days(year) % 10) == 3: return 29 # Nope, it's a 30 day month return 30 |
def byteswap(input,output=None,clobber=True): """Input GEIS files "input" will be read and converted to a new GEIS file whose byte-order has been swapped from its original state. Parameters ---------- input - str Full filename with path of input GEIS image header file output - str Full filename with path of output GEIS... |
- bool Overwrite any pre-existing output file? [Default: True] Notes ----- This function will automatically read and write out the data file using the GEIS image naming conventions. """ global dat cardLen = fits.Card.length # input file(s) must be of the form *.??h and *.??d if input[-1] != 'h' or input[-4] != '.': rai... |
input[:-1]+'d' # Create default output name if no output name was specified by the user if output is None: output = input.replace('.','_swap.') out_data = output[:-1]+'d' if os.path.exists(output) and not clobber: errstr = 'Output file already exists! Please remove or rename and start again...' raise IOError(errstr) _o... |
or _os[:6] == 'darwin': bytes_per_line = cardLen+1 else: raise "Platform %s is not supported (yet)." % _os end_card = 'END'+' '* (cardLen-3) # open input file im = open(input) # Generate the primary HDU so we can have access to keywords which describe # the number of groups and shape of each group's array # cards = [] ... |
= 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 = phdr['BITPIX'] _psize = phdr['PSIZE'] if phdr['DATATYPE']... |
+ _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 = list(range(1, pcount+1)) key = [phdr['PTYPE'+str(j)] for j in _range] comm = [phdr.cards['PTYPE'+st... |
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 file for i in range(1, pcount+1): ptype = key[i-1] pdtype = phdr['PD... |
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[_bitpix] _bscale = phdr.get('BSCALE', 1) _bzero = phdr.get('BZ... |
needed # in some platforms. f1 = open(data_file, mode='rb') dat = f1.read() f1.close() errormsg = "" loc = 0 outdat = b'' for k in range(gcount): ext_dat = numpy.fromstring(dat[loc:loc+data_size], dtype=_code) ext_dat = ext_dat.reshape(_shape).byteswap() outdat += ext_dat.tostring() ext_hdu = fits.hdu.ImageHDU(data=ext... |
to ',output) #------------------------------------------------------------------------------- """Input GEIS files "input" will be read and a HDUList object will be returned that matches the waiver-FITS format written out by 'stwfits' in IRAF. The user can use the writeto method to write the HDUList object to a FITS fil... |
file(s) must be of the form *.??h and *.??d if input[-1] != 'h' or input[-4] != '.': raise "Illegal input GEIS file name %s" % 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... |
_os end_card = 'END'+' '* (cardLen-3) # open input file im = open(input) # Generate the primary HDU cards = [] 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() phdr.set('FILENAME'... |
_naxis = [phdr['NAXIS'+str(j)] for j in range(1, _naxis0+1)] _naxis.insert(0, _naxis0) _bitpix = phdr['BITPIX'] _psize = phdr['PSIZE'] if phdr['DATATYPE'][:4] == 'REAL': _bitpix = -_bitpix if _naxis0 > 0: size = reduce(lambda x,y:x*y, _naxis[1:]) data_size = abs(_bitpix) * size // 8 else: data_size = 0 group_size = dat... |
= phdr['GROUPS'] gcount = phdr['GCOUNT'] pcount = phdr['PCOUNT'] formats = [] bools = [] floats = [] cols = [] # column definitions used for extension table cols_dict = {} # provides name access to Column defs _range = list(range(1, pcount+1)) key = [phdr['PTYPE'+str(j)] for j in _range] comm = [phdr.cards['PTYPE'+str(... |
['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 file for i in range(1, pcount+1): ptype = key[i-... |
# collect boolean keywords since they need special attention later if _type == 'LOGICAL': bools.append(i) if pdtype == 'REAL*4': floats.append(i) # identify keywords which require conversion to special units if ptype in kw_DOUBLE: _type = 'DOUBLE' fmt = geis_fmt[_type] + _bytes formats.append((ptype,fmt)) # Set up defi... |
nrpt = _bytes nbits = _bytes afmt = cols_fmt[_type]+ nbits if 'LOGICAL' in _type: afmt = cols_fmt[_type] cfmt = cols_pfmt[_type]+nrpt #print 'Column format for ',ptype,': ',cfmt,' with dtype of ',afmt cols_dict[ptype] = fits.Column(name=ptype,format=cfmt,array=numpy.zeros(gcount,dtype=afmt)) cols.append(cols_dict[ptype... |
= 32768 else: _uint16 = 0 # delete from 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['GROUPS'] = False _after = 'NAXIS' if _naxis0 > 0: _after += str(_naxis0) ... |
copy-on-write for all data types since byteswap may be needed # in some platforms. f1 = open(data_file, mode='rb') dat = f1.read() errormsg = "" # Define data array for all groups arr_shape = _naxis[:] arr_shape[0] = gcount arr_stack = numpy.zeros(arr_shape,dtype=_code) loc = 0 for k in range(gcount): ext_dat = numpy.f... |
there are any NaN's 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 += "===================================... |
errormsg += "= of 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 += "==========================... |
with maximum bitvalues. =\n" errormsg += "===================================\n" arr_stack[k] = ext_dat rec = numpy.fromstring(dat[loc+data_size:loc+group_size], dtype=formats) loc += group_size # Add data from this GPB to table for i in range(1, pcount+1): val = rec[0][i-1] if i in bools: if val: val = 'T' else: val =... |
0: # Create separate PyFITS Card objects for each entry in 'rec' # and update Primary HDU with these keywords after PSIZE for i in range(1, pcount+1): #val = rec.field(i-1)[0] val = rec[0][i-1] if val.dtype.kind == 'S': val = val.decode('ascii') if i in bools: if val: val = True else: val = False if i in floats: # use ... |
deprecated in pyfits 0.9 _str = '%-8s= %20.13G / %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]) phdr.insert(phdr_indx+i, _card) # deal with bscale/bzero if (_bscale != 1 or _bzero != 0): phdr['BSCALE'] = _bscale phdr['BZERO'] =... |
of table extension to match stwfits output for i in range(len(key)): ext_table.header.append(fits.Card(keyword=key[i], value=comm[i])) if errormsg != "": errormsg += "===================================\n" errormsg += "= This file may have been =\n" errormsg += "= written out on a platform =\n" errormsg += "= with a di... |
or apply the =\n" errormsg += "= '.byteswap()' method. =\n" errormsg += "===================================\n" print(errormsg) f1.close() hdulist = fits.HDUList([fits.PrimaryHDU(header=phdr, data=arr_stack)]) hdulist.append(ext_table) return hdulist |
def start(self, measurementId, durationInSeconds=None): """ Initialises the device if required then enters a read loop taking data from the provider and passing it to the handler. It will continue until either breakRead is true or the duration (if provided) has passed. :return: """ logger.info(">> measurement " + measu... |
= None self.measurementOverflowed = False self.dataHandler.start(measurementId) self.breakRead = False self.startTime = time.time() self.doInit() # this must follow doInit because doInit sets status to INITIALISED self.status = RecordingDeviceStatus.RECORDING elapsedTime = 0 try: self._sampleIdx = 0 while True: logger.... |
= 0 break except: self.status = RecordingDeviceStatus.FAILED self.failureCode = str(sys.exc_info()) logger.exception(measurementId + " failed") finally: expectedSamples = self.fs * (durationInSeconds if durationInSeconds is not None else elapsedTime) if self._sampleIdx < expectedSamples: self.status = RecordingDeviceSt... |
RecordingDeviceStatus.FAILED self.failureCode = "Measurement overflow detected" if self.status == RecordingDeviceStatus.FAILED: logger.error("<< measurement " + measurementId + " - FAILED - " + self.failureCode) else: self.status = RecordingDeviceStatus.INITIALISED logger.info("<< measurement " + measurementId + " - " ... |
def get(self, targetId): """ Yields the analysed wav data. :param targetId: :return: """ result = self._targetController.analyse(targetId) if result: if len(result) == 2: if result[1] == 404: return result else: return {'name': targetId, 'data': self._jsonify(result)}, 200 else: return None, 404 else: return None, 500 |
def put(self, targetId): """ stores a new target. :param targetId: the target to store. :return: """ json = request.get_json() if 'hinge' in json: logger.info('Storing target ' + targetId) if self._targetController.storeFromHinge(targetId, json['hinge']): logger.info('Stored target ' + targetId) return None, 200 else: ... |
def to_datetime(jdc): '''Return a datetime for the input floating point Julian Day Count''' year, month, day = gregorian.from_jd(jdc) # in jdc: 0.0 = noon, 0.5 = midnight # the 0.5 changes it to 0.0 = midnight, 0.5 = noon frac = (jdc + 0.5) % 1 hours = int(24 * frac) mfrac = frac * 24 - hours mins = int(60 * round(mfra... |
sfrac = mfrac * 60 - mins secs = int(60 * round(sfrac, 6)) msfrac = sfrac * 60 - secs # down to ms, which are 1/1000 of a second ms = int(1000 * round(msfrac, 6)) return datetime(year, month, day, int(hours), int(mins), int(secs), int(ms), tzinfo=utc) |
def dict_from_qs(qs): ''' Slightly introverted parser for lists of dot-notation nested fields i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}} ''' entries = qs.split(',') if qs.strip() else [] entries = [entry.strip() for entry in entries] def _dict_from_qs(line, d): if '.' in line: key, value = line.sp... |
line in entries: _dict_from_qs(line, d) return d |
def qs_from_dict(qsdict, prefix=""): ''' Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr" ''' prefix = prefix + '.' if prefix else "" def descend(qsd): for key, val in sorted(qsd.items()): if val: yield qs_from_dict(val, prefix + key) else: yield prefix + key return ... |
def dbcon(func): """Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.""" @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.dbcon is None: # set up connection self.dbcon = sqlite3.connect(self.db) self.dbcur = self.dbcon.cur... |
self.dbcon.rollback() self.dbcon.commit() self.dbcon.close() self.dbcon = None self.dbcur = None raise e else: # commit everything and close connection self.dbcon.commit() self.dbcon.close() self.dbcon = None self.dbcur = None else: result = func(*args, **kwargs) return result return wrapper |
def add(self, sid, token): """ Add new sensor to the database Parameters ---------- sid : str SensorId token : str """ try: self.dbcur.execute(SQL_SENSOR_INS, (sid, token)) except sqlite3.IntegrityError: # sensor entry exists pass |
def remove(self, sid): """ Remove sensor from the database Parameters ---------- sid : str SensorID """ self.dbcur.execute(SQL_SENSOR_DEL, (sid,)) self.dbcur.execute(SQL_TMPO_DEL, (sid,)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.