import spatialdata as sd
from spatialdata_io import xenium

import matplotlib.pyplot as plt
import seaborn as sns

import scanpy as sc 
import pandas as pd
import squidpy as sq

import anndata
/home/lchen/miniconda3/envs/squidpy/lib/python3.11/site-packages/dask/dataframe/__init__.py:31: FutureWarning: The legacy Dask DataFrame implementation is deprecated and will be removed in a future version. Set the configuration option `dataframe.query-planning` to `True` or None to enable the new Dask Dataframe implementation and silence this warning.
  warnings.warn(
/home/lchen/miniconda3/envs/squidpy/lib/python3.11/site-packages/torch/cuda/__init__.py:61: FutureWarning: The pynvml package is deprecated. Please install nvidia-ml-py instead. If you did not install pynvml directly, please report this to the maintainers of the package that installed pynvml for you.
  import pynvml  # type: ignore[import]
/home/lchen/miniconda3/envs/squidpy/lib/python3.11/site-packages/xarray_schema/__init__.py:1: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81.
  from pkg_resources import DistributionNotFound, get_distribution
/home/lchen/miniconda3/envs/squidpy/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
# Prepare inputs for stmut-hires from Atera

# Set default figdir
sc.settings.figdir = "/stomics_data/liminData/Visium/Atera/figures"


# file format
sc.settings.file_format_figs = "pdf"

# figure quality
sc.settings.set_figure_params(
    dpi=100,
    dpi_save=300,
    frameon=False
) # dpi --> display; dpi_save-->saved file
dir1 = "/stomics_data/liminData/Visium/Atera"

atera_path = f"{dir1}/cervical_cancer_wta_ffpe"
zarr_path = f"{dir1}/analysis/cervical_cancer.zarr"

sdata = xenium(atera_path)
sdata

/tmp/ipykernel_235128/746865148.py:6: DeprecationWarning: The default value of `cells_as_circles` will change to `False` in the next release. Please pass `True` explicitly to maintain the current behavior.
  sdata = xenium(atera_path)
/home/lchen/miniconda3/envs/squidpy/lib/python3.11/functools.py:909: ImplicitModificationWarning: Transforming to str index.
  return dispatch(args[0].__class__)(*args, **kw)
SpatialData object
├── Images
│     └── 'morphology_focus': DataTree[cyx] (4, 41877, 42001), (4, 20938, 21000), (4, 10469, 10500), (4, 5234, 5250), (4, 2617, 2625)
├── Labels
│     ├── 'cell_labels': DataTree[yx] (41877, 42001), (20938, 21000), (10469, 10500), (5234, 5250), (2617, 2625)
│     └── 'nucleus_labels': DataTree[yx] (41877, 42001), (20938, 21000), (10469, 10500), (5234, 5250), (2617, 2625)
├── Points
│     └── 'transcripts': DataFrame with shape: (<Delayed>, 13) (3D points)
├── Shapes
│     ├── 'cell_boundaries': GeoDataFrame shape: (717576, 1) (2D shapes)
│     ├── 'cell_circles': GeoDataFrame shape: (717576, 2) (2D shapes)
│     └── 'nucleus_boundaries': GeoDataFrame shape: (710540, 1) (2D shapes)
└── Tables
      └── 'table': AnnData (717576, 18028)
with coordinate systems:
    ▸ 'global', with elements:
        morphology_focus (Images), cell_labels (Labels), nucleus_labels (Labels), transcripts (Points), cell_boundaries (Shapes), cell_circles (Shapes), nucleus_boundaries (Shapes)
import zarr
import pandas as pd

# Path to your file
zarr_path = f"{dir1}/cervical_cancer_wta_ffpe/analysis.zarr.zip"

# 1. Open the ZipStore correctly
store = zarr.storage.ZipStore(zarr_path, mode='r')
root = zarr.open(store)
# print(root.tree())
import zarr
import pandas as pd
import numpy as np

# Paths
dir_path = "/stomics_data/liminData/Visium/Atera/breast_cancer"
zarr_path = f"{dir_path}/analysis.zarr.zip"
parquet_path = f"{dir_path}/cells.parquet"

# 1. Get Barcodes from Parquet (ensures order matches analysis)
cells_df = pd.read_parquet(parquet_path)
barcodes = cells_df['cell_id'].values

# 2. Open Zarr and extract Graph-based (Group 0)
store = zarr.storage.ZipStore(zarr_path, mode='r')
root = zarr.open(store)

indices = root['cell_groups/0/indices'][:]
indptr = root['cell_groups/0/indptr'][:]

# 3. Reconstruct assignments
# Create an array to hold the cluster ID for every cell
cluster_assignments = np.zeros(len(barcodes), dtype=int)

for cluster_idx in range(len(indptr) - 1):
    start = indptr[cluster_idx]
    end = indptr[cluster_idx + 1]
    # These are the positions in the original barcode list
    affected_cell_indices = indices[start:end]
    # Assign cluster ID (using 1-based indexing to match Explorer usually)
    cluster_assignments[affected_cell_indices] = cluster_idx + 1

# 4. Final CSV
result_df = pd.DataFrame({
    'Barcode': barcodes,
    'Graph-based': cluster_assignments
})

result_df['Graph-based'] = "Cluster " + result_df['Graph-based'].astype(str)
result_df.to_csv(f"{dir_path}/stmut_input/graph_based_clusters.csv", index=False)
print(f"Success: Exported {len(result_df)} cells and {len(indptr)-1} clusters.")
Success: Exported 170057 cells and 34 clusters.
f1 = "/stomics_data/liminData/Visium/stmut_python/BD17_bin8_inputs/"
visiumhd = pd.read_parquet(f"{f1}/spatial/tissue_positions.parquet")
visiumhd
barcode in_tissue array_row array_col pxl_row_in_fullres pxl_col_in_fullres
0 s_008um_00000_00000-1 1 0 0 10403.994819 5261.295725
1 s_008um_00000_00001-1 1 0 1 10404.002446 5268.886621
2 s_008um_00000_00002-1 1 0 2 10404.010073 5276.477516
3 s_008um_00000_00003-1 1 0 3 10404.017701 5284.068412
4 s_008um_00000_00004-1 1 0 4 10404.025328 5291.659306
... ... ... ... ... ... ...
702239 s_008um_00837_00833-1 1 837 833 4056.920142 11590.764046
702240 s_008um_00837_00834-1 1 837 834 4056.927932 11598.354482
702241 s_008um_00837_00835-1 1 837 835 4056.935722 11605.944917
702242 s_008um_00837_00836-1 1 837 836 4056.943511 11613.535352
702243 s_008um_00837_00837-1 1 837 837 4056.951301 11621.125787

702244 rows × 6 columns

f2 = "/stomics_data/liminData/Visium/Atera/breast_cancer"
atera = pd.read_parquet(f"{f2}/cells.parquet")
atera 
atera_sub = atera[["cell_id", "x_centroid", "y_centroid"]]
atera_sub = atera_sub.rename(
    columns={
        'cell_id': "barcode",
        'x_centroid': "array_col",
        'y_centroid': "array_row"
    }
)

atera_sub.to_parquet(f"{f2}/stmut_input/transformed_position.parquet")
INDIR="/stomics_data/liminData/Visium/Atera/data/stmut_input"
OUTDIR="/stomics_data/liminData/Visium/Atera/analysis"

stmut-hires run \
    --exp_h5 ${INDIR}/cell_feature_matrix.h5 \
    --cluster_file ${INDIR}/graph_based_29clusters.csv \
    --spatial_file ${INDIR}/transformed_position.parquet \
    --output_dir ${OUTDIR} \
    --cutoff 10 \
    --num_processes 10 \
    --cores 10 \
    --pmtimes 50 \
    --ncluster 6
cell_id        object
x_centroid    float64
y_centroid    float64
dtype: object