File size: 4,951 Bytes
fd5bf9c | 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 | import argparse
import csv
import json
import os
import re
TCGA_ID_RE = re.compile(r"(TCGA-[A-Z0-9]{2}-[A-Z0-9]+)")
def extract_case_id(name):
m = TCGA_ID_RE.search(name)
return m.group(1) if m else None
def read_cases_from_split(path):
cases = set()
with open(path, newline='') as f:
reader = csv.DictReader(f)
for r in reader:
for key in ('train', 'val', 'test'):
item = (r.get(key) or '').strip()
if not item:
continue
cid = extract_case_id(item)
if cid:
cases.add(cid)
return cases
def list_input_csvs(input_dir, output_path):
files = []
for n in os.listdir(input_dir):
if n.startswith('.'):
continue
if not n.startswith('splits_') or not n.endswith('.csv'):
continue
if 'MERGED' in n.upper():
continue
files.append(os.path.join(input_dir, n))
files = sorted(files)
if output_path:
out_abs = os.path.abspath(output_path)
files = [p for p in files if os.path.abspath(p) != out_abs]
return files
def choose_default_inputs(input_dir):
return list_input_csvs(input_dir, None)
def build_case_label_map(inputs):
case_to_label = {}
conflicts = []
for label, path in enumerate(inputs):
cases = read_cases_from_split(path)
for cid in cases:
if cid in case_to_label and case_to_label[cid] != label:
conflicts.append((cid, case_to_label[cid], label, path))
continue
case_to_label[cid] = label
return case_to_label, conflicts
def write_labels_csv(case_to_label, merged_cases, output_path):
missing = []
rows = []
for cid in sorted(merged_cases):
if cid not in case_to_label:
missing.append(cid)
continue
rows.append((cid, case_to_label[cid]))
with open(output_path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['case_id', 'label'])
for cid, label in rows:
writer.writerow([cid, label])
return rows, missing
def write_mapping(mapping_rows, mapping_output):
if not mapping_output:
return
if mapping_output.lower().endswith('.json'):
with open(mapping_output, 'w', encoding='utf-8') as f:
json.dump(mapping_rows, f, ensure_ascii=True, indent=2)
return
with open(mapping_output, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['label', 'source_name', 'source_csv'])
for row in mapping_rows:
writer.writerow([row['label'], row['source_name'], row['source_csv']])
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', default='/mnt/datadisk0/data_process')
parser.add_argument('--inputs', nargs='*', default=None)
parser.add_argument('--merged', default='/mnt/datadisk0/data_process/splits_ALL_MERGED.csv')
parser.add_argument('--output', default='/mnt/datadisk0/data_process/splits_5MERGED_labels.csv')
parser.add_argument('--mapping_output', default=None)
args = parser.parse_args()
if args.inputs:
inputs = args.inputs
else:
inputs = choose_default_inputs(args.input_dir)
mapping_rows = []
for label, path in enumerate(inputs):
base_name = os.path.basename(path)
source_name = os.path.splitext(base_name)[0].replace('splits_', '')
mapping_rows.append({'label': label, 'source_name': source_name, 'source_csv': path})
if args.mapping_output is None:
base_out = os.path.splitext(args.output)[0]
args.mapping_output = base_out + '_map.csv'
merged_cases = read_cases_from_split(args.merged)
case_to_label, conflicts = build_case_label_map(inputs)
rows, missing = write_labels_csv(case_to_label, merged_cases, args.output)
write_mapping(mapping_rows, args.mapping_output)
print('Input CSVs:', len(inputs))
print('Merged file:', args.merged)
print('Merged cases:', len(merged_cases))
print('Labeled cases:', len(rows))
print('Output CSV:', args.output)
print('Mapping output:', args.mapping_output)
print('Label mapping:')
for row in mapping_rows:
print(f" {row['label']} -> {row['source_name']} ({row['source_csv']})")
if missing:
print('Missing labels for cases:', len(missing))
for cid in missing[:20]:
print(' ', cid)
if len(missing) > 20:
print(' ... and', len(missing) - 20, 'more')
if conflicts:
print('Conflicting labels:', len(conflicts))
for cid, old_label, new_label, path in conflicts[:20]:
print(' ', cid, 'existing=', old_label, 'new=', new_label, 'from', path)
if len(conflicts) > 20:
print(' ... and', len(conflicts) - 20, 'more')
if __name__ == '__main__':
main()
|