Repository navigation
Expand file tree
/
Copy pathcore.js
More file actions
2177 lines (1957 loc) · 94.1 KB
/
Copy pathcore.js
File metadata and controls
2177 lines (1957 loc) · 94.1 KB
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let currentView='home';
let mnInited=false;
let hbInited=false;
let pcInited=false;
let srcImg=null;
function go(v,pushState=true){
const viewEl=document.getElementById('v-'+v);
if(!viewEl) return;
document.querySelectorAll('.view').forEach(el=>el.classList.remove('active'));
viewEl.classList.add('active');
document.querySelectorAll('.nav-btn').forEach(b=>b.classList.remove('active'));
const nb=document.querySelector(`.nav-btn[data-v="${v}"]`);
if(nb) nb.classList.add('active');
window.scrollTo(0,0);
currentView=v;
initToggles(viewEl);
if(pushState){
try{history.pushState({view:v},'', '#'+v);}catch(e){}
}
if(v==='filter'){
if(!srcImg){createDefImg();applyF();}
const st=document.getElementById('up-status');
if(st && st.textContent.trim()==='') st.textContent='기본 도형 이미지가 적용되었습니다. 직접 업로드하여 변경할 수 있습니다.';
}
if(v==='pool'){try{pRst();}catch(e){}}
if(v==='perceptron'){
if(!pcInited){pcInited=true;pcInit();}
else{try{pcUpdate();}catch(e){}}
}
if(v==='mnist'){
if(!mnInited){mnInited=true;mnInit();}
else{mnRefresh();}
initToggles(viewEl);
}
if(v==='hamming'){
if(!hbInited){hbInited=true;hbInit();}
else{hbRefresh();}
initToggles(viewEl);
}
if(v==='conv'){
requestAnimationFrame(()=>{
try{ecRender();ecFitCanvas('eye');ecFitCanvas('cnn');}catch(e){}
});
}
}
document.querySelectorAll('.nav-btn').forEach(b=>b.addEventListener('click',()=>go(b.dataset.v)));
window.addEventListener('popstate',e=>{
const v=(e.state&&e.state.view)?e.state.view:'home';
if(document.getElementById('v-'+v)) go(v,false);
else if(document.getElementById('v-home')) go('home',false);
});
window.addEventListener('beforeunload',e=>{if(currentView!=='home'){e.preventDefault();}});
function htab(n,el){document.querySelectorAll('#v-hamming .tab').forEach(t=>t.classList.remove('on'));el.classList.add('on');document.querySelectorAll('#v-hamming .tpanel').forEach(p=>p.classList.remove('on'));document.getElementById('ht'+n).classList.add('on');}
function ctab(n,el){document.querySelectorAll('#v-conv .tab').forEach(t=>t.classList.remove('on'));el.classList.add('on');document.querySelectorAll('#v-conv .tpanel').forEach(p=>p.classList.remove('on'));document.getElementById('ct'+n).classList.add('on');}
function ptab(n,el){document.querySelectorAll('#v-pool .tab').forEach(t=>t.classList.remove('on'));el.classList.add('on');document.querySelectorAll('#v-pool .tpanel').forEach(p=>p.classList.remove('on'));document.getElementById('pt'+n).classList.add('on');}
function initToggles(root){
const scope=root||document;
scope.querySelectorAll('.card,.info').forEach(el=>{
if(el.dataset.tglDone==='1') return;
if(el.closest && el.closest('[data-no-toggle=\"1\"]')) return;
const isCard=el.classList.contains('card');
// 1) try :scope (modern browsers), 2) fallback to direct-child scan (older browsers)
let head=null;
try{
head = isCard ? el.querySelector(':scope>h3,:scope>h4') : el.querySelector(':scope>strong');
}catch(e){
head = null;
}
if(!head){
for(let i=0;i<el.children.length;i++){
const ch=el.children[i];
const t=ch.tagName;
if(isCard){
if(t==='H3' || t==='H4'){ head=ch; break; }
}else{
if(t==='STRONG'){ head=ch; break; }
}
}
}
if(!head) return;
// 인터랙티브 요소가 있으면 자동 토글로 감싸지 않습니다.
if(el.querySelector('button,input,select,textarea,canvas,video,audio,.tabs,.btn-row,.upz')) return;
const body=document.createElement('div');
body.className='tgl-body';
let node=head.nextSibling;
while(node){
const next=node.nextSibling;
body.appendChild(node);
node=next;
}
el.appendChild(body);
head.classList.add('tgl-head');
head.addEventListener('click',()=>{
head.classList.toggle('open');
body.classList.toggle('open');
});
el.dataset.tglDone='1';
});
}
let mnDS=null;
let mnLabel=0;
let mnDraw=false;
let mnLast=null;
function mnLoad(){
try{
const raw=localStorage.getItem('aimath_mnist_dataset_v1');
if(raw) mnDS=JSON.parse(raw);
}catch(e){}
if(!mnDS || !Array.isArray(mnDS.samples)) mnDS={meta:{ver:1,size:28,createdAt:new Date().toISOString()},samples:[]};
}
function mnSave(){
try{localStorage.setItem('aimath_mnist_dataset_v1', JSON.stringify(mnDS));}catch(e){}
}
function mnInit(){
mnLoad();
const labs=document.getElementById('mn-labs');
if(labs){
labs.innerHTML='';
for(let d=0; d<=9; d++){
const b=document.createElement('button');
b.type='button';
b.textContent=String(d);
b.className=(d===mnLabel)?'on':'';
b.onclick=()=>{
mnLabel=d;
labs.querySelectorAll('button').forEach(x=>x.classList.remove('on'));
b.classList.add('on');
};
labs.appendChild(b);
}
}
const cv=document.getElementById('mn-cv');
if(cv){
const ctx=cv.getContext('2d');
ctx.fillStyle='#fff';
ctx.fillRect(0,0,cv.width,cv.height);
const getPos=(e)=>{
const r=cv.getBoundingClientRect();
const x=(e.clientX - r.left) * (cv.width / r.width);
const y=(e.clientY - r.top) * (cv.height / r.height);
return {x,y};
};
const down=(e)=>{
mnDraw=true;
cv.setPointerCapture?.(e.pointerId);
mnLast=getPos(e);
};
const move=(e)=>{
if(!mnDraw) return;
const p=getPos(e);
ctx.strokeStyle='#000';
ctx.lineWidth=18;
ctx.lineCap='round';
ctx.lineJoin='round';
ctx.beginPath();
ctx.moveTo(mnLast.x,mnLast.y);
ctx.lineTo(p.x,p.y);
ctx.stroke();
mnLast=p;
mnUpdatePreview();
};
const up=()=>{
mnDraw=false; mnLast=null;
mnUpdatePreview();
};
cv.addEventListener('pointerdown', down);
cv.addEventListener('pointermove', move);
cv.addEventListener('pointerup', up);
cv.addEventListener('pointercancel', up);
cv.addEventListener('pointerleave', up);
}
mnRefresh();
mnUpdatePreview();
}
function mnClear(){
const cv=document.getElementById('mn-cv'); if(!cv) return;
const ctx=cv.getContext('2d');
ctx.fillStyle='#fff'; ctx.fillRect(0,0,cv.width,cv.height);
mnUpdatePreview();
}
function mnReset(){
mnDS={meta:{ver:1,size:28,createdAt:new Date().toISOString()},samples:[]};
mnSave();
mnRefresh();
mnClear();
const st=document.getElementById('mn-stat'); if(st) st.textContent='샘플 0개';
}
function mnRaster28(){
const cv=document.getElementById('mn-cv'); if(!cv) return null;
const off=document.createElement('canvas');
off.width=28; off.height=28;
const octx=off.getContext('2d');
octx.fillStyle='#fff';
octx.fillRect(0,0,28,28);
octx.drawImage(cv,0,0,28,28);
const img=octx.getImageData(0,0,28,28).data;
const px=new Array(28*28);
let ink=0;
for(let i=0;i<28*28;i++){
const r=img[i*4], g=img[i*4+1], b=img[i*4+2];
const gray=Math.round((r+g+b)/3);
const v=255-gray;
px[i]=v;
if(v>10) ink++;
}
if(ink<8) return null; // too empty
return {label:mnLabel,pixels:px};
}
function mnUpdatePreview(){
const samp=mnRaster28();
const pv=document.getElementById('mn-prev');
if(!pv) return;
const ctx=pv.getContext('2d');
const W=pv.width,H=pv.height;
ctx.clearRect(0,0,W,H);
ctx.fillStyle='#fff'; ctx.fillRect(0,0,W,H);
if(!samp){
ctx.fillStyle='rgba(0,0,0,0.35)';
ctx.font='700 14px Pretendard';
ctx.fillText('그려보세요', 16, 28);
return;
}
const img=ctx.createImageData(28,28);
for(let i=0;i<28*28;i++){
const v=samp.pixels[i]; // 0..255
img.data[i*4]=v;
img.data[i*4+1]=v;
img.data[i*4+2]=v;
img.data[i*4+3]=255;
}
const off=document.createElement('canvas');
off.width=28; off.height=28;
off.getContext('2d').putImageData(img,0,0);
ctx.imageSmoothingEnabled=false;
ctx.drawImage(off,0,0,W,H);
}
function mnAdd(){
mnLoad();
const samp=mnRaster28();
const st=document.getElementById('mn-stat');
if(!samp){
const msg=document.getElementById('mn-stat');
if(msg) msg.textContent='샘플 추가 실패 (너무 비어있음)';
return;
}
mnDS.samples.push({label:samp.label,pixels:samp.pixels});
mnSave();
mnRefresh();
mnClear();
if(st) st.textContent=`샘플 ${mnDS.samples.length}개`;
}
function mnRemove(i){
mnLoad();
if(i<0||i>=mnDS.samples.length) return;
mnDS.samples.splice(i,1);
mnSave();
mnRefresh();
}
function mnRefresh(){
mnLoad();
const list=document.getElementById('mn-list');
const st=document.getElementById('mn-stat');
if(st) st.textContent=`샘플 ${mnDS.samples.length}개`;
if(!list) return;
list.innerHTML='';
mnDS.samples.slice().reverse().forEach((s,revIdx)=>{
const idx = mnDS.samples.length-1-revIdx;
const box=document.createElement('div');
box.className='mn-smp';
box.innerHTML=`<canvas width="56" height="56"></canvas>
<div class="row"><span class="tag">y=${s.label}</span>
<button class="rm" title="삭제" onclick="mnRemove(${idx})">✕</button></div>`;
const cv=box.querySelector('canvas');
const ctx=cv.getContext('2d');
const img=ctx.createImageData(28,28);
for(let i=0;i<28*28;i++){
const v=s.pixels[i];
img.data[i*4]=v; img.data[i*4+1]=v; img.data[i*4+2]=v; img.data[i*4+3]=255;
}
const off=document.createElement('canvas');
off.width=28; off.height=28;
off.getContext('2d').putImageData(img,0,0);
ctx.imageSmoothingEnabled=false;
ctx.drawImage(off,0,0,56,56);
list.appendChild(box);
});
}
function mnExport(){
mnLoad();
const out={
meta:{...mnDS.meta, exportedAt:new Date().toISOString()},
samples: mnDS.samples
};
const blob=new Blob([JSON.stringify(out)],{type:'application/json'});
const a=document.createElement('a');
const ts=new Date().toISOString().replace(/[:.]/g,'-');
a.download=`mn_dataset_${ts}.json`;
a.href=URL.createObjectURL(blob);
document.body.appendChild(a);
a.click();
setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},0);
}
let hA=[1,0,1,1,0,0,1,0,1,0],hB=[1,1,0,1,0,1,1,0,0,1];
function rHD(){
const box=document.getElementById('hd-box');box.innerHTML='';
const mkRow=(lbl,arr,tog)=>{
const r=document.createElement('div');r.style.cssText='display:flex;align-items:center;gap:2px;';
const lb=document.createElement('span');lb.style.cssText='font-family:var(--mono);font-size:0.62rem;color:var(--muted);width:2.2rem;text-align:right;margin-right:0.3rem;';lb.textContent=lbl;r.appendChild(lb);
arr.forEach((v,i)=>{const e=document.createElement('span');e.style.cssText=`display:inline-flex;align-items:center;justify-content:center;width:2.1rem;height:2.1rem;background:${v?'var(--fg)':'var(--card)'};color:${v?'var(--bg)':'var(--fg)'};font-family:var(--mono);font-size:0.8rem;font-weight:600;border-radius:4px;cursor:pointer;transition:all 0.12s;border:1px solid var(--border);`;e.textContent=v;if(tog)e.onclick=()=>{arr[i]^=1;rHD();};r.appendChild(e);});
return r;
};
box.appendChild(mkRow('A',hA,true));box.appendChild(mkRow('B',hB,true));
const xr=document.createElement('div');xr.style.cssText='display:flex;align-items:center;gap:2px;';
const xl=document.createElement('span');xl.style.cssText='font-family:var(--mono);font-size:0.62rem;color:var(--muted);width:2.2rem;text-align:right;margin-right:0.3rem;';xl.textContent='A⊕B';xr.appendChild(xl);
let d=0;for(let i=0;i<hA.length;i++){const x=hA[i]^hB[i];d+=x;const e=document.createElement('span');e.style.cssText=`display:inline-flex;align-items:center;justify-content:center;width:2.1rem;height:2.1rem;background:${x?'var(--red)':'var(--card)'};color:${x?'#fff':'var(--muted)'};font-family:var(--mono);font-size:0.8rem;font-weight:600;border-radius:4px;border:1px solid ${x?'var(--red)':'var(--border)'};`;e.textContent=x;xr.appendChild(e);}
box.appendChild(xr);document.getElementById('hd-res').textContent=`해밍 거리 = ${d}`;
}
rHD();
let bSz=6,uBmp=[],isDraw=false,dVal=1;
let curRefDigit=null;
let hGuess=new Array(10).fill('');
const REFS={};
REFS[6]=[
[0,1,1,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,0,1,1,0,1,1,1,1,0],
[0,0,1,1,0,0,0,1,1,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,1,1,1],
[0,1,1,1,1,0,1,0,0,0,0,1,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1],
[1,1,1,1,1,0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,1,1,0],
[1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,1,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,0],
[1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,1,1,0],
[0,1,1,1,1,0,1,1,0,0,0,0,1,1,1,1,1,0,1,0,0,0,0,1,1,1,0,0,1,1,0,1,1,1,1,0],
[1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0],
[0,1,1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,0,0,1,1,0,1,1,1,1,0],
[0,1,1,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1,0,0,0,0,1,1,0,1,1,1,1,0],
];
REFS[8]=[
[0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0],
[0,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,1,0],
[0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0],
[0,0,1,1,1,1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,0,0,1,1,1,1,0,0],
[0,0,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,1,0,0,0,1,1,0,0,1,0,0,1,1,0,0,0,1,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0],
[0,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,0,0,1,1,1,1,0,0],
[0,0,1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0],
[0,1,1,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0],
[0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0],
[0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0],
];
REFS[12]=(()=>{const r=[];for(let d=0;d<10;d++){const s=REFS[6][d],o=[];for(let y=0;y<6;y++){const r1=[],r2=[];for(let x=0;x<6;x++){const v=s[y*6+x];r1.push(v,v);r2.push(v,v);}o.push(...r1,...r2);}r.push(o);}return r;})();
function setSz(n,el){
bSz=n;
uBmp=Array(n*n).fill(0);
hGuess=new Array(10).fill('');
isDraw=false;
dVal=1;
curRefDigit=null;
document.querySelectorAll('.bsz').forEach(b=>b.classList.remove('active'));
el.classList.add('active');
rBmp();
initHGuessUI();
document.getElementById('hbest').textContent='';
document.getElementById('hoverlap').innerHTML='';
document.getElementById('refpreview').innerHTML='';
const ov=document.getElementById('ovpreview');
if(ov) ov.innerHTML='';
rRef();
}
function rBmp(){
const g=document.getElementById('ubmp');const cs=bSz<=6?'2rem':bSz<=8?'1.6rem':'1.2rem';
g.style.gridTemplateColumns=`repeat(${bSz},1fr)`;g.innerHTML='';
for(let i=0;i<bSz*bSz;i++){const c=document.createElement('div');c.className='bc'+(uBmp[i]?' on':'');c.style.width=cs;c.style.height=cs;
c.dataset.idx=i;
c.addEventListener('mousedown',e=>{e.preventDefault();isDraw=true;dVal=uBmp[i]?0:1;uBmp[i]=dVal;rBmpVisual();});
c.addEventListener('mouseenter',()=>{if(isDraw){uBmp[i]=dVal;rBmpVisual();}});
g.appendChild(c);}
bindTouch();
}
function rBmpVisual(){
const cells=document.getElementById('ubmp').children;
for(let i=0;i<cells.length;i++){cells[i].className='bc'+(uBmp[i]?' on':'');}
renderOverlapPreview();
}
function bindTouch(){
const g=document.getElementById('ubmp');
g.ontouchstart=e=>{
e.preventDefault();
const t=e.touches[0];
const el=document.elementFromPoint(t.clientX,t.clientY);
if(el&&el.dataset&&el.dataset.idx!==undefined){
const idx=parseInt(el.dataset.idx);
isDraw=true;dVal=uBmp[idx]?0:1;uBmp[idx]=dVal;rBmpVisual();
}
};
g.ontouchmove=e=>{
e.preventDefault();
if(!isDraw)return;
const t=e.touches[0];
const el=document.elementFromPoint(t.clientX,t.clientY);
if(el&&el.dataset&&el.dataset.idx!==undefined){
const idx=parseInt(el.dataset.idx);
if(uBmp[idx]!==dVal){uBmp[idx]=dVal;rBmpVisual();}
}
};
g.ontouchend=()=>{isDraw=false;};
}
document.addEventListener('mouseup',()=>{isDraw=false;});
function rRef(){
const b=document.getElementById('rbtn');
if(!b) return;
b.innerHTML='';
for(let d=0;d<10;d++){
const e=document.createElement('button');
e.className='btn'+(curRefDigit===d?' pri':'');
e.textContent=d;
e.style.padding='0.35rem 0.55rem';
e.onclick=()=>showRefPreview(d);
b.appendChild(e);
}
}
function renderOverlapPreview(){
const box=document.getElementById('ovpreview');
if(!box) return;
if(curRefDigit===null || !REFS[bSz] || !REFS[bSz][curRefDigit]){box.innerHTML='';return;}
const ref=REFS[bSz][curRefDigit];
const cs=bSz<=6?'1.2rem':bSz<=8?'1rem':'0.7rem';
let html=`<p class="mat-label" style="margin-bottom:0.3rem;">겹친 부분 (내 그림 ∧ 참조)</p>`;
html+=`<div class="bmp" style="grid-template-columns:repeat(${bSz},1fr);cursor:default;">`;
for(let i=0;i<bSz*bSz;i++){
const on=(uBmp[i]===1 && ref[i]===1);
html+=`<div class="bc${on?' on':''}" style="width:${cs};height:${cs};pointer-events:none;"></div>`;
}
html+=`</div>`;
box.innerHTML=html;
}
function showRefPreview(digit){
curRefDigit=digit;
const ref=REFS[bSz][digit];
const cs=bSz<=6?'1.2rem':bSz<=8?'1rem':'0.7rem';
const box=document.getElementById('refpreview');
let html=`<p class="mat-label" style="margin-bottom:0.3rem;">참조: 숫자 ${digit}</p>`;
html+=`<div class="bmp" style="grid-template-columns:repeat(${bSz},1fr);cursor:default;">`;
for(let i=0;i<bSz*bSz;i++){
html+=`<div class="bc${ref[i]?' on':''}" style="width:${cs};height:${cs};pointer-events:none;"></div>`;
}
html+=`</div>`;
box.innerHTML=html;
renderOverlapPreview();
rRef();
}
function hbInit(){
if(!uBmp || !uBmp.length) uBmp = Array(bSz*bSz).fill(0);
try{rBmp();rRef();}catch(e){}
try{initHGuessUI();}catch(e){}
try{hdgInit();}catch(e){}
}
function hbRefresh(){
try{rBmp();rRef();}catch(e){}
try{initHGuessUI();}catch(e){}
try{hdgInit();}catch(e){}
}
function initHGuessUI(){
const box=document.getElementById('hbars');
if(!box) return;
box.innerHTML='';
for(let d=0; d<10; d++){
const row=document.createElement('div');
row.className='hb';
row.dataset.digit=d;
row.innerHTML = `
<span class="dl">${d}</span>
<div class="tk"><div class="fl" style="width:0%"></div></div>
<input class="hguess" type="number" inputmode="numeric" placeholder="내 답" aria-label="digit ${d} hamming guess">
<span class="dv"></span>
`;
box.appendChild(row);
}
const hint=document.createElement('p');
hint.style.fontSize='0.72rem';
hint.style.color='var(--muted)';
hint.style.marginTop='0.5rem';
hint.textContent='각 숫자(0~9)와의 해밍 거리를 직접 계산해 입력한 뒤, “해밍 거리 계산”을 눌러 채점해보세요.';
box.appendChild(hint);
box.querySelectorAll('input.hguess').forEach(inp=>{
const d=parseInt(inp.parentElement.dataset.digit);
inp.value = (hGuess[d] ?? '');
inp.addEventListener('input', ()=>{
hGuess[d]=inp.value;
const dl=inp.parentElement.querySelector('.dl');
if(dl) dl.style.color='';
});
});
}
function clrBmp(){
uBmp=Array(bSz*bSz).fill(0);
rBmp();
try{initHGuessUI();}catch(e){}
document.getElementById('hbest').textContent='';
document.getElementById('hoverlap').innerHTML='';
document.getElementById('refpreview').innerHTML='';
const ov=document.getElementById('ovpreview');
if(ov) ov.innerHTML='';
curRefDigit=null;
rRef();
}
function calcH(){
const refs=REFS[bSz];
if(!refs) return;
const tot=bSz*bSz;
const ds=refs.map((ref,i)=>{
let d=0;
for(let j=0;j<tot;j++) d+=(uBmp[j]^ref[j]);
return {digit:i,dist:d,sim:((tot-d)/tot*100).toFixed(1)};
});
const mx=Math.max(...ds.map(d=>d.dist),1);
const mn=Math.min(...ds.map(d=>d.dist));
const box=document.getElementById('hbars');
if(!box) return;
const guessMap={};
box.querySelectorAll('.hb').forEach(row=>{
const digit=parseInt(row.dataset.digit);
const inp=row.querySelector('input.hguess');
if(inp) guessMap[digit]=inp.value;
});
box.innerHTML='';
ds.forEach(({digit,dist,sim})=>{
const e=document.createElement('div');
e.className='hb';
e.dataset.digit=digit;
const g=(guessMap[digit] ?? '').toString().trim();
const gNum = g==='' ? null : Number(String(g).trim());
const isOk = (gNum!==null && Number.isFinite(gNum) && gNum===dist);
e.innerHTML = `
<span class="dl" style="${gNum===null?'':(isOk?'color:var(--green);':'color:var(--red);')}">${digit}</span>
<div class="tk"><div class="fl ${dist===mn?'best':''}" style="width:${(dist/mx*100)}%"></div></div>
<input class="hguess" type="number" inputmode="numeric" placeholder="내 답" value="${g}">
<span class="dv">${dist} (${sim}%)</span>
`;
box.appendChild(e);
});
box.querySelectorAll('input.hguess').forEach(inp=>{
const d=parseInt(inp.parentElement.dataset.digit);
inp.addEventListener('input', ()=>{
hGuess[d]=inp.value;
const dl=inp.parentElement.querySelector('.dl');
if(dl) dl.style.color='';
});
});
const best=ds.reduce((a,b)=>a.dist<b.dist?a:b);
const bestEl=document.getElementById('hbest');
if(bestEl) bestEl.textContent=`가장 유사: ${best.digit} (거리 ${best.dist}, 유사도 ${best.sim}%)`;
const ovBox=document.getElementById('hoverlap');
if(ovBox){
const cs=bSz<=6?'1.05rem':bSz<=8?'0.92rem':'0.72rem';
let html=`<p class="mat-label" style="margin-bottom:0.45rem;">내 그림 vs 모든 숫자 겹침 비교</p>`;
html+=`<div style="display:flex;flex-wrap:wrap;gap:0.8rem;align-items:flex-start;">`;
ds.forEach(({digit,dist,sim})=>{
const ref=refs[digit];
const isBest = digit===best.digit;
html+=`<div style="background:var(--bg);border:1px solid ${isBest?'var(--fg)':'var(--border)'};border-radius:var(--radius);padding:0.65rem;flex:1 1 230px;max-width:300px;">`;
html+=`<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.45rem;">`;
html+=`<span style="font-family:var(--mono);font-weight:800;color:${isBest?'var(--fg)':'var(--muted)'};">숫자 ${digit}${isBest?' · BEST':''}</span>`;
html+=`<span style="font-family:var(--mono);font-size:0.72rem;color:var(--muted);">거리 ${dist} · ${sim}%</span>`;
html+=`</div>`;
html+=`<div class="ovlap" style="grid-template-columns:repeat(${bSz},1fr);">`;
for(let i=0;i<tot;i++){
const u=uBmp[i], r=ref[i];
let cls;
if(u===1&&r===1) cls='both';
else if(u===0&&r===0) cls='match';
else if(u===1&&r===0) cls='only-user';
else cls='only-ref';
html+=`<div class="oc ${cls}" style="width:${cs};height:${cs};"></div>`;
}
html+=`</div></div>`;
});
html+=`</div>`;
html+=`<div style="display:flex;gap:0.8rem;margin-top:0.6rem;flex-wrap:wrap;">`;
html+=`<span style="font-size:0.62rem;color:var(--muted);display:flex;align-items:center;gap:0.25rem;"><span style="display:inline-block;width:0.6rem;height:0.6rem;background:var(--fg);border-radius:2px;"></span>둘 다 1</span>`;
html+=`<span style="font-size:0.62rem;color:var(--muted);display:flex;align-items:center;gap:0.25rem;"><span style="display:inline-block;width:0.6rem;height:0.6rem;background:var(--card);border:1px solid var(--border);border-radius:2px;"></span>둘 다 0</span>`;
html+=`<span style="font-size:0.62rem;color:var(--muted);display:flex;align-items:center;gap:0.25rem;"><span style="display:inline-block;width:0.6rem;height:0.6rem;background:var(--red);opacity:0.7;border-radius:2px;"></span>내 그림에만</span>`;
html+=`<span style="font-size:0.62rem;color:var(--muted);display:flex;align-items:center;gap:0.25rem;"><span style="display:inline-block;width:0.6rem;height:0.6rem;background:var(--blue);opacity:0.7;border-radius:2px;"></span>참조에만</span>`;
html+=`</div>`;
ovBox.innerHTML=html;
}
}
function mkEG(id,data,rows,cols,onCh){
const g=document.getElementById(id);g.innerHTML='';g.style.gridTemplateColumns=`repeat(${cols},1fr)`;
for(let r=0;r<rows;r++)for(let c=0;c<cols;c++){
const cell=document.createElement('div');cell.className='ec';
const inp=document.createElement('input');inp.type='number';inp.value=data[r][c];
inp.addEventListener('change',()=>{data[r][c]=parseInt(inp.value)||0;if(onCh)onCh();});
inp.addEventListener('focus',()=>inp.select());
cell.appendChild(inp);g.appendChild(cell);
}
}
let mI=[[1,2,0,1],[0,1,3,2],[1,0,2,1],[2,1,0,3]],mK=[[1,0,-1],[0,1,0],[-1,0,1]],mO=[[0,0],[0,0]];
function newMan(){
for(let r=0;r<4;r++)for(let c=0;c<4;c++)mI[r][c]=Math.floor(Math.random()*5);
const ks=[[[1,0,-1],[0,1,0],[-1,0,1]],[[0,-1,0],[-1,5,-1],[0,-1,0]],[[1,1,1],[0,0,0],[-1,-1,-1]]];
const p=ks[Math.floor(Math.random()*ks.length)];for(let r=0;r<3;r++)for(let c=0;c<3;c++)mK[r][c]=p[r][c];
mO=[[0,0],[0,0]];mkEG('mi',mI,4,4);mkEG('mk',mK,3,3);mkEG('mo',mO,2,2);
document.getElementById('mres').style.display='none';document.getElementById('msol').style.display='none';
}
function chkMan(){
const cor=[];
for(let r=0;r<2;r++){cor.push([]);for(let c=0;c<2;c++){let s=0;for(let kr=0;kr<3;kr++)for(let kc=0;kc<3;kc++)s+=mI[r+kr][c+kc]*mK[kr][kc];cor[r].push(s);}}
let ok=true;const det=[];
for(let r=0;r<2;r++)for(let c=0;c<2;c++){
const right=mO[r][c]===cor[r][c];if(!right)ok=false;
let t=[];for(let kr=0;kr<3;kr++)for(let kc=0;kc<3;kc++)t.push(`${mI[r+kr][c+kc]}×(${mK[kr][kc]})`);
det.push(`위치(${r},${c}): ${t.join(' + ')} = ${cor[r][c]}${right?'':' (입력값: '+mO[r][c]+')'}`);
}
const res=document.getElementById('mres');res.style.display='block';
res.innerHTML=ok?'<strong>정답입니다.</strong>':'<strong>일부 틀렸습니다.</strong> 아래 풀이를 확인하세요.';
res.style.borderLeftColor=ok?'var(--green)':'var(--red)';
const sol=document.getElementById('msol');sol.style.display='block';
sol.innerHTML=`<div class="card"><h3>풀이 과정</h3>${det.map(d=>'<p style="font-size:0.8rem;color:var(--muted);font-family:var(--mono);margin:0.25rem 0;">'+d+'</p>').join('')}</div>`;
}
newMan();
const AI=[[0,0,0,0,0],[0,1,1,1,0],[0,1,0,1,0],[0,1,1,1,0],[0,0,0,0,0]];
const AK=[[1,0,1],[0,1,0],[1,0,1]];
let ap=-1,ar=Array(9).fill('?');
function bldA(){
['ai','ak','ao'].forEach(id=>document.getElementById(id).innerHTML='');
for(let r=0;r<5;r++)for(let c=0;c<5;c++){const e=document.createElement('div');e.className='mc';e.id=`ai${r}${c}`;e.textContent=AI[r][c];document.getElementById('ai').appendChild(e);}
for(let r=0;r<3;r++)for(let c=0;c<3;c++){const e=document.createElement('div');e.className='mc';e.textContent=AK[r][c];document.getElementById('ak').appendChild(e);}
for(let i=0;i<9;i++){const e=document.createElement('div');e.className='mc';e.id=`ao${i}`;e.textContent=ar[i];document.getElementById('ao').appendChild(e);}
}
bldA();
function aStep(){
ap++;if(ap>=9){ap=8;return;}
const row=Math.floor(ap/3),col=ap%3;
for(let r=0;r<5;r++)for(let c=0;c<5;c++)document.getElementById(`ai${r}${c}`).className='mc';
let sum=0,terms=[];
for(let kr=0;kr<3;kr++)for(let kc=0;kc<3;kc++){
const ir=row+kr,ic=col+kc;
document.getElementById(`ai${ir}${ic}`).className='mc win';
}
for(let kr=0;kr<3;kr++)for(let kc=0;kc<3;kc++){
const ir=row+kr,ic=col+kc;
const kv=AK[kr][kc];
if(kv!==0) document.getElementById(`ai${ir}${ic}`).className='mc win-active';
const p=AI[ir][ic]*kv;sum+=p;terms.push(`(${AI[ir][ic]}×${kv})`);
}
ar[ap]=sum;
for(let i=0;i<9;i++){const e=document.getElementById(`ao${i}`);e.textContent=ar[i];e.className=i===ap?'mc res':ar[i]!=='?'?'mc done':'mc';}
document.getElementById('ast').textContent=`위치 (${row}, ${col}) → ${sum}`;
document.getElementById('acalc').innerHTML=`<strong>계산:</strong> ${terms.join(' + ')} = <strong>${sum}</strong><br><span style="font-size:0.65rem;">진한 색 = 필터값이 0이 아닌 곳 (실제 곱셈 발생) · 연한 색 = 필터값 0 (곱해도 0)</span>`;
}
let aIv=null;
function aAuto(){if(aIv){clearInterval(aIv);aIv=null;}aReset();let s=0;aIv=setInterval(()=>{aStep();s++;if(s>=9){clearInterval(aIv);aIv=null;}},800);}
function aReset(){if(aIv){clearInterval(aIv);aIv=null;}ap=-1;ar=Array(9).fill('?');bldA();document.getElementById('ast').textContent='';document.getElementById('acalc').innerHTML='시작 버튼을 눌러 연산 과정을 확인하세요.';}
const FL={
'Identity':{k:[[0,0,0],[0,1,0],[0,0,0]],d:'원본 그대로 출력합니다.'},
'Box Blur':{k:[[1,1,1],[1,1,1],[1,1,1]],d:'주변 9픽셀 평균으로 흐리게 합니다.',n:9},
'Sobel X':{k:[[-1,0,1],[-2,0,2],[-1,0,1]],d:'세로선(수직 경계)을 검출합니다.'},
'Sobel Y':{k:[[-1,-2,-1],[0,0,0],[1,2,1]],d:'가로선(수평 경계)을 검출합니다.'},
'Sharpen':{k:[[0,-1,0],[-1,5,-1],[0,-1,0]],d:'경계를 또렷하게 선명화합니다.'},
'Edge':{k:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],d:'윤곽선만 추출합니다.'},
};
let aF='Identity',cK=[[0,0,0],[0,1,0],[0,0,0]];
'Identity',cK=[[0,0,0],[0,1,0],[0,0,0]];
function bldFC(){
const box=document.getElementById('fc');box.innerHTML='';
Object.keys(FL).forEach(n=>{const ch=document.createElement('button');ch.className='chip'+(n===aF?' on':'');ch.textContent=n;
ch.onclick=()=>{aF=n;document.querySelectorAll('#fc .chip').forEach(c=>c.classList.remove('on'));ch.classList.add('on');cK=FL[n].k.map(r=>[...r]);rFK();applyF();};
box.appendChild(ch);});
}
function rFK(){
mkEG('fk',cK,3,3);
const f=FL[aF];
const m=document.getElementById('fmult');
if(m) m.textContent = (f && f.n) ? `1/${f.n} ×` : '';
document.getElementById('fd').textContent=f?f.d:'커스텀 커널';
}
function applyCustom(){aF='Custom';document.querySelectorAll('#fc .chip').forEach(c=>c.classList.remove('on'));document.getElementById('fd').textContent='사용자 정의 커널 적용';applyF();}
function createDefImg(){
const cv=document.getElementById('fin'),ctx=cv.getContext('2d'),W=240;
ctx.fillStyle='#e8e0d6';ctx.fillRect(0,0,W,W);
ctx.fillStyle='#3a342e';ctx.beginPath();ctx.arc(120,75,45,0,Math.PI*2);ctx.fill();
ctx.fillStyle='#78726a';ctx.fillRect(35,155,70,55);
ctx.fillStyle='#a89888';ctx.beginPath();ctx.moveTo(180,210);ctx.lineTo(145,155);ctx.lineTo(215,155);ctx.closePath();ctx.fill();
ctx.strokeStyle='#1a1714';ctx.lineWidth=3;ctx.beginPath();ctx.moveTo(25,25);ctx.lineTo(70,70);ctx.stroke();
ctx.beginPath();ctx.moveTo(165,25);ctx.lineTo(215,25);ctx.stroke();ctx.beginPath();ctx.moveTo(190,15);ctx.lineTo(190,55);ctx.stroke();
for(let i=0;i<10;i++){ctx.fillStyle='#1a1714';ctx.beginPath();ctx.arc(25+i*21,120,3,0,Math.PI*2);ctx.fill();}
srcImg=ctx.getImageData(0,0,W,W);
}
function loadImg(file){
const reader=new FileReader();reader.onload=e=>{const img=new Image();img.onload=()=>{
const cv=document.getElementById('fin'),ctx=cv.getContext('2d');ctx.clearRect(0,0,240,240);
const sc=Math.min(240/img.width,240/img.height),w=img.width*sc,h=img.height*sc;
ctx.fillStyle='#e8e0d6';ctx.fillRect(0,0,240,240);ctx.drawImage(img,(240-w)/2,(240-h)/2,w,h);
srcImg=ctx.getImageData(0,0,240,240);applyF();
document.getElementById('up-status').textContent='이미지가 적용되었습니다. (' +file.name+')';
document.getElementById('upz').style.borderColor='var(--green)';
setTimeout(()=>{document.getElementById('upz').style.borderColor='';},2000);
};img.src=e.target.result;};reader.readAsDataURL(file);
}
const uz=document.getElementById('upz'),fi=document.getElementById('fup');
uz.onclick=()=>fi.click();fi.onchange=e=>{if(e.target.files[0])loadImg(e.target.files[0]);};
uz.ondragover=e=>{e.preventDefault();uz.classList.add('dg');};uz.ondragleave=()=>uz.classList.remove('dg');
uz.ondrop=e=>{e.preventDefault();uz.classList.remove('dg');if(e.dataTransfer.files[0])loadImg(e.dataTransfer.files[0]);};
function applyF(){
if(!srcImg)return;const k=cK,f=FL[aF],norm=f&&f.n?f.n:1;
const W=srcImg.width,H=srcImg.height,oc=document.getElementById('fout'),octx=oc.getContext('2d'),out=octx.createImageData(W,H);
for(let y=1;y<H-1;y++)for(let x=1;x<W-1;x++){
let r=0,g=0,b=0;
for(let ky=-1;ky<=1;ky++)for(let kx=-1;kx<=1;kx++){const idx=((y+ky)*W+(x+kx))*4,w=k[ky+1][kx+1];r+=srcImg.data[idx]*w;g+=srcImg.data[idx+1]*w;b+=srcImg.data[idx+2]*w;}
const oi=(y*W+x)*4;out.data[oi]=Math.min(255,Math.max(0,r/norm));out.data[oi+1]=Math.min(255,Math.max(0,g/norm));out.data[oi+2]=Math.min(255,Math.max(0,b/norm));out.data[oi+3]=255;
}
octx.putImageData(out,0,0);
}
bldFC();rFK();
let pI=[[9,8,4,8],[7,9,4,8],[2,8,9,7],[6,5,9,5]],pP=-1,pR=['?','?','?','?'],pIv=null;
function bldP(){
mkEG('pi',pI,4,4);
const o=document.getElementById('po');o.innerHTML='';
for(let i=0;i<4;i++){const e=document.createElement('div');e.className='mc';e.id=`po${i}`;e.textContent=pR[i];o.appendChild(e);}
}
function pRst(){if(pIv){clearInterval(pIv);pIv=null;}pP=-1;pR=['?','?','?','?'];bldP();document.getElementById('pst').textContent='';}
function pStp(){
pP++;if(pP>=4){pP=3;return;}
const sr=pP<2?0:2,sc=pP%2===0?0:2;
document.querySelectorAll('#pi .ec').forEach(c=>{c.style.background='';c.style.outline='';const inp=c.querySelector('input');if(inp)inp.style.color='';});
let mx=-Infinity;
for(let r=sr;r<sr+2;r++)for(let c=sc;c<sc+2;c++){if(pI[r][c]>mx)mx=pI[r][c];}
for(let r=sr;r<sr+2;r++)for(let c=sc;c<sc+2;c++){
const idx=r*4+c,cells=document.getElementById('pi').children;
const isMax=pI[r][c]===mx;
cells[idx].style.background=isMax?'var(--green)':'var(--fg)';
cells[idx].querySelector('input').style.color=isMax?'#fff':'var(--bg)';
if(isMax)cells[idx].style.outline='2px solid var(--green)';
}
pR[pP]=mx;
for(let i=0;i<4;i++){const e=document.getElementById(`po${i}`);e.textContent=pR[i];e.className=i===pP?'mc res':pR[i]!=='?'?'mc done':'mc';}
document.getElementById('pst').textContent=`${sr}~${sr+1}행, ${sc}~${sc+1}열 → max = ${mx}`;
}
function pAut(){if(pIv){clearInterval(pIv);pIv=null;}pRst();let s=0;pIv=setInterval(()=>{pStp();s++;if(s>=4){clearInterval(pIv);pIv=null;}},1000);}
pRst();
const PC_N=3;
let pcInputs=[1,0.5,-0.3];
let pcWeights=[0.8,-0.5,0.6];
let pcBias=0;
let pcAct='step';
let pcTheta=0;
const PC_ACTS={
'step':{name:'계단 함수',hasTheta:true},
'relu':{name:'ReLU',hasTheta:true},
'sigmoid':{name:'시그모이드',hasTheta:false},
};
function pcInit(){
const box=document.getElementById('pc-inputs');
box.innerHTML='';
for(let i=0;i<PC_N;i++){
const row=document.createElement('div');
row.style.cssText='display:flex;align-items:center;gap:0.6rem;margin-bottom:0.8rem;';
row.innerHTML=`
<span class="mono" style="width:1.5rem;flex-shrink:0;">x${i+1}</span>
<input type="range" class="ns" id="pc-x${i}" min="-2" max="2" step="0.05" value="${pcInputs[i]}" style="max-width:10rem;flex:1;">
<span id="pc-xv${i}" style="font-family:var(--mono);font-size:0.78rem;min-width:2.5rem;text-align:right;">${pcInputs[i].toFixed(2)}</span>
<span class="mono" style="color:var(--muted);flex-shrink:0;">w${i+1}</span>
<input type="number" id="pc-w${i}" value="${pcWeights[i]}" step="0.1" style="width:4rem;font-family:var(--mono);font-size:0.78rem;padding:0.3rem 0.4rem;border:1px solid var(--border);border-radius:var(--radius);background:var(--card);color:var(--fg);text-align:center;">
`;
box.appendChild(row);
document.getElementById(`pc-x${i}`).addEventListener('input',function(){
pcInputs[i]=parseFloat(this.value);
document.getElementById(`pc-xv${i}`).textContent=pcInputs[i].toFixed(2);
pcUpdate();
});
const __wEl=document.getElementById(`pc-w${i}`);
if(__wEl) __wEl.addEventListener('input',function(){
pcWeights[i]=parseFloat(this.value)||0;
pcUpdate();
});
}
const __pcBias=document.getElementById('pc-bias');
if(__pcBias) __pcBias.addEventListener('input',function(){
pcBias=parseFloat(this.value);
document.getElementById('pc-bias-val').textContent=pcBias.toFixed(1);
pcUpdate();
});
const actBox=document.getElementById('pc-act-chips');
actBox.innerHTML='';
Object.keys(PC_ACTS).forEach(key=>{
const ch=document.createElement('button');
ch.className='chip'+(key===pcAct?' on':'');
ch.textContent=PC_ACTS[key].name;
ch.onclick=()=>{
pcAct=key;
actBox.querySelectorAll('.chip').forEach(c=>c.classList.remove('on'));
ch.classList.add('on');
document.getElementById('pc-threshold-wrap').style.display=PC_ACTS[key].hasTheta?'block':'none';
pcUpdate();
};
actBox.appendChild(ch);
});
const __pcTheta=document.getElementById('pc-theta');
if(__pcTheta) __pcTheta.addEventListener('input',function(){
pcTheta=parseFloat(this.value);
document.getElementById('pc-theta-val').textContent=pcTheta.toFixed(1);
pcUpdate();
});
pcUpdate();
}
function pcActivate(x){
switch(pcAct){
case 'step': return x>=pcTheta?1:0;
case 'relu': return x>=pcTheta?x-pcTheta:0;
case 'sigmoid': return 1/(1+Math.exp(-(x)));
}
}
function pcUpdate(){
let wsum=pcBias;
const terms=[];
for(let i=0;i<PC_N;i++){
wsum+=pcInputs[i]*pcWeights[i];
terms.push(`(${pcInputs[i].toFixed(2)} × ${pcWeights[i].toFixed(1)})`);
}
const y=pcActivate(wsum);
const calcEl=document.getElementById('pc-calc');
calcEl.innerHTML=
`가중합: ${terms.join(' + ')} + ${pcBias.toFixed(1)}<br>`+
`<span style="color:var(--fg);font-weight:600;">x = ${wsum.toFixed(3)}</span><br>`+
`f(x) = ${pcAct==='step'?'계단(θ='+pcTheta.toFixed(1)+')':pcAct==='relu'?'ReLU(θ='+pcTheta.toFixed(1)+')':'σ(x)'}`;
document.getElementById('pc-output').textContent=y.toFixed(4);
pcDrawGraph(wsum,y);
}
function pcDrawGraph(curX,curY){
const cv=document.getElementById('pc-graph');
const ctx=cv.getContext('2d');
const W=cv.width,H=cv.height;
const pad=40;
ctx.clearRect(0,0,W,H);
const xMin=-6,xMax=6,yMin=-0.5,yMax=pcAct==='relu'?4:1.5;
const toSX=x=>pad+(x-xMin)/(xMax-xMin)*(W-2*pad);
const toSY=y=>H-pad-(y-yMin)/(yMax-yMin)*(H-2*pad);
ctx.strokeStyle='#e8e0d6';
ctx.lineWidth=1;
for(let gx=Math.ceil(xMin);gx<=Math.floor(xMax);gx++){
const sx=toSX(gx);
ctx.beginPath();ctx.moveTo(sx,pad);ctx.lineTo(sx,H-pad);ctx.stroke();
}
for(let gy=Math.ceil(yMin*2)/2;gy<=yMax;gy+=0.5){
const sy=toSY(gy);
ctx.beginPath();ctx.moveTo(pad,sy);ctx.lineTo(W-pad,sy);ctx.stroke();
}
ctx.strokeStyle='#c8b9a6';
ctx.lineWidth=1.5;
const ax0=toSY(0);
ctx.beginPath();ctx.moveTo(pad,ax0);ctx.lineTo(W-pad,ax0);ctx.stroke();
const ay0=toSX(0);
ctx.beginPath();ctx.moveTo(ay0,pad);ctx.lineTo(ay0,H-pad);ctx.stroke();
ctx.fillStyle='#78726a';
ctx.font='11px "JetBrains Mono"';
ctx.textAlign='center';
for(let gx=Math.ceil(xMin);gx<=Math.floor(xMax);gx++){
if(gx===0)continue;
ctx.fillText(gx,toSX(gx),ax0+14);
}
ctx.textAlign='right';
for(let gy=0;gy<=yMax;gy+=0.5){
if(gy===0)continue;
const sy=toSY(gy);
if(sy>pad&&sy<H-pad) ctx.fillText(gy.toFixed(1),ay0-6,sy+4);
}
if(pcAct!=='sigmoid'){
const tx=toSX(pcTheta);
ctx.strokeStyle='#4a6b8a';
ctx.lineWidth=1;
ctx.setLineDash([4,4]);
ctx.beginPath();ctx.moveTo(tx,pad);ctx.lineTo(tx,H-pad);ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle='#4a6b8a';
ctx.textAlign='center';
ctx.fillText('θ='+pcTheta.toFixed(1),tx,pad-6);
}
ctx.strokeStyle='#1a1714';
ctx.lineWidth=2.5;
ctx.beginPath();
let first=true;
for(let px=pad;px<=W-pad;px++){
const x=xMin+(px-pad)/(W-2*pad)*(xMax-xMin);
const y=pcActivate(x);
const sy=toSY(y);
if(sy<pad-10||sy>H-pad+10){if(!first){ctx.stroke();ctx.beginPath();first=true;}continue;}
if(first){ctx.moveTo(px,sy);first=false;}
else ctx.lineTo(px,sy);
}
ctx.stroke();
const px=toSX(curX),py=toSY(curY);
ctx.strokeStyle='#b44133';
ctx.lineWidth=1;
ctx.setLineDash([3,3]);
ctx.beginPath();ctx.moveTo(px,ax0);ctx.lineTo(px,py);ctx.stroke();
ctx.beginPath();ctx.moveTo(ay0,py);ctx.lineTo(px,py);ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle='#b44133';
ctx.beginPath();ctx.arc(px,py,6,0,Math.PI*2);ctx.fill();
ctx.fillStyle='#fff';
ctx.beginPath();ctx.arc(px,py,2.5,0,Math.PI*2);ctx.fill();