repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
oceanprotocol/squid-py
squid_py/keeper/conditions/condition_base.py
ConditionBase.generate_id
def generate_id(self, agreement_id, types, values): """ Generate id for the condition. :param agreement_id: id of the agreement, hex str :param types: list of types :param values: list of values :return: id, str """ values_hash = utils.generate_multi_value_hash(types, values) return utils.generate_multi_value_hash( ['bytes32', 'address', 'bytes32'], [agreement_id, self.address, values_hash] )
python
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] )
[ "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. :param agreement_id: id of the agreement, hex str :param types: list of types :param values: list of values :return: id, str
[ "Generate", "id", "for", "the", "condition", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_base.py#L16-L29
oceanprotocol/squid-py
squid_py/keeper/conditions/condition_base.py
ConditionBase._fulfill
def _fulfill(self, *args, **kwargs): """ Fulfill the condition. :param args: :param kwargs: :return: true if the condition was successfully fulfilled, bool """ tx_hash = self.send_transaction('fulfill', args, **kwargs) receipt = self.get_tx_receipt(tx_hash) return receipt.status == 1
python
def _fulfill(self, *args, **kwargs): tx_hash = self.send_transaction('fulfill', args, **kwargs) receipt = self.get_tx_receipt(tx_hash) return receipt.status == 1
[ "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. :param args: :param kwargs: :return: true if the condition was successfully fulfilled, bool
[ "Fulfill", "the", "condition", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_base.py#L31-L41
oceanprotocol/squid-py
squid_py/keeper/conditions/condition_base.py
ConditionBase.subscribe_condition_fulfilled
def subscribe_condition_fulfilled(self, agreement_id, timeout, callback, args, timeout_callback=None, wait=False): """ Subscribe to the condition fullfilled event. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param timeout_callback: :param wait: if true block the listener until get the event, bool :return: """ logger.info( f'Subscribing {self.FULFILLED_EVENT} event with agreement id {agreement_id}.') return self.subscribe_to_event( self.FULFILLED_EVENT, timeout, {'_agreementId': Web3Provider.get_web3().toBytes(hexstr=agreement_id)}, callback=callback, timeout_callback=timeout_callback, args=args, wait=wait )
python
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': Web3Provider.get_web3().toBytes(hexstr=agreement_id)}, callback=callback, timeout_callback=timeout_callback, args=args, wait=wait )
[ "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'", ":", "Web3Provider", ".", "get_web3", "(", ")", ".", "toBytes", "(", "hexstr", "=", "agreement_id", ")", "}", ",", "callback", "=", "callback", ",", "timeout_callback", "=", "timeout_callback", ",", "args", "=", "args", ",", "wait", "=", "wait", ")" ]
Subscribe to the condition fullfilled event. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param timeout_callback: :param wait: if true block the listener until get the event, bool :return:
[ "Subscribe", "to", "the", "condition", "fullfilled", "event", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_base.py#L62-L85
oceanprotocol/squid-py
squid_py/keeper/web3/contract.py
transact_with_contract_function
def transact_with_contract_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ 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. """ transact_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, transaction=transaction, fn_abi=fn_abi, fn_args=args, fn_kwargs=kwargs, ) passphrase = None if transaction and 'passphrase' in transaction: passphrase = transaction['passphrase'] transact_transaction.pop('passphrase') if passphrase: txn_hash = web3.personal.sendTransaction(transact_transaction, passphrase) else: txn_hash = web3.eth.sendTransaction(transact_transaction) return txn_hash
python
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=fn_abi, fn_args=args, fn_kwargs=kwargs, ) passphrase = None if transaction and 'passphrase' in transaction: passphrase = transaction['passphrase'] transact_transaction.pop('passphrase') if passphrase: txn_hash = web3.personal.sendTransaction(transact_transaction, passphrase) else: txn_hash = web3.eth.sendTransaction(transact_transaction) return txn_hash
[ "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", "=", "fn_abi", ",", "fn_args", "=", "args", ",", "fn_kwargs", "=", "kwargs", ",", ")", "passphrase", "=", "None", "if", "transaction", "and", "'passphrase'", "in", "transaction", ":", "passphrase", "=", "transaction", "[", "'passphrase'", "]", "transact_transaction", ".", "pop", "(", "'passphrase'", ")", "if", "passphrase", ":", "txn_hash", "=", "web3", ".", "personal", ".", "sendTransaction", "(", "transact_transaction", ",", "passphrase", ")", "else", ":", "txn_hash", "=", "web3", ".", "eth", ".", "sendTransaction", "(", "transact_transaction", ")", "return", "txn_hash" ]
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.
[ "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", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/web3/contract.py#L67-L102
oceanprotocol/squid-py
squid_py/keeper/web3/contract.py
SquidContractFunction.transact
def transact(self, transaction=None): """ 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. Note: will fallback to `eth_sendTransaction` if `passphrase` is not provided in the `transaction` dict. :param transaction: dict which has the required transaction arguments per `personal_sendTransaction` requirements. :return: hex str transaction hash """ 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_transaction.setdefault('to', cf.address) if cf.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', cf.web3.eth.defaultAccount) if 'to' not in transact_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.transact` from a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) if 'gas' not in transact_transaction: tx = transaction.copy() if 'passphrase' in tx: tx.pop('passphrase') gas = cf.estimateGas(tx) transact_transaction['gas'] = gas return transact_with_contract_function( cf.address, cf.web3, cf.function_identifier, transact_transaction, cf.contract_abi, cf.abi, *cf.args, **cf.kwargs )
python
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_transaction.setdefault('to', cf.address) if cf.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', cf.web3.eth.defaultAccount) if 'to' not in transact_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.transact` from a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) if 'gas' not in transact_transaction: tx = transaction.copy() if 'passphrase' in tx: tx.pop('passphrase') gas = cf.estimateGas(tx) transact_transaction['gas'] = gas return transact_with_contract_function( cf.address, cf.web3, cf.function_identifier, transact_transaction, cf.contract_abi, cf.abi, *cf.args, **cf.kwargs )
[ "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_transaction", ".", "setdefault", "(", "'to'", ",", "cf", ".", "address", ")", "if", "cf", ".", "web3", ".", "eth", ".", "defaultAccount", "is", "not", "empty", ":", "transact_transaction", ".", "setdefault", "(", "'from'", ",", "cf", ".", "web3", ".", "eth", ".", "defaultAccount", ")", "if", "'to'", "not", "in", "transact_transaction", ":", "if", "isinstance", "(", "self", ",", "type", ")", ":", "raise", "ValueError", "(", "\"When using `Contract.transact` from a contract factory you \"", "\"must provide a `to` address with the transaction\"", ")", "else", ":", "raise", "ValueError", "(", "\"Please ensure that this contract instance has an address.\"", ")", "if", "'gas'", "not", "in", "transact_transaction", ":", "tx", "=", "transaction", ".", "copy", "(", ")", "if", "'passphrase'", "in", "tx", ":", "tx", ".", "pop", "(", "'passphrase'", ")", "gas", "=", "cf", ".", "estimateGas", "(", "tx", ")", "transact_transaction", "[", "'gas'", "]", "=", "gas", "return", "transact_with_contract_function", "(", "cf", ".", "address", ",", "cf", ".", "web3", ",", "cf", ".", "function_identifier", ",", "transact_transaction", ",", "cf", ".", "contract_abi", ",", "cf", ".", "abi", ",", "*", "cf", ".", "args", ",", "*", "*", "cf", ".", "kwargs", ")" ]
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. Note: will fallback to `eth_sendTransaction` if `passphrase` is not provided in the `transaction` dict. :param transaction: dict which has the required transaction arguments per `personal_sendTransaction` requirements. :return: hex str transaction hash
[ "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", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/web3/contract.py#L10-L64
oceanprotocol/squid-py
squid_py/keeper/conditions/escrow_reward.py
EscrowRewardCondition.fulfill
def fulfill(self, agreement_id, amount, receiver_address, sender_address, lock_condition_id, release_condition_id, account): """ Fulfill the escrow reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :param account: Account instance :return: """ return self._fulfill( agreement_id, amount, receiver_address, sender_address, lock_condition_id, release_condition_id, transact={'from': account.address, 'passphrase': account.password} )
python
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': account.password} )
[ "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'", ":", "account", ".", "password", "}", ")" ]
Fulfill the escrow reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :param account: Account instance :return:
[ "Fulfill", "the", "escrow", "reward", "condition", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/escrow_reward.py#L11-L40
oceanprotocol/squid-py
squid_py/keeper/conditions/escrow_reward.py
EscrowRewardCondition.hash_values
def hash_values(self, amount, receiver_address, sender_address, lock_condition_id, release_condition_id): """ Hash the values of the escrow reward condition. :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :return: hex str """ return self._hash_values( amount, receiver_address, sender_address, lock_condition_id, release_condition_id )
python
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 )
[ "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. :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :return: hex str
[ "Hash", "the", "values", "of", "the", "escrow", "reward", "condition", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/escrow_reward.py#L42-L60
oceanprotocol/squid-py
squid_py/agreements/service_agreement_condition.py
Parameter.as_dictionary
def as_dictionary(self): """ Return the parameter as a dictionary. :return: dict """ return { "name": self.name, "type": self.type, "value": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value }
python
def as_dictionary(self): return { "name": self.name, "type": self.type, "value": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value }
[ "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. :return: dict
[ "Return", "the", "parameter", "as", "a", "dictionary", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_condition.py#L21-L31
oceanprotocol/squid-py
squid_py/agreements/service_agreement_condition.py
ServiceAgreementCondition.init_from_condition_json
def init_from_condition_json(self, condition_json): """ Init the condition values from a condition json. :param condition_json: dict """ 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.parameters = [Parameter(p) for p in condition_json['parameters']] self.events = [Event(e) for e in condition_json['events']]
python
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.parameters = [Parameter(p) for p in condition_json['parameters']] self.events = [Event(e) for e in condition_json['events']]
[ "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", ".", "parameters", "=", "[", "Parameter", "(", "p", ")", "for", "p", "in", "condition_json", "[", "'parameters'", "]", "]", "self", ".", "events", "=", "[", "Event", "(", "e", ")", "for", "e", "in", "condition_json", "[", "'events'", "]", "]" ]
Init the condition values from a condition json. :param condition_json: dict
[ "Init", "the", "condition", "values", "from", "a", "condition", "json", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_condition.py#L93-L105
oceanprotocol/squid-py
squid_py/agreements/service_agreement_condition.py
ServiceAgreementCondition.as_dictionary
def as_dictionary(self): """ Return the condition as a dictionary. :return: dict """ 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 self.parameters], } return condition_dict
python
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 self.parameters], } return condition_dict
[ "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", "self", ".", "parameters", "]", ",", "}", "return", "condition_dict" ]
Return the condition as a dictionary. :return: dict
[ "Return", "the", "condition", "as", "a", "dictionary", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_condition.py#L107-L123
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.update_value
def update_value(self, name, value): """ Update value in the array of values. :param name: Key of the value, str :param value: New value, str :return: None """ if name not in {'id', self.SERVICE_ENDPOINT, self.CONSUME_ENDPOINT, 'type'}: self._values[name] = value
python
def update_value(self, name, value): if name not in {'id', self.SERVICE_ENDPOINT, self.CONSUME_ENDPOINT, 'type'}: self._values[name] = value
[ "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. :param name: Key of the value, str :param value: New value, str :return: None
[ "Update", "value", "in", "the", "array", "of", "values", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L92-L101
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.as_text
def as_text(self, is_pretty=False): """Return the service as a JSON string.""" 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: # add extra service values to the dictionary for name, value in self._values.items(): values[name] = value if is_pretty: return json.dumps(values, indent=4, separators=(',', ': ')) return json.dumps(values)
python
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] = value if is_pretty: return json.dumps(values, indent=4, separators=(',', ': ')) return json.dumps(values)
[ "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", ":", "# add extra service values to the dictionary", "for", "name", ",", "value", "in", "self", ".", "_values", ".", "items", "(", ")", ":", "values", "[", "name", "]", "=", "value", "if", "is_pretty", ":", "return", "json", ".", "dumps", "(", "values", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "return", "json", ".", "dumps", "(", "values", ")" ]
Return the service as a JSON string.
[ "Return", "the", "service", "as", "a", "JSON", "string", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L116-L132
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.as_dictionary
def as_dictionary(self): """Return the service as a python dictionary.""" 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: # add extra service values to the dictionary for name, value in self._values.items(): if isinstance(value, object) and hasattr(value, 'as_dictionary'): value = value.as_dictionary() elif isinstance(value, list): value = [v.as_dictionary() if hasattr(v, 'as_dictionary') else v for v in value] values[name] = value return values
python
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, object) and hasattr(value, 'as_dictionary'): value = value.as_dictionary() elif isinstance(value, list): value = [v.as_dictionary() if hasattr(v, 'as_dictionary') else v for v in value] values[name] = value return values
[ "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", ":", "# add extra service values to the dictionary", "for", "name", ",", "value", "in", "self", ".", "_values", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "object", ")", "and", "hasattr", "(", "value", ",", "'as_dictionary'", ")", ":", "value", "=", "value", ".", "as_dictionary", "(", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "v", ".", "as_dictionary", "(", ")", "if", "hasattr", "(", "v", ",", "'as_dictionary'", ")", "else", "v", "for", "v", "in", "value", "]", "values", "[", "name", "]", "=", "value", "return", "values" ]
Return the service as a python dictionary.
[ "Return", "the", "service", "as", "a", "python", "dictionary", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L134-L151
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.from_json
def from_json(cls, service_dict): """Create a service object from a JSON string.""" 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.error('Service definition in DDO document is missing the "type" key/value.') raise IndexError sd.pop(cls.SERVICE_ENDPOINT) sd.pop('type') return cls( service_endpoint, _type, sd )
python
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.error('Service definition in DDO document is missing the "type" key/value.') raise IndexError sd.pop(cls.SERVICE_ENDPOINT) sd.pop('type') return cls( service_endpoint, _type, sd )
[ "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", ".", "error", "(", "'Service definition in DDO document is missing the \"type\" key/value.'", ")", "raise", "IndexError", "sd", ".", "pop", "(", "cls", ".", "SERVICE_ENDPOINT", ")", "sd", ".", "pop", "(", "'type'", ")", "return", "cls", "(", "service_endpoint", ",", "_type", ",", "sd", ")" ]
Create a service object from a JSON string.
[ "Create", "a", "service", "object", "from", "a", "JSON", "string", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L154-L174
oceanprotocol/squid-py
squid_py/keeper/conditions/access.py
AccessSecretStoreCondition.fulfill
def fulfill(self, agreement_id, document_id, grantee_address, account): """ Fulfill the access secret store condition. :param agreement_id: id of the agreement, hex str :param document_id: refers to the DID in which secret store will issue the decryption keys, DID :param grantee_address: is the address of the granted user, str :param account: Account instance :return: true if the condition was successfully fulfilled, bool """ return self._fulfill( agreement_id, document_id, grantee_address, transact={'from': account.address, 'passphrase': account.password} )
python
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} )
[ "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. :param agreement_id: id of the agreement, hex str :param document_id: refers to the DID in which secret store will issue the decryption keys, DID :param grantee_address: is the address of the granted user, str :param account: Account instance :return: true if the condition was successfully fulfilled, bool
[ "Fulfill", "the", "access", "secret", "store", "condition", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/access.py#L13-L30
oceanprotocol/squid-py
squid_py/keeper/conditions/access.py
AccessSecretStoreCondition.get_purchased_assets_by_address
def get_purchased_assets_by_address(self, address, from_block=0, to_block='latest'): """ Get the list of the assets dids consumed for an address. :param address: is the address of the granted user, hex-str :param from_block: block to start to listen :param to_block: block to stop to listen :return: list of dids """ 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_items = block_filter.get_all_entries(max_tries=5) did_list = [] for log_i in log_items: did_list.append(id_to_did(log_i.args['_documentId'])) return did_list
python
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_items = block_filter.get_all_entries(max_tries=5) did_list = [] for log_i in log_items: did_list.append(id_to_did(log_i.args['_documentId'])) return did_list
[ "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_items", "=", "block_filter", ".", "get_all_entries", "(", "max_tries", "=", "5", ")", "did_list", "=", "[", "]", "for", "log_i", "in", "log_items", ":", "did_list", ".", "append", "(", "id_to_did", "(", "log_i", ".", "args", "[", "'_documentId'", "]", ")", ")", "return", "did_list" ]
Get the list of the assets dids consumed for an address. :param address: is the address of the granted user, hex-str :param from_block: block to start to listen :param to_block: block to stop to listen :return: list of dids
[ "Get", "the", "list", "of", "the", "assets", "dids", "consumed", "for", "an", "address", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/access.py#L55-L76
oceanprotocol/squid-py
squid_py/keeper/web3_provider.py
Web3Provider.get_web3
def get_web3(): """Return the web3 instance to interact with the ethereum client.""" 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) # Reset attributes to avoid lint issue about no attribute Web3Provider._web3.eth = getattr(Web3Provider._web3, 'eth') Web3Provider._web3.net = getattr(Web3Provider._web3, 'net') Web3Provider._web3.personal = getattr(Web3Provider._web3, 'personal') Web3Provider._web3.version = getattr(Web3Provider._web3, 'version') Web3Provider._web3.txpool = getattr(Web3Provider._web3, 'txpool') Web3Provider._web3.miner = getattr(Web3Provider._web3, 'miner') Web3Provider._web3.admin = getattr(Web3Provider._web3, 'admin') Web3Provider._web3.parity = getattr(Web3Provider._web3, 'parity') Web3Provider._web3.testing = getattr(Web3Provider._web3, 'testing') return Web3Provider._web3
python
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') Web3Provider._web3.net = getattr(Web3Provider._web3, 'net') Web3Provider._web3.personal = getattr(Web3Provider._web3, 'personal') Web3Provider._web3.version = getattr(Web3Provider._web3, 'version') Web3Provider._web3.txpool = getattr(Web3Provider._web3, 'txpool') Web3Provider._web3.miner = getattr(Web3Provider._web3, 'miner') Web3Provider._web3.admin = getattr(Web3Provider._web3, 'admin') Web3Provider._web3.parity = getattr(Web3Provider._web3, 'parity') Web3Provider._web3.testing = getattr(Web3Provider._web3, 'testing') return Web3Provider._web3
[ "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", ")", "# Reset attributes to avoid lint issue about no attribute", "Web3Provider", ".", "_web3", ".", "eth", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'eth'", ")", "Web3Provider", ".", "_web3", ".", "net", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'net'", ")", "Web3Provider", ".", "_web3", ".", "personal", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'personal'", ")", "Web3Provider", ".", "_web3", ".", "version", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'version'", ")", "Web3Provider", ".", "_web3", ".", "txpool", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'txpool'", ")", "Web3Provider", ".", "_web3", ".", "miner", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'miner'", ")", "Web3Provider", ".", "_web3", ".", "admin", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'admin'", ")", "Web3Provider", ".", "_web3", ".", "parity", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'parity'", ")", "Web3Provider", ".", "_web3", ".", "testing", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'testing'", ")", "return", "Web3Provider", ".", "_web3" ]
Return the web3 instance to interact with the ethereum client.
[ "Return", "the", "web3", "instance", "to", "interact", "with", "the", "ethereum", "client", "." ]
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/web3_provider.py#L15-L38
BlueBrain/NeuroM
neurom/core/_soma.py
_get_type
def _get_type(points, soma_class): '''get the type of the soma Args: points: Soma points soma_class(str): one of 'contour' or 'cylinder' to specify the type ''' 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.P] == 1 and points[2][COLS.P] == 1): L.warning('Using neuromorpho 3-Point soma') # NeuroMorpho is the main provider of morphologies, but they # with SWC as their default file format: they convert all # uploads to SWC. In the process of conversion, they turn all # somas into their custom 'Three-point soma representation': # http://neuromorpho.org/SomaFormat.html return SomaNeuromorphoThreePointCylinders return {0: None, 1: SomaSinglePoint}.get(npoints, SomaCylinders)
python
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.P] == 1 and points[2][COLS.P] == 1): L.warning('Using neuromorpho 3-Point soma') return SomaNeuromorphoThreePointCylinders return {0: None, 1: SomaSinglePoint}.get(npoints, SomaCylinders)
[ "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", ".", "P", "]", "==", "1", "and", "points", "[", "2", "]", "[", "COLS", ".", "P", "]", "==", "1", ")", ":", "L", ".", "warning", "(", "'Using neuromorpho 3-Point soma'", ")", "# NeuroMorpho is the main provider of morphologies, but they", "# with SWC as their default file format: they convert all", "# uploads to SWC. In the process of conversion, they turn all", "# somas into their custom 'Three-point soma representation':", "# http://neuromorpho.org/SomaFormat.html", "return", "SomaNeuromorphoThreePointCylinders", "return", "{", "0", ":", "None", ",", "1", ":", "SomaSinglePoint", "}", ".", "get", "(", "npoints", ",", "SomaCylinders", ")" ]
get the type of the soma Args: points: Soma points soma_class(str): one of 'contour' or 'cylinder' to specify the type
[ "get", "the", "type", "of", "the", "soma" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_soma.py#L203-L232
BlueBrain/NeuroM
neurom/core/_soma.py
make_soma
def make_soma(points, soma_check=None, soma_class=SOMA_CONTOUR): '''Make a soma object from a set of points Infers the soma type (SomaSinglePoint, SomaSimpleContour) from the points and the 'soma_class' Parameters: points: collection of points forming a soma. soma_check: optional validation function applied to points. Should raise a SomaError if points not valid. soma_class(str): one of 'contour' or 'cylinder' to specify the type Raises: SomaError if no soma points found, points incompatible with soma, or if soma_check(points) fails. ''' if soma_check: soma_check(points) stype = _get_type(points, soma_class) if stype is None: raise SomaError('Invalid soma points') return stype(points)
python
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)
[ "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 Infers the soma type (SomaSinglePoint, SomaSimpleContour) from the points and the 'soma_class' Parameters: points: collection of points forming a soma. soma_check: optional validation function applied to points. Should raise a SomaError if points not valid. soma_class(str): one of 'contour' or 'cylinder' to specify the type Raises: SomaError if no soma points found, points incompatible with soma, or if soma_check(points) fails.
[ "Make", "a", "soma", "object", "from", "a", "set", "of", "points" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_soma.py#L235-L260
BlueBrain/NeuroM
neurom/core/_soma.py
SomaSimpleContour.center
def center(self): '''Obtain the center from the average of all points''' points = np.array(self._points) return np.mean(points[:, COLS.XYZ], axis=0)
python
def center(self): points = np.array(self._points) return np.mean(points[:, COLS.XYZ], axis=0)
[ "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
[ "Obtain", "the", "center", "from", "the", "average", "of", "all", "points" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_soma.py#L188-L191
BlueBrain/NeuroM
neurom/fst/sectionfunc.py
section_tortuosity
def section_tortuosity(section): '''Tortuosity of a section The tortuosity is defined as the ratio of the path length of a section and the euclidian distnce between its end points. The path length is the sum of distances between consecutive points. If the section contains less than 2 points, the value 1 is returned. ''' pts = section.points return 1 if len(pts) < 2 else mm.section_length(pts) / mm.point_dist(pts[-1], pts[0])
python
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])
[ "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 The tortuosity is defined as the ratio of the path length of a section and the euclidian distnce between its end points. The path length is the sum of distances between consecutive points. If the section contains less than 2 points, the value 1 is returned.
[ "Tortuosity", "of", "a", "section" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/sectionfunc.py#L50-L61
BlueBrain/NeuroM
neurom/fst/sectionfunc.py
section_end_distance
def section_end_distance(section): '''End to end distance of a section The end to end distance of a section is defined as the euclidian distnce between its end points. If the section contains less than 2 points, the value 0 is returned. ''' pts = section.points return 0 if len(pts) < 2 else mm.point_dist(pts[-1], pts[0])
python
def section_end_distance(section): pts = section.points return 0 if len(pts) < 2 else mm.point_dist(pts[-1], pts[0])
[ "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 The end to end distance of a section is defined as the euclidian distnce between its end points. If the section contains less than 2 points, the value 0 is returned.
[ "End", "to", "end", "distance", "of", "a", "section" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/sectionfunc.py#L64-L73
BlueBrain/NeuroM
neurom/fst/sectionfunc.py
section_meander_angles
def section_meander_angles(section): '''Inter-segment opening angles in a section''' p = section.points return [mm.angle_3points(p[i - 1], p[i - 2], p[i]) for i in range(2, len(p))]
python
def section_meander_angles(section): p = section.points return [mm.angle_3points(p[i - 1], p[i - 2], p[i]) for i in range(2, len(p))]
[ "def", "section_meander_angles", "(", "section", ")", ":", "p", "=", "section", ".", "points", "return", "[", "mm", ".", "angle_3points", "(", "p", "[", "i", "-", "1", "]", ",", "p", "[", "i", "-", "2", "]", ",", "p", "[", "i", "]", ")", "for", "i", "in", "range", "(", "2", ",", "len", "(", "p", ")", ")", "]" ]
Inter-segment opening angles in a section
[ "Inter", "-", "segment", "opening", "angles", "in", "a", "section" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/sectionfunc.py#L101-L105
BlueBrain/NeuroM
neurom/fst/sectionfunc.py
strahler_order
def strahler_order(section): '''Branching order of a tree section The strahler order is the inverse of the branch order, since this is computed from the tips of the tree towards the root. This implementation is a translation of the three steps described in Wikipedia (https://en.wikipedia.org/wiki/Strahler_number): - If the node is a leaf (has no children), its Strahler number is one. - If the node has one child with Strahler number i, and all other children have Strahler numbers less than i, then the Strahler number of the node is i again. - If the node has two or more children with Strahler number i, and no children with greater number, then the Strahler number of the node is i + 1. No efforts have been invested in making it computationnaly efficient, but it computes acceptably fast on tested morphologies (i.e., no waiting time). ''' 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) # check if there are *two* or more children w/ the max_so_children any(it) if any(it): return max_so_children + 1 return max_so_children return 1
python
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
[ "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", ")", "# check if there are *two* or more children w/ the max_so_children", "any", "(", "it", ")", "if", "any", "(", "it", ")", ":", "return", "max_so_children", "+", "1", "return", "max_so_children", "return", "1" ]
Branching order of a tree section The strahler order is the inverse of the branch order, since this is computed from the tips of the tree towards the root. This implementation is a translation of the three steps described in Wikipedia (https://en.wikipedia.org/wiki/Strahler_number): - If the node is a leaf (has no children), its Strahler number is one. - If the node has one child with Strahler number i, and all other children have Strahler numbers less than i, then the Strahler number of the node is i again. - If the node has two or more children with Strahler number i, and no children with greater number, then the Strahler number of the node is i + 1. No efforts have been invested in making it computationnaly efficient, but it computes acceptably fast on tested morphologies (i.e., no waiting time).
[ "Branching", "order", "of", "a", "tree", "section" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/sectionfunc.py#L108-L138
BlueBrain/NeuroM
neurom/view/common.py
figure_naming
def figure_naming(pretitle='', posttitle='', prefile='', postfile=''): """ Helper function to define the strings that handle pre-post conventions for viewing - plotting title and saving options. Args: pretitle(str): String to include before the general title of the figure. posttitle(str): String to include after the general title of the figure. prefile(str): String to include before the general filename of the figure. postfile(str): String to include after the general filename of the figure. Returns: str: String to include in the figure name and title, in a suitable form. """ 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
python
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
[ "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. Args: pretitle(str): String to include before the general title of the figure. posttitle(str): String to include after the general title of the figure. prefile(str): String to include before the general filename of the figure. postfile(str): String to include after the general filename of the figure. Returns: str: String to include in the figure name and title, in a suitable form.
[ "Helper", "function", "to", "define", "the", "strings", "that", "handle", "pre", "-", "post", "conventions", "for", "viewing", "-", "plotting", "title", "and", "saving", "options", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L56-L82
BlueBrain/NeuroM
neurom/view/common.py
get_figure
def get_figure(new_fig=True, subplot='111', params=None): """ Function to be used for viewing - plotting, to initialize the matplotlib figure - axes. Args: new_fig(bool): Defines if a new figure will be created, if false current figure is used subplot (tuple or matplolib subplot specifier string): Create axes with these parameters params (dict): extra options passed to add_subplot() Returns: Matplotlib Figure and Axes """ _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, **params) return fig, ax
python
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, **params) return fig, ax
[ "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", ",", "*", "*", "params", ")", "return", "fig", ",", "ax" ]
Function to be used for viewing - plotting, to initialize the matplotlib figure - axes. Args: new_fig(bool): Defines if a new figure will be created, if false current figure is used subplot (tuple or matplolib subplot specifier string): Create axes with these parameters params (dict): extra options passed to add_subplot() Returns: Matplotlib Figure and Axes
[ "Function", "to", "be", "used", "for", "viewing", "-", "plotting", "to", "initialize", "the", "matplotlib", "figure", "-", "axes", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L85-L112
BlueBrain/NeuroM
neurom/view/common.py
save_plot
def save_plot(fig, prefile='', postfile='', output_path='./', output_name='Figure', output_format='png', dpi=300, transparent=False, **_): """Generates a figure file in the selected directory. Args: fig: matplotlib figure prefile(str): Include before the general filename of the figure postfile(str): Included after the general filename of the figure output_path(str): Define the path to the output directory output_name(str): String to define the name of the output figure output_format(str): String to define the format of the output figure dpi(int): Define the DPI (Dots per Inch) of the figure transparent(bool): If True the saved figure will have a transparent background """ if not os.path.exists(output_path): os.makedirs(output_path) # Make output directory if non-exsiting output = os.path.join(output_path, prefile + output_name + postfile + "." + output_format) fig.savefig(output, dpi=dpi, transparent=transparent)
python
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 + "." + output_format) fig.savefig(output, dpi=dpi, transparent=transparent)
[ "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", ")", "# Make output directory if non-exsiting", "output", "=", "os", ".", "path", ".", "join", "(", "output_path", ",", "prefile", "+", "output_name", "+", "postfile", "+", "\".\"", "+", "output_format", ")", "fig", ".", "savefig", "(", "output", ",", "dpi", "=", "dpi", ",", "transparent", "=", "transparent", ")" ]
Generates a figure file in the selected directory. Args: fig: matplotlib figure prefile(str): Include before the general filename of the figure postfile(str): Included after the general filename of the figure output_path(str): Define the path to the output directory output_name(str): String to define the name of the output figure output_format(str): String to define the format of the output figure dpi(int): Define the DPI (Dots per Inch) of the figure transparent(bool): If True the saved figure will have a transparent background
[ "Generates", "a", "figure", "file", "in", "the", "selected", "directory", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L115-L135
BlueBrain/NeuroM
neurom/view/common.py
plot_style
def plot_style(fig, ax, # pylint: disable=too-many-arguments, too-many-locals # plot_title pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None, # plot_labels label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None, # plot_ticks tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None, # update_plot_limits white_space=30, # plot_legend no_legend=True, legend_arg=None, # internal no_axes=False, aspect_ratio='equal', tight=False, **_): """Set the basic options of a matplotlib figure, to be used by viewing - plotting functions Args: fig(matplotlib figure): figure ax(matplotlib axes, belonging to `fig`): axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_args(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_args(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_args(dict): Passsed into matplotlib as zticks arguments white_space(float): whitespace added to surround the tight limit of the data no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call no_axes(bool): If True the labels and the frame will be set off aspect_ratio(str): Sets aspect ratio of the figure, according to matplotlib aspect_ratio tight(bool): If True the tight layout of matplotlib will be activated Returns: Matplotlib figure, matplotlib axes """ plot_title(ax, pretitle, title, posttitle, title_fontsize, title_arg) plot_labels(ax, label_fontsize, xlabel, xlabel_arg, ylabel, ylabel_arg, zlabel, zlabel_arg) plot_ticks(ax, tick_fontsize, xticks, xticks_args, yticks, yticks_args, zticks, zticks_args) update_plot_limits(ax, white_space) plot_legend(ax, no_legend, legend_arg) if no_axes: ax.set_frame_on(False) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_aspect(aspect_ratio) if tight: fig.set_tight_layout(True)
python
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=None, yticks_args=None, zticks=None, zticks_args=None, white_space=30, no_legend=True, legend_arg=None, no_axes=False, aspect_ratio='equal', tight=False, **_): plot_title(ax, pretitle, title, posttitle, title_fontsize, title_arg) plot_labels(ax, label_fontsize, xlabel, xlabel_arg, ylabel, ylabel_arg, zlabel, zlabel_arg) plot_ticks(ax, tick_fontsize, xticks, xticks_args, yticks, yticks_args, zticks, zticks_args) update_plot_limits(ax, white_space) plot_legend(ax, no_legend, legend_arg) if no_axes: ax.set_frame_on(False) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_aspect(aspect_ratio) if tight: fig.set_tight_layout(True)
[ "def", "plot_style", "(", "fig", ",", "ax", ",", "# pylint: disable=too-many-arguments, too-many-locals", "# plot_title", "pretitle", "=", "''", ",", "title", "=", "'Figure'", ",", "posttitle", "=", "''", ",", "title_fontsize", "=", "14", ",", "title_arg", "=", "None", ",", "# plot_labels", "label_fontsize", "=", "14", ",", "xlabel", "=", "None", ",", "xlabel_arg", "=", "None", ",", "ylabel", "=", "None", ",", "ylabel_arg", "=", "None", ",", "zlabel", "=", "None", ",", "zlabel_arg", "=", "None", ",", "# plot_ticks", "tick_fontsize", "=", "12", ",", "xticks", "=", "None", ",", "xticks_args", "=", "None", ",", "yticks", "=", "None", ",", "yticks_args", "=", "None", ",", "zticks", "=", "None", ",", "zticks_args", "=", "None", ",", "# update_plot_limits", "white_space", "=", "30", ",", "# plot_legend", "no_legend", "=", "True", ",", "legend_arg", "=", "None", ",", "# internal", "no_axes", "=", "False", ",", "aspect_ratio", "=", "'equal'", ",", "tight", "=", "False", ",", "*", "*", "_", ")", ":", "plot_title", "(", "ax", ",", "pretitle", ",", "title", ",", "posttitle", ",", "title_fontsize", ",", "title_arg", ")", "plot_labels", "(", "ax", ",", "label_fontsize", ",", "xlabel", ",", "xlabel_arg", ",", "ylabel", ",", "ylabel_arg", ",", "zlabel", ",", "zlabel_arg", ")", "plot_ticks", "(", "ax", ",", "tick_fontsize", ",", "xticks", ",", "xticks_args", ",", "yticks", ",", "yticks_args", ",", "zticks", ",", "zticks_args", ")", "update_plot_limits", "(", "ax", ",", "white_space", ")", "plot_legend", "(", "ax", ",", "no_legend", ",", "legend_arg", ")", "if", "no_axes", ":", "ax", ".", "set_frame_on", "(", "False", ")", "ax", ".", "xaxis", ".", "set_visible", "(", "False", ")", "ax", ".", "yaxis", ".", "set_visible", "(", "False", ")", "ax", ".", "set_aspect", "(", "aspect_ratio", ")", "if", "tight", ":", "fig", ".", "set_tight_layout", "(", "True", ")" ]
Set the basic options of a matplotlib figure, to be used by viewing - plotting functions Args: fig(matplotlib figure): figure ax(matplotlib axes, belonging to `fig`): axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_args(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_args(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_args(dict): Passsed into matplotlib as zticks arguments white_space(float): whitespace added to surround the tight limit of the data no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call no_axes(bool): If True the labels and the frame will be set off aspect_ratio(str): Sets aspect ratio of the figure, according to matplotlib aspect_ratio tight(bool): If True the tight layout of matplotlib will be activated Returns: Matplotlib figure, matplotlib axes
[ "Set", "the", "basic", "options", "of", "a", "matplotlib", "figure", "to", "be", "used", "by", "viewing", "-", "plotting", "functions" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L138-L225
BlueBrain/NeuroM
neurom/view/common.py
plot_title
def plot_title(ax, pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None): """Set title options of a matplotlib plot Args: ax: matplotlib axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call """ 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, **title_arg)
python
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, **title_arg)
[ "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", ",", "*", "*", "title_arg", ")" ]
Set title options of a matplotlib plot Args: ax: matplotlib axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call
[ "Set", "title", "options", "of", "a", "matplotlib", "plot" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L228-L246
BlueBrain/NeuroM
neurom/view/common.py
plot_labels
def plot_labels(ax, label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None): """Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments """ 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(xlabel_arg) ylabel_arg = dict_if_none(ylabel_arg) ax.set_xlabel(xlabel, fontsize=label_fontsize, **xlabel_arg) ax.set_ylabel(ylabel, fontsize=label_fontsize, **ylabel_arg) if hasattr(ax, 'zaxis'): zlabel = zlabel if zlabel is not None else ax.get_zlabel() or 'Z' zlabel_arg = dict_if_none(zlabel_arg) ax.set_zlabel(zlabel, fontsize=label_fontsize, **zlabel_arg)
python
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(xlabel_arg) ylabel_arg = dict_if_none(ylabel_arg) ax.set_xlabel(xlabel, fontsize=label_fontsize, **xlabel_arg) ax.set_ylabel(ylabel, fontsize=label_fontsize, **ylabel_arg) if hasattr(ax, 'zaxis'): zlabel = zlabel if zlabel is not None else ax.get_zlabel() or 'Z' zlabel_arg = dict_if_none(zlabel_arg) ax.set_zlabel(zlabel, fontsize=label_fontsize, **zlabel_arg)
[ "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", "(", "xlabel_arg", ")", "ylabel_arg", "=", "dict_if_none", "(", "ylabel_arg", ")", "ax", ".", "set_xlabel", "(", "xlabel", ",", "fontsize", "=", "label_fontsize", ",", "*", "*", "xlabel_arg", ")", "ax", ".", "set_ylabel", "(", "ylabel", ",", "fontsize", "=", "label_fontsize", ",", "*", "*", "ylabel_arg", ")", "if", "hasattr", "(", "ax", ",", "'zaxis'", ")", ":", "zlabel", "=", "zlabel", "if", "zlabel", "is", "not", "None", "else", "ax", ".", "get_zlabel", "(", ")", "or", "'Z'", "zlabel_arg", "=", "dict_if_none", "(", "zlabel_arg", ")", "ax", ".", "set_zlabel", "(", "zlabel", ",", "fontsize", "=", "label_fontsize", ",", "*", "*", "zlabel_arg", ")" ]
Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments
[ "Sets", "the", "labels", "options", "of", "a", "matplotlib", "plot" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L249-L277
BlueBrain/NeuroM
neurom/view/common.py
plot_ticks
def plot_ticks(ax, tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None): """Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_arg(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_arg(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_arg(dict): Passsed into matplotlib as zticks arguments """ 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_args) if yticks is not None: ax.set_yticks(yticks) yticks_args = dict_if_none(yticks_args) ax.yaxis.set_tick_params(labelsize=tick_fontsize, **yticks_args) if zticks is not None: ax.set_zticks(zticks) zticks_args = dict_if_none(zticks_args) ax.zaxis.set_tick_params(labelsize=tick_fontsize, **zticks_args)
python
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_args) if yticks is not None: ax.set_yticks(yticks) yticks_args = dict_if_none(yticks_args) ax.yaxis.set_tick_params(labelsize=tick_fontsize, **yticks_args) if zticks is not None: ax.set_zticks(zticks) zticks_args = dict_if_none(zticks_args) ax.zaxis.set_tick_params(labelsize=tick_fontsize, **zticks_args)
[ "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_args", ")", "if", "yticks", "is", "not", "None", ":", "ax", ".", "set_yticks", "(", "yticks", ")", "yticks_args", "=", "dict_if_none", "(", "yticks_args", ")", "ax", ".", "yaxis", ".", "set_tick_params", "(", "labelsize", "=", "tick_fontsize", ",", "*", "*", "yticks_args", ")", "if", "zticks", "is", "not", "None", ":", "ax", ".", "set_zticks", "(", "zticks", ")", "zticks_args", "=", "dict_if_none", "(", "zticks_args", ")", "ax", ".", "zaxis", ".", "set_tick_params", "(", "labelsize", "=", "tick_fontsize", ",", "*", "*", "zticks_args", ")" ]
Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_arg(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_arg(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_arg(dict): Passsed into matplotlib as zticks arguments
[ "Function", "that", "defines", "the", "labels", "options", "of", "a", "matplotlib", "plot", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L280-L309
BlueBrain/NeuroM
neurom/view/common.py
update_plot_limits
def update_plot_limits(ax, white_space): """Sets the limit options of a matplotlib plot. Args: ax: matplotlib axes white_space(float): whitespace added to surround the tight limit of the data Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d """ 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.bounds ax.set_zlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) else: bounds = ax.dataLim.bounds assert not any(map(np.isinf, bounds)), 'Cannot set bounds if dataLim has infinite elements' 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)
python
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.bounds ax.set_zlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) else: bounds = ax.dataLim.bounds assert not any(map(np.isinf, bounds)), 'Cannot set bounds if dataLim has infinite elements' 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)
[ "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", ".", "bounds", "ax", ".", "set_zlim", "(", "bounds", "[", "0", "]", "-", "white_space", ",", "bounds", "[", "0", "]", "+", "bounds", "[", "2", "]", "+", "white_space", ")", "else", ":", "bounds", "=", "ax", ".", "dataLim", ".", "bounds", "assert", "not", "any", "(", "map", "(", "np", ".", "isinf", ",", "bounds", ")", ")", ",", "'Cannot set bounds if dataLim has infinite elements'", "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", ")" ]
Sets the limit options of a matplotlib plot. Args: ax: matplotlib axes white_space(float): whitespace added to surround the tight limit of the data Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d
[ "Sets", "the", "limit", "options", "of", "a", "matplotlib", "plot", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L312-L333
BlueBrain/NeuroM
neurom/view/common.py
plot_legend
def plot_legend(ax, no_legend=True, legend_arg=None): """ Function that defines the legend options of a matplotlib plot. Args: ax: matplotlib axes no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call """ legend_arg = dict_if_none(legend_arg) if not no_legend: ax.legend(**legend_arg)
python
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)
[ "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. Args: ax: matplotlib axes no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call
[ "Function", "that", "defines", "the", "legend", "options", "of", "a", "matplotlib", "plot", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L336-L349
BlueBrain/NeuroM
neurom/view/common.py
_get_normals
def _get_normals(v): '''get two vectors that form a basis w/ v Note: returned vectors are unit ''' not_v = np.array([1, 0, 0]) if np.all(np.abs(v) == not_v): not_v = np.array([0, 1, 0]) n1 = np.cross(v, not_v) n1 /= norm(n1) n2 = np.cross(v, n1) return n1, n2
python
def _get_normals(v): not_v = np.array([1, 0, 0]) if np.all(np.abs(v) == not_v): not_v = np.array([0, 1, 0]) n1 = np.cross(v, not_v) n1 /= norm(n1) n2 = np.cross(v, n1) return n1, n2
[ "def", "_get_normals", "(", "v", ")", ":", "not_v", "=", "np", ".", "array", "(", "[", "1", ",", "0", ",", "0", "]", ")", "if", "np", ".", "all", "(", "np", ".", "abs", "(", "v", ")", "==", "not_v", ")", ":", "not_v", "=", "np", ".", "array", "(", "[", "0", ",", "1", ",", "0", "]", ")", "n1", "=", "np", ".", "cross", "(", "v", ",", "not_v", ")", "n1", "/=", "norm", "(", "n1", ")", "n2", "=", "np", ".", "cross", "(", "v", ",", "n1", ")", "return", "n1", ",", "n2" ]
get two vectors that form a basis w/ v Note: returned vectors are unit
[ "get", "two", "vectors", "that", "form", "a", "basis", "w", "/", "v" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L355-L366
BlueBrain/NeuroM
neurom/view/common.py
generate_cylindrical_points
def generate_cylindrical_points(start, end, start_radius, end_radius, linspace_count=_LINSPACE_COUNT): '''Generate a 3d mesh of a cylinder with start and end points, and varying radius Based on: http://stackoverflow.com/a/32383775 ''' v = end - start length = norm(v) v = v / length n1, n2 = _get_normals(v) # pylint: disable=unbalanced-tuple-unpacking l, theta = np.meshgrid(np.linspace(0, length, linspace_count), np.linspace(0, 2 * np.pi, linspace_count)) radii = np.linspace(start_radius, end_radius, linspace_count) rsin = np.multiply(radii, np.sin(theta)) rcos = np.multiply(radii, np.cos(theta)) return np.array([start[i] + v[i] * l + n1[i] * rsin + n2[i] * rcos for i in range(3)])
python
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)) radii = np.linspace(start_radius, end_radius, linspace_count) rsin = np.multiply(radii, np.sin(theta)) rcos = np.multiply(radii, np.cos(theta)) return np.array([start[i] + v[i] * l + n1[i] * rsin + n2[i] * rcos for i in range(3)])
[ "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", ")", "# pylint: disable=unbalanced-tuple-unpacking", "l", ",", "theta", "=", "np", ".", "meshgrid", "(", "np", ".", "linspace", "(", "0", ",", "length", ",", "linspace_count", ")", ",", "np", ".", "linspace", "(", "0", ",", "2", "*", "np", ".", "pi", ",", "linspace_count", ")", ")", "radii", "=", "np", ".", "linspace", "(", "start_radius", ",", "end_radius", ",", "linspace_count", ")", "rsin", "=", "np", ".", "multiply", "(", "radii", ",", "np", ".", "sin", "(", "theta", ")", ")", "rcos", "=", "np", ".", "multiply", "(", "radii", ",", "np", ".", "cos", "(", "theta", ")", ")", "return", "np", ".", "array", "(", "[", "start", "[", "i", "]", "+", "v", "[", "i", "]", "*", "l", "+", "n1", "[", "i", "]", "*", "rsin", "+", "n2", "[", "i", "]", "*", "rcos", "for", "i", "in", "range", "(", "3", ")", "]", ")" ]
Generate a 3d mesh of a cylinder with start and end points, and varying radius Based on: http://stackoverflow.com/a/32383775
[ "Generate", "a", "3d", "mesh", "of", "a", "cylinder", "with", "start", "and", "end", "points", "and", "varying", "radius" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L369-L391
BlueBrain/NeuroM
neurom/view/common.py
project_cylinder_onto_2d
def project_cylinder_onto_2d(ax, plane, start, end, start_radius, end_radius, color='black', alpha=1.): '''take cylinder defined by start/end, and project it onto the plane Args: ax: matplotlib axes plane(tuple of int): where x, y, z = 0, 1, 2, so (0, 1) is the xy axis start(np.array): start coordinates end(np.array): end coordinates start_radius(float): start radius end_radius(float): end radius color: matplotlib color alpha(float): alpha value Note: There are probably more efficient ways of doing this: here the 3d outline is calculated, the non-used plane coordinates are dropped, a tight convex hull is found, and that is used for a filled polygon ''' points = generate_cylindrical_points(start, end, start_radius, end_radius, 10) points = np.vstack([points[plane[0]].ravel(), points[plane[1]].ravel()]) points = points.T hull = ConvexHull(points) ax.add_patch(Polygon(points[hull.vertices], fill=True, color=color, alpha=alpha))
python
def project_cylinder_onto_2d(ax, plane, start, end, start_radius, end_radius, color='black', alpha=1.): points = generate_cylindrical_points(start, end, start_radius, end_radius, 10) points = np.vstack([points[plane[0]].ravel(), points[plane[1]].ravel()]) points = points.T hull = ConvexHull(points) ax.add_patch(Polygon(points[hull.vertices], fill=True, color=color, alpha=alpha))
[ "def", "project_cylinder_onto_2d", "(", "ax", ",", "plane", ",", "start", ",", "end", ",", "start_radius", ",", "end_radius", ",", "color", "=", "'black'", ",", "alpha", "=", "1.", ")", ":", "points", "=", "generate_cylindrical_points", "(", "start", ",", "end", ",", "start_radius", ",", "end_radius", ",", "10", ")", "points", "=", "np", ".", "vstack", "(", "[", "points", "[", "plane", "[", "0", "]", "]", ".", "ravel", "(", ")", ",", "points", "[", "plane", "[", "1", "]", "]", ".", "ravel", "(", ")", "]", ")", "points", "=", "points", ".", "T", "hull", "=", "ConvexHull", "(", "points", ")", "ax", ".", "add_patch", "(", "Polygon", "(", "points", "[", "hull", ".", "vertices", "]", ",", "fill", "=", "True", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ")", ")" ]
take cylinder defined by start/end, and project it onto the plane Args: ax: matplotlib axes plane(tuple of int): where x, y, z = 0, 1, 2, so (0, 1) is the xy axis start(np.array): start coordinates end(np.array): end coordinates start_radius(float): start radius end_radius(float): end radius color: matplotlib color alpha(float): alpha value Note: There are probably more efficient ways of doing this: here the 3d outline is calculated, the non-used plane coordinates are dropped, a tight convex hull is found, and that is used for a filled polygon
[ "take", "cylinder", "defined", "by", "start", "/", "end", "and", "project", "it", "onto", "the", "plane" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L394-L418
BlueBrain/NeuroM
neurom/view/common.py
plot_cylinder
def plot_cylinder(ax, start, end, start_radius, end_radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): '''plot a 3d cylinder''' 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) ax.plot_surface(x, y, z, color=color, alpha=alpha)
python
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) ax.plot_surface(x, y, z, color=color, alpha=alpha)
[ "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", ")", "ax", ".", "plot_surface", "(", "x", ",", "y", ",", "z", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ")" ]
plot a 3d cylinder
[ "plot", "a", "3d", "cylinder" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L421-L427
BlueBrain/NeuroM
neurom/view/common.py
plot_sphere
def plot_sphere(ax, center, radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): """ Plots a 3d sphere, given the center and the radius. """ 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] + radius * np.outer(np.sin(u), sin_v) z = center[2] + radius * np.outer(np.ones_like(u), np.cos(v)) ax.plot_surface(x, y, z, linewidth=0.0, color=color, alpha=alpha)
python
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] + radius * np.outer(np.sin(u), sin_v) z = center[2] + radius * np.outer(np.ones_like(u), np.cos(v)) ax.plot_surface(x, y, z, linewidth=0.0, color=color, alpha=alpha)
[ "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", "]", "+", "radius", "*", "np", ".", "outer", "(", "np", ".", "sin", "(", "u", ")", ",", "sin_v", ")", "z", "=", "center", "[", "2", "]", "+", "radius", "*", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "u", ")", ",", "np", ".", "cos", "(", "v", ")", ")", "ax", ".", "plot_surface", "(", "x", ",", "y", ",", "z", ",", "linewidth", "=", "0.0", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ")" ]
Plots a 3d sphere, given the center and the radius.
[ "Plots", "a", "3d", "sphere", "given", "the", "center", "and", "the", "radius", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L430-L440
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_sequential_ids
def has_sequential_ids(data_wrapper): '''Check that IDs are increasing and consecutive returns tuple (bool, list of IDs that are not consecutive with their predecessor) ''' 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)
python
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)
[ "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 returns tuple (bool, list of IDs that are not consecutive with their predecessor)
[ "Check", "that", "IDs", "are", "increasing", "and", "consecutive" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L39-L48
BlueBrain/NeuroM
neurom/check/structural_checks.py
no_missing_parents
def no_missing_parents(data_wrapper): '''Check that all points have existing parents Point's parent ID must exist and parent must be declared before child. Returns: CheckResult with result and list of IDs that have no parent ''' 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)
python
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)
[ "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. Returns: CheckResult with result and list of IDs that have no parent
[ "Check", "that", "all", "points", "have", "existing", "parents", "Point", "s", "parent", "ID", "must", "exist", "and", "parent", "must", "be", "declared", "before", "child", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L51-L61
BlueBrain/NeuroM
neurom/check/structural_checks.py
is_single_tree
def is_single_tree(data_wrapper): '''Check that data forms a single tree Only the first point has ID of -1. Returns: CheckResult with result and list of IDs Note: This assumes no_missing_parents passed. ''' db = data_wrapper.data_block bad_ids = db[db[:, COLS.P] == -1][1:, COLS.ID] return CheckResult(len(bad_ids) == 0, bad_ids.tolist())
python
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())
[ "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 Only the first point has ID of -1. Returns: CheckResult with result and list of IDs Note: This assumes no_missing_parents passed.
[ "Check", "that", "data", "forms", "a", "single", "tree" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L64-L77
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_soma_points
def has_soma_points(data_wrapper): '''Checks if the TYPE column of raw data block has an element of type soma Returns: CheckResult with result ''' db = data_wrapper.data_block return CheckResult(POINT_TYPE.SOMA in db[:, COLS.TYPE], None)
python
def has_soma_points(data_wrapper): db = data_wrapper.data_block return CheckResult(POINT_TYPE.SOMA in db[:, COLS.TYPE], None)
[ "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 Returns: CheckResult with result
[ "Checks", "if", "the", "TYPE", "column", "of", "raw", "data", "block", "has", "an", "element", "of", "type", "soma" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L93-L100
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_all_finite_radius_neurites
def has_all_finite_radius_neurites(data_wrapper, threshold=0.0): '''Check that all points with neurite type have a finite radius Returns: CheckResult with result and list of IDs of neurite points with zero radius ''' 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).tolist() return CheckResult(len(bad_pts) == 0, bad_pts)
python
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).tolist() return CheckResult(len(bad_pts) == 0, bad_pts)
[ "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", ")", ".", "tolist", "(", ")", "return", "CheckResult", "(", "len", "(", "bad_pts", ")", "==", "0", ",", "bad_pts", ")" ]
Check that all points with neurite type have a finite radius Returns: CheckResult with result and list of IDs of neurite points with zero radius
[ "Check", "that", "all", "points", "with", "neurite", "type", "have", "a", "finite", "radius" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L103-L114
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_valid_soma
def has_valid_soma(data_wrapper): '''Check if a data block has a valid soma Returns: CheckResult with result ''' try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
python
def has_valid_soma(data_wrapper): try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
[ "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 Returns: CheckResult with result
[ "Check", "if", "a", "data", "block", "has", "a", "valid", "soma" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L117-L127
BlueBrain/NeuroM
doc/source/conf.py
_pelita_member_filter
def _pelita_member_filter(parent_name, item_names): """ Filter a list of autodoc items for which to generate documentation. Include only imports that come from the documented module or its submodules. """ 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 (location + ".").startswith(parent_name + "."): filtered_names.append(item_name) return filtered_names
python
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 (location + ".").startswith(parent_name + "."): filtered_names.append(item_name) return filtered_names
[ "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", "(", "location", "+", "\".\"", ")", ".", "startswith", "(", "parent_name", "+", "\".\"", ")", ":", "filtered_names", ".", "append", "(", "item_name", ")", "return", "filtered_names" ]
Filter a list of autodoc items for which to generate documentation. Include only imports that come from the documented module or its submodules.
[ "Filter", "a", "list", "of", "autodoc", "items", "for", "which", "to", "generate", "documentation", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/doc/source/conf.py#L158-L179
BlueBrain/NeuroM
examples/boxplot.py
boxplot
def boxplot(neurons, feature, new_fig=True, subplot=False): ''' Plot a histogram of the selected feature for the population of neurons. Plots x-axis versus y-axis on a scatter|histogram|binned values plot. More information about the plot and how it works. Parameters ---------- neurons : list List of Neurons. Single neurons must be encapsulated in a list. feature : str The feature of interest. Options ------- subplot : bool Default is False, which returns a matplotlib figure object. If True, returns a matplotlib axis object, for use as a subplot. ''' feature_values = [getattr(neu, 'get_' + feature)() for neu in neurons] _, ax = common.get_figure(new_fig=new_fig, subplot=subplot) ax.boxplot(feature_values) x_labels = ['neuron_id' for _ in neurons] ax.set_xticklabels(x_labels)
python
def boxplot(neurons, feature, new_fig=True, subplot=False): feature_values = [getattr(neu, 'get_' + feature)() for neu in neurons] _, ax = common.get_figure(new_fig=new_fig, subplot=subplot) ax.boxplot(feature_values) x_labels = ['neuron_id' for _ in neurons] ax.set_xticklabels(x_labels)
[ "def", "boxplot", "(", "neurons", ",", "feature", ",", "new_fig", "=", "True", ",", "subplot", "=", "False", ")", ":", "feature_values", "=", "[", "getattr", "(", "neu", ",", "'get_'", "+", "feature", ")", "(", ")", "for", "neu", "in", "neurons", "]", "_", ",", "ax", "=", "common", ".", "get_figure", "(", "new_fig", "=", "new_fig", ",", "subplot", "=", "subplot", ")", "ax", ".", "boxplot", "(", "feature_values", ")", "x_labels", "=", "[", "'neuron_id'", "for", "_", "in", "neurons", "]", "ax", ".", "set_xticklabels", "(", "x_labels", ")" ]
Plot a histogram of the selected feature for the population of neurons. Plots x-axis versus y-axis on a scatter|histogram|binned values plot. More information about the plot and how it works. Parameters ---------- neurons : list List of Neurons. Single neurons must be encapsulated in a list. feature : str The feature of interest. Options ------- subplot : bool Default is False, which returns a matplotlib figure object. If True, returns a matplotlib axis object, for use as a subplot.
[ "Plot", "a", "histogram", "of", "the", "selected", "feature", "for", "the", "population", "of", "neurons", ".", "Plots", "x", "-", "axis", "versus", "y", "-", "axis", "on", "a", "scatter|histogram|binned", "values", "plot", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/boxplot.py#L36-L67
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_axon
def has_axon(neuron, treefun=_read_neurite_type): '''Check if a neuron has an axon Arguments: neuron(Neuron): The neuron object to test treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result ''' return CheckResult(NeuriteType.axon in (treefun(n) for n in neuron.neurites))
python
def has_axon(neuron, treefun=_read_neurite_type): return CheckResult(NeuriteType.axon in (treefun(n) for n in neuron.neurites))
[ "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 Arguments: neuron(Neuron): The neuron object to test treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result
[ "Check", "if", "a", "neuron", "has", "an", "axon" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L54-L65
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_apical_dendrite
def has_apical_dendrite(neuron, min_number=1, treefun=_read_neurite_type): '''Check if a neuron has apical dendrites Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of apical dendrites required treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result ''' types = [treefun(n) for n in neuron.neurites] return CheckResult(types.count(NeuriteType.apical_dendrite) >= min_number)
python
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)
[ "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 Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of apical dendrites required treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result
[ "Check", "if", "a", "neuron", "has", "apical", "dendrites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L68-L81
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_basal_dendrite
def has_basal_dendrite(neuron, min_number=1, treefun=_read_neurite_type): '''Check if a neuron has basal dendrites Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of basal dendrites required treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result ''' types = [treefun(n) for n in neuron.neurites] return CheckResult(types.count(NeuriteType.basal_dendrite) >= min_number)
python
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)
[ "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 Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of basal dendrites required treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result
[ "Check", "if", "a", "neuron", "has", "basal", "dendrites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L84-L97
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_no_flat_neurites
def has_no_flat_neurites(neuron, tol=0.1, method='ratio'): '''Check that a neuron has no flat neurites Arguments: neuron(Neuron): The neuron object to test tol(float): tolerance method(string): way of determining flatness, 'tolerance', 'ratio' \ as described in :meth:`neurom.check.morphtree.get_flat_neurites` Returns: CheckResult with result ''' return CheckResult(len(get_flat_neurites(neuron, tol, method)) == 0)
python
def has_no_flat_neurites(neuron, tol=0.1, method='ratio'): return CheckResult(len(get_flat_neurites(neuron, tol, method)) == 0)
[ "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 Arguments: neuron(Neuron): The neuron object to test tol(float): tolerance method(string): way of determining flatness, 'tolerance', 'ratio' \ as described in :meth:`neurom.check.morphtree.get_flat_neurites` Returns: CheckResult with result
[ "Check", "that", "a", "neuron", "has", "no", "flat", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L100-L112
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_all_nonzero_segment_lengths
def has_all_nonzero_segment_lengths(neuron, threshold=0.0): '''Check presence of neuron segments with length not above threshold Arguments: neuron(Neuron): The neuron object to test threshold(float): value above which a segment length is considered to be non-zero Returns: CheckResult with result including list of (section_id, segment_id) of zero length segments ''' 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) == 0, bad_ids)
python
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) == 0, bad_ids)
[ "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", ")", "==", "0", ",", "bad_ids", ")" ]
Check presence of neuron segments with length not above threshold Arguments: neuron(Neuron): The neuron object to test threshold(float): value above which a segment length is considered to be non-zero Returns: CheckResult with result including list of (section_id, segment_id) of zero length segments
[ "Check", "presence", "of", "neuron", "segments", "with", "length", "not", "above", "threshold" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L128-L147
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_all_nonzero_section_lengths
def has_all_nonzero_section_lengths(neuron, threshold=0.0): '''Check presence of neuron sections with length not above threshold Arguments: neuron(Neuron): The neuron object to test threshold(float): value above which a section length is considered to be non-zero Returns: CheckResult with result including list of ids of bad sections ''' 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)
python
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)
[ "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 Arguments: neuron(Neuron): The neuron object to test threshold(float): value above which a section length is considered to be non-zero Returns: CheckResult with result including list of ids of bad sections
[ "Check", "presence", "of", "neuron", "sections", "with", "length", "not", "above", "threshold" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L150-L164
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_all_nonzero_neurite_radii
def has_all_nonzero_neurite_radii(neuron, threshold=0.0): '''Check presence of neurite points with radius not above threshold Arguments: neuron(Neuron): The neuron object to test threshold: value above which a radius is considered to be non-zero Returns: CheckResult with result including list of (section ID, point ID) pairs of zero-radius points ''' 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 CheckResult(len(bad_ids) == 0, bad_ids)
python
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 CheckResult(len(bad_ids) == 0, bad_ids)
[ "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", "CheckResult", "(", "len", "(", "bad_ids", ")", "==", "0", ",", "bad_ids", ")" ]
Check presence of neurite points with radius not above threshold Arguments: neuron(Neuron): The neuron object to test threshold: value above which a radius is considered to be non-zero Returns: CheckResult with result including list of (section ID, point ID) pairs of zero-radius points
[ "Check", "presence", "of", "neurite", "points", "with", "radius", "not", "above", "threshold" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L167-L187
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_no_jumps
def has_no_jumps(neuron, max_distance=30.0, axis='z'): '''Check if there are jumps (large movements in the `axis`) Arguments: neuron(Neuron): The neuron object to test max_distance(float): value above which consecutive z-values are considered a jump axis(str): one of x/y/z, which axis to check for jumps Returns: CheckResult with result list of ids of bad sections ''' bad_ids = [] axis = {'x': COLS.X, 'y': COLS.Y, 'z': COLS.Z, }[axis.lower()] for neurite in iter_neurites(neuron): section_segment = ((sec, seg) for sec in iter_sections(neurite) for seg in iter_segments(sec)) for sec, (p0, p1) in islice(section_segment, 1, None): # Skip neurite root segment if max_distance < abs(p0[axis] - p1[axis]): bad_ids.append((sec.id, [p0, p1])) return CheckResult(len(bad_ids) == 0, bad_ids)
python
def has_no_jumps(neuron, max_distance=30.0, axis='z'): bad_ids = [] axis = {'x': COLS.X, 'y': COLS.Y, 'z': COLS.Z, }[axis.lower()] for neurite in iter_neurites(neuron): section_segment = ((sec, seg) for sec in iter_sections(neurite) for seg in iter_segments(sec)) for sec, (p0, p1) in islice(section_segment, 1, None): if max_distance < abs(p0[axis] - p1[axis]): bad_ids.append((sec.id, [p0, p1])) return CheckResult(len(bad_ids) == 0, bad_ids)
[ "def", "has_no_jumps", "(", "neuron", ",", "max_distance", "=", "30.0", ",", "axis", "=", "'z'", ")", ":", "bad_ids", "=", "[", "]", "axis", "=", "{", "'x'", ":", "COLS", ".", "X", ",", "'y'", ":", "COLS", ".", "Y", ",", "'z'", ":", "COLS", ".", "Z", ",", "}", "[", "axis", ".", "lower", "(", ")", "]", "for", "neurite", "in", "iter_neurites", "(", "neuron", ")", ":", "section_segment", "=", "(", "(", "sec", ",", "seg", ")", "for", "sec", "in", "iter_sections", "(", "neurite", ")", "for", "seg", "in", "iter_segments", "(", "sec", ")", ")", "for", "sec", ",", "(", "p0", ",", "p1", ")", "in", "islice", "(", "section_segment", ",", "1", ",", "None", ")", ":", "# Skip neurite root segment", "if", "max_distance", "<", "abs", "(", "p0", "[", "axis", "]", "-", "p1", "[", "axis", "]", ")", ":", "bad_ids", ".", "append", "(", "(", "sec", ".", "id", ",", "[", "p0", ",", "p1", "]", ")", ")", "return", "CheckResult", "(", "len", "(", "bad_ids", ")", "==", "0", ",", "bad_ids", ")" ]
Check if there are jumps (large movements in the `axis`) Arguments: neuron(Neuron): The neuron object to test max_distance(float): value above which consecutive z-values are considered a jump axis(str): one of x/y/z, which axis to check for jumps Returns: CheckResult with result list of ids of bad sections
[ "Check", "if", "there", "are", "jumps", "(", "large", "movements", "in", "the", "axis", ")" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L203-L223
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_no_fat_ends
def has_no_fat_ends(neuron, multiple_of_mean=2.0, final_point_count=5): '''Check if leaf points are too large Arguments: neuron(Neuron): The neuron object to test multiple_of_mean(float): how many times larger the final radius has to be compared to the mean of the final points final_point_count(int): how many points to include in the mean Returns: CheckResult with result list of ids of bad sections Note: A fat end is defined as a leaf segment whose last point is larger by a factor of `multiple_of_mean` than the mean of the points in `final_point_count` ''' bad_ids = [] for leaf in _nf.iter_sections(neuron.neurites, iterator_type=Tree.ileaf): mean_radius = np.mean(leaf.points[1:][-final_point_count:, COLS.R]) if mean_radius * multiple_of_mean <= leaf.points[-1, COLS.R]: bad_ids.append((leaf.id, leaf.points[-1:])) return CheckResult(len(bad_ids) == 0, bad_ids)
python
def has_no_fat_ends(neuron, multiple_of_mean=2.0, final_point_count=5): bad_ids = [] for leaf in _nf.iter_sections(neuron.neurites, iterator_type=Tree.ileaf): mean_radius = np.mean(leaf.points[1:][-final_point_count:, COLS.R]) if mean_radius * multiple_of_mean <= leaf.points[-1, COLS.R]: bad_ids.append((leaf.id, leaf.points[-1:])) return CheckResult(len(bad_ids) == 0, bad_ids)
[ "def", "has_no_fat_ends", "(", "neuron", ",", "multiple_of_mean", "=", "2.0", ",", "final_point_count", "=", "5", ")", ":", "bad_ids", "=", "[", "]", "for", "leaf", "in", "_nf", ".", "iter_sections", "(", "neuron", ".", "neurites", ",", "iterator_type", "=", "Tree", ".", "ileaf", ")", ":", "mean_radius", "=", "np", ".", "mean", "(", "leaf", ".", "points", "[", "1", ":", "]", "[", "-", "final_point_count", ":", ",", "COLS", ".", "R", "]", ")", "if", "mean_radius", "*", "multiple_of_mean", "<=", "leaf", ".", "points", "[", "-", "1", ",", "COLS", ".", "R", "]", ":", "bad_ids", ".", "append", "(", "(", "leaf", ".", "id", ",", "leaf", ".", "points", "[", "-", "1", ":", "]", ")", ")", "return", "CheckResult", "(", "len", "(", "bad_ids", ")", "==", "0", ",", "bad_ids", ")" ]
Check if leaf points are too large Arguments: neuron(Neuron): The neuron object to test multiple_of_mean(float): how many times larger the final radius has to be compared to the mean of the final points final_point_count(int): how many points to include in the mean Returns: CheckResult with result list of ids of bad sections Note: A fat end is defined as a leaf segment whose last point is larger by a factor of `multiple_of_mean` than the mean of the points in `final_point_count`
[ "Check", "if", "leaf", "points", "are", "too", "large" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L226-L250
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_no_narrow_start
def has_no_narrow_start(neuron, frac=0.9): '''Check if neurites have a narrow start Arguments: neuron(Neuron): The neuron object to test frac(float): Ratio that the second point must be smaller than the first Returns: CheckResult with a list of all first segments of neurites with a narrow start ''' bad_ids = [(neurite.root_node.id, [neurite.root_node.points[1]]) for neurite in neuron.neurites if neurite.root_node.points[1][COLS.R] < frac * neurite.root_node.points[2][COLS.R]] return CheckResult(len(bad_ids) == 0, bad_ids)
python
def has_no_narrow_start(neuron, frac=0.9): bad_ids = [(neurite.root_node.id, [neurite.root_node.points[1]]) for neurite in neuron.neurites if neurite.root_node.points[1][COLS.R] < frac * neurite.root_node.points[2][COLS.R]] return CheckResult(len(bad_ids) == 0, bad_ids)
[ "def", "has_no_narrow_start", "(", "neuron", ",", "frac", "=", "0.9", ")", ":", "bad_ids", "=", "[", "(", "neurite", ".", "root_node", ".", "id", ",", "[", "neurite", ".", "root_node", ".", "points", "[", "1", "]", "]", ")", "for", "neurite", "in", "neuron", ".", "neurites", "if", "neurite", ".", "root_node", ".", "points", "[", "1", "]", "[", "COLS", ".", "R", "]", "<", "frac", "*", "neurite", ".", "root_node", ".", "points", "[", "2", "]", "[", "COLS", ".", "R", "]", "]", "return", "CheckResult", "(", "len", "(", "bad_ids", ")", "==", "0", ",", "bad_ids", ")" ]
Check if neurites have a narrow start Arguments: neuron(Neuron): The neuron object to test frac(float): Ratio that the second point must be smaller than the first Returns: CheckResult with a list of all first segments of neurites with a narrow start
[ "Check", "if", "neurites", "have", "a", "narrow", "start" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L253-L266
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_no_dangling_branch
def has_no_dangling_branch(neuron): '''Check if the neuron has dangling neurites''' soma_center = neuron.soma.points[:, COLS.XYZ].mean(axis=0) recentered_soma = neuron.soma.points[:, COLS.XYZ] - soma_center radius = np.linalg.norm(recentered_soma, axis=1) soma_max_radius = radius.max() def is_dangling(neurite): '''Is the neurite dangling ?''' starting_point = neurite.points[1][COLS.XYZ] if np.linalg.norm(starting_point - soma_center) - soma_max_radius <= 12.: return False if neurite.type != NeuriteType.axon: return True all_points = list(chain.from_iterable(n.points[1:] for n in iter_neurites(neurite) if n.type != NeuriteType.axon)) res = [np.linalg.norm(starting_point - p[COLS.XYZ]) >= 2 * p[COLS.R] + 2 for p in all_points] return all(res) bad_ids = [(n.root_node.id, [n.root_node.points[1]]) for n in iter_neurites(neuron) if is_dangling(n)] return CheckResult(len(bad_ids) == 0, bad_ids)
python
def has_no_dangling_branch(neuron): soma_center = neuron.soma.points[:, COLS.XYZ].mean(axis=0) recentered_soma = neuron.soma.points[:, COLS.XYZ] - soma_center radius = np.linalg.norm(recentered_soma, axis=1) soma_max_radius = radius.max() def is_dangling(neurite): starting_point = neurite.points[1][COLS.XYZ] if np.linalg.norm(starting_point - soma_center) - soma_max_radius <= 12.: return False if neurite.type != NeuriteType.axon: return True all_points = list(chain.from_iterable(n.points[1:] for n in iter_neurites(neurite) if n.type != NeuriteType.axon)) res = [np.linalg.norm(starting_point - p[COLS.XYZ]) >= 2 * p[COLS.R] + 2 for p in all_points] return all(res) bad_ids = [(n.root_node.id, [n.root_node.points[1]]) for n in iter_neurites(neuron) if is_dangling(n)] return CheckResult(len(bad_ids) == 0, bad_ids)
[ "def", "has_no_dangling_branch", "(", "neuron", ")", ":", "soma_center", "=", "neuron", ".", "soma", ".", "points", "[", ":", ",", "COLS", ".", "XYZ", "]", ".", "mean", "(", "axis", "=", "0", ")", "recentered_soma", "=", "neuron", ".", "soma", ".", "points", "[", ":", ",", "COLS", ".", "XYZ", "]", "-", "soma_center", "radius", "=", "np", ".", "linalg", ".", "norm", "(", "recentered_soma", ",", "axis", "=", "1", ")", "soma_max_radius", "=", "radius", ".", "max", "(", ")", "def", "is_dangling", "(", "neurite", ")", ":", "'''Is the neurite dangling ?'''", "starting_point", "=", "neurite", ".", "points", "[", "1", "]", "[", "COLS", ".", "XYZ", "]", "if", "np", ".", "linalg", ".", "norm", "(", "starting_point", "-", "soma_center", ")", "-", "soma_max_radius", "<=", "12.", ":", "return", "False", "if", "neurite", ".", "type", "!=", "NeuriteType", ".", "axon", ":", "return", "True", "all_points", "=", "list", "(", "chain", ".", "from_iterable", "(", "n", ".", "points", "[", "1", ":", "]", "for", "n", "in", "iter_neurites", "(", "neurite", ")", "if", "n", ".", "type", "!=", "NeuriteType", ".", "axon", ")", ")", "res", "=", "[", "np", ".", "linalg", ".", "norm", "(", "starting_point", "-", "p", "[", "COLS", ".", "XYZ", "]", ")", ">=", "2", "*", "p", "[", "COLS", ".", "R", "]", "+", "2", "for", "p", "in", "all_points", "]", "return", "all", "(", "res", ")", "bad_ids", "=", "[", "(", "n", ".", "root_node", ".", "id", ",", "[", "n", ".", "root_node", ".", "points", "[", "1", "]", "]", ")", "for", "n", "in", "iter_neurites", "(", "neuron", ")", "if", "is_dangling", "(", "n", ")", "]", "return", "CheckResult", "(", "len", "(", "bad_ids", ")", "==", "0", ",", "bad_ids", ")" ]
Check if the neuron has dangling neurites
[ "Check", "if", "the", "neuron", "has", "dangling", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L269-L295
BlueBrain/NeuroM
neurom/check/neuron_checks.py
has_no_narrow_neurite_section
def has_no_narrow_neurite_section(neuron, neurite_filter, radius_threshold=0.05, considered_section_min_length=50): '''Check if the neuron has dendrites with narrow sections Arguments: neuron(Neuron): The neuron object to test neurite_filter(callable): filter the neurites by this callable radius_threshold(float): radii below this are considered narro considered_section_min_length(float): sections with length below this are not taken into account Returns: CheckResult with result. result.info contains the narrow section ids and their first point ''' considered_sections = (sec for sec in iter_sections(neuron, neurite_filter=neurite_filter) if sec.length > considered_section_min_length) def narrow_section(section): '''Select narrow sections''' return section.points[:, COLS.R].mean() < radius_threshold bad_ids = [(section.id, section.points[1]) for section in considered_sections if narrow_section(section)] return CheckResult(len(bad_ids) == 0, bad_ids)
python
def has_no_narrow_neurite_section(neuron, neurite_filter, radius_threshold=0.05, considered_section_min_length=50): considered_sections = (sec for sec in iter_sections(neuron, neurite_filter=neurite_filter) if sec.length > considered_section_min_length) def narrow_section(section): return section.points[:, COLS.R].mean() < radius_threshold bad_ids = [(section.id, section.points[1]) for section in considered_sections if narrow_section(section)] return CheckResult(len(bad_ids) == 0, bad_ids)
[ "def", "has_no_narrow_neurite_section", "(", "neuron", ",", "neurite_filter", ",", "radius_threshold", "=", "0.05", ",", "considered_section_min_length", "=", "50", ")", ":", "considered_sections", "=", "(", "sec", "for", "sec", "in", "iter_sections", "(", "neuron", ",", "neurite_filter", "=", "neurite_filter", ")", "if", "sec", ".", "length", ">", "considered_section_min_length", ")", "def", "narrow_section", "(", "section", ")", ":", "'''Select narrow sections'''", "return", "section", ".", "points", "[", ":", ",", "COLS", ".", "R", "]", ".", "mean", "(", ")", "<", "radius_threshold", "bad_ids", "=", "[", "(", "section", ".", "id", ",", "section", ".", "points", "[", "1", "]", ")", "for", "section", "in", "considered_sections", "if", "narrow_section", "(", "section", ")", "]", "return", "CheckResult", "(", "len", "(", "bad_ids", ")", "==", "0", ",", "bad_ids", ")" ]
Check if the neuron has dendrites with narrow sections Arguments: neuron(Neuron): The neuron object to test neurite_filter(callable): filter the neurites by this callable radius_threshold(float): radii below this are considered narro considered_section_min_length(float): sections with length below this are not taken into account Returns: CheckResult with result. result.info contains the narrow section ids and their first point
[ "Check", "if", "the", "neuron", "has", "dendrites", "with", "narrow", "sections" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/neuron_checks.py#L298-L325
BlueBrain/NeuroM
examples/synthesis_json.py
extract_data
def extract_data(neurons, feature, params=None): '''Extracts feature from a list of neurons and transforms the fitted distribution in the correct format. Returns the optimal distribution and corresponding parameters. Normal distribution params (mean, std) Exponential distribution params (loc, scale) Uniform distribution params (min, range) ''' if params is None: params = {} feature_data = [get(FEATURE_MAP[feature], n, **params) for n in neurons] feature_data = list(chain(*feature_data)) return stats.optimal_distribution(feature_data)
python
def extract_data(neurons, feature, params=None): if params is None: params = {} feature_data = [get(FEATURE_MAP[feature], n, **params) for n in neurons] feature_data = list(chain(*feature_data)) return stats.optimal_distribution(feature_data)
[ "def", "extract_data", "(", "neurons", ",", "feature", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "feature_data", "=", "[", "get", "(", "FEATURE_MAP", "[", "feature", "]", ",", "n", ",", "*", "*", "params", ")", "for", "n", "in", "neurons", "]", "feature_data", "=", "list", "(", "chain", "(", "*", "feature_data", ")", ")", "return", "stats", ".", "optimal_distribution", "(", "feature_data", ")" ]
Extracts feature from a list of neurons and transforms the fitted distribution in the correct format. Returns the optimal distribution and corresponding parameters. Normal distribution params (mean, std) Exponential distribution params (loc, scale) Uniform distribution params (min, range)
[ "Extracts", "feature", "from", "a", "list", "of", "neurons", "and", "transforms", "the", "fitted", "distribution", "in", "the", "correct", "format", ".", "Returns", "the", "optimal", "distribution", "and", "corresponding", "parameters", ".", "Normal", "distribution", "params", "(", "mean", "std", ")", "Exponential", "distribution", "params", "(", "loc", "scale", ")", "Uniform", "distribution", "params", "(", "min", "range", ")" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/synthesis_json.py#L76-L89
BlueBrain/NeuroM
examples/synthesis_json.py
transform_header
def transform_header(mtype_name): '''Add header to json output to wrap around distribution data. ''' head_dict = OrderedDict() head_dict["m-type"] = mtype_name head_dict["components"] = defaultdict(OrderedDict) return head_dict
python
def transform_header(mtype_name): head_dict = OrderedDict() head_dict["m-type"] = mtype_name head_dict["components"] = defaultdict(OrderedDict) return head_dict
[ "def", "transform_header", "(", "mtype_name", ")", ":", "head_dict", "=", "OrderedDict", "(", ")", "head_dict", "[", "\"m-type\"", "]", "=", "mtype_name", "head_dict", "[", "\"components\"", "]", "=", "defaultdict", "(", "OrderedDict", ")", "return", "head_dict" ]
Add header to json output to wrap around distribution data.
[ "Add", "header", "to", "json", "output", "to", "wrap", "around", "distribution", "data", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/synthesis_json.py#L92-L100
BlueBrain/NeuroM
examples/synthesis_json.py
transform_package
def transform_package(mtype, files, components): '''Put together header and list of data into one json output. feature_list contains all the information about the data to be extracted: features, feature_names, feature_components, feature_min, feature_max ''' data_dict = transform_header(mtype) neurons = load_neurons(files) for comp in components: params = PARAM_MAP[comp.name] for feature in comp.features: result = stats.fit_results_to_dict( extract_data(neurons, feature.name, params), feature.limits.min, feature.limits.max ) # When the distribution is normal with sigma = 0 # it will be replaced with constant if result['type'] == 'normal' and result['sigma'] == 0.0: replace_result = OrderedDict((('type', 'constant'), ('val', result['mu']))) result = replace_result data_dict["components"][comp.name].update({feature.name: result}) return data_dict
python
def transform_package(mtype, files, components): data_dict = transform_header(mtype) neurons = load_neurons(files) for comp in components: params = PARAM_MAP[comp.name] for feature in comp.features: result = stats.fit_results_to_dict( extract_data(neurons, feature.name, params), feature.limits.min, feature.limits.max ) if result['type'] == 'normal' and result['sigma'] == 0.0: replace_result = OrderedDict((('type', 'constant'), ('val', result['mu']))) result = replace_result data_dict["components"][comp.name].update({feature.name: result}) return data_dict
[ "def", "transform_package", "(", "mtype", ",", "files", ",", "components", ")", ":", "data_dict", "=", "transform_header", "(", "mtype", ")", "neurons", "=", "load_neurons", "(", "files", ")", "for", "comp", "in", "components", ":", "params", "=", "PARAM_MAP", "[", "comp", ".", "name", "]", "for", "feature", "in", "comp", ".", "features", ":", "result", "=", "stats", ".", "fit_results_to_dict", "(", "extract_data", "(", "neurons", ",", "feature", ".", "name", ",", "params", ")", ",", "feature", ".", "limits", ".", "min", ",", "feature", ".", "limits", ".", "max", ")", "# When the distribution is normal with sigma = 0", "# it will be replaced with constant", "if", "result", "[", "'type'", "]", "==", "'normal'", "and", "result", "[", "'sigma'", "]", "==", "0.0", ":", "replace_result", "=", "OrderedDict", "(", "(", "(", "'type'", ",", "'constant'", ")", ",", "(", "'val'", ",", "result", "[", "'mu'", "]", ")", ")", ")", "result", "=", "replace_result", "data_dict", "[", "\"components\"", "]", "[", "comp", ".", "name", "]", ".", "update", "(", "{", "feature", ".", "name", ":", "result", "}", ")", "return", "data_dict" ]
Put together header and list of data into one json output. feature_list contains all the information about the data to be extracted: features, feature_names, feature_components, feature_min, feature_max
[ "Put", "together", "header", "and", "list", "of", "data", "into", "one", "json", "output", ".", "feature_list", "contains", "all", "the", "information", "about", "the", "data", "to", "be", "extracted", ":", "features", "feature_names", "feature_components", "feature_min", "feature_max" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/synthesis_json.py#L103-L128
BlueBrain/NeuroM
examples/synthesis_json.py
parse_args
def parse_args(): '''Parse command line arguments''' parser = argparse.ArgumentParser( description='Morphology fit distribution extractor', epilog='Note: Outputs json of the optimal distribution \ and corresponding parameters.') parser.add_argument('datapaths', nargs='+', help='Morphology data directory paths') parser.add_argument('--mtype', choices=MTYPE_GETTERS.keys(), help='Get mtype from filename or parent directory') return parser.parse_args()
python
def parse_args(): parser = argparse.ArgumentParser( description='Morphology fit distribution extractor', epilog='Note: Outputs json of the optimal distribution \ and corresponding parameters.') parser.add_argument('datapaths', nargs='+', help='Morphology data directory paths') parser.add_argument('--mtype', choices=MTYPE_GETTERS.keys(), help='Get mtype from filename or parent directory') return parser.parse_args()
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Morphology fit distribution extractor'", ",", "epilog", "=", "'Note: Outputs json of the optimal distribution \\\n and corresponding parameters.'", ")", "parser", ".", "add_argument", "(", "'datapaths'", ",", "nargs", "=", "'+'", ",", "help", "=", "'Morphology data directory paths'", ")", "parser", ".", "add_argument", "(", "'--mtype'", ",", "choices", "=", "MTYPE_GETTERS", ".", "keys", "(", ")", ",", "help", "=", "'Get mtype from filename or parent directory'", ")", "return", "parser", ".", "parse_args", "(", ")" ]
Parse command line arguments
[ "Parse", "command", "line", "arguments" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/synthesis_json.py#L153-L167
BlueBrain/NeuroM
neurom/view/plotly.py
draw
def draw(obj, plane='3d', inline=False, **kwargs): '''Draw the morphology using in the given plane plane (str): a string representing the 2D plane (example: 'xy') or '3d', '3D' for a 3D view inline (bool): must be set to True for interactive ipython notebook plotting ''' if plane.lower() == '3d': return _plot_neuron3d(obj, inline, **kwargs) return _plot_neuron(obj, plane, inline, **kwargs)
python
def draw(obj, plane='3d', inline=False, **kwargs): if plane.lower() == '3d': return _plot_neuron3d(obj, inline, **kwargs) return _plot_neuron(obj, plane, inline, **kwargs)
[ "def", "draw", "(", "obj", ",", "plane", "=", "'3d'", ",", "inline", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "plane", ".", "lower", "(", ")", "==", "'3d'", ":", "return", "_plot_neuron3d", "(", "obj", ",", "inline", ",", "*", "*", "kwargs", ")", "return", "_plot_neuron", "(", "obj", ",", "plane", ",", "inline", ",", "*", "*", "kwargs", ")" ]
Draw the morphology using in the given plane plane (str): a string representing the 2D plane (example: 'xy') or '3d', '3D' for a 3D view inline (bool): must be set to True for interactive ipython notebook plotting
[ "Draw", "the", "morphology", "using", "in", "the", "given", "plane" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/plotly.py#L21-L31
BlueBrain/NeuroM
neurom/view/plotly.py
_plot_neuron3d
def _plot_neuron3d(neuron, inline, **kwargs): ''' Generates a figure of the neuron, that contains a soma and a list of trees. ''' return _plotly(neuron, plane='3d', title='neuron-3D', inline=inline, **kwargs)
python
def _plot_neuron3d(neuron, inline, **kwargs): return _plotly(neuron, plane='3d', title='neuron-3D', inline=inline, **kwargs)
[ "def", "_plot_neuron3d", "(", "neuron", ",", "inline", ",", "*", "*", "kwargs", ")", ":", "return", "_plotly", "(", "neuron", ",", "plane", "=", "'3d'", ",", "title", "=", "'neuron-3D'", ",", "inline", "=", "inline", ",", "*", "*", "kwargs", ")" ]
Generates a figure of the neuron, that contains a soma and a list of trees.
[ "Generates", "a", "figure", "of", "the", "neuron", "that", "contains", "a", "soma", "and", "a", "list", "of", "trees", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/plotly.py#L38-L43
BlueBrain/NeuroM
neurom/view/plotly.py
_make_trace
def _make_trace(neuron, plane): '''Create the trace to be plotted''' for neurite in iter_neurites(neuron): segments = list(iter_segments(neurite)) segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in segments] coords = dict(x=list(chain.from_iterable((p1[0], p2[0], None) for p1, p2 in segs)), y=list(chain.from_iterable((p1[1], p2[1], None) for p1, p2 in segs)), z=list(chain.from_iterable((p1[2], p2[2], None) for p1, p2 in segs))) color = TREE_COLOR.get(neurite.root_node.type, 'black') if plane.lower() == '3d': plot_fun = go.Scatter3d else: plot_fun = go.Scatter coords = dict(x=coords[plane[0]], y=coords[plane[1]]) yield plot_fun( line=dict(color=color, width=2), mode='lines', **coords )
python
def _make_trace(neuron, plane): for neurite in iter_neurites(neuron): segments = list(iter_segments(neurite)) segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in segments] coords = dict(x=list(chain.from_iterable((p1[0], p2[0], None) for p1, p2 in segs)), y=list(chain.from_iterable((p1[1], p2[1], None) for p1, p2 in segs)), z=list(chain.from_iterable((p1[2], p2[2], None) for p1, p2 in segs))) color = TREE_COLOR.get(neurite.root_node.type, 'black') if plane.lower() == '3d': plot_fun = go.Scatter3d else: plot_fun = go.Scatter coords = dict(x=coords[plane[0]], y=coords[plane[1]]) yield plot_fun( line=dict(color=color, width=2), mode='lines', **coords )
[ "def", "_make_trace", "(", "neuron", ",", "plane", ")", ":", "for", "neurite", "in", "iter_neurites", "(", "neuron", ")", ":", "segments", "=", "list", "(", "iter_segments", "(", "neurite", ")", ")", "segs", "=", "[", "(", "s", "[", "0", "]", "[", "COLS", ".", "XYZ", "]", ",", "s", "[", "1", "]", "[", "COLS", ".", "XYZ", "]", ")", "for", "s", "in", "segments", "]", "coords", "=", "dict", "(", "x", "=", "list", "(", "chain", ".", "from_iterable", "(", "(", "p1", "[", "0", "]", ",", "p2", "[", "0", "]", ",", "None", ")", "for", "p1", ",", "p2", "in", "segs", ")", ")", ",", "y", "=", "list", "(", "chain", ".", "from_iterable", "(", "(", "p1", "[", "1", "]", ",", "p2", "[", "1", "]", ",", "None", ")", "for", "p1", ",", "p2", "in", "segs", ")", ")", ",", "z", "=", "list", "(", "chain", ".", "from_iterable", "(", "(", "p1", "[", "2", "]", ",", "p2", "[", "2", "]", ",", "None", ")", "for", "p1", ",", "p2", "in", "segs", ")", ")", ")", "color", "=", "TREE_COLOR", ".", "get", "(", "neurite", ".", "root_node", ".", "type", ",", "'black'", ")", "if", "plane", ".", "lower", "(", ")", "==", "'3d'", ":", "plot_fun", "=", "go", ".", "Scatter3d", "else", ":", "plot_fun", "=", "go", ".", "Scatter", "coords", "=", "dict", "(", "x", "=", "coords", "[", "plane", "[", "0", "]", "]", ",", "y", "=", "coords", "[", "plane", "[", "1", "]", "]", ")", "yield", "plot_fun", "(", "line", "=", "dict", "(", "color", "=", "color", ",", "width", "=", "2", ")", ",", "mode", "=", "'lines'", ",", "*", "*", "coords", ")" ]
Create the trace to be plotted
[ "Create", "the", "trace", "to", "be", "plotted" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/plotly.py#L46-L67
BlueBrain/NeuroM
neurom/view/plotly.py
get_figure
def get_figure(neuron, plane, title): '''Returns the plotly figure containing the neuron''' data = list(_make_trace(neuron, plane)) axis = dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ) if plane != '3d': soma_2d = [ # filled circle { 'type': 'circle', 'xref': 'x', 'yref': 'y', 'fillcolor': 'rgba(50, 171, 96, 0.7)', 'x0': neuron.soma.center[0] - neuron.soma.radius, 'y0': neuron.soma.center[1] - neuron.soma.radius, 'x1': neuron.soma.center[0] + neuron.soma.radius, 'y1': neuron.soma.center[1] + neuron.soma.radius, 'line': { 'color': 'rgba(50, 171, 96, 1)', }, }, ] else: soma_2d = [] theta = np.linspace(0, 2 * np.pi, 100) phi = np.linspace(0, np.pi, 100) z = np.outer(np.ones(100), np.cos(phi)) + neuron.soma.center[2] r = neuron.soma.radius data.append( go.Surface( x=(np.outer(np.cos(theta), np.sin(phi)) + neuron.soma.center[0]) * r, y=(np.outer(np.sin(theta), np.sin(phi)) + neuron.soma.center[1]) * r, z=z * r, cauto=False, surfacecolor=['black'] * len(z), showscale=False, ) ) layout = dict( autosize=True, title=title, scene=dict( # This is used for 3D plots xaxis=axis, yaxis=axis, zaxis=axis, camera=dict(up=dict(x=0, y=0, z=1), eye=dict(x=-1.7428, y=1.0707, z=0.7100,)), aspectmode='data' ), yaxis=dict(scaleanchor="x"), # This is used for 2D plots shapes=soma_2d, ) res = dict(data=data, layout=layout) return res
python
def get_figure(neuron, plane, title): data = list(_make_trace(neuron, plane)) axis = dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ) if plane != '3d': soma_2d = [ { 'type': 'circle', 'xref': 'x', 'yref': 'y', 'fillcolor': 'rgba(50, 171, 96, 0.7)', 'x0': neuron.soma.center[0] - neuron.soma.radius, 'y0': neuron.soma.center[1] - neuron.soma.radius, 'x1': neuron.soma.center[0] + neuron.soma.radius, 'y1': neuron.soma.center[1] + neuron.soma.radius, 'line': { 'color': 'rgba(50, 171, 96, 1)', }, }, ] else: soma_2d = [] theta = np.linspace(0, 2 * np.pi, 100) phi = np.linspace(0, np.pi, 100) z = np.outer(np.ones(100), np.cos(phi)) + neuron.soma.center[2] r = neuron.soma.radius data.append( go.Surface( x=(np.outer(np.cos(theta), np.sin(phi)) + neuron.soma.center[0]) * r, y=(np.outer(np.sin(theta), np.sin(phi)) + neuron.soma.center[1]) * r, z=z * r, cauto=False, surfacecolor=['black'] * len(z), showscale=False, ) ) layout = dict( autosize=True, title=title, scene=dict( xaxis=axis, yaxis=axis, zaxis=axis, camera=dict(up=dict(x=0, y=0, z=1), eye=dict(x=-1.7428, y=1.0707, z=0.7100,)), aspectmode='data' ), yaxis=dict(scaleanchor="x"), shapes=soma_2d, ) res = dict(data=data, layout=layout) return res
[ "def", "get_figure", "(", "neuron", ",", "plane", ",", "title", ")", ":", "data", "=", "list", "(", "_make_trace", "(", "neuron", ",", "plane", ")", ")", "axis", "=", "dict", "(", "gridcolor", "=", "'rgb(255, 255, 255)'", ",", "zerolinecolor", "=", "'rgb(255, 255, 255)'", ",", "showbackground", "=", "True", ",", "backgroundcolor", "=", "'rgb(230, 230,230)'", ")", "if", "plane", "!=", "'3d'", ":", "soma_2d", "=", "[", "# filled circle", "{", "'type'", ":", "'circle'", ",", "'xref'", ":", "'x'", ",", "'yref'", ":", "'y'", ",", "'fillcolor'", ":", "'rgba(50, 171, 96, 0.7)'", ",", "'x0'", ":", "neuron", ".", "soma", ".", "center", "[", "0", "]", "-", "neuron", ".", "soma", ".", "radius", ",", "'y0'", ":", "neuron", ".", "soma", ".", "center", "[", "1", "]", "-", "neuron", ".", "soma", ".", "radius", ",", "'x1'", ":", "neuron", ".", "soma", ".", "center", "[", "0", "]", "+", "neuron", ".", "soma", ".", "radius", ",", "'y1'", ":", "neuron", ".", "soma", ".", "center", "[", "1", "]", "+", "neuron", ".", "soma", ".", "radius", ",", "'line'", ":", "{", "'color'", ":", "'rgba(50, 171, 96, 1)'", ",", "}", ",", "}", ",", "]", "else", ":", "soma_2d", "=", "[", "]", "theta", "=", "np", ".", "linspace", "(", "0", ",", "2", "*", "np", ".", "pi", ",", "100", ")", "phi", "=", "np", ".", "linspace", "(", "0", ",", "np", ".", "pi", ",", "100", ")", "z", "=", "np", ".", "outer", "(", "np", ".", "ones", "(", "100", ")", ",", "np", ".", "cos", "(", "phi", ")", ")", "+", "neuron", ".", "soma", ".", "center", "[", "2", "]", "r", "=", "neuron", ".", "soma", ".", "radius", "data", ".", "append", "(", "go", ".", "Surface", "(", "x", "=", "(", "np", ".", "outer", "(", "np", ".", "cos", "(", "theta", ")", ",", "np", ".", "sin", "(", "phi", ")", ")", "+", "neuron", ".", "soma", ".", "center", "[", "0", "]", ")", "*", "r", ",", "y", "=", "(", "np", ".", "outer", "(", "np", ".", "sin", "(", "theta", ")", ",", "np", ".", "sin", "(", "phi", ")", ")", "+", "neuron", ".", "soma", ".", "center", "[", "1", "]", ")", "*", "r", ",", "z", "=", "z", "*", "r", ",", "cauto", "=", "False", ",", "surfacecolor", "=", "[", "'black'", "]", "*", "len", "(", "z", ")", ",", "showscale", "=", "False", ",", ")", ")", "layout", "=", "dict", "(", "autosize", "=", "True", ",", "title", "=", "title", ",", "scene", "=", "dict", "(", "# This is used for 3D plots", "xaxis", "=", "axis", ",", "yaxis", "=", "axis", ",", "zaxis", "=", "axis", ",", "camera", "=", "dict", "(", "up", "=", "dict", "(", "x", "=", "0", ",", "y", "=", "0", ",", "z", "=", "1", ")", ",", "eye", "=", "dict", "(", "x", "=", "-", "1.7428", ",", "y", "=", "1.0707", ",", "z", "=", "0.7100", ",", ")", ")", ",", "aspectmode", "=", "'data'", ")", ",", "yaxis", "=", "dict", "(", "scaleanchor", "=", "\"x\"", ")", ",", "# This is used for 2D plots", "shapes", "=", "soma_2d", ",", ")", "res", "=", "dict", "(", "data", "=", "data", ",", "layout", "=", "layout", ")", "return", "res" ]
Returns the plotly figure containing the neuron
[ "Returns", "the", "plotly", "figure", "containing", "the", "neuron" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/plotly.py#L70-L129
BlueBrain/NeuroM
neurom/geom/transform.py
rotate
def rotate(obj, axis, angle, origin=None): ''' Rotation around unit vector following the right hand rule Parameters: obj : obj to be rotated (e.g. neurite, neuron). Must implement a transform method. axis : unit vector for the axis of rotation angle : rotation angle in rads Returns: A copy of the object with the applied translation. ''' R = _rodrigues_to_dcm(axis, angle) try: return obj.transform(PivotRotation(R, origin)) except AttributeError: raise NotImplementedError
python
def rotate(obj, axis, angle, origin=None): R = _rodrigues_to_dcm(axis, angle) try: return obj.transform(PivotRotation(R, origin)) except AttributeError: raise NotImplementedError
[ "def", "rotate", "(", "obj", ",", "axis", ",", "angle", ",", "origin", "=", "None", ")", ":", "R", "=", "_rodrigues_to_dcm", "(", "axis", ",", "angle", ")", "try", ":", "return", "obj", ".", "transform", "(", "PivotRotation", "(", "R", ",", "origin", ")", ")", "except", "AttributeError", ":", "raise", "NotImplementedError" ]
Rotation around unit vector following the right hand rule Parameters: obj : obj to be rotated (e.g. neurite, neuron). Must implement a transform method. axis : unit vector for the axis of rotation angle : rotation angle in rads Returns: A copy of the object with the applied translation.
[ "Rotation", "around", "unit", "vector", "following", "the", "right", "hand", "rule" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/geom/transform.py#L128-L146
BlueBrain/NeuroM
neurom/geom/transform.py
_sin
def _sin(x): '''sine with case for pi multiples''' return 0. if np.isclose(np.mod(x, np.pi), 0.) else np.sin(x)
python
def _sin(x): return 0. if np.isclose(np.mod(x, np.pi), 0.) else np.sin(x)
[ "def", "_sin", "(", "x", ")", ":", "return", "0.", "if", "np", ".", "isclose", "(", "np", ".", "mod", "(", "x", ",", "np", ".", "pi", ")", ",", "0.", ")", "else", "np", ".", "sin", "(", "x", ")" ]
sine with case for pi multiples
[ "sine", "with", "case", "for", "pi", "multiples" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/geom/transform.py#L149-L151
BlueBrain/NeuroM
neurom/geom/transform.py
_rodrigues_to_dcm
def _rodrigues_to_dcm(axis, angle): ''' Generates transformation matrix from unit vector and rotation angle. The rotation is applied in the direction of the axis which is a unit vector following the right hand rule. Inputs : axis : unit vector of the direction of the rotation angle : angle of rotation in rads Returns : 3x3 Rotation matrix ''' ux, uy, uz = axis / np.linalg.norm(axis) uxx = ux * ux uyy = uy * uy uzz = uz * uz uxy = ux * uy uxz = ux * uz uyz = uy * uz sn = _sin(angle) cs = _sin(np.pi / 2. - angle) cs1 = 1. - cs R = np.zeros([3, 3]) R[0, 0] = cs + uxx * cs1 R[0, 1] = uxy * cs1 - uz * sn R[0, 2] = uxz * cs1 + uy * sn R[1, 0] = uxy * cs1 + uz * sn R[1, 1] = cs + uyy * cs1 R[1, 2] = uyz * cs1 - ux * sn R[2, 0] = uxz * cs1 - uy * sn R[2, 1] = uyz * cs1 + ux * sn R[2, 2] = cs + uzz * cs1 return R
python
def _rodrigues_to_dcm(axis, angle): ux, uy, uz = axis / np.linalg.norm(axis) uxx = ux * ux uyy = uy * uy uzz = uz * uz uxy = ux * uy uxz = ux * uz uyz = uy * uz sn = _sin(angle) cs = _sin(np.pi / 2. - angle) cs1 = 1. - cs R = np.zeros([3, 3]) R[0, 0] = cs + uxx * cs1 R[0, 1] = uxy * cs1 - uz * sn R[0, 2] = uxz * cs1 + uy * sn R[1, 0] = uxy * cs1 + uz * sn R[1, 1] = cs + uyy * cs1 R[1, 2] = uyz * cs1 - ux * sn R[2, 0] = uxz * cs1 - uy * sn R[2, 1] = uyz * cs1 + ux * sn R[2, 2] = cs + uzz * cs1 return R
[ "def", "_rodrigues_to_dcm", "(", "axis", ",", "angle", ")", ":", "ux", ",", "uy", ",", "uz", "=", "axis", "/", "np", ".", "linalg", ".", "norm", "(", "axis", ")", "uxx", "=", "ux", "*", "ux", "uyy", "=", "uy", "*", "uy", "uzz", "=", "uz", "*", "uz", "uxy", "=", "ux", "*", "uy", "uxz", "=", "ux", "*", "uz", "uyz", "=", "uy", "*", "uz", "sn", "=", "_sin", "(", "angle", ")", "cs", "=", "_sin", "(", "np", ".", "pi", "/", "2.", "-", "angle", ")", "cs1", "=", "1.", "-", "cs", "R", "=", "np", ".", "zeros", "(", "[", "3", ",", "3", "]", ")", "R", "[", "0", ",", "0", "]", "=", "cs", "+", "uxx", "*", "cs1", "R", "[", "0", ",", "1", "]", "=", "uxy", "*", "cs1", "-", "uz", "*", "sn", "R", "[", "0", ",", "2", "]", "=", "uxz", "*", "cs1", "+", "uy", "*", "sn", "R", "[", "1", ",", "0", "]", "=", "uxy", "*", "cs1", "+", "uz", "*", "sn", "R", "[", "1", ",", "1", "]", "=", "cs", "+", "uyy", "*", "cs1", "R", "[", "1", ",", "2", "]", "=", "uyz", "*", "cs1", "-", "ux", "*", "sn", "R", "[", "2", ",", "0", "]", "=", "uxz", "*", "cs1", "-", "uy", "*", "sn", "R", "[", "2", ",", "1", "]", "=", "uyz", "*", "cs1", "+", "ux", "*", "sn", "R", "[", "2", ",", "2", "]", "=", "cs", "+", "uzz", "*", "cs1", "return", "R" ]
Generates transformation matrix from unit vector and rotation angle. The rotation is applied in the direction of the axis which is a unit vector following the right hand rule. Inputs : axis : unit vector of the direction of the rotation angle : angle of rotation in rads Returns : 3x3 Rotation matrix
[ "Generates", "transformation", "matrix", "from", "unit", "vector", "and", "rotation", "angle", ".", "The", "rotation", "is", "applied", "in", "the", "direction", "of", "the", "axis", "which", "is", "a", "unit", "vector", "following", "the", "right", "hand", "rule", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/geom/transform.py#L154-L194
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
total_length
def total_length(nrn_pop, neurite_type=NeuriteType.all): '''Get the total length of all sections in the group of neurons or neurites''' nrns = _neuronfunc.neuron_population(nrn_pop) return list(sum(section_lengths(n, neurite_type=neurite_type)) for n in nrns)
python
def total_length(nrn_pop, neurite_type=NeuriteType.all): nrns = _neuronfunc.neuron_population(nrn_pop) return list(sum(section_lengths(n, neurite_type=neurite_type)) for n in nrns)
[ "def", "total_length", "(", "nrn_pop", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "nrns", "=", "_neuronfunc", ".", "neuron_population", "(", "nrn_pop", ")", "return", "list", "(", "sum", "(", "section_lengths", "(", "n", ",", "neurite_type", "=", "neurite_type", ")", ")", "for", "n", "in", "nrns", ")" ]
Get the total length of all sections in the group of neurons or neurites
[ "Get", "the", "total", "length", "of", "all", "sections", "in", "the", "group", "of", "neurons", "or", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L45-L48
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
n_segments
def n_segments(neurites, neurite_type=NeuriteType.all): '''Number of segments in a collection of neurites''' return sum(len(s.points) - 1 for s in iter_sections(neurites, neurite_filter=is_type(neurite_type)))
python
def n_segments(neurites, neurite_type=NeuriteType.all): return sum(len(s.points) - 1 for s in iter_sections(neurites, neurite_filter=is_type(neurite_type)))
[ "def", "n_segments", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "sum", "(", "len", "(", "s", ".", "points", ")", "-", "1", "for", "s", "in", "iter_sections", "(", "neurites", ",", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", ")", ")" ]
Number of segments in a collection of neurites
[ "Number", "of", "segments", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L51-L54
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
n_neurites
def n_neurites(neurites, neurite_type=NeuriteType.all): '''Number of neurites in a collection of neurites''' return sum(1 for _ in iter_neurites(neurites, filt=is_type(neurite_type)))
python
def n_neurites(neurites, neurite_type=NeuriteType.all): return sum(1 for _ in iter_neurites(neurites, filt=is_type(neurite_type)))
[ "def", "n_neurites", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "sum", "(", "1", "for", "_", "in", "iter_neurites", "(", "neurites", ",", "filt", "=", "is_type", "(", "neurite_type", ")", ")", ")" ]
Number of neurites in a collection of neurites
[ "Number", "of", "neurites", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L57-L59
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
n_sections
def n_sections(neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder): '''Number of sections in a collection of neurites''' return sum(1 for _ in iter_sections(neurites, iterator_type=iterator_type, neurite_filter=is_type(neurite_type)))
python
def n_sections(neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder): return sum(1 for _ in iter_sections(neurites, iterator_type=iterator_type, neurite_filter=is_type(neurite_type)))
[ "def", "n_sections", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ",", "iterator_type", "=", "Tree", ".", "ipreorder", ")", ":", "return", "sum", "(", "1", "for", "_", "in", "iter_sections", "(", "neurites", ",", "iterator_type", "=", "iterator_type", ",", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", ")", ")" ]
Number of sections in a collection of neurites
[ "Number", "of", "sections", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L62-L66
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
n_bifurcation_points
def n_bifurcation_points(neurites, neurite_type=NeuriteType.all): '''number of bifurcation points in a collection of neurites''' return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
python
def n_bifurcation_points(neurites, neurite_type=NeuriteType.all): return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
[ "def", "n_bifurcation_points", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "n_sections", "(", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ")" ]
number of bifurcation points in a collection of neurites
[ "number", "of", "bifurcation", "points", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L69-L71
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
n_forking_points
def n_forking_points(neurites, neurite_type=NeuriteType.all): '''number of forking points in a collection of neurites''' return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.iforking_point)
python
def n_forking_points(neurites, neurite_type=NeuriteType.all): return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.iforking_point)
[ "def", "n_forking_points", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "n_sections", "(", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "iforking_point", ")" ]
number of forking points in a collection of neurites
[ "number", "of", "forking", "points", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L74-L76
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
n_leaves
def n_leaves(neurites, neurite_type=NeuriteType.all): '''number of leaves points in a collection of neurites''' return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
python
def n_leaves(neurites, neurite_type=NeuriteType.all): return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
[ "def", "n_leaves", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "n_sections", "(", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ileaf", ")" ]
number of leaves points in a collection of neurites
[ "number", "of", "leaves", "points", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L79-L81
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
total_area_per_neurite
def total_area_per_neurite(neurites, neurite_type=NeuriteType.all): '''Surface area in a collection of neurites. The area is defined as the sum of the area of the sections. ''' return [neurite.area for neurite in iter_neurites(neurites, filt=is_type(neurite_type))]
python
def total_area_per_neurite(neurites, neurite_type=NeuriteType.all): return [neurite.area for neurite in iter_neurites(neurites, filt=is_type(neurite_type))]
[ "def", "total_area_per_neurite", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "[", "neurite", ".", "area", "for", "neurite", "in", "iter_neurites", "(", "neurites", ",", "filt", "=", "is_type", "(", "neurite_type", ")", ")", "]" ]
Surface area in a collection of neurites. The area is defined as the sum of the area of the sections.
[ "Surface", "area", "in", "a", "collection", "of", "neurites", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L84-L89
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
map_sections
def map_sections(fun, neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder): '''Map `fun` to all the sections in a collection of neurites''' return map(fun, iter_sections(neurites, iterator_type=iterator_type, neurite_filter=is_type(neurite_type)))
python
def map_sections(fun, neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder): return map(fun, iter_sections(neurites, iterator_type=iterator_type, neurite_filter=is_type(neurite_type)))
[ "def", "map_sections", "(", "fun", ",", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ",", "iterator_type", "=", "Tree", ".", "ipreorder", ")", ":", "return", "map", "(", "fun", ",", "iter_sections", "(", "neurites", ",", "iterator_type", "=", "iterator_type", ",", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", ")", ")" ]
Map `fun` to all the sections in a collection of neurites
[ "Map", "fun", "to", "all", "the", "sections", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L92-L96
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_lengths
def section_lengths(neurites, neurite_type=NeuriteType.all): '''section lengths in a collection of neurites''' return map_sections(_section_length, neurites, neurite_type=neurite_type)
python
def section_lengths(neurites, neurite_type=NeuriteType.all): return map_sections(_section_length, neurites, neurite_type=neurite_type)
[ "def", "section_lengths", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "_section_length", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ")" ]
section lengths in a collection of neurites
[ "section", "lengths", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L104-L106
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_term_lengths
def section_term_lengths(neurites, neurite_type=NeuriteType.all): '''Termination section lengths in a collection of neurites''' return map_sections(_section_length, neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
python
def section_term_lengths(neurites, neurite_type=NeuriteType.all): return map_sections(_section_length, neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
[ "def", "section_term_lengths", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "_section_length", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ileaf", ")" ]
Termination section lengths in a collection of neurites
[ "Termination", "section", "lengths", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L109-L112
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_bif_lengths
def section_bif_lengths(neurites, neurite_type=NeuriteType.all): '''Bifurcation section lengths in a collection of neurites''' return map_sections(_section_length, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
python
def section_bif_lengths(neurites, neurite_type=NeuriteType.all): return map_sections(_section_length, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
[ "def", "section_bif_lengths", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "_section_length", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ")" ]
Bifurcation section lengths in a collection of neurites
[ "Bifurcation", "section", "lengths", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L115-L118
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_branch_orders
def section_branch_orders(neurites, neurite_type=NeuriteType.all): '''section branch orders in a collection of neurites''' return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type)
python
def section_branch_orders(neurites, neurite_type=NeuriteType.all): return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type)
[ "def", "section_branch_orders", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "sectionfunc", ".", "branch_order", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ")" ]
section branch orders in a collection of neurites
[ "section", "branch", "orders", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L121-L123
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_bif_branch_orders
def section_bif_branch_orders(neurites, neurite_type=NeuriteType.all): '''Bifurcation section branch orders in a collection of neurites''' return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
python
def section_bif_branch_orders(neurites, neurite_type=NeuriteType.all): return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
[ "def", "section_bif_branch_orders", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "sectionfunc", ".", "branch_order", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ")" ]
Bifurcation section branch orders in a collection of neurites
[ "Bifurcation", "section", "branch", "orders", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L126-L129
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_term_branch_orders
def section_term_branch_orders(neurites, neurite_type=NeuriteType.all): '''Termination section branch orders in a collection of neurites''' return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
python
def section_term_branch_orders(neurites, neurite_type=NeuriteType.all): return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
[ "def", "section_term_branch_orders", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "sectionfunc", ".", "branch_order", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ileaf", ")" ]
Termination section branch orders in a collection of neurites
[ "Termination", "section", "branch", "orders", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L132-L135
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_path_lengths
def section_path_lengths(neurites, neurite_type=NeuriteType.all): '''Path lengths of a collection of neurites ''' # Calculates and stores the section lengths in one pass, # then queries the lengths in the path length iterations. # This avoids repeatedly calculating the lengths of the # same sections. dist = {} neurite_filter = is_type(neurite_type) for s in iter_sections(neurites, neurite_filter=neurite_filter): dist[s] = s.length def pl2(node): '''Calculate the path length using cached section lengths''' return sum(dist[n] for n in node.iupstream()) return map_sections(pl2, neurites, neurite_type=neurite_type)
python
def section_path_lengths(neurites, neurite_type=NeuriteType.all): dist = {} neurite_filter = is_type(neurite_type) for s in iter_sections(neurites, neurite_filter=neurite_filter): dist[s] = s.length def pl2(node): return sum(dist[n] for n in node.iupstream()) return map_sections(pl2, neurites, neurite_type=neurite_type)
[ "def", "section_path_lengths", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "# Calculates and stores the section lengths in one pass,", "# then queries the lengths in the path length iterations.", "# This avoids repeatedly calculating the lengths of the", "# same sections.", "dist", "=", "{", "}", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", "for", "s", "in", "iter_sections", "(", "neurites", ",", "neurite_filter", "=", "neurite_filter", ")", ":", "dist", "[", "s", "]", "=", "s", ".", "length", "def", "pl2", "(", "node", ")", ":", "'''Calculate the path length using cached section lengths'''", "return", "sum", "(", "dist", "[", "n", "]", "for", "n", "in", "node", ".", "iupstream", "(", ")", ")", "return", "map_sections", "(", "pl2", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ")" ]
Path lengths of a collection of neurites
[ "Path", "lengths", "of", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L138-L154
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
map_neurons
def map_neurons(fun, neurites, neurite_type): '''Map `fun` to all the neurites in a single or collection of neurons''' nrns = _neuronfunc.neuron_population(neurites) return [fun(n, neurite_type=neurite_type) for n in nrns]
python
def map_neurons(fun, neurites, neurite_type): nrns = _neuronfunc.neuron_population(neurites) return [fun(n, neurite_type=neurite_type) for n in nrns]
[ "def", "map_neurons", "(", "fun", ",", "neurites", ",", "neurite_type", ")", ":", "nrns", "=", "_neuronfunc", ".", "neuron_population", "(", "neurites", ")", "return", "[", "fun", "(", "n", ",", "neurite_type", "=", "neurite_type", ")", "for", "n", "in", "nrns", "]" ]
Map `fun` to all the neurites in a single or collection of neurons
[ "Map", "fun", "to", "all", "the", "neurites", "in", "a", "single", "or", "collection", "of", "neurons" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L157-L160
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
map_segments
def map_segments(func, neurites, neurite_type): ''' Map `func` to all the segments in a collection of neurites `func` accepts a section and returns list of values corresponding to each segment. ''' neurite_filter = is_type(neurite_type) return [ s for ss in iter_sections(neurites, neurite_filter=neurite_filter) for s in func(ss) ]
python
def map_segments(func, neurites, neurite_type): neurite_filter = is_type(neurite_type) return [ s for ss in iter_sections(neurites, neurite_filter=neurite_filter) for s in func(ss) ]
[ "def", "map_segments", "(", "func", ",", "neurites", ",", "neurite_type", ")", ":", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", "return", "[", "s", "for", "ss", "in", "iter_sections", "(", "neurites", ",", "neurite_filter", "=", "neurite_filter", ")", "for", "s", "in", "func", "(", "ss", ")", "]" ]
Map `func` to all the segments in a collection of neurites `func` accepts a section and returns list of values corresponding to each segment.
[ "Map", "func", "to", "all", "the", "segments", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L193-L201
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
segment_lengths
def segment_lengths(neurites, neurite_type=NeuriteType.all): '''Lengths of the segments in a collection of neurites''' def _seg_len(sec): '''list of segment lengths of a section''' return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1) return map_segments(_seg_len, neurites, neurite_type)
python
def segment_lengths(neurites, neurite_type=NeuriteType.all): def _seg_len(sec): return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1) return map_segments(_seg_len, neurites, neurite_type)
[ "def", "segment_lengths", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "def", "_seg_len", "(", "sec", ")", ":", "'''list of segment lengths of a section'''", "return", "np", ".", "linalg", ".", "norm", "(", "np", ".", "diff", "(", "sec", ".", "points", "[", ":", ",", "COLS", ".", "XYZ", "]", ",", "axis", "=", "0", ")", ",", "axis", "=", "1", ")", "return", "map_segments", "(", "_seg_len", ",", "neurites", ",", "neurite_type", ")" ]
Lengths of the segments in a collection of neurites
[ "Lengths", "of", "the", "segments", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L204-L210
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
segment_volumes
def segment_volumes(neurites, neurite_type=NeuriteType.all): '''Volumes of the segments in a collection of neurites''' def _func(sec): '''list of segment volumes of a section''' return [morphmath.segment_volume(seg) for seg in zip(sec.points[:-1], sec.points[1:])] return map_segments(_func, neurites, neurite_type)
python
def segment_volumes(neurites, neurite_type=NeuriteType.all): def _func(sec): return [morphmath.segment_volume(seg) for seg in zip(sec.points[:-1], sec.points[1:])] return map_segments(_func, neurites, neurite_type)
[ "def", "segment_volumes", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "def", "_func", "(", "sec", ")", ":", "'''list of segment volumes of a section'''", "return", "[", "morphmath", ".", "segment_volume", "(", "seg", ")", "for", "seg", "in", "zip", "(", "sec", ".", "points", "[", ":", "-", "1", "]", ",", "sec", ".", "points", "[", "1", ":", "]", ")", "]", "return", "map_segments", "(", "_func", ",", "neurites", ",", "neurite_type", ")" ]
Volumes of the segments in a collection of neurites
[ "Volumes", "of", "the", "segments", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L213-L219
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
segment_radii
def segment_radii(neurites, neurite_type=NeuriteType.all): '''arithmetic mean of the radii of the points in segments in a collection of neurites''' def _seg_radii(sec): '''vectorized mean radii''' pts = sec.points[:, COLS.R] return np.divide(np.add(pts[:-1], pts[1:]), 2.0) return map_segments(_seg_radii, neurites, neurite_type)
python
def segment_radii(neurites, neurite_type=NeuriteType.all): def _seg_radii(sec): pts = sec.points[:, COLS.R] return np.divide(np.add(pts[:-1], pts[1:]), 2.0) return map_segments(_seg_radii, neurites, neurite_type)
[ "def", "segment_radii", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "def", "_seg_radii", "(", "sec", ")", ":", "'''vectorized mean radii'''", "pts", "=", "sec", ".", "points", "[", ":", ",", "COLS", ".", "R", "]", "return", "np", ".", "divide", "(", "np", ".", "add", "(", "pts", "[", ":", "-", "1", "]", ",", "pts", "[", "1", ":", "]", ")", ",", "2.0", ")", "return", "map_segments", "(", "_seg_radii", ",", "neurites", ",", "neurite_type", ")" ]
arithmetic mean of the radii of the points in segments in a collection of neurites
[ "arithmetic", "mean", "of", "the", "radii", "of", "the", "points", "in", "segments", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L222-L229
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
segment_taper_rates
def segment_taper_rates(neurites, neurite_type=NeuriteType.all): '''taper rates of the segments in a collection of neurites The taper rate is defined as the absolute radii differences divided by length of the section ''' def _seg_taper_rates(sec): '''vectorized taper rates''' pts = sec.points[:, COLS.XYZR] diff = np.diff(pts, axis=0) distance = np.linalg.norm(diff[:, COLS.XYZ], axis=1) return np.divide(2 * np.abs(diff[:, COLS.R]), distance) return map_segments(_seg_taper_rates, neurites, neurite_type)
python
def segment_taper_rates(neurites, neurite_type=NeuriteType.all): def _seg_taper_rates(sec): pts = sec.points[:, COLS.XYZR] diff = np.diff(pts, axis=0) distance = np.linalg.norm(diff[:, COLS.XYZ], axis=1) return np.divide(2 * np.abs(diff[:, COLS.R]), distance) return map_segments(_seg_taper_rates, neurites, neurite_type)
[ "def", "segment_taper_rates", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "def", "_seg_taper_rates", "(", "sec", ")", ":", "'''vectorized taper rates'''", "pts", "=", "sec", ".", "points", "[", ":", ",", "COLS", ".", "XYZR", "]", "diff", "=", "np", ".", "diff", "(", "pts", ",", "axis", "=", "0", ")", "distance", "=", "np", ".", "linalg", ".", "norm", "(", "diff", "[", ":", ",", "COLS", ".", "XYZ", "]", ",", "axis", "=", "1", ")", "return", "np", ".", "divide", "(", "2", "*", "np", ".", "abs", "(", "diff", "[", ":", ",", "COLS", ".", "R", "]", ")", ",", "distance", ")", "return", "map_segments", "(", "_seg_taper_rates", ",", "neurites", ",", "neurite_type", ")" ]
taper rates of the segments in a collection of neurites The taper rate is defined as the absolute radii differences divided by length of the section
[ "taper", "rates", "of", "the", "segments", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L232-L244
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
segment_meander_angles
def segment_meander_angles(neurites, neurite_type=NeuriteType.all): '''Inter-segment opening angles in a section''' return list(chain.from_iterable(map_sections( sectionfunc.section_meander_angles, neurites, neurite_type)))
python
def segment_meander_angles(neurites, neurite_type=NeuriteType.all): return list(chain.from_iterable(map_sections( sectionfunc.section_meander_angles, neurites, neurite_type)))
[ "def", "segment_meander_angles", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "list", "(", "chain", ".", "from_iterable", "(", "map_sections", "(", "sectionfunc", ".", "section_meander_angles", ",", "neurites", ",", "neurite_type", ")", ")", ")" ]
Inter-segment opening angles in a section
[ "Inter", "-", "segment", "opening", "angles", "in", "a", "section" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L247-L250
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
segment_midpoints
def segment_midpoints(neurites, neurite_type=NeuriteType.all): '''Return a list of segment mid-points in a collection of neurites''' def _seg_midpoint(sec): '''Return the mid-points of segments in a section''' pts = sec.points[:, COLS.XYZ] return np.divide(np.add(pts[:-1], pts[1:]), 2.0) return map_segments(_seg_midpoint, neurites, neurite_type)
python
def segment_midpoints(neurites, neurite_type=NeuriteType.all): def _seg_midpoint(sec): pts = sec.points[:, COLS.XYZ] return np.divide(np.add(pts[:-1], pts[1:]), 2.0) return map_segments(_seg_midpoint, neurites, neurite_type)
[ "def", "segment_midpoints", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "def", "_seg_midpoint", "(", "sec", ")", ":", "'''Return the mid-points of segments in a section'''", "pts", "=", "sec", ".", "points", "[", ":", ",", "COLS", ".", "XYZ", "]", "return", "np", ".", "divide", "(", "np", ".", "add", "(", "pts", "[", ":", "-", "1", "]", ",", "pts", "[", "1", ":", "]", ")", ",", "2.0", ")", "return", "map_segments", "(", "_seg_midpoint", ",", "neurites", ",", "neurite_type", ")" ]
Return a list of segment mid-points in a collection of neurites
[ "Return", "a", "list", "of", "segment", "mid", "-", "points", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L253-L260
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
segment_radial_distances
def segment_radial_distances(neurites, neurite_type=NeuriteType.all, origin=None): '''Lengths of the segments in a collection of neurites''' def _seg_rd(sec, pos): '''list of radial distances of all segments of a section''' # TODO: remove this disable when pylint is fixed # pylint: disable=assignment-from-no-return mid_pts = np.divide(np.add(sec.points[:-1], sec.points[1:])[:, :3], 2.0) return np.sqrt([morphmath.point_dist2(p, pos) for p in mid_pts]) dist = [] for n in iter_neurites(neurites, filt=is_type(neurite_type)): pos = n.root_node.points[0] if origin is None else origin dist.extend([s for ss in n.iter_sections() for s in _seg_rd(ss, pos)]) return dist
python
def segment_radial_distances(neurites, neurite_type=NeuriteType.all, origin=None): def _seg_rd(sec, pos): mid_pts = np.divide(np.add(sec.points[:-1], sec.points[1:])[:, :3], 2.0) return np.sqrt([morphmath.point_dist2(p, pos) for p in mid_pts]) dist = [] for n in iter_neurites(neurites, filt=is_type(neurite_type)): pos = n.root_node.points[0] if origin is None else origin dist.extend([s for ss in n.iter_sections() for s in _seg_rd(ss, pos)]) return dist
[ "def", "segment_radial_distances", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ",", "origin", "=", "None", ")", ":", "def", "_seg_rd", "(", "sec", ",", "pos", ")", ":", "'''list of radial distances of all segments of a section'''", "# TODO: remove this disable when pylint is fixed", "# pylint: disable=assignment-from-no-return", "mid_pts", "=", "np", ".", "divide", "(", "np", ".", "add", "(", "sec", ".", "points", "[", ":", "-", "1", "]", ",", "sec", ".", "points", "[", "1", ":", "]", ")", "[", ":", ",", ":", "3", "]", ",", "2.0", ")", "return", "np", ".", "sqrt", "(", "[", "morphmath", ".", "point_dist2", "(", "p", ",", "pos", ")", "for", "p", "in", "mid_pts", "]", ")", "dist", "=", "[", "]", "for", "n", "in", "iter_neurites", "(", "neurites", ",", "filt", "=", "is_type", "(", "neurite_type", ")", ")", ":", "pos", "=", "n", ".", "root_node", ".", "points", "[", "0", "]", "if", "origin", "is", "None", "else", "origin", "dist", ".", "extend", "(", "[", "s", "for", "ss", "in", "n", ".", "iter_sections", "(", ")", "for", "s", "in", "_seg_rd", "(", "ss", ",", "pos", ")", "]", ")", "return", "dist" ]
Lengths of the segments in a collection of neurites
[ "Lengths", "of", "the", "segments", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L263-L277
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
local_bifurcation_angles
def local_bifurcation_angles(neurites, neurite_type=NeuriteType.all): '''Get a list of local bifurcation angles in a collection of neurites''' return map_sections(_bifurcationfunc.local_bifurcation_angle, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
python
def local_bifurcation_angles(neurites, neurite_type=NeuriteType.all): return map_sections(_bifurcationfunc.local_bifurcation_angle, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
[ "def", "local_bifurcation_angles", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "_bifurcationfunc", ".", "local_bifurcation_angle", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ")" ]
Get a list of local bifurcation angles in a collection of neurites
[ "Get", "a", "list", "of", "local", "bifurcation", "angles", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L280-L285
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
remote_bifurcation_angles
def remote_bifurcation_angles(neurites, neurite_type=NeuriteType.all): '''Get a list of remote bifurcation angles in a collection of neurites''' return map_sections(_bifurcationfunc.remote_bifurcation_angle, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
python
def remote_bifurcation_angles(neurites, neurite_type=NeuriteType.all): return map_sections(_bifurcationfunc.remote_bifurcation_angle, neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point)
[ "def", "remote_bifurcation_angles", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map_sections", "(", "_bifurcationfunc", ".", "remote_bifurcation_angle", ",", "neurites", ",", "neurite_type", "=", "neurite_type", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ")" ]
Get a list of remote bifurcation angles in a collection of neurites
[ "Get", "a", "list", "of", "remote", "bifurcation", "angles", "in", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L288-L293
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
bifurcation_partitions
def bifurcation_partitions(neurites, neurite_type=NeuriteType.all): '''Partition at bifurcation points of a collection of neurites''' return map(_bifurcationfunc.bifurcation_partition, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, neurite_filter=is_type(neurite_type)))
python
def bifurcation_partitions(neurites, neurite_type=NeuriteType.all): return map(_bifurcationfunc.bifurcation_partition, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, neurite_filter=is_type(neurite_type)))
[ "def", "bifurcation_partitions", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map", "(", "_bifurcationfunc", ".", "bifurcation_partition", ",", "iter_sections", "(", "neurites", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ",", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", ")", ")" ]
Partition at bifurcation points of a collection of neurites
[ "Partition", "at", "bifurcation", "points", "of", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L296-L301
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
partition_asymmetries
def partition_asymmetries(neurites, neurite_type=NeuriteType.all): '''Partition asymmetry at bifurcation points of a collection of neurites''' return map(_bifurcationfunc.partition_asymmetry, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, neurite_filter=is_type(neurite_type)))
python
def partition_asymmetries(neurites, neurite_type=NeuriteType.all): return map(_bifurcationfunc.partition_asymmetry, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, neurite_filter=is_type(neurite_type)))
[ "def", "partition_asymmetries", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map", "(", "_bifurcationfunc", ".", "partition_asymmetry", ",", "iter_sections", "(", "neurites", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ",", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", ")", ")" ]
Partition asymmetry at bifurcation points of a collection of neurites
[ "Partition", "asymmetry", "at", "bifurcation", "points", "of", "a", "collection", "of", "neurites" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L304-L309
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
partition_pairs
def partition_pairs(neurites, neurite_type=NeuriteType.all): '''Partition pairs at bifurcation points of a collection of neurites. Partition pait is defined as the number of bifurcations at the two daughters of the bifurcating section''' return map(_bifurcationfunc.partition_pair, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, neurite_filter=is_type(neurite_type)))
python
def partition_pairs(neurites, neurite_type=NeuriteType.all): return map(_bifurcationfunc.partition_pair, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, neurite_filter=is_type(neurite_type)))
[ "def", "partition_pairs", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "return", "map", "(", "_bifurcationfunc", ".", "partition_pair", ",", "iter_sections", "(", "neurites", ",", "iterator_type", "=", "Tree", ".", "ibifurcation_point", ",", "neurite_filter", "=", "is_type", "(", "neurite_type", ")", ")", ")" ]
Partition pairs at bifurcation points of a collection of neurites. Partition pait is defined as the number of bifurcations at the two daughters of the bifurcating section
[ "Partition", "pairs", "at", "bifurcation", "points", "of", "a", "collection", "of", "neurites", ".", "Partition", "pait", "is", "defined", "as", "the", "number", "of", "bifurcations", "at", "the", "two", "daughters", "of", "the", "bifurcating", "section" ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L312-L319
BlueBrain/NeuroM
neurom/fst/_neuritefunc.py
section_radial_distances
def section_radial_distances(neurites, neurite_type=NeuriteType.all, origin=None, iterator_type=Tree.ipreorder): '''Section radial distances in a collection of neurites. The iterator_type can be used to select only terminal sections (ileaf) or only bifurcations (ibifurcation_point).''' dist = [] for n in iter_neurites(neurites, filt=is_type(neurite_type)): pos = n.root_node.points[0] if origin is None else origin dist.extend(sectionfunc.section_radial_distance(s, pos) for s in iter_sections(n, iterator_type=iterator_type)) return dist
python
def section_radial_distances(neurites, neurite_type=NeuriteType.all, origin=None, iterator_type=Tree.ipreorder): dist = [] for n in iter_neurites(neurites, filt=is_type(neurite_type)): pos = n.root_node.points[0] if origin is None else origin dist.extend(sectionfunc.section_radial_distance(s, pos) for s in iter_sections(n, iterator_type=iterator_type)) return dist
[ "def", "section_radial_distances", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ",", "origin", "=", "None", ",", "iterator_type", "=", "Tree", ".", "ipreorder", ")", ":", "dist", "=", "[", "]", "for", "n", "in", "iter_neurites", "(", "neurites", ",", "filt", "=", "is_type", "(", "neurite_type", ")", ")", ":", "pos", "=", "n", ".", "root_node", ".", "points", "[", "0", "]", "if", "origin", "is", "None", "else", "origin", "dist", ".", "extend", "(", "sectionfunc", ".", "section_radial_distance", "(", "s", ",", "pos", ")", "for", "s", "in", "iter_sections", "(", "n", ",", "iterator_type", "=", "iterator_type", ")", ")", "return", "dist" ]
Section radial distances in a collection of neurites. The iterator_type can be used to select only terminal sections (ileaf) or only bifurcations (ibifurcation_point).
[ "Section", "radial", "distances", "in", "a", "collection", "of", "neurites", ".", "The", "iterator_type", "can", "be", "used", "to", "select", "only", "terminal", "sections", "(", "ileaf", ")", "or", "only", "bifurcations", "(", "ibifurcation_point", ")", "." ]
train
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L322-L333