# BioCypher example project

Checked against BioCypher 0.17.0. Part of the BioCypher LLM guides; index: https://biocypher.org/BioCypher/agents/llms.txt

A complete, runnable project: two CSV files become protein nodes and protein-protein interaction edges, written as Neo4j import files. It uses headless mode, so it needs no network access, and CSV output, so it needs no `pyarrow`. The output at the end was produced by running exactly these files.

In a project generated with the cookiecutter template, keep the template's layout (`src/<package_name>/adapters/<adapter_name>.py`, `create_knowledge_graph.py`) and apply the same patterns there.

## Layout

```text
example/
├── create_knowledge_graph.py
├── adapters/
│   ├── __init__.py          # empty
│   └── protein_adapter.py
├── config/
│   ├── biocypher_config.yaml
│   └── schema_config.yaml
└── data/
    ├── proteins.csv
    └── interactions.csv
```

## data/proteins.csv

```text
uniprot_id,gene_symbol,name,organism,is_reviewed
P04637,TP53,Cellular tumor antigen p53,9606,true
P38398,BRCA1,Breast cancer type 1 susceptibility protein,9606,true
Q00987,MDM2,E3 ubiquitin-protein ligase Mdm2,9606,false
Q00987,MDM2,E3 ubiquitin-protein ligase Mdm2,9606,false
```

## data/interactions.csv

```text
source,target,method,score
P04637,Q00987,two hybrid,0.99
P04637,P38398,affinity chromatography,0.87
P04637,X99999,two hybrid,0.10
```

The data contains a repeated protein row and an interaction with an unknown protein, to show how the adapter handles them.

## config/schema_config.yaml

```yaml
protein:
  represented_as: node
  namespace: uniprot
  input_label: uniprot_protein
  properties:
    gene_symbol: str
    name: str
    organism: int
    is_reviewed: bool

protein protein interaction:
  is_a: pairwise molecular interaction
  represented_as: edge
  input_label: protein_interacts_with_protein
  source: protein
  target: protein
  properties:
    method: str
    score: float
```

## config/biocypher_config.yaml

```yaml
biocypher:
  dbms: neo4j
  offline: true
  strict_mode: false
  schema_config_path: config/schema_config.yaml
  head_ontology: null      # headless: no Biolink download
  output_directory: biocypher-out
  cache_directory: .cache

neo4j:
  file_format: csv         # parquet (the default) needs pyarrow
  edge_labels_order: Leaves
```

## adapters/protein_adapter.py

```python
"""Adapter for a protein table and a protein-protein interaction table."""

import csv
import logging
from collections.abc import Iterator
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)

NodeTuple = tuple[str, str, dict[str, Any]]
EdgeTuple = tuple[str | None, str, str, str, dict[str, Any]]


def _to_bool(value: str) -> bool:
    return value.strip().lower() in {"true", "1", "yes"}


class ProteinAdapter:
    """Yield BioCypher node and edge tuples from two CSV files."""

    def __init__(self, data_dir: str | Path):
        self.data_dir = Path(data_dir)
        self._node_ids: set[str] = set()

    def get_nodes(self) -> Iterator[NodeTuple]:
        with open(self.data_dir / "proteins.csv", newline="") as f:
            for row in csv.DictReader(f):
                node_id = f"uniprot:{row['uniprot_id'].strip()}"
                if node_id in self._node_ids:  # skip exact repeats ourselves
                    continue
                self._node_ids.add(node_id)
                yield (
                    node_id,
                    "uniprot_protein",  # == input_label in schema_config.yaml
                    {
                        "gene_symbol": row["gene_symbol"].strip().upper(),
                        "name": row["name"].strip(),
                        "organism": int(row["organism"]),  # schema says int
                        "is_reviewed": _to_bool(row["is_reviewed"]),  # schema says bool
                    },
                )

    def get_edges(self) -> Iterator[EdgeTuple]:
        # Call after get_nodes() has been consumed, so self._node_ids is filled.
        with open(self.data_dir / "interactions.csv", newline="") as f:
            for row in csv.DictReader(f):
                source_id = f"uniprot:{row['source'].strip()}"
                target_id = f"uniprot:{row['target'].strip()}"
                if source_id not in self._node_ids or target_id not in self._node_ids:
                    logger.warning("Skipping edge with unknown endpoint: %s -> %s", source_id, target_id)
                    continue
                yield (
                    None,  # edge_id: None lets BioCypher handle it
                    source_id,
                    target_id,
                    "protein_interacts_with_protein",  # == input_label
                    {"method": row["method"].strip(), "score": float(row["score"])},
                )
```

Points to note:

- IDs are CURIEs built the same way for nodes and edge endpoints.
- Every value is converted to the schema type; `"false"` is parsed explicitly, because `bool("false")` is `True`.
- The adapter removes repeated rows and dangling edges itself and logs them, instead of relying on BioCypher's silent deduplication.
- Tuples are yielded from generators. Edges are 5-tuples with the label in 4th position.

## create_knowledge_graph.py

```python
from biocypher import BioCypher

from adapters.protein_adapter import ProteinAdapter

bc = BioCypher(
    biocypher_config_path="config/biocypher_config.yaml",
    schema_config_path="config/schema_config.yaml",
)
adapter = ProteinAdapter(data_dir="data")

bc.write_nodes(adapter.get_nodes())  # consume nodes first
bc.write_edges(adapter.get_edges())
bc.write_import_call()  # offline Neo4j: writes neo4j-admin-import-call.sh
bc.log_missing_input_labels()
bc.log_duplicates()  # bc.summary() would fail in headless mode
```

Run it from the `example/` directory: `python create_knowledge_graph.py` (with `biocypher` installed).

## Output

Log (excerpt):

```text
INFO -- Writing 3 entries to Protein-part000.csv
Skipping edge with unknown endpoint: uniprot:P04637 -> uniprot:X99999
INFO -- Writing 2 entries to ProteinProteinInteraction-part000.csv
INFO -- No missing labels in input.
INFO -- No duplicate nodes in input.
INFO -- No duplicate edges in input.
```

`biocypher-out/Protein-header.csv` and `Protein-part000.csv`:

```text
:ID,gene_symbol,name,organism:long,is_reviewed:boolean,id,preferred_id,:LABEL
uniprot:P04637,"TP53","Cellular tumor antigen p53",9606,true,"uniprot:P04637","uniprot","Protein"
uniprot:P38398,"BRCA1","Breast cancer type 1 susceptibility protein",9606,true,"uniprot:P38398","uniprot","Protein"
uniprot:Q00987,"MDM2","E3 ubiquitin-protein ligase Mdm2",9606,false,"uniprot:Q00987","uniprot","Protein"
```

`biocypher-out/ProteinProteinInteraction-header.csv` and `ProteinProteinInteraction-part000.csv`:

```text
:START_ID,id,method,score:double,:END_ID,:TYPE
uniprot:P04637,,"two hybrid",0.99,uniprot:Q00987,"ProteinProteinInteraction"
uniprot:P04637,,"affinity chromatography",0.87,uniprot:P38398,"ProteinProteinInteraction"
```

Plus `neo4j-admin-import-call.sh`, which imports these files with `neo4j-admin database import full` (Neo4j 5+) or `neo4j-admin import` (older versions).

## Variant: in-memory graph

Change the config to `dbms: networkx` (or `pandas`) and `offline: false`, then:

```python
bc.add(adapter.get_nodes())
bc.add(adapter.get_edges())
kg = bc.get_kg()  # networkx.DiGraph with 3 nodes and 2 edges
                  # (pandas: dict of DataFrames keyed by class name)
```
