Skip to content

neurostatx.io.loader

Classes

NameDescription
DatasetLoaderLoad, reshape, and persist tabular datasets.
GraphLoaderLoad, build, annotate, and visualize NetworkX graphs.

Functions

NameDescription
filter_node_centroidsReturn True if n is a cluster-centroid node label.
filter_node_subjectsReturn True if n is a subject node label.

DatasetLoaderclass#

class DatasetLoader()

Load, reshape, and persist tabular datasets.

dataattributeinstance attribute#

data = None

nb_subjectsattributeinstance attribute#

nb_subjects = None

nb_variablesattributeinstance attribute#

nb_variables = None

custom_functionmethod#

def custom_function(func, **kwargs)

Apply func to the loaded DataFrame.

Parameters

NameTypeDefaultDescription
funccallablerequiredFunction called as func(data, **kwargs).
**kwargs{}Additional keyword arguments forwarded to func.

Returns

result
Return value of func.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2]], columns=["a", "b"])
>>> loader.custom_function(lambda df: df.shape)
(1, 2)

drop_columnsmethod#

def drop_columns(columns)

Drop columns by integer index or name.

Parameters

NameTypeDescription
columnslistColumn indices or names to drop.

Returns

selfDatasetLoader
Loader with the specified columns removed.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2], [3, 4]],
... columns=["id", "x"])
>>> loader.drop_columns(["id"]).get_data().columns.tolist()
['x']

get_datamethod#

def get_data()

Return the loaded DataFrame.

Returns

datapandas.DataFrame
The loaded data.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> DatasetLoader().import_data([[1, 2]]).get_data().shape
(1, 2)

get_descriptive_columnsmethod#

def get_descriptive_columns(columns)

Return selected descriptive columns by integer index.

Parameters

NameTypeDescription
columnslistInteger column indices to extract.

Returns

datapandas.DataFrame
DataFrame containing the selected columns.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2], [3, 4]],
... columns=["id", "x"])
>>> loader.get_descriptive_columns([0]).columns.tolist()
['id']

get_metadatamethod#

def get_metadata()

Return the number of rows and columns.

Returns

metadatadict
Mapping with nb_subjects and nb_variables.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2], [3, 4]])
>>> loader.get_metadata()["nb_subjects"]
2

import_datamethod#

def import_data(data, columns=None, index=None, **kwargs)

Import data from a DataFrame, mapping, or array-like object.

Parameters

NameTypeDefaultDescription
datapandas.DataFrame or array - likerequiredData to import.
columnslistNoneColumn names to use. If None, pandas default names are kept.
indexarray - likeNoneIndex used when constructing a DataFrame from array-like data.
**kwargs{}Additional keyword arguments forwarded to pandas.DataFrame.from_dict.

Returns

selfDatasetLoader
Loader with the imported data.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2], [3, 4]],
... columns=["a", "b"])
>>> loader.get_data().shape
(2, 2)

joinmethod#

def join(df, left=True, **kwargs)

Concatenate df with the loaded table along columns.

Parameters

NameTypeDefaultDescription
dfpandas.DataFramerequiredDataFrame or Series to concatenate.
leftboolTrueIf True, df is placed on the left. Defaults to True.
**kwargs{}Additional keyword arguments forwarded to pandas.concat.

Returns

selfDatasetLoader
Loader with the concatenated table.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1], [2]], columns=["a"])
>>> extra = pd.DataFrame({"b": [3, 4]})
>>> loader.join(extra, left=False).get_data().columns.tolist()
['a', 'b']

load_datamethod#

def load_data(file, **kwargs)

Load tabular data from .txt, .csv, .tsv, or .xlsx.

Parameters

NameTypeDefaultDescription
filestrrequiredInput file to load.
**kwargs{}Additional keyword arguments forwarded to pandas.

Returns

selfDatasetLoader
Loader with data populated.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> DatasetLoader().load_data("data.csv")

reset_indexmethod#

def reset_index(**kwargs)

Reset the DataFrame index in place.

Parameters

NameDefaultDescription
**kwargs{}Additional keyword arguments forwarded to pandas.DataFrame.reset_index.

Returns

selfDatasetLoader
Loader with a reset index.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1], [2]], columns=["a"],
... index=[10, 20])
>>> loader.reset_index().get_data().index.tolist()
[0, 1]

save_datamethod#

def save_data(file, **kwargs)

Save the loaded table to .csv, .tsv, .txt, or .xlsx.

Parameters

NameTypeDefaultDescription
filestrrequiredOutput file name.
**kwargs{}Additional keyword arguments forwarded to pandas.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2]], columns=["a", "b"])
>>> loader.save_data("out.csv", index=False)

set_typemethod#

def set_type(dtype, columns=None)

Cast selected columns, or the full table, to dtype.

Parameters

NameTypeDefaultDescription
dtypestrrequiredTarget dtype.
columnslistNoneInteger column indices to convert. If None, all columns are converted.

Returns

selfDatasetLoader
Loader with updated dtypes.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2], [3, 4]],
... columns=["a", "b"])
>>> loader.set_type("float").get_data()["a"].dtype.kind
'f'

transposemethod#

def transpose()

Transpose the loaded table.

Returns

selfDatasetLoader
Loader with transposed data.

Examples

>>> from neurostatx.io.loader import DatasetLoader
>>> loader = DatasetLoader().import_data([[1, 2], [3, 4]],
... columns=["a", "b"])
>>> loader.transpose().get_data().shape
(2, 2)

GraphLoaderclass#

class GraphLoader()

Load, build, annotate, and visualize NetworkX graphs.

graphattributeinstance attribute#

graph = None

nb_edgesattributeinstance attribute#

nb_edges = None

nb_nodesattributeinstance attribute#

nb_nodes = None

add_edge_attributemethod#

def add_edge_attribute(attributes)

Set edge attributes from a nested dictionary.

Parameters

NameTypeDescription
attributesdictMapping of edge to attribute dictionary.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"]})
>>> g = GraphLoader().build_graph(edges)
>>> g.add_edge_attribute({("s1", "c1"): {"membership": 0.8}})

add_node_attributemethod#

def add_node_attribute(attributes)

Set node attributes from a nested dictionary.

Parameters

NameTypeDescription
attributesdictMapping of node to attribute dictionary.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"]})
>>> g = GraphLoader().build_graph(edges)
>>> g.add_node_attribute({"s1": {"age": 20}})

build_graphmethod#

def build_graph(data, source='source', target='target', **kwargs)

Build a graph from an edgelist DataFrame.

Parameters

NameTypeDefaultDescription
datapandas.DataFramerequiredEdgelist used to construct the graph.
sourcestr'source'Source-node column name. Defaults to "source".
targetstr'target'Target-node column name. Defaults to "target".
**kwargs{}Additional keyword arguments forwarded to networkx.from_pandas_edgelist.

Returns

selfGraphLoader
Loader with the constructed graph.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"],
... "membership": [0.8]})
>>> GraphLoader().build_graph(edges, edge_attr="membership").nb_nodes
2

custom_functionmethod#

def custom_function(func, **kwargs)

Apply func to the loaded graph.

Parameters

NameTypeDefaultDescription
funccallablerequiredFunction called as func(graph, **kwargs).
**kwargs{}Additional keyword arguments forwarded to func.

Returns

result
Return value of func.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"]})
>>> GraphLoader().build_graph(edges).custom_function(
... lambda g: g.number_of_nodes())
2

fetch_attributes_dfmethod#

def fetch_attributes_df(attributes=None)

Return subject-node attributes as a DatasetLoader.

Parameters

NameTypeDefaultDescription
attributeslistNoneAttribute names to fetch. If None, all attributes except label are returned.

Returns

dataDatasetLoader
Loader containing subject-node attributes.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"]})
>>> g = GraphLoader().build_graph(edges)
>>> g.add_node_attribute({"s1": {"age": 20}})
>>> g.fetch_attributes_df(["age"]).get_data().loc["s1", "age"]
20

fetch_edge_datamethod#

def fetch_edge_data(weight='membership')

Return subject-to-cluster edge weights as a DatasetLoader.

Parameters

NameTypeDefaultDescription
weightstr'membership'Edge attribute used as weights. Defaults to "membership".

Returns

dataDatasetLoader
Loader containing one column per cluster.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"],
... "membership": [0.8]})
>>> g = GraphLoader().build_graph(edges, edge_attr="membership")
>>> g.fetch_edge_data().get_data().shape[1]
1

get_graphmethod#

def get_graph()

Return the loaded NetworkX graph.

Returns

graphnetworkx.Graph
The loaded graph.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"]})
>>> GraphLoader().build_graph(edges).get_graph().number_of_nodes()
2

get_metadatamethod#

def get_metadata()

Return the number of nodes and edges.

Returns

metadatadict
Mapping with nb_nodes and nb_edges.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"]})
>>> GraphLoader().build_graph(edges).get_metadata()["nb_nodes"]
2

layoutmethod#

def layout(layout=NetworkLayout.Spring, weight='membership', **kwargs)

Compute node positions and store them as a pos attribute.

Parameters

NameTypeDefaultDescription
layoutNetworkLayoutNetworkLayout.SpringLayout algorithm to use.
weightstr'membership'Edge attribute used as layout weights. Defaults to "membership".
**kwargs{}Additional keyword arguments forwarded to the NetworkX layout function.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> from neurostatx.network.viz import NetworkLayout
>>> edges = pd.DataFrame({"source": ["s1", "s2"],
... "target": ["c1", "c1"],
... "membership": [0.8, 0.4]})
>>> g = GraphLoader().build_graph(edges, edge_attr="membership")
>>> g.layout(NetworkLayout.Spring)

load_graphmethod#

def load_graph(file, **kwargs)

Load a graph from .gml, .graphml, or .gexf.

Parameters

NameTypeDefaultDescription
filestrrequiredInput file to load.
**kwargs{}Additional keyword arguments forwarded to NetworkX.

Returns

selfGraphLoader
Loader with graph populated.

Examples

>>> from neurostatx.io.loader import GraphLoader
>>> GraphLoader().load_graph("network.gml")

save_graphmethod#

def save_graph(file, **kwargs)

Save the graph to .gml, .graphml, or .gexf.

Parameters

NameTypeDefaultDescription
filestrrequiredOutput file to save.
**kwargs{}Additional keyword arguments forwarded to NetworkX.

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"]})
>>> GraphLoader().build_graph(edges).save_graph("network.gml")

visualizemethod#

def visualize(output, weight='weight', centroids_labelling=True, subjects_labelling=False, centroid_node_shape=500, centroid_alpha=1, centroid_node_color='white', centroid_edge_color='black', subject_node_shape=5, subject_alpha=0.3, subject_node_color='black', subject_edge_color=None, edge_width_multiplier=1, colormap='plasma', title='Graph Network', legend_title='Membership values')

Draw the graph network and write it to output.

Parameters

NameTypeDefaultDescription
outputstrrequiredOutput file name.
weightstr'weight'Edge attribute used as edge weights. Defaults to "weight".
centroids_labellingboolTrueIf True, label centroid nodes. Defaults to True.
subjects_labellingboolFalseIf True, label subject nodes. Defaults to False.
centroid_node_shapeint500Size of centroid nodes. Defaults to 500.
centroid_alphafloat1Alpha of centroid nodes. Defaults to 1.
centroid_node_colorstr'white'Face color of centroid nodes. Defaults to "white".
centroid_edge_colorstr'black'Edge color of centroid nodes. Defaults to "black".
subject_node_shapeint5Size of subject nodes. Defaults to 5.
subject_alphafloat0.3Alpha of subject nodes. Defaults to 0.3.
subject_node_colorstr'black'Face color of subject nodes. Defaults to "black".
subject_edge_colorstrNoneEdge color of subject nodes. Defaults to None.
edge_width_multiplierfloat1Scale factor applied to edge widths. Defaults to 1.
colormapstr'plasma'Matplotlib colormap name for edges. Defaults to "plasma".
titlestr'Graph Network'Title of the plot. Defaults to "Graph Network".
legend_titlestr'Membership values'Title of the colorbar. Defaults to "Membership values".

Examples

>>> import pandas as pd
>>> from neurostatx.io.loader import GraphLoader
>>> from neurostatx.network.viz import NetworkLayout
>>> edges = pd.DataFrame({"source": ["s1"], "target": ["c1"],
... "weight": [0.8]})
>>> g = GraphLoader().build_graph(edges, edge_attr="weight")
>>> g.layout(NetworkLayout.Spring, weight="weight")
>>> g.visualize("graph.png")

filter_node_centroidsfunction#

def filter_node_centroids(n)

Return True if n is a cluster-centroid node label.

Parameters

NameTypeDescription
nstrNode label.

Returns

matchbool
True when the label contains "c".

Examples

>>> from neurostatx.io.loader import filter_node_centroids
>>> filter_node_centroids("c1")
True

filter_node_subjectsfunction#

def filter_node_subjects(n)

Return True if n is a subject node label.

Parameters

NameTypeDescription
nstrNode label.

Returns

matchbool
True when the label does not contain "c".

Examples

>>> from neurostatx.io.loader import filter_node_subjects
>>> filter_node_subjects("s01")
True