你可以使用以下shell脚本来处理stereoseq数据并生成矩阵和坐标文件:
#!/bin/bash
input_file="$1"
output_prefix="${input_file%.*}"
# 第一步:处理数据并生成中间文件
awk '
# 跳过注释行和header
/^#/ { next }
NR == 1 { next }
{
geneID = $1
x = $2
y = $3
count = $4
# 计算bin坐标
bin_x = int(x/100)
bin_y = int(y/100)
bin_name = "bin100_" bin_x "_" bin_y
# 累加count
data[geneID][bin_name] += count
# 记录所有基因和bin
genes[geneID] = 1
bins[bin_name] = 1
bin_coords[bin_name] = bin_x "_" bin_y
}
END {
# 生成矩阵文件
matrix_file = "'${output_prefix}'_matrix.txt"
coord_file = "'${output_prefix}'_coordinates.txt"
# 输出矩阵header
printf "geneID" > matrix_file
for (bin in bins) {
printf "\t%s", bin >> matrix_file
}
printf "\n" >> matrix_file
# 输出矩阵数据
for (gene in genes) {
printf "%s", gene >> matrix_file
for (bin in bins) {
count = (gene in data && bin in data[gene]) ? data[gene][bin] : 0
printf "\t%d", count >> matrix_file
}
printf "\n" >> matrix_file
}
# 生成坐标文件
printf "bin_name\tx_center\ty_center\tbin_x\tbin_y\n" > coord_file
for (bin in bins) {
split(bin_coords[bin], coords, "_")
bin_x = coords[1]
bin_y = coords[2]
x_center = bin_x * 100 + 50
y_center = bin_y * 100 + 50
printf "%s\t%d\t%d\t%d\t%d\n", bin, x_center, y_center, bin_x, bin_y >> coord_file
}
print "Matrix file generated: " matrix_file
print "Coordinates file generated: " coord_file
}' "$input_file"
如果你希望输出更紧凑的格式(只包含非零值),可以使用这个版本:
#!/bin/bash
input_file="$1"
output_prefix="${input_file%.*}"
awk '
/^#/ { next }
NR == 1 { next }
{
geneID = $1
x = $2
y = $3
count = $4
bin_x = int(x/100)
bin_y = int(y/100)
bin_name = "bin100_" bin_x "_" bin_y
data[geneID][bin_name] += count
genes[geneID] = 1
bins[bin_name] = 1
bin_coords[bin_name] = bin_x "_" bin_y
}
END {
matrix_file = "'${output_prefix}'_matrix.txt"
coord_file = "'${output_prefix}'_coordinates.txt"
sparse_file = "'${output_prefix}'_sparse.txt"
# 1. 生成完整矩阵
printf "geneID" > matrix_file
n = asorti(bins, sorted_bins)
for (i = 1; i <= n; i++) {
printf "\t%s", sorted_bins[i] >> matrix_file
}
printf "\n" >> matrix_file
asorti(genes, sorted_genes)
for (i = 1; i <= length(sorted_genes); i++) {
gene = sorted_genes[i]
printf "%s", gene >> matrix_file
for (j = 1; j <= n; j++) {
bin = sorted_bins[j]
count = (gene in data && bin in data[gene]) ? data[gene][bin] : 0
printf "\t%d", count >> matrix_file
}
printf "\n" >> matrix_file
}
# 2. 生成坐标文件
printf "bin_name\tx_center\ty_center\tbin_x\tbin_y\n" > coord_file
for (i = 1; i <= n; i++) {
bin = sorted_bins[i]
split(bin_coords[bin], coords, "_")
bin_x = coords[1]
bin_y = coords[2]
x_center = bin_x * 100 + 50
y_center = bin_y * 100 + 50
printf "%s\t%d\t%d\t%d\t%d\n", bin, x_center, y_center, bin_x, bin_y >> coord_file
}
# 3. 生成稀疏格式 (可选)
printf "geneID\tbin_name\tMIDCounts\n" > sparse_file
for (gene in genes) {
if (gene in data) {
for (bin in data[gene]) {
if (data[gene][bin] > 0) {
printf "%s\t%s\t%d\n", gene, bin, data[gene][bin] >> sparse_file
}
}
}
}
print "Files generated:"
print " Matrix: " matrix_file
print " Coordinates: " coord_file
print " Sparse: " sparse_file
}' "$input_file"