Search is not available for this dataset
text
stringlengths
75
104k
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_valu...
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_has...
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 call...
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 fr...
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...
def fulfill(self, agreement_id, amount, receiver_address, sender_address, lock_condition_id, release_condition_id, account): """ Fulfill the escrow reward condition. :param agreement_...
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 ...
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 }
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'] ...
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, "functio...
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[n...
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...
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 ...
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 "serviceEndpo...
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...
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 sto...
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 CustomHTTPProvid...
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: retur...
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 valid...
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)
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 ...
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 els...
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))]
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/w...
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...
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 specifi...
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 fi...
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=1...
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 gene...
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' fo...
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): Define...
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 ha...
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 ...
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
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)...
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...
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, ...
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.c...
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) retu...
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[:, ...
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:,...
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)
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...
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)
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 ...
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 : li...
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...
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 neur...
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'...
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.che...
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: C...
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: C...
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 inc...
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, whic...
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 f...
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...
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_d...
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): ...
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 ...
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
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)...
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', ...
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....
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)
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 seg...
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)' ) ...
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 r...
def _sin(x): '''sine with case for pi multiples''' return 0. if np.isclose(np.mod(x, np.pi), 0.) else np.sin(x)
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...
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)
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)))
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)))
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_...
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)
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)
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)
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))]
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_...
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)
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)
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)
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)
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)
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)
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...
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]
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, neuri...
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...
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,...
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 ma...
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....
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)))
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)...
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: disab...
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, ...
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, ...
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, ...
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, ...
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_se...
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_poi...