| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395 |
- #!/usr/bin/env python3
- """Per-chamber & per-position individual sensor parser for `thermal_mt_results`.
- Zero cross-sensor averaging: reports and plots every individual chamber sensor
- (ct1_ch1_front .. ct8_ch4_rear), every active MCU BMC channel (BMC0..BMC23),
- every Redfish temperature / fan / PWM / power sensor, and every MemTest86
- console sensor independently with exact start / end / min / max values.
- Supports:
- - multi-station directories (S1_..., S2_..., S3_...)
- - single-station directories
- - `.zip` archives (flat or wrapped)
- - 115-col v1 & 117-col v2 `*_comprehensive.csv`, 34-col `*_template.csv`,
- `master_events.jsonl`, `*_console.log`, and `live_status.json`
- Outputs:
- - `PARSED_METRICS.json`: structured per-chamber & per-position metrics
- - `PARSED_REPORT.md`: Markdown report broken down by individual sensor
- - `PARSED_DASHBOARD.html`: self-contained offline interactive HTML5 dashboard
- - optional `--export-clean-csv <dir>`: unified per-sensor clean CSVs
- - optional `--gui`: Tkinter desktop launcher
- Uses Python 3 standard library only (Linux & Windows).
- """
- from __future__ import annotations
- import argparse
- import base64
- import csv
- from dataclasses import dataclass
- from datetime import datetime, timezone
- import html
- import io
- import json
- import math
- import os
- from pathlib import Path, PurePosixPath
- import re
- import statistics
- import sys
- import threading
- import webbrowser
- import zipfile
- from typing import Any
- PARSER_VERSION = "2.2.0"
- CAMPAIGN_AGGREGATE_IGNORE = {
- "cpu0_dimm_mean_c", "all_dimm_max_c", "all_dimm_min_c", "all_dimm_spread_c",
- }
- CAMPAIGN_KNOWN_SENSORS: list[tuple[str, str, str, str]] = [
- # (key, label, group, unit)
- ("DIMM_CPU0_A_Temp", "DIMM CPU0_A", "dimm_temp", "°C"),
- ("DIMM_CPU0_B_Temp", "DIMM CPU0_B", "dimm_temp", "°C"),
- ("DIMM_CPU0_C_Temp", "DIMM CPU0_C", "dimm_temp", "°C"),
- ("DIMM_CPU0_D_Temp", "DIMM CPU0_D", "dimm_temp", "°C"),
- ("DIMM_CPU1_A_Temp", "DIMM CPU1_A", "dimm_temp", "°C"),
- ("CPU0_Temp", "CPU0 温度", "cpu_temp", "°C"),
- ("CPU1_Temp", "CPU1 温度", "cpu_temp", "°C"),
- ("DDR0_Power", "DDR0 功耗", "power", "W"),
- ("DDR2_Power", "DDR2 功耗", "power", "W"),
- ("DDR0_Curr", "DDR0 电流", "electrical", "A"),
- ("DDR2_Curr", "DDR2 电流", "electrical", "A"),
- ("P12V_DDR0", "P12V DDR0 电压", "electrical", "V"),
- ("P12V_DDR2", "P12V DDR2 电压", "electrical", "V"),
- ("PVCCD_CPU0_Input_Power", "PVCCD CPU0 功耗", "power", "W"),
- ("PVCCD_CPU1_Input_Power", "PVCCD CPU1 功耗", "power", "W"),
- ("Dimm_Power_CPU0", "PECI DIMM CPU0 功耗", "power", "W"),
- ("Dimm_Power_CPU1", "PECI DIMM CPU1 功耗", "power", "W"),
- ("CPU0_Power_Avg", "PECI CPU0 功耗", "power", "W"),
- ("CPU1_Power_Avg", "PECI CPU1 功耗", "power", "W"),
- ("PSU0_PIn", "PSU0 输入功耗", "power", "W"),
- ("PSU0_POut", "PSU0 输出功耗", "power", "W"),
- ]
- TEMPLATE_HEADERS: list[str] = (
- ["序号", "计时"]
- + [f"BMC{i}" for i in range(24)]
- + ["腔1前", "腔1后", "腔2前", "腔2后", "腔3前", "腔3后", "腔4前", "腔4后"]
- )
- CHAMBER_SENSORS: list[tuple[str, str, str, str]] = [
- ("ct1_ch1_front", "腔1前", "ch1", "front"),
- ("ct2_ch1_rear", "腔1后", "ch1", "rear"),
- ("ct3_ch2_front", "腔2前", "ch2", "front"),
- ("ct4_ch2_rear", "腔2后", "ch2", "rear"),
- ("ct5_ch3_front", "腔3前", "ch3", "front"),
- ("ct6_ch3_rear", "腔3后", "ch3", "rear"),
- ("ct7_ch4_front", "腔4前", "ch4", "front"),
- ("ct8_ch4_rear", "腔4后", "ch4", "rear"),
- ]
- CHAMBER_PAIRS: list[tuple[str, str, str, str]] = [
- ("ch1", "腔1", "ct1_ch1_front", "ct2_ch1_rear"),
- ("ch2", "腔2", "ct3_ch2_front", "ct4_ch2_rear"),
- ("ch3", "腔3", "ct5_ch3_front", "ct6_ch3_rear"),
- ("ch4", "腔4", "ct7_ch4_front", "ct8_ch4_rear"),
- ]
- REDFISH_TEMP_SENSORS: list[tuple[str, str]] = [
- ("rf_dimm_cpu0_a_c", "RF DIMM CPU0_A"),
- ("rf_dimm_cpu1_a_c", "RF DIMM CPU1_A"),
- ("rf_cpu0_c", "RF CPU0"),
- ("rf_cpu1_c", "RF CPU1"),
- ("rf_mb_c", "RF 主板 MB"),
- ("rf_psu0_c", "RF 电源 PSU0"),
- ("rf_pvccin_cpu0_c", "RF PVCCIN CPU0"),
- ("rf_pvccin_cpu1_c", "RF PVCCIN CPU1"),
- ("rf_pvccfa_cpu0_c", "RF PVCCFA CPU0"),
- ("rf_pvccfa_cpu1_c", "RF PVCCFA CPU1"),
- ("rf_pvccd_cpu0_c", "RF PVCCD CPU0"),
- ("rf_pvccd_cpu1_c", "RF PVCCD CPU1"),
- ]
- MT_CONSOLE_TEMP_SENSORS: list[tuple[str, str]] = [
- ("mt_spd_dimm0_c", "MT SPD DIMM0"),
- ("mt_spd_dimm1_c", "MT SPD DIMM1"),
- ("mt_cpu_c", "MT CPU"),
- ]
- POWER_RAIL_SENSORS: list[tuple[str, str]] = [
- ("rf_total_power_w", "整机功耗(W)"),
- ("rf_psu0_pin_w", "PSU0输入(W)"),
- ("rf_psu0_pout_w", "PSU0输出(W)"),
- ("rf_psu0_iin_a", "PSU0输入电流(A)"),
- ("rf_psu0_iout_a", "PSU0输出电流(A)"),
- ("rf_ddr0_power_w", "DDR0功耗(W)"),
- ("rf_ddr1_power_w", "DDR1功耗(W)"),
- ("rf_ddr2_power_w", "DDR2功耗(W)"),
- ("rf_ddr3_power_w", "DDR3功耗(W)"),
- ("rf_dimm_power_cpu0_w", "CPU0 DIMM功耗(W)"),
- ("rf_dimm_power_cpu1_w", "CPU1 DIMM功耗(W)"),
- ("rf_cpu0_power_avg_w", "CPU0功耗(W)"),
- ("rf_cpu1_power_avg_w", "CPU1功耗(W)"),
- ]
- FAN_ACTUATOR_SENSORS: list[tuple[str, str]] = [
- ("cmd_ptc_pct", "罩PTC(%)"),
- ("cmd_fan_front_pct", "罩前风扇(%)"),
- ("cmd_fan_rear_pct", "罩后风扇(%)"),
- ("cmd_ssr_pct", "罩SSR(%)"),
- ("rf_fan1_rpm", "FAN1(RPM)"),
- ("rf_fan2_rpm", "FAN2(RPM)"),
- ("rf_fan3_rpm", "FAN3(RPM)"),
- ("rf_fan4_rpm", "FAN4(RPM)"),
- ("rf_fan5_rpm", "FAN5(RPM)"),
- ("rf_pwm1_pct", "PWM1(%)"),
- ("rf_pwm2_pct", "PWM2(%)"),
- ("rf_pwm3_pct", "PWM3(%)"),
- ("rf_pwm4_pct", "PWM4(%)"),
- ("rf_pwm5_pct", "PWM5(%)"),
- ]
- CANONICAL_MT_NAMES: dict[int, str] = {
- 0: "Test 0 [Address test, walking ones, 1 CPU]",
- 1: "Test 1 [Address test, own address, 1 CPU]",
- 2: "Test 2 [Address test, own address]",
- 3: "Test 3 [Moving inversions, ones & zeroes]",
- 4: "Test 4 [Moving inversions, 8-bit pattern]",
- 5: "Test 5 [Moving inversions, random pattern]",
- 6: "Test 6 [Block move, 64-byte blocks]",
- 7: "Test 7 [Moving inversions, 32-bit pattern]",
- 8: "Test 8 [Random number sequence]",
- 9: "Test 9 [Modulo 20, ones & zeroes]",
- 10: "Test 10 [Bit fade test, 2 patterns]",
- 11: "Test 11 [Random number sequence, 64-bit]",
- 12: "Test 12 [Random number sequence, 128-bit]",
- 13: "Test 13 [Hammer test]",
- 14: "Test 14 [DMA test (experimental)]",
- 15: "Test 15 [March C algorithm]",
- 16: "Test 16 [Galloping Pattern (GALPAT)]",
- 17: "Test 17 [Galloping Pattern (LINEAR)]",
- 18: "Test 18 [Galloping Pattern (RANDOMADDRESS)]",
- 19: "Test 19 [Galloping Pattern (BANKJUMP)]",
- 20: "Test 20 [Galloping Pattern (VICTIM)]",
- 21: "Test 21 [Galloping Pattern (MARCHIC)]",
- 22: "Test 22 [Galloping Pattern (MARCHSSE)]",
- 23: "Test 23 [Galloping Pattern (BUTTERFLY)]",
- 24: "Test 24 [March SS+ algorithm]",
- 25: "Test 25 [StressApp memory stress test]",
- }
- ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
- ANSI_OTHER_RE = re.compile(r"\x1b[@-Z\\-_]")
- TEST_PREFIX_RE = re.compile(r"^Test\s+(\d+)\b")
- RUNNING_TEST_RE = re.compile(r"Running test #(\d+)\s*\((.+)\)\s*$")
- TEST_EXEC_RE = re.compile(
- r"MtSupportRunAllTests\s*-\s*Test execution time:\s*([0-9.]+)s\s*"
- r"\(Test\s+(\d+)\s+cumulative error count:\s*(\d+),\s*buffer full count:\s*(\d+)\)"
- )
- RANGE_WARN_RE = re.compile(
- 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\)"
- )
- CONSOLE_DIMM_TEMP_RE = re.compile(r"^DIMM(\d+)\s+temperature:\s*([0-9.]+)C$")
- CONSOLE_CPU_TEMP_RE = re.compile(r"^Current CPU temperature:\s*([0-9.]+)C$")
- MEM_TIMINGS_RE = re.compile(r"Current mem timings:\s*(.+)$")
- SYS_BIOS_RE = re.compile(r"\[SYS_BIOS\](.+)$")
- HS_DRAM_RE = re.compile(r"\[(HS|HD)_DRAM\](.+)$")
- HS_CPU_RE = re.compile(r"\[(HS|HD)_CPU\]Processor Information Name:\s*(.+)$")
- TOTAL_MEM_RE = re.compile(r"Total Memory:\s*(.+)$")
- SMBIOS_BIOS_RE = re.compile(r"SMBIOS BIOS INFO\s+(.+)$")
- SMBIOS_SYS_RE = re.compile(r"SMBIOS SYSTEM INFO\s+(.+)$")
- SMBIOS_SLOT_SIZE_RE = re.compile(r"^\[Slot\s+(\d+)\].*?\bSize:\s*(-?\d+).*?\bSpeed:\s*(\d+)")
- SMBIOS_SLOT_LOC_RE = re.compile(
- r"^\[Slot\s+(\d+)\]\s*DeviceLocator:\s*([^,]+),\s*BankLocator:\s*([^,]+),\s*"
- r"Manufacturer:\s*([^,]*),\s*S/N:\s*([^,]*),\s*AssetTag:\s*([^,]*),\s*PartNumber:\s*(.*)$"
- )
- def bmc_slot_label(idx: int) -> str:
- cpu = 0 if idx < 12 else 1
- ch = chr(ord("A") + (idx % 12))
- return f"BMC{idx} (CPU{cpu}_{ch})"
- def strip_ansi(text: str) -> str:
- text = ANSI_CSI_RE.sub("", text)
- return ANSI_OTHER_RE.sub("", text)
- def normalize_algorithm_name(raw: str, console_map: dict[int, str] | None = None) -> str:
- s = (raw or "").strip()
- if not s:
- return ""
- m = TEST_PREFIX_RE.match(s)
- if m:
- tnum = int(m.group(1))
- if console_map and tnum in console_map:
- return console_map[tnum]
- if s.count("(") > s.count(")") or s.count("[") > s.count("]"):
- if tnum in CANONICAL_MT_NAMES:
- return CANONICAL_MT_NAMES[tnum]
- fixed = s
- if fixed.count("(") > fixed.count(")"):
- fixed += ")" * (fixed.count("(") - fixed.count(")"))
- if fixed.count("[") > fixed.count("]"):
- fixed += "]" * (fixed.count("[") - fixed.count("]"))
- return fixed
- return s
- def _to_int(val: Any) -> int | None:
- if val is None:
- return None
- s = str(val).strip()
- if not s:
- return None
- try:
- return int(s)
- except ValueError:
- try:
- return int(float(s))
- except ValueError:
- return None
- def _to_float(val: Any) -> float | None:
- if val is None:
- return None
- s = str(val).strip()
- if not s:
- return None
- try:
- f = float(s)
- if f != f:
- return None
- return f
- except ValueError:
- return None
- def _fmt_hms(seconds: float) -> str:
- sec = max(0, int(round(seconds)))
- h, rem = divmod(sec, 3600)
- m, s = divmod(rem, 60)
- return f"{h}:{m:02d}:{s:02d}"
- def _sensor_stats(vals: list[float], digits: int = 2) -> dict[str, float | int] | None:
- """Exact per-sensor statistics without computing averages."""
- if not vals:
- return None
- s_val = round(vals[0], digits)
- e_val = round(vals[-1], digits)
- mn = round(min(vals), digits)
- mx = round(max(vals), digits)
- return {
- "count": len(vals),
- "start": s_val,
- "end": e_val,
- "min": mn,
- "max": mx,
- "delta": round(e_val - s_val, digits),
- "span": round(mx - mn, digits),
- }
- def _round_opt(val: float | None, digits: int = 2) -> float | None:
- return None if val is None else round(val, digits)
- class VirtualStation:
- """Uniform read-only accessor for a station folder in a directory or zip archive."""
- def __init__(self, station_key: str, files: dict[str, tuple[str, zipfile.ZipFile | None, Path | None]]):
- self.station_key = station_key
- self._files = files
- def list_files(self, suffix: str = "") -> list[str]:
- names = sorted(self._files.keys())
- if suffix:
- names = [n for n in names if n.endswith(suffix)]
- return names
- def exists(self, name: str) -> bool:
- return name in self._files
- def read_bytes(self, name: str) -> bytes:
- member, zf, lp = self._files[name]
- if lp is not None:
- return lp.read_bytes()
- assert zf is not None
- return zf.read(member)
- def read_text(self, name: str) -> str:
- return self.read_bytes(name).decode("utf-8", errors="replace")
- @dataclass
- class BundleSource:
- input_path: Path
- source_kind: str
- stations: dict[str, VirtualStation]
- _zip_handle: zipfile.ZipFile | None = None
- def close(self) -> None:
- if self._zip_handle is not None:
- self._zip_handle.close()
- self._zip_handle = None
- def __enter__(self) -> "BundleSource":
- return self
- def __exit__(self, *args: Any) -> None:
- self.close()
- def _looks_like_station_files(names: set[str]) -> bool:
- markers = ("master_continuous_comprehensive.csv", "master_events.jsonl", "live_status.json", "master_console.log")
- if any(m in names for m in markers):
- return True
- return any(n.endswith("_comprehensive.csv") or n.endswith("_template.csv") for n in names)
- def open_bundle_source(input_path: str | Path) -> BundleSource:
- p = Path(input_path).resolve()
- if not p.exists():
- raise FileNotFoundError(f"Input path does not exist: {p}")
- if p.is_file() and p.suffix.lower() == ".zip":
- zf = zipfile.ZipFile(p, "r")
- by_dir: dict[str, dict[str, tuple[str, zipfile.ZipFile | None, Path | None]]] = {}
- root_files: dict[str, str] = {}
- for info in zf.infolist():
- if info.is_dir():
- continue
- posix = PurePosixPath(info.filename)
- parts = [part for part in posix.parts if part not in ("", ".")]
- if not parts:
- continue
- if len(parts) == 1:
- root_files[parts[0]] = info.filename
- else:
- parent = "/".join(parts[:-1])
- by_dir.setdefault(parent, {})[parts[-1]] = (info.filename, zf, None)
- stations: dict[str, VirtualStation] = {}
- if _looks_like_station_files(set(root_files.keys())):
- sfiles = {fname: (member, zf, None) for fname, member in root_files.items()}
- stations[p.stem] = VirtualStation(p.stem, sfiles)
- else:
- for dpath, fdict in sorted(by_dir.items()):
- if _looks_like_station_files(set(fdict.keys())):
- skey = PurePosixPath(dpath).name
- stations[skey] = VirtualStation(skey, fdict)
- if not stations:
- zf.close()
- raise ValueError(f"No station telemetry directories found in zip archive: {p}")
- return BundleSource(input_path=p, source_kind="zip", stations=stations, _zip_handle=zf)
- if not p.is_dir():
- raise ValueError(f"Unsupported input (expected directory or .zip): {p}")
- top_files = {c.name for c in p.iterdir() if c.is_file()}
- if _looks_like_station_files(top_files):
- sfiles = {c.name: (c.name, None, c) for c in p.iterdir() if c.is_file()}
- return BundleSource(
- input_path=p,
- source_kind="single_dir",
- stations={p.name: VirtualStation(p.name, sfiles)},
- )
- stations = {}
- for sub in sorted(c for c in p.iterdir() if c.is_dir()):
- sub_files = {f.name: (f.name, None, f) for f in sub.iterdir() if f.is_file()}
- if _looks_like_station_files(set(sub_files.keys())):
- stations[sub.name] = VirtualStation(sub.name, sub_files)
- if not stations:
- raise ValueError(f"No station subdirectories or telemetry files found in: {p}")
- return BundleSource(input_path=p, source_kind="multi_dir", stations=stations)
- def audit_template_csv(
- raw_bytes: bytes,
- comp_rows: list[dict[str, Any]] | None = None,
- ) -> dict[str, Any]:
- has_bom = raw_bytes.startswith(b"\xef\xbb\xbf")
- has_crlf = b"\r\n" in raw_bytes and b"\n" not in raw_bytes.replace(b"\r\n", b"")
- text = raw_bytes.decode("utf-8-sig", errors="replace")
- reader = csv.reader(io.StringIO(text, newline=""))
- all_rows = list(reader)
- if not all_rows:
- return {
- "rows": 0,
- "has_bom": has_bom,
- "has_crlf": has_crlf,
- "header_match": False,
- "col_count_34": False,
- "seq_contiguous": False,
- "non_zero_bmc_channels": [],
- "value_mismatches_vs_comprehensive": None,
- "status": "FAIL",
- }
- header = all_rows[0]
- data_rows = all_rows[1:]
- header_match = header == TEMPLATE_HEADERS
- col_count_34 = all(len(r) == 34 for r in data_rows)
- seq_contiguous = True
- non_zero_bmc: set[int] = set()
- parsed_rows: list[tuple[int, str, list[int], list[int]]] = []
- for idx, row in enumerate(data_rows, start=1):
- if len(row) != 34:
- seq_contiguous = False
- continue
- seq = _to_int(row[0])
- if seq != idx:
- seq_contiguous = False
- bmcs = [_to_int(row[2 + i]) or 0 for i in range(24)]
- for i, v in enumerate(bmcs):
- if v != 0:
- non_zero_bmc.add(i)
- cts = [_to_int(row[26 + i]) or 0 for i in range(8)]
- parsed_rows.append((seq if seq is not None else -1, row[1], bmcs, cts))
- mismatches: int | None = None
- if comp_rows is not None:
- mismatches = 0
- if len(comp_rows) != len(parsed_rows):
- mismatches += abs(len(comp_rows) - len(parsed_rows))
- for (seq, hms, bmcs, cts), crow in zip(parsed_rows, comp_rows):
- if seq != _to_int(crow.get("seq")) or hms != str(crow.get("elapsed_hms") or "").strip():
- mismatches += 1
- bmc_list = crow.get("bmc24_raw")
- for i in range(24):
- 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"))
- expected = 0 if (raw_v is None or raw_v == 255) else int(raw_v)
- if bmcs[i] != expected:
- mismatches += 1
- c_ct8 = crow.get("ct8")
- if not (isinstance(c_ct8, list) and len(c_ct8) == 8):
- c_ct8 = [_to_int(crow.get(col)) for col, _, _, _ in CHAMBER_SENSORS]
- for i in range(8):
- if cts[i] != (c_ct8[i] or 0):
- mismatches += 1
- ok = has_bom and has_crlf and header_match and col_count_34 and seq_contiguous and (mismatches in (None, 0))
- return {
- "rows": len(data_rows),
- "has_bom": has_bom,
- "has_crlf": has_crlf,
- "header_match": header_match,
- "col_count_34": col_count_34,
- "seq_contiguous": seq_contiguous,
- "non_zero_bmc_channels": sorted(non_zero_bmc),
- "value_mismatches_vs_comprehensive": mismatches,
- "status": "PASS" if ok else "WARN",
- }
- def parse_comprehensive_csv(
- raw_bytes: bytes,
- console_algo_map: dict[int, str] | None = None,
- ) -> dict[str, Any]:
- has_bom = raw_bytes.startswith(b"\xef\xbb\xbf")
- has_crlf = b"\r\n" in raw_bytes
- text = raw_bytes.decode("utf-8-sig", errors="replace")
- reader = csv.DictReader(io.StringIO(text, newline=""))
- fieldnames = list(reader.fieldnames or [])
- col_count = len(fieldnames)
- if col_count == 115 and "station_id" not in fieldnames:
- schema_version = "v1_115col"
- elif col_count >= 117 and "station_id" in fieldnames and "bmc_host" in fieldnames:
- schema_version = "v2_117col" if col_count == 117 else f"v2_{col_count}col"
- else:
- schema_version = f"custom_{col_count}col"
- rows: list[dict[str, Any]] = []
- seq_contiguous = True
- prev_unix: int | None = None
- gaps_over_2s: list[dict[str, Any]] = []
- dt_samples: list[int] = []
- mcu_offline_rows = 0
- cpld_lost_rows = 0
- server_power_non_on = 0
- for idx, raw in enumerate(reader, start=1):
- seq = _to_int(raw.get("seq"))
- if seq != idx:
- seq_contiguous = False
- unix_ms = _to_int(raw.get("unix_ms"))
- if unix_ms is not None and prev_unix is not None:
- dt = unix_ms - prev_unix
- dt_samples.append(dt)
- if dt > 2000:
- gaps_over_2s.append({
- "seq": seq,
- "timestamp_cst": raw.get("timestamp_cst", ""),
- "gap_ms": dt,
- })
- if unix_ms is not None:
- prev_unix = unix_ms
- mcu_online = _to_int(raw.get("mcu_online"))
- if mcu_online != 1:
- mcu_offline_rows += 1
- cpld_lost = _to_int(raw.get("mcu_cpld_lost"))
- if cpld_lost not in (None, 0):
- cpld_lost_rows += 1
- srv_pwr = (raw.get("server_power") or "").strip()
- if srv_pwr and srv_pwr != "on":
- server_power_non_on += 1
- ct8 = [_to_int(raw.get(col)) for col, _, _, _ in CHAMBER_SENSORS]
- bmc24_raw = [_to_int(raw.get(f"mcu_bmc{i}_raw")) for i in range(24)]
- raw_algo = (raw.get("active_algorithm") or "").strip()
- norm_algo = normalize_algorithm_name(raw_algo, console_algo_map)
- rec: dict[str, Any] = {
- "seq": seq,
- "timestamp_cst": (raw.get("timestamp_cst") or "").strip(),
- "unix_ms": unix_ms,
- "elapsed_s": _to_float(raw.get("elapsed_s")),
- "elapsed_hms": (raw.get("elapsed_hms") or "").strip(),
- "test_phase": (raw.get("test_phase") or "").strip(),
- "station_id": (raw.get("station_id") or "").strip(),
- "bmc_host": (raw.get("bmc_host") or "").strip(),
- "server_power": srv_pwr,
- "firmware_phase": (raw.get("firmware_phase") or "").strip(),
- "active_algorithm_raw": raw_algo,
- "active_algorithm": norm_algo,
- "mt_test_num": _to_int(raw.get("mt_test_num")),
- "mt_pass_num": _to_int(raw.get("mt_pass_num")),
- "mt_mem_range": (raw.get("mt_mem_range") or "").strip(),
- "mt_timings": (raw.get("mt_timings") or "").strip(),
- "mt_cum_errors": _to_int(raw.get("mt_cum_errors")) or 0,
- "mt_last_completed_test": (raw.get("mt_last_completed_test") or "").strip(),
- "mt_last_test_exec_s": _to_float(raw.get("mt_last_test_exec_s")),
- "mcu_online": mcu_online,
- "mcu_mode": (raw.get("mcu_mode") or "").strip(),
- "mcu_flags_hex": (raw.get("mcu_flags_hex") or "").strip(),
- "mcu_cpld_lost": cpld_lost,
- "mcu_target_c": _to_float(raw.get("mcu_target_c")),
- "mcu_f0_seq": _to_int(raw.get("mcu_f0_seq")),
- "mcu_pid_kp": _to_float(raw.get("mcu_pid_kp")),
- "mcu_pid_ki": _to_float(raw.get("mcu_pid_ki")),
- "mcu_pid_kd": _to_float(raw.get("mcu_pid_kd")),
- "ct8": ct8,
- "ct_min": _to_float(raw.get("ct_min")),
- "ct_max": _to_float(raw.get("ct_max")),
- "bmc24_raw": bmc24_raw,
- "is_residual_prelaunch": False,
- }
- for col, _, _, _ in CHAMBER_SENSORS:
- rec[col] = _to_float(raw.get(col))
- for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS:
- rec[col] = _to_float(raw.get(col))
- rows.append(rec)
- return {
- "schema_version": schema_version,
- "col_count": col_count,
- "fieldnames": fieldnames,
- "has_bom": has_bom,
- "has_crlf": has_crlf,
- "seq_contiguous": seq_contiguous,
- "dt_ms_median": round(statistics.median(dt_samples), 1) if dt_samples else None,
- "dt_ms_max": max(dt_samples) if dt_samples else None,
- "gaps_over_2s": gaps_over_2s,
- "mcu_offline_rows": mcu_offline_rows,
- "cpld_lost_rows": cpld_lost_rows,
- "server_power_non_on": server_power_non_on,
- "rows": rows,
- }
- def parse_events_jsonl(raw_text: str) -> dict[str, Any]:
- events: list[dict[str, Any]] = []
- parse_errors = 0
- for line in raw_text.splitlines():
- s = line.strip()
- if not s:
- continue
- try:
- ev = json.loads(s)
- if isinstance(ev, dict):
- events.append(ev)
- else:
- parse_errors += 1
- except json.JSONDecodeError:
- parse_errors += 1
- suite_init = None
- suite_complete = []
- antirebound_soaks = []
- preheat_handovers = []
- cooldown_outcomes = []
- mt_launches = []
- mt_algo_starts = []
- mt_algo_dones = []
- mcu_cmds = []
- phase_starts = []
- kind_counts: dict[str, int] = {}
- open_fan_round: dict[tuple[str, int], dict[str, Any]] = {}
- open_soak_round: dict[tuple[str, int], dict[str, Any]] = {}
- for ev in events:
- kind = str(ev.get("kind") or "unknown")
- kind_counts[kind] = kind_counts.get(kind, 0) + 1
- phase = str(ev.get("phase") or "")
- phase_group = re.sub(r"_(fan\d+_round\d+|antirebound_soak_round\d+)$", "", phase)
- if kind == "suite_init" and suite_init is None:
- suite_init = ev
- elif kind == "phase_start":
- phase_starts.append(ev)
- elif kind == "cooldown_fan_start":
- rnd = int(ev.get("round") or 0)
- open_fan_round[(phase_group, rnd)] = {
- "phase_group": phase_group,
- "round": rnd,
- "fan_pct": ev.get("fan_pct"),
- "start_time_cst": ev.get("time_cst"),
- "start_unix_ms": ev.get("unix_ms"),
- "outcome": "in_progress",
- }
- elif kind in ("cooldown_target_reached", "cooldown_timeout"):
- rnd = int(ev.get("round") or 0)
- rec = open_fan_round.pop((phase_group, rnd), {"phase_group": phase_group, "round": rnd})
- rec["outcome"] = "target_reached" if kind == "cooldown_target_reached" else "timeout"
- rec["end_time_cst"] = ev.get("time_cst")
- rec["end_unix_ms"] = ev.get("unix_ms")
- if rec.get("start_unix_ms") and ev.get("unix_ms"):
- rec["duration_s"] = round((ev["unix_ms"] - rec["start_unix_ms"]) / 1000.0, 2)
- elif "elapsed_s" in ev:
- rec["duration_s"] = round(float(ev["elapsed_s"]), 2)
- rec["ct_max"] = ev.get("ct_max")
- rec["dimm_max"] = ev.get("dimm_max")
- cooldown_outcomes.append(rec)
- elif kind == "antirebound_soak_start":
- rnd = int(ev.get("round") or 0)
- open_soak_round[(phase_group, rnd)] = {
- "start_unix_ms": ev.get("unix_ms"),
- "soak_sec": ev.get("soak_sec"),
- }
- elif kind == "antirebound_soak_result":
- rnd = int(ev.get("round") or 0)
- soak_meta = open_soak_round.pop((phase_group, rnd), {})
- norm = dict(ev)
- norm["phase_group"] = phase_group
- norm["start_unix_ms"] = soak_meta.get("start_unix_ms")
- norm["soak_sec"] = soak_meta.get("soak_sec")
- norm["max_rebound_norm"] = ev.get("max_rebound") if ev.get("max_rebound") is not None else ev.get("rebound_delta")
- norm["base_ct_norm"] = ev.get("base_ct_max") if ev.get("base_ct_max") is not None else ev.get("base_ct")
- norm["peak_ct_norm"] = ev.get("peak_ct_max") if ev.get("peak_ct_max") is not None else ev.get("peak_ct")
- antirebound_soaks.append(norm)
- elif kind == "test1_pid_handover":
- preheat_handovers.append(ev)
- elif kind == "mt_launched":
- mt_launches.append(ev)
- elif kind == "mt_algo_start":
- ev_norm = dict(ev)
- ev_norm["algorithm_norm"] = normalize_algorithm_name(str(ev.get("algorithm") or ""))
- mt_algo_starts.append(ev_norm)
- elif kind == "mt_algo_done":
- mt_algo_dones.append(ev)
- elif kind == "mcu_cmd":
- mcu_cmds.append(ev)
- elif kind == "suite_complete":
- suite_complete.append(ev)
- for rec in open_fan_round.values():
- cooldown_outcomes.append(rec)
- cooldown_outcomes.sort(key=lambda r: (r.get("start_unix_ms") or 0, r.get("round") or 0))
- return {
- "event_count": len(events),
- "parse_errors": parse_errors,
- "kind_counts": kind_counts,
- "events": events,
- "suite_init": suite_init,
- "phase_starts": phase_starts,
- "cooldown_outcomes": cooldown_outcomes,
- "antirebound_soaks": antirebound_soaks,
- "preheat_handovers": preheat_handovers,
- "mt_launches": mt_launches,
- "mt_algo_starts": mt_algo_starts,
- "mt_algo_dones": mt_algo_dones,
- "mcu_cmds": mcu_cmds,
- "suite_complete": suite_complete,
- }
- def _parse_kv_fields(text: str) -> dict[str, str]:
- out: dict[str, str] = {}
- for part in text.split(","):
- if ":" in part:
- k, v = part.split(":", 1)
- out[k.strip()] = v.strip()
- return out
- def parse_console_log(raw_text: str, filename: str = "") -> dict[str, Any]:
- cleaned = strip_ansi(raw_text)
- lines = cleaned.splitlines()
- bios_versions: list[str] = []
- smbios_bios: str | None = None
- smbios_system: str | None = None
- cpu_names: list[str] = []
- total_memories: list[str] = []
- mem_timings: list[str] = []
- dram_entries: dict[str, dict[str, str]] = {}
- smbios_slots: dict[int, dict[str, Any]] = {}
- mt_config: dict[str, str] = {}
- algo_names_by_num: dict[int, str] = {}
- running_tests: list[dict[str, Any]] = []
- completed_tests: list[dict[str, Any]] = []
- range_warnings: list[dict[str, Any]] = []
- dimm0_temps: list[float] = []
- dimm1_temps: list[float] = []
- cpu_temps: list[float] = []
- real_errors: list[str] = []
- for ln in lines:
- s = ln.strip()
- if not s:
- continue
- if "[SYS_BIOS]" in s:
- m = SYS_BIOS_RE.search(s)
- if m and m.group(1).strip() not in bios_versions:
- bios_versions.append(m.group(1).strip())
- elif "SMBIOS BIOS INFO" in s:
- m = SMBIOS_BIOS_RE.search(s)
- if m and not smbios_bios:
- smbios_bios = m.group(1).strip()
- elif "SMBIOS SYSTEM INFO" in s:
- m = SMBIOS_SYS_RE.search(s)
- if m and not smbios_system:
- smbios_system = m.group(1).strip()
- elif "Processor Information Name:" in s:
- m = HS_CPU_RE.search(s)
- if m:
- val = m.group(2).strip()
- if val not in cpu_names:
- cpu_names.append(val)
- elif "Total Memory:" in s:
- m = TOTAL_MEM_RE.search(s)
- if m:
- val = m.group(1).strip()
- if val not in total_memories:
- total_memories.append(val)
- elif "Current mem timings:" in s:
- m = MEM_TIMINGS_RE.search(s)
- if m:
- val = m.group(1).strip()
- if val not in mem_timings:
- mem_timings.append(val)
- elif "_DRAM]" in s:
- m = HS_DRAM_RE.search(s)
- if m:
- kv = _parse_kv_fields(m.group(2))
- loc = kv.get("DimmLocation") or f"S{kv.get('Socket','?')}_C{kv.get('Channel','?')}_D{kv.get('Dimm','?')}"
- dram_entries[loc] = kv
- elif s.startswith("[Slot "):
- ms = SMBIOS_SLOT_SIZE_RE.match(s)
- if ms:
- slot = int(ms.group(1))
- size = int(ms.group(2))
- speed = int(ms.group(3))
- if size > 0:
- smbios_slots.setdefault(slot, {})["size_mb"] = size
- smbios_slots[slot]["speed_mt_s"] = speed
- ml = SMBIOS_SLOT_LOC_RE.match(s)
- if ml:
- slot = int(ml.group(1))
- if slot in smbios_slots:
- smbios_slots[slot].update({
- "device_locator": ml.group(2).strip(),
- "bank_locator": ml.group(3).strip(),
- "manufacturer": ml.group(4).strip(),
- "sn": ml.group(5).strip(),
- "part_number": ml.group(7).strip(),
- })
- elif s.startswith("[CONFIG] ") and ":" in s:
- key, val = s[9:].split(":", 1)
- k_clean = key.strip()
- if not k_clean.startswith("Unknown line"):
- mt_config[k_clean] = val.strip()
- mr = RUNNING_TEST_RE.search(s)
- if mr:
- tnum = int(mr.group(1))
- aname = mr.group(2).strip()
- algo_names_by_num[tnum] = aname
- running_tests.append({"test_num": tnum, "algorithm": aname})
- continue
- me = TEST_EXEC_RE.search(s)
- if me:
- exec_s = float(me.group(1))
- tnum = int(me.group(2))
- err_cnt = int(me.group(3))
- buf_full = int(me.group(4))
- completed_tests.append({
- "test_num": tnum,
- "exec_s": exec_s,
- "cum_errors": err_cnt,
- "buffer_full_count": buf_full,
- })
- if err_cnt > 0:
- real_errors.append(s)
- continue
- mw = RANGE_WARN_RE.search(s)
- if mw:
- range_warnings.append({
- "wait_s": int(mw.group(1)),
- "cpu_id": int(mw.group(2)),
- "bsp_time_ms": int(mw.group(3)),
- })
- continue
- md = CONSOLE_DIMM_TEMP_RE.match(s)
- if md:
- idx = int(md.group(1))
- val = float(md.group(2))
- if idx == 0:
- dimm0_temps.append(val)
- elif idx == 1:
- dimm1_temps.append(val)
- continue
- mc = CONSOLE_CPU_TEMP_RE.match(s)
- if mc:
- cpu_temps.append(float(mc.group(1)))
- continue
- if (
- ("Test Complete" in s and "0 Errors" not in s)
- or "Error Confidence" in s
- or re.search(r"\bTest\s+\d+.*?\bFAIL\b", s)
- or re.search(r"ECC\s+(Uncorrectable|Correctable)\s+Error", s, re.IGNORECASE)
- ):
- real_errors.append(s)
- return {
- "filename": filename,
- "bytes": len(raw_text.encode("utf-8", errors="replace")),
- "lines": len(lines),
- "bios_versions": bios_versions,
- "smbios_bios": smbios_bios,
- "smbios_system": smbios_system,
- "cpu_names": cpu_names,
- "total_memories": total_memories,
- "mem_timings": mem_timings,
- "dram_entries": list(dram_entries.values()),
- "smbios_populated_slots": [{"slot": k, **v} for k, v in sorted(smbios_slots.items())],
- "mt_config": mt_config,
- "algo_names_by_num": algo_names_by_num,
- "running_tests": running_tests,
- "completed_tests": completed_tests,
- "range_warnings_count": len(range_warnings),
- "range_warnings_max_cpu": max((w["cpu_id"] for w in range_warnings), default=None),
- "range_warnings_max_bsp_ms": max((w["bsp_time_ms"] for w in range_warnings), default=None),
- "console_dimm0_temp": _sensor_stats(dimm0_temps, 2),
- "console_dimm1_temp": _sensor_stats(dimm1_temps, 2),
- "console_cpu_temp": _sensor_stats(cpu_temps, 2),
- "real_errors": real_errors,
- }
- def _discover_active_bmc_channels(rows: list[dict[str, Any]]) -> list[int]:
- active: list[int] = []
- for i in range(24):
- if any(r["bmc24_raw"][i] not in (None, 255) for r in rows):
- active.append(i)
- return active
- def _compute_individual_sensor_block(
- rows: list[dict[str, Any]],
- active_bmc_channels: list[int],
- ) -> dict[str, Any]:
- """Compute start/end/min/max/delta/span for every chamber & position sensor individually."""
- chamber_sensors: dict[str, Any] = {}
- for col, zh_label, ch_id, side in CHAMBER_SENSORS:
- vals = [r[col] for r in rows if r.get(col) is not None]
- st = _sensor_stats(vals, 2)
- if st is not None:
- st["label"] = zh_label
- st["chamber"] = ch_id
- st["side"] = side
- chamber_sensors[col] = st
- chambers_paired: dict[str, Any] = {}
- for ch_id, ch_label, f_col, r_col in CHAMBER_PAIRS:
- diffs = [
- r[f_col] - r[r_col]
- for r in rows
- if r.get(f_col) is not None and r.get(r_col) is not None
- ]
- chambers_paired[ch_id] = {
- "label": ch_label,
- "front": chamber_sensors[f_col],
- "rear": chamber_sensors[r_col],
- "front_minus_rear": _sensor_stats(diffs, 2),
- }
- bmc_channels: dict[str, Any] = {}
- for idx in active_bmc_channels:
- vals = [float(r["bmc24_raw"][idx]) for r in rows if r["bmc24_raw"][idx] not in (None, 255)]
- st = _sensor_stats(vals, 2)
- if st is not None:
- st["label"] = bmc_slot_label(idx)
- st["channel_idx"] = idx
- bmc_channels[f"BMC{idx}"] = st
- redfish_temps: dict[str, Any] = {}
- for col, label in REDFISH_TEMP_SENSORS:
- vals = [r[col] for r in rows if r.get(col) is not None]
- st = _sensor_stats(vals, 2)
- if st is not None:
- st["label"] = label
- redfish_temps[col] = st
- mt_console_temps: dict[str, Any] = {}
- for col, label in MT_CONSOLE_TEMP_SENSORS:
- vals = [r[col] for r in rows if r.get(col) is not None]
- st = _sensor_stats(vals, 2)
- if st is not None:
- st["label"] = label
- mt_console_temps[col] = st
- power_rails: dict[str, Any] = {}
- for col, label in POWER_RAIL_SENSORS:
- vals = [r[col] for r in rows if r.get(col) is not None]
- st = _sensor_stats(vals, 2)
- if st is not None:
- st["label"] = label
- power_rails[col] = st
- fans_and_actuators: dict[str, Any] = {}
- for col, label in FAN_ACTUATOR_SENSORS:
- vals = [r[col] for r in rows if r.get(col) is not None]
- st = _sensor_stats(vals, 1 if "pct" in col else 0)
- if st is not None:
- st["label"] = label
- fans_and_actuators[col] = st
- return {
- "chamber_sensors": chamber_sensors,
- "chambers": chambers_paired,
- "bmc_channels": bmc_channels,
- "redfish_temps": redfish_temps,
- "mt_console_temps": mt_console_temps,
- "power_rails": power_rails,
- "fans_and_actuators": fans_and_actuators,
- }
- def _compute_phase_metrics(
- rows: list[dict[str, Any]],
- active_bmc_channels: list[int],
- ) -> dict[str, Any]:
- if not rows:
- return {"rows": 0}
- mcu_modes: dict[str, int] = {}
- for r in rows:
- m = r["mcu_mode"] or "unknown"
- mcu_modes[m] = mcu_modes.get(m, 0) + 1
- duration_hms = rows[-1]["elapsed_hms"] or _fmt_hms(
- ((rows[-1]["unix_ms"] or 0) - (rows[0]["unix_ms"] or 0)) / 1000.0
- )
- sensors = _compute_individual_sensor_block(rows, active_bmc_channels)
- return {
- "rows": len(rows),
- "start_time_cst": rows[0]["timestamp_cst"],
- "end_time_cst": rows[-1]["timestamp_cst"],
- "duration_hms": duration_hms,
- "mcu_modes": mcu_modes,
- "mt_cum_errors": max(r["mt_cum_errors"] for r in rows),
- **sensors,
- }
- def _mark_residual_prelaunch_rows(
- rows: list[dict[str, Any]],
- mt_launch_unix_ms: int | None = None,
- ) -> int:
- residual_count = 0
- for r in rows:
- algo = r["active_algorithm_raw"]
- fw = r["firmware_phase"]
- if algo == "MemTest86 Launching" or fw == "mt":
- break
- if mt_launch_unix_ms is not None and r["unix_ms"] is not None and r["unix_ms"] >= mt_launch_unix_ms:
- break
- if TEST_PREFIX_RE.match(algo) and fw != "mt":
- r["is_residual_prelaunch"] = True
- residual_count += 1
- elif algo.startswith("UEFI Shell Idle"):
- continue
- else:
- break
- return residual_count
- def _aggregate_algorithms(
- rows: list[dict[str, Any]],
- active_bmc_channels: list[int],
- *,
- console_exec_by_test: dict[int, list[float]] | None = None,
- event_exec_by_test: dict[int, list[float]] | None = None,
- ) -> dict[str, dict[str, Any]]:
- grouped: dict[str, list[dict[str, Any]]] = {}
- for r in rows:
- if r.get("is_residual_prelaunch"):
- continue
- key = r["active_algorithm"] or r["active_algorithm_raw"] or "Unknown"
- grouped.setdefault(key, []).append(r)
- result: dict[str, dict[str, Any]] = {}
- for algo, grows in grouped.items():
- m = TEST_PREFIX_RE.match(algo)
- tnum = int(m.group(1)) if m else None
- sensors = _compute_individual_sensor_block(grows, active_bmc_channels)
- # Instantaneous simultaneous DDR0 vs DDR2 asymmetry (no mean!)
- inst_ratios: list[float] = []
- for r in grows:
- d0_v = r.get("rf_ddr0_power_w")
- d2_v = r.get("rf_ddr2_power_w")
- if d0_v is not None and d2_v is not None and min(d0_v, d2_v) > 0.5:
- inst_ratios.append(max(d0_v, d2_v) / min(d0_v, d2_v))
- asym_ratio = round(max(inst_ratios), 2) if inst_ratios else None
- asym_seconds = sum(1 for x in inst_ratios if x >= 1.5)
- is_asym = bool(
- asym_ratio is not None
- and asym_ratio >= 1.8
- and (asym_seconds >= 3 or len(grows) <= 3)
- )
- result[algo] = {
- "samples_s": len(grows),
- "test_num": tnum,
- "cum_errors": max(r["mt_cum_errors"] for r in grows),
- "console_exec_s": (
- console_exec_by_test[tnum][0]
- if console_exec_by_test and tnum in console_exec_by_test and console_exec_by_test[tnum]
- else None
- ),
- "event_exec_s": (
- event_exec_by_test[tnum][0]
- if event_exec_by_test and tnum in event_exec_by_test and event_exec_by_test[tnum]
- else None
- ),
- "ddr_peak_asymmetry_ratio": asym_ratio,
- "ddr_asymmetric_seconds": asym_seconds,
- "is_asymmetric_load": is_asym,
- **sensors,
- }
- return result
- def analyze_station(station_key: str, accessor: VirtualStation) -> tuple[dict[str, Any], dict[str, Any]]:
- # 1. Parse console logs first for hardware inventory & full algorithm names
- console_files = accessor.list_files("_console.log")
- console_parsed: dict[str, dict[str, Any]] = {}
- merged_algo_map: dict[int, str] = {}
- for cf in console_files:
- cp = parse_console_log(accessor.read_text(cf), cf)
- console_parsed[cf] = cp
- merged_algo_map.update(cp["algo_names_by_num"])
- ordered_consoles = sorted(
- console_parsed.values(),
- key=lambda c: (0 if c["filename"] == "master_console.log" else 1, c["filename"]),
- )
- bios_versions: list[str] = []
- cpu_names: list[str] = []
- total_memories: list[str] = []
- mem_timings: list[str] = []
- dram_entries: list[dict[str, str]] = []
- seen_dram_locs: set[str] = set()
- smbios_bios = None
- smbios_system = None
- mt_config: dict[str, str] = {}
- total_console_real_errors: list[dict[str, str]] = []
- console_phase_summaries: dict[str, Any] = {}
- for cp in ordered_consoles:
- for b in cp["bios_versions"]:
- if b not in bios_versions:
- bios_versions.append(b)
- if not smbios_bios and cp["smbios_bios"]:
- smbios_bios = cp["smbios_bios"]
- if not smbios_system and cp["smbios_system"]:
- smbios_system = cp["smbios_system"]
- for c in cp["cpu_names"]:
- if c not in cpu_names:
- cpu_names.append(c)
- for tm in cp["total_memories"]:
- if tm not in total_memories:
- total_memories.append(tm)
- for mt in cp["mem_timings"]:
- if mt not in mem_timings:
- mem_timings.append(mt)
- for de in cp["dram_entries"]:
- loc = de.get("DimmLocation") or json.dumps(de, sort_keys=True)
- if loc not in seen_dram_locs:
- seen_dram_locs.add(loc)
- dram_entries.append(de)
- if not mt_config and cp["mt_config"]:
- mt_config = cp["mt_config"]
- for err in cp["real_errors"]:
- total_console_real_errors.append({"file": cp["filename"], "line": err})
- console_phase_summaries[cp["filename"]] = {
- "bytes": cp["bytes"],
- "lines": cp["lines"],
- "running_tests_count": len(cp["running_tests"]),
- "completed_tests": cp["completed_tests"],
- "range_warnings_count": cp["range_warnings_count"],
- "range_warnings_max_cpu": cp["range_warnings_max_cpu"],
- "range_warnings_max_bsp_ms": cp["range_warnings_max_bsp_ms"],
- "console_dimm0_temp": cp["console_dimm0_temp"],
- "console_dimm1_temp": cp["console_dimm1_temp"],
- "console_cpu_temp": cp["console_cpu_temp"],
- "real_errors_count": len(cp["real_errors"]),
- }
- # 2. Parse events & live_status
- events_parsed = (
- parse_events_jsonl(accessor.read_text("master_events.jsonl"))
- if accessor.exists("master_events.jsonl")
- else parse_events_jsonl("")
- )
- live_status = (
- json.loads(accessor.read_text("live_status.json"))
- if accessor.exists("live_status.json")
- else None
- )
- # 3. Parse comprehensive CSVs
- comp_files = accessor.list_files("_comprehensive.csv")
- comp_parsed_by_name: dict[str, dict[str, Any]] = {}
- for cf in comp_files:
- comp_parsed_by_name[cf] = parse_comprehensive_csv(accessor.read_bytes(cf), merged_algo_map)
- master_comp_name = "master_continuous_comprehensive.csv"
- master_comp = comp_parsed_by_name.get(master_comp_name)
- all_rows_for_bmc = (
- master_comp["rows"]
- if master_comp is not None
- else [r for cp in comp_parsed_by_name.values() for r in cp["rows"]]
- )
- active_bmc_channels = _discover_active_bmc_channels(all_rows_for_bmc)
- # 4. Audit all 34-column template CSVs
- template_files = accessor.list_files("_template.csv")
- template_checks: dict[str, Any] = {}
- for tf in template_files:
- matching_comp_name = tf.replace("_template.csv", "_comprehensive.csv")
- comp_rows = comp_parsed_by_name[matching_comp_name]["rows"] if matching_comp_name in comp_parsed_by_name else None
- template_checks[tf] = audit_template_csv(accessor.read_bytes(tf), comp_rows)
- # 5. Compute phase metrics and MT algorithm breakdown (all individual sensors)
- phases_detail: dict[str, Any] = {}
- mt_launches_by_phase: dict[str, int] = {
- str(ev.get("phase") or ""): int(ev["unix_ms"])
- for ev in events_parsed["mt_launches"]
- if ev.get("unix_ms") is not None
- }
- event_exec_by_phase: dict[str, dict[int, list[float]]] = {}
- for ev in events_parsed["mt_algo_dones"]:
- ph = str(ev.get("phase") or "")
- tnum = ev.get("test_num")
- ex = ev.get("exec_s")
- if tnum is not None and ex is not None:
- event_exec_by_phase.setdefault(ph, {}).setdefault(int(tnum), []).append(float(ex))
- residual_findings: list[dict[str, Any]] = []
- algorithms_by_phase: dict[str, dict[str, Any]] = {}
- phase_comp_names = [cf for cf in comp_files if cf != master_comp_name]
- synthesized_phases: list[tuple[str, list[dict[str, Any]]]] = []
- if not phase_comp_names and master_comp is not None:
- grouped_master: dict[str, list[dict[str, Any]]] = {}
- for r in master_comp["rows"]:
- tp = r["test_phase"] or "unknown"
- if tp == "init":
- continue
- bucket = re.sub(r"_(fan\d+_round\d+|antirebound_soak_round\d+)$", "", tp)
- grouped_master.setdefault(bucket, []).append(r)
- for bucket, grows in grouped_master.items():
- synthesized_phases.append((f"{bucket}_comprehensive.csv", grows))
- phase_sources: list[tuple[str, list[dict[str, Any]], str, bool, int]] = []
- for cf in phase_comp_names:
- cp = comp_parsed_by_name[cf]
- phase_sources.append((cf, cp["rows"], cp["schema_version"], cp["seq_contiguous"], len(cp["gaps_over_2s"])))
- for cf, grows in synthesized_phases:
- phase_sources.append((cf, grows, master_comp["schema_version"] if master_comp else "unknown", True, 0))
- for cf, prows, p_schema, p_seq_ok, p_gaps_cnt in phase_sources:
- phase_base = cf.replace("_comprehensive.csv", "")
- launch_ms = mt_launches_by_phase.get(phase_base)
- if "_mt_" in phase_base:
- res_cnt = _mark_residual_prelaunch_rows(prows, launch_ms)
- if res_cnt > 0:
- residual_findings.append({
- "file": cf,
- "phase": phase_base,
- "residual_rows": res_cnt,
- "residual_label": prows[0]["active_algorithm"],
- "note": "Leading rows before MemTest86 launch carried residual algorithm label from prior run",
- })
- pm = _compute_phase_metrics(prows, active_bmc_channels)
- pm["schema_version"] = p_schema
- pm["seq_contiguous"] = p_seq_ok
- pm["gaps_over_2s_count"] = p_gaps_cnt
- phases_detail[cf] = pm
- if "_mt_" in phase_base:
- console_name = f"{phase_base}_console.log"
- cp_con = console_parsed.get(console_name)
- con_exec: dict[int, list[float]] = {}
- if cp_con:
- for ct in cp_con["completed_tests"]:
- con_exec.setdefault(int(ct["test_num"]), []).append(float(ct["exec_s"]))
- algorithms_by_phase[phase_base] = _aggregate_algorithms(
- prows,
- active_bmc_channels,
- console_exec_by_test=con_exec,
- event_exec_by_test=event_exec_by_phase.get(phase_base),
- )
- master_rows = master_comp["rows"] if master_comp else []
- if master_rows and residual_findings:
- residual_windows: list[tuple[int, int]] = []
- for rf in residual_findings:
- prows = comp_parsed_by_name[rf["file"]]["rows"]
- r_subset = [r for r in prows if r["is_residual_prelaunch"] and r["unix_ms"] is not None]
- if r_subset:
- residual_windows.append((min(r["unix_ms"] for r in r_subset) - 50, max(r["unix_ms"] for r in r_subset) + 50))
- for r in master_rows:
- um = r["unix_ms"]
- if um is not None and any(lo <= um <= hi for lo, hi in residual_windows):
- r["is_residual_prelaunch"] = True
- # 6. Enrich cooldown soak rounds with per-chamber 8-channel rebound details from CSV
- soak_items: list[dict[str, Any]] = []
- for sk in events_parsed["antirebound_soaks"]:
- end_ms = sk.get("unix_ms")
- start_ms = sk.get("start_unix_ms")
- per_chamber_rebound: dict[str, Any] = {}
- dimm0_end_csv = None
- dimm1_end_csv = None
- bmc_end_csv: dict[str, int | None] = {}
- if master_rows and end_ms is not None:
- if start_ms is not None:
- win_rows = [
- r for r in master_rows
- if r["unix_ms"] is not None and (start_ms - 500) <= r["unix_ms"] <= (end_ms + 500)
- ]
- else:
- win_rows = []
- if win_rows:
- for col, zh_label, ch_id, side in CHAMBER_SENSORS:
- vals = [r[col] for r in win_rows if r.get(col) is not None]
- if vals:
- per_chamber_rebound[col] = {
- "label": zh_label,
- "start": vals[0],
- "peak": max(vals),
- "end": vals[-1],
- "rebound": round(max(vals) - vals[0], 2),
- }
- nearest = min(
- (r for r in master_rows if r["unix_ms"] is not None),
- key=lambda r: abs(int(r["unix_ms"]) - int(end_ms)),
- default=None,
- )
- if nearest is not None:
- dimm0_end_csv = nearest.get("rf_dimm_cpu0_a_c")
- dimm1_end_csv = nearest.get("rf_dimm_cpu1_a_c")
- for b_idx in active_bmc_channels:
- bv = nearest["bmc24_raw"][b_idx]
- bmc_end_csv[f"BMC{b_idx}"] = None if bv in (None, 255) else bv
- soak_items.append({
- "phase_group": sk["phase_group"],
- "phase": sk.get("phase"),
- "round": sk.get("round"),
- "time_cst": sk.get("time_cst"),
- "base_ct_max": sk.get("base_ct_norm"),
- "peak_ct_max": sk.get("peak_ct_norm"),
- "max_rebound": sk.get("max_rebound_norm"),
- "ct_end": sk.get("ct_end"),
- "dimm_end_event": sk.get("dimm_end"),
- "dimm0_end_csv": dimm0_end_csv,
- "dimm1_end_csv": dimm1_end_csv,
- "bmc_end_csv": bmc_end_csv,
- "per_chamber_rebound": per_chamber_rebound,
- })
- # 7. Enrich preheat handovers with individual per-chamber CT8 & +300s individual sensors
- preheat_enriched: list[dict[str, Any]] = []
- for hv in events_parsed["preheat_handovers"]:
- item = dict(hv)
- ct8 = hv.get("ct8") or []
- if len(ct8) == 8:
- item["chambers_at_handover"] = {
- ch_id: {
- "front": ct8[idx * 2],
- "rear": ct8[idx * 2 + 1],
- "front_minus_rear": ct8[idx * 2] - ct8[idx * 2 + 1],
- }
- for idx, (ch_id, _, _, _) in enumerate(CHAMBER_PAIRS)
- }
- hv_ms = hv.get("unix_ms")
- if master_rows and hv_ms is not None:
- preheat_rows = [r for r in master_rows if r["test_phase"] == hv.get("phase")]
- if preheat_rows:
- item["start_sensors"] = {
- "ct8": preheat_rows[0]["ct8"],
- "rf_dimm_cpu0_a_c": preheat_rows[0]["rf_dimm_cpu0_a_c"],
- "rf_dimm_cpu1_a_c": preheat_rows[0]["rf_dimm_cpu1_a_c"],
- "bmc": {f"BMC{i}": preheat_rows[0]["bmc24_raw"][i] for i in active_bmc_channels},
- }
- after_300 = [r for r in master_rows if r["unix_ms"] is not None and r["unix_ms"] >= hv_ms + 299_000]
- if after_300:
- r300 = after_300[0]
- item["post_300s_sensors"] = {
- "ct8": r300["ct8"],
- "rf_dimm_cpu0_a_c": r300["rf_dimm_cpu0_a_c"],
- "rf_dimm_cpu1_a_c": r300["rf_dimm_cpu1_a_c"],
- "bmc": {f"BMC{i}": r300["bmc24_raw"][i] for i in active_bmc_channels},
- }
- preheat_enriched.append(item)
- # 8. Station identity & integrity
- station_id = ""
- bmc_host = ""
- m_key = re.match(r"^(S\d+)_(.+)$", station_key)
- if m_key:
- station_id, bmc_host = m_key.group(1), m_key.group(2)
- for r in master_rows[:5]:
- if r.get("station_id") and not station_id:
- station_id = r["station_id"]
- if r.get("bmc_host") and not bmc_host:
- bmc_host = r["bmc_host"]
- if not station_id:
- station_id = station_key
- phase_row_sum = sum(len(comp_parsed_by_name[cf]["rows"]) for cf in phase_comp_names)
- master_row_count = len(master_rows)
- total_mt_errors = max(
- [max((r["mt_cum_errors"] for r in master_rows), default=0)]
- + [int(ct["cum_errors"]) for cp in console_parsed.values() for ct in cp["completed_tests"]]
- + [int(ev.get("cum_errors") or 0) for ev in events_parsed["mt_algo_dones"]]
- + [len(total_console_real_errors)]
- )
- template_all_ok = all(t["status"] == "PASS" for t in template_checks.values()) if template_checks else False
- integrity = {
- "schema_version": master_comp["schema_version"] if master_comp else "unknown",
- "master_rows": master_row_count,
- "phase_sum_rows": phase_row_sum,
- "master_minus_phase_rows": master_row_count - phase_row_sum,
- "master_seq_contiguous": master_comp["seq_contiguous"] if master_comp else False,
- "master_dt_ms_median": master_comp["dt_ms_median"] if master_comp else None,
- "master_dt_ms_max": master_comp["dt_ms_max"] if master_comp else None,
- "master_gaps_over_2s": master_comp["gaps_over_2s"] if master_comp else [],
- "mcu_offline_rows": master_comp["mcu_offline_rows"] if master_comp else 0,
- "cpld_lost_rows": master_comp["cpld_lost_rows"] if master_comp else 0,
- "server_power_non_on": master_comp["server_power_non_on"] if master_comp else 0,
- "template_files_count": len(template_checks),
- "template_all_pass": template_all_ok,
- "template_total_mismatches": sum((t["value_mismatches_vs_comprehensive"] or 0) for t in template_checks.values()),
- "residual_prelaunch_findings": residual_findings,
- "mt_total_errors": total_mt_errors,
- "console_real_errors": total_console_real_errors[:20],
- "events_parse_errors": events_parsed["parse_errors"],
- }
- suite_init = events_parsed["suite_init"] or {}
- station_info = {
- "station_key": station_key,
- "station_id": station_id,
- "bmc_host": bmc_host,
- "mcu_uid": suite_init.get("uid"),
- "mcu_app_info": suite_init.get("app_info"),
- "pid_text": suite_init.get("pid_text"),
- "active_bmc_channels": [
- {"idx": idx, "key": f"BMC{idx}", "label": bmc_slot_label(idx)}
- for idx in active_bmc_channels
- ],
- "bios_versions": bios_versions,
- "smbios_bios": smbios_bios,
- "smbios_system": smbios_system,
- "cpu_names": cpu_names,
- "total_memories": total_memories,
- "mem_timings": mem_timings,
- "dram_inventory": dram_entries,
- "mt_config": mt_config,
- "total_duration_hms": master_rows[-1]["elapsed_hms"] if master_rows else None,
- "start_time_cst": master_rows[0]["timestamp_cst"] if master_rows else None,
- "end_time_cst": master_rows[-1]["timestamp_cst"] if master_rows else None,
- }
- # Overall full-run individual sensor stats from master_continuous
- overall_sensors = _compute_individual_sensor_block(master_rows, active_bmc_channels) if master_rows else {}
- station_report = {
- "station_info": station_info,
- "integrity": integrity,
- "live_status": live_status,
- "template_checks": template_checks,
- "overall_sensors": overall_sensors,
- "phases_detail": phases_detail,
- "cooldown_outcomes": events_parsed["cooldown_outcomes"],
- "antirebound_soaks": soak_items,
- "preheat_handovers": preheat_enriched,
- "algorithms_by_phase": algorithms_by_phase,
- "console_summary": console_phase_summaries,
- "events_meta": {
- "event_count": events_parsed["event_count"],
- "kind_counts": events_parsed["kind_counts"],
- "events": events_parsed["events"],
- },
- }
- series = _build_compact_series(master_rows, active_bmc_channels)
- return station_report, {"master_rows": master_rows, "active_bmc_channels": active_bmc_channels, "series": series}
- def _build_compact_series(rows: list[dict[str, Any]], active_bmc_channels: list[int]) -> dict[str, Any]:
- phase_names: list[str] = []
- phase_idx: dict[str, int] = {}
- algo_names: list[str] = []
- algo_idx: dict[str, int] = {}
- mode_names: list[str] = []
- mode_idx: dict[str, int] = {}
- cols: dict[str, list[Any]] = {
- "seq": [],
- "t": [],
- "ts": [],
- "ph": [],
- "al": [],
- "md": [],
- "res": [],
- "tgt": [],
- "err": [],
- }
- for col, _, _, _ in CHAMBER_SENSORS:
- cols[col] = []
- for idx in active_bmc_channels:
- cols[f"bmc{idx}"] = []
- for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS:
- cols[col] = []
- for r in rows:
- ph = r["test_phase"] or "unknown"
- if ph not in phase_idx:
- phase_idx[ph] = len(phase_names)
- phase_names.append(ph)
- al = r["active_algorithm"] or "Unknown"
- if al not in algo_idx:
- algo_idx[al] = len(algo_names)
- algo_names.append(al)
- md = r["mcu_mode"] or "unknown"
- if md not in mode_idx:
- mode_idx[md] = len(mode_names)
- mode_names.append(md)
- cols["seq"].append(r["seq"])
- cols["t"].append(round(r["elapsed_s"], 1) if r["elapsed_s"] is not None else len(cols["t"]))
- ts = r["timestamp_cst"]
- cols["ts"].append(ts[11:19] if len(ts) >= 19 else ts)
- cols["ph"].append(phase_idx[ph])
- cols["al"].append(algo_idx[al])
- cols["md"].append(mode_idx[md])
- cols["res"].append(1 if r.get("is_residual_prelaunch") else 0)
- cols["tgt"].append(_round_opt(r["mcu_target_c"], 1))
- cols["err"].append(r["mt_cum_errors"])
- for col, _, _, _ in CHAMBER_SENSORS:
- cols[col].append(_round_opt(r.get(col), 1))
- for idx in active_bmc_channels:
- bv = r["bmc24_raw"][idx]
- cols[f"bmc{idx}"].append(None if bv in (None, 255) else bv)
- for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS:
- cols[col].append(_round_opt(r.get(col), 2))
- for col, _ in FAN_ACTUATOR_SENSORS:
- cols[col].append(_round_opt(r.get(col), 1 if "pct" in col else 0))
- return {
- "phase_names": phase_names,
- "algo_names": algo_names,
- "mode_names": mode_names,
- "active_bmc_channels": [
- {"idx": idx, "col": f"bmc{idx}", "key": f"BMC{idx}", "label": bmc_slot_label(idx)}
- for idx in active_bmc_channels
- ],
- "cols": cols,
- }
- def parse_bundle(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
- with open_bundle_source(input_path) as src:
- stations_out: dict[str, Any] = {}
- artifacts: dict[str, Any] = {}
- for skey, accessor in src.stations.items():
- rep, art = analyze_station(skey, accessor)
- stations_out[skey] = rep
- artifacts[skey] = art
- total_rows = sum(s["integrity"]["master_rows"] for s in stations_out.values())
- total_mt_errors = sum(s["integrity"]["mt_total_errors"] for s in stations_out.values())
- all_templates_pass = all(s["integrity"]["template_all_pass"] for s in stations_out.values())
- summary = {
- "parser_version": PARSER_VERSION,
- "mode": "per_chamber_and_position_sensor_no_means",
- "parsed_utc": datetime.now(timezone.utc).isoformat(),
- "input_path": str(src.input_path),
- "source_kind": src.source_kind,
- "station_count": len(stations_out),
- "total_1hz_rows": total_rows,
- "total_mt_errors": total_mt_errors,
- "all_templates_pass": all_templates_pass,
- "stations": stations_out,
- }
- return summary, artifacts
- def _fmt_range(st: dict[str, Any] | None, unit: str = "°C", include_endpoints: bool = True) -> str:
- if not st:
- return "-"
- if include_endpoints:
- return f"`{st['min']}~{st['max']}{unit}` ({st['start']}→{st['end']})"
- return f"`{st['min']}~{st['max']}{unit}`"
- def render_markdown_report(parsed: dict[str, Any]) -> str:
- lines: list[str] = []
- lines.append("# 高温罩 + MemTest86 逐腔室与逐位置传感器独立解析报告(无均值)")
- lines.append("")
- lines.append(f"- **输入来源**:`{parsed['input_path']}` (`{parsed['source_kind']}`)")
- lines.append(f"- **解析时间 (UTC)**:`{parsed['parsed_utc']}` · 解析器版本 `v{parsed['parser_version']}` (`per_chamber_and_position_sensor_no_means`)")
- lines.append(
- f"- **总体结论**:共 **{parsed['station_count']}** 个工位,合计 **{parsed['total_1hz_rows']:,}** 行 1Hz 遥测样本,"
- f"MemTest86 累计错误数 **`{parsed['total_mt_errors']}`**,"
- f"34 列模板结构与逐行数值核验 **`{'全部 PASS' if parsed['all_templates_pass'] else '存在异常'}`**"
- )
- lines.extend(["", "---", "", "## 1. 工位硬件清单、有效传感器通道与数据完整性审计", ""])
- lines.append("| 工位 | BMC IP | MCU UID / PID | CPU & 内存 | 有效 BMC 通道 | 1Hz 总行数 (时长) | 模板核验 | MT 错误 | 数据告警 |")
- lines.append("|---|---|---|---|---|---|---|---|---|")
- for skey, s in parsed["stations"].items():
- info = s["station_info"]
- integ = s["integrity"]
- cpu = (info.get("cpu_names") or ["-"])[0]
- mem = (info.get("total_memories") or ["-"])[0]
- pid = (info.get("pid_text") or "").replace("OK ", "")
- bmc_list = ", ".join(b["key"] for b in info.get("active_bmc_channels") or []) or "-"
- tpl_status = f"PASS ({integ['template_files_count']}份, 0失配)" if integ["template_all_pass"] else "WARN"
- warns = [f"{rf['phase']} 前 {rf['residual_rows']}s 残留标签" for rf in integ["residual_prelaunch_findings"]]
- if integ["master_gaps_over_2s"]:
- warns.append(f"采样间隔>2s: {len(integ['master_gaps_over_2s'])}次")
- if integ["mcu_offline_rows"] or integ["cpld_lost_rows"]:
- warns.append(f"MCU离线={integ['mcu_offline_rows']} CPLD失联={integ['cpld_lost_rows']}")
- warn_txt = ";".join(warns) if warns else "无"
- lines.append(
- f"| **{info['station_id']}** | `{info['bmc_host'] or '-'}` | "
- f"`{info.get('mcu_uid') or '-'}` · `{pid}` | {cpu}; {mem} | `{bmc_list}` | "
- f"`{integ['master_rows']:,}` (`{info.get('total_duration_hms') or '-'}`) | "
- f"`{integ['schema_version']}` / {tpl_status} | **`{integ['mt_total_errors']}`** | {warn_txt} |"
- )
- lines.extend(["", "## 2. 各阶段高温罩 4 腔室 × 8 路位置传感器独立统计 (`min~max` 及 `起点→终点`)", ""])
- lines.append("| 工位 | 阶段 | 行数 / 时长 | 腔1前 (CT1) | 腔1后 (CT2) | 腔2前 (CT3) | 腔2后 (CT4) | 腔3前 (CT5) | 腔3后 (CT6) | 腔4前 (CT7) | 腔4后 (CT8) |")
- lines.append("|---|---|---|---|---|---|---|---|---|---|---|")
- for skey, s in parsed["stations"].items():
- sid = s["station_info"]["station_id"]
- for pname, pm in s["phases_detail"].items():
- short_p = pname.replace("_comprehensive.csv", "")
- cs = pm["chamber_sensors"]
- cols = [_fmt_range(cs.get(col), "°C") for col, _, _, _ in CHAMBER_SENSORS]
- lines.append(f"| **{sid}** | `{short_p}` | `{pm['rows']}` / `{pm['duration_hms']}` | " + " | ".join(cols) + " |")
- lines.extend(["", "## 3. 各阶段服务器位置传感器、功耗轨与风扇逐通道独立统计", ""])
- lines.append("### 3.1 内存、MCU BMC、CPU、主板与电源温度传感器 (`min~max`, `起点→终点`)")
- lines.append("")
- 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 |")
- lines.append("|---|---|---|---|---|---|---|---|---|---|")
- for skey, s in parsed["stations"].items():
- sid = s["station_info"]["station_id"]
- for pname, pm in s["phases_detail"].items():
- short_p = pname.replace("_comprehensive.csv", "")
- rf = pm["redfish_temps"]
- bmc = pm["bmc_channels"]
- mt = pm["mt_console_temps"]
- spd_txt = f"{_fmt_range(mt.get('mt_spd_dimm0_c'), '°C', False)} / {_fmt_range(mt.get('mt_spd_dimm1_c'), '°C', False)}"
- cpu_txt = f"{_fmt_range(rf.get('rf_cpu0_c'), '°C', False)} / {_fmt_range(rf.get('rf_cpu1_c'), '°C', False)}"
- mb_txt = f"{_fmt_range(rf.get('rf_mb_c'), '°C', False)} / {_fmt_range(rf.get('rf_psu0_c'), '°C', False)}"
- vr_txt = (
- f"{_fmt_range(rf.get('rf_pvccin_cpu0_c'), '', False)}/{_fmt_range(rf.get('rf_pvccin_cpu1_c'), '', False)} · "
- f"{_fmt_range(rf.get('rf_pvccfa_cpu0_c'), '', False)}/{_fmt_range(rf.get('rf_pvccfa_cpu1_c'), '', False)} · "
- f"{_fmt_range(rf.get('rf_pvccd_cpu0_c'), '', False)}/{_fmt_range(rf.get('rf_pvccd_cpu1_c'), '', False)}"
- )
- lines.append(
- f"| **{sid}** | `{short_p}` | {_fmt_range(rf.get('rf_dimm_cpu0_a_c'))} | {_fmt_range(rf.get('rf_dimm_cpu1_a_c'))} | "
- f"{_fmt_range(bmc.get('BMC0'))} | {_fmt_range(bmc.get('BMC12'))} | {spd_txt} | {cpu_txt} | {mb_txt} | {vr_txt} |"
- )
- lines.extend(["", "### 3.2 各电源/DDR/CPU 功耗轨与各风扇通道 (`min~max`)", ""])
- lines.append("| 工位 | 阶段 | 整机功耗 | DDR0 / DDR1 / DDR2 / DDR3 | CPU0 DIMM / CPU1 DIMM | CPU0 / CPU1 功耗 | 罩 PTC / 前扇 / 后扇 | RF FAN1..5 (RPM) |")
- lines.append("|---|---|---|---|---|---|---|---|")
- for skey, s in parsed["stations"].items():
- sid = s["station_info"]["station_id"]
- for pname, pm in s["phases_detail"].items():
- short_p = pname.replace("_comprehensive.csv", "")
- pw = pm["power_rails"]
- fa = pm["fans_and_actuators"]
- ddrs = " / ".join(_fmt_range(pw.get(f"rf_ddr{i}_power_w"), "W", False) for i in range(4))
- 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)}"
- 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)}"
- 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)}"
- fans = " / ".join(_fmt_range(fa.get(f"rf_fan{i}_rpm"), "", False) for i in range(1, 6))
- lines.append(f"| **{sid}** | `{short_p}` | {_fmt_range(pw.get('rf_total_power_w'), 'W', False)} | {ddrs} | {dimm_p} | {cpu_p} | {hood} | {fans} |")
- lines.extend(["", "## 4. 降温防反弹(逐腔室 8 路实测反弹)与预加热移交", ""])
- lines.append("| 工位 | 降温阶段 | Round | 吹扫耗时 / 结果 | 腔1前/后反弹 | 腔2前/后反弹 | 腔3前/后反弹 | 腔4前/后反弹 | 静置末 DIMM0 / DIMM1 |")
- lines.append("|---|---|---|---|---|---|---|---|---|")
- for skey, s in parsed["stations"].items():
- sid = s["station_info"]["station_id"]
- cd_map = {(c["phase_group"], c["round"]): c for c in s["cooldown_outcomes"]}
- for sk in s["antirebound_soaks"]:
- cd = cd_map.get((sk["phase_group"], sk["round"]), {})
- cd_txt = f"{cd.get('duration_s', '-')}s ({cd.get('outcome', '-')})"
- pcr = sk.get("per_chamber_rebound") or {}
- ch_txts = []
- for _, _, fc, rc in CHAMBER_PAIRS:
- f_info = pcr.get(fc)
- r_info = pcr.get(rc)
- f_s = f"{f_info['start']}→{f_info['peak']}(+{f_info['rebound']})" if f_info else "-"
- r_s = f"{r_info['start']}→{r_info['peak']}(+{r_info['rebound']})" if r_info else "-"
- ch_txts.append(f"{f_s} / {r_s}")
- d0e = sk.get("dimm0_end_csv")
- d1e = sk.get("dimm1_end_csv")
- dimm_txt = f"`{d0e if d0e is not None else '-'} / {d1e if d1e is not None else '-'}°C`"
- lines.append(f"| **{sid}** | `{sk['phase_group']}` | R{sk['round']} | {cd_txt} | " + " | ".join(ch_txts) + f" | {dimm_txt} |")
- lines.append("")
- lines.append("| 工位 | 预热耗时 (0x81 02) | 移交瞬时 8路 [腔1前,后 .. 腔4前,后] | 移交各腔前后差 (腔1..4) | 移交 BMC0 / BMC12 | +300s 8路 CT8 | +300s RF DIMM0 / DIMM1 |")
- lines.append("|---|---|---|---|---|---|---|")
- for skey, s in parsed["stations"].items():
- sid = s["station_info"]["station_id"]
- for hv in s["preheat_handovers"]:
- ch_h = hv.get("chambers_at_handover") or {}
- diffs = " / ".join(f"{ch_h[c]['front_minus_rear']:+d}°C" for c in ("ch1", "ch2", "ch3", "ch4") if c in ch_h) or "-"
- p300 = hv.get("post_300s_sensors") or {}
- p300_d = f"{p300.get('rf_dimm_cpu0_a_c', '-')}/{p300.get('rf_dimm_cpu1_a_c', '-')}°C" if p300 else "-"
- lines.append(
- f"| **{sid}** | `{hv.get('preheat_elapsed_s', 0):.1f}s` | `{hv.get('ct8')}` | `{diffs}` | "
- f"`{hv.get('bmc0')}/{hv.get('bmc12')}°C` | `{p300.get('ct8', '-')}` | {p300_d} |"
- )
- lines.extend(["", "## 5. MT 阶段按算法拆解(逐腔室 8 路 & 逐位置传感器实测范围 `min~max`,无均值)", ""])
- for skey, s in parsed["stations"].items():
- sid = s["station_info"]["station_id"]
- lines.append(f"### {sid} (`{s['station_info']['bmc_host'] or skey}`)")
- lines.append("")
- for phase_base, algos in s["algorithms_by_phase"].items():
- lines.append(f"#### 阶段 `{phase_base}`")
- lines.append("")
- lines.append("| 算法 | 样本(s) | 耗时(s) | RF DIMM0 | RF DIMM1 | BMC0 / BMC12 | 腔1前 / 后 | 腔2前 / 后 | 腔3前 / 后 | 腔4前 / 后 | DDR0 / DDR2 功耗 | CPU0 / CPU1 功耗 | 峰值非对称比 | 错误 |")
- lines.append("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|")
- for aname, av in algos.items():
- rf = av["redfish_temps"]
- bmc = av["bmc_channels"]
- cs = av["chamber_sensors"]
- pw = av["power_rails"]
- cexec = f"{av['console_exec_s']:.2f}s" if av.get("console_exec_s") is not None else "-"
- bmc_txt = f"{_fmt_range(bmc.get('BMC0'), '', False)} / {_fmt_range(bmc.get('BMC12'), '', False)}"
- ch_cols = [
- f"{_fmt_range(cs.get(fc), '', False)} / {_fmt_range(cs.get(rc), '', False)}"
- for _, _, fc, rc in CHAMBER_PAIRS
- ]
- ddr_txt = f"{_fmt_range(pw.get('rf_ddr0_power_w'), 'W', False)} / {_fmt_range(pw.get('rf_ddr2_power_w'), 'W', False)}"
- 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)}"
- 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 "-")
- lines.append(
- f"| `{aname}` | `{av['samples_s']}` | `{cexec}` | "
- 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} | "
- + " | ".join(ch_cols)
- + f" | {ddr_txt} | {cpu_txt} | {asym} | `{av['cum_errors']}` |"
- )
- lines.append("")
- lines.extend(["## 6. 控制台 BIOS/DRAM 硬件指纹与 MemTest86 执行核对", ""])
- lines.append("| 工位 | BIOS 版本 | DRAM 条目 (控制台) | MemTest86 配置 | Console 执行记录 & CPU 等待告警 | 实测错误 |")
- lines.append("|---|---|---|---|---|---|")
- for skey, s in parsed["stations"].items():
- info = s["station_info"]
- sid = info["station_id"]
- bios = "; ".join(info.get("bios_versions") or []) or (info.get("smbios_bios") or "-")
- drams = "; ".join(
- 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 '-'})"
- for d in (info.get("dram_inventory") or [])
- ) or "-"
- cfg = info.get("mt_config") or {}
- cfg_txt = f"Tests={cfg.get('Tests Selected','-')}; Pass={cfg.get('Number of passes','-')}; Exit={cfg.get('Exit mode','-')}"
- mcon = s["console_summary"].get("master_console.log") or {}
- warn_cnt = sum(c.get("range_warnings_count", 0) for c in s["console_summary"].values())
- con_txt = f"master完成={len(mcon.get('completed_tests', []))}项; CPU等待告警={warn_cnt}"
- lines.append(f"| **{sid}** | `{bios}` | `{drams}` | `{cfg_txt}` | {con_txt} | `{s['integrity']['mt_total_errors']}` |")
- return "\n".join(lines) + "\n"
- def render_html_dashboard(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
- slim_stations: dict[str, Any] = {}
- for skey, s in parsed["stations"].items():
- slim_stations[skey] = {
- "station_info": s["station_info"],
- "integrity": s["integrity"],
- "live_status": s["live_status"],
- "template_checks": s["template_checks"],
- "overall_sensors": s["overall_sensors"],
- "phases_detail": s["phases_detail"],
- "cooldown_outcomes": s["cooldown_outcomes"],
- "antirebound_soaks": s["antirebound_soaks"],
- "preheat_handovers": s["preheat_handovers"],
- "algorithms_by_phase": s["algorithms_by_phase"],
- "console_summary": s["console_summary"],
- "events": s["events_meta"]["events"],
- "event_kind_counts": s["events_meta"]["kind_counts"],
- }
- payload = {
- "meta": {
- "parser_version": parsed["parser_version"],
- "mode": parsed["mode"],
- "parsed_utc": parsed["parsed_utc"],
- "input_path": parsed["input_path"],
- "source_kind": parsed["source_kind"],
- "station_count": parsed["station_count"],
- "total_1hz_rows": parsed["total_1hz_rows"],
- "total_mt_errors": parsed["total_mt_errors"],
- "all_templates_pass": parsed["all_templates_pass"],
- },
- "stations": slim_stations,
- "series": {skey: art["series"] for skey, art in artifacts.items()},
- }
- payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
- title = html.escape(f"逐腔室/逐位置传感器独立解析看板 ({parsed['station_count']} 工位 · {parsed['total_1hz_rows']:,} 样本)")
- return f"""<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>{title}</title>
- <style>
- :root {{
- --bg: #0b101b;
- --bg-card: #121a2b;
- --bg-alt: #182338;
- --text: #e6edf7;
- --muted: #93a4be;
- --border: #253554;
- --accent: #38bdf8;
- --accent2: #818cf8;
- --good: #22c55e;
- --warn: #f59e0b;
- --bad: #ef4444;
- }}
- body.light {{
- --bg: #f1f5f9;
- --bg-card: #ffffff;
- --bg-alt: #e8eff8;
- --text: #0f172a;
- --muted: #475569;
- --border: #cbd5e1;
- --accent: #0284c7;
- --accent2: #4f46e5;
- }}
- * {{ box-sizing: border-box; margin: 0; padding: 0; }}
- 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;
- }}
- header {{
- background: var(--bg-card);
- border-bottom: 1px solid var(--border);
- padding: 16px 24px;
- display: flex;
- flex-wrap: wrap;
- justify-content: space-between;
- align-items: center;
- gap: 12px;
- position: sticky;
- top: 0;
- z-index: 20;
- }}
- .hdr-title h1 {{ font-size: 18px; font-weight: 700; }}
- .hdr-sub {{ font-size: 12px; color: var(--muted); margin-top: 2px; }}
- .controls {{ display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }}
- select, input, button {{
- background: var(--bg-alt);
- color: var(--text);
- border: 1px solid var(--border);
- border-radius: 6px;
- padding: 6px 10px;
- font-size: 13px;
- }}
- button {{ cursor: pointer; font-weight: 500; }}
- button:hover {{ border-color: var(--accent); }}
- button.active {{ background: var(--accent); color: #07101e; border-color: var(--accent); font-weight: 600; }}
- .btn-xs {{ padding: 3px 8px; font-size: 12px; }}
- .container {{ max-width: 1580px; margin: 18px auto; padding: 0 20px; }}
- .kpi-grid {{
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
- gap: 12px;
- margin-bottom: 16px;
- }}
- .kpi-card {{
- background: var(--bg-card);
- border: 1px solid var(--border);
- border-radius: 10px;
- padding: 12px 14px;
- }}
- .kpi-label {{ font-size: 12px; color: var(--muted); }}
- .kpi-val {{ font-size: 20px; font-weight: 700; margin-top: 4px; }}
- .kpi-sub {{ font-size: 12px; color: var(--muted); margin-top: 2px; }}
- .badge {{
- display: inline-block;
- padding: 2px 8px;
- border-radius: 999px;
- font-size: 11px;
- font-weight: 600;
- }}
- .badge.pass {{ background: rgba(34,197,94,0.16); color: var(--good); border: 1px solid rgba(34,197,94,0.35); }}
- .badge.warn {{ background: rgba(245,158,11,0.16); color: var(--warn); border: 1px solid rgba(245,158,11,0.35); }}
- .badge.fail {{ background: rgba(239,68,68,0.16); color: var(--bad); border: 1px solid rgba(239,68,68,0.35); }}
- .tabs {{
- display: flex;
- flex-wrap: wrap;
- gap: 8px;
- margin-bottom: 14px;
- border-bottom: 1px solid var(--border);
- padding-bottom: 10px;
- }}
- .tab-panel {{ display: none; }}
- .tab-panel.active {{ display: block; }}
- .card {{
- background: var(--bg-card);
- border: 1px solid var(--border);
- border-radius: 10px;
- padding: 14px 16px;
- margin-bottom: 16px;
- }}
- .card-hdr {{
- display: flex;
- flex-wrap: wrap;
- justify-content: space-between;
- align-items: center;
- gap: 10px;
- margin-bottom: 10px;
- }}
- .card-hdr h3 {{ font-size: 15px; font-weight: 600; }}
- .legend {{ display: flex; flex-wrap: wrap; gap: 8px 12px; font-size: 12px; color: var(--muted); }}
- .legend-item {{ display: inline-flex; align-items: center; gap: 5px; cursor: pointer; user-select: none; }}
- .legend-item.off {{ opacity: 0.35; text-decoration: line-through; }}
- .swatch {{ width: 12px; height: 3px; border-radius: 2px; display: inline-block; }}
- .chart-wrap {{ position: relative; width: 100%; height: 320px; overflow: hidden; }}
- .chart-wrap canvas {{ width: 100%; height: 100%; display: block; }}
- .table-scroll {{ overflow-x: auto; }}
- table {{ width: 100%; border-collapse: collapse; font-size: 12px; }}
- th, td {{ padding: 6px 8px; border-bottom: 1px solid var(--border); text-align: left; white-space: nowrap; }}
- th {{ background: var(--bg-alt); color: var(--muted); font-weight: 600; position: sticky; top: 0; }}
- tr:hover td {{ background: rgba(56,189,248,0.06); }}
- .mono {{ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }}
- .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: 470px;
- box-shadow: 0 8px 24px rgba(0,0,0,0.5);
- }}
- .zoom-bar {{ display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }}
- </style>
- </head>
- <body>
- <header>
- <div class="hdr-title">
- <h1>高温罩 + MemTest86 逐腔室与逐位置传感器独立解析看板 (无均值)</h1>
- <div class="hdr-sub" id="hdr-sub">加载中...</div>
- </div>
- <div class="controls">
- <label>当前工位:
- <select id="station-select"></select>
- </label>
- <button type="button" id="btn-theme">切换亮/暗主题</button>
- </div>
- </header>
- <div class="container">
- <div class="kpi-grid" id="kpi-grid"></div>
- <div class="tabs">
- <button type="button" class="tab-btn active" data-tab="tab-charts">1Hz 逐传感器曲线</button>
- <button type="button" class="tab-btn" data-tab="tab-phases">逐腔室与位置传感器统计</button>
- <button type="button" class="tab-btn" data-tab="tab-algos">MT 算法逐通道拆解</button>
- <button type="button" class="tab-btn" data-tab="tab-audit">硬件与模板审计</button>
- <button type="button" class="tab-btn" data-tab="tab-events">事件与控制台日志</button>
- </div>
- <div id="tab-charts" class="tab-panel active">
- <div class="card">
- <div class="card-hdr">
- <h3>窗口缩放 (按阶段或拖拽框选,双击复位)</h3>
- <div class="zoom-bar" id="zoom-bar"></div>
- </div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 1 · 高温罩 4 腔室 × 8 路位置温度独立曲线 (腔1前/后 .. 腔4前/后 · 无均值)</h3>
- <div class="controls">
- <button type="button" class="btn-xs" data-ct-preset="all">全8路</button>
- <button type="button" class="btn-xs" data-ct-preset="ch1">仅腔1</button>
- <button type="button" class="btn-xs" data-ct-preset="ch2">仅腔2</button>
- <button type="button" class="btn-xs" data-ct-preset="ch3">仅腔3</button>
- <button type="button" class="btn-xs" data-ct-preset="ch4">仅腔4</button>
- <button type="button" class="btn-xs" data-ct-preset="front">4路前侧</button>
- <button type="button" class="btn-xs" data-ct-preset="rear">4路后侧</button>
- </div>
- </div>
- <div class="legend" id="legend-chambers" style="margin-bottom:8px"></div>
- <div class="chart-wrap"><canvas id="chart-chambers"></canvas></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 2 · 服务器各位置温度传感器独立曲线 (DIMM · MCU BMC · MT SPD · CPU · MB · PSU · VR)</h3>
- <div class="controls">
- <button type="button" class="btn-xs" data-pos-preset="core">内存+BMC+CPU</button>
- <button type="button" class="btn-xs" data-pos-preset="vr">VR供电位置</button>
- <button type="button" class="btn-xs" data-pos-preset="all">全部点亮</button>
- </div>
- </div>
- <div class="legend" id="legend-positions" style="margin-bottom:8px"></div>
- <div class="chart-wrap"><canvas id="chart-positions"></canvas></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 3 · 各功耗轨、风扇 RPM 与高温罩控制独立曲线 (无合并)</h3>
- <div class="controls">
- <button type="button" class="btn-xs" data-pwr-preset="power">功耗轨+罩控制</button>
- <button type="button" class="btn-xs" data-pwr-preset="fans">5路服务器风扇RPM</button>
- <button type="button" class="btn-xs" data-pwr-preset="all">全部显示</button>
- </div>
- </div>
- <div class="legend" id="legend-pwr" style="margin-bottom:8px"></div>
- <div class="chart-wrap"><canvas id="chart-pwr"></canvas></div>
- </div>
- </div>
- <div id="tab-phases" class="tab-panel">
- <div class="card">
- <div class="card-hdr"><h3>高温罩 4 腔室 × 8 路温度传感器的分阶段实测范围 (min~max, 起点→终点)</h3></div>
- <div class="table-scroll" id="phase-chambers-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>服务器各位置温度传感器分阶段实测范围 (DIMM / BMC / CPU / MB / PSU / VR / MT SPD)</h3></div>
- <div class="table-scroll" id="phase-positions-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>电源/DDR/CPU 功耗轨与 5 路服务器风扇分阶段实测范围</h3></div>
- <div class="table-scroll" id="phase-power-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>降温防反弹(逐腔室 8 路起→峰反弹)与预加热移交记录</h3></div>
- <div class="table-scroll" id="cooldown-table"></div>
- <div class="table-scroll" id="handover-table" style="margin-top:12px"></div>
- </div>
- </div>
- <div id="tab-algos" class="tab-panel">
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 4 · 算法维度逐通道峰值/区间对比 (无均值)</h3>
- <div class="controls">
- <select id="algo-phase-select"></select>
- <select id="algo-metric-select">
- <option value="ddr_max">DDR0 vs DDR2 峰值功耗 (W)</option>
- <option value="dimm_max">RF DIMM0 vs DIMM1 峰值温度 (°C)</option>
- <option value="cpu_pwr_max">CPU0 vs CPU1 峰值功耗 (W)</option>
- <option value="ch_front_max">腔1前..腔4前 峰值温度 (°C)</option>
- <option value="ch_rear_max">腔1后..腔4后 峰值温度 (°C)</option>
- </select>
- </div>
- </div>
- <div class="chart-wrap"><canvas id="chart-algo"></canvas></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>MT 阶段按算法拆解(逐腔室 8 路 & 逐位置传感器实测 min~max)</h3></div>
- <div class="table-scroll" id="algo-table"></div>
- </div>
- </div>
- <div id="tab-audit" class="tab-panel">
- <div class="card">
- <div class="card-hdr"><h3>工位硬件指纹与数据完整性总表</h3></div>
- <div class="table-scroll" id="audit-overview-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>34 列模板 CSV (`*_template.csv`) 结构与逐行交叉校验</h3></div>
- <div class="table-scroll" id="template-audit-table"></div>
- </div>
- </div>
- <div id="tab-events" class="tab-panel">
- <div class="card">
- <div class="card-hdr"><h3>控制台 BIOS / MemTest86 诊断摘要</h3></div>
- <div class="table-scroll" id="console-summary-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>`master_events.jsonl` 结构化事件流水</h3>
- <div class="controls">
- <select id="event-kind-filter"><option value="">全部事件类型</option></select>
- <input type="text" id="event-search" placeholder="关键字过滤...">
- </div>
- </div>
- <div class="table-scroll" id="events-table"></div>
- </div>
- </div>
- </div>
- <div class="tooltip" id="tooltip"></div>
- <script id="embedded-data" type="application/json">{payload_json}</script>
- <script>
- (() => {{
- const DATA = JSON.parse(document.getElementById('embedded-data').textContent);
- const stationKeys = Object.keys(DATA.stations);
- let activeKey = stationKeys[0];
- let zoomStart = 0;
- let zoomEnd = null;
- let hoverIdx = null;
- let dragStartIdx = null;
- let dragCurIdx = null;
- let algoBarsCache = [];
- const chamberSeries = [
- {{ key: 'ct1_ch1_front', label: '腔1前(CT1)', color: '#ef4444', width: 1.6 }},
- {{ key: 'ct2_ch1_rear', label: '腔1后(CT2)', color: '#fca5a5', width: 1.4, dash: [4, 2] }},
- {{ key: 'ct3_ch2_front', label: '腔2前(CT3)', color: '#f59e0b', width: 1.6 }},
- {{ key: 'ct4_ch2_rear', label: '腔2后(CT4)', color: '#fcd34d', width: 1.4, dash: [4, 2] }},
- {{ key: 'ct5_ch3_front', label: '腔3前(CT5)', color: '#22c55e', width: 1.6 }},
- {{ key: 'ct6_ch3_rear', label: '腔3后(CT6)', color: '#86efac', width: 1.4, dash: [4, 2] }},
- {{ key: 'ct7_ch4_front', label: '腔4前(CT7)', color: '#38bdf8', width: 1.6 }},
- {{ key: 'ct8_ch4_rear', label: '腔4后(CT8)', color: '#a855f7', width: 1.5, dash: [4, 2] }},
- {{ key: 'tgt', label: '目标温度', color: '#f43f5e', width: 1.4, dash: [6, 4] }},
- ];
- const enabledChambers = new Set(chamberSeries.map(s => s.key));
- const fixedPositionSeries = [
- {{ key: 'rf_dimm_cpu0_a_c', label: 'RF DIMM CPU0_A', color: '#38bdf8', width: 1.8, group: 'core' }},
- {{ key: 'rf_dimm_cpu1_a_c', label: 'RF DIMM CPU1_A', color: '#818cf8', width: 1.8, group: 'core' }},
- {{ key: 'mt_spd_dimm0_c', label: 'MT SPD DIMM0', color: '#22d3ee', width: 1.2, dash: [3, 2], group: 'core' }},
- {{ key: 'mt_spd_dimm1_c', label: 'MT SPD DIMM1', color: '#c084fc', width: 1.2, dash: [3, 2], group: 'core' }},
- {{ key: 'rf_cpu0_c', label: 'RF CPU0', color: '#22c55e', width: 1.4, group: 'core' }},
- {{ key: 'rf_cpu1_c', label: 'RF CPU1', color: '#84cc16', width: 1.4, group: 'core' }},
- {{ key: 'mt_cpu_c', label: 'MT CPU', color: '#10b981', width: 1.1, dash: [2, 2], group: 'vr' }},
- {{ key: 'rf_mb_c', label: 'RF 主板 MB', color: '#94a3b8', width: 1.2, group: 'core' }},
- {{ key: 'rf_psu0_c', label: 'RF PSU0', color: '#64748b', width: 1.2, group: 'vr' }},
- {{ key: 'rf_pvccin_cpu0_c', label: 'PVCCIN CPU0', color: '#fb7185', width: 1.2, group: 'vr' }},
- {{ key: 'rf_pvccin_cpu1_c', label: 'PVCCIN CPU1', color: '#f43f5e', width: 1.2, dash: [4, 2], group: 'vr' }},
- {{ key: 'rf_pvccfa_cpu0_c', label: 'PVCCFA CPU0', color: '#fbbf24', width: 1.2, group: 'vr' }},
- {{ key: 'rf_pvccfa_cpu1_c', label: 'PVCCFA CPU1', color: '#d97706', width: 1.2, dash: [4, 2], group: 'vr' }},
- {{ key: 'rf_pvccd_cpu0_c', label: 'PVCCD CPU0', color: '#34d399', width: 1.2, group: 'vr' }},
- {{ key: 'rf_pvccd_cpu1_c', label: 'PVCCD CPU1', color: '#059669', width: 1.2, dash: [4, 2], group: 'vr' }},
- ];
- const bmcPalette = ['#f97316', '#ec4899', '#eab308', '#14b8a6', '#a855f7', '#06b6d4'];
- let activePositionSeries = [];
- let enabledPositions = new Set();
- const pwrSeries = [
- {{ key: 'rf_total_power_w', label: '整机功耗(W)', color: '#38bdf8', width: 1.6, axis: 'left', group: 'power' }},
- {{ key: 'rf_cpu0_power_avg_w', label: 'CPU0功耗(W)', color: '#818cf8', width: 1.3, axis: 'left', group: 'power' }},
- {{ key: 'rf_cpu1_power_avg_w', label: 'CPU1功耗(W)', color: '#c084fc', width: 1.3, axis: 'left', group: 'power' }},
- {{ key: 'rf_ddr0_power_w', label: 'DDR0(W)×10', color: '#22c55e', width: 1.5, scale: 10, axis: 'left', group: 'power' }},
- {{ key: 'rf_ddr1_power_w', label: 'DDR1(W)×10', color: '#10b981', width: 1.1, scale: 10, axis: 'left', group: 'extra' }},
- {{ key: 'rf_ddr2_power_w', label: 'DDR2(W)×10', color: '#f59e0b', width: 1.5, scale: 10, axis: 'left', group: 'power' }},
- {{ key: 'rf_ddr3_power_w', label: 'DDR3(W)×10', color: '#fbbf24', width: 1.1, scale: 10, axis: 'left', group: 'extra' }},
- {{ key: 'rf_dimm_power_cpu0_w', label: 'DIMM0功耗×10', color: '#06b6d4', width: 1.2, scale: 10, axis: 'left', group: 'extra' }},
- {{ key: 'rf_dimm_power_cpu1_w', label: 'DIMM1功耗×10', color: '#ec4899', width: 1.2, scale: 10, axis: 'left', group: 'extra' }},
- {{ key: 'rf_fan1_rpm', label: 'FAN1(RPM)', color: '#38bdf8', width: 1.3, axis: 'left', group: 'fans' }},
- {{ key: 'rf_fan2_rpm', label: 'FAN2(RPM)', color: '#22c55e', width: 1.3, axis: 'left', group: 'fans' }},
- {{ key: 'rf_fan3_rpm', label: 'FAN3(RPM)', color: '#f59e0b', width: 1.3, axis: 'left', group: 'fans' }},
- {{ key: 'rf_fan4_rpm', label: 'FAN4(RPM)', color: '#a855f7', width: 1.3, axis: 'left', group: 'fans' }},
- {{ key: 'rf_fan5_rpm', label: 'FAN5(RPM)', color: '#ef4444', width: 1.3, axis: 'left', group: 'fans' }},
- {{ key: 'cmd_ptc_pct', label: '罩PTC(%)', color: '#ef4444', width: 1.2, axis: 'right', group: 'power' }},
- {{ key: 'cmd_fan_front_pct', label: '罩前扇(%)', color: '#06b6d4', width: 1.2, axis: 'right', group: 'power' }},
- {{ key: 'cmd_fan_rear_pct', label: '罩后扇(%)', color: '#fb7185', width: 1.2, dash: [3, 2], axis: 'right', group: 'power' }},
- ];
- const enabledPwr = new Set(pwrSeries.filter(s => s.group === 'power').map(s => s.key));
- const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[c]));
- const fmtR = (st, unit='°C') => st ? `${{st.min}}~${{st.max}}${{unit}} (${{st.start}}→${{st.end}})` : '-';
- const fmtMM = (st, unit='') => st ? `${{st.min}}~${{st.max}}${{unit}}` : '-';
- document.getElementById('hdr-sub').textContent =
- `来源: ${{DATA.meta.input_path}} (${{DATA.meta.source_kind}}) | 工位数: ${{DATA.meta.station_count}} | 总样本: ${{DATA.meta.total_1hz_rows.toLocaleString()}} 行 | 模式: 逐腔室/位置单独解析 (无均值)`;
- const sel = document.getElementById('station-select');
- stationKeys.forEach(k => {{
- const opt = document.createElement('option');
- opt.value = k;
- const s = DATA.stations[k];
- opt.textContent = `${{k}} (${{s.integrity.master_rows}}行 · ${{(s.station_info.cpu_names[0] || '').replace('Intel(R) Xeon(R) ', '')}})`;
- sel.appendChild(opt);
- }});
- sel.addEventListener('change', () => {{
- activeKey = sel.value;
- zoomStart = 0;
- zoomEnd = null;
- hoverIdx = null;
- renderStation();
- }});
- document.getElementById('btn-theme').addEventListener('click', () => {{
- document.body.classList.toggle('light');
- drawCharts();
- drawAlgoChart();
- }});
- document.querySelectorAll('.tab-btn').forEach(btn => {{
- btn.addEventListener('click', () => {{
- document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
- document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
- btn.classList.add('active');
- document.getElementById(btn.dataset.tab).classList.add('active');
- if (btn.dataset.tab === 'tab-charts') drawCharts();
- if (btn.dataset.tab === 'tab-algos') drawAlgoChart();
- }});
- }});
- function buildLegends() {{
- const ser = DATA.series[activeKey];
- const bmcItems = (ser.active_bmc_channels || []).map((b, idx) => ({{
- key: b.col, label: `MCU ${{b.label}}`, color: bmcPalette[idx % bmcPalette.length], width: 1.5, group: 'core',
- }}));
- activePositionSeries = [...bmcItems, ...fixedPositionSeries];
- enabledPositions = new Set(activePositionSeries.filter(s => s.group === 'core').map(s => s.key));
- const make = (elId, list, set) => {{
- const el = document.getElementById(elId);
- el.innerHTML = '';
- list.forEach(item => {{
- const sp = document.createElement('span');
- sp.className = 'legend-item' + (set.has(item.key) ? '' : ' off');
- sp.innerHTML = `<span class="swatch" style="background:${{item.color}}"></span>${{esc(item.label)}}`;
- sp.onclick = () => {{
- if (set.has(item.key)) set.delete(item.key); else set.add(item.key);
- sp.classList.toggle('off');
- drawCharts();
- }};
- el.appendChild(sp);
- }});
- }};
- make('legend-chambers', chamberSeries, enabledChambers);
- make('legend-positions', activePositionSeries, enabledPositions);
- make('legend-pwr', pwrSeries, enabledPwr);
- }}
- document.querySelectorAll('[data-ct-preset]').forEach(btn => {{
- btn.onclick = () => {{
- const p = btn.dataset.ctPreset;
- enabledChambers.clear();
- chamberSeries.forEach(s => {{
- if (p === 'all' || s.key === 'tgt') enabledChambers.add(s.key);
- else if (p === 'ch1' && s.key.includes('ch1')) enabledChambers.add(s.key);
- else if (p === 'ch2' && s.key.includes('ch2')) enabledChambers.add(s.key);
- else if (p === 'ch3' && s.key.includes('ch3')) enabledChambers.add(s.key);
- else if (p === 'ch4' && s.key.includes('ch4')) enabledChambers.add(s.key);
- else if (p === 'front' && s.key.endsWith('_front')) enabledChambers.add(s.key);
- else if (p === 'rear' && s.key.endsWith('_rear')) enabledChambers.add(s.key);
- }});
- buildLegendSync('legend-chambers', chamberSeries, enabledChambers);
- drawCharts();
- }};
- }});
- document.querySelectorAll('[data-pos-preset]').forEach(btn => {{
- btn.onclick = () => {{
- const p = btn.dataset.posPreset;
- enabledPositions.clear();
- activePositionSeries.forEach(s => {{
- if (p === 'all' || s.group === p) enabledPositions.add(s.key);
- }});
- buildLegendSync('legend-positions', activePositionSeries, enabledPositions);
- drawCharts();
- }};
- }});
- document.querySelectorAll('[data-pwr-preset]').forEach(btn => {{
- btn.onclick = () => {{
- const p = btn.dataset.pwrPreset;
- enabledPwr.clear();
- pwrSeries.forEach(s => {{
- if (p === 'all' || s.group === p) enabledPwr.add(s.key);
- }});
- buildLegendSync('legend-pwr', pwrSeries, enabledPwr);
- drawCharts();
- }};
- }});
- function buildLegendSync(elId, list, set) {{
- const el = document.getElementById(elId);
- Array.from(el.children).forEach((node, idx) => {{
- node.classList.toggle('off', !set.has(list[idx].key));
- }});
- }}
- function renderKpis() {{
- const s = DATA.stations[activeKey];
- const m = DATA.meta;
- const integ = s.integrity;
- const info = s.station_info;
- const ov = s.overall_sensors || {{}};
- const cs = ov.chamber_sensors || {{}};
- const rf = ov.redfish_temps || {{}};
- const errCls = integ.mt_total_errors === 0 ? 'pass' : 'fail';
- const tplCls = integ.template_all_pass ? 'pass' : 'warn';
- const resCnt = integ.residual_prelaunch_findings.reduce((a, b) => a + b.residual_rows, 0);
- const ctKeys = Object.keys(cs).filter(k => cs[k]);
- const ctMinAll = ctKeys.length ? Math.min(...ctKeys.map(k => cs[k].min)) : '-';
- const ctMaxAll = ctKeys.length ? Math.max(...ctKeys.map(k => cs[k].max)) : '-';
- document.getElementById('kpi-grid').innerHTML = `
- <div class="kpi-card">
- <div class="kpi-label">全套样本 / 当前工位</div>
- <div class="kpi-val">${{m.total_1hz_rows.toLocaleString()}} <span style="font-size:12px;color:var(--muted)">行</span></div>
- <div class="kpi-sub">${{esc(info.station_id)}}: ${{integ.master_rows.toLocaleString()}}行 (${{esc(info.total_duration_hms || '-')}})</div>
- </div>
- <div class="kpi-card">
- <div class="kpi-label">8路腔室独立传感器全量范围</div>
- <div class="kpi-val">${{ctMinAll}}~${{ctMaxAll}}°C</div>
- <div class="kpi-sub">腔1..4 前/后全部单独展示 (无均值)</div>
- </div>
- <div class="kpi-card">
- <div class="kpi-label">RF DIMM0 / DIMM1 独立范围</div>
- <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>
- <div class="kpi-sub">有效 BMC 通道: ${{esc((info.active_bmc_channels || []).map(b=>b.key).join(', '))}}</div>
- </div>
- <div class="kpi-card">
- <div class="kpi-label">MT 错误与模板审计</div>
- <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>
- <div class="kpi-sub">${{esc(integ.schema_version)}} · 残留标签 ${{resCnt}}s · 失配 ${{integ.template_total_mismatches}}</div>
- </div>
- `;
- }}
- function buildZoomBar() {{
- const bar = document.getElementById('zoom-bar');
- const ser = DATA.series[activeKey];
- const n = ser.cols.seq.length;
- if (zoomEnd === null || zoomEnd > n) zoomEnd = n;
- bar.innerHTML = '';
- const mkBtn = (label, a, b) => {{
- const btn = document.createElement('button');
- btn.type = 'button';
- btn.textContent = label;
- if (zoomStart === a && zoomEnd === b) btn.classList.add('active');
- btn.onclick = () => {{ zoomStart = a; zoomEnd = b; buildZoomBar(); drawCharts(); }};
- bar.appendChild(btn);
- }};
- mkBtn(`全过程 (${{n}}s)`, 0, n);
- [
- ['Phase0 初降温', p => p.startsWith('phase0_')],
- ['Test1 70°C预热', p => p.startsWith('test1_')],
- ['Test2 70°C MT', p => p.startsWith('test2_')],
- ['间歇降温→40°C', p => p.startsWith('phase_inter_')],
- ['Test3 40°C MT', p => p.startsWith('test3_')],
- ].forEach(([label, pred]) => {{
- let lo = null, hi = null;
- for (let i = 0; i < n; i++) {{
- const p = ser.phase_names[ser.cols.ph[i]];
- if (pred(p)) {{ if (lo === null) lo = i; hi = i + 1; }}
- }}
- if (lo !== null) mkBtn(label, lo, hi);
- }});
- }}
- function setupCanvas(canvas) {{
- const rect = canvas.parentElement.getBoundingClientRect();
- const dpr = window.devicePixelRatio || 1;
- const w = Math.max(320, Math.floor(rect.width));
- const h = Math.max(240, Math.floor(rect.height));
- canvas.width = w * dpr;
- canvas.height = h * dpr;
- const ctx = canvas.getContext('2d');
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
- return {{ ctx, w, h }};
- }}
- function drawTimeSeries(canvasId, seriesList, enabledSet, rightAxis) {{
- const canvas = document.getElementById(canvasId);
- if (!canvas) return;
- const {{ ctx, w, h }} = setupCanvas(canvas);
- const ser = DATA.series[activeKey];
- const cols = ser.cols;
- const n = cols.seq.length;
- const sIdx = Math.max(0, zoomStart);
- const eIdx = Math.min(n, zoomEnd ?? n);
- const span = Math.max(1, eIdx - sIdx);
- const pad = {{ l: 54, r: rightAxis ? 48 : 18, t: 14, b: 26 }};
- const pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
- const cs = getComputedStyle(document.body);
- const borderCol = cs.getPropertyValue('--border').trim();
- const mutedCol = cs.getPropertyValue('--muted').trim();
- let yMin = Infinity, yMax = -Infinity;
- seriesList.forEach(s => {{
- if (!enabledSet.has(s.key) || s.axis === 'right') return;
- const arr = cols[s.key];
- if (!arr) return;
- const sc = s.scale || 1;
- for (let i = sIdx; i < eIdx; i++) {{
- const v = arr[i];
- if (v !== null && v !== undefined) {{
- const sv = v * sc;
- if (sv < yMin) yMin = sv;
- if (sv > yMax) yMax = sv;
- }}
- }}
- }});
- if (!isFinite(yMin)) {{ yMin = 0; yMax = 100; }}
- const yPad = Math.max(2, (yMax - yMin) * 0.08);
- yMin = Math.floor(yMin - yPad);
- yMax = Math.ceil(yMax + yPad);
- ctx.strokeStyle = borderCol;
- ctx.lineWidth = 1;
- ctx.font = '11px sans-serif';
- ctx.fillStyle = mutedCol;
- for (let g = 0; g <= 5; g++) {{
- const yy = pad.t + ph - (g / 5) * ph;
- ctx.beginPath(); ctx.moveTo(pad.l, yy); ctx.lineTo(pad.l + pw, yy); ctx.stroke();
- ctx.textAlign = 'right';
- ctx.fillText((yMin + (g / 5) * (yMax - yMin)).toFixed(0), pad.l - 6, yy + 4);
- if (rightAxis) {{
- ctx.textAlign = 'left';
- ctx.fillText((g * 20) + '%', pad.l + pw + 6, yy + 4);
- }}
- }}
- ctx.textAlign = 'center';
- for (let t = 0; t <= 6; t++) {{
- const idx = Math.min(n - 1, sIdx + Math.floor((t / 6) * (span - 1)));
- const xx = pad.l + (t / 6) * pw;
- ctx.fillText(cols.ts[idx] || '', xx, h - 7);
- }}
- ctx.fillStyle = 'rgba(245,158,11,0.12)';
- for (let i = sIdx; i < eIdx; i++) {{
- if (cols.res[i]) {{
- const x1 = pad.l + ((i - sIdx) / span) * pw;
- const x2 = pad.l + ((i + 1 - sIdx) / span) * pw;
- ctx.fillRect(x1, pad.t, Math.max(1, x2 - x1), ph);
- }}
- }}
- const xAt = i => pad.l + ((i - sIdx) / Math.max(1, span - 1)) * pw;
- const yLeft = v => pad.t + ph - ((v - yMin) / Math.max(1e-6, yMax - yMin)) * ph;
- const yRight = v => pad.t + ph - (Math.max(0, Math.min(100, v)) / 100) * ph;
- const stride = Math.max(1, Math.floor(span / (pw * 2)));
- seriesList.forEach(s => {{
- if (!enabledSet.has(s.key)) return;
- const arr = cols[s.key];
- if (!arr) return;
- const sc = s.scale || 1;
- const yf = s.axis === 'right' ? yRight : yLeft;
- ctx.save();
- ctx.strokeStyle = s.color;
- ctx.lineWidth = s.width;
- if (s.dash) ctx.setLineDash(s.dash);
- ctx.beginPath();
- let started = false;
- for (let i = sIdx; i < eIdx; i += stride) {{
- const v = arr[i];
- if (v === null || v === undefined) {{ started = false; continue; }}
- const x = xAt(i), y = yf(v * sc);
- if (!started) {{ ctx.moveTo(x, y); started = true; }}
- else ctx.lineTo(x, y);
- }}
- ctx.stroke();
- ctx.restore();
- }});
- if (dragStartIdx !== null && dragCurIdx !== null && dragStartIdx !== dragCurIdx) {{
- const lo = Math.max(sIdx, Math.min(dragStartIdx, dragCurIdx));
- const hi = Math.min(eIdx - 1, Math.max(dragStartIdx, dragCurIdx));
- const x1 = xAt(lo), x2 = xAt(hi);
- ctx.fillStyle = 'rgba(56,189,248,0.18)';
- ctx.fillRect(x1, pad.t, Math.max(2, x2 - x1), ph);
- }}
- if (hoverIdx !== null && hoverIdx >= sIdx && hoverIdx < eIdx) {{
- const hx = xAt(hoverIdx);
- ctx.strokeStyle = 'rgba(255,255,255,0.45)';
- ctx.lineWidth = 1;
- ctx.beginPath(); ctx.moveTo(hx, pad.t); ctx.lineTo(hx, pad.t + ph); ctx.stroke();
- }}
- }}
- function attachHover(canvasId, rightAxis) {{
- const canvas = document.getElementById(canvasId);
- const tip = document.getElementById('tooltip');
- const idxFromEvent = ev => {{
- const rect = canvas.getBoundingClientRect();
- const x = ev.clientX - rect.left;
- const ser = DATA.series[activeKey];
- const n = ser.cols.seq.length;
- const sIdx = Math.max(0, zoomStart);
- const eIdx = Math.min(n, zoomEnd ?? n);
- const padL = 54, padR = rightAxis ? 48 : 18;
- const pw = rect.width - padL - padR;
- const ratio = Math.max(0, Math.min(1, (x - padL) / Math.max(1, pw)));
- return Math.min(n - 1, sIdx + Math.round(ratio * Math.max(0, eIdx - sIdx - 1)));
- }};
- canvas.onmousedown = ev => {{ dragStartIdx = idxFromEvent(ev); dragCurIdx = dragStartIdx; }};
- canvas.onmouseup = () => {{
- if (dragStartIdx !== null && dragCurIdx !== null && Math.abs(dragCurIdx - dragStartIdx) >= 5) {{
- zoomStart = Math.min(dragStartIdx, dragCurIdx);
- zoomEnd = Math.max(dragStartIdx, dragCurIdx) + 1;
- buildZoomBar();
- }}
- dragStartIdx = null; dragCurIdx = null; drawCharts();
- }};
- canvas.ondblclick = () => {{
- const ser = DATA.series[activeKey];
- zoomStart = 0; zoomEnd = ser.cols.seq.length; buildZoomBar(); drawCharts();
- }};
- canvas.onmousemove = ev => {{
- const ser = DATA.series[activeKey];
- hoverIdx = idxFromEvent(ev);
- if (dragStartIdx !== null) dragCurIdx = hoverIdx;
- drawCharts();
- const c = ser.cols;
- const i = hoverIdx;
- const bmcTxt = (ser.active_bmc_channels || []).map(b => `${{b.key}}:${{c[b.col]?.[i] ?? '-'}}`).join(' · ');
- tip.style.display = 'block';
- tip.style.left = Math.min(window.innerWidth - 480, ev.clientX + 14) + 'px';
- tip.style.top = Math.min(window.innerHeight - 310, ev.clientY + 14) + 'px';
- tip.innerHTML = `
- <div><b>${{esc(activeKey)}}</b> · #${{c.seq[i]}} · <b>${{esc(c.ts[i])}}</b> (${{c.t[i]}}s)</div>
- <div>阶段: <span class="mono">${{esc(ser.phase_names[c.ph[i]])}}</span></div>
- <div>算法: <b>${{esc(ser.algo_names[c.al[i]])}}</b>${{c.res[i] ? ' <span class="badge warn">残留标签</span>' : ''}}</div>
- <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>
- <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>
- <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>
- <div>RF DIMM0/1: <b>${{c.rf_dimm_cpu0_a_c[i]}} / ${{c.rf_dimm_cpu1_a_c[i]}}°C</b> · ${{esc(bmcTxt)}}</div>
- <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>
- <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>
- <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>
- `;
- }};
- canvas.onmouseleave = () => {{ hoverIdx = null; dragStartIdx = null; dragCurIdx = null; tip.style.display = 'none'; drawCharts(); }};
- }}
- function drawCharts() {{
- drawTimeSeries('chart-chambers', chamberSeries, enabledChambers, false);
- drawTimeSeries('chart-positions', activePositionSeries, enabledPositions, false);
- drawTimeSeries('chart-pwr', pwrSeries, enabledPwr, true);
- }}
- function renderPhaseTables() {{
- const s = DATA.stations[activeKey];
- const bmcKeys = (s.station_info.active_bmc_channels || []).map(b => b.key);
- 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>`;
- Object.entries(s.phases_detail).forEach(([fn, p]) => {{
- const cs = p.chamber_sensors || {{}};
- hc1 += `<tr><td class="mono">${{esc(fn.replace('_comprehensive.csv',''))}}</td><td class="mono">${{p.rows}} / ${{esc(p.duration_hms)}}</td>` +
- ['ct1_ch1_front','ct2_ch1_rear','ct3_ch2_front','ct4_ch2_rear','ct5_ch3_front','ct6_ch3_rear','ct7_ch4_front','ct8_ch4_rear']
- .map(col => `<td class="mono">${{esc(fmtR(cs[col]))}}</td>`).join('') + `</tr>`;
- }});
- hc1 += '</tbody></table>';
- document.getElementById('phase-chambers-table').innerHTML = hc1;
- 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>`;
- Object.entries(s.phases_detail).forEach(([fn, p]) => {{
- const rf = p.redfish_temps || {{}}, bmc = p.bmc_channels || {{}}, mt = p.mt_console_temps || {{}};
- hp2 += `<tr>
- <td class="mono">${{esc(fn.replace('_comprehensive.csv',''))}}</td>
- <td class="mono">${{esc(fmtR(rf.rf_dimm_cpu0_a_c))}}</td>
- <td class="mono">${{esc(fmtR(rf.rf_dimm_cpu1_a_c))}}</td>
- ${{bmcKeys.map(k => `<td class="mono">${{esc(fmtR(bmc[k]))}}</td>`).join('')}}
- <td class="mono">${{esc(fmtMM(mt.mt_spd_dimm0_c))}} / ${{esc(fmtMM(mt.mt_spd_dimm1_c))}}</td>
- <td class="mono">${{esc(fmtMM(rf.rf_cpu0_c))}} / ${{esc(fmtMM(rf.rf_cpu1_c))}}</td>
- <td class="mono">${{esc(fmtMM(rf.rf_mb_c))}} / ${{esc(fmtMM(rf.rf_psu0_c))}}</td>
- <td class="mono">${{esc(fmtMM(rf.rf_pvccin_cpu0_c))}} / ${{esc(fmtMM(rf.rf_pvccin_cpu1_c))}}</td>
- <td class="mono">${{esc(fmtMM(rf.rf_pvccfa_cpu0_c))}} / ${{esc(fmtMM(rf.rf_pvccfa_cpu1_c))}}</td>
- <td class="mono">${{esc(fmtMM(rf.rf_pvccd_cpu0_c))}} / ${{esc(fmtMM(rf.rf_pvccd_cpu1_c))}}</td>
- </tr>`;
- }});
- hp2 += '</tbody></table>';
- document.getElementById('phase-positions-table').innerHTML = hp2;
- 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>`;
- Object.entries(s.phases_detail).forEach(([fn, p]) => {{
- const pw = p.power_rails || {{}}, fa = p.fans_and_actuators || {{}};
- hp3 += `<tr>
- <td class="mono">${{esc(fn.replace('_comprehensive.csv',''))}}</td>
- <td class="mono">${{esc(fmtMM(pw.rf_total_power_w, 'W'))}}</td>
- <td class="mono">${{esc(fmtMM(pw.rf_psu0_pin_w))}} / ${{esc(fmtMM(pw.rf_psu0_pout_w))}}W</td>
- <td class="mono">${{[0,1,2,3].map(i => fmtMM(pw[`rf_ddr${{i}}_power_w`])).join(' / ')}}W</td>
- <td class="mono">${{esc(fmtMM(pw.rf_dimm_power_cpu0_w))}} / ${{esc(fmtMM(pw.rf_dimm_power_cpu1_w))}}W</td>
- <td class="mono">${{esc(fmtMM(pw.rf_cpu0_power_avg_w))}} / ${{esc(fmtMM(pw.rf_cpu1_power_avg_w))}}W</td>
- <td class="mono">${{esc(fmtMM(fa.cmd_ptc_pct,'%'))}} / ${{esc(fmtMM(fa.cmd_fan_front_pct,'%'))}} / ${{esc(fmtMM(fa.cmd_fan_rear_pct,'%'))}}</td>
- <td class="mono">${{[1,2,3,4,5].map(i => fmtMM(fa[`rf_fan${{i}}_rpm`])).join(' / ')}}</td>
- </tr>`;
- }});
- hp3 += '</tbody></table>';
- document.getElementById('phase-power-table').innerHTML = hp3;
- const cdMap = {{}};
- s.cooldown_outcomes.forEach(c => {{ cdMap[c.phase_group + '#' + c.round] = c; }});
- 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>`;
- s.antirebound_soaks.forEach(sk => {{
- const cd = cdMap[sk.phase_group + '#' + sk.round] || {{}};
- const pcr = sk.per_chamber_rebound || {{}};
- const pairCell = (fc, rc) => {{
- const f = pcr[fc], r = pcr[rc];
- const fs = f ? `${{f.start}}→${{f.peak}}(+${{f.rebound}})` : '-';
- const rs = r ? `${{r.start}}→${{r.peak}}(+${{r.rebound}})` : '-';
- return `<td class="mono">${{fs}} / ${{rs}}</td>`;
- }};
- hcd += `<tr>
- <td class="mono">${{esc(sk.phase_group)}}</td>
- <td>R${{sk.round}}</td>
- <td>${{esc(cd.outcome || '-')}} (${{cd.duration_s ?? '-'}}s)</td>
- ${{pairCell('ct1_ch1_front','ct2_ch1_rear')}}
- ${{pairCell('ct3_ch2_front','ct4_ch2_rear')}}
- ${{pairCell('ct5_ch3_front','ct6_ch3_rear')}}
- ${{pairCell('ct7_ch4_front','ct8_ch4_rear')}}
- <td class="mono">${{sk.dimm0_end_csv ?? '-'}} / ${{sk.dimm1_end_csv ?? '-'}}°C</td>
- </tr>`;
- }});
- hcd += '</tbody></table>';
- document.getElementById('cooldown-table').innerHTML = hcd;
- 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>`;
- s.preheat_handovers.forEach(hv => {{
- const p3 = hv.post_300s_sensors || {{}};
- hh += `<tr>
- <td class="mono">${{esc(hv.phase)}}</td>
- <td class="mono">${{(hv.preheat_elapsed_s ?? 0).toFixed(1)}}s</td>
- <td class="mono">${{esc(JSON.stringify(hv.ct8 || []))}}</td>
- <td class="mono">${{hv.bmc0 ?? '-'}} / ${{hv.bmc12 ?? '-'}}°C</td>
- <td class="mono">${{esc(JSON.stringify(p3.ct8 || []))}}</td>
- <td class="mono">${{p3.rf_dimm_cpu0_a_c ?? '-'}} / ${{p3.rf_dimm_cpu1_a_c ?? '-'}}°C</td>
- </tr>`;
- }});
- hh += '</tbody></table>';
- document.getElementById('handover-table').innerHTML = hh;
- }}
- function populateAlgoSelectors() {{
- const pSel = document.getElementById('algo-phase-select');
- const prev = pSel.value;
- const allPhases = new Set();
- stationKeys.forEach(k => Object.keys(DATA.stations[k].algorithms_by_phase).forEach(p => allPhases.add(p)));
- pSel.innerHTML = '';
- Array.from(allPhases).forEach(p => {{
- const o = document.createElement('option');
- o.value = p; o.textContent = p;
- pSel.appendChild(o);
- }});
- if (prev && allPhases.has(prev)) pSel.value = prev;
- }}
- function drawAlgoChart() {{
- const canvas = document.getElementById('chart-algo');
- if (!canvas) return;
- const {{ ctx, w, h }} = setupCanvas(canvas);
- const phase = document.getElementById('algo-phase-select').value;
- const metric = document.getElementById('algo-metric-select').value;
- const s = DATA.stations[activeKey];
- const algos = s.algorithms_by_phase[phase] || {{}};
- const entries = Object.entries(algos).filter(([, v]) => v.test_num !== null || v.samples_s >= 5);
- const pad = {{ l: 50, r: 18, t: 28, b: 64 }};
- const pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
- const cs = getComputedStyle(document.body);
- const borderCol = cs.getPropertyValue('--border').trim();
- const mutedCol = cs.getPropertyValue('--muted').trim();
- let maxV = 1;
- const seriesColors = ['#38bdf8', '#818cf8', '#22c55e', '#f59e0b'];
- const bars = entries.map(([name, av]) => {{
- const pwR = av.power_rails || {{}}, rf = av.redfish_temps || {{}}, chS = av.chamber_sensors || {{}};
- let vals = [];
- if (metric === 'ddr_max') {{
- vals = [(pwR.rf_ddr0_power_w || {{}}).max || 0, (pwR.rf_ddr2_power_w || {{}}).max || 0];
- }} else if (metric === 'dimm_max') {{
- vals = [(rf.rf_dimm_cpu0_a_c || {{}}).max || 0, (rf.rf_dimm_cpu1_a_c || {{}}).max || 0];
- }} else if (metric === 'cpu_pwr_max') {{
- vals = [(pwR.rf_cpu0_power_avg_w || {{}}).max || 0, (pwR.rf_cpu1_power_avg_w || {{}}).max || 0];
- }} else if (metric === 'ch_front_max') {{
- vals = ['ct1_ch1_front','ct3_ch2_front','ct5_ch3_front','ct7_ch4_front'].map(k => (chS[k] || {{}}).max || 0);
- }} else {{
- vals = ['ct2_ch1_rear','ct4_ch2_rear','ct6_ch3_rear','ct8_ch4_rear'].map(k => (chS[k] || {{}}).max || 0);
- }}
- maxV = Math.max(maxV, ...vals);
- return {{ label: av.test_num !== null ? 'T' + av.test_num : name.slice(0, 10), vals, asym: av.is_asymmetric_load }};
- }});
- maxV = Math.ceil(maxV * 1.15);
- ctx.strokeStyle = borderCol;
- ctx.font = '11px sans-serif';
- ctx.fillStyle = mutedCol;
- 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((maxV * g / 4).toFixed(1), pad.l - 6, yy + 4);
- }}
- const slotW = pw / Math.max(1, bars.length);
- algoBarsCache = [];
- bars.forEach((b, idx) => {{
- const k = b.vals.length;
- const bw = Math.max(3, Math.min(18, (slotW * 0.78) / k));
- const startX = pad.l + idx * slotW + (slotW - bw * k) / 2;
- b.vals.forEach((v, j) => {{
- const hh = (v / maxV) * ph;
- ctx.fillStyle = (metric === 'ddr_max' && b.asym) ? (j === 0 ? '#ef4444' : '#f59e0b') : seriesColors[j % seriesColors.length];
- ctx.fillRect(startX + j * bw, pad.t + ph - hh, Math.max(2, bw - 1), hh);
- }});
- ctx.fillStyle = mutedCol;
- ctx.textAlign = 'center';
- ctx.fillText(b.label, pad.l + idx * slotW + slotW / 2, pad.t + ph + 16);
- const entry = entries[idx];
- algoBarsCache.push({{ x1: pad.l + idx * slotW, x2: pad.l + (idx + 1) * slotW, name: entry[0], av: entry[1] }});
- }});
- const legendLabels = metric === 'ddr_max' ? ['DDR0 峰值(W)', 'DDR2 峰值(W)']
- : metric === 'dimm_max' ? ['DIMM0 峰值(°C)', 'DIMM1 峰值(°C)']
- : metric === 'cpu_pwr_max' ? ['CPU0 峰值(W)', 'CPU1 峰值(W)']
- : metric === 'ch_front_max' ? ['腔1前', '腔2前', '腔3前', '腔4前']
- : ['腔1后', '腔2后', '腔3后', '腔4后'];
- ctx.textAlign = 'left';
- let lx = pad.l;
- legendLabels.forEach((lbl, j) => {{
- ctx.fillStyle = seriesColors[j % seriesColors.length];
- ctx.fillRect(lx, 6, 10, 10);
- ctx.fillStyle = mutedCol;
- ctx.fillText(lbl, lx + 14, 15);
- lx += 14 + lbl.length * 9 + 18;
- }});
- const tip = document.getElementById('tooltip');
- canvas.onmousemove = ev => {{
- const rect = canvas.getBoundingClientRect();
- const x = ev.clientX - rect.left;
- const hit = algoBarsCache.find(b => x >= b.x1 && x <= b.x2);
- if (!hit) {{ tip.style.display = 'none'; return; }}
- const av = hit.av, ch = av.chamber_sensors || {{}}, rf = av.redfish_temps || {{}}, pwR = av.power_rails || {{}};
- tip.style.display = 'block';
- tip.style.left = Math.min(window.innerWidth - 460, ev.clientX + 14) + 'px';
- tip.style.top = Math.min(window.innerHeight - 250, ev.clientY + 14) + 'px';
- tip.innerHTML = `
- <div><b>${{esc(hit.name)}}</b> (${{av.samples_s}}s · Console:${{av.console_exec_s ?? '-'}}s)</div>
- <div>DIMM0 / DIMM1: <b>${{fmtMM(rf.rf_dimm_cpu0_a_c, '°C')}}</b> / <b>${{fmtMM(rf.rf_dimm_cpu1_a_c, '°C')}}</b></div>
- <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>
- <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>
- <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>
- <div>CPU0 / CPU1 功耗: ${{fmtMM(pwR.rf_cpu0_power_avg_w, 'W')}} / ${{fmtMM(pwR.rf_cpu1_power_avg_w, 'W')}}</div>
- `;
- }};
- canvas.onmouseleave = () => {{ tip.style.display = 'none'; }};
- }}
- function renderAlgoTable() {{
- const phase = document.getElementById('algo-phase-select').value;
- const s = DATA.stations[activeKey];
- const algos = s.algorithms_by_phase[phase] || {{}};
- 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>`;
- Object.entries(algos).forEach(([aname, av]) => {{
- const rf = av.redfish_temps || {{}}, bmc = av.bmc_channels || {{}}, cs = av.chamber_sensors || {{}}, pw = av.power_rails || {{}};
- 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}}×` : '-');
- h += `<tr>
- <td><b>${{esc(aname)}}</b></td>
- <td class="mono">${{av.samples_s}}s</td>
- <td class="mono">${{av.console_exec_s ?? '-'}}</td>
- <td class="mono">${{esc(fmtMM(rf.rf_dimm_cpu0_a_c, '°C'))}}</td>
- <td class="mono">${{esc(fmtMM(rf.rf_dimm_cpu1_a_c, '°C'))}}</td>
- <td class="mono">${{esc(fmtMM(bmc.BMC0))}} / ${{esc(fmtMM(bmc.BMC12))}}</td>
- <td class="mono">${{esc(fmtMM(cs.ct1_ch1_front))}} / ${{esc(fmtMM(cs.ct2_ch1_rear))}}</td>
- <td class="mono">${{esc(fmtMM(cs.ct3_ch2_front))}} / ${{esc(fmtMM(cs.ct4_ch2_rear))}}</td>
- <td class="mono">${{esc(fmtMM(cs.ct5_ch3_front))}} / ${{esc(fmtMM(cs.ct6_ch3_rear))}}</td>
- <td class="mono">${{esc(fmtMM(cs.ct7_ch4_front))}} / ${{esc(fmtMM(cs.ct8_ch4_rear))}}</td>
- <td class="mono">${{esc(fmtMM(pw.rf_ddr0_power_w, 'W'))}} / ${{esc(fmtMM(pw.rf_ddr2_power_w, 'W'))}}</td>
- <td class="mono">${{esc(fmtMM(pw.rf_cpu0_power_avg_w, 'W'))}} / ${{esc(fmtMM(pw.rf_cpu1_power_avg_w, 'W'))}}</td>
- <td>${{asym}}</td>
- <td class="mono">${{av.cum_errors}}</td>
- </tr>`;
- }});
- h += '</tbody></table>';
- document.getElementById('algo-table').innerHTML = h;
- }}
- function renderAuditTables() {{
- 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>`;
- stationKeys.forEach(k => {{
- const s = DATA.stations[k];
- const inf = s.station_info, ig = s.integrity, app = inf.mcu_app_info || {{}};
- const resSum = ig.residual_prelaunch_findings.map(r => `${{r.phase}}:${{r.residual_rows}}s`).join(', ');
- h1 += `<tr>
- <td><b>${{esc(k)}}</b></td>
- <td class="mono">${{esc(inf.bmc_host || '-')}}</td>
- <td class="mono">${{esc(inf.mcu_uid || '-')}} · ${{esc(app.app_version || '-')}} · ${{esc(inf.pid_text || '-')}}</td>
- <td>${{esc((inf.cpu_names[0] || '-'))}} / ${{esc((inf.total_memories[0] || '-'))}}</td>
- <td class="mono">${{esc((inf.active_bmc_channels || []).map(b=>b.key).join(', '))}}</td>
- <td class="mono">${{ig.master_rows.toLocaleString()}} (${{esc(inf.total_duration_hms || '-')}})</td>
- <td class="mono">${{esc(ig.schema_version)}}</td>
- <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>
- <td><span class="badge ${{ig.mt_total_errors === 0 ? 'pass' : 'fail'}}">${{ig.mt_total_errors}}</span></td>
- <td>${{esc(resSum || '无')}}</td>
- </tr>`;
- }});
- h1 += '</tbody></table>';
- document.getElementById('audit-overview-table').innerHTML = h1;
- const s = DATA.stations[activeKey];
- 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>`;
- Object.entries(s.template_checks).forEach(([fn, tc]) => {{
- h2 += `<tr>
- <td class="mono">${{esc(fn)}}</td>
- <td class="mono">${{tc.rows}}</td>
- <td>${{tc.has_bom ? '✓' : '✗'}}</td>
- <td>${{tc.has_crlf ? '✓' : '✗'}}</td>
- <td>${{tc.header_match ? '✓' : '✗'}}</td>
- <td>${{tc.col_count_34 ? '✓' : '✗'}}</td>
- <td>${{tc.seq_contiguous ? '✓' : '✗'}}</td>
- <td class="mono">${{esc((tc.non_zero_bmc_channels || []).join(','))}}</td>
- <td class="mono">${{tc.value_mismatches_vs_comprehensive ?? '-'}}</td>
- <td><span class="badge ${{tc.status === 'PASS' ? 'pass' : 'warn'}}">${{tc.status}}</span></td>
- </tr>`;
- }});
- h2 += '</tbody></table>';
- document.getElementById('template-audit-table').innerHTML = h2;
- }}
- function renderConsoleAndEvents() {{
- const s = DATA.stations[activeKey];
- 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>`;
- Object.entries(s.console_summary).forEach(([fn, cs]) => {{
- hc += `<tr>
- <td class="mono">${{esc(fn)}}</td>
- <td class="mono">${{(cs.bytes / 1024).toFixed(1)}} KB</td>
- <td class="mono">${{cs.lines}}</td>
- <td class="mono">${{cs.running_tests_count}}</td>
- <td class="mono">${{cs.completed_tests.length}}</td>
- <td class="mono">${{cs.range_warnings_count}}${{cs.range_warnings_max_cpu != null ? ` (max CPU#${{cs.range_warnings_max_cpu}})` : ''}}</td>
- <td class="mono">${{esc(fmtMM(cs.console_dimm0_temp))}} / ${{esc(fmtMM(cs.console_dimm1_temp))}}°C</td>
- <td><span class="badge ${{cs.real_errors_count === 0 ? 'pass' : 'fail'}}">${{cs.real_errors_count}}</span></td>
- </tr>`;
- }});
- hc += '</tbody></table>';
- document.getElementById('console-summary-table').innerHTML = hc;
- const kFilter = document.getElementById('event-kind-filter');
- const prevK = kFilter.value;
- kFilter.innerHTML = '<option value="">全部事件类型</option>';
- Object.keys(s.event_kind_counts || {{}}).sort().forEach(k => {{
- const o = document.createElement('option');
- o.value = k; o.textContent = `${{k}} (${{s.event_kind_counts[k]}})`;
- kFilter.appendChild(o);
- }});
- if (prevK) kFilter.value = prevK;
- renderEventsRows();
- }}
- function renderEventsRows() {{
- const s = DATA.stations[activeKey];
- const kf = document.getElementById('event-kind-filter').value;
- const q = document.getElementById('event-search').value.trim().toLowerCase();
- const filtered = (s.events || []).filter(ev => {{
- if (kf && ev.kind !== kf) return false;
- if (q && !JSON.stringify(ev).toLowerCase().includes(q)) return false;
- return true;
- }});
- let he = `<table><thead><tr><th>时间 (CST)</th><th>阶段</th><th>类型</th><th>详情载荷</th></tr></thead><tbody>`;
- filtered.slice(0, 400).forEach(ev => {{
- const rest = {{}};
- Object.entries(ev).forEach(([k, v]) => {{
- if (!['unix_ms', 'time_cst', 'phase', 'kind', 'station_id', 'bmc_host'].includes(k)) rest[k] = v;
- }});
- 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>`;
- }});
- he += '</tbody></table>';
- if (filtered.length > 400) he += `<p style="padding:8px;color:var(--muted)">仅显示前 400 条 (共 ${{filtered.length}} 条)</p>`;
- document.getElementById('events-table').innerHTML = he;
- }}
- document.getElementById('algo-phase-select').addEventListener('change', () => {{ drawAlgoChart(); renderAlgoTable(); }});
- document.getElementById('algo-metric-select').addEventListener('change', () => drawAlgoChart());
- document.getElementById('event-kind-filter').addEventListener('change', renderEventsRows);
- document.getElementById('event-search').addEventListener('input', renderEventsRows);
- function renderStation() {{
- buildLegends();
- renderKpis();
- buildZoomBar();
- drawCharts();
- renderPhaseTables();
- populateAlgoSelectors();
- drawAlgoChart();
- renderAlgoTable();
- renderAuditTables();
- renderConsoleAndEvents();
- }}
- attachHover('chart-chambers', false);
- attachHover('chart-positions', false);
- attachHover('chart-pwr', true);
- window.addEventListener('resize', () => {{ drawCharts(); drawAlgoChart(); }});
- renderStation();
- }})();
- </script>
- </body>
- </html>
- """
- def export_clean_csvs(parsed: dict[str, Any], artifacts: dict[str, Any], export_dir: Path) -> list[Path]:
- export_dir.mkdir(parents=True, exist_ok=True)
- written: list[Path] = []
- for skey, sdata in parsed["stations"].items():
- info = sdata["station_info"]
- art = artifacts[skey]
- rows = art["master_rows"]
- active_bmcs = art["active_bmc_channels"]
- headers = [
- "seq", "timestamp_cst", "unix_ms", "elapsed_s", "elapsed_hms",
- "station_id", "bmc_host", "test_phase", "firmware_phase",
- "active_algorithm_norm", "active_algorithm_raw", "is_residual_prelaunch",
- "mt_test_num", "mt_cum_errors", "mcu_mode", "mcu_target_c",
- ]
- headers += [col for col, _, _, _ in CHAMBER_SENSORS]
- headers += [f"{ch_id}_front_minus_rear" for ch_id, _, _, _ in CHAMBER_PAIRS]
- headers += [f"mcu_bmc{i}" for i in active_bmcs]
- headers += [col for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS]
- out_path = export_dir / f"{skey}_per_sensor_clean.csv"
- with out_path.open("w", encoding="utf-8-sig", newline="") as fp:
- w = csv.writer(fp, lineterminator="\r\n")
- w.writerow(headers)
- for r in rows:
- out_row = [
- r["seq"], r["timestamp_cst"], r["unix_ms"], r["elapsed_s"], r["elapsed_hms"],
- r["station_id"] or info["station_id"], r["bmc_host"] or info["bmc_host"],
- r["test_phase"], r["firmware_phase"],
- r["active_algorithm"], r["active_algorithm_raw"], 1 if r.get("is_residual_prelaunch") else 0,
- r["mt_test_num"], r["mt_cum_errors"], r["mcu_mode"], r["mcu_target_c"],
- ]
- out_row += [r.get(col) for col, _, _, _ in CHAMBER_SENSORS]
- for _, _, fc, rc in CHAMBER_PAIRS:
- fv, rv = r.get(fc), r.get(rc)
- out_row.append(round(fv - rv, 2) if (fv is not None and rv is not None) else "")
- for i in active_bmcs:
- bv = r["bmc24_raw"][i]
- out_row.append("" if bv in (None, 255) else bv)
- for col, _ in REDFISH_TEMP_SENSORS + MT_CONSOLE_TEMP_SENSORS + POWER_RAIL_SENSORS + FAN_ACTUATOR_SENSORS:
- v = r.get(col)
- out_row.append("" if v is None else v)
- w.writerow(out_row)
- written.append(out_path)
- return written
- def _is_thermal_campaign_input(input_path: Path) -> bool:
- if input_path.is_file():
- return input_path.suffix.lower() in (".csv", ".jsonl")
- if input_path.is_dir():
- has_campaign = (
- (input_path / "thermal_campaign_samples.jsonl").is_file()
- or (input_path / "thermal_campaign_timeseries.csv").is_file()
- )
- has_mt_results = (
- (input_path / "master_continuous_comprehensive.csv").is_file()
- or any(
- (c / "master_continuous_comprehensive.csv").is_file()
- for c in input_path.iterdir()
- if c.is_dir()
- )
- )
- return has_campaign and not has_mt_results
- return False
- def _load_campaign_rows(input_path: Path) -> tuple[list[dict[str, Any]], dict[str, Any] | None, Path]:
- summary_meta: dict[str, Any] | None = None
- data_file: Path
- base_dir = input_path if input_path.is_dir() else input_path.parent
- for cand in (
- base_dir / "thermal_campaign_summary.json",
- base_dir.parent / "thermal_campaign_summary.json",
- base_dir.parent.parent / "thermal_campaign_summary.json",
- ):
- if cand.is_file():
- try:
- summary_meta = json.loads(cand.read_text(encoding="utf-8"))
- break
- except Exception:
- pass
- if input_path.is_dir():
- if (input_path / "thermal_campaign_samples.jsonl").is_file():
- data_file = input_path / "thermal_campaign_samples.jsonl"
- elif (input_path / "thermal_campaign_timeseries.csv").is_file():
- data_file = input_path / "thermal_campaign_timeseries.csv"
- else:
- raise FileNotFoundError(f"No thermal_campaign_samples.jsonl or thermal_campaign_timeseries.csv in {input_path}")
- else:
- data_file = input_path
- raw_rows: list[dict[str, Any]] = []
- if data_file.suffix.lower() == ".jsonl":
- for line in data_file.read_text(encoding="utf-8", errors="replace").splitlines():
- s = line.strip()
- if not s:
- continue
- raw_rows.append(json.loads(s))
- else:
- with data_file.open("r", encoding="utf-8-sig", newline="") as fp:
- for r in csv.DictReader(fp):
- raw_rows.append(r)
- if not raw_rows:
- raise ValueError(f"No rows found in campaign file: {data_file}")
- return raw_rows, summary_meta, data_file
- def _load_campaign_aux_assets(input_path: Path, data_file: Path) -> tuple[dict[str, Any] | None, dict[str, Any] | None, list[dict[str, Any]]]:
- base_dir = input_path if input_path.is_dir() else input_path.parent
- search_dirs: list[Path] = []
- 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):
- if d.is_dir() and d not in search_dirs:
- search_dirs.append(d)
- benchmark_data = None
- for d in search_dirs:
- cand = d / "bmc_benchmark_result.json"
- if cand.is_file():
- try:
- raw_bm = json.loads(cand.read_text(encoding="utf-8"))
- ipmi_b = raw_bm.get("ipmi") or {}
- obmc_b = raw_bm.get("openbmc") or {}
- benchmark_data = {
- "bmc_host": raw_bm.get("bmc_host"),
- "ipmi_sdr_temp_latency_ms": ipmi_b.get("ipmi_sdr_temp_latency_ms"),
- "ipmi_sdr_compact_latency_ms": ipmi_b.get("ipmi_sdr_compact_latency_ms"),
- "openbmc_discover_ms": obmc_b.get("discover_ms"),
- "dbus_sensor_count": obmc_b.get("dbus_sensor_count"),
- "dbus_sensor_services": obmc_b.get("dbus_sensor_services") or [],
- "dbus_sensors_sample": obmc_b.get("dbus_sensors_sample") or [],
- "ipmi_sample_temp_sdr": ipmi_b.get("sample_temp_sdr", ""),
- "ipmi_sample_psu_sdr": ipmi_b.get("sample_psu_sdr", ""),
- }
- break
- except Exception:
- pass
- metrics_meta = None
- for d in search_dirs:
- cand = d / "campaign_computed_metrics.json"
- if cand.is_file():
- try:
- metrics_meta = json.loads(cand.read_text(encoding="utf-8"))
- break
- except Exception:
- pass
- fig_titles = {
- "01_MT_BlockMove64B": "Fig 01 · MT Test 6 (Block Move 64B) 1Hz 温升/功耗曲线",
- "02_AMT_B_WRUP": "Fig 02 · AMT Algo 0: B-WRUP (MATS+) 1Hz 温升/功耗曲线",
- "03_AMT_B_SCM": "Fig 03 · AMT Algo 1: B-SCM (Checkerboard March) 1Hz 曲线",
- "04_AMT_S_SI": "Fig 04 · AMT Algo 2: S-SI (Stripe/Strobe Inversion) 1Hz 曲线",
- "05_AMT_A_HDS": "Fig 05 · AMT Algo 5: A-HDS (Array Hammer) 1Hz 曲线",
- "06_AMT_B_CrossWR": "Fig 06 · AMT Algo 9: B-CrossWR (Cross-Bank/Row) 1Hz 曲线",
- "07_AMT_R_VRT": "Fig 07 · AMT Algo 11: R-VRT (Variable Retention) 1Hz 脉动曲线",
- "cross_comparison": "Fig 08 · 七大单算法独立温升 / 功耗 / 斜率横向对比总览",
- "spatial_tau": "Fig 09 · 同通道 4-DIMM 热耦合 vs 孤立条空间梯度与 τ_cool",
- }
- ordered_keys = [
- "01_MT_BlockMove64B", "02_AMT_B_WRUP", "03_AMT_B_SCM", "04_AMT_S_SI",
- "05_AMT_A_HDS", "06_AMT_B_CrossWR", "07_AMT_R_VRT", "cross_comparison", "spatial_tau",
- ]
- found_figs: list[dict[str, Any]] = []
- seen_names: set[str] = set()
- fig_map = (metrics_meta or {}).get("figures") or {}
- for fk in ordered_keys:
- raw_p = fig_map.get(fk)
- if not raw_p:
- continue
- fp = Path(str(raw_p))
- resolved: Path | None = None
- if fp.is_file():
- resolved = fp
- else:
- for d in search_dirs:
- alt = d / fp.name
- if alt.is_file():
- resolved = alt
- break
- if resolved is not None and resolved.name not in seen_names:
- seen_names.add(resolved.name)
- found_figs.append({
- "key": fk,
- "title": fig_titles.get(fk, resolved.stem),
- "filename": resolved.name,
- "path": str(resolved),
- "size_bytes": resolved.stat().st_size,
- })
- if not found_figs:
- cand_files: list[Path] = []
- for d in search_dirs:
- for fp in sorted(d.glob("fig_0[1-9]_*.png")):
- if fp.is_file() and fp.name not in seen_names:
- seen_names.add(fp.name)
- cand_files.append(fp)
- for fp in sorted(cand_files, key=lambda x: x.name):
- fk = fp.stem.replace("fig_", "")
- title = fp.stem
- for ok in ordered_keys:
- 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":
- title = fig_titles.get(ok, fp.stem)
- fk = ok
- break
- found_figs.append({
- "key": fk,
- "title": title,
- "filename": fp.name,
- "path": str(fp),
- "size_bytes": fp.stat().st_size,
- })
- return benchmark_data, metrics_meta, found_figs
- def _phase_group(phase: str) -> str:
- if phase == "pre_baseline":
- return "baseline"
- if phase.startswith("loop_"):
- return "active_loop"
- if phase == "cooldown":
- return "cooldown"
- if phase in ("boot_to_amt", "init"):
- return "startup"
- if phase in ("inter_algo_settle", "idle_check"):
- return "idle"
- return "other"
- def _ols_slope(xs: list[float], ys: list[float]) -> float | None:
- if len(xs) < 2 or len(xs) != len(ys):
- return None
- n = len(xs)
- mx = sum(xs) / n
- my = sum(ys) / n
- num = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
- den = sum((x - mx) ** 2 for x in xs)
- if den <= 1e-9:
- return None
- return num / den
- def _fit_tau_cool_points(t_vals: list[float], y_vals: list[float | None], t_inf: float) -> float | None:
- 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]
- if len(pts) < 8:
- return None
- t0 = pts[0][0]
- tx = [t - t0 for t, _ in pts]
- if tx[-1] < 10.0:
- return None
- slope = _ols_slope(tx, [ly for _, ly in pts])
- if slope is None or slope >= -1e-4:
- return None
- tau = max(5.0, min(600.0, -1.0 / slope))
- return round(tau, 2)
- def _discover_campaign_sensors(raw_rows: list[dict[str, Any]]) -> list[dict[str, str]]:
- meta_keys = {
- "unix_ts", "iso_time", "campaign_elapsed_s", "run_elapsed_s", "poll_latency_ms",
- "run_key", "algo_name", "short_name", "engine", "phase", "loop_index", "loop_total",
- }
- all_keys = list(raw_rows[0].keys())
- for r in raw_rows[:20]:
- for k in r.keys():
- if k not in all_keys:
- all_keys.append(k)
- sensors: list[dict[str, str]] = []
- seen: set[str] = set()
- for key, lbl, grp, unit in CAMPAIGN_KNOWN_SENSORS:
- if key in all_keys:
- seen.add(key)
- sensors.append({"key": key, "label": lbl, "group": grp, "unit": unit})
- for key in all_keys:
- if key in seen or key in meta_keys or key in CAMPAIGN_AGGREGATE_IGNORE:
- continue
- if key.startswith("DIMM_"):
- grp, unit = "dimm_temp", "°C"
- elif key.endswith("_Temp") or key.endswith("_c"):
- grp, unit = "cpu_temp", "°C"
- elif "Power" in key or key.endswith("_PIn") or key.endswith("_POut"):
- grp, unit = "power", "W"
- elif "Curr" in key:
- grp, unit = "electrical", "A"
- elif key.startswith("P12V_") or "Volt" in key:
- grp, unit = "electrical", "V"
- else:
- continue
- sensors.append({"key": key, "label": key, "group": grp, "unit": unit})
- return sensors
- def _campaign_block_stats(rows: list[dict[str, Any]], sensors: list[dict[str, str]]) -> dict[str, Any]:
- out: dict[str, Any] = {}
- for s in sensors:
- k = s["key"]
- vals = [_to_float(r.get(k)) for r in rows]
- clean = [v for v in vals if v is not None]
- st = _sensor_stats(clean, 2)
- if st is not None:
- st["label"] = s["label"]
- st["group"] = s["group"]
- st["unit"] = s["unit"]
- out[k] = st
- return out
- def _detect_campaign_micro_events(
- norm_rows: list[dict[str, Any]],
- global_slices: list[dict[str, Any]],
- dimm_keys: list[str],
- runs_detail: dict[str, Any],
- ) -> list[dict[str, Any]]:
- events: list[dict[str, Any]] = []
- eid = 1
- def add_ev(
- *,
- severity: str,
- category: str,
- run_key: str,
- phase: str,
- seq_start: int,
- seq_end: int,
- title: str,
- detail: str,
- focus_chart: str = "all",
- focus_sensors: list[str] | None = None,
- pad_s: int = 12,
- ) -> None:
- nonlocal eid
- r0 = norm_rows[max(0, seq_start - 1)]
- r1 = norm_rows[min(len(norm_rows) - 1, seq_end - 1)]
- events.append({
- "id": f"ME-{eid:02d}",
- "severity": severity,
- "category": category,
- "run_key": run_key,
- "phase": phase,
- "seq_start": seq_start,
- "seq_end": seq_end,
- "rows": seq_end - seq_start + 1,
- "t_start": _round_opt(r0["campaign_elapsed_s"], 1),
- "t_end": _round_opt(r1["campaign_elapsed_s"], 1),
- "iso_start": r0["iso_time"],
- "iso_end": r1["iso_time"],
- "title": title,
- "detail": detail,
- "focus_chart": focus_chart,
- "focus_sensors": focus_sensors or [],
- "pad_s": pad_s,
- })
- eid += 1
- # 1. Non-active stage DIMM thermal excursion (>= 2.0 C rise)
- for sl in global_slices:
- if sl["phase_group"] not in ("startup", "idle", "baseline") or sl["rows"] < 5:
- continue
- sl_rows = norm_rows[sl["idx_start"]:sl["idx_end"]]
- for dk in dimm_keys:
- pts = [(r["seq"], r[dk]) for r in sl_rows if r.get(dk) is not None]
- if len(pts) < 4:
- continue
- min_seq, min_v = min(pts, key=lambda x: x[1])
- post = [(sq, v) for sq, v in pts if sq >= min_seq]
- if not post:
- continue
- max_seq, max_v = max(post, key=lambda x: x[1])
- rise = round(max_v - min_v, 2)
- if rise >= 2.0:
- 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)
- 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)
- add_ev(
- severity="warn" if rise >= 3.0 else "info",
- category="非算法阶段温升",
- run_key=sl["run_key"],
- phase=sl["phase"],
- seq_start=min_seq,
- seq_end=max_seq,
- title=f"{sl['run_key']} · {sl['phase']} 阶段 {dk.replace('_Temp','')} 上升 +{rise}°C",
- 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 初始化预热)。",
- focus_chart="temp",
- focus_sensors=[dk, "DDR2_Power", "DDR0_Power"],
- pad_s=18,
- )
- # 2. Cooldown power spikes (>= 20W DDR0_Power after first 2 seconds of cooldown)
- for sl in global_slices:
- if sl["phase"] != "cooldown":
- continue
- sl_rows = norm_rows[sl["idx_start"]:sl["idx_end"]]
- buf: list[dict[str, Any]] = []
- for idx_c, r in enumerate(sl_rows):
- if idx_c >= 2 and (r.get("DDR0_Power") or 0.0) >= 20.0:
- buf.append(r)
- elif buf:
- pk0 = max((x.get("DDR0_Power") or 0.0) for x in buf)
- pk2 = max((x.get("DDR2_Power") or 0.0) for x in buf)
- p_psu = max((x.get("PSU0_PIn") or 0.0) for x in buf)
- add_ev(
- severity="warn",
- category="冷却期DXE功耗脉冲",
- run_key=sl["run_key"],
- phase="cooldown",
- seq_start=buf[0]["seq"],
- seq_end=buf[-1]["seq"],
- title=f"{sl['run_key']} · cooldown 热重启 DXE 功耗脉冲 {pk0:.2f}W",
- 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。",
- focus_chart="pwr_mem",
- focus_sensors=["DDR0_Power", "DDR2_Power", "PVCCD_CPU0_Input_Power"],
- pad_s=15,
- )
- buf = []
- if buf:
- pk0 = max((x.get("DDR0_Power") or 0.0) for x in buf)
- pk2 = max((x.get("DDR2_Power") or 0.0) for x in buf)
- p_psu = max((x.get("PSU0_PIn") or 0.0) for x in buf)
- add_ev(
- severity="warn",
- category="冷却期DXE功耗脉冲",
- run_key=sl["run_key"],
- phase="cooldown",
- seq_start=buf[0]["seq"],
- seq_end=buf[-1]["seq"],
- title=f"{sl['run_key']} · cooldown 热重启 DXE 功耗脉冲 {pk0:.2f}W",
- 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。",
- focus_chart="pwr_mem",
- focus_sensors=["DDR0_Power", "DDR2_Power", "PVCCD_CPU0_Input_Power"],
- pad_s=15,
- )
- # 3. SPD5118 telemetry blackout spans (>= 5 consecutive rows with all DIMMs None)
- cool_start_by_run: dict[str, int] = {}
- for sl in global_slices:
- if sl["phase"] == "cooldown" and sl["run_key"] not in cool_start_by_run:
- cool_start_by_run[sl["run_key"]] = sl["seq_start"]
- blk_buf: list[dict[str, Any]] = []
- def flush_spd_blackout() -> None:
- if len(blk_buf) < 5:
- return
- r0, r1 = blk_buf[0], blk_buf[-1]
- in_cool = any(x["phase"] == "cooldown" for x in blk_buf)
- c_start = cool_start_by_run.get(r0["run_key"])
- is_late_handover = bool(in_cool and c_start is not None and (r0["seq"] - c_start) >= 50)
- sev = "warn" if in_cool else "info"
- if is_late_handover:
- title = f"{r0['run_key']} · cooldown 二次切回OS瞬断 ({len(blk_buf)}s)"
- hint = "cooldown 约 +100s 处切回 OS 交接重启,SPD5118 与 PMBus (DDR0_Power) 同步离线,随后恢复并重连 PECI"
- elif in_cool:
- title = f"{r0['run_key']} · cooldown 初期热重启 SPD 离线 {len(blk_buf)}s"
- hint = "停载退出后热重启回 UEFI Shell 期间 SPD5118 不可访问,导致冷却表观首读数低于峰值约 2~3°C"
- else:
- title = f"{r0['run_key']} · {r0['phase']} SPD5118 全离线 {len(blk_buf)}s"
- hint = "热重启进入 BIOS MRC 训练窗口,SPD5118 不可读"
- add_ev(
- severity=sev,
- category="SPD5118离线空窗",
- run_key=r0["run_key"],
- phase=r0["phase"],
- seq_start=r0["seq"],
- seq_end=r1["seq"],
- title=title,
- detail=f"#{r0['seq']}..#{r1['seq']}(共 {len(blk_buf)} 行)5 路 DIMM 温度全部为 null;{hint}。",
- focus_chart="temp",
- focus_sensors=dimm_keys[:2] + ["DDR0_Power"],
- pad_s=12,
- )
- for r in norm_rows:
- all_null = bool(dimm_keys) and all(r.get(dk) is None for dk in dimm_keys)
- if all_null and (not blk_buf or blk_buf[-1]["run_key"] == r["run_key"] and blk_buf[-1]["phase"] == r["phase"]):
- blk_buf.append(r)
- else:
- flush_spd_blackout()
- blk_buf = [r] if all_null else []
- flush_spd_blackout()
- # 4. PECI RAPL availability offline window (Dimm_Power_CPU0 is None)
- if any(r.get("Dimm_Power_CPU0") is not None for r in norm_rows):
- p_buf: list[dict[str, Any]] = []
- for r in norm_rows:
- if r.get("Dimm_Power_CPU0") is None:
- p_buf.append(r)
- else:
- if len(p_buf) >= 20:
- add_ev(
- severity="info",
- category="PECI RAPL空窗",
- run_key=p_buf[0]["run_key"],
- phase=p_buf[0]["phase"],
- seq_start=p_buf[0]["seq"],
- seq_end=p_buf[-1]["seq"],
- title=f"{p_buf[0]['run_key']} · BIOS AMT 期间 PECI 功耗遥测离线 ({len(p_buf)}s)",
- 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 后自动恢复。",
- focus_chart="pwr_mem",
- focus_sensors=["Dimm_Power_CPU0", "DDR0_Power"],
- pad_s=10,
- )
- p_buf = []
- if len(p_buf) >= 20:
- add_ev(
- severity="info",
- category="PECI RAPL空窗",
- run_key=p_buf[0]["run_key"],
- phase=p_buf[0]["phase"],
- seq_start=p_buf[0]["seq"],
- seq_end=p_buf[-1]["seq"],
- title=f"{p_buf[0]['run_key']} · BIOS AMT 期间 PECI 功耗遥测离线 ({len(p_buf)}s)",
- detail=f"#{p_buf[0]['seq']}..#{p_buf[-1]['seq']} 期间 Dimm_Power_CPU0/1 与 CPU0/1_Power_Avg 为 null。",
- focus_chart="pwr_mem",
- focus_sensors=["Dimm_Power_CPU0", "DDR0_Power"],
- pad_s=10,
- )
- # 5. Global peak DIMM temperature & max 5-DIMM spatial spread
- peak_temp_row = None
- peak_temp_key = ""
- peak_temp_val = -1e9
- max_spread_row = None
- max_spread_val = -1.0
- max_spread_pair = ("", "", 0.0, 0.0)
- for r in norm_rows:
- vals = [(dk, r[dk]) for dk in dimm_keys if r.get(dk) is not None]
- if not vals:
- continue
- hi_k, hi_v = max(vals, key=lambda x: x[1])
- lo_k, lo_v = min(vals, key=lambda x: x[1])
- if hi_v > peak_temp_val:
- peak_temp_val = hi_v
- peak_temp_key = hi_k
- peak_temp_row = r
- sp = round(hi_v - lo_v, 2)
- if sp > max_spread_val:
- max_spread_val = sp
- max_spread_row = r
- max_spread_pair = (hi_k, lo_k, hi_v, lo_v)
- if peak_temp_row is not None and len(norm_rows) >= 10:
- add_ev(
- severity="peak",
- category="全局峰值热节点",
- run_key=peak_temp_row["run_key"],
- phase=peak_temp_row["phase"],
- seq_start=peak_temp_row["seq"],
- seq_end=peak_temp_row["seq"],
- title=f"全周期最高 DIMM 温度 {peak_temp_val}°C ({peak_temp_key.replace('_Temp','')})",
- 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 '-'})。",
- focus_chart="temp",
- focus_sensors=dimm_keys,
- pad_s=35,
- )
- # 6. P12V_DDR0 significant rail voltage droop (>= 0.03V)
- 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]
- if p12_vals:
- p12_max = max(v for _, v, _, _ in p12_vals)
- p12_min = min(v for _, v, _, _ in p12_vals)
- if (p12_max - p12_min) >= 0.03:
- droop_rows = [r for r in norm_rows if r.get("P12V_DDR0") is not None and r["P12V_DDR0"] <= p12_min + 0.005]
- if droop_rows:
- # Merge contiguous or near-contiguous
- s0, s1 = droop_rows[0]["seq"], droop_rows[-1]["seq"]
- max_curr = max((r.get("DDR0_Curr") or 0.0) for r in droop_rows)
- max_pwr = max((r.get("DDR0_Power") or 0.0) for r in droop_rows)
- add_ev(
- severity="peak",
- category="12V 供电轨压降",
- run_key=droop_rows[0]["run_key"],
- phase=droop_rows[0]["phase"],
- seq_start=s0,
- seq_end=s1,
- title=f"{droop_rows[0]['run_key']} · P12V_DDR0 压降至 {p12_min:.3f}V (峰值电流 {max_curr:.2f}A)",
- 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)。",
- focus_chart="elec_volt",
- focus_sensors=["P12V_DDR0", "P12V_DDR2", "DDR0_Curr"],
- pad_s=25,
- )
- # 7. Active loop power pattern signatures (square-wave pulse vs zero-gap steady load)
- for rk, rd in runs_detail.items():
- if rd["active_rows"] < 20:
- continue
- act_slices = [s for s in rd["phases"] if s["phase_group"] == "active_loop"]
- if not act_slices:
- continue
- a_s, a_e = act_slices[0]["seq_start"], act_slices[-1]["seq_end"]
- act_r = norm_rows[a_s - 1:a_e]
- d0 = [r["DDR0_Power"] for r in act_r if r.get("DDR0_Power") is not None]
- if not d0:
- continue
- if (max(d0) - min(d0)) >= 15.0 and min(d0) < 10.0:
- add_ev(
- severity="info",
- category="方波脉动功耗特征",
- run_key=rk,
- phase=act_slices[0]["phase"],
- seq_start=a_s,
- seq_end=a_e,
- title=f"{rk} · 写入-保持-回读脉动负载 ({min(d0):.1f}~{max(d0):.2f}W 剧烈方波)",
- detail=f"#{a_s}..#{a_e} 负载期 DDR0 功耗在 {min(d0):.2f}W(Retention Pause 空窗)与 {max(d0):.2f}W(突发写/回读峰值,超 {round(max(d0),1)}W)间高频方波切换,解释了平均功耗温和但瞬时峰值极高的现象。",
- focus_chart="pwr_mem",
- focus_sensors=["DDR0_Power", "DDR2_Power", "PVCCD_CPU0_Input_Power"],
- pad_s=15,
- )
- elif len(act_slices) >= 2:
- tail_rows = norm_rows[act_slices[1]["idx_start"]:act_slices[-1]["idx_end"]]
- d0_tail = [r["DDR0_Power"] for r in tail_rows if r.get("DDR0_Power") is not None]
- if d0_tail and min(d0_tail) >= 18.0 and (max(d0_tail) - min(d0_tail)) < 1.5:
- add_ev(
- severity="info",
- category="无间隙极稳态特征",
- run_key=rk,
- phase="loop_2+",
- seq_start=act_slices[1]["seq_start"],
- seq_end=act_slices[-1]["seq_end"],
- title=f"{rk} · 无轮间低谷持续稳态功耗 ({min(d0_tail):.2f}~{max(d0_tail):.2f}W)",
- 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)。",
- focus_chart="pwr_mem",
- focus_sensors=["DDR0_Power", "DDR2_Power"],
- pad_s=15,
- )
- # 8. High poll latency spikes (>= 500ms)
- lat_buf: list[dict[str, Any]] = []
- def flush_lat() -> None:
- if not lat_buf:
- return
- pk = max((x.get("poll_latency_ms") or 0.0) for x in lat_buf)
- r0, r1 = lat_buf[0], lat_buf[-1]
- add_ev(
- severity="warn" if pk >= 1500 else "info",
- category="BMC采集高延迟",
- run_key=r0["run_key"],
- phase=r0["phase"],
- seq_start=r0["seq"],
- seq_end=r1["seq"],
- title=f"{r0['run_key']} · BMC D-Bus 轮询尖峰 {pk:.0f}ms",
- detail=f"#{r0['seq']}..#{r1['seq']} ({r0['phase']}) 单次采集耗时达 {pk:.1f}ms(多发生在热重启切换重连或 BMC 重建 D-Bus 瞬间,采集周期仍严格对齐 1Hz)。",
- focus_chart="elec_lat",
- focus_sensors=[],
- pad_s=12,
- )
- for r in norm_rows:
- if (r.get("poll_latency_ms") or 0.0) >= 500.0:
- if not lat_buf or (r["seq"] - lat_buf[-1]["seq"]) <= 2:
- lat_buf.append(r)
- else:
- flush_lat()
- lat_buf = [r]
- else:
- if lat_buf and (r["seq"] - lat_buf[-1]["seq"]) > 2:
- flush_lat()
- lat_buf = []
- flush_lat()
- events.sort(key=lambda e: (e["seq_start"], e["seq_end"]))
- for idx_e, ev in enumerate(events, start=1):
- ev["id"] = f"ME-{idx_e:02d}"
- return events
- def parse_thermal_campaign(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
- p = Path(input_path).resolve()
- raw_rows, summary_meta, data_file = _load_campaign_rows(p)
- benchmark_data, metrics_meta, found_figs = _load_campaign_aux_assets(p, data_file)
- sensors = _discover_campaign_sensors(raw_rows)
- dimm_keys = [s["key"] for s in sensors if s["group"] == "dimm_temp"]
- norm_rows: list[dict[str, Any]] = []
- for idx, r in enumerate(raw_rows, start=1):
- rec: dict[str, Any] = {
- "seq": idx,
- "unix_ts": _to_float(r.get("unix_ts")),
- "iso_time": str(r.get("iso_time") or "").strip(),
- "campaign_elapsed_s": _to_float(r.get("campaign_elapsed_s")),
- "run_elapsed_s": _to_float(r.get("run_elapsed_s")),
- "poll_latency_ms": _to_float(r.get("poll_latency_ms")),
- "run_key": str(r.get("run_key") or "").strip(),
- "algo_name": str(r.get("algo_name") or "").strip(),
- "short_name": str(r.get("short_name") or "").strip(),
- "engine": str(r.get("engine") or "").strip(),
- "phase": str(r.get("phase") or "").strip(),
- "loop_index": _to_int(r.get("loop_index")) or 0,
- "loop_total": _to_int(r.get("loop_total")) or 0,
- }
- for s in sensors:
- rec[s["key"]] = _to_float(r.get(s["key"]))
- norm_rows.append(rec)
- # Global chronological contiguous phase slices by (run_key, phase)
- global_slices: list[dict[str, Any]] = []
- cur_rk: str | None = None
- cur_ph: str | None = None
- cur_buf: list[dict[str, Any]] = []
- def push_global_slice() -> None:
- if not cur_buf:
- return
- ph = cur_ph or "unknown"
- rk = cur_rk or "unknown"
- t0 = cur_buf[0]["campaign_elapsed_s"]
- t1 = cur_buf[-1]["campaign_elapsed_s"]
- dur_s = round((t1 - t0) + 1.0, 1) if (t0 is not None and t1 is not None) else float(len(cur_buf))
- spd_valid = sum(1 for row in cur_buf if any(row.get(dk) is not None for dk in dimm_keys))
- peci_valid = sum(
- 1 for row in cur_buf
- if row.get("Dimm_Power_CPU0") is not None or row.get("CPU0_Power_Avg") is not None
- )
- global_slices.append({
- "run_key": rk,
- "phase": ph,
- "phase_group": _phase_group(ph),
- "loop_index": cur_buf[0]["loop_index"],
- "seq_start": cur_buf[0]["seq"],
- "seq_end": cur_buf[-1]["seq"],
- "idx_start": cur_buf[0]["seq"] - 1,
- "idx_end": cur_buf[-1]["seq"],
- "rows": len(cur_buf),
- "start_time": cur_buf[0]["iso_time"],
- "end_time": cur_buf[-1]["iso_time"],
- "t_start": _round_opt(t0, 1),
- "t_end": _round_opt(t1, 1),
- "duration_s": dur_s,
- "spd_valid_rows": spd_valid,
- "spd_null_rows": len(cur_buf) - spd_valid,
- "peci_valid_rows": peci_valid,
- "peci_null_rows": len(cur_buf) - peci_valid,
- "sensors": _campaign_block_stats(cur_buf, sensors),
- })
- for r in norm_rows:
- rk = r["run_key"] or "unknown"
- ph = r["phase"] or "unknown"
- if cur_rk is None or rk != cur_rk or ph != cur_ph:
- push_global_slice()
- cur_rk, cur_ph = rk, ph
- cur_buf = [r]
- else:
- cur_buf.append(r)
- push_global_slice()
- summary_by_run: dict[str, dict[str, Any]] = {}
- for sr in (summary_meta or {}).get("runs") or []:
- if isinstance(sr, dict) and sr.get("run_key"):
- summary_by_run[str(sr["run_key"])] = sr
- metrics_by_run: dict[str, dict[str, Any]] = {}
- for mr in (metrics_meta or {}).get("algorithms") or []:
- if isinstance(mr, dict) and mr.get("run_key"):
- metrics_by_run[str(mr["run_key"])] = mr
- # Group rows by run_key preserving execution order
- run_order: list[str] = []
- by_run: dict[str, list[dict[str, Any]]] = {}
- for r in norm_rows:
- rk = r["run_key"] or "unknown"
- if rk not in by_run:
- run_order.append(rk)
- by_run[rk] = []
- by_run[rk].append(r)
- def _nearest_sample(ts: float | None, rows_pool: list[dict[str, Any]]) -> dict[str, Any] | None:
- if ts is None or not rows_pool:
- return None
- best = None
- best_dt = 1e18
- for row in rows_pool:
- uts = row.get("unix_ts")
- if uts is None:
- continue
- dt = abs(uts - ts)
- if dt < best_dt:
- best_dt = dt
- best = row
- return best
- runs_detail: dict[str, Any] = {}
- for rk in run_order:
- rrows = by_run[rk]
- first = rrows[0]
- base_rows = [r for r in rrows if r["phase"] == "pre_baseline"]
- active_rows = [r for r in rrows if r["phase"].startswith("loop_")]
- cool_rows = [r for r in rrows if r["phase"] == "cooldown"]
- active_dur_s = 0.0
- if len(active_rows) >= 2 and active_rows[0]["unix_ts"] is not None and active_rows[-1]["unix_ts"] is not None:
- active_dur_s = round(active_rows[-1]["unix_ts"] - active_rows[0]["unix_ts"], 2)
- elif active_rows:
- active_dur_s = float(len(active_rows))
- active_stats = _campaign_block_stats(active_rows, sensors) if active_rows else {}
- base_stats = _campaign_block_stats(base_rows, sensors) if base_rows else {}
- cool_stats = _campaign_block_stats(cool_rows, sensors) if cool_rows else {}
- # Per-DIMM heating rate (C/min), early 40s slope, cooldown recovery, and per-DIMM tau_cool
- dimm_rates: dict[str, Any] = {}
- t_act0 = active_rows[0]["unix_ts"] if active_rows else None
- early_limit_s = min(40.0, max(15.0, active_dur_s * 0.6))
- t_cool0 = cool_rows[0]["unix_ts"] if cool_rows else None
- for dk in dimm_keys:
- ast = active_stats.get(dk)
- bst = base_stats.get(dk)
- cst = cool_stats.get(dk)
- rate = None
- if ast and active_dur_s > 0:
- rate = round((ast["max"] - ast["start"]) / (active_dur_s / 60.0), 2)
- net_from_base = None
- if ast and bst:
- net_from_base = round(ast["max"] - bst["end"], 2)
- cool_drop = None
- if cst:
- cool_drop = round(cst["start"] - cst["end"], 2)
- cool_drop_from_peak = None
- if ast and cst:
- cool_drop_from_peak = round(ast["max"] - cst["end"], 2)
- early_slope = None
- if active_rows and t_act0 is not None:
- exs: list[float] = []
- eys: list[float] = []
- for rr in active_rows:
- rv = rr.get(dk)
- rts = rr.get("unix_ts")
- if rv is not None and rts is not None and (rts - t_act0) <= early_limit_s:
- exs.append(rts - t_act0)
- eys.append(rv)
- if len(exs) >= 5:
- sl = _ols_slope(exs, eys)
- if sl is not None:
- early_slope = round(sl * 60.0, 2)
- cool_delay_s = None
- cool_valid = 0
- cool_null = len(cool_rows)
- tau_dimm = None
- if cool_rows:
- cool_valid = cst["count"] if cst else 0
- cool_null = len(cool_rows) - cool_valid
- first_v_row = next((rr for rr in cool_rows if rr.get(dk) is not None), None)
- if first_v_row is not None:
- if t_cool0 is not None and first_v_row.get("unix_ts") is not None:
- cool_delay_s = round(first_v_row["unix_ts"] - t_cool0, 1)
- else:
- cool_delay_s = float(first_v_row["seq"] - cool_rows[0]["seq"])
- if bst is not None:
- c_ts = [rr["campaign_elapsed_s"] for rr in cool_rows]
- c_ys = [rr.get(dk) for rr in cool_rows]
- tau_dimm = _fit_tau_cool_points(c_ts, c_ys, bst["end"] - 0.15)
- dimm_rates[dk] = {
- "baseline_start_c": bst["start"] if bst else None,
- "baseline_end_c": bst["end"] if bst else None,
- "baseline_min_c": bst["min"] if bst else None,
- "baseline_max_c": bst["max"] if bst else None,
- "active_start_c": ast["start"] if ast else None,
- "active_end_c": ast["end"] if ast else None,
- "active_min_c": ast["min"] if ast else None,
- "active_max_c": ast["max"] if ast else None,
- "active_delta_c": ast["delta"] if ast else None,
- "net_rise_from_baseline_c": net_from_base,
- "heating_rate_c_per_min": rate,
- "early_slope_c_per_min": early_slope,
- "cooldown_start_c": cst["start"] if cst else None,
- "cooldown_end_c": cst["end"] if cst else None,
- "cooldown_drop_c": cool_drop,
- "cooldown_total_drop_from_peak_c": cool_drop_from_peak,
- "cooldown_first_valid_delay_s": cool_delay_s,
- "cooldown_valid_rows": cool_valid,
- "cooldown_null_rows": cool_null,
- "tau_cool_s": tau_dimm,
- }
- run_slices = [
- {k: v for k, v in sl.items() if k != "run_key"}
- for sl in global_slices
- if sl["run_key"] == rk
- ]
- core_slices = [s for s in run_slices if s["phase_group"] in ("baseline", "active_loop", "cooldown")]
- if core_slices:
- core_win = [core_slices[0]["idx_start"], core_slices[-1]["idx_end"]]
- elif run_slices:
- core_win = [run_slices[0]["idx_start"], run_slices[-1]["idx_end"]]
- else:
- core_win = [0, 0]
- full_win = [run_slices[0]["idx_start"], run_slices[-1]["idx_end"]] if run_slices else [0, 0]
- # Pointwise spatial spreads across populated DIMMs (no averages)
- max_all_spread = None
- cpu0_dimms = [dk for dk in dimm_keys if dk.startswith("DIMM_CPU0_")]
- max_cpu0_spread = None
- for rr in active_rows:
- vals = [rr[dk] for dk in dimm_keys if rr.get(dk) is not None]
- if len(vals) >= 2:
- sp = round(max(vals) - min(vals), 2)
- if max_all_spread is None or sp > max_all_spread:
- max_all_spread = sp
- if len(cpu0_dimms) >= 2:
- cvals = [rr[dk] for dk in cpu0_dimms if rr.get(dk) is not None]
- if len(cvals) >= 2:
- csp = round(max(cvals) - min(cvals), 2)
- if max_cpu0_spread is None or csp > max_cpu0_spread:
- max_cpu0_spread = csp
- s_meta = summary_by_run.get(rk) or {}
- m_meta = metrics_by_run.get(rk) or {}
- enriched_loop_events: list[dict[str, Any]] = []
- for le in s_meta.get("loop_events") or []:
- if not isinstance(le, dict):
- continue
- uts = _to_float(le.get("unix_ts"))
- ns = _nearest_sample(uts, rrows)
- enriched_loop_events.append({
- "event": le.get("event") or ("socket_done" if "socket" in le else "event"),
- "loop": le.get("loop"),
- "socket": le.get("socket"),
- "fw_sec": le.get("fw_sec"),
- "unix_ts": uts,
- "seq": ns["seq"] if ns else None,
- "t_s": _round_opt(ns["campaign_elapsed_s"], 1) if ns else None,
- "iso_time": ns["iso_time"] if ns else None,
- })
- runs_detail[rk] = {
- "run_key": rk,
- "algo_name": first["algo_name"],
- "short_name": first["short_name"],
- "engine": first["engine"],
- "category": s_meta.get("category") or m_meta.get("category") or "",
- "tp_plan": s_meta.get("tp_plan") or "",
- "total_rows": len(rrows),
- "active_rows": len(active_rows),
- "active_duration_s": active_dur_s,
- "loop_total": max((r["loop_total"] for r in rrows), default=0),
- "start_time": first["iso_time"],
- "end_time": rrows[-1]["iso_time"],
- "full_window": full_win,
- "core_window": core_win,
- "max_all_dimm_spread_c": max_all_spread,
- "max_cpu0_cluster_spread_c": max_cpu0_spread,
- "ref_tau_cool_s": m_meta.get("tau_cool_cpu0_s"),
- "pre_baseline_sensors": base_stats,
- "active_sensors": active_stats,
- "cooldown_sensors": cool_stats,
- "per_dimm_thermal_response": dimm_rates,
- "phases": run_slices,
- "loop_events": enriched_loop_events,
- }
- latencies = [r["poll_latency_ms"] for r in norm_rows if r["poll_latency_ms"] is not None]
- total_dur_s = round((norm_rows[-1]["campaign_elapsed_s"] or 0.0), 1)
- overall_sensors = _campaign_block_stats(norm_rows, sensors)
- micro_events = _detect_campaign_micro_events(norm_rows, global_slices, dimm_keys, runs_detail)
- parsed = {
- "parser_version": PARSER_VERSION,
- "mode": "unheated_algorithm_campaign_per_position_no_means",
- "parsed_utc": datetime.now(timezone.utc).isoformat(),
- "input_path": str(p),
- "data_file": str(data_file),
- "source_kind": "thermal_campaign",
- "bmc_host": (summary_meta or {}).get("bmc_host") or "unknown",
- "total_1hz_rows": len(norm_rows),
- "total_duration_s": total_dur_s,
- "total_duration_hms": _fmt_hms(total_dur_s),
- "poll_latency_ms": _sensor_stats(latencies, 2),
- "sensors": sensors,
- "dimm_keys": dimm_keys,
- "overall_sensors": overall_sensors,
- "runs": runs_detail,
- "micro_events": micro_events,
- "bmc_benchmark": benchmark_data,
- }
- # Compact columnar series for HTML dashboard
- run_names: list[str] = []
- run_idx: dict[str, int] = {}
- phase_names: list[str] = []
- phase_idx: dict[str, int] = {}
- cols: dict[str, list[Any]] = {
- "seq": [], "t": [], "ts": [], "rk": [], "ph": [], "loop": [], "lat": [],
- }
- for s in sensors:
- cols[s["key"]] = []
- for r in norm_rows:
- rk = r["run_key"] or "unknown"
- if rk not in run_idx:
- run_idx[rk] = len(run_names)
- run_names.append(rk)
- ph = r["phase"] or "unknown"
- if ph not in phase_idx:
- phase_idx[ph] = len(phase_names)
- phase_names.append(ph)
- cols["seq"].append(r["seq"])
- cols["t"].append(round(r["campaign_elapsed_s"] or 0.0, 1))
- ts = r["iso_time"]
- cols["ts"].append(ts[11:19] if len(ts) >= 19 else ts)
- cols["rk"].append(run_idx[rk])
- cols["ph"].append(phase_idx[ph])
- cols["loop"].append(r["loop_index"])
- cols["lat"].append(_round_opt(r["poll_latency_ms"], 1))
- for s in sensors:
- cols[s["key"]].append(_round_opt(r.get(s["key"]), 3))
- series = {
- "run_names": run_names,
- "phase_names": phase_names,
- "sensors": sensors,
- "cols": cols,
- }
- embedded_figures: list[dict[str, Any]] = []
- for fmeta in found_figs:
- fp = Path(fmeta["path"])
- try:
- b64 = base64.b64encode(fp.read_bytes()).decode("ascii")
- embedded_figures.append({
- "key": fmeta["key"],
- "title": fmeta["title"],
- "filename": fmeta["filename"],
- "size_bytes": fmeta["size_bytes"],
- "data_uri": f"data:image/png;base64,{b64}",
- })
- except Exception:
- pass
- return parsed, {
- "rows": norm_rows,
- "sensors": sensors,
- "series": series,
- "embedded_figures": embedded_figures,
- }
- def render_campaign_markdown_report(parsed: dict[str, Any]) -> str:
- dimm_keys = parsed["dimm_keys"]
- lines: list[str] = []
- lines.append("# 无温控直跑单算法多位置传感器独立解析报告(无均值)")
- lines.append("")
- lines.append(f"- **输入来源**:`{parsed['data_file']}` (`{parsed['source_kind']}`)")
- lines.append(f"- **被测 BMC 主机**:`{parsed['bmc_host']}` · 温控模式:**无高温罩温控(裸机直跑单算法)**")
- lines.append(f"- **解析时间 (UTC)**:`{parsed['parsed_utc']}` · 解析器版本 `v{parsed['parser_version']}` (`{parsed['mode']}`)")
- lines.append(
- f"- **总采样规模**:`{parsed['total_1hz_rows']:,}` 行 1Hz 遥测(总时长 `{parsed['total_duration_hms']}` / `{parsed['total_duration_s']}s`),"
- f"识别独立位置传感器 `{len(parsed['sensors'])}` 路,自动检出微事件/异常切换 `{len(parsed.get('micro_events') or [])}` 项"
- )
- lines.extend(["", "---", "", "## 1. 全部独立位置传感器全周期实测范围 (`min~max`, `起点→终点`)", ""])
- lines.append("| 传感器 | 类别 | 有效样本 | 最小值 | 最大值 | 起点 | 终点 | 全周期变化 |")
- lines.append("|---|---|---:|---:|---:|---:|---:|---:|")
- for s in parsed["sensors"]:
- st = parsed["overall_sensors"].get(s["key"])
- if not st:
- continue
- u = s["unit"]
- 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}` |")
- lines.extend(["", "## 2. 各算法负载窗口逐 DIMM 插槽独立温升 (`min~max`, `起点→峰值`, 升温斜率 `°C/min`)", ""])
- hdr_dimm = " | ".join(f"{dk.replace('_Temp','')} (起→峰 / +Δ / 全斜率 / 前40s斜率)" for dk in dimm_keys)
- lines.append(f"| 算法 Run | 引擎 / 轮数 | 有效负载时长 | 最大跨槽极差 | {hdr_dimm} |")
- lines.append("|---|---|---|---|" + "|".join(["---"] * len(dimm_keys)) + "|")
- for rk, rd in parsed["runs"].items():
- if not rd["active_rows"]:
- continue
- cells = []
- for dk in dimm_keys:
- dr = rd["per_dimm_thermal_response"].get(dk) or {}
- if dr.get("active_max_c") is None:
- cells.append("-")
- else:
- es = dr.get("early_slope_c_per_min")
- es_txt = f" / 初期`{es}°C/m`" if es is not None else ""
- cells.append(
- 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})"
- )
- sp_txt = f"`{rd['max_all_dimm_spread_c']}°C`" if rd.get("max_all_dimm_spread_c") is not None else "-"
- 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) + " |")
- lines.extend(["", "## 3. 各算法负载窗口逐供电/功耗与 CPU 位置传感器独立范围 (`min~max`)", ""])
- 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 |")
- lines.append("|---|---|---|---|---|---|---|---|---|")
- for rk, rd in parsed["runs"].items():
- if not rd["active_rows"]:
- continue
- act = rd["active_sensors"]
- lines.append(
- f"| `{rk}` | {_fmt_range(act.get('DDR0_Power'), 'W', False)} | {_fmt_range(act.get('DDR2_Power'), 'W', False)} | "
- f"{_fmt_range(act.get('P12V_DDR0'), 'V', False)} / {_fmt_range(act.get('P12V_DDR2'), 'V', False)} | "
- f"{_fmt_range(act.get('PVCCD_CPU0_Input_Power'), 'W', False)} / {_fmt_range(act.get('PVCCD_CPU1_Input_Power'), 'W', False)} | "
- f"{_fmt_range(act.get('Dimm_Power_CPU0'), 'W', False)} / {_fmt_range(act.get('Dimm_Power_CPU1'), 'W', False)} | "
- f"{_fmt_range(act.get('CPU0_Power_Avg'), 'W', False)} / {_fmt_range(act.get('CPU1_Power_Avg'), 'W', False)} | "
- f"{_fmt_range(act.get('CPU0_Temp'), '°C', False)} / {_fmt_range(act.get('CPU1_Temp'), '°C', False)} | "
- f"{_fmt_range(act.get('PSU0_PIn'), 'W', False)} / {_fmt_range(act.get('PSU0_POut'), 'W', False)} |"
- )
- lines.extend(["", "## 4. 各算法停载后 150s 冷却恢复(逐 DIMM 插槽实测回落、SPD 延迟与 τ_cool)", ""])
- hdr_cool = " | ".join(f"{dk.replace('_Temp','')} (起→末 / 距峰值回落 / τ_cool)" for dk in dimm_keys)
- lines.append(f"| 算法 Run | 冷却有效/空值行 (首读延迟) | {hdr_cool} |")
- lines.append("|---|---|" + "|".join(["---"] * len(dimm_keys)) + "|")
- for rk, rd in parsed["runs"].items():
- if not rd["cooldown_sensors"]:
- continue
- dr0 = rd["per_dimm_thermal_response"].get(dimm_keys[0]) or {}
- c_cnt = dr0.get("cooldown_valid_rows", 0)
- c_null = dr0.get("cooldown_null_rows", 0)
- delay = dr0.get("cooldown_first_valid_delay_s")
- delay_txt = f", 首读+{delay}s" if delay is not None and delay > 0 else ""
- cells = []
- for dk in dimm_keys:
- dr = rd["per_dimm_thermal_response"].get(dk) or {}
- if dr.get("cooldown_start_c") is None:
- cells.append("-")
- else:
- delta_c = round(dr["cooldown_end_c"] - dr["cooldown_start_c"], 2)
- pk_drop = dr.get("cooldown_total_drop_from_peak_c")
- tau_txt = f" / `τ={dr['tau_cool_s']}s`" if dr.get("tau_cool_s") is not None else ""
- pk_txt = f" (较峰`-{pk_drop}°C`)" if pk_drop is not None else ""
- cells.append(f"`{dr['cooldown_start_c']}→{dr['cooldown_end_c']}°C` (`{delta_c:+}°C`{pk_txt}{tau_txt})")
- lines.append(f"| `{rk}` | `{c_cnt}s` / null `{c_null}s`{delay_txt} | " + " | ".join(cells) + " |")
- mevs = parsed.get("micro_events") or []
- if mevs:
- lines.extend(["", "## 5. 自动检出微事件与异常细节定位 (`#seq` 精确索引)", ""])
- lines.append("| 编号 | 类别 | Run / 阶段 | `#seq` 区间 | 事件标题 | 实测详情 |")
- lines.append("|---|---|---|---|---|---|")
- for ev in mevs:
- seq_txt = f"`#{ev['seq_start']}`" if ev["seq_start"] == ev["seq_end"] else f"`#{ev['seq_start']}..#{ev['seq_end']}` (`{ev['rows']}s`)"
- lines.append(f"| `{ev['id']}` | `{ev['category']}` | `{ev['run_key']}` · `{ev['phase']}` | {seq_txt} | **{ev['title']}** | {ev['detail']} |")
- lines.extend(["", "## 6. 全部连续阶段切片汇总 (按时间先后,含空值审计)", ""])
- lines.append("| `#seq` | Run | 子阶段 | 时长 | SPD有效/空 | PECI有效/空 | `CPU0_A` | `CPU1_A` | `DDR0_Power` | `PSU0_PIn` |")
- lines.append("|---|---|---|---:|---:|---:|---|---|---|---|")
- all_slices: list[tuple[str, dict[str, Any]]] = []
- for rk, rd in parsed["runs"].items():
- for sl in rd.get("phases") or []:
- all_slices.append((rk, sl))
- all_slices.sort(key=lambda x: x[1]["seq_start"])
- for rk, sl in all_slices:
- ss = sl["sensors"]
- lines.append(
- f"| `#{sl['seq_start']}..{sl['seq_end']}` | `{rk}` | `{sl['phase']}` | `{sl['rows']}s` | "
- f"`{sl['spd_valid_rows']}/{sl['spd_null_rows']}` | `{sl['peci_valid_rows']}/{sl['peci_null_rows']}` | "
- f"{_fmt_range(ss.get('DIMM_CPU0_A_Temp'), '°C')} | {_fmt_range(ss.get('DIMM_CPU1_A_Temp'), '°C')} | "
- f"{_fmt_range(ss.get('DDR0_Power'), 'W', False)} | {_fmt_range(ss.get('PSU0_PIn'), 'W', False)} |"
- )
- return "\n".join(lines) + "\n"
- def render_campaign_html_dashboard(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
- payload = {
- "meta": {
- "parser_version": parsed["parser_version"],
- "mode": parsed["mode"],
- "parsed_utc": parsed["parsed_utc"],
- "data_file": parsed["data_file"],
- "bmc_host": parsed["bmc_host"],
- "total_1hz_rows": parsed["total_1hz_rows"],
- "total_duration_hms": parsed["total_duration_hms"],
- "total_duration_s": parsed["total_duration_s"],
- "poll_latency_ms": parsed.get("poll_latency_ms"),
- "sensors": parsed["sensors"],
- "dimm_keys": parsed["dimm_keys"],
- },
- "overall_sensors": parsed["overall_sensors"],
- "runs": parsed["runs"],
- "micro_events": parsed.get("micro_events") or [],
- "bmc_benchmark": parsed.get("bmc_benchmark"),
- "series": artifacts["series"],
- }
- payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
- figs_json = json.dumps(artifacts.get("embedded_figures") or [], ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
- title = html.escape(f"2026-11-13 无温控直跑单算法 · 逐阶段逐传感器完整报告 ({parsed['total_1hz_rows']:,} 行)")
- head_html = r"""<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>__TITLE__</title>
- <style>
- :root {
- --bg: #0b101b; --bg-card: #121a2b; --bg-alt: #182338;
- --text: #e6edf7; --muted: #93a4be; --border: #253554;
- --accent: #38bdf8; --accent2: #818cf8; --good: #22c55e; --warn: #f59e0b; --bad: #ef4444;
- }
- body.light {
- --bg: #f1f5f9; --bg-card: #ffffff; --bg-alt: #e8eff8;
- --text: #0f172a; --muted: #475569; --border: #cbd5e1;
- --accent: #0284c7; --accent2: #4f46e5;
- }
- * { box-sizing: border-box; margin: 0; padding: 0; }
- 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; }
- 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; }
- .hdr-title h1 { font-size: 17px; font-weight: 700; }
- .hdr-sub { font-size: 12px; color: var(--muted); margin-top: 2px; }
- .controls { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
- select, button, input[type="number"], input[type="text"] {
- background: var(--bg-alt); color: var(--text); border: 1px solid var(--border);
- border-radius: 6px; padding: 5px 9px; font-size: 12.5px;
- }
- button, select { cursor: pointer; }
- button:hover, select:hover { border-color: var(--accent); }
- button.active { background: var(--accent); color: #07101e; border-color: var(--accent); font-weight: 600; }
- button.primary { background: var(--accent); color: #07101e; border-color: var(--accent); font-weight: 600; }
- .btn-xs { padding: 3px 8px; font-size: 11.5px; }
- .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; }
- .toggle-pill input { accent-color: var(--accent); }
- .container { max-width: 1620px; margin: 16px auto; padding: 0 18px; }
- .kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; margin-bottom: 14px; }
- .kpi-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 11px 14px; }
- .kpi-label { font-size: 11.5px; color: var(--muted); }
- .kpi-val { font-size: 18px; font-weight: 700; margin-top: 3px; }
- .kpi-sub { font-size: 11.5px; color: var(--muted); margin-top: 3px; }
- .tabs { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
- .tab-btn { padding: 7px 13px; font-size: 13px; }
- .tab-panel { display: none; }
- .tab-panel.active { display: block; }
- .card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 12px 15px; margin-bottom: 14px; }
- .card-hdr { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 8px; }
- .card-hdr h3 { font-size: 14.5px; font-weight: 600; }
- .sub-note { font-size: 12px; color: var(--muted); }
- .badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; }
- .badge.pass { background: rgba(34,197,94,0.16); color: var(--good); border: 1px solid rgba(34,197,94,0.35); }
- .badge.warn { background: rgba(245,158,11,0.16); color: var(--warn); border: 1px solid rgba(245,158,11,0.35); }
- .badge.peak { background: rgba(239,68,68,0.16); color: var(--bad); border: 1px solid rgba(239,68,68,0.35); }
- .badge.info { background: rgba(56,189,248,0.16); color: var(--accent); border: 1px solid rgba(56,189,248,0.35); }
- .legend { display: flex; flex-wrap: wrap; gap: 6px 12px; font-size: 11.5px; color: var(--muted); margin-bottom: 6px; }
- .legend-item { display: inline-flex; align-items: center; gap: 5px; cursor: pointer; user-select: none; }
- .legend-item.off { opacity: 0.35; text-decoration: line-through; }
- .swatch { width: 12px; height: 3px; border-radius: 2px; display: inline-block; }
- .chart-wrap { position: relative; width: 100%; height: 245px; overflow: hidden; }
- .chart-wrap.sm { height: 195px; }
- .chart-wrap.xs { height: 170px; }
- .chart-wrap.lg { height: 300px; }
- .chart-wrap canvas { width: 100%; height: 100%; display: block; }
- .phase-legend { display: flex; flex-wrap: wrap; gap: 10px; font-size: 11.5px; color: var(--muted); margin-top: 6px; }
- .ph-dot { width: 10px; height: 10px; border-radius: 2px; display: inline-block; vertical-align: middle; margin-right: 4px; }
- .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; }
- .me-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 10px; max-height: 360px; overflow-y: auto; padding-right: 4px; }
- .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; }
- .me-card-top { display: flex; justify-content: space-between; align-items: center; gap: 6px; font-size: 11.5px; color: var(--muted); }
- .me-title { font-size: 13px; font-weight: 600; color: var(--text); }
- .me-detail { font-size: 12px; color: var(--muted); line-height: 1.45; }
- .fig-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(430px, 1fr)); gap: 14px; }
- .fig-card { background: var(--bg-alt); border: 1px solid var(--border); border-radius: 8px; padding: 10px; }
- .fig-card img { width: 100%; height: auto; border-radius: 6px; cursor: zoom-in; border: 1px solid var(--border); background: #fff; }
- .fig-hdr { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 8px; font-size: 12.5px; font-weight: 600; }
- .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; }
- .modal.open { display: flex; }
- .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; }
- .modal-box img { max-width: 92vw; max-height: 82vh; object-fit: contain; background: #fff; border-radius: 6px; }
- .table-scroll { overflow-x: auto; max-height: 620px; overflow-y: auto; }
- table { width: 100%; border-collapse: collapse; font-size: 11.8px; }
- th, td { padding: 5px 8px; border-bottom: 1px solid var(--border); text-align: left; white-space: nowrap; }
- th { background: var(--bg-alt); color: var(--muted); font-weight: 600; position: sticky; top: 0; z-index: 2; }
- tr:hover td { background: rgba(56,189,248,0.07); }
- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
- .null-cell { color: var(--muted); font-style: italic; opacity: 0.72; }
- .anom-warn { background: rgba(245,158,11,0.18); color: #fbbf24; font-weight: 600; border-radius: 4px; padding: 1px 4px; }
- .anom-droop { background: rgba(239,68,68,0.18); color: #f87171; font-weight: 600; border-radius: 4px; padding: 1px 4px; }
- .anom-warm { background: rgba(56,189,248,0.18); color: #38bdf8; font-weight: 600; border-radius: 4px; padding: 1px 4px; }
- 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; }
- .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); }
- .filter-grid { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 10px; }
- </style>
- </head>
- <body>
- <header>
- <div class="hdr-title">
- <h1>2026-11-13 无温控直跑单算法 · 全阶段与全传感器 1Hz 独立解析报告 (无均值)</h1>
- <div class="hdr-sub" id="hdr-sub">加载中...</div>
- </div>
- <div class="controls">
- <button type="button" id="btn-jump-raw">逐秒明细 & 微事件</button>
- <button type="button" id="btn-export-all">导出全量 clean CSV</button>
- <button type="button" id="btn-theme">亮/暗主题</button>
- </div>
- </header>
- <div class="container">
- <div class="kpi-grid" id="kpi-grid"></div>
- <div class="tabs">
- <button type="button" class="tab-btn active" data-tab="tab-waves">1. 1Hz 同步多维传感器曲线</button>
- <button type="button" class="tab-btn" data-tab="tab-algos">2. 7 大算法对比 & 曲线截图集</button>
- <button type="button" class="tab-btn" data-tab="tab-phases">3. 全部详细阶段 & 轮次 (全 21 路传感器)</button>
- <button type="button" class="tab-btn" data-tab="tab-raw">4. 全量 1Hz 逐秒明细 & 微事件排查</button>
- <button type="button" class="tab-btn" data-tab="tab-bench">5. Sensor 清单 · BMC 基准 · 总结</button>
- </div>
- <div id="tab-waves" class="tab-panel active">
- <div class="card">
- <div class="card-hdr">
- <h3>区间缩放 & 微变化快捷定位 (4 图 X 轴联动 · 左键拖拽框选放大 · 单击固定采样点 · 双击复位)</h3>
- <div class="controls">
- <label class="toggle-pill"><input type="checkbox" id="chk-skip-boot"> 跳过前置 boot/init (仅看 基线→Loop→冷却)</label>
- <button type="button" class="btn-xs" id="btn-reset-zoom">复位全过程</button>
- </div>
- </div>
- <div class="controls" id="zoom-bar" style="margin-bottom:8px"></div>
- <div class="controls" id="me-pills" style="margin-bottom:6px"></div>
- <div class="phase-legend">
- <span><i class="ph-dot" style="background:rgba(245,158,11,0.35)"></i>boot_to_amt / init (重启或初始化)</span>
- <span><i class="ph-dot" style="background:rgba(56,189,248,0.35)"></i>pre_baseline (静息基线)</span>
- <span><i class="ph-dot" style="background:rgba(34,197,94,0.38)"></i>loop_1..N (单算法运行)</span>
- <span><i class="ph-dot" style="background:rgba(168,85,247,0.35)"></i>cooldown (150s 停载冷却;AMT含初段~18-22s热重启SPD空窗及~100s二次切OS约10s空窗)</span>
- </div>
- </div>
- <div class="pin-bar" id="pin-bar">
- <span id="pin-text" class="mono">提示:在任意曲线图上单击可固定某 1 秒采样点,快速核对该秒全 21 路传感器或跳转至明细表。</span>
- <span class="controls" id="pin-actions" style="display:none">
- <button type="button" class="btn-xs primary" id="btn-pin-raw">在逐秒明细表定位</button>
- <button type="button" class="btn-xs" id="btn-pin-clear">清除固定</button>
- </span>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 1A · 5 路独立 DIMM 插槽 + CPU0/1 温度 1Hz 曲线 (°C,无均值)</h3>
- <div class="controls">
- <span class="mono badge info" id="win-badge"></span>
- <button type="button" class="btn-xs" data-tmp-preset="all">全部显示</button>
- <button type="button" class="btn-xs" data-tmp-preset="dimms">仅5路DIMM</button>
- <button type="button" class="btn-xs" data-tmp-preset="cpu0">仅CPU0 A..D</button>
- <button type="button" class="btn-xs" data-tmp-preset="edge">CPU0_A vs CPU1_A</button>
- </div>
- </div>
- <div class="legend" id="legend-temp"></div>
- <div class="chart-wrap"><canvas id="chart-temp"></canvas></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 1B · 内存供电轨独立功耗 1Hz 曲线 (DDR0/DDR2/PVCCD/PECI DIMM, 0~55W 独立坐标轴)</h3>
- <div class="controls">
- <button type="button" class="btn-xs" data-mpwr-preset="all">全部显示</button>
- <button type="button" class="btn-xs" data-mpwr-preset="vr">仅PMBus VR (DDR0/DDR2)</button>
- <button type="button" class="btn-xs" data-mpwr-preset="peci">对比PMBus vs PECI</button>
- </div>
- </div>
- <div class="legend" id="legend-mpwr"></div>
- <div class="chart-wrap sm"><canvas id="chart-mpwr"></canvas></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 1C · 整机 PSU0 与 CPU0/CPU1 功耗 1Hz 曲线 (100~800W)</h3>
- <div class="controls">
- <button type="button" class="btn-xs" data-spwr-preset="all">全部显示</button>
- <button type="button" class="btn-xs" data-spwr-preset="psu">仅PSU0输入/输出</button>
- <button type="button" class="btn-xs" data-spwr-preset="cpu">仅CPU0/CPU1功耗</button>
- </div>
- </div>
- <div class="legend" id="legend-spwr"></div>
- <div class="chart-wrap sm"><canvas id="chart-spwr"></canvas></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3 id="elec-chart-title">Chart 1D · 电参数 & 采集健康度 (当前:DDR0/DDR2 电流 A)</h3>
- <div class="controls">
- <button type="button" class="btn-xs active" data-elec-mode="curr">电流 (DDR0/2_Curr A)</button>
- <button type="button" class="btn-xs" data-elec-mode="volt">12V 供电电压压降 (P12V V)</button>
- <button type="button" class="btn-xs" data-elec-mode="lat">BMC 1Hz 采集耗时 (ms)</button>
- </div>
- </div>
- <div class="legend" id="legend-elec"></div>
- <div class="chart-wrap xs"><canvas id="chart-elec"></canvas></div>
- </div>
- </div>
- <div id="tab-algos" class="tab-panel">
- <div class="card">
- <div class="card-hdr">
- <h3>Chart 2 · 7 大单算法逐插槽热/功耗/时间常数对比 (无均值)</h3>
- <div class="controls">
- <select id="bar-metric-select">
- <option value="dimm_delta">5 路 DIMM 负载期温升 ΔT (°C)</option>
- <option value="dimm_max">5 路 DIMM 峰值温度 (°C)</option>
- <option value="dimm_rate">全负载窗口升温斜率 (°C/min)</option>
- <option value="dimm_early">前 40s 初期升温斜率 (°C/min)</option>
- <option value="tau_cool">停载冷却时间常数 τ_cool (s, 越小散热越快)</option>
- <option value="ddr_max">DDR0 vs DDR2 vs PVCCD 峰值功耗 (W)</option>
- <option value="psu_max">PSU0 PIn vs CPU0 vs CPU1 峰值功耗 (W)</option>
- </select>
- </div>
- </div>
- <div class="chart-wrap lg"><canvas id="chart-bars"></canvas></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>各算法负载窗口 · 逐 DIMM 插槽独立温升、初期/全窗斜率与跨槽极差</h3></div>
- <div class="table-scroll" id="algo-dimm-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>各算法负载窗口 · 逐供电/电流/电压/PECI 与 CPU 位置传感器范围 (<code>min~max</code>)</h3></div>
- <div class="table-scroll" id="algo-pwr-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>停载冷却恢复 (150s Cooldown) 逐插槽实测回落、SPD 首读延迟与 τ_cool</h3></div>
- <div class="table-scroll" id="algo-cool-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>高精度实测曲线截图集 (PNG 离线内嵌 · 点击放大 / 右上角另存发送)</h3>
- <span class="sub-note" id="fig-count-note"></span>
- </div>
- <div id="fig-gallery" class="fig-grid"></div>
- </div>
- </div>
- <div id="tab-phases" class="tab-panel">
- <div class="card">
- <div class="card-hdr">
- <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>
- <div class="controls">
- <label>Run:<select id="phase-run-filter"><option value="">全部 Run</option></select></label>
- <label>阶段类型:<select id="phase-grp-filter">
- <option value="">全部阶段</option>
- <option value="baseline">仅 pre_baseline</option>
- <option value="active_loop">仅 loop_1..N</option>
- <option value="cooldown">仅 cooldown</option>
- <option value="startup">仅 boot_to_amt / init</option>
- <option value="idle">仅 inter_algo_settle / idle_check</option>
- </select></label>
- <label>显示传感器列:<select id="phase-col-preset">
- <option value="core">核心温度 + 功耗 + 12V (11路)</option>
- <option value="all">全部 21 路传感器展开</option>
- <option value="dimm">仅 5 路 DIMM + CPU0/1 温度</option>
- <option value="pwr">全部功耗 + 电流 + 12V + PECI</option>
- </select></label>
- </div>
- </div>
- <div class="table-scroll" id="phases-detail-table"></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>BIOS 固件 Loop 完成事件记录 (<code>loop_events</code> · Socket 0 vs Socket 1 实测秒数对照)</h3>
- <span class="sub-note">来自 <code>thermal_campaign_summary.json</code>,精确映射至对应 1Hz 采样 <code>#seq</code></span>
- </div>
- <div class="table-scroll" id="loop-events-table"></div>
- </div>
- </div>
- <div id="tab-raw" class="tab-panel">
- <div class="card">
- <div class="card-hdr">
- <h3>自动检出微事件 & 异常变化定向排查书签 (<span id="me-count">0</span> 项)</h3>
- <div class="controls">
- <label>筛选类别:<select id="me-cat-filter"><option value="">全部类别</option></select></label>
- <span class="sub-note">点击卡片按钮可直接将曲线放大至该瞬态窗口,或锁定到下方 1Hz 逐秒记录。</span>
- </div>
- </div>
- <div class="me-grid" id="me-cards"></div>
- </div>
- <div class="card">
- <div class="card-hdr">
- <h3>全量 1Hz 逐秒遥测数据浏览器 (逐样本 × 逐位置传感器,支持条件过滤与离线 CSV 导出)</h3>
- <div class="controls">
- <span class="mono sub-note" id="raw-count-info">0 行</span>
- <button type="button" class="primary btn-xs" id="btn-raw-export">导出当前筛选 CSV</button>
- </div>
- </div>
- <div class="filter-grid">
- <label>Run: <select id="raw-run"><option value="">全部</option></select></label>
- <label>阶段: <select id="raw-phase"><option value="">全部</option></select></label>
- <label>快捷排查: <select id="raw-preset">
- <option value="all">全部 1Hz 样本</option>
- <option value="spd_null">SPD 传感器离线 (任意 DIMM=null)</option>
- <option value="peci_null">PECI 功耗离线 (Dimm_Power_CPU0=null)</option>
- <option value="cool_spike">cooldown 阶段高功耗脉冲 (DDR0≥20W)</option>
- <option value="p12v_droop">12V 供电下探 (P12V_DDR0≤12.13V)</option>
- <option value="high_lat">BMC 高采集延迟 (poll_latency≥300ms)</option>
- <option value="temp_jump">DIMM 单秒温跳 (|ΔDIMM|≥0.75°C/s)</option>
- <option value="pwr_jump">DDR0 功耗阶跃 (|ΔDDR0|≥5W/s)</option>
- </select></label>
- <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>
- <label>自定义:
- <select id="raw-cust-col"><option value="">(不限指标)</option></select>
- <select id="raw-cust-op">
- <option value="gt">></option>
- <option value="ge">>=</option>
- <option value="lt"><</option>
- <option value="le"><=</option>
- <option value="isnull">is null</option>
- <option value="notnull">not null</option>
- </select>
- <input type="number" step="any" id="raw-cust-val" placeholder="阈值" style="width:78px">
- </label>
- <label>列组:
- <select id="raw-col-group">
- <option value="core">核心温度 + 功耗 + 12V (11列)</option>
- <option value="all">全部 21 路传感器展开</option>
- <option value="temps">全部温度 + 延迟</option>
- <option value="elec">全部功耗 + 电流 + 12V + PECI</option>
- </select>
- </label>
- <label>每页:
- <select id="raw-page-size">
- <option value="50">50</option>
- <option value="100" selected>100</option>
- <option value="200">200</option>
- <option value="500">500</option>
- </select>
- </label>
- <button type="button" class="btn-xs" id="btn-raw-reset">重置筛选</button>
- </div>
- <div class="controls" style="margin-bottom:8px;justify-content:space-between">
- <div class="controls">
- <button type="button" class="btn-xs" id="raw-prev">上一页</button>
- <span class="mono" id="raw-page-info">1 / 1</span>
- <button type="button" class="btn-xs" id="raw-next">下一页</button>
- </div>
- <span class="sub-note">提示:点击行号 <code>#seq</code> 可切回曲线页并放大至该时刻 <code>±30s</code>;表格内斜体灰字表示硬件当时不可访问 (<code>null</code>)。</span>
- </div>
- <div class="table-scroll" id="raw-table-wrap"></div>
- </div>
- </div>
- <div id="tab-bench" class="tab-panel">
- <div class="card">
- <div class="card-hdr"><h3>全部 21 路独立位置传感器全周期统计 (<code>min~max</code>, <code>起点→终点</code>, 有效/空值计数)</h3></div>
- <div class="table-scroll" id="overall-sensors-table"></div>
- </div>
- <div class="card" id="bench-card">
- <div class="card-hdr"><h3>BMC 采集链路基准对比 (<code>ipmitool lanplus</code> vs <code>OpenBMC D-Bus GetManagedObjects</code>)</h3></div>
- <div id="bench-body"></div>
- </div>
- <div class="card">
- <div class="card-hdr"><h3>核心数据洞察 & 工程要点索引</h3></div>
- <div id="conclusions-box" style="font-size:13px;line-height:1.7"></div>
- </div>
- </div>
- </div>
- <div class="tooltip" id="tooltip"></div>
- <div class="modal" id="fig-modal">
- <div class="modal-box">
- <div class="card-hdr" style="margin:0">
- <h3 id="modal-title">图片预览</h3>
- <div class="controls">
- <a id="modal-dl" download class="badge info" style="text-decoration:none;padding:5px 10px">下载 PNG 原图</a>
- <button type="button" id="modal-close">关闭 (Esc)</button>
- </div>
- </div>
- <img id="modal-img" alt="figure preview">
- </div>
- </div>
- """.replace("__TITLE__", title)
- script_js = r"""
- <script>
- (() => {
- const DATA = JSON.parse(document.getElementById('embedded-data').textContent);
- const FIGS = JSON.parse(document.getElementById('embedded-figures').textContent);
- const ser = DATA.series;
- const cols = ser.cols;
- const n = cols.seq.length;
- const microEvents = DATA.micro_events || [];
- let zoomStart = 0, zoomEnd = n, hoverIdx = null, pinnedIdx = null;
- let dragStartIdx = null, dragCurIdx = null, dragStartClientX = 0;
- let elecMode = 'curr';
- let activeRunZoom = 'ALL';
- let rawPage = 1, rawFiltered = [];
- let barCache = [];
- const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
- const fmtMM = (st, u='') => st ? `${st.min}~${st.max}${u}` : '-';
- const fmtSE = (st, u='') => st ? `${st.start}→${st.end}${u}` : '-';
- // Precompute contiguous phase segments once for fast canvas shading & labels
- const phaseSegs = [];
- for (let i = 0; i < n; ) {
- const rId = cols.rk[i], pId = cols.ph[i];
- let j = i + 1;
- while (j < n && cols.rk[j] === rId && cols.ph[j] === pId) j++;
- phaseSegs.push({ rk: ser.run_names[rId], ph: ser.phase_names[pId], s: i, e: j });
- i = j;
- }
- const tempSeries = [
- { key: 'DIMM_CPU0_A_Temp', label: 'DIMM CPU0_A', color: '#ef4444', width: 1.8, grp: 'cpu0' },
- { key: 'DIMM_CPU0_B_Temp', label: 'DIMM CPU0_B', color: '#f59e0b', width: 1.6, grp: 'cpu0' },
- { key: 'DIMM_CPU0_C_Temp', label: 'DIMM CPU0_C', color: '#22c55e', width: 1.6, grp: 'cpu0' },
- { key: 'DIMM_CPU0_D_Temp', label: 'DIMM CPU0_D', color: '#38bdf8', width: 1.6, grp: 'cpu0' },
- { key: 'DIMM_CPU1_A_Temp', label: 'DIMM CPU1_A', color: '#a855f7', width: 1.9, grp: 'dimms' },
- { key: 'CPU0_Temp', label: 'CPU0 温度', color: '#94a3b8', width: 1.2, dash: [4, 2], grp: 'cpu' },
- { key: 'CPU1_Temp', label: 'CPU1 温度', color: '#64748b', width: 1.2, dash: [4, 2], grp: 'cpu' },
- ].filter(s => cols[s.key]);
- const enabledTemp = new Set(tempSeries.map(s => s.key));
- const memPwrSeries = [
- { key: 'DDR0_Power', label: 'DDR0 PMBus(W)', color: '#22c55e', width: 1.8, grp: 'vr' },
- { key: 'DDR2_Power', label: 'DDR2 PMBus(W)', color: '#f59e0b', width: 1.8, grp: 'vr' },
- { key: 'PVCCD_CPU0_Input_Power', label: 'PVCCD CPU0(W)', color: '#06b6d4', width: 1.3, grp: 'vr' },
- { key: 'PVCCD_CPU1_Input_Power', label: 'PVCCD CPU1(W)', color: '#ec4899', width: 1.3, grp: 'vr' },
- { key: 'Dimm_Power_CPU0', label: 'PECI DIMM0(W)', color: '#84cc16', width: 1.4, dash: [3,2], grp: 'peci' },
- { key: 'Dimm_Power_CPU1', label: 'PECI DIMM1(W)', color: '#fb7185', width: 1.4, dash: [3,2], grp: 'peci' },
- ].filter(s => cols[s.key]);
- const enabledMemPwr = new Set(memPwrSeries.map(s => s.key));
- const sysPwrSeries = [
- { key: 'PSU0_PIn', label: 'PSU0 PIn(W)', color: '#38bdf8', width: 1.7, grp: 'psu' },
- { key: 'PSU0_POut', label: 'PSU0 POut(W)', color: '#0ea5e9', width: 1.3, dash: [4,2], grp: 'psu' },
- { key: 'CPU0_Power_Avg', label: 'PECI CPU0(W)', color: '#818cf8', width: 1.5, grp: 'cpu' },
- { key: 'CPU1_Power_Avg', label: 'PECI CPU1(W)', color: '#c084fc', width: 1.5, grp: 'cpu' },
- ].filter(s => cols[s.key]);
- const enabledSysPwr = new Set(sysPwrSeries.map(s => s.key));
- const elecModeConfigs = {
- curr: {
- title: 'Chart 1D · 电参数 & 采集健康度 (当前:DDR0/DDR2 供电电流 A)',
- decimals: 2,
- series: [
- { key: 'DDR0_Curr', label: 'DDR0_Curr (A)', color: '#10b981', width: 1.6 },
- { key: 'DDR2_Curr', label: 'DDR2_Curr (A)', color: '#fbbf24', width: 1.6 },
- ].filter(s => cols[s.key]),
- },
- volt: {
- title: 'Chart 1D · 电参数 & 采集健康度 (当前:P12V 供电轨电压压降 V · 3位小数精细轴)',
- decimals: 3,
- series: [
- { key: 'P12V_DDR0', label: 'P12V_DDR0 (V)', color: '#ef4444', width: 1.6 },
- { key: 'P12V_DDR2', label: 'P12V_DDR2 (V)', color: '#38bdf8', width: 1.6 },
- ].filter(s => cols[s.key]),
- },
- lat: {
- title: 'Chart 1D · 电参数 & 采集健康度 (当前:OpenBMC D-Bus 单次轮询耗时 ms)',
- decimals: 0,
- series: [
- { key: 'lat', label: 'poll_latency_ms (ms)', color: '#f59e0b', width: 1.5 },
- ],
- },
- };
- const enabledElec = new Set(['DDR0_Curr', 'DDR2_Curr', 'P12V_DDR0', 'P12V_DDR2', 'lat']);
- document.getElementById('hdr-sub').textContent =
- `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}`;
- document.getElementById('btn-jump-raw').textContent = `逐秒明细 & 微事件 (${n.toLocaleString()}行)`;
- document.getElementById('btn-theme').onclick = () => { document.body.classList.toggle('light'); drawAll(); };
- function switchTab(tabId) {
- document.querySelectorAll('.tab-btn').forEach(b => b.classList.toggle('active', b.dataset.tab === tabId));
- document.querySelectorAll('.tab-panel').forEach(p => p.classList.toggle('active', p.id === tabId));
- requestAnimationFrame(() => drawAll());
- }
- document.querySelectorAll('.tab-btn').forEach(btn => { btn.onclick = () => switchTab(btn.dataset.tab); });
- document.getElementById('btn-jump-raw').onclick = () => switchTab('tab-raw');
- function exportCsvForIndices(indices, filename) {
- const hdr = ['seq', 'iso_ts_hms', 'campaign_elapsed_s', 'run_key', 'phase', 'loop_index', 'poll_latency_ms']
- .concat(DATA.meta.sensors.map(s => s.key));
- const lines = [hdr.join(',')];
- for (const i of indices) {
- const row = [
- cols.seq[i], cols.ts[i], cols.t[i],
- ser.run_names[cols.rk[i]], ser.phase_names[cols.ph[i]],
- cols.loop[i], cols.lat[i] ?? '',
- ];
- for (const s of DATA.meta.sensors) {
- const v = cols[s.key]?.[i];
- row.push(v == null ? '' : v);
- }
- lines.push(row.join(','));
- }
- const blob = new Blob(['\ufeff' + lines.join('\r\n')], { type: 'text/csv;charset=utf-8;' });
- const a = document.createElement('a');
- a.href = URL.createObjectURL(blob);
- a.download = filename;
- a.click();
- setTimeout(() => URL.revokeObjectURL(a.href), 1500);
- }
- document.getElementById('btn-export-all').onclick = () => {
- const allIdx = Array.from({ length: n }, (_, i) => i);
- exportCsvForIndices(allIdx, 'thermal_campaign_all_3119_per_sensor.csv');
- };
- function setElecMode(mode) {
- if (!elecModeConfigs[mode]) return;
- elecMode = mode;
- document.querySelectorAll('[data-elec-mode]').forEach(b => b.classList.toggle('active', b.dataset.elecMode === mode));
- document.getElementById('elec-chart-title').textContent = elecModeConfigs[mode].title;
- buildElecLegend();
- drawCharts();
- }
- document.querySelectorAll('[data-elec-mode]').forEach(btn => {
- btn.onclick = () => setElecMode(btn.dataset.elecMode);
- });
- function applyRunZoom(rk) {
- activeRunZoom = rk;
- const skipBoot = document.getElementById('chk-skip-boot').checked;
- if (rk === 'ALL') {
- zoomStart = 0; zoomEnd = n;
- } else {
- const rd = DATA.runs[rk];
- if (rd) {
- const win = (skipBoot && rd.core_window) ? rd.core_window : rd.full_window;
- zoomStart = win[0]; zoomEnd = win[1];
- }
- }
- buildZoomBar(); drawCharts();
- }
- document.getElementById('chk-skip-boot').onchange = () => {
- if (activeRunZoom !== 'ALL') applyRunZoom(activeRunZoom);
- };
- document.getElementById('btn-reset-zoom').onclick = () => applyRunZoom('ALL');
- window.zoomToSeqRange = (seqA, seqB, focusChart = 'all', pinSeq = null, pad = 15) => {
- switchTab('tab-waves');
- activeRunZoom = '';
- zoomStart = Math.max(0, seqA - 1 - pad);
- zoomEnd = Math.min(n, seqB + pad);
- if (pinSeq != null) pinnedIdx = Math.max(0, Math.min(n - 1, pinSeq - 1));
- if (focusChart === 'elec_volt') setElecMode('volt');
- else if (focusChart === 'elec_lat') setElecMode('lat');
- else if (focusChart === 'elec_curr') setElecMode('curr');
- updatePinBar();
- buildZoomBar();
- requestAnimationFrame(() => drawCharts());
- };
- window.jumpToRawRange = (runKey = '', phase = '', seqMin = '', seqMax = '', preset = 'all') => {
- document.getElementById('raw-run').value = runKey;
- document.getElementById('raw-phase').value = phase;
- document.getElementById('raw-seq-min').value = seqMin;
- document.getElementById('raw-seq-max').value = seqMax;
- document.getElementById('raw-preset').value = preset;
- document.getElementById('raw-cust-col').value = '';
- document.getElementById('raw-cust-val').value = '';
- rawPage = 1;
- switchTab('tab-raw');
- applyRawFilter();
- };
- function updatePinBar() {
- const txt = document.getElementById('pin-text');
- const act = document.getElementById('pin-actions');
- if (pinnedIdx == null || pinnedIdx < 0 || pinnedIdx >= n) {
- txt.textContent = '提示:在任意曲线图上单击可固定某 1 秒采样点,核对该秒全 21 路传感器或跳转明细表。';
- act.style.display = 'none';
- return;
- }
- const i = pinnedIdx;
- const rk = ser.run_names[cols.rk[i]], ph = ser.phase_names[cols.ph[i]];
- txt.innerHTML = `已固定 <b>#${cols.seq[i]}</b> (${esc(cols.ts[i])} · ${cols.t[i]}s) · <b>${esc(rk)}</b> / ${esc(ph)} | ` +
- `CPU0_A=<b>${cols.DIMM_CPU0_A_Temp?.[i] ?? 'null'}°C</b> CPU1_A=<b>${cols.DIMM_CPU1_A_Temp?.[i] ?? 'null'}°C</b> | ` +
- `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>`;
- act.style.display = 'inline-flex';
- }
- document.getElementById('btn-pin-clear').onclick = () => { pinnedIdx = null; updatePinBar(); drawCharts(); };
- document.getElementById('btn-pin-raw').onclick = () => {
- if (pinnedIdx == null) return;
- const sq = cols.seq[pinnedIdx];
- window.jumpToRawRange('', '', Math.max(1, sq - 5), Math.min(n, sq + 5), 'all');
- };
- function renderKpis() {
- const ov = DATA.overall_sensors, dKeys = DATA.meta.dimm_keys;
- const dMin = Math.min(...dKeys.map(k => (ov[k] || {}).min ?? 999));
- const dMax = Math.max(...dKeys.map(k => (ov[k] || {}).max ?? -999));
- const runCnt = Object.values(DATA.runs).filter(r => r.active_rows > 0).length;
- const lat = DATA.meta.poll_latency_ms;
- const p12 = ov.P12V_DDR0 || {};
- document.getElementById('kpi-grid').innerHTML = `
- <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>
- <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>
- <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>
- <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>
- <div class="kpi-card"><div class="kpi-label">微事件 & 异常切换</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>
- `;
- const link = document.getElementById('kpi-me-link');
- if (link) link.onclick = e => { e.preventDefault(); switchTab('tab-raw'); };
- }
- function buildZoomBar() {
- const bar = document.getElementById('zoom-bar'); bar.innerHTML = '';
- const mk = (lbl, rk) => {
- const btn = document.createElement('button'); btn.type = 'button'; btn.textContent = lbl;
- if (activeRunZoom === rk) btn.classList.add('active');
- btn.onclick = () => applyRunZoom(rk);
- bar.appendChild(btn);
- };
- mk(`全过程 (${n}s)`, 'ALL');
- Object.keys(DATA.runs).forEach(rk => {
- if (rk === '00_init') return;
- mk(rk, rk);
- });
- const mp = document.getElementById('me-pills'); mp.innerHTML = '<span class="sub-note">微事件快捷缩放:</span>';
- microEvents.slice(0, 10).forEach(ev => {
- const b = document.createElement('button'); b.type = 'button'; b.className = 'btn-xs';
- b.textContent = `${ev.id}: ${ev.title.length > 34 ? ev.title.slice(0, 34) + '…' : ev.title}`;
- b.title = ev.detail;
- b.onclick = () => window.zoomToSeqRange(ev.seq_start, ev.seq_end, ev.focus_chart, ev.seq_start, ev.pad_s);
- mp.appendChild(b);
- });
- }
- function makeLegend(id, list, set) {
- const el = document.getElementById(id); if (!el) return;
- el.innerHTML = '';
- list.forEach(item => {
- const sp = document.createElement('span');
- sp.className = 'legend-item' + (set.has(item.key) ? '' : ' off');
- sp.innerHTML = `<span class="swatch" style="background:${item.color}"></span>${esc(item.label)}`;
- sp.onclick = () => {
- if (set.has(item.key)) set.delete(item.key); else set.add(item.key);
- sp.classList.toggle('off'); drawCharts();
- };
- el.appendChild(sp);
- });
- }
- function buildElecLegend() { makeLegend('legend-elec', elecModeConfigs[elecMode].series, enabledElec); }
- function buildLegends() {
- makeLegend('legend-temp', tempSeries, enabledTemp);
- makeLegend('legend-mpwr', memPwrSeries, enabledMemPwr);
- makeLegend('legend-spwr', sysPwrSeries, enabledSysPwr);
- buildElecLegend();
- }
- document.querySelectorAll('[data-tmp-preset]').forEach(btn => {
- btn.onclick = () => {
- const p = btn.dataset.tmpPreset; enabledTemp.clear();
- tempSeries.forEach(s => {
- 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'))) {
- enabledTemp.add(s.key);
- }
- });
- makeLegend('legend-temp', tempSeries, enabledTemp); drawCharts();
- };
- });
- document.querySelectorAll('[data-mpwr-preset]').forEach(btn => {
- btn.onclick = () => {
- const p = btn.dataset.mpwrPreset; enabledMemPwr.clear();
- memPwrSeries.forEach(s => {
- 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'))) {
- enabledMemPwr.add(s.key);
- }
- });
- makeLegend('legend-mpwr', memPwrSeries, enabledMemPwr); drawCharts();
- };
- });
- document.querySelectorAll('[data-spwr-preset]').forEach(btn => {
- btn.onclick = () => {
- const p = btn.dataset.spwrPreset; enabledSysPwr.clear();
- sysPwrSeries.forEach(s => { if (p === 'all' || s.grp === p) enabledSysPwr.add(s.key); });
- makeLegend('legend-spwr', sysPwrSeries, enabledSysPwr); drawCharts();
- };
- });
- function setupCanvas(canvas) {
- const rect = canvas.parentElement.getBoundingClientRect();
- const dpr = window.devicePixelRatio || 1;
- const w = Math.max(320, Math.floor(rect.width)), h = Math.max(150, Math.floor(rect.height));
- canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);
- canvas.style.width = w + 'px'; canvas.style.height = h + 'px';
- const ctx = canvas.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
- return { ctx, w, h };
- }
- function phaseStyle(ph) {
- if (ph === 'pre_baseline') return { bg: 'rgba(56,189,248,0.09)', lbl: 'base' };
- if (ph === 'boot_to_amt') return { bg: 'rgba(245,158,11,0.07)', lbl: 'boot' };
- if (ph === 'init') return { bg: 'rgba(245,158,11,0.10)', lbl: 'init' };
- if (ph.startsWith('loop_')) {
- const lnum = parseInt(ph.slice(5), 10) || 1;
- return { bg: (lnum % 2 === 1) ? 'rgba(34,197,94,0.12)' : 'rgba(16,185,129,0.20)', lbl: 'L' + lnum };
- }
- if (ph === 'cooldown') return { bg: 'rgba(168,85,247,0.09)', lbl: 'cool' };
- return { bg: 'rgba(148,163,184,0.06)', lbl: '' };
- }
- function drawLineChart(canvasId, seriesList, enabledSet, opts = {}) {
- const canvas = document.getElementById(canvasId); if (!canvas) return;
- const { ctx, w, h } = setupCanvas(canvas);
- const sIdx = Math.max(0, zoomStart), eIdx = Math.min(n, zoomEnd), span = Math.max(1, eIdx - sIdx);
- const decimals = opts.decimals ?? 1;
- const pad = { l: 58, r: 24, t: 18, b: 24 }, pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
- const cs = getComputedStyle(document.body), borderCol = cs.getPropertyValue('--border').trim(), mutedCol = cs.getPropertyValue('--muted').trim();
- let yMin = Infinity, yMax = -Infinity;
- seriesList.forEach(s => {
- if (!enabledSet.has(s.key)) return;
- const arr = cols[s.key]; if (!arr) return;
- for (let i = sIdx; i < eIdx; i++) {
- const v = arr[i];
- if (v !== null && v !== undefined) {
- if (v < yMin) yMin = v;
- if (v > yMax) yMax = v;
- }
- }
- });
- if (!isFinite(yMin)) { yMin = 0; yMax = 100; }
- const rawRange = yMax - yMin;
- const minSpan = decimals >= 3 ? 0.02 : (decimals === 2 ? 0.2 : 2.0);
- const effSpan = Math.max(minSpan, rawRange);
- const yPad = effSpan * 0.12;
- yMin = yMin - yPad; yMax = yMax + yPad;
- if (decimals <= 1 && yMin > 0 && rawRange < 5 && opts.zeroBase) yMin = 0;
- const xAt = i => pad.l + ((i - sIdx) / Math.max(1, span - 1)) * pw;
- const xBound = i => pad.l + ((i - sIdx) / Math.max(1, span)) * pw;
- const yAt = v => pad.t + ph - ((v - yMin) / Math.max(1e-9, yMax - yMin)) * ph;
- // Phase shading & non-overlapping labels
- let prevRk = null;
- ctx.font = '10px monospace';
- for (const seg of phaseSegs) {
- if (seg.e <= sIdx || seg.s >= eIdx) continue;
- const a = Math.max(sIdx, seg.s), b = Math.min(eIdx, seg.e);
- const x1 = xBound(a), x2 = xBound(b), segW = Math.max(1, x2 - x1);
- const st = phaseStyle(seg.ph);
- ctx.fillStyle = st.bg;
- ctx.fillRect(x1, pad.t, segW, ph);
- if (prevRk !== null && prevRk !== seg.rk) {
- ctx.save(); ctx.strokeStyle = 'rgba(148,163,184,0.35)'; ctx.setLineDash([3, 3]);
- ctx.beginPath(); ctx.moveTo(x1, pad.t); ctx.lineTo(x1, pad.t + ph); ctx.stroke(); ctx.restore();
- }
- if (segW >= 26 && st.lbl && opts.showPhaseLabels) {
- ctx.fillStyle = mutedCol; ctx.textAlign = 'center';
- ctx.fillText(st.lbl, x1 + segW / 2, pad.t - 4);
- }
- prevRk = seg.rk;
- }
- // Grid lines & window badge
- ctx.strokeStyle = borderCol; ctx.font = '11px sans-serif'; ctx.fillStyle = mutedCol;
- 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(decimals), pad.l - 6, yy + 4);
- }
- for (let t = 0; t <= 6; t++) {
- const idx = Math.min(n - 1, sIdx + Math.floor((t / 6) * (span - 1)));
- ctx.textAlign = t === 0 ? 'left' : (t === 6 ? 'right' : 'center');
- ctx.fillText(`${cols.ts[idx] || ''} (#${cols.seq[idx]})`, pad.l + (t / 6) * pw, h - 6);
- }
- if (opts.showPhaseLabels) {
- const wb = document.getElementById('win-badge');
- if (wb) wb.textContent = `窗口: #${cols.seq[sIdx]}..#${cols.seq[eIdx - 1]} (${span}s)`;
- }
- // Plot all points without skipping 1s transients
- const stride = span > 15000 ? Math.floor(span / 8000) : 1;
- seriesList.forEach(s => {
- if (!enabledSet.has(s.key)) return;
- const arr = cols[s.key]; if (!arr) return;
- ctx.save(); ctx.strokeStyle = s.color; ctx.fillStyle = s.color; ctx.lineWidth = s.width;
- if (s.dash) ctx.setLineDash(s.dash);
- ctx.beginPath();
- let started = false, runPts = 0, lastX = 0, lastY = 0;
- for (let i = sIdx; i < eIdx; i += stride) {
- const v = arr[i];
- if (v === null || v === undefined) {
- if (runPts === 1) ctx.fillRect(lastX - 1.5, lastY - 1.5, 3, 3);
- started = false; runPts = 0; continue;
- }
- const x = xAt(i), y = yAt(v);
- if (!started) { ctx.moveTo(x, y); started = true; runPts = 1; }
- else { ctx.lineTo(x, y); runPts++; }
- lastX = x; lastY = y;
- }
- if (runPts === 1) ctx.fillRect(lastX - 1.5, lastY - 1.5, 3, 3);
- ctx.stroke(); ctx.restore();
- });
- if (dragStartIdx !== null && dragCurIdx !== null && dragStartIdx !== dragCurIdx) {
- const x1 = xAt(Math.max(sIdx, Math.min(dragStartIdx, dragCurIdx)));
- const x2 = xAt(Math.min(eIdx - 1, Math.max(dragStartIdx, dragCurIdx)));
- ctx.fillStyle = 'rgba(56,189,248,0.18)'; ctx.fillRect(x1, pad.t, Math.max(2, x2 - x1), ph);
- }
- if (pinnedIdx !== null && pinnedIdx >= sIdx && pinnedIdx < eIdx) {
- const px = xAt(pinnedIdx);
- ctx.save(); ctx.strokeStyle = '#f59e0b'; ctx.lineWidth = 1.6; ctx.setLineDash([4, 3]);
- ctx.beginPath(); ctx.moveTo(px, pad.t); ctx.lineTo(px, pad.t + ph); ctx.stroke(); ctx.restore();
- }
- if (hoverIdx !== null && hoverIdx >= sIdx && hoverIdx < eIdx) {
- const hx = xAt(hoverIdx);
- ctx.strokeStyle = 'rgba(255,255,255,0.55)'; ctx.lineWidth = 1;
- ctx.beginPath(); ctx.moveTo(hx, pad.t); ctx.lineTo(hx, pad.t + ph); ctx.stroke();
- }
- }
- function attachHover(canvasId) {
- const canvas = document.getElementById(canvasId), tip = document.getElementById('tooltip');
- const idxFromEvent = ev => {
- const rect = canvas.getBoundingClientRect(), x = ev.clientX - rect.left;
- const sIdx = Math.max(0, zoomStart), eIdx = Math.min(n, zoomEnd);
- const ratio = Math.max(0, Math.min(1, (x - 58) / Math.max(1, rect.width - 82)));
- return Math.min(n - 1, sIdx + Math.round(ratio * Math.max(0, eIdx - sIdx - 1)));
- };
- canvas.onmousedown = ev => {
- dragStartClientX = ev.clientX;
- dragStartIdx = idxFromEvent(ev);
- dragCurIdx = dragStartIdx;
- };
- canvas.onmouseup = ev => {
- const pxMoved = Math.abs(ev.clientX - dragStartClientX);
- if (pxMoved < 6 && dragStartIdx !== null) {
- pinnedIdx = dragStartIdx;
- updatePinBar();
- } else if (dragStartIdx !== null && dragCurIdx !== null && Math.abs(dragCurIdx - dragStartIdx) >= 3) {
- activeRunZoom = '';
- zoomStart = Math.min(dragStartIdx, dragCurIdx);
- zoomEnd = Math.max(dragStartIdx, dragCurIdx) + 1;
- buildZoomBar();
- }
- dragStartIdx = null; dragCurIdx = null; drawCharts();
- };
- canvas.ondblclick = () => applyRunZoom('ALL');
- canvas.onmousemove = ev => {
- hoverIdx = idxFromEvent(ev); if (dragStartIdx !== null) dragCurIdx = hoverIdx; drawCharts();
- const i = hoverIdx, rk = ser.run_names[cols.rk[i]], ph = ser.phase_names[cols.ph[i]];
- const dStr = (k, d=2) => {
- const v = cols[k]?.[i], p = i > 0 ? cols[k]?.[i - 1] : null;
- if (v == null) return 'null';
- if (p != null && Math.abs(v - p) >= (k.includes('Temp') ? 0.5 : (k.startsWith('P12V') ? 0.02 : 3.0))) {
- const df = +(v - p).toFixed(d);
- return `${v}(${df > 0 ? '+' : ''}${df})`;
- }
- return String(v);
- };
- tip.style.display = 'block';
- tip.style.left = Math.min(window.innerWidth - 530, ev.clientX + 14) + 'px';
- tip.style.top = Math.min(window.innerHeight - 280, ev.clientY + 14) + 'px';
- tip.innerHTML = `
- <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>
- <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>
- <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>
- <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>
- <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>
- <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>
- `;
- };
- canvas.onmouseleave = () => { hoverIdx = null; dragStartIdx = null; dragCurIdx = null; tip.style.display = 'none'; drawCharts(); };
- }
- function drawCharts() {
- drawLineChart('chart-temp', tempSeries, enabledTemp, { decimals: 1, showPhaseLabels: true });
- drawLineChart('chart-mpwr', memPwrSeries, enabledMemPwr, { decimals: 1, showPhaseLabels: false });
- drawLineChart('chart-spwr', sysPwrSeries, enabledSysPwr, { decimals: 0, showPhaseLabels: false });
- const em = elecModeConfigs[elecMode];
- drawLineChart('chart-elec', em.series, enabledElec, { decimals: em.decimals, showPhaseLabels: false });
- }
- function drawBars() {
- const canvas = document.getElementById('chart-bars'); if (!canvas) return;
- const { ctx, w, h } = setupCanvas(canvas);
- const metric = document.getElementById('bar-metric-select').value;
- const runList = Object.values(DATA.runs).filter(r => r.active_rows > 0);
- const dKeys = DATA.meta.dimm_keys, colors = ['#ef4444', '#f59e0b', '#22c55e', '#38bdf8', '#a855f7'];
- const pad = { l: 50, r: 18, t: 28, b: 56 }, pw = w - pad.l - pad.r, ph = h - pad.t - pad.b;
- const cs = getComputedStyle(document.body), borderCol = cs.getPropertyValue('--border').trim(), mutedCol = cs.getPropertyValue('--muted').trim();
- let maxV = 1, legLabels = [];
- const bars = runList.map(r => {
- let vals = [];
- if (metric === 'dimm_delta') {
- legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
- 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)));
- } else if (metric === 'dimm_max') {
- legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
- vals = dKeys.map(k => r.per_dimm_thermal_response[k]?.active_max_c ?? 0);
- } else if (metric === 'dimm_rate') {
- legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
- vals = dKeys.map(k => Math.max(0, r.per_dimm_thermal_response[k]?.heating_rate_c_per_min ?? 0));
- } else if (metric === 'dimm_early') {
- legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
- vals = dKeys.map(k => Math.max(0, r.per_dimm_thermal_response[k]?.early_slope_c_per_min ?? 0));
- } else if (metric === 'tau_cool') {
- legLabels = dKeys.map(k => k.replace('DIMM_','').replace('_Temp',''));
- vals = dKeys.map(k => r.per_dimm_thermal_response[k]?.tau_cool_s ?? 0);
- } else if (metric === 'ddr_max') {
- legLabels = ['DDR0(W)', 'DDR2(W)', 'PVCCD0(W)', 'PVCCD1(W)'];
- vals = ['DDR0_Power', 'DDR2_Power', 'PVCCD_CPU0_Input_Power', 'PVCCD_CPU1_Input_Power'].map(k => (r.active_sensors[k] || {}).max ?? 0);
- } else {
- legLabels = ['PSU0_PIn(W)', 'CPU0(W)', 'CPU1(W)'];
- vals = ['PSU0_PIn', 'CPU0_Power_Avg', 'CPU1_Power_Avg'].map(k => (r.active_sensors[k] || {}).max ?? 0);
- }
- maxV = Math.max(maxV, ...vals);
- return { label: r.short_name || r.run_key, run: r, vals };
- });
- maxV = Math.ceil(maxV * 1.15);
- ctx.strokeStyle = borderCol; ctx.font = '11px sans-serif'; ctx.fillStyle = mutedCol;
- 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((maxV * g / 4).toFixed(1), pad.l - 6, yy + 4);
- }
- const slotW = pw / Math.max(1, bars.length); barCache = [];
- bars.forEach((b, idx) => {
- const k = b.vals.length, bw = Math.max(4, Math.min(18, (slotW * 0.78) / k));
- const sx = pad.l + idx * slotW + (slotW - bw * k) / 2;
- b.vals.forEach((v, j) => {
- const hh = (v / maxV) * ph; ctx.fillStyle = colors[j % colors.length];
- ctx.fillRect(sx + j * bw, pad.t + ph - hh, Math.max(2, bw - 1), hh);
- });
- ctx.fillStyle = mutedCol; ctx.textAlign = 'center';
- ctx.fillText(b.label, pad.l + idx * slotW + slotW / 2, pad.t + ph + 16);
- barCache.push({ x1: pad.l + idx * slotW, x2: pad.l + (idx + 1) * slotW, run: b.run, vals: b.vals, legLabels });
- });
- ctx.textAlign = 'left'; let lx = pad.l;
- legLabels.forEach((lbl, j) => {
- ctx.fillStyle = colors[j % colors.length]; ctx.fillRect(lx, 6, 10, 10);
- ctx.fillStyle = mutedCol; ctx.fillText(lbl, lx + 14, 15); lx += 14 + lbl.length * 7 + 16;
- });
- const tip = document.getElementById('tooltip');
- canvas.onmousemove = ev => {
- const rect = canvas.getBoundingClientRect(), x = ev.clientX - rect.left;
- const hit = barCache.find(b => x >= b.x1 && x <= b.x2);
- if (!hit) { tip.style.display = 'none'; return; }
- tip.style.display = 'block';
- tip.style.left = Math.min(window.innerWidth - 420, ev.clientX + 14) + 'px';
- tip.style.top = Math.min(window.innerHeight - 220, ev.clientY + 14) + 'px';
- tip.innerHTML = `<div><b>${esc(hit.run.run_key)}</b> (${esc(hit.run.algo_name)})</div>` +
- hit.legLabels.map((lbl, j) => `<div>${esc(lbl)}: <b>${hit.vals[j].toFixed(2)}</b></div>`).join('');
- };
- canvas.onmouseleave = () => { tip.style.display = 'none'; };
- }
- function renderTables() {
- const dKeys = DATA.meta.dimm_keys;
- const runList = Object.values(DATA.runs).filter(r => r.active_rows > 0);
- 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>`;
- runList.forEach(r => {
- 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>` +
- dKeys.map(k => {
- const d = r.per_dimm_thermal_response[k];
- if (!d || d.active_max_c == null) return '<td>-</td>';
- const base = d.baseline_end_c ?? d.active_start_c;
- const es = d.early_slope_c_per_min != null ? ` / 初${d.early_slope_c_per_min}` : '';
- 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>`;
- }).join('') +
- `<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>`;
- });
- document.getElementById('algo-dimm-table').innerHTML = h1 + '</tbody></table>';
- 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>`;
- runList.forEach(r => {
- const a = r.active_sensors;
- h2 += `<tr><td><b>${esc(r.run_key)}</b></td>
- <td class="mono">${esc(fmtMM(a.DDR0_Power,'W'))}</td>
- <td class="mono">${esc(fmtMM(a.DDR2_Power,'W'))}</td>
- <td class="mono">${esc(fmtMM(a.DDR0_Curr,'A'))} / ${esc(fmtMM(a.DDR2_Curr,'A'))}</td>
- <td class="mono">${esc(fmtMM(a.P12V_DDR0,'V'))} / ${esc(fmtMM(a.P12V_DDR2,'V'))}</td>
- <td class="mono">${esc(fmtMM(a.PVCCD_CPU0_Input_Power,'W'))} / ${esc(fmtMM(a.PVCCD_CPU1_Input_Power,'W'))}</td>
- <td class="mono">${esc(fmtMM(a.Dimm_Power_CPU0,'W'))} / ${esc(fmtMM(a.Dimm_Power_CPU1,'W'))}</td>
- <td class="mono">${esc(fmtMM(a.CPU0_Power_Avg,'W'))} / ${esc(fmtMM(a.CPU1_Power_Avg,'W'))}</td>
- <td class="mono">${esc(fmtMM(a.CPU0_Temp,'°C'))} / ${esc(fmtMM(a.CPU1_Temp,'°C'))}</td>
- <td class="mono">${esc(fmtMM(a.PSU0_PIn,'W'))} / ${esc(fmtMM(a.PSU0_POut,'W'))}</td></tr>`;
- });
- document.getElementById('algo-pwr-table').innerHTML = h2 + '</tbody></table>';
- 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>`;
- runList.forEach(r => {
- const d0 = r.per_dimm_thermal_response[dKeys[0]] || {};
- const delayTxt = (d0.cooldown_first_valid_delay_s != null && d0.cooldown_first_valid_delay_s > 0) ? `+${d0.cooldown_first_valid_delay_s}s` : '0s';
- 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>` +
- dKeys.map(k => {
- const d = r.per_dimm_thermal_response[k];
- if (!d || d.cooldown_start_c == null) return '<td>-</td>';
- const delta = +(d.cooldown_end_c - d.cooldown_start_c).toFixed(2);
- const sign = delta > 0 ? '+' : '';
- const pkDrop = d.cooldown_total_drop_from_peak_c != null ? ` · 较峰-${d.cooldown_total_drop_from_peak_c}` : '';
- const tau = d.tau_cool_s != null ? ` · τ=${d.tau_cool_s}s` : '';
- 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>`;
- }).join('') + `</tr>`;
- });
- document.getElementById('algo-cool-table').innerHTML = h3 + '</tbody></table>';
- // Gallery of embedded publication PNGs
- const gal = document.getElementById('fig-gallery');
- const figNote = document.getElementById('fig-count-note');
- if (!FIGS.length) {
- figNote.textContent = '当前输入目录未包含 fig_01..fig_09.png 静态曲线截图。';
- gal.innerHTML = '<div class="sub-note">请使用 Tab 1 交互曲线或传入原始 scratch/thermal_study 目录生成内嵌图集。</div>';
- } else {
- figNote.textContent = `已离线 Base64 内嵌 ${FIGS.length} 张高清曲线截图`;
- gal.innerHTML = FIGS.map((fg, idx) => `
- <div class="fig-card">
- <div class="fig-hdr">
- <span>${esc(fg.title)}</span>
- <span class="controls">
- <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>
- <button type="button" class="btn-xs" onclick="window.__openFig(${idx})">放大</button>
- </span>
- </div>
- <img src="${fg.data_uri}" alt="${esc(fg.title)}" onclick="window.__openFig(${idx})">
- </div>
- `).join('');
- }
- // Tab 3 filters
- const pSel = document.getElementById('phase-run-filter');
- Object.keys(DATA.runs).forEach(rk => {
- const o = document.createElement('option'); o.value = rk; o.textContent = rk; pSel.appendChild(o);
- });
- pSel.onchange = renderPhaseRows;
- document.getElementById('phase-grp-filter').onchange = renderPhaseRows;
- document.getElementById('phase-col-preset').onchange = renderPhaseRows;
- renderPhaseRows();
- renderLoopEvents();
- // Tab 4 micro-events & raw filter init
- initRawExplorer();
- // Tab 5 overall sensors + benchmark + conclusions
- 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>`;
- DATA.meta.sensors.forEach(s => {
- const st = DATA.overall_sensors[s.key]; if (!st) return;
- const u = s.unit;
- const nulls = n - st.count;
- ho += `<tr><td class="mono"><b>${esc(s.key)}</b></td><td>${esc(s.label)}</td><td class="mono">${esc(s.group)}</td>` +
- `<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>` +
- `<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>`;
- });
- document.getElementById('overall-sensors-table').innerHTML = ho + '</tbody></table>';
- const bm = DATA.bmc_benchmark;
- const bb = document.getElementById('bench-body');
- if (!bm) {
- bb.innerHTML = '<p class="sub-note">未在输入目录发现 bmc_benchmark_result.json。</p>';
- } else {
- const ipmiT = bm.ipmi_sdr_temp_latency_ms || {}, ipmiC = bm.ipmi_sdr_compact_latency_ms || {};
- const lat = DATA.meta.poll_latency_ms || {};
- bb.innerHTML = `
- <div class="table-scroll" style="margin-bottom:12px"><table><thead><tr><th>采集方式</th><th>最小耗时</th><th>中位/典型耗时</th><th>最大耗时</th><th>发现/精度特征</th></tr></thead><tbody>
- <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>
- <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>
- <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>
- </tbody></table></div>
- <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>
- <details style="margin-top:8px"><summary style="cursor:pointer;font-size:13px">展开查看 IPMI SDR 原始快照与 D-Bus 传感器样本路径</summary>
- <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>
- </details>
- `;
- }
- const mt = DATA.runs['01_MT_BlockMove64B'];
- const cbox = document.getElementById('conclusions-box');
- const ov = DATA.overall_sensors;
- cbox.innerHTML = `
- <ul>
- <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>
- <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>
- <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>
- <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>
- </ul>
- `;
- }
- window.__openFig = idx => {
- const fg = FIGS[idx]; if (!fg) return;
- document.getElementById('modal-title').textContent = fg.title;
- document.getElementById('modal-img').src = fg.data_uri;
- const dl = document.getElementById('modal-dl');
- dl.href = fg.data_uri; dl.download = fg.filename;
- document.getElementById('fig-modal').classList.add('open');
- };
- document.getElementById('modal-close').onclick = () => document.getElementById('fig-modal').classList.remove('open');
- document.getElementById('fig-modal').onclick = ev => { if (ev.target.id === 'fig-modal') document.getElementById('fig-modal').classList.remove('open'); };
- window.addEventListener('keydown', ev => { if (ev.key === 'Escape') document.getElementById('fig-modal').classList.remove('open'); });
- function renderPhaseRows() {
- const fRun = document.getElementById('phase-run-filter').value;
- const fGrp = document.getElementById('phase-grp-filter').value;
- const preset = document.getElementById('phase-col-preset').value;
- const allSlices = [];
- Object.entries(DATA.runs).forEach(([rk, r]) => {
- (r.phases || []).forEach(p => allSlices.push({ rk, p }));
- });
- allSlices.sort((a, b) => a.p.seq_start - b.p.seq_start);
- const sensorList = DATA.meta.sensors.filter(s => {
- if (preset === 'all') return true;
- if (preset === 'dimm') return s.group === 'dimm_temp' || s.group === 'cpu_temp';
- if (preset === 'pwr') return s.group === 'power' || s.group === 'electrical';
- 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);
- });
- 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>` +
- sensorList.map(s => `<th>${esc(s.key.replace('DIMM_','').replace('_Input_Power',''))} (${esc(s.unit)})</th>`).join('') +
- `</tr></thead><tbody>`;
- allSlices.forEach(({ rk, p }) => {
- if (fRun && rk !== fRun) return;
- if (fGrp && p.phase_group !== fGrp) return;
- const s = p.sensors || {};
- h += `<tr>
- <td class="mono">#${p.seq_start}..${p.seq_end} (${p.rows}s)</td>
- <td class="mono">${esc(rk)}</td>
- <td class="mono"><b>${esc(p.phase)}</b><br><span style="color:var(--muted)">${esc(p.phase_group)}</span></td>
- <td class="mono">${esc((p.start_time||'').slice(11,19))}→${esc((p.end_time||'').slice(11,19))}</td>
- <td class="mono">${p.spd_valid_rows} / <span class="${p.spd_null_rows?'anom-warn':''}">${p.spd_null_rows}</span></td>
- <td class="mono">${p.peci_valid_rows} / ${p.peci_null_rows}</td>
- <td class="mono">
- <button type="button" class="btn-xs" onclick="window.zoomToSeqRange(${p.seq_start},${p.seq_end},'all',${p.seq_start},12)">曲线</button>
- <button type="button" class="btn-xs" onclick="window.jumpToRawRange('${esc(rk)}','',${p.seq_start},${p.seq_end},'all')">明细</button>
- </td>` +
- sensorList.map(sn => {
- const st = s[sn.key];
- if (!st) return `<td class="null-cell">null</td>`;
- return `<td class="mono">${st.start}→${st.end}<br><span style="color:var(--muted)">${st.min}~${st.max}</span></td>`;
- }).join('') + `</tr>`;
- });
- document.getElementById('phases-detail-table').innerHTML = h + '</tbody></table>';
- }
- function renderLoopEvents() {
- const rows = [];
- Object.entries(DATA.runs).forEach(([rk, r]) => {
- (r.loop_events || []).forEach(le => rows.push({ rk, le }));
- });
- const el = document.getElementById('loop-events-table');
- if (!rows.length) {
- el.innerHTML = '<div class="sub-note">无 loop_events 固件事件记录。</div>';
- return;
- }
- 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>`;
- rows.forEach(({ rk, le }) => {
- const sq = le.seq;
- h += `<tr>
- <td class="mono"><b>${esc(rk)}</b></td>
- <td class="mono">${esc(le.event)}</td>
- <td class="mono">L${le.loop ?? '-'}</td>
- <td class="mono">${le.socket == null ? '-' : 'CPU' + le.socket}</td>
- <td class="mono">${le.fw_sec == null ? '-' : le.fw_sec + ' s'}</td>
- <td class="mono">${sq != null ? '#' + sq : '-'}</td>
- <td class="mono">${esc((le.iso_time || '').slice(11,19))} (${le.t_s ?? '-'}s)</td>
- <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>
- </tr>`;
- });
- el.innerHTML = h + '</tbody></table>';
- }
- function initRawExplorer() {
- const meCatSel = document.getElementById('me-cat-filter');
- const cats = Array.from(new Set(microEvents.map(e => e.category)));
- cats.forEach(c => {
- const o = document.createElement('option'); o.value = c; o.textContent = c; meCatSel.appendChild(o);
- });
- const renderMeCards = () => {
- const cat = meCatSel.value;
- const list = cat ? microEvents.filter(e => e.category === cat) : microEvents;
- document.getElementById('me-count').textContent = cat ? `${list.length} / ${microEvents.length}` : String(microEvents.length);
- document.getElementById('me-cards').innerHTML = list.map(ev => `
- <div class="me-card">
- <div>
- <div class="me-card-top">
- <span><span class="badge ${esc(ev.severity)}">${esc(ev.id)} · ${esc(ev.category)}</span></span>
- <span class="mono">#${ev.seq_start}..#${ev.seq_end} (${ev.rows}s)</span>
- </div>
- <div class="me-title" style="margin-top:5px">${esc(ev.title)}</div>
- <div class="me-detail" style="margin-top:4px">${esc(ev.detail)}</div>
- </div>
- <div class="controls">
- <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>
- <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>
- </div>
- </div>
- `).join('');
- };
- meCatSel.onchange = renderMeCards;
- renderMeCards();
- const rSel = document.getElementById('raw-run');
- ser.run_names.forEach(rk => {
- const o = document.createElement('option'); o.value = rk; o.textContent = rk; rSel.appendChild(o);
- });
- const pSel = document.getElementById('raw-phase');
- ser.phase_names.forEach(ph => {
- const o = document.createElement('option'); o.value = ph; o.textContent = ph; pSel.appendChild(o);
- });
- const cSel = document.getElementById('raw-cust-col');
- DATA.meta.sensors.forEach(s => {
- const o = document.createElement('option'); o.value = s.key; o.textContent = `${s.key} (${s.unit})`; cSel.appendChild(o);
- });
- const oLat = document.createElement('option'); oLat.value = 'lat'; oLat.textContent = 'poll_latency_ms (ms)'; cSel.appendChild(oLat);
- ['raw-run', 'raw-phase', 'raw-preset', 'raw-cust-col', 'raw-cust-op', 'raw-col-group'].forEach(id => {
- document.getElementById(id).onchange = () => { rawPage = 1; applyRawFilter(); };
- });
- ['raw-seq-min', 'raw-seq-max', 'raw-cust-val'].forEach(id => {
- document.getElementById(id).oninput = () => { rawPage = 1; applyRawFilter(); };
- });
- document.getElementById('raw-page-size').onchange = () => { rawPage = 1; renderRawTable(); };
- document.getElementById('raw-prev').onclick = () => { if (rawPage > 1) { rawPage--; renderRawTable(); } };
- document.getElementById('raw-next').onclick = () => {
- const ps = parseInt(document.getElementById('raw-page-size').value, 10) || 100;
- const totP = Math.max(1, Math.ceil(rawFiltered.length / ps));
- if (rawPage < totP) { rawPage++; renderRawTable(); }
- };
- document.getElementById('btn-raw-reset').onclick = () => window.jumpToRawRange('', '', '', '', 'all');
- document.getElementById('btn-raw-export').onclick = () => exportCsvForIndices(rawFiltered, 'filtered_1hz_telemetry.csv');
- applyRawFilter();
- }
- function applyRawFilter() {
- const fRun = document.getElementById('raw-run').value;
- const fPh = document.getElementById('raw-phase').value;
- const fPre = document.getElementById('raw-preset').value;
- const sMin = parseInt(document.getElementById('raw-seq-min').value, 10);
- const sMax = parseInt(document.getElementById('raw-seq-max').value, 10);
- const cCol = document.getElementById('raw-cust-col').value;
- const cOp = document.getElementById('raw-cust-op').value;
- const cVal = parseFloat(document.getElementById('raw-cust-val').value);
- const dKeys = DATA.meta.dimm_keys;
- rawFiltered = [];
- for (let i = 0; i < n; i++) {
- const sq = cols.seq[i];
- if (!isNaN(sMin) && sq < sMin) continue;
- if (!isNaN(sMax) && sq > sMax) continue;
- const rk = ser.run_names[cols.rk[i]];
- if (fRun && rk !== fRun) continue;
- const ph = ser.phase_names[cols.ph[i]];
- if (fPh && ph !== fPh) continue;
- if (fPre === 'spd_null') {
- if (!dKeys.some(k => cols[k]?.[i] == null)) continue;
- } else if (fPre === 'peci_null') {
- if (cols.Dimm_Power_CPU0?.[i] != null) continue;
- } else if (fPre === 'cool_spike') {
- if (!(ph === 'cooldown' && (cols.DDR0_Power?.[i] ?? 0) >= 20)) continue;
- } else if (fPre === 'p12v_droop') {
- if ((cols.P12V_DDR0?.[i] ?? 99) > 12.13) continue;
- } else if (fPre === 'high_lat') {
- if ((cols.lat[i] ?? 0) < 300) continue;
- } else if (fPre === 'temp_jump') {
- if (i === 0) continue;
- const jumped = dKeys.some(k => {
- const a = cols[k]?.[i], b = cols[k]?.[i - 1];
- return a != null && b != null && Math.abs(a - b) >= 0.75;
- });
- if (!jumped) continue;
- } else if (fPre === 'pwr_jump') {
- if (i === 0) continue;
- const a = cols.DDR0_Power?.[i], b = cols.DDR0_Power?.[i - 1];
- if (a == null || b == null || Math.abs(a - b) < 5.0) continue;
- }
- if (cCol && cols[cCol]) {
- const cv = cols[cCol][i];
- if (cOp === 'isnull') { if (cv != null) continue; }
- else if (cOp === 'notnull') { if (cv == null) continue; }
- else if (!isNaN(cVal)) {
- if (cv == null) continue;
- if (cOp === 'gt' && !(cv > cVal)) continue;
- if (cOp === 'ge' && !(cv >= cVal)) continue;
- if (cOp === 'lt' && !(cv < cVal)) continue;
- if (cOp === 'le' && !(cv <= cVal)) continue;
- }
- }
- rawFiltered.push(i);
- }
- renderRawTable();
- }
- function renderRawTable() {
- const cg = document.getElementById('raw-col-group').value;
- const ps = parseInt(document.getElementById('raw-page-size').value, 10) || 100;
- const tot = rawFiltered.length;
- const totPages = Math.max(1, Math.ceil(tot / ps));
- rawPage = Math.max(1, Math.min(rawPage, totPages));
- document.getElementById('raw-count-info').textContent = `匹配 ${tot.toLocaleString()} / ${n.toLocaleString()} 行`;
- document.getElementById('raw-page-info').textContent = `第 ${rawPage} / ${totPages} 页`;
- const selSensors = DATA.meta.sensors.filter(s => {
- if (cg === 'all') return true;
- if (cg === 'temps') return s.group === 'dimm_temp' || s.group === 'cpu_temp';
- if (cg === 'elec') return s.group === 'power' || s.group === 'electrical';
- 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);
- });
- const start = (rawPage - 1) * ps, end = Math.min(tot, start + ps);
- 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>`];
- selSensors.forEach(s => parts.push(`<th>${esc(s.key.replace('DIMM_','').replace('_Input_Power',''))}(${esc(s.unit)})</th>`));
- parts.push('</tr></thead><tbody>');
- for (let k = start; k < end; k++) {
- const i = rawFiltered[k];
- const rk = ser.run_names[cols.rk[i]], ph = ser.phase_names[cols.ph[i]];
- const lat = cols.lat[i];
- const latHtml = lat == null ? '<span class="null-cell">-</span>' : (lat >= 500 ? `<span class="anom-warn">${lat}</span>` : String(lat));
- 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>` +
- `<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>` +
- `<td class="mono">${cols.loop[i] || '-'}</td><td class="mono">${latHtml}</td>`);
- for (const s of selSensors) {
- const v = cols[s.key]?.[i];
- if (v == null) {
- parts.push(`<td class="null-cell">null</td>`);
- continue;
- }
- const pv = i > 0 ? cols[s.key]?.[i - 1] : null;
- let cls = '', tip = '';
- if (pv != null) {
- const d = +(v - pv).toFixed(3);
- if (d !== 0) tip = ` title="较上秒 Δ=${d > 0 ? '+' : ''}${d}"`;
- }
- if (s.key === 'DDR0_Power' && ph === 'cooldown' && v >= 20) cls = ' class="anom-warn"';
- else if (s.key === 'P12V_DDR0' && v <= 12.13) cls = ' class="anom-droop"';
- else if (s.group === 'dimm_temp' && pv != null && (v - pv) >= 0.75) cls = ' class="anom-warm"';
- parts.push(`<td class="mono"${tip}><span${cls}>${v}</span></td>`);
- }
- parts.push('</tr>');
- }
- parts.push('</tbody></table>');
- document.getElementById('raw-table-wrap').innerHTML = parts.join('');
- }
- function drawAll() { drawCharts(); drawBars(); }
- document.getElementById('bar-metric-select').onchange = drawBars;
- attachHover('chart-temp');
- attachHover('chart-mpwr');
- attachHover('chart-spwr');
- attachHover('chart-elec');
- window.addEventListener('resize', drawAll);
- renderKpis(); buildZoomBar(); buildLegends(); drawAll(); renderTables();
- })();
- </script>"""
- tail = script_js + "\n</body>\n</html>\n"
- return (
- head_html
- + '<script id="embedded-data" type="application/json">' + payload_json + "</script>\n"
- + '<script id="embedded-figures" type="application/json">' + figs_json + "</script>\n"
- + tail
- )
- def export_campaign_clean_csv(parsed: dict[str, Any], artifacts: dict[str, Any], export_dir: Path) -> list[Path]:
- export_dir.mkdir(parents=True, exist_ok=True)
- sensors = artifacts["sensors"]
- headers = [
- "seq", "unix_ts", "iso_time", "campaign_elapsed_s", "run_elapsed_s", "poll_latency_ms",
- "run_key", "algo_name", "short_name", "engine", "phase", "loop_index", "loop_total",
- ] + [s["key"] for s in sensors]
- out_path = export_dir / "thermal_campaign_per_sensor_clean.csv"
- with out_path.open("w", encoding="utf-8-sig", newline="") as fp:
- w = csv.writer(fp, lineterminator="\r\n")
- w.writerow(headers)
- for r in artifacts["rows"]:
- row = [
- r["seq"], r["unix_ts"], r["iso_time"], r["campaign_elapsed_s"], r["run_elapsed_s"], r["poll_latency_ms"],
- r["run_key"], r["algo_name"], r["short_name"], r["engine"], r["phase"], r["loop_index"], r["loop_total"],
- ]
- for s in sensors:
- v = r.get(s["key"])
- row.append("" if v is None else v)
- w.writerow(row)
- return [out_path]
- def _parse_kv_temp_map(text: str) -> dict[str, float]:
- out: dict[str, float] = {}
- for tok in (text or "").strip().split():
- if "=" in tok:
- k, v = tok.split("=", 1)
- fv = _to_float(v)
- if fv is not None:
- out[k.strip()] = fv
- return out
- def parse_thermal_endurance(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
- p = Path(input_path).resolve()
- if p.is_dir():
- cands = sorted(p.glob("thermal_*_Endurance.csv")) or sorted(p.glob("thermal_*.csv"))
- if not cands:
- raise FileNotFoundError(f"No thermal endurance CSV found in {p}")
- csv_path = cands[0]
- base_dir = p
- else:
- csv_path = p
- base_dir = p.parent
- milestone_cands = sorted(base_dir.glob("mt_milestones_*.csv"))
- milestone_path = milestone_cands[0] if milestone_cands else None
- event_cands = sorted(base_dir.glob("*.events.jsonl"))
- event_path = event_cands[0] if event_cands else None
- with csv_path.open("r", encoding="utf-8-sig", newline="") as fp:
- reader = csv.DictReader(fp)
- fieldnames = list(reader.fieldnames or [])
- raw_rows = list(reader)
- if not raw_rows:
- raise ValueError(f"Empty endurance CSV: {csv_path}")
- # Discover active individual sensor columns (skipping *_avg_c / *_min_c / *_max_c / *_spread_c)
- 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)]
- 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)]
- ipmi_candidates = [c for c in fieldnames if c.startswith("IPMI_CPU")]
- active_ipmi = [c for c in ipmi_candidates if any(r[c].strip() for r in raw_rows)]
- 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]
- all_sensor_cols = active_mcu + active_ct + active_ipmi + extra_cols
- rows: list[dict[str, Any]] = []
- for idx, r in enumerate(raw_rows, start=1):
- rec: dict[str, Any] = {
- "seq": idx,
- "timestamp_utc8": (r.get("timestamp_utc8") or "").strip(),
- "unix_ms": _to_int(r.get("unix_ms")),
- "elapsed_s": _to_float(r.get("elapsed_s")),
- "station_id": (r.get("station_id") or "").strip(),
- "station_phase": (r.get("station_phase") or "").strip(),
- "mcu_mode": (r.get("mcu_mode") or "").strip(),
- "mcu_target_c": _to_float(r.get("mcu_target_c")),
- "mcu_flags_hex": (r.get("mcu_flags_hex") or "").strip(),
- "stage_error_total": _to_int(r.get("stage_error_total")) or 0,
- "diag_err_cnt": _to_int(r.get("diag_err_cnt")) or 0,
- }
- for c in all_sensor_cols:
- rec[c] = _to_float(r.get(c))
- rows.append(rec)
- # Parse MT milestones if present
- milestones: list[dict[str, Any]] = []
- test_windows: list[dict[str, Any]] = []
- if milestone_path and milestone_path.is_file():
- with milestone_path.open("r", encoding="utf-8-sig", newline="") as fp:
- mrows = list(csv.DictReader(fp))
- open_tests: dict[tuple[str, str], dict[str, Any]] = {}
- for mr in mrows:
- ev_t = (mr.get("event_type") or "").strip()
- pnum = (mr.get("pass_num") or "").strip()
- tnum = (mr.get("test_num") or "").strip()
- tdesc = (mr.get("test_desc") or "").strip()
- ts_str = (mr.get("timestamp_utc8") or "").strip()
- mt_temps = _parse_kv_temp_map(mr.get("mt_dimm_temps_c") or "")
- mcu_temps = _parse_kv_temp_map(mr.get("mcu_dimm_temps_c") or "")
- ct8_temps = _parse_kv_temp_map(mr.get("ct8_temps_c") or "")
- ipmi_temps = _parse_kv_temp_map(mr.get("ipmi_dimm_temps_c") or "")
- mitem = {
- "timestamp_utc8": ts_str,
- "event_type": ev_t,
- "pass_num": _to_int(pnum),
- "test_num": _to_int(tnum),
- "test_desc": tdesc,
- "test_duration_s": _to_float(mr.get("test_duration_s")),
- "cum_errors": _to_int(mr.get("cum_errors")),
- "mt_cpu_temp_c": _to_float(mr.get("mt_cpu_temp_c")),
- "mcu_mode": (mr.get("mcu_mode") or "").strip(),
- "mt_dimm_temps": mt_temps,
- "mcu_dimm_temps": mcu_temps,
- "ct8_temps": ct8_temps,
- "ipmi_dimm_temps": ipmi_temps,
- }
- milestones.append(mitem)
- if ev_t == "test_start":
- open_tests[(pnum, tnum)] = {
- "pass_num": _to_int(pnum),
- "test_num": _to_int(tnum),
- "test_desc": tdesc,
- "start_ts": ts_str,
- "end_ts": None,
- "duration_s": None,
- "cum_errors": 0,
- "start_mt_dimm": mt_temps,
- "end_mt_dimm": {},
- "snapshots": [],
- }
- elif ev_t == "minute_snapshot" and (pnum, tnum) in open_tests:
- open_tests[(pnum, tnum)]["snapshots"].append(mitem)
- elif ev_t == "test_done":
- tw = open_tests.pop((pnum, tnum), {
- "pass_num": _to_int(pnum),
- "test_num": _to_int(tnum),
- "test_desc": tdesc,
- "start_ts": ts_str,
- "start_mt_dimm": mt_temps,
- "snapshots": [],
- })
- tw["end_ts"] = ts_str
- tw["duration_s"] = _to_float(mr.get("test_duration_s"))
- tw["cum_errors"] = _to_int(mr.get("cum_errors")) or 0
- tw["end_mt_dimm"] = mt_temps
- test_windows.append(tw)
- for rem in open_tests.values():
- rem["end_ts"] = rows[-1]["timestamp_utc8"]
- test_windows.append(rem)
- test_windows.sort(key=lambda w: (w["pass_num"] or 0, w["test_num"] or 0, w["start_ts"]))
- def _stats_block(sub_rows: list[dict[str, Any]]) -> dict[str, Any]:
- 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}
- # Correlate test windows to endurance CSV rows by timestamp_utc8
- # Note: Test 0/1 in milestones had bursty UART reads with identical start/end timestamps, while later tests span actual minutes.
- for tw in test_windows:
- s_ts, e_ts = tw["start_ts"], tw["end_ts"] or rows[-1]["timestamp_utc8"]
- win_rows = [r for r in rows if s_ts <= r["timestamp_utc8"] <= e_ts]
- if not win_rows and tw.get("snapshots"):
- sn_ts = [s["timestamp_utc8"] for s in tw["snapshots"]]
- win_rows = [r for r in rows if min(sn_ts) <= r["timestamp_utc8"] <= max(sn_ts)]
- tw["csv_rows"] = len(win_rows)
- tw["sensors"] = _stats_block(win_rows) if win_rows else {}
- # Compute MT DIMM0..4 min/max across start, snapshots, end
- mt_all: dict[str, list[float]] = {}
- 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 {}]:
- for dk, dv in dmap.items():
- mt_all.setdefault(dk, []).append(dv)
- tw["mt_dimm_stats"] = {dk: _sensor_stats(vs, 2) for dk, vs in sorted(mt_all.items())}
- tw.pop("snapshots", None)
- # MCU mode breakdown (idle, preheating, pid, offline)
- mode_slices: dict[str, Any] = {}
- cur_m = None
- cur_buf: list[dict[str, Any]] = []
- mode_transitions: list[dict[str, Any]] = []
- for r in rows:
- if cur_m is None or r["mcu_mode"] != cur_m:
- if cur_buf:
- mode_transitions.append({
- "mode": cur_m,
- "rows": len(cur_buf),
- "start_ts": cur_buf[0]["timestamp_utc8"],
- "end_ts": cur_buf[-1]["timestamp_utc8"],
- "sensors": _stats_block(cur_buf),
- })
- cur_m = r["mcu_mode"]
- cur_buf = [r]
- else:
- cur_buf.append(r)
- if cur_buf:
- mode_transitions.append({
- "mode": cur_m,
- "rows": len(cur_buf),
- "start_ts": cur_buf[0]["timestamp_utc8"],
- "end_ts": cur_buf[-1]["timestamp_utc8"],
- "sensors": _stats_block(cur_buf),
- })
- events_summary: dict[str, Any] = {"event_count": 0, "kind_counts": {}, "notable": []}
- if event_path and event_path.is_file():
- kc: dict[str, int] = {}
- notable: list[dict[str, Any]] = []
- ev_cnt = 0
- for ln in event_path.read_text(encoding="utf-8", errors="replace").splitlines():
- s = ln.strip()
- if not s:
- continue
- ev = json.loads(s)
- ev_cnt += 1
- k = str(ev.get("kind") or "unknown")
- kc[k] = kc.get(k, 0) + 1
- if k in ("record_start", "cmd_ok", "mcu_offline", "error", "warning") or len(notable) < 40:
- notable.append(ev)
- events_summary = {"event_count": ev_cnt, "kind_counts": kc, "notable": notable[:120]}
- total_s = round(rows[-1]["elapsed_s"] or len(rows), 1)
- parsed = {
- "parser_version": PARSER_VERSION,
- "mode": "thermal_endurance_per_position_no_means",
- "parsed_utc": datetime.now(timezone.utc).isoformat(),
- "input_path": str(p),
- "csv_file": str(csv_path),
- "milestone_file": str(milestone_path) if milestone_path else None,
- "source_kind": "thermal_endurance",
- "station_id": rows[0]["station_id"] or "S1",
- "total_1hz_rows": len(rows),
- "total_duration_s": total_s,
- "total_duration_hms": _fmt_hms(total_s),
- "start_ts": rows[0]["timestamp_utc8"],
- "end_ts": rows[-1]["timestamp_utc8"],
- "active_mcu_channels": active_mcu,
- "active_ct_channels": active_ct,
- "active_ipmi_channels": active_ipmi,
- "extra_cols": extra_cols,
- "overall_sensors": _stats_block(rows),
- "mode_transitions": mode_transitions,
- "test_windows": test_windows,
- "milestones_count": len(milestones),
- "mt_total_errors": max(
- [max(r["stage_error_total"] for r in rows)]
- + [tw["cum_errors"] for tw in test_windows]
- ),
- "events_summary": events_summary,
- }
- # Build compact columnar time-series (keep all 42k rows for lossless zoom, selected active cols)
- mode_names: list[str] = []
- mode_idx: dict[str, int] = {}
- cols: dict[str, list[Any]] = {"seq": [], "t": [], "ts": [], "md": []}
- for c in all_sensor_cols:
- cols[c] = []
- for r in rows:
- md = r["mcu_mode"] or "unknown"
- if md not in mode_idx:
- mode_idx[md] = len(mode_names)
- mode_names.append(md)
- cols["seq"].append(r["seq"])
- cols["t"].append(round(r["elapsed_s"] or 0.0, 1))
- ts = r["timestamp_utc8"]
- cols["ts"].append(ts[11:19] if len(ts) >= 19 else ts)
- cols["md"].append(mode_idx[md])
- for c in all_sensor_cols:
- cols[c].append(_round_opt(r.get(c), 2))
- return parsed, {"rows": rows, "all_sensor_cols": all_sensor_cols, "series": {"mode_names": mode_names, "cols": cols}}
- def render_endurance_markdown_report(parsed: dict[str, Any]) -> str:
- lines: list[str] = []
- lines.append("# 2026-11-14 11.8 小时 70°C 全流程耐久测试逐位置传感器解析报告(无均值)")
- lines.append("")
- lines.append(f"- **输入来源**:`{parsed['csv_file']}` (`{parsed['source_kind']}`)")
- lines.append(f"- **时间范围**:`{parsed['start_ts']}` → `{parsed['end_ts']}` · 共 `{parsed['total_1hz_rows']:,}` 行 (`{parsed['total_duration_hms']}`)")
- lines.append(f"- **独立通道**:MCU `{', '.join(parsed['active_mcu_channels'])}` · CT `{', '.join(parsed['active_ct_channels'])}` · IPMI `{', '.join(parsed['active_ipmi_channels'])}`")
- lines.append(f"- **MT 累计错误**:`{parsed['mt_total_errors']}`")
- lines.extend(["", "## 1. 全部位置传感器全周期实测范围 (`min~max`, `起点→终点`)", ""])
- lines.append("| 通道 | 样本数 | 最小值 | 最大值 | 起点 | 终点 |")
- lines.append("|---|---:|---:|---:|---:|---:|")
- for c, st in parsed["overall_sensors"].items():
- if not st:
- continue
- lines.append(f"| `{c}` | `{st['count']}` | `{st['min']}` | `{st['max']}` | `{st['start']}` | `{st['end']}` |")
- lines.extend(["", "## 2. MCU 运行模式分段统计 (含后段 `offline` 失控温升)", ""])
- lines.append("| MCU 模式 | 样本(s) | 时间区间 | MCU_CH01..04 / 13 | CT01..CT08 | IPMI CPU0_A..D / CPU1_A | PTC / SSR2 / FanF |")
- lines.append("|---|---:|---|---|---|---|---|")
- for mt in parsed["mode_transitions"]:
- s = mt["sensors"]
- mcus = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_mcu_channels"])
- cts = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ct_channels"])
- ipmis = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ipmi_channels"])
- 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)}"
- lines.append(f"| `{mt['mode']}` | `{mt['rows']}` | `{mt['start_ts'][11:19]}→{mt['end_ts'][11:19]}` | {mcus} | {cts} | {ipmis} | {act} |")
- lines.extend(["", "## 3. MemTest86 测试里程碑逐位置温度拆解 (`Test 0..19`)", ""])
- lines.append("| Test | 时长(s) | CSV样本 | MT DIMM0..4 (min~max) | IPMI CPU0_A..D / CPU1_A | CT01..08 | 错误 |")
- lines.append("|---|---:|---:|---|---|---|---:|")
- for tw in parsed["test_windows"]:
- mtd = " / ".join(_fmt_range(st, "", False) for st in tw["mt_dimm_stats"].values()) or "-"
- s = tw["sensors"]
- ipmis = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ipmi_channels"]) if s else "-"
- cts = " / ".join(_fmt_range(s.get(c), "", False) for c in parsed["active_ct_channels"]) if s else "-"
- lines.append(f"| `P{tw['pass_num']} {tw['test_desc']}` | `{tw.get('duration_s') or '-'}` | `{tw['csv_rows']}` | {mtd} | {ipmis} | {cts} | `{tw['cum_errors']}` |")
- return "\n".join(lines) + "\n"
- def render_endurance_html_dashboard(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
- payload = {
- "meta": {
- "parser_version": parsed["parser_version"],
- "station_id": parsed["station_id"],
- "total_1hz_rows": parsed["total_1hz_rows"],
- "total_duration_hms": parsed["total_duration_hms"],
- "start_ts": parsed["start_ts"],
- "end_ts": parsed["end_ts"],
- "active_mcu_channels": parsed["active_mcu_channels"],
- "active_ct_channels": parsed["active_ct_channels"],
- "active_ipmi_channels": parsed["active_ipmi_channels"],
- "extra_cols": parsed["extra_cols"],
- "mt_total_errors": parsed["mt_total_errors"],
- },
- "overall_sensors": parsed["overall_sensors"],
- "mode_transitions": parsed["mode_transitions"],
- "test_windows": parsed["test_windows"],
- "events_summary": parsed["events_summary"],
- "series": artifacts["series"],
- }
- payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
- title = html.escape(f"2026-11-14 11.8h 70°C 耐久测试逐位置解析报告 ({parsed['total_1hz_rows']:,} 行)")
- return f"""<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>{title}</title>
- <style>
- :root {{ --bg:#0b101b; --bg-card:#121a2b; --bg-alt:#182338; --text:#e6edf7; --muted:#93a4be; --border:#253554; --accent:#38bdf8; --good:#22c55e; --warn:#f59e0b; --bad:#ef4444; }}
- body.light {{ --bg:#f1f5f9; --bg-card:#ffffff; --bg-alt:#e8eff8; --text:#0f172a; --muted:#475569; --border:#cbd5e1; --accent:#0284c7; }}
- * {{ box-sizing:border-box; margin:0; padding:0; }}
- 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; }}
- 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; }}
- .hdr-title h1 {{ font-size:18px; font-weight:700; }}
- .hdr-sub {{ font-size:12px; color:var(--muted); margin-top:2px; }}
- .controls {{ display:flex; flex-wrap:wrap; gap:8px; align-items:center; }}
- 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; }}
- button.active {{ background:var(--accent); color:#07101e; border-color:var(--accent); font-weight:600; }}
- .container {{ max-width:1580px; margin:18px auto; padding:0 20px; }}
- .kpi-grid {{ display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; margin-bottom:16px; }}
- .kpi-card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:12px 14px; }}
- .kpi-label {{ font-size:12px; color:var(--muted); }}
- .kpi-val {{ font-size:19px; font-weight:700; margin-top:4px; }}
- .kpi-sub {{ font-size:12px; color:var(--muted); margin-top:2px; }}
- .tabs {{ display:flex; flex-wrap:wrap; gap:8px; margin-bottom:14px; border-bottom:1px solid var(--border); padding-bottom:10px; }}
- .tab-panel {{ display:none; }}
- .tab-panel.active {{ display:block; }}
- .card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:14px 16px; margin-bottom:16px; }}
- .card-hdr {{ display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:10px; margin-bottom:10px; }}
- .legend {{ display:flex; flex-wrap:wrap; gap:8px 12px; font-size:12px; color:var(--muted); margin-bottom:8px; }}
- .legend-item {{ display:inline-flex; align-items:center; gap:5px; cursor:pointer; user-select:none; }}
- .legend-item.off {{ opacity:0.35; text-decoration:line-through; }}
- .swatch {{ width:12px; height:3px; border-radius:2px; display:inline-block; }}
- .chart-wrap {{ position:relative; width:100%; height:310px; }}
- .table-scroll {{ overflow-x:auto; }}
- table {{ width:100%; border-collapse:collapse; font-size:12px; }}
- th, td {{ padding:6px 8px; border-bottom:1px solid var(--border); text-align:left; white-space:nowrap; }}
- th {{ background:var(--bg-alt); color:var(--muted); font-weight:600; position:sticky; top:0; }}
- .mono {{ font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }}
- .badge {{ display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; font-weight:600; }}
- .badge.pass {{ background:rgba(34,197,94,0.16); color:var(--good); }}
- .badge.warn {{ background:rgba(245,158,11,0.16); color:var(--warn); }}
- .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; }}
- </style>
- </head>
- <body>
- <header>
- <div class="hdr-title">
- <h1>2026-11-14 S1 70°C 全流程耐久测试 · 逐腔室与逐位置传感器独立解析报告 (无均值)</h1>
- <div class="hdr-sub" id="hdr-sub">加载中...</div>
- </div>
- <button type="button" id="btn-theme">切换亮/暗主题</button>
- </header>
- <div class="container">
- <div class="kpi-grid" id="kpi-grid"></div>
- <div class="tabs">
- <button type="button" class="tab-btn active" data-tab="tab-w">1Hz 全周期曲线</button>
- <button type="button" class="tab-btn" data-tab="tab-m">MCU 模式分段 & 失联告警</button>
- <button type="button" class="tab-btn" data-tab="tab-t">MT 算法里程碑 (Test 0..19)</button>
- <button type="button" class="tab-btn" data-tab="tab-s">全位置传感器范围</button>
- </div>
- <div id="tab-w" class="tab-panel active">
- <div class="card"><div class="card-hdr"><h3>按模式缩放 (拖拽框选 / 双击复位)</h3><div class="controls" id="zoom-bar"></div></div></div>
- <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>
- <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>
- <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>
- </div>
- <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>
- <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>
- <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>
- </div>
- <div class="tooltip" id="tooltip"></div>
- <script id="embedded-data" type="application/json">{payload_json}</script>
- <script>
- (() => {{
- const DATA = JSON.parse(document.getElementById('embedded-data').textContent);
- const cols = DATA.series.cols, n = cols.seq.length;
- let zoomStart = 0, zoomEnd = n, hoverIdx = null, dragStartIdx = null, dragCurIdx = null;
- const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[c]));
- const fmtMM = st => st ? `${{st.min}}~${{st.max}}` : '-';
- const pal = ['#ef4444','#fca5a5','#f59e0b','#fcd34d','#22c55e','#86efac','#38bdf8','#a855f7','#ec4899','#14b8a6'];
- const ctS = DATA.meta.active_ct_channels.map((c,i) => ({{ key:c, label:c, color:pal[i%pal.length], width:1.4 }}));
- 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 }}));
- 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}}));
- 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));
- 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}}`;
- document.getElementById('btn-theme').onclick = () => {{ document.body.classList.toggle('light'); drawAll(); }};
- document.querySelectorAll('.tab-btn').forEach(b => b.onclick = () => {{
- document.querySelectorAll('.tab-btn,.tab-panel').forEach(x=>x.classList.remove('active'));
- b.classList.add('active'); document.getElementById(b.dataset.tab).classList.add('active'); drawAll();
- }});
- const ov = DATA.overall_sensors;
- document.getElementById('kpi-grid').innerHTML = `
- <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>
- <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>
- <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>
- <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>
- `;
- function buildLeg(id, list, set) {{
- const el = document.getElementById(id); el.innerHTML = '';
- list.forEach(item => {{
- const sp = document.createElement('span');
- sp.className = 'legend-item' + (set.has(item.key)?'':' off');
- sp.innerHTML = `<span class="swatch" style="background:${{item.color}}"></span>${{esc(item.label)}}`;
- sp.onclick = () => {{ if(set.has(item.key)) set.delete(item.key); else set.add(item.key); sp.classList.toggle('off'); drawAll(); }};
- el.appendChild(sp);
- }});
- }}
- function buildZoom() {{
- const bar = document.getElementById('zoom-bar'); bar.innerHTML = '';
- 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); }};
- mk(`全过程 (${{n}}s)`, 0, n);
- DATA.series.mode_names.forEach((m, mi) => {{
- let lo=null, hi=null;
- for(let i=0;i<n;i++) if(cols.md[i]===mi){{if(lo===null)lo=i;hi=i+1;}}
- if(lo!==null) mk(`${{m}} (${{hi-lo}}s)`, lo, hi);
- }});
- }}
- function drawChart(cid, list, set) {{
- const cv = document.getElementById(cid); if(!cv) return;
- const rect=cv.parentElement.getBoundingClientRect(), dpr=window.devicePixelRatio||1;
- const w=Math.max(320,Math.floor(rect.width)), h=Math.max(240,Math.floor(rect.height));
- cv.width=w*dpr; cv.height=h*dpr; const ctx=cv.getContext('2d'); ctx.setTransform(dpr,0,0,dpr,0,0);
- const sIdx=Math.max(0,zoomStart), eIdx=Math.min(n,zoomEnd), span=Math.max(1,eIdx-sIdx);
- const pad={{l:48,r:16,t:12,b:24}}, pw=w-pad.l-pad.r, ph=h-pad.t-pad.b;
- const cs=getComputedStyle(document.body), bCol=cs.getPropertyValue('--border').trim(), mCol=cs.getPropertyValue('--muted').trim();
- let yMin=Infinity, yMax=-Infinity;
- 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;}}}}}});
- if(!isFinite(yMin)){{yMin=0;yMax=100;}} yMin=Math.floor(yMin-2); yMax=Math.ceil(yMax+2);
- ctx.strokeStyle=bCol; ctx.font='11px sans-serif'; ctx.fillStyle=mCol;
- 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);}}
- 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);}}
- 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;
- const st=Math.max(1,Math.floor(span/(pw*2)));
- 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();}});
- 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();}}
- }}
- function attach(cid) {{
- const cv=document.getElementById(cid), tip=document.getElementById('tooltip');
- 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)));}};
- cv.onmousedown=ev=>{{dragStartIdx=idxF(ev);dragCurIdx=dragStartIdx;}};
- 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();}};
- cv.ondblclick=()=>{{zoomStart=0;zoomEnd=n;buildZoom();drawAll();}};
- cv.onmousemove=ev=>{{
- hoverIdx=idxF(ev);if(dragStartIdx!==null)dragCurIdx=hoverIdx;drawAll();
- 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';
- 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>`+
- `<div class="mono">CT01..08: ${{DATA.meta.active_ct_channels.map(c=>cols[c]?.[i]??'-').join(' / ')}}</div>`+
- `<div class="mono">IPMI: ${{DATA.meta.active_ipmi_channels.map(c=>c.replace('IPMI_','')+':'+(cols[c]?.[i]??'-')).join(' ')}}</div>`+
- `<div class="mono">MCU: ${{DATA.meta.active_mcu_channels.map(c=>c.replace('MCU_','')+':'+(cols[c]?.[i]??'-')).join(' ')}}</div>`+
- `<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>`;
- }};
- cv.onmouseleave=()=>{{hoverIdx=null;tip.style.display='none';drawAll();}};
- }}
- function drawAll(){{drawChart('c-ct',ctS,enCt);drawChart('c-dimm',dimmS,enDimm);drawChart('c-act',actS,enAct);}}
- function renderTables(){{
- 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>`;
- DATA.mode_transitions.forEach(m=>{{
- 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>`+
- DATA.meta.active_ipmi_channels.map(c=>`<td class="mono">${{fmtMM(m.sensors[c])}}</td>`).join('')+
- DATA.meta.active_ct_channels.map(c=>`<td class="mono">${{fmtMM(m.sensors[c])}}</td>`).join('')+`</tr>`;
- }});
- document.getElementById('t-modes').innerHTML=hm+'</tbody></table>';
- 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>`;
- DATA.test_windows.forEach(tw=>{{
- const mtd=Object.entries(tw.mt_dimm_stats).map(([k,v])=>`${{k}}:${{v.min}}~${{v.max}}`).join(' ');
- 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>`+
- DATA.meta.active_ipmi_channels.map(c=>`<td class="mono">${{fmtMM((tw.sensors||{{}})[c])}}</td>`).join('')+`<td class="mono">${{tw.cum_errors}}</td></tr>`;
- }});
- document.getElementById('t-tests').innerHTML=ht+'</tbody></table>';
- let hs=`<table><thead><tr><th>传感器通道</th><th>样本数</th><th>最小值</th><th>最大值</th><th>起点</th><th>终点</th></tr></thead><tbody>`;
- 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>`;}});
- document.getElementById('t-sensors').innerHTML=hs+'</tbody></table>';
- }}
- 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();
- }})();
- </script>
- </body>
- </html>"""
- def parse_bmc_mt_run(input_path: str | Path) -> tuple[dict[str, Any], dict[str, Any]]:
- p = Path(input_path).resolve()
- mile = json.loads((p / "milestones.json").read_text(encoding="utf-8"))
- sdr_text = (p / "ipmi_sdr_temperature.txt").read_text(encoding="utf-8", errors="replace") if (p / "ipmi_sdr_temperature.txt").is_file() else ""
- 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 ""
- # Parse ipmi_sdr_temperature.txt individual rows
- sdr_sensors: list[dict[str, Any]] = []
- for ln in sdr_text.splitlines():
- parts = [x.strip() for x in ln.split("|")]
- if len(parts) >= 5:
- val_m = re.match(r"^(-?[0-9.]+)\s+degrees\s+C", parts[4])
- sdr_sensors.append({
- "name": parts[0],
- "id": parts[1],
- "status": parts[2],
- "entity": parts[3],
- "reading_raw": parts[4],
- "temp_c": float(val_m.group(1)) if val_m else None,
- })
- # Parse [HD_Sensor] and [HD_RMTSensor] from bios_serial_clean_timestamped.log
- bios_sensors: list[dict[str, Any]] = []
- hd_rx = re.compile(r"^\[([^\s|]+)\s*\|\s*\+\s*([0-9.]+)s\]\s*\[(HD_Sensor|HD_RMTSensor)\]([^:]+):([0-9.]+)")
- for ln in bios_text.splitlines():
- m = hd_rx.match(ln.strip())
- if m:
- bios_sensors.append({
- "timestamp_utc": m.group(1),
- "elapsed_s": float(m.group(2)),
- "stage_tag": m.group(3),
- "dimm_loc": m.group(4),
- "temp_c": float(m.group(5)),
- })
- # Parse MemTest86 screen snapshots for CPU temp, speed, test progress, errors
- snaps: list[dict[str, Any]] = []
- snap_path = p / "mt86_screen_snapshots.jsonl"
- if snap_path.is_file():
- for ln in snap_path.read_text(encoding="utf-8", errors="replace").splitlines():
- if not ln.strip():
- continue
- obj = json.loads(ln)
- txt = "\n".join(obj.get("lines") or [])
- cpu_m = re.search(r"Clk/Temp:\s*(\d+)\s*MHz(?:\s*/\s*(\d+)C)?", txt)
- test_m = re.search(r"Test\s+(\d+)\s+\[([^\]]+)\]", txt)
- pct_m = re.search(r"Test\s+(\d+)%", txt)
- pass_m = re.search(r"Pass\s+(\d+)%", txt)
- err_m = re.search(r"Errors:\s*(\d+)", txt)
- snaps.append({
- "elapsed_s": obj.get("elapsed_s"),
- "reason": obj.get("reason"),
- "clk_mhz": int(cpu_m.group(1)) if cpu_m else None,
- "cpu_temp_c": int(cpu_m.group(2)) if (cpu_m and cpu_m.group(2)) else None,
- "test_num": int(test_m.group(1)) if test_m else None,
- "test_name": test_m.group(2) if test_m else None,
- "test_pct": int(pct_m.group(1)) if pct_m else None,
- "pass_pct": int(pass_m.group(1)) if pass_m else None,
- "errors": int(err_m.group(1)) if err_m else None,
- })
- parsed = {
- "parser_version": PARSER_VERSION,
- "mode": "bmc_mt_run_snapshot_and_milestones_no_means",
- "parsed_utc": datetime.now(timezone.utc).isoformat(),
- "input_path": str(p),
- "source_kind": "bmc_mt_run",
- "bmc_host": mile.get("bmc_ip"),
- "total_1hz_rows": len(snaps),
- "t0_power_on_utc": mile.get("t0_power_on_utc"),
- "power_action": mile.get("power_action"),
- "milestones": mile.get("milestones") or [],
- "bios_dimm_sensors": bios_sensors,
- "ipmi_sdr_sensors": sdr_sensors,
- "test1_progress": mile.get("mt86_test1_progress") or [],
- "snapshots_count": len(snaps),
- "max_errors": max((s["errors"] or 0 for s in snaps), default=0),
- }
- return parsed, {"snaps": snaps}
- def render_bmc_mt_run_markdown(parsed: dict[str, Any]) -> str:
- lines = [
- "# 2026-11-05 BMC 166 开机 + MemTest86 Test 0/1 里程碑与逐传感器快照报告",
- "",
- f"- **BMC IP**:`{parsed['bmc_host']}` · **开机动作**:`{parsed['power_action']}` · **T0**:`{parsed['t0_power_on_utc']}`",
- f"- **屏显快照**:`{parsed['snapshots_count']}` 条 · **累计错误**:`{parsed['max_errors']}`",
- "",
- "## 1. BIOS MRC 阶段逐 DIMM 传感器读数 (`[HD_Sensor]` → `[HD_RMTSensor]`)",
- "",
- "| 阶段标签 | DIMM 位置 | 耗时 (s) | 温度 (°C) |",
- "|---|---|---:|---:|",
- ]
- for b in parsed["bios_dimm_sensors"]:
- lines.append(f"| `{b['stage_tag']}` | `{b['dimm_loc']}` | `{b['elapsed_s']}` | `{b['temp_c']}°C` |")
- lines.extend(["", "## 2. IPMI SDR 全量独立传感器快照 (`ipmi_sdr_temperature.txt`)", "", "| 传感器 | ID | 状态 | 读数 |", "|---|---|---|---|"])
- for s in parsed["ipmi_sdr_sensors"]:
- if s["temp_c"] is not None:
- lines.append(f"| `{s['name']}` | `{s['id']}` | `{s['status']}` | `{s['temp_c']}°C` |")
- lines.extend(["", "## 3. 启动至 MT86 全里程碑时间轴", "", "| 里程碑 | 耗时 (s) | 说明 |", "|---|---:|---|"])
- for m in parsed["milestones"]:
- lines.append(f"| `{m['key']}` | `{m['elapsed_s']}` | {m['detail']} |")
- return "\n".join(lines) + "\n"
- def render_bmc_mt_run_html(parsed: dict[str, Any], artifacts: dict[str, Any]) -> str:
- payload = {**parsed, "snaps": artifacts["snaps"]}
- payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
- return f"""<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
- <title>2026-11-05 BMC 166 开机 + MT86 里程碑与传感器快照报告</title>
- <style>
- :root {{ --bg:#0b101b; --bg-card:#121a2b; --bg-alt:#182338; --text:#e6edf7; --muted:#93a4be; --border:#253554; --accent:#38bdf8; --good:#22c55e; }}
- * {{ box-sizing:border-box; margin:0; padding:0; }}
- 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; }}
- header {{ background:var(--bg-card); border-bottom:1px solid var(--border); padding:14px 24px; }}
- .container {{ max-width:1460px; margin:18px auto; padding:0 20px; }}
- .kpi-grid {{ display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; margin-bottom:16px; }}
- .kpi-card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:12px 14px; }}
- .kpi-label {{ font-size:12px; color:var(--muted); }}
- .kpi-val {{ font-size:20px; font-weight:700; margin-top:4px; }}
- .card {{ background:var(--bg-card); border:1px solid var(--border); border-radius:10px; padding:14px 16px; margin-bottom:16px; }}
- .card h3 {{ font-size:15px; margin-bottom:10px; }}
- .chart-wrap {{ width:100%; height:260px; }}
- .table-scroll {{ overflow-x:auto; }}
- table {{ width:100%; border-collapse:collapse; font-size:12.5px; }}
- th,td {{ padding:6px 8px; border-bottom:1px solid var(--border); text-align:left; }}
- th {{ background:var(--bg-alt); color:var(--muted); }}
- .mono {{ font-family:ui-monospace,Consolas,monospace; }}
- </style>
- </head>
- <body>
- <header><h1>2026-11-05 BMC 166 开机 + MemTest86 Test 0/1 里程碑与逐传感器快照报告</h1></header>
- <div class="container">
- <div class="kpi-grid" id="kpis"></div>
- <div class="card"><h3>Test 1 进度与 MT86 CPU 温度实时曲线 (`mt86_screen_snapshots.jsonl`)</h3><div class="chart-wrap"><canvas id="c-prog"></canvas></div></div>
- <div class="card"><h3>BIOS MRC 阶段逐插槽传感器 (`[HD_Sensor]` / `[HD_RMTSensor]`)</h3><div class="table-scroll" id="t-bios"></div></div>
- <div class="card"><h3>IPMI SDR 全部独立传感器快照 (`ipmi_sdr_temperature.txt`)</h3><div class="table-scroll" id="t-sdr"></div></div>
- <div class="card"><h3>全流程 25 项阶段里程碑 (`milestones.json`)</h3><div class="table-scroll" id="t-mile"></div></div>
- </div>
- <script id="embedded-data" type="application/json">{payload_json}</script>
- <script>
- (() => {{
- const D = JSON.parse(document.getElementById('embedded-data').textContent);
- const esc = v => String(v??'').replace(/[&<>"']/g,c=>({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[c]));
- const activeSdr = D.ipmi_sdr_sensors.filter(s => s.temp_c !== null);
- document.getElementById('kpis').innerHTML = `
- <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>
- <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>
- <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>
- <div class="kpi-card"><div class="kpi-label">IPMI 有效温度通道</div><div class="kpi-val">${{activeSdr.length}} 路</div><div class="kpi-sub">单次快照 (无连续 1Hz 时序)</div></div>
- `;
- // Draw Test 1 progress & CPU temp
- const cv = document.getElementById('c-prog'), rect = cv.parentElement.getBoundingClientRect(), dpr = window.devicePixelRatio||1;
- const w = Math.max(320,Math.floor(rect.width)), h = Math.max(220,Math.floor(rect.height));
- cv.width=w*dpr; cv.height=h*dpr; const ctx=cv.getContext('2d'); ctx.setTransform(dpr,0,0,dpr,0,0);
- const pts = D.snaps.filter(s => s.elapsed_s != null && s.test_pct != null);
- if (pts.length) {{
- const pad={{l:44,r:44,t:16,b:24}}, pw=w-pad.l-pad.r, ph=h-pad.t-pad.b;
- const t0=pts[0].elapsed_s, t1=Math.max(t0+1,pts[pts.length-1].elapsed_s);
- const xAt=t=>pad.l+((t-t0)/(t1-t0))*pw, yPct=v=>pad.t+ph-(v/100)*ph;
- ctx.strokeStyle='#253554'; ctx.font='11px sans-serif'; ctx.fillStyle='#93a4be';
- 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);}}
- ctx.strokeStyle='#38bdf8'; ctx.lineWidth=1.8; ctx.beginPath();
- 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);}});
- ctx.stroke();
- }}
- document.getElementById('t-bios').innerHTML = `<table><thead><tr><th>阶段标签</th><th>DIMM 位置</th><th>时间(UTC)</th><th>耗时(s)</th><th>温度</th></tr></thead><tbody>`+
- 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>';
- document.getElementById('t-sdr').innerHTML = `<table><thead><tr><th>传感器名称</th><th>ID</th><th>状态</th><th>实测读数</th></tr></thead><tbody>`+
- 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>';
- document.getElementById('t-mile').innerHTML = `<table><thead><tr><th>里程碑</th><th>耗时(s)</th><th>时间(UTC)</th><th>详情</th></tr></thead><tbody>`+
- 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>';
- }})();
- </script>
- </body></html>"""
- def _detect_input_kind(input_path: Path) -> str:
- if input_path.is_file():
- name = input_path.name.lower()
- if "endurance" in name and name.endswith(".csv"):
- return "thermal_endurance"
- if name.endswith((".csv", ".jsonl")):
- return "thermal_campaign"
- return "thermal_mt_results"
- if input_path.is_dir():
- if (input_path / "thermal_campaign_samples.jsonl").is_file() or (input_path / "thermal_campaign_timeseries.csv").is_file():
- return "thermal_campaign"
- if any(input_path.glob("thermal_*_Endurance.csv")):
- return "thermal_endurance"
- if (input_path / "milestones.json").is_file() and (input_path / "mt86_screen_snapshots.jsonl").is_file():
- return "bmc_mt_run"
- return "thermal_mt_results"
- def run_parse_pipeline(
- input_path: Path,
- out_dir: Path | None = None,
- *,
- json_path: Path | None = None,
- md_path: Path | None = None,
- html_path: Path | None = None,
- clean_csv_dir: Path | None = None,
- ) -> dict[str, Any]:
- input_path = Path(input_path).resolve()
- if out_dir is None:
- if input_path.is_file():
- out_dir = input_path.parent / f"{input_path.stem}_parsed"
- else:
- out_dir = input_path / "parsed_output"
- out_dir = out_dir.resolve()
- out_dir.mkdir(parents=True, exist_ok=True)
- kind = _detect_input_kind(input_path)
- if kind == "thermal_campaign":
- parsed, artifacts = parse_thermal_campaign(input_path)
- md_text = render_campaign_markdown_report(parsed)
- html_text = render_campaign_html_dashboard(parsed, artifacts)
- elif kind == "thermal_endurance":
- parsed, artifacts = parse_thermal_endurance(input_path)
- md_text = render_endurance_markdown_report(parsed)
- html_text = render_endurance_html_dashboard(parsed, artifacts)
- elif kind == "bmc_mt_run":
- parsed, artifacts = parse_bmc_mt_run(input_path)
- md_text = render_bmc_mt_run_markdown(parsed)
- html_text = render_bmc_mt_run_html(parsed, artifacts)
- else:
- parsed, artifacts = parse_bundle(input_path)
- md_text = render_markdown_report(parsed)
- html_text = render_html_dashboard(parsed, artifacts)
- j_out = json_path or (out_dir / "PARSED_METRICS.json")
- j_out.parent.mkdir(parents=True, exist_ok=True)
- j_out.write_text(json.dumps(parsed, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
- outputs: dict[str, Any] = {"json": str(j_out)}
- m_out = md_path or (out_dir / "PARSED_REPORT.md")
- m_out.parent.mkdir(parents=True, exist_ok=True)
- m_out.write_text(md_text, encoding="utf-8")
- outputs["md"] = str(m_out)
- h_out = html_path or (out_dir / "PARSED_DASHBOARD.html")
- h_out.parent.mkdir(parents=True, exist_ok=True)
- h_out.write_text(html_text, encoding="utf-8")
- outputs["html"] = str(h_out)
- if clean_csv_dir is not None:
- if kind == "thermal_campaign":
- written = export_campaign_clean_csv(parsed, artifacts, clean_csv_dir)
- elif kind == "thermal_mt_results":
- written = export_clean_csvs(parsed, artifacts, clean_csv_dir)
- else:
- written = []
- outputs["clean_csvs"] = [str(p) for p in written]
- return {"parsed": parsed, "outputs": outputs, "out_dir": str(out_dir)}
- def launch_gui(initial_input: str = "") -> int:
- import tkinter as tk
- from tkinter import filedialog, messagebox, ttk
- root = tk.Tk()
- root.title("Thermal + MT Results 逐传感器解析工具")
- root.geometry("780x540")
- frm = ttk.Frame(root, padding=14)
- frm.pack(fill="both", expand=True)
- in_var = tk.StringVar(value=initial_input)
- out_var = tk.StringVar(value="")
- export_csv_var = tk.BooleanVar(value=True)
- last_outputs: dict[str, Any] = {}
- def pick_dir() -> None:
- p = filedialog.askdirectory(title="选择 thermal_mt_results / thermal_study 目录")
- if p:
- in_var.set(p)
- if not out_var.get():
- out_var.set(str(Path(p) / "parsed_output"))
- def pick_file() -> None:
- p = filedialog.askopenfilename(
- title="选择 ZIP / CSV / JSONL 文件",
- filetypes=[("Supported", "*.zip *.csv *.jsonl"), ("All files", "*.*")],
- )
- if p:
- in_var.set(p)
- if not out_var.get():
- pp = Path(p)
- out_var.set(str(pp.parent / f"{pp.stem}_parsed"))
- def pick_out() -> None:
- p = filedialog.askdirectory(title="选择输出目录")
- if p:
- out_var.set(p)
- row0 = ttk.Frame(frm)
- row0.pack(fill="x", pady=4)
- ttk.Label(row0, text="输入路径:", width=12).pack(side="left")
- ttk.Entry(row0, textvariable=in_var).pack(side="left", fill="x", expand=True, padx=4)
- ttk.Button(row0, text="选目录", command=pick_dir).pack(side="left", padx=2)
- ttk.Button(row0, text="选文件", command=pick_file).pack(side="left")
- row1 = ttk.Frame(frm)
- row1.pack(fill="x", pady=4)
- ttk.Label(row1, text="输出目录:", width=12).pack(side="left")
- ttk.Entry(row1, textvariable=out_var).pack(side="left", fill="x", expand=True, padx=4)
- ttk.Button(row1, text="浏览", command=pick_out).pack(side="left")
- row2 = ttk.Frame(frm)
- row2.pack(fill="x", pady=6)
- ttk.Checkbutton(row2, text="同时导出逐位置传感器独立 CSV", variable=export_csv_var).pack(side="left")
- log_box = tk.Text(frm, height=18, wrap="word")
- log_box.pack(fill="both", expand=True, pady=8)
- def log(msg: str) -> None:
- log_box.insert("end", msg + "\n")
- log_box.see("end")
- btn_open_html = ttk.Button(
- frm,
- text="打开 HTML 看板",
- state="disabled",
- command=lambda: webbrowser.open(Path(last_outputs["html"]).as_uri()),
- )
- def on_run() -> None:
- src = in_var.get().strip()
- if not src:
- messagebox.showwarning("缺少输入", "请先选择输入目录或 ZIP/CSV/JSONL 文件")
- return
- od = Path(out_var.get().strip()) if out_var.get().strip() else None
- log(f"开始逐腔室/位置传感器解析: {src}")
- run_btn.config(state="disabled")
- def worker() -> None:
- try:
- csv_dir = (od or (Path(src) / "parsed_output")) / "clean_csv" if export_csv_var.get() else None
- res = run_parse_pipeline(Path(src), od, clean_csv_dir=csv_dir)
- last_outputs.clear()
- last_outputs.update(res["outputs"])
- p = res["parsed"]
- def done_ui() -> None:
- log(f"完成! 模式={p['mode']}, 总行数={p['total_1hz_rows']}")
- for k, v in res["outputs"].items():
- log(f" {k}: {v}")
- btn_open_html.config(state="normal")
- run_btn.config(state="normal")
- root.after(0, done_ui)
- except Exception as exc:
- def err_ui() -> None:
- log(f"错误: {exc}")
- run_btn.config(state="normal")
- messagebox.showerror("解析失败", str(exc))
- root.after(0, err_ui)
- threading.Thread(target=worker, daemon=True).start()
- row3 = ttk.Frame(frm)
- row3.pack(fill="x")
- run_btn = ttk.Button(row3, text="开始解析", command=on_run)
- run_btn.pack(side="left", padx=4)
- btn_open_html.pack(side="left", padx=4)
- root.mainloop()
- return 0
- def main(argv: list[str] | None = None) -> int:
- ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- ap.add_argument("input", nargs="?", type=Path, help="thermal_mt_results dir/zip OR unheated thermal_campaign dir/csv/jsonl")
- ap.add_argument("-o", "--output-dir", type=Path, default=None, help="output directory (default: <input>/parsed_output or <stem>_parsed)")
- ap.add_argument("--json", type=Path, default=None, help="explicit path for PARSED_METRICS.json")
- ap.add_argument("--md", type=Path, default=None, help="explicit path for PARSED_REPORT.md")
- ap.add_argument("--html", type=Path, default=None, help="explicit path for PARSED_DASHBOARD.html")
- ap.add_argument("--export-clean-csv", type=Path, default=None, help="directory to export normalized per-sensor CSVs")
- ap.add_argument("--open", action="store_true", help="open generated HTML dashboard in default browser")
- ap.add_argument("--gui", action="store_true", help="launch Tkinter GUI")
- args = ap.parse_args(argv)
- if args.gui or (args.input is None and (sys.platform.startswith("win") or os.environ.get("DISPLAY"))):
- return launch_gui(str(args.input or ""))
- if args.input is None:
- ap.print_help()
- return 2
- res = run_parse_pipeline(
- args.input,
- args.output_dir,
- json_path=args.json,
- md_path=args.md,
- html_path=args.html,
- clean_csv_dir=args.export_clean_csv,
- )
- parsed = res["parsed"]
- brief = {
- "parser_version": parsed["parser_version"],
- "mode": parsed["mode"],
- "input_path": parsed["input_path"],
- "source_kind": parsed["source_kind"],
- "total_1hz_rows": parsed["total_1hz_rows"],
- "outputs": res["outputs"],
- }
- if parsed.get("source_kind") in ("multi_dir", "single_dir", "zip"):
- brief["station_count"] = parsed["station_count"]
- brief["total_mt_errors"] = parsed["total_mt_errors"]
- brief["all_templates_pass"] = parsed["all_templates_pass"]
- elif parsed.get("source_kind") == "thermal_campaign":
- brief["runs_count"] = len(parsed.get("runs", {}))
- elif parsed.get("source_kind") == "thermal_endurance":
- brief["test_windows_count"] = len(parsed.get("test_windows", []))
- brief["mt_total_errors"] = parsed.get("mt_total_errors")
- elif parsed.get("source_kind") == "bmc_mt_run":
- brief["milestones_count"] = len(parsed.get("milestones", []))
- brief["bios_dimm_sensors_count"] = len(parsed.get("bios_dimm_sensors", []))
- brief["ipmi_sdr_count"] = len(parsed.get("ipmi_sdr_sensors", []))
- print(json.dumps(brief, ensure_ascii=False, indent=2))
- if args.open:
- webbrowser.open(Path(res["outputs"]["html"]).as_uri())
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|