thermal_mt_parser.py 315 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395
  1. #!/usr/bin/env python3
  2. """Per-chamber & per-position individual sensor parser for `thermal_mt_results`.
  3. Zero cross-sensor averaging: reports and plots every individual chamber sensor
  4. (ct1_ch1_front .. ct8_ch4_rear), every active MCU BMC channel (BMC0..BMC23),
  5. every Redfish temperature / fan / PWM / power sensor, and every MemTest86
  6. console sensor independently with exact start / end / min / max values.
  7. Supports:
  8. - multi-station directories (S1_..., S2_..., S3_...)
  9. - single-station directories
  10. - `.zip` archives (flat or wrapped)
  11. - 115-col v1 & 117-col v2 `*_comprehensive.csv`, 34-col `*_template.csv`,
  12. `master_events.jsonl`, `*_console.log`, and `live_status.json`
  13. Outputs:
  14. - `PARSED_METRICS.json`: structured per-chamber & per-position metrics
  15. - `PARSED_REPORT.md`: Markdown report broken down by individual sensor
  16. - `PARSED_DASHBOARD.html`: self-contained offline interactive HTML5 dashboard
  17. - optional `--export-clean-csv <dir>`: unified per-sensor clean CSVs
  18. - optional `--gui`: Tkinter desktop launcher
  19. Uses Python 3 standard library only (Linux & Windows).
  20. """
  21. from __future__ import annotations
  22. import argparse
  23. import base64
  24. import csv
  25. from dataclasses import dataclass
  26. from datetime import datetime, timezone
  27. import html
  28. import io
  29. import json
  30. import math
  31. import os
  32. from pathlib import Path, PurePosixPath
  33. import re
  34. import statistics
  35. import sys
  36. import threading
  37. import webbrowser
  38. import zipfile
  39. from typing import Any
  40. PARSER_VERSION = "2.2.0"
  41. CAMPAIGN_AGGREGATE_IGNORE = {
  42. "cpu0_dimm_mean_c", "all_dimm_max_c", "all_dimm_min_c", "all_dimm_spread_c",
  43. }
  44. CAMPAIGN_KNOWN_SENSORS: list[tuple[str, str, str, str]] = [
  45. # (key, label, group, unit)
  46. ("DIMM_CPU0_A_Temp", "DIMM CPU0_A", "dimm_temp", "°C"),
  47. ("DIMM_CPU0_B_Temp", "DIMM CPU0_B", "dimm_temp", "°C"),
  48. ("DIMM_CPU0_C_Temp", "DIMM CPU0_C", "dimm_temp", "°C"),
  49. ("DIMM_CPU0_D_Temp", "DIMM CPU0_D", "dimm_temp", "°C"),
  50. ("DIMM_CPU1_A_Temp", "DIMM CPU1_A", "dimm_temp", "°C"),
  51. ("CPU0_Temp", "CPU0 温度", "cpu_temp", "°C"),
  52. ("CPU1_Temp", "CPU1 温度", "cpu_temp", "°C"),
  53. ("DDR0_Power", "DDR0 功耗", "power", "W"),
  54. ("DDR2_Power", "DDR2 功耗", "power", "W"),
  55. ("DDR0_Curr", "DDR0 电流", "electrical", "A"),
  56. ("DDR2_Curr", "DDR2 电流", "electrical", "A"),
  57. ("P12V_DDR0", "P12V DDR0 电压", "electrical", "V"),
  58. ("P12V_DDR2", "P12V DDR2 电压", "electrical", "V"),
  59. ("PVCCD_CPU0_Input_Power", "PVCCD CPU0 功耗", "power", "W"),
  60. ("PVCCD_CPU1_Input_Power", "PVCCD CPU1 功耗", "power", "W"),
  61. ("Dimm_Power_CPU0", "PECI DIMM CPU0 功耗", "power", "W"),
  62. ("Dimm_Power_CPU1", "PECI DIMM CPU1 功耗", "power", "W"),
  63. ("CPU0_Power_Avg", "PECI CPU0 功耗", "power", "W"),
  64. ("CPU1_Power_Avg", "PECI CPU1 功耗", "power", "W"),
  65. ("PSU0_PIn", "PSU0 输入功耗", "power", "W"),
  66. ("PSU0_POut", "PSU0 输出功耗", "power", "W"),
  67. ]
  68. TEMPLATE_HEADERS: list[str] = (
  69. ["序号", "计时"]
  70. + [f"BMC{i}" for i in range(24)]
  71. + ["腔1前", "腔1后", "腔2前", "腔2后", "腔3前", "腔3后", "腔4前", "腔4后"]
  72. )
  73. CHAMBER_SENSORS: list[tuple[str, str, str, str]] = [
  74. ("ct1_ch1_front", "腔1前", "ch1", "front"),
  75. ("ct2_ch1_rear", "腔1后", "ch1", "rear"),
  76. ("ct3_ch2_front", "腔2前", "ch2", "front"),
  77. ("ct4_ch2_rear", "腔2后", "ch2", "rear"),
  78. ("ct5_ch3_front", "腔3前", "ch3", "front"),
  79. ("ct6_ch3_rear", "腔3后", "ch3", "rear"),
  80. ("ct7_ch4_front", "腔4前", "ch4", "front"),
  81. ("ct8_ch4_rear", "腔4后", "ch4", "rear"),
  82. ]
  83. CHAMBER_PAIRS: list[tuple[str, str, str, str]] = [
  84. ("ch1", "腔1", "ct1_ch1_front", "ct2_ch1_rear"),
  85. ("ch2", "腔2", "ct3_ch2_front", "ct4_ch2_rear"),
  86. ("ch3", "腔3", "ct5_ch3_front", "ct6_ch3_rear"),
  87. ("ch4", "腔4", "ct7_ch4_front", "ct8_ch4_rear"),
  88. ]
  89. REDFISH_TEMP_SENSORS: list[tuple[str, str]] = [
  90. ("rf_dimm_cpu0_a_c", "RF DIMM CPU0_A"),
  91. ("rf_dimm_cpu1_a_c", "RF DIMM CPU1_A"),
  92. ("rf_cpu0_c", "RF CPU0"),
  93. ("rf_cpu1_c", "RF CPU1"),
  94. ("rf_mb_c", "RF 主板 MB"),
  95. ("rf_psu0_c", "RF 电源 PSU0"),
  96. ("rf_pvccin_cpu0_c", "RF PVCCIN CPU0"),
  97. ("rf_pvccin_cpu1_c", "RF PVCCIN CPU1"),
  98. ("rf_pvccfa_cpu0_c", "RF PVCCFA CPU0"),
  99. ("rf_pvccfa_cpu1_c", "RF PVCCFA CPU1"),
  100. ("rf_pvccd_cpu0_c", "RF PVCCD CPU0"),
  101. ("rf_pvccd_cpu1_c", "RF PVCCD CPU1"),
  102. ]
  103. MT_CONSOLE_TEMP_SENSORS: list[tuple[str, str]] = [
  104. ("mt_spd_dimm0_c", "MT SPD DIMM0"),
  105. ("mt_spd_dimm1_c", "MT SPD DIMM1"),
  106. ("mt_cpu_c", "MT CPU"),
  107. ]
  108. POWER_RAIL_SENSORS: list[tuple[str, str]] = [
  109. ("rf_total_power_w", "整机功耗(W)"),
  110. ("rf_psu0_pin_w", "PSU0输入(W)"),
  111. ("rf_psu0_pout_w", "PSU0输出(W)"),
  112. ("rf_psu0_iin_a", "PSU0输入电流(A)"),
  113. ("rf_psu0_iout_a", "PSU0输出电流(A)"),
  114. ("rf_ddr0_power_w", "DDR0功耗(W)"),
  115. ("rf_ddr1_power_w", "DDR1功耗(W)"),
  116. ("rf_ddr2_power_w", "DDR2功耗(W)"),
  117. ("rf_ddr3_power_w", "DDR3功耗(W)"),
  118. ("rf_dimm_power_cpu0_w", "CPU0 DIMM功耗(W)"),
  119. ("rf_dimm_power_cpu1_w", "CPU1 DIMM功耗(W)"),
  120. ("rf_cpu0_power_avg_w", "CPU0功耗(W)"),
  121. ("rf_cpu1_power_avg_w", "CPU1功耗(W)"),
  122. ]
  123. FAN_ACTUATOR_SENSORS: list[tuple[str, str]] = [
  124. ("cmd_ptc_pct", "罩PTC(%)"),
  125. ("cmd_fan_front_pct", "罩前风扇(%)"),
  126. ("cmd_fan_rear_pct", "罩后风扇(%)"),
  127. ("cmd_ssr_pct", "罩SSR(%)"),
  128. ("rf_fan1_rpm", "FAN1(RPM)"),
  129. ("rf_fan2_rpm", "FAN2(RPM)"),
  130. ("rf_fan3_rpm", "FAN3(RPM)"),
  131. ("rf_fan4_rpm", "FAN4(RPM)"),
  132. ("rf_fan5_rpm", "FAN5(RPM)"),
  133. ("rf_pwm1_pct", "PWM1(%)"),
  134. ("rf_pwm2_pct", "PWM2(%)"),
  135. ("rf_pwm3_pct", "PWM3(%)"),
  136. ("rf_pwm4_pct", "PWM4(%)"),
  137. ("rf_pwm5_pct", "PWM5(%)"),
  138. ]
  139. CANONICAL_MT_NAMES: dict[int, str] = {
  140. 0: "Test 0 [Address test, walking ones, 1 CPU]",
  141. 1: "Test 1 [Address test, own address, 1 CPU]",
  142. 2: "Test 2 [Address test, own address]",
  143. 3: "Test 3 [Moving inversions, ones & zeroes]",
  144. 4: "Test 4 [Moving inversions, 8-bit pattern]",
  145. 5: "Test 5 [Moving inversions, random pattern]",
  146. 6: "Test 6 [Block move, 64-byte blocks]",
  147. 7: "Test 7 [Moving inversions, 32-bit pattern]",
  148. 8: "Test 8 [Random number sequence]",
  149. 9: "Test 9 [Modulo 20, ones & zeroes]",
  150. 10: "Test 10 [Bit fade test, 2 patterns]",
  151. 11: "Test 11 [Random number sequence, 64-bit]",
  152. 12: "Test 12 [Random number sequence, 128-bit]",
  153. 13: "Test 13 [Hammer test]",
  154. 14: "Test 14 [DMA test (experimental)]",
  155. 15: "Test 15 [March C algorithm]",
  156. 16: "Test 16 [Galloping Pattern (GALPAT)]",
  157. 17: "Test 17 [Galloping Pattern (LINEAR)]",
  158. 18: "Test 18 [Galloping Pattern (RANDOMADDRESS)]",
  159. 19: "Test 19 [Galloping Pattern (BANKJUMP)]",
  160. 20: "Test 20 [Galloping Pattern (VICTIM)]",
  161. 21: "Test 21 [Galloping Pattern (MARCHIC)]",
  162. 22: "Test 22 [Galloping Pattern (MARCHSSE)]",
  163. 23: "Test 23 [Galloping Pattern (BUTTERFLY)]",
  164. 24: "Test 24 [March SS+ algorithm]",
  165. 25: "Test 25 [StressApp memory stress test]",
  166. }
  167. ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
  168. ANSI_OTHER_RE = re.compile(r"\x1b[@-Z\\-_]")
  169. TEST_PREFIX_RE = re.compile(r"^Test\s+(\d+)\b")
  170. RUNNING_TEST_RE = re.compile(r"Running test #(\d+)\s*\((.+)\)\s*$")
  171. TEST_EXEC_RE = re.compile(
  172. r"MtSupportRunAllTests\s*-\s*Test execution time:\s*([0-9.]+)s\s*"
  173. r"\(Test\s+(\d+)\s+cumulative error count:\s*(\d+),\s*buffer full count:\s*(\d+)\)"
  174. )
  175. RANGE_WARN_RE = re.compile(
  176. r"RunMemoryRangeTest\s*-\s*\*\*WARNING\*\*\s*waited for\s*(\d+)s\s*for CPU\s*#(\d+)\s*to finish\s*\(BSP test time\s*=\s*(\d+)ms\)"
  177. )
  178. CONSOLE_DIMM_TEMP_RE = re.compile(r"^DIMM(\d+)\s+temperature:\s*([0-9.]+)C$")
  179. CONSOLE_CPU_TEMP_RE = re.compile(r"^Current CPU temperature:\s*([0-9.]+)C$")
  180. MEM_TIMINGS_RE = re.compile(r"Current mem timings:\s*(.+)$")
  181. SYS_BIOS_RE = re.compile(r"\[SYS_BIOS\](.+)$")
  182. HS_DRAM_RE = re.compile(r"\[(HS|HD)_DRAM\](.+)$")
  183. HS_CPU_RE = re.compile(r"\[(HS|HD)_CPU\]Processor Information Name:\s*(.+)$")
  184. TOTAL_MEM_RE = re.compile(r"Total Memory:\s*(.+)$")
  185. SMBIOS_BIOS_RE = re.compile(r"SMBIOS BIOS INFO\s+(.+)$")
  186. SMBIOS_SYS_RE = re.compile(r"SMBIOS SYSTEM INFO\s+(.+)$")
  187. SMBIOS_SLOT_SIZE_RE = re.compile(r"^\[Slot\s+(\d+)\].*?\bSize:\s*(-?\d+).*?\bSpeed:\s*(\d+)")
  188. SMBIOS_SLOT_LOC_RE = re.compile(
  189. r"^\[Slot\s+(\d+)\]\s*DeviceLocator:\s*([^,]+),\s*BankLocator:\s*([^,]+),\s*"
  190. r"Manufacturer:\s*([^,]*),\s*S/N:\s*([^,]*),\s*AssetTag:\s*([^,]*),\s*PartNumber:\s*(.*)$"
  191. )
  192. def bmc_slot_label(idx: int) -> str:
  193. cpu = 0 if idx < 12 else 1
  194. ch = chr(ord("A") + (idx % 12))
  195. return f"BMC{idx} (CPU{cpu}_{ch})"
  196. def strip_ansi(text: str) -> str:
  197. text = ANSI_CSI_RE.sub("", text)
  198. return ANSI_OTHER_RE.sub("", text)
  199. def normalize_algorithm_name(raw: str, console_map: dict[int, str] | None = None) -> str:
  200. s = (raw or "").strip()
  201. if not s:
  202. return ""
  203. m = TEST_PREFIX_RE.match(s)
  204. if m:
  205. tnum = int(m.group(1))
  206. if console_map and tnum in console_map:
  207. return console_map[tnum]
  208. if s.count("(") > s.count(")") or s.count("[") > s.count("]"):
  209. if tnum in CANONICAL_MT_NAMES:
  210. return CANONICAL_MT_NAMES[tnum]
  211. fixed = s
  212. if fixed.count("(") > fixed.count(")"):
  213. fixed += ")" * (fixed.count("(") - fixed.count(")"))
  214. if fixed.count("[") > fixed.count("]"):
  215. fixed += "]" * (fixed.count("[") - fixed.count("]"))
  216. return fixed
  217. return s
  218. def _to_int(val: Any) -> int | None:
  219. if val is None:
  220. return None
  221. s = str(val).strip()
  222. if not s:
  223. return None
  224. try:
  225. return int(s)
  226. except ValueError:
  227. try:
  228. return int(float(s))
  229. except ValueError:
  230. return None
  231. def _to_float(val: Any) -> float | None:
  232. if val is None:
  233. return None
  234. s = str(val).strip()
  235. if not s:
  236. return None
  237. try:
  238. f = float(s)
  239. if f != f:
  240. return None
  241. return f
  242. except ValueError:
  243. return None
  244. def _fmt_hms(seconds: float) -> str:
  245. sec = max(0, int(round(seconds)))
  246. h, rem = divmod(sec, 3600)
  247. m, s = divmod(rem, 60)
  248. return f"{h}:{m:02d}:{s:02d}"
  249. def _sensor_stats(vals: list[float], digits: int = 2) -> dict[str, float | int] | None:
  250. """Exact per-sensor statistics without computing averages."""
  251. if not vals:
  252. return None
  253. s_val = round(vals[0], digits)
  254. e_val = round(vals[-1], digits)
  255. mn = round(min(vals), digits)
  256. mx = round(max(vals), digits)
  257. return {
  258. "count": len(vals),
  259. "start": s_val,
  260. "end": e_val,
  261. "min": mn,
  262. "max": mx,
  263. "delta": round(e_val - s_val, digits),
  264. "span": round(mx - mn, digits),
  265. }
  266. def _round_opt(val: float | None, digits: int = 2) -> float | None:
  267. return None if val is None else round(val, digits)
  268. class VirtualStation:
  269. """Uniform read-only accessor for a station folder in a directory or zip archive."""
  270. def __init__(self, station_key: str, files: dict[str, tuple[str, zipfile.ZipFile | None, Path | None]]):
  271. self.station_key = station_key
  272. self._files = files
  273. def list_files(self, suffix: str = "") -> list[str]:
  274. names = sorted(self._files.keys())
  275. if suffix:
  276. names = [n for n in names if n.endswith(suffix)]
  277. return names
  278. def exists(self, name: str) -> bool:
  279. return name in self._files
  280. def read_bytes(self, name: str) -> bytes:
  281. member, zf, lp = self._files[name]
  282. if lp is not None:
  283. return lp.read_bytes()
  284. assert zf is not None
  285. return zf.read(member)
  286. def read_text(self, name: str) -> str:
  287. return self.read_bytes(name).decode("utf-8", errors="replace")
  288. @dataclass
  289. class BundleSource:
  290. input_path: Path
  291. source_kind: str
  292. stations: dict[str, VirtualStation]
  293. _zip_handle: zipfile.ZipFile | None = None
  294. def close(self) -> None:
  295. if self._zip_handle is not None:
  296. self._zip_handle.close()
  297. self._zip_handle = None
  298. def __enter__(self) -> "BundleSource":
  299. return self
  300. def __exit__(self, *args: Any) -> None:
  301. self.close()
  302. def _looks_like_station_files(names: set[str]) -> bool:
  303. markers = ("master_continuous_comprehensive.csv", "master_events.jsonl", "live_status.json", "master_console.log")
  304. if any(m in names for m in markers):
  305. return True
  306. return any(n.endswith("_comprehensive.csv") or n.endswith("_template.csv") for n in names)
  307. def open_bundle_source(input_path: str | Path) -> BundleSource:
  308. p = Path(input_path).resolve()
  309. if not p.exists():
  310. raise FileNotFoundError(f"Input path does not exist: {p}")
  311. if p.is_file() and p.suffix.lower() == ".zip":
  312. zf = zipfile.ZipFile(p, "r")
  313. by_dir: dict[str, dict[str, tuple[str, zipfile.ZipFile | None, Path | None]]] = {}
  314. root_files: dict[str, str] = {}
  315. for info in zf.infolist():
  316. if info.is_dir():
  317. continue
  318. posix = PurePosixPath(info.filename)
  319. parts = [part for part in posix.parts if part not in ("", ".")]
  320. if not parts:
  321. continue
  322. if len(parts) == 1:
  323. root_files[parts[0]] = info.filename
  324. else:
  325. parent = "/".join(parts[:-1])
  326. by_dir.setdefault(parent, {})[parts[-1]] = (info.filename, zf, None)
  327. stations: dict[str, VirtualStation] = {}
  328. if _looks_like_station_files(set(root_files.keys())):
  329. sfiles = {fname: (member, zf, None) for fname, member in root_files.items()}
  330. stations[p.stem] = VirtualStation(p.stem, sfiles)
  331. else:
  332. for dpath, fdict in sorted(by_dir.items()):
  333. if _looks_like_station_files(set(fdict.keys())):
  334. skey = PurePosixPath(dpath).name
  335. stations[skey] = VirtualStation(skey, fdict)
  336. if not stations:
  337. zf.close()
  338. raise ValueError(f"No station telemetry directories found in zip archive: {p}")
  339. return BundleSource(input_path=p, source_kind="zip", stations=stations, _zip_handle=zf)
  340. if not p.is_dir():
  341. raise ValueError(f"Unsupported input (expected directory or .zip): {p}")
  342. top_files = {c.name for c in p.iterdir() if c.is_file()}
  343. if _looks_like_station_files(top_files):
  344. sfiles = {c.name: (c.name, None, c) for c in p.iterdir() if c.is_file()}
  345. return BundleSource(
  346. input_path=p,
  347. source_kind="single_dir",
  348. stations={p.name: VirtualStation(p.name, sfiles)},
  349. )
  350. stations = {}
  351. for sub in sorted(c for c in p.iterdir() if c.is_dir()):
  352. sub_files = {f.name: (f.name, None, f) for f in sub.iterdir() if f.is_file()}
  353. if _looks_like_station_files(set(sub_files.keys())):
  354. stations[sub.name] = VirtualStation(sub.name, sub_files)
  355. if not stations:
  356. raise ValueError(f"No station subdirectories or telemetry files found in: {p}")
  357. return BundleSource(input_path=p, source_kind="multi_dir", stations=stations)
  358. def audit_template_csv(
  359. raw_bytes: bytes,
  360. comp_rows: list[dict[str, Any]] | None = None,
  361. ) -> dict[str, Any]:
  362. has_bom = raw_bytes.startswith(b"\xef\xbb\xbf")
  363. has_crlf = b"\r\n" in raw_bytes and b"\n" not in raw_bytes.replace(b"\r\n", b"")
  364. text = raw_bytes.decode("utf-8-sig", errors="replace")
  365. reader = csv.reader(io.StringIO(text, newline=""))
  366. all_rows = list(reader)
  367. if not all_rows:
  368. return {
  369. "rows": 0,
  370. "has_bom": has_bom,
  371. "has_crlf": has_crlf,
  372. "header_match": False,
  373. "col_count_34": False,
  374. "seq_contiguous": False,
  375. "non_zero_bmc_channels": [],
  376. "value_mismatches_vs_comprehensive": None,
  377. "status": "FAIL",
  378. }
  379. header = all_rows[0]
  380. data_rows = all_rows[1:]
  381. header_match = header == TEMPLATE_HEADERS
  382. col_count_34 = all(len(r) == 34 for r in data_rows)
  383. seq_contiguous = True
  384. non_zero_bmc: set[int] = set()
  385. parsed_rows: list[tuple[int, str, list[int], list[int]]] = []
  386. for idx, row in enumerate(data_rows, start=1):
  387. if len(row) != 34:
  388. seq_contiguous = False
  389. continue
  390. seq = _to_int(row[0])
  391. if seq != idx:
  392. seq_contiguous = False
  393. bmcs = [_to_int(row[2 + i]) or 0 for i in range(24)]
  394. for i, v in enumerate(bmcs):
  395. if v != 0:
  396. non_zero_bmc.add(i)
  397. cts = [_to_int(row[26 + i]) or 0 for i in range(8)]
  398. parsed_rows.append((seq if seq is not None else -1, row[1], bmcs, cts))
  399. mismatches: int | None = None
  400. if comp_rows is not None:
  401. mismatches = 0
  402. if len(comp_rows) != len(parsed_rows):
  403. mismatches += abs(len(comp_rows) - len(parsed_rows))
  404. for (seq, hms, bmcs, cts), crow in zip(parsed_rows, comp_rows):
  405. if seq != _to_int(crow.get("seq")) or hms != str(crow.get("elapsed_hms") or "").strip():
  406. mismatches += 1
  407. bmc_list = crow.get("bmc24_raw")
  408. for i in range(24):
  409. raw_v = bmc_list[i] if isinstance(bmc_list, list) and len(bmc_list) == 24 else _to_int(crow.get(f"mcu_bmc{i}_raw"))
  410. expected = 0 if (raw_v is None or raw_v == 255) else int(raw_v)
  411. if bmcs[i] != expected:
  412. mismatches += 1
  413. c_ct8 = crow.get("ct8")
  414. if not (isinstance(c_ct8, list) and len(c_ct8) == 8):
  415. c_ct8 = [_to_int(crow.get(col)) for col, _, _, _ in CHAMBER_SENSORS]
  416. for i in range(8):
  417. if cts[i] != (c_ct8[i] or 0):
  418. mismatches += 1
  419. ok = has_bom and has_crlf and header_match and col_count_34 and seq_contiguous and (mismatches in (None, 0))
  420. return {
  421. "rows": len(data_rows),
  422. "has_bom": has_bom,
  423. "has_crlf": has_crlf,
  424. "header_match": header_match,
  425. "col_count_34": col_count_34,
  426. "seq_contiguous": seq_contiguous,
  427. "non_zero_bmc_channels": sorted(non_zero_bmc),
  428. "value_mismatches_vs_comprehensive": mismatches,
  429. "status": "PASS" if ok else "WARN",
  430. }
  431. def parse_comprehensive_csv(
  432. raw_bytes: bytes,
  433. console_algo_map: dict[int, str] | None = None,
  434. ) -> dict[str, Any]:
  435. has_bom = raw_bytes.startswith(b"\xef\xbb\xbf")
  436. has_crlf = b"\r\n" in raw_bytes
  437. text = raw_bytes.decode("utf-8-sig", errors="replace")
  438. reader = csv.DictReader(io.StringIO(text, newline=""))
  439. fieldnames = list(reader.fieldnames or [])
  440. col_count = len(fieldnames)
  441. if col_count == 115 and "station_id" not in fieldnames:
  442. schema_version = "v1_115col"
  443. elif col_count >= 117 and "station_id" in fieldnames and "bmc_host" in fieldnames:
  444. schema_version = "v2_117col" if col_count == 117 else f"v2_{col_count}col"
  445. else:
  446. schema_version = f"custom_{col_count}col"
  447. rows: list[dict[str, Any]] = []
  448. seq_contiguous = True
  449. prev_unix: int | None = None
  450. gaps_over_2s: list[dict[str, Any]] = []
  451. dt_samples: list[int] = []
  452. mcu_offline_rows = 0
  453. cpld_lost_rows = 0
  454. server_power_non_on = 0
  455. for idx, raw in enumerate(reader, start=1):
  456. seq = _to_int(raw.get("seq"))
  457. if seq != idx:
  458. seq_contiguous = False
  459. unix_ms = _to_int(raw.get("unix_ms"))
  460. if unix_ms is not None and prev_unix is not None:
  461. dt = unix_ms - prev_unix
  462. dt_samples.append(dt)
  463. if dt > 2000:
  464. gaps_over_2s.append({
  465. "seq": seq,
  466. "timestamp_cst": raw.get("timestamp_cst", ""),
  467. "gap_ms": dt,
  468. })
  469. if unix_ms is not None:
  470. prev_unix = unix_ms
  471. mcu_online = _to_int(raw.get("mcu_online"))
  472. if mcu_online != 1:
  473. mcu_offline_rows += 1
  474. cpld_lost = _to_int(raw.get("mcu_cpld_lost"))
  475. if cpld_lost not in (None, 0):
  476. cpld_lost_rows += 1
  477. srv_pwr = (raw.get("server_power") or "").strip()
  478. if srv_pwr and srv_pwr != "on":
  479. server_power_non_on += 1
  480. ct8 = [_to_int(raw.get(col)) for col, _, _, _ in CHAMBER_SENSORS]
  481. bmc24_raw = [_to_int(raw.get(f"mcu_bmc{i}_raw")) for i in range(24)]
  482. raw_algo = (raw.get("active_algorithm") or "").strip()
  483. norm_algo = normalize_algorithm_name(raw_algo, console_algo_map)
  484. rec: dict[str, Any] = {
  485. "seq": seq,
  486. "timestamp_cst": (raw.get("timestamp_cst") or "").strip(),
  487. "unix_ms": unix_ms,
  488. "elapsed_s": _to_float(raw.get("elapsed_s")),
  489. "elapsed_hms": (raw.get("elapsed_hms") or "").strip(),
  490. "test_phase": (raw.get("test_phase") or "").strip(),
  491. "station_id": (raw.get("station_id") or "").strip(),
  492. "bmc_host": (raw.get("bmc_host") or "").strip(),
  493. "server_power": srv_pwr,
  494. "firmware_phase": (raw.get("firmware_phase") or "").strip(),
  495. "active_algorithm_raw": raw_algo,
  496. "active_algorithm": norm_algo,
  497. "mt_test_num": _to_int(raw.get("mt_test_num")),
  498. "mt_pass_num": _to_int(raw.get("mt_pass_num")),
  499. "mt_mem_range": (raw.get("mt_mem_range") or "").strip(),
  500. "mt_timings": (raw.get("mt_timings") or "").strip(),
  501. "mt_cum_errors": _to_int(raw.get("mt_cum_errors")) or 0,
  502. "mt_last_completed_test": (raw.get("mt_last_completed_test") or "").strip(),
  503. "mt_last_test_exec_s": _to_float(raw.get("mt_last_test_exec_s")),
  504. "mcu_online": mcu_online,
  505. "mcu_mode": (raw.get("mcu_mode") or "").strip(),
  506. "mcu_flags_hex": (raw.get("mcu_flags_hex") or "").strip(),
  507. "mcu_cpld_lost": cpld_lost,
  508. "mcu_target_c": _to_float(raw.get("mcu_target_c")),
  509. "mcu_f0_seq": _to_int(raw.get("mcu_f0_seq")),
  510. "mcu_pid_kp": _to_float(raw.get("mcu_pid_kp")),
  511. "mcu_pid_ki": _to_float(raw.get("mcu_pid_ki")),
  512. "mcu_pid_kd": _to_float(raw.get("mcu_pid_kd")),
  513. "ct8": ct8,
  514. "ct_min": _to_float(raw.get("ct_min")),
  515. "ct_max": _to_float(raw.get("ct_max")),
  516. "bmc24_raw": bmc24_raw,
  517. "is_residual_prelaunch": False,
  518. }
  519. for col, _, _, _ in CHAMBER_SENSORS:
  520. rec[col] = _to_float(raw.get(col))
  521. for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS:
  522. rec[col] = _to_float(raw.get(col))
  523. rows.append(rec)
  524. return {
  525. "schema_version": schema_version,
  526. "col_count": col_count,
  527. "fieldnames": fieldnames,
  528. "has_bom": has_bom,
  529. "has_crlf": has_crlf,
  530. "seq_contiguous": seq_contiguous,
  531. "dt_ms_median": round(statistics.median(dt_samples), 1) if dt_samples else None,
  532. "dt_ms_max": max(dt_samples) if dt_samples else None,
  533. "gaps_over_2s": gaps_over_2s,
  534. "mcu_offline_rows": mcu_offline_rows,
  535. "cpld_lost_rows": cpld_lost_rows,
  536. "server_power_non_on": server_power_non_on,
  537. "rows": rows,
  538. }
  539. def parse_events_jsonl(raw_text: str) -> dict[str, Any]:
  540. events: list[dict[str, Any]] = []
  541. parse_errors = 0
  542. for line in raw_text.splitlines():
  543. s = line.strip()
  544. if not s:
  545. continue
  546. try:
  547. ev = json.loads(s)
  548. if isinstance(ev, dict):
  549. events.append(ev)
  550. else:
  551. parse_errors += 1
  552. except json.JSONDecodeError:
  553. parse_errors += 1
  554. suite_init = None
  555. suite_complete = []
  556. antirebound_soaks = []
  557. preheat_handovers = []
  558. cooldown_outcomes = []
  559. mt_launches = []
  560. mt_algo_starts = []
  561. mt_algo_dones = []
  562. mcu_cmds = []
  563. phase_starts = []
  564. kind_counts: dict[str, int] = {}
  565. open_fan_round: dict[tuple[str, int], dict[str, Any]] = {}
  566. open_soak_round: dict[tuple[str, int], dict[str, Any]] = {}
  567. for ev in events:
  568. kind = str(ev.get("kind") or "unknown")
  569. kind_counts[kind] = kind_counts.get(kind, 0) + 1
  570. phase = str(ev.get("phase") or "")
  571. phase_group = re.sub(r"_(fan\d+_round\d+|antirebound_soak_round\d+)$", "", phase)
  572. if kind == "suite_init" and suite_init is None:
  573. suite_init = ev
  574. elif kind == "phase_start":
  575. phase_starts.append(ev)
  576. elif kind == "cooldown_fan_start":
  577. rnd = int(ev.get("round") or 0)
  578. open_fan_round[(phase_group, rnd)] = {
  579. "phase_group": phase_group,
  580. "round": rnd,
  581. "fan_pct": ev.get("fan_pct"),
  582. "start_time_cst": ev.get("time_cst"),
  583. "start_unix_ms": ev.get("unix_ms"),
  584. "outcome": "in_progress",
  585. }
  586. elif kind in ("cooldown_target_reached", "cooldown_timeout"):
  587. rnd = int(ev.get("round") or 0)
  588. rec = open_fan_round.pop((phase_group, rnd), {"phase_group": phase_group, "round": rnd})
  589. rec["outcome"] = "target_reached" if kind == "cooldown_target_reached" else "timeout"
  590. rec["end_time_cst"] = ev.get("time_cst")
  591. rec["end_unix_ms"] = ev.get("unix_ms")
  592. if rec.get("start_unix_ms") and ev.get("unix_ms"):
  593. rec["duration_s"] = round((ev["unix_ms"] - rec["start_unix_ms"]) / 1000.0, 2)
  594. elif "elapsed_s" in ev:
  595. rec["duration_s"] = round(float(ev["elapsed_s"]), 2)
  596. rec["ct_max"] = ev.get("ct_max")
  597. rec["dimm_max"] = ev.get("dimm_max")
  598. cooldown_outcomes.append(rec)
  599. elif kind == "antirebound_soak_start":
  600. rnd = int(ev.get("round") or 0)
  601. open_soak_round[(phase_group, rnd)] = {
  602. "start_unix_ms": ev.get("unix_ms"),
  603. "soak_sec": ev.get("soak_sec"),
  604. }
  605. elif kind == "antirebound_soak_result":
  606. rnd = int(ev.get("round") or 0)
  607. soak_meta = open_soak_round.pop((phase_group, rnd), {})
  608. norm = dict(ev)
  609. norm["phase_group"] = phase_group
  610. norm["start_unix_ms"] = soak_meta.get("start_unix_ms")
  611. norm["soak_sec"] = soak_meta.get("soak_sec")
  612. norm["max_rebound_norm"] = ev.get("max_rebound") if ev.get("max_rebound") is not None else ev.get("rebound_delta")
  613. norm["base_ct_norm"] = ev.get("base_ct_max") if ev.get("base_ct_max") is not None else ev.get("base_ct")
  614. norm["peak_ct_norm"] = ev.get("peak_ct_max") if ev.get("peak_ct_max") is not None else ev.get("peak_ct")
  615. antirebound_soaks.append(norm)
  616. elif kind == "test1_pid_handover":
  617. preheat_handovers.append(ev)
  618. elif kind == "mt_launched":
  619. mt_launches.append(ev)
  620. elif kind == "mt_algo_start":
  621. ev_norm = dict(ev)
  622. ev_norm["algorithm_norm"] = normalize_algorithm_name(str(ev.get("algorithm") or ""))
  623. mt_algo_starts.append(ev_norm)
  624. elif kind == "mt_algo_done":
  625. mt_algo_dones.append(ev)
  626. elif kind == "mcu_cmd":
  627. mcu_cmds.append(ev)
  628. elif kind == "suite_complete":
  629. suite_complete.append(ev)
  630. for rec in open_fan_round.values():
  631. cooldown_outcomes.append(rec)
  632. cooldown_outcomes.sort(key=lambda r: (r.get("start_unix_ms") or 0, r.get("round") or 0))
  633. return {
  634. "event_count": len(events),
  635. "parse_errors": parse_errors,
  636. "kind_counts": kind_counts,
  637. "events": events,
  638. "suite_init": suite_init,
  639. "phase_starts": phase_starts,
  640. "cooldown_outcomes": cooldown_outcomes,
  641. "antirebound_soaks": antirebound_soaks,
  642. "preheat_handovers": preheat_handovers,
  643. "mt_launches": mt_launches,
  644. "mt_algo_starts": mt_algo_starts,
  645. "mt_algo_dones": mt_algo_dones,
  646. "mcu_cmds": mcu_cmds,
  647. "suite_complete": suite_complete,
  648. }
  649. def _parse_kv_fields(text: str) -> dict[str, str]:
  650. out: dict[str, str] = {}
  651. for part in text.split(","):
  652. if ":" in part:
  653. k, v = part.split(":", 1)
  654. out[k.strip()] = v.strip()
  655. return out
  656. def parse_console_log(raw_text: str, filename: str = "") -> dict[str, Any]:
  657. cleaned = strip_ansi(raw_text)
  658. lines = cleaned.splitlines()
  659. bios_versions: list[str] = []
  660. smbios_bios: str | None = None
  661. smbios_system: str | None = None
  662. cpu_names: list[str] = []
  663. total_memories: list[str] = []
  664. mem_timings: list[str] = []
  665. dram_entries: dict[str, dict[str, str]] = {}
  666. smbios_slots: dict[int, dict[str, Any]] = {}
  667. mt_config: dict[str, str] = {}
  668. algo_names_by_num: dict[int, str] = {}
  669. running_tests: list[dict[str, Any]] = []
  670. completed_tests: list[dict[str, Any]] = []
  671. range_warnings: list[dict[str, Any]] = []
  672. dimm0_temps: list[float] = []
  673. dimm1_temps: list[float] = []
  674. cpu_temps: list[float] = []
  675. real_errors: list[str] = []
  676. for ln in lines:
  677. s = ln.strip()
  678. if not s:
  679. continue
  680. if "[SYS_BIOS]" in s:
  681. m = SYS_BIOS_RE.search(s)
  682. if m and m.group(1).strip() not in bios_versions:
  683. bios_versions.append(m.group(1).strip())
  684. elif "SMBIOS BIOS INFO" in s:
  685. m = SMBIOS_BIOS_RE.search(s)
  686. if m and not smbios_bios:
  687. smbios_bios = m.group(1).strip()
  688. elif "SMBIOS SYSTEM INFO" in s:
  689. m = SMBIOS_SYS_RE.search(s)
  690. if m and not smbios_system:
  691. smbios_system = m.group(1).strip()
  692. elif "Processor Information Name:" in s:
  693. m = HS_CPU_RE.search(s)
  694. if m:
  695. val = m.group(2).strip()
  696. if val not in cpu_names:
  697. cpu_names.append(val)
  698. elif "Total Memory:" in s:
  699. m = TOTAL_MEM_RE.search(s)
  700. if m:
  701. val = m.group(1).strip()
  702. if val not in total_memories:
  703. total_memories.append(val)
  704. elif "Current mem timings:" in s:
  705. m = MEM_TIMINGS_RE.search(s)
  706. if m:
  707. val = m.group(1).strip()
  708. if val not in mem_timings:
  709. mem_timings.append(val)
  710. elif "_DRAM]" in s:
  711. m = HS_DRAM_RE.search(s)
  712. if m:
  713. kv = _parse_kv_fields(m.group(2))
  714. loc = kv.get("DimmLocation") or f"S{kv.get('Socket','?')}_C{kv.get('Channel','?')}_D{kv.get('Dimm','?')}"
  715. dram_entries[loc] = kv
  716. elif s.startswith("[Slot "):
  717. ms = SMBIOS_SLOT_SIZE_RE.match(s)
  718. if ms:
  719. slot = int(ms.group(1))
  720. size = int(ms.group(2))
  721. speed = int(ms.group(3))
  722. if size > 0:
  723. smbios_slots.setdefault(slot, {})["size_mb"] = size
  724. smbios_slots[slot]["speed_mt_s"] = speed
  725. ml = SMBIOS_SLOT_LOC_RE.match(s)
  726. if ml:
  727. slot = int(ml.group(1))
  728. if slot in smbios_slots:
  729. smbios_slots[slot].update({
  730. "device_locator": ml.group(2).strip(),
  731. "bank_locator": ml.group(3).strip(),
  732. "manufacturer": ml.group(4).strip(),
  733. "sn": ml.group(5).strip(),
  734. "part_number": ml.group(7).strip(),
  735. })
  736. elif s.startswith("[CONFIG] ") and ":" in s:
  737. key, val = s[9:].split(":", 1)
  738. k_clean = key.strip()
  739. if not k_clean.startswith("Unknown line"):
  740. mt_config[k_clean] = val.strip()
  741. mr = RUNNING_TEST_RE.search(s)
  742. if mr:
  743. tnum = int(mr.group(1))
  744. aname = mr.group(2).strip()
  745. algo_names_by_num[tnum] = aname
  746. running_tests.append({"test_num": tnum, "algorithm": aname})
  747. continue
  748. me = TEST_EXEC_RE.search(s)
  749. if me:
  750. exec_s = float(me.group(1))
  751. tnum = int(me.group(2))
  752. err_cnt = int(me.group(3))
  753. buf_full = int(me.group(4))
  754. completed_tests.append({
  755. "test_num": tnum,
  756. "exec_s": exec_s,
  757. "cum_errors": err_cnt,
  758. "buffer_full_count": buf_full,
  759. })
  760. if err_cnt > 0:
  761. real_errors.append(s)
  762. continue
  763. mw = RANGE_WARN_RE.search(s)
  764. if mw:
  765. range_warnings.append({
  766. "wait_s": int(mw.group(1)),
  767. "cpu_id": int(mw.group(2)),
  768. "bsp_time_ms": int(mw.group(3)),
  769. })
  770. continue
  771. md = CONSOLE_DIMM_TEMP_RE.match(s)
  772. if md:
  773. idx = int(md.group(1))
  774. val = float(md.group(2))
  775. if idx == 0:
  776. dimm0_temps.append(val)
  777. elif idx == 1:
  778. dimm1_temps.append(val)
  779. continue
  780. mc = CONSOLE_CPU_TEMP_RE.match(s)
  781. if mc:
  782. cpu_temps.append(float(mc.group(1)))
  783. continue
  784. if (
  785. ("Test Complete" in s and "0 Errors" not in s)
  786. or "Error Confidence" in s
  787. or re.search(r"\bTest\s+\d+.*?\bFAIL\b", s)
  788. or re.search(r"ECC\s+(Uncorrectable|Correctable)\s+Error", s, re.IGNORECASE)
  789. ):
  790. real_errors.append(s)
  791. return {
  792. "filename": filename,
  793. "bytes": len(raw_text.encode("utf-8", errors="replace")),
  794. "lines": len(lines),
  795. "bios_versions": bios_versions,
  796. "smbios_bios": smbios_bios,
  797. "smbios_system": smbios_system,
  798. "cpu_names": cpu_names,
  799. "total_memories": total_memories,
  800. "mem_timings": mem_timings,
  801. "dram_entries": list(dram_entries.values()),
  802. "smbios_populated_slots": [{"slot": k, **v} for k, v in sorted(smbios_slots.items())],
  803. "mt_config": mt_config,
  804. "algo_names_by_num": algo_names_by_num,
  805. "running_tests": running_tests,
  806. "completed_tests": completed_tests,
  807. "range_warnings_count": len(range_warnings),
  808. "range_warnings_max_cpu": max((w["cpu_id"] for w in range_warnings), default=None),
  809. "range_warnings_max_bsp_ms": max((w["bsp_time_ms"] for w in range_warnings), default=None),
  810. "console_dimm0_temp": _sensor_stats(dimm0_temps, 2),
  811. "console_dimm1_temp": _sensor_stats(dimm1_temps, 2),
  812. "console_cpu_temp": _sensor_stats(cpu_temps, 2),
  813. "real_errors": real_errors,
  814. }
  815. def _discover_active_bmc_channels(rows: list[dict[str, Any]]) -> list[int]:
  816. active: list[int] = []
  817. for i in range(24):
  818. if any(r["bmc24_raw"][i] not in (None, 255) for r in rows):
  819. active.append(i)
  820. return active
  821. def _compute_individual_sensor_block(
  822. rows: list[dict[str, Any]],
  823. active_bmc_channels: list[int],
  824. ) -> dict[str, Any]:
  825. """Compute start/end/min/max/delta/span for every chamber & position sensor individually."""
  826. chamber_sensors: dict[str, Any] = {}
  827. for col, zh_label, ch_id, side in CHAMBER_SENSORS:
  828. vals = [r[col] for r in rows if r.get(col) is not None]
  829. st = _sensor_stats(vals, 2)
  830. if st is not None:
  831. st["label"] = zh_label
  832. st["chamber"] = ch_id
  833. st["side"] = side
  834. chamber_sensors[col] = st
  835. chambers_paired: dict[str, Any] = {}
  836. for ch_id, ch_label, f_col, r_col in CHAMBER_PAIRS:
  837. diffs = [
  838. r[f_col] - r[r_col]
  839. for r in rows
  840. if r.get(f_col) is not None and r.get(r_col) is not None
  841. ]
  842. chambers_paired[ch_id] = {
  843. "label": ch_label,
  844. "front": chamber_sensors[f_col],
  845. "rear": chamber_sensors[r_col],
  846. "front_minus_rear": _sensor_stats(diffs, 2),
  847. }
  848. bmc_channels: dict[str, Any] = {}
  849. for idx in active_bmc_channels:
  850. vals = [float(r["bmc24_raw"][idx]) for r in rows if r["bmc24_raw"][idx] not in (None, 255)]
  851. st = _sensor_stats(vals, 2)
  852. if st is not None:
  853. st["label"] = bmc_slot_label(idx)
  854. st["channel_idx"] = idx
  855. bmc_channels[f"BMC{idx}"] = st
  856. redfish_temps: dict[str, Any] = {}
  857. for col, label in REDFISH_TEMP_SENSORS:
  858. vals = [r[col] for r in rows if r.get(col) is not None]
  859. st = _sensor_stats(vals, 2)
  860. if st is not None:
  861. st["label"] = label
  862. redfish_temps[col] = st
  863. mt_console_temps: dict[str, Any] = {}
  864. for col, label in MT_CONSOLE_TEMP_SENSORS:
  865. vals = [r[col] for r in rows if r.get(col) is not None]
  866. st = _sensor_stats(vals, 2)
  867. if st is not None:
  868. st["label"] = label
  869. mt_console_temps[col] = st
  870. power_rails: dict[str, Any] = {}
  871. for col, label in POWER_RAIL_SENSORS:
  872. vals = [r[col] for r in rows if r.get(col) is not None]
  873. st = _sensor_stats(vals, 2)
  874. if st is not None:
  875. st["label"] = label
  876. power_rails[col] = st
  877. fans_and_actuators: dict[str, Any] = {}
  878. for col, label in FAN_ACTUATOR_SENSORS:
  879. vals = [r[col] for r in rows if r.get(col) is not None]
  880. st = _sensor_stats(vals, 1 if "pct" in col else 0)
  881. if st is not None:
  882. st["label"] = label
  883. fans_and_actuators[col] = st
  884. return {
  885. "chamber_sensors": chamber_sensors,
  886. "chambers": chambers_paired,
  887. "bmc_channels": bmc_channels,
  888. "redfish_temps": redfish_temps,
  889. "mt_console_temps": mt_console_temps,
  890. "power_rails": power_rails,
  891. "fans_and_actuators": fans_and_actuators,
  892. }
  893. def _compute_phase_metrics(
  894. rows: list[dict[str, Any]],
  895. active_bmc_channels: list[int],
  896. ) -> dict[str, Any]:
  897. if not rows:
  898. return {"rows": 0}
  899. mcu_modes: dict[str, int] = {}
  900. for r in rows:
  901. m = r["mcu_mode"] or "unknown"
  902. mcu_modes[m] = mcu_modes.get(m, 0) + 1
  903. duration_hms = rows[-1]["elapsed_hms"] or _fmt_hms(
  904. ((rows[-1]["unix_ms"] or 0) - (rows[0]["unix_ms"] or 0)) / 1000.0
  905. )
  906. sensors = _compute_individual_sensor_block(rows, active_bmc_channels)
  907. return {
  908. "rows": len(rows),
  909. "start_time_cst": rows[0]["timestamp_cst"],
  910. "end_time_cst": rows[-1]["timestamp_cst"],
  911. "duration_hms": duration_hms,
  912. "mcu_modes": mcu_modes,
  913. "mt_cum_errors": max(r["mt_cum_errors"] for r in rows),
  914. **sensors,
  915. }
  916. def _mark_residual_prelaunch_rows(
  917. rows: list[dict[str, Any]],
  918. mt_launch_unix_ms: int | None = None,
  919. ) -> int:
  920. residual_count = 0
  921. for r in rows:
  922. algo = r["active_algorithm_raw"]
  923. fw = r["firmware_phase"]
  924. if algo == "MemTest86 Launching" or fw == "mt":
  925. break
  926. if mt_launch_unix_ms is not None and r["unix_ms"] is not None and r["unix_ms"] >= mt_launch_unix_ms:
  927. break
  928. if TEST_PREFIX_RE.match(algo) and fw != "mt":
  929. r["is_residual_prelaunch"] = True
  930. residual_count += 1
  931. elif algo.startswith("UEFI Shell Idle"):
  932. continue
  933. else:
  934. break
  935. return residual_count
  936. def _aggregate_algorithms(
  937. rows: list[dict[str, Any]],
  938. active_bmc_channels: list[int],
  939. *,
  940. console_exec_by_test: dict[int, list[float]] | None = None,
  941. event_exec_by_test: dict[int, list[float]] | None = None,
  942. ) -> dict[str, dict[str, Any]]:
  943. grouped: dict[str, list[dict[str, Any]]] = {}
  944. for r in rows:
  945. if r.get("is_residual_prelaunch"):
  946. continue
  947. key = r["active_algorithm"] or r["active_algorithm_raw"] or "Unknown"
  948. grouped.setdefault(key, []).append(r)
  949. result: dict[str, dict[str, Any]] = {}
  950. for algo, grows in grouped.items():
  951. m = TEST_PREFIX_RE.match(algo)
  952. tnum = int(m.group(1)) if m else None
  953. sensors = _compute_individual_sensor_block(grows, active_bmc_channels)
  954. # Instantaneous simultaneous DDR0 vs DDR2 asymmetry (no mean!)
  955. inst_ratios: list[float] = []
  956. for r in grows:
  957. d0_v = r.get("rf_ddr0_power_w")
  958. d2_v = r.get("rf_ddr2_power_w")
  959. if d0_v is not None and d2_v is not None and min(d0_v, d2_v) > 0.5:
  960. inst_ratios.append(max(d0_v, d2_v) / min(d0_v, d2_v))
  961. asym_ratio = round(max(inst_ratios), 2) if inst_ratios else None
  962. asym_seconds = sum(1 for x in inst_ratios if x >= 1.5)
  963. is_asym = bool(
  964. asym_ratio is not None
  965. and asym_ratio >= 1.8
  966. and (asym_seconds >= 3 or len(grows) <= 3)
  967. )
  968. result[algo] = {
  969. "samples_s": len(grows),
  970. "test_num": tnum,
  971. "cum_errors": max(r["mt_cum_errors"] for r in grows),
  972. "console_exec_s": (
  973. console_exec_by_test[tnum][0]
  974. if console_exec_by_test and tnum in console_exec_by_test and console_exec_by_test[tnum]
  975. else None
  976. ),
  977. "event_exec_s": (
  978. event_exec_by_test[tnum][0]
  979. if event_exec_by_test and tnum in event_exec_by_test and event_exec_by_test[tnum]
  980. else None
  981. ),
  982. "ddr_peak_asymmetry_ratio": asym_ratio,
  983. "ddr_asymmetric_seconds": asym_seconds,
  984. "is_asymmetric_load": is_asym,
  985. **sensors,
  986. }
  987. return result
  988. def analyze_station(station_key: str, accessor: VirtualStation) -> tuple[dict[str, Any], dict[str, Any]]:
  989. # 1. Parse console logs first for hardware inventory & full algorithm names
  990. console_files = accessor.list_files("_console.log")
  991. console_parsed: dict[str, dict[str, Any]] = {}
  992. merged_algo_map: dict[int, str] = {}
  993. for cf in console_files:
  994. cp = parse_console_log(accessor.read_text(cf), cf)
  995. console_parsed[cf] = cp
  996. merged_algo_map.update(cp["algo_names_by_num"])
  997. ordered_consoles = sorted(
  998. console_parsed.values(),
  999. key=lambda c: (0 if c["filename"] == "master_console.log" else 1, c["filename"]),
  1000. )
  1001. bios_versions: list[str] = []
  1002. cpu_names: list[str] = []
  1003. total_memories: list[str] = []
  1004. mem_timings: list[str] = []
  1005. dram_entries: list[dict[str, str]] = []
  1006. seen_dram_locs: set[str] = set()
  1007. smbios_bios = None
  1008. smbios_system = None
  1009. mt_config: dict[str, str] = {}
  1010. total_console_real_errors: list[dict[str, str]] = []
  1011. console_phase_summaries: dict[str, Any] = {}
  1012. for cp in ordered_consoles:
  1013. for b in cp["bios_versions"]:
  1014. if b not in bios_versions:
  1015. bios_versions.append(b)
  1016. if not smbios_bios and cp["smbios_bios"]:
  1017. smbios_bios = cp["smbios_bios"]
  1018. if not smbios_system and cp["smbios_system"]:
  1019. smbios_system = cp["smbios_system"]
  1020. for c in cp["cpu_names"]:
  1021. if c not in cpu_names:
  1022. cpu_names.append(c)
  1023. for tm in cp["total_memories"]:
  1024. if tm not in total_memories:
  1025. total_memories.append(tm)
  1026. for mt in cp["mem_timings"]:
  1027. if mt not in mem_timings:
  1028. mem_timings.append(mt)
  1029. for de in cp["dram_entries"]:
  1030. loc = de.get("DimmLocation") or json.dumps(de, sort_keys=True)
  1031. if loc not in seen_dram_locs:
  1032. seen_dram_locs.add(loc)
  1033. dram_entries.append(de)
  1034. if not mt_config and cp["mt_config"]:
  1035. mt_config = cp["mt_config"]
  1036. for err in cp["real_errors"]:
  1037. total_console_real_errors.append({"file": cp["filename"], "line": err})
  1038. console_phase_summaries[cp["filename"]] = {
  1039. "bytes": cp["bytes"],
  1040. "lines": cp["lines"],
  1041. "running_tests_count": len(cp["running_tests"]),
  1042. "completed_tests": cp["completed_tests"],
  1043. "range_warnings_count": cp["range_warnings_count"],
  1044. "range_warnings_max_cpu": cp["range_warnings_max_cpu"],
  1045. "range_warnings_max_bsp_ms": cp["range_warnings_max_bsp_ms"],
  1046. "console_dimm0_temp": cp["console_dimm0_temp"],
  1047. "console_dimm1_temp": cp["console_dimm1_temp"],
  1048. "console_cpu_temp": cp["console_cpu_temp"],
  1049. "real_errors_count": len(cp["real_errors"]),
  1050. }
  1051. # 2. Parse events & live_status
  1052. events_parsed = (
  1053. parse_events_jsonl(accessor.read_text("master_events.jsonl"))
  1054. if accessor.exists("master_events.jsonl")
  1055. else parse_events_jsonl("")
  1056. )
  1057. live_status = (
  1058. json.loads(accessor.read_text("live_status.json"))
  1059. if accessor.exists("live_status.json")
  1060. else None
  1061. )
  1062. # 3. Parse comprehensive CSVs
  1063. comp_files = accessor.list_files("_comprehensive.csv")
  1064. comp_parsed_by_name: dict[str, dict[str, Any]] = {}
  1065. for cf in comp_files:
  1066. comp_parsed_by_name[cf] = parse_comprehensive_csv(accessor.read_bytes(cf), merged_algo_map)
  1067. master_comp_name = "master_continuous_comprehensive.csv"
  1068. master_comp = comp_parsed_by_name.get(master_comp_name)
  1069. all_rows_for_bmc = (
  1070. master_comp["rows"]
  1071. if master_comp is not None
  1072. else [r for cp in comp_parsed_by_name.values() for r in cp["rows"]]
  1073. )
  1074. active_bmc_channels = _discover_active_bmc_channels(all_rows_for_bmc)
  1075. # 4. Audit all 34-column template CSVs
  1076. template_files = accessor.list_files("_template.csv")
  1077. template_checks: dict[str, Any] = {}
  1078. for tf in template_files:
  1079. matching_comp_name = tf.replace("_template.csv", "_comprehensive.csv")
  1080. comp_rows = comp_parsed_by_name[matching_comp_name]["rows"] if matching_comp_name in comp_parsed_by_name else None
  1081. template_checks[tf] = audit_template_csv(accessor.read_bytes(tf), comp_rows)
  1082. # 5. Compute phase metrics and MT algorithm breakdown (all individual sensors)
  1083. phases_detail: dict[str, Any] = {}
  1084. mt_launches_by_phase: dict[str, int] = {
  1085. str(ev.get("phase") or ""): int(ev["unix_ms"])
  1086. for ev in events_parsed["mt_launches"]
  1087. if ev.get("unix_ms") is not None
  1088. }
  1089. event_exec_by_phase: dict[str, dict[int, list[float]]] = {}
  1090. for ev in events_parsed["mt_algo_dones"]:
  1091. ph = str(ev.get("phase") or "")
  1092. tnum = ev.get("test_num")
  1093. ex = ev.get("exec_s")
  1094. if tnum is not None and ex is not None:
  1095. event_exec_by_phase.setdefault(ph, {}).setdefault(int(tnum), []).append(float(ex))
  1096. residual_findings: list[dict[str, Any]] = []
  1097. algorithms_by_phase: dict[str, dict[str, Any]] = {}
  1098. phase_comp_names = [cf for cf in comp_files if cf != master_comp_name]
  1099. synthesized_phases: list[tuple[str, list[dict[str, Any]]]] = []
  1100. if not phase_comp_names and master_comp is not None:
  1101. grouped_master: dict[str, list[dict[str, Any]]] = {}
  1102. for r in master_comp["rows"]:
  1103. tp = r["test_phase"] or "unknown"
  1104. if tp == "init":
  1105. continue
  1106. bucket = re.sub(r"_(fan\d+_round\d+|antirebound_soak_round\d+)$", "", tp)
  1107. grouped_master.setdefault(bucket, []).append(r)
  1108. for bucket, grows in grouped_master.items():
  1109. synthesized_phases.append((f"{bucket}_comprehensive.csv", grows))
  1110. phase_sources: list[tuple[str, list[dict[str, Any]], str, bool, int]] = []
  1111. for cf in phase_comp_names:
  1112. cp = comp_parsed_by_name[cf]
  1113. phase_sources.append((cf, cp["rows"], cp["schema_version"], cp["seq_contiguous"], len(cp["gaps_over_2s"])))
  1114. for cf, grows in synthesized_phases:
  1115. phase_sources.append((cf, grows, master_comp["schema_version"] if master_comp else "unknown", True, 0))
  1116. for cf, prows, p_schema, p_seq_ok, p_gaps_cnt in phase_sources:
  1117. phase_base = cf.replace("_comprehensive.csv", "")
  1118. launch_ms = mt_launches_by_phase.get(phase_base)
  1119. if "_mt_" in phase_base:
  1120. res_cnt = _mark_residual_prelaunch_rows(prows, launch_ms)
  1121. if res_cnt > 0:
  1122. residual_findings.append({
  1123. "file": cf,
  1124. "phase": phase_base,
  1125. "residual_rows": res_cnt,
  1126. "residual_label": prows[0]["active_algorithm"],
  1127. "note": "Leading rows before MemTest86 launch carried residual algorithm label from prior run",
  1128. })
  1129. pm = _compute_phase_metrics(prows, active_bmc_channels)
  1130. pm["schema_version"] = p_schema
  1131. pm["seq_contiguous"] = p_seq_ok
  1132. pm["gaps_over_2s_count"] = p_gaps_cnt
  1133. phases_detail[cf] = pm
  1134. if "_mt_" in phase_base:
  1135. console_name = f"{phase_base}_console.log"
  1136. cp_con = console_parsed.get(console_name)
  1137. con_exec: dict[int, list[float]] = {}
  1138. if cp_con:
  1139. for ct in cp_con["completed_tests"]:
  1140. con_exec.setdefault(int(ct["test_num"]), []).append(float(ct["exec_s"]))
  1141. algorithms_by_phase[phase_base] = _aggregate_algorithms(
  1142. prows,
  1143. active_bmc_channels,
  1144. console_exec_by_test=con_exec,
  1145. event_exec_by_test=event_exec_by_phase.get(phase_base),
  1146. )
  1147. master_rows = master_comp["rows"] if master_comp else []
  1148. if master_rows and residual_findings:
  1149. residual_windows: list[tuple[int, int]] = []
  1150. for rf in residual_findings:
  1151. prows = comp_parsed_by_name[rf["file"]]["rows"]
  1152. r_subset = [r for r in prows if r["is_residual_prelaunch"] and r["unix_ms"] is not None]
  1153. if r_subset:
  1154. residual_windows.append((min(r["unix_ms"] for r in r_subset) - 50, max(r["unix_ms"] for r in r_subset) + 50))
  1155. for r in master_rows:
  1156. um = r["unix_ms"]
  1157. if um is not None and any(lo <= um <= hi for lo, hi in residual_windows):
  1158. r["is_residual_prelaunch"] = True
  1159. # 6. Enrich cooldown soak rounds with per-chamber 8-channel rebound details from CSV
  1160. soak_items: list[dict[str, Any]] = []
  1161. for sk in events_parsed["antirebound_soaks"]:
  1162. end_ms = sk.get("unix_ms")
  1163. start_ms = sk.get("start_unix_ms")
  1164. per_chamber_rebound: dict[str, Any] = {}
  1165. dimm0_end_csv = None
  1166. dimm1_end_csv = None
  1167. bmc_end_csv: dict[str, int | None] = {}
  1168. if master_rows and end_ms is not None:
  1169. if start_ms is not None:
  1170. win_rows = [
  1171. r for r in master_rows
  1172. if r["unix_ms"] is not None and (start_ms - 500) <= r["unix_ms"] <= (end_ms + 500)
  1173. ]
  1174. else:
  1175. win_rows = []
  1176. if win_rows:
  1177. for col, zh_label, ch_id, side in CHAMBER_SENSORS:
  1178. vals = [r[col] for r in win_rows if r.get(col) is not None]
  1179. if vals:
  1180. per_chamber_rebound[col] = {
  1181. "label": zh_label,
  1182. "start": vals[0],
  1183. "peak": max(vals),
  1184. "end": vals[-1],
  1185. "rebound": round(max(vals) - vals[0], 2),
  1186. }
  1187. nearest = min(
  1188. (r for r in master_rows if r["unix_ms"] is not None),
  1189. key=lambda r: abs(int(r["unix_ms"]) - int(end_ms)),
  1190. default=None,
  1191. )
  1192. if nearest is not None:
  1193. dimm0_end_csv = nearest.get("rf_dimm_cpu0_a_c")
  1194. dimm1_end_csv = nearest.get("rf_dimm_cpu1_a_c")
  1195. for b_idx in active_bmc_channels:
  1196. bv = nearest["bmc24_raw"][b_idx]
  1197. bmc_end_csv[f"BMC{b_idx}"] = None if bv in (None, 255) else bv
  1198. soak_items.append({
  1199. "phase_group": sk["phase_group"],
  1200. "phase": sk.get("phase"),
  1201. "round": sk.get("round"),
  1202. "time_cst": sk.get("time_cst"),
  1203. "base_ct_max": sk.get("base_ct_norm"),
  1204. "peak_ct_max": sk.get("peak_ct_norm"),
  1205. "max_rebound": sk.get("max_rebound_norm"),
  1206. "ct_end": sk.get("ct_end"),
  1207. "dimm_end_event": sk.get("dimm_end"),
  1208. "dimm0_end_csv": dimm0_end_csv,
  1209. "dimm1_end_csv": dimm1_end_csv,
  1210. "bmc_end_csv": bmc_end_csv,
  1211. "per_chamber_rebound": per_chamber_rebound,
  1212. })
  1213. # 7. Enrich preheat handovers with individual per-chamber CT8 & +300s individual sensors
  1214. preheat_enriched: list[dict[str, Any]] = []
  1215. for hv in events_parsed["preheat_handovers"]:
  1216. item = dict(hv)
  1217. ct8 = hv.get("ct8") or []
  1218. if len(ct8) == 8:
  1219. item["chambers_at_handover"] = {
  1220. ch_id: {
  1221. "front": ct8[idx * 2],
  1222. "rear": ct8[idx * 2 + 1],
  1223. "front_minus_rear": ct8[idx * 2] - ct8[idx * 2 + 1],
  1224. }
  1225. for idx, (ch_id, _, _, _) in enumerate(CHAMBER_PAIRS)
  1226. }
  1227. hv_ms = hv.get("unix_ms")
  1228. if master_rows and hv_ms is not None:
  1229. preheat_rows = [r for r in master_rows if r["test_phase"] == hv.get("phase")]
  1230. if preheat_rows:
  1231. item["start_sensors"] = {
  1232. "ct8": preheat_rows[0]["ct8"],
  1233. "rf_dimm_cpu0_a_c": preheat_rows[0]["rf_dimm_cpu0_a_c"],
  1234. "rf_dimm_cpu1_a_c": preheat_rows[0]["rf_dimm_cpu1_a_c"],
  1235. "bmc": {f"BMC{i}": preheat_rows[0]["bmc24_raw"][i] for i in active_bmc_channels},
  1236. }
  1237. after_300 = [r for r in master_rows if r["unix_ms"] is not None and r["unix_ms"] >= hv_ms + 299_000]
  1238. if after_300:
  1239. r300 = after_300[0]
  1240. item["post_300s_sensors"] = {
  1241. "ct8": r300["ct8"],
  1242. "rf_dimm_cpu0_a_c": r300["rf_dimm_cpu0_a_c"],
  1243. "rf_dimm_cpu1_a_c": r300["rf_dimm_cpu1_a_c"],
  1244. "bmc": {f"BMC{i}": r300["bmc24_raw"][i] for i in active_bmc_channels},
  1245. }
  1246. preheat_enriched.append(item)
  1247. # 8. Station identity & integrity
  1248. station_id = ""
  1249. bmc_host = ""
  1250. m_key = re.match(r"^(S\d+)_(.+)$", station_key)
  1251. if m_key:
  1252. station_id, bmc_host = m_key.group(1), m_key.group(2)
  1253. for r in master_rows[:5]:
  1254. if r.get("station_id") and not station_id:
  1255. station_id = r["station_id"]
  1256. if r.get("bmc_host") and not bmc_host:
  1257. bmc_host = r["bmc_host"]
  1258. if not station_id:
  1259. station_id = station_key
  1260. phase_row_sum = sum(len(comp_parsed_by_name[cf]["rows"]) for cf in phase_comp_names)
  1261. master_row_count = len(master_rows)
  1262. total_mt_errors = max(
  1263. [max((r["mt_cum_errors"] for r in master_rows), default=0)]
  1264. + [int(ct["cum_errors"]) for cp in console_parsed.values() for ct in cp["completed_tests"]]
  1265. + [int(ev.get("cum_errors") or 0) for ev in events_parsed["mt_algo_dones"]]
  1266. + [len(total_console_real_errors)]
  1267. )
  1268. template_all_ok = all(t["status"] == "PASS" for t in template_checks.values()) if template_checks else False
  1269. integrity = {
  1270. "schema_version": master_comp["schema_version"] if master_comp else "unknown",
  1271. "master_rows": master_row_count,
  1272. "phase_sum_rows": phase_row_sum,
  1273. "master_minus_phase_rows": master_row_count - phase_row_sum,
  1274. "master_seq_contiguous": master_comp["seq_contiguous"] if master_comp else False,
  1275. "master_dt_ms_median": master_comp["dt_ms_median"] if master_comp else None,
  1276. "master_dt_ms_max": master_comp["dt_ms_max"] if master_comp else None,
  1277. "master_gaps_over_2s": master_comp["gaps_over_2s"] if master_comp else [],
  1278. "mcu_offline_rows": master_comp["mcu_offline_rows"] if master_comp else 0,
  1279. "cpld_lost_rows": master_comp["cpld_lost_rows"] if master_comp else 0,
  1280. "server_power_non_on": master_comp["server_power_non_on"] if master_comp else 0,
  1281. "template_files_count": len(template_checks),
  1282. "template_all_pass": template_all_ok,
  1283. "template_total_mismatches": sum((t["value_mismatches_vs_comprehensive"] or 0) for t in template_checks.values()),
  1284. "residual_prelaunch_findings": residual_findings,
  1285. "mt_total_errors": total_mt_errors,
  1286. "console_real_errors": total_console_real_errors[:20],
  1287. "events_parse_errors": events_parsed["parse_errors"],
  1288. }
  1289. suite_init = events_parsed["suite_init"] or {}
  1290. station_info = {
  1291. "station_key": station_key,
  1292. "station_id": station_id,
  1293. "bmc_host": bmc_host,
  1294. "mcu_uid": suite_init.get("uid"),
  1295. "mcu_app_info": suite_init.get("app_info"),
  1296. "pid_text": suite_init.get("pid_text"),
  1297. "active_bmc_channels": [
  1298. {"idx": idx, "key": f"BMC{idx}", "label": bmc_slot_label(idx)}
  1299. for idx in active_bmc_channels
  1300. ],
  1301. "bios_versions": bios_versions,
  1302. "smbios_bios": smbios_bios,
  1303. "smbios_system": smbios_system,
  1304. "cpu_names": cpu_names,
  1305. "total_memories": total_memories,
  1306. "mem_timings": mem_timings,
  1307. "dram_inventory": dram_entries,
  1308. "mt_config": mt_config,
  1309. "total_duration_hms": master_rows[-1]["elapsed_hms"] if master_rows else None,
  1310. "start_time_cst": master_rows[0]["timestamp_cst"] if master_rows else None,
  1311. "end_time_cst": master_rows[-1]["timestamp_cst"] if master_rows else None,
  1312. }
  1313. # Overall full-run individual sensor stats from master_continuous
  1314. overall_sensors = _compute_individual_sensor_block(master_rows, active_bmc_channels) if master_rows else {}
  1315. station_report = {
  1316. "station_info": station_info,
  1317. "integrity": integrity,
  1318. "live_status": live_status,
  1319. "template_checks": template_checks,
  1320. "overall_sensors": overall_sensors,
  1321. "phases_detail": phases_detail,
  1322. "cooldown_outcomes": events_parsed["cooldown_outcomes"],
  1323. "antirebound_soaks": soak_items,
  1324. "preheat_handovers": preheat_enriched,
  1325. "algorithms_by_phase": algorithms_by_phase,
  1326. "console_summary": console_phase_summaries,
  1327. "events_meta": {
  1328. "event_count": events_parsed["event_count"],
  1329. "kind_counts": events_parsed["kind_counts"],
  1330. "events": events_parsed["events"],
  1331. },
  1332. }
  1333. series = _build_compact_series(master_rows, active_bmc_channels)
  1334. return station_report, {"master_rows": master_rows, "active_bmc_channels": active_bmc_channels, "series": series}
  1335. def _build_compact_series(rows: list[dict[str, Any]], active_bmc_channels: list[int]) -> dict[str, Any]:
  1336. phase_names: list[str] = []
  1337. phase_idx: dict[str, int] = {}
  1338. algo_names: list[str] = []
  1339. algo_idx: dict[str, int] = {}
  1340. mode_names: list[str] = []
  1341. mode_idx: dict[str, int] = {}
  1342. cols: dict[str, list[Any]] = {
  1343. "seq": [],
  1344. "t": [],
  1345. "ts": [],
  1346. "ph": [],
  1347. "al": [],
  1348. "md": [],
  1349. "res": [],
  1350. "tgt": [],
  1351. "err": [],
  1352. }
  1353. for col, _, _, _ in CHAMBER_SENSORS:
  1354. cols[col] = []
  1355. for idx in active_bmc_channels:
  1356. cols[f"bmc{idx}"] = []
  1357. for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS:
  1358. cols[col] = []
  1359. for r in rows:
  1360. ph = r["test_phase"] or "unknown"
  1361. if ph not in phase_idx:
  1362. phase_idx[ph] = len(phase_names)
  1363. phase_names.append(ph)
  1364. al = r["active_algorithm"] or "Unknown"
  1365. if al not in algo_idx:
  1366. algo_idx[al] = len(algo_names)
  1367. algo_names.append(al)
  1368. md = r["mcu_mode"] or "unknown"
  1369. if md not in mode_idx:
  1370. mode_idx[md] = len(mode_names)
  1371. mode_names.append(md)
  1372. cols["seq"].append(r["seq"])
  1373. cols["t"].append(round(r["elapsed_s"], 1) if r["elapsed_s"] is not None else len(cols["t"]))
  1374. ts = r["timestamp_cst"]
  1375. cols["ts"].append(ts[11:19] if len(ts) >= 19 else ts)
  1376. cols["ph"].append(phase_idx[ph])
  1377. cols["al"].append(algo_idx[al])
  1378. cols["md"].append(mode_idx[md])
  1379. cols["res"].append(1 if r.get("is_residual_prelaunch") else 0)
  1380. cols["tgt"].append(_round_opt(r["mcu_target_c"], 1))
  1381. cols["err"].append(r["mt_cum_errors"])
  1382. for col, _, _, _ in CHAMBER_SENSORS:
  1383. cols[col].append(_round_opt(r.get(col), 1))
  1384. for idx in active_bmc_channels:
  1385. bv = r["bmc24_raw"][idx]
  1386. cols[f"bmc{idx}"].append(None if bv in (None, 255) else bv)
  1387. for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS:
  1388. cols[col].append(_round_opt(r.get(col), 2))
  1389. for col, _ in FAN_ACTUATOR_SENSORS:
  1390. cols[col].append(_round_opt(r.get(col), 1 if "pct" in col else 0))
  1391. return {
  1392. "phase_names": phase_names,
  1393. "algo_names": algo_names,
  1394. "mode_names": mode_names,
  1395. "active_bmc_channels": [
  1396. {"idx": idx, "col": f"bmc{idx}", "key": f"BMC{idx}", "label": bmc_slot_label(idx)}
  1397. for idx in active_bmc_channels
  1398. ],
  1399. "cols": cols,
  1400. }
  1401. def parse_bundle(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
  1402. with open_bundle_source(input_path) as src:
  1403. stations_out: dict[str, Any] = {}
  1404. artifacts: dict[str, Any] = {}
  1405. for skey, accessor in src.stations.items():
  1406. rep, art = analyze_station(skey, accessor)
  1407. stations_out[skey] = rep
  1408. artifacts[skey] = art
  1409. total_rows = sum(s["integrity"]["master_rows"] for s in stations_out.values())
  1410. total_mt_errors = sum(s["integrity"]["mt_total_errors"] for s in stations_out.values())
  1411. all_templates_pass = all(s["integrity"]["template_all_pass"] for s in stations_out.values())
  1412. summary = {
  1413. "parser_version": PARSER_VERSION,
  1414. "mode": "per_chamber_and_position_sensor_no_means",
  1415. "parsed_utc": datetime.now(timezone.utc).isoformat(),
  1416. "input_path": str(src.input_path),
  1417. "source_kind": src.source_kind,
  1418. "station_count": len(stations_out),
  1419. "total_1hz_rows": total_rows,
  1420. "total_mt_errors": total_mt_errors,
  1421. "all_templates_pass": all_templates_pass,
  1422. "stations": stations_out,
  1423. }
  1424. return summary, artifacts
  1425. def _fmt_range(st: dict[str, Any] | None, unit: str = "°C", include_endpoints: bool = True) -> str:
  1426. if not st:
  1427. return "-"
  1428. if include_endpoints:
  1429. return f"`{st['min']}~{st['max']}{unit}` ({st['start']}→{st['end']})"
  1430. return f"`{st['min']}~{st['max']}{unit}`"
  1431. def render_markdown_report(parsed: dict[str, Any]) -> str:
  1432. lines: list[str] = []
  1433. lines.append("# 高温罩 + MemTest86 逐腔室与逐位置传感器独立解析报告(无均值)")
  1434. lines.append("")
  1435. lines.append(f"- **输入来源**:`{parsed['input_path']}` (`{parsed['source_kind']}`)")
  1436. lines.append(f"- **解析时间 (UTC)**:`{parsed['parsed_utc']}` · 解析器版本 `v{parsed['parser_version']}` (`per_chamber_and_position_sensor_no_means`)")
  1437. lines.append(
  1438. f"- **总体结论**:共 **{parsed['station_count']}** 个工位,合计 **{parsed['total_1hz_rows']:,}** 行 1Hz 遥测样本,"
  1439. f"MemTest86 累计错误数 **`{parsed['total_mt_errors']}`**,"
  1440. f"34 列模板结构与逐行数值核验 **`{'全部 PASS' if parsed['all_templates_pass'] else '存在异常'}`**"
  1441. )
  1442. lines.extend(["", "---", "", "## 1. 工位硬件清单、有效传感器通道与数据完整性审计", ""])
  1443. lines.append("| 工位 | BMC IP | MCU UID / PID | CPU & 内存 | 有效 BMC 通道 | 1Hz 总行数 (时长) | 模板核验 | MT 错误 | 数据告警 |")
  1444. lines.append("|---|---|---|---|---|---|---|---|---|")
  1445. for skey, s in parsed["stations"].items():
  1446. info = s["station_info"]
  1447. integ = s["integrity"]
  1448. cpu = (info.get("cpu_names") or ["-"])[0]
  1449. mem = (info.get("total_memories") or ["-"])[0]
  1450. pid = (info.get("pid_text") or "").replace("OK ", "")
  1451. bmc_list = ", ".join(b["key"] for b in info.get("active_bmc_channels") or []) or "-"
  1452. tpl_status = f"PASS ({integ['template_files_count']}份, 0失配)" if integ["template_all_pass"] else "WARN"
  1453. warns = [f"{rf['phase']} 前 {rf['residual_rows']}s 残留标签" for rf in integ["residual_prelaunch_findings"]]
  1454. if integ["master_gaps_over_2s"]:
  1455. warns.append(f"采样间隔>2s: {len(integ['master_gaps_over_2s'])}次")
  1456. if integ["mcu_offline_rows"] or integ["cpld_lost_rows"]:
  1457. warns.append(f"MCU离线={integ['mcu_offline_rows']} CPLD失联={integ['cpld_lost_rows']}")
  1458. warn_txt = ";".join(warns) if warns else "无"
  1459. lines.append(
  1460. f"| **{info['station_id']}** | `{info['bmc_host'] or '-'}` | "
  1461. f"`{info.get('mcu_uid') or '-'}` · `{pid}` | {cpu}; {mem} | `{bmc_list}` | "
  1462. f"`{integ['master_rows']:,}` (`{info.get('total_duration_hms') or '-'}`) | "
  1463. f"`{integ['schema_version']}` / {tpl_status} | **`{integ['mt_total_errors']}`** | {warn_txt} |"
  1464. )
  1465. lines.extend(["", "## 2. 各阶段高温罩 4 腔室 × 8 路位置传感器独立统计 (`min~max` 及 `起点→终点`)", ""])
  1466. lines.append("| 工位 | 阶段 | 行数 / 时长 | 腔1前 (CT1) | 腔1后 (CT2) | 腔2前 (CT3) | 腔2后 (CT4) | 腔3前 (CT5) | 腔3后 (CT6) | 腔4前 (CT7) | 腔4后 (CT8) |")
  1467. lines.append("|---|---|---|---|---|---|---|---|---|---|---|")
  1468. for skey, s in parsed["stations"].items():
  1469. sid = s["station_info"]["station_id"]
  1470. for pname, pm in s["phases_detail"].items():
  1471. short_p = pname.replace("_comprehensive.csv", "")
  1472. cs = pm["chamber_sensors"]
  1473. cols = [_fmt_range(cs.get(col), "°C") for col, _, _, _ in CHAMBER_SENSORS]
  1474. lines.append(f"| **{sid}** | `{short_p}` | `{pm['rows']}` / `{pm['duration_hms']}` | " + " | ".join(cols) + " |")
  1475. lines.extend(["", "## 3. 各阶段服务器位置传感器、功耗轨与风扇逐通道独立统计", ""])
  1476. lines.append("### 3.1 内存、MCU BMC、CPU、主板与电源温度传感器 (`min~max`, `起点→终点`)")
  1477. lines.append("")
  1478. lines.append("| 工位 | 阶段 | RF DIMM0 | RF DIMM1 | MCU BMC0 | MCU BMC12 | MT SPD0 / SPD1 | RF CPU0 / CPU1 | RF MB / PSU0 | PVCCIN0/1 · PVCCFA0/1 · PVCCD0/1 |")
  1479. lines.append("|---|---|---|---|---|---|---|---|---|---|")
  1480. for skey, s in parsed["stations"].items():
  1481. sid = s["station_info"]["station_id"]
  1482. for pname, pm in s["phases_detail"].items():
  1483. short_p = pname.replace("_comprehensive.csv", "")
  1484. rf = pm["redfish_temps"]
  1485. bmc = pm["bmc_channels"]
  1486. mt = pm["mt_console_temps"]
  1487. spd_txt = f"{_fmt_range(mt.get('mt_spd_dimm0_c'), '°C', False)} / {_fmt_range(mt.get('mt_spd_dimm1_c'), '°C', False)}"
  1488. cpu_txt = f"{_fmt_range(rf.get('rf_cpu0_c'), '°C', False)} / {_fmt_range(rf.get('rf_cpu1_c'), '°C', False)}"
  1489. mb_txt = f"{_fmt_range(rf.get('rf_mb_c'), '°C', False)} / {_fmt_range(rf.get('rf_psu0_c'), '°C', False)}"
  1490. vr_txt = (
  1491. f"{_fmt_range(rf.get('rf_pvccin_cpu0_c'), '', False)}/{_fmt_range(rf.get('rf_pvccin_cpu1_c'), '', False)} · "
  1492. f"{_fmt_range(rf.get('rf_pvccfa_cpu0_c'), '', False)}/{_fmt_range(rf.get('rf_pvccfa_cpu1_c'), '', False)} · "
  1493. f"{_fmt_range(rf.get('rf_pvccd_cpu0_c'), '', False)}/{_fmt_range(rf.get('rf_pvccd_cpu1_c'), '', False)}"
  1494. )
  1495. lines.append(
  1496. f"| **{sid}** | `{short_p}` | {_fmt_range(rf.get('rf_dimm_cpu0_a_c'))} | {_fmt_range(rf.get('rf_dimm_cpu1_a_c'))} | "
  1497. f"{_fmt_range(bmc.get('BMC0'))} | {_fmt_range(bmc.get('BMC12'))} | {spd_txt} | {cpu_txt} | {mb_txt} | {vr_txt} |"
  1498. )
  1499. lines.extend(["", "### 3.2 各电源/DDR/CPU 功耗轨与各风扇通道 (`min~max`)", ""])
  1500. lines.append("| 工位 | 阶段 | 整机功耗 | DDR0 / DDR1 / DDR2 / DDR3 | CPU0 DIMM / CPU1 DIMM | CPU0 / CPU1 功耗 | 罩 PTC / 前扇 / 后扇 | RF FAN1..5 (RPM) |")
  1501. lines.append("|---|---|---|---|---|---|---|---|")
  1502. for skey, s in parsed["stations"].items():
  1503. sid = s["station_info"]["station_id"]
  1504. for pname, pm in s["phases_detail"].items():
  1505. short_p = pname.replace("_comprehensive.csv", "")
  1506. pw = pm["power_rails"]
  1507. fa = pm["fans_and_actuators"]
  1508. ddrs = " / ".join(_fmt_range(pw.get(f"rf_ddr{i}_power_w"), "W", False) for i in range(4))
  1509. dimm_p = f"{_fmt_range(pw.get('rf_dimm_power_cpu0_w'), 'W', False)} / {_fmt_range(pw.get('rf_dimm_power_cpu1_w'), 'W', False)}"
  1510. cpu_p = f"{_fmt_range(pw.get('rf_cpu0_power_avg_w'), 'W', False)} / {_fmt_range(pw.get('rf_cpu1_power_avg_w'), 'W', False)}"
  1511. hood = f"{_fmt_range(fa.get('cmd_ptc_pct'), '%', False)} / {_fmt_range(fa.get('cmd_fan_front_pct'), '%', False)} / {_fmt_range(fa.get('cmd_fan_rear_pct'), '%', False)}"
  1512. fans = " / ".join(_fmt_range(fa.get(f"rf_fan{i}_rpm"), "", False) for i in range(1, 6))
  1513. lines.append(f"| **{sid}** | `{short_p}` | {_fmt_range(pw.get('rf_total_power_w'), 'W', False)} | {ddrs} | {dimm_p} | {cpu_p} | {hood} | {fans} |")
  1514. lines.extend(["", "## 4. 降温防反弹(逐腔室 8 路实测反弹)与预加热移交", ""])
  1515. lines.append("| 工位 | 降温阶段 | Round | 吹扫耗时 / 结果 | 腔1前/后反弹 | 腔2前/后反弹 | 腔3前/后反弹 | 腔4前/后反弹 | 静置末 DIMM0 / DIMM1 |")
  1516. lines.append("|---|---|---|---|---|---|---|---|---|")
  1517. for skey, s in parsed["stations"].items():
  1518. sid = s["station_info"]["station_id"]
  1519. cd_map = {(c["phase_group"], c["round"]): c for c in s["cooldown_outcomes"]}
  1520. for sk in s["antirebound_soaks"]:
  1521. cd = cd_map.get((sk["phase_group"], sk["round"]), {})
  1522. cd_txt = f"{cd.get('duration_s', '-')}s ({cd.get('outcome', '-')})"
  1523. pcr = sk.get("per_chamber_rebound") or {}
  1524. ch_txts = []
  1525. for _, _, fc, rc in CHAMBER_PAIRS:
  1526. f_info = pcr.get(fc)
  1527. r_info = pcr.get(rc)
  1528. f_s = f"{f_info['start']}→{f_info['peak']}(+{f_info['rebound']})" if f_info else "-"
  1529. r_s = f"{r_info['start']}→{r_info['peak']}(+{r_info['rebound']})" if r_info else "-"
  1530. ch_txts.append(f"{f_s} / {r_s}")
  1531. d0e = sk.get("dimm0_end_csv")
  1532. d1e = sk.get("dimm1_end_csv")
  1533. dimm_txt = f"`{d0e if d0e is not None else '-'} / {d1e if d1e is not None else '-'}°C`"
  1534. lines.append(f"| **{sid}** | `{sk['phase_group']}` | R{sk['round']} | {cd_txt} | " + " | ".join(ch_txts) + f" | {dimm_txt} |")
  1535. lines.append("")
  1536. lines.append("| 工位 | 预热耗时 (0x81 02) | 移交瞬时 8路 [腔1前,后 .. 腔4前,后] | 移交各腔前后差 (腔1..4) | 移交 BMC0 / BMC12 | +300s 8路 CT8 | +300s RF DIMM0 / DIMM1 |")
  1537. lines.append("|---|---|---|---|---|---|---|")
  1538. for skey, s in parsed["stations"].items():
  1539. sid = s["station_info"]["station_id"]
  1540. for hv in s["preheat_handovers"]:
  1541. ch_h = hv.get("chambers_at_handover") or {}
  1542. diffs = " / ".join(f"{ch_h[c]['front_minus_rear']:+d}°C" for c in ("ch1", "ch2", "ch3", "ch4") if c in ch_h) or "-"
  1543. p300 = hv.get("post_300s_sensors") or {}
  1544. p300_d = f"{p300.get('rf_dimm_cpu0_a_c', '-')}/{p300.get('rf_dimm_cpu1_a_c', '-')}°C" if p300 else "-"
  1545. lines.append(
  1546. f"| **{sid}** | `{hv.get('preheat_elapsed_s', 0):.1f}s` | `{hv.get('ct8')}` | `{diffs}` | "
  1547. f"`{hv.get('bmc0')}/{hv.get('bmc12')}°C` | `{p300.get('ct8', '-')}` | {p300_d} |"
  1548. )
  1549. lines.extend(["", "## 5. MT 阶段按算法拆解(逐腔室 8 路 & 逐位置传感器实测范围 `min~max`,无均值)", ""])
  1550. for skey, s in parsed["stations"].items():
  1551. sid = s["station_info"]["station_id"]
  1552. lines.append(f"### {sid} (`{s['station_info']['bmc_host'] or skey}`)")
  1553. lines.append("")
  1554. for phase_base, algos in s["algorithms_by_phase"].items():
  1555. lines.append(f"#### 阶段 `{phase_base}`")
  1556. lines.append("")
  1557. lines.append("| 算法 | 样本(s) | 耗时(s) | RF DIMM0 | RF DIMM1 | BMC0 / BMC12 | 腔1前 / 后 | 腔2前 / 后 | 腔3前 / 后 | 腔4前 / 后 | DDR0 / DDR2 功耗 | CPU0 / CPU1 功耗 | 峰值非对称比 | 错误 |")
  1558. lines.append("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|")
  1559. for aname, av in algos.items():
  1560. rf = av["redfish_temps"]
  1561. bmc = av["bmc_channels"]
  1562. cs = av["chamber_sensors"]
  1563. pw = av["power_rails"]
  1564. cexec = f"{av['console_exec_s']:.2f}s" if av.get("console_exec_s") is not None else "-"
  1565. bmc_txt = f"{_fmt_range(bmc.get('BMC0'), '', False)} / {_fmt_range(bmc.get('BMC12'), '', False)}"
  1566. ch_cols = [
  1567. f"{_fmt_range(cs.get(fc), '', False)} / {_fmt_range(cs.get(rc), '', False)}"
  1568. for _, _, fc, rc in CHAMBER_PAIRS
  1569. ]
  1570. ddr_txt = f"{_fmt_range(pw.get('rf_ddr0_power_w'), 'W', False)} / {_fmt_range(pw.get('rf_ddr2_power_w'), 'W', False)}"
  1571. cpu_txt = f"{_fmt_range(pw.get('rf_cpu0_power_avg_w'), 'W', False)} / {_fmt_range(pw.get('rf_cpu1_power_avg_w'), 'W', False)}"
  1572. asym = f"**{av['ddr_peak_asymmetry_ratio']}×**" if av.get("is_asymmetric_load") else (f"{av['ddr_peak_asymmetry_ratio']}×" if av.get("ddr_peak_asymmetry_ratio") else "-")
  1573. lines.append(
  1574. f"| `{aname}` | `{av['samples_s']}` | `{cexec}` | "
  1575. f"{_fmt_range(rf.get('rf_dimm_cpu0_a_c'), '°C', False)} | {_fmt_range(rf.get('rf_dimm_cpu1_a_c'), '°C', False)} | {bmc_txt} | "
  1576. + " | ".join(ch_cols)
  1577. + f" | {ddr_txt} | {cpu_txt} | {asym} | `{av['cum_errors']}` |"
  1578. )
  1579. lines.append("")
  1580. lines.extend(["## 6. 控制台 BIOS/DRAM 硬件指纹与 MemTest86 执行核对", ""])
  1581. lines.append("| 工位 | BIOS 版本 | DRAM 条目 (控制台) | MemTest86 配置 | Console 执行记录 & CPU 等待告警 | 实测错误 |")
  1582. lines.append("|---|---|---|---|---|---|")
  1583. for skey, s in parsed["stations"].items():
  1584. info = s["station_info"]
  1585. sid = info["station_id"]
  1586. bios = "; ".join(info.get("bios_versions") or []) or (info.get("smbios_bios") or "-")
  1587. drams = "; ".join(
  1588. f"{d.get('DimmLocation','?')}: {d.get('Vendor','?')} {d.get('Size','?')} {d.get('Speed','?')}MT/s (SN:{d.get('DIMM_SN') or d.get('HS_DIMM_SN') or '-'})"
  1589. for d in (info.get("dram_inventory") or [])
  1590. ) or "-"
  1591. cfg = info.get("mt_config") or {}
  1592. cfg_txt = f"Tests={cfg.get('Tests Selected','-')}; Pass={cfg.get('Number of passes','-')}; Exit={cfg.get('Exit mode','-')}"
  1593. mcon = s["console_summary"].get("master_console.log") or {}
  1594. warn_cnt = sum(c.get("range_warnings_count", 0) for c in s["console_summary"].values())
  1595. con_txt = f"master完成={len(mcon.get('completed_tests', []))}项; CPU等待告警={warn_cnt}"
  1596. lines.append(f"| **{sid}** | `{bios}` | `{drams}` | `{cfg_txt}` | {con_txt} | `{s['integrity']['mt_total_errors']}` |")
  1597. return "\n".join(lines) + "\n"
  1598. def render_html_dashboard(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
  1599. slim_stations: dict[str, Any] = {}
  1600. for skey, s in parsed["stations"].items():
  1601. slim_stations[skey] = {
  1602. "station_info": s["station_info"],
  1603. "integrity": s["integrity"],
  1604. "live_status": s["live_status"],
  1605. "template_checks": s["template_checks"],
  1606. "overall_sensors": s["overall_sensors"],
  1607. "phases_detail": s["phases_detail"],
  1608. "cooldown_outcomes": s["cooldown_outcomes"],
  1609. "antirebound_soaks": s["antirebound_soaks"],
  1610. "preheat_handovers": s["preheat_handovers"],
  1611. "algorithms_by_phase": s["algorithms_by_phase"],
  1612. "console_summary": s["console_summary"],
  1613. "events": s["events_meta"]["events"],
  1614. "event_kind_counts": s["events_meta"]["kind_counts"],
  1615. }
  1616. payload = {
  1617. "meta": {
  1618. "parser_version": parsed["parser_version"],
  1619. "mode": parsed["mode"],
  1620. "parsed_utc": parsed["parsed_utc"],
  1621. "input_path": parsed["input_path"],
  1622. "source_kind": parsed["source_kind"],
  1623. "station_count": parsed["station_count"],
  1624. "total_1hz_rows": parsed["total_1hz_rows"],
  1625. "total_mt_errors": parsed["total_mt_errors"],
  1626. "all_templates_pass": parsed["all_templates_pass"],
  1627. },
  1628. "stations": slim_stations,
  1629. "series": {skey: art["series"] for skey, art in artifacts.items()},
  1630. }
  1631. payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
  1632. title = html.escape(f"逐腔室/逐位置传感器独立解析看板 ({parsed['station_count']} 工位 · {parsed['total_1hz_rows']:,} 样本)")
  1633. return f"""<!DOCTYPE html>
  1634. <html lang="zh-CN">
  1635. <head>
  1636. <meta charset="UTF-8">
  1637. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1638. <title>{title}</title>
  1639. <style>
  1640. :root {{
  1641. --bg: #0b101b;
  1642. --bg-card: #121a2b;
  1643. --bg-alt: #182338;
  1644. --text: #e6edf7;
  1645. --muted: #93a4be;
  1646. --border: #253554;
  1647. --accent: #38bdf8;
  1648. --accent2: #818cf8;
  1649. --good: #22c55e;
  1650. --warn: #f59e0b;
  1651. --bad: #ef4444;
  1652. }}
  1653. body.light {{
  1654. --bg: #f1f5f9;
  1655. --bg-card: #ffffff;
  1656. --bg-alt: #e8eff8;
  1657. --text: #0f172a;
  1658. --muted: #475569;
  1659. --border: #cbd5e1;
  1660. --accent: #0284c7;
  1661. --accent2: #4f46e5;
  1662. }}
  1663. * {{ box-sizing: border-box; margin: 0; padding: 0; }}
  1664. body {{
  1665. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
  1666. background: var(--bg);
  1667. color: var(--text);
  1668. line-height: 1.5;
  1669. padding-bottom: 48px;
  1670. }}
  1671. header {{
  1672. background: var(--bg-card);
  1673. border-bottom: 1px solid var(--border);
  1674. padding: 16px 24px;
  1675. display: flex;
  1676. flex-wrap: wrap;
  1677. justify-content: space-between;
  1678. align-items: center;
  1679. gap: 12px;
  1680. position: sticky;
  1681. top: 0;
  1682. z-index: 20;
  1683. }}
  1684. .hdr-title h1 {{ font-size: 18px; font-weight: 700; }}
  1685. .hdr-sub {{ font-size: 12px; color: var(--muted); margin-top: 2px; }}
  1686. .controls {{ display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }}
  1687. select, input, button {{
  1688. background: var(--bg-alt);
  1689. color: var(--text);
  1690. border: 1px solid var(--border);
  1691. border-radius: 6px;
  1692. padding: 6px 10px;
  1693. font-size: 13px;
  1694. }}
  1695. button {{ cursor: pointer; font-weight: 500; }}
  1696. button:hover {{ border-color: var(--accent); }}
  1697. button.active {{ background: var(--accent); color: #07101e; border-color: var(--accent); font-weight: 600; }}
  1698. .btn-xs {{ padding: 3px 8px; font-size: 12px; }}
  1699. .container {{ max-width: 1580px; margin: 18px auto; padding: 0 20px; }}
  1700. .kpi-grid {{
  1701. display: grid;
  1702. grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  1703. gap: 12px;
  1704. margin-bottom: 16px;
  1705. }}
  1706. .kpi-card {{
  1707. background: var(--bg-card);
  1708. border: 1px solid var(--border);
  1709. border-radius: 10px;
  1710. padding: 12px 14px;
  1711. }}
  1712. .kpi-label {{ font-size: 12px; color: var(--muted); }}
  1713. .kpi-val {{ font-size: 20px; font-weight: 700; margin-top: 4px; }}
  1714. .kpi-sub {{ font-size: 12px; color: var(--muted); margin-top: 2px; }}
  1715. .badge {{
  1716. display: inline-block;
  1717. padding: 2px 8px;
  1718. border-radius: 999px;
  1719. font-size: 11px;
  1720. font-weight: 600;
  1721. }}
  1722. .badge.pass {{ background: rgba(34,197,94,0.16); color: var(--good); border: 1px solid rgba(34,197,94,0.35); }}
  1723. .badge.warn {{ background: rgba(245,158,11,0.16); color: var(--warn); border: 1px solid rgba(245,158,11,0.35); }}
  1724. .badge.fail {{ background: rgba(239,68,68,0.16); color: var(--bad); border: 1px solid rgba(239,68,68,0.35); }}
  1725. .tabs {{
  1726. display: flex;
  1727. flex-wrap: wrap;
  1728. gap: 8px;
  1729. margin-bottom: 14px;
  1730. border-bottom: 1px solid var(--border);
  1731. padding-bottom: 10px;
  1732. }}
  1733. .tab-panel {{ display: none; }}
  1734. .tab-panel.active {{ display: block; }}
  1735. .card {{
  1736. background: var(--bg-card);
  1737. border: 1px solid var(--border);
  1738. border-radius: 10px;
  1739. padding: 14px 16px;
  1740. margin-bottom: 16px;
  1741. }}
  1742. .card-hdr {{
  1743. display: flex;
  1744. flex-wrap: wrap;
  1745. justify-content: space-between;
  1746. align-items: center;
  1747. gap: 10px;
  1748. margin-bottom: 10px;
  1749. }}
  1750. .card-hdr h3 {{ font-size: 15px; font-weight: 600; }}
  1751. .legend {{ display: flex; flex-wrap: wrap; gap: 8px 12px; font-size: 12px; color: var(--muted); }}
  1752. .legend-item {{ display: inline-flex; align-items: center; gap: 5px; cursor: pointer; user-select: none; }}
  1753. .legend-item.off {{ opacity: 0.35; text-decoration: line-through; }}
  1754. .swatch {{ width: 12px; height: 3px; border-radius: 2px; display: inline-block; }}
  1755. .chart-wrap {{ position: relative; width: 100%; height: 320px; overflow: hidden; }}
  1756. .chart-wrap canvas {{ width: 100%; height: 100%; display: block; }}
  1757. .table-scroll {{ overflow-x: auto; }}
  1758. table {{ width: 100%; border-collapse: collapse; font-size: 12px; }}
  1759. th, td {{ padding: 6px 8px; border-bottom: 1px solid var(--border); text-align: left; white-space: nowrap; }}
  1760. th {{ background: var(--bg-alt); color: var(--muted); font-weight: 600; position: sticky; top: 0; }}
  1761. tr:hover td {{ background: rgba(56,189,248,0.06); }}
  1762. .mono {{ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }}
  1763. .tooltip {{
  1764. position: fixed;
  1765. pointer-events: none;
  1766. background: rgba(11,16,27,0.96);
  1767. color: #e6edf7;
  1768. border: 1px solid #38bdf8;
  1769. border-radius: 8px;
  1770. padding: 9px 11px;
  1771. font-size: 11.5px;
  1772. line-height: 1.45;
  1773. z-index: 999;
  1774. display: none;
  1775. max-width: 470px;
  1776. box-shadow: 0 8px 24px rgba(0,0,0,0.5);
  1777. }}
  1778. .zoom-bar {{ display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }}
  1779. </style>
  1780. </head>
  1781. <body>
  1782. <header>
  1783. <div class="hdr-title">
  1784. <h1>高温罩 + MemTest86 逐腔室与逐位置传感器独立解析看板 (无均值)</h1>
  1785. <div class="hdr-sub" id="hdr-sub">加载中...</div>
  1786. </div>
  1787. <div class="controls">
  1788. <label>当前工位:
  1789. <select id="station-select"></select>
  1790. </label>
  1791. <button type="button" id="btn-theme">切换亮/暗主题</button>
  1792. </div>
  1793. </header>
  1794. <div class="container">
  1795. <div class="kpi-grid" id="kpi-grid"></div>
  1796. <div class="tabs">
  1797. <button type="button" class="tab-btn active" data-tab="tab-charts">1Hz 逐传感器曲线</button>
  1798. <button type="button" class="tab-btn" data-tab="tab-phases">逐腔室与位置传感器统计</button>
  1799. <button type="button" class="tab-btn" data-tab="tab-algos">MT 算法逐通道拆解</button>
  1800. <button type="button" class="tab-btn" data-tab="tab-audit">硬件与模板审计</button>
  1801. <button type="button" class="tab-btn" data-tab="tab-events">事件与控制台日志</button>
  1802. </div>
  1803. <div id="tab-charts" class="tab-panel active">
  1804. <div class="card">
  1805. <div class="card-hdr">
  1806. <h3>窗口缩放 (按阶段或拖拽框选,双击复位)</h3>
  1807. <div class="zoom-bar" id="zoom-bar"></div>
  1808. </div>
  1809. </div>
  1810. <div class="card">
  1811. <div class="card-hdr">
  1812. <h3>Chart 1 · 高温罩 4 腔室 × 8 路位置温度独立曲线 (腔1前/后 .. 腔4前/后 · 无均值)</h3>
  1813. <div class="controls">
  1814. <button type="button" class="btn-xs" data-ct-preset="all">全8路</button>
  1815. <button type="button" class="btn-xs" data-ct-preset="ch1">仅腔1</button>
  1816. <button type="button" class="btn-xs" data-ct-preset="ch2">仅腔2</button>
  1817. <button type="button" class="btn-xs" data-ct-preset="ch3">仅腔3</button>
  1818. <button type="button" class="btn-xs" data-ct-preset="ch4">仅腔4</button>
  1819. <button type="button" class="btn-xs" data-ct-preset="front">4路前侧</button>
  1820. <button type="button" class="btn-xs" data-ct-preset="rear">4路后侧</button>
  1821. </div>
  1822. </div>
  1823. <div class="legend" id="legend-chambers" style="margin-bottom:8px"></div>
  1824. <div class="chart-wrap"><canvas id="chart-chambers"></canvas></div>
  1825. </div>
  1826. <div class="card">
  1827. <div class="card-hdr">
  1828. <h3>Chart 2 · 服务器各位置温度传感器独立曲线 (DIMM · MCU BMC · MT SPD · CPU · MB · PSU · VR)</h3>
  1829. <div class="controls">
  1830. <button type="button" class="btn-xs" data-pos-preset="core">内存+BMC+CPU</button>
  1831. <button type="button" class="btn-xs" data-pos-preset="vr">VR供电位置</button>
  1832. <button type="button" class="btn-xs" data-pos-preset="all">全部点亮</button>
  1833. </div>
  1834. </div>
  1835. <div class="legend" id="legend-positions" style="margin-bottom:8px"></div>
  1836. <div class="chart-wrap"><canvas id="chart-positions"></canvas></div>
  1837. </div>
  1838. <div class="card">
  1839. <div class="card-hdr">
  1840. <h3>Chart 3 · 各功耗轨、风扇 RPM 与高温罩控制独立曲线 (无合并)</h3>
  1841. <div class="controls">
  1842. <button type="button" class="btn-xs" data-pwr-preset="power">功耗轨+罩控制</button>
  1843. <button type="button" class="btn-xs" data-pwr-preset="fans">5路服务器风扇RPM</button>
  1844. <button type="button" class="btn-xs" data-pwr-preset="all">全部显示</button>
  1845. </div>
  1846. </div>
  1847. <div class="legend" id="legend-pwr" style="margin-bottom:8px"></div>
  1848. <div class="chart-wrap"><canvas id="chart-pwr"></canvas></div>
  1849. </div>
  1850. </div>
  1851. <div id="tab-phases" class="tab-panel">
  1852. <div class="card">
  1853. <div class="card-hdr"><h3>高温罩 4 腔室 × 8 路温度传感器的分阶段实测范围 (min~max, 起点→终点)</h3></div>
  1854. <div class="table-scroll" id="phase-chambers-table"></div>
  1855. </div>
  1856. <div class="card">
  1857. <div class="card-hdr"><h3>服务器各位置温度传感器分阶段实测范围 (DIMM / BMC / CPU / MB / PSU / VR / MT SPD)</h3></div>
  1858. <div class="table-scroll" id="phase-positions-table"></div>
  1859. </div>
  1860. <div class="card">
  1861. <div class="card-hdr"><h3>电源/DDR/CPU 功耗轨与 5 路服务器风扇分阶段实测范围</h3></div>
  1862. <div class="table-scroll" id="phase-power-table"></div>
  1863. </div>
  1864. <div class="card">
  1865. <div class="card-hdr"><h3>降温防反弹(逐腔室 8 路起→峰反弹)与预加热移交记录</h3></div>
  1866. <div class="table-scroll" id="cooldown-table"></div>
  1867. <div class="table-scroll" id="handover-table" style="margin-top:12px"></div>
  1868. </div>
  1869. </div>
  1870. <div id="tab-algos" class="tab-panel">
  1871. <div class="card">
  1872. <div class="card-hdr">
  1873. <h3>Chart 4 · 算法维度逐通道峰值/区间对比 (无均值)</h3>
  1874. <div class="controls">
  1875. <select id="algo-phase-select"></select>
  1876. <select id="algo-metric-select">
  1877. <option value="ddr_max">DDR0 vs DDR2 峰值功耗 (W)</option>
  1878. <option value="dimm_max">RF DIMM0 vs DIMM1 峰值温度 (°C)</option>
  1879. <option value="cpu_pwr_max">CPU0 vs CPU1 峰值功耗 (W)</option>
  1880. <option value="ch_front_max">腔1前..腔4前 峰值温度 (°C)</option>
  1881. <option value="ch_rear_max">腔1后..腔4后 峰值温度 (°C)</option>
  1882. </select>
  1883. </div>
  1884. </div>
  1885. <div class="chart-wrap"><canvas id="chart-algo"></canvas></div>
  1886. </div>
  1887. <div class="card">
  1888. <div class="card-hdr"><h3>MT 阶段按算法拆解(逐腔室 8 路 & 逐位置传感器实测 min~max)</h3></div>
  1889. <div class="table-scroll" id="algo-table"></div>
  1890. </div>
  1891. </div>
  1892. <div id="tab-audit" class="tab-panel">
  1893. <div class="card">
  1894. <div class="card-hdr"><h3>工位硬件指纹与数据完整性总表</h3></div>
  1895. <div class="table-scroll" id="audit-overview-table"></div>
  1896. </div>
  1897. <div class="card">
  1898. <div class="card-hdr"><h3>34 列模板 CSV (`*_template.csv`) 结构与逐行交叉校验</h3></div>
  1899. <div class="table-scroll" id="template-audit-table"></div>
  1900. </div>
  1901. </div>
  1902. <div id="tab-events" class="tab-panel">
  1903. <div class="card">
  1904. <div class="card-hdr"><h3>控制台 BIOS / MemTest86 诊断摘要</h3></div>
  1905. <div class="table-scroll" id="console-summary-table"></div>
  1906. </div>
  1907. <div class="card">
  1908. <div class="card-hdr">
  1909. <h3>`master_events.jsonl` 结构化事件流水</h3>
  1910. <div class="controls">
  1911. <select id="event-kind-filter"><option value="">全部事件类型</option></select>
  1912. <input type="text" id="event-search" placeholder="关键字过滤...">
  1913. </div>
  1914. </div>
  1915. <div class="table-scroll" id="events-table"></div>
  1916. </div>
  1917. </div>
  1918. </div>
  1919. <div class="tooltip" id="tooltip"></div>
  1920. <script id="embedded-data" type="application/json">{payload_json}</script>
  1921. <script>
  1922. (() => {{
  1923. const DATA = JSON.parse(document.getElementById('embedded-data').textContent);
  1924. const stationKeys = Object.keys(DATA.stations);
  1925. let activeKey = stationKeys[0];
  1926. let zoomStart = 0;
  1927. let zoomEnd = null;
  1928. let hoverIdx = null;
  1929. let dragStartIdx = null;
  1930. let dragCurIdx = null;
  1931. let algoBarsCache = [];
  1932. const chamberSeries = [
  1933. {{ key: 'ct1_ch1_front', label: '腔1前(CT1)', color: '#ef4444', width: 1.6 }},
  1934. {{ key: 'ct2_ch1_rear', label: '腔1后(CT2)', color: '#fca5a5', width: 1.4, dash: [4, 2] }},
  1935. {{ key: 'ct3_ch2_front', label: '腔2前(CT3)', color: '#f59e0b', width: 1.6 }},
  1936. {{ key: 'ct4_ch2_rear', label: '腔2后(CT4)', color: '#fcd34d', width: 1.4, dash: [4, 2] }},
  1937. {{ key: 'ct5_ch3_front', label: '腔3前(CT5)', color: '#22c55e', width: 1.6 }},
  1938. {{ key: 'ct6_ch3_rear', label: '腔3后(CT6)', color: '#86efac', width: 1.4, dash: [4, 2] }},
  1939. {{ key: 'ct7_ch4_front', label: '腔4前(CT7)', color: '#38bdf8', width: 1.6 }},
  1940. {{ key: 'ct8_ch4_rear', label: '腔4后(CT8)', color: '#a855f7', width: 1.5, dash: [4, 2] }},
  1941. {{ key: 'tgt', label: '目标温度', color: '#f43f5e', width: 1.4, dash: [6, 4] }},
  1942. ];
  1943. const enabledChambers = new Set(chamberSeries.map(s => s.key));
  1944. const fixedPositionSeries = [
  1945. {{ key: 'rf_dimm_cpu0_a_c', label: 'RF DIMM CPU0_A', color: '#38bdf8', width: 1.8, group: 'core' }},
  1946. {{ key: 'rf_dimm_cpu1_a_c', label: 'RF DIMM CPU1_A', color: '#818cf8', width: 1.8, group: 'core' }},
  1947. {{ key: 'mt_spd_dimm0_c', label: 'MT SPD DIMM0', color: '#22d3ee', width: 1.2, dash: [3, 2], group: 'core' }},
  1948. {{ key: 'mt_spd_dimm1_c', label: 'MT SPD DIMM1', color: '#c084fc', width: 1.2, dash: [3, 2], group: 'core' }},
  1949. {{ key: 'rf_cpu0_c', label: 'RF CPU0', color: '#22c55e', width: 1.4, group: 'core' }},
  1950. {{ key: 'rf_cpu1_c', label: 'RF CPU1', color: '#84cc16', width: 1.4, group: 'core' }},
  1951. {{ key: 'mt_cpu_c', label: 'MT CPU', color: '#10b981', width: 1.1, dash: [2, 2], group: 'vr' }},
  1952. {{ key: 'rf_mb_c', label: 'RF 主板 MB', color: '#94a3b8', width: 1.2, group: 'core' }},
  1953. {{ key: 'rf_psu0_c', label: 'RF PSU0', color: '#64748b', width: 1.2, group: 'vr' }},
  1954. {{ key: 'rf_pvccin_cpu0_c', label: 'PVCCIN CPU0', color: '#fb7185', width: 1.2, group: 'vr' }},
  1955. {{ key: 'rf_pvccin_cpu1_c', label: 'PVCCIN CPU1', color: '#f43f5e', width: 1.2, dash: [4, 2], group: 'vr' }},
  1956. {{ key: 'rf_pvccfa_cpu0_c', label: 'PVCCFA CPU0', color: '#fbbf24', width: 1.2, group: 'vr' }},
  1957. {{ key: 'rf_pvccfa_cpu1_c', label: 'PVCCFA CPU1', color: '#d97706', width: 1.2, dash: [4, 2], group: 'vr' }},
  1958. {{ key: 'rf_pvccd_cpu0_c', label: 'PVCCD CPU0', color: '#34d399', width: 1.2, group: 'vr' }},
  1959. {{ key: 'rf_pvccd_cpu1_c', label: 'PVCCD CPU1', color: '#059669', width: 1.2, dash: [4, 2], group: 'vr' }},
  1960. ];
  1961. const bmcPalette = ['#f97316', '#ec4899', '#eab308', '#14b8a6', '#a855f7', '#06b6d4'];
  1962. let activePositionSeries = [];
  1963. let enabledPositions = new Set();
  1964. const pwrSeries = [
  1965. {{ key: 'rf_total_power_w', label: '整机功耗(W)', color: '#38bdf8', width: 1.6, axis: 'left', group: 'power' }},
  1966. {{ key: 'rf_cpu0_power_avg_w', label: 'CPU0功耗(W)', color: '#818cf8', width: 1.3, axis: 'left', group: 'power' }},
  1967. {{ key: 'rf_cpu1_power_avg_w', label: 'CPU1功耗(W)', color: '#c084fc', width: 1.3, axis: 'left', group: 'power' }},
  1968. {{ key: 'rf_ddr0_power_w', label: 'DDR0(W)×10', color: '#22c55e', width: 1.5, scale: 10, axis: 'left', group: 'power' }},
  1969. {{ key: 'rf_ddr1_power_w', label: 'DDR1(W)×10', color: '#10b981', width: 1.1, scale: 10, axis: 'left', group: 'extra' }},
  1970. {{ key: 'rf_ddr2_power_w', label: 'DDR2(W)×10', color: '#f59e0b', width: 1.5, scale: 10, axis: 'left', group: 'power' }},
  1971. {{ key: 'rf_ddr3_power_w', label: 'DDR3(W)×10', color: '#fbbf24', width: 1.1, scale: 10, axis: 'left', group: 'extra' }},
  1972. {{ key: 'rf_dimm_power_cpu0_w', label: 'DIMM0功耗×10', color: '#06b6d4', width: 1.2, scale: 10, axis: 'left', group: 'extra' }},
  1973. {{ key: 'rf_dimm_power_cpu1_w', label: 'DIMM1功耗×10', color: '#ec4899', width: 1.2, scale: 10, axis: 'left', group: 'extra' }},
  1974. {{ key: 'rf_fan1_rpm', label: 'FAN1(RPM)', color: '#38bdf8', width: 1.3, axis: 'left', group: 'fans' }},
  1975. {{ key: 'rf_fan2_rpm', label: 'FAN2(RPM)', color: '#22c55e', width: 1.3, axis: 'left', group: 'fans' }},
  1976. {{ key: 'rf_fan3_rpm', label: 'FAN3(RPM)', color: '#f59e0b', width: 1.3, axis: 'left', group: 'fans' }},
  1977. {{ key: 'rf_fan4_rpm', label: 'FAN4(RPM)', color: '#a855f7', width: 1.3, axis: 'left', group: 'fans' }},
  1978. {{ key: 'rf_fan5_rpm', label: 'FAN5(RPM)', color: '#ef4444', width: 1.3, axis: 'left', group: 'fans' }},
  1979. {{ key: 'cmd_ptc_pct', label: '罩PTC(%)', color: '#ef4444', width: 1.2, axis: 'right', group: 'power' }},
  1980. {{ key: 'cmd_fan_front_pct', label: '罩前扇(%)', color: '#06b6d4', width: 1.2, axis: 'right', group: 'power' }},
  1981. {{ key: 'cmd_fan_rear_pct', label: '罩后扇(%)', color: '#fb7185', width: 1.2, dash: [3, 2], axis: 'right', group: 'power' }},
  1982. ];
  1983. const enabledPwr = new Set(pwrSeries.filter(s => s.group === 'power').map(s => s.key));
  1984. const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}}[c]));
  1985. const fmtR = (st, unit='°C') => st ? `${{st.min}}~${{st.max}}${{unit}} (${{st.start}}→${{st.end}})` : '-';
  1986. const fmtMM = (st, unit='') => st ? `${{st.min}}~${{st.max}}${{unit}}` : '-';
  1987. document.getElementById('hdr-sub').textContent =
  1988. `来源: ${{DATA.meta.input_path}} (${{DATA.meta.source_kind}}) | 工位数: ${{DATA.meta.station_count}} | 总样本: ${{DATA.meta.total_1hz_rows.toLocaleString()}} 行 | 模式: 逐腔室/位置单独解析 (无均值)`;
  1989. const sel = document.getElementById('station-select');
  1990. stationKeys.forEach(k => {{
  1991. const opt = document.createElement('option');
  1992. opt.value = k;
  1993. const s = DATA.stations[k];
  1994. opt.textContent = `${{k}} (${{s.integrity.master_rows}}行 · ${{(s.station_info.cpu_names[0] || '').replace('Intel(R) Xeon(R) ', '')}})`;
  1995. sel.appendChild(opt);
  1996. }});
  1997. sel.addEventListener('change', () => {{
  1998. activeKey = sel.value;
  1999. zoomStart = 0;
  2000. zoomEnd = null;
  2001. hoverIdx = null;
  2002. renderStation();
  2003. }});
  2004. document.getElementById('btn-theme').addEventListener('click', () => {{
  2005. document.body.classList.toggle('light');
  2006. drawCharts();
  2007. drawAlgoChart();
  2008. }});
  2009. document.querySelectorAll('.tab-btn').forEach(btn => {{
  2010. btn.addEventListener('click', () => {{
  2011. document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  2012. document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
  2013. btn.classList.add('active');
  2014. document.getElementById(btn.dataset.tab).classList.add('active');
  2015. if (btn.dataset.tab === 'tab-charts') drawCharts();
  2016. if (btn.dataset.tab === 'tab-algos') drawAlgoChart();
  2017. }});
  2018. }});
  2019. function buildLegends() {{
  2020. const ser = DATA.series[activeKey];
  2021. const bmcItems = (ser.active_bmc_channels || []).map((b, idx) => ({{
  2022. key: b.col, label: `MCU ${{b.label}}`, color: bmcPalette[idx % bmcPalette.length], width: 1.5, group: 'core',
  2023. }}));
  2024. activePositionSeries = [...bmcItems, ...fixedPositionSeries];
  2025. enabledPositions = new Set(activePositionSeries.filter(s => s.group === 'core').map(s => s.key));
  2026. const make = (elId, list, set) => {{
  2027. const el = document.getElementById(elId);
  2028. el.innerHTML = '';
  2029. list.forEach(item => {{
  2030. const sp = document.createElement('span');
  2031. sp.className = 'legend-item' + (set.has(item.key) ? '' : ' off');
  2032. sp.innerHTML = `<span class="swatch" style="background:${{item.color}}"></span>${{esc(item.label)}}`;
  2033. sp.onclick = () => {{
  2034. if (set.has(item.key)) set.delete(item.key); else set.add(item.key);
  2035. sp.classList.toggle('off');
  2036. drawCharts();
  2037. }};
  2038. el.appendChild(sp);
  2039. }});
  2040. }};
  2041. make('legend-chambers', chamberSeries, enabledChambers);
  2042. make('legend-positions', activePositionSeries, enabledPositions);
  2043. make('legend-pwr', pwrSeries, enabledPwr);
  2044. }}
  2045. document.querySelectorAll('[data-ct-preset]').forEach(btn => {{
  2046. btn.onclick = () => {{
  2047. const p = btn.dataset.ctPreset;
  2048. enabledChambers.clear();
  2049. chamberSeries.forEach(s => {{
  2050. if (p === 'all' || s.key === 'tgt') enabledChambers.add(s.key);
  2051. else if (p === 'ch1' && s.key.includes('ch1')) enabledChambers.add(s.key);
  2052. else if (p === 'ch2' && s.key.includes('ch2')) enabledChambers.add(s.key);
  2053. else if (p === 'ch3' && s.key.includes('ch3')) enabledChambers.add(s.key);
  2054. else if (p === 'ch4' && s.key.includes('ch4')) enabledChambers.add(s.key);
  2055. else if (p === 'front' && s.key.endsWith('_front')) enabledChambers.add(s.key);
  2056. else if (p === 'rear' && s.key.endsWith('_rear')) enabledChambers.add(s.key);
  2057. }});
  2058. buildLegendSync('legend-chambers', chamberSeries, enabledChambers);
  2059. drawCharts();
  2060. }};
  2061. }});
  2062. document.querySelectorAll('[data-pos-preset]').forEach(btn => {{
  2063. btn.onclick = () => {{
  2064. const p = btn.dataset.posPreset;
  2065. enabledPositions.clear();
  2066. activePositionSeries.forEach(s => {{
  2067. if (p === 'all' || s.group === p) enabledPositions.add(s.key);
  2068. }});
  2069. buildLegendSync('legend-positions', activePositionSeries, enabledPositions);
  2070. drawCharts();
  2071. }};
  2072. }});
  2073. document.querySelectorAll('[data-pwr-preset]').forEach(btn => {{
  2074. btn.onclick = () => {{
  2075. const p = btn.dataset.pwrPreset;
  2076. enabledPwr.clear();
  2077. pwrSeries.forEach(s => {{
  2078. if (p === 'all' || s.group === p) enabledPwr.add(s.key);
  2079. }});
  2080. buildLegendSync('legend-pwr', pwrSeries, enabledPwr);
  2081. drawCharts();
  2082. }};
  2083. }});
  2084. function buildLegendSync(elId, list, set) {{
  2085. const el = document.getElementById(elId);
  2086. Array.from(el.children).forEach((node, idx) => {{
  2087. node.classList.toggle('off', !set.has(list[idx].key));
  2088. }});
  2089. }}
  2090. function renderKpis() {{
  2091. const s = DATA.stations[activeKey];
  2092. const m = DATA.meta;
  2093. const integ = s.integrity;
  2094. const info = s.station_info;
  2095. const ov = s.overall_sensors || {{}};
  2096. const cs = ov.chamber_sensors || {{}};
  2097. const rf = ov.redfish_temps || {{}};
  2098. const errCls = integ.mt_total_errors === 0 ? 'pass' : 'fail';
  2099. const tplCls = integ.template_all_pass ? 'pass' : 'warn';
  2100. const resCnt = integ.residual_prelaunch_findings.reduce((a, b) => a + b.residual_rows, 0);
  2101. const ctKeys = Object.keys(cs).filter(k => cs[k]);
  2102. const ctMinAll = ctKeys.length ? Math.min(...ctKeys.map(k => cs[k].min)) : '-';
  2103. const ctMaxAll = ctKeys.length ? Math.max(...ctKeys.map(k => cs[k].max)) : '-';
  2104. document.getElementById('kpi-grid').innerHTML = `
  2105. <div class="kpi-card">
  2106. <div class="kpi-label">全套样本 / 当前工位</div>
  2107. <div class="kpi-val">${{m.total_1hz_rows.toLocaleString()}} <span style="font-size:12px;color:var(--muted)">行</span></div>
  2108. <div class="kpi-sub">${{esc(info.station_id)}}: ${{integ.master_rows.toLocaleString()}}行 (${{esc(info.total_duration_hms || '-')}})</div>
  2109. </div>
  2110. <div class="kpi-card">
  2111. <div class="kpi-label">8路腔室独立传感器全量范围</div>
  2112. <div class="kpi-val">${{ctMinAll}}~${{ctMaxAll}}°C</div>
  2113. <div class="kpi-sub">腔1..4 前/后全部单独展示 (无均值)</div>
  2114. </div>
  2115. <div class="kpi-card">
  2116. <div class="kpi-label">RF DIMM0 / DIMM1 独立范围</div>
  2117. <div class="kpi-val" style="font-size:16px">${{fmtMM(rf.rf_dimm_cpu0_a_c, '°C')}} / ${{fmtMM(rf.rf_dimm_cpu1_a_c, '°C')}}</div>
  2118. <div class="kpi-sub">有效 BMC 通道: ${{esc((info.active_bmc_channels || []).map(b=>b.key).join(', '))}}</div>
  2119. </div>
  2120. <div class="kpi-card">
  2121. <div class="kpi-label">MT 错误与模板审计</div>
  2122. <div class="kpi-val"><span class="badge ${{errCls}}">${{integ.mt_total_errors}} ERR</span> <span class="badge ${{tplCls}}">${{integ.template_all_pass ? '34列PASS' : 'WARN'}}</span></div>
  2123. <div class="kpi-sub">${{esc(integ.schema_version)}} · 残留标签 ${{resCnt}}s · 失配 ${{integ.template_total_mismatches}}</div>
  2124. </div>
  2125. `;
  2126. }}
  2127. function buildZoomBar() {{
  2128. const bar = document.getElementById('zoom-bar');
  2129. const ser = DATA.series[activeKey];
  2130. const n = ser.cols.seq.length;
  2131. if (zoomEnd === null || zoomEnd > n) zoomEnd = n;
  2132. bar.innerHTML = '';
  2133. const mkBtn = (label, a, b) => {{
  2134. const btn = document.createElement('button');
  2135. btn.type = 'button';
  2136. btn.textContent = label;
  2137. if (zoomStart === a && zoomEnd === b) btn.classList.add('active');
  2138. btn.onclick = () => {{ zoomStart = a; zoomEnd = b; buildZoomBar(); drawCharts(); }};
  2139. bar.appendChild(btn);
  2140. }};
  2141. mkBtn(`全过程 (${{n}}s)`, 0, n);
  2142. [
  2143. ['Phase0 初降温', p => p.startsWith('phase0_')],
  2144. ['Test1 70°C预热', p => p.startsWith('test1_')],
  2145. ['Test2 70°C MT', p => p.startsWith('test2_')],
  2146. ['间歇降温→40°C', p => p.startsWith('phase_inter_')],
  2147. ['Test3 40°C MT', p => p.startsWith('test3_')],
  2148. ].forEach(([label, pred]) => {{
  2149. let lo = null, hi = null;
  2150. for (let i = 0; i < n; i++) {{
  2151. const p = ser.phase_names[ser.cols.ph[i]];
  2152. if (pred(p)) {{ if (lo === null) lo = i; hi = i + 1; }}
  2153. }}
  2154. if (lo !== null) mkBtn(label, lo, hi);
  2155. }});
  2156. }}
  2157. function setupCanvas(canvas) {{
  2158. const rect = canvas.parentElement.getBoundingClientRect();
  2159. const dpr = window.devicePixelRatio || 1;
  2160. const w = Math.max(320, Math.floor(rect.width));
  2161. const h = Math.max(240, Math.floor(rect.height));
  2162. canvas.width = w * dpr;
  2163. canvas.height = h * dpr;
  2164. const ctx = canvas.getContext('2d');
  2165. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2166. return {{ ctx, w, h }};
  2167. }}
  2168. function drawTimeSeries(canvasId, seriesList, enabledSet, rightAxis) {{
  2169. const canvas = document.getElementById(canvasId);
  2170. if (!canvas) return;
  2171. const {{ ctx, w, h }} = setupCanvas(canvas);
  2172. const ser = DATA.series[activeKey];
  2173. const cols = ser.cols;
  2174. const n = cols.seq.length;
  2175. const sIdx = Math.max(0, zoomStart);
  2176. const eIdx = Math.min(n, zoomEnd ?? n);
  2177. const span = Math.max(1, eIdx - sIdx);
  2178. const pad = {{ l: 54, r: rightAxis ? 48 : 18, t: 14, b: 26 }};
  2179. const pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
  2180. const cs = getComputedStyle(document.body);
  2181. const borderCol = cs.getPropertyValue('--border').trim();
  2182. const mutedCol = cs.getPropertyValue('--muted').trim();
  2183. let yMin = Infinity, yMax = -Infinity;
  2184. seriesList.forEach(s => {{
  2185. if (!enabledSet.has(s.key) || s.axis === 'right') return;
  2186. const arr = cols[s.key];
  2187. if (!arr) return;
  2188. const sc = s.scale || 1;
  2189. for (let i = sIdx; i < eIdx; i++) {{
  2190. const v = arr[i];
  2191. if (v !== null && v !== undefined) {{
  2192. const sv = v * sc;
  2193. if (sv < yMin) yMin = sv;
  2194. if (sv > yMax) yMax = sv;
  2195. }}
  2196. }}
  2197. }});
  2198. if (!isFinite(yMin)) {{ yMin = 0; yMax = 100; }}
  2199. const yPad = Math.max(2, (yMax - yMin) * 0.08);
  2200. yMin = Math.floor(yMin - yPad);
  2201. yMax = Math.ceil(yMax + yPad);
  2202. ctx.strokeStyle = borderCol;
  2203. ctx.lineWidth = 1;
  2204. ctx.font = '11px sans-serif';
  2205. ctx.fillStyle = mutedCol;
  2206. for (let g = 0; g <= 5; g++) {{
  2207. const yy = pad.t + ph - (g / 5) * ph;
  2208. ctx.beginPath(); ctx.moveTo(pad.l, yy); ctx.lineTo(pad.l + pw, yy); ctx.stroke();
  2209. ctx.textAlign = 'right';
  2210. ctx.fillText((yMin + (g / 5) * (yMax - yMin)).toFixed(0), pad.l - 6, yy + 4);
  2211. if (rightAxis) {{
  2212. ctx.textAlign = 'left';
  2213. ctx.fillText((g * 20) + '%', pad.l + pw + 6, yy + 4);
  2214. }}
  2215. }}
  2216. ctx.textAlign = 'center';
  2217. for (let t = 0; t <= 6; t++) {{
  2218. const idx = Math.min(n - 1, sIdx + Math.floor((t / 6) * (span - 1)));
  2219. const xx = pad.l + (t / 6) * pw;
  2220. ctx.fillText(cols.ts[idx] || '', xx, h - 7);
  2221. }}
  2222. ctx.fillStyle = 'rgba(245,158,11,0.12)';
  2223. for (let i = sIdx; i < eIdx; i++) {{
  2224. if (cols.res[i]) {{
  2225. const x1 = pad.l + ((i - sIdx) / span) * pw;
  2226. const x2 = pad.l + ((i + 1 - sIdx) / span) * pw;
  2227. ctx.fillRect(x1, pad.t, Math.max(1, x2 - x1), ph);
  2228. }}
  2229. }}
  2230. const xAt = i => pad.l + ((i - sIdx) / Math.max(1, span - 1)) * pw;
  2231. const yLeft = v => pad.t + ph - ((v - yMin) / Math.max(1e-6, yMax - yMin)) * ph;
  2232. const yRight = v => pad.t + ph - (Math.max(0, Math.min(100, v)) / 100) * ph;
  2233. const stride = Math.max(1, Math.floor(span / (pw * 2)));
  2234. seriesList.forEach(s => {{
  2235. if (!enabledSet.has(s.key)) return;
  2236. const arr = cols[s.key];
  2237. if (!arr) return;
  2238. const sc = s.scale || 1;
  2239. const yf = s.axis === 'right' ? yRight : yLeft;
  2240. ctx.save();
  2241. ctx.strokeStyle = s.color;
  2242. ctx.lineWidth = s.width;
  2243. if (s.dash) ctx.setLineDash(s.dash);
  2244. ctx.beginPath();
  2245. let started = false;
  2246. for (let i = sIdx; i < eIdx; i += stride) {{
  2247. const v = arr[i];
  2248. if (v === null || v === undefined) {{ started = false; continue; }}
  2249. const x = xAt(i), y = yf(v * sc);
  2250. if (!started) {{ ctx.moveTo(x, y); started = true; }}
  2251. else ctx.lineTo(x, y);
  2252. }}
  2253. ctx.stroke();
  2254. ctx.restore();
  2255. }});
  2256. if (dragStartIdx !== null && dragCurIdx !== null && dragStartIdx !== dragCurIdx) {{
  2257. const lo = Math.max(sIdx, Math.min(dragStartIdx, dragCurIdx));
  2258. const hi = Math.min(eIdx - 1, Math.max(dragStartIdx, dragCurIdx));
  2259. const x1 = xAt(lo), x2 = xAt(hi);
  2260. ctx.fillStyle = 'rgba(56,189,248,0.18)';
  2261. ctx.fillRect(x1, pad.t, Math.max(2, x2 - x1), ph);
  2262. }}
  2263. if (hoverIdx !== null && hoverIdx >= sIdx && hoverIdx < eIdx) {{
  2264. const hx = xAt(hoverIdx);
  2265. ctx.strokeStyle = 'rgba(255,255,255,0.45)';
  2266. ctx.lineWidth = 1;
  2267. ctx.beginPath(); ctx.moveTo(hx, pad.t); ctx.lineTo(hx, pad.t + ph); ctx.stroke();
  2268. }}
  2269. }}
  2270. function attachHover(canvasId, rightAxis) {{
  2271. const canvas = document.getElementById(canvasId);
  2272. const tip = document.getElementById('tooltip');
  2273. const idxFromEvent = ev => {{
  2274. const rect = canvas.getBoundingClientRect();
  2275. const x = ev.clientX - rect.left;
  2276. const ser = DATA.series[activeKey];
  2277. const n = ser.cols.seq.length;
  2278. const sIdx = Math.max(0, zoomStart);
  2279. const eIdx = Math.min(n, zoomEnd ?? n);
  2280. const padL = 54, padR = rightAxis ? 48 : 18;
  2281. const pw = rect.width - padL - padR;
  2282. const ratio = Math.max(0, Math.min(1, (x - padL) / Math.max(1, pw)));
  2283. return Math.min(n - 1, sIdx + Math.round(ratio * Math.max(0, eIdx - sIdx - 1)));
  2284. }};
  2285. canvas.onmousedown = ev => {{ dragStartIdx = idxFromEvent(ev); dragCurIdx = dragStartIdx; }};
  2286. canvas.onmouseup = () => {{
  2287. if (dragStartIdx !== null && dragCurIdx !== null && Math.abs(dragCurIdx - dragStartIdx) >= 5) {{
  2288. zoomStart = Math.min(dragStartIdx, dragCurIdx);
  2289. zoomEnd = Math.max(dragStartIdx, dragCurIdx) + 1;
  2290. buildZoomBar();
  2291. }}
  2292. dragStartIdx = null; dragCurIdx = null; drawCharts();
  2293. }};
  2294. canvas.ondblclick = () => {{
  2295. const ser = DATA.series[activeKey];
  2296. zoomStart = 0; zoomEnd = ser.cols.seq.length; buildZoomBar(); drawCharts();
  2297. }};
  2298. canvas.onmousemove = ev => {{
  2299. const ser = DATA.series[activeKey];
  2300. hoverIdx = idxFromEvent(ev);
  2301. if (dragStartIdx !== null) dragCurIdx = hoverIdx;
  2302. drawCharts();
  2303. const c = ser.cols;
  2304. const i = hoverIdx;
  2305. const bmcTxt = (ser.active_bmc_channels || []).map(b => `${{b.key}}:${{c[b.col]?.[i] ?? '-'}}`).join(' · ');
  2306. tip.style.display = 'block';
  2307. tip.style.left = Math.min(window.innerWidth - 480, ev.clientX + 14) + 'px';
  2308. tip.style.top = Math.min(window.innerHeight - 310, ev.clientY + 14) + 'px';
  2309. tip.innerHTML = `
  2310. <div><b>${{esc(activeKey)}}</b> · #${{c.seq[i]}} · <b>${{esc(c.ts[i])}}</b> (${{c.t[i]}}s)</div>
  2311. <div>阶段: <span class="mono">${{esc(ser.phase_names[c.ph[i]])}}</span></div>
  2312. <div>算法: <b>${{esc(ser.algo_names[c.al[i]])}}</b>${{c.res[i] ? ' <span class="badge warn">残留标签</span>' : ''}}</div>
  2313. <div>MCU: ${{esc(ser.mode_names[c.md[i]])}} · Target ${{c.tgt[i]}}°C · PTC ${{c.cmd_ptc_pct[i] ?? '-'}}% · 罩扇 F:${{c.cmd_fan_front_pct[i] ?? '-'}}% R:${{c.cmd_fan_rear_pct[i] ?? '-'}}%</div>
  2314. <div class="mono">腔1(前/后): <b>${{c.ct1_ch1_front[i]}} / ${{c.ct2_ch1_rear[i]}}</b> · 腔2: <b>${{c.ct3_ch2_front[i]}} / ${{c.ct4_ch2_rear[i]}}</b></div>
  2315. <div class="mono">腔3(前/后): <b>${{c.ct5_ch3_front[i]}} / ${{c.ct6_ch3_rear[i]}}</b> · 腔4: <b>${{c.ct7_ch4_front[i]}} / ${{c.ct8_ch4_rear[i]}}</b></div>
  2316. <div>RF DIMM0/1: <b>${{c.rf_dimm_cpu0_a_c[i]}} / ${{c.rf_dimm_cpu1_a_c[i]}}°C</b> · ${{esc(bmcTxt)}}</div>
  2317. <div>CPU0/1: ${{c.rf_cpu0_c[i]}}/${{c.rf_cpu1_c[i]}}°C · MB/PSU: ${{c.rf_mb_c[i]}}/${{c.rf_psu0_c[i]}}°C · PVCCIN:${{c.rf_pvccin_cpu0_c[i]}}/${{c.rf_pvccin_cpu1_c[i]}}</div>
  2318. <div>整机: <b>${{c.rf_total_power_w[i]}}W</b> · DDR0/1/2/3: <b>${{c.rf_ddr0_power_w[i]}}/${{c.rf_ddr1_power_w[i]}}/${{c.rf_ddr2_power_w[i]}}/${{c.rf_ddr3_power_w[i]}}W</b> · CPU0/1:${{c.rf_cpu0_power_avg_w[i]}}/${{c.rf_cpu1_power_avg_w[i]}}W</div>
  2319. <div class="mono">RF FAN1..5: ${{c.rf_fan1_rpm[i]}}/${{c.rf_fan2_rpm[i]}}/${{c.rf_fan3_rpm[i]}}/${{c.rf_fan4_rpm[i]}}/${{c.rf_fan5_rpm[i]}}</div>
  2320. `;
  2321. }};
  2322. canvas.onmouseleave = () => {{ hoverIdx = null; dragStartIdx = null; dragCurIdx = null; tip.style.display = 'none'; drawCharts(); }};
  2323. }}
  2324. function drawCharts() {{
  2325. drawTimeSeries('chart-chambers', chamberSeries, enabledChambers, false);
  2326. drawTimeSeries('chart-positions', activePositionSeries, enabledPositions, false);
  2327. drawTimeSeries('chart-pwr', pwrSeries, enabledPwr, true);
  2328. }}
  2329. function renderPhaseTables() {{
  2330. const s = DATA.stations[activeKey];
  2331. const bmcKeys = (s.station_info.active_bmc_channels || []).map(b => b.key);
  2332. let hc1 = `<table><thead><tr><th>阶段</th><th>行数/时长</th><th>腔1前 (CT1)</th><th>腔1后 (CT2)</th><th>腔2前 (CT3)</th><th>腔2后 (CT4)</th><th>腔3前 (CT5)</th><th>腔3后 (CT6)</th><th>腔4前 (CT7)</th><th>腔4后 (CT8)</th></tr></thead><tbody>`;
  2333. Object.entries(s.phases_detail).forEach(([fn, p]) => {{
  2334. const cs = p.chamber_sensors || {{}};
  2335. hc1 += `<tr><td class="mono">${{esc(fn.replace('_comprehensive.csv',''))}}</td><td class="mono">${{p.rows}} / ${{esc(p.duration_hms)}}</td>` +
  2336. ['ct1_ch1_front','ct2_ch1_rear','ct3_ch2_front','ct4_ch2_rear','ct5_ch3_front','ct6_ch3_rear','ct7_ch4_front','ct8_ch4_rear']
  2337. .map(col => `<td class="mono">${{esc(fmtR(cs[col]))}}</td>`).join('') + `</tr>`;
  2338. }});
  2339. hc1 += '</tbody></table>';
  2340. document.getElementById('phase-chambers-table').innerHTML = hc1;
  2341. let hp2 = `<table><thead><tr><th>阶段</th><th>RF DIMM0</th><th>RF DIMM1</th>${{bmcKeys.map(k => `<th>MCU ${{esc(k)}}</th>`).join('')}}<th>MT SPD0/1</th><th>RF CPU0 / CPU1</th><th>RF MB / PSU0</th><th>PVCCIN 0/1</th><th>PVCCFA 0/1</th><th>PVCCD 0/1</th></tr></thead><tbody>`;
  2342. Object.entries(s.phases_detail).forEach(([fn, p]) => {{
  2343. const rf = p.redfish_temps || {{}}, bmc = p.bmc_channels || {{}}, mt = p.mt_console_temps || {{}};
  2344. hp2 += `<tr>
  2345. <td class="mono">${{esc(fn.replace('_comprehensive.csv',''))}}</td>
  2346. <td class="mono">${{esc(fmtR(rf.rf_dimm_cpu0_a_c))}}</td>
  2347. <td class="mono">${{esc(fmtR(rf.rf_dimm_cpu1_a_c))}}</td>
  2348. ${{bmcKeys.map(k => `<td class="mono">${{esc(fmtR(bmc[k]))}}</td>`).join('')}}
  2349. <td class="mono">${{esc(fmtMM(mt.mt_spd_dimm0_c))}} / ${{esc(fmtMM(mt.mt_spd_dimm1_c))}}</td>
  2350. <td class="mono">${{esc(fmtMM(rf.rf_cpu0_c))}} / ${{esc(fmtMM(rf.rf_cpu1_c))}}</td>
  2351. <td class="mono">${{esc(fmtMM(rf.rf_mb_c))}} / ${{esc(fmtMM(rf.rf_psu0_c))}}</td>
  2352. <td class="mono">${{esc(fmtMM(rf.rf_pvccin_cpu0_c))}} / ${{esc(fmtMM(rf.rf_pvccin_cpu1_c))}}</td>
  2353. <td class="mono">${{esc(fmtMM(rf.rf_pvccfa_cpu0_c))}} / ${{esc(fmtMM(rf.rf_pvccfa_cpu1_c))}}</td>
  2354. <td class="mono">${{esc(fmtMM(rf.rf_pvccd_cpu0_c))}} / ${{esc(fmtMM(rf.rf_pvccd_cpu1_c))}}</td>
  2355. </tr>`;
  2356. }});
  2357. hp2 += '</tbody></table>';
  2358. document.getElementById('phase-positions-table').innerHTML = hp2;
  2359. let hp3 = `<table><thead><tr><th>阶段</th><th>整机功耗</th><th>PSU Pin/Pout</th><th>DDR0 / DDR1 / DDR2 / DDR3</th><th>DIMM CPU0/1 功耗</th><th>CPU0 / CPU1 功耗</th><th>罩 PTC / 前扇 / 后扇</th><th>RF FAN1..5 (RPM)</th></tr></thead><tbody>`;
  2360. Object.entries(s.phases_detail).forEach(([fn, p]) => {{
  2361. const pw = p.power_rails || {{}}, fa = p.fans_and_actuators || {{}};
  2362. hp3 += `<tr>
  2363. <td class="mono">${{esc(fn.replace('_comprehensive.csv',''))}}</td>
  2364. <td class="mono">${{esc(fmtMM(pw.rf_total_power_w, 'W'))}}</td>
  2365. <td class="mono">${{esc(fmtMM(pw.rf_psu0_pin_w))}} / ${{esc(fmtMM(pw.rf_psu0_pout_w))}}W</td>
  2366. <td class="mono">${{[0,1,2,3].map(i => fmtMM(pw[`rf_ddr${{i}}_power_w`])).join(' / ')}}W</td>
  2367. <td class="mono">${{esc(fmtMM(pw.rf_dimm_power_cpu0_w))}} / ${{esc(fmtMM(pw.rf_dimm_power_cpu1_w))}}W</td>
  2368. <td class="mono">${{esc(fmtMM(pw.rf_cpu0_power_avg_w))}} / ${{esc(fmtMM(pw.rf_cpu1_power_avg_w))}}W</td>
  2369. <td class="mono">${{esc(fmtMM(fa.cmd_ptc_pct,'%'))}} / ${{esc(fmtMM(fa.cmd_fan_front_pct,'%'))}} / ${{esc(fmtMM(fa.cmd_fan_rear_pct,'%'))}}</td>
  2370. <td class="mono">${{[1,2,3,4,5].map(i => fmtMM(fa[`rf_fan${{i}}_rpm`])).join(' / ')}}</td>
  2371. </tr>`;
  2372. }});
  2373. hp3 += '</tbody></table>';
  2374. document.getElementById('phase-power-table').innerHTML = hp3;
  2375. const cdMap = {{}};
  2376. s.cooldown_outcomes.forEach(c => {{ cdMap[c.phase_group + '#' + c.round] = c; }});
  2377. let hcd = `<table><thead><tr><th>降温阶段</th><th>Round</th><th>吹扫结果/耗时</th><th>腔1前/后反弹</th><th>腔2前/后反弹</th><th>腔3前/后反弹</th><th>腔4前/后反弹</th><th>静置末 DIMM0 / DIMM1</th></tr></thead><tbody>`;
  2378. s.antirebound_soaks.forEach(sk => {{
  2379. const cd = cdMap[sk.phase_group + '#' + sk.round] || {{}};
  2380. const pcr = sk.per_chamber_rebound || {{}};
  2381. const pairCell = (fc, rc) => {{
  2382. const f = pcr[fc], r = pcr[rc];
  2383. const fs = f ? `${{f.start}}→${{f.peak}}(+${{f.rebound}})` : '-';
  2384. const rs = r ? `${{r.start}}→${{r.peak}}(+${{r.rebound}})` : '-';
  2385. return `<td class="mono">${{fs}} / ${{rs}}</td>`;
  2386. }};
  2387. hcd += `<tr>
  2388. <td class="mono">${{esc(sk.phase_group)}}</td>
  2389. <td>R${{sk.round}}</td>
  2390. <td>${{esc(cd.outcome || '-')}} (${{cd.duration_s ?? '-'}}s)</td>
  2391. ${{pairCell('ct1_ch1_front','ct2_ch1_rear')}}
  2392. ${{pairCell('ct3_ch2_front','ct4_ch2_rear')}}
  2393. ${{pairCell('ct5_ch3_front','ct6_ch3_rear')}}
  2394. ${{pairCell('ct7_ch4_front','ct8_ch4_rear')}}
  2395. <td class="mono">${{sk.dimm0_end_csv ?? '-'}} / ${{sk.dimm1_end_csv ?? '-'}}°C</td>
  2396. </tr>`;
  2397. }});
  2398. hcd += '</tbody></table>';
  2399. document.getElementById('cooldown-table').innerHTML = hcd;
  2400. let hh = `<table><thead><tr><th>预热阶段</th><th>移交耗时</th><th>移交瞬时 CT8 [1前,1后..4前,4后]</th><th>移交 BMC0/12</th><th>+300s CT8</th><th>+300s RF DIMM0/1</th></tr></thead><tbody>`;
  2401. s.preheat_handovers.forEach(hv => {{
  2402. const p3 = hv.post_300s_sensors || {{}};
  2403. hh += `<tr>
  2404. <td class="mono">${{esc(hv.phase)}}</td>
  2405. <td class="mono">${{(hv.preheat_elapsed_s ?? 0).toFixed(1)}}s</td>
  2406. <td class="mono">${{esc(JSON.stringify(hv.ct8 || []))}}</td>
  2407. <td class="mono">${{hv.bmc0 ?? '-'}} / ${{hv.bmc12 ?? '-'}}°C</td>
  2408. <td class="mono">${{esc(JSON.stringify(p3.ct8 || []))}}</td>
  2409. <td class="mono">${{p3.rf_dimm_cpu0_a_c ?? '-'}} / ${{p3.rf_dimm_cpu1_a_c ?? '-'}}°C</td>
  2410. </tr>`;
  2411. }});
  2412. hh += '</tbody></table>';
  2413. document.getElementById('handover-table').innerHTML = hh;
  2414. }}
  2415. function populateAlgoSelectors() {{
  2416. const pSel = document.getElementById('algo-phase-select');
  2417. const prev = pSel.value;
  2418. const allPhases = new Set();
  2419. stationKeys.forEach(k => Object.keys(DATA.stations[k].algorithms_by_phase).forEach(p => allPhases.add(p)));
  2420. pSel.innerHTML = '';
  2421. Array.from(allPhases).forEach(p => {{
  2422. const o = document.createElement('option');
  2423. o.value = p; o.textContent = p;
  2424. pSel.appendChild(o);
  2425. }});
  2426. if (prev && allPhases.has(prev)) pSel.value = prev;
  2427. }}
  2428. function drawAlgoChart() {{
  2429. const canvas = document.getElementById('chart-algo');
  2430. if (!canvas) return;
  2431. const {{ ctx, w, h }} = setupCanvas(canvas);
  2432. const phase = document.getElementById('algo-phase-select').value;
  2433. const metric = document.getElementById('algo-metric-select').value;
  2434. const s = DATA.stations[activeKey];
  2435. const algos = s.algorithms_by_phase[phase] || {{}};
  2436. const entries = Object.entries(algos).filter(([, v]) => v.test_num !== null || v.samples_s >= 5);
  2437. const pad = {{ l: 50, r: 18, t: 28, b: 64 }};
  2438. const pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
  2439. const cs = getComputedStyle(document.body);
  2440. const borderCol = cs.getPropertyValue('--border').trim();
  2441. const mutedCol = cs.getPropertyValue('--muted').trim();
  2442. let maxV = 1;
  2443. const seriesColors = ['#38bdf8', '#818cf8', '#22c55e', '#f59e0b'];
  2444. const bars = entries.map(([name, av]) => {{
  2445. const pwR = av.power_rails || {{}}, rf = av.redfish_temps || {{}}, chS = av.chamber_sensors || {{}};
  2446. let vals = [];
  2447. if (metric === 'ddr_max') {{
  2448. vals = [(pwR.rf_ddr0_power_w || {{}}).max || 0, (pwR.rf_ddr2_power_w || {{}}).max || 0];
  2449. }} else if (metric === 'dimm_max') {{
  2450. vals = [(rf.rf_dimm_cpu0_a_c || {{}}).max || 0, (rf.rf_dimm_cpu1_a_c || {{}}).max || 0];
  2451. }} else if (metric === 'cpu_pwr_max') {{
  2452. vals = [(pwR.rf_cpu0_power_avg_w || {{}}).max || 0, (pwR.rf_cpu1_power_avg_w || {{}}).max || 0];
  2453. }} else if (metric === 'ch_front_max') {{
  2454. vals = ['ct1_ch1_front','ct3_ch2_front','ct5_ch3_front','ct7_ch4_front'].map(k => (chS[k] || {{}}).max || 0);
  2455. }} else {{
  2456. vals = ['ct2_ch1_rear','ct4_ch2_rear','ct6_ch3_rear','ct8_ch4_rear'].map(k => (chS[k] || {{}}).max || 0);
  2457. }}
  2458. maxV = Math.max(maxV, ...vals);
  2459. return {{ label: av.test_num !== null ? 'T' + av.test_num : name.slice(0, 10), vals, asym: av.is_asymmetric_load }};
  2460. }});
  2461. maxV = Math.ceil(maxV * 1.15);
  2462. ctx.strokeStyle = borderCol;
  2463. ctx.font = '11px sans-serif';
  2464. ctx.fillStyle = mutedCol;
  2465. for (let g = 0; g <= 4; g++) {{
  2466. const yy = pad.t + ph - (g / 4) * ph;
  2467. ctx.beginPath(); ctx.moveTo(pad.l, yy); ctx.lineTo(pad.l + pw, yy); ctx.stroke();
  2468. ctx.textAlign = 'right';
  2469. ctx.fillText((maxV * g / 4).toFixed(1), pad.l - 6, yy + 4);
  2470. }}
  2471. const slotW = pw / Math.max(1, bars.length);
  2472. algoBarsCache = [];
  2473. bars.forEach((b, idx) => {{
  2474. const k = b.vals.length;
  2475. const bw = Math.max(3, Math.min(18, (slotW * 0.78) / k));
  2476. const startX = pad.l + idx * slotW + (slotW - bw * k) / 2;
  2477. b.vals.forEach((v, j) => {{
  2478. const hh = (v / maxV) * ph;
  2479. ctx.fillStyle = (metric === 'ddr_max' && b.asym) ? (j === 0 ? '#ef4444' : '#f59e0b') : seriesColors[j % seriesColors.length];
  2480. ctx.fillRect(startX + j * bw, pad.t + ph - hh, Math.max(2, bw - 1), hh);
  2481. }});
  2482. ctx.fillStyle = mutedCol;
  2483. ctx.textAlign = 'center';
  2484. ctx.fillText(b.label, pad.l + idx * slotW + slotW / 2, pad.t + ph + 16);
  2485. const entry = entries[idx];
  2486. algoBarsCache.push({{ x1: pad.l + idx * slotW, x2: pad.l + (idx + 1) * slotW, name: entry[0], av: entry[1] }});
  2487. }});
  2488. const legendLabels = metric === 'ddr_max' ? ['DDR0 峰值(W)', 'DDR2 峰值(W)']
  2489. : metric === 'dimm_max' ? ['DIMM0 峰值(°C)', 'DIMM1 峰值(°C)']
  2490. : metric === 'cpu_pwr_max' ? ['CPU0 峰值(W)', 'CPU1 峰值(W)']
  2491. : metric === 'ch_front_max' ? ['腔1前', '腔2前', '腔3前', '腔4前']
  2492. : ['腔1后', '腔2后', '腔3后', '腔4后'];
  2493. ctx.textAlign = 'left';
  2494. let lx = pad.l;
  2495. legendLabels.forEach((lbl, j) => {{
  2496. ctx.fillStyle = seriesColors[j % seriesColors.length];
  2497. ctx.fillRect(lx, 6, 10, 10);
  2498. ctx.fillStyle = mutedCol;
  2499. ctx.fillText(lbl, lx + 14, 15);
  2500. lx += 14 + lbl.length * 9 + 18;
  2501. }});
  2502. const tip = document.getElementById('tooltip');
  2503. canvas.onmousemove = ev => {{
  2504. const rect = canvas.getBoundingClientRect();
  2505. const x = ev.clientX - rect.left;
  2506. const hit = algoBarsCache.find(b => x >= b.x1 && x <= b.x2);
  2507. if (!hit) {{ tip.style.display = 'none'; return; }}
  2508. const av = hit.av, ch = av.chamber_sensors || {{}}, rf = av.redfish_temps || {{}}, pwR = av.power_rails || {{}};
  2509. tip.style.display = 'block';
  2510. tip.style.left = Math.min(window.innerWidth - 460, ev.clientX + 14) + 'px';
  2511. tip.style.top = Math.min(window.innerHeight - 250, ev.clientY + 14) + 'px';
  2512. tip.innerHTML = `
  2513. <div><b>${{esc(hit.name)}}</b> (${{av.samples_s}}s · Console:${{av.console_exec_s ?? '-'}}s)</div>
  2514. <div>DIMM0 / DIMM1: <b>${{fmtMM(rf.rf_dimm_cpu0_a_c, '°C')}}</b> / <b>${{fmtMM(rf.rf_dimm_cpu1_a_c, '°C')}}</b></div>
  2515. <div class="mono">腔1(前/后): ${{fmtMM(ch.ct1_ch1_front)}} / ${{fmtMM(ch.ct2_ch1_rear)}} · 腔2: ${{fmtMM(ch.ct3_ch2_front)}} / ${{fmtMM(ch.ct4_ch2_rear)}}</div>
  2516. <div class="mono">腔3(前/后): ${{fmtMM(ch.ct5_ch3_front)}} / ${{fmtMM(ch.ct6_ch3_rear)}} · 腔4: ${{fmtMM(ch.ct7_ch4_front)}} / ${{fmtMM(ch.ct8_ch4_rear)}}</div>
  2517. <div>DDR0 / DDR2: <b>${{fmtMM(pwR.rf_ddr0_power_w, 'W')}}</b> / <b>${{fmtMM(pwR.rf_ddr2_power_w, 'W')}}</b> (${{av.ddr_peak_asymmetry_ratio ?? '-'}}×)</div>
  2518. <div>CPU0 / CPU1 功耗: ${{fmtMM(pwR.rf_cpu0_power_avg_w, 'W')}} / ${{fmtMM(pwR.rf_cpu1_power_avg_w, 'W')}}</div>
  2519. `;
  2520. }};
  2521. canvas.onmouseleave = () => {{ tip.style.display = 'none'; }};
  2522. }}
  2523. function renderAlgoTable() {{
  2524. const phase = document.getElementById('algo-phase-select').value;
  2525. const s = DATA.stations[activeKey];
  2526. const algos = s.algorithms_by_phase[phase] || {{}};
  2527. let h = `<table><thead><tr><th>算法</th><th>样本</th><th>耗时</th><th>RF DIMM0</th><th>RF DIMM1</th><th>BMC0 / BMC12</th><th>腔1前 / 后</th><th>腔2前 / 后</th><th>腔3前 / 后</th><th>腔4前 / 后</th><th>DDR0 / DDR2 功耗</th><th>CPU0 / CPU1 功耗</th><th>非对称</th><th>错</th></tr></thead><tbody>`;
  2528. Object.entries(algos).forEach(([aname, av]) => {{
  2529. const rf = av.redfish_temps || {{}}, bmc = av.bmc_channels || {{}}, cs = av.chamber_sensors || {{}}, pw = av.power_rails || {{}};
  2530. const asym = av.is_asymmetric_load ? `<span class="badge warn">${{av.ddr_peak_asymmetry_ratio}}×</span>` : (av.ddr_peak_asymmetry_ratio ? `${{av.ddr_peak_asymmetry_ratio}}×` : '-');
  2531. h += `<tr>
  2532. <td><b>${{esc(aname)}}</b></td>
  2533. <td class="mono">${{av.samples_s}}s</td>
  2534. <td class="mono">${{av.console_exec_s ?? '-'}}</td>
  2535. <td class="mono">${{esc(fmtMM(rf.rf_dimm_cpu0_a_c, '°C'))}}</td>
  2536. <td class="mono">${{esc(fmtMM(rf.rf_dimm_cpu1_a_c, '°C'))}}</td>
  2537. <td class="mono">${{esc(fmtMM(bmc.BMC0))}} / ${{esc(fmtMM(bmc.BMC12))}}</td>
  2538. <td class="mono">${{esc(fmtMM(cs.ct1_ch1_front))}} / ${{esc(fmtMM(cs.ct2_ch1_rear))}}</td>
  2539. <td class="mono">${{esc(fmtMM(cs.ct3_ch2_front))}} / ${{esc(fmtMM(cs.ct4_ch2_rear))}}</td>
  2540. <td class="mono">${{esc(fmtMM(cs.ct5_ch3_front))}} / ${{esc(fmtMM(cs.ct6_ch3_rear))}}</td>
  2541. <td class="mono">${{esc(fmtMM(cs.ct7_ch4_front))}} / ${{esc(fmtMM(cs.ct8_ch4_rear))}}</td>
  2542. <td class="mono">${{esc(fmtMM(pw.rf_ddr0_power_w, 'W'))}} / ${{esc(fmtMM(pw.rf_ddr2_power_w, 'W'))}}</td>
  2543. <td class="mono">${{esc(fmtMM(pw.rf_cpu0_power_avg_w, 'W'))}} / ${{esc(fmtMM(pw.rf_cpu1_power_avg_w, 'W'))}}</td>
  2544. <td>${{asym}}</td>
  2545. <td class="mono">${{av.cum_errors}}</td>
  2546. </tr>`;
  2547. }});
  2548. h += '</tbody></table>';
  2549. document.getElementById('algo-table').innerHTML = h;
  2550. }}
  2551. function renderAuditTables() {{
  2552. let h1 = `<table><thead><tr><th>工位</th><th>BMC IP</th><th>UID / 固件 / PID</th><th>CPU / 内存</th><th>有效 BMC 通道</th><th>总样本 / 时长</th><th>Schema</th><th>模板核验</th><th>MT 错误</th><th>数据提示</th></tr></thead><tbody>`;
  2553. stationKeys.forEach(k => {{
  2554. const s = DATA.stations[k];
  2555. const inf = s.station_info, ig = s.integrity, app = inf.mcu_app_info || {{}};
  2556. const resSum = ig.residual_prelaunch_findings.map(r => `${{r.phase}}:${{r.residual_rows}}s`).join(', ');
  2557. h1 += `<tr>
  2558. <td><b>${{esc(k)}}</b></td>
  2559. <td class="mono">${{esc(inf.bmc_host || '-')}}</td>
  2560. <td class="mono">${{esc(inf.mcu_uid || '-')}} · ${{esc(app.app_version || '-')}} · ${{esc(inf.pid_text || '-')}}</td>
  2561. <td>${{esc((inf.cpu_names[0] || '-'))}} / ${{esc((inf.total_memories[0] || '-'))}}</td>
  2562. <td class="mono">${{esc((inf.active_bmc_channels || []).map(b=>b.key).join(', '))}}</td>
  2563. <td class="mono">${{ig.master_rows.toLocaleString()}} (${{esc(inf.total_duration_hms || '-')}})</td>
  2564. <td class="mono">${{esc(ig.schema_version)}}</td>
  2565. <td><span class="badge ${{ig.template_all_pass ? 'pass' : 'warn'}}">${{ig.template_all_pass ? 'PASS' : 'WARN'}} (${{ig.template_files_count}}份, 失配=${{ig.template_total_mismatches}})</span></td>
  2566. <td><span class="badge ${{ig.mt_total_errors === 0 ? 'pass' : 'fail'}}">${{ig.mt_total_errors}}</span></td>
  2567. <td>${{esc(resSum || '无')}}</td>
  2568. </tr>`;
  2569. }});
  2570. h1 += '</tbody></table>';
  2571. document.getElementById('audit-overview-table').innerHTML = h1;
  2572. const s = DATA.stations[activeKey];
  2573. let h2 = `<table><thead><tr><th>模板文件名</th><th>行数</th><th>BOM</th><th>CRLF</th><th>34列表头</th><th>列数=34</th><th>序号连续</th><th>非零BMC通道</th><th>与Comprehensive失配</th><th>状态</th></tr></thead><tbody>`;
  2574. Object.entries(s.template_checks).forEach(([fn, tc]) => {{
  2575. h2 += `<tr>
  2576. <td class="mono">${{esc(fn)}}</td>
  2577. <td class="mono">${{tc.rows}}</td>
  2578. <td>${{tc.has_bom ? '✓' : '✗'}}</td>
  2579. <td>${{tc.has_crlf ? '✓' : '✗'}}</td>
  2580. <td>${{tc.header_match ? '✓' : '✗'}}</td>
  2581. <td>${{tc.col_count_34 ? '✓' : '✗'}}</td>
  2582. <td>${{tc.seq_contiguous ? '✓' : '✗'}}</td>
  2583. <td class="mono">${{esc((tc.non_zero_bmc_channels || []).join(','))}}</td>
  2584. <td class="mono">${{tc.value_mismatches_vs_comprehensive ?? '-'}}</td>
  2585. <td><span class="badge ${{tc.status === 'PASS' ? 'pass' : 'warn'}}">${{tc.status}}</span></td>
  2586. </tr>`;
  2587. }});
  2588. h2 += '</tbody></table>';
  2589. document.getElementById('template-audit-table').innerHTML = h2;
  2590. }}
  2591. function renderConsoleAndEvents() {{
  2592. const s = DATA.stations[activeKey];
  2593. let hc = `<table><thead><tr><th>控制台文件</th><th>大小</th><th>行数</th><th>Running测试</th><th>完成测试项</th><th>CPU等待告警</th><th>Console DIMM0/1</th><th>实测报错</th></tr></thead><tbody>`;
  2594. Object.entries(s.console_summary).forEach(([fn, cs]) => {{
  2595. hc += `<tr>
  2596. <td class="mono">${{esc(fn)}}</td>
  2597. <td class="mono">${{(cs.bytes / 1024).toFixed(1)}} KB</td>
  2598. <td class="mono">${{cs.lines}}</td>
  2599. <td class="mono">${{cs.running_tests_count}}</td>
  2600. <td class="mono">${{cs.completed_tests.length}}</td>
  2601. <td class="mono">${{cs.range_warnings_count}}${{cs.range_warnings_max_cpu != null ? ` (max CPU#${{cs.range_warnings_max_cpu}})` : ''}}</td>
  2602. <td class="mono">${{esc(fmtMM(cs.console_dimm0_temp))}} / ${{esc(fmtMM(cs.console_dimm1_temp))}}°C</td>
  2603. <td><span class="badge ${{cs.real_errors_count === 0 ? 'pass' : 'fail'}}">${{cs.real_errors_count}}</span></td>
  2604. </tr>`;
  2605. }});
  2606. hc += '</tbody></table>';
  2607. document.getElementById('console-summary-table').innerHTML = hc;
  2608. const kFilter = document.getElementById('event-kind-filter');
  2609. const prevK = kFilter.value;
  2610. kFilter.innerHTML = '<option value="">全部事件类型</option>';
  2611. Object.keys(s.event_kind_counts || {{}}).sort().forEach(k => {{
  2612. const o = document.createElement('option');
  2613. o.value = k; o.textContent = `${{k}} (${{s.event_kind_counts[k]}})`;
  2614. kFilter.appendChild(o);
  2615. }});
  2616. if (prevK) kFilter.value = prevK;
  2617. renderEventsRows();
  2618. }}
  2619. function renderEventsRows() {{
  2620. const s = DATA.stations[activeKey];
  2621. const kf = document.getElementById('event-kind-filter').value;
  2622. const q = document.getElementById('event-search').value.trim().toLowerCase();
  2623. const filtered = (s.events || []).filter(ev => {{
  2624. if (kf && ev.kind !== kf) return false;
  2625. if (q && !JSON.stringify(ev).toLowerCase().includes(q)) return false;
  2626. return true;
  2627. }});
  2628. let he = `<table><thead><tr><th>时间 (CST)</th><th>阶段</th><th>类型</th><th>详情载荷</th></tr></thead><tbody>`;
  2629. filtered.slice(0, 400).forEach(ev => {{
  2630. const rest = {{}};
  2631. Object.entries(ev).forEach(([k, v]) => {{
  2632. if (!['unix_ms', 'time_cst', 'phase', 'kind', 'station_id', 'bmc_host'].includes(k)) rest[k] = v;
  2633. }});
  2634. he += `<tr><td class="mono">${{esc(ev.time_cst || '')}}</td><td class="mono">${{esc(ev.phase || '')}}</td><td><b>${{esc(ev.kind || '')}}</b></td><td class="mono">${{esc(JSON.stringify(rest))}}</td></tr>`;
  2635. }});
  2636. he += '</tbody></table>';
  2637. if (filtered.length > 400) he += `<p style="padding:8px;color:var(--muted)">仅显示前 400 条 (共 ${{filtered.length}} 条)</p>`;
  2638. document.getElementById('events-table').innerHTML = he;
  2639. }}
  2640. document.getElementById('algo-phase-select').addEventListener('change', () => {{ drawAlgoChart(); renderAlgoTable(); }});
  2641. document.getElementById('algo-metric-select').addEventListener('change', () => drawAlgoChart());
  2642. document.getElementById('event-kind-filter').addEventListener('change', renderEventsRows);
  2643. document.getElementById('event-search').addEventListener('input', renderEventsRows);
  2644. function renderStation() {{
  2645. buildLegends();
  2646. renderKpis();
  2647. buildZoomBar();
  2648. drawCharts();
  2649. renderPhaseTables();
  2650. populateAlgoSelectors();
  2651. drawAlgoChart();
  2652. renderAlgoTable();
  2653. renderAuditTables();
  2654. renderConsoleAndEvents();
  2655. }}
  2656. attachHover('chart-chambers', false);
  2657. attachHover('chart-positions', false);
  2658. attachHover('chart-pwr', true);
  2659. window.addEventListener('resize', () => {{ drawCharts(); drawAlgoChart(); }});
  2660. renderStation();
  2661. }})();
  2662. </script>
  2663. </body>
  2664. </html>
  2665. """
  2666. def export_clean_csvs(parsed: dict[str, Any], artifacts: dict[str, Any], export_dir: Path) -> list[Path]:
  2667. export_dir.mkdir(parents=True, exist_ok=True)
  2668. written: list[Path] = []
  2669. for skey, sdata in parsed["stations"].items():
  2670. info = sdata["station_info"]
  2671. art = artifacts[skey]
  2672. rows = art["master_rows"]
  2673. active_bmcs = art["active_bmc_channels"]
  2674. headers = [
  2675. "seq", "timestamp_cst", "unix_ms", "elapsed_s", "elapsed_hms",
  2676. "station_id", "bmc_host", "test_phase", "firmware_phase",
  2677. "active_algorithm_norm", "active_algorithm_raw", "is_residual_prelaunch",
  2678. "mt_test_num", "mt_cum_errors", "mcu_mode", "mcu_target_c",
  2679. ]
  2680. headers += [col for col, _, _, _ in CHAMBER_SENSORS]
  2681. headers += [f"{ch_id}_front_minus_rear" for ch_id, _, _, _ in CHAMBER_PAIRS]
  2682. headers += [f"mcu_bmc{i}" for i in active_bmcs]
  2683. headers += [col for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS]
  2684. out_path = export_dir / f"{skey}_per_sensor_clean.csv"
  2685. with out_path.open("w", encoding="utf-8-sig", newline="") as fp:
  2686. w = csv.writer(fp, lineterminator="\r\n")
  2687. w.writerow(headers)
  2688. for r in rows:
  2689. out_row = [
  2690. r["seq"], r["timestamp_cst"], r["unix_ms"], r["elapsed_s"], r["elapsed_hms"],
  2691. r["station_id"] or info["station_id"], r["bmc_host"] or info["bmc_host"],
  2692. r["test_phase"], r["firmware_phase"],
  2693. r["active_algorithm"], r["active_algorithm_raw"], 1 if r.get("is_residual_prelaunch") else 0,
  2694. r["mt_test_num"], r["mt_cum_errors"], r["mcu_mode"], r["mcu_target_c"],
  2695. ]
  2696. out_row += [r.get(col) for col, _, _, _ in CHAMBER_SENSORS]
  2697. for _, _, fc, rc in CHAMBER_PAIRS:
  2698. fv, rv = r.get(fc), r.get(rc)
  2699. out_row.append(round(fv - rv, 2) if (fv is not None and rv is not None) else "")
  2700. for i in active_bmcs:
  2701. bv = r["bmc24_raw"][i]
  2702. out_row.append("" if bv in (None, 255) else bv)
  2703. for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS:
  2704. v = r.get(col)
  2705. out_row.append("" if v is None else v)
  2706. w.writerow(out_row)
  2707. written.append(out_path)
  2708. return written
  2709. def _is_thermal_campaign_input(input_path: Path) -> bool:
  2710. if input_path.is_file():
  2711. return input_path.suffix.lower() in (".csv", ".jsonl")
  2712. if input_path.is_dir():
  2713. has_campaign = (
  2714. (input_path / "thermal_campaign_samples.jsonl").is_file()
  2715. or (input_path / "thermal_campaign_timeseries.csv").is_file()
  2716. )
  2717. has_mt_results = (
  2718. (input_path / "master_continuous_comprehensive.csv").is_file()
  2719. or any(
  2720. (c / "master_continuous_comprehensive.csv").is_file()
  2721. for c in input_path.iterdir()
  2722. if c.is_dir()
  2723. )
  2724. )
  2725. return has_campaign and not has_mt_results
  2726. return False
  2727. def _load_campaign_rows(input_path: Path) -> tuple[list[dict[str, Any]], dict[str, Any] | None, Path]:
  2728. summary_meta: dict[str, Any] | None = None
  2729. data_file: Path
  2730. base_dir = input_path if input_path.is_dir() else input_path.parent
  2731. for cand in (
  2732. base_dir / "thermal_campaign_summary.json",
  2733. base_dir.parent / "thermal_campaign_summary.json",
  2734. base_dir.parent.parent / "thermal_campaign_summary.json",
  2735. ):
  2736. if cand.is_file():
  2737. try:
  2738. summary_meta = json.loads(cand.read_text(encoding="utf-8"))
  2739. break
  2740. except Exception:
  2741. pass
  2742. if input_path.is_dir():
  2743. if (input_path / "thermal_campaign_samples.jsonl").is_file():
  2744. data_file = input_path / "thermal_campaign_samples.jsonl"
  2745. elif (input_path / "thermal_campaign_timeseries.csv").is_file():
  2746. data_file = input_path / "thermal_campaign_timeseries.csv"
  2747. else:
  2748. raise FileNotFoundError(f"No thermal_campaign_samples.jsonl or thermal_campaign_timeseries.csv in {input_path}")
  2749. else:
  2750. data_file = input_path
  2751. raw_rows: list[dict[str, Any]] = []
  2752. if data_file.suffix.lower() == ".jsonl":
  2753. for line in data_file.read_text(encoding="utf-8", errors="replace").splitlines():
  2754. s = line.strip()
  2755. if not s:
  2756. continue
  2757. raw_rows.append(json.loads(s))
  2758. else:
  2759. with data_file.open("r", encoding="utf-8-sig", newline="") as fp:
  2760. for r in csv.DictReader(fp):
  2761. raw_rows.append(r)
  2762. if not raw_rows:
  2763. raise ValueError(f"No rows found in campaign file: {data_file}")
  2764. return raw_rows, summary_meta, data_file
  2765. def _load_campaign_aux_assets(input_path: Path, data_file: Path) -> tuple[dict[str, Any] | None, dict[str, Any] | None, list[dict[str, Any]]]:
  2766. base_dir = input_path if input_path.is_dir() else input_path.parent
  2767. search_dirs: list[Path] = []
  2768. for d in (base_dir, base_dir / "figures", base_dir.parent, base_dir.parent.parent, data_file.parent, data_file.parent.parent, data_file.parent.parent.parent):
  2769. if d.is_dir() and d not in search_dirs:
  2770. search_dirs.append(d)
  2771. benchmark_data = None
  2772. for d in search_dirs:
  2773. cand = d / "bmc_benchmark_result.json"
  2774. if cand.is_file():
  2775. try:
  2776. raw_bm = json.loads(cand.read_text(encoding="utf-8"))
  2777. ipmi_b = raw_bm.get("ipmi") or {}
  2778. obmc_b = raw_bm.get("openbmc") or {}
  2779. benchmark_data = {
  2780. "bmc_host": raw_bm.get("bmc_host"),
  2781. "ipmi_sdr_temp_latency_ms": ipmi_b.get("ipmi_sdr_temp_latency_ms"),
  2782. "ipmi_sdr_compact_latency_ms": ipmi_b.get("ipmi_sdr_compact_latency_ms"),
  2783. "openbmc_discover_ms": obmc_b.get("discover_ms"),
  2784. "dbus_sensor_count": obmc_b.get("dbus_sensor_count"),
  2785. "dbus_sensor_services": obmc_b.get("dbus_sensor_services") or [],
  2786. "dbus_sensors_sample": obmc_b.get("dbus_sensors_sample") or [],
  2787. "ipmi_sample_temp_sdr": ipmi_b.get("sample_temp_sdr", ""),
  2788. "ipmi_sample_psu_sdr": ipmi_b.get("sample_psu_sdr", ""),
  2789. }
  2790. break
  2791. except Exception:
  2792. pass
  2793. metrics_meta = None
  2794. for d in search_dirs:
  2795. cand = d / "campaign_computed_metrics.json"
  2796. if cand.is_file():
  2797. try:
  2798. metrics_meta = json.loads(cand.read_text(encoding="utf-8"))
  2799. break
  2800. except Exception:
  2801. pass
  2802. fig_titles = {
  2803. "01_MT_BlockMove64B": "Fig 01 · MT Test 6 (Block Move 64B) 1Hz 温升/功耗曲线",
  2804. "02_AMT_B_WRUP": "Fig 02 · AMT Algo 0: B-WRUP (MATS+) 1Hz 温升/功耗曲线",
  2805. "03_AMT_B_SCM": "Fig 03 · AMT Algo 1: B-SCM (Checkerboard March) 1Hz 曲线",
  2806. "04_AMT_S_SI": "Fig 04 · AMT Algo 2: S-SI (Stripe/Strobe Inversion) 1Hz 曲线",
  2807. "05_AMT_A_HDS": "Fig 05 · AMT Algo 5: A-HDS (Array Hammer) 1Hz 曲线",
  2808. "06_AMT_B_CrossWR": "Fig 06 · AMT Algo 9: B-CrossWR (Cross-Bank/Row) 1Hz 曲线",
  2809. "07_AMT_R_VRT": "Fig 07 · AMT Algo 11: R-VRT (Variable Retention) 1Hz 脉动曲线",
  2810. "cross_comparison": "Fig 08 · 七大单算法独立温升 / 功耗 / 斜率横向对比总览",
  2811. "spatial_tau": "Fig 09 · 同通道 4-DIMM 热耦合 vs 孤立条空间梯度与 τ_cool",
  2812. }
  2813. ordered_keys = [
  2814. "01_MT_BlockMove64B", "02_AMT_B_WRUP", "03_AMT_B_SCM", "04_AMT_S_SI",
  2815. "05_AMT_A_HDS", "06_AMT_B_CrossWR", "07_AMT_R_VRT", "cross_comparison", "spatial_tau",
  2816. ]
  2817. found_figs: list[dict[str, Any]] = []
  2818. seen_names: set[str] = set()
  2819. fig_map = (metrics_meta or {}).get("figures") or {}
  2820. for fk in ordered_keys:
  2821. raw_p = fig_map.get(fk)
  2822. if not raw_p:
  2823. continue
  2824. fp = Path(str(raw_p))
  2825. resolved: Path | None = None
  2826. if fp.is_file():
  2827. resolved = fp
  2828. else:
  2829. for d in search_dirs:
  2830. alt = d / fp.name
  2831. if alt.is_file():
  2832. resolved = alt
  2833. break
  2834. if resolved is not None and resolved.name not in seen_names:
  2835. seen_names.add(resolved.name)
  2836. found_figs.append({
  2837. "key": fk,
  2838. "title": fig_titles.get(fk, resolved.stem),
  2839. "filename": resolved.name,
  2840. "path": str(resolved),
  2841. "size_bytes": resolved.stat().st_size,
  2842. })
  2843. if not found_figs:
  2844. cand_files: list[Path] = []
  2845. for d in search_dirs:
  2846. for fp in sorted(d.glob("fig_0[1-9]_*.png")):
  2847. if fp.is_file() and fp.name not in seen_names:
  2848. seen_names.add(fp.name)
  2849. cand_files.append(fp)
  2850. for fp in sorted(cand_files, key=lambda x: x.name):
  2851. fk = fp.stem.replace("fig_", "")
  2852. title = fp.stem
  2853. for ok in ordered_keys:
  2854. if ok in fp.stem or fp.stem.startswith("fig_08") and ok == "cross_comparison" or fp.stem.startswith("fig_09") and ok == "spatial_tau":
  2855. title = fig_titles.get(ok, fp.stem)
  2856. fk = ok
  2857. break
  2858. found_figs.append({
  2859. "key": fk,
  2860. "title": title,
  2861. "filename": fp.name,
  2862. "path": str(fp),
  2863. "size_bytes": fp.stat().st_size,
  2864. })
  2865. return benchmark_data, metrics_meta, found_figs
  2866. def _phase_group(phase: str) -> str:
  2867. if phase == "pre_baseline":
  2868. return "baseline"
  2869. if phase.startswith("loop_"):
  2870. return "active_loop"
  2871. if phase == "cooldown":
  2872. return "cooldown"
  2873. if phase in ("boot_to_amt", "init"):
  2874. return "startup"
  2875. if phase in ("inter_algo_settle", "idle_check"):
  2876. return "idle"
  2877. return "other"
  2878. def _ols_slope(xs: list[float], ys: list[float]) -> float | None:
  2879. if len(xs) < 2 or len(xs) != len(ys):
  2880. return None
  2881. n = len(xs)
  2882. mx = sum(xs) / n
  2883. my = sum(ys) / n
  2884. num = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
  2885. den = sum((x - mx) ** 2 for x in xs)
  2886. if den <= 1e-9:
  2887. return None
  2888. return num / den
  2889. def _fit_tau_cool_points(t_vals: list[float], y_vals: list[float | None], t_inf: float) -> float | None:
  2890. pts = [(t, math.log(y - t_inf)) for t, y in zip(t_vals, y_vals) if t is not None and y is not None and (y - t_inf) > 0.35]
  2891. if len(pts) < 8:
  2892. return None
  2893. t0 = pts[0][0]
  2894. tx = [t - t0 for t, _ in pts]
  2895. if tx[-1] < 10.0:
  2896. return None
  2897. slope = _ols_slope(tx, [ly for _, ly in pts])
  2898. if slope is None or slope >= -1e-4:
  2899. return None
  2900. tau = max(5.0, min(600.0, -1.0 / slope))
  2901. return round(tau, 2)
  2902. def _discover_campaign_sensors(raw_rows: list[dict[str, Any]]) -> list[dict[str, str]]:
  2903. meta_keys = {
  2904. "unix_ts", "iso_time", "campaign_elapsed_s", "run_elapsed_s", "poll_latency_ms",
  2905. "run_key", "algo_name", "short_name", "engine", "phase", "loop_index", "loop_total",
  2906. }
  2907. all_keys = list(raw_rows[0].keys())
  2908. for r in raw_rows[:20]:
  2909. for k in r.keys():
  2910. if k not in all_keys:
  2911. all_keys.append(k)
  2912. sensors: list[dict[str, str]] = []
  2913. seen: set[str] = set()
  2914. for key, lbl, grp, unit in CAMPAIGN_KNOWN_SENSORS:
  2915. if key in all_keys:
  2916. seen.add(key)
  2917. sensors.append({"key": key, "label": lbl, "group": grp, "unit": unit})
  2918. for key in all_keys:
  2919. if key in seen or key in meta_keys or key in CAMPAIGN_AGGREGATE_IGNORE:
  2920. continue
  2921. if key.startswith("DIMM_"):
  2922. grp, unit = "dimm_temp", "°C"
  2923. elif key.endswith("_Temp") or key.endswith("_c"):
  2924. grp, unit = "cpu_temp", "°C"
  2925. elif "Power" in key or key.endswith("_PIn") or key.endswith("_POut"):
  2926. grp, unit = "power", "W"
  2927. elif "Curr" in key:
  2928. grp, unit = "electrical", "A"
  2929. elif key.startswith("P12V_") or "Volt" in key:
  2930. grp, unit = "electrical", "V"
  2931. else:
  2932. continue
  2933. sensors.append({"key": key, "label": key, "group": grp, "unit": unit})
  2934. return sensors
  2935. def _campaign_block_stats(rows: list[dict[str, Any]], sensors: list[dict[str, str]]) -> dict[str, Any]:
  2936. out: dict[str, Any] = {}
  2937. for s in sensors:
  2938. k = s["key"]
  2939. vals = [_to_float(r.get(k)) for r in rows]
  2940. clean = [v for v in vals if v is not None]
  2941. st = _sensor_stats(clean, 2)
  2942. if st is not None:
  2943. st["label"] = s["label"]
  2944. st["group"] = s["group"]
  2945. st["unit"] = s["unit"]
  2946. out[k] = st
  2947. return out
  2948. def _detect_campaign_micro_events(
  2949. norm_rows: list[dict[str, Any]],
  2950. global_slices: list[dict[str, Any]],
  2951. dimm_keys: list[str],
  2952. runs_detail: dict[str, Any],
  2953. ) -> list[dict[str, Any]]:
  2954. events: list[dict[str, Any]] = []
  2955. eid = 1
  2956. def add_ev(
  2957. *,
  2958. severity: str,
  2959. category: str,
  2960. run_key: str,
  2961. phase: str,
  2962. seq_start: int,
  2963. seq_end: int,
  2964. title: str,
  2965. detail: str,
  2966. focus_chart: str = "all",
  2967. focus_sensors: list[str] | None = None,
  2968. pad_s: int = 12,
  2969. ) -> None:
  2970. nonlocal eid
  2971. r0 = norm_rows[max(0, seq_start - 1)]
  2972. r1 = norm_rows[min(len(norm_rows) - 1, seq_end - 1)]
  2973. events.append({
  2974. "id": f"ME-{eid:02d}",
  2975. "severity": severity,
  2976. "category": category,
  2977. "run_key": run_key,
  2978. "phase": phase,
  2979. "seq_start": seq_start,
  2980. "seq_end": seq_end,
  2981. "rows": seq_end - seq_start + 1,
  2982. "t_start": _round_opt(r0["campaign_elapsed_s"], 1),
  2983. "t_end": _round_opt(r1["campaign_elapsed_s"], 1),
  2984. "iso_start": r0["iso_time"],
  2985. "iso_end": r1["iso_time"],
  2986. "title": title,
  2987. "detail": detail,
  2988. "focus_chart": focus_chart,
  2989. "focus_sensors": focus_sensors or [],
  2990. "pad_s": pad_s,
  2991. })
  2992. eid += 1
  2993. # 1. Non-active stage DIMM thermal excursion (>= 2.0 C rise)
  2994. for sl in global_slices:
  2995. if sl["phase_group"] not in ("startup", "idle", "baseline") or sl["rows"] < 5:
  2996. continue
  2997. sl_rows = norm_rows[sl["idx_start"]:sl["idx_end"]]
  2998. for dk in dimm_keys:
  2999. pts = [(r["seq"], r[dk]) for r in sl_rows if r.get(dk) is not None]
  3000. if len(pts) < 4:
  3001. continue
  3002. min_seq, min_v = min(pts, key=lambda x: x[1])
  3003. post = [(sq, v) for sq, v in pts if sq >= min_seq]
  3004. if not post:
  3005. continue
  3006. max_seq, max_v = max(post, key=lambda x: x[1])
  3007. rise = round(max_v - min_v, 2)
  3008. if rise >= 2.0:
  3009. ddr2_peak = max((r.get("DDR2_Power") or 0.0 for r in sl_rows if min_seq <= r["seq"] <= max_seq), default=0.0)
  3010. ddr0_peak = max((r.get("DDR0_Power") or 0.0 for r in sl_rows if min_seq <= r["seq"] <= max_seq), default=0.0)
  3011. add_ev(
  3012. severity="warn" if rise >= 3.0 else "info",
  3013. category="非算法阶段温升",
  3014. run_key=sl["run_key"],
  3015. phase=sl["phase"],
  3016. seq_start=min_seq,
  3017. seq_end=max_seq,
  3018. title=f"{sl['run_key']} · {sl['phase']} 阶段 {dk.replace('_Temp','')} 上升 +{rise}°C",
  3019. detail=f"在 {sl['phase']} (#{min_seq}→#{max_seq}) 从 {min_v}°C 升至 {max_v}°C (+{rise}°C);期间 DDR0 峰值 {ddr0_peak:.2f}W / DDR2 峰值 {ddr2_peak:.2f}W(如多 Socket 初始化预热)。",
  3020. focus_chart="temp",
  3021. focus_sensors=[dk, "DDR2_Power", "DDR0_Power"],
  3022. pad_s=18,
  3023. )
  3024. # 2. Cooldown power spikes (>= 20W DDR0_Power after first 2 seconds of cooldown)
  3025. for sl in global_slices:
  3026. if sl["phase"] != "cooldown":
  3027. continue
  3028. sl_rows = norm_rows[sl["idx_start"]:sl["idx_end"]]
  3029. buf: list[dict[str, Any]] = []
  3030. for idx_c, r in enumerate(sl_rows):
  3031. if idx_c >= 2 and (r.get("DDR0_Power") or 0.0) >= 20.0:
  3032. buf.append(r)
  3033. elif buf:
  3034. pk0 = max((x.get("DDR0_Power") or 0.0) for x in buf)
  3035. pk2 = max((x.get("DDR2_Power") or 0.0) for x in buf)
  3036. p_psu = max((x.get("PSU0_PIn") or 0.0) for x in buf)
  3037. add_ev(
  3038. severity="warn",
  3039. category="冷却期DXE功耗脉冲",
  3040. run_key=sl["run_key"],
  3041. phase="cooldown",
  3042. seq_start=buf[0]["seq"],
  3043. seq_end=buf[-1]["seq"],
  3044. title=f"{sl['run_key']} · cooldown 热重启 DXE 功耗脉冲 {pk0:.2f}W",
  3045. detail=f"进入 cooldown 后热重启回 UEFI Shell,在 #{buf[0]['seq']}..#{buf[-1]['seq']} 触发 BIOS DXE 初始化短脉冲:DDR0={pk0:.2f}W, DDR2={pk2:.2f}W, PSU0={p_psu:.0f}W。",
  3046. focus_chart="pwr_mem",
  3047. focus_sensors=["DDR0_Power", "DDR2_Power", "PVCCD_CPU0_Input_Power"],
  3048. pad_s=15,
  3049. )
  3050. buf = []
  3051. if buf:
  3052. pk0 = max((x.get("DDR0_Power") or 0.0) for x in buf)
  3053. pk2 = max((x.get("DDR2_Power") or 0.0) for x in buf)
  3054. p_psu = max((x.get("PSU0_PIn") or 0.0) for x in buf)
  3055. add_ev(
  3056. severity="warn",
  3057. category="冷却期DXE功耗脉冲",
  3058. run_key=sl["run_key"],
  3059. phase="cooldown",
  3060. seq_start=buf[0]["seq"],
  3061. seq_end=buf[-1]["seq"],
  3062. title=f"{sl['run_key']} · cooldown 热重启 DXE 功耗脉冲 {pk0:.2f}W",
  3063. detail=f"进入 cooldown 后热重启回 UEFI Shell,在 #{buf[0]['seq']}..#{buf[-1]['seq']} 触发 BIOS DXE 初始化短脉冲:DDR0={pk0:.2f}W, DDR2={pk2:.2f}W, PSU0={p_psu:.0f}W。",
  3064. focus_chart="pwr_mem",
  3065. focus_sensors=["DDR0_Power", "DDR2_Power", "PVCCD_CPU0_Input_Power"],
  3066. pad_s=15,
  3067. )
  3068. # 3. SPD5118 telemetry blackout spans (>= 5 consecutive rows with all DIMMs None)
  3069. cool_start_by_run: dict[str, int] = {}
  3070. for sl in global_slices:
  3071. if sl["phase"] == "cooldown" and sl["run_key"] not in cool_start_by_run:
  3072. cool_start_by_run[sl["run_key"]] = sl["seq_start"]
  3073. blk_buf: list[dict[str, Any]] = []
  3074. def flush_spd_blackout() -> None:
  3075. if len(blk_buf) < 5:
  3076. return
  3077. r0, r1 = blk_buf[0], blk_buf[-1]
  3078. in_cool = any(x["phase"] == "cooldown" for x in blk_buf)
  3079. c_start = cool_start_by_run.get(r0["run_key"])
  3080. is_late_handover = bool(in_cool and c_start is not None and (r0["seq"] - c_start) >= 50)
  3081. sev = "warn" if in_cool else "info"
  3082. if is_late_handover:
  3083. title = f"{r0['run_key']} · cooldown 二次切回OS瞬断 ({len(blk_buf)}s)"
  3084. hint = "cooldown 约 +100s 处切回 OS 交接重启,SPD5118 与 PMBus (DDR0_Power) 同步离线,随后恢复并重连 PECI"
  3085. elif in_cool:
  3086. title = f"{r0['run_key']} · cooldown 初期热重启 SPD 离线 {len(blk_buf)}s"
  3087. hint = "停载退出后热重启回 UEFI Shell 期间 SPD5118 不可访问,导致冷却表观首读数低于峰值约 2~3°C"
  3088. else:
  3089. title = f"{r0['run_key']} · {r0['phase']} SPD5118 全离线 {len(blk_buf)}s"
  3090. hint = "热重启进入 BIOS MRC 训练窗口,SPD5118 不可读"
  3091. add_ev(
  3092. severity=sev,
  3093. category="SPD5118离线空窗",
  3094. run_key=r0["run_key"],
  3095. phase=r0["phase"],
  3096. seq_start=r0["seq"],
  3097. seq_end=r1["seq"],
  3098. title=title,
  3099. detail=f"#{r0['seq']}..#{r1['seq']}(共 {len(blk_buf)} 行)5 路 DIMM 温度全部为 null;{hint}。",
  3100. focus_chart="temp",
  3101. focus_sensors=dimm_keys[:2] + ["DDR0_Power"],
  3102. pad_s=12,
  3103. )
  3104. for r in norm_rows:
  3105. all_null = bool(dimm_keys) and all(r.get(dk) is None for dk in dimm_keys)
  3106. if all_null and (not blk_buf or blk_buf[-1]["run_key"] == r["run_key"] and blk_buf[-1]["phase"] == r["phase"]):
  3107. blk_buf.append(r)
  3108. else:
  3109. flush_spd_blackout()
  3110. blk_buf = [r] if all_null else []
  3111. flush_spd_blackout()
  3112. # 4. PECI RAPL availability offline window (Dimm_Power_CPU0 is None)
  3113. if any(r.get("Dimm_Power_CPU0") is not None for r in norm_rows):
  3114. p_buf: list[dict[str, Any]] = []
  3115. for r in norm_rows:
  3116. if r.get("Dimm_Power_CPU0") is None:
  3117. p_buf.append(r)
  3118. else:
  3119. if len(p_buf) >= 20:
  3120. add_ev(
  3121. severity="info",
  3122. category="PECI RAPL空窗",
  3123. run_key=p_buf[0]["run_key"],
  3124. phase=p_buf[0]["phase"],
  3125. seq_start=p_buf[0]["seq"],
  3126. seq_end=p_buf[-1]["seq"],
  3127. title=f"{p_buf[0]['run_key']} · BIOS AMT 期间 PECI 功耗遥测离线 ({len(p_buf)}s)",
  3128. detail=f"#{p_buf[0]['seq']}..#{p_buf[-1]['seq']} 期间 Dimm_Power_CPU0/1 与 CPU0/1_Power_Avg 为 null(BIOS CPGC AMT 模式下 PECI 不上报,须以板载 PMBus DDR0/DDR2 为准);返回 UEFI Shell ~105s 后自动恢复。",
  3129. focus_chart="pwr_mem",
  3130. focus_sensors=["Dimm_Power_CPU0", "DDR0_Power"],
  3131. pad_s=10,
  3132. )
  3133. p_buf = []
  3134. if len(p_buf) >= 20:
  3135. add_ev(
  3136. severity="info",
  3137. category="PECI RAPL空窗",
  3138. run_key=p_buf[0]["run_key"],
  3139. phase=p_buf[0]["phase"],
  3140. seq_start=p_buf[0]["seq"],
  3141. seq_end=p_buf[-1]["seq"],
  3142. title=f"{p_buf[0]['run_key']} · BIOS AMT 期间 PECI 功耗遥测离线 ({len(p_buf)}s)",
  3143. detail=f"#{p_buf[0]['seq']}..#{p_buf[-1]['seq']} 期间 Dimm_Power_CPU0/1 与 CPU0/1_Power_Avg 为 null。",
  3144. focus_chart="pwr_mem",
  3145. focus_sensors=["Dimm_Power_CPU0", "DDR0_Power"],
  3146. pad_s=10,
  3147. )
  3148. # 5. Global peak DIMM temperature & max 5-DIMM spatial spread
  3149. peak_temp_row = None
  3150. peak_temp_key = ""
  3151. peak_temp_val = -1e9
  3152. max_spread_row = None
  3153. max_spread_val = -1.0
  3154. max_spread_pair = ("", "", 0.0, 0.0)
  3155. for r in norm_rows:
  3156. vals = [(dk, r[dk]) for dk in dimm_keys if r.get(dk) is not None]
  3157. if not vals:
  3158. continue
  3159. hi_k, hi_v = max(vals, key=lambda x: x[1])
  3160. lo_k, lo_v = min(vals, key=lambda x: x[1])
  3161. if hi_v > peak_temp_val:
  3162. peak_temp_val = hi_v
  3163. peak_temp_key = hi_k
  3164. peak_temp_row = r
  3165. sp = round(hi_v - lo_v, 2)
  3166. if sp > max_spread_val:
  3167. max_spread_val = sp
  3168. max_spread_row = r
  3169. max_spread_pair = (hi_k, lo_k, hi_v, lo_v)
  3170. if peak_temp_row is not None and len(norm_rows) >= 10:
  3171. add_ev(
  3172. severity="peak",
  3173. category="全局峰值热节点",
  3174. run_key=peak_temp_row["run_key"],
  3175. phase=peak_temp_row["phase"],
  3176. seq_start=peak_temp_row["seq"],
  3177. seq_end=peak_temp_row["seq"],
  3178. title=f"全周期最高 DIMM 温度 {peak_temp_val}°C ({peak_temp_key.replace('_Temp','')})",
  3179. detail=f"#{peak_temp_row['seq']} ({peak_temp_row['run_key']} · {peak_temp_row['phase']}) 达全局最高 {peak_temp_val}°C;最大 5-DIMM 跨槽极差 {max_spread_val}°C ({max_spread_pair[0].replace('_Temp','')} {max_spread_pair[2]}°C vs {max_spread_pair[1].replace('_Temp','')} {max_spread_pair[3]}°C @ #{max_spread_row['seq'] if max_spread_row else '-'})。",
  3180. focus_chart="temp",
  3181. focus_sensors=dimm_keys,
  3182. pad_s=35,
  3183. )
  3184. # 6. P12V_DDR0 significant rail voltage droop (>= 0.03V)
  3185. p12_vals = [(r["seq"], r["P12V_DDR0"], r["run_key"], r["phase"]) for r in norm_rows if r.get("P12V_DDR0") is not None]
  3186. if p12_vals:
  3187. p12_max = max(v for _, v, _, _ in p12_vals)
  3188. p12_min = min(v for _, v, _, _ in p12_vals)
  3189. if (p12_max - p12_min) >= 0.03:
  3190. droop_rows = [r for r in norm_rows if r.get("P12V_DDR0") is not None and r["P12V_DDR0"] <= p12_min + 0.005]
  3191. if droop_rows:
  3192. # Merge contiguous or near-contiguous
  3193. s0, s1 = droop_rows[0]["seq"], droop_rows[-1]["seq"]
  3194. max_curr = max((r.get("DDR0_Curr") or 0.0) for r in droop_rows)
  3195. max_pwr = max((r.get("DDR0_Power") or 0.0) for r in droop_rows)
  3196. add_ev(
  3197. severity="peak",
  3198. category="12V 供电轨压降",
  3199. run_key=droop_rows[0]["run_key"],
  3200. phase=droop_rows[0]["phase"],
  3201. seq_start=s0,
  3202. seq_end=s1,
  3203. title=f"{droop_rows[0]['run_key']} · P12V_DDR0 压降至 {p12_min:.3f}V (峰值电流 {max_curr:.2f}A)",
  3204. detail=f"大电流高功耗下 P12V_DDR0 由空载 {p12_max:.3f}V 下探至 {p12_min:.3f}V(-{(p12_max-p12_min)*1000:.0f}mV 压降,{len(droop_rows)} 行处于谷底,对应 DDR0_Curr 峰值 {max_curr:.2f}A / DDR0_Power {max_pwr:.2f}W)。",
  3205. focus_chart="elec_volt",
  3206. focus_sensors=["P12V_DDR0", "P12V_DDR2", "DDR0_Curr"],
  3207. pad_s=25,
  3208. )
  3209. # 7. Active loop power pattern signatures (square-wave pulse vs zero-gap steady load)
  3210. for rk, rd in runs_detail.items():
  3211. if rd["active_rows"] < 20:
  3212. continue
  3213. act_slices = [s for s in rd["phases"] if s["phase_group"] == "active_loop"]
  3214. if not act_slices:
  3215. continue
  3216. a_s, a_e = act_slices[0]["seq_start"], act_slices[-1]["seq_end"]
  3217. act_r = norm_rows[a_s - 1:a_e]
  3218. d0 = [r["DDR0_Power"] for r in act_r if r.get("DDR0_Power") is not None]
  3219. if not d0:
  3220. continue
  3221. if (max(d0) - min(d0)) >= 15.0 and min(d0) < 10.0:
  3222. add_ev(
  3223. severity="info",
  3224. category="方波脉动功耗特征",
  3225. run_key=rk,
  3226. phase=act_slices[0]["phase"],
  3227. seq_start=a_s,
  3228. seq_end=a_e,
  3229. title=f"{rk} · 写入-保持-回读脉动负载 ({min(d0):.1f}~{max(d0):.2f}W 剧烈方波)",
  3230. detail=f"#{a_s}..#{a_e} 负载期 DDR0 功耗在 {min(d0):.2f}W(Retention Pause 空窗)与 {max(d0):.2f}W(突发写/回读峰值,超 {round(max(d0),1)}W)间高频方波切换,解释了平均功耗温和但瞬时峰值极高的现象。",
  3231. focus_chart="pwr_mem",
  3232. focus_sensors=["DDR0_Power", "DDR2_Power", "PVCCD_CPU0_Input_Power"],
  3233. pad_s=15,
  3234. )
  3235. elif len(act_slices) >= 2:
  3236. tail_rows = norm_rows[act_slices[1]["idx_start"]:act_slices[-1]["idx_end"]]
  3237. d0_tail = [r["DDR0_Power"] for r in tail_rows if r.get("DDR0_Power") is not None]
  3238. if d0_tail and min(d0_tail) >= 18.0 and (max(d0_tail) - min(d0_tail)) < 1.5:
  3239. add_ev(
  3240. severity="info",
  3241. category="无间隙极稳态特征",
  3242. run_key=rk,
  3243. phase="loop_2+",
  3244. seq_start=act_slices[1]["seq_start"],
  3245. seq_end=act_slices[-1]["seq_end"],
  3246. title=f"{rk} · 无轮间低谷持续稳态功耗 ({min(d0_tail):.2f}~{max(d0_tail):.2f}W)",
  3247. detail=f"与其余算法轮间回落至 ~7.6W 不同,{rk} 在 #{act_slices[1]['seq_start']}..#{act_slices[-1]['seq_end']} 全程维持在 {min(d0_tail):.2f}~{max(d0_tail):.2f}W(波动仅 {max(d0_tail)-min(d0_tail):.2f}W)。",
  3248. focus_chart="pwr_mem",
  3249. focus_sensors=["DDR0_Power", "DDR2_Power"],
  3250. pad_s=15,
  3251. )
  3252. # 8. High poll latency spikes (>= 500ms)
  3253. lat_buf: list[dict[str, Any]] = []
  3254. def flush_lat() -> None:
  3255. if not lat_buf:
  3256. return
  3257. pk = max((x.get("poll_latency_ms") or 0.0) for x in lat_buf)
  3258. r0, r1 = lat_buf[0], lat_buf[-1]
  3259. add_ev(
  3260. severity="warn" if pk >= 1500 else "info",
  3261. category="BMC采集高延迟",
  3262. run_key=r0["run_key"],
  3263. phase=r0["phase"],
  3264. seq_start=r0["seq"],
  3265. seq_end=r1["seq"],
  3266. title=f"{r0['run_key']} · BMC D-Bus 轮询尖峰 {pk:.0f}ms",
  3267. detail=f"#{r0['seq']}..#{r1['seq']} ({r0['phase']}) 单次采集耗时达 {pk:.1f}ms(多发生在热重启切换重连或 BMC 重建 D-Bus 瞬间,采集周期仍严格对齐 1Hz)。",
  3268. focus_chart="elec_lat",
  3269. focus_sensors=[],
  3270. pad_s=12,
  3271. )
  3272. for r in norm_rows:
  3273. if (r.get("poll_latency_ms") or 0.0) >= 500.0:
  3274. if not lat_buf or (r["seq"] - lat_buf[-1]["seq"]) <= 2:
  3275. lat_buf.append(r)
  3276. else:
  3277. flush_lat()
  3278. lat_buf = [r]
  3279. else:
  3280. if lat_buf and (r["seq"] - lat_buf[-1]["seq"]) > 2:
  3281. flush_lat()
  3282. lat_buf = []
  3283. flush_lat()
  3284. events.sort(key=lambda e: (e["seq_start"], e["seq_end"]))
  3285. for idx_e, ev in enumerate(events, start=1):
  3286. ev["id"] = f"ME-{idx_e:02d}"
  3287. return events
  3288. def parse_thermal_campaign(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
  3289. p = Path(input_path).resolve()
  3290. raw_rows, summary_meta, data_file = _load_campaign_rows(p)
  3291. benchmark_data, metrics_meta, found_figs = _load_campaign_aux_assets(p, data_file)
  3292. sensors = _discover_campaign_sensors(raw_rows)
  3293. dimm_keys = [s["key"] for s in sensors if s["group"] == "dimm_temp"]
  3294. norm_rows: list[dict[str, Any]] = []
  3295. for idx, r in enumerate(raw_rows, start=1):
  3296. rec: dict[str, Any] = {
  3297. "seq": idx,
  3298. "unix_ts": _to_float(r.get("unix_ts")),
  3299. "iso_time": str(r.get("iso_time") or "").strip(),
  3300. "campaign_elapsed_s": _to_float(r.get("campaign_elapsed_s")),
  3301. "run_elapsed_s": _to_float(r.get("run_elapsed_s")),
  3302. "poll_latency_ms": _to_float(r.get("poll_latency_ms")),
  3303. "run_key": str(r.get("run_key") or "").strip(),
  3304. "algo_name": str(r.get("algo_name") or "").strip(),
  3305. "short_name": str(r.get("short_name") or "").strip(),
  3306. "engine": str(r.get("engine") or "").strip(),
  3307. "phase": str(r.get("phase") or "").strip(),
  3308. "loop_index": _to_int(r.get("loop_index")) or 0,
  3309. "loop_total": _to_int(r.get("loop_total")) or 0,
  3310. }
  3311. for s in sensors:
  3312. rec[s["key"]] = _to_float(r.get(s["key"]))
  3313. norm_rows.append(rec)
  3314. # Global chronological contiguous phase slices by (run_key, phase)
  3315. global_slices: list[dict[str, Any]] = []
  3316. cur_rk: str | None = None
  3317. cur_ph: str | None = None
  3318. cur_buf: list[dict[str, Any]] = []
  3319. def push_global_slice() -> None:
  3320. if not cur_buf:
  3321. return
  3322. ph = cur_ph or "unknown"
  3323. rk = cur_rk or "unknown"
  3324. t0 = cur_buf[0]["campaign_elapsed_s"]
  3325. t1 = cur_buf[-1]["campaign_elapsed_s"]
  3326. dur_s = round((t1 - t0) + 1.0, 1) if (t0 is not None and t1 is not None) else float(len(cur_buf))
  3327. spd_valid = sum(1 for row in cur_buf if any(row.get(dk) is not None for dk in dimm_keys))
  3328. peci_valid = sum(
  3329. 1 for row in cur_buf
  3330. if row.get("Dimm_Power_CPU0") is not None or row.get("CPU0_Power_Avg") is not None
  3331. )
  3332. global_slices.append({
  3333. "run_key": rk,
  3334. "phase": ph,
  3335. "phase_group": _phase_group(ph),
  3336. "loop_index": cur_buf[0]["loop_index"],
  3337. "seq_start": cur_buf[0]["seq"],
  3338. "seq_end": cur_buf[-1]["seq"],
  3339. "idx_start": cur_buf[0]["seq"] - 1,
  3340. "idx_end": cur_buf[-1]["seq"],
  3341. "rows": len(cur_buf),
  3342. "start_time": cur_buf[0]["iso_time"],
  3343. "end_time": cur_buf[-1]["iso_time"],
  3344. "t_start": _round_opt(t0, 1),
  3345. "t_end": _round_opt(t1, 1),
  3346. "duration_s": dur_s,
  3347. "spd_valid_rows": spd_valid,
  3348. "spd_null_rows": len(cur_buf) - spd_valid,
  3349. "peci_valid_rows": peci_valid,
  3350. "peci_null_rows": len(cur_buf) - peci_valid,
  3351. "sensors": _campaign_block_stats(cur_buf, sensors),
  3352. })
  3353. for r in norm_rows:
  3354. rk = r["run_key"] or "unknown"
  3355. ph = r["phase"] or "unknown"
  3356. if cur_rk is None or rk != cur_rk or ph != cur_ph:
  3357. push_global_slice()
  3358. cur_rk, cur_ph = rk, ph
  3359. cur_buf = [r]
  3360. else:
  3361. cur_buf.append(r)
  3362. push_global_slice()
  3363. summary_by_run: dict[str, dict[str, Any]] = {}
  3364. for sr in (summary_meta or {}).get("runs") or []:
  3365. if isinstance(sr, dict) and sr.get("run_key"):
  3366. summary_by_run[str(sr["run_key"])] = sr
  3367. metrics_by_run: dict[str, dict[str, Any]] = {}
  3368. for mr in (metrics_meta or {}).get("algorithms") or []:
  3369. if isinstance(mr, dict) and mr.get("run_key"):
  3370. metrics_by_run[str(mr["run_key"])] = mr
  3371. # Group rows by run_key preserving execution order
  3372. run_order: list[str] = []
  3373. by_run: dict[str, list[dict[str, Any]]] = {}
  3374. for r in norm_rows:
  3375. rk = r["run_key"] or "unknown"
  3376. if rk not in by_run:
  3377. run_order.append(rk)
  3378. by_run[rk] = []
  3379. by_run[rk].append(r)
  3380. def _nearest_sample(ts: float | None, rows_pool: list[dict[str, Any]]) -> dict[str, Any] | None:
  3381. if ts is None or not rows_pool:
  3382. return None
  3383. best = None
  3384. best_dt = 1e18
  3385. for row in rows_pool:
  3386. uts = row.get("unix_ts")
  3387. if uts is None:
  3388. continue
  3389. dt = abs(uts - ts)
  3390. if dt < best_dt:
  3391. best_dt = dt
  3392. best = row
  3393. return best
  3394. runs_detail: dict[str, Any] = {}
  3395. for rk in run_order:
  3396. rrows = by_run[rk]
  3397. first = rrows[0]
  3398. base_rows = [r for r in rrows if r["phase"] == "pre_baseline"]
  3399. active_rows = [r for r in rrows if r["phase"].startswith("loop_")]
  3400. cool_rows = [r for r in rrows if r["phase"] == "cooldown"]
  3401. active_dur_s = 0.0
  3402. if len(active_rows) >= 2 and active_rows[0]["unix_ts"] is not None and active_rows[-1]["unix_ts"] is not None:
  3403. active_dur_s = round(active_rows[-1]["unix_ts"] - active_rows[0]["unix_ts"], 2)
  3404. elif active_rows:
  3405. active_dur_s = float(len(active_rows))
  3406. active_stats = _campaign_block_stats(active_rows, sensors) if active_rows else {}
  3407. base_stats = _campaign_block_stats(base_rows, sensors) if base_rows else {}
  3408. cool_stats = _campaign_block_stats(cool_rows, sensors) if cool_rows else {}
  3409. # Per-DIMM heating rate (C/min), early 40s slope, cooldown recovery, and per-DIMM tau_cool
  3410. dimm_rates: dict[str, Any] = {}
  3411. t_act0 = active_rows[0]["unix_ts"] if active_rows else None
  3412. early_limit_s = min(40.0, max(15.0, active_dur_s * 0.6))
  3413. t_cool0 = cool_rows[0]["unix_ts"] if cool_rows else None
  3414. for dk in dimm_keys:
  3415. ast = active_stats.get(dk)
  3416. bst = base_stats.get(dk)
  3417. cst = cool_stats.get(dk)
  3418. rate = None
  3419. if ast and active_dur_s > 0:
  3420. rate = round((ast["max"] - ast["start"]) / (active_dur_s / 60.0), 2)
  3421. net_from_base = None
  3422. if ast and bst:
  3423. net_from_base = round(ast["max"] - bst["end"], 2)
  3424. cool_drop = None
  3425. if cst:
  3426. cool_drop = round(cst["start"] - cst["end"], 2)
  3427. cool_drop_from_peak = None
  3428. if ast and cst:
  3429. cool_drop_from_peak = round(ast["max"] - cst["end"], 2)
  3430. early_slope = None
  3431. if active_rows and t_act0 is not None:
  3432. exs: list[float] = []
  3433. eys: list[float] = []
  3434. for rr in active_rows:
  3435. rv = rr.get(dk)
  3436. rts = rr.get("unix_ts")
  3437. if rv is not None and rts is not None and (rts - t_act0) <= early_limit_s:
  3438. exs.append(rts - t_act0)
  3439. eys.append(rv)
  3440. if len(exs) >= 5:
  3441. sl = _ols_slope(exs, eys)
  3442. if sl is not None:
  3443. early_slope = round(sl * 60.0, 2)
  3444. cool_delay_s = None
  3445. cool_valid = 0
  3446. cool_null = len(cool_rows)
  3447. tau_dimm = None
  3448. if cool_rows:
  3449. cool_valid = cst["count"] if cst else 0
  3450. cool_null = len(cool_rows) - cool_valid
  3451. first_v_row = next((rr for rr in cool_rows if rr.get(dk) is not None), None)
  3452. if first_v_row is not None:
  3453. if t_cool0 is not None and first_v_row.get("unix_ts") is not None:
  3454. cool_delay_s = round(first_v_row["unix_ts"] - t_cool0, 1)
  3455. else:
  3456. cool_delay_s = float(first_v_row["seq"] - cool_rows[0]["seq"])
  3457. if bst is not None:
  3458. c_ts = [rr["campaign_elapsed_s"] for rr in cool_rows]
  3459. c_ys = [rr.get(dk) for rr in cool_rows]
  3460. tau_dimm = _fit_tau_cool_points(c_ts, c_ys, bst["end"] - 0.15)
  3461. dimm_rates[dk] = {
  3462. "baseline_start_c": bst["start"] if bst else None,
  3463. "baseline_end_c": bst["end"] if bst else None,
  3464. "baseline_min_c": bst["min"] if bst else None,
  3465. "baseline_max_c": bst["max"] if bst else None,
  3466. "active_start_c": ast["start"] if ast else None,
  3467. "active_end_c": ast["end"] if ast else None,
  3468. "active_min_c": ast["min"] if ast else None,
  3469. "active_max_c": ast["max"] if ast else None,
  3470. "active_delta_c": ast["delta"] if ast else None,
  3471. "net_rise_from_baseline_c": net_from_base,
  3472. "heating_rate_c_per_min": rate,
  3473. "early_slope_c_per_min": early_slope,
  3474. "cooldown_start_c": cst["start"] if cst else None,
  3475. "cooldown_end_c": cst["end"] if cst else None,
  3476. "cooldown_drop_c": cool_drop,
  3477. "cooldown_total_drop_from_peak_c": cool_drop_from_peak,
  3478. "cooldown_first_valid_delay_s": cool_delay_s,
  3479. "cooldown_valid_rows": cool_valid,
  3480. "cooldown_null_rows": cool_null,
  3481. "tau_cool_s": tau_dimm,
  3482. }
  3483. run_slices = [
  3484. {k: v for k, v in sl.items() if k != "run_key"}
  3485. for sl in global_slices
  3486. if sl["run_key"] == rk
  3487. ]
  3488. core_slices = [s for s in run_slices if s["phase_group"] in ("baseline", "active_loop", "cooldown")]
  3489. if core_slices:
  3490. core_win = [core_slices[0]["idx_start"], core_slices[-1]["idx_end"]]
  3491. elif run_slices:
  3492. core_win = [run_slices[0]["idx_start"], run_slices[-1]["idx_end"]]
  3493. else:
  3494. core_win = [0, 0]
  3495. full_win = [run_slices[0]["idx_start"], run_slices[-1]["idx_end"]] if run_slices else [0, 0]
  3496. # Pointwise spatial spreads across populated DIMMs (no averages)
  3497. max_all_spread = None
  3498. cpu0_dimms = [dk for dk in dimm_keys if dk.startswith("DIMM_CPU0_")]
  3499. max_cpu0_spread = None
  3500. for rr in active_rows:
  3501. vals = [rr[dk] for dk in dimm_keys if rr.get(dk) is not None]
  3502. if len(vals) >= 2:
  3503. sp = round(max(vals) - min(vals), 2)
  3504. if max_all_spread is None or sp > max_all_spread:
  3505. max_all_spread = sp
  3506. if len(cpu0_dimms) >= 2:
  3507. cvals = [rr[dk] for dk in cpu0_dimms if rr.get(dk) is not None]
  3508. if len(cvals) >= 2:
  3509. csp = round(max(cvals) - min(cvals), 2)
  3510. if max_cpu0_spread is None or csp > max_cpu0_spread:
  3511. max_cpu0_spread = csp
  3512. s_meta = summary_by_run.get(rk) or {}
  3513. m_meta = metrics_by_run.get(rk) or {}
  3514. enriched_loop_events: list[dict[str, Any]] = []
  3515. for le in s_meta.get("loop_events") or []:
  3516. if not isinstance(le, dict):
  3517. continue
  3518. uts = _to_float(le.get("unix_ts"))
  3519. ns = _nearest_sample(uts, rrows)
  3520. enriched_loop_events.append({
  3521. "event": le.get("event") or ("socket_done" if "socket" in le else "event"),
  3522. "loop": le.get("loop"),
  3523. "socket": le.get("socket"),
  3524. "fw_sec": le.get("fw_sec"),
  3525. "unix_ts": uts,
  3526. "seq": ns["seq"] if ns else None,
  3527. "t_s": _round_opt(ns["campaign_elapsed_s"], 1) if ns else None,
  3528. "iso_time": ns["iso_time"] if ns else None,
  3529. })
  3530. runs_detail[rk] = {
  3531. "run_key": rk,
  3532. "algo_name": first["algo_name"],
  3533. "short_name": first["short_name"],
  3534. "engine": first["engine"],
  3535. "category": s_meta.get("category") or m_meta.get("category") or "",
  3536. "tp_plan": s_meta.get("tp_plan") or "",
  3537. "total_rows": len(rrows),
  3538. "active_rows": len(active_rows),
  3539. "active_duration_s": active_dur_s,
  3540. "loop_total": max((r["loop_total"] for r in rrows), default=0),
  3541. "start_time": first["iso_time"],
  3542. "end_time": rrows[-1]["iso_time"],
  3543. "full_window": full_win,
  3544. "core_window": core_win,
  3545. "max_all_dimm_spread_c": max_all_spread,
  3546. "max_cpu0_cluster_spread_c": max_cpu0_spread,
  3547. "ref_tau_cool_s": m_meta.get("tau_cool_cpu0_s"),
  3548. "pre_baseline_sensors": base_stats,
  3549. "active_sensors": active_stats,
  3550. "cooldown_sensors": cool_stats,
  3551. "per_dimm_thermal_response": dimm_rates,
  3552. "phases": run_slices,
  3553. "loop_events": enriched_loop_events,
  3554. }
  3555. latencies = [r["poll_latency_ms"] for r in norm_rows if r["poll_latency_ms"] is not None]
  3556. total_dur_s = round((norm_rows[-1]["campaign_elapsed_s"] or 0.0), 1)
  3557. overall_sensors = _campaign_block_stats(norm_rows, sensors)
  3558. micro_events = _detect_campaign_micro_events(norm_rows, global_slices, dimm_keys, runs_detail)
  3559. parsed = {
  3560. "parser_version": PARSER_VERSION,
  3561. "mode": "unheated_algorithm_campaign_per_position_no_means",
  3562. "parsed_utc": datetime.now(timezone.utc).isoformat(),
  3563. "input_path": str(p),
  3564. "data_file": str(data_file),
  3565. "source_kind": "thermal_campaign",
  3566. "bmc_host": (summary_meta or {}).get("bmc_host") or "unknown",
  3567. "total_1hz_rows": len(norm_rows),
  3568. "total_duration_s": total_dur_s,
  3569. "total_duration_hms": _fmt_hms(total_dur_s),
  3570. "poll_latency_ms": _sensor_stats(latencies, 2),
  3571. "sensors": sensors,
  3572. "dimm_keys": dimm_keys,
  3573. "overall_sensors": overall_sensors,
  3574. "runs": runs_detail,
  3575. "micro_events": micro_events,
  3576. "bmc_benchmark": benchmark_data,
  3577. }
  3578. # Compact columnar series for HTML dashboard
  3579. run_names: list[str] = []
  3580. run_idx: dict[str, int] = {}
  3581. phase_names: list[str] = []
  3582. phase_idx: dict[str, int] = {}
  3583. cols: dict[str, list[Any]] = {
  3584. "seq": [], "t": [], "ts": [], "rk": [], "ph": [], "loop": [], "lat": [],
  3585. }
  3586. for s in sensors:
  3587. cols[s["key"]] = []
  3588. for r in norm_rows:
  3589. rk = r["run_key"] or "unknown"
  3590. if rk not in run_idx:
  3591. run_idx[rk] = len(run_names)
  3592. run_names.append(rk)
  3593. ph = r["phase"] or "unknown"
  3594. if ph not in phase_idx:
  3595. phase_idx[ph] = len(phase_names)
  3596. phase_names.append(ph)
  3597. cols["seq"].append(r["seq"])
  3598. cols["t"].append(round(r["campaign_elapsed_s"] or 0.0, 1))
  3599. ts = r["iso_time"]
  3600. cols["ts"].append(ts[11:19] if len(ts) >= 19 else ts)
  3601. cols["rk"].append(run_idx[rk])
  3602. cols["ph"].append(phase_idx[ph])
  3603. cols["loop"].append(r["loop_index"])
  3604. cols["lat"].append(_round_opt(r["poll_latency_ms"], 1))
  3605. for s in sensors:
  3606. cols[s["key"]].append(_round_opt(r.get(s["key"]), 3))
  3607. series = {
  3608. "run_names": run_names,
  3609. "phase_names": phase_names,
  3610. "sensors": sensors,
  3611. "cols": cols,
  3612. }
  3613. embedded_figures: list[dict[str, Any]] = []
  3614. for fmeta in found_figs:
  3615. fp = Path(fmeta["path"])
  3616. try:
  3617. b64 = base64.b64encode(fp.read_bytes()).decode("ascii")
  3618. embedded_figures.append({
  3619. "key": fmeta["key"],
  3620. "title": fmeta["title"],
  3621. "filename": fmeta["filename"],
  3622. "size_bytes": fmeta["size_bytes"],
  3623. "data_uri": f"data:image/png;base64,{b64}",
  3624. })
  3625. except Exception:
  3626. pass
  3627. return parsed, {
  3628. "rows": norm_rows,
  3629. "sensors": sensors,
  3630. "series": series,
  3631. "embedded_figures": embedded_figures,
  3632. }
  3633. def render_campaign_markdown_report(parsed: dict[str, Any]) -> str:
  3634. dimm_keys = parsed["dimm_keys"]
  3635. lines: list[str] = []
  3636. lines.append("# 无温控直跑单算法多位置传感器独立解析报告(无均值)")
  3637. lines.append("")
  3638. lines.append(f"- **输入来源**:`{parsed['data_file']}` (`{parsed['source_kind']}`)")
  3639. lines.append(f"- **被测 BMC 主机**:`{parsed['bmc_host']}` · 温控模式:**无高温罩温控(裸机直跑单算法)**")
  3640. lines.append(f"- **解析时间 (UTC)**:`{parsed['parsed_utc']}` · 解析器版本 `v{parsed['parser_version']}` (`{parsed['mode']}`)")
  3641. lines.append(
  3642. f"- **总采样规模**:`{parsed['total_1hz_rows']:,}` 行 1Hz 遥测(总时长 `{parsed['total_duration_hms']}` / `{parsed['total_duration_s']}s`),"
  3643. f"识别独立位置传感器 `{len(parsed['sensors'])}` 路,自动检出微事件/异常切换 `{len(parsed.get('micro_events') or [])}` 项"
  3644. )
  3645. lines.extend(["", "---", "", "## 1. 全部独立位置传感器全周期实测范围 (`min~max`, `起点→终点`)", ""])
  3646. lines.append("| 传感器 | 类别 | 有效样本 | 最小值 | 最大值 | 起点 | 终点 | 全周期变化 |")
  3647. lines.append("|---|---|---:|---:|---:|---:|---:|---:|")
  3648. for s in parsed["sensors"]:
  3649. st = parsed["overall_sensors"].get(s["key"])
  3650. if not st:
  3651. continue
  3652. u = s["unit"]
  3653. lines.append(f"| `{s['key']}` ({s['label']}) | `{s['group']}` | `{st['count']}` | `{st['min']}{u}` | `{st['max']}{u}` | `{st['start']}{u}` | `{st['end']}{u}` | `{st['delta']:+}{u}` |")
  3654. lines.extend(["", "## 2. 各算法负载窗口逐 DIMM 插槽独立温升 (`min~max`, `起点→峰值`, 升温斜率 `°C/min`)", ""])
  3655. hdr_dimm = " | ".join(f"{dk.replace('_Temp','')} (起→峰 / +Δ / 全斜率 / 前40s斜率)" for dk in dimm_keys)
  3656. lines.append(f"| 算法 Run | 引擎 / 轮数 | 有效负载时长 | 最大跨槽极差 | {hdr_dimm} |")
  3657. lines.append("|---|---|---|---|" + "|".join(["---"] * len(dimm_keys)) + "|")
  3658. for rk, rd in parsed["runs"].items():
  3659. if not rd["active_rows"]:
  3660. continue
  3661. cells = []
  3662. for dk in dimm_keys:
  3663. dr = rd["per_dimm_thermal_response"].get(dk) or {}
  3664. if dr.get("active_max_c") is None:
  3665. cells.append("-")
  3666. else:
  3667. es = dr.get("early_slope_c_per_min")
  3668. es_txt = f" / 初期`{es}°C/m`" if es is not None else ""
  3669. cells.append(
  3670. f"`{dr['active_start_c']}→{dr['active_max_c']}°C` (`+{round((dr['active_max_c'] - dr['active_start_c']), 2)}°C` / 全`{dr['heating_rate_c_per_min']}°C/m`{es_txt})"
  3671. )
  3672. sp_txt = f"`{rd['max_all_dimm_spread_c']}°C`" if rd.get("max_all_dimm_spread_c") is not None else "-"
  3673. lines.append(f"| `{rk}` ({rd['algo_name']}) | `{rd['engine']}` · `{rd['loop_total']} loops` | `{rd['active_duration_s']}s` (`{rd['active_rows']}行`) | {sp_txt} | " + " | ".join(cells) + " |")
  3674. lines.extend(["", "## 3. 各算法负载窗口逐供电/功耗与 CPU 位置传感器独立范围 (`min~max`)", ""])
  3675. lines.append("| 算法 Run | DDR0_Power | DDR2_Power | P12V_DDR0/2 | PVCCD_CPU0 / CPU1 | Dimm_Power CPU0 / CPU1 | CPU0 / CPU1 Power | CPU0 / CPU1 Temp | PSU0 PIn / POut |")
  3676. lines.append("|---|---|---|---|---|---|---|---|---|")
  3677. for rk, rd in parsed["runs"].items():
  3678. if not rd["active_rows"]:
  3679. continue
  3680. act = rd["active_sensors"]
  3681. lines.append(
  3682. f"| `{rk}` | {_fmt_range(act.get('DDR0_Power'), 'W', False)} | {_fmt_range(act.get('DDR2_Power'), 'W', False)} | "
  3683. f"{_fmt_range(act.get('P12V_DDR0'), 'V', False)} / {_fmt_range(act.get('P12V_DDR2'), 'V', False)} | "
  3684. f"{_fmt_range(act.get('PVCCD_CPU0_Input_Power'), 'W', False)} / {_fmt_range(act.get('PVCCD_CPU1_Input_Power'), 'W', False)} | "
  3685. f"{_fmt_range(act.get('Dimm_Power_CPU0'), 'W', False)} / {_fmt_range(act.get('Dimm_Power_CPU1'), 'W', False)} | "
  3686. f"{_fmt_range(act.get('CPU0_Power_Avg'), 'W', False)} / {_fmt_range(act.get('CPU1_Power_Avg'), 'W', False)} | "
  3687. f"{_fmt_range(act.get('CPU0_Temp'), '°C', False)} / {_fmt_range(act.get('CPU1_Temp'), '°C', False)} | "
  3688. f"{_fmt_range(act.get('PSU0_PIn'), 'W', False)} / {_fmt_range(act.get('PSU0_POut'), 'W', False)} |"
  3689. )
  3690. lines.extend(["", "## 4. 各算法停载后 150s 冷却恢复(逐 DIMM 插槽实测回落、SPD 延迟与 τ_cool)", ""])
  3691. hdr_cool = " | ".join(f"{dk.replace('_Temp','')} (起→末 / 距峰值回落 / τ_cool)" for dk in dimm_keys)
  3692. lines.append(f"| 算法 Run | 冷却有效/空值行 (首读延迟) | {hdr_cool} |")
  3693. lines.append("|---|---|" + "|".join(["---"] * len(dimm_keys)) + "|")
  3694. for rk, rd in parsed["runs"].items():
  3695. if not rd["cooldown_sensors"]:
  3696. continue
  3697. dr0 = rd["per_dimm_thermal_response"].get(dimm_keys[0]) or {}
  3698. c_cnt = dr0.get("cooldown_valid_rows", 0)
  3699. c_null = dr0.get("cooldown_null_rows", 0)
  3700. delay = dr0.get("cooldown_first_valid_delay_s")
  3701. delay_txt = f", 首读+{delay}s" if delay is not None and delay > 0 else ""
  3702. cells = []
  3703. for dk in dimm_keys:
  3704. dr = rd["per_dimm_thermal_response"].get(dk) or {}
  3705. if dr.get("cooldown_start_c") is None:
  3706. cells.append("-")
  3707. else:
  3708. delta_c = round(dr["cooldown_end_c"] - dr["cooldown_start_c"], 2)
  3709. pk_drop = dr.get("cooldown_total_drop_from_peak_c")
  3710. tau_txt = f" / `τ={dr['tau_cool_s']}s`" if dr.get("tau_cool_s") is not None else ""
  3711. pk_txt = f" (较峰`-{pk_drop}°C`)" if pk_drop is not None else ""
  3712. cells.append(f"`{dr['cooldown_start_c']}→{dr['cooldown_end_c']}°C` (`{delta_c:+}°C`{pk_txt}{tau_txt})")
  3713. lines.append(f"| `{rk}` | `{c_cnt}s` / null `{c_null}s`{delay_txt} | " + " | ".join(cells) + " |")
  3714. mevs = parsed.get("micro_events") or []
  3715. if mevs:
  3716. lines.extend(["", "## 5. 自动检出微事件与异常细节定位 (`#seq` 精确索引)", ""])
  3717. lines.append("| 编号 | 类别 | Run / 阶段 | `#seq` 区间 | 事件标题 | 实测详情 |")
  3718. lines.append("|---|---|---|---|---|---|")
  3719. for ev in mevs:
  3720. seq_txt = f"`#{ev['seq_start']}`" if ev["seq_start"] == ev["seq_end"] else f"`#{ev['seq_start']}..#{ev['seq_end']}` (`{ev['rows']}s`)"
  3721. lines.append(f"| `{ev['id']}` | `{ev['category']}` | `{ev['run_key']}` · `{ev['phase']}` | {seq_txt} | **{ev['title']}** | {ev['detail']} |")
  3722. lines.extend(["", "## 6. 全部连续阶段切片汇总 (按时间先后,含空值审计)", ""])
  3723. lines.append("| `#seq` | Run | 子阶段 | 时长 | SPD有效/空 | PECI有效/空 | `CPU0_A` | `CPU1_A` | `DDR0_Power` | `PSU0_PIn` |")
  3724. lines.append("|---|---|---|---:|---:|---:|---|---|---|---|")
  3725. all_slices: list[tuple[str, dict[str, Any]]] = []
  3726. for rk, rd in parsed["runs"].items():
  3727. for sl in rd.get("phases") or []:
  3728. all_slices.append((rk, sl))
  3729. all_slices.sort(key=lambda x: x[1]["seq_start"])
  3730. for rk, sl in all_slices:
  3731. ss = sl["sensors"]
  3732. lines.append(
  3733. f"| `#{sl['seq_start']}..{sl['seq_end']}` | `{rk}` | `{sl['phase']}` | `{sl['rows']}s` | "
  3734. f"`{sl['spd_valid_rows']}/{sl['spd_null_rows']}` | `{sl['peci_valid_rows']}/{sl['peci_null_rows']}` | "
  3735. f"{_fmt_range(ss.get('DIMM_CPU0_A_Temp'), '°C')} | {_fmt_range(ss.get('DIMM_CPU1_A_Temp'), '°C')} | "
  3736. f"{_fmt_range(ss.get('DDR0_Power'), 'W', False)} | {_fmt_range(ss.get('PSU0_PIn'), 'W', False)} |"
  3737. )
  3738. return "\n".join(lines) + "\n"
  3739. def render_campaign_html_dashboard(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
  3740. payload = {
  3741. "meta": {
  3742. "parser_version": parsed["parser_version"],
  3743. "mode": parsed["mode"],
  3744. "parsed_utc": parsed["parsed_utc"],
  3745. "data_file": parsed["data_file"],
  3746. "bmc_host": parsed["bmc_host"],
  3747. "total_1hz_rows": parsed["total_1hz_rows"],
  3748. "total_duration_hms": parsed["total_duration_hms"],
  3749. "total_duration_s": parsed["total_duration_s"],
  3750. "poll_latency_ms": parsed.get("poll_latency_ms"),
  3751. "sensors": parsed["sensors"],
  3752. "dimm_keys": parsed["dimm_keys"],
  3753. },
  3754. "overall_sensors": parsed["overall_sensors"],
  3755. "runs": parsed["runs"],
  3756. "micro_events": parsed.get("micro_events") or [],
  3757. "bmc_benchmark": parsed.get("bmc_benchmark"),
  3758. "series": artifacts["series"],
  3759. }
  3760. payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
  3761. figs_json = json.dumps(artifacts.get("embedded_figures") or [], ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
  3762. title = html.escape(f"2026-11-13 无温控直跑单算法 · 逐阶段逐传感器完整报告 ({parsed['total_1hz_rows']:,} 行)")
  3763. head_html = r"""<!DOCTYPE html>
  3764. <html lang="zh-CN">
  3765. <head>
  3766. <meta charset="UTF-8">
  3767. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  3768. <title>__TITLE__</title>
  3769. <style>
  3770. :root {
  3771. --bg: #0b101b; --bg-card: #121a2b; --bg-alt: #182338;
  3772. --text: #e6edf7; --muted: #93a4be; --border: #253554;
  3773. --accent: #38bdf8; --accent2: #818cf8; --good: #22c55e; --warn: #f59e0b; --bad: #ef4444;
  3774. }
  3775. body.light {
  3776. --bg: #f1f5f9; --bg-card: #ffffff; --bg-alt: #e8eff8;
  3777. --text: #0f172a; --muted: #475569; --border: #cbd5e1;
  3778. --accent: #0284c7; --accent2: #4f46e5;
  3779. }
  3780. * { box-sizing: border-box; margin: 0; padding: 0; }
  3781. body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; background: var(--bg); color: var(--text); line-height: 1.5; padding-bottom: 52px; }
  3782. header { background: var(--bg-card); border-bottom: 1px solid var(--border); padding: 12px 24px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; position: sticky; top: 0; z-index: 30; }
  3783. .hdr-title h1 { font-size: 17px; font-weight: 700; }
  3784. .hdr-sub { font-size: 12px; color: var(--muted); margin-top: 2px; }
  3785. .controls { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
  3786. select, button, input[type="number"], input[type="text"] {
  3787. background: var(--bg-alt); color: var(--text); border: 1px solid var(--border);
  3788. border-radius: 6px; padding: 5px 9px; font-size: 12.5px;
  3789. }
  3790. button, select { cursor: pointer; }
  3791. button:hover, select:hover { border-color: var(--accent); }
  3792. button.active { background: var(--accent); color: #07101e; border-color: var(--accent); font-weight: 600; }
  3793. button.primary { background: var(--accent); color: #07101e; border-color: var(--accent); font-weight: 600; }
  3794. .btn-xs { padding: 3px 8px; font-size: 11.5px; }
  3795. .toggle-pill { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg-alt); font-size: 12px; cursor: pointer; user-select: none; }
  3796. .toggle-pill input { accent-color: var(--accent); }
  3797. .container { max-width: 1620px; margin: 16px auto; padding: 0 18px; }
  3798. .kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; margin-bottom: 14px; }
  3799. .kpi-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 11px 14px; }
  3800. .kpi-label { font-size: 11.5px; color: var(--muted); }
  3801. .kpi-val { font-size: 18px; font-weight: 700; margin-top: 3px; }
  3802. .kpi-sub { font-size: 11.5px; color: var(--muted); margin-top: 3px; }
  3803. .tabs { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
  3804. .tab-btn { padding: 7px 13px; font-size: 13px; }
  3805. .tab-panel { display: none; }
  3806. .tab-panel.active { display: block; }
  3807. .card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 12px 15px; margin-bottom: 14px; }
  3808. .card-hdr { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 8px; }
  3809. .card-hdr h3 { font-size: 14.5px; font-weight: 600; }
  3810. .sub-note { font-size: 12px; color: var(--muted); }
  3811. .badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; }
  3812. .badge.pass { background: rgba(34,197,94,0.16); color: var(--good); border: 1px solid rgba(34,197,94,0.35); }
  3813. .badge.warn { background: rgba(245,158,11,0.16); color: var(--warn); border: 1px solid rgba(245,158,11,0.35); }
  3814. .badge.peak { background: rgba(239,68,68,0.16); color: var(--bad); border: 1px solid rgba(239,68,68,0.35); }
  3815. .badge.info { background: rgba(56,189,248,0.16); color: var(--accent); border: 1px solid rgba(56,189,248,0.35); }
  3816. .legend { display: flex; flex-wrap: wrap; gap: 6px 12px; font-size: 11.5px; color: var(--muted); margin-bottom: 6px; }
  3817. .legend-item { display: inline-flex; align-items: center; gap: 5px; cursor: pointer; user-select: none; }
  3818. .legend-item.off { opacity: 0.35; text-decoration: line-through; }
  3819. .swatch { width: 12px; height: 3px; border-radius: 2px; display: inline-block; }
  3820. .chart-wrap { position: relative; width: 100%; height: 245px; overflow: hidden; }
  3821. .chart-wrap.sm { height: 195px; }
  3822. .chart-wrap.xs { height: 170px; }
  3823. .chart-wrap.lg { height: 300px; }
  3824. .chart-wrap canvas { width: 100%; height: 100%; display: block; }
  3825. .phase-legend { display: flex; flex-wrap: wrap; gap: 10px; font-size: 11.5px; color: var(--muted); margin-top: 6px; }
  3826. .ph-dot { width: 10px; height: 10px; border-radius: 2px; display: inline-block; vertical-align: middle; margin-right: 4px; }
  3827. .pin-bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 12px; border-radius: 8px; background: rgba(56,189,248,0.08); border: 1px solid rgba(56,189,248,0.28); margin-bottom: 12px; font-size: 12px; }
  3828. .me-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 10px; max-height: 360px; overflow-y: auto; padding-right: 4px; }
  3829. .me-card { background: var(--bg-alt); border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; display: flex; flex-direction: column; justify-content: space-between; gap: 8px; }
  3830. .me-card-top { display: flex; justify-content: space-between; align-items: center; gap: 6px; font-size: 11.5px; color: var(--muted); }
  3831. .me-title { font-size: 13px; font-weight: 600; color: var(--text); }
  3832. .me-detail { font-size: 12px; color: var(--muted); line-height: 1.45; }
  3833. .fig-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(430px, 1fr)); gap: 14px; }
  3834. .fig-card { background: var(--bg-alt); border: 1px solid var(--border); border-radius: 8px; padding: 10px; }
  3835. .fig-card img { width: 100%; height: auto; border-radius: 6px; cursor: zoom-in; border: 1px solid var(--border); background: #fff; }
  3836. .fig-hdr { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 8px; font-size: 12.5px; font-weight: 600; }
  3837. .modal { position: fixed; inset: 0; background: rgba(6,10,18,0.88); z-index: 1000; display: none; align-items: center; justify-content: center; padding: 20px; }
  3838. .modal.open { display: flex; }
  3839. .modal-box { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; max-width: 96vw; max-height: 94vh; padding: 14px; display: flex; flex-direction: column; gap: 10px; }
  3840. .modal-box img { max-width: 92vw; max-height: 82vh; object-fit: contain; background: #fff; border-radius: 6px; }
  3841. .table-scroll { overflow-x: auto; max-height: 620px; overflow-y: auto; }
  3842. table { width: 100%; border-collapse: collapse; font-size: 11.8px; }
  3843. th, td { padding: 5px 8px; border-bottom: 1px solid var(--border); text-align: left; white-space: nowrap; }
  3844. th { background: var(--bg-alt); color: var(--muted); font-weight: 600; position: sticky; top: 0; z-index: 2; }
  3845. tr:hover td { background: rgba(56,189,248,0.07); }
  3846. .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
  3847. .null-cell { color: var(--muted); font-style: italic; opacity: 0.72; }
  3848. .anom-warn { background: rgba(245,158,11,0.18); color: #fbbf24; font-weight: 600; border-radius: 4px; padding: 1px 4px; }
  3849. .anom-droop { background: rgba(239,68,68,0.18); color: #f87171; font-weight: 600; border-radius: 4px; padding: 1px 4px; }
  3850. .anom-warm { background: rgba(56,189,248,0.18); color: #38bdf8; font-weight: 600; border-radius: 4px; padding: 1px 4px; }
  3851. pre { background: var(--bg-alt); border: 1px solid var(--border); border-radius: 8px; padding: 10px; font-size: 11.5px; overflow-x: auto; max-height: 300px; }
  3852. .tooltip { position: fixed; pointer-events: none; background: rgba(11,16,27,0.96); color: #e6edf7; border: 1px solid #38bdf8; border-radius: 8px; padding: 9px 11px; font-size: 11.5px; line-height: 1.45; z-index: 999; display: none; max-width: 520px; box-shadow: 0 8px 24px rgba(0,0,0,0.5); }
  3853. .filter-grid { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 10px; }
  3854. </style>
  3855. </head>
  3856. <body>
  3857. <header>
  3858. <div class="hdr-title">
  3859. <h1>2026-11-13 无温控直跑单算法 · 全阶段与全传感器 1Hz 独立解析报告 (无均值)</h1>
  3860. <div class="hdr-sub" id="hdr-sub">加载中...</div>
  3861. </div>
  3862. <div class="controls">
  3863. <button type="button" id="btn-jump-raw">逐秒明细 &amp; 微事件</button>
  3864. <button type="button" id="btn-export-all">导出全量 clean CSV</button>
  3865. <button type="button" id="btn-theme">亮/暗主题</button>
  3866. </div>
  3867. </header>
  3868. <div class="container">
  3869. <div class="kpi-grid" id="kpi-grid"></div>
  3870. <div class="tabs">
  3871. <button type="button" class="tab-btn active" data-tab="tab-waves">1. 1Hz 同步多维传感器曲线</button>
  3872. <button type="button" class="tab-btn" data-tab="tab-algos">2. 7 大算法对比 &amp; 曲线截图集</button>
  3873. <button type="button" class="tab-btn" data-tab="tab-phases">3. 全部详细阶段 &amp; 轮次 (全 21 路传感器)</button>
  3874. <button type="button" class="tab-btn" data-tab="tab-raw">4. 全量 1Hz 逐秒明细 &amp; 微事件排查</button>
  3875. <button type="button" class="tab-btn" data-tab="tab-bench">5. Sensor 清单 · BMC 基准 · 总结</button>
  3876. </div>
  3877. <div id="tab-waves" class="tab-panel active">
  3878. <div class="card">
  3879. <div class="card-hdr">
  3880. <h3>区间缩放 &amp; 微变化快捷定位 (4 图 X 轴联动 · 左键拖拽框选放大 · 单击固定采样点 · 双击复位)</h3>
  3881. <div class="controls">
  3882. <label class="toggle-pill"><input type="checkbox" id="chk-skip-boot"> 跳过前置 boot/init (仅看 基线→Loop→冷却)</label>
  3883. <button type="button" class="btn-xs" id="btn-reset-zoom">复位全过程</button>
  3884. </div>
  3885. </div>
  3886. <div class="controls" id="zoom-bar" style="margin-bottom:8px"></div>
  3887. <div class="controls" id="me-pills" style="margin-bottom:6px"></div>
  3888. <div class="phase-legend">
  3889. <span><i class="ph-dot" style="background:rgba(245,158,11,0.35)"></i>boot_to_amt / init (重启或初始化)</span>
  3890. <span><i class="ph-dot" style="background:rgba(56,189,248,0.35)"></i>pre_baseline (静息基线)</span>
  3891. <span><i class="ph-dot" style="background:rgba(34,197,94,0.38)"></i>loop_1..N (单算法运行)</span>
  3892. <span><i class="ph-dot" style="background:rgba(168,85,247,0.35)"></i>cooldown (150s 停载冷却;AMT含初段~18-22s热重启SPD空窗及~100s二次切OS约10s空窗)</span>
  3893. </div>
  3894. </div>
  3895. <div class="pin-bar" id="pin-bar">
  3896. <span id="pin-text" class="mono">提示:在任意曲线图上单击可固定某 1 秒采样点,快速核对该秒全 21 路传感器或跳转至明细表。</span>
  3897. <span class="controls" id="pin-actions" style="display:none">
  3898. <button type="button" class="btn-xs primary" id="btn-pin-raw">在逐秒明细表定位</button>
  3899. <button type="button" class="btn-xs" id="btn-pin-clear">清除固定</button>
  3900. </span>
  3901. </div>
  3902. <div class="card">
  3903. <div class="card-hdr">
  3904. <h3>Chart 1A · 5 路独立 DIMM 插槽 + CPU0/1 温度 1Hz 曲线 (°C,无均值)</h3>
  3905. <div class="controls">
  3906. <span class="mono badge info" id="win-badge"></span>
  3907. <button type="button" class="btn-xs" data-tmp-preset="all">全部显示</button>
  3908. <button type="button" class="btn-xs" data-tmp-preset="dimms">仅5路DIMM</button>
  3909. <button type="button" class="btn-xs" data-tmp-preset="cpu0">仅CPU0 A..D</button>
  3910. <button type="button" class="btn-xs" data-tmp-preset="edge">CPU0_A vs CPU1_A</button>
  3911. </div>
  3912. </div>
  3913. <div class="legend" id="legend-temp"></div>
  3914. <div class="chart-wrap"><canvas id="chart-temp"></canvas></div>
  3915. </div>
  3916. <div class="card">
  3917. <div class="card-hdr">
  3918. <h3>Chart 1B · 内存供电轨独立功耗 1Hz 曲线 (DDR0/DDR2/PVCCD/PECI DIMM, 0~55W 独立坐标轴)</h3>
  3919. <div class="controls">
  3920. <button type="button" class="btn-xs" data-mpwr-preset="all">全部显示</button>
  3921. <button type="button" class="btn-xs" data-mpwr-preset="vr">仅PMBus VR (DDR0/DDR2)</button>
  3922. <button type="button" class="btn-xs" data-mpwr-preset="peci">对比PMBus vs PECI</button>
  3923. </div>
  3924. </div>
  3925. <div class="legend" id="legend-mpwr"></div>
  3926. <div class="chart-wrap sm"><canvas id="chart-mpwr"></canvas></div>
  3927. </div>
  3928. <div class="card">
  3929. <div class="card-hdr">
  3930. <h3>Chart 1C · 整机 PSU0 与 CPU0/CPU1 功耗 1Hz 曲线 (100~800W)</h3>
  3931. <div class="controls">
  3932. <button type="button" class="btn-xs" data-spwr-preset="all">全部显示</button>
  3933. <button type="button" class="btn-xs" data-spwr-preset="psu">仅PSU0输入/输出</button>
  3934. <button type="button" class="btn-xs" data-spwr-preset="cpu">仅CPU0/CPU1功耗</button>
  3935. </div>
  3936. </div>
  3937. <div class="legend" id="legend-spwr"></div>
  3938. <div class="chart-wrap sm"><canvas id="chart-spwr"></canvas></div>
  3939. </div>
  3940. <div class="card">
  3941. <div class="card-hdr">
  3942. <h3 id="elec-chart-title">Chart 1D · 电参数 &amp; 采集健康度 (当前:DDR0/DDR2 电流 A)</h3>
  3943. <div class="controls">
  3944. <button type="button" class="btn-xs active" data-elec-mode="curr">电流 (DDR0/2_Curr A)</button>
  3945. <button type="button" class="btn-xs" data-elec-mode="volt">12V 供电电压压降 (P12V V)</button>
  3946. <button type="button" class="btn-xs" data-elec-mode="lat">BMC 1Hz 采集耗时 (ms)</button>
  3947. </div>
  3948. </div>
  3949. <div class="legend" id="legend-elec"></div>
  3950. <div class="chart-wrap xs"><canvas id="chart-elec"></canvas></div>
  3951. </div>
  3952. </div>
  3953. <div id="tab-algos" class="tab-panel">
  3954. <div class="card">
  3955. <div class="card-hdr">
  3956. <h3>Chart 2 · 7 大单算法逐插槽热/功耗/时间常数对比 (无均值)</h3>
  3957. <div class="controls">
  3958. <select id="bar-metric-select">
  3959. <option value="dimm_delta">5 路 DIMM 负载期温升 ΔT (°C)</option>
  3960. <option value="dimm_max">5 路 DIMM 峰值温度 (°C)</option>
  3961. <option value="dimm_rate">全负载窗口升温斜率 (°C/min)</option>
  3962. <option value="dimm_early">前 40s 初期升温斜率 (°C/min)</option>
  3963. <option value="tau_cool">停载冷却时间常数 τ_cool (s, 越小散热越快)</option>
  3964. <option value="ddr_max">DDR0 vs DDR2 vs PVCCD 峰值功耗 (W)</option>
  3965. <option value="psu_max">PSU0 PIn vs CPU0 vs CPU1 峰值功耗 (W)</option>
  3966. </select>
  3967. </div>
  3968. </div>
  3969. <div class="chart-wrap lg"><canvas id="chart-bars"></canvas></div>
  3970. </div>
  3971. <div class="card">
  3972. <div class="card-hdr"><h3>各算法负载窗口 · 逐 DIMM 插槽独立温升、初期/全窗斜率与跨槽极差</h3></div>
  3973. <div class="table-scroll" id="algo-dimm-table"></div>
  3974. </div>
  3975. <div class="card">
  3976. <div class="card-hdr"><h3>各算法负载窗口 · 逐供电/电流/电压/PECI 与 CPU 位置传感器范围 (<code>min~max</code>)</h3></div>
  3977. <div class="table-scroll" id="algo-pwr-table"></div>
  3978. </div>
  3979. <div class="card">
  3980. <div class="card-hdr"><h3>停载冷却恢复 (150s Cooldown) 逐插槽实测回落、SPD 首读延迟与 τ_cool</h3></div>
  3981. <div class="table-scroll" id="algo-cool-table"></div>
  3982. </div>
  3983. <div class="card">
  3984. <div class="card-hdr">
  3985. <h3>高精度实测曲线截图集 (PNG 离线内嵌 · 点击放大 / 右上角另存发送)</h3>
  3986. <span class="sub-note" id="fig-count-note"></span>
  3987. </div>
  3988. <div id="fig-gallery" class="fig-grid"></div>
  3989. </div>
  3990. </div>
  3991. <div id="tab-phases" class="tab-panel">
  3992. <div class="card">
  3993. <div class="card-hdr">
  3994. <h3>全部连续阶段切片拆解 (<code>idle_check</code> / <code>init</code> / <code>boot_to_amt</code> / <code>pre_baseline</code> / <code>loop_1..N</code> / <code>cooldown</code>)</h3>
  3995. <div class="controls">
  3996. <label>Run:<select id="phase-run-filter"><option value="">全部 Run</option></select></label>
  3997. <label>阶段类型:<select id="phase-grp-filter">
  3998. <option value="">全部阶段</option>
  3999. <option value="baseline">仅 pre_baseline</option>
  4000. <option value="active_loop">仅 loop_1..N</option>
  4001. <option value="cooldown">仅 cooldown</option>
  4002. <option value="startup">仅 boot_to_amt / init</option>
  4003. <option value="idle">仅 inter_algo_settle / idle_check</option>
  4004. </select></label>
  4005. <label>显示传感器列:<select id="phase-col-preset">
  4006. <option value="core">核心温度 + 功耗 + 12V (11路)</option>
  4007. <option value="all">全部 21 路传感器展开</option>
  4008. <option value="dimm">仅 5 路 DIMM + CPU0/1 温度</option>
  4009. <option value="pwr">全部功耗 + 电流 + 12V + PECI</option>
  4010. </select></label>
  4011. </div>
  4012. </div>
  4013. <div class="table-scroll" id="phases-detail-table"></div>
  4014. </div>
  4015. <div class="card">
  4016. <div class="card-hdr">
  4017. <h3>BIOS 固件 Loop 完成事件记录 (<code>loop_events</code> · Socket 0 vs Socket 1 实测秒数对照)</h3>
  4018. <span class="sub-note">来自 <code>thermal_campaign_summary.json</code>,精确映射至对应 1Hz 采样 <code>#seq</code></span>
  4019. </div>
  4020. <div class="table-scroll" id="loop-events-table"></div>
  4021. </div>
  4022. </div>
  4023. <div id="tab-raw" class="tab-panel">
  4024. <div class="card">
  4025. <div class="card-hdr">
  4026. <h3>自动检出微事件 &amp; 异常变化定向排查书签 (<span id="me-count">0</span> 项)</h3>
  4027. <div class="controls">
  4028. <label>筛选类别:<select id="me-cat-filter"><option value="">全部类别</option></select></label>
  4029. <span class="sub-note">点击卡片按钮可直接将曲线放大至该瞬态窗口,或锁定到下方 1Hz 逐秒记录。</span>
  4030. </div>
  4031. </div>
  4032. <div class="me-grid" id="me-cards"></div>
  4033. </div>
  4034. <div class="card">
  4035. <div class="card-hdr">
  4036. <h3>全量 1Hz 逐秒遥测数据浏览器 (逐样本 × 逐位置传感器,支持条件过滤与离线 CSV 导出)</h3>
  4037. <div class="controls">
  4038. <span class="mono sub-note" id="raw-count-info">0 行</span>
  4039. <button type="button" class="primary btn-xs" id="btn-raw-export">导出当前筛选 CSV</button>
  4040. </div>
  4041. </div>
  4042. <div class="filter-grid">
  4043. <label>Run: <select id="raw-run"><option value="">全部</option></select></label>
  4044. <label>阶段: <select id="raw-phase"><option value="">全部</option></select></label>
  4045. <label>快捷排查: <select id="raw-preset">
  4046. <option value="all">全部 1Hz 样本</option>
  4047. <option value="spd_null">SPD 传感器离线 (任意 DIMM=null)</option>
  4048. <option value="peci_null">PECI 功耗离线 (Dimm_Power_CPU0=null)</option>
  4049. <option value="cool_spike">cooldown 阶段高功耗脉冲 (DDR0≥20W)</option>
  4050. <option value="p12v_droop">12V 供电下探 (P12V_DDR0≤12.13V)</option>
  4051. <option value="high_lat">BMC 高采集延迟 (poll_latency≥300ms)</option>
  4052. <option value="temp_jump">DIMM 单秒温跳 (|ΔDIMM|≥0.75°C/s)</option>
  4053. <option value="pwr_jump">DDR0 功耗阶跃 (|ΔDDR0|≥5W/s)</option>
  4054. </select></label>
  4055. <label>#seq: <input type="number" id="raw-seq-min" placeholder="起" style="width:72px"> ~ <input type="number" id="raw-seq-max" placeholder="止" style="width:72px"></label>
  4056. <label>自定义:
  4057. <select id="raw-cust-col"><option value="">(不限指标)</option></select>
  4058. <select id="raw-cust-op">
  4059. <option value="gt">&gt;</option>
  4060. <option value="ge">&gt;=</option>
  4061. <option value="lt">&lt;</option>
  4062. <option value="le">&lt;=</option>
  4063. <option value="isnull">is null</option>
  4064. <option value="notnull">not null</option>
  4065. </select>
  4066. <input type="number" step="any" id="raw-cust-val" placeholder="阈值" style="width:78px">
  4067. </label>
  4068. <label>列组:
  4069. <select id="raw-col-group">
  4070. <option value="core">核心温度 + 功耗 + 12V (11列)</option>
  4071. <option value="all">全部 21 路传感器展开</option>
  4072. <option value="temps">全部温度 + 延迟</option>
  4073. <option value="elec">全部功耗 + 电流 + 12V + PECI</option>
  4074. </select>
  4075. </label>
  4076. <label>每页:
  4077. <select id="raw-page-size">
  4078. <option value="50">50</option>
  4079. <option value="100" selected>100</option>
  4080. <option value="200">200</option>
  4081. <option value="500">500</option>
  4082. </select>
  4083. </label>
  4084. <button type="button" class="btn-xs" id="btn-raw-reset">重置筛选</button>
  4085. </div>
  4086. <div class="controls" style="margin-bottom:8px;justify-content:space-between">
  4087. <div class="controls">
  4088. <button type="button" class="btn-xs" id="raw-prev">上一页</button>
  4089. <span class="mono" id="raw-page-info">1 / 1</span>
  4090. <button type="button" class="btn-xs" id="raw-next">下一页</button>
  4091. </div>
  4092. <span class="sub-note">提示:点击行号 <code>#seq</code> 可切回曲线页并放大至该时刻 <code>±30s</code>;表格内斜体灰字表示硬件当时不可访问 (<code>null</code>)。</span>
  4093. </div>
  4094. <div class="table-scroll" id="raw-table-wrap"></div>
  4095. </div>
  4096. </div>
  4097. <div id="tab-bench" class="tab-panel">
  4098. <div class="card">
  4099. <div class="card-hdr"><h3>全部 21 路独立位置传感器全周期统计 (<code>min~max</code>, <code>起点→终点</code>, 有效/空值计数)</h3></div>
  4100. <div class="table-scroll" id="overall-sensors-table"></div>
  4101. </div>
  4102. <div class="card" id="bench-card">
  4103. <div class="card-hdr"><h3>BMC 采集链路基准对比 (<code>ipmitool lanplus</code> vs <code>OpenBMC D-Bus GetManagedObjects</code>)</h3></div>
  4104. <div id="bench-body"></div>
  4105. </div>
  4106. <div class="card">
  4107. <div class="card-hdr"><h3>核心数据洞察 &amp; 工程要点索引</h3></div>
  4108. <div id="conclusions-box" style="font-size:13px;line-height:1.7"></div>
  4109. </div>
  4110. </div>
  4111. </div>
  4112. <div class="tooltip" id="tooltip"></div>
  4113. <div class="modal" id="fig-modal">
  4114. <div class="modal-box">
  4115. <div class="card-hdr" style="margin:0">
  4116. <h3 id="modal-title">图片预览</h3>
  4117. <div class="controls">
  4118. <a id="modal-dl" download class="badge info" style="text-decoration:none;padding:5px 10px">下载 PNG 原图</a>
  4119. <button type="button" id="modal-close">关闭 (Esc)</button>
  4120. </div>
  4121. </div>
  4122. <img id="modal-img" alt="figure preview">
  4123. </div>
  4124. </div>
  4125. """.replace("__TITLE__", title)
  4126. script_js = r"""
  4127. <script>
  4128. (() => {
  4129. const DATA = JSON.parse(document.getElementById('embedded-data').textContent);
  4130. const FIGS = JSON.parse(document.getElementById('embedded-figures').textContent);
  4131. const ser = DATA.series;
  4132. const cols = ser.cols;
  4133. const n = cols.seq.length;
  4134. const microEvents = DATA.micro_events || [];
  4135. let zoomStart = 0, zoomEnd = n, hoverIdx = null, pinnedIdx = null;
  4136. let dragStartIdx = null, dragCurIdx = null, dragStartClientX = 0;
  4137. let elecMode = 'curr';
  4138. let activeRunZoom = 'ALL';
  4139. let rawPage = 1, rawFiltered = [];
  4140. let barCache = [];
  4141. const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  4142. const fmtMM = (st, u='') => st ? `${st.min}~${st.max}${u}` : '-';
  4143. const fmtSE = (st, u='') => st ? `${st.start}→${st.end}${u}` : '-';
  4144. // Precompute contiguous phase segments once for fast canvas shading & labels
  4145. const phaseSegs = [];
  4146. for (let i = 0; i < n; ) {
  4147. const rId = cols.rk[i], pId = cols.ph[i];
  4148. let j = i + 1;
  4149. while (j < n && cols.rk[j] === rId && cols.ph[j] === pId) j++;
  4150. phaseSegs.push({ rk: ser.run_names[rId], ph: ser.phase_names[pId], s: i, e: j });
  4151. i = j;
  4152. }
  4153. const tempSeries = [
  4154. { key: 'DIMM_CPU0_A_Temp', label: 'DIMM CPU0_A', color: '#ef4444', width: 1.8, grp: 'cpu0' },
  4155. { key: 'DIMM_CPU0_B_Temp', label: 'DIMM CPU0_B', color: '#f59e0b', width: 1.6, grp: 'cpu0' },
  4156. { key: 'DIMM_CPU0_C_Temp', label: 'DIMM CPU0_C', color: '#22c55e', width: 1.6, grp: 'cpu0' },
  4157. { key: 'DIMM_CPU0_D_Temp', label: 'DIMM CPU0_D', color: '#38bdf8', width: 1.6, grp: 'cpu0' },
  4158. { key: 'DIMM_CPU1_A_Temp', label: 'DIMM CPU1_A', color: '#a855f7', width: 1.9, grp: 'dimms' },
  4159. { key: 'CPU0_Temp', label: 'CPU0 温度', color: '#94a3b8', width: 1.2, dash: [4, 2], grp: 'cpu' },
  4160. { key: 'CPU1_Temp', label: 'CPU1 温度', color: '#64748b', width: 1.2, dash: [4, 2], grp: 'cpu' },
  4161. ].filter(s => cols[s.key]);
  4162. const enabledTemp = new Set(tempSeries.map(s => s.key));
  4163. const memPwrSeries = [
  4164. { key: 'DDR0_Power', label: 'DDR0 PMBus(W)', color: '#22c55e', width: 1.8, grp: 'vr' },
  4165. { key: 'DDR2_Power', label: 'DDR2 PMBus(W)', color: '#f59e0b', width: 1.8, grp: 'vr' },
  4166. { key: 'PVCCD_CPU0_Input_Power', label: 'PVCCD CPU0(W)', color: '#06b6d4', width: 1.3, grp: 'vr' },
  4167. { key: 'PVCCD_CPU1_Input_Power', label: 'PVCCD CPU1(W)', color: '#ec4899', width: 1.3, grp: 'vr' },
  4168. { key: 'Dimm_Power_CPU0', label: 'PECI DIMM0(W)', color: '#84cc16', width: 1.4, dash: [3,2], grp: 'peci' },
  4169. { key: 'Dimm_Power_CPU1', label: 'PECI DIMM1(W)', color: '#fb7185', width: 1.4, dash: [3,2], grp: 'peci' },
  4170. ].filter(s => cols[s.key]);
  4171. const enabledMemPwr = new Set(memPwrSeries.map(s => s.key));
  4172. const sysPwrSeries = [
  4173. { key: 'PSU0_PIn', label: 'PSU0 PIn(W)', color: '#38bdf8', width: 1.7, grp: 'psu' },
  4174. { key: 'PSU0_POut', label: 'PSU0 POut(W)', color: '#0ea5e9', width: 1.3, dash: [4,2], grp: 'psu' },
  4175. { key: 'CPU0_Power_Avg', label: 'PECI CPU0(W)', color: '#818cf8', width: 1.5, grp: 'cpu' },
  4176. { key: 'CPU1_Power_Avg', label: 'PECI CPU1(W)', color: '#c084fc', width: 1.5, grp: 'cpu' },
  4177. ].filter(s => cols[s.key]);
  4178. const enabledSysPwr = new Set(sysPwrSeries.map(s => s.key));
  4179. const elecModeConfigs = {
  4180. curr: {
  4181. title: 'Chart 1D · 电参数 & 采集健康度 (当前:DDR0/DDR2 供电电流 A)',
  4182. decimals: 2,
  4183. series: [
  4184. { key: 'DDR0_Curr', label: 'DDR0_Curr (A)', color: '#10b981', width: 1.6 },
  4185. { key: 'DDR2_Curr', label: 'DDR2_Curr (A)', color: '#fbbf24', width: 1.6 },
  4186. ].filter(s => cols[s.key]),
  4187. },
  4188. volt: {
  4189. title: 'Chart 1D · 电参数 & 采集健康度 (当前:P12V 供电轨电压压降 V · 3位小数精细轴)',
  4190. decimals: 3,
  4191. series: [
  4192. { key: 'P12V_DDR0', label: 'P12V_DDR0 (V)', color: '#ef4444', width: 1.6 },
  4193. { key: 'P12V_DDR2', label: 'P12V_DDR2 (V)', color: '#38bdf8', width: 1.6 },
  4194. ].filter(s => cols[s.key]),
  4195. },
  4196. lat: {
  4197. title: 'Chart 1D · 电参数 & 采集健康度 (当前:OpenBMC D-Bus 单次轮询耗时 ms)',
  4198. decimals: 0,
  4199. series: [
  4200. { key: 'lat', label: 'poll_latency_ms (ms)', color: '#f59e0b', width: 1.5 },
  4201. ],
  4202. },
  4203. };
  4204. const enabledElec = new Set(['DDR0_Curr', 'DDR2_Curr', 'P12V_DDR0', 'P12V_DDR2', 'lat']);
  4205. document.getElementById('hdr-sub').textContent =
  4206. `BMC: ${DATA.meta.bmc_host} | 无高温罩温控裸机直跑 | 样本: ${DATA.meta.total_1hz_rows.toLocaleString()} 行 (${DATA.meta.total_duration_hms}) | 传感器: ${DATA.meta.sensors.length} 路 | 检出微事件: ${microEvents.length} 项 | v${DATA.meta.parser_version}`;
  4207. document.getElementById('btn-jump-raw').textContent = `逐秒明细 & 微事件 (${n.toLocaleString()}行)`;
  4208. document.getElementById('btn-theme').onclick = () => { document.body.classList.toggle('light'); drawAll(); };
  4209. function switchTab(tabId) {
  4210. document.querySelectorAll('.tab-btn').forEach(b => b.classList.toggle('active', b.dataset.tab === tabId));
  4211. document.querySelectorAll('.tab-panel').forEach(p => p.classList.toggle('active', p.id === tabId));
  4212. requestAnimationFrame(() => drawAll());
  4213. }
  4214. document.querySelectorAll('.tab-btn').forEach(btn => { btn.onclick = () => switchTab(btn.dataset.tab); });
  4215. document.getElementById('btn-jump-raw').onclick = () => switchTab('tab-raw');
  4216. function exportCsvForIndices(indices, filename) {
  4217. const hdr = ['seq', 'iso_ts_hms', 'campaign_elapsed_s', 'run_key', 'phase', 'loop_index', 'poll_latency_ms']
  4218. .concat(DATA.meta.sensors.map(s => s.key));
  4219. const lines = [hdr.join(',')];
  4220. for (const i of indices) {
  4221. const row = [
  4222. cols.seq[i], cols.ts[i], cols.t[i],
  4223. ser.run_names[cols.rk[i]], ser.phase_names[cols.ph[i]],
  4224. cols.loop[i], cols.lat[i] ?? '',
  4225. ];
  4226. for (const s of DATA.meta.sensors) {
  4227. const v = cols[s.key]?.[i];
  4228. row.push(v == null ? '' : v);
  4229. }
  4230. lines.push(row.join(','));
  4231. }
  4232. const blob = new Blob(['\ufeff' + lines.join('\r\n')], { type: 'text/csv;charset=utf-8;' });
  4233. const a = document.createElement('a');
  4234. a.href = URL.createObjectURL(blob);
  4235. a.download = filename;
  4236. a.click();
  4237. setTimeout(() => URL.revokeObjectURL(a.href), 1500);
  4238. }
  4239. document.getElementById('btn-export-all').onclick = () => {
  4240. const allIdx = Array.from({ length: n }, (_, i) => i);
  4241. exportCsvForIndices(allIdx, 'thermal_campaign_all_3119_per_sensor.csv');
  4242. };
  4243. function setElecMode(mode) {
  4244. if (!elecModeConfigs[mode]) return;
  4245. elecMode = mode;
  4246. document.querySelectorAll('[data-elec-mode]').forEach(b => b.classList.toggle('active', b.dataset.elecMode === mode));
  4247. document.getElementById('elec-chart-title').textContent = elecModeConfigs[mode].title;
  4248. buildElecLegend();
  4249. drawCharts();
  4250. }
  4251. document.querySelectorAll('[data-elec-mode]').forEach(btn => {
  4252. btn.onclick = () => setElecMode(btn.dataset.elecMode);
  4253. });
  4254. function applyRunZoom(rk) {
  4255. activeRunZoom = rk;
  4256. const skipBoot = document.getElementById('chk-skip-boot').checked;
  4257. if (rk === 'ALL') {
  4258. zoomStart = 0; zoomEnd = n;
  4259. } else {
  4260. const rd = DATA.runs[rk];
  4261. if (rd) {
  4262. const win = (skipBoot && rd.core_window) ? rd.core_window : rd.full_window;
  4263. zoomStart = win[0]; zoomEnd = win[1];
  4264. }
  4265. }
  4266. buildZoomBar(); drawCharts();
  4267. }
  4268. document.getElementById('chk-skip-boot').onchange = () => {
  4269. if (activeRunZoom !== 'ALL') applyRunZoom(activeRunZoom);
  4270. };
  4271. document.getElementById('btn-reset-zoom').onclick = () => applyRunZoom('ALL');
  4272. window.zoomToSeqRange = (seqA, seqB, focusChart = 'all', pinSeq = null, pad = 15) => {
  4273. switchTab('tab-waves');
  4274. activeRunZoom = '';
  4275. zoomStart = Math.max(0, seqA - 1 - pad);
  4276. zoomEnd = Math.min(n, seqB + pad);
  4277. if (pinSeq != null) pinnedIdx = Math.max(0, Math.min(n - 1, pinSeq - 1));
  4278. if (focusChart === 'elec_volt') setElecMode('volt');
  4279. else if (focusChart === 'elec_lat') setElecMode('lat');
  4280. else if (focusChart === 'elec_curr') setElecMode('curr');
  4281. updatePinBar();
  4282. buildZoomBar();
  4283. requestAnimationFrame(() => drawCharts());
  4284. };
  4285. window.jumpToRawRange = (runKey = '', phase = '', seqMin = '', seqMax = '', preset = 'all') => {
  4286. document.getElementById('raw-run').value = runKey;
  4287. document.getElementById('raw-phase').value = phase;
  4288. document.getElementById('raw-seq-min').value = seqMin;
  4289. document.getElementById('raw-seq-max').value = seqMax;
  4290. document.getElementById('raw-preset').value = preset;
  4291. document.getElementById('raw-cust-col').value = '';
  4292. document.getElementById('raw-cust-val').value = '';
  4293. rawPage = 1;
  4294. switchTab('tab-raw');
  4295. applyRawFilter();
  4296. };
  4297. function updatePinBar() {
  4298. const txt = document.getElementById('pin-text');
  4299. const act = document.getElementById('pin-actions');
  4300. if (pinnedIdx == null || pinnedIdx < 0 || pinnedIdx >= n) {
  4301. txt.textContent = '提示:在任意曲线图上单击可固定某 1 秒采样点,核对该秒全 21 路传感器或跳转明细表。';
  4302. act.style.display = 'none';
  4303. return;
  4304. }
  4305. const i = pinnedIdx;
  4306. const rk = ser.run_names[cols.rk[i]], ph = ser.phase_names[cols.ph[i]];
  4307. txt.innerHTML = `已固定 <b>#${cols.seq[i]}</b> (${esc(cols.ts[i])} · ${cols.t[i]}s) · <b>${esc(rk)}</b> / ${esc(ph)} | ` +
  4308. `CPU0_A=<b>${cols.DIMM_CPU0_A_Temp?.[i] ?? 'null'}°C</b> CPU1_A=<b>${cols.DIMM_CPU1_A_Temp?.[i] ?? 'null'}°C</b> | ` +
  4309. `DDR0=<b>${cols.DDR0_Power?.[i] ?? '-'}W</b> (${cols.DDR0_Curr?.[i] ?? '-'}A @ ${cols.P12V_DDR0?.[i] ?? '-'}V) | PSU0=<b>${cols.PSU0_PIn?.[i] ?? '-'}W</b>`;
  4310. act.style.display = 'inline-flex';
  4311. }
  4312. document.getElementById('btn-pin-clear').onclick = () => { pinnedIdx = null; updatePinBar(); drawCharts(); };
  4313. document.getElementById('btn-pin-raw').onclick = () => {
  4314. if (pinnedIdx == null) return;
  4315. const sq = cols.seq[pinnedIdx];
  4316. window.jumpToRawRange('', '', Math.max(1, sq - 5), Math.min(n, sq + 5), 'all');
  4317. };
  4318. function renderKpis() {
  4319. const ov = DATA.overall_sensors, dKeys = DATA.meta.dimm_keys;
  4320. const dMin = Math.min(...dKeys.map(k => (ov[k] || {}).min ?? 999));
  4321. const dMax = Math.max(...dKeys.map(k => (ov[k] || {}).max ?? -999));
  4322. const runCnt = Object.values(DATA.runs).filter(r => r.active_rows > 0).length;
  4323. const lat = DATA.meta.poll_latency_ms;
  4324. const p12 = ov.P12V_DDR0 || {};
  4325. document.getElementById('kpi-grid').innerHTML = `
  4326. <div class="kpi-card"><div class="kpi-label">总样本 / 时长</div><div class="kpi-val">${n.toLocaleString()} 行 (${DATA.meta.total_duration_hms})</div><div class="kpi-sub">轮询耗时 min=${lat?.min ?? '-'} / max=${lat?.max ?? '-'}ms · ${phaseSegs.length} 个连续阶段</div></div>
  4327. <div class="kpi-card"><div class="kpi-label">无温控单算法矩阵</div><div class="kpi-val">${runCnt} 项单算法</div><div class="kpi-sub">MT Test 6 (384T) + 6 项 BIOS AMT CPGC</div></div>
  4328. <div class="kpi-card"><div class="kpi-label">5 路 DIMM 独立温区 (无均值)</div><div class="kpi-val">${dMin}~${dMax}°C</div><div class="kpi-sub">最热 CPU0_A ${ov.DIMM_CPU0_A_Temp?.max ?? '-'}°C · 1Hz SPD 0.25°C</div></div>
  4329. <div class="kpi-card"><div class="kpi-label">供电与整机边界</div><div class="kpi-val" style="font-size:15.5px">DDR0 ${ov.DDR0_Power?.max ?? '-'}W / PSU0 ${ov.PSU0_PIn?.max ?? '-'}W</div><div class="kpi-sub">DDR2 max=${ov.DDR2_Power?.max ?? '-'}W · P12V_DDR0=${p12.min ?? '-'}~${p12.max ?? '-'}V</div></div>
  4330. <div class="kpi-card"><div class="kpi-label">微事件 &amp; 异常切换</div><div class="kpi-val">${microEvents.length} 项自动检出</div><div class="kpi-sub"><a href="#" id="kpi-me-link" style="color:var(--accent);text-decoration:none">查看 DXE 尖峰 / 12V压降 / SPD空窗 / R-VRT脉动 →</a></div></div>
  4331. `;
  4332. const link = document.getElementById('kpi-me-link');
  4333. if (link) link.onclick = e => { e.preventDefault(); switchTab('tab-raw'); };
  4334. }
  4335. function buildZoomBar() {
  4336. const bar = document.getElementById('zoom-bar'); bar.innerHTML = '';
  4337. const mk = (lbl, rk) => {
  4338. const btn = document.createElement('button'); btn.type = 'button'; btn.textContent = lbl;
  4339. if (activeRunZoom === rk) btn.classList.add('active');
  4340. btn.onclick = () => applyRunZoom(rk);
  4341. bar.appendChild(btn);
  4342. };
  4343. mk(`全过程 (${n}s)`, 'ALL');
  4344. Object.keys(DATA.runs).forEach(rk => {
  4345. if (rk === '00_init') return;
  4346. mk(rk, rk);
  4347. });
  4348. const mp = document.getElementById('me-pills'); mp.innerHTML = '<span class="sub-note">微事件快捷缩放:</span>';
  4349. microEvents.slice(0, 10).forEach(ev => {
  4350. const b = document.createElement('button'); b.type = 'button'; b.className = 'btn-xs';
  4351. b.textContent = `${ev.id}: ${ev.title.length > 34 ? ev.title.slice(0, 34) + '…' : ev.title}`;
  4352. b.title = ev.detail;
  4353. b.onclick = () => window.zoomToSeqRange(ev.seq_start, ev.seq_end, ev.focus_chart, ev.seq_start, ev.pad_s);
  4354. mp.appendChild(b);
  4355. });
  4356. }
  4357. function makeLegend(id, list, set) {
  4358. const el = document.getElementById(id); if (!el) return;
  4359. el.innerHTML = '';
  4360. list.forEach(item => {
  4361. const sp = document.createElement('span');
  4362. sp.className = 'legend-item' + (set.has(item.key) ? '' : ' off');
  4363. sp.innerHTML = `<span class="swatch" style="background:${item.color}"></span>${esc(item.label)}`;
  4364. sp.onclick = () => {
  4365. if (set.has(item.key)) set.delete(item.key); else set.add(item.key);
  4366. sp.classList.toggle('off'); drawCharts();
  4367. };
  4368. el.appendChild(sp);
  4369. });
  4370. }
  4371. function buildElecLegend() { makeLegend('legend-elec', elecModeConfigs[elecMode].series, enabledElec); }
  4372. function buildLegends() {
  4373. makeLegend('legend-temp', tempSeries, enabledTemp);
  4374. makeLegend('legend-mpwr', memPwrSeries, enabledMemPwr);
  4375. makeLegend('legend-spwr', sysPwrSeries, enabledSysPwr);
  4376. buildElecLegend();
  4377. }
  4378. document.querySelectorAll('[data-tmp-preset]').forEach(btn => {
  4379. btn.onclick = () => {
  4380. const p = btn.dataset.tmpPreset; enabledTemp.clear();
  4381. tempSeries.forEach(s => {
  4382. if (p === 'all' || (p === 'dimms' && (s.grp === 'cpu0' || s.grp === 'dimms')) || (p === 'cpu0' && s.grp === 'cpu0') || (p === 'edge' && (s.key === 'DIMM_CPU0_A_Temp' || s.key === 'DIMM_CPU1_A_Temp'))) {
  4383. enabledTemp.add(s.key);
  4384. }
  4385. });
  4386. makeLegend('legend-temp', tempSeries, enabledTemp); drawCharts();
  4387. };
  4388. });
  4389. document.querySelectorAll('[data-mpwr-preset]').forEach(btn => {
  4390. btn.onclick = () => {
  4391. const p = btn.dataset.mpwrPreset; enabledMemPwr.clear();
  4392. memPwrSeries.forEach(s => {
  4393. if (p === 'all' || (p === 'vr' && (s.key === 'DDR0_Power' || s.key === 'DDR2_Power')) || (p === 'peci' && (s.key === 'DDR0_Power' || s.key === 'DDR2_Power' || s.grp === 'peci'))) {
  4394. enabledMemPwr.add(s.key);
  4395. }
  4396. });
  4397. makeLegend('legend-mpwr', memPwrSeries, enabledMemPwr); drawCharts();
  4398. };
  4399. });
  4400. document.querySelectorAll('[data-spwr-preset]').forEach(btn => {
  4401. btn.onclick = () => {
  4402. const p = btn.dataset.spwrPreset; enabledSysPwr.clear();
  4403. sysPwrSeries.forEach(s => { if (p === 'all' || s.grp === p) enabledSysPwr.add(s.key); });
  4404. makeLegend('legend-spwr', sysPwrSeries, enabledSysPwr); drawCharts();
  4405. };
  4406. });
  4407. function setupCanvas(canvas) {
  4408. const rect = canvas.parentElement.getBoundingClientRect();
  4409. const dpr = window.devicePixelRatio || 1;
  4410. const w = Math.max(320, Math.floor(rect.width)), h = Math.max(150, Math.floor(rect.height));
  4411. canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);
  4412. canvas.style.width = w + 'px'; canvas.style.height = h + 'px';
  4413. const ctx = canvas.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  4414. return { ctx, w, h };
  4415. }
  4416. function phaseStyle(ph) {
  4417. if (ph === 'pre_baseline') return { bg: 'rgba(56,189,248,0.09)', lbl: 'base' };
  4418. if (ph === 'boot_to_amt') return { bg: 'rgba(245,158,11,0.07)', lbl: 'boot' };
  4419. if (ph === 'init') return { bg: 'rgba(245,158,11,0.10)', lbl: 'init' };
  4420. if (ph.startsWith('loop_')) {
  4421. const lnum = parseInt(ph.slice(5), 10) || 1;
  4422. return { bg: (lnum % 2 === 1) ? 'rgba(34,197,94,0.12)' : 'rgba(16,185,129,0.20)', lbl: 'L' + lnum };
  4423. }
  4424. if (ph === 'cooldown') return { bg: 'rgba(168,85,247,0.09)', lbl: 'cool' };
  4425. return { bg: 'rgba(148,163,184,0.06)', lbl: '' };
  4426. }
  4427. function drawLineChart(canvasId, seriesList, enabledSet, opts = {}) {
  4428. const canvas = document.getElementById(canvasId); if (!canvas) return;
  4429. const { ctx, w, h } = setupCanvas(canvas);
  4430. const sIdx = Math.max(0, zoomStart), eIdx = Math.min(n, zoomEnd), span = Math.max(1, eIdx - sIdx);
  4431. const decimals = opts.decimals ?? 1;
  4432. const pad = { l: 58, r: 24, t: 18, b: 24 }, pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
  4433. const cs = getComputedStyle(document.body), borderCol = cs.getPropertyValue('--border').trim(), mutedCol = cs.getPropertyValue('--muted').trim();
  4434. let yMin = Infinity, yMax = -Infinity;
  4435. seriesList.forEach(s => {
  4436. if (!enabledSet.has(s.key)) return;
  4437. const arr = cols[s.key]; if (!arr) return;
  4438. for (let i = sIdx; i < eIdx; i++) {
  4439. const v = arr[i];
  4440. if (v !== null && v !== undefined) {
  4441. if (v < yMin) yMin = v;
  4442. if (v > yMax) yMax = v;
  4443. }
  4444. }
  4445. });
  4446. if (!isFinite(yMin)) { yMin = 0; yMax = 100; }
  4447. const rawRange = yMax - yMin;
  4448. const minSpan = decimals >= 3 ? 0.02 : (decimals === 2 ? 0.2 : 2.0);
  4449. const effSpan = Math.max(minSpan, rawRange);
  4450. const yPad = effSpan * 0.12;
  4451. yMin = yMin - yPad; yMax = yMax + yPad;
  4452. if (decimals <= 1 && yMin > 0 && rawRange < 5 && opts.zeroBase) yMin = 0;
  4453. const xAt = i => pad.l + ((i - sIdx) / Math.max(1, span - 1)) * pw;
  4454. const xBound = i => pad.l + ((i - sIdx) / Math.max(1, span)) * pw;
  4455. const yAt = v => pad.t + ph - ((v - yMin) / Math.max(1e-9, yMax - yMin)) * ph;
  4456. // Phase shading & non-overlapping labels
  4457. let prevRk = null;
  4458. ctx.font = '10px monospace';
  4459. for (const seg of phaseSegs) {
  4460. if (seg.e <= sIdx || seg.s >= eIdx) continue;
  4461. const a = Math.max(sIdx, seg.s), b = Math.min(eIdx, seg.e);
  4462. const x1 = xBound(a), x2 = xBound(b), segW = Math.max(1, x2 - x1);
  4463. const st = phaseStyle(seg.ph);
  4464. ctx.fillStyle = st.bg;
  4465. ctx.fillRect(x1, pad.t, segW, ph);
  4466. if (prevRk !== null && prevRk !== seg.rk) {
  4467. ctx.save(); ctx.strokeStyle = 'rgba(148,163,184,0.35)'; ctx.setLineDash([3, 3]);
  4468. ctx.beginPath(); ctx.moveTo(x1, pad.t); ctx.lineTo(x1, pad.t + ph); ctx.stroke(); ctx.restore();
  4469. }
  4470. if (segW >= 26 && st.lbl && opts.showPhaseLabels) {
  4471. ctx.fillStyle = mutedCol; ctx.textAlign = 'center';
  4472. ctx.fillText(st.lbl, x1 + segW / 2, pad.t - 4);
  4473. }
  4474. prevRk = seg.rk;
  4475. }
  4476. // Grid lines & window badge
  4477. ctx.strokeStyle = borderCol; ctx.font = '11px sans-serif'; ctx.fillStyle = mutedCol;
  4478. for (let g = 0; g <= 4; g++) {
  4479. const yy = pad.t + ph - (g / 4) * ph;
  4480. ctx.beginPath(); ctx.moveTo(pad.l, yy); ctx.lineTo(pad.l + pw, yy); ctx.stroke();
  4481. ctx.textAlign = 'right';
  4482. ctx.fillText((yMin + (g / 4) * (yMax - yMin)).toFixed(decimals), pad.l - 6, yy + 4);
  4483. }
  4484. for (let t = 0; t <= 6; t++) {
  4485. const idx = Math.min(n - 1, sIdx + Math.floor((t / 6) * (span - 1)));
  4486. ctx.textAlign = t === 0 ? 'left' : (t === 6 ? 'right' : 'center');
  4487. ctx.fillText(`${cols.ts[idx] || ''} (#${cols.seq[idx]})`, pad.l + (t / 6) * pw, h - 6);
  4488. }
  4489. if (opts.showPhaseLabels) {
  4490. const wb = document.getElementById('win-badge');
  4491. if (wb) wb.textContent = `窗口: #${cols.seq[sIdx]}..#${cols.seq[eIdx - 1]} (${span}s)`;
  4492. }
  4493. // Plot all points without skipping 1s transients
  4494. const stride = span > 15000 ? Math.floor(span / 8000) : 1;
  4495. seriesList.forEach(s => {
  4496. if (!enabledSet.has(s.key)) return;
  4497. const arr = cols[s.key]; if (!arr) return;
  4498. ctx.save(); ctx.strokeStyle = s.color; ctx.fillStyle = s.color; ctx.lineWidth = s.width;
  4499. if (s.dash) ctx.setLineDash(s.dash);
  4500. ctx.beginPath();
  4501. let started = false, runPts = 0, lastX = 0, lastY = 0;
  4502. for (let i = sIdx; i < eIdx; i += stride) {
  4503. const v = arr[i];
  4504. if (v === null || v === undefined) {
  4505. if (runPts === 1) ctx.fillRect(lastX - 1.5, lastY - 1.5, 3, 3);
  4506. started = false; runPts = 0; continue;
  4507. }
  4508. const x = xAt(i), y = yAt(v);
  4509. if (!started) { ctx.moveTo(x, y); started = true; runPts = 1; }
  4510. else { ctx.lineTo(x, y); runPts++; }
  4511. lastX = x; lastY = y;
  4512. }
  4513. if (runPts === 1) ctx.fillRect(lastX - 1.5, lastY - 1.5, 3, 3);
  4514. ctx.stroke(); ctx.restore();
  4515. });
  4516. if (dragStartIdx !== null && dragCurIdx !== null && dragStartIdx !== dragCurIdx) {
  4517. const x1 = xAt(Math.max(sIdx, Math.min(dragStartIdx, dragCurIdx)));
  4518. const x2 = xAt(Math.min(eIdx - 1, Math.max(dragStartIdx, dragCurIdx)));
  4519. ctx.fillStyle = 'rgba(56,189,248,0.18)'; ctx.fillRect(x1, pad.t, Math.max(2, x2 - x1), ph);
  4520. }
  4521. if (pinnedIdx !== null && pinnedIdx >= sIdx && pinnedIdx < eIdx) {
  4522. const px = xAt(pinnedIdx);
  4523. ctx.save(); ctx.strokeStyle = '#f59e0b'; ctx.lineWidth = 1.6; ctx.setLineDash([4, 3]);
  4524. ctx.beginPath(); ctx.moveTo(px, pad.t); ctx.lineTo(px, pad.t + ph); ctx.stroke(); ctx.restore();
  4525. }
  4526. if (hoverIdx !== null && hoverIdx >= sIdx && hoverIdx < eIdx) {
  4527. const hx = xAt(hoverIdx);
  4528. ctx.strokeStyle = 'rgba(255,255,255,0.55)'; ctx.lineWidth = 1;
  4529. ctx.beginPath(); ctx.moveTo(hx, pad.t); ctx.lineTo(hx, pad.t + ph); ctx.stroke();
  4530. }
  4531. }
  4532. function attachHover(canvasId) {
  4533. const canvas = document.getElementById(canvasId), tip = document.getElementById('tooltip');
  4534. const idxFromEvent = ev => {
  4535. const rect = canvas.getBoundingClientRect(), x = ev.clientX - rect.left;
  4536. const sIdx = Math.max(0, zoomStart), eIdx = Math.min(n, zoomEnd);
  4537. const ratio = Math.max(0, Math.min(1, (x - 58) / Math.max(1, rect.width - 82)));
  4538. return Math.min(n - 1, sIdx + Math.round(ratio * Math.max(0, eIdx - sIdx - 1)));
  4539. };
  4540. canvas.onmousedown = ev => {
  4541. dragStartClientX = ev.clientX;
  4542. dragStartIdx = idxFromEvent(ev);
  4543. dragCurIdx = dragStartIdx;
  4544. };
  4545. canvas.onmouseup = ev => {
  4546. const pxMoved = Math.abs(ev.clientX - dragStartClientX);
  4547. if (pxMoved < 6 && dragStartIdx !== null) {
  4548. pinnedIdx = dragStartIdx;
  4549. updatePinBar();
  4550. } else if (dragStartIdx !== null && dragCurIdx !== null && Math.abs(dragCurIdx - dragStartIdx) >= 3) {
  4551. activeRunZoom = '';
  4552. zoomStart = Math.min(dragStartIdx, dragCurIdx);
  4553. zoomEnd = Math.max(dragStartIdx, dragCurIdx) + 1;
  4554. buildZoomBar();
  4555. }
  4556. dragStartIdx = null; dragCurIdx = null; drawCharts();
  4557. };
  4558. canvas.ondblclick = () => applyRunZoom('ALL');
  4559. canvas.onmousemove = ev => {
  4560. hoverIdx = idxFromEvent(ev); if (dragStartIdx !== null) dragCurIdx = hoverIdx; drawCharts();
  4561. const i = hoverIdx, rk = ser.run_names[cols.rk[i]], ph = ser.phase_names[cols.ph[i]];
  4562. const dStr = (k, d=2) => {
  4563. const v = cols[k]?.[i], p = i > 0 ? cols[k]?.[i - 1] : null;
  4564. if (v == null) return 'null';
  4565. if (p != null && Math.abs(v - p) >= (k.includes('Temp') ? 0.5 : (k.startsWith('P12V') ? 0.02 : 3.0))) {
  4566. const df = +(v - p).toFixed(d);
  4567. return `${v}(${df > 0 ? '+' : ''}${df})`;
  4568. }
  4569. return String(v);
  4570. };
  4571. tip.style.display = 'block';
  4572. tip.style.left = Math.min(window.innerWidth - 530, ev.clientX + 14) + 'px';
  4573. tip.style.top = Math.min(window.innerHeight - 280, ev.clientY + 14) + 'px';
  4574. tip.innerHTML = `
  4575. <div><b>${esc(rk)}</b> · <b>#${cols.seq[i]}</b> · ${esc(cols.ts[i])} (${cols.t[i]}s) · <span class="mono">${esc(ph)}</span> · lat=${cols.lat[i] ?? '-'}ms</div>
  4576. <div class="mono">DIMM CPU0 A/B/C/D: <b>${dStr('DIMM_CPU0_A_Temp')} / ${dStr('DIMM_CPU0_B_Temp')} / ${dStr('DIMM_CPU0_C_Temp')} / ${dStr('DIMM_CPU0_D_Temp')} °C</b></div>
  4577. <div class="mono">DIMM CPU1_A: <b>${dStr('DIMM_CPU1_A_Temp')} °C</b> · CPU0/1: ${cols.CPU0_Temp?.[i] ?? '-'} / ${cols.CPU1_Temp?.[i] ?? '-'} °C</div>
  4578. <div class="mono">DDR0/2: <b>${dStr('DDR0_Power')} / ${dStr('DDR2_Power')} W</b> · 电流: ${cols.DDR0_Curr?.[i] ?? '-'}/${cols.DDR2_Curr?.[i] ?? '-'}A · 12V: <b>${cols.P12V_DDR0?.[i] ?? '-'}/${cols.P12V_DDR2?.[i] ?? '-'}V</b></div>
  4579. <div class="mono">PVCCD0/1: ${cols.PVCCD_CPU0_Input_Power?.[i] ?? '-'}/${cols.PVCCD_CPU1_Input_Power?.[i] ?? '-'}W · PECI DIMM0/1: ${cols.Dimm_Power_CPU0?.[i] ?? 'null'}/${cols.Dimm_Power_CPU1?.[i] ?? 'null'}W</div>
  4580. <div class="mono">PECI CPU0/1: ${cols.CPU0_Power_Avg?.[i] ?? 'null'}/${cols.CPU1_Power_Avg?.[i] ?? 'null'}W · PSU0: <b>${cols.PSU0_PIn?.[i] ?? '-'}/${cols.PSU0_POut?.[i] ?? '-'}W</b></div>
  4581. `;
  4582. };
  4583. canvas.onmouseleave = () => { hoverIdx = null; dragStartIdx = null; dragCurIdx = null; tip.style.display = 'none'; drawCharts(); };
  4584. }
  4585. function drawCharts() {
  4586. drawLineChart('chart-temp', tempSeries, enabledTemp, { decimals: 1, showPhaseLabels: true });
  4587. drawLineChart('chart-mpwr', memPwrSeries, enabledMemPwr, { decimals: 1, showPhaseLabels: false });
  4588. drawLineChart('chart-spwr', sysPwrSeries, enabledSysPwr, { decimals: 0, showPhaseLabels: false });
  4589. const em = elecModeConfigs[elecMode];
  4590. drawLineChart('chart-elec', em.series, enabledElec, { decimals: em.decimals, showPhaseLabels: false });
  4591. }
  4592. function drawBars() {
  4593. const canvas = document.getElementById('chart-bars'); if (!canvas) return;
  4594. const { ctx, w, h } = setupCanvas(canvas);
  4595. const metric = document.getElementById('bar-metric-select').value;
  4596. const runList = Object.values(DATA.runs).filter(r => r.active_rows > 0);
  4597. const dKeys = DATA.meta.dimm_keys, colors = ['#ef4444', '#f59e0b', '#22c55e', '#38bdf8', '#a855f7'];
  4598. const pad = { l: 50, r: 18, t: 28, b: 56 }, pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
  4599. const cs = getComputedStyle(document.body), borderCol = cs.getPropertyValue('--border').trim(), mutedCol = cs.getPropertyValue('--muted').trim();
  4600. let maxV = 1, legLabels = [];
  4601. const bars = runList.map(r => {
  4602. let vals = [];
  4603. if (metric === 'dimm_delta') {
  4604. legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
  4605. vals = dKeys.map(k => Math.max(0, (r.per_dimm_thermal_response[k]?.active_max_c ?? 0) - (r.per_dimm_thermal_response[k]?.active_start_c ?? 0)));
  4606. } else if (metric === 'dimm_max') {
  4607. legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
  4608. vals = dKeys.map(k => r.per_dimm_thermal_response[k]?.active_max_c ?? 0);
  4609. } else if (metric === 'dimm_rate') {
  4610. legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
  4611. vals = dKeys.map(k => Math.max(0, r.per_dimm_thermal_response[k]?.heating_rate_c_per_min ?? 0));
  4612. } else if (metric === 'dimm_early') {
  4613. legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
  4614. vals = dKeys.map(k => Math.max(0, r.per_dimm_thermal_response[k]?.early_slope_c_per_min ?? 0));
  4615. } else if (metric === 'tau_cool') {
  4616. legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
  4617. vals = dKeys.map(k => r.per_dimm_thermal_response[k]?.tau_cool_s ?? 0);
  4618. } else if (metric === 'ddr_max') {
  4619. legLabels = ['DDR0(W)', 'DDR2(W)', 'PVCCD0(W)', 'PVCCD1(W)'];
  4620. vals = ['DDR0_Power', 'DDR2_Power', 'PVCCD_CPU0_Input_Power', 'PVCCD_CPU1_Input_Power'].map(k => (r.active_sensors[k] || {}).max ?? 0);
  4621. } else {
  4622. legLabels = ['PSU0_PIn(W)', 'CPU0(W)', 'CPU1(W)'];
  4623. vals = ['PSU0_PIn', 'CPU0_Power_Avg', 'CPU1_Power_Avg'].map(k => (r.active_sensors[k] || {}).max ?? 0);
  4624. }
  4625. maxV = Math.max(maxV, ...vals);
  4626. return { label: r.short_name || r.run_key, run: r, vals };
  4627. });
  4628. maxV = Math.ceil(maxV * 1.15);
  4629. ctx.strokeStyle = borderCol; ctx.font = '11px sans-serif'; ctx.fillStyle = mutedCol;
  4630. for (let g = 0; g <= 4; g++) {
  4631. const yy = pad.t + ph - (g / 4) * ph;
  4632. ctx.beginPath(); ctx.moveTo(pad.l, yy); ctx.lineTo(pad.l + pw, yy); ctx.stroke();
  4633. ctx.textAlign = 'right'; ctx.fillText((maxV * g / 4).toFixed(1), pad.l - 6, yy + 4);
  4634. }
  4635. const slotW = pw / Math.max(1, bars.length); barCache = [];
  4636. bars.forEach((b, idx) => {
  4637. const k = b.vals.length, bw = Math.max(4, Math.min(18, (slotW * 0.78) / k));
  4638. const sx = pad.l + idx * slotW + (slotW - bw * k) / 2;
  4639. b.vals.forEach((v, j) => {
  4640. const hh = (v / maxV) * ph; ctx.fillStyle = colors[j % colors.length];
  4641. ctx.fillRect(sx + j * bw, pad.t + ph - hh, Math.max(2, bw - 1), hh);
  4642. });
  4643. ctx.fillStyle = mutedCol; ctx.textAlign = 'center';
  4644. ctx.fillText(b.label, pad.l + idx * slotW + slotW / 2, pad.t + ph + 16);
  4645. barCache.push({ x1: pad.l + idx * slotW, x2: pad.l + (idx + 1) * slotW, run: b.run, vals: b.vals, legLabels });
  4646. });
  4647. ctx.textAlign = 'left'; let lx = pad.l;
  4648. legLabels.forEach((lbl, j) => {
  4649. ctx.fillStyle = colors[j % colors.length]; ctx.fillRect(lx, 6, 10, 10);
  4650. ctx.fillStyle = mutedCol; ctx.fillText(lbl, lx + 14, 15); lx += 14 + lbl.length * 7 + 16;
  4651. });
  4652. const tip = document.getElementById('tooltip');
  4653. canvas.onmousemove = ev => {
  4654. const rect = canvas.getBoundingClientRect(), x = ev.clientX - rect.left;
  4655. const hit = barCache.find(b => x >= b.x1 && x <= b.x2);
  4656. if (!hit) { tip.style.display = 'none'; return; }
  4657. tip.style.display = 'block';
  4658. tip.style.left = Math.min(window.innerWidth - 420, ev.clientX + 14) + 'px';
  4659. tip.style.top = Math.min(window.innerHeight - 220, ev.clientY + 14) + 'px';
  4660. tip.innerHTML = `<div><b>${esc(hit.run.run_key)}</b> (${esc(hit.run.algo_name)})</div>` +
  4661. hit.legLabels.map((lbl, j) => `<div>${esc(lbl)}: <b>${hit.vals[j].toFixed(2)}</b></div>`).join('');
  4662. };
  4663. canvas.onmouseleave = () => { tip.style.display = 'none'; };
  4664. }
  4665. function renderTables() {
  4666. const dKeys = DATA.meta.dimm_keys;
  4667. const runList = Object.values(DATA.runs).filter(r => r.active_rows > 0);
  4668. let h1 = `<table><thead><tr><th>算法 Run</th><th>引擎 / 轮数 / 时长</th>${dKeys.map(k => `<th>${esc(k.replace('_Temp',''))} (基线→峰 / +Δ / 全/初斜率)</th>`).join('')}<th>最大5条极差 / CPU0簇内差</th></tr></thead><tbody>`;
  4669. runList.forEach(r => {
  4670. h1 += `<tr><td><b>${esc(r.run_key)}</b><br><span style="color:var(--muted)">${esc(r.algo_name)}</span></td><td class="mono">${esc(r.engine)} · ${r.loop_total}L · ${r.active_duration_s}s</td>` +
  4671. dKeys.map(k => {
  4672. const d = r.per_dimm_thermal_response[k];
  4673. if (!d || d.active_max_c == null) return '<td>-</td>';
  4674. const base = d.baseline_end_c ?? d.active_start_c;
  4675. const es = d.early_slope_c_per_min != null ? ` / 初${d.early_slope_c_per_min}` : '';
  4676. return `<td class="mono">${base}→<b>${d.active_max_c}°C</b><br><span style="color:var(--muted)">+${(d.active_max_c - d.active_start_c).toFixed(2)} (${d.heating_rate_c_per_min ?? '-'}${es}°C/m)</span></td>`;
  4677. }).join('') +
  4678. `<td class="mono"><b>${r.max_all_dimm_spread_c ?? '-'}°C</b><br><span style="color:var(--muted)">簇内 ${r.max_cpu0_cluster_spread_c ?? '-'}°C</span></td></tr>`;
  4679. });
  4680. document.getElementById('algo-dimm-table').innerHTML = h1 + '</tbody></table>';
  4681. let h2 = `<table><thead><tr><th>算法 Run</th><th>DDR0_Power</th><th>DDR2_Power</th><th>DDR0/2 电流(A)</th><th>P12V DDR0/2(V)</th><th>PVCCD0 / PVCCD1</th><th>PECI DIMM0/1</th><th>CPU0/1 Power</th><th>CPU0/1 Temp</th><th>PSU0 PIn / POut</th></tr></thead><tbody>`;
  4682. runList.forEach(r => {
  4683. const a = r.active_sensors;
  4684. h2 += `<tr><td><b>${esc(r.run_key)}</b></td>
  4685. <td class="mono">${esc(fmtMM(a.DDR0_Power,'W'))}</td>
  4686. <td class="mono">${esc(fmtMM(a.DDR2_Power,'W'))}</td>
  4687. <td class="mono">${esc(fmtMM(a.DDR0_Curr,'A'))} / ${esc(fmtMM(a.DDR2_Curr,'A'))}</td>
  4688. <td class="mono">${esc(fmtMM(a.P12V_DDR0,'V'))} / ${esc(fmtMM(a.P12V_DDR2,'V'))}</td>
  4689. <td class="mono">${esc(fmtMM(a.PVCCD_CPU0_Input_Power,'W'))} / ${esc(fmtMM(a.PVCCD_CPU1_Input_Power,'W'))}</td>
  4690. <td class="mono">${esc(fmtMM(a.Dimm_Power_CPU0,'W'))} / ${esc(fmtMM(a.Dimm_Power_CPU1,'W'))}</td>
  4691. <td class="mono">${esc(fmtMM(a.CPU0_Power_Avg,'W'))} / ${esc(fmtMM(a.CPU1_Power_Avg,'W'))}</td>
  4692. <td class="mono">${esc(fmtMM(a.CPU0_Temp,'°C'))} / ${esc(fmtMM(a.CPU1_Temp,'°C'))}</td>
  4693. <td class="mono">${esc(fmtMM(a.PSU0_PIn,'W'))} / ${esc(fmtMM(a.PSU0_POut,'W'))}</td></tr>`;
  4694. });
  4695. document.getElementById('algo-pwr-table').innerHTML = h2 + '</tbody></table>';
  4696. let h3 = `<table><thead><tr><th>算法 Run</th><th>冷却有效 / SPD空窗 (首读延迟)</th>${dKeys.map(k => `<th>${esc(k.replace('_Temp',''))} (表观起→末 / 距峰值 / τ_cool)</th>`).join('')}</tr></thead><tbody>`;
  4697. runList.forEach(r => {
  4698. const d0 = r.per_dimm_thermal_response[dKeys[0]] || {};
  4699. const delayTxt = (d0.cooldown_first_valid_delay_s != null && d0.cooldown_first_valid_delay_s > 0) ? `+${d0.cooldown_first_valid_delay_s}s` : '0s';
  4700. h3 += `<tr><td><b>${esc(r.run_key)}</b></td><td class="mono">${d0.cooldown_valid_rows ?? '-'}s / <span style="color:var(--muted)">${d0.cooldown_null_rows ?? '-'}s null</span> (延迟 ${delayTxt})</td>` +
  4701. dKeys.map(k => {
  4702. const d = r.per_dimm_thermal_response[k];
  4703. if (!d || d.cooldown_start_c == null) return '<td>-</td>';
  4704. const delta = +(d.cooldown_end_c - d.cooldown_start_c).toFixed(2);
  4705. const sign = delta > 0 ? '+' : '';
  4706. const pkDrop = d.cooldown_total_drop_from_peak_c != null ? ` · 较峰-${d.cooldown_total_drop_from_peak_c}` : '';
  4707. const tau = d.tau_cool_s != null ? ` · τ=${d.tau_cool_s}s` : '';
  4708. return `<td class="mono">${d.cooldown_start_c}→${d.cooldown_end_c}°C (${sign}${delta})<br><span style="color:var(--muted)">${pkDrop}${tau}</span></td>`;
  4709. }).join('') + `</tr>`;
  4710. });
  4711. document.getElementById('algo-cool-table').innerHTML = h3 + '</tbody></table>';
  4712. // Gallery of embedded publication PNGs
  4713. const gal = document.getElementById('fig-gallery');
  4714. const figNote = document.getElementById('fig-count-note');
  4715. if (!FIGS.length) {
  4716. figNote.textContent = '当前输入目录未包含 fig_01..fig_09.png 静态曲线截图。';
  4717. gal.innerHTML = '<div class="sub-note">请使用 Tab 1 交互曲线或传入原始 scratch/thermal_study 目录生成内嵌图集。</div>';
  4718. } else {
  4719. figNote.textContent = `已离线 Base64 内嵌 ${FIGS.length} 张高清曲线截图`;
  4720. gal.innerHTML = FIGS.map((fg, idx) => `
  4721. <div class="fig-card">
  4722. <div class="fig-hdr">
  4723. <span>${esc(fg.title)}</span>
  4724. <span class="controls">
  4725. <a class="btn-xs" href="${fg.data_uri}" download="${esc(fg.filename)}" style="text-decoration:none;background:var(--bg-card);border:1px solid var(--border);border-radius:5px;color:var(--text)">下载 PNG</a>
  4726. <button type="button" class="btn-xs" onclick="window.__openFig(${idx})">放大</button>
  4727. </span>
  4728. </div>
  4729. <img src="${fg.data_uri}" alt="${esc(fg.title)}" onclick="window.__openFig(${idx})">
  4730. </div>
  4731. `).join('');
  4732. }
  4733. // Tab 3 filters
  4734. const pSel = document.getElementById('phase-run-filter');
  4735. Object.keys(DATA.runs).forEach(rk => {
  4736. const o = document.createElement('option'); o.value = rk; o.textContent = rk; pSel.appendChild(o);
  4737. });
  4738. pSel.onchange = renderPhaseRows;
  4739. document.getElementById('phase-grp-filter').onchange = renderPhaseRows;
  4740. document.getElementById('phase-col-preset').onchange = renderPhaseRows;
  4741. renderPhaseRows();
  4742. renderLoopEvents();
  4743. // Tab 4 micro-events & raw filter init
  4744. initRawExplorer();
  4745. // Tab 5 overall sensors + benchmark + conclusions
  4746. let ho = `<table><thead><tr><th>传感器 Key</th><th>位置说明</th><th>类别</th><th>有效样本</th><th>空值 (null)</th><th>最小值</th><th>最大值</th><th>起点</th><th>终点</th><th>全周期变化</th></tr></thead><tbody>`;
  4747. DATA.meta.sensors.forEach(s => {
  4748. const st = DATA.overall_sensors[s.key]; if (!st) return;
  4749. const u = s.unit;
  4750. const nulls = n - st.count;
  4751. ho += `<tr><td class="mono"><b>${esc(s.key)}</b></td><td>${esc(s.label)}</td><td class="mono">${esc(s.group)}</td>` +
  4752. `<td class="mono">${st.count}</td><td class="mono">${nulls}</td><td class="mono">${st.min}${u}</td><td class="mono">${st.max}${u}</td>` +
  4753. `<td class="mono">${st.start}${u}</td><td class="mono">${st.end}${u}</td><td class="mono">${st.delta >= 0 ? '+' : ''}${st.delta}${u}</td></tr>`;
  4754. });
  4755. document.getElementById('overall-sensors-table').innerHTML = ho + '</tbody></table>';
  4756. const bm = DATA.bmc_benchmark;
  4757. const bb = document.getElementById('bench-body');
  4758. if (!bm) {
  4759. bb.innerHTML = '<p class="sub-note">未在输入目录发现 bmc_benchmark_result.json。</p>';
  4760. } else {
  4761. const ipmiT = bm.ipmi_sdr_temp_latency_ms || {}, ipmiC = bm.ipmi_sdr_compact_latency_ms || {};
  4762. const lat = DATA.meta.poll_latency_ms || {};
  4763. bb.innerHTML = `
  4764. <div class="table-scroll" style="margin-bottom:12px"><table><thead><tr><th>采集方式</th><th>最小耗时</th><th>中位/典型耗时</th><th>最大耗时</th><th>发现/精度特征</th></tr></thead><tbody>
  4765. <tr><td><code>ipmitool -I lanplus sdr type Temperature</code></td><td class="mono">${ipmiT.min ?? '-'} ms</td><td class="mono">${ipmiT.median ?? '-'} ms</td><td class="mono">${ipmiT.max ?? '-'} ms</td><td>8-bit 线性截断 (0.40°C / 2W 台阶)</td></tr>
  4766. <tr><td><code>ipmitool -I lanplus sdr list</code> (紧凑表)</td><td class="mono">${ipmiC.min ?? '-'} ms</td><td class="mono">${ipmiC.median ?? '-'} ms</td><td class="mono">${ipmiC.max ?? '-'} ms</td><td>仅状态位,无精确浮点值</td></tr>
  4767. <tr><td><b>OpenBMC 持久 SSH + D-Bus GetManagedObjects</b></td><td class="mono">${lat.min ?? '-'} ms</td><td class="mono">${lat.start ?? '-'} / ${lat.end ?? '-'} ms</td><td class="mono">${lat.max ?? '-'} ms</td><td><span class="badge pass">132 路 D-Bus 对象</span> · SPD 0.25°C / PMBus 0.01W · 1.0 Hz 零丢帧</td></tr>
  4768. </tbody></table></div>
  4769. <p class="sub-note">D-Bus 服务列表 (${(bm.dbus_sensor_services || []).length}): <code>${esc((bm.dbus_sensor_services || []).join(', '))}</code> · 总传感器对象: <b>${bm.dbus_sensor_count ?? '-'}</b></p>
  4770. <details style="margin-top:8px"><summary style="cursor:pointer;font-size:13px">展开查看 IPMI SDR 原始快照与 D-Bus 传感器样本路径</summary>
  4771. <pre>${esc(bm.ipmi_sample_temp_sdr || '')}\n---\n${esc(bm.ipmi_sample_psu_sdr || '')}\n---\n${esc((bm.dbus_sensors_sample || []).join('\n'))}</pre>
  4772. </details>
  4773. `;
  4774. }
  4775. const mt = DATA.runs['01_MT_BlockMove64B'];
  4776. const cbox = document.getElementById('conclusions-box');
  4777. const ov = DATA.overall_sensors;
  4778. cbox.innerHTML = `
  4779. <ul>
  4780. <li><b>无温控裸机条子极热与功耗上限</b>:MT Test 6 (384核并行 BlockMove64B) 将 CPU0 簇推至 <code>${ov.DIMM_CPU0_A_Temp?.max ?? '-'}°C</code>(CPU0_A 单轮次内净升 <code>+${mt ? ((mt.per_dimm_thermal_response.DIMM_CPU0_A_Temp?.active_max_c ?? 0) - (mt.per_dimm_thermal_response.DIMM_CPU0_A_Temp?.active_start_c ?? 0)).toFixed(2) : '-'}°C</code>,初期斜率 <code>${mt?.per_dimm_thermal_response.DIMM_CPU0_A_Temp?.early_slope_c_per_min ?? '-'}°C/min</code>),<code>DDR0_Power</code> 达 <code>${ov.DDR0_Power?.max ?? '-'}W</code> / <code>${ov.DDR0_Curr?.max ?? '-'}A</code>,并在 12V 输入侧引起 <code>-40mV</code> IR 压降(<code>12.16V → 12.12V</code>)。</li>
  4781. <li><b>跨插槽极差显著</b>:MT6 仅压测 Socket 0(CPU1_A 停在 42°C),跨槽最大温差达 <code>${mt?.max_all_dimm_spread_c ?? '-'}°C</code>;BIOS CPGC 6 项单算法中,<code>05_AMT_A_HDS</code> 温升最大(CPU0_A <code>55.0°C</code> / CPU1_A <code>52.0°C</code>),而 <code>07_AMT_R_VRT</code> 呈 <code>7.6~29.86W</code> 高峰谷方波脉动。</li>
  4782. <li><b>解释了每一个看似"异常"的阶段数字</b>:AMT cooldown 表观起点有时低于主动期峰值约 2~3°C,系停载热重启回 UEFI Shell 导致前 <code>18~22s</code> SPD 离线(个别 Run 第 0 秒刚好抢到切换前最后一帧,随后 ~100s 处还有 ~10s 二次切回 OS 重连 PECI 的 SPD+PMBus 双离线窗口,合计 <code>28~32s</code> null);冷却第 ~4~6s 的 <code>30.5~30.9W</code> 脉冲为 BIOS DXE 内存重初始化瞬态。</li>
  4783. <li><b>PECI RAPL 与板载 PMBus 差异</b>:BIOS CPGC AMT 期间 PECI 遥测(<code>Dimm_Power_CPU0/1</code>、<code>CPU0/1_Power_Avg</code>)返回 <code>null</code>,必须依赖 <code>DDR0/DDR2 PMBus</code> 进行高精度功耗监控;UEFI MT6 下二者可交叉互校。</li>
  4784. </ul>
  4785. `;
  4786. }
  4787. window.__openFig = idx => {
  4788. const fg = FIGS[idx]; if (!fg) return;
  4789. document.getElementById('modal-title').textContent = fg.title;
  4790. document.getElementById('modal-img').src = fg.data_uri;
  4791. const dl = document.getElementById('modal-dl');
  4792. dl.href = fg.data_uri; dl.download = fg.filename;
  4793. document.getElementById('fig-modal').classList.add('open');
  4794. };
  4795. document.getElementById('modal-close').onclick = () => document.getElementById('fig-modal').classList.remove('open');
  4796. document.getElementById('fig-modal').onclick = ev => { if (ev.target.id === 'fig-modal') document.getElementById('fig-modal').classList.remove('open'); };
  4797. window.addEventListener('keydown', ev => { if (ev.key === 'Escape') document.getElementById('fig-modal').classList.remove('open'); });
  4798. function renderPhaseRows() {
  4799. const fRun = document.getElementById('phase-run-filter').value;
  4800. const fGrp = document.getElementById('phase-grp-filter').value;
  4801. const preset = document.getElementById('phase-col-preset').value;
  4802. const allSlices = [];
  4803. Object.entries(DATA.runs).forEach(([rk, r]) => {
  4804. (r.phases || []).forEach(p => allSlices.push({ rk, p }));
  4805. });
  4806. allSlices.sort((a, b) => a.p.seq_start - b.p.seq_start);
  4807. const sensorList = DATA.meta.sensors.filter(s => {
  4808. if (preset === 'all') return true;
  4809. if (preset === 'dimm') return s.group === 'dimm_temp' || s.group === 'cpu_temp';
  4810. if (preset === 'pwr') return s.group === 'power' || s.group === 'electrical';
  4811. return ['DIMM_CPU0_A_Temp','DIMM_CPU0_B_Temp','DIMM_CPU0_C_Temp','DIMM_CPU0_D_Temp','DIMM_CPU1_A_Temp','CPU0_Temp','DDR0_Power','DDR2_Power','P12V_DDR0','PVCCD_CPU0_Input_Power','PSU0_PIn'].includes(s.key);
  4812. });
  4813. let h = `<table><thead><tr><th>#seq (行数/s)</th><th>算法 Run</th><th>阶段 (` + `phase_group` + `)</th><th>时间区间 (UTC)</th><th>SPD有效/空</th><th>PECI有效/空</th><th>定位</th>` +
  4814. sensorList.map(s => `<th>${esc(s.key.replace('DIMM_','').replace('_Input_Power',''))} (${esc(s.unit)})</th>`).join('') +
  4815. `</tr></thead><tbody>`;
  4816. allSlices.forEach(({ rk, p }) => {
  4817. if (fRun && rk !== fRun) return;
  4818. if (fGrp && p.phase_group !== fGrp) return;
  4819. const s = p.sensors || {};
  4820. h += `<tr>
  4821. <td class="mono">#${p.seq_start}..${p.seq_end} (${p.rows}s)</td>
  4822. <td class="mono">${esc(rk)}</td>
  4823. <td class="mono"><b>${esc(p.phase)}</b><br><span style="color:var(--muted)">${esc(p.phase_group)}</span></td>
  4824. <td class="mono">${esc((p.start_time||'').slice(11,19))}→${esc((p.end_time||'').slice(11,19))}</td>
  4825. <td class="mono">${p.spd_valid_rows} / <span class="${p.spd_null_rows?'anom-warn':''}">${p.spd_null_rows}</span></td>
  4826. <td class="mono">${p.peci_valid_rows} / ${p.peci_null_rows}</td>
  4827. <td class="mono">
  4828. <button type="button" class="btn-xs" onclick="window.zoomToSeqRange(${p.seq_start},${p.seq_end},'all',${p.seq_start},12)">曲线</button>
  4829. <button type="button" class="btn-xs" onclick="window.jumpToRawRange('${esc(rk)}','',${p.seq_start},${p.seq_end},'all')">明细</button>
  4830. </td>` +
  4831. sensorList.map(sn => {
  4832. const st = s[sn.key];
  4833. if (!st) return `<td class="null-cell">null</td>`;
  4834. return `<td class="mono">${st.start}→${st.end}<br><span style="color:var(--muted)">${st.min}~${st.max}</span></td>`;
  4835. }).join('') + `</tr>`;
  4836. });
  4837. document.getElementById('phases-detail-table').innerHTML = h + '</tbody></table>';
  4838. }
  4839. function renderLoopEvents() {
  4840. const rows = [];
  4841. Object.entries(DATA.runs).forEach(([rk, r]) => {
  4842. (r.loop_events || []).forEach(le => rows.push({ rk, le }));
  4843. });
  4844. const el = document.getElementById('loop-events-table');
  4845. if (!rows.length) {
  4846. el.innerHTML = '<div class="sub-note">无 loop_events 固件事件记录。</div>';
  4847. return;
  4848. }
  4849. let h = `<table><thead><tr><th>Run</th><th>事件类型</th><th>Loop</th><th>Socket</th><th>固件报告耗时 (fw_sec)</th><th>映射 1Hz #seq</th><th>对应时刻 / elapsed</th><th>操作</th></tr></thead><tbody>`;
  4850. rows.forEach(({ rk, le }) => {
  4851. const sq = le.seq;
  4852. h += `<tr>
  4853. <td class="mono"><b>${esc(rk)}</b></td>
  4854. <td class="mono">${esc(le.event)}</td>
  4855. <td class="mono">L${le.loop ?? '-'}</td>
  4856. <td class="mono">${le.socket == null ? '-' : 'CPU' + le.socket}</td>
  4857. <td class="mono">${le.fw_sec == null ? '-' : le.fw_sec + ' s'}</td>
  4858. <td class="mono">${sq != null ? '#' + sq : '-'}</td>
  4859. <td class="mono">${esc((le.iso_time || '').slice(11,19))} (${le.t_s ?? '-'}s)</td>
  4860. <td>${sq != null ? `<button type="button" class="btn-xs" onclick="window.zoomToSeqRange(${sq},${sq},'all',${sq},20)">曲线定位</button> <button type="button" class="btn-xs" onclick="window.jumpToRawRange('','',${Math.max(1,sq-2)},${Math.min(n,sq+2)},'all')">看行</button>` : '-'}</td>
  4861. </tr>`;
  4862. });
  4863. el.innerHTML = h + '</tbody></table>';
  4864. }
  4865. function initRawExplorer() {
  4866. const meCatSel = document.getElementById('me-cat-filter');
  4867. const cats = Array.from(new Set(microEvents.map(e => e.category)));
  4868. cats.forEach(c => {
  4869. const o = document.createElement('option'); o.value = c; o.textContent = c; meCatSel.appendChild(o);
  4870. });
  4871. const renderMeCards = () => {
  4872. const cat = meCatSel.value;
  4873. const list = cat ? microEvents.filter(e => e.category === cat) : microEvents;
  4874. document.getElementById('me-count').textContent = cat ? `${list.length} / ${microEvents.length}` : String(microEvents.length);
  4875. document.getElementById('me-cards').innerHTML = list.map(ev => `
  4876. <div class="me-card">
  4877. <div>
  4878. <div class="me-card-top">
  4879. <span><span class="badge ${esc(ev.severity)}">${esc(ev.id)} · ${esc(ev.category)}</span></span>
  4880. <span class="mono">#${ev.seq_start}..#${ev.seq_end} (${ev.rows}s)</span>
  4881. </div>
  4882. <div class="me-title" style="margin-top:5px">${esc(ev.title)}</div>
  4883. <div class="me-detail" style="margin-top:4px">${esc(ev.detail)}</div>
  4884. </div>
  4885. <div class="controls">
  4886. <button type="button" class="btn-xs primary" onclick="window.zoomToSeqRange(${ev.seq_start},${ev.seq_end},'${esc(ev.focus_chart)}',${ev.seq_start},${ev.pad_s})">曲线定点放大</button>
  4887. <button type="button" class="btn-xs" onclick="window.jumpToRawRange('','',${Math.max(1, ev.seq_start - 2)},${Math.min(n, ev.seq_end + 2)},'all')">锁定这 ${ev.rows} 行明细</button>
  4888. </div>
  4889. </div>
  4890. `).join('');
  4891. };
  4892. meCatSel.onchange = renderMeCards;
  4893. renderMeCards();
  4894. const rSel = document.getElementById('raw-run');
  4895. ser.run_names.forEach(rk => {
  4896. const o = document.createElement('option'); o.value = rk; o.textContent = rk; rSel.appendChild(o);
  4897. });
  4898. const pSel = document.getElementById('raw-phase');
  4899. ser.phase_names.forEach(ph => {
  4900. const o = document.createElement('option'); o.value = ph; o.textContent = ph; pSel.appendChild(o);
  4901. });
  4902. const cSel = document.getElementById('raw-cust-col');
  4903. DATA.meta.sensors.forEach(s => {
  4904. const o = document.createElement('option'); o.value = s.key; o.textContent = `${s.key} (${s.unit})`; cSel.appendChild(o);
  4905. });
  4906. const oLat = document.createElement('option'); oLat.value = 'lat'; oLat.textContent = 'poll_latency_ms (ms)'; cSel.appendChild(oLat);
  4907. ['raw-run', 'raw-phase', 'raw-preset', 'raw-cust-col', 'raw-cust-op', 'raw-col-group'].forEach(id => {
  4908. document.getElementById(id).onchange = () => { rawPage = 1; applyRawFilter(); };
  4909. });
  4910. ['raw-seq-min', 'raw-seq-max', 'raw-cust-val'].forEach(id => {
  4911. document.getElementById(id).oninput = () => { rawPage = 1; applyRawFilter(); };
  4912. });
  4913. document.getElementById('raw-page-size').onchange = () => { rawPage = 1; renderRawTable(); };
  4914. document.getElementById('raw-prev').onclick = () => { if (rawPage > 1) { rawPage--; renderRawTable(); } };
  4915. document.getElementById('raw-next').onclick = () => {
  4916. const ps = parseInt(document.getElementById('raw-page-size').value, 10) || 100;
  4917. const totP = Math.max(1, Math.ceil(rawFiltered.length / ps));
  4918. if (rawPage < totP) { rawPage++; renderRawTable(); }
  4919. };
  4920. document.getElementById('btn-raw-reset').onclick = () => window.jumpToRawRange('', '', '', '', 'all');
  4921. document.getElementById('btn-raw-export').onclick = () => exportCsvForIndices(rawFiltered, 'filtered_1hz_telemetry.csv');
  4922. applyRawFilter();
  4923. }
  4924. function applyRawFilter() {
  4925. const fRun = document.getElementById('raw-run').value;
  4926. const fPh = document.getElementById('raw-phase').value;
  4927. const fPre = document.getElementById('raw-preset').value;
  4928. const sMin = parseInt(document.getElementById('raw-seq-min').value, 10);
  4929. const sMax = parseInt(document.getElementById('raw-seq-max').value, 10);
  4930. const cCol = document.getElementById('raw-cust-col').value;
  4931. const cOp = document.getElementById('raw-cust-op').value;
  4932. const cVal = parseFloat(document.getElementById('raw-cust-val').value);
  4933. const dKeys = DATA.meta.dimm_keys;
  4934. rawFiltered = [];
  4935. for (let i = 0; i < n; i++) {
  4936. const sq = cols.seq[i];
  4937. if (!isNaN(sMin) && sq < sMin) continue;
  4938. if (!isNaN(sMax) && sq > sMax) continue;
  4939. const rk = ser.run_names[cols.rk[i]];
  4940. if (fRun && rk !== fRun) continue;
  4941. const ph = ser.phase_names[cols.ph[i]];
  4942. if (fPh && ph !== fPh) continue;
  4943. if (fPre === 'spd_null') {
  4944. if (!dKeys.some(k => cols[k]?.[i] == null)) continue;
  4945. } else if (fPre === 'peci_null') {
  4946. if (cols.Dimm_Power_CPU0?.[i] != null) continue;
  4947. } else if (fPre === 'cool_spike') {
  4948. if (!(ph === 'cooldown' && (cols.DDR0_Power?.[i] ?? 0) >= 20)) continue;
  4949. } else if (fPre === 'p12v_droop') {
  4950. if ((cols.P12V_DDR0?.[i] ?? 99) > 12.13) continue;
  4951. } else if (fPre === 'high_lat') {
  4952. if ((cols.lat[i] ?? 0) < 300) continue;
  4953. } else if (fPre === 'temp_jump') {
  4954. if (i === 0) continue;
  4955. const jumped = dKeys.some(k => {
  4956. const a = cols[k]?.[i], b = cols[k]?.[i - 1];
  4957. return a != null && b != null && Math.abs(a - b) >= 0.75;
  4958. });
  4959. if (!jumped) continue;
  4960. } else if (fPre === 'pwr_jump') {
  4961. if (i === 0) continue;
  4962. const a = cols.DDR0_Power?.[i], b = cols.DDR0_Power?.[i - 1];
  4963. if (a == null || b == null || Math.abs(a - b) < 5.0) continue;
  4964. }
  4965. if (cCol && cols[cCol]) {
  4966. const cv = cols[cCol][i];
  4967. if (cOp === 'isnull') { if (cv != null) continue; }
  4968. else if (cOp === 'notnull') { if (cv == null) continue; }
  4969. else if (!isNaN(cVal)) {
  4970. if (cv == null) continue;
  4971. if (cOp === 'gt' && !(cv > cVal)) continue;
  4972. if (cOp === 'ge' && !(cv >= cVal)) continue;
  4973. if (cOp === 'lt' && !(cv < cVal)) continue;
  4974. if (cOp === 'le' && !(cv <= cVal)) continue;
  4975. }
  4976. }
  4977. rawFiltered.push(i);
  4978. }
  4979. renderRawTable();
  4980. }
  4981. function renderRawTable() {
  4982. const cg = document.getElementById('raw-col-group').value;
  4983. const ps = parseInt(document.getElementById('raw-page-size').value, 10) || 100;
  4984. const tot = rawFiltered.length;
  4985. const totPages = Math.max(1, Math.ceil(tot / ps));
  4986. rawPage = Math.max(1, Math.min(rawPage, totPages));
  4987. document.getElementById('raw-count-info').textContent = `匹配 ${tot.toLocaleString()} / ${n.toLocaleString()} 行`;
  4988. document.getElementById('raw-page-info').textContent = `第 ${rawPage} / ${totPages} 页`;
  4989. const selSensors = DATA.meta.sensors.filter(s => {
  4990. if (cg === 'all') return true;
  4991. if (cg === 'temps') return s.group === 'dimm_temp' || s.group === 'cpu_temp';
  4992. if (cg === 'elec') return s.group === 'power' || s.group === 'electrical';
  4993. return ['DIMM_CPU0_A_Temp','DIMM_CPU0_B_Temp','DIMM_CPU0_C_Temp','DIMM_CPU0_D_Temp','DIMM_CPU1_A_Temp','CPU0_Temp','DDR0_Power','DDR2_Power','P12V_DDR0','PVCCD_CPU0_Input_Power','PSU0_PIn'].includes(s.key);
  4994. });
  4995. const start = (rawPage - 1) * ps, end = Math.min(tot, start + ps);
  4996. const parts = [`<table><thead><tr><th>#seq</th><th>时间</th><th>t(s)</th><th>Run</th><th>Phase</th><th>L#</th><th>lat(ms)</th>`];
  4997. selSensors.forEach(s => parts.push(`<th>${esc(s.key.replace('DIMM_','').replace('_Input_Power',''))}(${esc(s.unit)})</th>`));
  4998. parts.push('</tr></thead><tbody>');
  4999. for (let k = start; k < end; k++) {
  5000. const i = rawFiltered[k];
  5001. const rk = ser.run_names[cols.rk[i]], ph = ser.phase_names[cols.ph[i]];
  5002. const lat = cols.lat[i];
  5003. const latHtml = lat == null ? '<span class="null-cell">-</span>' : (lat >= 500 ? `<span class="anom-warn">${lat}</span>` : String(lat));
  5004. parts.push(`<tr><td class="mono"><button type="button" class="btn-xs" title="切回曲线并放大至此处 ±30s" onclick="window.zoomToSeqRange(${Math.max(1,cols.seq[i]-30)},${Math.min(n,cols.seq[i]+30)},'all',${cols.seq[i]},0)">#${cols.seq[i]}</button></td>` +
  5005. `<td class="mono">${esc(cols.ts[i])}</td><td class="mono">${cols.t[i]}</td><td class="mono">${esc(rk)}</td><td class="mono">${esc(ph)}</td>` +
  5006. `<td class="mono">${cols.loop[i] || '-'}</td><td class="mono">${latHtml}</td>`);
  5007. for (const s of selSensors) {
  5008. const v = cols[s.key]?.[i];
  5009. if (v == null) {
  5010. parts.push(`<td class="null-cell">null</td>`);
  5011. continue;
  5012. }
  5013. const pv = i > 0 ? cols[s.key]?.[i - 1] : null;
  5014. let cls = '', tip = '';
  5015. if (pv != null) {
  5016. const d = +(v - pv).toFixed(3);
  5017. if (d !== 0) tip = ` title="较上秒 Δ=${d > 0 ? '+' : ''}${d}"`;
  5018. }
  5019. if (s.key === 'DDR0_Power' && ph === 'cooldown' && v >= 20) cls = ' class="anom-warn"';
  5020. else if (s.key === 'P12V_DDR0' && v <= 12.13) cls = ' class="anom-droop"';
  5021. else if (s.group === 'dimm_temp' && pv != null && (v - pv) >= 0.75) cls = ' class="anom-warm"';
  5022. parts.push(`<td class="mono"${tip}><span${cls}>${v}</span></td>`);
  5023. }
  5024. parts.push('</tr>');
  5025. }
  5026. parts.push('</tbody></table>');
  5027. document.getElementById('raw-table-wrap').innerHTML = parts.join('');
  5028. }
  5029. function drawAll() { drawCharts(); drawBars(); }
  5030. document.getElementById('bar-metric-select').onchange = drawBars;
  5031. attachHover('chart-temp');
  5032. attachHover('chart-mpwr');
  5033. attachHover('chart-spwr');
  5034. attachHover('chart-elec');
  5035. window.addEventListener('resize', drawAll);
  5036. renderKpis(); buildZoomBar(); buildLegends(); drawAll(); renderTables();
  5037. })();
  5038. </script>"""
  5039. tail = script_js + "\n</body>\n</html>\n"
  5040. return (
  5041. head_html
  5042. + '<script id="embedded-data" type="application/json">' + payload_json + "</script>\n"
  5043. + '<script id="embedded-figures" type="application/json">' + figs_json + "</script>\n"
  5044. + tail
  5045. )
  5046. def export_campaign_clean_csv(parsed: dict[str, Any], artifacts: dict[str, Any], export_dir: Path) -> list[Path]:
  5047. export_dir.mkdir(parents=True, exist_ok=True)
  5048. sensors = artifacts["sensors"]
  5049. headers = [
  5050. "seq", "unix_ts", "iso_time", "campaign_elapsed_s", "run_elapsed_s", "poll_latency_ms",
  5051. "run_key", "algo_name", "short_name", "engine", "phase", "loop_index", "loop_total",
  5052. ] + [s["key"] for s in sensors]
  5053. out_path = export_dir / "thermal_campaign_per_sensor_clean.csv"
  5054. with out_path.open("w", encoding="utf-8-sig", newline="") as fp:
  5055. w = csv.writer(fp, lineterminator="\r\n")
  5056. w.writerow(headers)
  5057. for r in artifacts["rows"]:
  5058. row = [
  5059. r["seq"], r["unix_ts"], r["iso_time"], r["campaign_elapsed_s"], r["run_elapsed_s"], r["poll_latency_ms"],
  5060. r["run_key"], r["algo_name"], r["short_name"], r["engine"], r["phase"], r["loop_index"], r["loop_total"],
  5061. ]
  5062. for s in sensors:
  5063. v = r.get(s["key"])
  5064. row.append("" if v is None else v)
  5065. w.writerow(row)
  5066. return [out_path]
  5067. def _parse_kv_temp_map(text: str) -> dict[str, float]:
  5068. out: dict[str, float] = {}
  5069. for tok in (text or "").strip().split():
  5070. if "=" in tok:
  5071. k, v = tok.split("=", 1)
  5072. fv = _to_float(v)
  5073. if fv is not None:
  5074. out[k.strip()] = fv
  5075. return out
  5076. def parse_thermal_endurance(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
  5077. p = Path(input_path).resolve()
  5078. if p.is_dir():
  5079. cands = sorted(p.glob("thermal_*_Endurance.csv")) or sorted(p.glob("thermal_*.csv"))
  5080. if not cands:
  5081. raise FileNotFoundError(f"No thermal endurance CSV found in {p}")
  5082. csv_path = cands[0]
  5083. base_dir = p
  5084. else:
  5085. csv_path = p
  5086. base_dir = p.parent
  5087. milestone_cands = sorted(base_dir.glob("mt_milestones_*.csv"))
  5088. milestone_path = milestone_cands[0] if milestone_cands else None
  5089. event_cands = sorted(base_dir.glob("*.events.jsonl"))
  5090. event_path = event_cands[0] if event_cands else None
  5091. with csv_path.open("r", encoding="utf-8-sig", newline="") as fp:
  5092. reader = csv.DictReader(fp)
  5093. fieldnames = list(reader.fieldnames or [])
  5094. raw_rows = list(reader)
  5095. if not raw_rows:
  5096. raise ValueError(f"Empty endurance CSV: {csv_path}")
  5097. # Discover active individual sensor columns (skipping *_avg_c / *_min_c / *_max_c / *_spread_c)
  5098. active_mcu = [f"MCU_CH{i:02d}" for i in range(1, 25) if f"MCU_CH{i:02d}" in fieldnames and any(r[f"MCU_CH{i:02d}"].strip() for r in raw_rows)]
  5099. active_ct = [f"CT{i:02d}" for i in range(1, 9) if f"CT{i:02d}" in fieldnames and any(r[f"CT{i:02d}"].strip() for r in raw_rows)]
  5100. ipmi_candidates = [c for c in fieldnames if c.startswith("IPMI_CPU")]
  5101. active_ipmi = [c for c in ipmi_candidates if any(r[c].strip() for r in raw_rows)]
  5102. extra_cols = [c for c in ("ct0_board_c", "ptc_avg_duty", "ssr1_duty", "ssr2_duty", "ssr4_duty", "fan_front_avg_duty", "fan_rear_avg_duty") if c in fieldnames]
  5103. all_sensor_cols = active_mcu + active_ct + active_ipmi + extra_cols
  5104. rows: list[dict[str, Any]] = []
  5105. for idx, r in enumerate(raw_rows, start=1):
  5106. rec: dict[str, Any] = {
  5107. "seq": idx,
  5108. "timestamp_utc8": (r.get("timestamp_utc8") or "").strip(),
  5109. "unix_ms": _to_int(r.get("unix_ms")),
  5110. "elapsed_s": _to_float(r.get("elapsed_s")),
  5111. "station_id": (r.get("station_id") or "").strip(),
  5112. "station_phase": (r.get("station_phase") or "").strip(),
  5113. "mcu_mode": (r.get("mcu_mode") or "").strip(),
  5114. "mcu_target_c": _to_float(r.get("mcu_target_c")),
  5115. "mcu_flags_hex": (r.get("mcu_flags_hex") or "").strip(),
  5116. "stage_error_total": _to_int(r.get("stage_error_total")) or 0,
  5117. "diag_err_cnt": _to_int(r.get("diag_err_cnt")) or 0,
  5118. }
  5119. for c in all_sensor_cols:
  5120. rec[c] = _to_float(r.get(c))
  5121. rows.append(rec)
  5122. # Parse MT milestones if present
  5123. milestones: list[dict[str, Any]] = []
  5124. test_windows: list[dict[str, Any]] = []
  5125. if milestone_path and milestone_path.is_file():
  5126. with milestone_path.open("r", encoding="utf-8-sig", newline="") as fp:
  5127. mrows = list(csv.DictReader(fp))
  5128. open_tests: dict[tuple[str, str], dict[str, Any]] = {}
  5129. for mr in mrows:
  5130. ev_t = (mr.get("event_type") or "").strip()
  5131. pnum = (mr.get("pass_num") or "").strip()
  5132. tnum = (mr.get("test_num") or "").strip()
  5133. tdesc = (mr.get("test_desc") or "").strip()
  5134. ts_str = (mr.get("timestamp_utc8") or "").strip()
  5135. mt_temps = _parse_kv_temp_map(mr.get("mt_dimm_temps_c") or "")
  5136. mcu_temps = _parse_kv_temp_map(mr.get("mcu_dimm_temps_c") or "")
  5137. ct8_temps = _parse_kv_temp_map(mr.get("ct8_temps_c") or "")
  5138. ipmi_temps = _parse_kv_temp_map(mr.get("ipmi_dimm_temps_c") or "")
  5139. mitem = {
  5140. "timestamp_utc8": ts_str,
  5141. "event_type": ev_t,
  5142. "pass_num": _to_int(pnum),
  5143. "test_num": _to_int(tnum),
  5144. "test_desc": tdesc,
  5145. "test_duration_s": _to_float(mr.get("test_duration_s")),
  5146. "cum_errors": _to_int(mr.get("cum_errors")),
  5147. "mt_cpu_temp_c": _to_float(mr.get("mt_cpu_temp_c")),
  5148. "mcu_mode": (mr.get("mcu_mode") or "").strip(),
  5149. "mt_dimm_temps": mt_temps,
  5150. "mcu_dimm_temps": mcu_temps,
  5151. "ct8_temps": ct8_temps,
  5152. "ipmi_dimm_temps": ipmi_temps,
  5153. }
  5154. milestones.append(mitem)
  5155. if ev_t == "test_start":
  5156. open_tests[(pnum, tnum)] = {
  5157. "pass_num": _to_int(pnum),
  5158. "test_num": _to_int(tnum),
  5159. "test_desc": tdesc,
  5160. "start_ts": ts_str,
  5161. "end_ts": None,
  5162. "duration_s": None,
  5163. "cum_errors": 0,
  5164. "start_mt_dimm": mt_temps,
  5165. "end_mt_dimm": {},
  5166. "snapshots": [],
  5167. }
  5168. elif ev_t == "minute_snapshot" and (pnum, tnum) in open_tests:
  5169. open_tests[(pnum, tnum)]["snapshots"].append(mitem)
  5170. elif ev_t == "test_done":
  5171. tw = open_tests.pop((pnum, tnum), {
  5172. "pass_num": _to_int(pnum),
  5173. "test_num": _to_int(tnum),
  5174. "test_desc": tdesc,
  5175. "start_ts": ts_str,
  5176. "start_mt_dimm": mt_temps,
  5177. "snapshots": [],
  5178. })
  5179. tw["end_ts"] = ts_str
  5180. tw["duration_s"] = _to_float(mr.get("test_duration_s"))
  5181. tw["cum_errors"] = _to_int(mr.get("cum_errors")) or 0
  5182. tw["end_mt_dimm"] = mt_temps
  5183. test_windows.append(tw)
  5184. for rem in open_tests.values():
  5185. rem["end_ts"] = rows[-1]["timestamp_utc8"]
  5186. test_windows.append(rem)
  5187. test_windows.sort(key=lambda w: (w["pass_num"] or 0, w["test_num"] or 0, w["start_ts"]))
  5188. def _stats_block(sub_rows: list[dict[str, Any]]) -> dict[str, Any]:
  5189. return {c: _sensor_stats([r[c] for r in sub_rows if r.get(c) is not None], 2) for c in all_sensor_cols}
  5190. # Correlate test windows to endurance CSV rows by timestamp_utc8
  5191. # Note: Test 0/1 in milestones had bursty UART reads with identical start/end timestamps, while later tests span actual minutes.
  5192. for tw in test_windows:
  5193. s_ts, e_ts = tw["start_ts"], tw["end_ts"] or rows[-1]["timestamp_utc8"]
  5194. win_rows = [r for r in rows if s_ts <= r["timestamp_utc8"] <= e_ts]
  5195. if not win_rows and tw.get("snapshots"):
  5196. sn_ts = [s["timestamp_utc8"] for s in tw["snapshots"]]
  5197. win_rows = [r for r in rows if min(sn_ts) <= r["timestamp_utc8"] <= max(sn_ts)]
  5198. tw["csv_rows"] = len(win_rows)
  5199. tw["sensors"] = _stats_block(win_rows) if win_rows else {}
  5200. # Compute MT DIMM0..4 min/max across start, snapshots, end
  5201. mt_all: dict[str, list[float]] = {}
  5202. for dmap in [tw.get("start_mt_dimm") or {}] + [s.get("mt_dimm_temps") or {} for s in tw.get("snapshots") or []] + [tw.get("end_mt_dimm") or {}]:
  5203. for dk, dv in dmap.items():
  5204. mt_all.setdefault(dk, []).append(dv)
  5205. tw["mt_dimm_stats"] = {dk: _sensor_stats(vs, 2) for dk, vs in sorted(mt_all.items())}
  5206. tw.pop("snapshots", None)
  5207. # MCU mode breakdown (idle, preheating, pid, offline)
  5208. mode_slices: dict[str, Any] = {}
  5209. cur_m = None
  5210. cur_buf: list[dict[str, Any]] = []
  5211. mode_transitions: list[dict[str, Any]] = []
  5212. for r in rows:
  5213. if cur_m is None or r["mcu_mode"] != cur_m:
  5214. if cur_buf:
  5215. mode_transitions.append({
  5216. "mode": cur_m,
  5217. "rows": len(cur_buf),
  5218. "start_ts": cur_buf[0]["timestamp_utc8"],
  5219. "end_ts": cur_buf[-1]["timestamp_utc8"],
  5220. "sensors": _stats_block(cur_buf),
  5221. })
  5222. cur_m = r["mcu_mode"]
  5223. cur_buf = [r]
  5224. else:
  5225. cur_buf.append(r)
  5226. if cur_buf:
  5227. mode_transitions.append({
  5228. "mode": cur_m,
  5229. "rows": len(cur_buf),
  5230. "start_ts": cur_buf[0]["timestamp_utc8"],
  5231. "end_ts": cur_buf[-1]["timestamp_utc8"],
  5232. "sensors": _stats_block(cur_buf),
  5233. })
  5234. events_summary: dict[str, Any] = {"event_count": 0, "kind_counts": {}, "notable": []}
  5235. if event_path and event_path.is_file():
  5236. kc: dict[str, int] = {}
  5237. notable: list[dict[str, Any]] = []
  5238. ev_cnt = 0
  5239. for ln in event_path.read_text(encoding="utf-8", errors="replace").splitlines():
  5240. s = ln.strip()
  5241. if not s:
  5242. continue
  5243. ev = json.loads(s)
  5244. ev_cnt += 1
  5245. k = str(ev.get("kind") or "unknown")
  5246. kc[k] = kc.get(k, 0) + 1
  5247. if k in ("record_start", "cmd_ok", "mcu_offline", "error", "warning") or len(notable) < 40:
  5248. notable.append(ev)
  5249. events_summary = {"event_count": ev_cnt, "kind_counts": kc, "notable": notable[:120]}
  5250. total_s = round(rows[-1]["elapsed_s"] or len(rows), 1)
  5251. parsed = {
  5252. "parser_version": PARSER_VERSION,
  5253. "mode": "thermal_endurance_per_position_no_means",
  5254. "parsed_utc": datetime.now(timezone.utc).isoformat(),
  5255. "input_path": str(p),
  5256. "csv_file": str(csv_path),
  5257. "milestone_file": str(milestone_path) if milestone_path else None,
  5258. "source_kind": "thermal_endurance",
  5259. "station_id": rows[0]["station_id"] or "S1",
  5260. "total_1hz_rows": len(rows),
  5261. "total_duration_s": total_s,
  5262. "total_duration_hms": _fmt_hms(total_s),
  5263. "start_ts": rows[0]["timestamp_utc8"],
  5264. "end_ts": rows[-1]["timestamp_utc8"],
  5265. "active_mcu_channels": active_mcu,
  5266. "active_ct_channels": active_ct,
  5267. "active_ipmi_channels": active_ipmi,
  5268. "extra_cols": extra_cols,
  5269. "overall_sensors": _stats_block(rows),
  5270. "mode_transitions": mode_transitions,
  5271. "test_windows": test_windows,
  5272. "milestones_count": len(milestones),
  5273. "mt_total_errors": max(
  5274. [max(r["stage_error_total"] for r in rows)]
  5275. + [tw["cum_errors"] for tw in test_windows]
  5276. ),
  5277. "events_summary": events_summary,
  5278. }
  5279. # Build compact columnar time-series (keep all 42k rows for lossless zoom, selected active cols)
  5280. mode_names: list[str] = []
  5281. mode_idx: dict[str, int] = {}
  5282. cols: dict[str, list[Any]] = {"seq": [], "t": [], "ts": [], "md": []}
  5283. for c in all_sensor_cols:
  5284. cols[c] = []
  5285. for r in rows:
  5286. md = r["mcu_mode"] or "unknown"
  5287. if md not in mode_idx:
  5288. mode_idx[md] = len(mode_names)
  5289. mode_names.append(md)
  5290. cols["seq"].append(r["seq"])
  5291. cols["t"].append(round(r["elapsed_s"] or 0.0, 1))
  5292. ts = r["timestamp_utc8"]
  5293. cols["ts"].append(ts[11:19] if len(ts) >= 19 else ts)
  5294. cols["md"].append(mode_idx[md])
  5295. for c in all_sensor_cols:
  5296. cols[c].append(_round_opt(r.get(c), 2))
  5297. return parsed, {"rows": rows, "all_sensor_cols": all_sensor_cols, "series": {"mode_names": mode_names, "cols": cols}}
  5298. def render_endurance_markdown_report(parsed: dict[str, Any]) -> str:
  5299. lines: list[str] = []
  5300. lines.append("# 2026-11-14 11.8 小时 70°C 全流程耐久测试逐位置传感器解析报告(无均值)")
  5301. lines.append("")
  5302. lines.append(f"- **输入来源**:`{parsed['csv_file']}` (`{parsed['source_kind']}`)")
  5303. lines.append(f"- **时间范围**:`{parsed['start_ts']}` → `{parsed['end_ts']}` · 共 `{parsed['total_1hz_rows']:,}` 行 (`{parsed['total_duration_hms']}`)")
  5304. lines.append(f"- **独立通道**:MCU `{', '.join(parsed['active_mcu_channels'])}` · CT `{', '.join(parsed['active_ct_channels'])}` · IPMI `{', '.join(parsed['active_ipmi_channels'])}`")
  5305. lines.append(f"- **MT 累计错误**:`{parsed['mt_total_errors']}`")
  5306. lines.extend(["", "## 1. 全部位置传感器全周期实测范围 (`min~max`, `起点→终点`)", ""])
  5307. lines.append("| 通道 | 样本数 | 最小值 | 最大值 | 起点 | 终点 |")
  5308. lines.append("|---|---:|---:|---:|---:|---:|")
  5309. for c, st in parsed["overall_sensors"].items():
  5310. if not st:
  5311. continue
  5312. lines.append(f"| `{c}` | `{st['count']}` | `{st['min']}` | `{st['max']}` | `{st['start']}` | `{st['end']}` |")
  5313. lines.extend(["", "## 2. MCU 运行模式分段统计 (含后段 `offline` 失控温升)", ""])
  5314. lines.append("| MCU 模式 | 样本(s) | 时间区间 | MCU_CH01..04 / 13 | CT01..CT08 | IPMI CPU0_A..D / CPU1_A | PTC / SSR2 / FanF |")
  5315. lines.append("|---|---:|---|---|---|---|---|")
  5316. for mt in parsed["mode_transitions"]:
  5317. s = mt["sensors"]
  5318. mcus = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_mcu_channels"])
  5319. cts = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ct_channels"])
  5320. ipmis = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ipmi_channels"])
  5321. act = f"{_fmt_range(s.get('ptc_avg_duty'),'%',False)} / {_fmt_range(s.get('ssr2_duty'),'%',False)} / {_fmt_range(s.get('fan_front_avg_duty'),'%',False)}"
  5322. lines.append(f"| `{mt['mode']}` | `{mt['rows']}` | `{mt['start_ts'][11:19]}→{mt['end_ts'][11:19]}` | {mcus} | {cts} | {ipmis} | {act} |")
  5323. lines.extend(["", "## 3. MemTest86 测试里程碑逐位置温度拆解 (`Test 0..19`)", ""])
  5324. lines.append("| Test | 时长(s) | CSV样本 | MT DIMM0..4 (min~max) | IPMI CPU0_A..D / CPU1_A | CT01..08 | 错误 |")
  5325. lines.append("|---|---:|---:|---|---|---|---:|")
  5326. for tw in parsed["test_windows"]:
  5327. mtd = " / ".join(_fmt_range(st, "", False) for st in tw["mt_dimm_stats"].values()) or "-"
  5328. s = tw["sensors"]
  5329. ipmis = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ipmi_channels"]) if s else "-"
  5330. cts = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ct_channels"]) if s else "-"
  5331. lines.append(f"| `P{tw['pass_num']} {tw['test_desc']}` | `{tw.get('duration_s') or '-'}` | `{tw['csv_rows']}` | {mtd} | {ipmis} | {cts} | `{tw['cum_errors']}` |")
  5332. return "\n".join(lines) + "\n"
  5333. def render_endurance_html_dashboard(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
  5334. payload = {
  5335. "meta": {
  5336. "parser_version": parsed["parser_version"],
  5337. "station_id": parsed["station_id"],
  5338. "total_1hz_rows": parsed["total_1hz_rows"],
  5339. "total_duration_hms": parsed["total_duration_hms"],
  5340. "start_ts": parsed["start_ts"],
  5341. "end_ts": parsed["end_ts"],
  5342. "active_mcu_channels": parsed["active_mcu_channels"],
  5343. "active_ct_channels": parsed["active_ct_channels"],
  5344. "active_ipmi_channels": parsed["active_ipmi_channels"],
  5345. "extra_cols": parsed["extra_cols"],
  5346. "mt_total_errors": parsed["mt_total_errors"],
  5347. },
  5348. "overall_sensors": parsed["overall_sensors"],
  5349. "mode_transitions": parsed["mode_transitions"],
  5350. "test_windows": parsed["test_windows"],
  5351. "events_summary": parsed["events_summary"],
  5352. "series": artifacts["series"],
  5353. }
  5354. payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
  5355. title = html.escape(f"2026-11-14 11.8h 70°C 耐久测试逐位置解析报告 ({parsed['total_1hz_rows']:,} 行)")
  5356. return f"""<!DOCTYPE html>
  5357. <html lang="zh-CN">
  5358. <head>
  5359. <meta charset="UTF-8">
  5360. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5361. <title>{title}</title>
  5362. <style>
  5363. :root {{ --bg:#0b101b; --bg-card:#121a2b; --bg-alt:#182338; --text:#e6edf7; --muted:#93a4be; --border:#253554; --accent:#38bdf8; --good:#22c55e; --warn:#f59e0b; --bad:#ef4444; }}
  5364. body.light {{ --bg:#f1f5f9; --bg-card:#ffffff; --bg-alt:#e8eff8; --text:#0f172a; --muted:#475569; --border:#cbd5e1; --accent:#0284c7; }}
  5365. * {{ box-sizing:border-box; margin:0; padding:0; }}
  5366. body {{ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; background:var(--bg); color:var(--text); line-height:1.5; padding-bottom:48px; }}
  5367. header {{ background:var(--bg-card); border-bottom:1px solid var(--border); padding:14px 24px; display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:12px; position:sticky; top:0; z-index:20; }}
  5368. .hdr-title h1 {{ font-size:18px; font-weight:700; }}
  5369. .hdr-sub {{ font-size:12px; color:var(--muted); margin-top:2px; }}
  5370. .controls {{ display:flex; flex-wrap:wrap; gap:8px; align-items:center; }}
  5371. button, select {{ background:var(--bg-alt); color:var(--text); border:1px solid var(--border); border-radius:6px; padding:6px 10px; font-size:13px; cursor:pointer; }}
  5372. button.active {{ background:var(--accent); color:#07101e; border-color:var(--accent); font-weight:600; }}
  5373. .container {{ max-width:1580px; margin:18px auto; padding:0 20px; }}
  5374. .kpi-grid {{ display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; margin-bottom:16px; }}
  5375. .kpi-card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:12px 14px; }}
  5376. .kpi-label {{ font-size:12px; color:var(--muted); }}
  5377. .kpi-val {{ font-size:19px; font-weight:700; margin-top:4px; }}
  5378. .kpi-sub {{ font-size:12px; color:var(--muted); margin-top:2px; }}
  5379. .tabs {{ display:flex; flex-wrap:wrap; gap:8px; margin-bottom:14px; border-bottom:1px solid var(--border); padding-bottom:10px; }}
  5380. .tab-panel {{ display:none; }}
  5381. .tab-panel.active {{ display:block; }}
  5382. .card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:14px 16px; margin-bottom:16px; }}
  5383. .card-hdr {{ display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:10px; margin-bottom:10px; }}
  5384. .legend {{ display:flex; flex-wrap:wrap; gap:8px 12px; font-size:12px; color:var(--muted); margin-bottom:8px; }}
  5385. .legend-item {{ display:inline-flex; align-items:center; gap:5px; cursor:pointer; user-select:none; }}
  5386. .legend-item.off {{ opacity:0.35; text-decoration:line-through; }}
  5387. .swatch {{ width:12px; height:3px; border-radius:2px; display:inline-block; }}
  5388. .chart-wrap {{ position:relative; width:100%; height:310px; }}
  5389. .table-scroll {{ overflow-x:auto; }}
  5390. table {{ width:100%; border-collapse:collapse; font-size:12px; }}
  5391. th, td {{ padding:6px 8px; border-bottom:1px solid var(--border); text-align:left; white-space:nowrap; }}
  5392. th {{ background:var(--bg-alt); color:var(--muted); font-weight:600; position:sticky; top:0; }}
  5393. .mono {{ font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }}
  5394. .badge {{ display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; font-weight:600; }}
  5395. .badge.pass {{ background:rgba(34,197,94,0.16); color:var(--good); }}
  5396. .badge.warn {{ background:rgba(245,158,11,0.16); color:var(--warn); }}
  5397. .tooltip {{ position:fixed; pointer-events:none; background:rgba(11,16,27,0.96); color:#e6edf7; border:1px solid #38bdf8; border-radius:8px; padding:9px 11px; font-size:11.5px; line-height:1.45; z-index:999; display:none; max-width:480px; }}
  5398. </style>
  5399. </head>
  5400. <body>
  5401. <header>
  5402. <div class="hdr-title">
  5403. <h1>2026-11-14 S1 70°C 全流程耐久测试 · 逐腔室与逐位置传感器独立解析报告 (无均值)</h1>
  5404. <div class="hdr-sub" id="hdr-sub">加载中...</div>
  5405. </div>
  5406. <button type="button" id="btn-theme">切换亮/暗主题</button>
  5407. </header>
  5408. <div class="container">
  5409. <div class="kpi-grid" id="kpi-grid"></div>
  5410. <div class="tabs">
  5411. <button type="button" class="tab-btn active" data-tab="tab-w">1Hz 全周期曲线</button>
  5412. <button type="button" class="tab-btn" data-tab="tab-m">MCU 模式分段 & 失联告警</button>
  5413. <button type="button" class="tab-btn" data-tab="tab-t">MT 算法里程碑 (Test 0..19)</button>
  5414. <button type="button" class="tab-btn" data-tab="tab-s">全位置传感器范围</button>
  5415. </div>
  5416. <div id="tab-w" class="tab-panel active">
  5417. <div class="card"><div class="card-hdr"><h3>按模式缩放 (拖拽框选 / 双击复位)</h3><div class="controls" id="zoom-bar"></div></div></div>
  5418. <div class="card"><div class="card-hdr"><h3>Chart 1 · CT01..CT08 独立腔室温度曲线 (无均值)</h3></div><div class="legend" id="leg-ct"></div><div class="chart-wrap"><canvas id="c-ct"></canvas></div></div>
  5419. <div class="card"><div class="card-hdr"><h3>Chart 2 · IPMI_CPU0_A..D / CPU1_A 与 MCU_CH01..04,13 独立曲线</h3></div><div class="legend" id="leg-dimm"></div><div class="chart-wrap"><canvas id="c-dimm"></canvas></div></div>
  5420. <div class="card"><div class="card-hdr"><h3>Chart 3 · PTC / SSR1,2,4 / 风扇占空比</h3></div><div class="legend" id="leg-act"></div><div class="chart-wrap"><canvas id="c-act"></canvas></div></div>
  5421. </div>
  5422. <div id="tab-m" class="tab-panel"><div class="card"><div class="card-hdr"><h3>MCU 模式切分 (`idle` / `preheating` / `pid` / `offline`)</h3></div><div class="table-scroll" id="t-modes"></div></div></div>
  5423. <div id="tab-t" class="tab-panel"><div class="card"><div class="card-hdr"><h3>MemTest86 20 个算法里程碑逐通道统计 (`Test 0..19`)</h3></div><div class="table-scroll" id="t-tests"></div></div></div>
  5424. <div id="tab-s" class="tab-panel"><div class="card"><div class="card-hdr"><h3>全量独立位置传感器统计 (`min~max`, `起点→终点`)</h3></div><div class="table-scroll" id="t-sensors"></div></div></div>
  5425. </div>
  5426. <div class="tooltip" id="tooltip"></div>
  5427. <script id="embedded-data" type="application/json">{payload_json}</script>
  5428. <script>
  5429. (() => {{
  5430. const DATA = JSON.parse(document.getElementById('embedded-data').textContent);
  5431. const cols = DATA.series.cols, n = cols.seq.length;
  5432. let zoomStart = 0, zoomEnd = n, hoverIdx = null, dragStartIdx = null, dragCurIdx = null;
  5433. const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}}[c]));
  5434. const fmtMM = st => st ? `${{st.min}}~${{st.max}}` : '-';
  5435. const pal = ['#ef4444','#fca5a5','#f59e0b','#fcd34d','#22c55e','#86efac','#38bdf8','#a855f7','#ec4899','#14b8a6'];
  5436. const ctS = DATA.meta.active_ct_channels.map((c,i) => ({{ key:c, label:c, color:pal[i%pal.length], width:1.4 }}));
  5437. const dimmS = [...DATA.meta.active_ipmi_channels, ...DATA.meta.active_mcu_channels].map((c,i) => ({{ key:c, label:c, color:pal[i%pal.length], width:c.startsWith('IPMI')?1.6:1.2, dash:c.startsWith('MCU')?[4,2]:null }}));
  5438. const actS = ['ptc_avg_duty','ssr1_duty','ssr2_duty','ssr4_duty','fan_front_avg_duty','fan_rear_avg_duty'].filter(c=>cols[c]).map((c,i)=>({{key:c,label:c,color:pal[i%pal.length],width:1.4}}));
  5439. const enCt = new Set(ctS.map(s=>s.key)), enDimm = new Set(DATA.meta.active_ipmi_channels), enAct = new Set(actS.map(s=>s.key));
  5440. document.getElementById('hdr-sub').textContent = `S1 · ${{DATA.meta.start_ts}} → ${{DATA.meta.end_ts}} | ${{n.toLocaleString()}} 行 (${{DATA.meta.total_duration_hms}}) | MT错误: ${{DATA.meta.mt_total_errors}}`;
  5441. document.getElementById('btn-theme').onclick = () => {{ document.body.classList.toggle('light'); drawAll(); }};
  5442. document.querySelectorAll('.tab-btn').forEach(b => b.onclick = () => {{
  5443. document.querySelectorAll('.tab-btn,.tab-panel').forEach(x=>x.classList.remove('active'));
  5444. b.classList.add('active'); document.getElementById(b.dataset.tab).classList.add('active'); drawAll();
  5445. }});
  5446. const ov = DATA.overall_sensors;
  5447. document.getElementById('kpi-grid').innerHTML = `
  5448. <div class="kpi-card"><div class="kpi-label">总样本 / 时长</div><div class="kpi-val">${{n.toLocaleString()}} 行</div><div class="kpi-sub">${{DATA.meta.total_duration_hms}} · 1 Hz</div></div>
  5449. <div class="kpi-card"><div class="kpi-label">IPMI DIMM 峰值区间</div><div class="kpi-val">${{fmtMM(ov.IPMI_CPU0_A)}}°C</div><div class="kpi-sub">含后段 MCU offline 失联冲高至 96°C</div></div>
  5450. <div class="kpi-card"><div class="kpi-label">8路 CT 腔室通道</div><div class="kpi-val">CT01..CT08</div><div class="kpi-sub">全部独立记录 (无 ct_avg)</div></div>
  5451. <div class="kpi-card"><div class="kpi-label">MT 里程碑 / 错误</div><div class="kpi-val"><span class="badge pass">${{DATA.meta.mt_total_errors}} ERR</span></div><div class="kpi-sub">${{DATA.test_windows.length}} 个测试里程碑窗口</div></div>
  5452. `;
  5453. function buildLeg(id, list, set) {{
  5454. const el = document.getElementById(id); el.innerHTML = '';
  5455. list.forEach(item => {{
  5456. const sp = document.createElement('span');
  5457. sp.className = 'legend-item' + (set.has(item.key)?'':' off');
  5458. sp.innerHTML = `<span class="swatch" style="background:${{item.color}}"></span>${{esc(item.label)}}`;
  5459. sp.onclick = () => {{ if(set.has(item.key)) set.delete(item.key); else set.add(item.key); sp.classList.toggle('off'); drawAll(); }};
  5460. el.appendChild(sp);
  5461. }});
  5462. }}
  5463. function buildZoom() {{
  5464. const bar = document.getElementById('zoom-bar'); bar.innerHTML = '';
  5465. const mk = (l,a,b) => {{ const bt=document.createElement('button'); bt.textContent=l; if(zoomStart===a&&zoomEnd===b)bt.classList.add('active'); bt.onclick=()=>{{zoomStart=a;zoomEnd=b;buildZoom();drawAll();}}; bar.appendChild(bt); }};
  5466. mk(`全过程 (${{n}}s)`, 0, n);
  5467. DATA.series.mode_names.forEach((m, mi) => {{
  5468. let lo=null, hi=null;
  5469. for(let i=0;i<n;i++) if(cols.md[i]===mi){{if(lo===null)lo=i;hi=i+1;}}
  5470. if(lo!==null) mk(`${{m}} (${{hi-lo}}s)`, lo, hi);
  5471. }});
  5472. }}
  5473. function drawChart(cid, list, set) {{
  5474. const cv = document.getElementById(cid); if(!cv) return;
  5475. const rect=cv.parentElement.getBoundingClientRect(), dpr=window.devicePixelRatio||1;
  5476. const w=Math.max(320,Math.floor(rect.width)), h=Math.max(240,Math.floor(rect.height));
  5477. cv.width=w*dpr; cv.height=h*dpr; const ctx=cv.getContext('2d'); ctx.setTransform(dpr,0,0,dpr,0,0);
  5478. const sIdx=Math.max(0,zoomStart), eIdx=Math.min(n,zoomEnd), span=Math.max(1,eIdx-sIdx);
  5479. const pad={{l:48,r:16,t:12,b:24}}, pw=w-pad.l-pad.r, ph=h-pad.t-pad.b;
  5480. const cs=getComputedStyle(document.body), bCol=cs.getPropertyValue('--border').trim(), mCol=cs.getPropertyValue('--muted').trim();
  5481. let yMin=Infinity, yMax=-Infinity;
  5482. list.forEach(s=>{{if(!set.has(s.key))return; const a=cols[s.key]; for(let i=sIdx;i<eIdx;i++){{const v=a[i];if(v!=null){{if(v<yMin)yMin=v;if(v>yMax)yMax=v;}}}}}});
  5483. if(!isFinite(yMin)){{yMin=0;yMax=100;}} yMin=Math.floor(yMin-2); yMax=Math.ceil(yMax+2);
  5484. ctx.strokeStyle=bCol; ctx.font='11px sans-serif'; ctx.fillStyle=mCol;
  5485. for(let g=0;g<=4;g++){{const yy=pad.t+ph-(g/4)*ph; ctx.beginPath();ctx.moveTo(pad.l,yy);ctx.lineTo(pad.l+pw,yy);ctx.stroke(); ctx.textAlign='right';ctx.fillText((yMin+(g/4)*(yMax-yMin)).toFixed(0),pad.l-5,yy+4);}}
  5486. ctx.textAlign='center'; for(let t=0;t<=6;t++){{const i=Math.min(n-1,sIdx+Math.floor((t/6)*(span-1))); ctx.fillText(cols.ts[i]||'',pad.l+(t/6)*pw,h-6);}}
  5487. const xAt=i=>pad.l+((i-sIdx)/Math.max(1,span-1))*pw, yAt=v=>pad.t+ph-((v-yMin)/Math.max(1e-6,yMax-yMin))*ph;
  5488. const st=Math.max(1,Math.floor(span/(pw*2)));
  5489. list.forEach(s=>{{if(!set.has(s.key))return; const a=cols[s.key]; ctx.save();ctx.strokeStyle=s.color;ctx.lineWidth=s.width;if(s.dash)ctx.setLineDash(s.dash);ctx.beginPath();let ok=false;for(let i=sIdx;i<eIdx;i+=st){{const v=a[i];if(v==null){{ok=false;continue;}}const x=xAt(i),y=yAt(v);if(!ok){{ctx.moveTo(x,y);ok=true;}}else ctx.lineTo(x,y);}}ctx.stroke();ctx.restore();}});
  5490. if(hoverIdx!==null&&hoverIdx>=sIdx&&hoverIdx<eIdx){{const hx=xAt(hoverIdx);ctx.strokeStyle='rgba(255,255,255,0.45)';ctx.beginPath();ctx.moveTo(hx,pad.t);ctx.lineTo(hx,pad.t+ph);ctx.stroke();}}
  5491. }}
  5492. function attach(cid) {{
  5493. const cv=document.getElementById(cid), tip=document.getElementById('tooltip');
  5494. const idxF=ev=>{{const r=cv.getBoundingClientRect(),sI=zoomStart,eI=zoomEnd;return Math.min(n-1,sI+Math.round(Math.max(0,Math.min(1,(ev.clientX-r.left-48)/Math.max(1,r.width-64)))*Math.max(0,eI-sI-1)));}};
  5495. cv.onmousedown=ev=>{{dragStartIdx=idxF(ev);dragCurIdx=dragStartIdx;}};
  5496. cv.onmouseup=()=>{{if(dragStartIdx!==null&&dragCurIdx!==null&&Math.abs(dragCurIdx-dragStartIdx)>=5){{zoomStart=Math.min(dragStartIdx,dragCurIdx);zoomEnd=Math.max(dragStartIdx,dragCurIdx)+1;buildZoom();}}dragStartIdx=null;dragCurIdx=null;drawAll();}};
  5497. cv.ondblclick=()=>{{zoomStart=0;zoomEnd=n;buildZoom();drawAll();}};
  5498. cv.onmousemove=ev=>{{
  5499. hoverIdx=idxF(ev);if(dragStartIdx!==null)dragCurIdx=hoverIdx;drawAll();
  5500. const i=hoverIdx; tip.style.display='block'; tip.style.left=Math.min(window.innerWidth-480,ev.clientX+14)+'px'; tip.style.top=Math.min(window.innerHeight-280,ev.clientY+14)+'px';
  5501. tip.innerHTML=`<div><b>#${{cols.seq[i]}}</b> · ${{esc(cols.ts[i])}} (${{cols.t[i]}}s) · mode:<b>${{esc(DATA.series.mode_names[cols.md[i]])}}</b></div>`+
  5502. `<div class="mono">CT01..08: ${{DATA.meta.active_ct_channels.map(c=>cols[c]?.[i]??'-').join(' / ')}}</div>`+
  5503. `<div class="mono">IPMI: ${{DATA.meta.active_ipmi_channels.map(c=>c.replace('IPMI_','')+':'+(cols[c]?.[i]??'-')).join(' ')}}</div>`+
  5504. `<div class="mono">MCU: ${{DATA.meta.active_mcu_channels.map(c=>c.replace('MCU_','')+':'+(cols[c]?.[i]??'-')).join(' ')}}</div>`+
  5505. `<div class="mono">PTC:${{cols.ptc_avg_duty?.[i]??'-'}}% SSR1/2/4:${{cols.ssr1_duty?.[i]??'-'}}/${{cols.ssr2_duty?.[i]??'-'}}/${{cols.ssr4_duty?.[i]??'-'}}% FanF/R:${{cols.fan_front_avg_duty?.[i]??'-'}}/${{cols.fan_rear_avg_duty?.[i]??'-'}}%</div>`;
  5506. }};
  5507. cv.onmouseleave=()=>{{hoverIdx=null;tip.style.display='none';drawAll();}};
  5508. }}
  5509. function drawAll(){{drawChart('c-ct',ctS,enCt);drawChart('c-dimm',dimmS,enDimm);drawChart('c-act',actS,enAct);}}
  5510. function renderTables(){{
  5511. let hm=`<table><thead><tr><th>MCU模式</th><th>样本(s)</th><th>时间</th>${{DATA.meta.active_ipmi_channels.map(c=>`<th>${{esc(c.replace('IPMI_',''))}}</th>`).join('')}}${{DATA.meta.active_ct_channels.map(c=>`<th>${{c}}</th>`).join('')}}</tr></thead><tbody>`;
  5512. DATA.mode_transitions.forEach(m=>{{
  5513. hm+=`<tr><td><b>${{esc(m.mode)}}</b></td><td class="mono">${{m.rows}}</td><td class="mono">${{esc(m.start_ts.slice(11,19))}}→${{esc(m.end_ts.slice(11,19))}}</td>`+
  5514. DATA.meta.active_ipmi_channels.map(c=>`<td class="mono">${{fmtMM(m.sensors[c])}}</td>`).join('')+
  5515. DATA.meta.active_ct_channels.map(c=>`<td class="mono">${{fmtMM(m.sensors[c])}}</td>`).join('')+`</tr>`;
  5516. }});
  5517. document.getElementById('t-modes').innerHTML=hm+'</tbody></table>';
  5518. let ht=`<table><thead><tr><th>Test</th><th>时长</th><th>CSV样本</th><th>MT DIMM0..4</th>${{DATA.meta.active_ipmi_channels.map(c=>`<th>${{esc(c.replace('IPMI_',''))}}</th>`).join('')}}<th>错误</th></tr></thead><tbody>`;
  5519. DATA.test_windows.forEach(tw=>{{
  5520. const mtd=Object.entries(tw.mt_dimm_stats).map(([k,v])=>`${{k}}:${{v.min}}~${{v.max}}`).join(' ');
  5521. ht+=`<tr><td><b>P${{tw.pass_num}} ${{esc(tw.test_desc)}}</b></td><td class="mono">${{tw.duration_s??'-'}}</td><td class="mono">${{tw.csv_rows}}</td><td class="mono">${{esc(mtd||'-')}}</td>`+
  5522. DATA.meta.active_ipmi_channels.map(c=>`<td class="mono">${{fmtMM((tw.sensors||{{}})[c])}}</td>`).join('')+`<td class="mono">${{tw.cum_errors}}</td></tr>`;
  5523. }});
  5524. document.getElementById('t-tests').innerHTML=ht+'</tbody></table>';
  5525. let hs=`<table><thead><tr><th>传感器通道</th><th>样本数</th><th>最小值</th><th>最大值</th><th>起点</th><th>终点</th></tr></thead><tbody>`;
  5526. Object.entries(ov).forEach(([k,st])=>{{if(!st)return; hs+=`<tr><td class="mono"><b>${{esc(k)}}</b></td><td class="mono">${{st.count}}</td><td class="mono">${{st.min}}</td><td class="mono">${{st.max}}</td><td class="mono">${{st.start}}</td><td class="mono">${{st.end}}</td></tr>`;}});
  5527. document.getElementById('t-sensors').innerHTML=hs+'</tbody></table>';
  5528. }}
  5529. buildLeg('leg-ct',ctS,enCt);buildLeg('leg-dimm',dimmS,enDimm);buildLeg('leg-act',actS,enAct);buildZoom();attach('c-ct');attach('c-dimm');attach('c-act');window.addEventListener('resize',drawAll);drawAll();renderTables();
  5530. }})();
  5531. </script>
  5532. </body>
  5533. </html>"""
  5534. def parse_bmc_mt_run(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
  5535. p = Path(input_path).resolve()
  5536. mile = json.loads((p / "milestones.json").read_text(encoding="utf-8"))
  5537. sdr_text = (p / "ipmi_sdr_temperature.txt").read_text(encoding="utf-8", errors="replace") if (p / "ipmi_sdr_temperature.txt").is_file() else ""
  5538. bios_text = (p / "bios_serial_clean_timestamped.log").read_text(encoding="utf-8", errors="replace") if (p / "bios_serial_clean_timestamped.log").is_file() else ""
  5539. # Parse ipmi_sdr_temperature.txt individual rows
  5540. sdr_sensors: list[dict[str, Any]] = []
  5541. for ln in sdr_text.splitlines():
  5542. parts = [x.strip() for x in ln.split("|")]
  5543. if len(parts) >= 5:
  5544. val_m = re.match(r"^(-?[0-9.]+)\s+degrees\s+C", parts[4])
  5545. sdr_sensors.append({
  5546. "name": parts[0],
  5547. "id": parts[1],
  5548. "status": parts[2],
  5549. "entity": parts[3],
  5550. "reading_raw": parts[4],
  5551. "temp_c": float(val_m.group(1)) if val_m else None,
  5552. })
  5553. # Parse [HD_Sensor] and [HD_RMTSensor] from bios_serial_clean_timestamped.log
  5554. bios_sensors: list[dict[str, Any]] = []
  5555. hd_rx = re.compile(r"^\[([^\s|]+)\s*\|\s*\+\s*([0-9.]+)s\]\s*\[(HD_Sensor|HD_RMTSensor)\]([^:]+):([0-9.]+)")
  5556. for ln in bios_text.splitlines():
  5557. m = hd_rx.match(ln.strip())
  5558. if m:
  5559. bios_sensors.append({
  5560. "timestamp_utc": m.group(1),
  5561. "elapsed_s": float(m.group(2)),
  5562. "stage_tag": m.group(3),
  5563. "dimm_loc": m.group(4),
  5564. "temp_c": float(m.group(5)),
  5565. })
  5566. # Parse MemTest86 screen snapshots for CPU temp, speed, test progress, errors
  5567. snaps: list[dict[str, Any]] = []
  5568. snap_path = p / "mt86_screen_snapshots.jsonl"
  5569. if snap_path.is_file():
  5570. for ln in snap_path.read_text(encoding="utf-8", errors="replace").splitlines():
  5571. if not ln.strip():
  5572. continue
  5573. obj = json.loads(ln)
  5574. txt = "\n".join(obj.get("lines") or [])
  5575. cpu_m = re.search(r"Clk/Temp:\s*(\d+)\s*MHz(?:\s*/\s*(\d+)C)?", txt)
  5576. test_m = re.search(r"Test\s+(\d+)\s+\[([^\]]+)\]", txt)
  5577. pct_m = re.search(r"Test\s+(\d+)%", txt)
  5578. pass_m = re.search(r"Pass\s+(\d+)%", txt)
  5579. err_m = re.search(r"Errors:\s*(\d+)", txt)
  5580. snaps.append({
  5581. "elapsed_s": obj.get("elapsed_s"),
  5582. "reason": obj.get("reason"),
  5583. "clk_mhz": int(cpu_m.group(1)) if cpu_m else None,
  5584. "cpu_temp_c": int(cpu_m.group(2)) if (cpu_m and cpu_m.group(2)) else None,
  5585. "test_num": int(test_m.group(1)) if test_m else None,
  5586. "test_name": test_m.group(2) if test_m else None,
  5587. "test_pct": int(pct_m.group(1)) if pct_m else None,
  5588. "pass_pct": int(pass_m.group(1)) if pass_m else None,
  5589. "errors": int(err_m.group(1)) if err_m else None,
  5590. })
  5591. parsed = {
  5592. "parser_version": PARSER_VERSION,
  5593. "mode": "bmc_mt_run_snapshot_and_milestones_no_means",
  5594. "parsed_utc": datetime.now(timezone.utc).isoformat(),
  5595. "input_path": str(p),
  5596. "source_kind": "bmc_mt_run",
  5597. "bmc_host": mile.get("bmc_ip"),
  5598. "total_1hz_rows": len(snaps),
  5599. "t0_power_on_utc": mile.get("t0_power_on_utc"),
  5600. "power_action": mile.get("power_action"),
  5601. "milestones": mile.get("milestones") or [],
  5602. "bios_dimm_sensors": bios_sensors,
  5603. "ipmi_sdr_sensors": sdr_sensors,
  5604. "test1_progress": mile.get("mt86_test1_progress") or [],
  5605. "snapshots_count": len(snaps),
  5606. "max_errors": max((s["errors"] or 0 for s in snaps), default=0),
  5607. }
  5608. return parsed, {"snaps": snaps}
  5609. def render_bmc_mt_run_markdown(parsed: dict[str, Any]) -> str:
  5610. lines = [
  5611. "# 2026-11-05 BMC 166 开机 + MemTest86 Test 0/1 里程碑与逐传感器快照报告",
  5612. "",
  5613. f"- **BMC IP**:`{parsed['bmc_host']}` · **开机动作**:`{parsed['power_action']}` · **T0**:`{parsed['t0_power_on_utc']}`",
  5614. f"- **屏显快照**:`{parsed['snapshots_count']}` 条 · **累计错误**:`{parsed['max_errors']}`",
  5615. "",
  5616. "## 1. BIOS MRC 阶段逐 DIMM 传感器读数 (`[HD_Sensor]` → `[HD_RMTSensor]`)",
  5617. "",
  5618. "| 阶段标签 | DIMM 位置 | 耗时 (s) | 温度 (°C) |",
  5619. "|---|---|---:|---:|",
  5620. ]
  5621. for b in parsed["bios_dimm_sensors"]:
  5622. lines.append(f"| `{b['stage_tag']}` | `{b['dimm_loc']}` | `{b['elapsed_s']}` | `{b['temp_c']}°C` |")
  5623. lines.extend(["", "## 2. IPMI SDR 全量独立传感器快照 (`ipmi_sdr_temperature.txt`)", "", "| 传感器 | ID | 状态 | 读数 |", "|---|---|---|---|"])
  5624. for s in parsed["ipmi_sdr_sensors"]:
  5625. if s["temp_c"] is not None:
  5626. lines.append(f"| `{s['name']}` | `{s['id']}` | `{s['status']}` | `{s['temp_c']}°C` |")
  5627. lines.extend(["", "## 3. 启动至 MT86 全里程碑时间轴", "", "| 里程碑 | 耗时 (s) | 说明 |", "|---|---:|---|"])
  5628. for m in parsed["milestones"]:
  5629. lines.append(f"| `{m['key']}` | `{m['elapsed_s']}` | {m['detail']} |")
  5630. return "\n".join(lines) + "\n"
  5631. def render_bmc_mt_run_html(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
  5632. payload = {**parsed, "snaps": artifacts["snaps"]}
  5633. payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
  5634. return f"""<!DOCTYPE html>
  5635. <html lang="zh-CN">
  5636. <head>
  5637. <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
  5638. <title>2026-11-05 BMC 166 开机 + MT86 里程碑与传感器快照报告</title>
  5639. <style>
  5640. :root {{ --bg:#0b101b; --bg-card:#121a2b; --bg-alt:#182338; --text:#e6edf7; --muted:#93a4be; --border:#253554; --accent:#38bdf8; --good:#22c55e; }}
  5641. * {{ box-sizing:border-box; margin:0; padding:0; }}
  5642. body {{ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif; background:var(--bg); color:var(--text); line-height:1.5; padding-bottom:48px; }}
  5643. header {{ background:var(--bg-card); border-bottom:1px solid var(--border); padding:14px 24px; }}
  5644. .container {{ max-width:1460px; margin:18px auto; padding:0 20px; }}
  5645. .kpi-grid {{ display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; margin-bottom:16px; }}
  5646. .kpi-card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:12px 14px; }}
  5647. .kpi-label {{ font-size:12px; color:var(--muted); }}
  5648. .kpi-val {{ font-size:20px; font-weight:700; margin-top:4px; }}
  5649. .card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:14px 16px; margin-bottom:16px; }}
  5650. .card h3 {{ font-size:15px; margin-bottom:10px; }}
  5651. .chart-wrap {{ width:100%; height:260px; }}
  5652. .table-scroll {{ overflow-x:auto; }}
  5653. table {{ width:100%; border-collapse:collapse; font-size:12.5px; }}
  5654. th,td {{ padding:6px 8px; border-bottom:1px solid var(--border); text-align:left; }}
  5655. th {{ background:var(--bg-alt); color:var(--muted); }}
  5656. .mono {{ font-family:ui-monospace,Consolas,monospace; }}
  5657. </style>
  5658. </head>
  5659. <body>
  5660. <header><h1>2026-11-05 BMC 166 开机 + MemTest86 Test 0/1 里程碑与逐传感器快照报告</h1></header>
  5661. <div class="container">
  5662. <div class="kpi-grid" id="kpis"></div>
  5663. <div class="card"><h3>Test 1 进度与 MT86 CPU 温度实时曲线 (`mt86_screen_snapshots.jsonl`)</h3><div class="chart-wrap"><canvas id="c-prog"></canvas></div></div>
  5664. <div class="card"><h3>BIOS MRC 阶段逐插槽传感器 (`[HD_Sensor]` / `[HD_RMTSensor]`)</h3><div class="table-scroll" id="t-bios"></div></div>
  5665. <div class="card"><h3>IPMI SDR 全部独立传感器快照 (`ipmi_sdr_temperature.txt`)</h3><div class="table-scroll" id="t-sdr"></div></div>
  5666. <div class="card"><h3>全流程 25 项阶段里程碑 (`milestones.json`)</h3><div class="table-scroll" id="t-mile"></div></div>
  5667. </div>
  5668. <script id="embedded-data" type="application/json">{payload_json}</script>
  5669. <script>
  5670. (() => {{
  5671. const D = JSON.parse(document.getElementById('embedded-data').textContent);
  5672. const esc = v => String(v??'').replace(/[&<>"']/g,c=>({{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}}[c]));
  5673. const activeSdr = D.ipmi_sdr_sensors.filter(s => s.temp_c !== null);
  5674. document.getElementById('kpis').innerHTML = `
  5675. <div class="kpi-card"><div class="kpi-label">BMC 主机 / 开机时间</div><div class="kpi-val">${{esc(D.bmc_host)}}</div><div class="kpi-sub">${{esc(D.t0_power_on_utc)}}</div></div>
  5676. <div class="kpi-card"><div class="kpi-label">屏显快照数 / 报错</div><div class="kpi-val">${{D.snapshots_count.toLocaleString()}}</div><div class="kpi-sub">累计 Errors: ${{D.max_errors}}</div></div>
  5677. <div class="kpi-card"><div class="kpi-label">BIOS MRC DIMM 传感器</div><div class="kpi-val">${{D.bios_dimm_sensors.length}} 条记录</div><div class="kpi-sub">[HD_Sensor] 21.5~22.5°C → [HD_RMTSensor] 33~33.5°C</div></div>
  5678. <div class="kpi-card"><div class="kpi-label">IPMI 有效温度通道</div><div class="kpi-val">${{activeSdr.length}} 路</div><div class="kpi-sub">单次快照 (无连续 1Hz 时序)</div></div>
  5679. `;
  5680. // Draw Test 1 progress & CPU temp
  5681. const cv = document.getElementById('c-prog'), rect = cv.parentElement.getBoundingClientRect(), dpr = window.devicePixelRatio||1;
  5682. const w = Math.max(320,Math.floor(rect.width)), h = Math.max(220,Math.floor(rect.height));
  5683. cv.width=w*dpr; cv.height=h*dpr; const ctx=cv.getContext('2d'); ctx.setTransform(dpr,0,0,dpr,0,0);
  5684. const pts = D.snaps.filter(s => s.elapsed_s != null && s.test_pct != null);
  5685. if (pts.length) {{
  5686. const pad={{l:44,r:44,t:16,b:24}}, pw=w-pad.l-pad.r, ph=h-pad.t-pad.b;
  5687. const t0=pts[0].elapsed_s, t1=Math.max(t0+1,pts[pts.length-1].elapsed_s);
  5688. const xAt=t=>pad.l+((t-t0)/(t1-t0))*pw, yPct=v=>pad.t+ph-(v/100)*ph;
  5689. ctx.strokeStyle='#253554'; ctx.font='11px sans-serif'; ctx.fillStyle='#93a4be';
  5690. for(let g=0;g<=4;g++){{const yy=pad.t+ph-(g/4)*ph;ctx.beginPath();ctx.moveTo(pad.l,yy);ctx.lineTo(pad.l+pw,yy);ctx.stroke();ctx.fillText((g*25)+'%',6,yy+4);}}
  5691. ctx.strokeStyle='#38bdf8'; ctx.lineWidth=1.8; ctx.beginPath();
  5692. pts.forEach((p,idx)=>{{const x=xAt(p.elapsed_s),y=yPct(p.test_pct); if(idx===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);}});
  5693. ctx.stroke();
  5694. }}
  5695. document.getElementById('t-bios').innerHTML = `<table><thead><tr><th>阶段标签</th><th>DIMM 位置</th><th>时间(UTC)</th><th>耗时(s)</th><th>温度</th></tr></thead><tbody>`+
  5696. D.bios_dimm_sensors.map(b=>`<tr><td class="mono">${{esc(b.stage_tag)}}</td><td class="mono">${{esc(b.dimm_loc)}}</td><td class="mono">${{esc(b.timestamp_utc)}}</td><td class="mono">${{b.elapsed_s}}</td><td class="mono"><b>${{b.temp_c}}°C</b></td></tr>`).join('')+'</tbody></table>';
  5697. document.getElementById('t-sdr').innerHTML = `<table><thead><tr><th>传感器名称</th><th>ID</th><th>状态</th><th>实测读数</th></tr></thead><tbody>`+
  5698. D.ipmi_sdr_sensors.map(s=>`<tr><td class="mono"><b>${{esc(s.name)}}</b></td><td class="mono">${{esc(s.id)}}</td><td>${{esc(s.status)}}</td><td class="mono">${{esc(s.reading_raw)}}</td></tr>`).join('')+'</tbody></table>';
  5699. document.getElementById('t-mile').innerHTML = `<table><thead><tr><th>里程碑</th><th>耗时(s)</th><th>时间(UTC)</th><th>详情</th></tr></thead><tbody>`+
  5700. D.milestones.map(m=>`<tr><td class="mono"><b>${{esc(m.key)}}</b></td><td class="mono">${{m.elapsed_s}}</td><td class="mono">${{esc(m.timestamp_utc)}}</td><td>${{esc(m.detail)}}</td></tr>`).join('')+'</tbody></table>';
  5701. }})();
  5702. </script>
  5703. </body></html>"""
  5704. def _detect_input_kind(input_path: Path) -> str:
  5705. if input_path.is_file():
  5706. name = input_path.name.lower()
  5707. if "endurance" in name and name.endswith(".csv"):
  5708. return "thermal_endurance"
  5709. if name.endswith((".csv", ".jsonl")):
  5710. return "thermal_campaign"
  5711. return "thermal_mt_results"
  5712. if input_path.is_dir():
  5713. if (input_path / "thermal_campaign_samples.jsonl").is_file() or (input_path / "thermal_campaign_timeseries.csv").is_file():
  5714. return "thermal_campaign"
  5715. if any(input_path.glob("thermal_*_Endurance.csv")):
  5716. return "thermal_endurance"
  5717. if (input_path / "milestones.json").is_file() and (input_path / "mt86_screen_snapshots.jsonl").is_file():
  5718. return "bmc_mt_run"
  5719. return "thermal_mt_results"
  5720. def run_parse_pipeline(
  5721. input_path: Path,
  5722. out_dir: Path | None = None,
  5723. *,
  5724. json_path: Path | None = None,
  5725. md_path: Path | None = None,
  5726. html_path: Path | None = None,
  5727. clean_csv_dir: Path | None = None,
  5728. ) -> dict[str, Any]:
  5729. input_path = Path(input_path).resolve()
  5730. if out_dir is None:
  5731. if input_path.is_file():
  5732. out_dir = input_path.parent / f"{input_path.stem}_parsed"
  5733. else:
  5734. out_dir = input_path / "parsed_output"
  5735. out_dir = out_dir.resolve()
  5736. out_dir.mkdir(parents=True, exist_ok=True)
  5737. kind = _detect_input_kind(input_path)
  5738. if kind == "thermal_campaign":
  5739. parsed, artifacts = parse_thermal_campaign(input_path)
  5740. md_text = render_campaign_markdown_report(parsed)
  5741. html_text = render_campaign_html_dashboard(parsed, artifacts)
  5742. elif kind == "thermal_endurance":
  5743. parsed, artifacts = parse_thermal_endurance(input_path)
  5744. md_text = render_endurance_markdown_report(parsed)
  5745. html_text = render_endurance_html_dashboard(parsed, artifacts)
  5746. elif kind == "bmc_mt_run":
  5747. parsed, artifacts = parse_bmc_mt_run(input_path)
  5748. md_text = render_bmc_mt_run_markdown(parsed)
  5749. html_text = render_bmc_mt_run_html(parsed, artifacts)
  5750. else:
  5751. parsed, artifacts = parse_bundle(input_path)
  5752. md_text = render_markdown_report(parsed)
  5753. html_text = render_html_dashboard(parsed, artifacts)
  5754. j_out = json_path or (out_dir / "PARSED_METRICS.json")
  5755. j_out.parent.mkdir(parents=True, exist_ok=True)
  5756. j_out.write_text(json.dumps(parsed, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
  5757. outputs: dict[str, Any] = {"json": str(j_out)}
  5758. m_out = md_path or (out_dir / "PARSED_REPORT.md")
  5759. m_out.parent.mkdir(parents=True, exist_ok=True)
  5760. m_out.write_text(md_text, encoding="utf-8")
  5761. outputs["md"] = str(m_out)
  5762. h_out = html_path or (out_dir / "PARSED_DASHBOARD.html")
  5763. h_out.parent.mkdir(parents=True, exist_ok=True)
  5764. h_out.write_text(html_text, encoding="utf-8")
  5765. outputs["html"] = str(h_out)
  5766. if clean_csv_dir is not None:
  5767. if kind == "thermal_campaign":
  5768. written = export_campaign_clean_csv(parsed, artifacts, clean_csv_dir)
  5769. elif kind == "thermal_mt_results":
  5770. written = export_clean_csvs(parsed, artifacts, clean_csv_dir)
  5771. else:
  5772. written = []
  5773. outputs["clean_csvs"] = [str(p) for p in written]
  5774. return {"parsed": parsed, "outputs": outputs, "out_dir": str(out_dir)}
  5775. def launch_gui(initial_input: str = "") -> int:
  5776. import tkinter as tk
  5777. from tkinter import filedialog, messagebox, ttk
  5778. root = tk.Tk()
  5779. root.title("Thermal + MT Results 逐传感器解析工具")
  5780. root.geometry("780x540")
  5781. frm = ttk.Frame(root, padding=14)
  5782. frm.pack(fill="both", expand=True)
  5783. in_var = tk.StringVar(value=initial_input)
  5784. out_var = tk.StringVar(value="")
  5785. export_csv_var = tk.BooleanVar(value=True)
  5786. last_outputs: dict[str, Any] = {}
  5787. def pick_dir() -> None:
  5788. p = filedialog.askdirectory(title="选择 thermal_mt_results / thermal_study 目录")
  5789. if p:
  5790. in_var.set(p)
  5791. if not out_var.get():
  5792. out_var.set(str(Path(p) / "parsed_output"))
  5793. def pick_file() -> None:
  5794. p = filedialog.askopenfilename(
  5795. title="选择 ZIP / CSV / JSONL 文件",
  5796. filetypes=[("Supported", "*.zip *.csv *.jsonl"), ("All files", "*.*")],
  5797. )
  5798. if p:
  5799. in_var.set(p)
  5800. if not out_var.get():
  5801. pp = Path(p)
  5802. out_var.set(str(pp.parent / f"{pp.stem}_parsed"))
  5803. def pick_out() -> None:
  5804. p = filedialog.askdirectory(title="选择输出目录")
  5805. if p:
  5806. out_var.set(p)
  5807. row0 = ttk.Frame(frm)
  5808. row0.pack(fill="x", pady=4)
  5809. ttk.Label(row0, text="输入路径:", width=12).pack(side="left")
  5810. ttk.Entry(row0, textvariable=in_var).pack(side="left", fill="x", expand=True, padx=4)
  5811. ttk.Button(row0, text="选目录", command=pick_dir).pack(side="left", padx=2)
  5812. ttk.Button(row0, text="选文件", command=pick_file).pack(side="left")
  5813. row1 = ttk.Frame(frm)
  5814. row1.pack(fill="x", pady=4)
  5815. ttk.Label(row1, text="输出目录:", width=12).pack(side="left")
  5816. ttk.Entry(row1, textvariable=out_var).pack(side="left", fill="x", expand=True, padx=4)
  5817. ttk.Button(row1, text="浏览", command=pick_out).pack(side="left")
  5818. row2 = ttk.Frame(frm)
  5819. row2.pack(fill="x", pady=6)
  5820. ttk.Checkbutton(row2, text="同时导出逐位置传感器独立 CSV", variable=export_csv_var).pack(side="left")
  5821. log_box = tk.Text(frm, height=18, wrap="word")
  5822. log_box.pack(fill="both", expand=True, pady=8)
  5823. def log(msg: str) -> None:
  5824. log_box.insert("end", msg + "\n")
  5825. log_box.see("end")
  5826. btn_open_html = ttk.Button(
  5827. frm,
  5828. text="打开 HTML 看板",
  5829. state="disabled",
  5830. command=lambda: webbrowser.open(Path(last_outputs["html"]).as_uri()),
  5831. )
  5832. def on_run() -> None:
  5833. src = in_var.get().strip()
  5834. if not src:
  5835. messagebox.showwarning("缺少输入", "请先选择输入目录或 ZIP/CSV/JSONL 文件")
  5836. return
  5837. od = Path(out_var.get().strip()) if out_var.get().strip() else None
  5838. log(f"开始逐腔室/位置传感器解析: {src}")
  5839. run_btn.config(state="disabled")
  5840. def worker() -> None:
  5841. try:
  5842. csv_dir = (od or (Path(src) / "parsed_output")) / "clean_csv" if export_csv_var.get() else None
  5843. res = run_parse_pipeline(Path(src), od, clean_csv_dir=csv_dir)
  5844. last_outputs.clear()
  5845. last_outputs.update(res["outputs"])
  5846. p = res["parsed"]
  5847. def done_ui() -> None:
  5848. log(f"完成! 模式={p['mode']}, 总行数={p['total_1hz_rows']}")
  5849. for k, v in res["outputs"].items():
  5850. log(f" {k}: {v}")
  5851. btn_open_html.config(state="normal")
  5852. run_btn.config(state="normal")
  5853. root.after(0, done_ui)
  5854. except Exception as exc:
  5855. def err_ui() -> None:
  5856. log(f"错误: {exc}")
  5857. run_btn.config(state="normal")
  5858. messagebox.showerror("解析失败", str(exc))
  5859. root.after(0, err_ui)
  5860. threading.Thread(target=worker, daemon=True).start()
  5861. row3 = ttk.Frame(frm)
  5862. row3.pack(fill="x")
  5863. run_btn = ttk.Button(row3, text="开始解析", command=on_run)
  5864. run_btn.pack(side="left", padx=4)
  5865. btn_open_html.pack(side="left", padx=4)
  5866. root.mainloop()
  5867. return 0
  5868. def main(argv: list[str] | None = None) -> int:
  5869. ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  5870. ap.add_argument("input", nargs="?", type=Path, help="thermal_mt_results dir/zip OR unheated thermal_campaign dir/csv/jsonl")
  5871. ap.add_argument("-o", "--output-dir", type=Path, default=None, help="output directory (default: <input>/parsed_output or <stem>_parsed)")
  5872. ap.add_argument("--json", type=Path, default=None, help="explicit path for PARSED_METRICS.json")
  5873. ap.add_argument("--md", type=Path, default=None, help="explicit path for PARSED_REPORT.md")
  5874. ap.add_argument("--html", type=Path, default=None, help="explicit path for PARSED_DASHBOARD.html")
  5875. ap.add_argument("--export-clean-csv", type=Path, default=None, help="directory to export normalized per-sensor CSVs")
  5876. ap.add_argument("--open", action="store_true", help="open generated HTML dashboard in default browser")
  5877. ap.add_argument("--gui", action="store_true", help="launch Tkinter GUI")
  5878. args = ap.parse_args(argv)
  5879. if args.gui or (args.input is None and (sys.platform.startswith("win") or os.environ.get("DISPLAY"))):
  5880. return launch_gui(str(args.input or ""))
  5881. if args.input is None:
  5882. ap.print_help()
  5883. return 2
  5884. res = run_parse_pipeline(
  5885. args.input,
  5886. args.output_dir,
  5887. json_path=args.json,
  5888. md_path=args.md,
  5889. html_path=args.html,
  5890. clean_csv_dir=args.export_clean_csv,
  5891. )
  5892. parsed = res["parsed"]
  5893. brief = {
  5894. "parser_version": parsed["parser_version"],
  5895. "mode": parsed["mode"],
  5896. "input_path": parsed["input_path"],
  5897. "source_kind": parsed["source_kind"],
  5898. "total_1hz_rows": parsed["total_1hz_rows"],
  5899. "outputs": res["outputs"],
  5900. }
  5901. if parsed.get("source_kind") in ("multi_dir", "single_dir", "zip"):
  5902. brief["station_count"] = parsed["station_count"]
  5903. brief["total_mt_errors"] = parsed["total_mt_errors"]
  5904. brief["all_templates_pass"] = parsed["all_templates_pass"]
  5905. elif parsed.get("source_kind") == "thermal_campaign":
  5906. brief["runs_count"] = len(parsed.get("runs", {}))
  5907. elif parsed.get("source_kind") == "thermal_endurance":
  5908. brief["test_windows_count"] = len(parsed.get("test_windows", []))
  5909. brief["mt_total_errors"] = parsed.get("mt_total_errors")
  5910. elif parsed.get("source_kind") == "bmc_mt_run":
  5911. brief["milestones_count"] = len(parsed.get("milestones", []))
  5912. brief["bios_dimm_sensors_count"] = len(parsed.get("bios_dimm_sensors", []))
  5913. brief["ipmi_sdr_count"] = len(parsed.get("ipmi_sdr_sensors", []))
  5914. print(json.dumps(brief, ensure_ascii=False, indent=2))
  5915. if args.open:
  5916. webbrowser.open(Path(res["outputs"]["html"]).as_uri())
  5917. return 0
  5918. if __name__ == "__main__":
  5919. raise SystemExit(main())