Beispiel #1
0
def test_adapt_reference(data_pool):
    """Test that we can map a Reference object to a PyOpenWorm
    Experiment object."""
    r = data_pool.get_reference()

    reference_adapter = Adapter.create(r)

    experiment = reference_adapter.get_pow()
    reference = reference_adapter.get_cw()

    PyOpenWorm.connect()

    pyow_dict = {
        'authors': experiment.author(),
        'doi': experiment.doi(),
        'pmid': experiment.pmid(),
        'title': experiment.title(),
        'url': experiment.uri(),
        'year': experiment.year(),
    }

    cw_dict = {
        'authors': set([reference.authors]),
        'doi': reference.doi,
        'pmid': reference.PMID,
        'title': reference.title,
        'url': set([reference.url]),
        'year': reference.year
    }

    PyOpenWorm.disconnect()

    assert pyow_dict == cw_dict
Beispiel #2
0
def serialize_as_n3():
    dest = '../WormData.n3'
    # XXX: Properties aren't initialized until the first object of a class is created,
    #      so we create them here

    P.config('rdf.graph').serialize(dest, format='n3')
    print('serialized to n3 file')
Beispiel #3
0
def serialize_as_n3():
    dest = "../WormData.n3"
    # XXX: Properties aren't initialized until the first object of a class is created,
    #      so we create them here

    P.config("rdf.graph").serialize(dest, format="n3")
    print("serialized to n3 file")
 def read(self):
     conns = []
     cells = []
     
     cell_names = owr.get_cells_in_model()
 
     for s in self.all_connections:
         pre = str(s.pre_cell().name())
         post = str(s.post_cell().name())
         
         if isinstance(s.post_cell(), P.Neuron) and pre in cell_names and post in cell_names:  
             syntype = str(s.syntype())
             syntype = syntype[0].upper()+syntype[1:]
             num = int(s.number())
             synclass = str(s.synclass())
             ci = ConnectionInfo(pre, post, num, syntype, synclass)
             conns.append(ci)
             if pre not in cells:
                 cells.append(pre)
             if post not in cells:
                 cells.append(post)
                 
     logger.info("Total cells read " + str(len(cells)))
     logger.info("Total connections read " + str(len(conns)))
     P.disconnect()
     return cells, conns
    def __init__(self, cw_obj):
        # initialize PyOpenWorm connection so we can access its API
        P.connect()

        self.channelworm_object = cw_obj
        cw_dict = model_to_dict(self.channelworm_object)

        experiment_id = cw_dict.pop('experiment')
        patch_clamp_id = cw_dict.pop('id')

        self.pyopenworm_object = P.Experiment()
        
        # get the CW model's experiment
        cw_evidence = C.Experiment.objects.get(id=experiment_id)

        # make a PyOW evidence object with it
        pow_evidence = P.Evidence(doi=cw_evidence.doi)

        # add it to the PyOW experiment model
        self.pyopenworm_object.reference(pow_evidence)

        for key, value in cw_dict.iteritems():
            self.pyopenworm_object.conditions.set(key, value)

        # we not longer need PyOW API so we can kill the connection
        P.disconnect()
Beispiel #6
0
def do_insert(config="default.conf", logging=False):
    if config:
        if isinstance(config, P.Configure):
            pass
        elif isinstance(config, str):
            config = P.Configure.open(config)
        elif isinstance(config, dict):
            config = P.Configure().copy(config)
        else:
            raise Exception("Invalid configuration object "+ str(config))

    P.connect(conf=config, do_logging=logging)
    try:
        w = P.Worm()
        net = P.Network()
        w.neuron_network(net)
        w.save()

        upload_neurons()
        upload_muscles()
        upload_lineage_and_descriptions()
        upload_synapses()
        upload_receptors_and_innexins()
        upload_types()
        serialize_as_n3()
        #infer()
    except:
        traceback.print_exc()
    finally:
        P.disconnect()
Beispiel #7
0
    def __init__(self, cw_obj):
        self.channelworm_object = cw_obj
        self.map_properties()

        P.connect()
        self.pyopenworm_object.set_data(cw_obj.asarray())
        P.disconnect()
Beispiel #8
0
    def __init__(self, cw_obj):
        self.channelworm_object = cw_obj
        self.map_properties()

        P.connect()
        # mapping evidence to Assertions
        pmids = cw_obj.expression_evidences.split(', ')
        for pmid in pmids:
            e = P.Evidence()
            e.pmid(pmid)
            e.asserts(self.pyopenworm_object.expression_pattern)
            e.save()

        pmids = cw_obj.description_evidences.split(', ')
        for pmid in pmids:
            e = P.Evidence()
            e.pmid(pmid)
            e.asserts(self.pyopenworm_object.description)
            e.save()

        # proteins in CW are ;-delimited, but should be 
        #multiple values in PyOpenWorm
        pros = cw_obj.proteins.split('; ')
        for p in pros:
            self.pyopenworm_object.proteins(p)
 def __init__(self):
     logger.info("Initialising OpenWormReader")
     P.connect()
     self.net = P.Worm().get_neuron_network()
     self.all_connections = self.net.synapses()
     self.neuron_connections = set(filter(lambda x: x.termination() == u'neuron', self.all_connections))
     self.muscle_connections = set(filter(lambda x: x.termination() == u'muscle', self.all_connections))
     logger.info("Finished initialising OpenWormReader")
Beispiel #10
0
 def setUp(self):
     # Set do_logging to True if you like walls of text
     self.TestConfig = Configure.open(TEST_CONFIG)
     td = '__tempdir__'
     z = self.TestConfig['rdf.store_conf']
     if z.startswith(td):
         x = z[len(td):]
         h=tempfile.mkdtemp()
         self.TestConfig['rdf.store_conf'] = h + x
     self.delete_dir()
     PyOpenWorm.connect(conf=self.TestConfig, do_logging=False)
Beispiel #11
0
def serialize_as_n3():
    dest = '../WormData.n3'
    # XXX: Properties aren't initialized until the first object of a class is created,
    #      so we create them here

    for x in dir(P):
        if isinstance(getattr(P, x), type) and issubclass(getattr(P, x), P.DataObject):
            c = getattr(P, x)
            if x == 'values':
                c("dummy")
            else:
                c()
    P.config('rdf.graph').serialize(dest, format='n3')
    print('serialized to n3 file')
Beispiel #12
0
def test_adapt_GraphData(data_pool):
    """
    Test that we can map some GraphData to a PyOpenWorm 
    data object.
    """
    graph_data = data_pool.get_graph_data()
    gda = Adapter.create(graph_data)

    cw_obj = gda.get_cw()
    pow_obj = gda.get_pow()

    PyOpenWorm.connect()

    assert cw_obj.asarray() == pow_obj.data

    PyOpenWorm.disconnect()
Beispiel #13
0
    def map_properties(self):
        """
        Map between the properties defined in the subclass.
        """

        # initialize PyOpenWorm connection so we can access its API
        P.connect()

        # initialize pyopenworm object
        self.pyopenworm_object = self.pyopenworm_class()

        for p, c in self.pyow_to_cw.items():
            cw_value = getattr(self.channelworm_object, c)
            pow_property = getattr(self.pyopenworm_object, p)
            map(pow_property, [cw_value])

        P.disconnect()
    def read(self):
        conns = []
        cells = []
        for s in self.all_connections:
            pre = str(s.pre_cell())
            post = str(s.post_cell())
            syntype = str(s.syntype())
            num = int(s.number())
            synclass = str(s.synclass())

            conns.append(ConnectionInfo(pre, post, num, syntype, synclass))

            if pre not in cells:
                cells.append(pre)
            if post not in cells:
                cells.append(post)

        logger.info("Total cells read " + str(len(cells)))
        logger.info("Total connections read " + str(len(conns)))
        P.disconnect()
        return cells, conns
Beispiel #15
0
def do_insert(config="default.conf", logging=False):
    global SQLITE_EVIDENCE
    global WORM
    global NETWORK

    if config:
        if isinstance(config, P.Configure):
            pass
        elif isinstance(config, str):
            config = P.Configure.open(config)
        elif isinstance(config, dict):
            config = P.Configure().copy(config)
        else:
            raise Exception("Invalid configuration object " + str(config))

    P.connect(conf=config, do_logging=logging)
    SQLITE_EVIDENCE = P.Evidence(key="C_elegans_SQLite_DB", title="C. elegans sqlite database")
    try:
        WORM = P.Worm()
        NETWORK = P.Network()
        WORM.neuron_network(NETWORK)
        NETWORK.worm(WORM)

        upload_neurons()
        upload_muscles()
        upload_lineage_and_descriptions()
        upload_connections()
        upload_receptors_types_neurotransmitters_neuropeptides_innexins()

        print("Saving...")
        WORM.save()

        infer()
        print("Serializing...")
        serialize_as_n3()

    except:
        traceback.print_exc()
    finally:
        P.disconnect()
Beispiel #16
0
def test_adapt_PatchClamp(data_pool):
    """
    Test that we can map a PatchClamp object to a PyOpenWorm
    PatchClamp object.
    """
    pc = data_pool.get_patch_clamp()

    pca = Adapter.create(pc)

    cw_obj = pca.get_cw()
    pow_obj = pca.get_pow()

    PyOpenWorm.connect()

    pow_dict = {
        'delta_t': pow_obj.delta_t(),
        'duration': pow_obj.duration(),
        'end_time': pow_obj.end_time(),
        'ion_channel': pow_obj.ion_channel(),
        'protocol_end': pow_obj.protocol_end(),
        'protocol_start': pow_obj.protocol_start(),
        'protocol_step': pow_obj.protocol_step(),
        'start_time': pow_obj.start_time(),
    }

    cw_dict = {
        'delta_t': cw_obj.deltat,
        'duration': cw_obj.duration,
        'end_time': cw_obj.end_time,
        'ion_channel': cw_obj.ion_channel,
        'protocol_end': cw_obj.protocol_end,
        'protocol_start': cw_obj.protocol_start,
        'protocol_step': cw_obj.protocol_step,
        'start_time': cw_obj.start_time,
    }

    PyOpenWorm.disconnect()

    assert cw_dict == pow_dict
Beispiel #17
0
def do_insert():
    import sys
    logging = False
    if len(sys.argv) > 1 and sys.argv[1] == '-l':
        logging = True
    P.connect(configFile='default.conf', do_logging=logging)
    try:
        upload_muscles()
        print ("uploaded muscles")
        upload_lineage_and_descriptions()
        print ("uploaded lineage and descriptions")
        upload_synapses()
        print ("uploaded synapses")
        upload_receptors_and_innexins()
        print ("uploaded receptors and innexins")
        update_neurons_and_muscles_with_lineage_and_descriptions()
        print ("updated muscles and neurons with cell data")
        infer()
        print ("filled in with inferred data")
    except:
        traceback.print_exc()
    finally:
        P.disconnect()
Beispiel #18
0
 def setUp(self):
     # Set do_logging to True if you like walls of text
     self.TestConfig = Data.open(TEST_CONFIG)
     td = '__tempdir__'
     z = self.TestConfig['rdf.store_conf']
     if z.startswith(td):
         x = z[len(td):]
         h = tempfile.mkdtemp()
         self.TestConfig['rdf.store_conf'] = h + x
     self.delete_dir()
     self.connection = PyOpenWorm.connect(conf=self.TestConfig, do_logging=False)
     self.context = Context(ident='http://example.org/test-context',
                            conf=self.TestConfig)
     typ = type(self)
     if hasattr(typ, 'ctx_classes'):
         if isinstance(dict, typ.ctx_classes):
             self.ctx = self.context(typ.ctx_classes)
         else:
             self.ctx = self.context({x.__name__: x for x in typ.ctx_classes})
Beispiel #19
0
    def get(self, **kwargs):
        """Get a list of neighboring neurons.

           Parameters
           ----------
           See parameters for PyOpenWorm.connection.Connection

           Returns
           -------
           list of Neuron
        """
        if len(self._conns) > 0:
            for c in self._conns:
                for post in c.post_cell.get():
                    yield post
        else:
            c = P.Connection(pre_cell=self.owner, **kwargs)
            for r in c.load():
                yield r.post_cell()
Beispiel #20
0
                def add_synapse(source, target):
                    c = P.Connection(pre_cell=source,
                                     post_cell=target,
                                     number=weight,
                                     syntype=syn_type)
                    n.synapse(c)
                    e.asserts(c)

                    if isinstance(source, P.Neuron) and isinstance(
                            target, P.Neuron):
                        c.termination('neuron')
                    elif isinstance(source, P.Neuron) and isinstance(
                            target, P.Muscle):
                        c.termination('muscle')
                    elif isinstance(source, P.Muscle) and isinstance(
                            target, P.Neuron):
                        c.termination('muscle')

                    return c
Beispiel #21
0
    def test_verify_neurons_have_evidence(self):
        """ For each neuron in PyOpenWorm, verify
        that there is supporting evidence"""

        neurons = list(P.Neuron().load())
        evcheck = []
        for n in neurons:

            hasEvidence = len(get_supporting_evidence(n)) + len(
                get_supporting_evidence(n.neurotransmitter)) + len(
                    get_supporting_evidence(n.type)) + len(
                        get_supporting_evidence(n.innexin)) + len(
                            get_supporting_evidence(n.neuropeptide)) + len(
                                get_supporting_evidence(n.receptor))

            print get_supporting_evidence(n.neurotransmitter)

            evcheck.append(hasEvidence)

        self.assertTrue(0 not in evcheck,
                        "There appears to be no evidence: " + str(evcheck))
 def setUp(self):
     # Set do_logging to True if you like walls of text
     self.TestConfig = Data.open(TEST_CONFIG)
     td = '__tempdir__'
     z = self.TestConfig['rdf.store_conf']
     if z.startswith(td):
         x = z[len(td):]
         h = tempfile.mkdtemp()
         self.TestConfig['rdf.store_conf'] = h + x
     self.delete_dir()
     self.connection = PyOpenWorm.connect(conf=self.TestConfig,
                                          do_logging=False)
     self.context = Context(ident='http://example.org/test-context',
                            conf=self.TestConfig)
     typ = type(self)
     if hasattr(typ, 'ctx_classes'):
         if isinstance(dict, typ.ctx_classes):
             self.ctx = self.context(typ.ctx_classes)
         else:
             self.ctx = self.context(
                 {x.__name__: x
                  for x in typ.ctx_classes})
Beispiel #23
0
    def aneuron(self, name):
        """
        Get a neuron by name.

        Example::

            # Grabs the representation of the neuronal network
            >>> net = P.Worm().get_neuron_network()

            # Grab a specific neuron
            >>> aval = net.aneuron('AVAL')

            >>> aval.type()
            set([u'interneuron'])


        :param name: Name of a c. elegans neuron
        :returns: Neuron corresponding to the name given
        :rtype: PyOpenWorm.Neuron
        """
        n = P.Neuron(name=name,conf=self.conf)
        return n
Beispiel #24
0
def update_neurons_and_muscles_with_lineage_and_descriptions():
    v = P.values('neurons and muscles')
    #XXX: This could be expensive...the lineage name and description should be loaded with
    #     the cell though.
    cells = {next(x.name()) : (norn(x.lineageName()), norn(x.description())) for x in P.Cell().load() }
    def dtt(x):
        """ Do the thing """
        try:
            name = next(x.name())
            if cells[name][0] is not None:
                x.lineageName(cells[name][0])
            if cells[name][1] is not None:
                x.description(cells[name][1])
            v.value(x)
        except:
            traceback.print_exc()
    for x in P.Neuron().load():
        dtt(x)
    for x in P.Muscle().load():
        dtt(x)

    v.save()
    def setUpClass(cls):
        import csv
        PyOpenWorm.connect(
            conf=Configure(
                **{'rdf.store_conf': 'tests/test.db', 'rdf.source': 'ZODB'}))
        PyOpenWorm.loadData(skipIfNewer=False)
        PyOpenWorm.disconnect()
        # grab the list of the names of the 302 neurons

        csvfile = open('OpenWormData/aux_data/neurons.csv', 'r')
        reader = csv.reader(csvfile, delimiter=';', quotechar='|')

        # array that holds the names of the 302 neurons at class-level scope
        cls.neurons = []
        for row in reader:
            if len(row[0]) > 0:  # Only saves valid neuron names
                cls.neurons.append(row[0])
Beispiel #26
0
    def set(self, ob, **kwargs):
        self.real_neighbor(ob)
        if isinstance(ob, NeuronClass):
            ob_name = ob.name()
            this_name = self.owner.name()
            for x in ob.member():
                # Get the name for the neighbor
                # XXX:

                try:
                    n = x.name()
                    side = n[n.find(ob_name) + len(ob_name):]

                    name_here = this_name + side
                    this_neuron = P.Neuron(name_here)
                    self.owner.member(this_neuron)
                    this_neuron.neighbor(x, **kwargs)
                except ValueError:
                    # XXX: could default to all-to-all semantics
                    print 'Do not recoginze the membership of this neuron/neuron class', ob
        elif isinstance(ob, Neuron):
            for x in self.owner.member:
                x.neighbor(ob)
    def setUpClass(cls):
        import csv
        PyOpenWorm.connect(conf=Configure(
            **{
                'rdf.store_conf': 'tests/test.db',
                'rdf.source': 'ZODB'
            }))
        PyOpenWorm.loadData(skipIfNewer=False)
        PyOpenWorm.disconnect()
        # grab the list of the names of the 302 neurons

        csvfile = open('OpenWormData/aux_data/neurons.csv', 'r')
        reader = csv.reader(csvfile, delimiter=';', quotechar='|')

        # array that holds the names of the 302 neurons at class-level scope
        cls.neurons = []
        for row in reader:
            if len(row[0]) > 0:  # Only saves valid neuron names
                cls.neurons.append(row[0])
    def setUpClass(cls):
        import csv

        cls.neurons = [] #array that holds the names of the 302 neurons at class-level scope

        if not USE_BINARY_DB:
            PyOpenWorm.connect(conf=Data()) # Connect for integrity tests that use PyOpenWorm functions
            cls.g = PyOpenWorm.config('rdf.graph') # declare class-level scope for the database
            cls.g.parse("OpenWormData/WormData.n3", format="n3") # load in the database
        else:
            conf = Configure(**{ "rdf.source" : "ZODB", "rdf.store_conf" : BINARY_DB })
            PyOpenWorm.connect(conf=conf)
            cls.g = PyOpenWorm.config('rdf.graph')

        #grab the list of the names of the 302 neurons

        csvfile = open('OpenWormData/aux_data/neurons.csv', 'r')
        reader = csv.reader(csvfile, delimiter=';', quotechar='|')

        for row in reader:
            if len(row[0]) > 0: # Only saves valid neuron names
                cls.neurons.append(row[0])
Beispiel #29
0
 def test_network_neurons(self):
     self.assertTrue('AVAL' in PyOpenWorm.Network().neurons())
     self.assertTrue('DD5' in PyOpenWorm.Network().neurons())
     self.assertEquals(len(PyOpenWorm.Network().neurons()), 302)
Beispiel #30
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     self.ctx = None
     self.worm = None
     self.net = None
     P.disconnect()
Beispiel #31
0
def upload_lineage_and_descriptions():
    """ Upload lineage names and descriptions pulled from the WormAtlas master cell list

    Assumes that Neurons and Muscles have already been added
    """
    # XXX: This wants a way to insert cells, then later, to insert neurons from the same set
    # and have the later recoginzed as the former. Identifier matching limits us here. It would
    # be best to establish owl:sameAs links to the super class (Cell) from the subclass (Neuron)
    # at the sub-class insert and have a reasoner relate
    # the two sets of inserts.
    cells = dict()
    try:
        w = P.Worm()
        net = w.neuron_network.one()
        ev = P.Evidence(uri="http://www.wormatlas.org/celllist.htm")
        # insert neurons.
        # save
        cell_data = open(LINEAGE_LIST_LOC, "r")

        # Skip headers
        next(cell_data)

        cell_name_counters = dict()
        data = dict()
        for x in cell_data:
             j = [x.strip().strip("\"") for x in x.split("\t")]
             name = j[0]
             lineageName = j[1]
             desc = j[2]

             # XXX: These renaming choices are arbitrary and may be inappropriate
             if name == "DB1/3":
                 name = "DB1"
             elif name == "DB3/1":
                 name = "DB3"
             elif name == "AVFL/R":
                 if lineageName[0] == "W":
                     name = "AVFL"
                 elif lineageName[0] == "P":
                     name = "AVFR"

             if name in cell_name_counters:
                 while (name in cell_name_counters):
                     cell_name_counters[name] += 1
                     name = name + "("+ str(cell_name_counters[name]) +")"
             else:
                 cell_name_counters[name] = 0

             data[name] = {"lineageName" : lineageName, "desc": desc}

        for n in net.neuron():
             name = n.name.one()
             neuron_data = data[str(name)]
             n.lineageName(neuron_data['lineageName'])
             n.description(neuron_data['desc'])
             w.cell(n)

        ev.asserts(w)
        ev.save()
    except Exception, e:
        traceback.print_exc()
Beispiel #32
0
 def test_muscle(self):
     self.assertTrue(
         isinstance(PyOpenWorm.Muscle('MDL08'), PyOpenWorm.Muscle))
Beispiel #33
0
 def test_worm_get_network(self):
     self.assertTrue(
         isinstance(PyOpenWorm.Worm().get_neuron_network(),
                    PyOpenWorm.Network))
Beispiel #34
0
 def test_network_as_networkx(self):
     self.assertTrue(
         isinstance(PyOpenWorm.Network().as_networkx(), networkx.DiGraph))
Beispiel #35
0
 def test_neuron_name(self):
     self.assertEquals(PyOpenWorm.Network().aneuron('AVAL').name(), 'AVAL')
     self.assertEquals(PyOpenWorm.Network().aneuron('AVAR').name(), 'AVAR')
Beispiel #36
0
"""
How to reference supporting evidence for some object in the database.

See: "Metadata in PyOpenWorm" for discussion on semantics of what giving
evidence for an object means.
"""

import sys
import PyOpenWorm as P

#Create dummy database configuration.
d = P.Data({})

#Connect to database with dummy configuration
P.connect(conf=d)

#Create a new Neuron object to work with
n = P.Neuron(name='AVAL')

#Create a new Evidence object with `doi` and `pmid` fields populated.
#See `PyOpenWorm/evidence.py` for other available fields.
e = P.Evidence(doi='125.41.3/ploscompbiol', pmid='57182010')

#Evidence object asserts something about the enclosed dataObject.
#Here we add a receptor to the Neuron we made earlier, and "assert it".
#As the discussion (see top) reads, this might be asserting the existence of
#receptor UNC-8 on neuron AVAL.
e.asserts(n.receptor('UNC-8'))

#Save the Neuron and Evidence objects to the database.
n.save()
Beispiel #37
0
"""

from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.evidence import Evidence
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.document import Document
from PyOpenWorm.data import Data
from PyOpenWorm.context import Context

# Create dummy database configuration.
d = Data()

# Connect to database with dummy configuration
conn = P.connect(conf=d)

ctx = Context(ident='http://example.org/data', conf=conn.conf)
evctx = Context(ident='http://example.org/meta', conf=conn.conf)

# Create a new Neuron object to work with
n = ctx(Neuron)(name='AVAL')

# Create a new Evidence object with `doi` and `pmid` fields populated.
# See `PyOpenWorm/evidence.py` for other available fields.
d = evctx(Document)(key='Anonymous2011', doi='125.41.3/ploscompbiol', pmid='12345678')
e = evctx(Evidence)(key='Anonymous2011', reference=d)

# Evidence object asserts something about the enclosed dataObject.
# Here we add a receptor to the Neuron we made earlier, and "assert it".
# As the discussion (see top) reads, this might be asserting the existence of
Beispiel #38
0
Note how the attributes of a neuron are accessed: `list(neuron.attribute())`
where attribute is one of the attributes outlined in the neuron API.

Also note that, for attributes with only one value, the value can be accessed by
doing `neuron.attribute.one()`.

Example: Something like `adal.name.one()` might return "ADAL", assuming we have
declared the variable `adal`.
"""

from __future__ import print_function
from __future__ import absolute_import
import PyOpenWorm as P
import os
print(os.getcwd())
P.connect('default.conf')


def get_names(it):
    res = []
    for x in it:
        res.append(x.name())
    return res


w = P.Worm()
net = w.neuron_network()
print("Retrieving names...")
inter = get_names(net.interneurons())
motor = get_names(net.motor())
sensory = get_names(net.sensory())
"""

from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.evidence import Evidence
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.document import Document
from PyOpenWorm.data import Data
from PyOpenWorm.context import Context

# Create dummy database configuration.
d = Data()

# Connect to database with dummy configuration
conn = P.connect(conf=d)

ctx = Context(ident='http://example.org/data', conf=conn.conf)
evctx = Context(ident='http://example.org/meta', conf=conn.conf)

# Create a new Neuron object to work with
n = ctx(Neuron)(name='AVAL')

# Create a new Evidence object with `doi` and `pmid` fields populated.
# See `PyOpenWorm/evidence.py` for other available fields.
d = evctx(Document)(key='Anonymous2011',
                    doi='125.41.3/ploscompbiol',
                    pmid='12345678')
e = evctx(Evidence)(key='Anonymous2011', reference=d)

# Evidence object asserts something about the enclosed dataObject.
 def tearDownClass(cls):
     PyOpenWorm.disconnect()
 def tearDown(self):
     PyOpenWorm.disconnect()
Beispiel #42
0
 def test_worm_muscles(self):
     self.assertTrue('MDL08' in PyOpenWorm.Worm().muscles())
     self.assertTrue('MDL15' in PyOpenWorm.Worm().muscles())
Beispiel #43
0
 def test_neuron_type(self):
     self.assertEquals(PyOpenWorm.Network().aneuron('AVAL').type(),
                       'interneuron')
     self.assertEquals(PyOpenWorm.Network().aneuron('DD5').type(), 'motor')
     self.assertEquals(PyOpenWorm.Network().aneuron('PHAL').type(),
                       'sensory')
Also note that, for attributes with only one value, the value can be accessed by
doing `neuron.attribute.one()`.

Example: Something like `adal.name.one()` might return "ADAL", assuming we have
declared the variable `adal`.
"""

from __future__ import print_function
from __future__ import absolute_import
import PyOpenWorm as P
from PyOpenWorm.worm import Worm
from PyOpenWorm.context import Context
from OpenWormData import BIO_ENT_NS
import os
print(os.getcwd())
conn = P.connect('default.conf')


def get_names(it):
    res = []
    for x in it:
        res.append(x.name())
    return res


ctx = Context(ident=BIO_ENT_NS['worm0'], conf=conn.conf).stored

w = ctx(Worm)()
net = w.neuron_network()
print("Retrieving names...")
inter = get_names(net.interneurons())
Beispiel #45
0
 def test_neuron_Syn_degree(self):
     self.assertEquals(PyOpenWorm.Network().aneuron('AVAL').Syn_degree(),
                       74)
 def setUpClass(self):
     PyOpenWorm.connect()
     PyOpenWorm.loadData(skipIfNewer=False)
     PyOpenWorm.disconnect()
     os.chdir('examples')
Beispiel #47
0
 def test_neuron_receptors(self):
     self.assertTrue('GLR-2' in PyOpenWorm.Neuron('AVAL').receptors())
     self.assertTrue('OSM-9' in PyOpenWorm.Neuron('PHAL').receptors())
Beispiel #48
0
Try running this script and see what it prints out. It takes a while to run
because there are so many connections, so feel free to comment out some of the
neuron names in the arbitrary list declared further below.
"""
from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.worm import Worm
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.context import Context
from OpenWormData import BIO_ENT_NS


print("Connecting to the database...")
conn = P.connect('default.conf')

ctx = Context(ident=BIO_ENT_NS['worm0'], conf=conn.conf).stored

#Get the worm object.
worm = ctx(Worm)()

#Extract the network object from the worm object.
net = worm.neuron_network()

#Make a list of some arbitrary neuron names.
some_neuron_names = ["ADAL", "AIBL", "I1R", "PVCR", "DD5"]

#Go through our list and get the neuron object associated with each name.
#Store these in another list.
some_neurons = [ctx(Neuron)(name) for name in some_neuron_names]
Beispiel #49
0
 def test_neuron_get_reference(self):
     self.assertEquals(
         PyOpenWorm.Neuron('ADER').get_reference(0, 'EXP-1'),
         ['http://dx.doi.org/10.100.123/natneuro'])
     self.assertEquals(
         PyOpenWorm.Neuron('ADER').get_reference(0, 'DOP-2'), None)
Beispiel #50
0
 def test_network(self):
     self.assertTrue(isinstance(PyOpenWorm.Network(), PyOpenWorm.Network))
Beispiel #51
0
def my_signal_handler(signal, frame):
    P.disconnect()
    sys.exit(0)
Beispiel #52
0
 def test_network_aneuron(self):
     self.assertTrue(
         isinstance(PyOpenWorm.Network().aneuron('AVAL'),
                    PyOpenWorm.Neuron))
Beispiel #53
0
def serialize_as_nquads():
    P.config('rdf.graph').serialize('WormData.n4', format='nquads')
    print('serialized to nquads file')
 def setUp(self):
     PyOpenWorm.connect(configFile='tests/data_integrity_test.conf')
     self.g = PyOpenWorm.config("rdf.graph")
     self.context = Context()
     self.qctx = self.context.stored
 def tearDown(self):
     PyOpenWorm.disconnect()
Beispiel #56
0
def do_insert(ident,
              config="default.conf",
              logging=False,
              imports_context_ident=None,
              basedir=aux_data()):

    sources = init_sources()
    extras = init_extra_sources(basedir)
    data_sources_by_key = {x.key: x for x in sources + extras}
    trans_map = init_translators() + init_extra_neuron_data_translators(extras)
    P.connect(configFile=config, do_logging=logging)
    P.config()

    CTX = Context(ident=ident + '-data',
                  imported=(P.CONTEXT, ),
                  conf=P.config())

    EVCTX = Context(ident=ident + '-evidence',
                    imported=(P.CONTEXT, ),
                    conf=P.config())

    IWCTX = Context(ident=ident, imported=(CTX, EVCTX), conf=P.config())

    imports_context = Context(ident=imports_context_ident, conf=P.config())

    try:
        t0 = time()
        translators = dict()
        remaining = list(trans_map)
        last_remaining = None
        saved_contexts = set([])
        while remaining != last_remaining:
            next_remaining = []
            for t in remaining:
                if not isinstance(t[0], (list, tuple)):
                    source_keys = (t[0], )
                else:
                    source_keys = t[0]

                sources = tuple(
                    data_sources_by_key.get(s) for s in source_keys)
                if None in sources:
                    next_remaining.append(t)
                    continue
                translator_class = t[1]
                if len(t) > 2:
                    output_key = t[2]
                else:
                    output_key = None
                translator = translators.get(translator_class, None)
                if not translator:
                    translator = translator_class()
                    translators[translator_class] = translator

                print('\n'.join(
                    'Input({}/{}): {}'.format(i + 1, len(sources), s)
                    for i, s in enumerate(sources)))
                print('Translating with {}'.format(translator))
                orig_wd = os.getcwd()
                os.chdir(basedir)
                try:
                    res = translator(*sources, output_key=output_key)
                finally:
                    os.chdir(orig_wd)

                print('Result: {}'.format(res))
                if isinstance(res, DataWithEvidenceDataSource):
                    res.data_context.save_context(
                        inline_imports=True, saved_contexts=saved_contexts)
                    res.data_context.save_imports(imports_context)
                    res.evidence_context.save_context(
                        inline_imports=True, saved_contexts=saved_contexts)
                    res.evidence_context.save_imports(imports_context)
                    for ctx in res.contexts:
                        raise Exception()

                if res:
                    if res.key:
                        data_sources_by_key[res.key] = res
                    else:
                        data_sources_by_key[res.identifier] = res
            last_remaining = list(remaining)
            remaining = next_remaining
        for x in remaining:
            warn("Failed to process: {}".format(x))

        # attach_neuromlfiles_to_channel()

        t1 = time()
        print("Saving data...")
        graph = P.config('rdf.graph')
        for src in data_sources_by_key.values():
            if isinstance(src, DataWithEvidenceDataSource):
                print('saving', src)
                CTX.add_import(src.data_context)
                EVCTX.add_import(src.evidence_context)
                for ctx in src.contexts:
                    IWCTX.add_import(ctx)
        IWCTX.save_context(graph, saved_contexts=saved_contexts)
        IWCTX.save_imports(imports_context)
        print('imports context size', len(imports_context))
        print("Saved %d triples." % IWCTX.triples_saved)
        t2 = time()

        print("Serializing...")
        serialize_as_nquads()
        t3 = time()
        print("generating objects took", t1 - t0, "seconds")
        print("saving objects took", t2 - t1, "seconds")
        print("serializing objects took", t3 - t2, "seconds")

    except Exception:
        traceback.print_exc()
    finally:
        P.disconnect()
 def setUp(self):
     PyOpenWorm.connect(configFile='tests/data_integrity_test.conf')
     self.g = PyOpenWorm.config("rdf.graph")
     self.context = Context()
     self.qctx = self.context.stored
Beispiel #58
0
from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P

P.connect('default.conf')

class NC_neighbor(P.Property):
    def __init__(self, *args, **kwargs):
        P.Property.__init__(self, '_nb', *args, **kwargs)
        self.real_neighbor = self.owner.neighbor

        # Re-assigning neighbor Property
        self.owner.neighbor = self

    def get(self,**kwargs):
        # get the members of the class
        for x in self.owner.neighbor():
            yield x

    def set(self, ob, **kwargs):
        self.real_neighbor(ob)
        if isinstance(ob, NeuronClass):
            ob_name = ob.name()
            this_name = self.owner.name()
            for x in ob.member():
                # Get the name for the neighbor
                # XXX:

                try:
                    n = x.name()
                    side = n[n.find(ob_name)+len(ob_name):]
Beispiel #59
0
"""

from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.evidence import Evidence
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.document import Document
from PyOpenWorm.data import Data
from PyOpenWorm.context import Context

# Create dummy database configuration.
d = Data({'rdf.source': 'ZODB'})

# Connect to database with dummy configuration
P.connect(conf=d)

ctx = Context(ident='http://example.org/data')
evctx = Context(ident='http://example.org/meta')

# Create a new Neuron object to work with
n = ctx(Neuron)(name='AVAL')

# Create a new Evidence object with `doi` and `pmid` fields populated.
# See `PyOpenWorm/evidence.py` for other available fields.
d = evctx(Document)(key='Anonymous2011', doi='125.41.3/ploscompbiol', pmid='12345678')
e = evctx(Evidence)(key='Anonymous2011', reference=d)

# Evidence object asserts something about the enclosed dataObject.
# Here we add a receptor to the Neuron we made earlier, and "assert it".
# As the discussion (see top) reads, this might be asserting the existence of
 def __init__(self):
     logger.info("Initialising OpenWormReader")
     P.connect()
     self.net = P.Worm().get_neuron_network()
     self.all_connections = self.net.synapses()
     logger.info("Finished initialising OpenWormReader")