code stringlengths 1 18.2k |
|---|
string of values for array return str(self) |
def set(self, value, field=None, index=None, check=1): """Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is within the min-max range or in th... |
self._coerceOneValue(value) if check: self.value[sumindex] = self.checkOneValue(value) else: self.value[sumindex] = value return except IndexError: # should never happen raise SyntaxError("Illegal index [" + repr(sumindex) + "] for array parameter " + self.name) if field: self._setField(value,field,check=check) else: i... |
def checkValue(self,value,strict=0): """Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.) """ v = self._coerceValue(value,strict) for i in range(len(v)): self.checkOneValue(v[i],strict=strict) return v |
def _sumindex(self, index=None): """Convert tuple index to 1-D index into value""" try: ndim = len(index) except TypeError: # turn index into a 1-tuple index = (index,) ndim = 1 if len(self.shape) != ndim: raise ValueError("Index to %d-dimensional array %s has too %s dimensions" % (len(self.shape), self.name, ["many","... |
index1 >= self.shape[i]: raise ValueError("Dimension %d index for array %s is out of bounds (value=%d)" % (i+1, self.name, index1)) sumindex = index1 + sumindex*self.shape[i] return sumindex |
def _coerceValue(self,value,strict=0): """Coerce parameter to appropriate type Should accept None or null string. Must be an array. """ try: if isinstance(value,str): # allow single blank-separated string as input value = value.split() if len(value) != len(self.value): raise IndexError v = len(self.value)*[0] for i in ... |
" + self.name) |
def _setChoiceDict(self): """Create min-match dictionary for choice list""" # value is full name of choice parameter self.choiceDict = minmatch.MinMatchDict() for c in self.choice: self.choiceDict.add(c, c) |
def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.min: warning("Minimum value not allowed for boolean-type parameter " + self.name, strict) self.min = None if self.max: if not self.prompt: warning("Maximum value not allowed for boolean-type parameter " + self.name + " (... |
value not allowed for boolean-type parameter " + self.name, strict) self.max = None if self.choice: warning("Choice values not allowed for boolean-type parameter " + self.name, strict) self.choice = None |
def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.choice: warning("Choice values not allowed for real-type parameter " + self.name, strict) self.choice = None |
def patch(self, deviceId): """ Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometerSensitivity: 2 } A heartbeat is sent on completion of the request to ensure the analyser gets a ... |
self.recordingDevices.get(deviceId) if device.status == RecordingDeviceStatus.INITIALISED: errors = self._handlePatch(device) if len(errors) == 0: return device, 200 else: return device, 500 else: return device, 400 finally: logger.info("Sending adhoc heartbeat on device state update") self.heartbeater.sendHeartbeat() |
def legal_date(year, month, day): '''Check if this is a legal date in the Gregorian calendar''' if month == 2: daysinmonth = 29 if isleap(year) else 28 else: daysinmonth = 30 if month in HAVE_30_DAYS else 31 if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't have a day {}".format(month, day)) return Tr... |
def to_jd2(year, month, day): '''Gregorian to Julian Day Count for years between 1801-2099''' # http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html legal_date(year, month, day) if month <= 2: year = year - 1 month = month + 12 a = floor(year / 100) b = floor(a / 4) c = 2 - a + b e = floor(365.25 * (year + 4716)) f =... |
c + day + e + f - 1524.5 |
def from_jd(jd): '''Return Gregorian date in a (Y, M, D) tuple''' wjd = floor(jd - 0.5) + 0.5 depoch = wjd - EPOCH quadricent = floor(depoch / INTERCALATION_CYCLE_DAYS) dqc = depoch % INTERCALATION_CYCLE_DAYS cent = floor(dqc / LEAP_SUPPRESSION_DAYS) dcent = dqc % LEAP_SUPPRESSION_DAYS quad = floor(dcent / LEAP_CYCLE_D... |
+ cent * LEAP_SUPPRESSION_YEARS + quad * LEAP_CYCLE_YEARS + yindex ) if not (cent == 4 or yindex == 4): year += 1 yearday = wjd - to_jd(year, 1, 1) leap = isleap(year) if yearday < 58 + leap: leap_adj = 0 elif leap: leap_adj = 1 else: leap_adj = 2 month = floor((((yearday + leap_adj) * 12) + 373) / 367) day = |
int(wjd - to_jd(year, month, 1)) + 1 return (year, month, day) |
def storeFromHinge(self, name, hingePoints): """ Stores a new item in the cache if it is allowed in. :param name: the name. :param hingePoints: the hinge points. :return: true if it is stored. """ if name not in self._cache: if self._valid(hingePoints): self._cache[name] = {'name': name, 'type': 'hinge', 'hinge': hinge... |
def storeFromWav(self, uploadCacheEntry, start, end): """ Stores a new item in the cache. :param name: file name. :param start: start time. :param end: end time. :return: true if stored. """ prefix = uploadCacheEntry['name'] + '_' + start + '_' + end match = next((x for x in self._cache.values() if x['type'] == 'wav' a... |
prefix + '_' + n, 'analysis': n, 'start': start, 'end': end, 'type': 'wav', 'filename': uploadCacheEntry['name'] } for n in ['spectrum', 'peakSpectrum'] ] for cache in cached: self._cache[cache['name']] = cache self.writeCache() return True return False |
def delete(self, name): """ Deletes the named entry in the cache. :param name: the name. :return: true if it is deleted. """ if name in self._cache: del self._cache[name] self.writeCache() # TODO clean files return True return False |
def analyse(self, name): """ reads the specified file. :param name: the name. :return: the analysis as frequency/Pxx. """ if name in self._cache: target = self._cache[name] if target['type'] == 'wav': signal = self._uploadController.loadSignal(target['filename'], start=target['start'] if target['start'] != 'start' else... |
pass elif target['type'] == 'hinge': hingePoints = np.array(target['hinge']).astype(np.float64) x = hingePoints[:, 1] y = hingePoints[:, 0] # extend as straight line from 0 to 500 if x[0] != 0: x = np.insert(x, 0, 0.0000001) y = np.insert(y, 0, y[0]) if x[-1] != 500: x = np.insert(x, len(x), 500.0) y = np.insert(y, len... |
y = 10 ** (y / 10) # perform a logspace interpolation f = self.log_interp1d(x, y) # remap to 0-500 xnew = np.linspace(x[0], x[-1], num=500, endpoint=False) # and convert back to dB return xnew, 10 * np.log10(f(xnew)) else: logger.error('Unknown target type with name ' + name) return None |
def log_interp1d(self, xx, yy, kind='linear'): """ Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function. """ logx = np.log10(xx) logy = np.log10(yy) lin_interp = interp1d(logx,... |
def to_jd(year, month, day): "Retrieve the Julian date equivalent for this date" return day + (month - 1) * 30 + (year - 1) * 365 + floor(year / 4) + EPOCH - 1 |
def from_jd(jdc): "Create a new date from a Julian date." cdc = floor(jdc) + 0.5 - EPOCH year = floor((cdc - floor((cdc + 366) / 1461)) / 365) + 1 yday = jdc - to_jd(year, 1, 1) month = floor(yday / 30) + 1 day = yday - (month - 1) * 30 + 1 return year, month, day |
def troll(roll, dec, v2, v3): """ Computes the roll angle at the target position based on:: the roll angle at the V1 axis(roll), the dec of the target(dec), and the V2/V3 position of the aperture (v2,v3) in arcseconds. Based on the algorithm provided by Colin Cox that is used in Generic Conversion at STScI. """ # Conve... |
_dec = DEGTORAD(dec) _v2 = DEGTORAD(v2 / 3600.) _v3 = DEGTORAD(v3 / 3600.) # compute components sin_rho = sqrt((pow(sin(_v2),2)+pow(sin(_v3),2)) - (pow(sin(_v2),2)*pow(sin(_v3),2))) rho = asin(sin_rho) beta = asin(sin(_v3)/sin_rho) if _v2 < 0: beta = pi - beta gamma = asin(sin(_v2)/sin_rho) if _v3 < 0: gamma = pi - gam... |
final value troll = RADTODEG(pi - (gamma+B)) return troll |
def print_archive(self,format=True): """ Prints out archived WCS keywords.""" if len(list(self.orig_wcs.keys())) > 0: block = 'Original WCS keywords for ' + self.rootname+ '\n' block += ' backed up on '+repr(self.orig_wcs['WCSCDATE'])+'\n' if not format: for key in self.wcstrans.keys(): block += key.upper() + " = " + r... |
'+repr(self.get_archivekw('CD2_2')) +'\n' block += 'CRVAL : '+repr(self.get_archivekw('CRVAL1'))+' '+repr(self.get_archivekw('CRVAL2')) + '\n' block += 'CRPIX : '+repr(self.get_archivekw('CRPIX1'))+' '+repr(self.get_archivekw('CRPIX2')) + '\n' block += 'NAXIS : '+repr(int(self.get_archivekw('NAXIS1')))+' '+repr(int(sel... |
def set_pscale(self): """ Compute the pixel scale based on active WCS values. """ if self.new: self.pscale = 1.0 else: self.pscale = self.compute_pscale(self.cd11,self.cd21) |
def compute_pscale(self,cd11,cd21): """ Compute the pixel scale based on active WCS values. """ return N.sqrt(N.power(cd11,2)+N.power(cd21,2)) * 3600. |
def set_orient(self): """ Return the computed orientation based on CD matrix. """ self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22)) |
def updateWCS(self, pixel_scale=None, orient=None,refpos=None,refval=None,size=None): """ Create a new CD Matrix from the absolute pixel scale and reference image orientation. """ # Set up parameters necessary for updating WCS # Check to see if new value is provided, # If not, fall back on old value as the default _upd... |
= orient self._orient_lin = orient _updateCD = yes else: # In case only pixel_scale was specified pa = DEGTORAD(self.orient) if pixel_scale is not None and pixel_scale != self.pscale: _ratio = pixel_scale / self.pscale self.pscale = pixel_scale _updateCD = yes else: # In case, only orient was specified pixel_scale = se... |
size should be revised accordingly # along with the default reference pixel position. # Added 31 Mar 03, WJH. if _ratio is not None: self.naxis1 /= _ratio self.naxis2 /= _ratio self.crpix1 = self.naxis1/2. self.crpix2 = self.naxis2/2. # However, if the user provides a given size, # set it to use that no matter what. if... |
size[1] # Insure that naxis1,2 always return as integer values. self.naxis1 = int(self.naxis1) self.naxis2 = int(self.naxis2) if refpos is not None: self.crpix1 = refpos[0] self.crpix2 = refpos[1] if self.crpix1 is None: self.crpix1 = self.naxis1/2. self.crpix2 = self.naxis2/2. if refval is not None: self.crval1 = refv... |
change... pscale = pixel_scale / 3600. self.cd11 = -pscale * N.cos(pa) self.cd12 = pscale * N.sin(pa) self.cd21 = self.cd12 self.cd22 = -self.cd11 # Now make sure that all derived values are really up-to-date based # on these changes self.update() |
def scale_WCS(self,pixel_scale,retain=True): ''' Scale the WCS to a new pixel_scale. The 'retain' parameter [default value: True] controls whether or not to retain the original distortion solution in the CD matrix. ''' _ratio = pixel_scale / self.pscale # Correct the size of the image and CRPIX values for scaled WCS se... |
Correct the WCS while retaining original distortion information self.cd11 *= _ratio self.cd12 *= _ratio self.cd21 *= _ratio self.cd22 *= _ratio else: pscale = pixel_scale / 3600. self.cd11 = -pscale * N.cos(pa) self.cd12 = pscale * N.sin(pa) self.cd21 = self.cd12 self.cd22 = -self.cd11 # Now make sure that all derived ... |
def xy2rd(self,pos): """ This method would apply the WCS keywords to a position to generate a new sky position. The algorithm comes directly from 'imgtools.xy2rd' translate (x,y) to (ra, dec) """ if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: print('XY2RD only supported for TAN projections.') raise Type... |
and Y values posx = pos[:,0] posy = pos[:,1] else: # Otherwise, we are working with a single X,Y tuple posx = pos[0] posy = pos[1] xi = self.cd11 * (posx - self.crpix1) + self.cd12 * (posy - self.crpix2) eta = self.cd21 * (posx - self.crpix1) + self.cd22 * (posy - self.crpix2) xi = DEGTORAD(xi) eta = DEGTORAD(eta) ra0 ... |
ra = N.arctan((xi / (N.cos(dec0)-eta*N.sin(dec0)))) + ra0 dec = N.arctan( ((eta*N.cos(dec0)+N.sin(dec0)) / (N.sqrt((N.cos(dec0)-eta*N.sin(dec0))**2 + xi**2))) ) ra = RADTODEG(ra) dec = RADTODEG(dec) ra = DIVMOD(ra, 360.) # Otherwise, just return the RA,Dec tuple. return ra,dec |
def rd2xy(self,skypos,hour=no): """ This method would use the WCS keywords to compute the XY position from a given RA/Dec tuple (in deg). NOTE: Investigate how to let this function accept arrays as well as single positions. WJH 27Mar03 """ if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: print('RD2XY only... |
raise ArithmeticError("singular CD matrix!") cdinv11 = self.cd22 / det cdinv12 = -self.cd12 / det cdinv21 = -self.cd21 / det cdinv22 = self.cd11 / det # translate (ra, dec) to (x, y) ra0 = DEGTORAD(self.crval1) dec0 = DEGTORAD(self.crval2) if hour: skypos[0] = skypos[0] * 15. ra = DEGTORAD(skypos[0]) dec = DEGTORAD(sky... |
= RADTODEG((N.cos(dec) * N.sin(ra-ra0) / bottom)) eta = RADTODEG((N.sin(dec)*N.cos(dec0) - N.cos(dec)*N.sin(dec0)*N.cos(ra-ra0)) / bottom) x = cdinv11 * xi + cdinv12 * eta + self.crpix1 y = cdinv21 * xi + cdinv22 * eta + self.crpix2 return x,y |
def rotateCD(self,orient): """ Rotates WCS CD matrix to new orientation given by 'orient' """ # Determine where member CRVAL position falls in ref frame # Find out whether this needs to be rotated to align with # reference frame. _delta = self.get_orient() - orient if _delta == 0.: return # Start by building the rotati... |
matrix and update the values... _cd = N.array([[self.cd11,self.cd12],[self.cd21,self.cd22]],dtype=N.float64) _cdrot = N.dot(_cd,_rot) self.cd11 = _cdrot[0][0] self.cd12 = _cdrot[0][1] self.cd21 = _cdrot[1][0] self.cd22 = _cdrot[1][1] self.orient = orient |
def write(self,fitsname=None,wcs=None,archive=True,overwrite=False,quiet=True): """ Write out the values of the WCS keywords to the specified image. If it is a GEIS image and 'fitsname' has been provided, it will automatically make a multi-extension FITS copy of the GEIS and update that file. Otherwise, it throw an Exc... |
keyword values to file. If overwrite=True, replace archived WCS values in file with new values. If a WCSObject is passed through the 'wcs' keyword, then the WCS keywords of this object are copied to the header of the image to be updated. A use case fo rthis is updating the WCS of a WFPC2 data quality (_c1h.fits) file i... |
with the science (_c0h.fits) file. """ ## Start by making sure all derived values are in sync with CD matrix self.update() image = self.rootname _fitsname = fitsname if image.find('.fits') < 0 and _fitsname is not None: # A non-FITS image was provided, and openImage made a copy # Update attributes to point to new copy ... |
# Open image as writable FITS object fimg = fileutil.openImage(image, mode='update', fitsname=_fitsname) _root,_iextn = fileutil.parseFilename(image) _extn = fileutil.getExtn(fimg,_iextn) # Write out values to header... if wcs: _wcsobj = wcs else: _wcsobj = self for key in _wcsobj.wcstrans.keys(): _dkey = _wcsobj.wcstr... |
def restore(self): """ Reset the active WCS keywords to values stored in the backup keywords. """ # If there are no backup keys, do nothing... if len(list(self.backup.keys())) == 0: return for key in self.backup.keys(): if key != 'WCSCDATE': self.__dict__[self.wcstrans[key]] = self.orig_wcs[self.backup[key]] self.updat... |
def archive(self,prepend=None,overwrite=no,quiet=yes): """ Create backup copies of the WCS keywords with the given prepended string. If backup keywords are already present, only update them if 'overwrite' is set to 'yes', otherwise, do warn the user and do nothing. Set the WCSDATE at this time as well. """ # Verify tha... |
no: if not quiet: print('WARNING: Backup WCS keywords already exist! No backup made.') print(' The values can only be overridden if overwrite=yes.') return # Establish what prepend string to use... if prepend is None: if self.prepend is not None: _prefix = self.prepend else: _prefix = DEFAULT_PREFIX else: _prefix = pre... |
prefix # Go through and append them to self.backup self.prepend = _prefix for key in self.wcstrans.keys(): if key != 'pixel scale': _archive_key = self._buildNewKeyname(key,_prefix) else: _archive_key = self.prepend.lower()+'pscale' # if key != 'pixel scale': self.orig_wcs[_archive_key] = self.__dict__[self.wcstrans[ke... |
def read_archive(self,header,prepend=None): """ Extract a copy of WCS keywords from an open file header, if they have already been created and remember the prefix used for those keywords. Otherwise, setup the current WCS keywords as the archive values. """ # Start by looking for the any backup WCS keywords to # determi... |
_prefix = None _archive = False if header is not None: for kw in header.items(): if kw[0][1:] in self.wcstrans.keys(): _prefix = kw[0][0] _archive = True break if not _archive: self.archive(prepend=prepend) return # We have archive keywords and a defined prefix # Go through and append them to self.backup if _prefix is ... |
_archive_key = self._buildNewKeyname(key,_prefix) if key!= 'pixel scale': if _archive_key in header: self.orig_wcs[_archive_key] = header[_archive_key] else: self.orig_wcs[_archive_key] = header[key] self.backup[key] = _archive_key self.revert[_archive_key] = key # Establish plate scale value _cd11str = self.prepend+'C... |
'WCSCDATE' in header: self.orig_wcs['WCSCDATE'] = header['WCSCDATE'] else: self.orig_wcs['WCSCDATE'] = fileutil.getLTime() self.backup['WCSCDATE'] = 'WCSCDATE' self.revert['WCSCDATE'] = 'WCSCDATE' |
def write_archive(self,fitsname=None,overwrite=no,quiet=yes): """ Saves a copy of the WCS keywords from the image header as new keywords with the user-supplied 'prepend' character(s) prepended to the old keyword names. If the file is a GEIS image and 'fitsname' is not None, create a FITS copy and update that version; o... |
in update mode # Copying of GEIS images handled by 'openImage'. fimg = fileutil.openImage(self.rootname,mode='update',fitsname=_fitsname) if self.rootname.find('.fits') < 0 and _fitsname is not None: # A non-FITS image was provided, and openImage made a copy # Update attributes to point to new copy instead self.geisnam... |
quiet: print('Updating archive WCS keywords for ',_fitsname) # Write out values to header... for key in self.orig_wcs.keys(): _comment = None _dkey = self.revert[key] # Verify that archive keywords will not be overwritten, # unless overwrite=yes. _old_key = key in _extn.header if _old_key == True and overwrite == no: i... |
in file, or overwrite=yes... # Extract the value for the original keyword if _dkey in _extn.header: # Extract any comment string for the keyword as well _indx_key = _extn.header.index(_dkey) _full_key = _extn.header.cards[_indx_key] if not quiet: print('updating ',key,' with value of: ',self.orig_wcs[key]) _extn.header... |
were backed up. _extn.header[key] = (self.orig_wcs[key], "Time WCS keywords were copied.") # Close the now updated image fimg.close() del fimg |
def restoreWCS(self,prepend=None): """ Resets the WCS values to the original values stored in the backup keywords recorded in self.backup. """ # Open header for image image = self.rootname if prepend: _prepend = prepend elif self.prepend: _prepend = self.prepend else: _prepend = None # Open image as writable FITS objec... |
= fileutil.getExtn(fimg,_iextn) if len(self.backup) > 0: # If it knows about the backup keywords already, # use this to restore the original values to the original keywords for newkey in self.revert.keys(): if newkey != 'opscale': _orig_key = self.revert[newkey] _extn.header[_orig_key] = _extn.header[newkey] elif _prep... |
scale': _okey = self._buildNewKeyname(key,_prepend) if _okey in _extn.header: _extn.header[key] = _extn.header[_okey] else: print('No original WCS values found. Exiting...') break else: print('No original WCS values found. Exiting...') fimg.close() del fimg |
def createReferenceWCS(self,refname,overwrite=yes): """ Write out the values of the WCS keywords to the NEW specified image 'fitsname'. """ hdu = self.createWcsHDU() # If refname already exists, delete it to make way for new file if os.path.exists(refname): if overwrite==yes: # Remove previous version and re-create wit... |
e in oldhdu: if 'extname' in e.header and e.header['extname'] == 'WCS': wcs_append = False if wcs_append == True: oldhdu.append(hdu) oldhdu.close() del oldhdu else: # No previous file, so generate new one from scratch hdu.writeto(refname) # Clean up del hdu |
def createWcsHDU(self): """ Generate a WCS header object that can be used to populate a reference WCS HDU. """ hdu = fits.ImageHDU() hdu.header['EXTNAME'] = 'WCS' hdu.header['EXTVER'] = 1 # Now, update original image size information hdu.header['WCSAXES'] = (2, "number of World Coordinate System axes") hdu.header['NPIX... |
of pixels in array") # Write out values to header... excluded_keys = ['naxis1','naxis2'] for key in self.wcskeys: _dkey = self.wcstrans[key] if _dkey not in excluded_keys: hdu.header[key] = self.__dict__[_dkey] return hdu |
def main(args=None): """ The main routine. """ logger = cfg.configureLogger() for root, dirs, files in os.walk(cfg.dataDir): for dir in dirs: newDir = os.path.join(root, dir) try: os.removedirs(newDir) logger.info("Deleted empty dir " + str(newDir)) except: pass if cfg.useTwisted: import logging logger = logging.getLog... |
import endpoints class ReactApp: """ Handles the react app (excluding the static dir). """ def __init__(self, path): # TODO allow this to load when in debug mode even if the files don't exist self.publicFiles = {f: static.File(os.path.join(path, f)) for f in os.listdir(path) if os.path.exists(os.path.join(path, f))} se... |
does actually exist (i.e. is an icon or something like that) """ return self.publicFiles.get(path.decode('utf-8'), self.indexHtml) class ReactIndex(static.File): """ a twisted File which overrides getChild so it always just serves index.html (NB: this is a bit of a hack, there is probably a more correct way to do this ... |
a WSGI resource while allow the react index.html (and its associated static content) to be served as the default page. """ def __init__(self): super().__init__() self.wsgi = WSGIResource(reactor, reactor.getThreadPool(), app) import sys if getattr(sys, 'frozen', False): # pyinstaller lets you copy files to arbitrary lo... |
setuptools doesn't seem to include # files from outside the package uiRoot = os.path.dirname(__file__) logger.info('Serving ui from ' + str(uiRoot)) self.react = ReactApp(os.path.join(uiRoot, 'ui')) self.static = static.File(os.path.join(uiRoot, 'ui', 'static')) def getChild(self, path, request): """ Overrides getChild... |
various concrete files (i.e. the public dir from react-app) or to index.html (i.e. the react app) for everything else. :param path: :param request: :return: """ if path == b'api': request.prepath.pop() request.postpath.insert(0, path) return self.wsgi elif path == b'static': return self.static else: return self.react.g... |
config from a flask standard place not our config yml app.run(debug=cfg.runInDebug(), host='0.0.0.0', port=cfg.getPort()) |
def leap(year, method=None): ''' Determine if this is a leap year in the FR calendar using one of three methods: 4, 100, 128 (every 4th years, every 4th or 400th but not 100th, every 4th but not 128th) ''' method = method or 'equinox' if year in (3, 7, 11): return True elif year < 15: return False if method in (4, 'con... |
(year <= 16 and method in (128, 'madler', 4, 'continuous')): return year % 4 == 3 elif method in (100, 'romme'): return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 elif method in (128, 'madler'): return year % 4 == 0 and year % 128 != 0 elif method == 'equinox': # Is equinox on |
366th day after (year, 1, 1) startjd = to_jd(year, 1, 1, method='equinox') if premier_da_la_annee(startjd + 367) - startjd == 366.0: return True else: raise ValueError("Unknown leap year method. Try: continuous, romme, madler or equinox") return False |
def premier_da_la_annee(jd): '''Determine the year in the French revolutionary calendar in which a given Julian day falls. Returns Julian day number containing fall equinox (first day of the FR year)''' p = ephem.previous_fall_equinox(dublin.from_jd(jd)) previous = trunc(dublin.to_jd(p) - 0.5) + 0.5 if previous + 364 <... |
= ephem.next_fall_equinox(dublin.from_jd(jd)) nxt = trunc(dublin.to_jd(n) - 0.5) + 0.5 if nxt <= jd: return nxt return previous |
def to_jd(year, month, day, method=None): '''Obtain Julian day from a given French Revolutionary calendar date.''' method = method or 'equinox' if day < 1 or day > 30: raise ValueError("Invalid day for this calendar") if month > 13: raise ValueError("Invalid month for this calendar") if month == 13 and day > 5 + leap(y... |
if method == 'equinox': return _to_jd_equinox(year, month, day) else: return _to_jd_schematic(year, month, day, method) |
def _to_jd_schematic(year, month, day, method): '''Calculate JD using various leap-year calculation methods''' y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0 intercal_cycle_yrs, over_cycle_yrs, leap_suppression_yrs = None, None, None # Use the every-four-years method below year 16 (madler) or below 15 (romme) if ((method in... |
= 4 if method in (4, 'continuous'): # Leap years: 15, 19, 23, ... y5 = -365 elif method in (100, 'romme'): year = year - 13 y5 = DAYS_IN_YEAR * 12 + 3 leap_suppression_yrs = 100. leap_suppression_days = 36524 # leap_cycle_days * 25 - 1 intercal_cycle_yrs = 400. intercal_cycle_days = 146097 # leap_suppression_days * 4 +... |
# intercal_cycle_days * 10 - 1 elif method in (128, 'madler'): year = year - 17 y5 = DAYS_IN_YEAR * 16 + 4 leap_suppression_days = 46751 # 32 * leap_cycle_days - 1 leap_suppression_yrs = 128 else: raise ValueError("Unknown leap year method. Try: continuous, romme, madler or equinox") if over_cycle_yrs: y0 = trunc(year ... |
cycles in days (400 years long or None) if intercal_cycle_yrs: y1 = trunc(year / intercal_cycle_yrs) * intercal_cycle_days year = year % intercal_cycle_yrs # count leap suppresion cycles in days (100 or 128 years long) if leap_suppression_yrs: y2 = trunc(year / leap_suppression_yrs) * leap_suppression_days year = year ... |
one to account for lack of year 0 y4 = year * DAYS_IN_YEAR yj = y0 + y1 + y2 + y3 + y4 + y5 mj = (month - 1) * 30 return EPOCH + yj + mj + day - 1 |
def from_jd(jd, method=None): '''Calculate date in the French Revolutionary calendar from Julian day. The five or six "sansculottides" are considered a thirteenth month in the results of this function.''' method = method or 'equinox' if method == 'equinox': return _from_jd_equinox(jd) else: return _from_jd_schematic(jd... |
def _from_jd_schematic(jd, method): '''Convert from JD using various leap-year calculation methods''' if jd < EPOCH: raise ValueError("Can't convert days before the French Revolution") # days since Epoch J = trunc(jd) + 0.5 - EPOCH y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0 intercal_cycle_days = leap_suppression_days = ... |
<= DAYS_IN_YEAR * 12 + 3 and method in (100, 'romme')) or (J <= DAYS_IN_YEAR * 17 + 4 and method in (128, 'madler')): method = 4 # set p and r in Hatcher algorithm if method in (4, 'continuous'): # Leap years: 15, 19, 23, ... # Reorganize so that leap day is last day of cycle J = J + 365 y5 |
= - 1 elif method in (100, 'romme'): # Year 15 is not a leap year # Year 16 is leap, then multiples of 4, not multiples of 100, yes multiples of 400 y5 = 12 J = J - DAYS_IN_YEAR * 12 - 3 leap_suppression_yrs = 100. leap_suppression_days = 36524 # LEAP_CYCLE_DAYS * 25 - 1 intercal_cycle_yrs = 400. intercal_cycle_days = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.