using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using Keps.WinForms.Infrastructure; using Keps.WinForms.Models; namespace Keps.WinForms.Services { /// /// 표본 추출(실 데이터 기준) 관련 로직을 제공하는 서비스입니다. /// public sealed class SamplingService { private sealed class CandidateMeta { public string Name { get; set; } public string VoteKey { get; set; } public string RatioKey { get; set; } } private readonly SqlConnectionFactory _connectionFactory; /// /// 표본 추출 서비스 인스턴스를 생성합니다. /// /// DB 연결을 제공하는 팩토리. public SamplingService(SqlConnectionFactory connectionFactory) { _connectionFactory = connectionFactory; } /// /// 실 추출 화면 구성을 위한 초기 컨텍스트를 로드합니다. /// /// 선거명 또는 연월. /// 시도명. /// 군집(층) 최대 개수. /// 자동/수동 행과 정렬 옵션을 포함한 컨텍스트. public RealScenarioContext LoadRealScenario(string electionName, string areaName, int clusterMax) { List rows = new List(); using (SqlConnection connection = _connectionFactory.Open()) { Dictionary ratioMap = new Dictionary(); using (SqlCommand ratioCommand = new SqlCommand(LegacySqlCatalog.RealClusterRatio, connection)) { ratioCommand.Parameters.AddWithValue("@electionName", electionName); ratioCommand.Parameters.AddWithValue("@areaName", areaName); ratioCommand.Parameters.AddWithValue("@clusterMax", clusterMax); using (SqlDataReader reader = ratioCommand.ExecuteReader()) { while (reader.Read()) { ratioMap[Convert.ToInt32(reader["군집"])] = Convert.ToDecimal(reader["비율"]); } } } for (int clusterNo = 1; clusterNo <= clusterMax; clusterNo++) { string countSql = string.Format(LegacySqlCatalog.RealClusterCountTemplate, clusterMax); int count = 0; using (SqlCommand countCommand = new SqlCommand(countSql, connection)) { countCommand.Parameters.AddWithValue("@electionName", electionName); countCommand.Parameters.AddWithValue("@areaName", areaName); countCommand.Parameters.AddWithValue("@clusterNo", clusterNo); object scalar = countCommand.ExecuteScalar(); count = scalar == null || scalar == DBNull.Value ? 0 : Convert.ToInt32(scalar); } decimal ratio = ratioMap.ContainsKey(clusterNo) ? ratioMap[clusterNo] : 0m; rows.Add(new ClusterSummaryRow { ClusterNo = clusterNo, ClusterLabel = clusterNo + " 층", PollingPlaceCount = count, Ratio = ratio, SampleCount = 0 }); } } LookupService lookupService = new LookupService(_connectionFactory); return new RealScenarioContext { AutoRows = CloneRows(rows), ManualRows = CloneRows(rows), SortOptions = lookupService.LoadCandidateOptions(electionName) }; } /// /// 군집별 비율에 따라 총 표본 수를 자동 배분합니다(소수점 버림 후 잔여는 앞쪽부터 1개씩 할당). /// /// 군집 비율 및 개수 정보를 담은 행 목록. /// 전체 표본 수. /// 배분된 표본 수가 채워진 새 목록. public List AllocateAutoSampleCounts(List rows, int totalSampleCount) { List result = CloneRows(rows); if (rows == null || rows.Count == 0 || totalSampleCount <= 0) { return result; } int assigned = 0; List> sampleTu = new List>(); for (int i = 0; i < result.Count; i++) { decimal exact = totalSampleCount * result[i].Ratio; int floor = (int)Math.Floor(exact); result[i].SampleCount = floor; assigned += floor; sampleTu.Add(new Tuple(result[i], exact - floor, i + 1)); } int remaining = totalSampleCount - assigned; /*********************************기존 버그 내용*************************************/ /* if (remaining > 0) { if (sampleTu.Count >= 2 && sampleTu[0].Item2 < sampleTu[1].Item2) { Tuple temp = sampleTu[0]; sampleTu[0] = sampleTu[1]; sampleTu[1] = temp; } for (int i = 0; i < sampleTu.Count && remaining > 0; i++) { sampleTu[i].Item1.SampleCount += 1; remaining--; } } */ /*********************************기존 버그 내용************************************* / /*********************************정상 구동*************************************/ if (remaining > 0) { var ranked = sampleTu .OrderByDescending(x => x.Item2) // 소수부 큰 순 .ThenBy(x => x.Item1.ClusterNo) // 동률이면 군집번호 작은 순 .ToList(); for (int i = 0; i < ranked.Count && remaining > 0; i++) { ranked[i].Item1.SampleCount += 1; remaining--; } } /*********************************정상 구동*************************************/ return result; } /// /// 실 데이터에서 군집별 표본을 등간격으로 추출하고, 관련 산출물(보정, 검증, 모집단 목록)을 생성합니다. /// /// 선거명 또는 연월. /// 시도명. /// 군집(층) 최대 개수. /// 정렬 기준 키(예: "투표인수" 또는 cand_ratio_*). /// 정렬 기준 표시 이름. /// 내림차순 여부. /// 군집별 배분 정보(표본 수 포함). /// 등간격 오프셋(양수/음수). /// 오프셋 설명 문자열. /// 자동 배분으로 생성되었는지 여부. /// 실 추출 결과 DTO. public RealExtractionResult RunRealExtraction( string electionName, string areaName, int clusterMax, string sortKey, string sortDisplayName, bool descending, List workingRows, int signedOffset, string offsetDescription, bool isAutoAllocation) { List allRows = LoadRealPollingRows(electionName, areaName, clusterMax); List candidateMeta = LoadCandidateMeta(electionName, allRows); List extractedRows = new List(); List populationRows = new List(); List extractedSourceRows = new List(); foreach (ClusterSummaryRow workingRow in workingRows.OrderBy(x => x.ClusterNo)) { List clusterRows = allRows.Where(x => x.ClusterValue == workingRow.ClusterNo).ToList(); clusterRows = descending ? clusterRows.OrderByDescending(x => x.GetSortValue(sortKey)).ThenBy(x => x.EupMyeonDong).ThenBy(x => GetPollingPlaceSortValue(x.PollingPlaceNo)).ThenBy(x => x.PollingPlaceNo).ToList() : clusterRows.OrderBy(x => x.GetSortValue(sortKey)).ThenBy(x => x.EupMyeonDong).ThenBy(x => GetPollingPlaceSortValue(x.PollingPlaceNo)).ThenBy(x => x.PollingPlaceNo).ToList(); int interval; int startPosition; List extractIds = SelectLegacyExtractIds(clusterRows.Count, workingRow.SampleCount, signedOffset, out interval, out startPosition); HashSet selectedPositions = new HashSet(extractIds); for (int i = 0; i < clusterRows.Count; i++) { int originalOrder = i + 1; PollingPlaceRecord row = clusterRows[i]; populationRows.Add(CreateExtractionRow(row, workingRow.ClusterNo, originalOrder, originalOrder, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), selectedPositions.Contains(originalOrder), selectedPositions.Contains(originalOrder))); } for (int i = 0; i < extractIds.Count; i++) { int extractId = extractIds[i]; if (extractId < 1 || extractId > clusterRows.Count) { continue; } PollingPlaceRecord row = clusterRows[extractId - 1]; extractedSourceRows.Add(row); extractedRows.Add(CreateExtractionRow(row, workingRow.ClusterNo, i + 1, extractId, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), true, true)); } } List candidateNames = candidateMeta.Select(x => x.Name).ToList(); List candidateVoteKeys = candidateMeta.Select(x => x.VoteKey).ToList(); List candidateRatioKeys = candidateMeta.Select(x => x.RatioKey).ToList(); return new RealExtractionResult { CandidateNames = candidateNames, CandidateVoteKeys = candidateVoteKeys, CandidateRatioKeys = candidateRatioKeys, ExtractedRows = extractedRows.OrderBy(x => x.ClusterNo).ThenBy(x => x.ClusterOrder).ToList(), PopulationRows = populationRows.OrderBy(x => x.ClusterNo).ThenBy(x => x.OriginalOrder).ToList(), AdjustmentRows = BuildAdjustmentRows(extractedRows), VerificationRows = BuildVerificationRows(allRows, extractedSourceRows, workingRows, candidateMeta), ClusterMax = clusterMax, TotalSampleCount = workingRows.Sum(x => x.SampleCount), IsAutoAllocation = isAutoAllocation, SortDisplayName = sortDisplayName, SortDescending = descending, OffsetDescription = offsetDescription }; } /// /// 실 데이터 테이블에서 투표구 행들을 조회하여 도메인 모델로 변환합니다. /// /// 선거명 또는 연월. /// 시도명. /// 군집(층) 최대 개수(동적 군집 컬럼 선택에 사용). /// 조회된 투표구 원시 행 목록. private List LoadRealPollingRows(string electionName, string areaName, int clusterMax) { List result = new List(); string sql = string.Format(LegacySqlCatalog.RealPollingRowsTemplate, clusterMax); using (SqlConnection connection = _connectionFactory.Open()) using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@electionName", electionName); command.Parameters.AddWithValue("@areaName", areaName); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { PollingPlaceRecord row = new PollingPlaceRecord(); row.ElectionName = Convert.ToString(reader["선거명"]); row.AreaName = Convert.ToString(reader["시도명"]); row.DistrictName = Convert.ToString(reader["선거구명"]); row.SiGunGu = Convert.ToString(reader["시군구"]); row.EupMyeonDong = Convert.ToString(reader["읍면동"]); row.PollingPlaceNo = Convert.ToString(reader["투표구명"]); row.PollingPlaceName = row.EupMyeonDong + " " + row.PollingPlaceNo + "투"; row.ClusterValue = reader["선택군집"] == DBNull.Value ? 0 : Convert.ToInt32(reader["선택군집"]); row.EligibleVoterCount = reader["t_유권자수"] == DBNull.Value ? 0 : Convert.ToInt32(reader["t_유권자수"]); row.ElectorateCount = reader["선거인수"] == DBNull.Value ? 0 : Convert.ToInt32(reader["선거인수"]); row.VoteCount = reader["투표인수"] == DBNull.Value ? 0 : Convert.ToInt32(reader["투표인수"]); row.TotalCandidateVoteCount = reader["후보별득표수계"] == DBNull.Value ? 0 : Convert.ToInt32(reader["후보별득표수계"]); row.DuplicateFlag = Convert.ToString(reader["투표소_중복여부"]); row.BuildingName = Convert.ToString(reader["건물명"]); row.Address1 = Convert.ToString(reader["주소1"]); row.AreaDetail = Convert.ToString(reader["관할구역"]); row.Note = Convert.ToString(reader["비고_기타"]); row.CandidateVotes = JsonHelper.ParseDecimalMap(Convert.ToString(reader["cand"])); row.CandidateRatios = JsonHelper.ParseDecimalMap(Convert.ToString(reader["cand_ratio"])); result.Add(row); } } } return result; } /// /// 후보자 메타 정보(표시명, 득표/비율 키)를 DB 또는 데이터에서 유추하여 생성합니다. /// /// 선거명 또는 연월. /// 후보자 득표/비율 정보가 포함될 수 있는 모집단 행 목록. /// 정렬용 후보 메타 정보 목록. private List LoadCandidateMeta(string electionName, List rows) { List result = new List(); using (SqlConnection connection = _connectionFactory.Open()) using (SqlCommand command = new SqlCommand(LegacySqlCatalog.RealCandidateNames, connection)) { command.Parameters.AddWithValue("@electionName", electionName); try { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string candNo = Convert.ToString(reader["cand_no"]); string candName = Convert.ToString(reader["cand_name"]); if (string.IsNullOrWhiteSpace(candNo)) { continue; } int candNoValue; if (!int.TryParse(candNo, out candNoValue)) { continue; } result.Add(new CandidateMeta { Name = string.IsNullOrWhiteSpace(candName) ? "cand_" + candNoValue : candName, VoteKey = "cand_" + candNoValue, RatioKey = "cand_ratio_" + candNoValue }); } } } catch { } } result = result .GroupBy(x => x.VoteKey) .Select(x => x.First()) .OrderBy(x => ExtractCandidateKeyNumber(x.VoteKey)) .ToList(); if (result.Count == 0) { List keys = rows .Where(x => x.CandidateVotes != null) .SelectMany(x => x.CandidateVotes.Keys) .Distinct() .OrderBy(ExtractCandidateKeyNumber) .ToList(); foreach (string key in keys) { result.Add(new CandidateMeta { Name = key, VoteKey = key, RatioKey = key.Replace("cand_", "cand_ratio_") }); } } return result.Take(3).ToList(); } /// /// 투표구 원시 행을 보고서/엑셀 출력용 추출 행 DTO로 변환합니다. /// /// 원본 투표구 행. /// 군집 번호. /// 군집 내 추출 순번. /// 정렬 모집단 상의 원래 순번. /// 등간격 간격. /// 등간격 시작 위치. /// 오프셋 설명. /// 정렬 기준 값. /// 자동 추출 여부. /// 보정 반영 여부. /// 변환된 추출 행. private static ExtractionRow CreateExtractionRow(PollingPlaceRecord row, int clusterNo, int clusterOrder, int originalOrder, int interval, int startPosition, string offsetDescription, decimal sortValue, bool isAutoSelected, bool isAdjustedSelected) { return new ExtractionRow { ClusterNo = clusterNo, ClusterOrder = clusterOrder, OriginalOrder = originalOrder, StartPosition = startPosition, Interval = interval, OffsetDescription = offsetDescription, AreaName = row.AreaName, DistrictName = row.DistrictName, SiGunGu = row.SiGunGu, EupMyeonDong = row.EupMyeonDong, PollingPlaceName = row.PollingPlaceName, PollingPlaceNo = row.PollingPlaceNo, EligibleVoterCount = row.EligibleVoterCount, ElectorateCount = row.ElectorateCount, VoteCount = row.VoteCount, TotalCandidateVoteCount = row.TotalCandidateVoteCount, DuplicateFlag = row.DuplicateFlag, BuildingName = row.BuildingName, Address1 = row.Address1, Note = row.Note, SortValue = sortValue, IsAutoSelected = isAutoSelected, IsAdjustedSelected = isAdjustedSelected, CandidateVotes = row.CandidateVotes == null ? new Dictionary() : new Dictionary(row.CandidateVotes), CandidateRatios = row.CandidateRatios == null ? new Dictionary() : new Dictionary(row.CandidateRatios) }; } /// /// 레거시 규칙에 맞춰 등간격 추출 ID 목록을 계산합니다. /// /// 모집단 크기(정렬된 투표구 수). /// 추출할 표본 수. /// 시작 위치 보정값(양수면 뒤로, 음수면 앞으로 이동). /// 계산된 등간격 간격(출력). /// 계산된 시작 위치(출력). /// 1부터 시작하는 추출 대상 인덱스 목록. private static List SelectLegacyExtractIds(int totalCount, int sampleCount, int signedOffset, out int interval, out int startPosition) { List extractIds = new List(); interval = 1; startPosition = 1; if (totalCount <= 0 || sampleCount <= 0) { return extractIds; } if (sampleCount >= totalCount) { for (int i = 1; i <= totalCount; i++) { extractIds.Add(i); } return extractIds; } interval = (int)Math.Floor((decimal)totalCount / sampleCount); if (interval <= 0) { interval = 1; } int start = interval / 2; int endPoint = start + (interval * (sampleCount - 1)); int x1 = totalCount - endPoint; int x2 = start - 1; start = Convert.ToInt32(Math.Round((x1 + x2) / 2d, 0, MidpointRounding.AwayFromZero)); start += signedOffset; if (start <= 0) { start = 1; } if (start > totalCount) { start = totalCount; } startPosition = start; int current = start; while (current <= totalCount && extractIds.Count < sampleCount) { extractIds.Add(current); current += interval; } return extractIds; } /// /// 추출된 표본 행들에서 보정 내역(원래 순번/보정 순번)을 생성합니다. /// /// 최종 추출 표본 행 목록. /// 보정 내역 행 목록. private static List BuildAdjustmentRows(List extractedRows) { return extractedRows .OrderBy(x => x.ClusterNo) .ThenBy(x => x.OriginalOrder) .Select(x => new AdjustmentRow { ClusterNo = x.ClusterNo, ExtractId = x.OriginalOrder, AdjustId = null }) .ToList(); } /// /// 추출 표본과 모집단을 비교하여 요약 검증 지표(가중 오차, 군집 내 오차 등)를 계산합니다. /// /// 모집단(전체) 원시 행 목록. /// 추출된 원시 행 목록. /// 군집별 비율 및 표본 수 정보. /// 후보자 메타 정보(표시명/키). /// 검증 요약 행 목록. private static List BuildVerificationRows( List populationRows, List extractedRows, List allocationRows, List candidateMeta) { List result = new List(); while (candidateMeta.Count < 3) { candidateMeta.Add(new CandidateMeta { Name = "후보" + (candidateMeta.Count + 1), VoteKey = "cand_" + (candidateMeta.Count + 1), RatioKey = "cand_ratio_" + (candidateMeta.Count + 1) }); } decimal totalActual1 = Round1(ComputeCandidateRatioExact(populationRows, candidateMeta[0].VoteKey)); decimal totalActual2 = Round1(ComputeCandidateRatioExact(populationRows, candidateMeta[1].VoteKey)); decimal totalActual3 = Round1(ComputeCandidateRatioExact(populationRows, candidateMeta[2].VoteKey)); decimal totalExtractedWeighted1 = 0m; decimal totalExtractedWeighted2 = 0m; decimal totalExtractedWeighted3 = 0m; foreach (ClusterSummaryRow allocation in allocationRows.OrderBy(x => x.ClusterNo)) { List clusterPopulation = populationRows.Where(x => x.ClusterValue == allocation.ClusterNo).ToList(); List clusterExtracted = extractedRows.Where(x => x.ClusterValue == allocation.ClusterNo).ToList(); decimal clusterExtractedSource1 = ComputeCandidateRatioExact(clusterExtracted, candidateMeta[0].VoteKey); decimal clusterExtractedSource2 = ComputeCandidateRatioExact(clusterExtracted, candidateMeta[1].VoteKey); decimal clusterExtractedSource3 = ComputeCandidateRatioExact(clusterExtracted, candidateMeta[2].VoteKey); decimal clusterExtracted1 = Round1(clusterExtractedSource1); decimal clusterExtracted2 = Round1(clusterExtractedSource2); decimal clusterExtracted3 = Round1(clusterExtractedSource3); decimal clusterActual1 = Round1(Round2(ComputeCandidateRatioExact(clusterPopulation, candidateMeta[0].VoteKey))); decimal clusterActual2 = Round1(Round2(ComputeCandidateRatioExact(clusterPopulation, candidateMeta[1].VoteKey))); decimal clusterActual3 = Round1(Round2(ComputeCandidateRatioExact(clusterPopulation, candidateMeta[2].VoteKey))); totalExtractedWeighted1 += allocation.Ratio * clusterExtractedSource1; totalExtractedWeighted2 += allocation.Ratio * clusterExtractedSource2; totalExtractedWeighted3 += allocation.Ratio * clusterExtractedSource3; decimal overallError1 = Round1(clusterExtracted1 - totalActual1); decimal overallError2 = Round1(clusterExtracted2 - totalActual2); decimal overallError3 = Round1(clusterExtracted3 - totalActual3); decimal inClusterError1 = Round1(clusterExtracted1 - clusterActual1); decimal inClusterError2 = Round1(clusterExtracted2 - clusterActual2); decimal inClusterError3 = Round1(clusterExtracted3 - clusterActual3); result.Add(new VerificationSummaryRow { RowLabel = allocation.ClusterNo + " 층", ClusterRatio = allocation.Ratio, SampleCount = allocation.SampleCount, Extracted1 = clusterExtracted1, Extracted2 = clusterExtracted2, Extracted3 = clusterExtracted3, Actual1 = clusterActual1, Actual2 = clusterActual2, Actual3 = clusterActual3, WeightedError1 = overallError1, WeightedError2 = overallError2, WeightedError3 = overallError3, WeightedErrorSum = Round1(Math.Abs(overallError1) + Math.Abs(overallError2) + Math.Abs(overallError3)), InClusterError1 = inClusterError1, InClusterError2 = inClusterError2, InClusterError3 = inClusterError3, InClusterErrorSum = Round1(Math.Abs(inClusterError1) + Math.Abs(inClusterError2) + Math.Abs(inClusterError3)) }); } decimal totalExtracted1 = Round1(totalExtractedWeighted1); decimal totalExtracted2 = Round1(totalExtractedWeighted2); decimal totalExtracted3 = Round1(totalExtractedWeighted3); decimal totalOverallError1 = Round1(totalExtracted1 - totalActual1); decimal totalOverallError2 = Round1(totalExtracted2 - totalActual2); decimal totalOverallError3 = Round1(totalExtracted3 - totalActual3); result.Insert(0, new VerificationSummaryRow { RowLabel = "전체", ClusterRatio = 1m, SampleCount = allocationRows.Sum(x => x.SampleCount), Extracted1 = totalExtracted1, Extracted2 = totalExtracted2, Extracted3 = totalExtracted3, Actual1 = totalActual1, Actual2 = totalActual2, Actual3 = totalActual3, WeightedError1 = totalOverallError1, WeightedError2 = totalOverallError2, WeightedError3 = totalOverallError3, WeightedErrorSum = Round1(Math.Abs(totalOverallError1) + Math.Abs(totalOverallError2) + Math.Abs(totalOverallError3)), InClusterError1 = 0m, InClusterError2 = 0m, InClusterError3 = 0m, InClusterErrorSum = 0m }); return result; } /// /// 지정한 후보 득표수 키에 대한 실제 비율(%)을 계산합니다. /// /// 대상 행 목록. /// 득표수 조회 키(예: cand_1). /// 득표율(%), 분모가 0이면 0. private static decimal ComputeCandidateRatioExact(List rows, string voteKey) { if (rows == null || rows.Count == 0 || string.IsNullOrWhiteSpace(voteKey)) { return 0m; } decimal total = rows.Sum(x => (decimal)x.TotalCandidateVoteCount); if (total <= 0m) { return 0m; } decimal vote = 0m; foreach (PollingPlaceRecord row in rows) { if (row.CandidateVotes != null && row.CandidateVotes.ContainsKey(voteKey)) { vote += row.CandidateVotes[voteKey]; } } return (vote / total) * 100m; } /// /// 소수점 둘째 자리에서 반올림(away from zero)합니다. /// /// 반올림할 값. /// 소수 둘째 자리 반올림 값. private static decimal Round2(decimal value) { return Math.Round(value, 2, MidpointRounding.AwayFromZero); } /// /// 투표구 번호 문자열에서 정렬용 숫자 값을 추출합니다(예: "제1투" → 1). /// /// 투표구 번호 문자열. /// 정렬용 정수 값. 추출 실패 시 매우 큰 값으로 취급합니다. private static int GetPollingPlaceSortValue(string pollingPlaceNo) { int value; return int.TryParse(pollingPlaceNo, out value) ? value : int.MaxValue; } /// /// 후보 득표 키에서 번호를 추출합니다(예: "cand_3" → 3). 실패 시 큰 값 반환. /// /// 후보 득표 키. /// 숫자 값. 파싱 실패 시 int.MaxValue. private static int ExtractCandidateKeyNumber(string key) { if (string.IsNullOrWhiteSpace(key)) { return int.MaxValue; } string text = new string(key.Where(char.IsDigit).ToArray()); int value; return int.TryParse(text, out value) ? value : int.MaxValue; } /// /// 소수점 첫째 자리에서 반올림(away from zero)합니다. /// /// 반올림할 값. /// 소수 첫째 자리 반올림 값. private static decimal Round1(decimal value) { return Math.Round(value, 1, MidpointRounding.AwayFromZero); } /// /// 군집 요약 행 목록을 얕은 복사하여 변경 부작용을 방지합니다. /// /// 원본 행 목록. /// 복제된 새 목록. private static List CloneRows(List rows) { return rows.Select(x => new ClusterSummaryRow { ClusterNo = x.ClusterNo, ClusterLabel = x.ClusterLabel, PollingPlaceCount = x.PollingPlaceCount, Ratio = x.Ratio, SampleCount = x.SampleCount }).ToList(); } } }