text stringlengths 81 112k |
|---|
Return if this version is the published version of a layer
def is_published_version(self):
""" Return if this version is the published version of a layer """
pub_ver = getattr(self, 'published_version', None)
this_ver = getattr(self, 'this_version', None)
return this_ver and pub_ver and... |
Return if this version is the draft version of a layer
def is_draft_version(self):
""" Return if this version is the draft version of a layer """
pub_ver = getattr(self, 'published_version', None)
latest_ver = getattr(self, 'latest_version', None)
this_ver = getattr(self, 'this_version'... |
Filterable list of versions of a layer, always ordered newest to oldest.
If the version’s source supports revisions, you can get a specific revision using
``.filter(data__source__revision=value)``. Specific values depend on the source type.
Use ``data__source_revision__lt`` or ``data__source_re... |
Get a specific version of this layer
def get_version(self, version_id, expand=[]):
"""
Get a specific version of this layer
"""
target_url = self._client.get_url('VERSION', 'GET', 'single', {'layer_id': self.id, 'version_id': version_id})
return self._manager._get(target_url, ex... |
Get the current draft version of this layer.
:raises NotFound: if there is no draft version.
def get_draft_version(self, expand=[]):
"""
Get the current draft version of this layer.
:raises NotFound: if there is no draft version.
"""
target_url = self._client.get_url('VE... |
Starts importing this draft layerversion (cancelling any running import), even
if the data object hasn’t changed from the previous version.
:raises Conflict: if this version is already published.
def start_import(self, version_id=None):
"""
Starts importing this draft layerversion (can... |
A shortcut to create a new version and start importing it.
Effectively the same as :py:meth:`.create_draft_version` followed by :py:meth:`koordinates.layers.Layer.start_import`.
:rtype: Layer
:return: the new version
:raises Conflict: if there is already a draft version for this layer.
... |
Creates a publish task just for this version, which publishes as soon as any import is complete.
:return: the publish task
:rtype: Publish
:raises Conflict: If the version is already published, or already has a publish job.
def publish(self, version_id=None):
"""
Creates a publ... |
Edits this draft layerversion.
# If anything in the data object has changed, cancel any existing import and start a new one.
:param bool with_data: if ``True``, send the data object, which will start a new import and cancel
any existing one. If ``False``, the data object will *not* be sent,... |
Deletes this draft version (revert to published)
:raises NotAllowed: if this version is already published.
:raises Conflict: if this version is already deleted.
def delete_version(self, version_id=None):
"""
Deletes this draft version (revert to published)
:raises NotAllowed: ... |
Return the model class matching a URL
def _get_item_class(self, url):
""" Return the model class matching a URL """
if '/layers/' in url:
return Layer
elif '/tables/' in url:
return Table
elif '/sets/' in url:
return Set
# elif '/documents/' i... |
Calculate the fraction of the year since moon swap.
def get_year_since_resonance(ringcube):
"Calculate the fraction of the year since moon swap."
t0 = dt(2006, 1, 21)
td = ringcube.imagetime - t0
return td.days / 365.25 |
Create and return poly1d objects.
Uses the parameters from Morgan to create poly1d objects for
calculations.
def create_polynoms():
"""Create and return poly1d objects.
Uses the parameters from Morgan to create poly1d objects for
calculations.
"""
fname = pr.resource_filename('pyciss', 'd... |
Workhorse function.
Creates the polynom.
Calculates radius constraints from attributes in `ringcube` object.
Parameters
----------
ringcube : pyciss.ringcube.RingCube
A containter class for a ring-projected ISS image file.
Returns
-------
dict
Dictionary with all solit... |
Return the active manager for the given model.
:param model: Model class to look up the manager instance for.
:return: Manager instance for the model associated with this client.
def get_manager(self, model):
"""
Return the active manager for the given model.
:param model: Model... |
Takes the supplied headers and adds in any which
are defined at a client level and then returns
the result.
:param user_headers: a `dict` containing headers defined at the
request level, optional.
:return: a `dict` instance
def _assemble_headers(self, meth... |
Extracts parameters from a populated URL
:param datatype: a string identifying the data the url accesses.
:param url: the fully-qualified URL to extract parameters from.
:param verb: the HTTP verb needed for use with the url.
:param urltype: an adjective used to the nature of the reques... |
Returns a fully formed url
:param datatype: a string identifying the data the url will access.
:param verb: the HTTP verb needed for use with the url.
:param urltype: an adjective used to the nature of the request.
:param \*\*params: substitution variables for the URL.
:return: ... |
Turn CDMRemote variable into something like a numpy.ndarray.
def open_store_variable(self, name, var):
"""Turn CDMRemote variable into something like a numpy.ndarray."""
data = indexing.LazilyOuterIndexedArray(CDMArrayWrapper(name, self))
return Variable(var.dimensions, data, {a: getattr(var, a... |
Get the global attributes from underlying data set.
def get_attrs(self):
"""Get the global attributes from underlying data set."""
return FrozenOrderedDict((a, getattr(self.ds, a)) for a in self.ds.ncattrs()) |
Get the dimensions from underlying data set.
def get_dimensions(self):
"""Get the dimensions from underlying data set."""
return FrozenOrderedDict((k, len(v)) for k, v in self.ds.dimensions.items()) |
Identify the base URL of the THREDDS server from the catalog URL.
Will retain URL scheme, host, port and username/password when present.
def _find_base_tds_url(catalog_url):
"""Identify the base URL of the THREDDS server from the catalog URL.
Will retain URL scheme, host, port and username/password when ... |
Filter keys for an item closest to the desired time.
Loops over all keys in the collection and uses `regex` to extract and build
`datetime`s. The collection of `datetime`s is compared to `start` and the value that
has a `datetime` closest to that requested is returned.If none of the keys in the... |
Filter keys for all items within the desired time range.
Loops over all keys in the collection and uses `regex` to extract and build
`datetime`s. From the collection of `datetime`s, all values within `start` and `end`
(inclusive) are returned. If none of the keys in the collection match the reg... |
Remove and return the value associated with case-insensitive ``key``.
def pop(self, key, *args, **kwargs):
"""Remove and return the value associated with case-insensitive ``key``."""
return super(CaseInsensitiveDict, self).pop(CaseInsensitiveStr(key)) |
Convert key set to lowercase.
def _keys_to_lower(self):
"""Convert key set to lowercase."""
for k in list(self.keys()):
val = super(CaseInsensitiveDict, self).__getitem__(k)
super(CaseInsensitiveDict, self).__delitem__(k)
self.__setitem__(CaseInsensitiveStr(k), val) |
Resolve the url of the dataset when reading latest.xml.
Parameters
----------
catalog_url : str
The catalog url to be resolved
def resolve_url(self, catalog_url):
"""Resolve the url of the dataset when reading latest.xml.
Parameters
----------
catal... |
Make fully qualified urls for the access methods enabled on the dataset.
Parameters
----------
catalog_url : str
The top level server url
all_services : List[SimpleService]
list of :class:`SimpleService` objects associated with the dataset
metadata : dict... |
Create an access method from a catalog element.
def add_access_element_info(self, access_element):
"""Create an access method from a catalog element."""
service_name = access_element.attrib['serviceName']
url_path = access_element.attrib['urlPath']
self.access_element_info[service_name]... |
Download the dataset to a local file.
Parameters
----------
filename : str, optional
The full path to which the dataset will be saved
def download(self, filename=None):
"""Download the dataset to a local file.
Parameters
----------
filename : str, o... |
Access the remote dataset.
Open the remote dataset and get a netCDF4-compatible `Dataset` object providing
index-based subsetting capabilities.
Parameters
----------
service : str, optional
The name of the service to use for access to the dataset, either
... |
Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'NetcdfSubset'
or 'NetcdfServer', in that order, depending on t... |
Access the dataset using a particular service.
Return an Python object capable of communicating with the server using the particular
service. For instance, for 'HTTPServer' this is a file-like object capable of
HTTP communication; for OPENDAP this is a netCDF4 dataset.
Parameters
... |
r"""Calculate the U, V wind vector components from the speed and direction.
Parameters
----------
speed : array_like
The wind speed (magnitude)
wdir : array_like
The wind direction, specified as the direction from which the wind is
blowing, with 0 being North.
Returns
-... |
Get header information and store as metadata for the endpoint.
def _get_metadata(self):
"""Get header information and store as metadata for the endpoint."""
self.metadata = self.fetch_header()
self.variables = {g.name for g in self.metadata.grids} |
Make a header request to the endpoint.
def fetch_header(self):
"""Make a header request to the endpoint."""
query = self.query().add_query_parameter(req='header')
return self._parse_messages(self.get_query(query).content)[0] |
Request the featureType from the endpoint.
def fetch_feature_type(self):
"""Request the featureType from the endpoint."""
query = self.query().add_query_parameter(req='featureType')
return self.get_query(query).content |
Pull down coordinate data from the endpoint.
def fetch_coords(self, query):
"""Pull down coordinate data from the endpoint."""
q = query.add_query_parameter(req='coord')
return self._parse_messages(self.get_query(q).content) |
Retreive IGRA version 2 data for one station.
Parameters
--------
site_id : str
11-character IGRA2 station identifier.
time : datetime
The date and time of the desired observation. If list of two times is given,
dataframes for all dates within the two ... |
Process the IGRA2 text file for observations at site_id matching time.
Return:
-------
:class: `pandas.DataFrame` containing the body data.
:class: `pandas.DataFrame` containing the header data.
def _get_data(self):
"""Process the IGRA2 text file for observations at sit... |
Download observations matching the time range.
Returns a tuple with a string for the body, string for the headers,
and a list of dates.
def _get_data_raw(self):
"""Download observations matching the time range.
Returns a tuple with a string for the body, string for the headers,
... |
Identify lines containing headers within the range begin_date to end_date.
Parameters
-----
lines: list
list of lines from the IGRA2 data file.
def _select_date_range(self, lines):
"""Identify lines containing headers within the range begin_date to end_date.
Parame... |
Produce a dictionary with names, colspecs, and dtype for IGRA2 data.
Returns a dict with entries 'body' and 'header'.
def _get_fwf_params(self):
"""Produce a dictionary with names, colspecs, and dtype for IGRA2 data.
Returns a dict with entries 'body' and 'header'.
"""
def _cd... |
Format the dataframe, remove empty rows, and add units attribute.
def _clean_body_df(self, df):
"""Format the dataframe, remove empty rows, and add units attribute."""
if self.suffix == '-drvd.txt':
df = df.dropna(subset=('temperature', 'reported_relative_humidity',
... |
Format the header dataframe and add units.
def _clean_header_df(self, df):
"""Format the header dataframe and add units."""
if self.suffix == '-drvd.txt':
df.units = {'release_time': 'second',
'precipitable_water': 'millimeter',
'inv_pressure'... |
Retrieve the realtime buoy data from NDBC.
Parameters
----------
buoy : str
Name of buoy
data_type : str
Type of data requested, must be one of
'txt' standard meteorological data
'drift' meteorological data from drifting buoys and limited ... |
Parse standard meteorological data from NDBC buoys.
Parameters
----------
content : str
Data to parse
Returns
-------
:class:`pandas.DataFrame` containing the data
def _parse_met(content):
"""Parse standard meteorological data from NDBC buoys.
... |
Parse supplemental measurements data.
Parameters
----------
content : str
Data to parse
Returns
-------
:class:`pandas.DataFrame` containing the data
def _parse_supl(content):
"""Parse supplemental measurements data.
Parameters
... |
Check if a url is valid (returns 200) or not.
Parameters
----------
url : str
URL to check
Returns
-------
bool if url is valid
def _check_if_url_valid(url):
"""Check if a url is valid (returns 200) or not.
Parameters
----------... |
Determine which types of data are available for a given buoy.
Parameters
----------
buoy : str
Buoy name
Returns
-------
dict of valid file extensions and their descriptions
def buoy_data_types(cls, buoy):
"""Determine which types of data are av... |
Retrieve the raw buoy data contents from NDBC.
Parameters
----------
buoy : str
Name of buoy
data_type : str
Type of data requested, must be one of
'txt' standard meteorological data
'drift' meteorological data from drifting buoys and lim... |
Create a new HTTP session with our user-agent set.
Returns
-------
session : requests.Session
The created session
See Also
--------
urlopen, set_session_options
def create_session(self):
"""Create a new HTTP session with our user-agent set.
... |
GET a file-like object for a URL using HTTP.
This is a thin wrapper around :meth:`requests.Session.get` that returns a file-like
object wrapped around the resulting content.
Parameters
----------
url : str
The URL to request
kwargs : arbitrary keyword argum... |
Add a latitude/longitude bounding box to the query.
This adds a request for a spatial bounding box, bounded by ('north', 'south')
for latitude and ('east', 'west') for the longitude. This modifies the query
in-place, but returns `self` so that multiple queries can be chained together
on... |
Add a latitude/longitude point to the query.
This adds a request for a (`lon`, `lat`) point. This modifies the query
in-place, but returns `self` so that multiple queries can be chained together on
one line.
This replaces any existing spatial queries that have been set.
Parame... |
Add a request for a specific time to the query.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
This replaces any existing temporal queries that have been set.
Parameters
----------
time : datetime.date... |
Add a request for a time range to the query.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
This replaces any existing temporal queries that have been set.
Parameters
----------
start : datetime.dateti... |
Make a GET request, including a query, to the endpoint.
The path of the request is to the base URL assigned to the endpoint.
Parameters
----------
query : DataQuery
The query to pass when making the request
Returns
-------
resp : requests.Response
... |
Make a GET request, optionally including a query, to a relative path.
The path of the request includes a path on top of the base URL
assigned to the endpoint.
Parameters
----------
path : str
The path to request, relative to the endpoint
query : DataQuery, o... |
Make a GET request, optionally including a parameters, to a path.
The path of the request is the full URL.
Parameters
----------
path : str
The URL to request
params : DataQuery, optional
The query to pass when making the request
Returns
... |
Return the full path to the Group, including any parent Groups.
def path(self):
"""Return the full path to the Group, including any parent Groups."""
# If root, return '/'
if self.dataset is self:
return ''
else: # Otherwise recurse
return self.dataset.path + '/... |
Load a Group from an NCStream object.
def load_from_stream(self, group):
"""Load a Group from an NCStream object."""
self._unpack_attrs(group.atts)
self.name = group.name
for dim in group.dims:
new_dim = Dimension(self, dim.name)
self.dimensions[dim.name] = new_... |
Populate the Variable from an NCStream object.
def load_from_stream(self, var):
"""Populate the Variable from an NCStream object."""
dims = []
for d in var.shape:
dim = Dimension(None, d.name)
dim.load_from_stream(d)
dims.append(dim)
self.dimensions ... |
Load from an NCStream object.
def load_from_stream(self, dim):
"""Load from an NCStream object."""
self.unlimited = dim.isUnlimited
self.private = dim.isPrivate
self.vlen = dim.isVlen
if not self.vlen:
self.size = dim.length |
Get the needed header information to initialize dataset.
def _read_header(self):
"""Get the needed header information to initialize dataset."""
self._header = self.cdmrf.fetch_header()
self.load_from_stream(self._header) |
Populate the CoverageDataset from the protobuf information.
def load_from_stream(self, header):
"""Populate the CoverageDataset from the protobuf information."""
self._unpack_attrs(header.atts)
self.name = header.name
self.lon_lat_domain = header.latlonRect
self.proj_domain = he... |
Retrieve upper air observations from Iowa State's archive for a single station.
Parameters
----------
time : datetime
The date and time of the desired observation.
site_id : str
The three letter ICAO identifier of the station for which data should be
... |
Retrieve upper air observations from Iowa State's archive for all stations.
Parameters
----------
time : datetime
The date and time of the desired observation.
pressure : float, optional
The mandatory pressure level at which to request data (in hPa). If none is ... |
Download data from Iowa State's upper air archive.
Parameters
----------
time : datetime
Date and time for which data should be downloaded
site_id : str
Site id for which data should be downloaded
pressure : float, optional
Mandatory pressure ... |
r"""Download data from the Iowa State's upper air archive.
Parameters
----------
time : datetime
Date and time for which data should be downloaded
site_id : str
Site id for which data should be downloaded
pressure : float, optional
Mandatory p... |
Parse station list XML file.
def parse_station_table(root):
"""Parse station list XML file."""
stations = [parse_xml_station(elem) for elem in root.findall('station')]
return {st.id: st for st in stations} |
Create a :class:`Station` instance from an XML tag.
def parse_xml_station(elem):
"""Create a :class:`Station` instance from an XML tag."""
stid = elem.attrib['id']
name = elem.find('name').text
lat = float(elem.find('latitude').text)
lon = float(elem.find('longitude').text)
elev = float(elem.fi... |
Specify one or more stations for the query.
This modifies the query in-place, but returns `self` so that multiple
queries can be chained together on one line.
This replaces any existing spatial queries that have been set.
Parameters
----------
stns : one or more string... |
Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : RadarQuery
The query to validate
Returns
-------
... |
Fetch a parsed THREDDS catalog from the radar server.
Requests a catalog of radar data files data from the radar server given the
parameters in `query` and returns a :class:`~siphon.catalog.TDSCatalog` instance.
Parameters
----------
query : RadarQuery
The parameter... |
Request data from the ACIS Web Services API.
Makes a request from the ACIS Web Services API for data
based on a given method (StnMeta,StnData,MultiStnData,GridData,General)
and parameters string. Information about the parameters can be obtained at:
http://www.rcc-acis.org/docs_webservices.html
If ... |
Parse XML data returned by NCSS.
def parse_xml(data, handle_units):
"""Parse XML data returned by NCSS."""
root = ET.fromstring(data)
return squish(parse_xml_dataset(root, handle_units)) |
Parse an XML point tag.
def parse_xml_point(elem):
"""Parse an XML point tag."""
point = {}
units = {}
for data in elem.findall('data'):
name = data.get('name')
unit = data.get('units')
point[name] = float(data.text) if name != 'date' else parse_iso_date(data.text)
if un... |
Combine multiple Point tags into an array.
def combine_xml_points(l, units, handle_units):
"""Combine multiple Point tags into an array."""
ret = {}
for item in l:
for key, value in item.items():
ret.setdefault(key, []).append(value)
for key, value in ret.items():
if key !=... |
Create a netCDF-like dataset from XML data.
def parse_xml_dataset(elem, handle_units):
"""Create a netCDF-like dataset from XML data."""
points, units = zip(*[parse_xml_point(p) for p in elem.findall('point')])
# Group points by the contents of each point
datasets = {}
for p in points:
data... |
Handle CSV-formatted HTTP responses.
def parse_csv_response(data, unit_handler):
"""Handle CSV-formatted HTTP responses."""
return squish([parse_csv_dataset(d, unit_handler) for d in data.split(b'\n\n')]) |
Parse the CSV header returned by TDS.
def parse_csv_header(line):
"""Parse the CSV header returned by TDS."""
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
names.append(str(var))
continue
else:
names.app... |
Parse CSV data into a netCDF-like dataset.
def parse_csv_dataset(data, handle_units):
"""Parse CSV data into a netCDF-like dataset."""
fobj = BytesIO(data)
names, units = parse_csv_header(fobj.readline().decode('utf-8'))
arrs = np.genfromtxt(fobj, dtype=None, names=names, delimiter=',', unpack=True,
... |
Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : NCSSQuery
The query to validate
Returns
-------
v... |
Fetch parsed data from a THREDDS server using NCSS.
Requests data from the NCSS endpoint given the parameters in `query` and
handles parsing of the returned content based on the mimetype.
Parameters
----------
query : NCSSQuery
The parameters to send to the NCSS end... |
Add a bounding box in projected (native) coordinates to the query.
This adds a request for a spatial bounding box, bounded by (`min_x`, `max_x`) for
x direction and (`min_y`, `max_y`) for the y direction. This modifies the query
in-place, but returns ``self`` so that multiple queries can be cha... |
Set time and/or spatial (horizontal) strides.
This is only used on grid requests. Used to skip points in the returned data.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
Parameters
----------
time : in... |
Register a function to handle a particular mimetype.
def register(self, mimetype):
"""Register a function to handle a particular mimetype."""
def dec(func):
self._reg[mimetype] = func
return func
return dec |
Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType in netcdfJava
in the DataType enum. Possibilities are:
... |
r"""Download and parse upper air observations from an online archive.
Parameters
----------
time : datetime
The date and time of the desired observation.
site_id : str
The three letter ICAO identifier of the station for which data should be
downloade... |
Download data from the University of Wyoming's upper air archive.
Parameters
----------
time : datetime
Date and time for which data should be downloaded
site_id : str
Site id for which data should be downloaded
Returns
-------
text of th... |
Handle reading an NcStream v1 data block from a file-like object.
def read_ncstream_data(fobj):
"""Handle reading an NcStream v1 data block from a file-like object."""
data = read_proto_object(fobj, stream.Data)
if data.dataType in (stream.STRING, stream.OPAQUE) or data.vdata:
log.debug('Reading st... |
Handle reading an NcStream error from a file-like object and raise as error.
def read_ncstream_err(fobj):
"""Handle reading an NcStream error from a file-like object and raise as error."""
err = read_proto_object(fobj, stream.Error)
raise RuntimeError(err.message) |
Read messages from a file-like object until stream is exhausted.
def read_messages(fobj, magic_table):
"""Read messages from a file-like object until stream is exhausted."""
messages = []
while True:
magic = read_magic(fobj)
if not magic:
break
func = magic_table.get(m... |
Read a block of data and parse using the given protobuf object.
def read_proto_object(fobj, klass):
"""Read a block of data and parse using the given protobuf object."""
log.debug('%s chunk', klass.__name__)
obj = klass()
obj.ParseFromString(read_block(fobj))
log.debug('Header: %s', str(obj))
r... |
Read a block.
Reads a block from a file object by first reading the number of bytes to read, which must
be encoded as a variable-byte length integer.
Parameters
----------
fobj : file-like object
The file to read from.
Returns
-------
bytes
block of bytes read
def rea... |
Process vlen coming back from NCStream v2.
This takes the array of values and slices into an object array, with entries containing
the appropriate pieces of the original array. Sizes are controlled by the passed in
`data_header`.
Parameters
----------
data_header : Header
array : :class:`n... |
Convert DataCol from NCStream v2 into an array with appropriate type.
Depending on the data type specified, this extracts data from the appropriate members
and packs into a :class:`numpy.ndarray`, recursing as necessary for compound data types.
Parameters
----------
datacol : DataCol
Returns
... |
Extract the appropriate array shape from the header.
Can handle taking a data header and either bytes containing data or a StructureData
instance, which will have binary data as well as some additional information.
Parameters
----------
array : :class:`numpy.ndarray`
data_header : Data
def re... |
Convert an ncstream datatype to a numpy one.
def data_type_to_numpy(datatype, unsigned=False):
"""Convert an ncstream datatype to a numpy one."""
basic_type = _dtypeLookup[datatype]
if datatype in (stream.STRING, stream.OPAQUE):
return np.dtype(basic_type)
if unsigned:
basic_type = ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.