text
stringlengths
18
773k
def measure_mags(measures): """ Given a list of readings compute the magnitudes for all sources in each reading. @param measures: list of readings @return: None """ import daophot image_downloader = ImageDownloader() observations = {} for measure in measures: for reading i...
def match_planted(fk_candidate_observations, match_filename, bright_limit=BRIGHT_LIMIT, object_planted=OBJECT_PLANTED, minimum_bright_detections=MINIMUM_BRIGHT_DETECTIONS, bright_fraction=MINIMUM_BRIGHT_FRACTION): """ Using the fk_candidate_observations as input get the Object.planted file fro...
def append(self, item): """Adds a new item to the end of the collection.""" if len(self) == 0: # Special case, we make this the current item self.index = 0 self.items.append(item)
def fix_tags_on_cands_missing_reals(user_id, vos_dir, property): "At the moment this just checks for a single user's missing reals. Easy to generalise it to all users." con = context.get_context(vos_dir) user_progress = [] listing = con.get_listing(tasks.get_suffix('reals')) mpc_listing = con.get_li...
def make_error(self, message: str, *, error: Exception = None, # ``error_class: Type[Exception]=None`` doesn't work on # Python 3.5.2, but that is exact version ran by Read the # Docs :( More info: http://s...
def make_response(self, data: Any = None, **kwargs: Any) -> Any: r"""Validate response data and wrap it inside response factory. :param data: Response data. Could be ommited. :param \*\*kwargs: Keyword arguments to be passed to response factory. ...
def validate_request(self, data: Any, *additional: AnyMapping, merged_class: Type[dict] = dict) -> Any: r"""Validate request data against request schema from module. :param data: Request data. :param \*additional: ...
def _merge_data(self, data: AnyMapping, *additional: AnyMapping) -> dict: r"""Merge base data and additional dicts. :param data: Base data. :param \*additional: Additional data dicts to be merged into base dict. """ return defaults( dict(data) if not isinstance(data,...
def _pure_data(self, data: Any) -> Any: """ If data is dict-like object, convert it to pure dict instance, so it will be possible to pass to default ``jsonschema.validate`` func. :param data: Request or response data. """ if not isinstance(data, dict) and not isinstance(...
def _validate(self, data: Any, schema: AnyMapping) -> Any: """Validate data against given schema. :param data: Data to validate. :param schema: Schema to use for validation. """ try: return self.validate_func(schema, self._pure_data(data)) except self.validat...
def getCert(certHost=vos.vos.SERVER, certfile=None, certQuery="/cred/proxyCert?daysValid=",daysValid=2): """Access the cadc certificate server""" if certfile is None: certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem") dirname = os.path.dirname(certfile) try: ...
def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'): """"Getting the username/password for host from .netrc filie """ if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK): auth=netrc.netrc().authenticators(host) else: auth=False if not auth: sys.st...
def clear_tags(my_expnum, ops_set, my_ccds, dry_run=True): """ Clear the tags for the given expnum/ccd set. @param ops: @param my_expnum: @return: """ for ops in ops_set: for fake in ops[0]: for my_program in ops[1]: for version in ops[2]: props = {...
def to_bool(value: Any) -> bool: """Convert string or other Python object to boolean. **Rationalle** Passing flags is one of the most common cases of using environment vars and as values are strings we need to have an easy way to convert them to boolean Python value. Without this function int...
def to_int(value: str, default: T = None) -> Union[int, Optional[T]]: """Convert given value to int. If conversion failed, return default value without raising Exception. :param value: Value to convert to int. :param default: Default value to use in case of failed conversion. """ try: ...
def mk_dict(results,description): """Given a result list and descrition sequence, return a list of dictionaries""" rows=[] for row in results: row_dict={} for idx in range(len(row)): col=description[idx][0] row_dict[col]=row[idx] rows.append(row_dict)...
def get_orbits(official='%'): """Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned """ sql= "SELECT * FROM orbits WHERE official LIKE '%s' " % (official, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(),cfep...
def get_astrom(official='%',provisional='%'): """Query the measure table for all measurements of a particular object. Default is to return all the astrometry in the measure table, sorted by mjdate""" sql= "SELECT m.* FROM measure m " sql+="LEFT JOIN object o ON m.provisional LIKE o.provisional " ...
def getData(file_id,ra,dec): """Create a link that connects to a getData URL""" DATA="www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca" BASE="http://"+DATA+"/authProxy/getData" archive="CFHT" wcs="corrected" import re groups=re.match('^(?P<file_id>\d{6}).*',file_id) if not groups: return No...
def create_event(self, event): """Create event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be added) """ ev = api.Event.create(self.journal.collection, event) ev.save()
def update_event(self, event, uid): """Edit event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be updated) uid : uid of event to be updated """ ev_for_change = self.calendar.get(uid) ev_for_change.cont...
def delete_event(self, uid): """Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted """ ev_for_deletion = self.calendar.get(uid) ev_for_deletion.delete()
def simple_lmdb_settings(path, map_size=1e9, user_supplied_id=False): """ Creates a decorator that can be used to configure sane default LMDB persistence settings for a model Args: path (str): The path where the LMDB database files will be created map_size (int): The amount of space to ...
def simple_in_memory_settings(cls): """ Decorator that returns a class that "persists" data in-memory. Mostly useful for testing :param cls: the class whose features should be persisted in-memory :return: A new class that will persist features in memory """ class Settings(ff.PersistenceSe...
def offset(self, index=0): """Offset the camera pointing to be centred on a particular CCD.""" eta = self._geometry[self.camera][index]["ra"] xi = self._geometry[self.camera][index]["dec"] ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree dec = self.origin.dec - ...
def coord(self): """The center of the camera pointing in sky coordinates""" if self._coordinate is None: self._coordinate = SkyCoord(self.origin.ra, self.origin.dec + 45 * units.arcsec) return self._coordinate
def geometry(self): """Return an array of rectangles that represent the 'ra,dec' corners of the FOV @rtype: list """ if self.coord is None: return None ra = self.coord.ra.degree dec = self.coord.dec.degree ccds = [] for geo in self._geometry...
def separation(self, ra, dec): """Compute the separation between self and (ra,dec)""" if self.coord is None: return None return self.coord.separation(SkyCoord(ra, dec, unit=('degree', 'degree')))
def trim(hdu): """TRIM a CFHT MEGAPRIME frame using the DATASEC keyword""" datasec = re.findall(r'(\d+)', hdu.header.get('DATASEC')) l=int(datasec[0])-1 r=int(datasec[1]) b=int(datasec[2])-1 t=int(datasec[3]) if opt.verbose: print "Trimming [%d:%d,%d:%d]" % ...
def overscan(hdu): """Overscan subtract a CFHT MEGAPRIME frame. oversan(hdu) --> status The BIAS section keywords are expected to be BSEC[A|B] (for amps A and B) and the AMP sectoin is ASEC[A|B]. """ for amp in (['A','B']): AMPKW= 'ASEC'+amp BIASKW= 'BSEC'+amp dsec=re.f...
def requires_lock(function): """ Decorator to check if the user owns the required lock. The first argument must be the filename. """ def new_lock_requiring_function(self, filename, *args, **kwargs): if self.owns_lock(filename): return function(self, filename, *args, **kwargs) ...
def clean(self, suffixes=None): """ Remove all persistence-related files from the directory. """ if suffixes is None: suffixes = [DONE_SUFFIX, LOCK_SUFFIX, PART_SUFFIX] for suffix in suffixes: listing = self.working_context.get_listing(suffix) ...
def setFigForm(): """set the rcparams to EmulateApJ columnwidth=245.26 pts """ fig_width_pt = 245.26*2 inches_per_pt = 1.0/72.27 golden_mean = (math.sqrt(5.)-1.0)/2.0 fig_width = fig_width_pt*inches_per_pt fig_height = fig_width*golden_mean fig_size = [1.5*fig_width, fig_height] pa...
def getCert(username, password, certHost=_SERVER, certfile=None, certQuery=_PROXY): """Access the cadc certificate server.""" if certfile is None: certfile = tempfile.NamedTemporaryFile() # Add the username and password. # If we knew the realm, we could use ...
def getGroupsURL(certfile, group): """given a certfile load a list of groups that user is a member of""" GMS = "https://" + _SERVER + _GMS certfile.seek(0) buf = certfile.read() x509 = crypto.load_certificate(crypto.FILETYPE_PEM, buf) sep = "" dn = "" parts = [] for i in x509.get_...
def isMember(userid, password, group): """Test to see if the given userid/password combo is an authenticated member of group. userid: CADC Username (str) password: CADC Password (str) group: CADC GMS group (str) """ try: certfile = getCert(userid, password) group_url = get...
def stub(): """Just some left over code""" form = cgi.FieldStorage() userid = form['userid'].value password = form['passwd'].value group = form['group'].value
def sky2xypv(ra, dec, crpix1, crpix2, crval1, crval2, dc, pv, nord, maxiter=300): """ Transforms from celestial coordinates to pixel coordinates to taking non-linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe. For the inverse operation see xy2sky. ...
def xy2skypv(x, y, crpix1, crpix2, crval1, crval2, cd, pv, nord): """ Transforms from pixel coordinates to celestial coordinates taking non-linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe. For the inverse operation see sky2xy Reference material...
def parse_pv(header): """ Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]] Note that N de...
def safe_unit_norm(a): """ Ensure that the vector or vectors have unit norm """ if 1 == len(a.shape): n = np.linalg.norm(a) if n: return a / n return a norm = np.sum(np.abs(a) ** 2, axis=-1) ** (1. / 2) # Dividing by a norm of zero will cause a warning to be...
def pad(a, desiredlength): """ Pad an n-dimensional numpy array with zeros along the zero-th dimension so that it is the desired length. Return it unchanged if it is greater than or equal to the desired length """ if len(a) >= desiredlength: return a islist = isinstance(a, list) ...
def _wpad(l, windowsize, stepsize): """ Parameters l - The length of the input array windowsize - the size of each window of samples stepsize - the number of samples to move the window each step Returns The length the input array should be so that no samples are leftover ...
def _wcut(l, windowsize, stepsize): """ Parameters l - The length of the input array windowsize - the size of each window of samples stepsize - the number of samples to move the window each step Returns The length the input array should be so that leftover samples are ignore...
def windowed(a, windowsize, stepsize=None, dopad=False): """ Parameters a - the input array to restructure into overlapping windows windowsize - the size of each window of samples stepsize - the number of samples to shift the window each step. If not speci...
def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._posit...
def extend(self, items): """ extend the numpy array with multiple items, growing the wrapped array if necessary """ items = np.array(items) pos = items.shape[0] + self.logical_size if pos > self.physical_size: # more physical memory is needed than has ...
def display(self, cutout, use_pixel_coords=False): """ :param cutout: source cutout object to be display :type cutout: source.SourceCutout """ logging.debug("Current display list contains: {}".format(self._displayables_by_cutout.keys())) logging.debug("Looking for {}".for...
def draw_uncertainty_ellipse(self, cutout): """ Draws an ErrEllipse with the spcified dimensions. Only one ErrEllipse can be drawn and only once (not movable). """ if not self.mark_prediction: return try: colour = cutout.reading.from_input_file a...
def align(self, cutout, reading, source): """ Set the display center to the reference point. @param cutout: The cutout to align on @type cutout: SourceCutout @param reading: The reading this cutout is from @type reading: SourceReading @param source: The source ...
def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3, maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True): """ Compute the centroids and magnitudes of a bunch sources on fits image. :rtype : astropy.table.Table :param fits_filename: Name of fits image to...
def phot_mag(*args, **kwargs): """Wrapper around phot which only returns the computed magnitude directly.""" try: return phot(*args, **kwargs) except IndexError: raise TaskError("No photometric records returned for {0}".format(kwargs))
def all_blocks(self): status = OrderedDict.fromkeys(parameters.BLOCKS.keys()) status['13AE'] = ['discovery complete', '50', '24.05'] status['13AO'] = ['discovery complete', '36', '24.40'] status['13BL'] = ['discovery complete', '79', '24.48'] status['14BH'] = ['discovery running...
def from_env(key: str, default: T = None) -> Union[str, Optional[T]]: """Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None`` """ return os.getenv(key, ...
def immutable_settings(defaults: Settings, **optionals: Any) -> types.MappingProxyType: r"""Initialize and return immutable Settings dictionary. Settings dictionary allows you to setup settings values from multiple sources and make sure that values cannot be changed, updated by anyon...
def inject_settings(mixed: Union[str, Settings], context: MutableMapping[str, Any], fail_silently: bool = False) -> None: """Inject settings values to given context. :param mixed: Settings can be a string (that it will be read from Python path), Python mo...
def iter_settings(mixed: Settings) -> Iterator[Tuple[str, Any]]: """Iterate over settings values from settings module or dict-like instance. :param mixed: Settings instance to iterate. """ if isinstance(mixed, types.ModuleType): for attr in dir(mixed): if not is_setting_key(attr): ...
def setup_locale(lc_all: str, first_weekday: int = None, *, lc_collate: str = None, lc_ctype: str = None, lc_messages: str = None, lc_monetary: str = None, lc_numeric: str = None, lc_t...
def setup_timezone(timezone: str) -> None: """Shortcut helper to configure timezone for backend application. :param timezone: Timezone to use, e.g. "UTC", "Europe/Kiev". """ if timezone and hasattr(time, 'tzset'): tz_root = '/usr/share/zoneinfo' tz_filename = os.path.join(tz_root, *(tim...
def inputs(header): """Read through the HISTORY cards in an image header looking for detrend input lines. Detrend inputs are given on lines like: HISTORY imcombred: file_id We require that the value in file_id be store in the CADC archive before adding to the inputs list. """ import st...
def elixir_decode(elixir_filename): """ Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits """ import re, pyfits parts_RE=re.compile(r'([^\.\s]+)') dataset_name =...
def create_mef(filename=None): """ Create a file an MEF fits file called filename. Generate a random filename if None given """ import pyfits, time if not filename: ### here I know what filename is to start with. import tempfile filename=tempfile.mktemp(suffix='.fits') ...
def strip_pad(hdu): """Remove the padding lines that CFHT adds to headers""" l = hdu.header.ascardlist() d = [] for index in range(len(l)): if l[index].key in __comment_keys and str(l[index])==__cfht_padding: d.append(index) d.reverse() for index in d: del l[inde...
def stack(outfile,infiles,verbose=0): """ Stick infiles into outfiles as FITS extensions. outfile willl contain an MEF format file of the single extension FITS files named in the infiles array """ import os, sys, string, tempfile, shutil import pyfits, re, time ### if there is a pre-e...
def adGet(file_id, archive="CFHT", extno=None, cutout=None ): """Use get a fits image from the CADC.""" import os, string, re,urllib #proxy="http://www1.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData" proxy="http://test.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData" if file_id is No...
def _open(file,mode='copyonwrite'): """Opens a FITS format file and calls _open_fix if header doesn't verify correctly. """ import pyfits try: infits=pyfits.open(file,mode) hdu=infits except (ValueError,pyfits.VerifyError,pyfits.FITS_SevereError): import sys #...
def find_proc_date(header): """Search the HISTORY fields of a header looking for the FLIPS processing date. """ import string, re for h in header.ascardlist(): if h.key=="HISTORY": g=h.value if ( string.find(g,'FLIPS 1.0 -:') ): result=re.search('imred...
def find_detrend_keyword(header, type): """Search through header and find the elixir formated string(s) that match the the input 'type'. header is a FITS HDU. Elixir formated strings are crunid.type.filter/exptime.chipid.version. """ import re, string value='NULL' #print type fo...
def _open_fix(file): """Takes in a fits file name, open the file in binary mode and creates an HDU. Will attempt to fix some of the header keywords to match the standard FITS format. """ import pyfits, re, string temp = pyfits.HDUList() hdu = pyfits.PrimaryHDU() hdu._file=open(file,'rb') ...
def query_ssos(self, mpc_observations, lunation_count=None): """Send a query to the SSOS web service, looking for available observations using the given track. :param mpc_observations: a list of mpc.Observations :param lunation_count: how many dark runs (+ and -) to search into :return:...
def query_ssos(self, target_name, lunation_count=None): """Send a query to the SSOS web service, looking for available observations using the given track. :param target_name: name of target to query against SSOIS db :param lunation_count: ignored :rtype: SSOSData """ # ...
def build_source_reading(expnum, ccd=None, ftype='p'): """ Build an astrom.Observation object for a SourceReading :param expnum: (str) Name or CFHT Exposure number of the observation. :param ccd: (str) CCD is this observation associated with. (can be None) :param ftype: (str) ex...
def parse(self, ssos_result_filename_or_lines, mpc_observations=None): """ given the result table create 'source' objects. :param ssos_result_filename_or_lines: :param mpc_observations: a list of mpc.Observation objects used to retrieve the SSOS observations """ table_re...
def search_end_date(self, search_end_date): """ :type search_end_date: astropy.io.Time :param search_end_date: search for frames take after the given date. """ assert isinstance(search_end_date, Time) self._search_end_date = search_end_date.replicate(format='iso') ...
def params(self): """ :return: A dictionary of SSOS query parameters. :rtype: dict """ params = dict(format=RESPONSE_FORMAT, verbose=self.verbose, epoch1=str(self.search_start_date), epoch2=str(self.search_end_date...
def get(self): """ :return: A string containing the TSV result from SSOS :rtype: str :raise: AssertionError """ params = self.param_dict_builder.params logger.debug(pprint.pformat(format(params))) response = requests.post(SSOS_URL, ...
def SetFocus(self, **kwargs): """ Over-rides normal behaviour of shifting focus to any child. Prefers the one set explicityly by use_as_focus. :param **kwargs: """ if self._focus is not None: self._focus.SetFocus() else: # fall back on the...
def step3(expnums, ccd, version, rate_min, rate_max, angle, width, field=None, prefix=None, dry_run=False, maximum_flux_ratio=3, minimum_area=5, minimum_median_flux=1000.0): """run the actual step3 on the given exp/ccd combo""" jmp_args = ['step3jmp'] matt_args = ['step3jjk'] idx ...
def extract_init_args(instance): """ Given an instance, and under the assumption that member variables have the same name as the __init__ arguments, extract the arguments so they can be used to reconstruct the instance when deserializing """ cls = instance.__class__ args = [x for x in inspec...
def list(self,header,choices): "Display list of choices. As many as we can get in a page." if not self.__list_window: (y,x)=self.__main.getmaxyx() self.__list_window = self.__main.subwin(35,x,0,0) _lw=self.__list_window _lw.keypad(1) (y_ma...
def recenter(self): """ Reset the reference position values to correspond to the center of the reference frame. Algorithm used here developed by Colin Cox - 27-Jan-2004. """ if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: print 'WCS.recenter() o...
def _buildNewKeyname(self,key,prepend): """ Builds a new keyword based on original keyword name and a prepend string. """ if len(prepend+key) <= 8: _new_key = prepend+key else: _new_key = str(prepend+key)[:8] return _new_key
def copy(self,deep=yes): """ Makes a (deep)copy of this object for use by other objects. """ if deep: return copy.deepcopy(self) else: return copy.copy(self)
def scrambleTriples(expnums,ccd): """Pull the three images and then scramble the MJD-OBS keywords""" import pyfits, MOPfits mjd=[] fid=[] fs=[] filenames=[] for expnum in expnums: if int(ccd)<18: cutout="[-*,-*]" else: cutout="[*,*]" filenames....
def getTriples(expnums,ccd): """Pull the three images and then scramble the MJD-OBS keywords""" import pyfits, MOPfits filenames=[] for expnum in expnums: if int(ccd)<18: cutout="[-*,-*]" else: cutout="[*,*]" filenames.append(MOPfits.adGet(str(expnum)+opt....
def searchTriples(filenames,plant=False): """Given a list of exposure numbers, find all the KBOs in that set of exposures""" print filenames if opt.none : return import MOPfits,os import MOPdbaccess import string import os.path import pyfits if len(filenames)!=3: ...
def ushort(filename): """Ushort a the pixels""" import pyfits f=pyfits.open(filename,mode='update') f[0].scale('int16','',bzero=32768) f.flush() f.close()
def parse(self, filename): """ Parses a file into an AstromData structure. Args: filename: str The name of the file whose contents will be parsed. Returns: data: AstromData The file contents extracted into a data structure for programmatic ...
def _write_observation_headers(self, observations): """ See src/pipematt/step1matt-c """ for observation in observations: header = observation.header def get_header_vals(header_list): header_vals = [] for key in header_list: ...
def _write_sys_header(self, sys_header): """ See src/pipematt/step3matt-c """ header_vals = [sys_header[RMIN], sys_header[RMAX], sys_header[ANGLE], sys_header[AWIDTH]] self._write_line("## RMIN RMAX ANGLE AWIDTH") self._write_line("# %8.1...
def _write_source_data(self, sources): """ See src/jjk/measure3 """ for i, source in enumerate(sources): self._write_source(source)
def write_headers(self, observations, sys_header): """ Writes the header part of the astrom file so that only the source data has to be filled in. """ if self._header_written: raise AstromFormatError("Astrom file already has headers.") self._write_observation...
def write_source(self, source): """ Writes out data for a single source. """ if not self._header_written: observations = [reading.get_observation() for reading in source.get_readings()] self.write_headers(observations, self.sys_header) self._write_source(...
def write_astrom_data(self, astrom_data): """ Writes a full AstromData structure at once. """ self.write_headers(astrom_data.observations, astrom_data.sys_header) self._write_source_data(astrom_data.sources)
def _original_frame(self, x, y): """ Return x/y in the original frame, based on a guess as much as anything. :param x: x pixel coordinate :type x: float :param y: y pixel coordinate :type y: float :return: x,y :rtype: float, float """ if se...
def pix_coord(self, pix_coord): """ :type pix_coord: list :param pix_coord: an x,y pixel coordinate, origin = 1 """ try: pix_coord = list(pix_coord) except: pass if not isinstance(pix_coord, list) or len(pix_coord) != 2: raise V...
def reference_source_point(self): """ The location of the source in the reference image, in terms of the current image coordinates. """ xref = isinstance(self.xref, Quantity) and self.xref.value or self.xref yref = isinstance(self.yref, Quantity) and self.yref.value or se...
def get_coordinate_offset(self, other_reading): """ Calculates the offsets between readings' coordinate systems. Args: other_reading: ossos.astrom.SourceReading The reading to compare coordinate systems with. Returns: (offset_x, offset_y): Th...
def compute_inverted(self): """ Returns: inverted: bool True if the stored image is inverted. """ # astheader = storage.get_astheader(self.obs.expnum, self.obs.ccdnum, version=self.obs.ftype) # pvwcs = wcs.WCS(astheader) # (x, y) = pvwcs.sky2xy(self....
def from_source_reference(expnum, ccd, x, y): """ Given the location of a source in the image, create an Observation. """ image_uri = storage.dbimages_uri(expnum=expnum, ccd=None, version='p', ...