Ejemplo n.º 1
0
def test_add_to_graph_not_supported(custom_bundle):
    dep_desc = Descriptor.load('''
    id: dep
    includes:
      - http://example.com/ctx
    ''')

    test_desc = Descriptor.load('''
    id: test
    dependencies:
      - dep
    ''')

    depgraph = ConjunctiveGraph()
    ctx_graph = depgraph.get_context('http://example.com/ctx')
    quad = (URIRef('http://example.org/sub'),
            URIRef('http://example.org/prop'),
            URIRef('http://example.org/obj'), ctx_graph)
    depgraph.add(quad)

    with custom_bundle(dep_desc, graph=depgraph) as depbun, \
            custom_bundle(test_desc, bundles_directory=depbun.bundles_directory) as testbun, \
            Bundle('test', bundles_directory=testbun.bundles_directory) as bnd:

        with pytest.raises(ZODB.POSException.ReadOnlyError):
            with transaction.manager:
                bnd.rdf.add((URIRef('http://example.org/sub'),
                             URIRef('http://example.org/prop'),
                             URIRef('http://example.org/obj')))
Ejemplo n.º 2
0
def test_specified_bundle_does_not_exist(tempdir):
    bundles_directory = p(tempdir, 'bundles')
    makedirs(p(bundles_directory, 'example'))
    b = Bundle('example', bundles_directory=bundles_directory, version=2)
    with pytest.raises(BundleNotFound,
                       match='at version 2.*specified version'):
        b._get_bundle_directory()
Ejemplo n.º 3
0
def test_triples_choices_context_not_included(custom_bundle):
    dep_desc = Descriptor.load('''
    id: dep
    includes:
      - http://example.com/ctxg
    ''')

    test_desc = Descriptor.load('''
    id: test
    dependencies:
      - dep
    ''')

    depgraph = ConjunctiveGraph()
    ctx_graph = depgraph.get_context('http://example.com/ctx')
    quad = (URIRef('http://example.org/sub'),
            URIRef('http://example.org/prop'),
            URIRef('http://example.org/obj'), ctx_graph)
    depgraph.add(quad)

    with custom_bundle(dep_desc, graph=depgraph) as depbun, \
            custom_bundle(test_desc, bundles_directory=depbun.bundles_directory) as testbun, \
            Bundle('test', bundles_directory=testbun.bundles_directory) as bnd:
        match = False
        for x in bnd.rdf.triples_choices((URIRef('http://example.org/sub'),
                                          URIRef('http://example.org/prop'),
                                          [URIRef('http://example.org/obj')]),
                                         context=ctx_graph):
            match = True
        assert not match
Ejemplo n.º 4
0
def test_no_versioned_bundles(tempdir):
    bundles_directory = p(tempdir, 'bundles')
    makedirs(p(bundles_directory, 'example'))
    b = Bundle('example', bundles_directory=bundles_directory)
    with pytest.raises(BundleNotFound,
                       match='No versioned bundle directories'):
        b._get_bundle_directory()
Ejemplo n.º 5
0
def test_dependency_version_in_manifest_without_spec(dirs):
    '''
    It is permitted to not specify the version of a bundle dependency in the descriptor,
    but we must pin a specific version of the bundle in the manifest.
    '''
    ctxid_1 = 'http://example.org/ctx1'
    ctxid_2 = 'http://example.org/ctx2'

    # Make a descriptor that includes ctx1 and the imports, but not ctx2
    d = Descriptor('test')
    d.includes.add(make_include_func(ctxid_1))
    d.dependencies.add(DependencyDescriptor('dep'))

    dep_d = Descriptor('dep')
    dep_d.includes.add(make_include_func(ctxid_2))

    # Add some triples so the contexts aren't empty -- we can't save an empty context
    g = rdflib.ConjunctiveGraph()

    cg_1 = g.get_context(ctxid_1)
    cg_2 = g.get_context(ctxid_2)

    cg_1.add((aURI('a'), aURI('b'), aURI('c')))
    cg_2.add((aURI('d'), aURI('e'), aURI('f')))

    bi = Installer(*dirs, graph=g)
    bi.install(dep_d)
    bi.install(d)
    test_bnd = Bundle('test', bundles_directory=dirs.bundles_directory)
    assert test_bnd.manifest_data['dependencies'][0]['version'] == 1
Ejemplo n.º 6
0
def test_bundle_contextualize(bundle):
    with Bundle(bundle.descriptor.id,
                version=bundle.descriptor.version,
                bundles_directory=bundle.bundles_directory) as cut:
        ctxble = Mock(spec=Contextualizable)
        cut(ctxble)
        ctxble.contextualize.assert_called_with(ContextWithNoId())
Ejemplo n.º 7
0
def test_bundles_directory_None():
    with patch('owmeta_core.bundle.expandvars') as expandvars, \
            patch('owmeta_core.bundle.realpath') as realpath, \
            patch('owmeta_core.bundle.expanduser') as expanduser:
        assert realpath(
            expandvars(expanduser(DEFAULT_BUNDLES_DIRECTORY))) == Bundle(
                'test', None).bundles_directory
Ejemplo n.º 8
0
def test_transitive_dep_null_context_triples_no_imports(custom_bundle):
    dep_dep_desc = Descriptor.load('''
    id: dep_dep
    includes:
      - http://example.com/ctx
    ''')

    dep_desc = Descriptor.load('''
    id: dep
    dependencies:
      - dep_dep
    ''')

    test_desc = Descriptor.load('''
    id: test
    dependencies:
      - dep
    ''')

    depgraph = ConjunctiveGraph()
    ctx_graph = depgraph.get_context('http://example.com/ctx')
    quad = (URIRef('http://example.org/sub'),
            URIRef('http://example.org/prop'),
            URIRef('http://example.org/obj'), ctx_graph)
    depgraph.add(quad)

    with custom_bundle(dep_dep_desc, graph=depgraph) as depdepbun, \
            custom_bundle(dep_desc, bundles_directory=depdepbun.bundles_directory) as depbun, \
            custom_bundle(test_desc, bundles_directory=depbun.bundles_directory) as testbun, \
            Bundle('test', bundles_directory=testbun.bundles_directory) as bnd:
        assert set([quad[:3]]) == set(bnd.rdf.triples((None, None, None)))
Ejemplo n.º 9
0
def test_unrelated_imports_excluded(dirs):
    imports_ctxid = 'http://example.org/imports'
    ctxid_1 = 'http://example.org/ctx1'
    ctxid_2 = 'http://example.org/ctx2'
    ctxid_3 = 'http://example.org/ctx3'
    ctxid_4 = 'http://example.org/ctx4'

    # Make a descriptor that includes ctx1 and the imports, but not ctx2
    d = Descriptor('test')
    d.includes.add(make_include_func(ctxid_1))
    d.includes.add(make_include_func(ctxid_2))

    # Add some triples so the contexts aren't empty -- we can't save an empty context
    g = rdflib.ConjunctiveGraph()
    cg_1 = g.get_context(ctxid_1)
    cg_2 = g.get_context(ctxid_2)
    cg_3 = g.get_context(ctxid_3)
    cg_4 = g.get_context(ctxid_4)
    cg_imp = g.get_context(imports_ctxid)
    with transaction.manager:
        cg_1.add((aURI('a'), aURI('b'), aURI('c')))
        cg_2.add((aURI('d'), aURI('e'), aURI('f')))
        cg_3.add((aURI('g'), aURI('h'), aURI('i')))
        cg_4.add((aURI('j'), aURI('k'), aURI('l')))
        cg_imp.add((URIRef(ctxid_1), CONTEXT_IMPORTS, URIRef(ctxid_2)))
        cg_imp.add((URIRef(ctxid_3), CONTEXT_IMPORTS, URIRef(ctxid_4)))

    bi = Installer(*dirs, imports_ctx=imports_ctxid, graph=g)
    bi.install(d)
    with Bundle(d.id, dirs.bundles_directory) as bnd:
        g = bnd.rdf.get_context(bnd.conf[IMPORTS_CONTEXT_KEY])
        assert (URIRef(ctxid_3), CONTEXT_IMPORTS, URIRef(ctxid_4)) not in g
Ejemplo n.º 10
0
def test_imports_are_included(dirs):
    '''
    If we have imports and no dependencies, then thrown an exception if we have not
    included them in the bundle
    '''
    imports_ctxid = 'http://example.org/imports'
    ctxid_1 = 'http://example.org/ctx1'
    ctxid_2 = 'http://example.org/ctx2'

    # Make a descriptor that includes ctx1 and the imports, but not ctx2
    d = Descriptor('test')
    d.includes.add(make_include_func(ctxid_1))
    d.includes.add(make_include_func(ctxid_2))

    # Add some triples so the contexts aren't empty -- we can't save an empty context
    g = rdflib.ConjunctiveGraph()
    cg_1 = g.get_context(ctxid_1)
    cg_2 = g.get_context(ctxid_2)
    cg_imp = g.get_context(imports_ctxid)
    with transaction.manager:
        cg_1.add((aURI('a'), aURI('b'), aURI('c')))
        cg_2.add((aURI('d'), aURI('e'), aURI('f')))
        cg_imp.add((URIRef(ctxid_1), CONTEXT_IMPORTS, URIRef(ctxid_2)))

    bi = Installer(*dirs, imports_ctx=imports_ctxid, graph=g)
    bi.install(d)
    with Bundle(d.id, dirs.bundles_directory) as bnd:
        g = bnd.rdf.get_context(bnd.conf[IMPORTS_CONTEXT_KEY])
        assert (URIRef(ctxid_1), CONTEXT_IMPORTS, URIRef(ctxid_2)) in g
Ejemplo n.º 11
0
def test_load_from_class_registry_from_conjunctive(custom_bundle):
    '''
    Test that we can load from the class registry for un-imported classes
    '''
    from owmeta_core.dataobject import DataObject

    class_registry_ctxid = 'http://example.org/class_registry'
    data_ctxid = 'http://example.org/data_context'
    defctxid = 'http://example.org/Person'

    # Add some triples so the contexts aren't empty -- we can't save an empty context
    g = rdflib.ConjunctiveGraph()

    with open(p('tests', 'test_data', 'owmbundletest01_data.n3'), 'rb') as f:
        g.get_context(data_ctxid).parse(f, format='n3')

    with open(p('tests', 'test_data', 'owmbundletest01_class_registry.n3'),
              'rb') as f:
        g.get_context(class_registry_ctxid).parse(f, format='n3')

    with open(p('tests', 'test_data', 'owmbundletest01_defctx.n3'), 'rb') as f:
        g.get_context(defctxid).parse(f, format='n3')

    # Make a descriptor that includes ctx1 and the imports, but not ctx2
    d = Descriptor('test')
    d.includes.add(make_include_func(data_ctxid))
    d.includes.add(make_include_func(defctxid))

    with custom_bundle(d, graph=g, class_registry_ctx=class_registry_ctxid) as testbun, \
            Bundle('test', bundles_directory=testbun.bundles_directory) as bnd:

        bctx = bnd(Context)().stored
        for m in bctx(DataObject)().load():
            assert type(m).__name__ == 'Person'
            break
        else:  # no break
            pytest.fail('Expected an object')

    with custom_bundle(d, graph=g) as testbun, \
            Bundle('test', bundles_directory=testbun.bundles_directory) as bnd:

        bctx = bnd(Context)().stored
        for m in bctx(DataObject)().load():
            assert type(m).__name__ != 'Person'
            break
        else:  # no break
            pytest.fail('Expected an object')
Ejemplo n.º 12
0
def test_ignore_non_version_number(tempdir):
    bundles_directory = p(tempdir, 'bundles')
    b = Bundle('example', bundles_directory=bundles_directory)
    makedirs(p(bundles_directory, 'example', 'ignore_me'))
    expected = p(bundles_directory, 'example', '5')
    makedirs(expected)
    actual = b._get_bundle_directory()
    assert actual == expected
Ejemplo n.º 13
0
 def setUp(self):
     self.bnd = Bundle('openworm/owmeta-data')
     self.bnd.initdb()
     self.conn = self.bnd.connection
     self.conf = self.conn.conf
     self.g = self.conf["rdf.graph"]
     self.context = self.conn(Context)(ident="http://openworm.org/data")
     self.qctx = self.context.stored
Ejemplo n.º 14
0
def test_specified_version_fetched(tempdir):
    bundles_directory = p(tempdir, 'bundles')
    makedirs(p(bundles_directory, 'example', '1'))
    expected = p(bundles_directory, 'example', '2')
    makedirs(expected)
    makedirs(p(bundles_directory, 'example', '3'))
    b = Bundle('example', version=2, bundles_directory=bundles_directory)
    assert expected == b._get_bundle_directory()
Ejemplo n.º 15
0
def test_latest_bundle_fetched(tempdir):
    bundles_directory = p(tempdir, 'bundles')
    makedirs(p(bundles_directory, 'example', '1'))
    makedirs(p(bundles_directory, 'example', '2'))
    expected = p(bundles_directory, 'example', '3')
    makedirs(expected)
    b = Bundle('example', bundles_directory=bundles_directory)
    assert expected == b._get_bundle_directory()
Ejemplo n.º 16
0
def test_bundle_selected_remotes(tempdir):
    with patch('owmeta_core.bundle.Fetcher') as Fetcher:
        remotes = (object(), object())
        cut = Bundle('bundle_id',
                     version=1,
                     bundles_directory=tempdir,
                     remotes=remotes)
        cut.resolve()
        Fetcher().fetch.assert_called_with(ANY, 1, remotes)
Ejemplo n.º 17
0
def test_specified_bundles_root_permission_denied(tempdir):
    bundles_directory = p(tempdir, 'bundles')
    b = Bundle('example', bundles_directory=bundles_directory)
    makedirs(bundles_directory)
    chmod(bundles_directory, 0)
    try:
        with pytest.raises(OSError, match='[Pp]ermission denied'):
            b._get_bundle_directory()
    finally:
        chmod(bundles_directory, 0o777)
Ejemplo n.º 18
0
def test_bundle_store_conf_with_two_dep_levels(custom_bundle):
    '''
    Test that transitive dependenices shared by multiple bundles are not included more
    than once
    '''
    imports_ctxid = 'http://example.org/imports'
    ctxid_1 = 'http://example.org/ctx1'
    ctxid_2 = 'http://example.org/ctx2'

    # Make a descriptor that includes ctx1 and the imports, but not ctx2
    d = Descriptor('test')
    d.includes.add(make_include_func(ctxid_1))
    d.includes.add(make_include_func(imports_ctxid))
    d.dependencies.add(DependencyDescriptor('dep'))
    d.dependencies.add(DependencyDescriptor('dep_dep'))

    dep_d = Descriptor('dep')
    dep_d.dependencies.add(DependencyDescriptor('dep_dep'))

    dep_dep_d = Descriptor('dep_dep')
    dep_dep_d.includes.add(make_include_func(ctxid_2))

    # Add some triples so the contexts aren't empty -- we can't save an empty context
    g = rdflib.ConjunctiveGraph()
    cg_1 = g.get_context(ctxid_1)
    cg_2 = g.get_context(ctxid_2)
    cg_1.add((aURI('a'), aURI('b'), aURI('c')))
    cg_2.add((aURI('d'), aURI('e'), aURI('f')))

    # End setup

    with custom_bundle(dep_dep_d, graph=g) as depdepbun, \
            custom_bundle(dep_d, bundles_directory=depdepbun.bundles_directory) as depbun, \
            custom_bundle(d, bundles_directory=depbun.bundles_directory) as testbun, \
            Bundle('test', bundles_directory=testbun.bundles_directory) as bnd:
        assert bnd.conf['rdf.store_conf'] == [
            ('FileStorageZODB',
             dict(url=p(testbun.bundle_directory, BUNDLE_INDEXED_DB_NAME),
                  read_only=True)),
            # dep
            ('owmeta_core_bds',
             dict(type='agg',
                  conf=[('FileStorageZODB',
                         dict(url=p(depbun.bundle_directory,
                                    BUNDLE_INDEXED_DB_NAME),
                              read_only=True)),
                        ('owmeta_core_bds',
                         dict(type='agg',
                              conf=[('FileStorageZODB',
                                     dict(url=p(depdepbun.bundle_directory,
                                                BUNDLE_INDEXED_DB_NAME),
                                          read_only=True))]))]))
        ]
Ejemplo n.º 19
0
def test_bundle_retrieve_remotes_default_dir(tempdir):
    with patch('owmeta_core.bundle.retrieve_remotes') as retrieve_remotes:
        remotes_dir = '/tmp/remotes_dir'
        cut = Bundle('bundle_id',
                     version=1,
                     bundles_directory=tempdir,
                     remotes_directory=remotes_dir)
        try:
            cut.resolve()
        except NoRemoteAvailable:
            pass
        retrieve_remotes.assert_called_with(remotes_dir)
Ejemplo n.º 20
0
def test_class_registry_contents(dirs):
    '''
    If a class registry context is specified, then include it
    '''
    cr_ctxid = 'http://example.org/class_registry'

    # Make a descriptor that includes ctx1 and the imports, but not ctx2
    d = Descriptor('test')

    # Add some triples so the contexts aren't empty -- we can't save an empty context
    g = rdflib.ConjunctiveGraph()
    cg_cr = g.get_context(cr_ctxid)
    with transaction.manager:
        cg_cr.add((aURI('blah'), aURI('bruh'), aURI('uhhhh')))

    bi = Installer(*dirs, class_registry_ctx=cr_ctxid, graph=g)
    bi.install(d)

    with Bundle(d.id, dirs.bundles_directory) as bnd:
        g = bnd.rdf.get_context(bnd.conf[CLASS_REGISTRY_CONTEXT_KEY])
        assert (aURI('blah'), aURI('bruh'), aURI('uhhhh')) in g
Ejemplo n.º 21
0
def test_quad_not_in_dependency(custom_bundle):
    dep_desc = Descriptor.load('''
    id: dep
    includes:
      - http://example.com/ctx
    ''')

    test_desc = Descriptor.load('''
    id: test
    dependencies:
      - dep
    ''')

    depgraph = ConjunctiveGraph()
    ctx_graph = depgraph.get_context('http://example.com/other_ctx')
    quad = (URIRef('http://example.org/sub'),
            URIRef('http://example.org/prop'),
            URIRef('http://example.org/obj'), ctx_graph)
    depgraph.add(quad)

    with custom_bundle(dep_desc, graph=depgraph) as depbun, \
            custom_bundle(test_desc, bundles_directory=depbun.bundles_directory) as testbun, \
            Bundle('test', bundles_directory=testbun.bundles_directory) as bnd:
        assert quad not in bnd.rdf
Ejemplo n.º 22
0
def test_specified_bundles_root_directory_does_not_exist(tempdir):
    bundles_directory = p(tempdir, 'bundles')
    b = Bundle('example', bundles_directory=bundles_directory)
    with pytest.raises(BundleNotFound, match='Bundle directory'):
        b._get_bundle_directory()
Ejemplo n.º 23
0
def generate_c302_info(nml_doc, verbose=False):

    net = nml_doc.networks[0]

    cc_exc_conns = {}
    cc_inh_conns = {}
    all_cells = []

    for cp in net.continuous_projections:
        if not cp.presynaptic_population in cc_exc_conns.keys():
            cc_exc_conns[cp.presynaptic_population] = {}
        if not cp.presynaptic_population in cc_inh_conns.keys():
            cc_inh_conns[cp.presynaptic_population] = {}

        if not cp.presynaptic_population in all_cells:
            all_cells.append(cp.presynaptic_population)
        if not cp.postsynaptic_population in all_cells:
            all_cells.append(cp.postsynaptic_population)

        for c in cp.continuous_connection_instance_ws:
            if 'inh' in c.post_component:
                cc_inh_conns[cp.presynaptic_population][
                    cp.postsynaptic_population] = float(c.weight)
            else:
                cc_exc_conns[cp.presynaptic_population][
                    cp.postsynaptic_population] = float(c.weight)

    gj_conns = {}
    for ep in net.electrical_projections:
        if not ep.presynaptic_population in gj_conns.keys():
            gj_conns[ep.presynaptic_population] = {}

        if not ep.presynaptic_population in all_cells:
            all_cells.append(ep.presynaptic_population)
        if not ep.postsynaptic_population in all_cells:
            all_cells.append(ep.postsynaptic_population)

        for e in ep.electrical_connection_instance_ws:
            gj_conns[ep.presynaptic_population][
                ep.postsynaptic_population] = float(e.weight)

    all_cells = sorted(all_cells)

    try:
        from PyOpenWorm import connect as pyow_connect, __version__ as pyow_version, ConnectionFailError
        pow_conn = pyow_connect('./pyopenworm.conf')
        all_neuron_info, all_muscle_info = c302._get_cell_info(
            pow_conn, all_cells)
        ver_info = 'PyOpenWorm v%s' % pyow_version
    except Exception as e:
        c302.print_('Unable to connect to PyOpenWorm database: %s' % e)
        from owmeta_core.bundle import Bundle

        from owmeta_core import __version__ as owc_version
        from owmeta import __version__ as owmeta_version

        ver_info = 'owmeta v%s (owmeta core v%s)' % (owmeta_version,
                                                     owc_version)

        with Bundle('openworm/owmeta-data', version=6) as bnd:
            all_neuron_info, all_muscle_info = c302._get_cell_info(
                bnd, all_cells)

    all_neurons = []
    all_muscles = []
    for c in all_cells:
        if c302.is_muscle(c):
            all_muscles.append(c)
        else:
            all_neurons.append(c)

    info = '# Information on neuron and muscles\n'
    info += '## Generated using %s\n' % ver_info

    info += '### Neurons (%i)\n' % (len(all_neuron_info))
    info += '<table>\n'
    for n in all_neuron_info:
        info += '<tr>\n'
        ni = all_neuron_info[n]
        #print(ni)
        info += (
            '<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>Colour: %s</td>'
            % (n, _info_set(ni[1]), _info_set(ni[2]), _info_set(
                ni[3]), ni[4], ni[5]))
        info += '</tr>\n'
    info += '</table>\n'

    info += '### Muscles (%i)\n' % (len(all_muscle_info))
    info += '<table>\n'
    for n in all_muscle_info:
        info += '<tr>\n'
        ni = all_muscle_info[n]
        info += (
            '<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>Colour: %s</td>'
            % (n, _info_set(ni[1]), _info_set(ni[2]), _info_set(
                ni[3]), ni[4], ni[5]))
        info += '</tr>\n'
    info += '</table>\n'

    with open('examples/summary/summary.md', 'w') as f2:
        #f2.write('<html><body>%s</body></html>'%info)
        f2.write('%s' % info)
Ejemplo n.º 24
0
from owmeta_core.bundle import Bundle
from owmeta_core.context import Context
from owmeta.neuron import Neuron
from owmeta.worm import Worm

with Bundle('openworm/owmeta-data') as bnd:
    ctx = bnd(Context)(ident="http://openworm.org/data").stored
    # Extract the network object from the worm object.
    net = ctx(Worm).query().neuron_network()

    syn = net.synapse.expr
    pre = syn.pre_cell
    post = syn.post_cell

    (pre | post).rdf_type(multiple=True)

    (pre | post).name()
    pre()
    post()
    syn.syntype()
    syn.synclass()
    syn.number()
    connlist = syn.to_objects()

conns = []
for conn in connlist:
    if (Neuron.rdf_type in conn.pre_cell.rdf_type
            and Neuron.rdf_type in conn.post_cell.rdf_type):
        num = conn.number
        syntype = conn.syntype or ''
        synclass = conn.synclass or ''
Ejemplo n.º 25
0
    def _read_connections(self, termination=None):
        if not self.cached:
            with Bundle('openworm/owmeta-data', version=6) as bnd:
                ctx = bnd(Context)(ident="http://openworm.org/data").stored
                # Extract the network object from the worm object.
                net = ctx(Worm).query().neuron_network()

                syn = net.synapse.expr
                pre = syn.pre_cell
                post = syn.post_cell

                (pre | post).rdf_type(multiple=True)

                (pre | post).name()
                pre()
                post()
                syn.syntype()
                syn.synclass()
                syn.number()
                self.connlist = syn.to_objects()

                self.cell_names = self.get_cells_in_model(net)
            self.cached = True

        if termination == 'neuron':
            term_type = set([Neuron.rdf_type])
        elif termination == 'muscle':
            term_type = set([BodyWallMuscle.rdf_type])
        else:
            term_type = set([Neuron.rdf_type, BodyWallMuscle.rdf_type])

        conns = []
        pre_cell_names = set()
        post_cell_names = set()
        for conn in self.connlist:
            if (Neuron.rdf_type in conn.pre_cell.rdf_type and
                    term_type & set(conn.post_cell.rdf_type)):
                num = conn.number
                syntype = conn.syntype or ''
                synclass = conn.synclass or ''
                pre_name = conn.pre_cell.name
                post_name = conn.post_cell.name
                if BodyWallMuscle.rdf_type in conn.post_cell.rdf_type:
                    post_name = format_muscle_name(post_name)

                if not synclass:
                    # Hack/guess
                    if syntype and syntype.lower() == "gapjunction":
                        synclass = "Generic_GJ"
                    else:
                        if pre_name.startswith("DD") or pre_name.startswith("VD"):
                            synclass = "GABA"
                        synclass = "Acetylcholine"
                conns.append(ConnectionInfo(pre_name, post_name, num, syntype, synclass))

                pre_cell_names.add(pre_name)
                post_cell_names.add(post_name)

        print_("Total cells %i (%i with connections)" % (
            len(self.cell_names | pre_cell_names | post_cell_names),
            len(pre_cell_names | post_cell_names)))
        print_("Total connections found %i " % len(conns))

        return list(self.cell_names), pre_cell_names, post_cell_names, conns
Ejemplo n.º 26
0
def generate_conn_matrix(nml_doc, save_fig_dir=None, verbose=False):

    net = nml_doc.networks[0]

    cc_exc_conns = {}
    cc_inh_conns = {}
    all_cells = []

    for cp in net.continuous_projections:
        if not cp.presynaptic_population in cc_exc_conns.keys():
            cc_exc_conns[cp.presynaptic_population] = {}
        if not cp.presynaptic_population in cc_inh_conns.keys():
            cc_inh_conns[cp.presynaptic_population] = {}

        if not cp.presynaptic_population in all_cells:
            all_cells.append(cp.presynaptic_population)
        if not cp.postsynaptic_population in all_cells:
            all_cells.append(cp.postsynaptic_population)

        for c in cp.continuous_connection_instance_ws:
            if 'inh' in c.post_component:
                cc_inh_conns[cp.presynaptic_population][
                    cp.postsynaptic_population] = float(c.weight)
            else:
                cc_exc_conns[cp.presynaptic_population][
                    cp.postsynaptic_population] = float(c.weight)

    gj_conns = {}
    for ep in net.electrical_projections:
        if not ep.presynaptic_population in gj_conns.keys():
            gj_conns[ep.presynaptic_population] = {}

        if not ep.presynaptic_population in all_cells:
            all_cells.append(ep.presynaptic_population)
        if not ep.postsynaptic_population in all_cells:
            all_cells.append(ep.postsynaptic_population)

        for e in ep.electrical_connection_instance_ws:
            gj_conns[ep.presynaptic_population][
                ep.postsynaptic_population] = float(e.weight)

    all_cells = sorted(all_cells)

    try:
        with Bundle('openworm/owmeta-data', version=6) as bnd:
            all_neuron_info, all_muscle_info = c302._get_cell_info(
                bnd, all_cells)
    except Exception as e:
        c302.print_('Unable to connect to owmeta bundle: %s' % e)
        traceback.print_exc()

    all_neurons = []
    all_muscles = []
    for c in all_cells:
        if c302.is_muscle(c):
            all_muscles.append(c)
        else:
            all_neurons.append(c)

    data_exc_n = np.zeros((len(all_neurons), len(all_neurons)))
    data_exc_m = np.zeros((len(all_neurons), len(all_muscles)))

    data_inh_n = np.zeros((len(all_neurons), len(all_neurons)))
    data_inh_m = np.zeros((len(all_neurons), len(all_muscles)))

    for pre in cc_exc_conns.keys():
        for post in cc_exc_conns[pre].keys():
            c302.print_(
                "Exc Conn %s -> %s: %s" % (pre, post, cc_exc_conns[pre][post]),
                verbose)
            if post in all_neurons:
                data_exc_n[all_neurons.index(pre),
                           all_neurons.index(post)] = cc_exc_conns[pre][post]
            else:
                data_exc_m[all_neurons.index(pre),
                           all_muscles.index(post)] = cc_exc_conns[pre][post]
            if pre in all_muscles:
                raise Exception("Unexpected...")

    for pre in cc_inh_conns.keys():
        for post in cc_inh_conns[pre].keys():
            c302.print_(
                "Inh Conn %s -> %s: %s" % (pre, post, cc_inh_conns[pre][post]),
                verbose)
            if post in all_neurons:
                data_inh_n[all_neurons.index(pre),
                           all_neurons.index(post)] = cc_inh_conns[pre][post]
            else:
                data_inh_m[all_neurons.index(pre),
                           all_muscles.index(post)] = cc_inh_conns[pre][post]
            if pre in all_muscles:
                raise Exception("Unexpected...")

    _show_conn_matrix(data_exc_n,
                      'Excitatory (non GABA) conns to neurons',
                      all_neuron_info,
                      all_neuron_info,
                      net.id,
                      save_figure_to='%s/%s_exc_to_neurons.png' %
                      (save_fig_dir, net.id) if save_fig_dir else None)

    _show_conn_matrix(data_exc_m,
                      'Excitatory (non GABA) conns to muscles',
                      all_neuron_info,
                      all_muscle_info,
                      net.id,
                      save_figure_to='%s/%s_exc_to_muscles.png' %
                      (save_fig_dir, net.id) if save_fig_dir else None)

    _show_conn_matrix(data_inh_n,
                      'Inhibitory (GABA) conns to neurons',
                      all_neuron_info,
                      all_neuron_info,
                      net.id,
                      save_figure_to='%s/%s_inh_to_neurons.png' %
                      (save_fig_dir, net.id) if save_fig_dir else None)
    _show_conn_matrix(data_inh_m,
                      'Inhibitory (GABA) conns to muscles',
                      all_neuron_info,
                      all_muscle_info,
                      net.id,
                      save_figure_to='%s/%s_inh_to_muscles.png' %
                      (save_fig_dir, net.id) if save_fig_dir else None)

    data_n = np.zeros((len(all_neurons), len(all_neurons)))
    data_n_m = np.zeros((len(all_neurons), len(all_muscles)))
    data_m_m = np.zeros((len(all_muscles), len(all_muscles)))

    neuron_muscle = False
    muscle_muscle = False

    for pre in gj_conns.keys():
        for post in gj_conns[pre].keys():
            c302.print_(
                "Elect Conn %s -> %s: %s" % (pre, post, gj_conns[pre][post]),
                verbose)

            if pre in all_neurons and post in all_neurons:
                data_n[all_neurons.index(pre),
                       all_neurons.index(post)] = gj_conns[pre][post]
            elif pre in all_neurons and post in all_muscles or pre in all_muscles and post in all_neurons:
                if pre in all_neurons:
                    data_n_m[all_neurons.index(pre),
                             all_muscles.index(post)] = gj_conns[pre][post]
                else:
                    data_n_m[all_muscles.index(pre),
                             all_neurons.index(post)] = gj_conns[pre][post]
                neuron_muscle = True
            elif pre in all_muscles and post in all_muscles:
                muscle_muscle = True
                data_m_m[all_muscles.index(pre),
                         all_muscles.index(post)] = gj_conns[pre][post]
            else:
                raise Exception("Unexpected...")

    _show_conn_matrix(data_n,
                      'Electrical (gap junction) conns to neurons',
                      all_neuron_info,
                      all_neuron_info,
                      net.id,
                      save_figure_to='%s/%s_elec_neurons_neurons.png' %
                      (save_fig_dir, net.id) if save_fig_dir else None)

    if neuron_muscle:
        _show_conn_matrix(
            data_n_m,
            'Electrical (gap junction) conns between neurons and muscles',
            all_neuron_info,
            all_muscle_info,
            net.id,
            save_figure_to='%s/%s_elec_neurons_muscles.png' %
            (save_fig_dir, net.id) if save_fig_dir else None)

    if muscle_muscle:
        _show_conn_matrix(data_m_m,
                          'Electrical (gap junction) conns between muscles',
                          all_muscle_info,
                          all_muscle_info,
                          net.id,
                          save_figure_to='%s/%s_elec_muscles_muscles.png' %
                          (save_fig_dir, net.id) if save_fig_dir else None)
Ejemplo n.º 27
0
def test_bundle_empty_str_ident():
    with pytest.raises(ValueError, match=r'non-empty string'):
        Bundle('')
Ejemplo n.º 28
0
def test_bundle_contextualize_non_contextualizable(bundle):
    cut = Bundle(bundle.descriptor.id,
                 version=bundle.descriptor.version,
                 bundles_directory=bundle.bundles_directory)
    token = object()
    assert cut(token) == token
Ejemplo n.º 29
0
from owmeta_core.bundle import Bundle
from owmeta_core.context import Context
from owmeta_core.dataobject import DataObject


with Bundle('person_bundle') as bnd:
    ctx = bnd(Context)().stored
    for x in ctx(DataObject)(ident='http://example.org/people/mevers').load():
        assert type(x).__name__ == 'Person'
        break
    else: # no break
        raise Exception('Expected a result')