idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
46,500
def compute_service_descriptor ( price , consume_endpoint , service_endpoint , timeout ) : return ( ServiceTypes . CLOUD_COMPUTE , { 'price' : price , 'consumeEndpoint' : consume_endpoint , 'serviceEndpoint' : service_endpoint , 'timeout' : timeout } )
Compute service descriptor .
46,501
def build_services ( did , service_descriptors ) : services = [ ] sa_def_key = ServiceAgreement . SERVICE_DEFINITION_ID for i , service_desc in enumerate ( service_descriptors ) : service = ServiceFactory . build_service ( service_desc , did ) service . update_value ( sa_def_key , str ( i ) ) services . append ( servic...
Build a list of services .
46,502
def build_service ( service_descriptor , did ) : assert isinstance ( service_descriptor , tuple ) and len ( service_descriptor ) == 2 , 'Unknown service descriptor format.' service_type , kwargs = service_descriptor if service_type == ServiceTypes . METADATA : return ServiceFactory . build_metadata_service ( did , kwar...
Build a service .
46,503
def build_metadata_service ( did , metadata , service_endpoint ) : return Service ( service_endpoint , ServiceTypes . METADATA , values = { 'metadata' : metadata } , did = did )
Build a metadata service .
46,504
def build_access_service ( did , price , consume_endpoint , service_endpoint , timeout , template_id ) : param_map = { '_documentId' : did_to_id ( did ) , '_amount' : price , '_rewardAddress' : Keeper . get_instance ( ) . escrow_reward_condition . address , } sla_template_path = get_sla_template_path ( ) sla_template =...
Build the access service .
46,505
def record_service_agreement ( storage_path , service_agreement_id , did , service_definition_id , price , files , start_time , status = 'pending' ) : conn = sqlite3 . connect ( storage_path ) try : cursor = conn . cursor ( ) cursor . execute ( ) cursor . execute ( 'INSERT OR REPLACE INTO service_agreements VALUES (?,?...
Records the given pending service agreement .
46,506
def update_service_agreement_status ( storage_path , service_agreement_id , status = 'pending' ) : conn = sqlite3 . connect ( storage_path ) try : cursor = conn . cursor ( ) cursor . execute ( 'UPDATE service_agreements SET status=? WHERE id=?' , ( status , service_agreement_id ) , ) conn . commit ( ) finally : conn . ...
Update the service agreement status .
46,507
def setup_logging ( default_path = 'logging.yaml' , default_level = logging . INFO , env_key = 'LOG_CFG' ) : path = default_path value = os . getenv ( env_key , None ) if value : path = value if os . path . exists ( path ) : with open ( path , 'rt' ) as file : try : config = yaml . safe_load ( file . read ( ) ) logging...
Logging setup .
46,508
def encrypt ( self , document_id , content , account ) : return self . _secret_store ( account ) . encrypt_document ( document_id , content )
Encrypt string data using the DID as an secret store id if secret store is enabled then return the result from secret store encryption
46,509
def get_resolve_url ( self , did_bytes ) : data = self . _did_registry . get_registered_attribute ( did_bytes ) if not ( data and data . get ( 'value' ) ) : return None return data [ 'value' ]
Return a did value and value type from the block chain event record using did .
46,510
def get_instance ( cls , dependencies = None ) : assert cls is not ContractBase , 'ContractBase is not meant to be used directly.' assert cls . CONTRACT_NAME , 'CONTRACT_NAME must be set to a valid keeper contract name.' return cls ( cls . CONTRACT_NAME , dependencies )
Return an instance for a contract name .
46,511
def get_tx_receipt ( tx_hash ) : try : Web3Provider . get_web3 ( ) . eth . waitForTransactionReceipt ( tx_hash , timeout = 20 ) except Timeout : logger . info ( 'Waiting for transaction receipt timed out.' ) return return Web3Provider . get_web3 ( ) . eth . getTransactionReceipt ( tx_hash )
Get the receipt of a tx .
46,512
def subscribe_to_event ( self , event_name , timeout , event_filter , callback = False , timeout_callback = None , args = None , wait = False ) : from squid_py . keeper . event_listener import EventListener return EventListener ( self . CONTRACT_NAME , event_name , args , filters = event_filter ) . listen_once ( callba...
Create a listener for the event choose .
46,513
def refund_reward ( event , agreement_id , did , service_agreement , price , consumer_account , publisher_address , condition_ids ) : logger . debug ( f"trigger refund after event {event}." ) access_id , lock_id = condition_ids [ : 2 ] name_to_parameter = { param . name : param for param in service_agreement . conditio...
Refund the reward to the publisher address .
46,514
def consume_asset ( event , agreement_id , did , service_agreement , consumer_account , consume_callback ) : logger . debug ( f"consuming asset after event {event}." ) if consume_callback : config = ConfigProvider . get_config ( ) secret_store = SecretStoreProvider . get_secret_store ( config . secret_store_url , confi...
Consumption of an asset after get the event call .
46,515
def verify_contracts ( ) : artifacts_path = ConfigProvider . get_config ( ) . keeper_path logger . info ( f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}' ) if os . environ . get ( 'KEEPER_NETWORK_NAME' ) : logger . warning ( f'The `KEEPER_NETWORK_NAME` env var is set to ' f'{os.environ.get("KEEPER_NE...
Verify that the contracts are deployed correctly in the network .
46,516
def create_access_service ( price , service_endpoint , consume_endpoint , timeout = None ) : timeout = timeout or 3600 service = ServiceDescriptor . access_service_descriptor ( price , service_endpoint , consume_endpoint , timeout , '' ) return service
Publish an asset with an Access service according to the supplied attributes .
46,517
def lock_reward ( self , agreement_id , amount , account ) : return self . _keeper . lock_reward_condition . fulfill ( agreement_id , self . _keeper . escrow_reward_condition . address , amount , account )
Lock reward condition .
46,518
def grant_access ( self , agreement_id , did , grantee_address , account ) : return self . _keeper . access_secret_store_condition . fulfill ( agreement_id , add_0x_prefix ( did_to_id ( did ) ) , grantee_address , account )
Grant access condition .
46,519
def release_reward ( self , agreement_id , amount , account ) : agreement_values = self . _keeper . agreement_manager . get_agreement ( agreement_id ) consumer , provider = self . _keeper . escrow_access_secretstore_template . get_agreement_data ( agreement_id ) access_id , lock_id = agreement_values . condition_ids [ ...
Release reward condition .
46,520
def refund_reward ( self , agreement_id , amount , account ) : return self . release_reward ( agreement_id , amount , account )
Refund reaward condition .
46,521
def from_json_file ( cls , path ) : with open ( path ) as jsf : template_json = json . load ( jsf ) return cls ( template_json = template_json )
Return a template from a json allocated in a path .
46,522
def parse_template_json ( self , template_json ) : assert template_json [ 'type' ] == self . DOCUMENT_TYPE , '' self . template_id = template_json [ 'templateId' ] self . name = template_json . get ( 'name' ) self . creator = template_json . get ( 'creator' ) self . template = template_json [ 'serviceAgreementTemplate'...
Parse a template from a json .
46,523
def as_dictionary ( self ) : template = { 'contractName' : self . contract_name , 'events' : [ e . as_dictionary ( ) for e in self . agreement_events ] , 'fulfillmentOrder' : self . fulfillment_order , 'conditionDependency' : self . condition_dependency , 'conditions' : [ cond . as_dictionary ( ) for cond in self . con...
Return the service agreement template as a dictionary .
46,524
def request ( self , account , amount ) : return self . _keeper . dispenser . request_tokens ( amount , account )
Request a number of tokens to be minted and transfered to account
46,525
def transfer ( self , receiver_address , amount , sender_account ) : self . _keeper . token . token_approve ( receiver_address , amount , sender_account ) self . _keeper . token . transfer ( receiver_address , amount , sender_account )
Transfer a number of tokens from sender_account to receiver_address
46,526
def list_assets ( self ) : response = self . requests_session . get ( self . _base_url ) . content if not response : return { } try : asset_list = json . loads ( response ) except TypeError : asset_list = None except ValueError : raise ValueError ( response . decode ( 'UTF-8' ) ) if not asset_list : return [ ] if 'ids'...
List all the assets registered in the aquarius instance .
46,527
def get_asset_ddo ( self , did ) : response = self . requests_session . get ( f'{self.url}/{did}' ) . content if not response : return { } try : parsed_response = json . loads ( response ) except TypeError : parsed_response = None except ValueError : raise ValueError ( response . decode ( 'UTF-8' ) ) if parsed_response...
Retrieve asset ddo for a given did .
46,528
def get_asset_metadata ( self , did ) : response = self . requests_session . get ( f'{self._base_url}/metadata/{did}' ) . content if not response : return { } try : parsed_response = json . loads ( response ) except TypeError : parsed_response = None except ValueError : raise ValueError ( response . decode ( 'UTF-8' ) ...
Retrieve asset metadata for a given did .
46,529
def list_assets_ddo ( self ) : return json . loads ( self . requests_session . get ( self . url ) . content )
List all the ddos registered in the aquarius instance .
46,530
def publish_asset_ddo ( self , ddo ) : try : asset_did = ddo . did response = self . requests_session . post ( self . url , data = ddo . as_text ( ) , headers = self . _headers ) except AttributeError : raise AttributeError ( 'DDO invalid. Review that all the required parameters are filled.' ) if response . status_code...
Register asset ddo in aquarius .
46,531
def update_asset_ddo ( self , did , ddo ) : response = self . requests_session . put ( f'{self.url}/{did}' , data = ddo . as_text ( ) , headers = self . _headers ) if response . status_code == 200 or response . status_code == 201 : return json . loads ( response . content ) else : raise Exception ( f'Unable to update D...
Update the ddo of a did already registered .
46,532
def text_search ( self , text , sort = None , offset = 100 , page = 1 ) : assert page >= 1 , f'Invalid page value {page}. Required page >= 1.' payload = { "text" : text , "sort" : sort , "offset" : offset , "page" : page } response = self . requests_session . get ( f'{self.url}/query' , params = payload , headers = sel...
Search in aquarius using text query .
46,533
def query_search ( self , search_query , sort = None , offset = 100 , page = 1 ) : assert page >= 1 , f'Invalid page value {page}. Required page >= 1.' search_query [ 'sort' ] = sort search_query [ 'offset' ] = offset search_query [ 'page' ] = page response = self . requests_session . post ( f'{self.url}/query' , data ...
Search using a query .
46,534
def retire_asset_ddo ( self , did ) : response = self . requests_session . delete ( f'{self.url}/{did}' , headers = self . _headers ) if response . status_code == 200 : logging . debug ( f'Removed asset DID: {did} from metadata store' ) return response raise AquariusGenericError ( f'Unable to remove DID: {response}' )
Retire asset ddo of Aquarius .
46,535
def validate_metadata ( self , metadata ) : response = self . requests_session . post ( f'{self.url}/validate' , data = json . dumps ( metadata ) , headers = self . _headers ) if response . content == b'true\n' : return True else : logger . info ( self . _parse_search_response ( response . content ) ) return False
Validate that the metadata of your ddo is valid .
46,536
def get_sla_template_path ( service_type = ServiceTypes . ASSET_ACCESS ) : if service_type == ServiceTypes . ASSET_ACCESS : name = 'access_sla_template.json' elif service_type == ServiceTypes . CLOUD_COMPUTE : name = 'compute_sla_template.json' elif service_type == ServiceTypes . FITCHAIN_COMPUTE : name = 'fitchain_sla...
Get the template for a ServiceType .
46,537
def balance ( self , account ) : return Balance ( self . _keeper . get_ether_balance ( account . address ) , self . _keeper . token . get_token_balance ( account . address ) )
Return the balance a tuple with the eth and ocn balance .
46,538
def process_agreement_events_consumer ( publisher_address , agreement_id , did , service_agreement , price , consumer_account , condition_ids , consume_callback ) : conditions_dict = service_agreement . condition_by_name events_manager = EventsManager . get_instance ( Keeper . get_instance ( ) ) events_manager . watch_...
Process the agreement events during the register of the service agreement for the consumer side .
46,539
def process_agreement_events_publisher ( publisher_account , agreement_id , did , service_agreement , price , consumer_address , condition_ids ) : conditions_dict = service_agreement . condition_by_name events_manager = EventsManager . get_instance ( Keeper . get_instance ( ) ) events_manager . watch_lock_reward_event ...
Process the agreement events during the register of the service agreement for the publisher side
46,540
def execute_pending_service_agreements ( storage_path , account , actor_type , did_resolver_fn ) : keeper = Keeper . get_instance ( ) for ( agreement_id , did , _ , price , files , start_time , _ ) in get_service_agreements ( storage_path ) : ddo = did_resolver_fn ( did ) for service in ddo . services : if service . ty...
Iterates over pending service agreements recorded in the local storage fetches their service definitions and subscribes to service agreement events .
46,541
def generate_multi_value_hash ( types , values ) : assert len ( types ) == len ( values ) return Web3Provider . get_web3 ( ) . soliditySha3 ( types , values )
Return the hash of the given list of values . This is equivalent to packing and hashing values in a solidity smart contract hence the use of soliditySha3 .
46,542
def process_tx_receipt ( tx_hash , event , event_name ) : web3 = Web3Provider . get_web3 ( ) try : web3 . eth . waitForTransactionReceipt ( tx_hash , timeout = 20 ) except Timeout : logger . info ( 'Waiting for transaction receipt timed out. Cannot verify receipt and event.' ) return receipt = web3 . eth . getTransacti...
Wait until the tx receipt is processed .
46,543
def get_condition ( self , condition_id ) : condition = self . contract_concise . getCondition ( condition_id ) if condition and len ( condition ) == 7 : return ConditionValues ( * condition ) return None
Retrieve the condition for a condition_id .
46,544
def fulfill ( self , agreement_id , message , account_address , signature , from_account ) : return self . _fulfill ( agreement_id , message , account_address , signature , transact = { 'from' : from_account . address , 'passphrase' : from_account . password } )
Fulfill the sign conditon .
46,545
def create ( self , did , service_definition_id , agreement_id , service_agreement_signature , consumer_address , account ) : assert consumer_address and Web3Provider . get_web3 ( ) . isChecksumAddress ( consumer_address ) , f'Invalid consumer address {consumer_address}' assert account . address in self . _keeper . acc...
Execute the service agreement on - chain using keeper s ServiceAgreement contract .
46,546
def is_access_granted ( self , agreement_id , did , consumer_address ) : agreement_consumer = self . _keeper . escrow_access_secretstore_template . get_agreement_consumer ( agreement_id ) if agreement_consumer != consumer_address : logger . warning ( f'Invalid consumer address {consumer_address} and/or ' f'service agre...
Check permission for the agreement .
46,547
def _verify_service_agreement_signature ( self , did , agreement_id , service_definition_id , consumer_address , signature , ddo = None ) : if not ddo : ddo = self . _asset_resolver . resolve ( did ) service_agreement = ServiceAgreement . from_ddo ( service_definition_id , ddo ) agreement_hash = service_agreement . get...
Verify service agreement signature .
46,548
def status ( self , agreement_id ) : condition_ids = self . _keeper . agreement_manager . get_agreement ( agreement_id ) . condition_ids result = { "agreementId" : agreement_id } conditions = dict ( ) for i in condition_ids : conditions [ self . _keeper . get_condition_name_by_address ( self . _keeper . condition_manag...
Get the status of a service agreement .
46,549
def create_agreement ( self , agreement_id , did , condition_ids , time_locks , time_outs , consumer_address , account ) : logger . info ( f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.' ) tx_hash = self . send_transaction ( 'createAgreement' , ( agreement_id , did , condition_ids , ti...
Create the service agreement . Return true if it is created successfully .
46,550
def subscribe_agreement_created ( self , agreement_id , timeout , callback , args , wait = False ) : logger . info ( f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.' ) return self . subscribe_to_event ( self . AGREEMENT_CREATED_EVENT , timeout , { '_agreementId' : Web3Provider . get...
Subscribe to an agreement created .
46,551
def generate_id ( self , agreement_id , types , values ) : values_hash = utils . generate_multi_value_hash ( types , values ) return utils . generate_multi_value_hash ( [ 'bytes32' , 'address' , 'bytes32' ] , [ agreement_id , self . address , values_hash ] )
Generate id for the condition .
46,552
def _fulfill ( self , * args , ** kwargs ) : tx_hash = self . send_transaction ( 'fulfill' , args , ** kwargs ) receipt = self . get_tx_receipt ( tx_hash ) return receipt . status == 1
Fulfill the condition .
46,553
def subscribe_condition_fulfilled ( self , agreement_id , timeout , callback , args , timeout_callback = None , wait = False ) : logger . info ( f'Subscribing {self.FULFILLED_EVENT} event with agreement id {agreement_id}.' ) return self . subscribe_to_event ( self . FULFILLED_EVENT , timeout , { '_agreementId' : Web3Pr...
Subscribe to the condition fullfilled event .
46,554
def transact_with_contract_function ( address , web3 , function_name = None , transaction = None , contract_abi = None , fn_abi = None , * args , ** kwargs ) : transact_transaction = prepare_transaction ( address , web3 , fn_identifier = function_name , contract_abi = contract_abi , transaction = transaction , fn_abi =...
Helper function for interacting with a contract function by sending a transaction . This is copied from web3 transact_with_contract_function so we can use personal_sendTransaction when possible .
46,555
def transact ( self , transaction = None ) : if transaction is None : transact_transaction = { } else : transact_transaction = dict ( ** transaction ) if 'data' in transact_transaction : raise ValueError ( "Cannot set data in transact transaction" ) cf = self . _contract_function if cf . address is not None : transact_...
Customize calling smart contract transaction functions to use personal_sendTransaction instead of eth_sendTransaction and to estimate gas limit . This function is largely copied from web3 ContractFunction with important addition .
46,556
def fulfill ( self , agreement_id , amount , receiver_address , sender_address , lock_condition_id , release_condition_id , account ) : return self . _fulfill ( agreement_id , amount , receiver_address , sender_address , lock_condition_id , release_condition_id , transact = { 'from' : account . address , 'passphrase' :...
Fulfill the escrow reward condition .
46,557
def hash_values ( self , amount , receiver_address , sender_address , lock_condition_id , release_condition_id ) : return self . _hash_values ( amount , receiver_address , sender_address , lock_condition_id , release_condition_id )
Hash the values of the escrow reward condition .
46,558
def as_dictionary ( self ) : return { "name" : self . name , "type" : self . type , "value" : remove_0x_prefix ( self . value ) if self . type == 'bytes32' else self . value }
Return the parameter as a dictionary .
46,559
def init_from_condition_json ( self , condition_json ) : self . name = condition_json [ 'name' ] self . timelock = condition_json [ 'timelock' ] self . timeout = condition_json [ 'timeout' ] self . contract_name = condition_json [ 'contractName' ] self . function_name = condition_json [ 'functionName' ] self . paramete...
Init the condition values from a condition json .
46,560
def as_dictionary ( self ) : condition_dict = { "name" : self . name , "timelock" : self . timelock , "timeout" : self . timeout , "contractName" : self . contract_name , "functionName" : self . function_name , "events" : [ e . as_dictionary ( ) for e in self . events ] , "parameters" : [ p . as_dictionary ( ) for p in...
Return the condition as a dictionary .
46,561
def update_value ( self , name , value ) : if name not in { 'id' , self . SERVICE_ENDPOINT , self . CONSUME_ENDPOINT , 'type' } : self . _values [ name ] = value
Update value in the array of values .
46,562
def as_text ( self , is_pretty = False ) : values = { 'type' : self . _type , self . SERVICE_ENDPOINT : self . _service_endpoint , } if self . _consume_endpoint is not None : values [ self . CONSUME_ENDPOINT ] = self . _consume_endpoint if self . _values : for name , value in self . _values . items ( ) : values [ name ...
Return the service as a JSON string .
46,563
def as_dictionary ( self ) : values = { 'type' : self . _type , self . SERVICE_ENDPOINT : self . _service_endpoint , } if self . _consume_endpoint is not None : values [ self . CONSUME_ENDPOINT ] = self . _consume_endpoint if self . _values : for name , value in self . _values . items ( ) : if isinstance ( value , obje...
Return the service as a python dictionary .
46,564
def from_json ( cls , service_dict ) : sd = service_dict . copy ( ) service_endpoint = sd . get ( cls . SERVICE_ENDPOINT ) if not service_endpoint : logger . error ( 'Service definition in DDO document is missing the "serviceEndpoint" key/value.' ) raise IndexError _type = sd . get ( 'type' ) if not _type : logger . er...
Create a service object from a JSON string .
46,565
def fulfill ( self , agreement_id , document_id , grantee_address , account ) : return self . _fulfill ( agreement_id , document_id , grantee_address , transact = { 'from' : account . address , 'passphrase' : account . password } )
Fulfill the access secret store condition .
46,566
def get_purchased_assets_by_address ( self , address , from_block = 0 , to_block = 'latest' ) : block_filter = EventFilter ( ConditionBase . FULFILLED_EVENT , getattr ( self . events , ConditionBase . FULFILLED_EVENT ) , from_block = from_block , to_block = to_block , argument_filters = { '_grantee' : address } ) log_i...
Get the list of the assets dids consumed for an address .
46,567
def get_web3 ( ) : if Web3Provider . _web3 is None : config = ConfigProvider . get_config ( ) provider = ( config . web3_provider if config . web3_provider else CustomHTTPProvider ( config . keeper_url ) ) Web3Provider . _web3 = Web3 ( provider ) Web3Provider . _web3 . eth = getattr ( Web3Provider . _web3 , 'eth' ) Web...
Return the web3 instance to interact with the ethereum client .
46,568
def _get_type ( points , soma_class ) : assert soma_class in ( SOMA_CONTOUR , SOMA_CYLINDER ) npoints = len ( points ) if soma_class == SOMA_CONTOUR : return { 0 : None , 1 : SomaSinglePoint , 2 : None } . get ( npoints , SomaSimpleContour ) if ( npoints == 3 and points [ 0 ] [ COLS . P ] == - 1 and points [ 1 ] [ COLS...
get the type of the soma
46,569
def make_soma ( points , soma_check = None , soma_class = SOMA_CONTOUR ) : if soma_check : soma_check ( points ) stype = _get_type ( points , soma_class ) if stype is None : raise SomaError ( 'Invalid soma points' ) return stype ( points )
Make a soma object from a set of points
46,570
def center ( self ) : points = np . array ( self . _points ) return np . mean ( points [ : , COLS . XYZ ] , axis = 0 )
Obtain the center from the average of all points
46,571
def section_tortuosity ( section ) : pts = section . points return 1 if len ( pts ) < 2 else mm . section_length ( pts ) / mm . point_dist ( pts [ - 1 ] , pts [ 0 ] )
Tortuosity of a section
46,572
def section_end_distance ( section ) : pts = section . points return 0 if len ( pts ) < 2 else mm . point_dist ( pts [ - 1 ] , pts [ 0 ] )
End to end distance of a section
46,573
def strahler_order ( section ) : if section . children : child_orders = [ strahler_order ( child ) for child in section . children ] max_so_children = max ( child_orders ) it = iter ( co == max_so_children for co in child_orders ) any ( it ) if any ( it ) : return max_so_children + 1 return max_so_children return 1
Branching order of a tree section
46,574
def figure_naming ( pretitle = '' , posttitle = '' , prefile = '' , postfile = '' ) : if pretitle : pretitle = "%s -- " % pretitle if posttitle : posttitle = " -- %s" % posttitle if prefile : prefile = "%s_" % prefile if postfile : postfile = "_%s" % postfile return pretitle , posttitle , prefile , postfile
Helper function to define the strings that handle pre - post conventions for viewing - plotting title and saving options .
46,575
def get_figure ( new_fig = True , subplot = '111' , params = None ) : _get_plt ( ) if new_fig : fig = plt . figure ( ) else : fig = plt . gcf ( ) params = dict_if_none ( params ) if isinstance ( subplot , ( tuple , list ) ) : ax = fig . add_subplot ( * subplot , ** params ) else : ax = fig . add_subplot ( subplot , ** ...
Function to be used for viewing - plotting to initialize the matplotlib figure - axes .
46,576
def save_plot ( fig , prefile = '' , postfile = '' , output_path = './' , output_name = 'Figure' , output_format = 'png' , dpi = 300 , transparent = False , ** _ ) : if not os . path . exists ( output_path ) : os . makedirs ( output_path ) output = os . path . join ( output_path , prefile + output_name + postfile + "."...
Generates a figure file in the selected directory .
46,577
def plot_style ( fig , ax , pretitle = '' , title = 'Figure' , posttitle = '' , title_fontsize = 14 , title_arg = None , label_fontsize = 14 , xlabel = None , xlabel_arg = None , ylabel = None , ylabel_arg = None , zlabel = None , zlabel_arg = None , tick_fontsize = 12 , xticks = None , xticks_args = None , yticks = No...
Set the basic options of a matplotlib figure to be used by viewing - plotting functions
46,578
def plot_title ( ax , pretitle = '' , title = 'Figure' , posttitle = '' , title_fontsize = 14 , title_arg = None ) : current_title = ax . get_title ( ) if not current_title : current_title = pretitle + title + posttitle title_arg = dict_if_none ( title_arg ) ax . set_title ( current_title , fontsize = title_fontsize , ...
Set title options of a matplotlib plot
46,579
def plot_labels ( ax , label_fontsize = 14 , xlabel = None , xlabel_arg = None , ylabel = None , ylabel_arg = None , zlabel = None , zlabel_arg = None ) : xlabel = xlabel if xlabel is not None else ax . get_xlabel ( ) or 'X' ylabel = ylabel if ylabel is not None else ax . get_ylabel ( ) or 'Y' xlabel_arg = dict_if_none...
Sets the labels options of a matplotlib plot
46,580
def plot_ticks ( ax , tick_fontsize = 12 , xticks = None , xticks_args = None , yticks = None , yticks_args = None , zticks = None , zticks_args = None ) : if xticks is not None : ax . set_xticks ( xticks ) xticks_args = dict_if_none ( xticks_args ) ax . xaxis . set_tick_params ( labelsize = tick_fontsize , ** xticks_a...
Function that defines the labels options of a matplotlib plot .
46,581
def update_plot_limits ( ax , white_space ) : if hasattr ( ax , 'zz_dataLim' ) : bounds = ax . xy_dataLim . bounds ax . set_xlim ( bounds [ 0 ] - white_space , bounds [ 0 ] + bounds [ 2 ] + white_space ) ax . set_ylim ( bounds [ 1 ] - white_space , bounds [ 1 ] + bounds [ 3 ] + white_space ) bounds = ax . zz_dataLim . ...
Sets the limit options of a matplotlib plot .
46,582
def plot_legend ( ax , no_legend = True , legend_arg = None ) : legend_arg = dict_if_none ( legend_arg ) if not no_legend : ax . legend ( ** legend_arg )
Function that defines the legend options of a matplotlib plot .
46,583
def generate_cylindrical_points ( start , end , start_radius , end_radius , linspace_count = _LINSPACE_COUNT ) : v = end - start length = norm ( v ) v = v / length n1 , n2 = _get_normals ( v ) l , theta = np . meshgrid ( np . linspace ( 0 , length , linspace_count ) , np . linspace ( 0 , 2 * np . pi , linspace_count ) ...
Generate a 3d mesh of a cylinder with start and end points and varying radius
46,584
def plot_cylinder ( ax , start , end , start_radius , end_radius , color = 'black' , alpha = 1. , linspace_count = _LINSPACE_COUNT ) : assert not np . all ( start == end ) , 'Cylinder must have length' x , y , z = generate_cylindrical_points ( start , end , start_radius , end_radius , linspace_count = linspace_count ) ...
plot a 3d cylinder
46,585
def plot_sphere ( ax , center , radius , color = 'black' , alpha = 1. , linspace_count = _LINSPACE_COUNT ) : u = np . linspace ( 0 , 2 * np . pi , linspace_count ) v = np . linspace ( 0 , np . pi , linspace_count ) sin_v = np . sin ( v ) x = center [ 0 ] + radius * np . outer ( np . cos ( u ) , sin_v ) y = center [ 1 ]...
Plots a 3d sphere given the center and the radius .
46,586
def has_sequential_ids ( data_wrapper ) : db = data_wrapper . data_block ids = db [ : , COLS . ID ] steps = ids [ np . where ( np . diff ( ids ) != 1 ) [ 0 ] + 1 ] . astype ( int ) return CheckResult ( len ( steps ) == 0 , steps )
Check that IDs are increasing and consecutive
46,587
def no_missing_parents ( data_wrapper ) : db = data_wrapper . data_block ids = np . setdiff1d ( db [ : , COLS . P ] , db [ : , COLS . ID ] ) [ 1 : ] return CheckResult ( len ( ids ) == 0 , ids . astype ( np . int ) + 1 )
Check that all points have existing parents Point s parent ID must exist and parent must be declared before child .
46,588
def is_single_tree ( data_wrapper ) : db = data_wrapper . data_block bad_ids = db [ db [ : , COLS . P ] == - 1 ] [ 1 : , COLS . ID ] return CheckResult ( len ( bad_ids ) == 0 , bad_ids . tolist ( ) )
Check that data forms a single tree
46,589
def has_soma_points ( data_wrapper ) : db = data_wrapper . data_block return CheckResult ( POINT_TYPE . SOMA in db [ : , COLS . TYPE ] , None )
Checks if the TYPE column of raw data block has an element of type soma
46,590
def has_all_finite_radius_neurites ( data_wrapper , threshold = 0.0 ) : db = data_wrapper . data_block neurite_ids = np . in1d ( db [ : , COLS . TYPE ] , POINT_TYPE . NEURITES ) zero_radius_ids = db [ : , COLS . R ] <= threshold bad_pts = np . array ( db [ neurite_ids & zero_radius_ids ] [ : , COLS . ID ] , dtype = int...
Check that all points with neurite type have a finite radius
46,591
def has_valid_soma ( data_wrapper ) : try : make_soma ( data_wrapper . soma_points ( ) ) return CheckResult ( True ) except SomaError : return CheckResult ( False )
Check if a data block has a valid soma
46,592
def _pelita_member_filter ( parent_name , item_names ) : filtered_names = [ ] if parent_name not in sys . modules : return item_names module = sys . modules [ parent_name ] for item_name in item_names : item = getattr ( module , item_name , None ) location = getattr ( item , '__module__' , None ) if location is None or...
Filter a list of autodoc items for which to generate documentation .
46,593
def has_axon ( neuron , treefun = _read_neurite_type ) : return CheckResult ( NeuriteType . axon in ( treefun ( n ) for n in neuron . neurites ) )
Check if a neuron has an axon
46,594
def has_apical_dendrite ( neuron , min_number = 1 , treefun = _read_neurite_type ) : types = [ treefun ( n ) for n in neuron . neurites ] return CheckResult ( types . count ( NeuriteType . apical_dendrite ) >= min_number )
Check if a neuron has apical dendrites
46,595
def has_basal_dendrite ( neuron , min_number = 1 , treefun = _read_neurite_type ) : types = [ treefun ( n ) for n in neuron . neurites ] return CheckResult ( types . count ( NeuriteType . basal_dendrite ) >= min_number )
Check if a neuron has basal dendrites
46,596
def has_no_flat_neurites ( neuron , tol = 0.1 , method = 'ratio' ) : return CheckResult ( len ( get_flat_neurites ( neuron , tol , method ) ) == 0 )
Check that a neuron has no flat neurites
46,597
def has_all_nonzero_segment_lengths ( neuron , threshold = 0.0 ) : bad_ids = [ ] for sec in _nf . iter_sections ( neuron ) : p = sec . points for i , s in enumerate ( zip ( p [ : - 1 ] , p [ 1 : ] ) ) : if segment_length ( s ) <= threshold : bad_ids . append ( ( sec . id , i ) ) return CheckResult ( len ( bad_ids ) == ...
Check presence of neuron segments with length not above threshold
46,598
def has_all_nonzero_section_lengths ( neuron , threshold = 0.0 ) : bad_ids = [ s . id for s in _nf . iter_sections ( neuron . neurites ) if section_length ( s . points ) <= threshold ] return CheckResult ( len ( bad_ids ) == 0 , bad_ids )
Check presence of neuron sections with length not above threshold
46,599
def has_all_nonzero_neurite_radii ( neuron , threshold = 0.0 ) : bad_ids = [ ] seen_ids = set ( ) for s in _nf . iter_sections ( neuron ) : for i , p in enumerate ( s . points ) : info = ( s . id , i ) if p [ COLS . R ] <= threshold and info not in seen_ids : seen_ids . add ( info ) bad_ids . append ( info ) return Che...
Check presence of neurite points with radius not above threshold