docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Create `OcrdPage </../../ocrd_models/ocrd_models.ocrd_page.html>`_
from an `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_
representing an image (i.e. should have ``mimetype`` starting with ``image/``).
Arguments:
* input_file (OcrdFile): | def page_from_image(input_file):
if input_file.local_filename is None:
raise Exception("input_file must have 'local_filename' property")
exif = exif_from_filename(input_file.local_filename)
now = datetime.now()
return PcGtsType(
Metadata=MetadataType(
Creator="OCR-D/core... | 641,142 |
Create a new PAGE-XML from a METS file representing a PAGE-XML or an image.
Arguments:
* input_file (OcrdFile): | def page_from_file(input_file):
# print("PARSING PARSING '%s'" % input_file)
if input_file.mimetype.startswith('image'):
return page_from_image(input_file)
if input_file.mimetype == MIMETYPE_PAGE:
return parse(input_file.local_filename, silence=True)
raise Exception("Unsupported mi... | 641,143 |
Parse a string, create the object tree, and export it.
Arguments:
- inString -- A string. This XML fragment should not start
with an XML declaration containing an encoding.
- silence -- A boolean. If False, export the object.
Returns -- The root object in the tree. | def parseString(inString, silence=False):
parser = None
rootNode= parsexmlstring_(inString, parser)
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = 'PcGts'
rootClass = PcGts
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python... | 641,162 |
Validate a parameter dict against a parameter schema from an ocrd-tool.json
Args:
obj (dict):
schema (dict): | def validate(self, *args, **kwargs): # pylint: disable=arguments-differ
return super(ParameterValidator, self)._validate(*args, **kwargs) | 641,374 |
Construct a ParameterValidator.
Arguments:
ocrd_tool (dict): Parsed ``ocrd-tool.json``. | def __init__(self, ocrd_tool):
required = []
if ocrd_tool is None:
ocrd_tool = {}
if 'parameters' not in ocrd_tool:
ocrd_tool['parameters'] = {}
p = ocrd_tool['parameters']
for n in p:
if 'required' in p[n]:
if p[n]['re... | 641,375 |
Construct a new ConsistencyError.
Arguments:
tag (string): Level of the inconsistent element
ID (string): ``ID`` of the inconsistent element
actual (string):
expected (string): | def __init__(self, tag, ID, actual, expected):
self.tag = tag
self.ID = ID
self.actual = actual
self.expected = expected
super(ConsistencyError, self).__init__("INCONSISTENCY in %s ID '%s': text results '%s' != concatenated '%s'" % (tag, ID, actual, expected)) | 641,380 |
Validates a PAGE file for consistency by filename, OcrdFile or passing OcrdPage directly.
Arguments:
filename (string): Path to PAGE
ocrd_page (OcrdPage): OcrdPage instance
ocrd_file (OcrdFile): OcrdFile instance wrapping OcrdPage
strictness (string): 'strict', '... | def validate(filename=None, ocrd_page=None, ocrd_file=None, strictness='strict', strategy='index1'):
if ocrd_page:
validator = PageValidator(ocrd_page, strictness, strategy)
elif ocrd_file:
validator = PageValidator(page_from_file(ocrd_file), strictness, strategy)
... | 641,381 |
Override all logger filter levels to include lvl and above.
- Set root logger level
- iterates all existing loggers and sets their log level to ``NOTSET``.
Args:
lvl (string): Log level name. | def setOverrideLogLevel(lvl):
if lvl is None:
return
logging.info('Overriding log level globally to %s', lvl)
lvl = getLevelName(lvl)
global _overrideLogLevel # pylint: disable=global-statement
_overrideLogLevel = lvl
logging.getLogger('').setLevel(lvl)
for loggerName in logging... | 641,403 |
Spill a workspace, i.e. unpack it and turn it into a workspace.
See https://ocr-d.github.com/ocrd_zip#unpacking-ocrd-zip-to-a-workspace
Arguments:
src (string): Path to OCRD-ZIP
dest (string): Path to directory to unpack data folder to | def spill(self, src, dest):
# print(dest)
if exists(dest) and not isdir(dest):
raise Exception("Not a directory: %s" % dest)
# If dest is an existing directory, try to derive its name from src
if isdir(dest):
workspace_name = re.sub(r'(\.ocrd)?\.zip$',... | 641,412 |
Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file | def download_url(self, url, **kwargs):
if self.baseurl and '://' not in url:
url = join(self.baseurl, url)
return self.resolver.download_to_directory(self.directory, url, **kwargs) | 641,415 |
Get the EXIF metadata about an image URL as :class:`OcrdExif`
Args:
image_url (string) : URL of image
Return
:class:`OcrdExif` | def resolve_image_exif(self, image_url):
files = self.mets.find_files(url=image_url)
if files:
image_filename = self.download_file(files[0]).local_filename
else:
image_filename = self.download_url(image_url)
if image_url not in self.image_cache['exif']:
... | 641,419 |
Resolve an image URL to a PIL image.
Args:
coords (list) : Coordinates of the bounding box to cut from the image
Returns:
Image or region in image as PIL.Image | def resolve_image_as_pil(self, image_url, coords=None):
files = self.mets.find_files(url=image_url)
if files:
image_filename = self.download_file(files[0]).local_filename
else:
image_filename = self.download_url(image_url)
if image_url not in self.image_... | 641,420 |
Add a new ``mets:fileGrp``.
Arguments:
fileGrp (string): ``USE`` attribute of the new filegroup. | def add_file_group(self, fileGrp):
el_fileSec = self._tree.getroot().find('mets:fileSec', NS)
if el_fileSec is None:
el_fileSec = ET.SubElement(self._tree.getroot(), TAG_METS_FILESEC)
el_fileGrp = el_fileSec.find('mets:fileGrp[@USE="%s"]' % fileGrp, NS)
if el_fileGrp... | 641,438 |
Add a `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_.
Arguments:
fileGrp (string): Add file to ``mets:fileGrp`` with this ``USE`` attribute
mimetype (string):
url (string):
ID (string):
pageId (string):
force (boolean): Whethe... | def add_file(self, fileGrp, mimetype=None, url=None, ID=None, pageId=None, force=False, local_filename=None, **kwargs):
if not ID:
raise Exception("Must set ID of the mets:file")
el_fileGrp = self._tree.getroot().find(".//mets:fileGrp[@USE='%s']" % (fileGrp), NS)
if el_fileG... | 641,439 |
Construct a new WorkspaceValidator.
Args:
resolver (Resolver):
mets_url (string):
src_dir (string):
skip (list):
download (boolean):
page_strictness ("strict"|"lax"|"fix"|"off"): | def __init__(self, resolver, mets_url, src_dir=None, skip=None, download=False, page_strictness='strict'):
self.report = ValidationReport()
self.skip = skip if skip else []
log.debug('resolver=%s mets_url=%s src_dir=%s', resolver, mets_url, src_dir)
self.resolver = resolver
... | 641,442 |
Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR). | def contains_vasp_input(dir_name):
for f in ["INCAR", "POSCAR", "POTCAR", "KPOINTS"]:
if not os.path.exists(os.path.join(dir_name, f)) and \
not os.path.exists(os.path.join(dir_name, f + ".orig")):
return False
return True | 641,681 |
Helper method to get the coordination number of all sites in the final
structure from a run.
Args:
d:
Run dict generated by VaspToDbTaskDrone.
Returns:
Coordination numbers as a list of dict of [{"site": site_dict,
"coordination": number}, ...]. | def get_coordination_numbers(d):
structure = Structure.from_dict(d["output"]["crystal"])
f = VoronoiNN()
cn = []
for i, s in enumerate(structure.sites):
try:
n = f.get_cn(structure, i)
number = int(round(n))
cn.append({"site": s.as_dict(), "coordination":... | 641,682 |
Returns the URI path for a directory. This allows files hosted on
different file servers to have distinct locations.
Args:
dir_name:
A directory name.
Returns:
Full URI path, e.g., fileserver.host.com:/full/path/of/dir_name. | def get_uri(dir_name):
fullpath = os.path.abspath(dir_name)
try:
hostname = socket.gethostbyaddr(socket.gethostname())[0]
except:
hostname = socket.gethostname()
return "{}:{}".format(hostname, fullpath) | 641,683 |
Simple post-processing for various files other than the vasprun.xml.
Called by generate_task_doc. Modify this if your runs have other
kinds of processing requirements.
Args:
dir_name:
The dir_name.
d:
Current doc generated. | def post_process(self, dir_name, d):
logger.info("Post-processing dir:{}".format(dir_name))
fullpath = os.path.abspath(dir_name)
# VASP input generated by pymatgen's alchemy has a
# transformations.json file that keeps track of the origin of a
# particular structure. T... | 641,689 |
Returns a structure from the database given the task id.
Args:
task_id:
The task_id to query for.
final_structure:
Whether to obtain the final or initial structure. Defaults to
True. | def get_structure_from_id(self, task_id, final_structure=True):
args = {'task_id': task_id}
field = 'output.crystal' if final_structure else 'input.crystal'
results = tuple(self.query([field], args))
if len(results) > 1:
raise QueryError("More than one result found ... | 641,741 |
Initialize a QueryEngine from a JSON config file generated using mgdb
init.
Args:
config_file:
Filename of config file.
use_admin:
If True, the admin user and password in the config file is
used. Otherwise, the readonly_user and pa... | def from_config(config_file, use_admin=False):
with open(config_file) as f:
d = json.load(f)
user = d["admin_user"] if use_admin else d["readonly_user"]
password = d["admin_password"] if use_admin \
else d["readonly_password"]
return Query... | 641,742 |
Uploads a record to the server
Parameters:
marcxml - *str* the XML to upload.
mode - *str* the mode to use for the upload.
"-i" insert new records
"-r" replace existing records
"-c" correct fields of records
... | def upload_marcxml(self, marcxml, mode):
if mode not in ["-i", "-r", "-c", "-a", "-ir"]:
raise NameError, "Incorrect mode " + str(mode)
# Are we running locally? If so, submit directly
if self.local:
(code, marcxml_filepath) = tempfile.mkstemp(prefix="upload_%s"... | 642,060 |
Add a faked resource to this manager.
For URI-based lookup, the resource is also added to the faked HMC.
Parameters:
properties (dict):
Resource properties. If the URI property (e.g. 'object-uri') or the
object ID property (e.g. 'object-id') are not specified, they
... | def add(self, properties):
resource = self.resource_class(self, properties)
self._resources[resource.oid] = resource
self._hmc.all_resources[resource.uri] = resource
return resource | 642,735 |
Remove a faked resource from this manager.
Parameters:
oid (string):
The object ID of the resource (e.g. value of the 'object-uri'
property). | def remove(self, oid):
uri = self._resources[oid].uri
del self._resources[oid]
del self._hmc.all_resources[uri] | 642,736 |
List the faked resources of this manager.
Parameters:
filter_args (dict):
Filter arguments. `None` causes no filtering to happen. See
:meth:`~zhmcclient.BaseManager.list()` for details.
Returns:
list of FakedBaseResource: The faked resource objects of this
... | def list(self, filter_args=None):
res = list()
for oid in self._resources:
resource = self._resources[oid]
if self._matches_filters(resource, filter_args):
res.append(resource)
return res | 642,737 |
Remove a faked HBA resource.
This method also updates the 'hba-uris' property in the parent
Partition resource, by removing the URI for the faked HBA resource.
Parameters:
oid (string):
The object ID of the faked HBA resource. | def remove(self, oid):
hba = self.lookup_by_oid(oid)
partition = self.parent
devno = hba.properties.get('device-number', None)
if devno:
partition.devno_free_if_allocated(devno)
wwpn = hba.properties.get('wwpn', None)
if wwpn:
partition.ww... | 642,767 |
Remove a faked NIC resource.
This method also updates the 'nic-uris' property in the parent
Partition resource, by removing the URI for the faked NIC resource.
Parameters:
oid (string):
The object ID of the faked NIC resource. | def remove(self, oid):
nic = self.lookup_by_oid(oid)
partition = self.parent
devno = nic.properties.get('device-number', None)
if devno:
partition.devno_free_if_allocated(devno)
assert 'nic-uris' in partition.properties
nic_uris = partition.properties... | 642,773 |
Free a device number allocated with :meth:`devno_alloc`.
The device number must be allocated.
Parameters:
devno (string): The device number as four hexadecimal digits.
Raises:
ValueError: Device number not in pool range or not currently
allocated. | def devno_free(self, devno):
devno_int = int(devno, 16)
self._devno_pool.free(devno_int) | 642,779 |
Free a device number allocated with :meth:`devno_alloc`.
If the device number is not currently allocated or not in the pool
range, nothing happens.
Parameters:
devno (string): The device number as four hexadecimal digits. | def devno_free_if_allocated(self, devno):
devno_int = int(devno, 16)
self._devno_pool.free_if_allocated(devno_int) | 642,780 |
Free a WWPN allocated with :meth:`wwpn_alloc`.
The WWPN must be allocated.
Parameters:
WWPN (string): The WWPN as 16 hexadecimal digits.
Raises:
ValueError: WWPN not in pool range or not currently
allocated. | def wwpn_free(self, wwpn):
wwpn_int = int(wwpn[-4:], 16)
self._wwpn_pool.free(wwpn_int) | 642,782 |
Free a WWPN allocated with :meth:`wwpn_alloc`.
If the WWPN is not currently allocated or not in the pool
range, nothing happens.
Parameters:
WWPN (string): The WWPN as 16 hexadecimal digits. | def wwpn_free_if_allocated(self, wwpn):
wwpn_int = int(wwpn[-4:], 16)
self._wwpn_pool.free_if_allocated(wwpn_int) | 642,783 |
Remove a faked Port resource.
This method also updates the 'network-port-uris' or 'storage-port-uris'
property in the parent Adapter resource, by removing the URI for the
faked Port resource.
Parameters:
oid (string):
The object ID of the faked Port resource. | def remove(self, oid):
port = self.lookup_by_oid(oid)
adapter = self.parent
if 'network-port-uris' in adapter.properties:
port_uris = adapter.properties['network-port-uris']
port_uris.remove(port.uri)
if 'storage-port-uris' in adapter.properties:
... | 642,786 |
Remove a faked Virtual Function resource.
This method also updates the 'virtual-function-uris' property in the
parent Partition resource, by removing the URI for the faked Virtual
Function resource.
Parameters:
oid (string):
The object ID of the faked Virtual Fun... | def remove(self, oid):
virtual_function = self.lookup_by_oid(oid)
partition = self.parent
devno = virtual_function.properties.get('device-number', None)
if devno:
partition.devno_free_if_allocated(devno)
assert 'virtual-function-uris' in partition.properties
... | 642,790 |
Get a faked metric group definition by its group name.
Parameters:
group_name (:term:`string`): Name of the metric group.
Returns:
:class:~zhmcclient.FakedMetricGroupDefinition`: Definition of the
metric group.
Raises:
ValueError: A metric group de... | def get_metric_group_definition(self, group_name):
if group_name not in self._metric_group_defs:
raise ValueError("A metric group definition with this name does "
"not exist: {}".format(group_name))
return self._metric_group_defs[group_name] | 642,801 |
Add one set of faked metric values for a particular resource to the
metrics response for a particular metric group, for later retrieval.
For defined metric groups, see chapter "Metric groups" in the
:term:`HMC API` book.
Parameters:
values (:class:`~zhmclient.FakedMetricObje... | def add_metric_values(self, values):
assert isinstance(values, FakedMetricObjectValues)
group_name = values.group_name
if group_name not in self._metric_values:
self._metric_values[group_name] = []
self._metric_values[group_name].append(values)
if group_name ... | 642,802 |
Get the time statistics for a name.
If a time statistics for that name does not exist yet, create one.
Parameters:
name (string):
Name of the time statistics.
Returns:
TimeStats: The time statistics for the specified name. If the
statistics keeper is... | def get_stats(self, name):
if not self.enabled:
return self._disabled_stats
if name not in self._time_stats:
self._time_stats[name] = TimeStats(self, name)
return self._time_stats[name] | 642,919 |
Return the JSON payload in the HTTP response as a Python dict.
Parameters:
result (requests.Response): HTTP response object.
Raises:
zhmcclient.ParseError: Error parsing the returned JSON. | def _result_object(result):
content_type = result.headers.get('content-type', None)
if content_type is None or content_type.startswith('application/json'):
# This function is only called when there is content expected.
# Therefore, a response without content will result in a ParseError.
... | 643,068 |
Log the HTTP request of an HMC REST API call, at the debug level.
Parameters:
method (:term:`string`): HTTP method name in upper case, e.g. 'GET'
url (:term:`string`): HTTP URL (base URL and operation URI)
headers (iterable): HTTP headers used for the request
content... | def _log_http_request(method, url, headers=None, content=None):
if method == 'POST' and url.endswith('/api/sessions'):
# In Python 3 up to 3.5, json.loads() requires unicode strings.
if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \
isinstan... | 643,076 |
Log the HTTP response of an HMC REST API call, at the debug level.
Parameters:
method (:term:`string`): HTTP method name in upper case, e.g. 'GET'
url (:term:`string`): HTTP URL (base URL and operation URI)
status (integer): HTTP status code
headers (iterable): HTTP ... | def _log_http_response(method, url, status, headers=None, content=None):
if method == 'POST' and url.endswith('/api/sessions'):
# In Python 3 up to 3.5, json.loads() requires unicode strings.
if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \
... | 643,077 |
A utility function for selecting the first non-null query.
Parameters:
funcs: One or more functions
Returns:
A function that, when called with a :class:`Node`, will
pass the input to each `func`, and return the first non-Falsey
result.
Examples:
>>> s = Soupy("<p>hi</... | def either(*funcs):
def either(val):
for func in funcs:
result = val.apply(func)
if result:
return result
return Null()
return either | 643,327 |
Return a new Collection excluding some items
Parameters:
func : function(Node) -> Scalar
A function that, when called on each item
in the collection, returns a boolean-like
value. If no function is provided, then
truthy items will be... | def exclude(self, func=None):
func = _make_callable(func)
inverse = lambda x: not func(x)
return self.filter(inverse) | 643,343 |
Return a new Collection with the last few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
at and after the first item where bool(func(item)) == False
Examples:
node.find_all('tr').takew... | def takewhile(self, func=None):
func = _make_callable(func)
return Collection(takewhile(func, self._items)) | 643,345 |
Return a new Collection with the first few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
before the first item where bool(func(item)) == True | def dropwhile(self, func=None):
func = _make_callable(func)
return Collection(dropwhile(func, self._items)) | 643,346 |
Zip the items of this collection with one or more
other sequences, and wrap the result.
Unlike Python's zip, all sequences must be the same length.
Parameters:
others: One or more iterables or Collections
Returns:
A new collection.
Examples:
... | def zip(self, *others):
args = [_unwrap(item) for item in (self,) + others]
ct = self.count()
if not all(len(arg) == ct for arg in args):
raise ValueError("Arguments are not all the same length")
return Collection(map(Wrapper.wrap, zip(*args))) | 643,349 |
Turn this collection into a Scalar(dict), by zipping keys and items.
Parameters:
keys: list or Collection of NavigableStrings
The keys of the dictionary
Examples:
>>> c = Collection([Scalar(1), Scalar(2)])
>>> c.dictzip(['a', 'b']).val() == {'a': 1... | def dictzip(self, keys):
return Scalar(dict(zip(_unwrap(keys), self.val()))) | 643,350 |
Method to get simplenote auth token
Arguments:
- user (string): simplenote email address
- password (string): simplenote password
Returns:
Simplenote API token as string | def authenticate(self, user, password):
request = Request(AUTH_URL)
request.add_header('X-Simperium-API-Key', API_KEY)
if sys.version_info < (3, 3):
request.add_data(json.dumps({'username': user, 'password': password}))
else:
request.data = json.dumps({'... | 643,759 |
Method to get a specific note
Arguments:
- noteid (string): ID of the note to get
- version (int): optional version of the note to get
Returns:
A tuple `(note, status)`
- note (dict): note object
- status (int): 0 on success and -1 otherwise | def get_note(self, noteid, version=None):
# request note
params_version = ""
if version is not None:
params_version = '/v/' + str(version)
params = '/i/%s%s' % (str(noteid), params_version)
request = Request(DATA_URL+params)
request.add_header(self.h... | 643,761 |
Method to move a note to the trash
Arguments:
- note_id (string): key of the note to trash
Returns:
A tuple `(note, status)`
- note (dict): the newly created note or an error message
- status (int): 0 on success and -1 otherwise | def trash_note(self, note_id):
# get note
note, status = self.get_note(note_id)
if (status == -1):
return note, status
# set deleted property, but only if not already trashed
# TODO: A 412 is ok, that's unmodified. Should handle this in update_note and
... | 643,765 |
Method to permanently delete a note
Arguments:
- note_id (string): key of the note to trash
Returns:
A tuple `(note, status)`
- note (dict): an empty dict or an error message
- status (int): 0 on success and -1 otherwise | def delete_note(self, note_id):
# notes have to be trashed before deletion
note, status = self.trash_note(note_id)
if (status == -1):
return note, status
params = '/i/%s' % (str(note_id))
request = Request(url=DATA_URL+params, method='DELETE')
reques... | 643,766 |
Validate the bearer token against the OAuth provider.
Arguments:
token (str): Access token to validate
Returns:
(tuple): tuple containing:
user (User): User associated with the access token
access_token (str): Access token
Raises:
... | def authenticate_credentials(self, token):
try:
user_info = self.get_user_info(token)
except UserInfoRetrievalFailed:
msg = 'Failed to retrieve user info. Unable to authenticate.'
logger.error(msg)
raise exceptions.AuthenticationFailed(msg)
... | 643,770 |
Retrieves the user info from the OAuth provider.
Arguments:
token (str): OAuth2 access token.
Returns:
dict
Raises:
UserInfoRetrievalFailed: Retrieval of user info from the remote server failed. | def get_user_info(self, token):
url = self.get_user_info_url()
try:
headers = {'Authorization': 'Bearer {}'.format(token)}
response = requests.get(url, headers=headers)
except requests.RequestException:
logger.exception('Failed to retrieve user info... | 643,771 |
Authenticate the user, requiring a logged-in account and CSRF.
This is exactly the same as the `SessionAuthentication` implementation,
with the `user.is_active` check removed.
Args:
request (HttpRequest)
Returns:
Tuple of `(user, token)`
Raises:
... | def authenticate(self, request):
# Get the underlying HttpRequest object
request = request._request # pylint: disable=protected-access
user = getattr(request, 'user', None)
# Unauthenticated, CSRF validation not required
# This is where regular `SessionAuthentication` ... | 643,790 |
Display an HTML representation of a table with INDRA statements to
manually inspect for validity.
Args:
sts: A list of INDRA statements to be manually inspected for validity. | def create_statement_inspection_table(sts: List[Influence]):
columns = [
"un_groundings",
"subj_polarity",
"obj_polarity",
"Sentence",
"Source API",
]
polarity_to_str = lambda x: "+" if x == 1 else "-" if x == -1 else "None"
l = []
for s in sts:
... | 645,218 |
Indicates whether a line in the program is the first line of a subprogram
definition.
Args:
line
Returns:
(True, f_name) if line begins a definition for subprogram f_name;
(False, None) if line does not begin a subprogram definition. | def line_starts_subpgm(line: str) -> Tuple[bool, Optional[str]]:
match = RE_SUB_START.match(line)
if match != None:
f_name = match.group(1)
return (True, f_name)
match = RE_FN_START.match(line)
if match != None:
f_name = match.group(1)
return (True, f_name)
re... | 645,275 |
Construct an AnalysisGraph object from a list of INDRA statements.
Unknown polarities are set to positive by default.
Args:
sts: A list of INDRA Statements
Returns:
An AnalysisGraph instance constructed from a list of INDRA
statements. | def from_statements(
cls, sts: List[Influence], assign_default_polarities: bool = True
):
_dict = {}
for s in sts:
if assign_default_polarities:
for delta in deltas(s):
if delta["polarity"] is None:
delta["pola... | 645,330 |
Add probability distribution functions constructed from gradable
adjective data to the edges of the analysis graph data structure.
Args:
adjective_data
res | def assemble_transition_model_from_gradable_adjectives(self):
df = pd.read_sql_table("gradableAdjectiveData", con=engine)
gb = df.groupby("adjective")
rs = gaussian_kde(
flatMap(
lambda g: gaussian_kde(get_respdevs(g[1]))
.resample(self.res)... | 645,338 |
Sample observed state vector. This is the implementation of the
emission function.
Args:
s: Latent state vector.
Returns:
Observed state vector. | def sample_observed_state(self, s: pd.Series) -> Dict:
return {
n[0]: {
i.name: np.random.normal(s[n[0]] * i.mean, i.stdev)
for i in n[1]["indicators"].values()
}
for n in self.nodes(data=True)
} | 645,341 |
Sample a collection of observed state sequences from the likelihood
model given a collection of transition matrices.
Args:
n_timesteps: The number of timesteps for the sequences. | def sample_from_likelihood(self, n_timesteps=10):
self.latent_state_sequences = lmap(
lambda A: ltake(
n_timesteps,
iterate(
lambda s: pd.Series(A @ s.values, index=s.index), self.s0
),
),
self.tran... | 645,342 |
Create a BMI config file to initialize the model.
Args:
filename: The filename with which the config file should be saved. | def create_bmi_config_file(self, filename: str = "bmi_config.txt") -> None:
s0 = self.construct_default_initial_state()
s0.to_csv(filename, index_label="variable") | 645,347 |
Initialize the executable AnalysisGraph with a config file.
Args:
config_file
Returns:
AnalysisGraph | def initialize(
self, config_file: str = "bmi_config.txt", initialize_indicators=True
):
self.t = 0.0
if not os.path.isfile(config_file):
self.create_bmi_config_file(config_file)
self.s0 = [
pd.read_csv(
config_file, index_col=0, head... | 645,349 |
Return dict suitable for exporting to JSON.
Args:
n: A dict representing the data in a networkx AnalysisGraph node.
Returns:
The node dict with additional fields for name, units, dtype, and
arguments. | def export_node(self, n) -> Dict[str, Union[str, List[str]]]:
node_dict = {
"name": n[0],
"units": _get_units(n[0]),
"dtype": _get_dtype(n[0]),
"arguments": list(self.predecessors(n[0])),
}
if not n[1].get("indicators") is None:
... | 645,351 |
Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res: Minimum temporal resolution that the indicators
must have data for. | def map_concepts_to_indicators(
self, n: int = 1, min_temporal_res: Optional[str] = None
):
for node in self.nodes(data=True):
query_parts = [
"select Indicator from concept_to_indicator_mapping",
f"where `Concept` like '{node[0]}'",
... | 645,353 |
Parameterize the analysis graph.
Args:
country
year
month
fallback_aggaxes:
An iterable of strings denoting the axes upon which to perform
fallback aggregation if the desired constraints cannot be met.
aggfunc: The func... | def parameterize(
self,
country: Optional[str] = "South Sudan",
state: Optional[str] = None,
year: Optional[int] = None,
month: Optional[int] = None,
unit: Optional[str] = None,
fallback_aggaxes: List[str] = ["year", "month"],
aggfunc: Callable = np.mean,
... | 645,354 |
Prunes the CAG by removing redundant paths. If there are multiple
(directed) paths between two nodes, this function removes all but the
longest paths. Subsequently, it restricts the graph to the largest
connected component.
Args:
cutoff: The maximum path length to consider f... | def prune(self, cutoff: int = 2):
# Remove redundant paths.
for node_pair in tqdm(list(permutations(self.nodes(), 2))):
paths = [
list(pairwise(path))
for path in nx.all_simple_paths(self, *node_pair, cutoff)
]
if len(paths) >... | 645,360 |
Merge node n1 into node n2, with the option to specify relative
polarity.
Args:
n1
n2
same_polarity | def merge_nodes(self, n1: str, n2: str, same_polarity: bool = True):
for p in self.predecessors(n1):
for st in self[p][n1]["InfluenceStatements"]:
if not same_polarity:
st.obj_delta["polarity"] = -st.obj_delta["polarity"]
st.obj.db_refs["... | 645,361 |
Get subgraph comprised of simple paths between the source and the
target.
Args:
source
target
cutoff | def get_subgraph_for_concept_pair(
self, source: str, target: str, cutoff: Optional[int] = None
):
paths = nx.all_simple_paths(self, source, target, cutoff=cutoff)
return AnalysisGraph(self.subgraph(set(chain.from_iterable(paths)))) | 645,363 |
Get subgraph comprised of simple paths between the source and the
target.
Args:
concepts
cutoff | def get_subgraph_for_concept_pairs(
self, concepts: List[str], cutoff: Optional[int] = None
):
path_generator = (
nx.all_simple_paths(self, source, target, cutoff=cutoff)
for source, target in permutations(concepts, 2)
)
paths = chain.from_iterable(pa... | 645,364 |
Exports the CAG as a pygraphviz AGraph for visualization.
Args:
indicators: Whether to display indicators in the AGraph
indicator_values: Whether to display indicator values in the AGraph
nodes_to_highlight: Nodes to highlight in the AGraph.
Returns:
A Py... | def to_agraph(
self,
indicators: bool = False,
indicator_values: bool = False,
nodes_to_highlight=None,
*args,
**kwargs,
):
from delphi.utils.misc import choose_font
FONT = choose_font()
A = nx.nx_agraph.to_agraph(self)
A.gra... | 645,366 |
Executes the GrFN over a particular set of inputs and returns the
result.
Args:
inputs: Input set where keys are the names of input nodes in the
GrFN and each key points to a set of input values (or just one).
Returns:
A set of outputs from executing the G... | def run(
self,
inputs: Dict[str, Union[float, Iterable]],
torch_size: Optional[int] = None,
) -> Union[float, Iterable]:
# Set input values
for i in self.inputs:
self.nodes[i]["value"] = inputs[i]
for func_set in self.function_sets:
f... | 645,406 |
BFS traversal of nodes that returns name traversal as large string.
Args:
node_set: Set of input nodes to begin traversal.
depth: Current traversal depth for child node viewing.
Returns:
type: String containing tabbed traversal view. | def traverse_nodes(self, node_set, depth=0):
tab = " "
result = list()
for n in node_set:
repr = (
n
if self.nodes[n]["type"] == "variable"
else f"{n}{inspect.signature(self.nodes[n]['lambda_fn'])}"
)
... | 645,409 |
Builds a GrFN from a JSON object.
Args:
cls: The class variable for object creation.
file: Filename of a GrFN JSON file.
Returns:
type: A GroundedFunctionNetwork object. | def from_json_and_lambdas(cls, file: str, lambdas):
with open(file, "r") as f:
data = json.load(f)
return cls.from_dict(data, lambdas) | 645,410 |
Create a GroundedFunctionNetwork instance from a string with raw
Fortran code.
Args:
fortran_src: A string with Fortran source code.
dir: (Optional) - the directory in which the temporary Fortran file
will be created (make sure you have write permission!) Default... | def from_fortran_src(cls, fortran_src: str, dir: str = "."):
import tempfile
fp = tempfile.NamedTemporaryFile('w+t', delete=False, dir=dir)
fp.writelines(fortran_src)
fp.close()
G = cls.from_fortran_file(fp.name, dir)
os.remove(fp.name)
return G | 645,415 |
Creates a ForwardInfluenceBlanket object representing the
intersection of this model with the other input model.
Args:
other: The GroundedFunctionNetwork object to compare this model to.
Returns:
A ForwardInfluenceBlanket object to use for model comparison. | def to_FIB(self, other):
if not isinstance(other, GroundedFunctionNetwork):
raise TypeError(
f"Expected GroundedFunctionNetwork, but got {type(other)}"
)
def shortname(var):
return var[var.find("::") + 2 : var.rfind("_")]
def shortn... | 645,417 |
Executes the FIB over a particular set of inputs and returns the
result.
Args:
inputs: Input set where keys are the names of input nodes in the
GrFN and each key points to a set of input values (or just one).
Returns:
A set of outputs from executing the GrFN... | def run(
self,
inputs: Dict[str, Union[float, Iterable]],
covers: Dict[str, Union[float, Iterable]],
torch_size: Optional[int] = None,
) -> Union[float, Iterable]:
# Abort run if covers does not match our expected cover set
if len(covers) != len(self.cover_no... | 645,422 |
Parses the XML ast tree recursively to generate a JSON AST
which can be ingested by other scripts to generate Python
scripts.
Args:
root: The current root of the tree.
state: The current state of the tree defined by an object of the
ParseState class.
... | def parseTree(self, root, state: ParseState) -> List[Dict]:
if root.tag in self.AST_TAG_HANDLERS:
return self.AST_TAG_HANDLERS[root.tag](root, state)
elif root.tag in self.libRtns:
return self.process_libRtn(root, state)
else:
prog = []
... | 645,455 |
Loads a list with all the functions in the Fortran File
Args:
root: The root of the XML ast tree.
Returns:
None
Does not return anything but populates a list (self.functionList) that
contains all the functions in the Fortran File. | def loadFunction(self, root):
for element in root.iter():
if element.tag == "function":
self.functionList.append(element.attrib["name"]) | 645,456 |
'Drill down' into an edge in the analysis graph and inspect its
provenance. This function prints the provenance.
Args:
G
source
target | def inspect_edge(G: AnalysisGraph, source: str, target: str):
return create_statement_inspection_table(
G[source][target]["InfluenceStatements"]
) | 645,485 |
Return the sentences that led to the construction of a specified edge.
Args:
G
source: The source of the edge.
target: The target of the edge. | def _get_edge_sentences(
G: AnalysisGraph, source: str, target: str
) -> List[str]:
return chain.from_iterable(
[
[repr(e.text) for e in s.evidence]
for s in G.edges[source, target]["InfluenceStatements"]
]
) | 645,486 |
Create a dictionary mapping high-level concepts to low-level indicators
Args:
n: Number of indicators to return
Returns:
Dictionary that maps concept names to lists of indicator names. | def construct_concept_to_indicator_mapping(n: int = 1) -> Dict[str, List[str]]:
df = pd.read_sql_table("concept_to_indicator_mapping", con=engine)
gb = df.groupby("Concept")
_dict = {
k: [get_variable_and_source(x) for x in take(n, v["Indicator"].values)]
for k, v in gb
}
retu... | 645,516 |
Genera texto en markdown a partir de los metadatos de una `dataset`.
Args:
dataset (dict): Diccionario con metadatos de una `dataset`.
Returns:
str: Texto que describe una `dataset`. | def dataset_to_markdown(dataset):
text_template =
if "distribution" in dataset:
distributions = "".join(
map(distribution_to_markdown, dataset["distribution"]))
else:
distributions = ""
text = text_template.format(
title=dataset["title"],
description=d... | 645,608 |
Genera texto en markdown a partir de los metadatos de una
`distribution`.
Args:
distribution (dict): Diccionario con metadatos de una
`distribution`.
Returns:
str: Texto que describe una `distribution`. | def distribution_to_markdown(distribution):
text_template =
if "field" in distribution:
fields = "- " + \
"\n- ".join(map(field_to_markdown, distribution["field"]))
else:
fields = ""
text = text_template.format(
title=distribution["title"],
description... | 645,609 |
Genera texto en markdown a partir de los metadatos de un `field`.
Args:
field (dict): Diccionario con metadatos de un `field`.
Returns:
str: Texto que describe un `field`. | def field_to_markdown(field):
if "title" in field:
field_title = "**{}**".format(field["title"])
else:
raise Exception("Es necesario un `title` para describir un campo.")
field_type = " ({})".format(field["type"]) if "type" in field else ""
field_desc = ": {}".format(
field... | 645,610 |
Valida que un archivo `data.json` cumpla con el schema definido.
Chequea que el data.json tiene todos los campos obligatorios y que
tanto los campos obligatorios como los opcionales siguen la estructura
definida en el schema.
Args:
catalog (str o dict): Catálogo (dict, JSON... | def is_valid_catalog(self, catalog=None):
catalog = catalog or self
return validation.is_valid_catalog(catalog, validator=self.validator) | 645,620 |
Toma un dict con la metadata de un dataset, y devuelve un dict coni
los valores que dataset_report() usa para reportar sobre él.
Args:
dataset (dict): Diccionario con la metadata de un dataset.
Returns:
dict: Diccionario con los campos a nivel dataset que requiere
... | def _dataset_report_helper(cls, dataset, catalog_homepage=None):
publisher_name = helpers.traverse_dict(dataset, ["publisher", "name"])
languages = cls._stringify_list(dataset.get("language"))
super_themes = cls._stringify_list(dataset.get("superTheme"))
themes = cls._stringify... | 645,624 |
Toma un dict con la metadata de un catálogo, y devuelve un dict con
los valores que catalog_report() usa para reportar sobre él.
Args:
catalog (dict): Diccionario con la metadata de un catálogo.
validation (dict): Resultado, únicamente a nivel catálogo, de la
val... | def _catalog_report_helper(catalog, catalog_validation, url, catalog_id,
catalog_org):
fields = OrderedDict()
fields["catalog_metadata_url"] = url
fields["catalog_federation_id"] = catalog_id
fields["catalog_federation_org"] = catalog_org
f... | 645,625 |
Genera un reporte sobre los datasets de un único catálogo.
Args:
catalog (dict, str o unicode): Representación externa (path/URL) o
interna (dict) de un catálogo.
harvest (str): Criterio de cosecha ('all', 'none',
'valid', 'report' o 'good').
Ret... | def catalog_report(self, catalog, harvest='none', report=None,
catalog_id=None, catalog_homepage=None,
catalog_org=None):
url = catalog if isinstance(catalog, string_types) else None
catalog = readers.read_catalog(catalog)
validation = sel... | 645,628 |
Extrae de un reporte los datos necesarios para reconocer qué
datasets marcar para cosecha en cualquier generador.
Args:
report (str o list): Reporte (lista de dicts) o path a uno.
Returns:
list: Lista de tuplas con los títulos de catálogo y dataset de cada
r... | def _extract_datasets_to_harvest(cls, report):
assert isinstance(report, string_types + (list,))
# Si `report` es una lista de tuplas con longitud 2, asumimos que es un
# reporte procesado para extraer los datasets a harvestear. Se devuelve
# intacta.
if (isinstance(rep... | 645,633 |
Setea valor en diccionario anidado, siguiendo lista de keys.
Args:
dict_obj (dict): Un diccionario anidado.
keys (list): Una lista de keys para navegar el diccionario.
value (any): Un valor para reemplazar. | def _set_default_value(dict_obj, keys, value):
variable = dict_obj
if len(keys) == 1:
if not variable.get(keys[0]):
variable[keys[0]] = value
else:
for idx, field in enumerate(keys):
if idx < len(keys) - 1:
variable = variable[field]
if... | 645,656 |
Toma el path a un JSON y devuelve el diccionario que representa.
Se asume que el parámetro es una URL si comienza con 'http' o 'https', o
un path local de lo contrario.
Args:
json_path_or_url (str): Path local o URL remota a un archivo de texto
plano en formato JSON.
Returns:
... | def read_json(json_path_or_url):
assert isinstance(json_path_or_url, string_types)
parsed_url = urlparse(json_path_or_url)
if parsed_url.scheme in ["http", "https"]:
res = requests.get(json_path_or_url, verify=False)
json_dict = json.loads(res.content, encoding='utf-8')
else:
... | 645,657 |
Toma el path a un catálogo en formato XLSX y devuelve el diccionario
que representa.
Se asume que el parámetro es una URL si comienza con 'http' o 'https', o
un path local de lo contrario.
Args:
xlsx_path_or_url (str): Path local o URL remota a un libro XLSX de
formato específico p... | def read_xlsx_catalog(xlsx_path_or_url, logger=None):
logger = logger or pydj_logger
assert isinstance(xlsx_path_or_url, string_types)
parsed_url = urlparse(xlsx_path_or_url)
if parsed_url.scheme in ["http", "https"]:
res = requests.get(xlsx_path_or_url, verify=False)
tmpfilename =... | 645,658 |
Genera un diccionario de metadatos de catálogo a partir de un XLSX bien
formado.
Args:
xlsx_path (str): Path a un archivo XLSX "template" para describir la
metadata de un catálogo.
Returns:
dict: Diccionario con los metadatos de un catálogo. | def read_local_xlsx_catalog(xlsx_path, logger=None):
logger = logger or pydj_logger
wb = pyxl.load_workbook(open(xlsx_path, 'rb'), data_only=True,
read_only=True)
# Toma las hojas del modelo, resistente a mayúsuculas/minúsculas
ws_catalog = helpers.get_ws_case_insensit... | 645,663 |
Valida que un archivo `data.json` cumpla con el schema definido.
Chequea que el data.json tiene todos los campos obligatorios y que
tanto los campos obligatorios como los opcionales siguen la estructura
definida en el schema.
Args:
catalog (str o dict): Catálogo (dict, JSON o XLSX) a ser valid... | def is_valid_catalog(catalog, validator=None):
catalog = readers.read_catalog(catalog)
if not validator:
if hasattr(catalog, "validator"):
validator = catalog.validator
else:
validator = create_validator()
jsonschema_res = validator.is_valid(catalog)
custom_... | 645,710 |
Permite validar un catálogo por línea de comandos.
Args:
catalog (str): Path local o URL a un catálogo. | def main(catalog):
res = validate_catalog(catalog, only_errors=True, fmt="list",
export_path=None, validator=None)
print("")
print("=== Errores a nivel de CATALOGO ===")
pprint(res["catalog"])
print("")
print("=== Errores a nivel de DATASET ===")
pprint(res["... | 645,715 |
Toma un catálogo y escribe los temas de la taxonomía que no están
presentes.
Args:
catalog (DataJson): El catálogo de origen que contiene la
taxonomía.
portal_url (str): La URL del portal CKAN de destino.
apikey (str): La apikey de un usuario con los perm... | def push_new_themes(catalog, portal_url, apikey):
ckan_portal = RemoteCKAN(portal_url, apikey=apikey)
existing_themes = ckan_portal.call_action('group_list')
new_themes = [theme['id'] for theme in catalog[
'themeTaxonomy'] if theme['id'] not in existing_themes]
pushed_names = []
for new... | 645,725 |
Toma la url de un portal y un id, y devuelve la organización a buscar.
Args:
portal_url (str): La URL del portal CKAN de origen.
org_id (str): El id de la organización a buscar.
Returns:
dict: Diccionario con la información de la organización. | def get_organization_from_ckan(portal_url, org_id):
ckan_portal = RemoteCKAN(portal_url)
return ckan_portal.call_action('organization_show',
data_dict={'id': org_id}) | 645,726 |
Toma un id de organización y la purga del portal de destino.
Args:
portal_url (str): La URL del portal CKAN de destino.
apikey (str): La apikey de un usuario con los permisos que le
permitan borrar la organización.
organization_id(str): Id o name de la organiz... | def remove_organization_from_ckan(portal_url, apikey, organization_id):
portal = RemoteCKAN(portal_url, apikey=apikey)
try:
portal.call_action('organization_purge',
data_dict={'id': organization_id})
except Exception as e:
logger.exception('Ocurrió un error b... | 645,729 |
Toma una lista de ids de organización y las purga del portal de destino.
Args:
portal_url (str): La URL del portal CKAN de destino.
apikey (str): La apikey de un usuario con los permisos que le
permitan borrar la organización.
organization_list(list): Id o nam... | def remove_organizations_from_ckan(portal_url, apikey, organization_list):
for org in organization_list:
remove_organization_from_ckan(portal_url, apikey, org) | 645,730 |
Convierte los metadatos de un portal disponibilizados por la Action API
v3 de CKAN al estándar data.json.
Args:
portal_url (str): URL de un portal de datos CKAN que soporte la API v3.
Returns:
dict: Representación interna de un catálogo para uso en las funciones
de esta librerí... | def read_ckan_catalog(portal_url):
portal = RemoteCKAN(portal_url)
try:
status = portal.call_action(
'status_show', requests_kwargs={"verify": False})
packages_list = portal.call_action(
'package_list', requests_kwargs={"verify": False})
groups_list = portal.... | 645,823 |
Exporta una tabla en el formato deseado (CSV o XLSX).
La extensión del archivo debe ser ".csv" o ".xlsx", y en función de
ella se decidirá qué método usar para escribirlo.
Args:
table (list of dicts): Tabla a ser exportada.
path (str): Path al archivo CSV o XLSX de exportación. | def write_table(table, path, column_styles=None, cell_styles=None):
assert isinstance(path, string_types), "`path` debe ser un string"
assert isinstance(table, list), "`table` debe ser una lista de dicts"
# si la tabla está vacía, no escribe nada
if len(table) == 0:
logger.warning("Tabla v... | 645,832 |
Escribe el catálogo en Excel.
Args:
catalog (DataJson): Catálogo de datos.
path (str): Directorio absoluto donde se crea el archivo XLSX.
xlsx_fields (dict): Orden en que los campos del perfil de metadatos
se escriben en cada hoja del Excel. | def write_xlsx_catalog(catalog, path, xlsx_fields=None):
xlsx_fields = xlsx_fields or XLSX_FIELDS
catalog_dict = {}
catalog_dict["catalog"] = [
_tabulate_nested_dict(catalog.get_catalog_metadata(
exclude_meta_fields=["themeTaxonomy"]),
"catalog")
]
catalog_dict... | 645,843 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.