nichenetpy.network

  1from nichenetpy.io import read_network, read_weighted_network
  2from nichenetpy.typing import gene_t
  3
  4from collections.abc import Collection, Iterator
  5from itertools import chain
  6
  7import pandas as pd
  8
  9
 10class Network:
 11    '''
 12    A network with links. This is in essence a one to many mapping. 
 13
 14    Parameters
 15    ----------
 16    mapping : list or pandas.DataFrame or None
 17        sorted list of tuples (from, to) or pandas dataframe with keys ("from", "to")
 18    filename : str or None
 19        name of the file to read the network from
 20
 21    Raises
 22    ------
 23    TypeError
 24        if the arguments have the wrong type
 25    ValueError
 26        if neither mapping nor filename is provided
 27    
 28    Attributes
 29    ----------
 30    mapping : list
 31        sorted list of tuples (from, to)
 32    _index : dict
 33        index for the mapping
 34    
 35    Notes
 36    -----
 37    You must pass a list SORTED by "from" as mapping, a pandas dataframe with keys ("from", "to") or the name of a file to read from. 
 38    '''
 39    def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str|None=None):
 40        if mapping is not None:
 41            if type(mapping) is pd.DataFrame:
 42                mapping = sorted(
 43                    zip(mapping["from"].tolist(), mapping["to"].tolist()),
 44                    key=lambda x : x[0]
 45                )
 46            elif type(mapping) is not list:
 47                raise TypeError(f"mapping should have type list or pandas.DataFrame, was {type(mapping)}")
 48            self._mapping = mapping
 49        elif filename is not None:
 50            if type(filename) is not str:
 51                raise TypeError(f"filename should have type str, was {type(filename)}")
 52            self._mapping = sorted(
 53                read_network(filename),
 54                key=lambda x : x[0]
 55            )
 56        else:
 57            raise ValueError("either mapping or filename must be provided as arguments")
 58        self._index = dict()
 59        self._build_index()
 60    
 61    def __str__(self) -> str:
 62        return self._mapping.__str__()
 63
 64    def __getitem__(self, key) -> set:
 65        return set(self.mapping_iter(key))
 66    
 67    def __len__(self):
 68        return len(self._mapping)
 69    
 70    def __iter__(self):
 71        return self._mapping.__iter__()
 72    
 73    def __contains__(self, item:tuple):
 74        start, count = self._index[item[0]]
 75        return item in self._mapping[start:start+count]
 76    
 77    def _build_index(self):
 78        self._index.clear()
 79        for i, item in enumerate(self._mapping):
 80            if item[0] in self._index:
 81                self._index[item[0]][1] += 1
 82            else:
 83                self._index[item[0]] = [i, 1]
 84
 85    def key_iter(self):
 86        '''
 87        Iterates over the "from" values in the mapping. 
 88        
 89        Yields
 90        ------
 91        gene_t
 92            the "from" values in the mapping
 93        '''
 94        return (self._mapping[start][0] for start, _ in self._index.values())
 95
 96    def item_iter(self):
 97        '''
 98        Iterates over the "from" values in the mapping along with the corresponding "to" values. 
 99        
100        Yields
101        ------
102        tuple
103            the "from" values in the mapping and a list of corresponding "to" values
104        '''
105        return ((key, self[key]) for key in self.key_iter())
106    
107    def mapping_iter(self, key) -> Iterator:
108        '''
109        Iterates over the "to" values that correspond with the specified "from" value. 
110        
111        Yields
112        ------
113        tuple
114            the "to" values in the mapping
115        '''
116        try:
117            start, count = self._index[key]
118        except KeyError:
119            raise KeyError(f"there is no edge with '{key}' as source")
120        for item in self._mapping[start:start+count]:
121            yield item[1]
122    
123    def get_all(self) -> set:
124        '''
125        Return all values that are present in the network. 
126        
127        Yields
128        ------
129        set
130            all values present in the network
131        '''
132        return set(chain(*zip(*self._mapping)))
133    
134    def subset(self, from_to:Collection[tuple[gene_t, gene_t]]):
135        '''
136        Subset the network by the provided links. 
137
138        Parameters
139        ----------
140        from_to : Collection
141            collection of tuples (from, to) to subset by
142
143        Returns
144        -------
145        Network
146            the subsetted network
147        
148        Raises
149        ------
150        TypeError
151            if the arguments have the wrong type
152        '''
153        if not isinstance(from_to, Collection):
154            raise TypeError(f"from_to should be a Collection of tuple[gene_t, gene_t], was {type(from_to)}")
155        return type(self)(mapping=[tup for tup in self._mapping if (tup[0], tup[1]) in from_to])
156
157    def subset_sep(self, fr:Collection[gene_t]|None=None, to:Collection[gene_t]|None=None):
158        '''
159        Subset the network by the provided "from" and "to" values. 
160
161        Parameters
162        ----------
163        from : Collection or None
164            collection of "from" values to subset by
165        to : Collection or None
166            collection of "to" values to subset by
167
168        Returns
169        -------
170        Network
171            the subsetted network
172        
173        Raises
174        ------
175        TypeError
176            if the arguments have the wrong type
177        '''
178        if fr is None:
179            fr = set(self.key_iter())
180        if to is None:
181            to = set(e for _, e in self._mapping)
182        if not isinstance(fr, Collection):
183            raise TypeError(f"fr should be a Collection of gene_t, was {type(fr)}")
184        if not isinstance(to, Collection):
185            raise TypeError(f"to should be a Collection of gene_t, was {type(to)}")
186        return type(self)(mapping=[tup for tup in self._mapping if tup[0] in fr and tup[1] in to])
187    
188    def to_dataframe(self):
189        '''
190        Convert the network to a dataframe
191
192        Returns
193        -------
194        pandas.DataFrame
195            the network as a dataframe
196        '''
197        return pd.concat([
198            pd.DataFrame({"from": fr, "to": list(tos)})
199            for fr, tos in self.item_iter()
200        ])
201
202class LigandReceptorNetwork(Network):
203    '''
204    A ligand-receptor network without weights. This is in essence a one to many mapping. 
205
206    Parameters
207    ----------
208    mapping : list
209        sorted list of tuples (from, to)
210    filename : str
211        name of the file to read the network from
212    
213    Raises
214    ------
215    TypeError
216        if the arguments have the wrong type
217    ValueError
218        if neither mapping nor filename is provided
219    
220    Attributes
221    ----------
222    mapping : list
223        sorted list of tuples (from, to)
224    _index : dict
225        index for the mapping
226    
227    Notes
228    -----
229    You must pass a list SORTED by "from" as mapping or the name of a file to read from. 
230    '''
231    def get_ligands(self) -> set[gene_t]:
232        '''
233        Get all the ligands present in the network. 
234        
235        Returns
236        -------
237        set
238            set of ligands present in the network
239        '''
240        return set(self.key_iter())
241    
242    def get_receptors(self) -> set[gene_t]:
243        '''
244        Get all the receptors present in the network. 
245        
246        Returns
247        -------
248        set
249            set of receptors present in the network
250        '''
251        return set(receptor for _, receptor in self._mapping)
252
253class WeightedNetwork(Network):
254    '''
255    A ligand-receptor network with weighted links. This is in essence a one to many mapping. 
256
257    Parameters
258    ----------
259    mapping : list or pandas.DataFrame or None
260        sorted list of tuples (from, to, weight) or pandas dataframe with keys ("from", "to", "weight")
261    filename : str or None
262        name of the file to read the network from
263    
264    Raises
265    ------
266    TypeError
267        if the arguments have the wrong type
268    
269    Attributes
270    ----------
271    mapping : list
272        sorted list of tuples (from, to, weight)
273    _index : dict
274        index for the mapping
275    '''
276    def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str=None):
277        if filename is not None:
278            if type(filename) is not str:
279                raise TypeError(f"filename should have type str, was {type(filename)}")
280            mapping = sorted(
281                read_weighted_network(filename),
282                key=lambda x : x[0]
283            )
284        elif type(mapping) is pd.DataFrame:
285            mapping = sorted(
286                zip(mapping["from"], mapping["to"], mapping["weight"]),
287                key=lambda x : x[0]
288            )
289        super().__init__(mapping=mapping)
290    
291    def __getitem__(self, key:gene_t) -> dict[gene_t, float]:
292        start, count = self._index[key]
293        return dict(item[1:3] for item in self._mapping[start:start+count])
294    
295    def get_ligands(self) -> set[gene_t]:
296        '''
297        Get all the ligands present in the network. 
298        
299        Returns
300        -------
301        set
302            set of ligands present in the network
303        '''
304        return set(self.key_iter())
305    
306    def get_receptors(self) -> set[gene_t]:
307        '''
308        Get all the receptors present in the network. 
309        
310        Returns
311        -------
312        set
313            set of receptors present in the network
314        '''
315        return set(receptor for _, receptor, _ in self._mapping)
316    
317    def to_dataframe(self):
318        '''
319        Convert the network to a dataframe
320
321        Returns
322        -------
323        pandas.DataFrame
324            the network as a dataframe
325        '''
326        temp = []
327        for fr, mapping in self.item_iter():
328            tos, ws = zip(*mapping.items())
329            temp.append(pd.DataFrame({"from": fr, "to": tos, "weight": ws}))
330        return pd.concat(temp)
class Network:
 11class Network:
 12    '''
 13    A network with links. This is in essence a one to many mapping. 
 14
 15    Parameters
 16    ----------
 17    mapping : list or pandas.DataFrame or None
 18        sorted list of tuples (from, to) or pandas dataframe with keys ("from", "to")
 19    filename : str or None
 20        name of the file to read the network from
 21
 22    Raises
 23    ------
 24    TypeError
 25        if the arguments have the wrong type
 26    ValueError
 27        if neither mapping nor filename is provided
 28    
 29    Attributes
 30    ----------
 31    mapping : list
 32        sorted list of tuples (from, to)
 33    _index : dict
 34        index for the mapping
 35    
 36    Notes
 37    -----
 38    You must pass a list SORTED by "from" as mapping, a pandas dataframe with keys ("from", "to") or the name of a file to read from. 
 39    '''
 40    def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str|None=None):
 41        if mapping is not None:
 42            if type(mapping) is pd.DataFrame:
 43                mapping = sorted(
 44                    zip(mapping["from"].tolist(), mapping["to"].tolist()),
 45                    key=lambda x : x[0]
 46                )
 47            elif type(mapping) is not list:
 48                raise TypeError(f"mapping should have type list or pandas.DataFrame, was {type(mapping)}")
 49            self._mapping = mapping
 50        elif filename is not None:
 51            if type(filename) is not str:
 52                raise TypeError(f"filename should have type str, was {type(filename)}")
 53            self._mapping = sorted(
 54                read_network(filename),
 55                key=lambda x : x[0]
 56            )
 57        else:
 58            raise ValueError("either mapping or filename must be provided as arguments")
 59        self._index = dict()
 60        self._build_index()
 61    
 62    def __str__(self) -> str:
 63        return self._mapping.__str__()
 64
 65    def __getitem__(self, key) -> set:
 66        return set(self.mapping_iter(key))
 67    
 68    def __len__(self):
 69        return len(self._mapping)
 70    
 71    def __iter__(self):
 72        return self._mapping.__iter__()
 73    
 74    def __contains__(self, item:tuple):
 75        start, count = self._index[item[0]]
 76        return item in self._mapping[start:start+count]
 77    
 78    def _build_index(self):
 79        self._index.clear()
 80        for i, item in enumerate(self._mapping):
 81            if item[0] in self._index:
 82                self._index[item[0]][1] += 1
 83            else:
 84                self._index[item[0]] = [i, 1]
 85
 86    def key_iter(self):
 87        '''
 88        Iterates over the "from" values in the mapping. 
 89        
 90        Yields
 91        ------
 92        gene_t
 93            the "from" values in the mapping
 94        '''
 95        return (self._mapping[start][0] for start, _ in self._index.values())
 96
 97    def item_iter(self):
 98        '''
 99        Iterates over the "from" values in the mapping along with the corresponding "to" values. 
100        
101        Yields
102        ------
103        tuple
104            the "from" values in the mapping and a list of corresponding "to" values
105        '''
106        return ((key, self[key]) for key in self.key_iter())
107    
108    def mapping_iter(self, key) -> Iterator:
109        '''
110        Iterates over the "to" values that correspond with the specified "from" value. 
111        
112        Yields
113        ------
114        tuple
115            the "to" values in the mapping
116        '''
117        try:
118            start, count = self._index[key]
119        except KeyError:
120            raise KeyError(f"there is no edge with '{key}' as source")
121        for item in self._mapping[start:start+count]:
122            yield item[1]
123    
124    def get_all(self) -> set:
125        '''
126        Return all values that are present in the network. 
127        
128        Yields
129        ------
130        set
131            all values present in the network
132        '''
133        return set(chain(*zip(*self._mapping)))
134    
135    def subset(self, from_to:Collection[tuple[gene_t, gene_t]]):
136        '''
137        Subset the network by the provided links. 
138
139        Parameters
140        ----------
141        from_to : Collection
142            collection of tuples (from, to) to subset by
143
144        Returns
145        -------
146        Network
147            the subsetted network
148        
149        Raises
150        ------
151        TypeError
152            if the arguments have the wrong type
153        '''
154        if not isinstance(from_to, Collection):
155            raise TypeError(f"from_to should be a Collection of tuple[gene_t, gene_t], was {type(from_to)}")
156        return type(self)(mapping=[tup for tup in self._mapping if (tup[0], tup[1]) in from_to])
157
158    def subset_sep(self, fr:Collection[gene_t]|None=None, to:Collection[gene_t]|None=None):
159        '''
160        Subset the network by the provided "from" and "to" values. 
161
162        Parameters
163        ----------
164        from : Collection or None
165            collection of "from" values to subset by
166        to : Collection or None
167            collection of "to" values to subset by
168
169        Returns
170        -------
171        Network
172            the subsetted network
173        
174        Raises
175        ------
176        TypeError
177            if the arguments have the wrong type
178        '''
179        if fr is None:
180            fr = set(self.key_iter())
181        if to is None:
182            to = set(e for _, e in self._mapping)
183        if not isinstance(fr, Collection):
184            raise TypeError(f"fr should be a Collection of gene_t, was {type(fr)}")
185        if not isinstance(to, Collection):
186            raise TypeError(f"to should be a Collection of gene_t, was {type(to)}")
187        return type(self)(mapping=[tup for tup in self._mapping if tup[0] in fr and tup[1] in to])
188    
189    def to_dataframe(self):
190        '''
191        Convert the network to a dataframe
192
193        Returns
194        -------
195        pandas.DataFrame
196            the network as a dataframe
197        '''
198        return pd.concat([
199            pd.DataFrame({"from": fr, "to": list(tos)})
200            for fr, tos in self.item_iter()
201        ])

A network with links. This is in essence a one to many mapping.

Parameters
  • mapping (list or pandas.DataFrame or None): sorted list of tuples (from, to) or pandas dataframe with keys ("from", "to")
  • filename (str or None): name of the file to read the network from
Raises
  • TypeError: if the arguments have the wrong type
  • ValueError: if neither mapping nor filename is provided
Attributes
  • mapping (list): sorted list of tuples (from, to)
  • _index (dict): index for the mapping
Notes

You must pass a list SORTED by "from" as mapping, a pandas dataframe with keys ("from", "to") or the name of a file to read from.

Network( mapping: list | pandas.DataFrame | None = None, filename: str | None = None)
40    def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str|None=None):
41        if mapping is not None:
42            if type(mapping) is pd.DataFrame:
43                mapping = sorted(
44                    zip(mapping["from"].tolist(), mapping["to"].tolist()),
45                    key=lambda x : x[0]
46                )
47            elif type(mapping) is not list:
48                raise TypeError(f"mapping should have type list or pandas.DataFrame, was {type(mapping)}")
49            self._mapping = mapping
50        elif filename is not None:
51            if type(filename) is not str:
52                raise TypeError(f"filename should have type str, was {type(filename)}")
53            self._mapping = sorted(
54                read_network(filename),
55                key=lambda x : x[0]
56            )
57        else:
58            raise ValueError("either mapping or filename must be provided as arguments")
59        self._index = dict()
60        self._build_index()
def key_iter(self):
86    def key_iter(self):
87        '''
88        Iterates over the "from" values in the mapping. 
89        
90        Yields
91        ------
92        gene_t
93            the "from" values in the mapping
94        '''
95        return (self._mapping[start][0] for start, _ in self._index.values())

Iterates over the "from" values in the mapping.

Yields
  • gene_t: the "from" values in the mapping
def item_iter(self):
 97    def item_iter(self):
 98        '''
 99        Iterates over the "from" values in the mapping along with the corresponding "to" values. 
100        
101        Yields
102        ------
103        tuple
104            the "from" values in the mapping and a list of corresponding "to" values
105        '''
106        return ((key, self[key]) for key in self.key_iter())

Iterates over the "from" values in the mapping along with the corresponding "to" values.

Yields
  • tuple: the "from" values in the mapping and a list of corresponding "to" values
def mapping_iter(self, key) -> Iterator:
108    def mapping_iter(self, key) -> Iterator:
109        '''
110        Iterates over the "to" values that correspond with the specified "from" value. 
111        
112        Yields
113        ------
114        tuple
115            the "to" values in the mapping
116        '''
117        try:
118            start, count = self._index[key]
119        except KeyError:
120            raise KeyError(f"there is no edge with '{key}' as source")
121        for item in self._mapping[start:start+count]:
122            yield item[1]

Iterates over the "to" values that correspond with the specified "from" value.

Yields
  • tuple: the "to" values in the mapping
def get_all(self) -> set:
124    def get_all(self) -> set:
125        '''
126        Return all values that are present in the network. 
127        
128        Yields
129        ------
130        set
131            all values present in the network
132        '''
133        return set(chain(*zip(*self._mapping)))

Return all values that are present in the network.

Yields
  • set: all values present in the network
def subset(self, from_to: Collection[tuple[str | int, str | int]]):
135    def subset(self, from_to:Collection[tuple[gene_t, gene_t]]):
136        '''
137        Subset the network by the provided links. 
138
139        Parameters
140        ----------
141        from_to : Collection
142            collection of tuples (from, to) to subset by
143
144        Returns
145        -------
146        Network
147            the subsetted network
148        
149        Raises
150        ------
151        TypeError
152            if the arguments have the wrong type
153        '''
154        if not isinstance(from_to, Collection):
155            raise TypeError(f"from_to should be a Collection of tuple[gene_t, gene_t], was {type(from_to)}")
156        return type(self)(mapping=[tup for tup in self._mapping if (tup[0], tup[1]) in from_to])

Subset the network by the provided links.

Parameters
  • from_to (Collection): collection of tuples (from, to) to subset by
Returns
  • Network: the subsetted network
Raises
  • TypeError: if the arguments have the wrong type
def subset_sep( self, fr: Collection[str | int] | None = None, to: Collection[str | int] | None = None):
158    def subset_sep(self, fr:Collection[gene_t]|None=None, to:Collection[gene_t]|None=None):
159        '''
160        Subset the network by the provided "from" and "to" values. 
161
162        Parameters
163        ----------
164        from : Collection or None
165            collection of "from" values to subset by
166        to : Collection or None
167            collection of "to" values to subset by
168
169        Returns
170        -------
171        Network
172            the subsetted network
173        
174        Raises
175        ------
176        TypeError
177            if the arguments have the wrong type
178        '''
179        if fr is None:
180            fr = set(self.key_iter())
181        if to is None:
182            to = set(e for _, e in self._mapping)
183        if not isinstance(fr, Collection):
184            raise TypeError(f"fr should be a Collection of gene_t, was {type(fr)}")
185        if not isinstance(to, Collection):
186            raise TypeError(f"to should be a Collection of gene_t, was {type(to)}")
187        return type(self)(mapping=[tup for tup in self._mapping if tup[0] in fr and tup[1] in to])

Subset the network by the provided "from" and "to" values.

Parameters
  • from (Collection or None): collection of "from" values to subset by
  • to (Collection or None): collection of "to" values to subset by
Returns
  • Network: the subsetted network
Raises
  • TypeError: if the arguments have the wrong type
def to_dataframe(self):
189    def to_dataframe(self):
190        '''
191        Convert the network to a dataframe
192
193        Returns
194        -------
195        pandas.DataFrame
196            the network as a dataframe
197        '''
198        return pd.concat([
199            pd.DataFrame({"from": fr, "to": list(tos)})
200            for fr, tos in self.item_iter()
201        ])

Convert the network to a dataframe

Returns
  • pandas.DataFrame: the network as a dataframe
class LigandReceptorNetwork(Network):
203class LigandReceptorNetwork(Network):
204    '''
205    A ligand-receptor network without weights. This is in essence a one to many mapping. 
206
207    Parameters
208    ----------
209    mapping : list
210        sorted list of tuples (from, to)
211    filename : str
212        name of the file to read the network from
213    
214    Raises
215    ------
216    TypeError
217        if the arguments have the wrong type
218    ValueError
219        if neither mapping nor filename is provided
220    
221    Attributes
222    ----------
223    mapping : list
224        sorted list of tuples (from, to)
225    _index : dict
226        index for the mapping
227    
228    Notes
229    -----
230    You must pass a list SORTED by "from" as mapping or the name of a file to read from. 
231    '''
232    def get_ligands(self) -> set[gene_t]:
233        '''
234        Get all the ligands present in the network. 
235        
236        Returns
237        -------
238        set
239            set of ligands present in the network
240        '''
241        return set(self.key_iter())
242    
243    def get_receptors(self) -> set[gene_t]:
244        '''
245        Get all the receptors present in the network. 
246        
247        Returns
248        -------
249        set
250            set of receptors present in the network
251        '''
252        return set(receptor for _, receptor in self._mapping)

A ligand-receptor network without weights. This is in essence a one to many mapping.

Parameters
  • mapping (list): sorted list of tuples (from, to)
  • filename (str): name of the file to read the network from
Raises
  • TypeError: if the arguments have the wrong type
  • ValueError: if neither mapping nor filename is provided
Attributes
  • mapping (list): sorted list of tuples (from, to)
  • _index (dict): index for the mapping
Notes

You must pass a list SORTED by "from" as mapping or the name of a file to read from.

def get_ligands(self) -> set[str | int]:
232    def get_ligands(self) -> set[gene_t]:
233        '''
234        Get all the ligands present in the network. 
235        
236        Returns
237        -------
238        set
239            set of ligands present in the network
240        '''
241        return set(self.key_iter())

Get all the ligands present in the network.

Returns
  • set: set of ligands present in the network
def get_receptors(self) -> set[str | int]:
243    def get_receptors(self) -> set[gene_t]:
244        '''
245        Get all the receptors present in the network. 
246        
247        Returns
248        -------
249        set
250            set of receptors present in the network
251        '''
252        return set(receptor for _, receptor in self._mapping)

Get all the receptors present in the network.

Returns
  • set: set of receptors present in the network
class WeightedNetwork(Network):
254class WeightedNetwork(Network):
255    '''
256    A ligand-receptor network with weighted links. This is in essence a one to many mapping. 
257
258    Parameters
259    ----------
260    mapping : list or pandas.DataFrame or None
261        sorted list of tuples (from, to, weight) or pandas dataframe with keys ("from", "to", "weight")
262    filename : str or None
263        name of the file to read the network from
264    
265    Raises
266    ------
267    TypeError
268        if the arguments have the wrong type
269    
270    Attributes
271    ----------
272    mapping : list
273        sorted list of tuples (from, to, weight)
274    _index : dict
275        index for the mapping
276    '''
277    def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str=None):
278        if filename is not None:
279            if type(filename) is not str:
280                raise TypeError(f"filename should have type str, was {type(filename)}")
281            mapping = sorted(
282                read_weighted_network(filename),
283                key=lambda x : x[0]
284            )
285        elif type(mapping) is pd.DataFrame:
286            mapping = sorted(
287                zip(mapping["from"], mapping["to"], mapping["weight"]),
288                key=lambda x : x[0]
289            )
290        super().__init__(mapping=mapping)
291    
292    def __getitem__(self, key:gene_t) -> dict[gene_t, float]:
293        start, count = self._index[key]
294        return dict(item[1:3] for item in self._mapping[start:start+count])
295    
296    def get_ligands(self) -> set[gene_t]:
297        '''
298        Get all the ligands present in the network. 
299        
300        Returns
301        -------
302        set
303            set of ligands present in the network
304        '''
305        return set(self.key_iter())
306    
307    def get_receptors(self) -> set[gene_t]:
308        '''
309        Get all the receptors present in the network. 
310        
311        Returns
312        -------
313        set
314            set of receptors present in the network
315        '''
316        return set(receptor for _, receptor, _ in self._mapping)
317    
318    def to_dataframe(self):
319        '''
320        Convert the network to a dataframe
321
322        Returns
323        -------
324        pandas.DataFrame
325            the network as a dataframe
326        '''
327        temp = []
328        for fr, mapping in self.item_iter():
329            tos, ws = zip(*mapping.items())
330            temp.append(pd.DataFrame({"from": fr, "to": tos, "weight": ws}))
331        return pd.concat(temp)

A ligand-receptor network with weighted links. This is in essence a one to many mapping.

Parameters
  • mapping (list or pandas.DataFrame or None): sorted list of tuples (from, to, weight) or pandas dataframe with keys ("from", "to", "weight")
  • filename (str or None): name of the file to read the network from
Raises
  • TypeError: if the arguments have the wrong type
Attributes
  • mapping (list): sorted list of tuples (from, to, weight)
  • _index (dict): index for the mapping
WeightedNetwork(mapping: list | pandas.DataFrame | None = None, filename: str = None)
277    def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str=None):
278        if filename is not None:
279            if type(filename) is not str:
280                raise TypeError(f"filename should have type str, was {type(filename)}")
281            mapping = sorted(
282                read_weighted_network(filename),
283                key=lambda x : x[0]
284            )
285        elif type(mapping) is pd.DataFrame:
286            mapping = sorted(
287                zip(mapping["from"], mapping["to"], mapping["weight"]),
288                key=lambda x : x[0]
289            )
290        super().__init__(mapping=mapping)
def get_ligands(self) -> set[str | int]:
296    def get_ligands(self) -> set[gene_t]:
297        '''
298        Get all the ligands present in the network. 
299        
300        Returns
301        -------
302        set
303            set of ligands present in the network
304        '''
305        return set(self.key_iter())

Get all the ligands present in the network.

Returns
  • set: set of ligands present in the network
def get_receptors(self) -> set[str | int]:
307    def get_receptors(self) -> set[gene_t]:
308        '''
309        Get all the receptors present in the network. 
310        
311        Returns
312        -------
313        set
314            set of receptors present in the network
315        '''
316        return set(receptor for _, receptor, _ in self._mapping)

Get all the receptors present in the network.

Returns
  • set: set of receptors present in the network
def to_dataframe(self):
318    def to_dataframe(self):
319        '''
320        Convert the network to a dataframe
321
322        Returns
323        -------
324        pandas.DataFrame
325            the network as a dataframe
326        '''
327        temp = []
328        for fr, mapping in self.item_iter():
329            tos, ws = zip(*mapping.items())
330            temp.append(pd.DataFrame({"from": fr, "to": tos, "weight": ws}))
331        return pd.concat(temp)

Convert the network to a dataframe

Returns
  • pandas.DataFrame: the network as a dataframe