How to use the dipy.io.stateful_tractogram.StatefulTractogram function in dipy

To help you get started, we’ve selected a few dipy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yeatmanlab / pyAFQ / AFQ / bundles.py View on Github external
"""

        for bundle_name, bundle in self.bundles.items():
            if bundle.data_per_streamline is not None:
                new_sls, idx_in_bundle = seg.clean_bundle(
                    bundle,
                    return_idx=True,
                    **kwargs)
                new_idx = bundle.data_per_streamline['idx'][idx_in_bundle]
            else:
                new_sls = seg.clean_bundle(bundle,
                                           return_idx=False,
                                           **kwargs)
                new_idx = None
            self.bundles[bundle_name] = \
                StatefulTractogram(new_sls.streamlines,
                                   self.reference,
                                   self.space,
                                   origin=self.origin,
                                   data_per_streamline={'idx': new_idx})
            logging.disable(level=logging.WARNING)
        logging.disable(logging.NOTSET)
github scilus / scilpy / scripts / scil_clean_qbx_clusters.py View on Github external
# Early exit means everything else is rejected
    missing = len(args.in_bundles) - len(choices) - len(sft_rejected_on_size)
    len_accepted = len(sft_accepted_on_size)
    rejected_streamlines.extend(range(len_accepted - missing,
                                      len_accepted))
    if missing > 0:
        logging.info('{} clusters automatically rejected'
                     'from early exit'.format(missing))

    # Save accepted clusters (by GUI)
    accepted_streamlines = save_clusters(sft_accepted_on_size,
                                         accepted_streamlines,
                                         args.out_accepted_dir,
                                         filename_accepted_on_size)

    accepted_sft = StatefulTractogram(accepted_streamlines,
                                      sft_accepted_on_size[0],
                                      Space.RASMM)
    save_tractogram(accepted_sft, args.out_accepted, bbox_valid_check=False)

    # Save rejected clusters (by GUI)
    rejected_streamlines = save_clusters(sft_accepted_on_size,
                                         rejected_streamlines,
                                         args.out_rejected_dir,
                                         filename_accepted_on_size)

    # Save rejected clusters (by size)
    rejected_streamlines.extend(save_clusters(sft_rejected_on_size,
                                              range(len(sft_rejected_on_size)),
                                              args.out_rejected_dir,
                                              filename_rejected_on_size))
github scilus / scilpy / scripts / scil_compute_qbx.py View on Github external
thresholds = [40, 30, 20, args.dist_thresh]
    clusters = qbx_and_merge(streamlines, thresholds,
                             nb_pts=args.nb_points, verbose=False)

    for i, cluster in enumerate(clusters):
        if len(cluster.indices) > 1:
            cluster_streamlines = itemgetter(*cluster.indices)(streamlines)
        else:
            cluster_streamlines = streamlines[cluster.indices]

        new_sft = StatefulTractogram(cluster_streamlines, sft, Space.RASMM)
        save_tractogram(new_sft, os.path.join(args.output_clusters_dir,
                                              'cluster_{}.trk'.format(i)))

    if args.output_centroids:
        new_sft = StatefulTractogram(clusters.centroids, sft, Space.RASMM)
        save_tractogram(new_sft, args.output_centroids)
github scilus / scilpy / scilpy / utils / streamlines.py View on Github external
streamline_ids = np.asarray(streamline_ids, dtype=np.int)

    assert np.all(
        np.in1d(streamline_ids, np.arange(len(tractogram.streamlines)))
    ), "Received ids outside of streamline range"

    new_streamlines = tractogram.streamlines[streamline_ids]
    new_data_per_streamline = tractogram.data_per_streamline[streamline_ids]
    new_data_per_point = tractogram.data_per_point[streamline_ids]

    # Could have been nice to deepcopy the tractogram modify the attributes in
    # place instead of creating a new one, but tractograms cant be subsampled
    # if they have data

    return StatefulTractogram.from_sft(
        new_streamlines,
        tractogram,
        data_per_point=new_data_per_point,
        data_per_streamline=new_data_per_streamline)
github nipy / dipy / dipy / viz / app.py View on Github external
def new_window():
            active_streamlines = Streamlines()
            for bundle in self.cla.keys():
                if bundle.GetVisibility():
                    t = self.cla[bundle]['tractogram']
                    c = self.cla[bundle]['cluster']
                    indices = self.tractogram_clusters[t][c]
                    active_streamlines.extend(Streamlines(indices))

            # Using the header of the first of the tractograms
            active_sft = StatefulTractogram(active_streamlines,
                                            self.tractograms[0],
                                            Space.RASMM)
            hz2 = Horizon([active_sft],
                          self.images, cluster=True,
                          cluster_thr=self.cluster_thr/2.,
                          random_colors=self.random_colors,
                          length_lt=np.inf,
                          length_gt=0, clusters_lt=np.inf,
                          clusters_gt=0,
                          world_coords=True,
                          interactive=True)
            ren2 = hz2.build_scene()
            hz2.build_show(ren2)
github yeatmanlab / pyAFQ / AFQ / segmentation.py View on Github external
def _return_empty(self, bundle):
        """
        Helper function for segment_afq, to return an empty dict under
        some conditions.
        """

        if self.return_idx:
            self.fiber_groups[bundle] = {}
            self.fiber_groups[bundle]['sl'] = StatefulTractogram(
                [], self.img, Space.VOX)
            self.fiber_groups[bundle]['idx'] = np.array([])
        else:
            self.fiber_groups[bundle] = StatefulTractogram(
                [], self.img, Space.VOX)
github nipy / dipy / dipy / viz / app.py View on Github external
def save():
            saving_streamlines = Streamlines()
            for bundle in self.cla.keys():
                if bundle.GetVisibility():
                    t = self.cla[bundle]['tractogram']
                    c = self.cla[bundle]['cluster']
                    indices = self.tractogram_clusters[t][c]
                    saving_streamlines.extend(Streamlines(indices))
            print('Saving result in tmp.trk')

            # Using the header of the first of the tractograms
            sft_new = StatefulTractogram(saving_streamlines,
                                         self.tractograms[0],
                                         Space.RASMM)
            save_tractogram(sft_new, 'tmp.trk', bbox_valid_check=False)
            print('Saved!')
github yeatmanlab / pyAFQ / AFQ / segmentation.py View on Github external
def _return_empty(self, bundle):
        """
        Helper function for segment_afq, to return an empty dict under
        some conditions.
        """

        if self.return_idx:
            self.fiber_groups[bundle] = {}
            self.fiber_groups[bundle]['sl'] = StatefulTractogram(
                [], self.img, Space.VOX)
            self.fiber_groups[bundle]['idx'] = np.array([])
        else:
            self.fiber_groups[bundle] = StatefulTractogram(
                [], self.img, Space.VOX)
github dPys / PyNets / pynets / registration / register.py View on Github external
transform_streamlines(transform_streamlines(
            [sum(d, s) for d, s in zip(values_from_volume(mapping.get_forward_field(), streams_in_curr_grid,
                                                          ref_grid_aff), streams_in_curr_grid)],
            np.linalg.inv(adjusted_affine)), np.linalg.inv(warped_fa_img.affine)), np.eye(4), brain_mask, include=True))

    # Remove streamlines with negative voxel indices
    lin_T, offset = _mapping_to_voxel(np.eye(4))
    streams_final_filt_final = []
    for sl in streams_final_filt:
        inds = np.dot(sl, lin_T)
        inds += offset
        if not inds.min().round(decimals=6) < 0:
            streams_final_filt_final.append(sl)

    # Save streamlines
    stf = StatefulTractogram(streams_final_filt_final, reference=warped_fa_img, space=Space.RASMM, shifted_origin=True)
    stf.remove_invalid_streamlines()
    streams_final_filt_final = stf.streamlines
    save_tractogram(stf, streams_mni, bbox_valid_check=True)
    warped_fa_img.uncache()

    # DSN QC plotting
    # plot_gen.show_template_bundles(streams_final_filt_final, template_path, streams_warp_png)

    # Create and save MNI density map
    nib.save(nib.Nifti1Image(utils.density_map(streams_final_filt_final, affine=np.eye(4),
                                               vol_dims=warped_fa_shape), warped_fa_affine), density_mni)

    # Map parcellation from native space back to MNI-space and create an 'uncertainty-union' parcellation
    # with original mni-space uatlas
    uatlas_mni_img = nib.load(uatlas)