@operato/twin-kernel 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ import { type WorkCalendarEntry } from './contract.ts';
2
+ import type { OperationDef } from './domain-definition.ts';
3
+ /** 제약이 걸린 축 — 무엇을 늘려야 하는지가 여기서 갈린다. */
4
+ export type CapacityAxis = 'equipment' | 'personnel' | 'asset' | 'location';
5
+ export interface CapacityRequirement {
6
+ axis: CapacityAxis;
7
+ /** 요구 등급/종류(설비 kind · 인원 class · 자산 class · 자리 type). */
8
+ className: string;
9
+ /** 작업 한 건이 동시에 잡는 수. */
10
+ quantity: number;
11
+ /** 실제로 있는 수. */
12
+ available: number;
13
+ /** 가동률 — 설비만 mtbf/mttr 에서 나온다. 나머지는 1(모델 없음). */
14
+ availability: number;
15
+ /** 이 요구만 놓고 봤을 때 시간당 낼 수 있는 대수. */
16
+ perHour: number;
17
+ }
18
+ export interface OperationCapacity {
19
+ operation: string;
20
+ cycleHours: number;
21
+ /** 이 공정이 시간당 낼 수 있는 대수 = 요구들 중 가장 낮은 것. */
22
+ perHour: number;
23
+ /** 하류 수율까지 물린 소요량. */
24
+ requiredPerHour: number;
25
+ ok: boolean;
26
+ /** 이 공정을 묶고 있는 요구(가장 낮은 것). 요구가 하나도 없으면 없다. */
27
+ constraint?: CapacityRequirement;
28
+ requirements: CapacityRequirement[];
29
+ }
30
+ export interface CapacityAnalysis {
31
+ /** 근무 캘린더를 실제로 샘플링해서 얻는다 — 규칙을 다시 적지 않는다. */
32
+ workingHoursPerWeek: number;
33
+ workingDaysPerWeek: number;
34
+ demandPerHour: number;
35
+ operations: OperationCapacity[];
36
+ /** 라인 전체를 묶고 있는 공정과 축. 공정이 없으면 없다. */
37
+ bottleneck?: {
38
+ operation: string;
39
+ axis?: CapacityAxis;
40
+ className?: string;
41
+ };
42
+ /** 이 공장의 천장(하루). */
43
+ maxUnitsPerDay: number;
44
+ ok: boolean;
45
+ }
46
+ export interface CapacityInput {
47
+ operations: readonly OperationDef[];
48
+ /** 라우트 순서 — 수율을 거슬러 올릴 때 쓴다. 없으면 `operations` 순서를 쓴다. */
49
+ route?: readonly string[];
50
+ equipment?: readonly {
51
+ kind: string;
52
+ mtbfMs?: number;
53
+ mttrMs?: number;
54
+ }[];
55
+ persons?: readonly {
56
+ personnelClassIds?: readonly string[];
57
+ }[];
58
+ assets?: readonly {
59
+ assetClassIds?: readonly string[];
60
+ }[];
61
+ locations?: readonly {
62
+ type?: string;
63
+ capacity?: number;
64
+ }[];
65
+ calendar?: readonly WorkCalendarEntry[];
66
+ /**
67
+ * 가용 시간을 샘플링할 기준 주의 시작(월요일 00:00, ms).
68
+ *
69
+ * **공휴일이 없는 평상주를 골라야 한다** — 공휴일은 연간 가용량을 따로 깎지, 이 공장의 평상시
70
+ * 천장을 정하지 않는다. 기본값을 두지 않는 이유: 커널이 임의의 주를 고르면 그 주에 공휴일이
71
+ * 들어 있을 때 천장이 조용히 낮아진다.
72
+ */
73
+ sampleWeekStartMs: number;
74
+ utcOffsetMinutes?: number;
75
+ /** 하루 몇 대를 낼 것인가 — 선언된 수요. */
76
+ unitsPerDay: number;
77
+ }
78
+ /** ISO 8601 기간 → 시간. 명세가 쓰는 표기 그대로 읽는다(`PT1H40M`). */
79
+ export declare function isoDurationHours(iso: string | undefined): number;
80
+ /**
81
+ * 근무 캘린더에서 **가용 시간과 조업일**을 읽는다 — 1분 간격 샘플링.
82
+ *
83
+ * 교대·휴게·비근무 규칙을 여기 다시 적지 않는다. 규칙은 `inWorkCalendarAt` 한 곳에만 있고, 이 함수는
84
+ * 그것에 묻기만 한다. 두 벌이 되면 달력을 고칠 때 한쪽만 고쳐져 갈라진다.
85
+ *
86
+ * 캘린더가 없으면 **종일 가동**으로 본다(7일 × 24h) — 제약이 없는 것이 아니라 **선언되지 않은** 것이고,
87
+ * 선언이 없으면 커널은 멈출 이유를 모른다.
88
+ */
89
+ export declare function workingTimeOfWeek(calendar: readonly WorkCalendarEntry[] | undefined, weekStartMs: number, utcOffsetMinutes?: number): {
90
+ hoursPerWeek: number;
91
+ daysPerWeek: number;
92
+ };
93
+ /**
94
+ * 이 공장이 선언된 물량을 낼 수 있는가 — 공정마다, 자원 축마다.
95
+ *
96
+ * 순수 함수다. 커널 상태를 읽지 않고 넘겨받은 것만 본다 — 그래야 "이 설비를 두 대 더 놓으면?" 을
97
+ * 굴려 보지 않고 물을 수 있다(what-if 의 가장 싼 형태).
98
+ */
99
+ export declare function analyzeCapacity(input: CapacityInput): CapacityAnalysis;
@@ -0,0 +1,172 @@
1
+ /*
2
+ * 용량 분석 — **굴려 보기 전에 "이 공장이 그 물량을 낼 수 있는가" 에 답한다.**
3
+ *
4
+ * ── 왜 커널인가 ──────────────────────────────────────────────────────────────
5
+ * 이 계산을 처음에는 레퍼런스 마스터 옆에서 손으로 했다(Rosarito). 그러다 두 가지를 알았다.
6
+ *
7
+ * 첫째, **입력이 전부 커널에 있다.** 공정 명세(소요·셋업·수율)·설비와 그 신뢰도·인원·물리자산·자리·
8
+ * 근무 캘린더. 바깥에서 계산하면 그 값을 옮겨 적게 되고, 한쪽만 고치는 순간 "충분하다" 가 조용히
9
+ * 거짓이 된다.
10
+ *
11
+ * 둘째, **손계산은 설비만 셌다.** 표준 공정 명세는 네 축으로 자원을 요구한다(설비·인원·물리자산·자재)
12
+ * — 그리고 현장에서 가장 자주 모자라는 것은 사람이다. 설비만 세는 계산은 "용접 자격자가 2명뿐이라
13
+ * 로봇 6대가 논다" 를 구조적으로 못 본다. 네 축을 다 보는 자리는 커널뿐이다.
14
+ *
15
+ * ── 이것이 시뮬레이션과 다른 점 ─────────────────────────────────────────────
16
+ * 시뮬레이션은 **굴려 봐야** 답이 나오고, 변동·고장·줄서기가 섞인 결과를 준다. 이 계산은 **정상상태
17
+ * 상한**이다 — 모든 것이 계획대로 흘렀을 때의 천장. 둘은 서로를 대체하지 않는다:
18
+ * - 상한이 수요보다 낮으면 **시뮬레이션을 돌릴 필요가 없다.** 무슨 짓을 해도 못 낸다.
19
+ * - 상한이 충분한데 시뮬레이션이 못 내면 그것은 **흐름의 문제**다(줄서기·배치·변동).
20
+ *
21
+ * 그래서 이 계산은 진단이 아니라 **분류**다. 어느 쪽 문제인지부터 갈라 준다.
22
+ *
23
+ * ── 재지 않는 것 ─────────────────────────────────────────────────────────────
24
+ * 자재는 여기서 제약으로 세지 않는다. 자재는 **보충되는 것**이라 대수처럼 고정 공급이 아니고,
25
+ * 부족은 조달 문제이지 용량 문제가 아니다(자재 부족은 `work-backlog` 가 흐름에서 잡는다).
26
+ * 인원·자산에는 신뢰도 모델이 없다 — 가동률 1로 본다(설비만 mtbf/mttr 를 갖는다).
27
+ */
28
+ import { inWorkCalendarAt } from "./contract.js";
29
+ /** ISO 8601 기간 → 시간. 명세가 쓰는 표기 그대로 읽는다(`PT1H40M`). */
30
+ export function isoDurationHours(iso) {
31
+ if (!iso)
32
+ return 0;
33
+ const m = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?)?$/.exec(iso);
34
+ if (!m)
35
+ throw new Error(`기간 표기를 읽을 수 없다: ${iso}`);
36
+ return Number(m[1] ?? 0) * 24 + Number(m[2] ?? 0) + Number(m[3] ?? 0) / 60 + Number(m[4] ?? 0) / 3600;
37
+ }
38
+ function paramOf(op, id) {
39
+ return op.parameters?.find(p => p.id === id)?.value;
40
+ }
41
+ /**
42
+ * 근무 캘린더에서 **가용 시간과 조업일**을 읽는다 — 1분 간격 샘플링.
43
+ *
44
+ * 교대·휴게·비근무 규칙을 여기 다시 적지 않는다. 규칙은 `inWorkCalendarAt` 한 곳에만 있고, 이 함수는
45
+ * 그것에 묻기만 한다. 두 벌이 되면 달력을 고칠 때 한쪽만 고쳐져 갈라진다.
46
+ *
47
+ * 캘린더가 없으면 **종일 가동**으로 본다(7일 × 24h) — 제약이 없는 것이 아니라 **선언되지 않은** 것이고,
48
+ * 선언이 없으면 커널은 멈출 이유를 모른다.
49
+ */
50
+ export function workingTimeOfWeek(calendar, weekStartMs, utcOffsetMinutes) {
51
+ if (!calendar?.length)
52
+ return { hoursPerWeek: 7 * 24, daysPerWeek: 7 };
53
+ let minutes = 0;
54
+ const touched = new Set();
55
+ for (let m = 0; m < 7 * 24 * 60; m++) {
56
+ if (!inWorkCalendarAt(calendar, weekStartMs + m * 60_000, utcOffsetMinutes))
57
+ continue;
58
+ minutes++;
59
+ touched.add(Math.floor((m + (utcOffsetMinutes ?? 0)) / (24 * 60)));
60
+ }
61
+ /*
62
+ * 조업일은 **선언이 말하는 것**이지 타임라인이 번진 자국이 아니다.
63
+ *
64
+ * 야간 교대는 자정을 넘는다 — 금요일 밤에 시작한 교대는 토요일 새벽에 끝난다. 샘플링한 분을
65
+ * 날짜로 세면 월~금 3교대가 **6일**로 나오고, 그러면 주간 수요가 20% 부풀어 필요 없는 설비를
66
+ * 사라고 답한다. 교대는 "월~금에 **시작한다**" 고 선언돼 있고(`daysOfWeek`), 그것이 조업일이다.
67
+ *
68
+ * 요일 선언이 아예 없는 달력(절대 구간만 쓰는 경우)에서는 셀 근거가 없으므로 번진 자국을 쓴다.
69
+ */
70
+ const declared = new Set();
71
+ for (const e of calendar)
72
+ if (e.entryType !== 'non-working')
73
+ for (const d of e.daysOfWeek ?? [])
74
+ declared.add(d);
75
+ return { hoursPerWeek: minutes / 60, daysPerWeek: declared.size || touched.size };
76
+ }
77
+ function availabilityOf(records) {
78
+ /* 신뢰도를 선언하지 않은 설비는 고장 없음이다(계약의 규칙) — 1 로 센다. */
79
+ const ratios = records.map(r => (r.mtbfMs && r.mttrMs ? r.mtbfMs / (r.mtbfMs + r.mttrMs) : 1));
80
+ return ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : 1;
81
+ }
82
+ /**
83
+ * 이 공장이 선언된 물량을 낼 수 있는가 — 공정마다, 자원 축마다.
84
+ *
85
+ * 순수 함수다. 커널 상태를 읽지 않고 넘겨받은 것만 본다 — 그래야 "이 설비를 두 대 더 놓으면?" 을
86
+ * 굴려 보지 않고 물을 수 있다(what-if 의 가장 싼 형태).
87
+ */
88
+ export function analyzeCapacity(input) {
89
+ const { hoursPerWeek, daysPerWeek } = workingTimeOfWeek(input.calendar, input.sampleWeekStartMs, input.utcOffsetMinutes);
90
+ /*
91
+ * 수요는 **가동 시간당**이다. 하루 50대는 쉬는 시간에는 안 나오므로 168시간으로 나누면 안 된다 —
92
+ * 그렇게 나누면 필요한 대수가 실제보다 적게 나오고, 공장은 매주 조금씩 밀린다.
93
+ */
94
+ const demandPerHour = hoursPerWeek > 0 ? (input.unitsPerDay * daysPerWeek) / hoursPerWeek : 0;
95
+ /* 축별 공급 — 등급 이름으로 센다. 사람은 자격을 여럿 가질 수 있어 등급 간 합이 인원수를 넘는다
96
+ (같은 사람이 두 줄에 선다). 동시에 두 공정을 하지는 못하므로 이 계산은 **낙관적**이다. */
97
+ const equipmentByKind = new Map();
98
+ for (const e of input.equipment ?? []) {
99
+ const list = equipmentByKind.get(e.kind) ?? [];
100
+ list.push(e);
101
+ equipmentByKind.set(e.kind, list);
102
+ }
103
+ const countByClass = (rows, field) => {
104
+ const out = new Map();
105
+ for (const r of rows ?? [])
106
+ for (const c of r[field] ?? [])
107
+ out.set(c, (out.get(c) ?? 0) + 1);
108
+ return out;
109
+ };
110
+ const personsByClass = countByClass(input.persons, 'personnelClassIds');
111
+ const assetsByClass = countByClass(input.assets, 'assetClassIds');
112
+ const slotsByLocationType = new Map();
113
+ for (const l of input.locations ?? [])
114
+ if (l.type)
115
+ slotsByLocationType.set(l.type, (slotsByLocationType.get(l.type) ?? 0) + Math.max(l.capacity ?? 1, 1));
116
+ const order = input.route?.length
117
+ ? input.route.map(k => input.operations.find(o => o.key === k)).filter((o) => !!o)
118
+ : [...input.operations];
119
+ /* 하류 수율을 거슬러 올라가며 소요량을 부풀린다 — 도장에서 5% 를 잃으면 그 앞은 더 만들어야 한다. */
120
+ let downstream = 1;
121
+ const reversed = [];
122
+ for (const op of [...order].reverse()) {
123
+ const cycleHours = isoDurationHours(op.duration) + isoDurationHours(paramOf(op, 'setupDuration'));
124
+ downstream *= Number(paramOf(op, 'yield') ?? 1);
125
+ const requiredPerHour = downstream > 0 ? demandPerHour / downstream : Infinity;
126
+ const requirements = [];
127
+ const add = (axis, className, quantity, available, availability) => {
128
+ const q = Math.max(quantity, 1);
129
+ requirements.push({
130
+ axis, className, quantity: q, available, availability,
131
+ perHour: cycleHours > 0 ? (Math.floor(available / q) / cycleHours) * availability : Infinity
132
+ });
133
+ };
134
+ /* 설비 — 표준 EquipmentSpecification(등급+대수). 그것이 없으면 예전 표기(resourceType 한 대). */
135
+ const equipSpecs = op.equipmentSpecification?.length
136
+ ? op.equipmentSpecification.map(s => ({ className: s.equipmentClass ?? op.resourceType ?? '', quantity: s.quantity }))
137
+ : op.resourceType ? [{ className: op.resourceType, quantity: 1 }] : [];
138
+ for (const s of equipSpecs) {
139
+ if (!s.className)
140
+ continue;
141
+ const records = equipmentByKind.get(s.className) ?? [];
142
+ add('equipment', s.className, s.quantity, records.length, availabilityOf(records));
143
+ }
144
+ for (const s of op.personnelSpecification ?? [])
145
+ if (s.personnelClass)
146
+ add('personnel', s.personnelClass, s.quantity, personsByClass.get(s.personnelClass) ?? 0, 1);
147
+ for (const s of op.physicalAssetSpecification ?? [])
148
+ if (s.assetClass)
149
+ add('asset', s.assetClass, s.quantity, assetsByClass.get(s.assetClass) ?? 0, 1);
150
+ if (op.locationType)
151
+ add('location', op.locationType, 1, slotsByLocationType.get(op.locationType) ?? 0, 1);
152
+ /* 공정의 능력 = 요구들 중 가장 낮은 것. 전량 확보 규칙이라 하나만 모자라도 그만큼만 돈다. */
153
+ const constraint = requirements.length ? requirements.reduce((a, b) => (a.perHour <= b.perHour ? a : b)) : undefined;
154
+ const perHour = constraint ? constraint.perHour : Infinity;
155
+ reversed.push({ operation: op.key, cycleHours, perHour, requiredPerHour, ok: perHour >= requiredPerHour, constraint, requirements });
156
+ }
157
+ const operations = reversed.reverse();
158
+ /* 병목 = 여유가 가장 적은 공정. 라인 전체의 천장은 그 공정이 정한다. */
159
+ const tightest = operations.length
160
+ ? operations.reduce((a, b) => (a.perHour / a.requiredPerHour <= b.perHour / b.requiredPerHour ? a : b))
161
+ : undefined;
162
+ const headroom = operations.length ? Math.min(...operations.map(o => o.perHour / o.requiredPerHour)) : Infinity;
163
+ return {
164
+ workingHoursPerWeek: hoursPerWeek,
165
+ workingDaysPerWeek: daysPerWeek,
166
+ demandPerHour,
167
+ operations,
168
+ ...(tightest ? { bottleneck: { operation: tightest.operation, axis: tightest.constraint?.axis, className: tightest.constraint?.className } } : {}),
169
+ maxUnitsPerDay: input.unitsPerDay * headroom,
170
+ ok: operations.every(o => o.ok)
171
+ };
172
+ }