"""CPV1 · paso 42 (Python puro): línea base del pre-registro §7, «la división más frecuente del órgano» (si no, la de tipo × menor; si no, la global), con su confianza (la parte de la moda). Entrenamientos: ≤ 2022 (para 2023), ≤ 2023 (para 2024-2025) y ≤ 2023 sin cada fuente S (para S-2024-2025). Escribe interno/pred/base__.tsv (id, pred, conf).""" import sys, os, collections sys.path.insert(0, '/w/py') import cpvtexto as ct D = '/w/interno/datos'; P = '/w/interno/pred' LOSO = ['ANDALUCIA', 'CATALUNYA', 'CATALUNYA_PSCP', 'EUSKADI', 'EXTREMADURA', 'VALENCIA', 'ARAGON', 'TED', 'MURCIA'] # recuentos por (fuente, órgano, div) y (fuente, (tipo, menor), div) en ≤ 2022 y en 2023 co = {22: collections.Counter(), 23: collections.Counter()} ct_ = {22: collections.Counter(), 23: collections.Counter()} evals = {'E2023': [], 'E2425': []} with open(f'{D}/E.tsv', encoding='utf-8') as f: cab = f.readline().rstrip('\n').split('\t') I = {c: i for i, c in enumerate(cab)} for l in f: r = l.rstrip('\n').split('\t') if not ct.terminos(r[I['objeto']]): continue a = int(r[I['anio_ref']]); src = r[I['source']]; org = r[I['organo_clave']] tm = (r[I['tipo_contrato']], r[I['es_menor']]); y = r[I['div']] if a <= 2023: k = 22 if a <= 2022 else 23 if org: co[k][(src, org, y)] += 1 ct_[k][(src, tm, y)] += 1 if a == 2023: evals['E2023'].append((r[I['id_canonical']], src, org, tm)) elif a in (2024, 2025): evals['E2425'].append((r[I['id_canonical']], src, org, tm)) def tabla(cont_list, excl=None): o = collections.defaultdict(collections.Counter) for cont in cont_list: for (src, key, y), n in cont.items(): if src != excl: o[key][y] += n return o def moda(c): tot = sum(c.values()) y = min(c, key=lambda d: (-c[d], d)) return y, c[y] / tot def predice(nombre, filas, conts_o, conts_t, excl=None): to = tabla(conts_o, excl); tt = tabla(conts_t, excl) glob = collections.Counter() for c in tt.values(): glob.update(c) mo = {k: moda(c) for k, c in to.items()}; mt = {k: moda(c) for k, c in tt.items()}; mg = moda(glob) with open(f'{P}/base__{nombre}.tsv', 'w', encoding='utf-8') as fo: fo.write('id\tpred\tconf\n') n = 0 for idc, src, org, tm in filas: if excl and src != excl: continue y, c = mo.get(org) or mt.get(tm) or mg fo.write(f'{idc}\t{y}\t{c!r}\n'); n += 1 print(nombre, n, flush=True) predice('E2023', evals['E2023'], [co[22]], [ct_[22]]) predice('E2425', evals['E2425'], [co[22], co[23]], [ct_[22], ct_[23]]) for s in LOSO: predice(f'E2425_{s}', evals['E2425'], [co[22], co[23]], [ct_[22], ct_[23]], excl=s)