"""LOC1 · tablas fijas compartidas (la segunda implementación NO importa esto: tiene las suyas).""" import math, unicodedata, re # INE: código de provincia -> (nombre, CCAA ISO) PROV = {'01':('Araba/Álava','PV'),'02':('Albacete','CM'),'03':('Alicante/Alacant','VC'),'04':('Almería','AN'),'05':('Ávila','CL'), '06':('Badajoz','EX'),'07':('Illes Balears','IB'),'08':('Barcelona','CT'),'09':('Burgos','CL'),'10':('Cáceres','EX'),'11':('Cádiz','AN'), '12':('Castellón/Castelló','VC'),'13':('Ciudad Real','CM'),'14':('Córdoba','AN'),'15':('A Coruña','GA'),'16':('Cuenca','CM'),'17':('Girona','CT'), '18':('Granada','AN'),'19':('Guadalajara','CM'),'20':('Gipuzkoa','PV'),'21':('Huelva','AN'),'22':('Huesca','AR'),'23':('Jaén','AN'),'24':('León','CL'), '25':('Lleida','CT'),'26':('La Rioja','RI'),'27':('Lugo','GA'),'28':('Madrid','MD'),'29':('Málaga','AN'),'30':('Murcia','MC'),'31':('Navarra','NA'), '32':('Ourense','GA'),'33':('Asturias','AS'),'34':('Palencia','CL'),'35':('Las Palmas','CN'),'36':('Pontevedra','GA'),'37':('Salamanca','CL'), '38':('Santa Cruz de Tenerife','CN'),'39':('Cantabria','CB'),'40':('Segovia','CL'),'41':('Sevilla','AN'),'42':('Soria','CL'),'43':('Tarragona','CT'), '44':('Teruel','AR'),'45':('Toledo','CM'),'46':('Valencia/València','VC'),'47':('Valladolid','CL'),'48':('Bizkaia','PV'),'49':('Zamora','CL'), '50':('Zaragoza','AR'),'51':('Ceuta','CE'),'52':('Melilla','ML')} def norm(s): s = unicodedata.normalize('NFKD', s or '').encode('ascii', 'ignore').decode().upper() return re.sub(r'[^A-Z0-9]+', ' ', s).strip() # Nombres de provincia del BORME (Postgres borme.empresas.provincia) -> código INE BORME_PROV = {} for k, (n, _) in PROV.items(): for parte in [n] + n.split('/'): BORME_PROV[norm(parte)] = k BORME_PROV.update({norm('ARABA/ÁLAVA'): '01', 'ALAVA': '01', 'ARABA': '01', 'BALEARES': '07', 'ILLES BALEARS': '07', 'VIZCAYA': '48', 'GUIPUZCOA': '20', 'LA CORUNA': '15', 'CORUNA': '15', 'GERONA': '17', 'LERIDA': '25', 'ORENSE': '32', 'CASTELLON': '12', 'ALICANTE': '03', 'VALENCIA': '46', 'TENERIFE': '38', 'SANTA CRUZ DE TENERIFE': '38', 'LAS PALMAS': '35'}) # NUTS 2016 nivel 3 -> provincia INE (Canarias por islas; Baleares por islas) NUTS3 = {'ES111':'15','ES112':'27','ES113':'32','ES114':'36','ES120':'33','ES130':'39','ES211':'01','ES212':'20','ES213':'48','ES220':'31', 'ES230':'26','ES241':'22','ES242':'44','ES243':'50','ES300':'28','ES411':'05','ES412':'09','ES413':'24','ES414':'34','ES415':'37','ES416':'40', 'ES417':'42','ES418':'47','ES419':'49','ES421':'02','ES422':'13','ES423':'16','ES424':'19','ES425':'45','ES431':'06','ES432':'10','ES511':'08', 'ES512':'17','ES513':'25','ES514':'43','ES521':'03','ES522':'12','ES523':'46','ES531':'07','ES532':'07','ES533':'07','ES611':'04','ES612':'11', 'ES613':'14','ES614':'18','ES615':'21','ES616':'23','ES617':'29','ES618':'41','ES620':'30','ES630':'51','ES640':'52','ES703':'38','ES704':'35', 'ES705':'35','ES706':'38','ES707':'38','ES708':'35','ES709':'38'} # NUTS 2 de una sola provincia (sirven como provincia) NUTS2_UNA = {'ES12':'33','ES13':'39','ES22':'31','ES23':'26','ES30':'28','ES53':'07','ES62':'30','ES63':'51','ES64':'52'} # Cajones de oferta provincial s_{P,m} (cuota de la provincia del órgano en su mercado nacional), fijos BINS = [0.005, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32] def bin_s(s): for i, b in enumerate(BINS): if s < b: return i return len(BINS) Z95, Z998 = 1.959964, 3.090232 NMIN = 20 def percentil(v, q): s = sorted(v); n = len(s) if n == 0: return float('nan') h = (n - 1) * q; i = int(math.floor(h)); f = h - i return s[i] if i + 1 >= n else s[i] + f * (s[i + 1] - s[i]) def tau2(filas, winsor): """filas: (r, e, s) con n >= NMIN. Spiegelhalter 2005; winsor = 0.10 o None (sin winsorizar).""" zs = [(r - e) / s for r, e, s in filas if s > 0] I = len(zs) if I < 2: return 0.0, float('nan'), I if winsor: lo, hi = percentil(zs, winsor), percentil(zs, 1 - winsor); zs = [min(max(z, lo), hi) for z in zs] phi = sum(z * z for z in zs) / I w = [1 / (s * s) for r, e, s in filas if s > 0] sw = sum(w); sw2 = sum(a * a for a in w) t = (I * phi - (I - 1)) / (sw - sw2 / sw) if I * phi > I - 1 else 0.0 return max(t, 0.0), phi, I def posicion(n, zd): if n < NMIN: return 'muestra insuficiente' if zd > Z998: return 'por encima del 99,8 %' if zd > Z95: return 'por encima del 95 %' if zd >= -Z95: return 'dentro' if zd >= -Z998: return 'por debajo del 95 %' return 'por debajo del 99,8 %' def auc(score, y): pares = sorted(zip(score, y)); n1 = sum(y); n0 = len(y) - n1 if n1 == 0 or n0 == 0: return float('nan') i = 0; suma = 0.0 while i < len(pares): j = i while j < len(pares) and pares[j][0] == pares[i][0]: j += 1 suma += (i + 1 + j) / 2 * sum(1 for k in range(i, j) if pares[k][1] == 1); i = j return (suma - n1 * (n1 + 1) / 2) / (n1 * n0) def pois_ic(o): def cdf(k, mu): s = 0.0; t = math.exp(-mu) for i in range(k + 1): s += t; t *= mu / (i + 1) return s def bis(f, lo, hi): for _ in range(200): m = (lo + hi) / 2 if f(m): hi = m else: lo = m return (lo + hi) / 2 lo = 0.0 if o == 0 else bis(lambda mu: cdf(o - 1, mu) <= 0.975, 0, 10 * o + 10) return lo, bis(lambda mu: cdf(o, mu) <= 0.025, 0, 10 * o + 50) def or_woolf(a, b, c, d): if 0 in (a, b, c, d): a, b, c, d = a + .5, b + .5, c + .5, d + .5 o = a * d / (b * c); se = math.sqrt(1 / a + 1 / b + 1 / c + 1 / d) return o, o * math.exp(-1.96 * se), o * math.exp(1.96 * se) def municipios_ine(): """INE de 2019 (fichero 05 del Ministerio del Interior, el de FAM1): código PPMMM -> nombre.""" L = open('/et/familias/interno/datos/infoelectoral/2019/05041905.DAT', 'rb').read().decode('latin-1').splitlines() m = {} for l in L: if len(l) >= 118 and l[16:18] == '99': m[l[11:13] + l[13:16]] = l[18:118].strip() return m def variantes_muni(nombre): """Formas normalizadas de un nombre de municipio: entero, cada parte de un bilingüe, artículo pospuesto delante.""" out = set() for p in [nombre] + re.split(r'[/\-]', nombre): p = p.strip() if not p: continue out.add(norm(p)) m = re.match(r"^(.*),\s*(EL|LA|LOS|LAS|L'|LES|ELS|O|A|OS|AS|SA|ES|SES)$", p, re.I) if m: art = m.group(2) out.add(norm(art + ' ' + m.group(1))); out.add(norm(m.group(1))) return {v for v in out if v}