idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
249,100
def iter_module_paths ( modules = None ) : modules = modules or list ( sys . modules . values ( ) ) for module in modules : try : filename = module . __file__ except ( AttributeError , ImportError ) : # pragma: no cover continue if filename is not None : abs_filename = os . path . abspath ( filename ) if os . path . isfile ( abs_filename ) : yield abs_filename
Yield paths of all imported modules .
94
8
249,101
def update_paths ( self ) : new_paths = [ ] with self . lock : for path in expand_source_paths ( iter_module_paths ( ) ) : if path not in self . paths : self . paths . add ( path ) new_paths . append ( path ) if new_paths : self . watch_paths ( new_paths )
Check sys . modules for paths to add to our path set .
84
13
249,102
def search_traceback ( self , tb ) : new_paths = [ ] with self . lock : for filename , line , funcname , txt in traceback . extract_tb ( tb ) : path = os . path . abspath ( filename ) if path not in self . paths : self . paths . add ( path ) new_paths . append ( path ) if new_paths : self . watch_paths ( new_paths )
Inspect a traceback for new paths to add to our path set .
101
15
249,103
def args_from_interpreter_flags ( ) : flag_opt_map = { 'debug' : 'd' , 'dont_write_bytecode' : 'B' , 'no_user_site' : 's' , 'no_site' : 'S' , 'ignore_environment' : 'E' , 'verbose' : 'v' , 'bytes_warning' : 'b' , 'quiet' : 'q' , 'optimize' : 'O' , } args = [ ] for flag , opt in flag_opt_map . items ( ) : v = getattr ( sys . flags , flag , 0 ) if v > 0 : args . append ( '-' + opt * v ) for opt in sys . warnoptions : args . append ( '-W' + opt ) return args
Return a list of command - line arguments reproducing the current settings in sys . flags and sys . warnoptions .
180
23
249,104
def spawn ( spec , kwargs , pass_fds = ( ) ) : r , w = os . pipe ( ) for fd in [ r ] + list ( pass_fds ) : set_inheritable ( fd , True ) preparation_data = get_preparation_data ( ) r_handle = get_handle ( r ) args , env = get_command_line ( pipe_handle = r_handle ) process = subprocess . Popen ( args , env = env , close_fds = False ) to_child = os . fdopen ( w , 'wb' ) to_child . write ( pickle . dumps ( [ preparation_data , spec , kwargs ] ) ) to_child . close ( ) return process
Invoke a python function in a subprocess .
165
10
249,105
def get_watchman_sockpath ( binpath = 'watchman' ) : path = os . getenv ( 'WATCHMAN_SOCK' ) if path : return path cmd = [ binpath , '--output-encoding=json' , 'get-sockname' ] result = subprocess . check_output ( cmd ) result = json . loads ( result ) return result [ 'sockname' ]
Find the watchman socket or raise .
91
8
249,106
def start_reloader ( worker_path , reload_interval = 1 , shutdown_interval = default , verbose = 1 , logger = None , monitor_factory = None , worker_args = None , worker_kwargs = None , ignore_files = None , ) : if is_active ( ) : return get_reloader ( ) if logger is None : logger = DefaultLogger ( verbose ) if monitor_factory is None : monitor_factory = find_default_monitor_factory ( logger ) if shutdown_interval is default : shutdown_interval = reload_interval reloader = Reloader ( worker_path = worker_path , worker_args = worker_args , worker_kwargs = worker_kwargs , reload_interval = reload_interval , shutdown_interval = shutdown_interval , monitor_factory = monitor_factory , logger = logger , ignore_files = ignore_files , ) return reloader . run ( )
Start a monitor and then fork a worker process which starts by executing the importable function at worker_path .
212
22
249,107
def run ( self ) : self . _capture_signals ( ) self . _start_monitor ( ) try : while True : if not self . _run_worker ( ) : self . _wait_for_changes ( ) time . sleep ( self . reload_interval ) except KeyboardInterrupt : pass finally : self . _stop_monitor ( ) self . _restore_signals ( ) sys . exit ( 1 )
Execute the reloader forever blocking the current thread .
93
11
249,108
def run_once ( self ) : self . _capture_signals ( ) self . _start_monitor ( ) try : self . _run_worker ( ) except KeyboardInterrupt : return finally : self . _stop_monitor ( ) self . _restore_signals ( )
Execute the worker once .
62
6
249,109
def malloc ( self , key , shape , dtype ) : if key not in self . _memory or self . _memory [ key ] . shape != shape or self . _memory [ key ] . dtype != dtype : self . _memory [ key ] = Shmem ( key , shape , dtype , self . _uuid ) return self . _memory [ key ] . np_array
Allocates a block of shared memory and returns a numpy array whose data corresponds with that block .
85
21
249,110
def package_info ( pkg_name ) : indent = " " for config , _ in _iter_packages ( ) : if pkg_name == config [ "name" ] : print ( "Package:" , pkg_name ) print ( indent , "Platform:" , config [ "platform" ] ) print ( indent , "Version:" , config [ "version" ] ) print ( indent , "Path:" , config [ "path" ] ) print ( indent , "Worlds:" ) for world in config [ "maps" ] : world_info ( world [ "name" ] , world_config = world , initial_indent = " " )
Prints the information of a package .
140
8
249,111
def world_info ( world_name , world_config = None , initial_indent = "" , next_indent = " " ) : if world_config is None : for config , _ in _iter_packages ( ) : for world in config [ "maps" ] : if world [ "name" ] == world_name : world_config = world if world_config is None : raise HolodeckException ( "Couldn't find world " + world_name ) second_indent = initial_indent + next_indent agent_indent = second_indent + next_indent sensor_indent = agent_indent + next_indent print ( initial_indent , world_config [ "name" ] ) print ( second_indent , "Resolution:" , world_config [ "window_width" ] , "x" , world_config [ "window_height" ] ) print ( second_indent , "Agents:" ) for agent in world_config [ "agents" ] : print ( agent_indent , "Name:" , agent [ "agent_name" ] ) print ( agent_indent , "Type:" , agent [ "agent_type" ] ) print ( agent_indent , "Sensors:" ) for sensor in agent [ "sensors" ] : print ( sensor_indent , sensor )
Gets and prints the information of a world .
296
10
249,112
def install ( package_name ) : holodeck_path = util . get_holodeck_path ( ) binary_website = "https://s3.amazonaws.com/holodeckworlds/" if package_name not in packages : raise HolodeckException ( "Unknown package name " + package_name ) package_url = packages [ package_name ] print ( "Installing " + package_name + " at " + holodeck_path ) install_path = os . path . join ( holodeck_path , "worlds" ) binary_url = binary_website + util . get_os_key ( ) + "_" + package_url _download_binary ( binary_url , install_path ) if os . name == "posix" : _make_binary_excecutable ( package_name , install_path )
Installs a holodeck package .
189
8
249,113
def remove ( package_name ) : if package_name not in packages : raise HolodeckException ( "Unknown package name " + package_name ) for config , path in _iter_packages ( ) : if config [ "name" ] == package_name : shutil . rmtree ( path )
Removes a holodeck package .
65
8
249,114
def make ( world_name , gl_version = GL_VERSION . OPENGL4 , window_res = None , cam_res = None , verbose = False ) : holodeck_worlds = _get_worlds_map ( ) if world_name not in holodeck_worlds : raise HolodeckException ( "Invalid World Name" ) param_dict = copy ( holodeck_worlds [ world_name ] ) param_dict [ "start_world" ] = True param_dict [ "uuid" ] = str ( uuid . uuid4 ( ) ) param_dict [ "gl_version" ] = gl_version param_dict [ "verbose" ] = verbose if window_res is not None : param_dict [ "window_width" ] = window_res [ 0 ] param_dict [ "window_height" ] = window_res [ 1 ] if cam_res is not None : param_dict [ "camera_width" ] = cam_res [ 0 ] param_dict [ "camera_height" ] = cam_res [ 1 ] return HolodeckEnvironment ( * * param_dict )
Creates a holodeck environment using the supplied world name .
251
13
249,115
def unlink ( self ) : if os . name == "posix" : self . __linux_unlink__ ( ) elif os . name == "nt" : self . __windows_unlink__ ( ) else : raise HolodeckException ( "Currently unsupported os: " + os . name )
unlinks the shared memory
66
5
249,116
def add_number_parameters ( self , number ) : if isinstance ( number , list ) : for x in number : self . add_number_parameters ( x ) return self . _parameters . append ( "{ \"value\": " + str ( number ) + " }" )
Add given number parameters to the internal list .
62
9
249,117
def add_string_parameters ( self , string ) : if isinstance ( string , list ) : for x in string : self . add_string_parameters ( x ) return self . _parameters . append ( "{ \"value\": \"" + string + "\" }" )
Add given string parameters to the internal list .
61
9
249,118
def set_type ( self , weather_type ) : weather_type . lower ( ) exists = self . has_type ( weather_type ) if exists : self . add_string_parameters ( weather_type )
Set the weather type .
47
5
249,119
def uav_example ( ) : env = holodeck . make ( "UrbanCity" ) # This changes the control scheme for the uav env . set_control_scheme ( "uav0" , ControlSchemes . UAV_ROLL_PITCH_YAW_RATE_ALT ) for i in range ( 10 ) : env . reset ( ) # This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitude. command = np . array ( [ 0 , 0 , 2 , 10 ] ) for _ in range ( 1000 ) : state , reward , terminal , _ = env . step ( command ) # To access specific sensor data: pixels = state [ Sensors . PIXEL_CAMERA ] velocity = state [ Sensors . VELOCITY_SENSOR ]
A basic example of how to use the UAV agent .
180
12
249,120
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 ) # To access specific sensor data: pixels = state [ Sensors . PIXEL_CAMERA ] orientation = state [ Sensors . ORIENTATION_SENSOR ]
A basic example of how to use the sphere agent .
106
11
249,121
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 range ( 1000 ) : if j % 50 == 0 : command *= - 1 state , reward , terminal , _ = env . step ( command ) # To access specific sensor data: pixels = state [ Sensors . PIXEL_CAMERA ] orientation = state [ Sensors . ORIENTATION_SENSOR ]
A basic example of how to use the android agent .
136
11
249,122
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 coordinates are not blocked. sensors = [ Sensors . PIXEL_CAMERA , Sensors . LOCATION_SENSOR , Sensors . VELOCITY_SENSOR ] agent = AgentDefinition ( "uav1" , agents . UavAgent , sensors ) env . spawn_agent ( agent , [ 1 , 1 , 5 ] ) env . set_control_scheme ( "uav0" , ControlSchemes . UAV_ROLL_PITCH_YAW_RATE_ALT ) env . set_control_scheme ( "uav1" , ControlSchemes . UAV_ROLL_PITCH_YAW_RATE_ALT ) env . tick ( ) # Tick the environment once so the second agent spawns before we try to interact with it. env . act ( "uav0" , cmd0 ) env . act ( "uav1" , cmd1 ) for _ in range ( 1000 ) : states = env . tick ( ) uav0_terminal = states [ "uav0" ] [ Sensors . TERMINAL ] uav1_reward = states [ "uav1" ] [ Sensors . REWARD ]
A basic example of using multiple agents
344
7
249,123
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 to 6 AM. env . set_day_time ( 6 ) for _ in range ( 300 ) : _ = env . tick ( ) env . reset ( ) # reset() undoes all alterations to the world # The start_day_cycle command starts rotating the sun to emulate day cycles. # The parameter sets the day length in minutes. env . start_day_cycle ( 5 ) for _ in range ( 1500 ) : _ = env . tick ( ) env . reset ( ) # The set_fog_density changes the density of the fog in the world. 1 is the maximum density. env . set_fog_density ( .25 ) for _ in range ( 300 ) : _ = env . tick ( ) env . reset ( ) # The set_weather_command changes the weather in the world. The two available options are "rain" and "cloudy". # The rainfall particle system is attached to the agent, so the rain particles will only be found around each agent. # Every world is clear by default. env . set_weather ( "rain" ) for _ in range ( 500 ) : _ = env . tick ( ) env . reset ( ) env . set_weather ( "cloudy" ) for _ in range ( 500 ) : _ = env . tick ( ) env . reset ( ) env . teleport_camera ( [ 1000 , 1000 , 1000 ] , [ 0 , 0 , 0 ] ) for _ in range ( 500 ) : _ = env . tick ( ) env . reset ( )
A few examples to showcase commands for manipulating the worlds .
395
11
249,124
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 ) command = [ 0 , 0 , 10 , 50 ] for i in range ( 10 ) : env . reset ( ) for _ in range ( 1000 ) : state , reward , terminal , _ = env . step ( command )
This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine . Most people that use holodeck will not need this .
143
34
249,125
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 ] ) ] env = HolodeckEnvironment ( agent_definitions , start_world = False ) cmd0 = np . array ( [ 0 , 0 , - 2 , 10 ] ) cmd1 = np . array ( [ 0 , 0 , 5 , 10 ] ) for i in range ( 10 ) : env . reset ( ) env . act ( "uav0" , cmd0 ) env . act ( "uav1" , cmd1 ) for _ in range ( 1000 ) : states = env . tick ( ) uav0_terminal = states [ "uav0" ] [ Sensors . TERMINAL ] uav1_reward = states [ "uav1" ] [ Sensors . REWARD ]
This editor example shows how to interact with holodeck worlds that have multiple agents . This is specifically for when working with UE4 directly and not a prebuilt binary .
248
34
249,126
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 os . path . expanduser ( "~\\AppData\\Local\\holodeck" ) else : raise NotImplementedError ( "holodeck is only supported for Linux and Windows" )
Gets the path of the holodeck environment
137
10
249,127
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 ] elif isinstance ( value , unicode ) : return value . encode ( 'utf-8' ) else : return value
Resolves python 2 issue with json loading in unicode instead of string
97
14
249,128
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 ) . __name__ ) result . append ( "\n\t" ) result . append ( "Sensors:\n" ) for sensor in self . _sensor_map [ agent . name ] . keys ( ) : result . append ( "\t\t" ) result . append ( Sensors . name ( sensor ) ) result . append ( "\n" ) return "" . join ( result )
Returns a string with specific information about the environment . This information includes which agents are in the environment and which sensors they have .
154
25
249,129
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 . If it is a single agent environment it returns that state for that agent . Otherwise it returns a dict from agent name to state .
59
35
249,130
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 . Primary mode of interaction for single agent environments .
54
25
249,131
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 .
48
15
249,132
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 .
43
14
249,133
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 : self . _sensor_map [ agent_name ] = dict ( ) self . _sensor_map [ agent_name ] [ sensors ] = self . _client . malloc ( agent_name + "_" + Sensors . name ( sensors ) , Sensors . shape ( sensors ) , Sensors . dtype ( sensors ) )
Adds a sensor to a particular agent . This only works if the world you are running also includes that particular sensor on the agent .
136
26
249,134
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 . _commands . add_command ( command_to_send )
Queues a spawn agent command . It will be applied when tick or step is called next . The agent won t be able to be used until the next frame .
79
33
249,135
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 ) self . _commands . add_command ( command_to_send )
Queue up a change fog density command . It will be applied when tick or step is called next . By the next tick the exponential height fog in the world will have the new density . If there is no fog in the world it will be automatically created with the given density .
85
55
249,136
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 . By the next tick the lighting and the skysphere will be updated with the new hour . If there is no skysphere or directional light in the world the command will not function properly but will not cause a crash .
56
67
249,137
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 ) command_to_send . set_day_length ( day_length ) self . _commands . add_command ( command_to_send )
Queue up a day cycle command to start the day cycle . It will be applied when tick or step is called next . The sky sphere will now update each tick with an updated sun angle as it moves about the sky . The length of a day will be roughly equivalent to the number of minutes given .
98
60
249,138
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 . By the next tick day cycle will stop where it is .
53
36
249,139
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 . By the next tick the camera s location and rotation will be updated
57
25
249,140
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 .
67
9
249,141
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 clears the contents of the self . _commands list
71
33
249,142
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 the file. input_bytes = str . encode ( to_write ) for index , val in enumerate ( input_bytes ) : self . _command_buffer_ptr [ index ] = val
Write input to the command buffer . Reformat input string to the correct format .
118
16
249,143
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 ) val += 2 self . _teleport_bool_buffer [ 0 ] = val
Teleports the agent to a specific location with a specific rotation .
79
13
249,144
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 .
50
11
249,145
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 , object_id , relation ] if item is not None ) request = "/" . join ( request_items ) base_url = self . url ( request ) if self . access_token is not None : kwargs [ "access_token" ] = str ( self . access_token ) if kwargs : for key , value in kwargs . items ( ) : if not isinstance ( value , str ) : kwargs [ key ] = str ( value ) # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7) sorted_kwargs = SortedDict . from_dict ( kwargs ) result = "{}?{}" . format ( base_url , urlencode ( sorted_kwargs ) ) else : result = base_url return result
Helper method to build the url to query to access the object passed as parameter
251
15
249,146
def get_album ( self , object_id , relation = None , * * kwargs ) : return self . get_object ( "album" , object_id , relation = relation , * * kwargs )
Get the album with the provided id
47
7
249,147
def get_artist ( self , object_id , relation = None , * * kwargs ) : return self . get_object ( "artist" , object_id , relation = relation , * * kwargs )
Get the artist with the provided id
47
7
249,148
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 )
Search track album artist or user
59
6
249,149
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 ( [ '{}:"{}"' . format ( k , v ) for ( k , v ) in terms . items ( ) ] ) ) return self . get_object ( "search" , relation = relation , q = query , index = index , limit = limit , * * kwargs )
Advanced search of track album or artist .
136
8
249,150
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 ( value , Resource ) : value = value . asdict ( ) result [ key ] = value return result
Convert resource to dictionary
86
5
249,151
def get_relation ( self , relation , * * kwargs ) : # pylint: disable=E1101 return self . client . get_object ( self . type , self . id , relation , self , * * kwargs )
Generic method to load the relation from any resource .
53
10
249,152
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 ( items ) == 0 : break index += len ( items )
Generic method to iterate relation from any resource .
76
10
249,153
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") ontotemplate = open ( ONTODOCS_VIZ_TEMPLATES + "sigmajs.html" , "r" ) t = Template ( ontotemplate . read ( ) ) dict_graph = build_class_json ( graph . classes ) JSON_DATA_CLASSES = json . dumps ( dict_graph ) if False : c_mylist = build_D3treeStandard ( 0 , 99 , 1 , graph . toplayer_classes ) p_mylist = build_D3treeStandard ( 0 , 99 , 1 , graph . toplayer_properties ) s_mylist = build_D3treeStandard ( 0 , 99 , 1 , graph . toplayer_skos ) c_total = len ( graph . classes ) p_total = len ( graph . all_properties ) s_total = len ( graph . all_skos_concepts ) # hack to make sure that we have a default top level object JSON_DATA_CLASSES = json . dumps ( { 'children' : c_mylist , 'name' : 'owl:Thing' , 'id' : "None" } ) JSON_DATA_PROPERTIES = json . dumps ( { 'children' : p_mylist , 'name' : 'Properties' , 'id' : "None" } ) JSON_DATA_CONCEPTS = json . dumps ( { 'children' : s_mylist , 'name' : 'Concepts' , 'id' : "None" } ) c = Context ( { "ontology" : ontology , "main_uri" : uri , "STATIC_PATH" : ONTODOCS_VIZ_STATIC , "classes" : graph . classes , "classes_TOPLAYER" : len ( graph . toplayer_classes ) , "properties" : graph . all_properties , "properties_TOPLAYER" : len ( graph . toplayer_properties ) , "skosConcepts" : graph . all_skos_concepts , "skosConcepts_TOPLAYER" : len ( graph . toplayer_skos ) , # "TOTAL_CLASSES": c_total, # "TOTAL_PROPERTIES": p_total, # "TOTAL_CONCEPTS": s_total, 'JSON_DATA_CLASSES' : JSON_DATA_CLASSES , # 'JSON_DATA_PROPERTIES' : JSON_DATA_PROPERTIES, # 'JSON_DATA_CONCEPTS' : JSON_DATA_CONCEPTS, } ) rnd = t . render ( c ) return safe_str ( rnd )
2016 - 11 - 30
667
5
249,154
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
53
8
249,155
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 sorted_fmt_opts : if self . verbose : printDebug ( ".. trying rdf serialization: <%s>" % f ) try : if f == 'json-ld' : if self . verbose : printDebug ( "Detected JSONLD - loading data into rdflib.ConjunctiveGraph()" , fg = 'green' ) temp_graph = rdflib . ConjunctiveGraph ( ) else : temp_graph = rdflib . Graph ( ) temp_graph . parse ( uri , format = f ) if self . verbose : printDebug ( "..... success!" , bold = True ) success = True self . sources_valid += [ uri ] # ok, so merge self . rdflib_graph = self . rdflib_graph + temp_graph break except : temp = None if self . verbose : printDebug ( "..... failed" ) # self._debugGraph() if not success == True : self . loading_failed ( sorted_fmt_opts , uri = uri ) self . sources_invalid += [ uri ]
Load a single resource into the graph for this object .
329
11
249,156
def print_summary ( self ) : if self . sources_valid : printDebug ( "----------\nLoaded %d triples.\n----------" % len ( self . rdflib_graph ) , fg = 'white' ) printDebug ( "RDF sources loaded successfully: %d of %d." % ( len ( self . sources_valid ) , len ( self . sources_valid ) + len ( self . sources_invalid ) ) , fg = 'green' ) for s in self . sources_valid : printDebug ( "..... '" + s + "'" , fg = 'white' ) printDebug ( "----------" , fg = 'white' ) else : printDebug ( "Sorry - no valid RDF was found" , fg = 'red' ) if self . sources_invalid : printDebug ( "----------\nRDF sources failed to load: %d.\n----------" % ( len ( self . sources_invalid ) ) , fg = 'red' ) for s in self . sources_invalid : printDebug ( "-> " + s , fg = "red" )
print out stats about loading operation
248
6
249,157
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" ) printDebug ( "----------\nTIP: You can try one of the following RDF validation services\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\n<http://www.ivan-herman.net/Misc/2008/owlrl/>" ) return
default message if we need to abort loading
159
8
249,158
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
57
10
249,159
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 += [ x ] + self . ancestors ( x , noduplicates ) else : bag += [ x ] # finally: if noduplicates : return remove_duplicates ( bag ) else : return bag else : return [ ]
returns all ancestors in the taxonomy
110
8
249,160
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 += [ x ] + self . descendants ( x , noduplicates ) else : bag += [ x ] # finally: if noduplicates : return remove_duplicates ( bag ) else : return bag else : return [ ]
returns all descendants in the taxonomy
110
8
249,161
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 : return sorted ( self . triples )
wrapper that returns all triples for an onto . By default resources URIs are transformed into qnames
75
20
249,162
def printStats ( self ) : printDebug ( "----------------" ) printDebug ( "Parents......: %d" % len ( self . parents ( ) ) ) printDebug ( "Children.....: %d" % len ( self . children ( ) ) ) printDebug ( "Ancestors....: %d" % len ( self . ancestors ( ) ) ) printDebug ( "Descendants..: %d" % len ( self . descendants ( ) ) ) printDebug ( "Domain of....: %d" % len ( self . domain_of ) ) printDebug ( "Range of.....: %d" % len ( self . range_of ) ) printDebug ( "Instances....: %d" % self . count ( ) ) printDebug ( "----------------" )
shortcut to pull out useful info for interactive use
164
10
249,163
def load_sparql ( self , sparql_endpoint , verbose = False , hide_base_schemas = True , hide_implicit_types = True , hide_implicit_preds = True , credentials = None ) : try : # graph = rdflib.Graph('SPARQLStore') # graph = rdflib.ConjunctiveGraph('SPARQLStore') graph = rdflib . ConjunctiveGraph ( 'SPARQLUpdateStore' ) if credentials and type ( credentials ) == tuple : # https://github.com/RDFLib/rdflib/issues/343 graph . store . setCredentials ( credentials [ 0 ] , credentials [ 1 ] ) # graph.store.setHTTPAuth('BASIC') # graph.store.setHTTPAuth('DIGEST') graph . open ( sparql_endpoint ) self . rdflib_graph = graph self . sparql_endpoint = sparql_endpoint self . sources = [ sparql_endpoint ] self . sparqlHelper = SparqlHelper ( self . rdflib_graph , self . sparql_endpoint ) self . namespaces = sorted ( self . rdflib_graph . namespaces ( ) ) except : printDebug ( "Error trying to connect to Endpoint." ) raise
Set up a SPARQLStore backend as a virtual ontospy graph
295
15
249,164
def build_all ( self , verbose = False , hide_base_schemas = True , hide_implicit_types = True , hide_implicit_preds = True ) : if verbose : printDebug ( "Scanning entities..." , "green" ) printDebug ( "----------" , "comment" ) self . build_ontologies ( ) if verbose : printDebug ( "Ontologies.........: %d" % len ( self . all_ontologies ) , "comment" ) self . build_classes ( hide_base_schemas , hide_implicit_types ) if verbose : printDebug ( "Classes............: %d" % len ( self . all_classes ) , "comment" ) self . build_properties ( hide_implicit_preds ) if verbose : printDebug ( "Properties.........: %d" % len ( self . all_properties ) , "comment" ) if verbose : printDebug ( "..annotation.......: %d" % len ( self . all_properties_annotation ) , "comment" ) if verbose : printDebug ( "..datatype.........: %d" % len ( self . all_properties_datatype ) , "comment" ) if verbose : printDebug ( "..object...........: %d" % len ( self . all_properties_object ) , "comment" ) self . build_skos_concepts ( ) if verbose : printDebug ( "Concepts (SKOS)....: %d" % len ( self . all_skos_concepts ) , "comment" ) self . build_shapes ( ) if verbose : printDebug ( "Shapes (SHACL).....: %d" % len ( self . all_shapes ) , "comment" ) # self.__computeTopLayer() self . __computeInferredProperties ( ) if verbose : printDebug ( "----------" , "comment" )
Extract all ontology entities from an RDF graph and construct Python representations of them .
429
18
249,165
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 qres : if isBlankNode ( candidate [ 0 ] ) : if exclude_BNodes : continue else : checkDC_ID = [ x for x in self . rdflib_graph . objects ( candidate [ 0 ] , rdflib . namespace . DC . identifier ) ] if checkDC_ID : out += [ Ontology ( checkDC_ID [ 0 ] , namespaces = self . namespaces ) , ] else : vannprop = rdflib . URIRef ( "http://purl.org/vocab/vann/preferredNamespaceUri" ) vannpref = rdflib . URIRef ( "http://purl.org/vocab/vann/preferredNamespacePrefix" ) checkDC_ID = [ x for x in self . rdflib_graph . objects ( candidate [ 0 ] , vannprop ) ] if checkDC_ID : checkDC_prefix = [ x for x in self . rdflib_graph . objects ( candidate [ 0 ] , vannpref ) ] if checkDC_prefix : out += [ Ontology ( checkDC_ID [ 0 ] , namespaces = self . namespaces , prefPrefix = checkDC_prefix [ 0 ] ) ] else : out += [ Ontology ( checkDC_ID [ 0 ] , namespaces = self . namespaces ) ] else : out += [ Ontology ( candidate [ 0 ] , namespaces = self . namespaces ) ] else : pass # printDebug("No owl:Ontologies found") # finally... add all annotations/triples self . all_ontologies = out for onto in self . all_ontologies : onto . triples = self . sparqlHelper . entityTriples ( onto . uri ) onto . _buildGraph ( )
Extract ontology instances info from the graph then creates python objects for them .
461
16
249,166
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 ( ontospyClass ) ) return None else : pass qres = self . sparqlHelper . entityTriples ( uri ) if qres : entity = ontospyClass ( rdflib . URIRef ( uri ) , None , self . namespaces ) entity . triples = qres entity . _buildGraph ( ) # force construction of mini graph # try to add class info test = entity . getValuesForProperty ( rdflib . RDF . type ) if test : entity . rdftype = test entity . rdftype_qname = [ entity . _build_qname ( x ) for x in test ] return entity else : return None
Extract RDF statements having a URI as subject then instantiate the RDF_Entity Python object so that it can be queried further .
231
29
249,167
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 , showids , labels , showtype , TYPE_MARGIN ) else : printGenericTree ( element , 0 , showids , labels , showtype , TYPE_MARGIN )
Print nicely into stdout the class tree of an ontology
104
12
249,168
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 : printGenericTree ( x , 0 , showids , labels , showtype , TYPE_MARGIN ) else : printGenericTree ( element , 0 , showids , labels , showtype , TYPE_MARGIN )
Print nicely into stdout the property tree of an ontology
106
12
249,169
def add ( self , text = "" , default_continuousAdd = True ) : if not text and default_continuousAdd : self . continuousAdd ( ) else : pprefix = "" for x , y in self . rdflib_graph . namespaces ( ) : pprefix += "@prefix %s: <%s> . \n" % ( x , y ) # add final . if missing if text and ( not text . strip ( ) . endswith ( "." ) ) : text += " ." # smart replacements text = text . replace ( " sub " , " rdfs:subClassOf " ) text = text . replace ( " class " , " owl:Class " ) # finally self . rdflib_graph . parse ( data = pprefix + text , format = "turtle" )
add some turtle text
177
4
249,170
def rdf_source ( self , aformat = "turtle" ) : if aformat and aformat not in self . SUPPORTED_FORMATS : return "Sorry. Allowed formats are %s" % str ( self . SUPPORTED_FORMATS ) if aformat == "dot" : return self . __serializedDot ( ) else : # use stardard rdf serializations return self . rdflib_graph . serialize ( format = aformat )
Serialize graph using the format required
102
7
249,171
def omnigraffle ( self ) : temp = self . rdf_source ( "dot" ) try : # try to put in the user/tmp folder from os . path import expanduser home = expanduser ( "~" ) filename = home + "/tmp/turtle_sketch.dot" f = open ( filename , "w" ) except : filename = "turtle_sketch.dot" f = open ( filename , "w" ) f . write ( temp ) f . close ( ) try : os . system ( "open " + filename ) except : os . system ( "start " + filename )
tries to open an export directly in omnigraffle
136
13
249,172
def main ( ) : print ( "Ontospy " + VERSION ) Shell ( ) . _clear_screen ( ) print ( Style . BRIGHT + "** Ontospy Interactive Ontology Browser " + VERSION + " **" + Style . RESET_ALL ) # manager.get_or_create_home_repo() Shell ( ) . cmdloop ( ) raise SystemExit ( 1 )
standalone line script
86
4
249,173
def _print ( self , ms , style = "TIP" ) : styles1 = { 'IMPORTANT' : Style . BRIGHT , 'TIP' : Style . DIM , 'URI' : Style . BRIGHT , 'TEXT' : Fore . GREEN , 'MAGENTA' : Fore . MAGENTA , 'BLUE' : Fore . BLUE , 'GREEN' : Fore . GREEN , 'RED' : Fore . RED , 'DEFAULT' : Style . DIM , } try : print ( styles1 [ style ] + ms + Style . RESET_ALL ) except : print ( styles1 [ 'DEFAULT' ] + ms + Style . RESET_ALL )
abstraction for managing color printing
148
7
249,174
def _printM ( self , messages ) : if len ( messages ) == 2 : print ( Style . BRIGHT + messages [ 0 ] + Style . RESET_ALL + Fore . BLUE + messages [ 1 ] + Style . RESET_ALL ) else : print ( "Not implemented" )
print a list of strings - for the mom used only by stats printout
63
15
249,175
def _printDescription ( self , hrlinetop = True ) : if hrlinetop : self . _print ( "----------------" ) NOTFOUND = "[not found]" if self . currentEntity : obj = self . currentEntity [ 'object' ] label = obj . bestLabel ( ) or NOTFOUND description = obj . bestDescription ( ) or NOTFOUND print ( Style . BRIGHT + "OBJECT TYPE: " + Style . RESET_ALL + Fore . BLACK + uri2niceString ( obj . rdftype ) + Style . RESET_ALL ) print ( Style . BRIGHT + "URI : " + Style . RESET_ALL + Fore . GREEN + "<" + unicode ( obj . uri ) + ">" + Style . RESET_ALL ) print ( Style . BRIGHT + "TITLE : " + Style . RESET_ALL + Fore . BLACK + label + Style . RESET_ALL ) print ( Style . BRIGHT + "DESCRIPTION: " + Style . RESET_ALL + Fore . BLACK + description + Style . RESET_ALL ) else : self . _clear_screen ( ) self . _print ( "Graph: <" + self . current [ 'fullpath' ] + ">" , 'TIP' ) self . _print ( "----------------" , "TIP" ) self . _printStats ( self . current [ 'graph' ] ) for obj in self . current [ 'graph' ] . all_ontologies : print ( Style . BRIGHT + "Ontology URI: " + Style . RESET_ALL + Fore . RED + "<%s>" % str ( obj . uri ) + Style . RESET_ALL ) # self._print("==> Ontology URI: <%s>" % str(obj.uri), "IMPORTANT") # self._print("----------------", "TIP") label = obj . bestLabel ( ) or NOTFOUND description = obj . bestDescription ( ) or NOTFOUND print ( Style . BRIGHT + "Title : " + Style . RESET_ALL + Fore . BLACK + label + Style . RESET_ALL ) print ( Style . BRIGHT + "Description : " + Style . RESET_ALL + Fore . BLACK + description + Style . RESET_ALL ) self . _print ( "----------------" , "TIP" )
generic method to print out a description
506
7
249,176
def _next_ontology ( self ) : currentfile = self . current [ 'file' ] try : idx = self . all_ontologies . index ( currentfile ) return self . all_ontologies [ idx + 1 ] except : return self . all_ontologies [ 0 ]
Dynamically retrieves the next ontology in the list
63
12
249,177
def _load_ontology ( self , filename , preview_mode = False ) : if not preview_mode : fullpath = self . LOCAL_MODELS + filename g = manager . get_pickled_ontology ( filename ) if not g : g = manager . do_pickle_ontology ( filename ) else : fullpath = filename filename = os . path . basename ( os . path . normpath ( fullpath ) ) g = Ontospy ( fullpath , verbose = True ) self . current = { 'file' : filename , 'fullpath' : fullpath , 'graph' : g } self . currentEntity = None self . _print_entity_intro ( g )
Loads an ontology
151
5
249,178
def _select_property ( self , line ) : g = self . current [ 'graph' ] if not line : out = g . all_properties using_pattern = False else : using_pattern = True if line . isdigit ( ) : line = int ( line ) out = g . get_property ( line ) if out : if type ( out ) == type ( [ ] ) : choice = self . _selectFromList ( out , using_pattern , "property" ) if choice : self . currentEntity = { 'name' : choice . locale or choice . uri , 'object' : choice , 'type' : 'property' } else : self . currentEntity = { 'name' : out . locale or out . uri , 'object' : out , 'type' : 'property' } # ..finally: if self . currentEntity : self . _print_entity_intro ( entity = self . currentEntity ) else : print ( "not found" )
try to match a property and load it
210
8
249,179
def _select_concept ( self , line ) : g = self . current [ 'graph' ] if not line : out = g . all_skos_concepts using_pattern = False else : using_pattern = True if line . isdigit ( ) : line = int ( line ) out = g . get_skos ( line ) if out : if type ( out ) == type ( [ ] ) : choice = self . _selectFromList ( out , using_pattern , "concept" ) if choice : self . currentEntity = { 'name' : choice . locale or choice . uri , 'object' : choice , 'type' : 'concept' } else : self . currentEntity = { 'name' : out . locale or out . uri , 'object' : out , 'type' : 'concept' } # ..finally: if self . currentEntity : self . _print_entity_intro ( entity = self . currentEntity ) else : print ( "not found" )
try to match a class and load it
215
8
249,180
def do_visualize ( self , line ) : if not self . current : self . _help_noontology ( ) return line = line . split ( ) try : # from ..viz.builder import action_visualize from . . ontodocs . builder import action_visualize except : self . _print ( "This command requires the ontodocs package: `pip install ontodocs`" ) return import webbrowser url = action_visualize ( args = self . current [ 'file' ] , fromshell = True ) if url : webbrowser . open ( url ) return
Visualize an ontology - ie wrapper for export command
130
11
249,181
def do_import ( self , line ) : line = line . split ( ) if line and line [ 0 ] == "starter-pack" : actions . action_bootstrap ( ) elif line and line [ 0 ] == "uri" : self . _print ( "------------------\nEnter a valid graph URI: (e.g. http://www.w3.org/2009/08/skos-reference/skos.rdf)" ) var = input ( ) if var : if var . startswith ( "http" ) : try : actions . action_import ( var ) except : self . _print ( "OPS... An Unknown Error Occurred - Aborting installation of <%s>" % var ) else : self . _print ( "Not valid. TIP: URIs should start with 'http://'" ) elif line and line [ 0 ] == "file" : self . _print ( "------------------\nEnter a full file path: (e.g. '/Users/mike/Desktop/journals.ttl')" ) var = input ( ) if var : try : actions . action_import ( var ) except : self . _print ( "OPS... An Unknown Error Occurred - Aborting installation of <%s>" % var ) elif line and line [ 0 ] == "repo" : actions . action_webimport ( ) else : self . help_import ( ) self . all_ontologies = manager . get_localontologies ( ) return
Import an ontology
322
4
249,182
def do_file ( self , line ) : opts = self . FILE_OPTS if not self . all_ontologies : self . _help_nofiles ( ) return line = line . split ( ) if not line or line [ 0 ] not in opts : self . help_file ( ) return if line [ 0 ] == "rename" : self . _rename_file ( ) elif line [ 0 ] == "delete" : self . _delete_file ( ) else : return
PErform some file operation
109
6
249,183
def do_serialize ( self , line ) : opts = self . SERIALIZE_OPTS if not self . current : self . _help_noontology ( ) return line = line . split ( ) g = self . current [ 'graph' ] if not line : line = [ 'turtle' ] if line [ 0 ] not in opts : self . help_serialize ( ) return elif self . currentEntity : self . currentEntity [ 'object' ] . printSerialize ( line [ 0 ] ) else : self . _print ( g . rdf_source ( format = line [ 0 ] ) )
Serialize an entity into an RDF flavour
135
9
249,184
def do_back ( self , line ) : if self . currentEntity : self . currentEntity = None self . prompt = _get_prompt ( self . current [ 'file' ] ) else : self . current = None self . prompt = _get_prompt ( )
Go back one step . From entity = > ontology ; from ontology = > ontospy top level .
59
23
249,185
def do_zen ( self , line ) : _quote = random . choice ( QUOTES ) # print(_quote['source']) print ( Style . DIM + unicode ( _quote [ 'text' ] ) ) print ( Style . BRIGHT + unicode ( _quote [ 'source' ] ) + Style . RESET_ALL )
Inspiring quotes for the working ontologist
74
8
249,186
def complete_get ( self , text , line , begidx , endidx ) : options = self . GET_OPTS if not text : completions = options else : completions = [ f for f in options if f . startswith ( text ) ] return completions
completion for find command
60
5
249,187
def complete_info ( self , text , line , begidx , endidx ) : opts = self . INFO_OPTS if not text : completions = opts else : completions = [ f for f in opts if f . startswith ( text ) ] return completions
completion for info command
63
5
249,188
def build_D3treeStandard ( old , MAX_DEPTH , level = 1 , toplayer = None ) : out = [ ] if not old : old = toplayer for x in old : d = { } # print "*" * level, x.label d [ 'qname' ] = x . qname d [ 'name' ] = x . bestLabel ( quotes = False ) . replace ( "_" , " " ) d [ 'objid' ] = x . id if x . children ( ) and level < MAX_DEPTH : d [ 'size' ] = len ( x . children ( ) ) + 5 # fake size d [ 'realsize' ] = len ( x . children ( ) ) # real size d [ 'children' ] = build_D3treeStandard ( x . children ( ) , MAX_DEPTH , level + 1 ) else : d [ 'size' ] = 1 # default size d [ 'realsize' ] = 0 # default size out += [ d ] return out
For d3s examples all we need is a json with name children and size .. eg
221
18
249,189
def build_D3bubbleChart ( old , MAX_DEPTH , level = 1 , toplayer = None ) : out = [ ] if not old : old = toplayer for x in old : d = { } # print "*" * level, x.label d [ 'qname' ] = x . qname d [ 'name' ] = x . bestLabel ( quotes = False ) . replace ( "_" , " " ) d [ 'objid' ] = x . id if x . children ( ) and level < MAX_DEPTH : duplicate_row = { } duplicate_row [ 'qname' ] = x . qname duplicate_row [ 'name' ] = x . bestLabel ( quotes = False ) . replace ( "_" , " " ) duplicate_row [ 'objid' ] = x . id duplicate_row [ 'size' ] = len ( x . children ( ) ) + 5 # fake size duplicate_row [ 'realsize' ] = len ( x . children ( ) ) # real size out += [ duplicate_row ] d [ 'children' ] = build_D3bubbleChart ( x . children ( ) , MAX_DEPTH , level + 1 ) else : d [ 'size' ] = 1 # default size d [ 'realsize' ] = 0 # default size out += [ d ] return out
Similar to standar d3 but nodes with children need to be duplicated otherwise they are not depicted explicitly but just color coded
294
25
249,190
def infer_best_title ( self ) : if self . ontospy_graph . all_ontologies : return self . ontospy_graph . all_ontologies [ 0 ] . uri elif self . ontospy_graph . sources : return self . ontospy_graph . sources [ 0 ] else : return "Untitled"
Selects something usable as a title for an ontospy graph
74
13
249,191
def build ( self , output_path = "" ) : self . output_path = self . checkOutputPath ( output_path ) self . _buildStaticFiles ( ) self . final_url = self . _buildTemplates ( ) printDebug ( "Done." , "comment" ) printDebug ( "=> %s" % ( self . final_url ) , "comment" ) return self . final_url
method that should be inherited by all vis classes
88
9
249,192
def _buildTemplates ( self ) : # in this case we only have one contents = self . _renderTemplate ( self . template_name , extraContext = None ) # the main url used for opening viz f = self . main_file_name main_url = self . _save2File ( contents , f , self . output_path ) return main_url
do all the things necessary to build the viz should be adapted to work for single - file viz or multi - files etc .
78
25
249,193
def _build_basic_context ( self ) : # printDebug(str(self.ontospy_graph.toplayer_classes)) topclasses = self . ontospy_graph . toplayer_classes [ : ] if len ( topclasses ) < 3 : # massage the toplayer! for topclass in self . ontospy_graph . toplayer_classes : for child in topclass . children ( ) : if child not in topclasses : topclasses . append ( child ) if not self . static_url : self . static_url = "static/" # default context_data = { "STATIC_URL" : self . static_url , "ontodocs_version" : VERSION , "ontospy_graph" : self . ontospy_graph , "topclasses" : topclasses , "docs_title" : self . title , "namespaces" : self . ontospy_graph . namespaces , "stats" : self . ontospy_graph . stats ( ) , "sources" : self . ontospy_graph . sources , "ontologies" : self . ontospy_graph . all_ontologies , "classes" : self . ontospy_graph . all_classes , "properties" : self . ontospy_graph . all_properties , "objproperties" : self . ontospy_graph . all_properties_object , "dataproperties" : self . ontospy_graph . all_properties_datatype , "annotationproperties" : self . ontospy_graph . all_properties_annotation , "skosConcepts" : self . ontospy_graph . all_skos_concepts , "instances" : [ ] } return context_data
Return a standard dict used in django as a template context
383
12
249,194
def checkOutputPath ( self , output_path ) : if not output_path : # output_path = self.output_path_DEFAULT output_path = os . path . join ( self . output_path_DEFAULT , slugify ( unicode ( self . title ) ) ) if os . path . exists ( output_path ) : shutil . rmtree ( output_path ) os . makedirs ( output_path ) return output_path
Create or clean up output path
99
6
249,195
def highlight_code ( self , ontospy_entity ) : try : pygments_code = highlight ( ontospy_entity . rdf_source ( ) , TurtleLexer ( ) , HtmlFormatter ( ) ) pygments_code_css = HtmlFormatter ( ) . get_style_defs ( '.highlight' ) return { "pygments_code" : pygments_code , "pygments_code_css" : pygments_code_css } except Exception as e : printDebug ( "Error: Pygmentize Failed" , "red" ) return { }
produce an html version of Turtle code with syntax highlighted using Pygments CSS
129
15
249,196
def query ( self , q , format = "" , convert = True ) : lines = [ "PREFIX %s: <%s>" % ( k , r ) for k , r in self . prefixes . iteritems ( ) ] lines . extend ( q . split ( "\n" ) ) query = "\n" . join ( lines ) if self . verbose : print ( query , "\n\n" ) return self . __doQuery ( query , format , convert )
Generic SELECT query structure . q is the main body of the query .
103
14
249,197
def describe ( self , uri , format = "" , convert = True ) : lines = [ "PREFIX %s: <%s>" % ( k , r ) for k , r in self . prefixes . iteritems ( ) ] if uri . startswith ( "http://" ) : lines . extend ( [ "DESCRIBE <%s>" % uri ] ) else : # it's a shortened uri lines . extend ( [ "DESCRIBE %s" % uri ] ) query = "\n" . join ( lines ) if self . verbose : print ( query , "\n\n" ) return self . __doQuery ( query , format , convert )
A simple DESCRIBE query with no where arguments . uri is the resource you want to describe .
151
22
249,198
def __doQuery ( self , query , format , convert ) : self . __getFormat ( format ) self . sparql . setQuery ( query ) if convert : results = self . sparql . query ( ) . convert ( ) else : results = self . sparql . query ( ) return results
Inner method that does the actual query
63
8
249,199
def get_default_preds ( ) : g = ontospy . Ontospy ( rdfsschema , text = True , verbose = False , hide_base_schemas = False ) classes = [ ( x . qname , x . bestDescription ( ) ) for x in g . all_classes ] properties = [ ( x . qname , x . bestDescription ( ) ) for x in g . all_properties ] commands = [ ( 'exit' , 'exits the terminal' ) , ( 'show' , 'show current buffer' ) ] return rdfschema + owlschema + classes + properties + commands
dynamically build autocomplete options based on an external file
138
13