File size: 5,494 Bytes
bf004e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import os
import json
import csv
import pandas as pd

def clean_value(v):
    if isinstance(v, str):
        return v.replace("\n", ",")
    if isinstance(v, list):
        return ";".join(map(str, v))
    return v


def torsion_stats_dict(file_path):
    try:
        df = pd.read_csv(file_path)
    except FileNotFoundError:
        return {}
    # Detect torsion columns automatically
    torsion_cols = [c for c in df.columns if "_phi" in c or "_psi" in c or "_omega" in c]

    grouped = df.groupby("cluster")

    count_df = grouped.size().rename("count")
    mean_df = grouped[torsion_cols].mean()
    std_df = grouped[torsion_cols].std()

    mean_df.columns = [c + "_mean" for c in mean_df.columns]
    std_df.columns = [c + "_std" for c in std_df.columns]

    result_df = pd.concat([count_df, mean_df, std_df], axis=1)

    # Convert dataframe → formatted dictionary
    result_dict = {}

    for cluster_id, row in result_df.iterrows():

        cluster_key = f"Cluster {int(cluster_id)}"
        cluster_data = {}

        for col, val in row.items():

            if col == "count":
                cluster_data[col] = int(val)

            else:
                cluster_data[col] = round(float(val), 2)

        result_dict[cluster_key] = cluster_data

    return result_dict


raw_loc='../raw_data/'

GS_list = [
    d for d in os.listdir(raw_loc)
    if "GS" in d and os.path.isdir(os.path.join(raw_loc, d))
]

print('GS_list',len(GS_list))

data_archetype_term_list = ["glytoucan", "ID", "name", "glycam", "iupac", "iupac_extended", "wurcs", "glycoct",
                            "smiles", "oxford", "mass", "motifs", "termini", "components", "composition", "rot_bonds",
                            "hbond_donor", "hbond_acceptor", "entropy", "clusters","coverage_clusters","silhouette_scores","coverage_clusters_per_main","pca_variance", "length", "package", "forcefield",
                            "temperature", "pressure", "salt", ]
data_alpha_term_list = ["glycam", "iupac", "iupac_extended", "glytoucan", "wurcs", ]
data_beta_term_list = ["glycam", "iupac", "iupac_extended", "glytoucan", "wurcs", ]
data_meta_term_list = ["common_names", "description", "keywords"]
glygen_term_list=["number_monosaccharides","species","classification","enzyme","crossref","mass_pme","tool_support","missing_score","glycan_type","byonic","gwb","motifs","subsumption","section_stats","history",]



# ---- Build header ----
header_list=[]
header_list.extend(['SNFG','torsion_table','torsion_analysis'])
header_list.extend(data_archetype_term_list)
header_list.extend(["a_"+i for i in data_alpha_term_list])
header_list.extend(["b_"+i for i in data_beta_term_list])
header_list.extend(data_meta_term_list)
header_list.extend(['calculated_torsion','a_calculated_torsion','b_calculated_torsion',])
header_list.extend(['glycosmos'])
header_list.extend(glygen_term_list)

output_file = "../data/glycoshape_data.csv"
csvfile=open(output_file, "w", newline="", encoding="utf-8")
writer = csv.writer(csvfile)


# ---- load calculated torsion ---
with open("../data/glycan_dictionary.json", "r", encoding="utf-8") as f:
    calculated_torsion = json.load(f)
    f.close()



# Write header
writer.writerow(header_list)

for GS in GS_list:
    #print(GS)
    GS_loc=raw_loc+GS+'/'
    row = []

    ### add snfg.svg
    v='./raw_data'+GS+'/'+'snfg.svg'
    row.append(clean_value(v))


    ### add raw torsion table
    v = './torsion_data/' + GS + '_torsion_data.txt'
    row.append(clean_value(v))

    ## analysis torsion
    v=torsion_stats_dict('.'+v)
    row.append(clean_value(v))

    ### load data.json
    with open(GS_loc+"data.json", "r", encoding="utf-8") as f:
        data = json.load(f)
        f.close()

    for i in data_archetype_term_list:
        v = data.get('archetype', {}).get(i, "")
        row.append(clean_value(v))

    for i in data_alpha_term_list:
        v = data.get('alpha', {}).get(i, "")
        row.append(clean_value(v))

    for i in data_beta_term_list:
        v = data.get('beta', {}).get(i, "")
        row.append(clean_value(v))

    for i in data_meta_term_list:
        v = data.get('search_meta', {}).get(i, "")
        row.append(clean_value(v))

    gtouch=data['archetype']['glytoucan']
    a_gtouch=data['alpha']['glytoucan']
    b_gtouch=data['beta']['glytoucan']
    print(GS,gtouch,a_gtouch,b_gtouch)

    ### load calculated torsion json
    try:
        v=calculated_torsion[gtouch]
    except KeyError:
        v={}
    row.append(clean_value(v))

    try:
        v = calculated_torsion[a_gtouch]
    except KeyError:
        v = {}
    row.append(clean_value(v))

    try:
        v = calculated_torsion[b_gtouch]
    except KeyError:
        v = {}
    row.append(clean_value(v))


    ### load glycosmos.json
    with open(GS_loc+"glycosmos.json", "r", encoding="utf-8") as f:
        glycosmos = json.load(f)
        f.close()

    #print(glycosmos)
    v = glycosmos
    row.append(clean_value(v))

    ### load glygen.json
    with open(GS_loc+"glygen.json", "r", encoding="utf-8") as f:
        glygen = json.load(f)
        f.close()

    for i in glygen_term_list:
        try:
            v = glygen[i]
        except :
            v=[]
        row.append(clean_value(v))

    writer.writerow(row)
    #print(header_list)
    #print(row)