code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
record_set_md5 = get_record_set_md5(rs_dict["Name"], rs_dict["Type"]) rs = route53.RecordSetType.from_dict(record_set_md5, rs_dict) rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id) rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs) return self.template.add_resource(rs)
def create_record_set(self, rs_dict)
Accept a record_set dict. Return a Troposphere record_set object.
3.369064
2.985924
1.128315
rs = route53.RecordSetGroup.from_dict(name, g_dict) rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id) rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs) return self.template.add_resource(rs)
def create_record_set_group(self, name, g_dict)
Accept a record_set dict. Return a Troposphere record_set object.
3.938939
3.432224
1.147635
record_set_objects = [] for record_set_dict in record_set_dicts: # pop removes the 'Enabled' key and tests if True. if record_set_dict.pop('Enabled', True): record_set_objects.append( self.create_record_set(record_set_dict) ) return record_set_objects
def create_record_sets(self, record_set_dicts)
Accept list of record_set dicts. Return list of record_set objects.
3.108451
2.879383
1.079555
record_set_groups = [] for name, group in record_set_group_dicts.iteritems(): # pop removes the 'Enabled' key and tests if True. if group.pop('Enabled', True): record_set_groups.append( self.create_record_set_group(name, group) ) return record_set_groups
def create_record_set_groups(self, record_set_group_dicts)
Accept list of record_set_group dicts. Return list of record_set_group objects.
3.546461
3.463072
1.02408
list_buckets = [s3_arn(b) for b in buckets] object_buckets = [s3_objects_arn(b, folder) for b in buckets] bucket_resources = list_buckets + object_buckets return [ Statement( Effect=Allow, Resource=[s3_arn("*")], Action=[s3.ListAllMyBuckets] ), Statement( Effect=Allow, Resource=bucket_resources, Action=[Action('s3', 'Get*'), Action('s3', 'List*')] ) ]
def read_only_s3_bucket_policy_statements(buckets, folder="*")
Read only policy an s3 bucket.
3.162121
3.199392
0.988351
return Policy( Statement=[ Statement( Effect=Allow, Principal=Principal("*"), Action=[s3.GetObject], Resource=[s3_objects_arn(bucket)], ) ] )
def static_website_bucket_policy(bucket)
Attach this policy directly to an S3 bucket to make it a static website. This policy grants read access to **all unauthenticated** users.
2.978918
3.459396
0.861109
return [ Statement( Effect=Allow, Resource=['*'], Action=[ ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces, ec2.DeleteNetworkInterface, ] ) ]
def lambda_vpc_execution_statements()
Allow Lambda to manipuate EC2 ENIs for VPC support.
2.80062
2.444338
1.145758
return Policy( Statement=[ Statement( Effect=Allow, Resource=dynamodb_arns(tables), Action=[ dynamodb.DescribeTable, dynamodb.UpdateTable, ] ), Statement( Effect=Allow, Resource=['*'], Action=[ cloudwatch.PutMetricAlarm, cloudwatch.DescribeAlarms, cloudwatch.GetMetricStatistics, cloudwatch.SetAlarmState, cloudwatch.DeleteAlarms, ] ), ] )
def dynamodb_autoscaling_policy(tables)
Policy to allow AutoScaling a list of DynamoDB tables.
2.074776
2.036027
1.019032
return healpix_to_lonlat(healpix_index, self.nside, dx=dx, dy=dy, order=self.order)
def healpix_to_lonlat(self, healpix_index, dx=None, dy=None)
Convert HEALPix indices (optionally with offsets) to longitudes/latitudes Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix indices dx, dy : `~numpy.ndarray`, optional 1-D arrays of offsets inside the HEALPix pixel, which must be in the range [0:1] (0.5 is the center of the HEALPix pixels). If not specified, the position at the center of the pixel is used. Returns ------- lon : :class:`~astropy.coordinates.Longitude` The longitude values lat : :class:`~astropy.coordinates.Latitude` The latitude values
3.020779
6.224352
0.485316
return lonlat_to_healpix(lon, lat, self.nside, return_offsets=return_offsets, order=self.order)
def lonlat_to_healpix(self, lon, lat, return_offsets=False)
Convert longitudes/latitudes to HEALPix indices (optionally with offsets) Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` instances with angle units. return_offsets : bool If `True`, the returned values are the HEALPix pixel as well as ``dx`` and ``dy``, the fractional positions inside the pixel. If `False` (the default), only the HEALPix pixel is returned. Returns ------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix indices dx, dy : `~numpy.ndarray` 1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5 is the center of the HEALPix pixels). This is returned if ``return_offsets`` is `True`.
3.381206
7.115204
0.475209
return bilinear_interpolation_weights(lon, lat, self.nside, order=self.order)
def bilinear_interpolation_weights(self, lon, lat)
Get the four neighbours for each (lon, lat) position and the weight associated with each one for bilinear interpolation. Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` instances with angle units. Returns ------- indices : `~numpy.ndarray` 2-D array with shape (4, N) giving the four indices to use for the interpolation weights : `~numpy.ndarray` 2-D array with shape (4, N) giving the four weights to use for the interpolation
5.585576
10.212564
0.546932
if len(values) != self.npix: raise ValueError('values must be an array of length {0} (got {1})'.format(self.npix, len(values))) return interpolate_bilinear_lonlat(lon, lat, values, order=self.order)
def interpolate_bilinear_lonlat(self, lon, lat, values)
Interpolate values at specific longitudes/latitudes using bilinear interpolation If a position does not have four neighbours, this currently returns NaN. Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` instances with angle units. values : `~numpy.ndarray` 1-D array with the values in each HEALPix pixel. This must have a length of the form 12 * nside ** 2 (and nside is determined automatically from this). Returns ------- result : `~numpy.ndarray` 1-D array of interpolated values
2.905203
3.352129
0.866674
if not lon.isscalar or not lat.isscalar or not radius.isscalar: raise ValueError('The longitude, latitude and radius must be ' 'scalar Quantity objects') return healpix_cone_search(lon, lat, radius, self.nside, order=self.order)
def cone_search_lonlat(self, lon, lat, radius)
Find all the HEALPix pixels within a given radius of a longitude/latitude. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single lon/lat pair at a time, since different calls to the function may result in a different number of matches. Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude to search around radius : :class:`~astropy.units.Quantity` The search radius Returns ------- healpix_index : `~numpy.ndarray` 1-D array with all the matching HEALPix pixel indices.
4.085165
4.395921
0.929308
return boundaries_lonlat(healpix_index, step, self.nside, order=self.order)
def boundaries_lonlat(self, healpix_index, step)
Return the longitude and latitude of the edges of HEALPix pixels This returns the longitude and latitude of points along the edge of each HEALPIX pixel. The number of points returned for each pixel is ``4 * step``, so setting ``step`` to 1 returns just the corners. Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix pixels step : int The number of steps to take along each edge. Returns ------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude, as 2-D arrays where the first dimension is the same as the ``healpix_index`` input, and the second dimension has size ``4 * step``.
4.010952
11.983257
0.334713
return neighbours(healpix_index, self.nside, order=self.order)
def neighbours(self, healpix_index)
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel Parameters ---------- healpix_index : `~numpy.ndarray` Array of HEALPix pixels Returns ------- neigh : `~numpy.ndarray` Array giving the neighbours starting SW and rotating clockwise. This has one extra dimension compared to ``healpix_index`` - the first dimension - which is set to 8. For example if healpix_index has shape (2, 3), ``neigh`` has shape (8, 2, 3).
4.837823
10.275853
0.470795
if self.frame is None: raise NoFrameError("healpix_to_skycoord") lon, lat = self.healpix_to_lonlat(healpix_index, dx=dx, dy=dy) representation = UnitSphericalRepresentation(lon, lat, copy=False) return SkyCoord(self.frame.realize_frame(representation))
def healpix_to_skycoord(self, healpix_index, dx=None, dy=None)
Convert HEALPix indices (optionally with offsets) to celestial coordinates. Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.healpix_to_lonlat`. Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix indices dx, dy : `~numpy.ndarray`, optional 1-D arrays of offsets inside the HEALPix pixel, which must be in the range [0:1] (0.5 is the center of the HEALPix pixels). If not specified, the position at the center of the pixel is used. Returns ------- coord : :class:`~astropy.coordinates.SkyCoord` The resulting celestial coordinates
2.994009
3.092947
0.968012
if self.frame is None: raise NoFrameError("skycoord_to_healpix") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation.lon, representation.lat return self.lonlat_to_healpix(lon, lat, return_offsets=return_offsets)
def skycoord_to_healpix(self, skycoord, return_offsets=False)
Convert celestial coordinates to HEALPix indices (optionally with offsets). Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`. Parameters ---------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates to convert return_offsets : bool If `True`, the returned values are the HEALPix pixel as well as ``dx`` and ``dy``, the fractional positions inside the pixel. If `False` (the default), only the HEALPix pixel is returned. Returns ------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix indices dx, dy : `~numpy.ndarray` 1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5 is the center of the HEALPix pixels). This is returned if ``return_offsets`` is `True`.
2.643105
2.550197
1.036432
if self.frame is None: raise NoFrameError("interpolate_bilinear_skycoord") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation.lon, representation.lat return self.interpolate_bilinear_lonlat(lon, lat, values)
def interpolate_bilinear_skycoord(self, skycoord, values)
Interpolate values at specific celestial coordinates using bilinear interpolation. If a position does not have four neighbours, this currently returns NaN. Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.interpolate_bilinear_lonlat`. Parameters ---------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates at which to interpolate values : `~numpy.ndarray` 1-D array with the values in each HEALPix pixel. This must have a length of the form 12 * nside ** 2 (and nside is determined automatically from this). Returns ------- result : `~numpy.ndarray` 1-D array of interpolated values
2.921476
3.215598
0.908533
if self.frame is None: raise NoFrameError("cone_search_skycoord") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation.lon, representation.lat return self.cone_search_lonlat(lon, lat, radius)
def cone_search_skycoord(self, skycoord, radius)
Find all the HEALPix pixels within a given radius of a celestial position. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single celestial position at a time, since different calls to the function may result in a different number of matches. This method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.cone_search_lonlat`. Parameters ---------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates to use for the cone search radius : :class:`~astropy.units.Quantity` The search radius Returns ------- healpix_index : `~numpy.ndarray` 1-D array with all the matching HEALPix pixel indices.
2.822258
2.991918
0.943294
if self.frame is None: raise NoFrameError("boundaries_skycoord") lon, lat = self.boundaries_lonlat(healpix_index, step) representation = UnitSphericalRepresentation(lon, lat, copy=False) return SkyCoord(self.frame.realize_frame(representation))
def boundaries_skycoord(self, healpix_index, step)
Return the celestial coordinates of the edges of HEALPix pixels This returns the celestial coordinates of points along the edge of each HEALPIX pixel. The number of points returned for each pixel is ``4 * step``, so setting ``step`` to 1 returns just the corners. This method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`. Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix pixels step : int The number of steps to take along each edge. Returns ------- skycoord : :class:`~astropy.coordinates.SkyCoord` The celestial coordinates of the HEALPix pixel boundaries
3.932909
3.767884
1.043798
level = np.asarray(level, dtype=np.int64) _validate_level(level) return 2 ** level
def level_to_nside(level)
Find the pixel dimensions of the top-level HEALPix tiles. This is given by ``nside = 2**level``. Parameters ---------- level : int The resolution level Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
4.753771
9.311908
0.510505
nside = np.asarray(nside, dtype=np.int64) _validate_nside(nside) return np.log2(nside).astype(np.int64)
def nside_to_level(nside)
Find the HEALPix level for a given nside. This is given by ``level = log2(nside)``. This function is the inverse of `level_to_nside`. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Must be a power of two. Returns ------- level : int The level of the HEALPix cells
2.776373
5.36861
0.517149
uniq = np.asarray(uniq, dtype=np.int64) level = (np.log2(uniq//4)) // 2 level = level.astype(np.int64) _validate_level(level) ipix = uniq - (1 << 2*(level + 1)) _validate_npix(level, ipix) return level, ipix
def uniq_to_level_ipix(uniq)
Convert a HEALPix cell uniq number to its (level, ipix) equivalent. A uniq number is a 64 bits integer equaling to : ipix + 4*(4**level). Please read this `paper <http://ivoa.net/documents/MOC/20140602/REC-MOC-1.0-20140602.pdf>`_ for more details about uniq numbers. Parameters ---------- uniq : int The uniq number of a HEALPix cell. Returns ------- level, ipix: int, int The level and index of the HEALPix cell computed from ``uniq``.
3.949273
4.587614
0.860856
level = np.asarray(level, dtype=np.int64) ipix = np.asarray(ipix, dtype=np.int64) _validate_level(level) _validate_npix(level, ipix) return ipix + (1 << 2*(level + 1))
def level_ipix_to_uniq(level, ipix)
Convert a level and HEALPix index into a uniq number representing the cell. This function is the inverse of `uniq_to_level_ipix`. Parameters ---------- level : int The level of the HEALPix cell ipix : int The index of the HEALPix cell Returns ------- uniq : int The uniq number representing the HEALPix cell.
3.117934
4.299514
0.725183
nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) npix = 12 * nside * nside pixel_area = 4 * math.pi / npix * u.sr return pixel_area
def nside_to_pixel_area(nside)
Find the area of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- pixel_area : :class:`~astropy.units.Quantity` The area of the HEALPix pixels
3.164237
4.785823
0.661169
nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin)
def nside_to_pixel_resolution(nside)
Find the resolution of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- resolution : :class:`~astropy.units.Quantity` The resolution of the HEALPix pixels See also -------- pixel_resolution_to_nside
2.97333
5.323918
0.558485
resolution = resolution.to(u.rad).value pixel_area = resolution * resolution npix = 4 * math.pi / pixel_area nside = np.sqrt(npix / 12) # Now we have to round to the closest ``nside`` # Since ``nside`` must be a power of two, # we first compute the corresponding ``level = log2(nside)` # round the level and then go back to nside level = np.log2(nside) if round == 'up': level = np.ceil(level) elif round == 'nearest': level = np.round(level) elif round == 'down': level = np.floor(level) else: raise ValueError('Invalid value for round: {!r}'.format(round)) # For very low requested resolution (i.e. large angle values), we # return ``level=0``, i.e. ``nside=1``, i.e. the lowest resolution # that exists with HEALPix level = np.clip(level.astype(int), 0, None) return level_to_nside(level)
def pixel_resolution_to_nside(resolution, round='nearest')
Find closest HEALPix nside for a given angular resolution. This function is the inverse of `nside_to_pixel_resolution`, for the default rounding scheme of ``round='nearest'``. If you choose ``round='up'``, you'll get HEALPix pixels that have at least the requested resolution (usually a bit better due to rounding). Pixel resolution is defined as square root of pixel area. Parameters ---------- resolution : `~astropy.units.Quantity` Angular resolution round : {'up', 'nearest', 'down'} Which way to round Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Always a power of 2. Examples -------- >>> from astropy import units as u >>> from astropy_healpix import pixel_resolution_to_nside >>> pixel_resolution_to_nside(13 * u.arcmin) 256 >>> pixel_resolution_to_nside(13 * u.arcmin, round='up') 512
4.175046
4.756621
0.877734
nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) return 12 * nside ** 2
def nside_to_npix(nside)
Find the number of pixels corresponding to a HEALPix resolution. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- npix : int The number of pixels in the HEALPix map.
3.204844
5.655866
0.566641
npix = np.asanyarray(npix, dtype=np.int64) if not np.all(npix % 12 == 0): raise ValueError('Number of pixels must be divisible by 12') square_root = np.sqrt(npix / 12) if not np.all(square_root ** 2 == npix / 12): raise ValueError('Number of pixels is not of the form 12 * nside ** 2') return np.round(square_root).astype(int)
def npix_to_nside(npix)
Find the number of pixels on the side of one of the 12 'top-level' HEALPix tiles given a total number of pixels. Parameters ---------- npix : int The number of pixels in the HEALPix map. Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
2.698411
2.882182
0.936239
_validate_nside(nside) if _validate_order(order) == 'ring': func = _core.healpix_ring_to_lonlat else: # _validate_order(order) == 'nested' func = _core.healpix_nested_to_lonlat if dx is None: dx = 0.5 else: _validate_offset('x', dx) if dy is None: dy = 0.5 else: _validate_offset('y', dy) nside = np.asarray(nside, dtype=np.intc) lon, lat = func(healpix_index, nside, dx, dy) lon = Longitude(lon, unit=u.rad, copy=False) lat = Latitude(lat, unit=u.rad, copy=False) return lon, lat
def healpix_to_lonlat(healpix_index, nside, dx=None, dy=None, order='ring')
Convert HEALPix indices (optionally with offsets) to longitudes/latitudes. If no offsets (``dx`` and ``dy``) are provided, the coordinates will default to those at the center of the HEALPix pixels. Parameters ---------- healpix_index : int or `~numpy.ndarray` HEALPix indices (as a scalar or array) nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles dx, dy : float or `~numpy.ndarray`, optional Offsets inside the HEALPix pixel, which must be in the range [0:1], where 0.5 is the center of the HEALPix pixels (as scalars or arrays) order : { 'nested' | 'ring' }, optional Order of HEALPix pixels Returns ------- lon : :class:`~astropy.coordinates.Longitude` The longitude values lat : :class:`~astropy.coordinates.Latitude` The latitude values
2.203311
2.13926
1.029941
if _validate_order(order) == 'ring': func = _core.lonlat_to_healpix_ring else: # _validate_order(order) == 'nested' func = _core.lonlat_to_healpix_nested nside = np.asarray(nside, dtype=np.intc) lon = lon.to_value(u.rad) lat = lat.to_value(u.rad) healpix_index, dx, dy = func(lon, lat, nside) if return_offsets: return healpix_index, dx, dy else: return healpix_index
def lonlat_to_healpix(lon, lat, nside, return_offsets=False, order='ring')
Convert longitudes/latitudes to HEALPix indices Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` instances with angle units. nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles order : { 'nested' | 'ring' } Order of HEALPix pixels return_offsets : bool, optional If `True`, the returned values are the HEALPix pixel indices as well as ``dx`` and ``dy``, the fractional positions inside the pixels. If `False` (the default), only the HEALPix pixel indices is returned. Returns ------- healpix_index : int or `~numpy.ndarray` The HEALPix indices dx, dy : `~numpy.ndarray` Offsets inside the HEALPix pixel in the range [0:1], where 0.5 is the center of the HEALPix pixels
2.473161
2.367261
1.044735
nside = np.asarray(nside, dtype=np.intc) return _core.nested_to_ring(nested_index, nside)
def nested_to_ring(nested_index, nside)
Convert a HEALPix 'nested' index to a HEALPix 'ring' index Parameters ---------- nested_index : int or `~numpy.ndarray` Healpix index using the 'nested' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles Returns ------- ring_index : int or `~numpy.ndarray` Healpix index using the 'ring' ordering
4.212154
7.886545
0.534094
nside = np.asarray(nside, dtype=np.intc) return _core.ring_to_nested(ring_index, nside)
def ring_to_nested(ring_index, nside)
Convert a HEALPix 'ring' index to a HEALPix 'nested' index Parameters ---------- ring_index : int or `~numpy.ndarray` Healpix index using the 'ring' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles Returns ------- nested_index : int or `~numpy.ndarray` Healpix index using the 'nested' ordering
4.088155
7.70601
0.530515
lon = lon.to_value(u.rad) lat = lat.to_value(u.rad) _validate_nside(nside) nside = np.asarray(nside, dtype=np.intc) result = _core.bilinear_interpolation_weights(lon, lat, nside) indices = np.stack(result[:4]) weights = np.stack(result[4:]) if _validate_order(order) == 'nested': indices = ring_to_nested(indices, nside) return indices, weights
def bilinear_interpolation_weights(lon, lat, nside, order='ring')
Get the four neighbours for each (lon, lat) position and the weight associated with each one for bilinear interpolation. Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` instances with angle units. nside : int Number of pixels along the side of each of the 12 top-level HEALPix tiles order : { 'nested' | 'ring' } Order of HEALPix pixels Returns ------- indices : `~numpy.ndarray` 2-D array with shape (4, N) giving the four indices to use for the interpolation weights : `~numpy.ndarray` 2-D array with shape (4, N) giving the four weights to use for the interpolation
3.625296
3.210458
1.129215
nside = npix_to_nside(values.shape[0]) indices, weights = bilinear_interpolation_weights(lon, lat, nside, order=order) values = values[indices] # At this point values has shape (N, M) where both N and M might be several # dimensions, and weights has shape (N,), so we need to transpose in order # to benefit from broadcasting, then transpose back so that the dimension # with length 4 is at the start again, ready for summing. result = (values.T * weights.T).T return result.sum(axis=0)
def interpolate_bilinear_lonlat(lon, lat, values, order='ring')
Interpolate values at specific longitudes/latitudes using bilinear interpolation Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` instances with angle units. values : `~numpy.ndarray` Array with the values in each HEALPix pixel. The first dimension should have length 12 * nside ** 2 (and nside is determined automatically from this). order : { 'nested' | 'ring' } Order of HEALPix pixels Returns ------- result : float `~numpy.ndarray` The interpolated values
5.861803
6.694654
0.875595
_validate_nside(nside) nside = np.asarray(nside, dtype=np.intc) if _validate_order(order) == 'ring': func = _core.neighbours_ring else: # _validate_order(order) == 'nested' func = _core.neighbours_nested return np.stack(func(healpix_index, nside))
def neighbours(healpix_index, nside, order='ring')
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel Parameters ---------- healpix_index : `~numpy.ndarray` Array of HEALPix pixels nside : int Number of pixels along the side of each of the 12 top-level HEALPix tiles order : { 'nested' | 'ring' } Order of HEALPix pixels Returns ------- neigh : `~numpy.ndarray` Array giving the neighbours starting SW and rotating clockwise. This has one extra dimension compared to ``healpix_index`` - the first dimension - which is set to 8. For example if healpix_index has shape (2, 3), ``neigh`` has shape (8, 2, 3).
3.364803
3.943699
0.85321
lon = lon.to_value(u.deg) lat = lat.to_value(u.deg) radius = radius.to_value(u.deg) _validate_nside(nside) order = _validate_order(order) return _core.healpix_cone_search(lon, lat, radius, nside, order)
def healpix_cone_search(lon, lat, radius, nside, order='ring')
Find all the HEALPix pixels within a given radius of a longitude/latitude. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single lon/lat pair at a time, since different calls to the function may result in a different number of matches. Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude to search around radius : :class:`~astropy.units.Quantity` The search radius nside : int Number of pixels along the side of each of the 12 top-level HEALPix tiles order : { 'nested' | 'ring' } Order of HEALPix pixels Returns ------- healpix_index : `~numpy.ndarray` 1-D array with all the matching HEALPix pixel indices.
2.117633
2.719937
0.778559
healpix_index = np.asarray(healpix_index, dtype=np.int64) step = int(step) if step < 1: raise ValueError('step must be at least 1') # PERF: this could be optimized by writing a Cython routine to do this to # avoid allocating temporary arrays frac = np.linspace(0., 1., step + 1)[:-1] dx = np.hstack([1 - frac, np.repeat(0, step), frac, np.repeat(1, step)]) dy = np.hstack([np.repeat(1, step), 1 - frac, np.repeat(0, step), frac]) healpix_index, dx, dy = np.broadcast_arrays(healpix_index.reshape(-1, 1), dx, dy) lon, lat = healpix_to_lonlat(healpix_index.ravel(), nside, dx.ravel(), dy.ravel(), order=order) lon = lon.reshape(-1, 4 * step) lat = lat.reshape(-1, 4 * step) return lon, lat
def boundaries_lonlat(healpix_index, step, nside, order='ring')
Return the longitude and latitude of the edges of HEALPix pixels This returns the longitude and latitude of points along the edge of each HEALPIX pixel. The number of points returned for each pixel is ``4 * step``, so setting ``step`` to 1 returns just the corners. Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix pixels step : int The number of steps to take along each edge. nside : int Number of pixels along the side of each of the 12 top-level HEALPix tiles order : { 'nested' | 'ring' } Order of HEALPix pixels Returns ------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude, as 2-D arrays where the first dimension is the same as the ``healpix_index`` input, and the second dimension has size ``4 * step``.
2.609551
2.464078
1.059038
resolution = nside_to_pixel_resolution(nside) if arcmin: return resolution.to(u.arcmin).value else: return resolution.to(u.rad).value
def nside2resol(nside, arcmin=False)
Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`.
2.682082
2.749458
0.975495
area = nside_to_pixel_area(nside) if degrees: return area.to(u.deg ** 2).value else: return area.to(u.sr).value
def nside2pixarea(nside, degrees=False)
Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`.
2.354523
2.604379
0.904063
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return _lonlat_to_healpy(lon, lat, lonlat=lonlat)
def pix2ang(nside, ipix, nest=False, lonlat=False)
Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`.
3.447283
3.199796
1.077344
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
def ang2pix(nside, theta, phi, nest=False, lonlat=False)
Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`.
3.974988
3.71977
1.068611
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return ang2vec(*_lonlat_to_healpy(lon, lat))
def pix2vec(nside, ipix, nest=False)
Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.
4.445826
4.251808
1.045632
theta, phi = vec2ang(np.transpose([x, y, z])) # hp.vec2ang() returns raveled arrays, which are 1D. if np.isscalar(x): theta = theta.item() phi = phi.item() else: shape = np.shape(x) theta = theta.reshape(shape) phi = phi.reshape(shape) lon, lat = _healpy_to_lonlat(theta, phi) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
def vec2pix(nside, x, y, z, nest=False)
Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`.
3.841968
3.604975
1.06574
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return nested_to_ring(ipix, nside)
def nest2ring(nside, ipix)
Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`.
3.223363
2.96521
1.087061
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return ring_to_nested(ipix, nside)
def ring2nest(nside, ipix)
Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`.
3.395591
3.210824
1.057545
pix = np.asarray(pix) if pix.ndim > 1: # For consistency with healpy we only support scalars or 1D arrays raise ValueError("Array has to be one dimensional") lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring') rep_sph = UnitSphericalRepresentation(lon, lat) rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1) if rep_car.shape[0] == 1: return rep_car[0] else: return rep_car
def boundaries(nside, pix, step=1, nest=False)
Drop-in replacement for healpy `~healpy.boundaries`.
4.372715
4.210114
1.038622
x, y, z = vectors.transpose() rep_car = CartesianRepresentation(x, y, z) rep_sph = rep_car.represent_as(UnitSphericalRepresentation) return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat)
def vec2ang(vectors, lonlat=False)
Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`.
3.894551
3.650446
1.06687
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) rep_sph = UnitSphericalRepresentation(lon, lat) rep_car = rep_sph.represent_as(CartesianRepresentation) return rep_car.xyz.value
def ang2vec(theta, phi, lonlat=False)
Drop-in replacement for healpy `~healpy.pixelfunc.ang2vec`.
3.557552
3.277907
1.085312
# if phi is not given, theta is interpreted as pixel number if phi is None: theta, phi = pix2ang(nside, ipix=theta, nest=nest) lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return bilinear_interpolation_weights(lon, lat, nside, order='nested' if nest else 'ring')
def get_interp_weights(nside, theta, phi=None, nest=False, lonlat=False)
Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_weights`. Although note that the order of the weights and pixels may differ.
3.912051
4.048783
0.966229
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return interpolate_bilinear_lonlat(lon, lat, m, order='nested' if nest else 'ring')
def get_interp_val(m, theta, phi, nest=False, lonlat=False)
Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_val`.
5.76376
5.151153
1.118926
results = [] if fast: SIZES = [10, 1e3, 1e5] else: SIZES = [10, 1e3, 1e6] for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('pix2ang', bench_pix2ang, fast=fast, size=int(size), nside=nside, nest=nest)) for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('ang2pix', bench_ang2pix, fast=fast, size=int(size), nside=nside, nest=nest)) for size in SIZES: for nside in [1, 128]: results.append(run_single('nest2ring', bench_nest2ring, fast=fast, size=int(size), nside=nside)) for size in SIZES: for nside in [1, 128]: results.append(run_single('ring2nest', bench_ring2nest, fast=fast, size=int(size), nside=nside)) for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('get_interp_weights', bench_get_interp_weights, fast=fast, size=int(size), nside=nside, nest=nest)) return results
def bench_run(fast=False)
Run all benchmarks. Return results as a dict.
1.742473
1.733453
1.005204
table = Table(names=['function', 'nest', 'nside', 'size', 'time_healpy', 'time_self', 'ratio'], dtype=['S20', bool, int, int, float, float, float], masked=True) for row in results: table.add_row(row) table['time_self'].format = '10.7f' if HEALPY_INSTALLED: table['ratio'] = table['time_self'] / table['time_healpy'] table['time_healpy'].format = '10.7f' table['ratio'].format = '7.2f' table.pprint(max_lines=-1)
def bench_report(results)
Print a report for given benchmark results to the console.
3.824862
3.946434
0.969194
print('Running benchmarks...\n') results = bench_run(fast=fast) bench_report(results)
def main(fast=False)
Run all benchmarks and print report to the console.
8.428847
5.519098
1.527215
app.scoped_session = self @app.teardown_appcontext def remove_scoped_session(*args, **kwargs): # pylint: disable=missing-docstring,unused-argument,unused-variable app.scoped_session.remove()
def init_app(self, app)
Setup scoped sesssion creation and teardown for the passed ``app``. :param app: a :class:`~flask.Flask` application
3.874642
4.521788
0.856883
cache = f.cache = {} @functools.wraps(f) def decorator(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = f(*args, **kwargs) return cache[key] return decorator
def cached(f)
Cache decorator for functions taking one or more arguments. :param f: The function to be cached. :return: The cached value.
1.981943
2.205919
0.898466
templates_folder = 'templates' static_folder = 'dist' default_config = { 'client_realm': 'null', 'client_id': 'null', 'client_secret': 'null', 'app_name': 'null', 'docExpansion': "none", 'jsonEditor': False, 'defaultModelRendering': 'schema', 'showRequestHeaders': False, 'supportedSubmitMethods': ['get', 'post', 'put', 'delete', 'patch'], } if config: default_config.update(config) default_context = { 'page_title': page_title, 'favicon_url': favicon_url, 'base_url': uri_prefix + swagger_uri, 'api_url': api_url, 'app_name': default_config.pop('app_name'), 'client_realm': default_config.pop('client_realm'), 'client_id': default_config.pop('client_id'), 'client_secret': default_config.pop('client_secret'), # Rest are just serialized into json string # for inclusion in the .js file 'config_json': json.dumps(default_config) } app.add_sink( StaticSinkAdapter(static_folder), r'%s/(?P<filepath>.*)\Z' % swagger_uri, ) app.add_route( swagger_uri, SwaggerUiResource(templates_folder, default_context) )
def register_swaggerui_app(app, swagger_uri, api_url, page_title='Swagger UI', favicon_url=None, config=None, uri_prefix="")
:type app: falcon.API
2.99204
2.869084
1.042856
self.app = app self.dynamic_url = self.app.config.get('APIDOC_DYNAMIC_URL', self.dynamic_url) self.allow_absolute_url = self.app.config.get('APIDOC_ALLOW_ABSOLUTE_URL', self.allow_absolute_url) url = self.url_path if not self.url_path.endswith('/'): url += '/' app.add_url_rule(url, 'docs', self.__send_static_file, strict_slashes=True) app.add_url_rule(url + '<path:path>', 'docs', self.__send_static_file, strict_slashes=True)
def init_app(self, app)
Adds the flask url routes for the apidoc files. :param app: the flask application.
2.630974
2.553069
1.030514
if not path: path = 'index.html' file_name = join(self.folder_path, path) # the api_project.js has the absolute url # hard coded so we replace them by the current url. if self.dynamic_url and path == 'api_project.js': return self.__send_api_file(file_name) if self.allow_absolute_url and path == 'main.js': return self.__send_main_file(file_name) # Any other apidoc file is treated as a normal static file return self.app.send_static_file(file_name)
def __send_static_file(self, path=None)
Send apidoc files from the apidoc folder to the browser. :param path: the apidoc file.
5.904084
5.508704
1.071774
file_name = join(self.app.static_folder, file_name) with codecs.open(file_name, 'r', 'utf-8') as file: data = file.read() # replaces the hard coded url by the current url. api_project = self.__read_api_project() old_url = api_project.get('url') # replaces the project's url only if it is present in the file. if old_url: new_url = request.url_root.strip('/') data = data.replace(old_url, new_url) # creates a flask response to send # the file to the browser headers = Headers() headers['Content-Length'] = getsize(file_name) response = self.app.response_class(data, mimetype=mimetypes.guess_type(file_name)[0], headers=headers, direct_passthrough=True) response.last_modified = int(getmtime(file_name)) return response
def __send_api_file(self, file_name)
Send apidoc files from the apidoc folder to the browser. This method replaces all absolute urls in the file by the current url. :param file_name: the apidoc file.
3.583632
3.221468
1.112422
file_name = join(self.app.static_folder, file_name) with codecs.open(file_name, 'r', 'utf-8') as file: data = file.read() data = data.replace( 'fields.article.url = apiProject.url + fields.article.url;', '''if (fields.article.url.substr(0, 4).toLowerCase() !== \'http\') fields.article.url = apiProject.url + fields.article.url;''') headers = Headers() headers['Content-Length'] = getsize(file_name) response = self.app.response_class(data, mimetype=mimetypes.guess_type(file_name)[0], headers=headers, direct_passthrough=True) response.last_modified = int(getmtime(file_name)) return response
def __send_main_file(self, file_name)
Send apidoc files from the apidoc folder to the browser. This method replaces all absolute urls in the file by the current url. :param file_name: the apidoc file.
3.304463
3.121084
1.058755
file_name = join(self.app.static_folder, self.folder_path, 'api_project.json') with open(file_name, 'rt') as file: data = file.read() return json.loads(data)
def __read_api_project(self)
Reads the api_project.json file from apidoc folder as a json string. :return: a json string
4.219954
3.570947
1.181746
text_dict = { "error": reason } if data is not None: text_dict["errors"] = data raise cls( text=json.dumps(text_dict), content_type="application/json" )
def _raise_exception(cls, reason, data=None)
Raise aiohttp exception and pass payload/reason into it.
3.154145
2.842243
1.109738
validator = validator_cls(schema) _errors = defaultdict(list) for err in validator.iter_errors(data): path = err.schema_path # Code courtesy: Ruslan Karalkin # Looking in error schema path for # property that failed validation # Schema example: # { # "type": "object", # "properties": { # "foo": {"type": "number"}, # "bar": {"type": "string"} # } # "required": ["foo", "bar"] # } # # Related err.schema_path examples: # ['required'], # ['properties', 'foo', 'type'] if "properties" in path: path.remove("properties") key = path.popleft() # If validation failed by missing property, # then parse err.message to find property name # as it always first word enclosed in quotes if key == "required": key = err.message.split("'")[1] _errors[key].append(str(err)) if _errors: _raise_exception( web.HTTPBadRequest, "Request is invalid; There are validation errors.", _errors)
def _validate_data(data, schema, validator_cls)
Validate the dict against given schema (using given validator class).
5.124474
5.108462
1.003134
def wrapper(func): # Validating the schemas itself. # Die with exception if they aren't valid if request_schema is not None: _request_schema_validator = validator_for(request_schema) _request_schema_validator.check_schema(request_schema) if response_schema is not None: _response_schema_validator = validator_for(response_schema) _response_schema_validator.check_schema(response_schema) @asyncio.coroutine @functools.wraps(func) def wrapped(*args): if asyncio.iscoroutinefunction(func): coro = func else: coro = asyncio.coroutine(func) # Supports class based views see web.View if isinstance(args[0], AbstractView): class_based = True request = args[0].request else: class_based = False request = args[-1] # Strictly expect json object here try: req_body = yield from request.json() except (json.decoder.JSONDecodeError, TypeError): _raise_exception( web.HTTPBadRequest, "Request is malformed; could not decode JSON object.") # Validate request data against request schema (if given) if request_schema is not None: _validate_data(req_body, request_schema, _request_schema_validator) coro_args = req_body, request if class_based: coro_args = (args[0], ) + coro_args context = yield from coro(*coro_args) # No validation of response for websockets stream if isinstance(context, web.StreamResponse): return context # Validate response data against response schema (if given) if response_schema is not None: _validate_data(context, response_schema, _response_schema_validator) try: return web.json_response(context) except (TypeError, ): _raise_exception( web.HTTPInternalServerError, "Response is malformed; could not encode JSON object.") # Store schemas in wrapped handlers, so it later can be reused setattr(wrapped, "_request_schema", request_schema) setattr(wrapped, "_response_schema", response_schema) return wrapped return wrapper
def validate(request_schema=None, response_schema=None)
Decorate request handler to make it automagically validate it's request and response.
2.886258
2.856065
1.010572
print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))
def cli(yamlfile, inline, format)
Generate JSON Schema representation of a biolink model
10.185239
8.489369
1.199764
rval = dict() for k, v in data.__dict__.items(): if not k.startswith('_') and v is not None and (not isinstance(v, (dict, list)) or v): rval[k] = v return dumper.represent_data(rval)
def root_representer(dumper: yaml.Dumper, data: YAMLRoot)
YAML callback -- used to filter out empty values (None, {}, [] and false) @param dumper: data dumper @param data: data to be dumped @return:
3.213667
3.101948
1.036016
MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages)
def cli(yamlfile, format, dir, classes, img, noimages)
Generate markdown documentation of a biolink model
5.614479
5.8095
0.966431
if not self.gen_classes: return True elif en in self.schema.classes: return en in self.gen_classes_neighborhood.classrefs elif en in self.schema.slots: return en in self.gen_classes_neighborhood.slotrefs elif en in self.schema.types: return en in self.gen_classes_neighborhood.typerefs else: return True
def is_secondary_ref(self, en: str) -> bool
Determine whether 'en' is the name of something in the neighborhood of the requested classes @param en: element name @return: True if 'en' is the name of a slot, class or type in the immediate neighborhood of of what we are building
3.761022
2.836947
1.325729
return obj.name if isinstance(obj, Element ) else f'**{obj}**' if obj in builtin_names else obj
def bbin(obj: Union[str, Element]) -> str
Boldify built in types @param obj: object name or id @return:
14.442898
13.74709
1.050615
if obj.description and doing_descs: if isinstance(obj, SlotDefinition) and obj.is_a: parent = self.schema.slots[obj.is_a] elif isinstance(obj, ClassDefinition) and obj.is_a: parent = self.schema.classes[obj.is_a] else: parent = None return '' if parent and obj.description == parent.description else obj.description return ''
def desc_for(self, obj: Element, doing_descs: bool) -> str
Return a description for object if it is unique (different than its parent) @param obj: object to be described @param doing_descs: If false, always return an empty string @return: text or empty string
2.956663
2.92631
1.010373
obj = self.obj_for(ref) if isinstance(ref, str) else ref nl = '\n' if isinstance(obj, str) or obj is None or not self.is_secondary_ref(obj.name): return self.bbin(ref) if isinstance(obj, SlotDefinition): link_name = ((be(obj.domain) + '.') if obj.alias else '') + self.aliased_slot_name(obj) link_ref = underscore(obj.name) else: link_name = self.obj_name(obj) link_ref = link_name desc = self.desc_for(obj, use_desc) return f'[{link_name}]' \ f'({link_ref}.{self.format})' + \ (f' *subsets*: ({"| ".join(obj.in_subset)})' if add_subset and obj.in_subset else '') + \ (f' {after_link} ' if after_link else '') + (f' - {desc.split(nl)[0]}' if desc else '')
def link(self, ref: Optional[Union[str, Element]], *, after_link: str = None, use_desc: bool=False, add_subset: bool=True) -> str
Create a link to ref if appropriate. @param ref: the name or value of a class, slot, type or the name of a built in type. @param after_link: Text to put between link and description @param use_desc: True means append a description after the link if available @param add_subset: True means add any subset information that is available @return:
5.036597
4.902555
1.027341
print(OwlSchemaGenerator(yamlfile, format).serialize(output=output))
def cli(yamlfile, format, output)
Generate an OWL representation of a biolink model
12.318312
10.428553
1.18121
# Note: We use the raw name in OWL and add a subProperty arc slot_uri = self.prop_uri(slot.name) # Parent slots if slot.is_a: self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(slot.is_a))) for mixin in slot.mixins: self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(mixin))) # Slot range if not slot.range or slot.range in builtin_names: self.graph.add((slot_uri, RDF.type, OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, URIRef(builtin_uri(slot.range, expand=True)))) elif slot.range in self.schema.types: self.graph.add((slot_uri, RDF.type, OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, self.type_uri(slot.range))) else: self.graph.add((slot_uri, RDF.type, OWL.ObjectProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, self.class_uri(slot.range))) # Slot domain if slot.domain: self.graph.add((slot_uri, RDFS.domain, self.class_uri(slot.domain))) # Annotations self.graph.add((slot_uri, RDFS.label, Literal(slot.name))) if slot.description: self.graph.add((slot_uri, OBO.IAO_0000115, Literal(slot.description)))
def visit_slot(self, slot_name: str, slot: SlotDefinition) -> None
Add a slot definition per slot @param slot_name: @param slot: @return:
2.154574
2.147642
1.003228
if isinstance(data, str): if '\n' in data: return load_raw_schema((cast(TextIO, StringIO(data)))) # Not sure why typing doesn't see StringIO as TextIO elif '://' in data: # TODO: complete and test URL access req = Request(data) req.add_header("Accept", "application/yaml, text/yaml;q=0.9") with urlopen(req) as response: return load_raw_schema(response) else: fname = os.path.join(base_dir if base_dir else '', data) with open(fname) as f: return load_raw_schema(f, data, time.ctime(os.path.getmtime(fname)), os.path.getsize(fname)) else: schemadefs = yaml.load(data, DupCheckYamlLoader) # Some schemas don't have an outermost identifier. Construct one if necessary if 'name' in schemadefs: schemadefs = {schemadefs.pop('name'): schemadefs} elif 'id' in schemadefs: schemadefs = {schemadefs['id']: schemadefs} elif len(schemadefs) > 1 or not isinstance(list(schemadefs.values())[0], dict): schemadefs = {'Unnamed Schema': schemadefs} schema: SchemaDefinition = None for sname, sdef in {k: SchemaDefinition(name=k, **v) for k, v in schemadefs.items()}.items(): if schema is None: schema = sdef schema.source_file = os.path.basename(source_file) if source_file else None schema.source_file_date = source_file_date schema.source_file_size = source_file_size schema.generation_date = datetime.now().strftime("%Y-%m-%d %H:%M") schema.metamodel_version = metamodel_version else: merge_schemas(schema, sdef) return schema
def load_raw_schema(data: Union[str, TextIO], source_file: str=None, source_file_date: str=None, source_file_size: int=None, base_dir: Optional[str]=None) -> SchemaDefinition
Load and flatten SchemaDefinition from a file name, a URL or a block of text @param data: URL, file name or block of text @param source_file: Source file name for the schema @param source_file_date: timestamp of source file @param source_file_size: size of source file @param base_dir: Working directory of sources @return: Map from schema name to SchemaDefinition
2.940408
2.914275
1.008967
mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: raise ValueError(f"Duplicate key: \"{key}\"") mapping[key] = value return mapping
def map_constructor(self, loader, node, deep=False)
Walk the mapping, recording any duplicate keys.
1.977479
1.810911
1.09198
sys.exit(compare_files(file1, file2, comments))
def cli(file1, file2, comments) -> int
Compare file1 to file2 using a filter
7.765019
4.56438
1.701221
print(GolrSchemaGenerator(file, format).serialize(dirname=dir))
def cli(file, dir, format)
Generate GOLR representation of a biolink model
30.643219
14.1519
2.165308
DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)
def cli(yamlfile, directory, out, classname, format)
Generate graphviz representations of the biolink model
10.984835
12.743958
0.861964
print(JSONLDGenerator(yamlfile, format).serialize(context=context))
def cli(yamlfile, format, context)
Generate JSONLD file from biolink schema
9.790858
8.254242
1.186161
print(RDFGenerator(yamlfile, format).serialize(output=output, context=context))
def cli(yamlfile, format, output, context)
Generate an RDF representation of a biolink model
6.729128
5.783667
1.163471
if not isinstance(cls, ClassDefinition): cls = self.schema.classes[cls] return [self.schema.slots[s] for s in cls.slots]
def cls_slots(self, cls: CLASS_OR_CLASSNAME) -> List[SlotDefinition]
Return the list of slots directly included in the class definition. Includes slots whose domain is cls -- as declared in slot.domain or class.slots Does not include slots declared in mixins, apply_to or is_a links @param cls: class name or class definition name @return: all direct class slots
3.055183
3.859171
0.791668
def merge_definitions(cls_name: Optional[ClassDefinitionName]) -> None: if cls_name: for slot in self.all_slots(cls_name): aliased_name = self.aliased_slot_name(slot) if aliased_name not in known_slots: known_slots.add(aliased_name) rval.append(slot) if not isinstance(cls, ClassDefinition): cls = self.schema.classes[cls] known_slots: Set[str] = self.aliased_slot_names(cls.slots) rval: List[SlotDefinition] = [] if cls_slots_first: rval += self.cls_slots(cls) for mixin in cls.mixins: merge_definitions(mixin) merge_definitions(cls.is_a) else: merge_definitions(cls.is_a) for mixin in cls.mixins: merge_definitions(mixin) rval += self.cls_slots(cls) return rval
def all_slots(self, cls: CLASS_OR_CLASSNAME, *, cls_slots_first: bool = False) \ -> List[SlotDefinition]
Return all slots that are part of the class definition. This includes all is_a, mixin and apply_to slots but does NOT include slot_usage targets. If class B has a slot_usage entry for slot "s", only the slot definition for the redefined slot will be included, not its base. Slots are added in the order they appear in classes, with recursive is_a's being added first followed by mixins and finally apply_tos @param cls: class definition or class definition name @param cls_slots_first: True means return class slots at the top of the list @return: ordered list of slots in the class with slot usages removed
2.525023
2.549406
0.990436
definition = self.obj_for(definition) if definition is not None: return [definition.name] + self.ancestors(definition.is_a) else: return []
def ancestors(self, definition: Union[SLOT_OR_SLOTNAME, CLASS_OR_CLASSNAME]) \ -> List[Union[SlotDefinitionName, ClassDefinitionName]]
Return an ordered list of ancestor names for the supplied slot or class @param definition: Slot or class name or definition @return: List of ancestor names
4.551906
6.005414
0.757967
touches = References() for element in elements: if element in self.schema.classes: touches.classrefs.add(element) if None in touches.classrefs: raise ValueError("1") cls = self.schema.classes[element] if cls.is_a: touches.classrefs.add(cls.is_a) if None in touches.classrefs: raise ValueError("1") # Mixins include apply_to's touches.classrefs.update(set(cls.mixins)) for slotname in cls.slots: slot = self.schema.slots[slotname] if slot.range in self.schema.classes: touches.classrefs.add(slot.range) elif slot.range in self.schema.types: touches.typerefs.add(slot.range) if None in touches.classrefs: raise ValueError("1") if element in self.synopsis.rangerefs: for slotname in self.synopsis.rangerefs[element]: touches.slotrefs.add(slotname) if self.schema.slots[slotname].domain: touches.classrefs.add(self.schema.slots[slotname].domain) elif element in self.schema.slots: touches.slotrefs.add(element) slot = self.schema.slots[element] touches.slotrefs.update(set(slot.mixins)) if slot.is_a: touches.slotrefs.add(slot.is_a) if element in self.synopsis.inverses: touches.slotrefs.update(self.synopsis.inverses[element]) if slot.domain: touches.classrefs.add(slot.domain) if slot.range in self.schema.classes: touches.classrefs.add(slot.range) elif slot.range in self.schema.types: touches.typerefs.add(slot.range) elif element in self.schema.types: if element in self.synopsis.rangerefs: touches.slotrefs.update(self.synopsis.rangerefs[element]) return touches
def neighborhood(self, elements: List[ELEMENT_NAME]) \ -> References
Return a list of all slots, classes and types that touch any element in elements, including the element itself @param elements: Elements to do proximity with @return: All slots and classes that touch element
2.131791
2.122395
1.004427
if slot is not None and not isinstance(slot, str): slot = slot.range if slot is None: return DEFAULT_BUILTIN_TYPE_NAME # Default type name elif slot in builtin_names: return slot elif slot in self.schema.types: return self.grounded_slot_range(self.schema.types[slot].typeof) else: return slot
def grounded_slot_range(self, slot: Optional[Union[SlotDefinition, Optional[str]]]) -> str
Chase the slot range to its final form @param slot: slot to check @return: name of resolved range
4.769011
4.862785
0.980716
if isinstance(slot, str): slot = self.schema.slots[slot] return slot.alias if slot.alias else slot.name
def aliased_slot_name(self, slot: SLOT_OR_SLOTNAME) -> str
Return the overloaded slot name -- the alias if one exists otherwise the actual name @param slot: either a slot name or a definition @return: overloaded name
3.840322
4.183863
0.917889
return {self.aliased_slot_name(sn) for sn in slot_names}
def aliased_slot_names(self, slot_names: List[SlotDefinitionName]) -> Set[str]
Return the aliased slot names for all members of the list @param slot_names: actual slot names @return: aliases w/ duplicates removed
3.716951
4.776956
0.7781
name = obj_or_name.name if isinstance(obj_or_name, Element) else obj_or_name return self.schema.classes[name] if name in self.schema.classes \ else self.schema.slots[name] if name in self.schema.slots \ else self.schema.types[name] if name in self.schema.types else name if name in builtin_names \ else None
def obj_for(self, obj_or_name: Union[str, Element]) -> Optional[Union[str, Element]]
Return the class, slot or type that represents name or name itself if it is a builtin @param obj_or_name: Object or name @return: Corresponding element or None if not found (most likely cause is that it is a builtin type)
2.693197
2.299294
1.171315
if isinstance(obj, str): obj = self.obj_for(obj) if isinstance(obj, SlotDefinition): return underscore(self.aliased_slot_name(obj)) else: return camelcase(obj if isinstance(obj, str) else obj.name)
def obj_name(self, obj: Union[str, Element]) -> str
Return the formatted name used for the supplied definition
5.228339
4.386481
1.191921
print(CsvGenerator(yamlfile, format).serialize(classes=root))
def cli(yamlfile, root, format)
Generate CSV/TSV file from biolink model
28.328901
26.298582
1.077203
inherited_head = 'inherited_slots: List[str] = [' inherited_slots = ', '.join([f'"{underscore(slot.name)}"' for slot in self.schema.slots.values() if slot.inherited]) is_rows = split_line(inherited_slots, 120 - len(inherited_head)) return inherited_head + ('\n' + len(inherited_head) * ' ').join([r.strip() for r in is_rows]) + ']'
def gen_inherited(self) -> str
Generate the list of slot properties that are inherited across slot_usage or is_a paths
5.074507
4.613853
1.099842
rval = [] for cls in self.schema.classes.values(): pkeys = self.primary_keys_for(cls) for pk in pkeys: pk_slot = self.schema.slots[pk] classname = camelcase(cls.name) + camelcase(pk) if cls.is_a and getattr(self.schema.classes[cls.is_a], pk, None): parent = self.range_type_name(pk_slot, cls.is_a) else: parent = self.python_name_for(pk_slot.range) rval.append(f'class {classname}({parent}):\n\tpass') return '\n\n\n'.join(rval)
def gen_references(self) -> str
Generate python type declarations for all identifiers (primary keys)
3.963918
3.562686
1.112621
rval = [] for typ in self.schema.types.values(): typname = self.python_name_for(typ.name) parent = self.python_name_for(typ.typeof) rval.append(f'class {typname}({parent}):\n\tpass') return '\n\n\n'.join(rval) + ('\n' if rval else '')
def gen_typedefs(self) -> str
Generate python type declarations for all defined types
4.215275
3.610689
1.167443
return '\n'.join([self.gen_classdef(k, v) for k, v in self.schema.classes.items() if not v.mixin])
def gen_classdefs(self) -> str
Create class definitions for all non-mixin classes in the model Note that apply_to classes are transformed to mixins
4.716027
3.249808
1.451171
parentref = f'({self.python_name_for(cls.is_a) if cls.is_a else "YAMLRoot"})' slotdefs = self.gen_slot_variables(cls) postinits = self.gen_postinits(cls) if not slotdefs: slotdefs = 'pass' wrapped_description = f''' ''' if be(cls.description) else '' return f''' @dataclass class {camelcase(clsname)}{parentref}:{wrapped_description} {slotdefs} {postinits}'''
def gen_classdef(self, clsname: str, cls: ClassDefinition) -> str
Generate python definition for class clsname
6.55223
6.156785
1.064229
return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] + [self.gen_slot_variable(cls, slot) for slot in cls.slots if not self.schema.slots[slot].primary_key and not self.schema.slots[slot].identifier])
def gen_slot_variables(self, cls: ClassDefinition) -> str
Generate python definition for class cls, generating primary keys first followed by the rest of the slots
3.802263
2.843565
1.337146
slot = self.schema.slots[slotname] # Alias allows re-use of slot names in different contexts if slot.alias: slotname = slot.alias range_type = self.range_type_name(slot, cls.name) # Python version < 3.7 -- forward references have to be quoted if slot.inlined and slot.range in self.schema.classes and self.forward_reference(slot.range, cls.name): range_type = f'"{range_type}"' slot_range, default_val = self.range_cardinality(range_type, slot, cls) default = f'= {default_val}' if default_val else '' return f'''{underscore(slotname)}: {slot_range} {default}'''
def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str
Generate a slot variable for slotname as defined in class
5.396708
5.288744
1.020414
post_inits = [] if not cls.abstract: pkeys = self.primary_keys_for(cls) for pkey in pkeys: post_inits.append(self.gen_postinit(cls, pkey)) for slotname in cls.slots: slot = self.schema.slots[slotname] if not (slot.primary_key or slot.identifier): post_inits.append(self.gen_postinit(cls, slotname)) post_inits_line = '\n\t\t'.join([p for p in post_inits if p]) return (f''' def _fix_elements(self): super()._fix_elements() {post_inits_line}''' + '\n') if post_inits_line else ''
def gen_postinits(self, cls: ClassDefinition) -> str
Generate all the typing and existence checks post initialize
3.127403
2.98967
1.04607
rlines: List[str] = [] slot = self.schema.slots[slotname] if slot.alias: slotname = slot.alias slotname = self.python_name_for(slotname) range_type_name = self.range_type_name(slot, cls.name) # Generate existence check for required slots. Note that inherited classes have to check post-init because # named variables can't be mixed in the class signature if slot.primary_key or slot.identifier or slot.required: if cls.is_a: rlines.append(f'if self.{slotname} is None:') rlines.append(f'\traise ValueError(f"{slotname} must be supplied")') rlines.append(f'if not isinstance(self.{slotname}, {range_type_name}):') rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})') elif slot.range in self.schema.classes or slot.range in self.schema.types: if not slot.multivalued: rlines.append(f'if self.{slotname} and not isinstance(self.{slotname}, {range_type_name}):') # Another really wierd case -- a class that has no properties if slot.range in self.schema.classes and not self.all_slots_for(self.schema.classes[slot.range]): rlines.append(f'\tself.{slotname} = {range_type_name}()') else: rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})') elif slot.inlined: slot_range_cls = self.schema.classes[slot.range] pkeys = self.primary_keys_for(slot_range_cls) if pkeys: # Special situation -- if there are only two values: primary key and value, # we load it is a list, not a dictionary if len(self.all_slots_for(slot_range_cls)) - len(pkeys) == 1: class_init = '(k, v)' else: pkey_name = self.python_name_for(pkeys[0]) class_init = f'({pkey_name}=k, **({{}} if v is None else v))' rlines.append(f'for k, v in self.{slotname}.items():') rlines.append(f'\tif not isinstance(v, {range_type_name}):') rlines.append(f'\t\tself.{slotname}[k] = {range_type_name}{class_init}') else: rlines.append(f'self.{slotname} = [v if isinstance(v, {range_type_name})') indent = len(f'self.{slotname} = [') * ' ' rlines.append(f'{indent}else {range_type_name}(v) for v in self.{slotname}]') return '\n\t\t'.join(rlines)
def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str]
Generate python post init rules for slot in class
3.064825
3.016366
1.016065