示例#1
0
def assert_conversion_works(input_file):
    ext_in = input_file.lower().split('.')[-1]
    name = os.path.basename(input_file).split('.')[0]
    for ext_out in ['asc', 'h5', 'swc']:
        output_file = os.path.join('/tmp', name + '.' + ext_out)
        convert(input_file, output_file)
        input = Morphology(input_file)
        output = Morphology(output_file)
        diff_result = diff(input, output)
        ok_(
            not diff_result,
            'Difference between {} and {}: {}'.format(input_file, output_file,
                                                      diff_result.info))
        try:
            if ext_in == ext_out or {ext_in, ext_out} == {'asc', 'h5'}:
                assert_array_almost_equal(
                    Morphology(input_file).soma.points,
                    Morphology(output_file).soma.points)
            else:
                surf1 = _get_surface(input_file, ext_in)
                surf2 = _get_surface(output_file, ext_out)
                try:
                    assert_allclose(surf1, surf2, 5e-1)
                except Exception as e:
                    raise e
        except NotImplementedError:
            pass
示例#2
0
def test_v1():
    n = Morphology(H5V1_PATH / 'simple.h5')
    assert len(n.root_sections) == 2
    assert n.root_sections[0].type == 3
    assert n.root_sections[1].type == 2
    assert n.version == ("h5", 1, 1)

    n = Morphology(H5V1_PATH / 'Neuron.h5')
    assert n.version == ("h5", 1, 0)

    assert len(n.sections) == 84
    assert len(n.soma.points) == 3
    assert len(list(n.iter())) == 84
    assert len(n.points) == 924

    section_types = list(s.type for s in n.iter())
    assert len(section_types) == 84
    real_section_types = list(
        chain(repeat(SectionType.apical_dendrite, 21),
              repeat(SectionType.basal_dendrite, 42),
              repeat(SectionType.axon, 21)))

    assert section_types == real_section_types
    assert_array_equal(
        n.points[:7],
        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.10000000149011612],
         [0.5529246926307678, -0.7534923553466797, 0.9035181403160095],
         [1.2052767276763916, -1.3861794471740723, 1.6835479736328125],
         [1.2670834064483643, -1.3914604187011719, 2.4186644554138184],
         [1.271288275718689, -2.3130500316619873, 3.192789077758789],
         [1.605881929397583, -2.6893420219421387, 3.992844343185425]])
示例#3
0
def test_neurite_wrong_root_point():
    '''Test that for 3 points soma, the neurites are attached to first soma point'''

    # Not 3-points soma --> OK
    with captured_output() as (_, err):
        with ostream_redirect(stdout=True, stderr=True):
            n = Morphology(os.path.join(_path, 'soma_cylinders.swc'))
            assert_equal('', err.getvalue().strip())
        assert_equal(len(n.root_sections), 1)

    with captured_output() as (_, err):
        with ostream_redirect(stdout=True, stderr=True):
            n = Morphology(os.path.join(_path, 'neurite_wrong_root_point.swc'))
            assert_string_equal(
                '''Warning: with a 3 points soma, neurites must be connected to the first soma point:
{}/neurite_wrong_root_point.swc:4:warning

{}/neurite_wrong_root_point.swc:6:warning'''.format(_path, _path),
                err.getvalue())
    assert_equal(len(n.root_sections), 2)
    assert_array_equal(n.root_sections[0].points, [[0, 0, 0], [0, 0, 1]])

    with ignored_warning(Warning.wrong_root_point):
        with captured_output() as (_, err):
            with ostream_redirect(stdout=True, stderr=True):
                n = Morphology(
                    os.path.join(_path, 'neurite_wrong_root_point.swc'))
                assert_equal('', err.getvalue().strip())
示例#4
0
def test_weird_indent():

    with tmp_swc_file("""

                 # this is the same as simple.swc

# but with a questionable styling

     1 1  0  0 0 1. -1
 2 3  0  0 0 1.  1

 3 3  0  5 0 1.  2
 4 3 -5  5 0 0.  3



 5 3  6  5 0 0.  3
     6 2  0  0 0 1.  1
 7 2  0 -4 0 1.  6

 8 2  6 -4 0         0.  7
 9 2 -5      -4 0 0.  7 # 3 0 0
""") as tmp_file:
        n = Morphology(tmp_file.name)

    simple = Morphology(os.path.join(_path, 'simple.swc'))
    assert_array_equal(simple.points, n.points)
示例#5
0
def test_root_node_split():
    '''Test that a bifurcation at the root point produces
    two root sections
    '''
    with tmp_swc_file('''1	1	0 0 0 1	-1
                         2	3	1 0 0 1  1
                         3	3	1 1 0 1  2
                         4	3	1 0 1 1  2
                         ''') as tmp_file:
        n = Morphology(tmp_file.name)
        assert_equal(len(n.root_sections), 2)
        assert_array_equal(n.root_sections[0].points, [[1, 0, 0], [1, 1, 0]])
        assert_array_equal(n.root_sections[1].points, [[1, 0, 0], [1, 0, 1]])

    # Normal bifurcation
    with tmp_swc_file('''1	1	0 0 0 1	-1
                         2	3	1 0 0 1  1
                         3	3	2 1 0 1  2
                         4	3	1 1 0 1  3
                         5	3	1 0 1 1  3
                         ''') as tmp_file:
        n = Morphology(tmp_file.name)
        assert_equal(len(n.root_sections), 1)
        root = n.root_sections[0]
        assert_array_equal(root.points, [[1, 0, 0], [2, 1, 0]])
        assert_equal(len(root.children), 2)
        assert_array_equal(root.children[0].points, [[2, 1, 0], [1, 1, 0]])
        assert_array_equal(root.children[1].points, [[2, 1, 0], [1, 0, 1]])
示例#6
0
def test_v1():
    n = Morphology(os.path.join(H5V1_PATH, 'simple.h5'))
    assert_equal(len(n.root_sections), 2)
    assert_equal(n.root_sections[0].type, 3)
    assert_equal(n.root_sections[1].type, 2)

    n = Morphology(os.path.join(H5V1_PATH, 'Neuron.h5'))
    assert_equal(n.version, MorphologyVersion.MORPHOLOGY_VERSION_H5_1)

    assert_equal(len(n.sections), 84)
    assert_equal(len(n.soma.points), 3)
    assert_equal(len(list(n.iter())), 84)
    assert_equal(len(n.points), 924)

    section_types = list(s.type for s in n.iter())
    assert_equal(len(section_types), 84)
    real_section_types = list(
        chain(repeat(SectionType.apical_dendrite, 21),
              repeat(SectionType.basal_dendrite, 42),
              repeat(SectionType.axon, 21)))

    assert_equal(section_types, real_section_types)
    assert_array_equal(
        n.points[:7],
        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.10000000149011612],
         [0.5529246926307678, -0.7534923553466797, 0.9035181403160095],
         [1.2052767276763916, -1.3861794471740723, 1.6835479736328125],
         [1.2670834064483643, -1.3914604187011719, 2.4186644554138184],
         [1.271288275718689, -2.3130500316619873, 3.192789077758789],
         [1.605881929397583, -2.6893420219421387, 3.992844343185425]])
示例#7
0
def test_sanitize():
    with TemporaryDirectory('test-sanitize') as tmp_folder:
        output_path = Path(tmp_folder, 'sanitized.asc')
        sanitize(Path(PATH, 'simple-with-duplicates.asc'), output_path)
        neuron = Morphology(output_path)
        assert_equal(len(neuron.root_sections), 1)
        assert_array_equal(
            neuron.section(0).points,
            [[0., 0., 0.], [1., 1., 0.], [2., 0., 0.], [3., 0., 0.]])

        for input_morph, expected_exception in [
            ('no-soma.asc',
             '{} has an invalid or no soma'.format(Path(PATH, 'no-soma.asc'))),
            ('neurite-with-multiple-types.swc',
             ('{} has a neurite whose type changes along the way\n'
              'Child section (id: 5) has a different type (SectionType.basal_dendrite) '
              'than its parent (id: 3) (type: SectionType.axon)').format(
                  Path(PATH, 'neurite-with-multiple-types.swc')))
        ]:
            with assert_raises(CorruptedMorphology) as cm:
                sanitize(PATH / input_morph, Path(tmp_folder, 'output.asc'))
            assert_equal(str(cm.exception), expected_exception)

        out_path = Path(tmp_folder, 'output.asc')
        sanitize(PATH / 'negative-diameters.asc', out_path)
        assert_equal(next(Morphology(out_path).iter()).diameters, [2, 2, 0, 2])
示例#8
0
def diff(morph1, morph2, rtol=1.e-5, atol=1.e-8):
    '''
    Returns a DiffResult object that is equivalent to True when morphologies differ
    Additional information about why they differ is stored in DiffResult.info

    Morphologies with different formats can be compared.

    Morphologies are considered different if one of the following property differ:
    - number of root sections
    - sections type
    - sections point array
    - sections diameter array
    - sections perimeter array
    - sections number of children

    The soma are NOT taken into consideration

    Args:
        morph1 (str|morphio.Morphology|morphio.mut.Morphology): a morphology
        morph2 (str|morphio.Morphology|morphio.mut.Morphology): a morphology
        rtol (float): the relative tolerance used for comparing points (see numpy.allclose help)
        atol (float): the absolute tolerance used for comparing points (see numpy.allclose help)
    '''

    if not isinstance(morph1, Morphology):
        morph1 = Morphology(morph1)
    if not isinstance(morph2, Morphology):
        morph2 = Morphology(morph2)

    if len(morph1.root_sections) != len(morph2.root_sections):
        return DiffResult(
            True,
            'Both morphologies have different a different number of root sections'
        )

    for section1, section2 in zip(morph1.iter(), morph2.iter()):
        for attrib in ['points', 'diameters', 'perimeters']:
            val1, val2 = getattr(section1, attrib), getattr(section2, attrib)
            if val1.shape != val2.shape:
                return DiffResult(
                    True, 'Attributes Section.{} of:\n'
                    '{}\n{}\nhave different shapes: {} vs {}'.format(
                        attrib, section1, section2, val1.shape, val2.shape))
            if not allclose(val1, val2, rtol=rtol, atol=atol):
                return DiffResult(
                    True, 'Attributes Section.{} of:\n'
                    '{}\n{}\nhave the same shape but different values'.format(
                        attrib, section1, section2))
        if section1.type != section2.type:
            return DiffResult(
                True, '{} and {} have different section types'.format(
                    section1, section2))
        if len(section1.children) != len(section2.children):
            return DiffResult(
                True,
                '{} and {} have different a different number of children'.
                format(section1, section2))

    return DiffResult(False)
def test_neurolucida_markers():
    SIMPLE = Morphology(DATA_DIR / 'simple.asc')
    for marker, suffix in product(NEUROLUCIDA_MARKERS, ['', '7', '123']):
        marker += suffix
        with tmp_asc_file(f'''
({marker}
  (Color White)
  (Name "fat end")
  (   81.58   -77.98   -20.32     0.50)  ; 1
)  ;  End of markers

("CellBody"
 (Color Red)
 (CellBody)
 (0 0 0 2)
 )


({marker}
  (Color White)
  (Name "fat end")
  (   51.58   -77.78   -24.32     0.52)  ; 1
)  ;  End of markers

 ((Dendrite)
  (0 0 0 2)
  (0 5 0 2)
  (
   (-5 5 0 3)
   |
   (6 5 0 3)
   )
  )


 ((Axon)
  (0 0 0 2)
  (0 -4 0 2)
  (
   (6 -4 0 4)
   |
   (-5 -4 0 4)
   )
  )
                         )''') as tmp_file:
            neuron = Morphology(tmp_file.name)

        assert_array_equal(neuron.points, SIMPLE.points)
        assert len(neuron.markers) == 2
        assert_array_almost_equal(
            neuron.markers[0].points,
            np.array([[81.58, -77.98, -20.32]], dtype=np.float32))
        assert_array_almost_equal(neuron.markers[0].diameters,
                                  np.array([0.5], dtype=np.float32))
        assert_array_almost_equal(
            neuron.markers[1].points,
            np.array([[51.580002, -77.779999, -24.32]], dtype=np.float32))
        assert_array_almost_equal(neuron.markers[1].diameters,
                                  np.array([0.52], dtype=np.float32))
示例#10
0
def test_wrong_section_type():
    with assert_raises(RawDataError) as cm:
        Morphology(os.path.join(H5V1_PATH, 'simple-broken-section-type.h5'))
    assert_equal(str(cm.exception).strip(), 'Unsupported section type: 9')

    with assert_raises(RawDataError) as cm:
        Morphology(os.path.join(H5V1_PATH, 'simple-negative-section-type.h5'))
    assert_equal(str(cm.exception).strip(), 'Unsupported section type: -2')
示例#11
0
def diff(morph1, morph2, rtol=1.e-5, atol=1.e-8):
    """Returns a DiffResult object that is equivalent to True when morphologies differ.

    Additional information about why they differ is stored in DiffResult.info
    Morphologies with different formats can be compared.
    Morphologies are considered different if one of the following property differ:
    - number of root sections
    - sections type
    - sections point array
    - sections diameter array
    - sections perimeter array
    - sections number of children
    The soma are NOT taken into consideration

    Args:
        morph1 (str|morphio.Morphology|morphio.mut.Morphology): a morphology
        morph2 (str|morphio.Morphology|morphio.mut.Morphology): a morphology
        rtol (float): the relative tolerance used for comparing points (see numpy.isclose help)
        atol (float): the absolute tolerance used for comparing points (see numpy.isclose help)
    """
    if not isinstance(morph1, Morphology):
        morph1 = Morphology(morph1)
    if not isinstance(morph2, Morphology):
        morph2 = Morphology(morph2)

    if len(morph1.root_sections) != len(morph2.root_sections):
        return DiffResult(True,
                          'Both morphologies have a different number of root sections')

    for section1, section2 in zip(morph1.iter(), morph2.iter()):
        for attrib in ['points', 'diameters', 'perimeters']:
            val1, val2 = getattr(section1, attrib), getattr(section2, attrib)
            if val1.shape != val2.shape:
                return DiffResult(True,
                                  f'Attributes Section.{attrib} of:\n'
                                  f'{section1}\n'
                                  f'{section2}\n'
                                  f'have different shapes: {val1.shape} vs {val2.shape}'
                                  )
            is_close = np.isclose(val1, val2, rtol=rtol, atol=atol)
            if not is_close.all():
                first_diff_index = np.where(~is_close)[0][0]

                return DiffResult(True,
                                  f'Attributes Section.{attrib} of:\n'
                                  f'{section1}\n{section2}\nhave the same shape '
                                  'but different values\n'
                                  f'Vector {attrib} differs at index {first_diff_index}: '
                                  f'{val1[first_diff_index]} != {val2[first_diff_index]}')
        if section1.type != section2.type:
            return DiffResult(True,
                              f'{section1} and {section2} have different section types')
        if len(section1.children) != len(section2.children):
            return DiffResult(True,
                              f'{section1} and {section2} have a different number of children')

    return DiffResult(False)
示例#12
0
def test_read_without_duplicates():
    with tmp_asc_file(with_duplicate) as tmp_file:
        n_with_duplicate = Morphology(tmp_file.name)

    with tmp_asc_file(without_duplicate) as tmp_file:
        n_without_duplicate = Morphology(tmp_file.name)

    assert_array_equal(n_with_duplicate.root_sections[0].children[0].points,
                       n_without_duplicate.root_sections[0].children[0].points)

    assert_array_equal(n_with_duplicate.root_sections[0].points,
                       n_without_duplicate.root_sections[0].points)
示例#13
0
def test_get_apical_point():
    morph = Morphology(os.path.join(DATA, 'apical_test.swc'))
    point = apical_point_position(morph)
    eq_(point[COLS.Y], 25.0)

    # if we only take the very top, we only get one branch, whos common parents
    # is just itself
    point = apical_point_position(morph, tuft_percent=2)
    eq_(point[COLS.Y], 30.0)

    #try w/ a h5v2: this was converted using morphologyConverter
    morph = Morphology(os.path.join(DATA, 'apical_test.h5'))
    point = apical_point_position(morph)
    eq_(point[COLS.Y], 25.0)
示例#14
0
def test_get_apical_point():
    morph = Morphology(DATA / 'apical_test.swc')
    point = apical_point_position(morph)
    assert point[COLS.Y] == 25.0

    # if we only take the very top, we only get one branch, whos common parents
    # is just itself
    point = apical_point_position(morph, tuft_percent=2)
    assert point[COLS.Y] == 30.0

    #try w/ a h5v2: this was converted using morphologyConverter
    morph = Morphology(DATA / 'apical_test.h5')
    point = apical_point_position(morph)
    assert point[COLS.Y] == 25.0
示例#15
0
def test_single_children():
    '''Single children are no longer (starting at v2.8) merged with their parent

    They used to be until the decision in:
    https://github.com/BlueBrain/MorphIO/issues/235
    '''
    with tmp_asc_file('''
                     ((Dendrite)
                      (3 -4 0 2)
                      (3 -6 0 2)
                      (3 -8 0 2)
                      (3 -10 0 2)
                      (
                        (3 -10 0 4)
                        (0 -10 0 4)
                        (-3 -10 0 3)
                        (
                          (-5 -5 5 5)
                          |
                          (-6 -6 6 6)
                        )
                       )
                      )
                 ''') as tmp_file:

        n = Morphology(tmp_file.name)

        assert len(n.soma.points) == 0
        assert len(n.soma.points) == 0
        assert len(n.root_sections) == 1
        assert_array_equal(
            n.root_sections[0].points,
            np.array([[3, -4, 0], [3, -6, 0], [3, -8, 0], [3, -10, 0]],
                     dtype=np.float32))
        assert len(n.root_sections[0].children) == 1
示例#16
0
def _test_exception(content, exception, str1, str2, extension):
    '''Create tempfile with given content and check that the exception is raised'''
    with _tmp_file(content, extension) as tmp_file:
        with pytest.raises(exception) as obj:
            Morphology(tmp_file.name)
        assert obj.match(str1)
        assert obj.match(str2)
示例#17
0
def test_string_markers():
    cell = Morphology(DATA_DIR / 'pia.asc')

    # The for loop tests that the various constructors keep the markers alive
    for m in (cell, cell.as_mutable(), cell.as_mutable().as_immutable()):
        assert len(m.root_sections) == 1
        assert_array_equal(
            m.root_sections[0].points,
            np.array([[-2.87, -9.24, -5.06], [-2.76, -10.41, -5.13],
                      [-2.03, -12.48, -5.13], [-1.62, -13.30, -5.56]],
                     dtype=np.float32))

        assert len(m.markers) == 2
        pia = m.markers[0]
        assert pia.label == 'pia'
        assert_array_equal(pia.points,
                           [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
        assert_array_equal(pia.diameters, [3, 4, 5, 6])

        assert m.markers[1].label == 'layer1-2'
        assert_array_equal(
            m.markers[1].points,
            np.array([[983.07, 455.36, -0.19], [1192.31, 420.35, -0.19]],
                     dtype=np.float32))
        assert_array_equal(m.markers[1].diameters,
                           np.array([0.15, 0.15], dtype=np.float32))
示例#18
0
def test_endoplasmic_reticulum():
    morpho = Morphology(os.path.join(_path, "h5/v1/endoplasmic-reticulum.h5"))
    er = morpho.endoplasmic_reticulum
    assert_array_equal(er.section_indices, [1, 4, 5])
    assert_array_almost_equal(er.volumes, [10.55, 47.12, 0.83])
    assert_array_almost_equal(er.surface_areas, [111.24, 87.44, 0.11], decimal=5)
    assert_array_equal(er.filament_counts, [12, 42, 8])
示例#19
0
def test_read_with_duplicates():
    '''Section points are duplicated in the file
what I think the
https://developer.humanbrainproject.eu/docs/projects/morphology-documentation/0.0.2/h5v1.html
would look like'''

    with tmp_asc_file(with_duplicate) as tmp_file:
        n = Morphology(tmp_file.name)

    nt.assert_equal(len(n.root_sections), 1)

    assert_array_equal(n.root_sections[0].points,
                       [[3, -4, 0],
                        [3, -6, 0],
                        [3, -8, 0],
                        [3, -10, 0],
                        ])

    assert_array_equal(n.root_sections[0].children[0].points,
                       [[3, -10, 0],
                        [0, -10, 0],
                        [-3, -10, 0]])

    assert_array_equal(n.root_sections[0].children[1].points,
                       [[3, -10, 0],
                        [6, -10, 0],
                        [9, -10, 0]])
示例#20
0
def test_read_split_soma():
    with tmp_swc_file('''# A simple neuron consisting of a two-branch soma
                         # with a single branch neurite on each branch.
                         #
                         # initial soma point
                         1 1 1 0 1 4.0 -1
                         # first neurite
                         2 3 0 0 2 0.5 1
                         3 3 0 0 3 0.5 2
                         4 3 0 0 4 0.5 3
                         5 3 0 0 5 0.5 4
                         # soma branch, off initial point
                         6 1 2 0 0 4.0 1
                         7 1 3 0 0 4.0 6
                         # second neurite, off soma branch
                         8 3 0 0 6 0.5 1
                         9 3 0 0 7 0.5 8
                         10 3 0 0 8 0.5 9
                         11 3 0 0 9 0.5 10
                         ''') as tmp_file:
        n = Morphology(tmp_file.name)

    assert_array_equal(n.soma.points, [[1, 0, 1], [2, 0, 0], [3, 0, 0]])

    nt.assert_equal(len(n.root_sections), 2)
    assert_array_equal(n.root_sections[0].points,
                       [[0, 0, 2], [0, 0, 3], [0, 0, 4], [0, 0, 5]])

    assert_array_equal(n.root_sections[1].points,
                       [[0, 0, 6], [0, 0, 7], [0, 0, 8], [0, 0, 9]])

    nt.eq_(len(list(n.iter())), 2)
示例#21
0
def test_two_point_section():
    m = Morphology(os.path.join(_path, 'multiple_point_section.asc'),
                   options=Option.two_points_sections)
    assert_array_equal(
        [section.points for section in m.iter()],
        [[[0., 0., 0.], [10., 50., 0.]], [[10, 50, 0], [0, 1, 2]],
         [[10, 50, 0], [0, 4, 5]], [[0, 0, 0], [7, 7, 7]]])
示例#22
0
def test_same_conversion_as_asciitoh5():
    '''Check that the morph-tool conversion to produces the same h5 files as asciitoh5 converter.

    repo_base/02-morphology-repository-sanitized contains valid morphologies under ASC format
    repo_base/03-morphology-repository-sanitized-asciitoh5ed
        contains the expected conversion output

    Note: asciitoh5 also reorder the neurites but not 'morph-tool convert'
          so we compare the reordered files
    '''
    repo_base = '/gpfs/bbp.cscs.ch/project/proj30/jenkins/morph-tool/converter'

    with tempfile.TemporaryDirectory() as folder:
        sanitized = Path(repo_base, '02-morphology-repository-sanitized')
        for path in tqdm(list(_walk(sanitized))):
            morphio_morph = Path(folder, path.stem + '.h5')
            convert(path, str(morphio_morph))
            asciitoh5_morph = Path(
                repo_base, '03-morphology-repository-sanitized-asciitoh5ed',
                path.stem + '.h5')
            diff_result = diff(Morphology(morphio_morph, Option.nrn_order),
                               asciitoh5_morph)
            ok_(
                not diff_result,
                'mismatch:\n{}\n{}\n{}'.format(path, asciitoh5_morph,
                                               diff_result.info))
示例#23
0
def test_mitochondria():
    morpho = Morphology(os.path.join(_path, "h5/v1/mitochondria.h5"))
    mito = morpho.mitochondria
    assert_equal(len(mito.root_sections), 2)
    assert_equal(mito.root_sections[0].id, 0)
    mito_root = mito.root_sections

    assert_array_equal(mito_root[0].diameters, [10, 20])
    assert_array_equal(mito_root[0].relative_path_lengths,
                       np.array([0.5, 0.6], dtype=np.float32))
    assert_array_equal(mito_root[0].neurite_section_ids,
                       np.array([0., 0.], dtype=np.float32))

    assert_equal(len(mito_root[0].children), 1)
    mito_child = mito_root[0].children[0]
    assert_equal(mito_child.parent.id, mito_root[0].id)

    assert_array_equal(mito_child.diameters, [20, 30, 40, 50])
    assert_array_equal(mito_child.relative_path_lengths,
                       np.array([0.6, 0.7, 0.8, 0.9], dtype=np.float32))
    assert_array_equal(mito_child.neurite_section_ids,
                       np.array([3, 4, 4, 5], dtype=np.float32))

    assert_array_equal(mito_root[1].diameters, [5, 6, 7, 8])
    assert_array_equal(mito_root[1].relative_path_lengths,
                       np.array([0.6, 0.7, 0.8, 0.9], dtype=np.float32))
    assert_array_equal(mito_root[1].neurite_section_ids,
                       np.array([0, 1, 1, 2], dtype=np.float32))

    assert_equal(len(mito_root[1].children), 0)
示例#24
0
def _test_exception(content, exception, str1, str2, extension):
    '''Create tempfile with given content and check that the exception is raised'''
    with _tmp_file(content, extension) as tmp_file:
        with assert_raises(exception) as obj:
            Morphology(tmp_file.name)
        assert_substring(str1, str(obj.exception))
        assert_substring(str2, str(obj.exception))
示例#25
0
def load_neuron_from_morphio(path_or_obj, user_tree_types=None):
    """
    Create Neuron object from morphio object or from path
        loaded via morphio.
        Supported file formats: h5, swc, asc.

        Args:
            path_or_obj (Union[str, morphio.Morphology]):
                Filepath or morphio object

        Returns:
            neuron (Neuron): tmd Neuron object
    """
    from morphio import Morphology  # pylint: disable=import-outside-toplevel

    tree_types = redefine_types(user_tree_types)

    if isinstance(path_or_obj, (str, Path)):
        obj = Morphology(path_or_obj)
        filename = path_or_obj
    else:
        obj = path_or_obj
        # MorphIO does not support naming of objects yet.
        filename = ''

    neuron = Neuron.Neuron()
    neuron.name = filename
    neuron.set_soma(convert_morphio_soma(obj.soma))
    for tree in convert_morphio_trees(obj):
        neuron.append_tree(tree, tree_types)

    return neuron
示例#26
0
def test_single_point_section_duplicate_parent_complex():
    '''The following neuron represents a malformed tri-furcation. It is (badly) represented
    as a bifurcation of a bifurcation

    This is a simplification of the problem at:
    MorphologyRepository/Ani_Gupta/C030796A/C030796A-P2.asc:5915
    '''
    with tmp_asc_file('''
((Color Blue)
 (Axon)
    (1 0 0 1)
    (2 0 0 1)
    (
      (2 0 0 1) ; Bifurcation starts here
      (
        (4 0 0 1)
        |
        (5 0 0 1)
      )
      |           ; Bifurcation of the bifurcation
      (6 0 0 1)
  )
 )
''') as bad_tmp_file:
        neuron = Morphology(bad_tmp_file.name)

    children = neuron.root_sections[0].children
    assert_equal(len(children), 3)
    assert_array_equal(children[0].points, [[2, 0, 0], [4, 0, 0]])
    assert_array_equal(children[1].points, [[2, 0, 0], [5, 0, 0]])
    assert_array_equal(children[2].points, [[2, 0, 0], [6, 0, 0]])
示例#27
0
def test_nested_single_child():
    with captured_output() as (_, err):
        with ostream_redirect(stdout=True, stderr=True):
            n = Morphology(os.path.join(_path, 'nested_single_children.asc'))
    assert_array_equal(
        n.root_sections[0].points,
        [[0., 0., 0.], [0., 0., 1.], [0., 0., 2.], [0., 0., 3.], [0., 0., 4.]])
示例#28
0
def test_section_single_point():
    '''Test single point section.
    The parent section last point will be duplicated
    '''
    with tmp_asc_file('''
                     ((Dendrite)
                      (3 -4 0 2)
                      (3 -6 0 2)
                      (3 -8 0 2)
                      (3 -10 0 2)
                      (
                        (3 -10 2 4)  ; single point section
                       |
                        (3 -10 0 2)  ; normal section
                        (3 -10 1 2)
                        (3 -10 2 2)
                      )
                     )''') as tmp_file:

        n = Morphology(tmp_file.name)
        nt.assert_equal(len(n.root_sections), 1)
        nt.assert_equal(len(n.root_sections[0].children), 2)
        assert_array_equal(
            n.root_sections[0].children[0].points,
            np.array([[3, -10, 0], [3, -10, 2]], dtype=np.float32))

        assert_array_equal(
            n.root_sections[0].children[1].points,
            np.array([[3, -10, 0], [3, -10, 1], [3, -10, 2]],
                     dtype=np.float32))
示例#29
0
def test_set_raise_warnings():
    try:
        set_raise_warnings(True)
        with pytest.raises(MorphioError,
                           match='Warning: found a disconnected neurite'):
            Morphology(os.path.join(_path, 'disconnected_neurite.swc'))
    finally:
        set_raise_warnings(False)
示例#30
0
def test_point_to_section_segment():
    neuron = Morphology(os.path.join(DATA, 'apical_test.h5'))

    section, segment = spatial.point_to_section_segment(neuron, [0., 25., 0.])
    eq_(section, 2)
    eq_(segment, 1)

    assert_raises(ValueError, spatial.point_to_section_segment, neuron, [24, 0, 0])