Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def sphere_example():
env = holodeck.make("MazeWorld")
# This command is to constantly rotate to the right
command = 2
for i in range(10):
env.reset()
for _ in range(1000):
state, reward, terminal, _ = env.step(command)
... | [
"A basic example of how to use the sphere agent."
] |
Please provide a description of the function:def android_example():
env = holodeck.make("AndroidPlayground")
# The Android's command is a 94 length vector representing torques to be applied at each of his joints
command = np.ones(94) * 10
for i in range(10):
env.reset()
for j in ra... | [
"A basic example of how to use the android agent."
] |
Please provide a description of the function:def multi_agent_example():
env = holodeck.make("UrbanCity")
cmd0 = np.array([0, 0, -2, 10])
cmd1 = np.array([0, 0, 5, 10])
for i in range(10):
env.reset()
# This will queue up a new agent to spawn into the environment, given that the coo... | [
"A basic example of using multiple agents"
] |
Please provide a description of the function:def world_command_examples():
env = holodeck.make("MazeWorld")
# This is the unaltered MazeWorld
for _ in range(300):
_ = env.tick()
env.reset()
# The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it... | [
"A few examples to showcase commands for manipulating the worlds."
] |
Please provide a description of the function:def editor_example():
sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]
agent = AgentDefinition("uav0", agents.UavAgent, sensors)
env = HolodeckEnvironment(agent, start_world=False)
env.agents["uav0"].set_control_scheme(1... | [
"This editor example shows how to interact with holodeck worlds while they are being built\n in the Unreal Engine. Most people that use holodeck will not need this.\n "
] |
Please provide a description of the function:def editor_multi_agent_example():
agent_definitions = [
AgentDefinition("uav0", agents.UavAgent, [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR]),
AgentDefinition("uav1", agents.UavAgent, [Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR])
]
... | [
"This editor example shows how to interact with holodeck worlds that have multiple agents.\n This is specifically for when working with UE4 directly and not a prebuilt binary.\n "
] |
Please provide a description of the function:def get_holodeck_path():
if "HOLODECKPATH" in os.environ and os.environ["HOLODECKPATH"] != "":
return os.environ["HOLODECKPATH"]
if os.name == "posix":
return os.path.expanduser("~/.local/share/holodeck")
elif os.name == "nt":
return ... | [
"Gets the path of the holodeck environment\n\n Returns:\n (str): path to the current holodeck environment\n "
] |
Please provide a description of the function:def convert_unicode(value):
if isinstance(value, dict):
return {convert_unicode(key): convert_unicode(value)
for key, value in value.iteritems()}
elif isinstance(value, list):
return [convert_unicode(item) for item in value]
e... | [
"Resolves python 2 issue with json loading in unicode instead of string\n\n Args:\n value (str): Unicode value to be converted\n\n Returns:\n (str): converted string\n\n "
] |
Please provide a description of the function:def info(self):
result = list()
result.append("Agents:\n")
for agent in self._all_agents:
result.append("\tName: ")
result.append(agent.name)
result.append("\n\tType: ")
result.append(type(agent... | [
"Returns a string with specific information about the environment.\n This information includes which agents are in the environment and which sensors they have.\n\n Returns:\n str: The information in a string format.\n "
] |
Please provide a description of the function:def reset(self):
self._reset_ptr[0] = True
self._commands.clear()
for _ in range(self._pre_start_steps + 1):
self.tick()
return self._default_state_fn() | [
"Resets the environment, and returns the state.\n If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from\n agent name to state.\n\n Returns:\n tuple or dict: For single agent environment, returns the same as `step`.\n ... |
Please provide a description of the function:def step(self, action):
self._agent.act(action)
self._handle_command_buffer()
self._client.release()
self._client.acquire()
return self._get_single_state() | [
"Supplies an action to the main agent and tells the environment to tick once.\n Primary mode of interaction for single agent environments.\n\n Args:\n action (np.ndarray): An action for the main agent to carry out on the next tick.\n\n Returns:\n tuple: The (state, reward,... |
Please provide a description of the function:def teleport(self, agent_name, location=None, rotation=None):
self.agents[agent_name].teleport(location * 100, rotation) # * 100 to convert m to cm
self.tick() | [
"Teleports the target agent to any given location, and applies a specific rotation.\n\n Args:\n agent_name (str): The name of the agent to teleport.\n location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to.\n If no location is given, ... |
Please provide a description of the function:def tick(self):
self._handle_command_buffer()
self._client.release()
self._client.acquire()
return self._get_full_state() | [
"Ticks the environment once. Normally used for multi-agent environments.\n\n Returns:\n dict: A dictionary from agent name to its full state. The full state is another dictionary\n from :obj:`holodeck.sensors.Sensors` enum to np.ndarray, containing the sensors information\n f... |
Please provide a description of the function:def add_state_sensors(self, agent_name, sensors):
if isinstance(sensors, list):
for sensor in sensors:
self.add_state_sensors(agent_name, sensor)
else:
if agent_name not in self._sensor_map:
sel... | [
"Adds a sensor to a particular agent. This only works if the world you are running also includes\n that particular sensor on the agent.\n\n Args:\n agent_name (str): The name of the agent to add the sensor to.\n sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Se... |
Please provide a description of the function:def spawn_agent(self, agent_definition, location):
self._should_write_to_command_buffer = True
self._add_agents(agent_definition)
command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type)
self._comman... | [
"Queues a spawn agent command. It will be applied when `tick` or `step` is called next.\n The agent won't be able to be used until the next frame.\n\n Args:\n agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn.\n location (np.ndarray or list): The pos... |
Please provide a description of the function:def set_fog_density(self, density):
if density < 0 or density > 1:
raise HolodeckException("Fog density should be between 0 and 1")
self._should_write_to_command_buffer = True
command_to_send = ChangeFogDensityCommand(density)
... | [
"Queue up a change fog density command. It will be applied when `tick` or `step` is called next.\n By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the\n world, it will be automatically created with the given density.\n\n Args:\n ... |
Please provide a description of the function:def set_day_time(self, hour):
self._should_write_to_command_buffer = True
command_to_send = DayTimeCommand(hour % 24)
self._commands.add_command(command_to_send) | [
"Queue up a change day time command. It will be applied when `tick` or `step` is called next.\n By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere\n or directional light in the world, the command will not function properly but will not cause a ... |
Please provide a description of the function:def start_day_cycle(self, day_length):
if day_length <= 0:
raise HolodeckException("The given day length should be between above 0!")
self._should_write_to_command_buffer = True
command_to_send = DayCycleCommand(True)
com... | [
"Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next.\n The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a\n day will be roughly equivalent to the number of minutes given.\n\n Arg... |
Please provide a description of the function:def stop_day_cycle(self):
self._should_write_to_command_buffer = True
command_to_send = DayCycleCommand(False)
self._commands.add_command(command_to_send) | [
"Queue up a day cycle command to stop the day cycle. It will be applied when `tick` or `step` is called next.\n By the next tick, day cycle will stop where it is.\n "
] |
Please provide a description of the function:def teleport_camera(self, location, rotation):
self._should_write_to_command_buffer = True
command_to_send = TeleportCameraCommand(location, rotation)
self._commands.add_command(command_to_send) | [
"Queue up a teleport camera command to stop the day cycle.\n By the next tick, the camera's location and rotation will be updated\n "
] |
Please provide a description of the function:def set_weather(self, weather_type):
if not SetWeatherCommand.has_type(weather_type.lower()):
raise HolodeckException("Invalid weather type " + weather_type)
self._should_write_to_command_buffer = True
command_to_send = SetWeathe... | [
"Queue up a set weather command. It will be applied when `tick` or `step` is called next.\n By the next tick, the lighting, skysphere, fog, and relevant particle systems will be updated and/or spawned\n to the given weather. If there is no skysphere or directional light in the world, the command may n... |
Please provide a description of the function:def set_control_scheme(self, agent_name, control_scheme):
if agent_name not in self.agents:
print("No such agent %s" % agent_name)
else:
self.agents[agent_name].set_control_scheme(control_scheme) | [
"Set the control scheme for a specific agent.\n\n Args:\n agent_name (str): The name of the agent to set the control scheme for.\n control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`)\n "
] |
Please provide a description of the function:def _handle_command_buffer(self):
if self._should_write_to_command_buffer:
self._write_to_command_buffer(self._commands.to_json())
self._should_write_to_command_buffer = False
self._commands.clear() | [
"Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then\n clears the contents of the self._commands list"
] |
Please provide a description of the function:def _add_agents(self, agent_definitions):
if not isinstance(agent_definitions, list):
agent_definitions = [agent_definitions]
prepared_agents = self._prepare_agents(agent_definitions)
self._all_agents.extend(prepared_agents)
... | [
"Add specified agents to the client. Set up their shared memory and sensor linkages.\n Does not spawn an agent in the Holodeck, this is only for documenting and accessing already existing agents.\n This is an internal function.\n Positional Arguments:\n agent_definitions -- The agent(s) ... |
Please provide a description of the function:def _write_to_command_buffer(self, to_write):
# TODO(mitch): Handle the edge case of writing too much data to the buffer.
np.copyto(self._command_bool_ptr, True)
to_write += '0' # The gason JSON parser in holodeck expects a 0 at the end of t... | [
"Write input to the command buffer. Reformat input string to the correct format.\n\n Args:\n to_write (str): The string to write to the command buffer.\n "
] |
Please provide a description of the function:def set_control_scheme(self, index):
self._current_control_scheme = index % self._num_control_schemes
self._control_scheme_buffer[0] = self._current_control_scheme | [
"Sets the control scheme for the agent. See :obj:`ControlSchemes`.\n\n Args:\n index (int): The control scheme to use. Should be set with an enum from :obj:`ControlSchemes`.\n "
] |
Please provide a description of the function:def teleport(self, location=None, rotation=None):
val = 0
if location is not None:
val += 1
np.copyto(self._teleport_buffer, location)
if rotation is not None:
np.copyto(self._rotation_buffer, rotation)
... | [
"Teleports the agent to a specific location, with a specific rotation.\n\n Args:\n location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters.\n If None, keeps the current location. Defaults to None.\n rotation (np.ndarray, ... |
Please provide a description of the function:def get_object(
self, object_t, object_id=None, relation=None, parent=None, **kwargs
):
url = self.object_url(object_t, object_id, relation, **kwargs)
logging.debug(url)
response = yield self._async_client.fetch(url)
resp_... | [
"\n Actually query the Deezer API to retrieve the object\n\n :returns: json dictionary or raw string if other\n format requested\n "
] |
Please provide a description of the function:def _process_json(self, item, parent=None):
if "data" in item:
return [self._process_json(i, parent) for i in item["data"]]
result = {}
for key, value in item.items():
if isinstance(value, dict) and ("type" in value o... | [
"\n Recursively convert dictionary\n to :class:`~deezer.resources.Resource` object\n\n :returns: instance of :class:`~deezer.resources.Resource`\n "
] |
Please provide a description of the function:def url(self, request=""):
if request.startswith("/"):
request = request[1:]
return "{}://{}/{}".format(self.scheme, self.host, request) | [
"Build the url with the appended request if provided."
] |
Please provide a description of the function:def object_url(self, object_t, object_id=None, relation=None, **kwargs):
if object_t not in self.objects_types:
raise TypeError("{} is not a valid type".format(object_t))
request_items = (
str(item) for item in [object_t, obje... | [
"\n Helper method to build the url to query to access the object\n passed as parameter\n\n :raises TypeError: if the object type is invalid\n "
] |
Please provide a description of the function:def get_object(
self, object_t, object_id=None, relation=None, parent=None, **kwargs
):
url = self.object_url(object_t, object_id, relation, **kwargs)
response = self.session.get(url)
return self._process_json(response.json(), par... | [
"\n Actually query the Deezer API to retrieve the object\n\n :returns: json dictionary\n "
] |
Please provide a description of the function:def get_chart(self, relation=None, index=0, limit=10, **kwargs):
return self.get_object(
"chart", object_id="0", relation=relation, parent="chart", **kwargs
) | [
"\n Get chart\n\n :returns: a list of :class:`~deezer.resources.Resource` objects.\n "
] |
Please provide a description of the function:def get_album(self, object_id, relation=None, **kwargs):
return self.get_object("album", object_id, relation=relation, **kwargs) | [
"\n Get the album with the provided id\n\n :returns: an :class:`~deezer.resources.Album` object\n "
] |
Please provide a description of the function:def get_artist(self, object_id, relation=None, **kwargs):
return self.get_object("artist", object_id, relation=relation, **kwargs) | [
"\n Get the artist with the provided id\n\n :returns: an :class:`~deezer.resources.Artist` object\n "
] |
Please provide a description of the function:def search(self, query, relation=None, index=0, limit=25, **kwargs):
return self.get_object(
"search", relation=relation, q=query, index=index, limit=limit, **kwargs
) | [
"\n Search track, album, artist or user\n\n :returns: a list of :class:`~deezer.resources.Resource` objects.\n "
] |
Please provide a description of the function:def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs):
assert isinstance(terms, dict), "terms must be a dict"
# terms are sorted (for consistent tests between Python < 3.7 and >= 3.7)
query = " ".join(sorted(['{}:"{}"'.... | [
"\n Advanced search of track, album or artist.\n\n See `Search section of Deezer API\n <https://developers.deezer.com/api/search>`_ for search terms.\n\n :returns: a list of :class:`~deezer.resources.Resource` objects.\n\n >>> client.advanced_search({\"artist\": \"Daft Punk\", \"a... |
Please provide a description of the function:def asdict(self):
result = {}
for key in self._fields:
value = getattr(self, key)
if isinstance(value, list):
value = [i.asdict() if isinstance(i, Resource) else i for i in value]
if isinstance(valu... | [
"\n Convert resource to dictionary\n "
] |
Please provide a description of the function:def get_relation(self, relation, **kwargs):
# pylint: disable=E1101
return self.client.get_object(self.type, self.id, relation, self, **kwargs) | [
"\n Generic method to load the relation from any resource.\n\n Query the client with the object's known parameters\n and try to retrieve the provided relation type. This\n is not meant to be used directly by a client, it's more\n a helper method for the child objects.\n "
] |
Please provide a description of the function:def iter_relation(self, relation, **kwargs):
# pylint: disable=E1101
index = 0
while 1:
items = self.get_relation(relation, index=index, **kwargs)
for item in items:
yield (item)
if len(ite... | [
"\n Generic method to iterate relation from any resource.\n\n Query the client with the object's known parameters\n and try to retrieve the provided relation type. This\n is not meant to be used directly by a client, it's more\n a helper method for the child objects.\n "
] |
Please provide a description of the function:def get_artist(self):
# pylint: disable=E1101
assert isinstance(self, (Album, Track))
return self.client.get_artist(self.artist.id) | [
"\n :returns: the :mod:`Artist <deezer.resources.Artist>` of the resource\n :raises AssertionError: if the object is not album or track\n "
] |
Please provide a description of the function:def run(graph, save_on_github=False, main_entity=None):
try:
ontology = graph.all_ontologies[0]
uri = ontology.uri
except:
ontology = None
uri = ";".join([s for s in graph.sources])
# ontotemplate = open("template.html", "r"... | [
"\n 2016-11-30\n "
] |
Please provide a description of the function:def _buildTemplates(self):
c_mydict = build_class_json(self.ontospy_graph.all_classes)
JSON_DATA_CLASSES = json.dumps(c_mydict)
extra_context = {
"ontograph": self.ontospy_graph,
'JSON_DATA_CLASSES' : JSON_... | [
"\n OVERRIDING THIS METHOD from Factory\n "
] |
Please provide a description of the function:def main_cli(ctx, verbose=False):
sTime = time.time()
if ctx.obj is None: # Fix for bug (as of 3.0)
# https://github.com/pallets/click/issues/888
ctx.obj = {}
ctx.obj['VERBOSE'] = verbose
ctx.obj['STIME'] = sTime
click.secho("Ontosp... | [
"\nOntospy allows to extract and visualise ontology information included in RDF data. Use one of the commands listed below to find out more, or visit http://lambdamusic.github.io/ontospy \n "
] |
Please provide a description of the function:def scan(ctx, sources=None, endpoint=False, raw=False, extra=False):
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
'extra': extra,
}
if sources or (sources and endpoint):
action_analyz... | [
"SCAN: get ontology data from RDF source and print out a report.\n "
] |
Please provide a description of the function:def gendocs(ctx,
source=None,
outputpath="",
extra=False,
lib=False,
type="",
title="",
theme="",
showthemes=False,
showtypes=False):
verbose = ctx.obj['VERBO... | [
"GENDOCS: generate documentation in html or markdown format.\n "
] |
Please provide a description of the function:def lib(ctx,
filepath=None,
extra=False,
bootstrap=False,
cache=False,
reveal=False,
show=False,
save=False,
directory=False):
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = ... | [
"\n LIBRARY: work with a local library of RDF models.\n "
] |
Please provide a description of the function:def ser(ctx, source, output_format):
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
}
output_format = output_format
VALID_FORMATS = ['xml', 'n3', 'turtle', 'nt', 'pretty-xml', "json-ld"]
if not... | [
"SERIALIZE: tranform an RDF graph to a format of choice.\n "
] |
Please provide a description of the function:def utils(
ctx,
filepath=None,
jsonld=False,
discover=False,
):
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
}
DONE_ACTION = False
if jsonld:
if not filep... | [
"UTILS: miscellaneous bits and pieces.\n "
] |
Please provide a description of the function:def _debugGraph(self):
print("Len of graph: ", len(self.rdflib_graph))
for x, y, z in self.rdflib_graph:
print(x, y, z) | [
"internal util to print out contents of graph"
] |
Please provide a description of the function:def load_uri(self, uri):
# if self.verbose: printDebug("----------")
if self.verbose: printDebug("Reading: <%s>" % uri, fg="green")
success = False
sorted_fmt_opts = try_sort_fmt_opts(self.rdf_format_opts, uri)
for f in sor... | [
"\n Load a single resource into the graph for this object. \n\n Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://github.com/RDFLib/rdflib/iss... |
Please provide a description of the function:def resolve_redirects_if_needed(self, uri):
if type(uri) == type("string") or type(uri) == type(u"unicode"):
if uri.startswith("www."): # support for lazy people
uri = "http://%s" % str(uri)
if uri.startswith("http:/... | [
"\n substitute with final uri after 303 redirects (if it's a www location!)\n :param uri:\n :return:\n "
] |
Please provide a description of the function:def print_summary(self):
if self.sources_valid:
printDebug(
"----------\nLoaded %d triples.\n----------" % len(
self.rdflib_graph),
fg='white')
printDebug(
"RDF sourc... | [
"\n print out stats about loading operation\n "
] |
Please provide a description of the function:def loading_failed(self, rdf_format_opts, uri=""):
if uri:
uri = " <%s>" % str(uri)
printDebug(
"----------\nFatal error parsing graph%s\n(using RDF serializations: %s)"
% (uri, str(rdf_format_opts)), "red")
... | [
"default message if we need to abort loading"
] |
Please provide a description of the function:def printTriples(self):
printDebug(Fore.RED + self.uri + Style.RESET_ALL)
for x in self.triples:
printDebug(Fore.BLACK + "=> " + unicode(x[1]))
printDebug(Style.DIM + ".... " + unicode(x[2]) + Fore.RESET)
print("") | [
" display triples "
] |
Please provide a description of the function:def _build_qname(self, uri=None, namespaces=None):
if not uri:
uri = self.uri
if not namespaces:
namespaces = self.namespaces
return uri2niceString(uri, namespaces) | [
" extracts a qualified name for a uri "
] |
Please provide a description of the function:def _buildGraph(self):
for n in self.namespaces:
self.rdflib_graph.bind(n[0], rdflib.Namespace(n[1]))
if self.triples:
for terzetto in self.triples:
self.rdflib_graph.add(terzetto) | [
"\n transforms the triples list into a proper rdflib graph\n (which can be used later for querying)\n "
] |
Please provide a description of the function:def ancestors(self, cl=None, noduplicates=True):
if not cl:
cl = self
if cl.parents():
bag = []
for x in cl.parents():
if x.uri != cl.uri: # avoid circular relationships
bag += ... | [
" returns all ancestors in the taxonomy "
] |
Please provide a description of the function:def descendants(self, cl=None, noduplicates=True):
if not cl:
cl = self
if cl.children():
bag = []
for x in cl.children():
if x.uri != cl.uri: # avoid circular relationships
bag... | [
" returns all descendants in the taxonomy "
] |
Please provide a description of the function:def getValuesForProperty(self, aPropURIRef):
if not type(aPropURIRef) == rdflib.URIRef:
aPropURIRef = rdflib.URIRef(aPropURIRef)
return list(self.rdflib_graph.objects(None, aPropURIRef)) | [
"\n generic way to extract some prop value eg\n In [11]: c.getValuesForProperty(rdflib.RDF.type)\n Out[11]:\n [rdflib.term.URIRef(u'http://www.w3.org/2002/07/owl#Class'),\n rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#Class')]\n "
] |
Please provide a description of the function:def annotations(self, qname=True):
if qname:
return sorted([(uri2niceString(x, self.namespaces)
), (uri2niceString(y, self.namespaces)), z]
for x, y, z in self.triples)
else:
... | [
"\n wrapper that returns all triples for an onto.\n By default resources URIs are transformed into qnames\n "
] |
Please provide a description of the function:def stats(self):
printDebug("Classes.....: %d" % len(self.all_classes))
printDebug("Properties..: %d" % len(self.all_properties)) | [
" shotcut to pull out useful info for interactive use "
] |
Please provide a description of the function:def printStats(self):
printDebug("----------------")
printDebug("Parents......: %d" % len(self.parents()))
printDebug("Children.....: %d" % len(self.children()))
printDebug("Ancestors....: %d" % len(self.ancestors()))
printDeb... | [
" shortcut to pull out useful info for interactive use "
] |
Please provide a description of the function:def printStats(self):
printDebug("----------------")
printDebug("Parents......: %d" % len(self.parents()))
printDebug("Children.....: %d" % len(self.children()))
printDebug("Ancestors....: %d" % len(self.ancestors()))
printDeb... | [
" shotcut to pull out useful info for interactive use "
] |
Please provide a description of the function:def get_package_folders(top_folder, root_path):
_dirs = []
out = []
for root, dirs, files in os.walk(top_folder):
for dir in dirs:
_dirs.append(os.path.join(root, dir))
for d in _dirs:
_d = os.path.join(d, "*.*")
out.a... | [
"\n Utility to generate dynamically the list of folders needed by the package_data setting\n ..\n package_data={\n 'ontospy': ['viz/static/*.*', 'viz/templates/*.*', 'viz/templates/shared/*.*', 'viz/templates/splitter/*.*', 'viz/templates/markdown/*.*'],\n },\n ...\n "
] |
Please provide a description of the function:def _buildTemplates(self):
jsontree_classes = build_D3treeStandard(
0, 99, 1, self.ontospy_graph.toplayer_classes)
c_total = len(self.ontospy_graph.all_classes)
JSON_DATA_CLASSES = json.dumps({
'children': jsontree_c... | [
"\n OVERRIDING THIS METHOD from Factory\n "
] |
Please provide a description of the function:def getAllClasses(self, hide_base_schemas=True, hide_implicit_types=True):
query =
BIT_BASE_SCHEMAS =
BIT_IMPLICIT_TYPES =
if hide_base_schemas == False: # ..then do not filter out XML stuff
BIT_BASE_SCHEMAS = ""
... | [
"\n * hide_base_schemas: by default, obscure all RDF/RDFS/OWL/XML stuff\n * hide_implicit_types: don't make any inference based on rdf:type declarations\n ",
"SELECT DISTINCT ?x ?c\n WHERE {\n {\n { ?x a owl:Class }\n ... |
Please provide a description of the function:def getClassDirectSubs(self, aURI):
aURI = aURI
qres = self.rdflib_graph.query( % (aURI))
return list(qres) | [
"\n 2015-06-03: currenlty not used, inferred from above\n ",
"SELECT DISTINCT ?x\n WHERE {\n { ?x rdfs:subClassOf <%s> }\n FILTER (!isBlank(?x))\n }\n "
] |
Please provide a description of the function:def getClassAllSupers(self, aURI):
aURI = aURI
try:
qres = self.rdflib_graph.query( % (aURI))
except:
printDebug(
"... warning: the 'getClassAllSupers' query failed (maybe missing SPARQL 1.1 support?)"
... | [
"\n note: requires SPARQL 1.1\n 2015-06-04: currenlty not used, inferred from above\n ",
"SELECT DISTINCT ?x\n WHERE {\n { <%s> rdfs:subClassOf+ ?x }\n FILTER (!isBlank(?x))\n }\n "
] |
Please provide a description of the function:def getClassAllSubs(self, aURI):
aURI = aURI
try:
qres = self.rdflib_graph.query( % (aURI))
except:
printDebug(
"... warning: the 'getClassAllSubs' query failed (maybe missing SPARQL 1.1 support?)"
... | [
"\n note: requires SPARQL 1.1\n 2015-06-04: currenlty not used, inferred from above\n ",
"SELECT DISTINCT ?x\n WHERE {\n { ?x rdfs:subClassOf+ <%s> }\n FILTER (!isBlank(?x))\n }\n "
] |
Please provide a description of the function:def getPropAllSupers(self, aURI):
aURI = aURI
try:
qres = self.rdflib_graph.query( % (aURI))
except:
printDebug(
"... warning: the 'getPropAllSupers' query failed (maybe missing SPARQL 1.1 support?)"
... | [
"\n note: requires SPARQL 1.1\n 2015-06-04: currenlty not used, inferred from above\n ",
"SELECT DISTINCT ?x\n WHERE {\n { <%s> rdfs:subPropertyOf+ ?x }\n FILTER (!isBlank(?x))\n }\n "
... |
Please provide a description of the function:def getPropAllSubs(self, aURI):
aURI = aURI
try:
qres = self.rdflib_graph.query( % (aURI))
except:
printDebug(
"... warning: the 'getPropAllSubs' query failed (maybe missing SPARQL 1.1 support?)"
... | [
"\n note: requires SPARQL 1.1\n 2015-06-04: currenlty not used, inferred from above\n ",
"SELECT DISTINCT ?x\n WHERE {\n { ?x rdfs:subPropertyOf+ <%s> }\n FILTER (!isBlank(?x))\n }\n "
... |
Please provide a description of the function:def getSKOSDirectSubs(self, aURI):
aURI = aURI
qres = self.rdflib_graph.query( % (aURI, aURI))
return list(qres) | [
"\n 2015-08-19: currenlty not used, inferred from above\n ",
"SELECT DISTINCT ?x\n WHERE {\n {\n { ?x skos:broader <%s> }\n UNION\n { <%s> skos:narrower ?s }\n ... |
Please provide a description of the function:def parse_options():
parser = optparse.OptionParser(usage=USAGE, version=ontospy.VERSION)
parser.add_option("-p", "--port",
action="store", type="int", default=DEFAULT_PORT, dest="port",
help="A number specifying which port to use for the server.")
opts, args =... | [
"\n\tparse_options() -> opts, args\n\n\tParse any command-line options given returning both\n\tthe parsed options and arguments.\n\n\thttps://docs.python.org/2/library/optparse.html\n\n\t"
] |
Please provide a description of the function:def main():
# boilerplate
print("Ontospy " + ontospy.VERSION)
ontospy.get_or_create_home_repo()
ONTOSPY_LOCAL_MODELS = ontospy.get_home_location()
opts, args = parse_options()
sTime = time.time()
# switch dir and start server
startServer(port=DEFAULT_PORT, locati... | [
" command line script "
] |
Please provide a description of the function:def load_rdf(self,
uri_or_path=None,
data=None,
file_obj=None,
rdf_format="",
verbose=False,
hide_base_schemas=True,
hide_implicit_types=True,
... | [
"Load an RDF source into an ontospy/rdflib graph"
] |
Please provide a description of the function:def load_sparql(self,
sparql_endpoint,
verbose=False,
hide_base_schemas=True,
hide_implicit_types=True,
hide_implicit_preds=True, credentials=None):
try:
... | [
"\n Set up a SPARQLStore backend as a virtual ontospy graph\n\n Note: we're using a 'SPARQLUpdateStore' backend instead of 'SPARQLStore' cause otherwise authentication fails (https://github.com/RDFLib/rdflib/issues/755)\n\n @TODO this error seems to be fixed in upcoming rdflib versions\n ... |
Please provide a description of the function:def build_all(self,
verbose=False,
hide_base_schemas=True,
hide_implicit_types=True,
hide_implicit_preds=True):
if verbose:
printDebug("Scanning entities...", "green")
... | [
"\n Extract all ontology entities from an RDF graph and construct Python representations of them.\n "
] |
Please provide a description of the function:def build_ontologies(self, exclude_BNodes=False, return_string=False):
out = []
qres = self.sparqlHelper.getOntology()
if qres:
# NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..)
for candidate in q... | [
"\n Extract ontology instances info from the graph, then creates python objects for them.\n\n Note: often ontology info is nested in structures like this:\n\n [ a owl:Ontology ;\n vann:preferredNamespacePrefix \"bsym\" ;\n vann:preferredNamespaceUri \"http://bsym.bloomberg... |
Please provide a description of the function:def build_classes(self, hide_base_schemas=True, hide_implicit_types=True):
self.all_classes = [] # @todo: keep adding?
qres = self.sparqlHelper.getAllClasses(hide_base_schemas,
hide_implicit_types)
... | [
"\n 2015-06-04: removed sparql 1.1 queries\n 2015-05-25: optimized via sparql queries in order to remove BNodes\n 2015-05-09: new attempt\n\n Note: sparqlHelper.getAllClasses() returns a list of tuples,\n (class, classRDFtype)\n so in some cases there are duplicates if a cl... |
Please provide a description of the function:def build_properties(self, hide_implicit_preds=True):
self.all_properties = [] # @todo: keep adding?
self.all_properties_annotation = []
self.all_properties_object = []
self.all_properties_datatype = []
qres = self.sparqlHel... | [
"\n 2015-06-04: removed sparql 1.1 queries\n 2015-06-03: analogous to get classes\n\n # instantiate properties making sure duplicates are pruned\n # but the most specific rdftype is kept\n # eg OWL:ObjectProperty over RDF:property\n\n "
] |
Please provide a description of the function:def build_skos_concepts(self):
self.all_skos_concepts = [] # @todo: keep adding?
qres = self.sparqlHelper.getSKOSInstances()
# print("rdflib query done")
for candidate in qres:
test_existing_cl = self.get_skos(uri=cand... | [
"\n 2015-08-19: first draft\n "
] |
Please provide a description of the function:def build_shapes(self):
self.all_shapes = [] # @todo: keep adding?
qres = self.sparqlHelper.getShapes()
for candidate in qres:
test_existing_cl = self.get_any_entity(uri=candidate[0])
if not test_existing_cl:
... | [
"\n Extract SHACL data shapes from the rdf graph.\n <http://www.w3.org/ns/shacl#>\n\n Instatiate the Shape Python objects and relate it to existing classes,\n if available.\n "
] |
Please provide a description of the function:def build_entity_from_uri(self, uri, ontospyClass=None):
if not ontospyClass:
ontospyClass = RDF_Entity
elif not issubclass(ontospyClass, RDF_Entity):
click.secho("Error: <%s> is not a subclass of ontospy.RDF_Entity" % str(ont... | [
"\n Extract RDF statements having a URI as subject, then instantiate the RDF_Entity Python object so that it can be queried further.\n\n Passing <ontospyClass> allows to instantiate a user-defined RDF_Entity subclass.\n\n NOTE: the entity is not attached to any index. In future version we may c... |
Please provide a description of the function:def __buildDomainRanges(self, aProp):
domains = chain(aProp.rdflib_graph.objects(
None, rdflib.term.URIRef(u'http://schema.org/domainIncludes')), aProp.rdflib_graph.objects(
None, rdflib.RDFS.domain))
ranges = chain(aProp.rd... | [
"\n extract domain/range details and add to Python objects\n "
] |
Please provide a description of the function:def __computeTopLayer(self):
exit = []
for c in self.all_classes:
if not c.parents():
exit += [c]
self.toplayer_classes = exit # sorted(exit, key=lambda x: x.id) # doesnt work
# properties
exit =... | [
"\n deprecated: now this is calculated when entities get extracted\n "
] |
Please provide a description of the function:def get_class(self, id=None, uri=None, match=None):
if not id and not uri and not match:
return None
if type(id) == type("string"):
uri = id
id = None
if not is_http(uri):
match = uri
... | [
"\n get the saved-class with given ID or via other methods...\n\n Note: it tries to guess what is being passed..\n\n In [1]: g.get_class(uri='http://www.w3.org/2000/01/rdf-schema#Resource')\n Out[1]: <Class *http://www.w3.org/2000/01/rdf-schema#Resource*>\n\n In [2]: g.get_class(1... |
Please provide a description of the function:def get_property(self, id=None, uri=None, match=None):
if not id and not uri and not match:
return None
if type(id) == type("string"):
uri = id
id = None
if not is_http(uri):
match = u... | [
"\n get the saved-class with given ID or via other methods...\n\n Note: analogous to getClass method\n "
] |
Please provide a description of the function:def get_skos(self, id=None, uri=None, match=None):
if not id and not uri and not match:
return None
if type(id) == type("string"):
uri = id
id = None
if not is_http(uri):
match = uri
... | [
"\n get the saved skos concept with given ID or via other methods...\n\n Note: it tries to guess what is being passed as above\n "
] |
Please provide a description of the function:def get_any_entity(self, id=None, uri=None, match=None):
if not id and not uri and not match:
return None
if type(id) == type("string"):
uri = id
id = None
if not is_http(uri):
match =... | [
"\n get a generic entity with given ID or via other methods...\n "
] |
Please provide a description of the function:def get_ontology(self, id=None, uri=None, match=None):
if not id and not uri and not match:
return None
if type(id) == type("string"):
uri = id
id = None
if not is_http(uri):
match = u... | [
"\n get the saved-ontology with given ID or via other methods...\n "
] |
Please provide a description of the function:def ontologyClassTree(self):
treedict = {}
if self.all_classes:
treedict[0] = self.toplayer_classes
for element in self.all_classes:
if element.children():
treedict[element] = element.childr... | [
"\n Returns a dict representing the ontology tree\n Top level = {0:[top classes]}\n Multi inheritance is represented explicitly\n "
] |
Please provide a description of the function:def ontologyPropTree(self):
treedict = {}
if self.all_properties:
treedict[0] = self.toplayer_properties
for element in self.all_properties:
if element.children():
treedict[element] = elemen... | [
"\n Returns a dict representing the ontology tree\n Top level = {0:[top properties]}\n Multi inheritance is represented explicitly\n "
] |
Please provide a description of the function:def ontologyConceptTree(self):
treedict = {}
if self.all_skos_concepts:
treedict[0] = self.toplayer_skos
for element in self.all_skos_concepts:
if element.children():
treedict[element] = ele... | [
"\n Returns a dict representing the skos tree\n Top level = {0:[top concepts]}\n Multi inheritance is represented explicitly\n "
] |
Please provide a description of the function:def ontologyShapeTree(self):
treedict = {}
if self.all_shapes:
treedict[0] = self.toplayer_shapes
for element in self.all_shapes:
if element.children():
treedict[element] = element.children(... | [
"\n Returns a dict representing the ontology tree\n Top level = {0:[top properties]}\n Multi inheritance is represented explicitly\n "
] |
Please provide a description of the function:def rdf_source(self, format="turtle"):
s = self.rdflib_graph.serialize(format=format)
if isinstance(s, bytes):
s = s.decode('utf-8')
return s | [
"\n Wrapper for rdflib serializer method.\n Valid options are: xml, n3, turtle, nt, pretty-xml, json-ld [trix not working out of the box]\n "
] |
Please provide a description of the function:def query(self, stringa):
qres = self.rdflib_graph.query(stringa)
return list(qres) | [
"SPARQL query / wrapper for rdflib sparql query method "
] |
Please provide a description of the function:def stats(self):
out = []
out += [("Ontologies", len(self.all_ontologies))]
out += [("Triples", self.triplesCount())]
out += [("Classes", len(self.all_classes))]
out += [("Properties", len(self.all_properties))]
out +=... | [
" shotcut to pull out useful info for a graph"
] |
Please provide a description of the function:def printClassTree(self, element=None, showids=False, labels=False, showtype=False):
TYPE_MARGIN = 11 # length for owl:class etc..
if not element: # first time
for x in self.toplayer_classes:
printGenericTree(x, 0, show... | [
"\n Print nicely into stdout the class tree of an ontology\n\n Note: indentation is made so that ids up to 3 digits fit in, plus a space.\n [123]1--\n [1]123--\n [12]12--\n "
] |
Please provide a description of the function:def printPropertyTree(self, element=None, showids=False, labels=False, showtype=False):
TYPE_MARGIN = 18 # length for owl:AnnotationProperty etc..
if not element: # first time
for x in self.toplayer_properties:
printGen... | [
"\n Print nicely into stdout the property tree of an ontology\n\n Note: indentation is made so that ids up to 3 digits fit in, plus a space.\n [123]1--\n [1]123--\n [12]12--\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.