Beispiel #1
0
def setup(name, type):
    n = NeuronClass(name)
    n.type(type)
    n.member(P.Neuron(name + "R"))
    n.member(P.Neuron(name + "L"))
    net.neuron(n)
    return n
Beispiel #2
0
    def __init__(self,
                 pre_cell=None,
                 post_cell=None,
                 number=None,
                 syntype=None,
                 synclass=None,
                 termination=None,
                 **kwargs):
        super(Connection, self).__init__(**kwargs)

        Connection.ObjectProperty('post_cell', owner=self, value_type=Cell)
        Connection.ObjectProperty('pre_cell', owner=self, value_type=Cell)

        Connection.DatatypeProperty('number', owner=self)
        Connection.DatatypeProperty('synclass', owner=self)
        Connection.DatatypeProperty('syntype', owner=self)
        Connection.DatatypeProperty('termination', owner=self)

        if isinstance(pre_cell, P.Cell):
            self.pre_cell(pre_cell)
        elif pre_cell is not None:
            warnings.warn(
                'Passing bare strings for PyOpenWorm.Connection cells is' +
                ' deprecated. PyOpenWorm.Cell objects should be passed in' +
                ' instead.', DeprecationWarning)
            self.pre_cell(P.Neuron(name=pre_cell, conf=self.conf))

        if (isinstance(post_cell, P.Cell)):
            self.post_cell(post_cell)
        elif post_cell is not None:
            warnings.warn(
                'Passing bare strings for PyOpenWorm.Connection cells is' +
                ' deprecated. PyOpenWorm.Cell objects should be passed in' +
                ' instead.', DeprecationWarning)
            self.post_cell(P.Neuron(name=post_cell, conf=self.conf))

        if isinstance(termination, six.string_types):
            termination = termination.lower()
            if termination in ('neuron', Termination.Neuron):
                self.termination(Termination.Neuron)
            elif termination in ('muscle', Termination.Muscle):
                self.termination(Termination.Muscle)

        if isinstance(number, int):
            self.number(int(number))
        elif number is not None:
            raise Exception("Connection number must be an int, given %s" %
                            number)

        if isinstance(syntype, six.string_types):
            syntype = syntype.lower()
            if syntype in ('send', SynapseType.Chemical):
                self.syntype(SynapseType.Chemical)
            elif syntype in ('gapjunction', SynapseType.GapJunction):
                self.syntype(SynapseType.GapJunction)

        if isinstance(synclass, six.string_types):
            self.synclass(synclass)
Beispiel #3
0
    def __init__(self,
                 pre_cell=None,
                 post_cell=None,
                 number=None,
                 syntype=None,
                 synclass=None,
                 termination=None,
                 **kwargs):
        super(Connection, self).__init__(**kwargs)

        Connection.ObjectProperty('post_cell', owner=self, value_type=Cell)
        Connection.ObjectProperty('pre_cell', owner=self, value_type=Cell)

        Connection.DatatypeProperty('number', owner=self)
        Connection.DatatypeProperty('synclass', owner=self)
        Connection.DatatypeProperty('syntype', owner=self)
        Connection.DatatypeProperty('termination', owner=self)

        if isinstance(pre_cell, P.Cell):
            self.pre_cell(pre_cell)
        elif pre_cell is not None:
            # TODO: don't assume that the pre_cell is a neuron
            self.pre_cell(P.Neuron(name=pre_cell, conf=self.conf))

        if (isinstance(post_cell, P.Cell)):
            self.post_cell(post_cell)
        elif post_cell is not None:
            # TODO: don't assume that the post_cell is a neuron
            self.post_cell(P.Neuron(name=post_cell, conf=self.conf))

        if isinstance(termination, basestring):
            termination = termination.lower()
            if termination in ('neuron', Termination.Neuron):
                self.termination(Termination.Neuron)
            elif termination in ('muscle', Termination.Muscle):
                self.termination(Termination.Muscle)

        if isinstance(number, int):
            self.number(int(number))
        elif number is not None:
            raise Exception("Connection number must be an int, given %s" %
                            number)

        if isinstance(syntype, basestring):
            syntype = syntype.lower()
            if syntype in ('send', SynapseType.Chemical):
                self.syntype(SynapseType.Chemical)
            elif syntype in ('gapjunction', SynapseType.GapJunction):
                self.syntype(SynapseType.GapJunction)

        if isinstance(synclass, basestring):
            self.synclass(synclass)
Beispiel #4
0
def upload_receptors_and_innexins():
    try:
        conn = sqlite3.connect(SQLITE_DB_LOC)
        cur = conn.cursor()
        w = P.Worm()
        n = P.Network()
        w.neuron_network(n)
        # insert neurons.
        # save
        # get the receptor (354) and innexin (355)
        cur.execute("""
        SELECT DISTINCT a.Entity, b.Entity
        FROM
        tblrelationship q,
        tblrelationship r,
        tblentity a,
        tblentity b
        where q.EnID1=a.id and q.Relation = '1515' and q.EnID2='1'
        and   r.EnID1=a.id and r.Relation = '354'  and r.EnID2=b.id
        """)
        for r in cur.fetchall():
            neuron_name = str(r[0])
            receptor = str(r[1])
            neur = P.Neuron(name=neuron_name)
            neur.receptor(receptor)
            n.neuron(neur)
        cur.execute("""
        SELECT DISTINCT a.Entity, b.Entity
        FROM
        tblrelationship q,
        tblrelationship r,
        tblentity a,
        tblentity b
        where q.EnID1=a.id and q.Relation = '1515' and q.EnID2='1'
        and   r.EnID1=a.id and r.Relation = '355'  and r.EnID2=b.id
        """)
        for r in cur.fetchall():
            neuron_name = str(r[0])
            innexin = str(r[1])
            neur = P.Neuron(name=neuron_name)
            neur.innexin(innexin)
            n.neuron(neur)
        n.save()
        #second step, get the relationships between them and add them to the graph
    except Exception:
        traceback.print_exc()
    finally:
        conn.close()
 def scoring_neurons(self):
     print 'calculating neuron completion scores'
     score = 0
     for n in P.Neuron().load():
         score = 0
         if len(n.type()) > 0:
             score += 1
         if len(n.receptor()) > 0:
             score += 1
         if len(n.innexin()) > 0:
             score += 1
         if len(n.neurotransmitter()) > 0:
             score += 1
         if len(n.neuropeptide()) > 0:
             score += 1
         if len(n.neighbor()) > 0:
             score += 1
         if len(n.connection()) > 0:
             score += 1
         for ch in n.channel():
             score += IonChannel.objects.get(name=str(ch.name())).completion
         score = int((float(score) / (7 + 5 * len(n.channel()))) * float(5))
         neuron = Neuron(name=n.name(), completion=score)
         neuron.save()
     print 'done'
Beispiel #6
0
def upload_neurons():
    try:
        conn = sqlite3.connect(SQLITE_DB_LOC)
        cur = conn.cursor()
        ev = P.Evidence(title="C. elegans sqlite database")
        w = P.Worm()
        n = P.Network()
        w.neuron_network(n)
        # insert neurons.
        # save
        cur.execute("""
        SELECT DISTINCT a.Entity FROM tblrelationship, tblentity a, tblentity b
        where EnID1=a.id and Relation = '1515' and EnID2='1'
        """)
        for r in cur.fetchall():
            neuron_name = str(r[0])
            n.neuron(P.Neuron(name=neuron_name))
        ev.asserts(n)
        ev.save()
        #second step, get the relationships between them and add them to the graph
        print("uploaded neurons")
    except Exception:
        traceback.print_exc()
    finally:
        conn.close()
Beispiel #7
0
def upload_types():
    import csv
    ev = P.Evidence(title="neurons.csv")
    w = P.Worm()
    net = w.neuron_network.one()

    data = dict()
    for x in csv.reader(open('../aux_data/neurons.csv'), delimiter=';'):
        types = []
        name = x[0]
        types_string = x[1]
        if 'sensory' in (types_string.lower()):
            types.append('sensory')
        if 'interneuron' in (types_string.lower()):
            types.append('interneuron')
        if 'motor' in (types_string.lower()):
            types.append('motor')
        data[name] = types

    for name in data:
        n = P.Neuron(name=name)
        types = data[name]
        for t in types:
            n.type(t)
        net.neuron(n)
    ev.asserts(net)
    ev.save()
    print("uploaded types")
Beispiel #8
0
def upload_muscles():
    """ Upload muscles and the neurons that connect to them
    """
    try:
        ev = P.Evidence(title="C. elegans sqlite database")
        conn = sqlite3.connect(SQLITE_DB_LOC)
        cur = conn.cursor()
        w = P.Worm()
        cur.execute("""
        SELECT DISTINCT a.Entity, b.Entity
        FROM tblrelationship innervatedBy, tblentity b, tblentity a, tblrelationship type_b
        WHERE innervatedBy.EnID1=a.id and innervatedBy.Relation = '1516' and innervatedBy.EnID2=b.id
        and type_b.EnID1 = b.id and type_b.Relation='1515' and type_b.EnID2='1519'
        """)  # 1519 is the
        for r in cur.fetchall():
            neuron_name = str(r[0])
            muscle_name = str(r[1])
            m = P.Muscle(muscle_name)
            n = P.Neuron(neuron_name)
            w.muscle(m)
            m.innervatedBy(n)

        ev.asserts(w)
        ev.save()
        #second step, get the relationships between them and add them to the graph
        print("uploaded muscles")
    except Exception:
        traceback.print_exc()
    finally:
        conn.close()
Beispiel #9
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)
Beispiel #10
0
def upload_neurons():
    try:
        #TODO: Improve this evidence marker
        ev = P.Evidence(title="C. elegans Cell List - WormBase.csv")
        w = WORM
        n = NETWORK
        w.neuron_network(n)
        # insert neurons.
        i = 0
        with open(CELL_NAMES_SOURCE) as csvfile:
            csvreader = csv.reader(csvfile)

            for num, line in enumerate(csvreader):
                if num < 4:  # skip rows with no data
                    continue

                if line[5] == '1':  # neurons marked in this column
                    neuron_name = normalize(line[0]).upper()
                    n.neuron(P.Neuron(name=neuron_name))
                    i = i + 1

        ev.asserts(n)
        #second step, get the relationships between them and add them to the graph
        print("uploaded " + str(i) + " neurons")
    except Exception:
        traceback.print_exc()
Beispiel #11
0
    def aneuron(self, name):
        """
		Get a neuron by name
			
		:param name: Name of a c. elegans neuron
		:returns: Corresponding neuron to the name given
		:rtype: PyOpenWorm.Neuron
		"""
        return PyOpenWorm.Neuron(name)
 def test_INS_26_neuropeptide_neuron_list(self):
     """
     This test verifies that the set of neurons which contain the
     neuropeptide INS-26 is correct (the list is given below).
     """
     neuronlist = PyOpenWorm.Neuron()
     neuronlist.neuropeptide("INS-26")
     thlist = set(x.name() for x in neuronlist.load())
     self.assertEqual(set(['ASEL', 'ASER', 'ASIL', 'ASIR']), thlist)
Beispiel #13
0
 def test_TH_neuropeptide_neuron_list(self):
     """
     This test verifies that the set of neurons which contain the
     neuropeptide TH is correct (the list is given below).
     """
     neuronlist = PyOpenWorm.Neuron()
     neuronlist.neuropeptide("TH")
     thlist = set(x.name() for x in neuronlist.load())
     self.assertEqual(
         set(['CEPDR', 'PDER', 'CEPDL', 'PDEL', 'CEPVR', 'CEPVL']), thlist)
 def get(self, request, format=None):
     Cells = []
     try:
         for neuron in P.Neuron().load():
             Cells.append(Cell(name=str(neuron.name())))
         for muscle in P.Muscle().load():
             Cells.append(Cell(name=str(muscle.name())))
     finally:
         print "done"
     serializer = CellSerializer(Cells, many=True)
     return Response(serializer.data)
    def get(self, request, format=None):

        Neurons = []
        try:
            for neuron in P.Neuron().load():
                    Neurons.append(Neuron(name=str(neuron.name())))
        finally:
            print "done"
        Neurons.sort(key=operator.attrgetter('name'))
        serializer = NeuronSerializer(Neurons, many=True)
        return Response(serializer.data)
Beispiel #16
0
    def __init__(self,
                 pre_cell=None,
                 post_cell=None,
                 number=None,
                 syntype=None,
                 synclass=None,
                 **kwargs):
        Relationship.__init__(self, **kwargs)

        Connection.DatatypeProperty('syntype', owner=self)
        Connection.ObjectProperty('pre_cell', owner=self, value_type=Neuron)
        Connection.ObjectProperty('post_cell', owner=self, value_type=Neuron)

        Connection.DatatypeProperty('synclass', owner=self)
        Connection.DatatypeProperty('number', owner=self)

        if isinstance(pre_cell, P.Neuron):
            self.pre_cell(pre_cell)
        elif pre_cell is not None:
            self.pre_cell(P.Neuron(name=pre_cell, conf=self.conf))

        if (isinstance(post_cell, P.Neuron)):
            self.post_cell(post_cell)
        elif post_cell is not None:
            self.post_cell(P.Neuron(name=post_cell, conf=self.conf))

        if isinstance(number, int):
            self.number(int(number))
        elif number is not None:
            raise Exception("Connection number must be an int, given %s" %
                            number)

        if isinstance(syntype, basestring):
            syntype = syntype.lower()
            if syntype in ('send', SynapseType.Chemical):
                self.syntype(SynapseType.Chemical)
            elif syntype in ('gapjunction', SynapseType.GapJunction):
                self.syntype(SynapseType.GapJunction)
        if isinstance(synclass, basestring):
            self.synclass(synclass)
Beispiel #17
0
def _get_cell_info(cells):

    import PyOpenWorm as P
    print("Connecting to the PyOpenWorm database...")
    P.connect()

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

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

    #Go through our list and get the neuron object associated with each name.
    #Store these in another list.
    some_neurons = [P.Neuron(name) for name in cells]
    all_neuron_info = collections.OrderedDict()
    all_muscle_info = collections.OrderedDict()
    
    for neuron in some_neurons: 
        print("=====Checking properties of: %s"%neuron)
        print neuron.triples()
        print neuron.__class__
        short = ') %s'%neuron.name()
        if 'motor' in neuron.type():
            short = 'Mo%s'%short
        if 'sensory' in neuron.type():
            short = 'Se%s'%short
        if 'interneuron' in neuron.type():
            short = 'In%s'%short
        if _is_muscle(neuron.name()):
            short = 'Mu%s'%short
            
            
        short = '(%s'%short
        
        
        if 'GABA' in neuron.neurotransmitter():
            short = '- %s'%short
        elif len(neuron.neurotransmitter())==0:
            short = '? %s'%short
        else:
            short = '+ %s'%short
            
        info = (neuron, neuron.type(), neuron.receptor(), neuron.neurotransmitter(), short)
        #print dir(neuron)
        
        if _is_muscle(neuron.name()):
            all_muscle_info[neuron.name()] = info
        else:
            all_neuron_info[neuron.name()] = info
        
    return all_neuron_info, all_muscle_info
Beispiel #18
0
    def interneurons(self):
        """
        Get all interneurons

        :returns: A iterable of all interneurons
        :rtype: iter(Neuron)
        """

        # TODO: make sure these belong to *this* Network
        n = P.Neuron()
        n.type('interneuron')

        for x in n.load():
            yield x
 def get(self,request, format=None):
     print "in cell channel get data set view"
     serializer_class = ChannelSerializer
     cellname = self.request.query_params.get('cellname', None)
     if cellname==None:
         Channels=[]
     else:
         neurons=[]
         muscles=[]
         for n in P.Neuron().load():
             neurons.append(n.name())
         for m in P.Muscle().load():
             muscles.append(m.name())
         if cellname in neurons:
             Channels=[]
             for ch in P.Neuron(name=str(cellname)).channel():
                 Channels.append(Channel(name=ch.name()))
         if cellname in muscles:
             Channels=[]
             for ch in P.Muscle(name=str(cellname)).channel():
                 Channels.append(Channel(name=ch.name()))
     serializer = ChannelSerializer(Channels, many=True)
     print serializer.data
     return Response(serializer.data)
def Neurons(request):
    P.connect()

    try:
        NEURON_DICT = {}
        for neuron in P.Neuron().load():
            NEURON_DICT[str(neuron)] = {
                'name': str(neuron),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/neurons.html',
                              {'neurons': NEURON_DICT})
Beispiel #21
0
        def add_data_to_neuron(data_kind, relation_code):
            cur.execute("""
                SELECT DISTINCT a.Entity, b.Entity
                FROM
                tblrelationship q,
                tblrelationship r,
                tblentity a,
                tblentity b
                where q.EnID1=a.id and q.Relation = '1515' and q.EnID2='1'
                and   r.EnID1=a.id and r.Relation = '{}'  and r.EnID2=b.id
                """.format(relation_code))
            for r in cur.fetchall():
                name = str(r[0])
                data = str(r[1])

                if not (name in neurons):
                    neurons[name] = P.Neuron(name=name)

                getattr(neurons[name], data_kind)(data)
Beispiel #22
0
                def marshall(name):
                    ret = []
                    res = None
                    res2 = None
                    if name in neurons:
                        res = P.Neuron(name)
                    elif name in muscles:
                        res = P.Muscle(name)
                    elif name in to_expand_muscles:
                        res, res2 = expand_muscle(name)
                    elif name in other_cells:
                        res = P.Cell(name)

                    if res is not None:
                        ret.append(res)
                    if res2 is not None:
                        ret.append(res2)

                    return ret
def Neuron(request, neuron_id):
    P.connect()

    try:
        neuron_dict = {}
        for neuron in P.Neuron(neuron_id).load():
            neuron_dict[str(neuron)] = {
                'name': str(neuron),
                'type': list(neuron.type.get()),
                'receptor': list(neuron.receptor.get()),
                'innexin': list(neuron.innexin.get()),
                'neurotransmitter': list(neuron.neurotransmitter.get()),
                'neuropeptide': list(neuron.neuropeptide.get()),
                'completeness': '#2B7558'
            }
    finally:
        P.disconnect()

    return render_to_response('pyopenworm/neuron.html',
                              {'neuron': neuron_dict[neuron_id]})
Beispiel #24
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 get(self,request, format=None):

        neurons=[]
        muscles=[]
        for neuron in P.Neuron().load():
            neurons.append(str(neuron.name()))
        for muscle in P.Muscle().load():
            muscles.append(str(muscle.name()))
        cellname = self.request.query_params.get('cellname', None)
        if cellname==None:
            Channels=[]
        else:
            if cellname in neurons:
                net = P.Worm().get_neuron_network()
                neuron = net.aneuron(cellname)
                serializer = NeuronDetailSerializer(NeuronDetail(neuron))
            elif cellname in muscles:
                muscle = P.Muscle(cellname)
                serializer = MuscleDetailSerializer(MuscleDetail(muscle))
        print serializer.data
        return Response(serializer.data)
Beispiel #26
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
 def test_neuron_Syn_degree(self):
     """ Get the number of chemical synapses from a networkx representation """
     # was 187 -- now returning 105 -- are we sure this is correct?
     self.assertEqual(PyOpenWorm.Neuron(name='AVAL').Syn_degree(), 105)
Beispiel #28
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 #29
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 #30
0
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()
e.save()