Skip to content

File Writers

Network export functionality for various formats.

Overview

Export networks in multiple formats:

  • NEXUS: Compatible with PopART
  • GML: Graph Modeling Language
  • GraphML: XML-based graph format
  • JSON: JavaScript Object Notation

Modules

pypopart.io.network_export

Network export module for PyPopART.

Provides exporters for various network file formats.

GraphMLExporter

Export haplotype networks to GraphML format.

Source code in src/pypopart/io/network_export.py
class GraphMLExporter:
    """Export haplotype networks to GraphML format."""

    def __init__(self, filepath: Union[str, Path]):
        """
        Initialize GraphML exporter.

        Parameters
        ----------
        filepath :
            Output file path.
        """
        self.filepath = Path(filepath)

    def export(self, network: HaplotypeNetwork) -> None:
        """
        Export network to GraphML format.

        Parameters
        ----------
        network :
            HaplotypeNetwork object.
        """
        # Convert network to NetworkX graph if needed
        graph = network.graph if hasattr(network, 'graph') else network

        # Sanitize graph data for export (strict mode for GraphML)
        sanitized_graph = _sanitize_graph_for_export(graph, format_type='graphml')

        # Write to GraphML
        nx.write_graphml(sanitized_graph, self.filepath)
__init__
__init__(filepath: Union[str, Path])

Initialize GraphML exporter.

Parameters:

Name Type Description Default
filepath Union[str, Path]

Output file path.

required
Source code in src/pypopart/io/network_export.py
def __init__(self, filepath: Union[str, Path]):
    """
    Initialize GraphML exporter.

    Parameters
    ----------
    filepath :
        Output file path.
    """
    self.filepath = Path(filepath)
export
export(network: HaplotypeNetwork) -> None

Export network to GraphML format.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object.

required
Source code in src/pypopart/io/network_export.py
def export(self, network: HaplotypeNetwork) -> None:
    """
    Export network to GraphML format.

    Parameters
    ----------
    network :
        HaplotypeNetwork object.
    """
    # Convert network to NetworkX graph if needed
    graph = network.graph if hasattr(network, 'graph') else network

    # Sanitize graph data for export (strict mode for GraphML)
    sanitized_graph = _sanitize_graph_for_export(graph, format_type='graphml')

    # Write to GraphML
    nx.write_graphml(sanitized_graph, self.filepath)

GMLExporter

Export haplotype networks to GML format.

Source code in src/pypopart/io/network_export.py
class GMLExporter:
    """Export haplotype networks to GML format."""

    def __init__(self, filepath: Union[str, Path]):
        """
        Initialize GML exporter.

        Parameters
        ----------
        filepath :
            Output file path.
        """
        self.filepath = Path(filepath)

    def export(self, network: HaplotypeNetwork) -> None:
        """
        Export network to GML format.

        Parameters
        ----------
        network :
            HaplotypeNetwork object.
        """
        graph = network.graph if hasattr(network, 'graph') else network

        # Sanitize graph data for export (GML requires strings like GraphML)
        sanitized_graph = _sanitize_graph_for_export(graph, format_type='graphml')

        # Write to GML
        nx.write_gml(sanitized_graph, self.filepath)
__init__
__init__(filepath: Union[str, Path])

Initialize GML exporter.

Parameters:

Name Type Description Default
filepath Union[str, Path]

Output file path.

required
Source code in src/pypopart/io/network_export.py
def __init__(self, filepath: Union[str, Path]):
    """
    Initialize GML exporter.

    Parameters
    ----------
    filepath :
        Output file path.
    """
    self.filepath = Path(filepath)
export
export(network: HaplotypeNetwork) -> None

Export network to GML format.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object.

required
Source code in src/pypopart/io/network_export.py
def export(self, network: HaplotypeNetwork) -> None:
    """
    Export network to GML format.

    Parameters
    ----------
    network :
        HaplotypeNetwork object.
    """
    graph = network.graph if hasattr(network, 'graph') else network

    # Sanitize graph data for export (GML requires strings like GraphML)
    sanitized_graph = _sanitize_graph_for_export(graph, format_type='graphml')

    # Write to GML
    nx.write_gml(sanitized_graph, self.filepath)

CytoscapeExporter

Export haplotype networks to Cytoscape JSON format.

Source code in src/pypopart/io/network_export.py
class CytoscapeExporter:
    """Export haplotype networks to Cytoscape JSON format."""

    def __init__(self, filepath: Union[str, Path]):
        """
        Initialize Cytoscape exporter.

        Parameters
        ----------
        filepath :
            Output file path.
        """
        self.filepath = Path(filepath)

    def export(self, network: HaplotypeNetwork) -> None:
        """
        Export network to Cytoscape JSON format.

        Parameters
        ----------
        network :
            HaplotypeNetwork object.
        """
        graph = network.graph if hasattr(network, 'graph') else network

        # Sanitize graph data for export
        sanitized_graph = _sanitize_graph_for_export(graph)

        # Convert to Cytoscape JSON format
        cytoscape_data = nx.cytoscape_data(sanitized_graph)

        with open(self.filepath, 'w') as f:
            json.dump(cytoscape_data, f, indent=2)
__init__
__init__(filepath: Union[str, Path])

Initialize Cytoscape exporter.

Parameters:

Name Type Description Default
filepath Union[str, Path]

Output file path.

required
Source code in src/pypopart/io/network_export.py
def __init__(self, filepath: Union[str, Path]):
    """
    Initialize Cytoscape exporter.

    Parameters
    ----------
    filepath :
        Output file path.
    """
    self.filepath = Path(filepath)
export
export(network: HaplotypeNetwork) -> None

Export network to Cytoscape JSON format.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object.

required
Source code in src/pypopart/io/network_export.py
def export(self, network: HaplotypeNetwork) -> None:
    """
    Export network to Cytoscape JSON format.

    Parameters
    ----------
    network :
        HaplotypeNetwork object.
    """
    graph = network.graph if hasattr(network, 'graph') else network

    # Sanitize graph data for export
    sanitized_graph = _sanitize_graph_for_export(graph)

    # Convert to Cytoscape JSON format
    cytoscape_data = nx.cytoscape_data(sanitized_graph)

    with open(self.filepath, 'w') as f:
        json.dump(cytoscape_data, f, indent=2)

JSONExporter

Export haplotype networks to JSON format.

Source code in src/pypopart/io/network_export.py
class JSONExporter:
    """Export haplotype networks to JSON format."""

    def __init__(self, filepath: Union[str, Path]):
        """
        Initialize JSON exporter.

        Parameters
        ----------
        filepath :
            Output file path.
        """
        self.filepath = Path(filepath)

    def export(self, network: HaplotypeNetwork, include_layout: bool = True) -> None:
        """
        Export network to JSON format.

        Parameters
        ----------
        network :
            HaplotypeNetwork object.
        include_layout :
            Whether to include node layout positions.
        """
        graph = network.graph if hasattr(network, 'graph') else network

        # Sanitize graph data for export
        sanitized_graph = _sanitize_graph_for_export(graph)

        # Build JSON structure
        data = {'nodes': [], 'edges': [], 'metadata': {}}

        # Add nodes
        for node, attrs in sanitized_graph.nodes(data=True):
            node_data = {'id': str(node), 'attributes': dict(attrs)}
            data['nodes'].append(node_data)

        # Add edges
        for source, target, attrs in sanitized_graph.edges(data=True):
            edge_data = {
                'source': str(source),
                'target': str(target),
                'attributes': dict(attrs),
            }
            data['edges'].append(edge_data)

        # Add graph metadata
        if hasattr(sanitized_graph, 'graph'):
            data['metadata'] = dict(sanitized_graph.graph)

        with open(self.filepath, 'w') as f:
            json.dump(data, f, indent=2)
__init__
__init__(filepath: Union[str, Path])

Initialize JSON exporter.

Parameters:

Name Type Description Default
filepath Union[str, Path]

Output file path.

required
Source code in src/pypopart/io/network_export.py
def __init__(self, filepath: Union[str, Path]):
    """
    Initialize JSON exporter.

    Parameters
    ----------
    filepath :
        Output file path.
    """
    self.filepath = Path(filepath)
export
export(
    network: HaplotypeNetwork, include_layout: bool = True
) -> None

Export network to JSON format.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object.

required
include_layout bool

Whether to include node layout positions.

True
Source code in src/pypopart/io/network_export.py
def export(self, network: HaplotypeNetwork, include_layout: bool = True) -> None:
    """
    Export network to JSON format.

    Parameters
    ----------
    network :
        HaplotypeNetwork object.
    include_layout :
        Whether to include node layout positions.
    """
    graph = network.graph if hasattr(network, 'graph') else network

    # Sanitize graph data for export
    sanitized_graph = _sanitize_graph_for_export(graph)

    # Build JSON structure
    data = {'nodes': [], 'edges': [], 'metadata': {}}

    # Add nodes
    for node, attrs in sanitized_graph.nodes(data=True):
        node_data = {'id': str(node), 'attributes': dict(attrs)}
        data['nodes'].append(node_data)

    # Add edges
    for source, target, attrs in sanitized_graph.edges(data=True):
        edge_data = {
            'source': str(source),
            'target': str(target),
            'attributes': dict(attrs),
        }
        data['edges'].append(edge_data)

    # Add graph metadata
    if hasattr(sanitized_graph, 'graph'):
        data['metadata'] = dict(sanitized_graph.graph)

    with open(self.filepath, 'w') as f:
        json.dump(data, f, indent=2)

CSVExporter

Export haplotype network statistics to CSV format.

Source code in src/pypopart/io/network_export.py
class CSVExporter:
    """Export haplotype network statistics to CSV format."""

    def __init__(self, filepath: Union[str, Path]):
        """
        Initialize CSV exporter.

        Parameters
        ----------
        filepath :
            Output file path.
        """
        self.filepath = Path(filepath)

    def export_nodes(self, network: HaplotypeNetwork) -> None:
        """
        Export node attributes to CSV.

        Parameters
        ----------
        network :
            HaplotypeNetwork object.
        """
        graph = network.graph if hasattr(network, 'graph') else network

        # Collect all attribute keys
        all_keys = set()
        for _node, attrs in graph.nodes(data=True):
            all_keys.update(attrs.keys())

        fieldnames = ['node_id'] + sorted(all_keys)

        with open(self.filepath, 'w', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()

            for node, attrs in graph.nodes(data=True):
                row = {'node_id': str(node)}
                row.update(attrs)
                writer.writerow(row)

    def export_edges(self, network: HaplotypeNetwork) -> None:
        """
        Export edge attributes to CSV.

        Parameters
        ----------
        network :
            HaplotypeNetwork object.
        """
        graph = network.graph if hasattr(network, 'graph') else network

        # Collect all attribute keys
        all_keys = set()
        for _source, _target, attrs in graph.edges(data=True):
            all_keys.update(attrs.keys())

        fieldnames = ['source', 'target'] + sorted(all_keys)

        with open(self.filepath, 'w', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()

            for source, target, attrs in graph.edges(data=True):
                row = {'source': str(source), 'target': str(target)}
                row.update(attrs)
                writer.writerow(row)

    def export_statistics(
        self, network: HaplotypeNetwork, statistics: Dict[str, Any]
    ) -> None:
        """
        Export network statistics to CSV.

        Parameters
        ----------
        network :
            HaplotypeNetwork object.
        statistics :
            Dictionary of statistics to export.
        """
        with open(self.filepath, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['Statistic', 'Value'])

            for key, value in sorted(statistics.items()):
                writer.writerow([key, value])
__init__
__init__(filepath: Union[str, Path])

Initialize CSV exporter.

Parameters:

Name Type Description Default
filepath Union[str, Path]

Output file path.

required
Source code in src/pypopart/io/network_export.py
def __init__(self, filepath: Union[str, Path]):
    """
    Initialize CSV exporter.

    Parameters
    ----------
    filepath :
        Output file path.
    """
    self.filepath = Path(filepath)
export_nodes
export_nodes(network: HaplotypeNetwork) -> None

Export node attributes to CSV.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object.

required
Source code in src/pypopart/io/network_export.py
def export_nodes(self, network: HaplotypeNetwork) -> None:
    """
    Export node attributes to CSV.

    Parameters
    ----------
    network :
        HaplotypeNetwork object.
    """
    graph = network.graph if hasattr(network, 'graph') else network

    # Collect all attribute keys
    all_keys = set()
    for _node, attrs in graph.nodes(data=True):
        all_keys.update(attrs.keys())

    fieldnames = ['node_id'] + sorted(all_keys)

    with open(self.filepath, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()

        for node, attrs in graph.nodes(data=True):
            row = {'node_id': str(node)}
            row.update(attrs)
            writer.writerow(row)
export_edges
export_edges(network: HaplotypeNetwork) -> None

Export edge attributes to CSV.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object.

required
Source code in src/pypopart/io/network_export.py
def export_edges(self, network: HaplotypeNetwork) -> None:
    """
    Export edge attributes to CSV.

    Parameters
    ----------
    network :
        HaplotypeNetwork object.
    """
    graph = network.graph if hasattr(network, 'graph') else network

    # Collect all attribute keys
    all_keys = set()
    for _source, _target, attrs in graph.edges(data=True):
        all_keys.update(attrs.keys())

    fieldnames = ['source', 'target'] + sorted(all_keys)

    with open(self.filepath, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()

        for source, target, attrs in graph.edges(data=True):
            row = {'source': str(source), 'target': str(target)}
            row.update(attrs)
            writer.writerow(row)
export_statistics
export_statistics(
    network: HaplotypeNetwork, statistics: Dict[str, Any]
) -> None

Export network statistics to CSV.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object.

required
statistics Dict[str, Any]

Dictionary of statistics to export.

required
Source code in src/pypopart/io/network_export.py
def export_statistics(
    self, network: HaplotypeNetwork, statistics: Dict[str, Any]
) -> None:
    """
    Export network statistics to CSV.

    Parameters
    ----------
    network :
        HaplotypeNetwork object.
    statistics :
        Dictionary of statistics to export.
    """
    with open(self.filepath, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['Statistic', 'Value'])

        for key, value in sorted(statistics.items()):
            writer.writerow([key, value])