Project: s41467-025-56348-1 | Function: RTstop_mismatch (python)

system: You are an expert Python programmer implementing algorithms from scientific papers.
Complete the masked function based on the algorithm description.
Follow Python best practices and maintain consistent code style.
Return **only** the complete Python function code.

user: Complete this Python function:

**DESCRIPTION:** Core algorithm for analyzing RT stops and misincorporations at tRNA modification sites. Processes data for each position to calculate readthrough proportions based on coverage ratios, implementing the key computational method for detecting tRNA modifications described in the paper.

**KEY TERMS:** {
  "RTstop": "RT stops",
  "mismatch": "misincorporation",
  "readthrough": "readthrough frequency",
  "proportion": "frequency/rate calculation",
  "cov": "coverage/read counts"
}

**CONTEXT CODE:** 
    for file in ['cyto_Isodecoder','cyto_Anticodon','mito_Isodecoder']:

        print("file:",file)
        if file == 'cyto_Anticodon':path = "{}DESeq2/cyto/anticodon/".format(directory)
        elif file == 'cyto_Isodecoder':path = "{}DESeq2/cyto/isodecoder/".format(directory)
        elif file == 'mito_Isodecoder':path = "{}DESeq2/organelle/isodecoder/".format(directory)

        f1 = sampledic.loc[0,"sample"]
        f2 = sampledic.loc[1,"sample"]
        ff = [f1,f2]
        ff_ = ff
        col1 = [sampledic.loc[0,"file_unpaired_uniq"]]
        col2 = [sampledic.loc[1,"file_unpaired_uniq"]]
        df = pd.read_csv(f"{path}singleRep-normCounts.csv",usecols=["Gene"]+col1+col2).rename(columns={col1[0]:f1,col2[0]:f2})
        df = df[df['Gene'].str.contains(organism)].reset_index(drop=True)
        df['{}_log10'.format(f1)] = np.log10(df[f1])
        df['{}_log10'.format(f2)] = np.log10(df[f2])
        df.replace([np.inf,-np.inf],0,inplace=True)
        print(df.head())
        print("len(file):",len(df))

        # plot
        fig = plt.figure(figsize=(2.9,3.1))
        ax = fig.add_subplot(111)

        if log10 == 'log10':
            xcol = '{}_log10'.format(f1)
            ycol = '{}_log10'.format(f2)
        else:
            xcol = f1
            ycol = f2

        x = df[xcol]
        y = df[ycol]
        ax.scatter(x,y,c='darkgray',alpha=0.3,edgecolor="darkgray",s=10)
        ax.plot([0,6],[0,6],linewidth=0.5,c='gray')
        r, p_value = pearsonr(df[f1],df[f2])
        ax.text(4,0.5,"R = {}".format(round(r,2)))
        ax.set_ylim(0,6)#maxval)
        ax.set_xlim(0,6)#maxval)
        ax.tick_params(axis='x',labelsize=10)
        ax.tick_params(axis='y',labelsize=10)
        ax.set_xlabel(xcol,fontsize=10)
        ax.set_ylabel(ycol,fontsize=10)
        plt.tight_layout()
        plt.savefig('{}figures/differential_expression_{}.png'.format(directory,file))

# [4] Isodecoder毎に、modificationの判定をする
# 各isodecoderごとに、各位置のRTstopとmismatchのproportionをまとめた表
def RTstop_mismatch(directory,folder,sampledic,organism):#10%のthreshold判定をなくしてみた
    # MASKED: Core algorithm for analyzing RT stops and misincorporations at tRNA modification sites. Processes data for each position to calculate readthrough proportions based on coverage ratios, implementing the key computational method for detecting tRNA modifications described in the paper.
    raise NotImplementedError("This function is masked for testing purposes.")
# [5] % Full length reads
def full_length(directory,sample):
    out = pd.DataFrame()
    o = -1
    for s in sample:
        print("sample:",s)
        df = pd.read_csv("{}RTstop_mismatch_summarized_{}.csv".format(directory,s))
        df["cov"] = df["cov"].astype("float")
        # print(df.head())
        # print(df[df["canon_pos"]=="0"])
        for i in set(df["isodecoder"]):
            # print("isodecoder:",i)
            dfi = df[df["isodecoder"]==i]
            # print(dfi.head())
            for r in set(dfi["replicate_num"]):
                o += 1
                dfr = dfi[dfi["replicate_num"]==r].reset_index(drop=True)
                # print("replicate:",r)
                cov = dfr.loc[0,"cov"]
                if np.isnan(cov):
                    print("NaN in",i)
                    break
                if cov != min(dfr["cov"]):
                    print("min(coverage) does not equal coverage at position 1 in",i)
                    print("min cov",cov)
                    print(dfr.head())
                    # print(dfr.tail())
                # print(cov)
                # print(max(dfr["cov"]))
                # print(cov/max(dfr["cov"])*100)
                out.loc[o,"condition"] = s
                out.loc[o,"cyto_mito"] = dfr.loc[0,"cyto_mito"]
                out.loc[o,"full_length(%)"] = cov/max(dfr["cov"])*100
    print("done")
    # print(out.head())
    # print(out.tail())
    out.to_csv("{}full_length_reads.csv".format(directory),index=False)

    # plot
    sns.set()
    sns.set_style("ticks")
    # color = ["#d0dfed","#7fabdb","#2376c8","#d9c0d3","#d97aa6","#d3095f"]
    color = ["#D6FA8C","#A5D721","#82B300","#FDB777","#FD9346","#FF6200"]
    fig = plt.figure(figsize=(4,3*0.6*len(sample)))
    a = 0
    for cm in ["all","cyto","mito"]:
        a += 1
        ax = fig.add_subplot(3, 1, a)
        if cm == "all":
            data = out
        else:
            data = out[out["cyto_mito"]==cm].reset_index(drop=True)
        flierprops = dict(marker='o', markersize=1, alpha=0.5)
        # sns.boxplot(x="condition",y="full_length(%)",data=data,ax=ax,palette=color,order=sample,flierprops=flierprops)
        sns.violinplot(x="condition",y="full_length(%)",data=data,ax=ax,palette=color,order=sample,flierprops=flierprops)
        for l in range(len(sample)-1):
            # print(sample[l],"vs",sample[l+1])
            signal = test(data[data["condition"]==sample[l]]["full_length(%)"],data[data["condition"]==sample[l+1]]["full_length(%)"],sample[l],sample[l+1])
            if signal != "":
                plt.text(l+0.5,102,signal,ha="center",fontsize=20)
                plt.plot([l+0.1,l+0.9],[107,107],c="black")
        ax.set_title(f"{cm} tRNAs")
        plt.ylim(-10,120)
        plt.xticks(rotation=45)
        plt.tight_layout()
    plt.savefig("{}figures/Full-length_reads_version3.png".format(directory))

# [6] Sum of misincorporation proportions
def ave_mismatch(directory,sample):
    out = pd.DataFrame()
    o = -1
    for s in sample:
        print("sample:",s)
        df = pd.read_csv("{}RTstop_mismatch_summarized_{}.csv".format(directory,s))
        df = df[df["prop_type"]=="mismatch"].reset_index(drop=True)
        print(df.head())
        # print(df[df["canon_pos"]=="0"])
        for i in set(df["isodecoder"]):
            # print("isodecoder:",i)
            dfi = df[df["isodecoder"]==i]
            # print(dfi.head())
            for r in set(dfi["replicate_num"]):
                o += 1
                dfr = dfi[dfi["replicate_num"]==r].reset_index(drop=True)
                # print("len:",len(dfr))
                # print(dfr.head())
                # out.loc[o,"isodecoder"] = i
                out.loc[o,"cyto_mito"] = dfr.loc[0,"cyto_mito"]
                out.loc[o,"condition"] = s
                out.loc[o,"ave_mismatch"] = sum(dfr["proportion"])/len(dfr)
    print("done")
    print(out.head())
    # print(out.tail())
    out.to_csv("{}ave_misincorporation.csv".format(directory),index=False)

    # plot
    sns.set()


Complete the function implementation replacing "raise NotImplementedError".