Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
filebench
filebench-master/cvars/mtwist/mtcctest.cc
#ifndef lint #ifdef __GNUC__ #define ATTRIBUTE(attrs) __attribute__(attrs) #else #define ATTRIBUTE(attrs) #endif static char Rcs_Id[] ATTRIBUTE((used)) = "$Id: mtcctest.cc,v 1.7 2012-12-30 16:24:49-08 geoff Exp $"; #endif /* * Test the C++ version of the Mersenne Twister PRNG * * $Log: mtcctest.cc,v $ * Revision 1.7 2012-12-30 16:24:49-08 geoff * Use gcc attributes to suppress warnings on Rcs_Id. * * Revision 1.6 2010-06-24 01:45:46-07 geoff * Move volatile declarations to the top of the function to ensure they * are effective. * * Revision 1.5 2007-10-26 00:21:06-07 geoff * Don't throw away random values in the timing tests, since then the * compiler would optimize the entire loop away. * * Revision 1.4 2003/09/11 05:50:53 geoff * Use the standard namespace. Get rid of a troublesome setbuf call that * I'm too lazy to figure out how to get to work. * * Revision 1.3 2001/06/19 00:41:16 geoff * Put a newline after the saved data, now that the type doesn't. * * Revision 1.2 2001/06/18 05:40:11 geoff * Do 300 million timing loops by default. * * Revision 1.1 2001/06/14 10:52:29 geoff * Initial revision * */ #include "mtwist.h" #include <fstream> #include <iomanip> #include <iostream> #include <unistd.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/time.h> using namespace std; int main (int argc, char * argv[]); static void report_timing(long loops, struct rusage * then); /* * Base unit for timing loops, so the caller can think in millions. */ #define TIMING_LOOP_BASE 1000000 /* * Default number of timing loops to do */ #define TIMING_LOOPS (300 * TIMING_LOOP_BASE) /* * The following table contains values that were generated by Matsumoto and * Nishimura's C program for the Mersenne Twist algorithm, using the * default seed of 4357. These values are presumed to be correct. The * test program compares the values generated by this implementation with * the reference values to ensure that the generator has been implemented * correctly. */ static unsigned long correct_values[] = { 3510405877u, 4290933890u, 2191955339u, 564929546u, 152112058u, 4262624192u, 2687398418u, 268830360u, 1763988213u, 578848526u, 4212814465u, 3596577449u, 4146913070u, 950422373u, 1908844540u, 1452005258u, 3029421110u, 142578355u, 1583761762u, 1816660702u, 2530498888u, 1339965000u, 3874409922u, 3044234909u, 1962617717u, 2324289180u, 310281170u, 981016607u, 908202274u, 3371937721u, 2244849493u, 675678546u, 3196822098u, 1040470160u, 3059612017u, 3055400130u, 2826830282u, 2884538137u, 3090587696u, 2262235068u, 3506294894u, 2080537739u, 1636797501u, 4292933080u, 2037904983u, 2465694618u, 1249751105u, 30084166u, 112252926u, 1333718913u, 880414402u, 334691897u, 3337628481u, 17084333u, 1070118630u, 2111543209u, 1129029736u, 2769716594u, 198749844u, 2123740404u, 3372116884u, 667945179u, 1235233343u, 1413475797u, 2355129622u, 3131889314u, 1361507145u, 3419810344u, 3753862504u, 2643520359u, 854777807u, 2823672895u, 1563137348u, 2778071293u, 3360232580u, 1294979669u, 2667002587u, 4095439979u, 806669383u, 3717814038u, 1071953403u, 3630859637u, 771361748u, 1131385020u, 3697612515u, 4264844916u, 1364828348u, 2863894246u, 1109863328u, 3066937191u, 2778683115u, 3989613953u, 859474495u, 167522376u, 1094225558u, 1963711766u, 1257324636u, 1729949323u, 125753755u, 1068698284u, 1761594045u, 2106609220u, 1033190229u, 946183933u, 1100436279u, 489306665u, 2385045156u, 658699819u, 3308017340u, 2385997510u, 105622857u, 1976233741u, 1535497010u, 314176889u, 1247500738u, 2138106664u, 2757078771u, 2433460811u, 3970906471u, 1944201130u, 2366336502u, 2541539915u, 4284982935u, 224898482u, 1457988276u, 2188154237u, 3655119144u, 979144237u, 1279857832u, 2711710163u, 4093937260u, 2299893420u, 2121869254u, 2505459837u, 1847263294u, 2974457633u, 3439803738u, 1672773492u, 225684598u, 2496857387u, 611619631u, 3993022877u, 3508398016u, 1663733971u, 758566080u, 1653863133u, 1701066037u, 3782883361u, 3343813716u, 2602577666u, 629577870u, 3724093470u, 361301181u, 2674434977u, 1443899064u, 4104796692u, 140754167u, 4230942998u, 447458027u, 743917836u, 2818315151u, 1332110941u, 266033703u, 308176090u, 130356650u, 3074197472u, 3093392044u, 1602712035u, 1856287253u, 3375970245u, 3114872063u, 370413632u, 1435286098u, 645351481u, 908917276u, 2440368438u, 1599412846u, 2500100729u, 790131292u, 3684521490u, 4052663936u, 1566488352u, 295035953u, 4163443199u, 2997925650u, 678068969u, 3667661122u, 1273385972u, 3555794914u, 762012623u, 1091375739u, 1765680277u, 4238179361u, 3406590822u, 3797246256u, 388618876u, 2160693563u, 349961032u, 1392360403u, 3579025090u, 604490212u, 3577823930u, 2321462651u, 3790422055u, 3185735941u, 2229660586u, 1128575466u, 884862908u, 3330757128u, 3194168238u, 681073659u, 800341641u, 2006864675u, 2619636221u, 1577889182u, 3575155952u, 2260116784u, 3689141878u, 1657848984u, 2642380231u, 2878484564u, 3099953080u, 468844464u, 4134363631u, 4110639840u, 1904558184u, 1937194892u, 3137602491u, 3643695698u, 820242909u, 3068372731u, 3388748923u, 4235603065u, 2615115373u, 1555770904u, 1520951990u, 1047053830u, 1663094463u, 3948465044u, 1077597088u, 2996944317u, 3230974609u, 2019388652u, 865275198u, 2046271241u, 3163620630u, 269072378u, 2253440754u, 277763586u, 1114595358u, 2679817222u, 988885471u, 922982460u, 477046426u, 1161679484u, 2950091998u, 2088879880u, 3516906501u, 1403601752u, 1184069822u, 3531029460u, 3041313352u, 3359174170u, 2117925252u, 1529768389u, 1253051929u, 1829668776u, 2678766355u, 2138924913u, 3147299808u, 447212163u, 1069119222u, 3791704659u, 804904386u, 3580345412u, 1700215583u, 904016717u, 74539975u, 1288558083u, 1746888271u, 437611701u, 781576281u, 1166365552u, 2566333668u, 4292856916u, 4076802480u, 3968908047u, 3057346051u, 2074623641u, 3653637364u, 586217310u, 3211306229u, 2604443978u, 3303224219u, 50953535u, 2118693299u, 460196852u, 3355264342u, 500727351u, 1681849672u, 113995187u, 1200937601u, 3092561862u, 312936130u, 3916083024u, 2561711416u, 3713941700u, 2240434908u, 637144400u, 1946468041u, 3224254139u, 2242555323u, 2524984519u, 945834669u, 2805199117u, 1879274691u, 3792160120u, 37879558u, 1205870756u, 3508020184u, 2705733735u, 3134213377u, 3170077556u, 9055729u, 2147895752u, 3788046325u, 2422273092u, 1228026268u, 1275162816u, 1385450594u, 128490357u, 678715088u, 2466464403u, 2715463741u, 420067866u, 396072989u, 1729810791u, 4146068843u, 389936193u, 1010939382u, 794725144u, 633726173u, 3567793282u, 248988111u, 1254549356u, 1989964616u, 1425389196u, 2202358947u, 2830413406u, 3798927382u, 3442966168u, 269966252u, 2807646342u, 1794971636u, 1602977220u, 1360381486u, 1805272988u, 554730358u, 4259897540u, 2168740091u, 442942697u, 3744617621u, 3567326073u, 1232342342u, 3720210842u, 303505483u, 3533762586u, 2136482547u, 2813945830u, 3051833277u, 2830164695u, 3157472512u, 3186113013u, 1063305342u, 4133844231u, 2026873438u, 94687021u, 42670911u, 2205451721u, 200274097u, 3184342380u, 1216199867u, 1941807482u, 1902652464u, 4140258655u, 1934749011u, 2626251395u, 1041046135u, 3256560316u, 2005577300u, 367040511u, 2562291571u, 4179257085u, 394550850u, 3714400922u, 3096861476u, 3729796880u, 3528309113u, 1483426196u, 821348673u, 2057501468u, 3141389956u, 631596202u, 2325651773u, 3568751628u, 2300178836u, 257777076u, 3455675689u, 2853908813u, 223950412u, 2320715588u, 250378269u, 3557833937u, 927098460u, 315421373u, 1957400381u, 725633141u, 3345409284u, 1114863797u, 1830809043u, 1922707457u, 3785762071u, 3404751487u, 2434832700u, 1359584120u, 860423718u, 2979956529u, 888063953u, 641814761u, 180527770u, 3316862637u, 4012959929u, 28566252u, 1045558574u, 4131606737u, 215968520u, 362234156u, 2248115936u, 3069089212u, 3403600809u, 1812984601u, 1768934064u, 4007586160u, 1240758160u, 13887765u, 3514615109u, 3827374039u, 3341198715u, 1982839159u, 2033151304u, 4283902822u, 3744190534u, 726223056u, 3905246635u, 1875803225u, 2030522753u, 2822074688u, 3325482280u, 1691268105u, 3033866845u, 1716543028u, 1555574049u, 2661093496u, 1979855811u, 2251933935u, 1276056752u, 3341241268u, 1892612984u, 2194846054u, 486586963u, 2492823590u, 593230942u, 775986230u, 1255789287u, 2318099602u, 3056263080u, 158332807u, 2451929550u, 3374135491u, 372847709u, 1128359579u, 373993639u, 2419119952u, 829613207u, 2948211163u, 2324165819u, 160722663u, 1444930279u, 765460462u, 3780495422u, 592264489u, 316670611u, 2342138965u, 1439591408u, 3362218290u, 2860902653u, 1116562887u, 3033679152u, 1381679779u, 1291533463u, 1962666710u, 2222373514u, 1215751045u, 3569236064u, 1611254503u, 1171727980u, 3057484484u, 3263787664u, 3065712276u, 781477153u, 1881176626u, 3769042770u, 1193467712u, 2843905090u, 3437666358u, 2160717604u, 419274206u, 2767079897u, 4007363510u, 1325555048u, 4187736634u, 4066907010u, 3299749742u, 154249616u, 1941800223u, 1157563946u, 705258893u, 860757803u, 1310317854u, 1898329708u, 3491229573u, 312822728u, 3407001878u, 1029352733u, 3463910352u, 2741163037u, 2705583812u, 2644345635u, 683012156u, 948328240u, 2656867161u, 1644147624u, 2853875853u, 822059867u, 753937406u, 1604103884u, 1756360543u, 3400647193u, 2802766030u, 2268191056u, 3784643944u, 3009927237u, 394432056u, 1840177440u, 2651765924u, 1205254585u, 3551482241u, 2857937506u, 2522509113u, 3675764066u, 1234994787u, 3459183960u, 186529857u, 1329960799u, 2322397450u, 1078548606u, 113242357u, 2421327506u, 3306100881u, 211880652u, 847202265u, 1034020264u, 2374075486u, 755993425u, 2474409905u, 1885945103u, 3588026819u, 3326201431u, 747273957u, 3172561912u, 4064603659u, 2036147813u, 3539583488u, 2861164857u, 3303878586u, 2385840167u, 734771685u, 804646316u, 1158163327u, 2080435695u, 2455811362u, 2060318701u, 1223319334u, 2573853731u, 3341336861u, 3207344772u, 1654544724u, 1227774824u, 1779567885u, 4241425455u, 3942578957u, 2787959909u, 90390016u, 1235487669u, 2405269696u, 4096898260u, 2121644059u, 2432007152u, 2649006803u, 355642145u, 3998121079u, 3524581383u, 919279000u, 789586853u, 2465492036u, 220701650u, 2947224279u, 1329892616u, 3729919501u, 1219039514u, 3006882189u, 281458735u, 3800499491u, 730882493u, 2222118351u, 4107301035u, 2687550208u, 3260886108u, 3701859392u, 3862191362u, 1412535194u, 1694757183u, 772470279u, 689128388u, 2265554314u, 3499902942u, 2845535450u, 2570802968u, 1947307958u, 4027367903u, 1910806179u, 3858889779u, 4021735452u, 4078787932u, 3413032217u, 2980053565u, 2148809521u, 1497338125u, 2040525958u, 3112062074u, 2201881275u, 3672285015u, 3003099464u, 3809697025u, 3709177038u, 3264926503u, 1707537043u, 1104985157u, 3691862420u, 1898692192u, 2323051094u, 736562662u, 2300313916u, 3100486674u, 302436891u, 1288467611u, 1981059467u, 3645778636u, 1609399619u, 3418162375u, 3667843152u, 536318325u, 3040655354u, 2544467931u, 424476355u, 1601741596u, 246832728u, 2677287644u, 2835422307u, 1127786001u, 850991343u, 2067806155u, 3766212150u, 1001927094u, 3801068881u, 3242308737u, 1560596676u, 1681618985u, 2562998394u, 3484825522u, 2655391996u, 1746361319u, 3550836123u, 4038742826u, 735255465u, 3954076606u, 4101370050u, 3167012089u, 1966689481u, 1576556523u, 207036082u, 2337346669u, 3404885158u, 3372194402u, 2313772874u, 1511011541u, 3934253759u, 152017013u, 2305096656u, 1003233114u, 3788182044u, 2738083629u, 2667318735u, 4075851512u, 3919952624u, 3934687504u, 955697805u, 3721361893u, 1892740917u, 1925356403u, 3530645689u, 57355987u, 500963211u, 3812263275u, 3120702996u, 3348394440u, 2648242605u, 2950965560u, 2906248872u, 4195607563u, 1976120064u, 569029796u, 3204894397u, 836657553u, 4253104557u, 4029524248u, 1167446730u, 3164256694u, 1225943621u, 978942573u, 3887954057u, 4029693733u, 3371611138u, 2648127182u, 341670719u, 780349063u, 1249088385u, 2825987206u, 1409751402u, 3493141543u, 2454446995u, 3001899542u, 894695004u, 4113594037u, 2748119359u, 3811278462u, 337072564u, 3551268535u, 4210316453u, 2857304716u, 1656016234u, 3055850193u, 4074141119u, 2702683976u, 3903520288u, 2708109896u, 1303194166u, 676764765u, 1073839u, 3417024471u, 530027902u, 664548902u, 3934189521u, 1118172394u, 1598501076u, 1353136139u, 3556356767u, 3851436279u, 787984702u, 3614996657u, 2653843342u, 350845053u, 2540767452u, 341795141u, 4131579558u, 2852231303u, 347703279u, 304754275u, 3637218358u, 1191420956u, 4250273882u, 2217329477u, 3619012484u, 2320390083u, 1618600250u, 100602741u, 3962829626u, 3325838530u, 3310041575u, 2202357234u, 2410265700u, 1855854724u, 1586666379u, 1893433651u, 4212894970u, 3078470962u, 3005791950u, 3645097109u, 2729330720u, 178175659u, 1878759843u, 3613064024u, 2235022317u, 1229007963u, 1217716121u, 3424643385u, 2025817426u, 2541310454u, 3491127040u, 834075061u, 1476080952u, 527792572u, 3142617040u, 990164480u, 3538861805u, 1101804820u, 254185979u, 2139277356u, 3053978085u, 3636278570u, 1588526078u, 3265686058u, 3200724466u, 3305433961u, 1714292212u, 2894641386u, 286242900u, 2390694965u, 1104137642u, 1729447649u, 2603147116u, 1739535876u, 2332325654u, 3923517970u, 975963350u, 3046750553u, 4287139816u, 2887426453u, 3205373337u, 2829120066u, 3989557087u, 1090404329u, 2762938959u, 2016187695u, 188074317u, 562585328u, 1185556641u, 3980179851u, 2922039667u, 3215853289u, 946979886u, 2822925104u, 803185936u, 1852384677u, 2297156223u, 2799487985u, 1756284627u, 2317738144u, 1335401093u, 674337096u, 2899555797u, 3996541014u, 3014749938u, 283034558u, 3481962136u, 3810308241u, 2725662577u, 744192370u, 3665583468u, 571653166u, 3181462357u, 1782231829u, 563269281u, 1274600369u, 2386970918u, 363976120u, 2931953430u, 614822572u, 1661454733u, 449226294u, 3506516244u, 3427050773u, 2620464687u, 505585754u, 3256549852u, 321182353u, 3890429063u, 2030404657u, 1191957414u, 3469037079u, 947528907u, 578915297u, 2155016115u, 557136361u, 374100253u, 1716551606u, 1064892772u, 2282836509u, 2205887435u, 735861059u, 2088833463u, 3884993958u, 1520195389u, 3349226581u, 4116948321u, 3654190067u, 3585109483u, 2170692034u, 4104050396u, 1431760441u, 871040163u, 3131221596u, 4039637966u, 3255680597u, 1537348827u, 4274038615u, 2766931218u, 3080056590u, 2427576150u, 1698622741u, 491269657u, 2957152254u, 4003327323u, 1665870563u, 2898998885u, 350910601u, 3377912239u, 56558544u, 2757732126u, 3003019578u, 3020476484u, 1103562767u, 266867533u, 3238470691u, 101050052u, 2174141449u, 4261294044u, 3377977245u, 4283033233u, 1649319944u, 2407542500u, 1186270608u, 506638155u, 853299114u, 528018288u, 3370360190u, 3432726533u, 33304936u, 746516661u, 864441540u, 877624554u, 549536499u, 2512486873u, 1718378202u, 1877264374u, 3907125156u, 3480301523u, 1222420918u, 2962412787u, 1897386667u, 565602854u, 870635873u, 1837265416u, 2093005006u, 2069832336u, 421542850u, 546177829u, 3737295211u, 2022730805u, 114777545u, 1045010491u, 1474827040u, 7636789u, 3926378049u, 825140914u, 3894878768u, 2235348820u, 4209167372u, 1363271078u, 1633012431u, 2604598105u, 1475584955u, 363136592u, 2939993958u, 3395026321u, 2769982499u, 2579982422u, 3377853512u, 1926697291u, 1309179303u, 198769522u, 525328917u, 2939632387u, 3839345362u, 857890368u, 1404166316u, 1175685399u, 3359187637u, 2911320684u, 3331860351u, 150684895u, 1830720677u, 3549325302u, 1721173678u, 1541682359u, 3727128665u, 1378619663u, 3657645799u, 427125659u, 87651116u, 816648775u, 1111028388u, 3408906806u, 1198529401u, 4082457652u, 2373720194u, 1279364663u, 2697296422u, 4274091187u, 3991008751u, 2750937690u, 745247050u, 3020601003u, 3207637609u, 1522623855u, 3440826157u, 1459824707u, 275982735u, 1366156119u, 2084141301u, 3371738706u, 3652235981u, 3414352861u, 3867568134u, 4143632352u, 2508301197u, 2694712076u, 663648113u, 4084805516u, 2045731357u, 103690742u, 3579296438u, 3853685199u, 4040332527u, 3433047383u, 2160986205u, 3880533570u, 2124079194u, 898702193u, 1377522152u, 2510928900u, 524137274u, 2676839533u, 1147766985u, 2659663351u, 1441686856u, 2336342795u, 2323419808u, 2616909909u, 367789898u, 2802090548u, 3912305190u, 3394874017u, 4182826382u, 378652856u, 2456117771u, 3644581920u, 650421961u, 1356327939u, 1270283631u, 1353114655u, 1186775090u, 2229315614u, 60977715u, 255049167u, 1393113108u, 91557822u, 3460789587u, 4255756627u, 2680883563u, 1961238627u, 2706826361u, 86694213u, 3568183186u, 1174931951u, 3101787400u, 3245440880u, 1012545275u, 4023587262u, 25415056u, 3884392715u, 2033651573u, 1517048548u, 2157890606u, 1607160396u, 1733385865u, 4000967569u, 702762527u, 4219828471u, 2839214666u, 3612303148u, 2417079479u, 561191037u, 2668684575u, 1049452531u, 3056008028u, 752063538u, 1442500991u, 2201174758u, 1248774154u, 165187750u, 2945670372u, 435357616u, 3927358478u, 535926151u, 3753175365u, 256444691u, 2255485820u, 1023308722u, 4229846989u, 2519054772u, 651526182u, 4180758060u, 2654793384u, 2610214273u, 610288969u, 1979520346u, 1745042640u, 2256795625u, 954259986u, 1077808451u, 2678875090u, 955102447u, 2059446553u, 3293602562u, 1583006223u, 2748412790u, 4129522985u, 1799912684u, 461379416u, 3072251629u, 2023808855u, 3368588935u, 1852160624u, 3234147626u, 2398022056u, 3965955751u, 2934088597u, 2993217622u, 750328728u, 783088312u, 3770678320u, 3156679282u, 36274327u, 1466406645u, 4053852068u, 438490559u, 2718496037u, 3313180021u, 2382533773u, 3930250216u, 3894526091u, 3389067170u, 2754596462u, 2355173790u, 2384382760u, 2238960674u, 1652306376u, 4043138340u, 2268422975u, 702886942u, 2158419984u, 313074687u, 3916694140u, 2872536179u, 4110613033u, 3497889789u, 3345443240u, 3438724296u, 3831640476u, 1721511461u, 3181187841u, 293747726u, 1016981259u, 319715874u, 2604613639u, 3866375162u, 1129514664u, 4090305697u, 1415656234u, 3904058353u, 3454231580u, 1137421991u, 2313708721u, 3189903818u, 2359396326u, 4140811458u, 2619162542u, 4018716781u, 2943094968u, 4275110940u, 3753225546u, 393641299u, 793819538u, 3807603495u, 3584270096u, 583337815u, 3204343682u, 2704728429u, 1260285383u, 2070005280u, 1290966975u, 3841613013u, 3748951459u, 1996539050u, 15255144u, 3555533616u, 1896042895u, 457790456u, 2103229914u, 3549835684u, 2608881213u, 3750997458u, 1284886852u, 3983637798u, 2754133138u, 1375874601u, 3702999536u, 4047595327u, 1757722874u, 205211433u, 1550020058u, 2625086805u, 888856283u, 260526089u, 3603211830u, 3874949683u, 3705639611u, 1244107692u, 2576564054u, 1798606541u, 1538798258u, 1914115295u, 3465780481u, 2191768384u, 1053339258u, 482479463u, 1590615673u, 1678894824u, 2583029443u, 3312998864u, 2348965967u, 3592411649u, 2586886059u, 1193775683u, 3166643410u, 2848176518u, 4244785412u, 3263141460u, 2534433066u, 3857841146u, 4030264873u, 2160049808u, 2568607774u, 3962849448u, 1063016183u, 752325873u, 3916513901u, 3666512065u, 3742123864u, 240316886u, 273053100u, 1974725783u, 103853041u, 498343646u, 2849277012u, 1531820781u, 2800822870u, 2172374911u, 2608056220u, 2938222996u, 2495640435u, 2050031019u, 1581664696u, 1192708798u, 3958663429u, 3409883558u, 1261646904u, 2262137662u, 1495935118u, 3549216229u, 819898291u, 616300818u, 920698111u, 531434903u, 1750605108u, 2331202523u, 2604625024u, 311416415u, 3413350776u, 4091626041u, 3339815970u, 2156981844u, 1053778854u, 3946541364u, 757561673u, 2794628342u, 2560288402u, 3516100843u, 1078950707u, 1096405570u, 2565723989u, 3166139486u, 665944531u, 3426830504u, 1316229722u, 3470576224u, 174450923u, 1756691252u, 1809953431u, 2120869441u, 744710690u, 638114562u, 3462360879u, 662650689u, 654132881u, 2029278034u, 4053373589u, 659248560u, 1754023002u, 3683623866u, 684016545u, 2635610107u, 3319934252u, 877308702u, 32003886u, 3136239345u, 2204537667u, 617587244u, 3444132147u, 3394465910u, 707665795u, 3673280986u, 2732829120u, 2865909493u, 3553125825u, 2860898385u, 2982421098u, 1193861977u, 1034606365u, 1752852792u, 1621071619u, 2528057870u, 2138762952u, 2308749354u, 906867989u, 779669216u, 2232060698u, 480996617u, 2925606018u, 303678891u, 3851015553u, 3348999586u, 1213516375u, 3489393664u, 2606497132u, 4155605153u, 3740915058u, 3037706031u, 2239177712u, 3123401220u, 1990275519u, 3162603957u, 1918939652u, 776035672u, 2865857149u, 571764668u, 151622100u, 2353602509u, 2112275436u, 3057460223u, 1545579966u, 257397390u, 19209971u, 2138790032u, 3753848035u, 1085255822u, 4235734180u, 875019346u, 3217942945u, 1091459686u, 3587756657u, 3077984076u, 1491592709u, 3017547658u, 2252844554u, 1985555588u, 3040031536u, 558425569u, 1123411656u, 173859531u, 3673271296u, 495041198u, 1342690724u, 2894423806u, 673054854u, 3159268470u, 3113987190u, 2436187367u, 1936640302u, 1360880324u, 1912925050u, 1245740864u, 1374924892u, 3948122288u, 3665262872u, 1730168177u, 1418975463u, 1724598953u, 1518264520u, 155679217u, 2777491364u, 2127704373u, 479136316u, 467963358u, 2038497471u, 4009847343u, 3214679953u, 316320711u, 43436245u, 2439770433u, 3061525191u, 325285125u, 3418463477u, 265361904u, 3317034447u, 2046949609u, 2398727149u, 3035501454u, 3766818899u, 1907069371u, 3915369678u, 825294741u, 3960827812u, 2822610696u, 435348151u, 2960342732u, 2841517289u, 1245939424u, 501966471u, 1523054284u, 2986922068u, 3643707400u, 1960129231u, 605842596u, 498475817u, 2091802075u, 1546806085u, 4249712391u, 719048827u, 1236161870u, 1455705076u, 611924837u, 1606154038u, 3804768796u, 2147049065u, 3141135911u, 2326016873u, 1938285117u, 2106616699u, 3649256942u, 2518864732u, 3041005008u, 25486255u, 317223081u, 859651472u, 3423179818u, 3316420743u, 1720381191u, 2949551625u, 4153784543u, 2375654557u, 4245912914u, 3055577422u, 426826876u, 3371315320u, 393263103u, 1674632271u, 2001097492u, 3810913408u, 926582509u, 2004092737u, 1225977080u, 704646682u, 507362042u, 115002871u, 772062004u, 2509172666u, 671380383u, 741064994u, 1087280005u, 2458813622u, 3555270161u, 432569830u, 1768785658u, 2788242172u, 3626575210u, 3924321291u, 1056700312u, 807145567u, 2457173701u, 4163083585u, 2389340792u, 2527897320u, 148652138u, 809466003u, 1310067162u, 147554547u, 3006884242u, 1648641905u, 2507398430u, 286276539u, 1285247198u, 1497575669u, 4272381767u, 1630690228u, 528903131u, 3782308744u, 3328620223u, 2544636753u, 3716824890u, 3359475073u, 1715425081u, 493809452u, 1482469337u, 2880570645u, 4246120078u, 2462260788u, 4005994348u, 3376710207u, 3055770626u, 1224220146u, 706700781u, 146623188u, 1905647200u, 1835596148u, 114826369u, 1833749674u, 534781147u, 233967048u, 942256881u, 3699192716u, 188293730u, 3910438208u, 2394758371u, 3662527011u, 97504699u, 3543922236u, 4206828553u, 3734565571u, 3586763714u, 403958048u, 2063667481u, 2730205743u, 589502476u, 1149905623u, 4095869863u, 2805195184u, 4223446468u, 3102461252u, 423688803u, 4256209713u, 1518355137u, 4269931685u, 4174808463u, 2019550169u, 1704760048u, 1718939701u, 602013714u, 3655037789u, 1997992275u, 782052616u, 2168800816u, 284956141u, 3975978923u, 644864581u, 3042712626u, 2180684793u, 1466664828u, 1267605484u, 2784735889u, 1428685493u, 2544323949u, 889906898u, 4235848255u, 4186602195u, 855556210u, 2342896146u, 3307519234u, 2197566638u, 2509561763u, 20519604u, 2319402891u, 3907092227u, 805926263u, 1545081676u, 946901149u, 174874593u, 2904667651u, 1004586041u, 1671610396u, 2507164708u, 565710128u, 2195671193u, 2148970716u, 64150785u, 3111996478u, 3853037378u, 3929028523u, 992899482u, 698318534u, 1024524470u, 4196904510u, 3557517929u, 4285406934u, 94205271u, 3530304939u, 2305824750u, 1531731847u, 2100892683u, 4141695457u, 717968711u, 1020961798u, 1435297145u, 1174399738u, 3484051255u, 401988634u, 18353084u, 2476579762u, 3884197419u, 2161379550u, 3488516503u, 4291859194u, 429223686u, 2634560425u, 1960550128u, 3018314044u, 3956111413u, 3586019740u, 271458754u, 995152322u, 2784808343u, 2699155930u, 718003490u, 88374071u, 2116640876u, 2418838888u, 2473871392u, 3887260803u, 291756441u, 317239670u, 1991643081u, 1067021559u, 52172441u, 3466077380u, 2808782519u, 506095445u, 2721138411u, 3170096146u, 2636465745u, 3084352426u, 1216338971u, 1227230645u, 3998968120u, 2009459829u, 2474360224u, 345636082u, 601138538u, 1362885697u, 3578651252u, 698241090u, 1118227414u, 5507337u, 2780083822u, 703266438u, 864120870u, 1698678511u, 172897137u, 144366506u, 1820854951u, 2113926171u, 3294417442u, 3001580140u, 3365898069u, 2414288823u, 2191315816u, 2041923551u, 1374216245u, 1792102283u, 966439255u, 3142541052u, 3926566349u, 4034829900u, 2276773096u, 381471573u, 1895081823u, 1362996393u, 2592249580u, 2898726226u, 4223177326u, 3400414171u, 2052800787u, 3853885905u, 1028196740u, 3183947606u, 2486531127u, 3167268159u, 1866096562u, 2950293380u, 994523562u, 3023614567u, 4104267478u, 1191097596u, 3529256093u, 3418504368u, 3894797255u, 3908535736u, 3298561721u, 3288395583u, 912501104u, 831862193u, 858008061u, 3583526686u, 3604044732u, 11642333u, 532352558u, 2447342506u, 49917723u, 2465972387u, 49071225u, 189297954u, 3406843807u, 2379895567u, 2252069007u, 3118935217u, 2612642690u, 489772543u, 3046688150u, 1991370098u, 1491676633u, 2171172062u, 2631485941u, 111539597u, 1754135798u, 104108364u, 3801121441u, 961805875u, 3244343746u, 3927144143u, 1042956596u, 2171259252u, 1546798356u, 2949756312u, 1677484392u, 3916024040u, 2117087490u, 3806450987u, 3716708844u, 3052844593u, 1098132833u, 1944120348u, 1211978277u, 1373013705u, 1417003306u, 1935792551u, 2645561211u, 4148953952u, 530900685u, 4282117874u, 1246946090u, 3856432168u, 239949635u, 140665127u, 3955560396u, 1458503553u, 141173732u, 3283724848u, 2719866813u, 1750621676u, 550663579u, 491600368u, 3263446369u, 1961062013u, 1243373458u, 3444793917u, 3899300498u, 718538962u, 3064564239u, 101084001u, 4001046471u, 690719870u, 2544332192u, 2973901205u, 3510440400u, 2221840969u, 3581406537u, 2687583608u, 45358658u, 1597859661u, 314280821u, 3494340276u, 3133266884u, 1787593645u, 87373007u, 3037573439u, 3752761966u, 1788735812u, 2276942058u, 3166047868u, 1996038283u, 3602485091u, 493959987u, 2734283831u, 1597766558u, 1319887499u, 3957554749u, 967477137u, 1871108451u, 366543865u, 3417930960u, 3465456271u, 683117185u, 2140844389u, 1633256418u, 3595239200u, 272311865u, 3868727953u, 516898363u, 2749883233u, 3669048734u, 2889507150u, 343253656u, 1307200448u, 2276582436u, 1455456255u, 3095475925u, 3167968348u, 753145196u, 1720643028u, 1964199342u, 3245346896u, 2501510517u, 2401288980u, 3190253603u, 3392954261u, 927482091u, 2739586668u, 656503075u, 3631723682u, 2774039073u, 3581048448u, 2109905006u, 2654627331u, 625449654u, 3921753764u, 533200192u, 1708723687u, 3105862488u, 1938982508u, 284773522u, 3014100134u, 2332799199u, 3899421698u, 4054778144u, 1855118412u, 2423445164u, 2085429129u, 2525269691u, 1050404537u, 2665308718u, 2195447044u, 1546419073u, 6271311u, 848651525u, 2114666412u, 2361256342u, 1968111351u, 2378425902u, 2399819062u, 2046693061u, 2184541122u, 606566810u, 1184406086u, 3849119084u, 1782109246u, 1711162988u, 3725213412u, 1978982002u, 2084076307u, 4226808472u, 1381220175u, 2756022796u, 1155923374u, 1310996083u, 3892088705u, 2900168226u, 2172331364u, 1976800812u, 3446717919u, 3018115416u, 772796339u, 3119675141u, 3399966733u, 2483366635u, 2251157986u, 3721643942u, 92354950u, 2276558847u, 3199161030u, 391156337u, 516105765u, 3031568469u, 3056187358u, 327152205u, 2268820210u, 154728704u, 2498616329u, 2687795551u, 1661550221u, 3058059426u, 2011392238u, 3213116060u, 4232673760u, 188451691u, 2316494518u, 139654414u, 2820632408u, 741805800u, 3398953290u, 3029114036u, 4228239470u, 1294389995u, 220293836u, 832710216u, 3520956438u, 3326239211u, 2002353592u, 2910456568u, 1116726602u, 3947894185u, 2269194026u, 331201566u, 23448299u, 2501636454u, 1481063438u, 531225803u, 3374157189u, 1250339898u, 2807211779u, 3509443222u, 3149299112u, 2512315800u, 2156034521u, 3927375017u, 3009858040u, 3815089086u, 2493949982u, 3668001592u, 1185949870u, 2768980234u, 3004703555u, 1411869256u, 2625868727u, 3108166073u, 3689645521u, 4191339889u, 1933496174u, 1218198213u, 3716194408u, 1148391246u, 1345939134u, 3517135224u, 3320201329u, 4292973312u, 3428972922u, 1172742736u, 275920387u, 617064233u, 3754308093u, 842677508u, 529120787u, 1121641339u, 3300737790u, 3072286611u, 763885092u, 237936516u, 214735112u, 1071670392u, 2640290649u, 2253339066u, 406563643u, 857883160u, 1943298024u, 482572274u, 1387459037u, 3227802952u, 3719718158u, 254239224u, 2056147900u, 1907664448u, 3028647233u, 1385596859u, 2691640069u, 4156402531u, 2727923167u, 2529722889u, 3095622616u, 1958102896u, 576816725u, 1327262146u, 614269765u, 1721856728u, 1312650621u, 2437977684u, 1733921636u, 2123749922u, 3790190001u, 3934886640u, 2878714597u, 2564557568u, 157082304u, 2081155532u, 1874993431u, 29873796u, 1575628456u, 4088191944u, 2658510623u, 1984791300u, 3812698918u, 3787281972u, 4231096806u, 3785648472u, 2977746737u, 671867256u, 898437006u, 1316824526u, 2640443682u, 1404000060u, 3276358491u, 4161289148u, 1102117255u, 1256660265u, 209840788u, 385024522u, 2368673317u, 323107512u, 3455934026u, 3731694261u, 3391583476u, 2939001717u, 1103408741u, 1083361420u, 1698019267u, 1565815683u, 3463127127u, 3731607982u, 697017152u, 734146234u, 3016440987u, 2640822923u, 468448749u, 400190664u, 1063137237u, 1360374355u, 4071057687u, 3077992194u, 1418755066u, 2114340252u, 507520129u, 2219575806u, 2032764621u, 2022031889u, 4206268338u, 3431678471u, 2027400693u, 2669084807u, 831934007u, 2741455826u, 2363266155u, 246856212u, 632436514u, 3515740889u, 2195525760u, 971767468u, 1276384569u, 3850605480u, 249929275u, 4103572387u, 173516974u, 1665191261u, 3656906633u, 323924265u, 2631672499u, 1675859583u, 3734620872u, 1388796197u, 4080779261u, 2337389174u, 2655227505u, 2543838574u, 3971410265u, 420679752u, 496026352u, 186764349u, 165231151u, 1627667691u, 2166211449u, 1762978544u, 1450698279u, 244833631u, 3701624698u, 3546129192u, 432955709u, 2578973523u, 1268347370u, 3585006787u, 3065734222u, 3840890096u, 2730792797u, 1190210715u, 1229058459u, 2004508211u, 2236271394u, 1163898177u, 317061964u, 4104512475u, 3981785820u, 2724518087u, 2447324937u, 612066133u, 3833016990u, 581709676u, 709654776u, 2295002741u, 1137254807u, 3385935788u, 1271908877u, 1575381586u, 3541074184u, 2662027818u, 578812846u, 695633467u, 3826065625u, 2352553817u, 1189926887u, 3949219588u, 1149364385u, 1140956216u, 2758597267u, 2208280441u, 2004286835u, 23811599u, 101605991u, 1718702543u, 2565308531u, 3504199076u, 1093913647u, 2943472056u, 208957281u, 93183733u, 26200246u, 2515020035u, 3147530638u, 1167877885u, 4173286473u, 3769999835u, 1316803433u, 2676177653u, 2249893478u, 2728386872u, 1289080741u, 108414488u, 911939596u, 3631792077u, 1201915048u, 443256488u, 695071951u, 2382437614u, 2026588982u, 2632432926u, 3752320434u, 2522821802u, 645589903u, 2852069592u, 1507054019u, 3446656352u, 352137468u, 3660766493u, 659827898u, 2694662642u, 2414681487u, 981423112u, 2969509231u, 1181913590u, 3283845787u, 1579289584u, 1736014821u, 1868176940u, 944873323u, 1817775084u, 2530710862u, 1627730672u, 66245778u, 675589177u, 926873064u, 1555989601u, 3241218062u, 2208111558u, 2091107069u, 2186880097u, 1922662991u, 3262102331u, 407680084u, 3225806537u, 1728234429u, 2815516280u, 1467728810u, 4113584515u, 2523822574u, 3907401252u, 1890262741u, 2857922946u, 9312338u, 1743264483u, 1703482351u, 1125583605u, 3170904314u, 738854734u, 1759558300u, 3184633114u, 1178715144u, 1960548124u, 1037689637u, 2750727957u, 3611858166u, 2361354361u, 467381126u, 2712884168u, 3111383860u, 3607434155u, 2140986302u, 1659435938u, 2870614947u, 483402068u, 3327353724u, 173441805u, 2892921505u, 322459867u, 342084856u, 476285132u, 2067116357u, 2987638716u, 3139221121u, 3648371306u, 2249325349u, 616697281u, 3744830951u, 1842700074u, 2971192596u, 3726408523u, 109869626u, 1487813247u, 885160389u, 1639902238u, 2438016503u, 2809256484u, 467766414u, 2269768842u, 3533241669u, 1626201598u, 3396738581u, 3323794334u, 1684642258u, 630214583u, 683085617u, 1860535308u, 1692841768u, 213970453u, 1620501115u, 2950013140u, 2600979684u, 3101788642u, 3940886529u, 1051539558u, 3444502811u, 686778540u, 2040757101u, 453012501u, 2726351009u, 2450885997u, 3954218997u, 2161221709u, 4273602338u, 315911737u, 3837424460u, 3983366596u, 1961106069u, 3092378093u, 3794692952u, 3936554087u, 3931909059u, 403814402u, 494561694u, 735241236u, 1852073032u, 1338882628u, 253049925u, 831176075u, 2962932411u, 2624182132u, 276217644u, 2654594797u, 3505958190u, 2643143479u, 2909381563u, 2812077621u, 2561795171u, 2649734514u, 1600038684u, 572123377u, 2903239907u, 3676987477u, 1946232532u, 4192788977u, 3352250323u, 2072925788u, 3243132465u, 2710328260u, 559282756u, 2496495841u, 1663691009u, 289654448u, 3463704651u, 892590470u, 1840421798u, 3271090533u, 4143706049u, 617178688u, 134482073u, 2269042691u, 3230232400u, 1073622572u, 1292832927u, 1514583707u, 343422799u, 2568797335u, 1703121731u, 4246032950u, 1125492680u, 840571992u, 2904558028u, 373108020u, 4002658231u, 3705499974u, 3080886235u, 381031087u, 516747576u, 1882498794u, 2655103969u, 1722338904u, 3506481279u, 954136253u, 2194640986u, 458904938u, 2230909876u, 1232295042u, 4026050644u, 4268594314u, 386790887u, 4165330488u, 2512717163u, 2939124594u, 2996196263u, 751292327u, 4220296919u, 1806647125u, 3424044432u, 529412756u, 2785560848u, 1277215461u, 1255562273u, 3182925185u, 2338361557u, 1825211939u, 3677840444u, 1711411618u, 1758593657u, 3511837694u, 1349462441u, 3428028389u, 830423639u, 916445791u, 1046053695u, 1356825518u, 2206311325u, 4024885318u, 761804059u, 1750908698u, 633217941u, 1238957827u, 4111074188u, 2364254471u, 4075930521u, 3987296879u, 3614538834u, 1681622248u, 233233044u, 1350971022u, 703752965u, 742511090u, 1319273373u, 1551556057u, 801526694u, 2261637738u, 3429584111u, 2522240856u, 4033776321u, 993802642u, 276019073u, 1802442104u, 1624529825u, 3688548619u, 1428574037u, 2759605887u, 714112429u, 2464378249u, 790901819u, 1071757684u, 2328808137u, 745645834u, 549566994u, 812008863u, 1682615503u, 1156655121u, 601964903u, 2388185358u, 2263159343u, 2449211150u, 1437661351u, 12615427u, 215564646u, 2484119735u, 2932155371u, 1762139369u, 158159499u, 2365521282u, 2277660798u, 3067589594u, 1443309319u, 3875571875u, 3148481662u, 4251148624u, 899549959u, 2383987797u, 4054743020u, 1617718571u, 764855974u, 3623170507u, 1294195985u, 2092418947u, 1392907274u, 259338315u, 2169056952u, 486370816u, 2608182505u, 58281361u, 2489916780u, 2571322701u, 3789374714u, 451393610u, 1906658293u, 1412587058u, 4038584782u, 3111791370u, 614696571u, 3167192919u, 3717660107u, 3195921972u, 3815660283u, 3041128023u, 570765305u, 3981085879u, 1107446894u, 51726088u, 293239046u, 4206823928u, 2266071917u, 1624419600u, 3390262152u, 177263260u, 2064461558u, 1929086034u, 1656019088u, 501074449u, 1715323410u, 3733759909u, 2474982900u, 2025499441u, 969019452u, 659526089u, 840640563u, 2500391789u, 2464587729u, 3777665909u, 3610207335u, 4206950686u, 663950423u, 3911031610u, 374291529u, 3602165615u, 3828747911u, 1422398845u, 2633015130u, 911010235u, 1250039282u, 3668786465u, 2146176295u, 2998145602u, 3953806681u, 861918991u, 3533426566u, 1195908145u, 1897435392u, 3160397475u, 4038157920u, 3159042522u, 1607720526u, 2381657876u, 3862186850u, 3469342849u, 3639212634u, 112769417u, 452688082u, 1414408784u, 1229308228u, 507438193u, 1310342177u, 3867043376u, 3493923869u, 4076344759u, 1432407149u, 3844851205u, 292787671u, 889906511u, 858447165u, 4280160501u, 1754833546u, 1022797317u, 141082305u, 1717313637u, 341442863u, 2982165294u, 2660069911u, 2284313116u, 3729297709u, 3404076394u, 3170976459u, 594201128u, 2041497718u, 1243196847u, 1266663238u, 2859272421u, 3185066266u, 3090105225u, 126778336u, 2792308627u, 2668313630u, 1239558284u, 3271595203u, 3721632713u, 408692953u, 136209149u, 1308802615u, 2102270171u, 3155640269u, 326440485u, 295730848u, 523452312u, 3849023707u, 3647301u, 591283519u, 3240559410u, 3618341580u, 1257535485u, 749043246u, 214257867u, 2969963854u, 2265255083u, 2433422659u, 3703613001u, 1868981396u, 219206218u, 1921827284u, 827842542u, 1269673531u, 1710834839u, 1027401811u, 3163026058u, 1902411060u, 3815930641u, 621420248u, 2054777317u, 4124947909u, 2353234036u, 1977996769u, 2808784096u, 3225046473u, 2931747545u, 3142843391u, 1659837986u, 1888420283u, 4259740486u, 2350930487u, 3413152075u, 56968219u, 192969628u, 1423057188u, 1444249660u, 171197140u, 937248230u, 4099400349u, 2399265778u, 1578088554u, 775063037u, 3858403452u, 4225434954u, 478205274u, 1845362180u, 308036862u, 2216561886u, 2390053622u, 1312984120u, 465471307u, 3916802888u, 1751063625u, 3071743500u, 3294521276u, 4183444410u, 3328792670u, 4051235372u, 938291851u, 3776732923u, 519625569u, 2466919130u, 979838570u, 2725879728u, 1317420913u, 1463872356u, 637221019u, 3745811724u, 1494600622u, 893750819u, 930858754u, 650342654u, 2192050103u, 3365807907u, 873848167u, 2720924319u, 1145370623u, 2760666947u, 2161896752u, 1105360170u, 2076071521u, 2063127636u, 3903444955u, 4210510508u, 1867287227u, 3901733700u, 1228642505u, 1554715107u, 1256194637u, 3463194748u, 2108350785u, 3137801541u, 1377619644u, 2043599410u, 3670507577u, 2409694355u, 578584004u, 1915114417u, 2964200468u, 3084637701u, 487846941u, 3464913449u, 851931544u, 4091230055u, 3804622813u, 4062654036u, 1956958041u, 3982899036u, 3060878573u, 1850342510u, 3229380710u, 2199978100u, 3449841444u, 3404506672u, 4172579909u, 2858341611u, 4201756291u, 866708640u, 2147611665u, 2927066921u, 981820178u, 4145753222u, 2926114981u, 3142973742u, 3211993392u, 665956u, 186208327u, 2578776459u, 1544585027u, 4147670018u, 3264346428u, 3529968586u, 2309075249u, 3880526621u, 2125072657u, 481117536u, 2544413573u, 2202704127u, 1672537106u, 1318470792u, 3554362612u, 3127591861u, 3015316471u, 2945509163u, 291484478u, 2591981327u, 3245148648u, 739576946u, 515232136u, 2261837125u, 1917651136u, 579070195u, 3597260689u, 49188367u, 267006895u, 4276877494u, 3617401212u, 2853129749u, 935399421u, 1080878326u, 3188786708u, 3498791570u, 2384965785u, 1857094951u, 3407819412u, 704533477u, 4082950861u, 2567290570u, 395265201u, 2047624633u, 2518905836u, 3372367611u, 801791416u, 1901227854u, 38637635u, 3474202199u, 2474398228u, 1480879307u, 2850068007u, 692791272u, 1196752290u, 1921623773u, 740690709u, 3711563566u, 3014897166u, 1153198973u, 2587583270u, 3871261165u, 1304143030u, 1562173300u, 2399579836u, 3387085571u, 3066436323u, 273753460u, 548762751u, 4066258498u, 509964679u, 3892230842u, 2594454158u, 2641210074u, 4000290307u, 197544729u, 1226784640u, 2052493941u, 2015636260u, 619774998u, 610310685u, 3315794687u, 2524554198u, 109352219u, 3966261588u, 2482511907u, 3321871424u, 2144425402u, 3701574588u, 2168304673u, 382053842u, 4264336703u, 1620184274u, 2591819932u, 4150402746u, 765308994u, 2759980202u, 4277805943u, 1345011665u, 27080389u, 350826709u, 2183825604u, 4075076920u, 3445501223u, 4190013503u, 587180938u, 214271696u, 2154236153u, 1586367270u, 815350360u, 1444414461u, 3464262453u, 3976631943u, 2834310035u, 447344574u, 3456943467u, 1857849941u, 3288069997u, 3622828139u, 3766385238u, 1019699309u, 3574414672u, 664756051u, 1488760916u, 3602182757u, 501971136u, 361544844u, 638366795u, 2663513669u, 2577492878u, 288332466u, 1438600995u, 1325679288u, 3124931681u, 317950919u, 2003481973u, 1680270394u, 3336913304u, 4046786960u, 3928470606u, 379294149u, 258217508u, 137055764u, 1536935606u, 2068904415u, 245653279u, 3279034418u, 2000767513u, 1483858296u, 661632107u, 2388498781u, 2717721443u, 3490673092u, 408205055u, 3671951051u, 422302660u, 3750077128u, 3487755911u, 2475111658u, 225226079u, 3266015962u, 4163085962u, 160505654u, 826502426u, 3108568799u, 235837591u, 1843748945u, 3398011821u, 488014602u, 1703998678u, 2501340486u, 2457941993u, 1583675704u, 3998234784u, 1823676750u, 1727161627u, 3026833773u, 906959134u, 2137574027u, 3944299473u, 3781089529u, 724146943u, 358776094u, 3525324801u, 185536569u, 1029340467u, 4177714978u, 1881106148u, 2149519719u, 3090610550u, 1595510459u, 4026033108u, 1758720811u, 3443479698u, 579449978u, 166684833u, 1954913591u, 2436559945u, 3713643208u, 2787556827u, 80124672u, 668793893u, 984001090u, 4172095298u, 1237562645u, 4246985448u, 2944124287u, 4066835174u, 1203297508u, 3814830417u, 1041598911u, 2553744546u, 1696041541u, 2537753781u, 3964937529u, 1275077003u, 396554334u, 1508985930u, 257718692u, 3339554426u, 2816402520u, 120951742u, 475928291u, 3224192115u, 2290598180u, 3010053799u, 232875814u, 340483867u, 518492981u, 1202103710u, 2360369545u, 2906122107u, 4156373681u, 475597219u, 1589253586u, 146259718u, 1926066295u, 479682976u, 1340900563u, 827889393u, 1244772727u, 1312527732u, 4198626021u, 3996441052u, 10644110u, 3247648552u, 1281332215u, 3860750678u, 3285923885u, 186872129u, 3865515020u, 3302355353u, 2477862790u, 3310744082u, 3841112686u, 677846076u, 2053589237u, 1932534256u, 559147278u, 1877030045u, 385124408u, 254461835u, 508013400u, 4278960989u, 316600986u, 3139554192u, 118560138u, 1206070571u, 946801128u, 1202200929u, 3533120670u, 2072176200u, 3754732210u, 2202753449u, 2497549341u, 1824188449u, 4096170263u, 1778678071u, 2755925781u, 1162425729u, 3525283794u, 2549672156u, 186047547u, 949616424u, 514250452u, 428000582u, 1402456747u, 3275087661u, 1662527311u, 1062266134u, 2896808207u, 546372435u, 426202384u, 2470040092u, 3679462914u, 2850980138u, 4246129126u, 15470179u, 414350056u, 3096151869u, 389632407u, 2047499061u, 378474270u, 4081137159u, 536430886u, 1728154601u, 698697206u, 1062097602u, 836724005u, 1142685433u, 3332408589u, 3512314929u, 2582057314u, 14591221u, 3331171678u, 1926729414u, 1869132451u, 2013918714u, 871594890u, 3319674255u, 1404734878u, 2348955092u, 2795656019u, 1375503625u, 1259278002u, 257464350u, 813387295u, 895153179u, 844238198u, 1634630496u, 3998472331u, 3344820330u, 602607720u, 3622762973u, 1362293693u, 3720441663u, 769877944u, 3615743708u, 2648039718u, 970534205u, 2056260250u, 2135791038u, 451217943u, 1814422094u, 2393651123u, 1701892116u, 909762509u, 1408803141u, 4126742002u, 1074833343u, 2157239058u, 3166377133u, 4238930216u, 563692261u, 934622773u, 1780917021u, 3698369962u, 2567120916u, 4099632335u, 278317364u, 699067013u, 1433276974u, 3412965834u, 776182569u, 2945101563u, 1901527490u, 3590591554u, 1104453414u, 1815882203u, 3901802352u, 2083417226u, 3151899284u, 244057543u, 3209024595u, 147951658u, 756739207u, 1235768209u, 3156017009u, 3193645212u, 1880049815u, 1295819147u, 1168515246u, 974065603u, 3058698171u, 5709523u, 1911494647u, 3913099549u, 3609249161u, 3867419584u, 1950266164u, 1036231561u, 2487793992u, 2691309339u, 2942155942u, 2965968254u, 1746424309u, 253966721u, 4244463819u, 2067463969u, 1950849308u, 1246571141u, 4097566328u, 346406741u, 2506944995u, 2759023005u, 4117530649u, 2724202928u, 2058774036u, 162803051u, 4227611518u, 3088016137u, 1658512262u, 1416465784u, 2137055388u, 878100347u, 2277478293u, 525092662u, 1741194555u, 1309123261u, 460520284u, 119434317u, 2016523652u, 1640172061u, 3804988800u, 540190186u, 790962267u, 1460908145u, 3688753525u, 3461703962u, 3039026826u, 578931852u, 1006670859u, 3481601471u, 1918534958u, 1859686764u, 4023948837u, 3920621011u, 2540003721u, 67137340u, 2043405341u, 3268848308u, 1306808385u, 3605706053u, 1623313713u, 660869119u, 2853351111u, 3475175842u, 2821734805u, 3814658188u, 3654921032u, 2472577430u, 754344802u, 4088246401u, 88411392u, 700117482u, 703548004u, 2245532518u, 2639673532u, 3977880118u, 50148058u, 931630340u, 4041558803u, 3949109103u, 2965310022u, 1968230113u, 1448979683u, 2858564441u, 1523429339u, 1452231187u, 2696376206u, 3594274238u, 1221549017u, 2397200653u, 1488063947u, 2905130063u, 199399599u, 4073133774u, 4237311111u, 3055565669u, 3367773316u, 3162354197u, 297828300u, 4122926713u, 2903038630u, 2506015605u, 2493069266u, 396227382u, 3064295038u, 389390920u, 1684789502u, 2022004674u, 1546447938u, 2342558675u, 3323380043u, 593016737u, 3277745628u, 2071469665u, 3550721728u, 2172088092u, 1279295579u, 4216165077u, 1510998944u, 4075672776u, 2930025022u, 2136492188u, 182691603u, 4038078968u, 1396096227u, 3273166256u, 2094934945u, 4099357359u, 1007544560u, 3699672923u, 2300884465u, 2980210279u, 4244552370u, 589833589u, 714003734u, 4002387247u, 3389813967u, 845344855u, 3827405748u, 1095009851u, 1096246435u, 195059445u, 390829018u, 45983343u, 2942709471u, 2338891311u, 1314753483u, 1040822690u, 3615731833u, 2047806006u, 203722163u, 439422620u, 2262897255u, 2481399711u, 2730149622u, 268361952u, 351807012u, 1796447121u, 3551647148u, 3863815581u, 3930491804u, 3040825682u, 3498148643u, 3103447131u, 292250033u, 226867327u, 3034518570u, 3275929931u, 3242711804u, 3226789931u, 2600170516u, 3264262736u, 497730864u, 3847393656u, 2138081132u, 156554468u, 2050395814u, 3341597363u, 3771202984u, 3623479970u, 3811066097u, 4180581721u, 2728037769u, 2759868955u, 121442518u, 3472315639u, 205237287u, 2850789567u, 2312554204u, 1182211478u, 38967328u, 3702438304u, 375884310u, 3165268977u, 983625816u, 2735905787u, 2508035244u, 3513180306u, 10812940u, 2299525101u, 1370593040u, 2901849677u, 1637452236u, 1505988434u, 1234543967u, 197861388u, 1930286607u, 1561122202u, 1215392833u, 3981188336u, 3849737971u, 868629879u, 2183787208u, 3332599237u, 966010177u, 1084918212u, 82969797u, 3808821963u, 1864232486u, 3366209990u, 751714288u, 2695039573u, 1097849769u, 3022976865u, 587638393u, 2744414517u, 63322775u, 770817695u, 2209918549u, 1635742189u, 2095921391u, 495753095u, 2352947823u, 882910281u, 3059789361u, 2202887209u, 2519930578u, 1983703178u, 525620646u, 3007446873u, 3466043628u, 969502396u, 2222572818u, 3631038137u, 3440085912u, 3544306054u, 2279011116u, 1361979741u, 247624876u, 1609426453u, 633820846u, 457170537u, 3189982065u, 313104052u, 1671772203u, 3987982914u, 3878607460u, 442784563u, 239669768u, 1186013783u, 1469875483u, 2717949819u, 720088221u, 3130619991u, 627890744u, 2164497000u, 2241323725u, 1539052750u, 4116364762u, 3447090944u, 2435636794u, 1034457706u, 2225396704u, 2039700441u, 2193560651u, 2759784453u, 2838663578u, 3925342473u, 4229223551u, 3059096898u, 3615459818u, 1983004688u, 907253649u, 1326210552u, 3579190630u, 3272911913u, 4131935105u, 1327722125u, 2908147995u, 4092513009u, 746274712u, 736869831u, 1497858220u, 487961967u, 2386169970u, 1439014353u, 2738069928u, 1944184985u, 3492078389u, 2809697569u, 3555856753u, 74229530u, 1188033126u, 1042117947u, 1505471861u, 1978689067u, 4284088321u, 1879582610u, 197373605u, 1581803397u, 2542952419u, 2458103082u, 2609274498u, 1208734497u, 3053599284u, 3356619347u, 2786163035u, 294958267u, 62146935u, 2950201268u, 382600974u, 2796353027u, 480450472u, 1731575026u, 4086256647u, 797880888u, 2653010568u, 2663080685u, 3860407534u, 2658068184u, 807060335u, 674881738u, 51791346u, 2375548938u, 2339108673u, 2765711021u, 2074225046u, 1909060248u, 20753244u, 2726236940u, 2902081023u, 2864855158u, 2811409260u, 845253867u, 3292451361u, 3033695434u, 3775963086u, 3602564352u, 4196643721u, 3060262852u, 1753216383u, 2691205345u, 21535303u, 3469036080u, 2125167827u, 3818146091u, 2837019400u, 2727529820u, 3494652317u, 1112114299u, 2598168998u, 1146515049u, 108198915u, 3736718166u, 2342983819u, 1756214915u, 39732867u, 1665876672u, 2145382992u, 821052743u, 2839251707u, 649422276u, 2893622878u, 3782158454u, 1964100944u, 553504817u, 921832272u, 2790668159u, 2937271603u, 296629342u, 3972341743u, 4122628545u, 564370865u, 595711954u, 1004248294u, 1452078904u, 4220574292u, 1346997234u, 1135155980u, 2436887773u, 3222929103u, 2962393409u, 2323344035u, 3165484739u, 1084131787u, 2525794560u, 1899607021u, 695377600u, 1997857469u, 88053015u, 3734708914u, 2495304031u, 1581633088u, 2043722547u, 4094560820u, 4226819750u, 3423672780u, 3994550009u, 3250795980u, 2099028017u, 985784650u, 535968328u, 3219077037u, 2978028186u, 292695848u, 3814517741u, 3820167765u, 200283462u, 2302587436u, 4179722693u, 2429319487u, 2443111044u, 3933774850u, 3981281444u, 847952093u, 411105399u, 125762624u, 299104240u, 191979292u, 4260457698u, 1517829698u, 3157507235u, 2949795084u, 4045869099u, 442379810u, 670507780u, 342615858u, 60683203u, 2084538822u, 417237724u, 2900476740u, 490611202u, 2335306135u, 3861053900u, 894868909u, 2241567518u, 109806941u, 1561361784u, 1267909589u, 3504175937u, 2873638693u, 2322187772u, 918019581u, 90375045u, 1322819651u, 4275087498u, 4210332957u, 3544888221u, 1627085930u, 740314301u, 312214225u, 2148631325u, 3839821879u, 1647939052u, 4048129244u, 4267208914u, 1216066417u, 3131565549u, 875267714u, 515920142u, 402925233u, 2985339508u, 1088037711u, 2396879732u, 2985692501u, 594266515u, 1245163848u, 3795178832u, 4101911396u, 633610523u, 2036387890u, 1643319818u, 2737035221u, 4186394095u, 299255052u, 2124154322u, 2903433416u, 2427607473u, 3406501268u, 1153584787u, 3808804282u, 3574542198u, 3691414869u, 1247035742u, 1840699692u, 1894792930u, 1111698354u, 4163650221u, 878895484u, 4275109574u, 3605165959u, 2769656456u, 1792478603u, 653761709u, 2922494638u, 3535305080u, 1050649815u, 1969236932u, 3145103665u, 3434066363u, 2651068462u, 2685752418u, 710376912u, 1840537674u, 3316779381u, 1484595551u, 51421505u, 2391514678u, 667590861u, 17876313u, 3534564971u, 3837535426u, 1602866621u, 1174807010u, 1015036918u, 3927229866u, 803183846u, 3496648295u, 4082962459u, 918191827u, 183989530u, 17394283u, 2479064643u, 1243428848u, 1373442572u, 353721777u, 1830492352u, 183135121u, 1501139126u, 4013748963u, 3859067783u, 2918339539u, 3932596121u, 3504272451u, 4175022285u, 1267953507u, 1659009980u, 1433962594u, 1519724836u, 1659795277u, 3631005750u, 4207376111u, 1604931964u, 3717646468u, 569940483u, 3230062768u, 2708673706u, 773344531u, 2911040214u, 1867341976u, 863824450u, 3947365482u, 1273604501u, 1420223013u, 2630908838u, 337462969u, 2093655521u, 678151284u, 3709558257u, 2045368751u, 2930065301u, 3599726355u, 474927981u, 2317150878u, 3736594619u, 2753555624u, 195271580u, 94274512u, 1709600363u, 1794400717u, 885551916u, 2795594734u, 3607248528u, 1835059061u, 2747843334u, 2328234907u, 1001035435u, 1693652345u, 235805936u, 2638138829u, 547153028u, 3599697801u, 991695015u, 2877234179u, 3383722389u, 3059481083u, 2627013253u, 3567440638u, 498287328u, 3600036397u, 2959299970u, 2755364832u, 199929461u, 2562732425u, 3937982401u, 861395241u, 2412532711u, 3435590095u, 2920201743u, 3661847978u, 3022949305u, 3219949338u, 2562973337u, 3773797507u, 2145098192u, 935077289u, 3667892744u, 124435112u, 2733153171u, 2336633071u, 3049114028u, 296015014u, 2751679747u, 2396349832u, 1496705403u, 3603954500u, 518868682u, 2578755152u, 736840699u, 1805957349u, 666330774u, 608986249u, 2472363853u, 3800278416u, 40896582u, 1680781511u, 2082409749u, 2249181642u, 2210280556u, 357432911u, 2329972169u, 2886165767u, 2427904608u, 956912295u, 971928712u, 3095355668u, 2911246641u, 482262902u, 60312911u, 1312365275u, 2013765306u, 1783734131u, 2522610297u, 3690325440u, 2709933595u, 1909940033u, 1442425499u, 1704357789u, 899484502u, 2742977966u, 1497525367u, 1583123174u, 1318029612u, 2564838921u, 3763856450u, 2514174710u, 198316421u, 265990530u, 1768395667u, 2314710286u, 1683671620u, 221036278u, 571751506u, 2779207683u, 1555945911u, 423155030u, 2047935335u, 1434018760u, 787022731u, 3056004199u, 2284689631u, 4137760392u, 2701080567u, 1756642125u, 3912131294u, 1201533467u, 3956594108u, 3526202936u, 519557376u, 3159661834u, 3756697023u, 1583510448u, 1886607524u, 709938394u, 2280781434u, 1612256833u, 53104508u, 2131060933u, 281397192u, 1455261348u, 244810324u, 2671976612u, 2156407609u, 3899123681u, 2484549899u, 4017599516u, 3837959347u, 2804179735u, 3994219050u, 2424320044u, 3037372381u, 1925993718u, 332392405u, 1177246587u, 4177876254u, 2845483154u, 1390491309u, 2938496931u, 1463164366u, 707836749u, 2768827532u, 568741807u, 869407265u, 1280965775u, 1172620039u, 478972532u, 2987000536u, 3805122215u, 1468413102u, 543917782u, 3394277116u, 4044202117u, 1025405644u, 1707224750u, 1864686183u, 2240605571u, 1290357116u, 4101884836u, 1991992160u, 1996968929u, 3463552824u, 1219717543u, 502934926u, 3633464291u, 1725958720u, 870640282u, 41924200u, 2386735502u, 3737713709u, 2920533520u, 416930056u, 3319442073u, 3325200926u, 600730999u, 2558036132u, 3509898830u, 601814492u, 3250106394u, 768972570u, 1825868704u, 100617135u, 3218264529u, 1463864280u, 2589827818u, 2671592874u, 2112587743u, 1139666942u, 1054938100u, 3705456107u, 3529994423u, 2120736180u, 547125328u, 658109267u, 2980455600u, 636600577u, 2182547042u, 1783330846u, 2735761548u, 299718758u, 2517033811u, 3090526543u, 4228910553u, 1659076526u, 1860771466u, 2936600089u, 3509421045u, 2979075421u, 3031364810u, 3195690080u, 3566117579u, 1405740019u, 2816510332u, 3007319793u, 643248787u, 4020853943u, 171580820u, 300129979u, 3969161736u, 4289646346u, 3745142316u, 3090885346u, 584557670u, 634680948u, 3799101749u, 2430972807u, 2748166655u, 15868433u, 735399278u, 2677365711u, 3115162351u, 2206458278u, 1126454368u, 3266341386u, 1132674226u, 2751051383u, 553029961u, 2593118860u, 1053466729u, 3597461159u, 3933828494u, 663458002u, 2447294939u, 2927798739u, 492877382u, 4236233329u, 2763528638u, 195002750u, 986046518u, 639830937u, 1030191024u, 3193064705u, 1947250508u, 370040359u, 3154891784u, 1054651402u, 929718775u, 3784950826u, 4235202677u, 3848447182u, 1300324412u, 1614380154u, 793587525u, 1275759162u, 1938255782u, 3962698057u, 3322334872u, 4097609677u, 2040562167u, 3963663159u, 824929530u, 2196910585u, 3023064302u, 2785667685u, 27701234u, 3002859705u, 3296503982u, 317114949u, 1695591138u, 2139548806u, 965321175u, 3726861363u, 3331730566u, 1879689475u, 3480440163u, 1300921036u, 1949052871u, 3348542305u, 2126207026u, 2571967031u, 1969124223u, 1104069332u, 2844130133u, 2713773580u, 110283227u, 2481609072u, 581450358u, 1141429464u, 573767071u, 628702638u, 1226175933u, 1496995439u, 1105107520u, 3790323315u, 2629122303u, 1138385203u, 2081547238u, 4128122826u, 547119985u, 1760069398u, 341033734u, 2326900356u, 3647703883u, 3295713467u, 325211857u, 247163411u, 3534750987u, 1351316687u, 3425408611u, 1131435045u, 56237162u, 1182140676u, 2841516219u, 2036405666u, 3011909393u, 181354475u, 4099399022u, 2263280522u, 3301402229u, 171474648u, 671798090u, 1018093993u, 4168485423u, 1275944499u, 823679180u, 4200934132u, 1111934299u, 3199618087u, 3621066247u, 3422907952u, 1960186230u, 327155934u, 2648626799u, 3085590530u, 3118851840u, 3791862980u, 2023795762u, 9700208u, 2361138067u, 4268467660u, 3704256002u, 2875035367u, 2027303960u, 3457589647u, 885044336u, 2662844726u, 3072057497u, 4210718634u, 1713969286u, 1983796584u, 162684133u, 1680075615u, 1605451006u, 213476914u, 633139757u, 3749313632u, 1967155290u, 256432133u, 409228965u, 3211834734u, 2708956481u, 1130100839u, 2725640478u, 945525536u, 2527400967u, 835878402u, 3714026506u, 3349608339u, 3265722245u, 387938828u, 1661608822u, 1945317790u, 63762452u, 4267518590u, 2829827589u, 803587489u, 2011172466u, 3058409291u, 2493493652u, 2358944923u, 717080147u, 3264332285u, 4198730664u, 1575482429u, 318381561u, 665649665u, 4090251887u, 927143108u, 2862607660u, 1760435706u, 1877432652u, 1771873366u, 1874464602u, 1167059997u, 3020490408u, 1074066123u, 1379644398u, 126243592u, 3195614646u, 379454934u, 3916240656u, 2888173309u, 3691637364u, 3074570305u, 234168674u, 984718484u, 2323634090u, 2957625706u, 3571063313u, 3046748310u, 939117845u, 2447953439u, 3607149135u, 2109921668u, 1582617334u, 2947121532u, 2088820125u, 1311220491u, 1306760315u, 1526878608u, 3921204841u, 1464365659u, 4088339779u, 3839989510u, 2702193424u, 3033074280u, 3344899646u, 2784651874u, 1276498418u, 3085361132u, 3355531897u, 4084951190u, 1501726664u, 1175048372u, 404968257u, 1222303786u, 1754944111u, 2544068457u, 3514209187u, 2271843748u, 1475268510u, 3989245286u, 1371106318u, 129716112u, 3544402121u, 4044152139u, 2679423850u, 2290541585u, 3199575633u, 744603621u, 458754085u, 621232718u, 3523809203u, 3640321157u, 4159876693u, 3292542003u, 2614643405u, 2265268131u, 2175536109u, 2364640379u, 2464849350u, 788537884u, 947581145u, 1865279252u, 2550878652u, 287140567u, 3765319030u, 3181972603u, 1037202683u, 574960613u, 723287358u, 2264164901u, 1548449675u, 1992765225u, 1943406983u, 4007764606u, 2734816626u, 1133263828u, 4094045449u, 330380303u, 1351242405u, 2139587057u, 1170408100u, 2151621933u, 3076660584u, 577955961u, 2930728868u, 2191524223u, 990695029u, 3332539164u, 2415265923u, 402298882u, 4102255429u, 2991709119u, 2498622844u, 4105956877u, 183958547u, 653603897u, 1809232009u, 1453424169u, 1640850437u, 2483305045u, 3842897193u, 2820742683u, 675242394u, 234672814u, 1219775413u, 2856515609u, 488790066u, 2475713844u, 827998856u, 772322586u, 143954203u, 1728063401u, 2999097055u, 1258585961u, 139439149u, 3785937564u, 4250215304u, 1921492716u, 2854837455u, 3335291046u, 1117431624u, 1803714835u, 1365730596u, 176474541u, 1195819223u, 1905686043u, 2606575318u, 644255847u, 2626902930u, 1696029855u, 2469470787u, 3140744731u, 3124183743u, 681584615u, 3124853055u, 521289913u, 3037640139u, 694512606u, 4196362636u, 3221960124u, 1809151323u, 3104570936u, 3457186537u, 3230064790u, 949139600u, 2794693823u, 3605652340u, 2682195244u, 1972126161u, 1304624176u, 2917192451u, 3413390736u, 1272630300u, 1614264576u, 3114707895u, 2828194783u, 2737493590u, 1438642720u, 398059486u, 2046323248u, 3858845675u, 753870998u, 3263763629u, 3560607974u, 97620978u, 2751877635u, 1508838838u, 4235953225u, 889039423u, 2749896870u, 1058740777u, 186726216u, 1997325597u, 673398419u, 4054809100u, 3573007303u, 864341058u, 2870750111u, 1875827492u, 2133845783u, 1989074132u, 2286405673u, 1834455764u, 2866334629u, 2924929701u, 1437706889u, 3399134825u, 2989971535u, 360902372u, 1167328961u, 13923096u, 4046233402u, 4170341145u, 1168846931u, 4262408566u, 4159192264u, 1382737528u, 1362165181u, 134110655u, 1886221955u, 2952826762u, 3449176844u, 1662266626u, 1122229274u, 4041152892u, 3130892823u, 598378225u, 1217727498u, 1225176566u, 133190688u, 3323826221u, 547888910u, 1668299591u, 504078819u, 2524882623u, 2749626450u, 2984267770u, 1427332581u, 1374197092u, 2776391902u, 2950543940u, 3597584186u, 1694883952u, 3690380608u, 4219862249u, 3194989758u, 45833324u, 2290428961u, 1194523277u, 2080305090u, 727617120u, 1871861852u, 2852766462u, 1377621335u, 4205311198u, 639785910u, 283107621u, 2955818106u, 2342915166u, 553292194u, 1923106993u, 2037851645u, 2977117774u, 2451042230u, 2414973112u, 684116259u, 2194888935u, 1353049451u, 1794293340u, 2470657725u, 1586299181u, 2930169238u, 1014804130u, 2325649911u, 129021041u, 1332147710u, 1594434776u, 674914589u, 435079932u, 3519940708u, 2142186807u, 358685975u, 901678227u, 2225668560u, 1990950041u, 2073465681u, 3692487862u, 1345669515u, 4269341801u, 3287189638u, 557048773u, 975524480u, 1180641558u, 2197478024u, 100938323u, 2993700884u, 3977138677u, 392899815u, 1337314430u, 2115757123u, 1596565812u, 2447096231u, 1875036431u, 2756857064u, 4245104177u, 2570394607u, 1863785892u, 2677793010u, 1725064153u, 1458810935u, 1917847573u, 4193832098u, 643623708u, 3495798825u, 710289455u, 761817339u, 3299308563u, 671529304u, 230310926u, 1510576771u, 3374303917u, 1704698596u, 1640684325u, 822663837u, 2547915455u, 4069104144u, 2430564715u, 2053841090u, 986319080u, 2210107029u, 412064727u, 2783613259u, 279039381u, 499244831u, 99653989u, 2628011239u, 3746387564u, 1339491367u, 1544434309u, 582419827u, 399172998u, 2292817995u, 3518067082u, 1978161243u, 2134178320u, 50584408u, 1639288186u, 3729935645u, 3394981086u, 3970214462u, 2266863843u, 2098019031u, 3498932754u, 2425450669u, 3011644541u, 2154834295u, 1566569217u, 3550818423u, 3342256364u, 2855763981u, 3737540430u, 1191621881u, 3840446275u, 1890042079u, 672062740u, 2015167539u, 1224827706u, 163630564u, 1492072834u, 2802873157u, 1707472572u, 3763790259u, 1331259087u, 1950565242u, 3384631538u, 1117904786u, 856680687u, 4110420132u, 2624530728u, 3940769225u, 1495633832u, 3665314334u, 706218959u, 2446541599u, 3767005930u, 1761813284u, 793760371u, 3843098778u, 1378121808u, 2531610112u, 4281885086u, 722781736u, 3023014411u, 2799556405u, 2819357928u, 3141278046u, 2441527005u, 4151479894u, 1896941819u, 596201422u, 2064424897u, 2126371058u, 3296815812u, 4010070378u, 259579352u, 2113384079u, 1090898587u, 3505987476u, 678816428u, 1752720171u, 557092635u, 204016079u, 3300920851u, 2972890266u, 2447503403u, 3824050309u, 1206418589u, 40226916u, 1013674257u, 2994695015u, 2420661479u, 617755021u, 761607669u, 1276642071u, 1207975455u, 371458107u, 526906162u, 1617712095u, 583234254u, 3855581398u, 2661783995u, 3557719699u, 492761818u, 633313678u, 1392788289u, 2926435278u, 3269052534u, 2927639451u, 3355075155u, 4140349814u, 4017839768u, 273149017u, 4129597307u, 159613376u, 2525558019u, 2853612230u, 1277913653u, 2906920607u, 245739105u, 99670052u, 2124723003u, 1161668924u, 3249459940u, 4027543729u, 249730846u, 2654735532u, 1775757814u, 2799175066u, 994058658u, 3128508225u, 4060936510u, 1764669280u, 1591440959u, 3594681350u, 824721464u, 225498530u, 2961877671u, 2164367433u, 2227307590u, 3668888759u, 778727920u, 4021230187u, 1989921618u, 4074077089u, 1773124827u, 1248866715u, 1571786792u, 3651230686u, 1590808960u, 1798833201u, 3171851922u, 1907257896u, 422163767u, 771204939u, 1569344449u, 3620107018u, 312184228u, 2667690438u, 2736728328u, 3351679326u, 4293266120u, 1479297505u, 1321697177u, 1476450712u, 1821458355u, 510639697u, 3353685695u, 3223862600u, 1065307464u, 3396619366u, 2438080414u, 722925129u, 3029250790u, 3723401561u, 325572601u, 3630972120u, 385035816u, 2107583779u, 3204626616u, 100167064u, 3021789383u, 3958838301u, 863200373u, 1536140033u, 1653480108u, 3275112869u, 3452491352u, 830675654u, 1927345594u, 2721579912u, 3629599505u, 892928392u, 1071240868u, 251251858u, 196891116u, 3491476074u, 899382703u, 3890183726u, 3826018294u, 1017648853u, 920309298u, 3340661250u, 2612512342u, 2811793941u, 4174781029u, 3506353467u, 2033190700u, 3373457460u, 2339237219u, 1020418269u, 3590499880u, 3692832637u, 3566030303u, 1832595957u, 2775942935u, 58937028u, 226274185u, 2552664048u, 208605615u, 2633014230u, 3004371310u, 743686731u, 2417265339u, 3267972504u, 2486843234u, 1371501517u, 1968339331u, 3795872153u, 484975515u, 1740963751u, 890579912u, 399537152u, 3425765123u, 36545252u, 1700278613u, 2071323863u, 2207555149u, 3425290523u, 26019342u, 1529855572u, 2783751810u, 2802986929u, 3415140068u, 1064923916u, 3314992217u, 85471931u, 3509335678u, 3056191779u, 1825414916u, 1273785748u, 1884000304u, 2179774775u, 812453409u, 3224911175u, 3058589832u, 2859786012u, 2418387021u, 3114589689u, 2615992905u, 4042607554u, 970734203u, 3573160036u, 2692623241u, 1997039864u, 847852728u, 2229073638u, 74712714u, 1252676139u, 2628109988u, 2504938772u, 1379597940u, 2056368055u, 2089953286u, 1811579802u, 415412431u, 1439907673u, 1313375505u, 4204976878u, 1700729450u, 1039803553u, 2234612811u, 1824366910u, 2738413467u, 2205109633u, 1250436225u, 2132231554u, 3458837279u, 598753273u, 2368403394u, 4021049970u, 1394468059u, 1917980928u, 2513390407u, 2845111052u, 112183242u, 2065736285u, 3374680080u, 2630858879u, 2493197297u, 857666598u, 239366099u, 396468925u, 2165301993u, 2566000373u, 3177083531u, 1241714532u, 4138061872u, 2894145478u, 1129982759u, 1308535112u, 192836408u, 3902463321u, 21115860u, 2852921750u, 133647041u, 2764366837u, 1745066212u, 4175089945u, 626870811u, 1145341095u, 2949286171u, 875760879u, 1701610962u, 2050177321u, 3255313724u, 579430573u, 2941018813u, 1643825778u, 1448244108u, 1264534555u, 3064122081u, 1018367855u, 74340227u, 2032257813u, 3231709827u, 2162359926u, 3883904895u, 1769910445u, 2646114017u, 1568370967u, 3688753437u, 2727243902u, 2762786309u, 736986713u, 4164267736u, 2275640205u, 3502195760u, 2422971628u, 1314654948u, 231264130u, 2622060886u, 1428226261u, 1895991720u, 3901143259u, 21840777u, 1626372171u, 3100053354u, 1887939103u, 953797637u, 2090256210u, 1038111897u, 870472499u, 1782057015u, 881883769u, 2252280146u, 539294114u, 1255572216u, 2539098155u, 1593341126u, 3426128314u, 2067868398u, 3497890577u, 734480408u, 3561086192u, 2482993071u, 28230985u, 3952654161u, 2386376929u, 3187237308u, 1027326004u, 1322417976u, 674246931u, 2567828541u, 462810786u, 3906345343u, 2679088468u, 1635438811u, 917859212u, 397746780u, 2991343807u, 2242932293u, 3257743007u, 1536536942u, 2310652354u, 3858234926u, 1785883731u, 4148952914u, 542852434u, 405520301u, 1356469089u, 2662672540u, 2774250057u, 1100086288u, 3006372138u, 1239397222u, 1008026014u, 1943675912u, 1446208466u, 2821271137u, 2469856346u, 1735560439u, 306160955u, 1604643170u, 2628512252u, 1464887538u, 4040683764u, 1699601332u, 2569212800u, 3373761230u, 2970178404u, 394939247u, 1969326589u, 3641297762u, 3552329785u, 3494204604u, 2533477003u, 839404457u, 2837066589u, 1887770399u, 3963240603u, 1566589133u, 3277605804u, 3366293223u, 2503723792u, 2105674080u, 2170235408u, 4130642859u, 2899266769u, 1268252521u, 4054726046u, 1799410781u, 1691559077u, 2708694364u, 2508525360u, 4076845476u, 1933402539u, 106704659u, 3789369987u, 3771235034u, 520734008u, 2442493189u, 3815388346u, 2027438978u, 1095008152u, 590458232u, 98793519u, 1146786523u, 156665803u, 2792356386u, 2047668331u, 1210331595u, 2616724516u, 1009701537u, 697639289u, 1367514263u, 1077777630u, 3172655958u, 3111472002u, 3943877061u, 3567041390u, 1507343754u, 1349917753u, 2183327131u, 1308313591u, 1986589932u, 2085617066u, 4009147247u, 2968668381u, 3551135214u, 892982226u, 862813360u, 3985060019u, 1376926050u, 3024188003u, 949735999u, 2871900054u, 3171468848u, 576549665u, 2823667892u, 988046782u, 2391409204u, 1713668465u, 1020006796u, 2118242357u, 2201459024u, 1317303980u, 1749974557u, 632277769u, 3688223773u, 3145962284u, 262063403u, 2139143645u, 3099046811u, 2787373021u, 529996562u, 1510774569u, 1310986691u, 1510343925u, 1536308645u, 2630193557u, 1953926582u, 2246912376u, 3768067684u, 300316896u, 1802303731u, 1270975835u, 3884467171u, 497161489u, 2097346700u, 14945728u, 2290965917u, 3689541248u, 3254637316u, 3907317116u, 2862282616u, 4040733349u, 37537367u, 2387383048u, 395862630u, 2778708620u, 3411960647u, 2656086542u, 1787782087u, 4270883693u, 649699601u, 1274984918u, 3247080139u, 2726606914u, 101994024u, 2381680152u, 2496887912u, 1438931885u, 1972814463u, 3304990985u, 1411408562u, 3639691527u, 2127645603u, 1249273999u, 4042725697u, 3194015825u, 4004654193u, 564908550u, 2868688439u, 2039450632u, 1332535630u, 2602944856u, 1924842299u, 971814105u, 834403437u, 3193316525u, 1644914174u, 863939595u, 4014965922u, 3805794715u, 634057055u, 3608454301u, 3289222059u, 620808484u, 2329157819u, 1684810552u, 3258379622u, 1645866960u, 2399432486u, 3343530218u, 4263505887u, 722741832u, 3800010203u, 658988677u, 1484073050u, 3101531846u, 3874976772u, 4206597126u, 1848102857u, 3193138690u, 983512797u, 391404518u, 4027880681u, 1963064961u, }; int main(int argc, char* argv[]) { volatile double dummy_double; volatile unsigned long dummy_long; volatile unsigned long long dummy_longlong; mt_prng rng; static long timing_loops = TIMING_LOOPS; /* * If the user has given a number of timing loops, reset the loop count. */ if (argc > 1) timing_loops = atol(argv[1]) * TIMING_LOOP_BASE; /* * Compare the generated values against corresponding numbers from * Matsumoto and Nishimura's own generator, to make sure we're * doing the calculation correctly. */ cout << "Validity test..."; rng.seed32(4357); ofstream save("mtccsave"); save << rng << '\n'; save.close(); rng.seed32(1); ifstream restore("mtccsave"); restore >> rng; restore.close(); unlink("mtccsave"); for (unsigned long i = 0; i < sizeof correct_values / sizeof correct_values[0]; i++) { unsigned long random_value = rng.lrand(); if (random_value != correct_values[i]) { cerr << "Failure at value " << i << ": expected " << correct_values[i] << ", got " << random_value << '\n'; return 1; } } cout << "passed.\n"; /* * Timing tests. */ struct rusage then; cout << timing_loops << " longs took "; getrusage(RUSAGE_SELF, &then); unsigned long random_value = 0; for (long i = 0; i < timing_loops; i++) random_value += rng.lrand(); report_timing(timing_loops, &then); dummy_long = random_value; unsigned long long longlong_value = 0; cout << timing_loops << " long longs took "; getrusage(RUSAGE_SELF, &then); for (long i = 0; i < timing_loops; i++) longlong_value += rng.llrand(); report_timing(timing_loops, &then); dummy_longlong = longlong_value; double double_value = 0.0; cout << timing_loops << " fast doubles took "; getrusage(RUSAGE_SELF, &then); for (long i = 0; i < timing_loops; i++) double_value += rng.drand(); report_timing(timing_loops, &then); cout << timing_loops << " long doubles took "; getrusage(RUSAGE_SELF, &then); for (long i = 0; i < timing_loops; i++) double_value += rng.ldrand(); report_timing(timing_loops, &then); cout << timing_loops << " call doubles took "; getrusage(RUSAGE_SELF, &then); for (long i = 0; i < timing_loops; i++) double_value += rng(); report_timing(timing_loops, &then); dummy_double = double_value; return 0; } static void report_timing( long loops, /* Number of loops that were done */ struct rusage * then) /* Time test started */ { long diff; /* Difference in times */ long microdiff; /* Microsecond part of difference */ struct rusage now; /* Time test ended */ double secs; /* Actual seconds needed */ getrusage(RUSAGE_SELF, &now); diff = now.ru_utime.tv_sec - then->ru_utime.tv_sec; microdiff = now.ru_utime.tv_usec - then->ru_utime.tv_usec; if (microdiff < 0) { diff--; microdiff += 1000000; } secs = diff + (microdiff / 1000000.0); cout << setw(3) << diff << "." << setw(6) << setprecision(6) << microdiff; cout << setw(0) << setprecision(0) << " seconds (" << (long)(loops / secs) << "/sec).\n"; }
74,380
61.610269
78
cc
filebench
filebench-master/cvars/mtwist/mttest.c
#ifndef lint #ifdef __GNUC__ #define ATTRIBUTE(attrs) __attribute__(attrs) #else #define ATTRIBUTE(attrs) #endif static char Rcs_Id[] ATTRIBUTE((used)) = "$Id: mttest.c,v 1.16 2013-01-05 01:18:52-08 geoff Exp $"; #endif /* * Test the Mersenne Twister PRNG * * $Log: mttest.c,v $ * Revision 1.16 2013-01-05 01:18:52-08 geoff * Fix a lot of compiler warnings. * * Revision 1.15 2012-12-30 16:24:49-08 geoff * Use gcc attributes to suppress warnings on Rcs_Id. Add tests for seed * functions. * * Revision 1.14 2010-06-24 01:53:58-07 geoff * Switch to using types and formats from inttypes.h. * * Revision 1.13 2010-06-24 00:29:38-07 geoff * Define the correct values as being explicitly 32 bits in size. * * Revision 1.12 2005-11-11 00:21:48-08 geoff * When timing, accumulate results in a temporary to make sure that the * compiler doesn't optimize all the code out of the test loops due to * inlining and discovering unused variables. * * Revision 1.11 2003/09/11 05:55:19 geoff * Get rid of some minor compiler warnings. * * Revision 1.10 2002/10/30 07:39:53 geoff * Update the correct-value table to reflect M&N's new seeding algorithm, * and the code to use it. * * Revision 1.9 2001/06/18 05:40:11 geoff * Do 300 million timing loops by default. * * Revision 1.8 2001/06/14 10:26:59 geoff * Test taking pointers to functions. * * Revision 1.7 2001/06/14 10:10:38 geoff * Report RNs generated per second. Add some simple testing of state * saving and restoration. * * Revision 1.6 2001/04/23 09:19:03 geoff * Expand the validity test to 5000 numbers * * Revision 1.5 2001/04/23 08:36:42 geoff * Fix a misplaced declaration * * Revision 1.4 2001/04/09 08:44:59 geoff * Go from 1000 test values to 5000, and format them slightly more * neatly. Get rid of a number of warnings. * * Revision 1.3 2001/04/07 23:09:38 geoff * Accept an argument giving the number of millions of PRN's to generate * in the timing loops (default 10 million). * * Revision 1.2 2001/04/07 22:21:41 geoff * Add timing tests. * * Revision 1.1 2001/04/07 09:44:16 geoff * Initial revision * */ #include "mtwist.h" #include <inttypes.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/time.h> int main(int argc, char * argv[]); static void report_timing(unsigned long loops, struct rusage * then); static void report_clock_timing(struct timeval * then); /* * Base unit for timing loops, so the caller can think in millions. */ #define TIMING_LOOP_BASE 1000000 /* * Default number of timing loops to do */ #define TIMING_LOOPS (300 * TIMING_LOOP_BASE) /* * The following table contains values that were generated by Matsumoto and * Nishimura's C program for the Mersenne Twist algorithm, using the * default seed of 4357. These values are presumed to be correct. The * test program compares the values generated by this implementation with * the reference values to ensure that the generator has been implemented * correctly. */ static uint32_t correct_values[] = { 3499211612u, 581869302u, 3890346734u, 3586334585u, 545404204u, 4161255391u, 3922919429u, 949333985u, 2715962298u, 1323567403u, 418932835u, 2350294565u, 1196140740u, 809094426u, 2348838239u, 4264392720u, 4112460519u, 4279768804u, 4144164697u, 4156218106u, 676943009u, 3117454609u, 4168664243u, 4213834039u, 4111000746u, 471852626u, 2084672536u, 3427838553u, 3437178460u, 1275731771u, 609397212u, 20544909u, 1811450929u, 483031418u, 3933054126u, 2747762695u, 3402504553u, 3772830893u, 4120988587u, 2163214728u, 2816384844u, 3427077306u, 153380495u, 1551745920u, 3646982597u, 910208076u, 4011470445u, 2926416934u, 2915145307u, 1712568902u, 3254469058u, 3181055693u, 3191729660u, 2039073006u, 1684602222u, 1812852786u, 2815256116u, 746745227u, 735241234u, 1296707006u, 3032444839u, 3424291161u, 136721026u, 1359573808u, 1189375152u, 3747053250u, 198304612u, 640439652u, 417177801u, 4269491673u, 3536724425u, 3530047642u, 2984266209u, 537655879u, 1361931891u, 3280281326u, 4081172609u, 2107063880u, 147944788u, 2850164008u, 1884392678u, 540721923u, 1638781099u, 902841100u, 3287869586u, 219972873u, 3415357582u, 156513983u, 802611720u, 1755486969u, 2103522059u, 1967048444u, 1913778154u, 2094092595u, 2775893247u, 3410096536u, 3046698742u, 3955127111u, 3241354600u, 3468319344u, 1185518681u, 3031277329u, 2919300778u, 12105075u, 2813624502u, 3052449900u, 698412071u, 2765791248u, 511091141u, 1958646067u, 2140457296u, 3323948758u, 4122068897u, 2464257528u, 1461945556u, 3765644424u, 2513705832u, 3471087299u, 961264978u, 76338300u, 3226667454u, 3527224675u, 1095625157u, 3525484323u, 2173068963u, 4037587209u, 3002511655u, 1772389185u, 3826400342u, 1817480335u, 4120125281u, 2495189930u, 2350272820u, 678852156u, 595387438u, 3271610651u, 641212874u, 988512770u, 1105989508u, 3477783405u, 3610853094u, 4245667946u, 1092133642u, 1427854500u, 3497326703u, 1287767370u, 1045931779u, 58150106u, 3991156885u, 933029415u, 1503168825u, 3897101788u, 844370145u, 3644141418u, 1078396938u, 4101769245u, 2645891717u, 3345340191u, 2032760103u, 4241106803u, 1510366103u, 290319951u, 3568381791u, 3408475658u, 2513690134u, 2553373352u, 2361044915u, 3147346559u, 3939316793u, 2986002498u, 1227669233u, 2919803768u, 3252150224u, 1685003584u, 3237241796u, 2411870849u, 1634002467u, 893645500u, 2438775379u, 2265043167u, 325791709u, 1736062366u, 231714000u, 1515103006u, 2279758133u, 2546159170u, 3346497776u, 1530490810u, 4011545318u, 4144499009u, 557942923u, 663307952u, 2443079012u, 1696117849u, 2016017442u, 1663423246u, 51119001u, 3122246755u, 1447930741u, 1668894615u, 696567687u, 3983551422u, 3411426125u, 1873110678u, 1336658413u, 3705174600u, 2270032533u, 2664425968u, 711455903u, 513451233u, 2585492744u, 2027039028u, 1129453058u, 1461232481u, 2809248324u, 2275654012u, 2960153730u, 3075629128u, 3213286615u, 4245057188u, 1935061435u, 3094495853u, 360010077u, 3919490483u, 983448591u, 2171099548u, 3922754098u, 2397746050u, 654458600u, 2161184684u, 3546856898u, 1986311591u, 2312163142u, 2347594600u, 4278366025u, 1922360368u, 335761339u, 3669839044u, 1901288696u, 2595154464u, 458070173u, 2141230976u, 4131320786u, 4208748424u, 19903848u, 147391738u, 3328215103u, 4196191786u, 3510290616u, 1559873971u, 3731015357u, 2918514861u, 362649214u, 1487061100u, 1717053387u, 3675955720u, 1116134897u, 193529268u, 3436267940u, 2835191639u, 1852908272u, 3220971953u, 3911201640u, 571213604u, 781027019u, 4219206494u, 1133024903u, 409547355u, 625085180u, 1214072539u, 584409985u, 3445042528u, 3733581611u, 333104904u, 2489812253u, 2694595213u, 2361631596u, 34763086u, 622576118u, 2921810672u, 3663740744u, 2293225236u, 2671706445u, 1884059696u, 1507329019u, 857065948u, 2204390003u, 592711182u, 1725752375u, 1642107460u, 326274448u, 3274574484u, 1030432041u, 173822100u, 529650788u, 1086437636u, 789877945u, 2167974914u, 1030588245u, 3533061365u, 1792148406u, 4216468704u, 213264131u, 3536714075u, 3877136173u, 1296338417u, 4057830103u, 205919137u, 2108245233u, 1064497347u, 2101324080u, 2336703164u, 1450493809u, 3812754708u, 3865701845u, 1476779561u, 1585902852u, 142887412u, 477612192u, 699530444u, 3351157089u, 3768249319u, 1673915577u, 903239649u, 1038056164u, 1171465372u, 1734789440u, 2115022236u, 414269055u, 959581346u, 566820984u, 2105828892u, 4046076449u, 4101450561u, 4106566571u, 2800184123u, 2470502098u, 3253453343u, 256751188u, 1869365987u, 1008372035u, 2374606708u, 1516804538u, 228288551u, 3527001547u, 1385173098u, 66157275u, 1739381798u, 184785808u, 3901692666u, 725806641u, 3475217997u, 2787929747u, 1109372433u, 3142723729u, 557686578u, 2782047723u, 2118822689u, 1936702581u, 1625646963u, 2349385293u, 3085804937u, 1272688179u, 1236112995u, 3198431244u, 2677635414u, 811555596u, 3486972196u, 2949678043u, 1342211552u, 788174404u, 1656614077u, 1582629285u, 1477167035u, 2687011245u, 3503701453u, 3351051324u, 2874557775u, 348432514u, 1629591495u, 3991682351u, 1969229192u, 3331660584u, 1304012077u, 2090754125u, 3910846836u, 1871998370u, 2098597104u, 1918921592u, 3246092887u, 1315760974u, 464122393u, 2184028058u, 1690455542u, 2193747147u, 3737423698u, 3511684278u, 1549884962u, 3413774919u, 3938991454u, 2767325310u, 2335626851u, 1626114941u, 601913200u, 3485711542u, 858447440u, 2288468476u, 4075602213u, 1506361431u, 4252489875u, 4032981007u, 1031118352u, 3762145731u, 70955369u, 2362903502u, 1669089455u, 2673510137u, 3348740333u, 2521337794u, 2047144929u, 892246357u, 2319875070u, 1293843163u, 79245769u, 2022600352u, 3866257397u, 989939126u, 835351312u, 3626278636u, 3805332945u, 836506264u, 1895040349u, 970326679u, 634920763u, 733185481u, 1028655248u, 977810701u, 3434484235u, 1871311609u, 2031584214u, 1336174158u, 385787519u, 3965885375u, 2768323462u, 1847726660u, 2718987737u, 793780050u, 2509902580u, 3886434164u, 3120956802u, 4207987247u, 1523159183u, 1884932179u, 2922324286u, 477253416u, 3037922812u, 1108379444u, 697195677u, 1755438379u, 574393398u, 2555059183u, 1930828628u, 1126190880u, 180621093u, 2589191337u, 3424652760u, 3054648512u, 719646637u, 952394946u, 3570038180u, 504304985u, 1395707758u, 1274213163u, 2816553213u, 1369142370u, 1804702100u, 1821782344u, 3358274235u, 2181234724u, 486158240u, 367287522u, 4267199121u, 1127352639u, 779850007u, 3440331597u, 3276765484u, 125500149u, 1142120513u, 3989398167u, 1048565860u, 3136747194u, 432668526u, 2098559576u, 1478877150u, 2484746208u, 1209580219u, 1019125185u, 4160278734u, 1970740713u, 918146921u, 4136433784u, 2602441845u, 2348512686u, 973030509u, 2238261365u, 815637919u, 994690313u, 1724736366u, 2099799816u, 1775069742u, 2680317667u, 730798472u, 2916864943u, 1284417767u, 1698724919u, 2733611686u, 1578128411u, 651006053u, 4243350375u, 3303874296u, 162087183u, 3796616231u, 3801767645u, 4119825424u, 3922537059u, 77594039u, 3419583692u, 2503306160u, 423966005u, 3293613218u, 1124728190u, 1407880681u, 1440346680u, 554334954u, 2919409323u, 1253962019u, 586491243u, 3638308238u, 3097648541u, 991125519u, 458538714u, 2155963569u, 2807866455u, 6862945u, 2122460897u, 53853750u, 3346001678u, 1230879976u, 3071060893u, 423909157u, 3881450262u, 1652511030u, 3826483009u, 1526211009u, 1435219366u, 3092251623u, 3001090498u, 281084412u, 849586749u, 2207008400u, 131172352u, 1820973075u, 3195774605u, 2962673849u, 2147580010u, 1090677336u, 2061249893u, 1724513375u, 3885752424u, 1135918139u, 2619357288u, 4012575714u, 2652856935u, 2029480458u, 3691276589u, 2623865075u, 3459550738u, 2097670126u, 2477000057u, 2209844713u, 785646024u, 1052349661u, 1030500157u, 1430246618u, 3807539761u, 2157629976u, 123154542u, 2560049331u, 2104110449u, 1332109867u, 721241591u, 4136042859u, 4203401395u, 998151922u, 3060999432u, 3207929139u, 2149509272u, 1385268511u, 2023309182u, 1366796638u, 256061060u, 4090836236u, 2929047008u, 2296609403u, 182240337u, 3744374619u, 306855912u, 4014087816u, 2240468995u, 2865233169u, 415452309u, 1244206523u, 3513921306u, 281425419u, 3511338031u, 995954022u, 3102854413u, 3026765331u, 643667197u, 837979907u, 2832983005u, 1813414171u, 2227348307u, 4020325887u, 4178893912u, 610818241u, 2787397224u, 2762441380u, 3437393657u, 2030369078u, 1949046312u, 1876612561u, 1857107382u, 1049344864u, 3544695775u, 2172907342u, 358500115u, 3895295219u, 571965125u, 328582064u, 744698407u, 3066193991u, 1679065087u, 2650874932u, 3570748805u, 812110431u, 3450423805u, 1705023874u, 259721746u, 1192558045u, 1714799045u, 3685508436u, 2262914445u, 3903852862u, 1790140070u, 2651193482u, 2821191752u, 776610414u, 2697125035u, 2212010032u, 1254062056u, 3541766210u, 1853927671u, 1543286708u, 66516686u, 3505195914u, 4226521519u, 1260092911u, 717982876u, 739240369u, 456195732u, 2116515161u, 1599487648u, 838913496u, 850912042u, 3712172413u, 2103192411u, 877020153u, 1458113119u, 2646869271u, 4087221703u, 3771198399u, 3952796001u, 1685641891u, 226245966u, 4065518354u, 3169076409u, 715963611u, 1155859114u, 4174181651u, 1816065125u, 2422210778u, 2353087594u, 2569974907u, 4049024520u, 563593555u, 1794197249u, 2434290377u, 4222178191u, 2381045132u, 1294739153u, 1333544226u, 3011196239u, 518183212u, 2861903570u, 3168787443u, 2315530531u, 1042490149u, 2998340365u, 3534153126u, 2862715604u, 796613230u, 765073073u, 1342937225u, 549817636u, 3786981820u, 4291017601u, 2895722553u, 734959362u, 3175258828u, 140019477u, 268621172u, 2410334776u, 565052604u, 3787587805u, 386344800u, 2874086067u, 35710270u, 817904650u, 1960697289u, 1584484509u, 2724312018u, 1978802819u, 2275314726u, 4216102886u, 2138332912u, 671754166u, 1442240992u, 3674442465u, 1085868016u, 2769242611u, 1003628378u, 1616076847u, 743729558u, 820011032u, 2559719034u, 1839332599u, 3121982280u, 2070268989u, 3769147733u, 518022934u, 3037227899u, 2531915367u, 1008310588u, 971468687u, 2052976098u, 1651926578u, 78218926u, 2503907441u, 3209763057u, 1081499040u, 2812016370u, 1247433164u, 335294964u, 2650385171u, 2030527826u, 1139372809u, 4279827824u, 3540669095u, 2285341455u, 4220507154u, 3863048231u, 3136394663u, 3319584205u, 1476940506u, 875141230u, 2508558662u, 3896001866u, 462864388u, 1609807693u, 3892563868u, 3642514037u, 3778083990u, 1403162576u, 3512254868u, 1403323269u, 1119818229u, 2831288053u, 2552740643u, 2520136409u, 96690857u, 210381252u, 1826474872u, 3306977352u, 1343117402u, 2112059492u, 693571694u, 2096734379u, 767794921u, 1843084587u, 1816280216u, 1695342628u, 404711915u, 3334843684u, 2570639553u, 4186538211u, 2022604264u, 3214805180u, 2989079529u, 2725165355u, 3005995436u, 310011850u, 2742468706u, 2720274646u, 144327376u, 2271696819u, 295519962u, 1272030376u, 1372670420u, 1397272558u, 2280044719u, 2710639434u, 2810822904u, 4271368265u, 1750711132u, 2216408539u, 3521792518u, 3111505866u, 3085328191u, 1054735512u, 4160317205u, 1427385632u, 2282061755u, 3215251668u, 1396490078u, 2933318719u, 453673969u, 2926038256u, 2624047458u, 338625410u, 3344930154u, 1971116345u, 1818716442u, 2998517928u, 390083048u, 291563131u, 1144486353u, 296954266u, 659950561u, 2263631666u, 1206908601u, 1125491020u, 1890151284u, 2076080514u, 2264060846u, 561805191u, 1964622705u, 405620012u, 3759692386u, 517035386u, 2225016848u, 4165419081u, 4052828294u, 3248204933u, 2738939733u, 1151808775u, 4113264137u, 3113447491u, 1033828852u, 1785686386u, 2903923175u, 2038900010u, 1241522880u, 238119113u, 2885394101u, 2636011022u, 2985605703u, 2107193353u, 292026696u, 3884689974u, 1094315383u, 4016714705u, 962244585u, 3943968050u, 2868319718u, 1304919603u, 3626636694u, 3393461291u, 1479454799u, 971639318u, 3352306399u, 1928233566u, 2900529135u, 2190901098u, 28842068u, 990556577u, 2586302532u, 3057504668u, 1661169605u, 4228191763u, 3934152427u, 2814119472u, 4943754u, 1171095774u, 1986204006u, 2014406505u, 1822565279u, 12890078u, 1979620724u, 1917376192u, 3307810835u, 4170173371u, 1385005883u, 1308519769u, 3370429606u, 923886311u, 2024463563u, 1063369787u, 153599761u, 3463680785u, 755374878u, 2088947962u, 3099927142u, 1750207400u, 2033606872u, 926120766u, 655932557u, 2320365045u, 1465119024u, 3105365454u, 2608716819u, 1218456091u, 823539591u, 2331574954u, 3171519129u, 3246671799u, 1043031086u, 1425831588u, 3940307546u, 3443545749u, 1155610704u, 3681098065u, 3287797558u, 63959365u, 810297004u, 3800799806u, 1234795257u, 2547289014u, 391329364u, 370300179u, 2474800443u, 3972311925u, 2935022755u, 3924395679u, 2347599539u, 4212318274u, 1828491430u, 3865565525u, 2767860661u, 4078993078u, 2781496513u, 4013741232u, 2916354756u, 35752471u, 2730683119u, 3340599926u, 4059491907u, 111492530u, 897368671u, 2524912702u, 3046341697u, 2790787159u, 1014602604u, 1409764839u, 512802978u, 477082227u, 2608350570u, 533747000u, 1933326657u, 4182933327u, 1970210993u, 2290203137u, 2843031053u, 2844558050u, 3308351089u, 3041943368u, 1504174920u, 295229952u, 2843309586u, 884572473u, 1787387521u, 1861566286u, 3616058184u, 48071792u, 3577350513u, 297480282u, 1101405687u, 1473439254u, 2634793792u, 1341017984u, 2500741117u, 4263797064u, 2322457777u, 1155622524u, 3736368257u, 3681071476u, 1137217259u, 1527337250u, 1366117744u, 3207345339u, 512022531u, 3628630048u, 4036536846u, 932603285u, 2772624172u, 4144438051u, 2059278872u, 3058844153u, 2745845437u, 4220526355u, 2339537870u, 3263741374u, 2780181639u, 830046989u, 2335972292u, 1514360419u, 3096871669u, 843103547u, 2244100243u, 3573704535u, 4267928843u, 4091363370u, 939208984u, 3295829276u, 454400120u, 3702127846u, 471147023u, 1957060850u, 273122868u, 1428866210u, 1737657854u, 3600299128u, 1925746977u, 2380738123u, 1571168523u, 519113682u, 3279227474u, 911322179u, 2696794428u, 2109856536u, 3315630517u, 1759453958u, 4006575573u, 3262077008u, 4177890150u, 1533579172u, 824755459u, 3314795869u, 596460132u, 4215683940u, 2990441121u, 3634236923u, 402953931u, 3584672586u, 2256594729u, 1577088289u, 2277811099u, 217436774u, 3698567316u, 4190005167u, 2082429185u, 3618893459u, 1689882188u, 3734303933u, 2883774800u, 324263298u, 3183678634u, 139054154u, 2233608349u, 2636817029u, 1493414555u, 3159722767u, 644233309u, 2643671789u, 2517246253u, 2845974520u, 1125905547u, 4085649601u, 190928872u, 1141978180u, 3242413680u, 3948731627u, 1042755180u, 508509300u, 1900103462u, 1344606968u, 2954061670u, 3745707120u, 1542873415u, 1003492034u, 3162556541u, 3470584807u, 1695255693u, 2390285737u, 2935248785u, 4052698114u, 3023860703u, 2163389899u, 1899687290u, 2862238469u, 84085276u, 656982819u, 1421023770u, 4179985759u, 1822395411u, 2722008140u, 1160802626u, 767294975u, 846339630u, 318440919u, 3529265600u, 2125900493u, 1846498371u, 3375757997u, 3812947227u, 1995784281u, 1680118162u, 3792592105u, 3303321146u, 2780428251u, 1704206566u, 3879390424u, 3472541629u, 25656479u, 3243031424u, 2978825284u, 1620901527u, 2512940888u, 927794181u, 452523305u, 3394773138u, 4253391568u, 4077229251u, 987808226u, 1406882831u, 1429828258u, 2883058504u, 2960876800u, 1883965824u, 4129270661u, 3579857811u, 973235694u, 3302203860u, 3969586611u, 718348498u, 3763448734u, 3702177983u, 1854328632u, 4251468518u, 2022446019u, 2209431908u, 2414211768u, 3797958050u, 3597530801u, 2525552689u, 636981785u, 664656278u, 2745678888u, 858404277u, 4276042326u, 1747857698u, 2746176763u, 3215666565u, 1887716830u, 3545855489u, 121927034u, 3392865382u, 357130402u, 1368051231u, 2277909715u, 2293787949u, 3358670926u, 386335223u, 3163867151u, 479772539u, 816735136u, 585372041u, 1124539534u, 2914789461u, 1942376489u, 2126769104u, 1975800425u, 814799998u, 2893249499u, 2126033825u, 760007658u, 633972488u, 806727295u, 236112176u, 414407704u, 3653783114u, 1391030845u, 2407584835u, 731546725u, 3992639691u, 106232033u, 2992162823u, 3567584453u, 2503068146u, 1051529903u, 3502104364u, 610035711u, 3775335972u, 667618167u, 4247343049u, 1301421152u, 2243584u, 144192006u, 3717030438u, 1757884509u, 2630952942u, 3363490445u, 4251803751u, 1904267860u, 2266368667u, 75111294u, 2059537251u, 1227434503u, 3441761728u, 4086217716u, 978577973u, 735792426u, 2139298718u, 404370445u, 3869131990u, 1176441999u, 2468151139u, 864851519u, 3630012660u, 3234610115u, 3172435896u, 3439750920u, 2516795165u, 2517212416u, 1059716705u, 2134575208u, 2862235859u, 2538210759u, 358555951u, 2442940989u, 2688476819u, 794989882u, 2838735245u, 3872585781u, 3134260357u, 105064119u, 3825751229u, 1135488310u, 4218960221u, 3360877465u, 3302954754u, 2575700988u, 2497293657u, 2388927109u, 3987074240u, 414604988u, 2491469147u, 3980520027u, 72941163u, 1711077678u, 519087922u, 171381824u, 3705314333u, 2513057424u, 2080037686u, 1774744635u, 3628627514u, 556341778u, 899387995u, 2615372983u, 2372073252u, 237968744u, 2705328516u, 3643402537u, 137400382u, 1941599746u, 2640174030u, 2083120893u, 1556545397u, 289682033u, 212740831u, 949213043u, 2102687076u, 2767525426u, 826825825u, 4191165775u, 528640652u, 4077394318u, 882590735u, 3163125263u, 629276741u, 1807552501u, 812058805u, 2945204393u, 183190693u, 2947275637u, 2728154303u, 993281047u, 1210608922u, 4272525031u, 2313255113u, 1870857999u, 2985702525u, 3194565035u, 2143686960u, 1451916006u, 2301248018u, 1558711357u, 1912047123u, 4251516193u, 532285070u, 3114187491u, 2106068513u, 3597063679u, 3663599168u, 1709549131u, 3753489627u, 3658005357u, 1160905342u, 737028908u, 895334719u, 4069027351u, 2426568775u, 1507089618u, 2750118357u, 1653041143u, 1791125727u, 1716827395u, 884658094u, 3085360311u, 4071341754u, 3590238451u, 352493133u, 4083973780u, 454018536u, 274798275u, 610061980u, 2854116038u, 714942167u, 757252280u, 2666997071u, 1593252771u, 2464064684u, 723272092u, 223672858u, 486201858u, 3999479492u, 655297946u, 3129578082u, 1698731657u, 3169005768u, 1702847708u, 272320271u, 120106603u, 3695564069u, 1932873871u, 4013239442u, 423242330u, 4227958558u, 3934266541u, 3689114116u, 2002816339u, 3373950165u, 3217483675u, 2204939216u, 3132445400u, 762796738u, 3162414255u, 1711928854u, 2819853427u, 575230348u, 926867967u, 132669602u, 221159232u, 4033582912u, 252108313u, 1294099693u, 1809928527u, 1269308130u, 3480686231u, 1429950454u, 1360727790u, 2006042568u, 3797144724u, 2783990950u, 1757106005u, 108354209u, 865723626u, 3617249860u, 109520212u, 2401026515u, 285359527u, 3668331347u, 2905102117u, 1494129763u, 348216553u, 1915669884u, 1414811767u, 232956812u, 1587333052u, 760671069u, 3422476798u, 2846738947u, 757998238u, 1420899728u, 398188339u, 3858968607u, 256042460u, 507472720u, 1232254610u, 4245222671u, 3075136024u, 2319205464u, 2119746088u, 3036187191u, 3887480239u, 4292783817u, 1737542162u, 1236303522u, 289379017u, 1780360736u, 1610718605u, 1996472339u, 3644617197u, 3281170667u, 1566409334u, 3514159615u, 612510353u, 430448254u, 1811185798u, 765006468u, 3732165767u, 1544620190u, 4282260204u, 243544799u, 2292191785u, 2241481909u, 1694649590u, 1442460355u, 1427073089u, 754492744u, 184820092u, 897419112u, 3678705335u, 3887604945u, 776070980u, 2900783033u, 1431582005u, 2012055595u, 1852695797u, 3917579167u, 1406433072u, 446726308u, 1084867033u, 3202096017u, 565067593u, 3162244645u, 388787811u, 2413176429u, 4089423644u, 791107632u, 1200634140u, 2565003219u, 2483173661u, 1288219555u, 1516166336u, 576053616u, 1361342997u, 913116636u, 3336073388u, 3843745245u, 1589908914u, 306887506u, 822428140u, 1041471861u, 47350214u, 230873349u, 1684806060u, 1897181775u, 3894132289u, 57050902u, 4240348943u, 3853407495u, 3044803004u, 844640504u, 2739986313u, 401023306u, 2667408852u, 1320130763u, 3973251787u, 1958752748u, 3782783511u, 436666731u, 83547082u, 4275166304u, 3094116720u, 1426327861u, 2538655628u, 1277094853u, 242713550u, 266482191u, 2743531761u, 1280948101u, 1273335605u, 199077170u, 1995269917u, 2170797334u, 4071342218u, 3270299293u, 2370531852u, 2710424997u, 2162130831u, 386081723u, 572675806u, 347301455u, 3062850063u, 3338222668u, 3973274791u, 3887524097u, 3880712621u, 2292533076u, 2732854883u, 468813770u, 1468745823u, 3546822021u, 2850369516u, 1452118653u, 2833005065u, 1262604654u, 1161523326u, 3205391754u, 2758572095u, 44395426u, 1843630982u, 208079731u, 3445477275u, 2868677914u, 1426717537u, 2591875243u, 3051602711u, 2259592887u, 2810102394u, 3134078220u, 1033606524u, 3037630581u, 3947578497u, 3355988886u, 2593461472u, 1236851705u, 1646026810u, 2974402225u, 3350613492u, 2390878749u, 2126029173u, 1703043827u, 3801306369u, 264529892u, 1709343735u, 3350828389u, 1193733634u, 1449911677u, 1041642862u, 2610764215u, 6405054u, 3183661914u, 1696457265u, 450169463u, 867572082u, 549276402u, 3316035838u, 2360256790u, 2613301818u, 2084044430u, 3346024089u, 3824563931u, 2144873191u, 3431508285u, 1651463044u, 3153970916u, 3567962109u, 220468773u, 549571972u, 313039992u, 1072303166u, 380222551u, 2161023965u, 3428890854u, 550663883u, 4050189100u, 4203427051u, 2936536013u, 3121879936u, 567291980u, 959491494u, 3104078241u, 2931645971u, 473964590u, 1927186295u, 504627954u, 2886471106u, 2751862512u, 3905695311u, 1412246296u, 3602455955u, 2808101279u, 910058066u, 3217495121u, 4084815289u, 2504763616u, 3770515788u, 3178414637u, 3045433914u, 1008573896u, 4169182346u, 3156618604u, 1816382062u, 4168688896u, 3596074775u, 3723437259u, 400803335u, 370374482u, 2892345381u, 1573833307u, 422498541u, 1585696786u, 2995703619u, 2942174909u, 927503844u, 2568139773u, 3340754484u, 3390292334u, 346761085u, 1579057249u, 1740755247u, 884882916u, 891164653u, 372229989u, 365212537u, 3315430932u, 2229872005u, 883365323u, 4202570990u, 1667613977u, 713352031u, 2369870728u, 3944817852u, 983346721u, 1308899441u, 2757113982u, 2494900868u, 2080827335u, 3624427103u, 652171563u, 1666757625u, 3358372252u, 25827967u, 432100882u, 42605297u, 1263005308u, 852004783u, 1019509360u, 1689563162u, 2280078981u, 844049518u, 392984060u, 3587407155u, 1740816471u, 3348953483u, 450311223u, 331586083u, 482255964u, 1251638867u, 3369092147u, 1183178495u, 1252284967u, 2670206902u, 2592156382u, 3956400143u, 4142163820u, 968164509u, 1857508915u, 1223187601u, 2983937972u, 363499219u, 3256011603u, 1407877715u, 1858184655u, 223762808u, 2815342624u, 2623728343u, 471394359u, 2338922152u, 4010468018u, 1494235404u, 805138023u, 2263304220u, 1143229406u, 4294371569u, 3426654861u, 3673268051u, 2094242240u, 3878198506u, 3302650596u, 553215323u, 1700836024u, 2644918481u, 1172263171u, 3566289616u, 159921530u, 4242701100u, 2891779620u, 2772910690u, 1844965307u, 3222652689u, 1940205226u, 3252887615u, 2619316586u, 2863214944u, 255135220u, 2319400461u, 1356399792u, 3136420082u, 3318816270u, 3348965492u, 2991156919u, 2098723029u, 538297620u, 2550174061u, 558996197u, 4153977074u, 396650285u, 336629528u, 33587922u, 151050341u, 1817240964u, 1598635540u, 2815665370u, 334635542u, 3104928583u, 3368059279u, 2281526556u, 2049214434u, 467369481u, 1892587657u, 2713415926u, 1210292261u, 543312793u, 2219660615u, 576828305u, 1579949228u, 423458407u, 506340086u, 610002369u, 2571074778u, 722633826u, 71222137u, 842882706u, 2009087692u, 1363565258u, 457448717u, 1359052209u, 1454830478u, 934427297u, 373198223u, 1078216524u, 881146725u, 3835072521u, 2223843980u, 3020320737u, 2047751094u, 2386876295u, 151140833u, 792136558u, 3664204416u, 910665524u, 4082855445u, 332202002u, 3663329916u, 3924742864u, 4210357809u, 3035318721u, 3703582172u, 2395685358u, 3527486801u, 1346167233u, 3945460735u, 713838878u, 2569385804u, 2673605345u, 3550969220u, 4243147364u, 2309000764u, 731999942u, 3921900019u, 1107209281u, 720619514u, 1704240103u, 81125990u, 317805114u, 3678640075u, 2938170218u, 3613685474u, 1728244724u, 3385237271u, 4221245045u, 3133258246u, 1727367040u, 3154857385u, 2665765720u, 2518841063u, 663013272u, 2419053996u, 1637865178u, 3969548484u, 692065125u, 2599473883u, 3256068101u, 435175331u, 3741393791u, 2658647268u, 1506574630u, 3151733449u, 2944353448u, 1249681632u, 1263358766u, 1368483368u, 2279035519u, 2464850890u, 3575231217u, 2754206804u, 2566200848u, 238034272u, 1440151198u, 4208701947u, 1285161672u, 3403832724u, 1943870151u, 2745258239u, 1815249255u, 1392971118u, 1544497359u, 4177624680u, 2397962695u, 2169967634u, 3189208041u, 3957569271u, 1822504027u, 2446464090u, 1844069058u, 1917044074u, 536324405u, 4142347706u, 104943297u, 516241068u, 1246336192u, 4230215670u, 1363740512u, 987712840u, 2807577755u, 2564077993u, 4110008491u, 2449624894u, 4018933476u, 3284119631u, 1966606846u, 1770310834u, 1032846869u, 240023392u, 3280916673u, 2173260788u, 3261286273u, 738911634u, 3181059220u, 2272149255u, 3194117094u, 2295733216u, 454924713u, 2932109539u, 2927279746u, 2029061725u, 1989689036u, 1420837132u, 911234017u, 1608529501u, 423134779u, 592387170u, 3537225433u, 3132705035u, 751661097u, 1414330162u, 702527398u, 2836854972u, 2860393334u, 273776580u, 3841373097u, 3897191802u, 2218600621u, 449503320u, 3018083450u, 426281553u, 659665656u, 1685861555u, 4095066912u, 2859028254u, 2323079437u, 2128578931u, 2919434878u, 1985959120u, 157036961u, 907467960u, 3475504086u, 1758801206u, 3215293590u, 462673225u, 516199313u, 2101618132u, 2255051833u, 480276182u, 1399444775u, 1540169926u, 2346982492u, 1248385475u, 1713179789u, 1407905589u, 1782812514u, 1112519953u, 776262767u, 2341647152u, 1096877715u, 299066250u, 88200511u, 74481227u, 3967156568u, 579473510u, 2807619625u, 3850609488u, 4005544769u, 3188251219u, 702280284u, 2592713719u, 3956082585u, 4092611494u, 3413029630u, 3926299537u, 2479889188u, 1040891653u, 1889938488u, 3874351210u, 1106442576u, 1903244241u, 3229585166u, 2416701998u, 982127964u, 1508122208u, 275681456u, 157531183u, 3295655144u, 2421430989u, 2882791436u, 1491165734u, 3071814346u, 3314520194u, 2757630249u, 2706643074u, 1799798708u, 3833725166u, 1678310352u, 3702234087u, 3505295054u, 1450032842u, 1363342287u, 2850921603u, 3498421664u, 2939309820u, 3389044949u, 1718335002u, 3660445557u, 78993494u, 2171692745u, 17549235u, 2730144888u, 1676319386u, 4084060395u, 4294716373u, 1906811545u, 859270623u, 257778878u, 2697422981u, 3722662433u, 3949147603u, 2710934973u, 3662672644u, 1525029711u, 3555554520u, 4282096432u, 3966879769u, 962809256u, 1184851100u, 2802256012u, 2770295670u, 2598415034u, 1796104491u, 1663206446u, 4260805312u, 610689191u, 2021836756u, 107953943u, 2900545767u, 1808663339u, 4008622457u, 790704710u, 2452868627u, 3117181052u, 1882665914u, 1590695627u, 1374587697u, 3614473030u, 3931887505u, 3153492485u, 4218122191u, 2452537456u, 1201324194u, 759586707u, 84942475u, 4111933087u, 1444391735u, 1139549443u, 3805974531u, 3971044720u, 477880684u, 961086587u, 1340362124u, 1604444345u, 2254105549u, 375811159u, 512712169u, 2749279630u, 3267939599u, 775743625u, 1342835433u, 193493042u, 1241189548u, 3106006437u, 1399344769u, 1492233317u, 1768053880u, 2837327654u, 1131098881u, 1648703102u, 2089150983u, 2694432705u, 973706044u, 92985242u, 3999906913u, 3910868338u, 191327779u, 3438373242u, 4193928044u, 3203390558u, 3362940567u, 3492292949u, 1934984940u, 1646288108u, 918962490u, 2651194120u, 442802528u, 2471731585u, 2340716146u, 2276554727u, 2302476915u, 1181415588u, 2868758587u, 1067853265u, 347176489u, 1939773730u, 2777887450u, 978019153u, 625959233u, 3455084654u, 1731268224u, 4235285461u, 3944667737u, 128814437u, 1818688919u, 2300660171u, 2758723882u, 373993792u, 2644214523u, 3444956489u, 3434458008u, 4248345024u, 1901574406u, 287531999u, 3007537762u, 4034685229u, 3517853408u, 78071904u, 1139716314u, 2937064484u, 239252817u, 3366122534u, 3038632949u, 2294103376u, 3438832446u, 3802589858u, 4154544779u, 3861196633u, 4260830112u, 2688381633u, 181409553u, 592142795u, 3965383578u, 935450750u, 269811790u, 782289952u, 1638485324u, 179614966u, 548548887u, 459310932u, 1886180225u, 2647604623u, 36947705u, 4035813282u, 3753815615u, 1522375757u, 3809696647u, 1763638499u, 2226920609u, 4227748553u, 1313305235u, 4061231705u, 1702505565u, 2906166764u, 1729326608u, 4244725906u, 966149927u, 3293515724u, 2367813487u, 1446112345u, 1227910659u, 2844908425u, 1594427357u, 1048681939u, 212427838u, 1269193978u, 3496717749u, 2921343850u, 2668456969u, 2267084882u, 1334928840u, 1767780686u, 983963396u, 2588311435u, 1850331400u, 3223459079u, 3111775696u, 2506255888u, 3702554614u, 2369930792u, 2929647161u, 2506416716u, 2479117917u, 2198249807u, 3444428083u, 354733066u, 717644749u, 3090530204u, 2738017268u, 4278457915u, 4258807760u, 1522713227u, 3905745313u, 4171524857u, 2035336180u, 1487986097u, 2620568311u, 3807676884u, 3856083492u, 1952899566u, 3060080941u, 1775656683u, 1827822866u, 935152116u, 2266271948u, 539682350u, 981783224u, 1326778049u, 3842197721u, 3118594795u, 467228000u, 3362409922u, 4079824256u, 2979795106u, 1709741046u, 42100360u, 120392511u, 3621573700u, 1920136592u, 3961385783u, 884407395u, 3311223137u, 3826235090u, 183222673u, 4039028327u, 1624297109u, 326318752u, 3025115648u, 594985212u, 3133234670u, 2207588835u, 963262671u, 3724108540u, 1155581262u, 3462905334u, 2890646829u, 3607969926u, 2050813368u, 3936879051u, 2678841578u, 3541348965u, 1015523243u, 2818254642u, 760740720u, 3880905941u, 3563291220u, 1196395351u, 3293903482u, 3540091169u, 4013553601u, 2934740932u, 463379296u, 3078765390u, 782661164u, 3353858244u, 425610981u, 2844388125u, 2103519494u, 3224691896u, 829982391u, 868188911u, 3847825001u, 2442903745u, 425586795u, 2785754810u, 189689674u, 2997051076u, 2393564453u, 2738132518u, 3317841037u, 3475188031u, 1339772322u, 3390183362u, 768723894u, 3115470760u, 1455803558u, 116426970u, 902568622u, 4093525619u, 2191088390u, 585691733u, 3892805143u, 897281696u, 2701207772u, 561461717u, 436084723u, 3742605163u, 1678708375u, 3817938705u, 234576607u, 27356943u, 2152993718u, 2986534572u, 1854228316u, 3521019125u, 4284489069u, 2810677824u, 3485806537u, 1976235678u, 2085858020u, 3148717547u, 3841623852u, 2435052650u, 590758137u, 1905986752u, 1675058364u, 2257780991u, 3982964645u, 2430544059u, 3940605995u, 2752661619u, 3064777055u, 2559949677u, 2655738818u, 3295104124u, 1474410264u, 2912446382u, 4020206781u, 576447599u, 535900431u, 1077310659u, 3137840249u, 1423157467u, 2776599449u, 787981617u, 3578360533u, 2556456226u, 1710609124u, 3325599781u, 3220461886u, 1478864177u, 3587244773u, 1268625412u, 1384956853u, 3882391248u, 2371945596u, 2045842833u, 4205327602u, 2464830712u, 2359262182u, 1171364609u, 1419158616u, 682715999u, 2660610073u, 2991823783u, 1548922277u, 831618797u, 3249183760u, 597636688u, 1777690202u, 458256856u, 2114606129u, 1299095260u, 2983899478u, 1264581214u, 4177860236u, 17273196u, 1407696854u, 593370470u, 3598337265u, 3195346021u, 3174291042u, 741107679u, 4098148086u, 2795583024u, 137106654u, 3452336576u, 1532740620u, 2229449622u, 2846076572u, 380183779u, 1209039979u, 2995172882u, 989487735u, 3715237075u, 3054273866u, 1955734715u, 2682520233u, 3818975284u, 2536644837u, 2284983225u, 2836559461u, 1389069601u, 204245791u, 777929392u, 1498019328u, 2401467298u, 1938493040u, 1071806041u, 1034679075u, 1620524703u, 3071094964u, 439558162u, 3677274935u, 4238774239u, 1209066361u, 1088039431u, 3139839398u, 1795448587u, 591687111u, 1875516399u, 3593696961u, 3145148511u, 595289847u, 1648586281u, 2526340071u, 1268107314u, 1572631480u, 3645616041u, 3465005871u, 544293197u, 2163721987u, 2048400380u, 2102791667u, 3372026220u, 3766895552u, 4286553780u, 1516732531u, 3412212465u, 1930345401u, 117250582u, 4138331062u, 4120218221u, 181667649u, 1440931813u, 4178824234u, 201952914u, 812637199u, 2602482807u, 2865259846u, 4183543706u, 2518738954u, 2969539593u, 2899585754u, 2896888904u, 1550577888u, 862479326u, 2664075557u, 897196313u, 3483866497u, 3708057157u, 82710238u, 3717454735u, 360233959u, 3097186829u, 4186741298u, 86621536u, 2797524946u, 1609114124u, 993158854u, 1345445936u, 1732981263u, 2140204917u, 524074125u, 3131818693u, 1152935964u, 3070648776u, 1107440887u, 541231638u, 1424491339u, 3438607874u, 653840126u, 1420721291u, 1494681525u, 1776801700u, 522519102u, 1413795107u, 3797408458u, 2643175199u, 404922594u, 1348222327u, 3994494069u, 3366587261u, 1713777698u, 2879553944u, 203587743u, 2308248086u, 1470483001u, 3099400086u, 3160950562u, 3134392672u, 3413133866u, 2746553770u, 2340353022u, 2732453903u, 2947307338u, 438129945u, 3838123218u, 492730903u, 235328936u, 2388344531u, 1304215689u, 2005591534u, 198391212u, 3193756469u, 839566305u, 393940610u, 3093088558u, 3423367095u, 3099906696u, 2343498361u, 3770118303u, 4168129773u, 2501530535u, 883925372u, 303586901u, 3868847116u, 3963157752u, 3157301259u, 3437571950u, 3392902953u, 1228132404u, 1707178093u, 2335015782u, 3904565878u, 4229581755u, 492138180u, 3073813901u, 640665822u, 3603346999u, 922161726u, 1860839953u, 560459819u, 2021317766u, 297881981u, 2408245790u, 384530297u, 1155739363u, 2562994192u, 3217009820u, 4110041205u, 2164181515u, 519027455u, 2778026350u, 3674648725u, 1321757186u, 3531453112u, 595817782u, 2027376578u, 2042570202u, 2888809226u, 1556750754u, 704400727u, 3384921396u, 3289703113u, 3351345046u, 1037627351u, 2871238084u, 2307943700u, 573394694u, 3105141941u, 92581831u, 882519770u, 2404497529u, 2508795700u, 1292007850u, 620527306u, 4034734001u, 1963769227u, 4212949030u, 1791638453u, 1231025186u, 1700222598u, 3439496951u, 1936785558u, 3848768958u, 2681320752u, 2566357103u, 2405639388u, 3796822945u, 3362218643u, 4053296118u, 1293805338u, 2358616019u, 3463138327u, 3128397576u, 3015879164u, 2477158023u, 1475962738u, 111057009u, 88496518u, 1917835954u, 1662174364u, 2775845786u, 1363900744u, 2238549646u, 578031776u, 1599070698u, 1870290001u, 4024962733u, 3205774627u, 3562816366u, 40250330u, 3646794336u, 4283270024u, 1600022383u, 1209132687u, 2547708346u, 4168140719u, 3747584726u, 3382580702u, 4009358868u, 4201204527u, 2871032209u, 661220876u, 888098135u, 1666178348u, 2808266895u, 3943189777u, 309459048u, 2163423368u, 1746878799u, 1974582532u, 2864449124u, 509670988u, 4010321183u, 2575074271u, 3483003844u, 3644480339u, 2081118997u, 652915824u, 3250213093u, 2752162620u, 1791205177u, 3047448045u, 4173789058u, 348953149u, 4243319035u, 3095301674u, 3711485381u, 14525930u, 1670243072u, 3689494100u, 1953101249u, 4234735905u, 1059513456u, 831806169u, 3369071539u, 1444988928u, 3791758648u, 2638473230u, 3924361789u, 3909317902u, 2397815488u, 108384758u, 2572118926u, 525129562u, 639420665u, 669144050u, 3864239974u, 3201253704u, 1934425697u, 433412542u, 883355992u, 495200818u, 3863971557u, 4033311018u, 3275279952u, 2148897016u, 3790249833u, 731766156u, 1223851860u, 3678193481u, 2891483608u, 1426705768u, 2853060454u, 2263653682u, 527486390u, 1913529154u, 1749419299u, 1353895017u, 1182348463u, 659872483u, 3078073095u, 1352634951u, 1217126631u, 3663266877u, 3849144771u, 1728881200u, 3550129307u, 4033329575u, 1675151111u, 1759466246u, 2138476840u, 3303545893u, 2984165585u, 1559521459u, 3583587581u, 2754204271u, 2618339581u, 3734997486u, 2468477297u, 3982798873u, 1400340476u, 1775731536u, 1960328724u, 3992723360u, 3065728698u, 1881136493u, 3798490745u, 3473259209u, 3096051547u, 1515970810u, 79941263u, 1441182150u, 2898142851u, 1399408592u, 1883381057u, 416509126u, 1880423351u, 3093448915u, 502669317u, 27468357u, 3499031203u, 1762592447u, 1395243464u, 3871613901u, 1057541701u, 267568056u, 1471942076u, 3842828346u, 1613585440u, 1973730051u, 2347430656u, 1449022602u, 2413428676u, 1816723564u, 1700043520u, 935486730u, 1709959123u, 418061874u, 2213485346u, 1066247998u, 2824072173u, 1935834272u, 4084149685u, 1854534142u, 3102463245u, 1791912859u, 1718329419u, 1895590262u, 3572860213u, 657834953u, 576978784u, 43442786u, 259702811u, 3218038282u, 361838311u, 4090401236u, 703937918u, 3905131145u, 1392513962u, 318722468u, 1295906647u, 2204048009u, 50169489u, 387845619u, 2318874730u, 137969335u, 409622605u, 505726246u, 629276521u, 643912174u, 2710730823u, 3662425714u, 3690753083u, 1056548235u, 4184250032u, 3922653458u, 2451732360u, 3394781897u, 4281439047u, 4108402885u, 2377442948u, 1495144293u, 2213877196u, 2950896548u, 1420268666u, 2523549781u, 1846843665u, 1787890598u, 2112291765u, 4187105389u, 305101977u, 28097139u, 3812810910u, 2427959932u, 277599151u, 3192572462u, 1873400110u, 3204284336u, 3550346696u, 1186049286u, 1694513554u, 4015601921u, 2634854552u, 3468396689u, 3516035178u, 2194659629u, 3806350498u, 1790891005u, 3999094007u, 668799895u, 819413823u, 4265177898u, 1110602326u, 1230733198u, 3856303761u, 1152893805u, 2548469791u, 3362430037u, 2163976689u, 261211212u, 2631997142u, 3049954710u, 3519391742u, 2684474998u, 2284446581u, 3767319453u, 867905936u, 1477946054u, 1949457599u, 3082436333u, 1837863418u, 1909772278u, 4149164990u, 777712915u, 2663116186u, 2580037763u, 2986677112u, 1805877811u, 3093083469u, 47479577u, 1489903495u, 1265001771u, 2220456937u, 2751664031u, 2390985243u, 2999864559u, 672141846u, 3231315389u, 2414012330u, 1906819045u, 2984157392u, 3741192015u, 1831612599u, 412535655u, 3591754091u, 3679838215u, 3141283535u, 1326459140u, 1546321559u, 2053959246u, 1950827292u, 2489596315u, 1659531982u, 1336558483u, 3330981825u, 97580289u, 3153670395u, 2324499306u, 1848029250u, 3326835115u, 2979644611u, 1264461714u, 4059661017u, 3104006826u, 3368253358u, 2397455377u, 3030408045u, 3174369033u, 469586980u, 951616564u, 1674739403u, 3784254295u, 2537916485u, 1629754480u, 1973022275u, 1402612676u, 216208581u, 2781646564u, 982205675u, 4075937534u, 3582814745u, 2136790623u, 67193454u, 468091581u, 3709609904u, 4109050590u, 335304015u, 3973380988u, 2873516039u, 1614829131u, 2148391288u, 1996647808u, 936276241u, 1659295594u, 2455070843u, 4092282313u, 524798420u, 958595957u, 2882637010u, 3874299566u, 2575200323u, 45864893u, 240415769u, 2863710934u, 241991393u, 4026751870u, 654985261u, 73118816u, 84271844u, 9504786u, 1869064740u, 105677904u, 3574364025u, 2599606066u, 2651670594u, 438506082u, 2233938841u, 1670640089u, 3710285779u, 745377473u, 419609375u, 2602573397u, 3900054502u, 2650521038u, 463928187u, 1172984423u, 2220484190u, 1095807452u, 614850457u, 144205315u, 2402478324u, 1451658947u, 19669332u, 3097977779u, 3292874081u, 4095144717u, 3645178392u, 463290186u, 3937717357u, 3760375802u, 4238996472u, 1930769438u, 2169530151u, 1121118212u, 1165746984u, 3261547512u, 432720133u, 3457041397u, 2181194120u, 1036791209u, 2515172049u, 1493671637u, 3276575128u, 3151035990u, 356321858u, 1170285938u, 2841534012u, 3818274169u, 2220407942u, 3339536836u, 734645661u, 1250564386u, 4031075337u, 632013612u, 2536105946u, 1968372804u, 1892511539u, 3134146239u, 4045511005u, 3378295560u, 2817128396u, 3086852652u, 1941092040u, 1186603069u, 3606472960u, 70669832u, 2287600530u, 1638569324u, 2378926845u, 2315380185u, 2920859214u, 1455582985u, 1577068627u, 3591589856u, 1027745331u, 2126182285u, 2486457443u, 3623598128u, 3723251533u, 3911666366u, 1747092880u, 2402125269u, 483678340u, 1575314013u, 1906303350u, 3383365516u, 1289282189u, 1339901439u, 1723943420u, 2439753462u, 3579269267u, 363627112u, 1733571930u, 314184313u, 1675792864u, 4020770502u, 1548116196u, 2273911152u, 602392177u, 2838838375u, 1117250656u, 2740063266u, 372868020u, 2552512122u, 1844247494u, 4264502803u, 1105021132u, 3544737911u, 1277990640u, 2641105602u, 1824752961u, 3181211334u, 511991294u, 2236096341u, 2126296232u, 3094295258u, 3033995959u, 527724412u, 1046139663u, 2931463347u, 3371850311u, 3083598147u, 318212288u, 2898050586u, 1691716442u, 2861896595u, 14577642u, 2030754905u, 947800038u, 246325017u, 5585911u, 1615345507u, 812520481u, 2683069823u, 611964371u, 490907220u, 1151377635u, 2292093180u, 751155690u, 2811469882u, 595492796u, 4108972367u, 2572194110u, 4103704225u, 3870014217u, 3853331788u, 4034605360u, 3891903368u, 949980031u, 623024259u, 2073057785u, 1616375580u, 1614955440u, 2929877158u, 2249618123u, 2290570578u, 1137619107u, 3073303314u, 293592020u, 3539009164u, 1874010544u, 18293765u, 746693114u, 2924999677u, 112129180u, 3183436706u, 4100311944u, 3942948478u, 1849397958u, 2492102702u, 4129862629u, 89745884u, 3274545262u, 3595635232u, 31562271u, 2564379334u, 2920743717u, 1180122591u, 3032035420u, 1353651248u, 2770807059u, 25081401u, 2372152730u, 2069576326u, 936769856u, 723606552u, 3317287620u, 1611064790u, 979374201u, 2204611921u, 1592851823u, 4191754721u, 3826510149u, 720641424u, 3678110796u, 3723533932u, 1728438917u, 3122163332u, 1365881714u, 1765132094u, 2614069276u, 2921135690u, 3909258731u, 1560697876u, 3904546998u, 1269385037u, 2540878633u, 1980234534u, 1428383314u, 2964988624u, 3663880395u, 652791181u, 1900084498u, 326298089u, 3884177206u, 2537320201u, 142504470u, 2075689920u, 2286754314u, 3471190679u, 3077332658u, 4148280726u, 770095561u, 446553822u, 1445397914u, 2998794260u, 806220989u, 2035613576u, 1382666746u, 464938132u, 1734551383u, 940041372u, 2356074312u, 1821789369u, 209330661u, 812406143u, 2373966445u, 463302805u, 1180306011u, 1656902011u, 1037242088u, 359039185u, 1044300592u, 2379839739u, 662109823u, 74469949u, 4107776963u, 4280041364u, 4018634993u, 4291500862u, 3516351734u, 2761187869u, 3127860814u, 2593569870u, 755105602u, 3113400158u, 1547781563u, 3331942386u, 810846783u, 846702952u, 5147099u, 434277085u, 1359011478u, 979453305u, 3004832082u, 1651070055u, 2685450541u, 3023061945u, 2332434296u, 1449076389u, 1885650424u, 4063755770u, 1234490702u, 3464987032u, 2154609442u, 2310908165u, 3270815960u, 3468813887u, 3274517632u, 503947210u, 2474141277u, 1287887592u, 3211187438u, 1624803533u, 2772549594u, 3171469972u, 529223794u, 3413509397u, 2166372317u, 3391791557u, 1491475969u, 1785826673u, 395771269u, 3844001065u, 635008637u, 2943484153u, 851132384u, 152778962u, 2887378673u, 3751896912u, 1853326403u, 2472544967u, 2982442106u, 310002530u, 1102881285u, 2867283667u, 41913069u, 3504408015u, 2286138391u, 1935548655u, 1199979353u, 3426129152u, 4064027578u, 1591439016u, 3893144160u, 3401059997u, 1686567419u, 2610861827u, 106752445u, 66861635u, 2883799100u, 1424012493u, 3595620492u, 2699922466u, 4172559189u, 888884433u, 244524878u, 2283218712u, 1934126058u, 40293409u, 2501690904u, 2261381514u, 2949086966u, 1806374300u, 3089940133u, 2157022662u, 2791903748u, 3568420276u, 3122074238u, 2034253194u, 1605663501u, 1405079440u, 2497876014u, 3669352834u, 498725211u, 4140305918u, 247623610u, 1595801470u, 4208059585u, 1440824281u, 1223308576u, 2146301246u, 2555395148u, 2596810779u, 4132450170u, 2372835596u, 797911580u, 1831738774u, 829099694u, 2207504167u, 1467350244u, 2190713264u, 4006765973u, 140374436u, 1677904306u, 722287139u, 1173456818u, 3433373317u, 652607730u, 3578901879u, 1705569489u, 2756232453u, 1609420758u, 621700234u, 563133390u, 372364134u, 1868485656u, 3193050428u, 393046075u, 1655111696u, 2639802682u, 3745421913u, 47154834u, 3533792021u, 2462134617u, 833305539u, 3391863910u, 1193916378u, 1010892576u, 2314992090u, 1924230043u, 173327386u, 2445374764u, 3344539005u, 263717207u, 344458992u, 2131544513u, 2844286976u, 2758722915u, 1914807185u, 950329081u, 2499332236u, 3595130050u, 1404646615u, 4170736375u, 1208124202u, 3635143895u, 115864937u, 2173251121u, 1455416724u, 1197761604u, 3962211850u, 3206696551u, 856644982u, 1017608232u, 3649849172u, 4111766657u, 2621815082u, 2663996565u, 3485608353u, 2578106283u, 1608204161u, 741330692u, 230735732u, 388036276u, 3976257312u, 1096342811u, 3792877416u, 3687532372u, 143297888u, 3913003182u, 4134793368u, 3004904148u, 2873860186u, 3114634496u, 330405231u, 987353207u, 872230598u, 2474130781u, 489623837u, 3481621200u, 2178025230u, 1734494073u, 1599344169u, 4245314329u, 3047428366u, 386541963u, 2019633251u, 1378431249u, 961885261u, 2196484647u, 3638700902u, 260302352u, 3535293420u, 3116805903u, 1440364029u, 2390388754u, 332129148u, 2273583462u, 1740904163u, 3564747422u, 1320315490u, 3688341980u, 1943868361u, 3388853410u, 1775902309u, 1365082575u, 1522292425u, 1942216237u, 123405003u, 3230794558u, 335674543u, 471852445u, 2319546878u, 471339877u, 1623550474u, 1159141530u, 716060172u, 2253300242u, 2246457388u, 4177504571u, 2957827037u, 3051182067u, 2961392703u, 1339428272u, 1253728860u, 1251798837u, 2071393845u, 3652256935u, 3481290805u, 3915495864u, 4240793738u, 2745670169u, 223281082u, 1096807079u, 810830859u, 380816886u, 2578459915u, 3600280332u, 1900744475u, 2511347346u, 2563321948u, 4072096018u, 1553950434u, 262117258u, 938413725u, 2511015293u, 1852340894u, 1224529889u, 2111115142u, 3555082594u, 3061142695u, 820280543u, 640858393u, 1900651720u, 424329571u, 1689689543u, 2378182011u, 3550108203u, 2108998782u, 2907139217u, 1332214261u, 891648241u, 2578642005u, 1366249405u, 2619717552u, 574713818u, 1872350222u, 2883911152u, 1984517103u, 2452387999u, 3680102565u, 729143999u, 3828109877u, 634176716u, 4017428396u, 2044746818u, 570105749u, 3900270178u, 579273057u, 2371573676u, 2337057693u, 141475767u, 2428598393u, 231339503u, 2618261398u, 3457720245u, 1861956654u, 1938640241u, 2038507192u, 1643453033u, 2402192723u, 3391493865u, 3602341588u, 1564600188u, 4142473852u, 2286425538u, 3335048275u, 3056542298u, 827939153u, 3742963152u, 1076978789u, 1411711112u, 3847641540u, 2792235659u, 1291651070u, 4186889356u, 4111150675u, 326277337u, 2727536313u, 2521228115u, 3858177828u, 1777628964u, 1636457523u, 1327730835u, 3446030271u, 1133158582u, 2674837390u, 3258876318u, 782159572u, 4274420083u, 3678751963u, 801318243u, 1470311112u, 3354993392u, 776040423u, 840945944u, 688891617u, 4262149326u, 3180950192u, 3445687209u, 667765797u, 1822039854u, 687782533u, 3130446468u, 1679964477u, 2140412333u, 2521023888u, 3474586730u, 2738336824u, 1531194236u, 272855576u, 314578174u, 1581144125u, 2538288986u, 1693951845u, 3909226960u, 2978902193u, 832218336u, 3075520766u, 1857005512u, 2749313732u, 3217616529u, 3198048780u, 168296081u, 3310066596u, 4064434880u, 349245502u, 3279951952u, 1874146182u, 2400115994u, 2787873697u, 789599428u, 1353028316u, 2138673876u, 2629101256u, 2224129914u, 3943684346u, 4270241199u, 4159779981u, 3671560018u, 2926618313u, 4133493471u, 886437031u, 2916029412u, 2881600983u, 1733025272u, 2792441416u, 4015704600u, 2896243818u, 2059370462u, 1399747019u, 995537401u, 2091141688u, 1702053663u, 3365267716u, 3028284675u, 3322651442u, 2398992773u, 2459257550u, 3249704119u, 2616019886u, 4275558572u, 4064420660u, 4133611408u, 1932472852u, 2298095725u, 837597033u, 4139790660u, 4002343555u, 496609365u, 3443323042u, 220968740u, 115259491u, 1307168777u, 10893775u, 2491904934u, 2785586805u, 2280474953u, 1896693783u, 3870659286u, 2796532337u, 2321646396u, 4019162589u, 1855342622u, 555064786u, 2330736969u, 490959045u, 3059798279u, 2691359011u, 71617365u, 368895618u, 3439928998u, 419018537u, 612072889u, 3479288324u, 2055032196u, 2830468787u, 1103099434u, 3041119163u, 1585236715u, 3855831726u, 2842258668u, 609983082u, 728464288u, 2536667505u, 1197368241u, 3547774719u, 851356113u, 3864312376u, 837825852u, 4273019476u, 1403765610u, 93856629u, 3781022335u, 2115174301u, 2023367080u, 4204671851u, 1735035239u, 1350209486u, 769793322u, 2369278308u, 4161501167u, 2513836932u, 1750009075u, 1668300176u, 3627045746u, 2923342051u, 2642801157u, 2226004008u, 1617532275u, 1001520657u, 3767466920u, 1885880162u, 3370915495u, 2599368591u, 1996963441u, 2277814872u, 3496004282u, 3274173931u, 3858788183u, 3552951969u, 1843565531u, 115543966u, 1435933937u, 452057997u, 2562579798u, 3334697064u, 3874021024u, 92244728u, 3015352427u, 3170041258u, 1621157335u, 953309163u, 3156611667u, 2110349192u, 4097840272u, 1196730082u, 2331364547u, 3304400427u, 2319736876u, 3001421795u, 1336205705u, 4237191249u, 305950166u, 1712705041u, 781600154u, 3624113458u, 399384395u, 2120599518u, 1990671162u, 3380471556u, 40082822u, 2409046702u, 3930006359u, 4012814795u, 2760554721u, 3939403736u, 6094787u, 3297788831u, 130503754u, 1026191227u, 895372775u, 3125416230u, 1954064714u, 1284624943u, 546603443u, 3626978360u, 37141541u, 83539007u, 3122783124u, 606885410u, 1520918647u, 2239843287u, 3351989811u, 3057238962u, 1875425985u, 1530721995u, 1874988534u, 161234343u, 211369000u, 1095654062u, 213167395u, 250191778u, 391272265u, 2423828544u, 2551369610u, 3042101804u, 1035448140u, 609081370u, 3613652780u, 1185846656u, 3681700798u, 2614952462u, 4138682884u, 1223079049u, 2099808600u, 2225489336u, 946224690u, 660451857u, 971558712u, 3554881734u, 2305486057u, 2318507706u, 3273236262u, 2822055016u, 1492789566u, 1119554775u, 1980975322u, 3551807758u, 2745874641u, 3516761755u, 3939928313u, 934855953u, 693948913u, 3327192365u, 3073630675u, 101876780u, 2481369570u, 1459509195u, 1861004954u, 1141309060u, 3797793840u, 1224681030u, 1688144430u, 2547349531u, 768692429u, 1521051682u, 2720147032u, 930600186u, 2680061978u, 2879962111u, 1408498461u, 268182619u, 3448709763u, 1592216145u, 4292724704u, 1599508620u, 4213269118u, 4200181833u, 545619507u, 3236090571u, 997463821u, 3184203691u, 101500669u, 4217240112u, 2608903190u, 3784923509u, 475922416u, 1479115092u, 1750025272u, 1715568033u, 3797080982u, 1579103843u, 2354212356u, 151342425u, 1584856153u, 2496419603u, 894839189u, 1937607745u, 1893836937u, 3229688482u, 4106831221u, 289431749u, 532687253u, 3202403809u, 2021912759u, 1229083658u, 3680341718u, 1058577411u, 186360648u, 2192860281u, 2970507375u, 2648231048u, 4204710567u, 352803166u, 1216626353u, 3225302463u, 574582876u, 3263983952u, 2943253852u, 1230198514u, 3906077570u, 824346422u, 2623662301u, 3956313178u, 3865396696u, 757224614u, 830791623u, 3022714332u, 3240228920u, 1179843786u, 1487178451u, 2948056279u, 1797982458u, 4255319781u, 668811578u, 3585348844u, 3517580725u, 2599889368u, 2684026125u, 349060894u, 3172092854u, 3347081959u, 3457931495u, 3830541864u, 288719121u, 1581629673u, 4083613336u, 368413676u, 2137076974u, 3970376737u, 3243326972u, 2737649035u, 3188605479u, 3616098576u, 3569674338u, 1397648422u, 672170313u, 1282546981u, 1964125989u, 2005736712u, 2654721419u, 1122965097u, 4003697003u, 4268477949u, 3586676653u, 2818808298u, 3845814717u, 4128499149u, 2501897997u, 3860552691u, 2502878480u, 1499525956u, 3671878952u, 587611744u, 149747060u, 195690614u, 3802850345u, 2325782175u, 1751190503u, 583241465u, 156259644u, 2004610888u, 3204681020u, 2689211891u, 664984504u, 3604535295u, 618081556u, 3929972522u, 2602574315u, 1710016283u, 1092986901u, 3041253464u, 1392231705u, 3940751328u, 1725678863u, 534546529u, 1745360123u, 3943952830u, 1658678333u, 821965910u, 2619078892u, 1399242525u, 716790203u, 2665205988u, 807849282u, 3088407631u, 406427894u, 3934651902u, 1388074483u, 1077200174u, 3305393652u, 1386026765u, 1005529155u, 1606082383u, 3179845493u, 956152124u, 2975632437u, 1808432395u, 3539388960u, 2114561910u, 3556136492u, 2063776030u, 1260005679u, 2450967374u, 1328730778u, 3569386647u, 2246395892u, 958560479u, 1397148536u, 2977661875u, 3572736354u, 3484318978u, 3480189603u, 3538510658u, 2392289338u, 553042652u, 1129421929u, 657031522u, 2923009585u, 1833485762u, 1003532627u, 1380103857u, 1960332028u, 1889542857u, 1651702217u, 3630760968u, 2313275557u, 1716182045u, 4259335064u, 1188243733u, 3243646919u, 1943239771u, 4211021527u, 1276150468u, 1008383770u, 2592475956u, 2270143981u, 4206016496u, 220916187u, 1061014409u, 3250755412u, 405813977u, 2585483415u, 2282646335u, 3681511559u, 2796349024u, 4244618003u, 1140587439u, 3992105438u, 430549136u, 1758853233u, 4072612623u, 1466574u, 1215975886u, 2323054716u, 2601488966u, 892196231u, 516847440u, 941815809u, 4267193699u, 1399327243u, 1513367522u, 412099598u, 3006457623u, 3210632622u, 2929320506u, 3214821475u, 2787332623u, 2333453280u, 2286517530u, 1452267238u, 1233666122u, 3574845880u, 2697674u, 2373279437u, 1248356043u, 4112616366u, 2665803324u, 3834689917u, 2583683474u, 1531171380u, 2210054590u, 2346778254u, 2801479353u, 1488986759u, 4262756833u, 2674917603u, 2380821100u, 3421476965u, 1420809174u, 3203508306u, 2821835379u, 539174012u, 3238947696u, 3532155363u, 463909612u, 108020580u, 686311412u, 1779958481u, 3501283419u, 3141371161u, 2549322549u, 3355975804u, 151660038u, 1577481000u, 237654147u, 3199183092u, 1395812589u, 3832258389u, 3321416658u, 1041973628u, 1338155692u, 556614774u, 2802833609u, 966659181u, 3371464856u, 1503298306u, 4194717924u, 1233019036u, 2234408174u, 3983530663u, 304386537u, 220390885u, 3672604251u, 2545484329u, 1481477612u, 699645452u, 1206554024u, 3600925349u, 2351947411u, 719668723u, 1522666126u, 2156935220u, 2578961309u, 4292087425u, 851501823u, 1526462106u, 1538145242u, 202197234u, 923797659u, 917665233u, 1280176282u, 1708706026u, 1488528898u, 1433093941u, 328725394u, 986135364u, 789495949u, 4020605538u, 1543114480u, 2934273484u, 2050902067u, 4132247293u, 3175607941u, 1881080451u, 3551141606u, 4038715194u, 1337862187u, 25058210u, 3386659863u, 2621248714u, 4116323910u, 3440594177u, 239971622u, 1000648070u, 346758228u, 4004922487u, 486542737u, 3278188663u, 2457877853u, 3549573731u, 2257175936u, 2463007358u, 4094271342u, 3404112349u, 913435793u, 1413221177u, 3109328087u, 959761872u, 3135335463u, 1341689139u, 361014125u, 2510509240u, 1077003967u, 3564454102u, 1902586361u, 1247526901u, 2940736338u, 1728957925u, 3861749142u, 3702507913u, 6506179u, 2640286243u, 3185951192u, 4257119115u, 4170283151u, 874880000u, 960224933u, 3552835960u, 4133901877u, 2902803543u, 4029723476u, 1069229844u, 1097566470u, 2043483688u, 3492749477u, 1714015065u, 997956638u, 2574567667u, 3733818679u, 3438219097u, 3601196803u, 451266934u, 3291888764u, 3528067348u, 4204683957u, 3612438284u, 1162023843u, 1522592715u, 2943081924u, 1847134284u, 663478404u, 2457748727u, 3297874754u, 3010019326u, 387951882u, 3188883299u, 3829156090u, 3255087638u, 3365242650u, 1671295327u, 2343810092u, 1843840147u, 693346359u, 4107469050u, 492532155u, 2460893290u, 532996711u, 3649528417u, 2356748197u, 1186894091u, 2134551200u, 2672859557u, 3034429947u, 2526994202u, 2366878138u, 4138065547u, 2062701434u, 368949266u, 2351844505u, 2149626396u, 419191055u, 2240210598u, 1407993071u, 387260016u, 4097232872u, 3885512949u, 2155071777u, 3798421539u, 4274030102u, 1885446249u, 2981237059u, 3357473073u, 137290838u, 637652444u, 287471442u, 2662089150u, 2298526392u, 1119370200u, 478113897u, 1914078872u, 723733797u, 3624950286u, 3707741573u, 842693726u, 1780406925u, 1305032792u, 1968510495u, 2075734367u, 3590755543u, 1450891707u, 83344440u, 3429470524u, 3773462330u, 4241226826u, 3307743815u, 683104062u, 1884612196u, 1017390927u, 1347475469u, 3016083386u, 1524948889u, 1612638509u, 2128788363u, 4182030709u, 3347916223u, 4176020545u, 2603962123u, 2764662049u, 3055322347u, 3694096552u, 458347065u, 1726076036u, 2583701940u, 2714122091u, 4113553423u, 4231559144u, 1222406883u, 2402937181u, 1283962072u, 4009746733u, 3536942113u, 3093850505u, 2103058130u, 2078929575u, 4256494377u, 2744617663u, 1636520641u, 3812371327u, 1841438767u, 853567863u, 293694107u, 1698085228u, 77712651u, 4261360454u, 3773698328u, 1728087008u, 3789317723u, 2829767026u, 4156170415u, 3871260724u, 905192820u, 4275132168u, 2305686413u, 2805314924u, 2583657764u, 465730905u, 4205645334u, 155108597u, 696964616u, 2654681637u, 3442801575u, 2435866492u, 3014889847u, 4131606733u, 3379831463u, 3204498570u, 4096439241u, 2845484976u, 2127645355u, 2247613591u, 2703254578u, 1116237411u, 4213484460u, 4131731766u, 3202543611u, 2320158681u, 2454537032u, 130009356u, 2406857045u, 2990647864u, 1084825589u, 2232163876u, 3955791431u, 253534309u, 274296365u, 3822676536u, 264436337u, 1418207815u, 3310289547u, 986559116u, 3853187406u, 489405686u, 3596088854u, 1335402887u, 787430740u, 981109357u, 1197534756u, 2800306525u, 1916853569u, 284155565u, 2610413878u, 1182968776u, 106675122u, 1210408692u, 4251329608u, 3779855792u, 3736145590u, 1908384358u, 970818599u, 3246626431u, 3742565154u, 2591138191u, 3747660557u, 3364101596u, 2311379507u, 489328382u, 2031550691u, 4202899902u, 1584951024u, 3644694974u, 3312357739u, 217525025u, 3644269603u, 2002321607u, 3954860816u, 1398670148u, 2917504255u, 2706710400u, 220857550u, 989127374u, 2244289149u, 2490586984u, 2642071963u, 2590536648u, 4115793618u, 2576461102u, 1363138228u, 1925983082u, 1189640964u, 152142597u, 1764120035u, 2206817911u, 3313705895u, 1751187711u, 4081059871u, 464054176u, 2379176226u, 1975150787u, 340197618u, 1936526659u, 3404850845u, 2367129719u, 2924126064u, 3459185214u, 2363113359u, 3010128150u, 1881108460u, 3746222960u, 2651248795u, 224163596u, 508682106u, 943524043u, 2151289167u, 1974147403u, 1247690780u, 4116870452u, 2079216305u, 3393218954u, 3567954541u, 1940786677u, 1574417861u, 1432063148u, 2739922267u, 253812427u, 2591454480u, 3182164041u, 1793274063u, 2176665906u, 2497827999u, 858673115u, 3096781115u, 1834782321u, 3629534222u, 724519201u, 4056372476u, 3228503710u, 577268130u, 1582054841u, 301959526u, 4045076624u, 2865028790u, 73755492u, 1825462177u, 3560768027u, 1981121873u, 2691187765u, 188128347u, 2313898662u, 997804738u, 2793909018u, 3725300670u, 3120850068u, 3968046994u, 405825309u, 1595162944u, 3769151350u, 2640525979u, 61684932u, 1415789469u, 1264020135u, 3950226460u, 772728513u, 971672615u, 3978403595u, 588202301u, 292832750u, 1395744634u, 2495776388u, 3271786154u, 2736543666u, 2060545333u, 2797180204u, 141652380u, 3713523292u, 433967869u, 240314286u, 1601436731u, 3508366246u, 2271914741u, 2271704699u, 3087042934u, 2982212958u, 2930329007u, 912272095u, 2555606130u, 2333369619u, 230283885u, 3017301575u, 3446194064u, 4107855164u, 1100310667u, 1909294076u, 434149393u, 366780871u, 3555380811u, 246274064u, 1400899690u, 2703469266u, 570232921u, 3419563051u, 1660365526u, 2968644183u, 1329342932u, 1483085977u, 3122684163u, 4066546606u, 3861009980u, 2234200415u, 2739937896u, 4096595764u, 768251542u, 316090862u, 124090419u, 889195424u, 2979770918u, 3328719122u, 1415047028u, 3926406796u, 1428546568u, 3361029438u, 4211665632u, 1269309700u, 1527101308u, 652172402u, 3674640971u, 3641747964u, 3660382256u, 3370924808u, 115498466u, 1163212438u, 3820703862u, 978439546u, 921271064u, 1378784223u, 3577406236u, 3562940814u, 2671627138u, 3531245640u, 693194205u, 2451064185u, 2578017243u, 2455989585u, 2481212951u, 1228439114u, 3012282683u, 3002755761u, 3856715509u, 3419901832u, 211338799u, 1896610556u, 3548852272u, 1916481449u, 2574085613u, 2000004829u, 2000481307u, 1198464170u, 3173831883u, 2900714882u, 3372201736u, 3881209586u, 2588621608u, 3902089006u, 4177227927u, 3209186455u, 900943443u, 1118888408u, 2571008108u, 2961971973u, 161380270u, 566208408u, 1721643267u, 530432053u, 515707945u, 819921504u, 992966575u, 625914594u, 1250102554u, 2512743175u, 3531636148u, 315086074u, 1566977546u, 3531864233u, 930010731u, 3104844610u, 2733910504u, 3976529992u, 1345375192u, 2115866656u, 1763704995u, 2812700617u, 3160963817u, 3823051215u, 3657060267u, 2312949751u, 322667309u, 1212061965u, 72459214u, 4191705628u, 2896389243u, 156446385u, 4016046429u, 1401209769u, 1582631648u, 4179061694u, 3916756276u, 1567803172u, 2638882606u, 1327787509u, 1976869919u, 519314732u, 2342793709u, 3933183772u, 758814231u, 581874432u, 4123546062u, 1426435462u, 3733828360u, 3854646810u, 359046114u, 2145975155u, 3266914361u, 2642642879u, 4016733328u, 2504537053u, 424148936u, 2998977786u, 2572729225u, 125981442u, 1724033108u, 2267238861u, 4289876504u, 137751831u, 2478124794u, 3552549223u, 1304521882u, 1460229647u, 796181928u, 3636595890u, 745804678u, 1056860767u, 974631484u, 2497485889u, 3198571182u, 4027291544u, 1320904721u, 205244833u, 3484057229u, 231832262u, 3335419183u, 88553761u, 2986770319u, 2926927914u, 3677485767u, 2571089926u, 3267182695u, 489755279u, 671960175u, 3419847717u, 3886885702u, 2653648091u, 211741983u, 301564791u, 2853589419u, 297550915u, 1272390376u, 584147277u, 2971264785u, 3388262418u, 2419292619u, 396848377u, 400462790u, 1021638674u, 3544744847u, 1046459817u, 1131154364u, 450207978u, 974999278u, 3686597032u, 1290348400u, 2998745183u, 1317492534u, 3151398478u, 276900107u, 2794007767u, 1755609205u, 2217365206u, 1595486548u, 1401826344u, 4027763770u, 2842307113u, 2474293622u, 504939907u, 1018556149u, 634870958u, 2105780331u, 84888587u, 1118262728u, 4141601466u, 730125637u, 4167719882u, 949159370u, 531976824u, 3685828907u, 2007510762u, 3599556892u, 2820479277u, 492851583u, 1246337526u, 1940706935u, 3240710205u, 2042152385u, 2397098757u, 3475438049u, 1837355219u, 986711571u, 1147589739u, 1298991474u, 3237271788u, 1639728592u, 3858496958u, 993191411u, 3128643299u, 914694463u, 1747322140u, 1525827943u, 4030035866u, 967493702u, 1097052573u, 2880094426u, 2289918684u, 3468759489u, 4100640951u, 2142548389u, 1149966939u, 79830251u, 1074105259u, 2505154460u, 3984323976u, 3599632907u, 294558951u, 17254381u, 1285914862u, 2776786651u, 2540831914u, 3765303330u, 873163177u, 1692514385u, 2731097567u, 979124410u, 3428974151u, 467084174u, 2154789608u, 1647267729u, 2795216860u, 1039042602u, 3418600624u, 3228166887u, 1002332673u, 3974411194u, 2580583607u, 904733688u, 483022231u, 3917358149u, 2215196638u, 654516857u, 3598498336u, 4099774739u, 3954763417u, 1118670512u, 2139872644u, 3082249575u, 1192330715u, 420290154u, 2802551881u, 2603975185u, 3939768357u, 1474219045u, 2189743776u, 410209795u, 4184120550u, 2546630001u, 847306611u, 1677378142u, 477535865u, 3916441108u, 1277126944u, 2864665523u, 1702604657u, 773876494u, 1807131889u, 3702786021u, 1337776463u, 3572687626u, 2980033697u, 4255621298u, 394586502u, 3130582261u, 1726957441u, 3873244108u, 1267791874u, 3719934631u, 1316393651u, 1375414654u, 453381607u, 568651816u, 2550470125u, 3901112416u, 1214305419u, 3751458762u, 666671791u, 1284096272u, 2828953u, 3723372638u, 1218033032u, 2368557457u, 2365714712u, 848058200u, 3740496416u, 1949250944u, 181477083u, 3214116591u, 3885751315u, 3539347299u, 562529426u, 1283372361u, 3580838576u, 794172702u, 3437985472u, 2640564784u, 3942264960u, 2252660330u, 589714749u, 355166505u, 2167808774u, 3911578180u, 1739283430u, 582727528u, 745486761u, 709694981u, 2470394812u, 2784288873u, 2603686201u, 2503004545u, 921037450u, 248723197u, 2233092030u, 4241673838u, 4248520683u, 4035718652u, 2104169607u, 51010521u, 2984457723u, 2807166639u, 1767043292u, 3958216011u, 149364986u, 186549740u, 1257701956u, 553198631u, 3442166049u, 725301812u, 1488214709u, 3955036524u, 357839254u, 3523734991u, 2195185139u, 3754986293u, 1575537478u, 2389854207u, 3176040305u, 208578128u, 2253741825u, 2553968314u, 3455390865u, 1293117228u, 3508606804u, 1846102791u, 813773800u, 3404247876u, 531259344u, 3216075103u, 3526153030u, 456016676u, 2739749423u, 1093250703u, 69234044u, 792168263u, 3848095809u, 2202850158u, 2213519030u, 1007229102u, 2338703931u, 1765185701u, 2604649447u, 1522222943u, 3266048702u, 1921662655u, 3673686829u, 3415463996u, 1644407479u, 1107992188u, 363565489u, 3321072547u, 3151961821u, 3445798495u, 1425883319u, 4059119275u, 3606696770u, 2834384682u, 1596539449u, 3636233163u, 3557157499u, 3602705437u, 758141738u, 1412595934u, 556283557u, 2057068993u, 3779071200u, 1445808087u, 189318428u, 2040772438u, 2949440024u, 2802944456u, 3151530650u, 722184665u, 1877641340u, 1164797906u, 1631395717u, 1861106618u, 4207596651u, 3412368205u, 1713663690u, 2877098665u, 1890588414u, 2270170721u, 673484753u, 1712353108u, 1400306575u, 3682940464u, 1348885721u, 2224151036u, 3841851095u, 3451954494u, 1060960786u, 437589053u, 1334356198u, 2804921297u, 1756078580u, 3810757529u, 3040883626u, 2579239042u, 616918759u, 2853014080u, 3742299785u, 565628891u, 357151864u, 2285145814u, 1983148904u, 2565821297u, 130519865u, 3057750354u, 3234971651u, 981709724u, 3006660375u, 2608421078u, 921323098u, 1324171014u, 2920168401u, 633540935u, 2393553830u, 1860716086u, 3653638057u, 2418826530u, 2399020543u, 1069386495u, 3873088393u, 1540601308u, 1801814819u, 379787626u, 1538149557u, 3623779521u, 2100185394u, 2590016350u, 1099349030u, 83020443u, 3990751639u, 908730558u, 2004705277u, 566260495u, 1090955400u, 2559442672u, 1852069143u, 1139673340u, 3017343395u, 4132204778u, 1727993619u, 3383152526u, 780997206u, 935658414u, 3677570543u, 1746642030u, 2509125172u, 223854197u, 1604508661u, 1891081055u, 952170820u, 1620251131u, 940572554u, 3971328146u, 2242971249u, 4255333609u, 1861536355u, 3727697922u, 3183876408u, 286776617u, 302578855u, 2532118292u, 3639269404u, 2970666689u, 2920063380u, 1694233198u, 586913821u, 3422958506u, 3686809331u, 1981091823u, 858281024u, 814684694u, 2608505099u, 1816299992u, 2332360436u, 3899354093u, 697179254u, 1558653496u, 24279715u, 4124089548u, 3313503461u, 2741421184u, 3284737548u, 873011879u, 1808479090u, 3455057368u, 244010779u, 303799249u, 2515764191u, 3793164333u, 747991075u, 975903908u, 3129358949u, 1966190241u, 2294762589u, 3495328008u, 1086902846u, 3177987384u, 3938728764u, 867407692u, 3256420714u, 689048646u, 3809767992u, 2344280344u, 295485905u, 928125706u, 788247606u, 1836899313u, 3165702953u, 298675190u, 2992367488u, 2519000176u, 3337159108u, 2044324637u, 2155658777u, 2552272156u, 1827494965u, 2257947328u, 2625243482u, 4130751842u, }; int main( int argc, char * argv[]) { unsigned long i; uint32_t (*funcptr)(void); uint32_t random_value; uint64_t longlong_value; double double_value; volatile uint32_t dummy_long; /* Avoids optimization; see below */ volatile uint64_t dummy_longlong; volatile double dummy_double; uint32_t goodseedresult; FILE* savefile; uint32_t seedresult; static mt_state state; struct rusage then; struct timeval timeofday; static unsigned long timing_loops = TIMING_LOOPS; setbuf(stdout, (char *) NULL); /* * If the user has given a number of timing loops, reset the loop count. */ if (argc > 1) timing_loops = atol(argv[1]) * TIMING_LOOP_BASE; /* * Compare the generated values against corresponding numbers from * Matsumoto and Nishimura's own generator, to make sure we're * doing the calculation correctly. */ (void) printf ("Validity test..."); mt_seed32new(5489); savefile = fopen("mtsave", "w"); mt_savestate(savefile); fclose(savefile); mt_seed32new(1); savefile = fopen("mtsave", "r"); mt_loadstate(savefile); fclose(savefile); unlink("mtsave"); for (i = 0; i < sizeof correct_values / sizeof correct_values[0]; i++) { random_value = mt_lrand(); if (random_value != correct_values[i]) { (void) fprintf (stderr, "Failure at value %ld: expected %" PRIu32 ", got %" PRIu32 "\n", i, correct_values[i], random_value); return 1; } } (void) printf ("passed.\n"); /* * Make sure we can take a pointer to the inlined functions. */ funcptr = &mt_lrand; random_value = (*funcptr)(); /* * Timing tests. Each test sums up the random numbers, not * because we care about the sum, but because the PRNG functions * are inlined. If we don't sum up the numbers (and then assign * them to a volatile), the compiler will optimize the RNG code * right out of existence. */ (void) printf ("%ld default longs took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) random_value += mt_lrand(); report_timing(timing_loops, &then); (void) printf ("%ld state-based longs took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) random_value += mts_lrand(&state); report_timing(timing_loops, &then); dummy_long = random_value; (void)dummy_long; /* Silence compiler warning */ longlong_value = 0; /* * In the case of long longs, there aren't enough registers to * store them on a 32-bit x86, so they wind up on the stack. We'd * get faster timing if we just stored directly into * dummy_longlong. However, this would produce worse results on * more sensibly designed machines. Rather than tune our code to * a broken architecture, we'll stick with the generalized * version. */ (void) printf ("%ld default long longs took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) longlong_value += mt_llrand(); report_timing(timing_loops, &then); (void) printf ("%ld state-based long longs took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) longlong_value += mts_llrand(&state); report_timing(timing_loops, &then); dummy_longlong = longlong_value; (void)dummy_longlong; /* Silence compiler warning */ double_value = 0.0; /* * Similarly, the x86 winds up storing the double-precision sum on * the stack. Again, we'll tolerate that inefficiency. */ (void) printf ("%ld default fast doubles took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) double_value += mt_drand(); report_timing(timing_loops, &then); (void) printf ("%ld state-based fast doubles took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) double_value += mts_drand(&state); report_timing(timing_loops, &then); (void) printf ("%ld default long doubles took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) double_value += mt_ldrand(); report_timing(timing_loops, &then); (void) printf ("%ld state-based long doubles took ", timing_loops); getrusage(RUSAGE_SELF, &then); for (i = 0; i < timing_loops; i++) double_value += mts_ldrand(&state); report_timing(timing_loops, &then); dummy_double = double_value; (void)dummy_double; /* Silence compiler warning */ /* * Test seed timing. */ (void) printf ("Initializing from mt_seed took "); gettimeofday(&timeofday, NULL); seedresult = mt_seed(); report_clock_timing(&timeofday); if (seedresult == 0) (void) printf ("OOPS! Got zero seed from mt_seed!\n"); (void) printf ("Initializing from mt_goodseed took "); gettimeofday(&timeofday, NULL); goodseedresult = mt_goodseed(); report_clock_timing(&timeofday); if (goodseedresult == 0) (void) printf ("OOPS! Got zero seed from mt_goodseed!\n"); if (seedresult == goodseedresult) (void) printf ("OOPS! mt_seed and mt_goodseed both returned 0x%x!\n", seedresult); (void) printf ("Initializing from mt_bestseed took "); gettimeofday(&timeofday, NULL); mt_bestseed(); report_clock_timing(&timeofday); return 0; } static void report_timing( unsigned long loops, /* Number of loops that were done */ struct rusage * then) /* Time test started */ { long diff; /* Difference in times */ long microdiff; /* Microsecond part of difference */ struct rusage now; /* Time test ended */ double secs; /* Actual seconds needed */ getrusage(RUSAGE_SELF, &now); diff = now.ru_utime.tv_sec - then->ru_utime.tv_sec; microdiff = now.ru_utime.tv_usec - then->ru_utime.tv_usec; if (microdiff < 0) { diff--; microdiff += 1000000; } secs = diff + (microdiff / 1000000.0); (void) printf ("%3ld.%6.6ld seconds (%ld/sec).\n", diff, microdiff, (long)(loops / secs)); } static void report_clock_timing( struct timeval * then) /* Time test started */ { long diff; /* Difference in times */ long microdiff; /* Microsecond part of difference */ struct timeval now; /* Time test ended */ double secs; /* Actual seconds needed */ gettimeofday(&now, NULL); diff = now.tv_sec - then->tv_sec; microdiff = now.tv_usec - then->tv_usec; if (microdiff < 0) { diff--; microdiff += 1000000; } secs = diff + (microdiff / 1000000.0); (void) printf ("%3ld.%6.6ld seconds.\n", diff, microdiff); }
79,958
59.620925
76
c
filebench
filebench-master/cvars/mtwist/mtwist.c
#ifndef lint #ifdef __GNUC__ #define ATTRIBUTE(attrs) __attribute__(attrs) #else #define ATTRIBUTE(attrs) #endif static char Rcs_Id[] ATTRIBUTE((used)) = "$Id: mtwist.c,v 1.28 2014-01-23 21:11:42-08 geoff Exp $"; #endif /* * C library functions for generating pseudorandom numbers using the * Mersenne Twist algorithm. See M. Matsumoto and T. Nishimura, * "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform * Pseudo-Random Number Generator", ACM Transactions on Modeling and * Computer Simulation, Vol. 8, No. 1, January 1998, pp 3--30. * * The Web page on the Mersenne Twist algorithm is at: * * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html * * These functions were written by Geoff Kuenning, Claremont, CA. * * IMPORTANT NOTE: this implementation assumes a modern compiler. In * particular, it assumes that the "inline" keyword is available, and * that the "inttypes.h" header file is present. * * IMPORTANT NOTE: this software requires access to a 32-bit type. * The Mersenne Twist algorithms are not guaranteed to produce correct * results with a 64-bit type. * * This software is based on LGPL-ed code by Takuji Nishimura. It has * also been heavily influenced by code written by Shawn Cokus, and * somewhat influenced by code written by Richard J. Wagner. It is * therefore also distributed under the LGPL: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. You should have * received a copy of the GNU Library General Public License along * with this library; if not, write to the Free Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Log: mtwist.c,v $ * Revision 1.28 2014-01-23 21:11:42-08 geoff * Fix an obsolete gettimeofday call * * Revision 1.27 2013-06-12 23:22:03-07 geoff * Validity-check state pointer when saving. * * Revision 1.26 2013-01-01 01:18:52-08 geoff * Fix a lot of comiler warnings. Try to fall back to /dev/random if * /dev/urandom doesn't exist. * * Revision 1.25 2012-12-30 16:24:49-08 geoff * Use gcc attributes to suppress warnings on Rcs_Id. Also get rid of * most of the table of contents, to suppress a different gcc warning. * Fix mts_seed and mts_goodseed to return the 32-bit seeds they chose. * Fix all three /dev/Xrandom seeding functions to use only the entropy * they need, rather than letting stdio eat far more than necessary. * (Thanks to Markus Armbruster for all three ideas.) * * Revision 1.24 2011-02-18 00:49:12-08 geoff * Fix a (harmless) typecasting error in mts_bestseed. Thanks to Waclaw * Kusnierczyk for pointing it out. * * Revision 1.23 2010-12-11 00:28:18+13 geoff * Add support for GENERATE_CODE_IN_HEADER. Fix the URL for the original * Web page. * * Revision 1.22 2010-06-24 20:53:59+12 geoff * Switch to using types and formats from inttypes.h. Get rid of all * compilation options. * * Revision 1.21 2010-06-24 00:29:38-07 geoff * Correctly save and restore the state vector even if longs are wider * than 32 bits. * * Revision 1.20 2007-10-26 00:21:06-07 geoff * Use the new mt_u32bit_t type. * * Revision 1.19 2003/09/11 05:55:19 geoff * Get rid of some minor compiler warnings. * * Revision 1.18 2003/09/11 05:50:53 geoff * Don't #define inline to nothing, since that breaks standard include * files. Instead, use MT_INLINE as a synonym. * * Revision 1.17 2002/10/31 22:07:10 geoff * Make WIN32 detection work with GCC as well as MS C * * Revision 1.16 2002/10/31 22:04:59 geoff * Fix a typo in the WIN32 option * * Revision 1.15 2002/10/31 06:01:43 geoff * Incorporate Joseph Brill's Windows-portability changes * * Revision 1.14 2002/10/30 07:39:53 geoff * Reintroduce the old seeding functions (so that old code will still * produce the same results), and give the new versions new names. * * Revision 1.13 2002/10/30 01:08:26 geoff * Switch to M&T's new initialization method * * Revision 1.12 2001/06/18 05:40:12 geoff * Prefix the compile options with MT_. * * Revision 1.11 2001/06/14 10:26:59 geoff * Invert the sense of the #define flags so that the default is the * normal case (if gcc is normal!). Also default MT_MACHINE_BITS to 32. * * Revision 1.10 2001/06/14 10:10:38 geoff * Move the RNG functions into the header file so they can be inlined. * Add saving/loading of state. Add a function that marks the PRNG as * initialized while also calculating critical constants. Run the * refresh routine whenever seed32 is called. Add functions to seed * based on /dev/random or the time. * * Revision 1.9 2001/06/11 10:00:04 geoff * Major changes to improve flexibility and performance, and to prepare * for inlining. This code is about as fast as it can get without * inlining the various PRNG functions. Add seed/goodseed/bestseed for * seeding from random start values. Add the refresh routine a la Cokus, * but optimize it by unrolling loops. Change getstate to return a * complete state pointer, since knowing the position in the state vector * is critical to restoring state. Add more macros to improve * readability. Rename certain macros in preparation for inlining. Get * rid of leftover optimizer-bug stuff. Stop using mtwist_guts.h; * instead use direct code (via macros) and the refresh function. * * Revision 1.8 2001/04/23 08:36:03 geoff * Move the #defined code into a header file to ease stepping with a debugger. * * Revision 1.7 2001/04/23 08:00:13 geoff * Add code to work around optimizer bug * * Revision 1.6 2001/04/14 01:33:32 geoff * Clarify the license * * Revision 1.5 2001/04/09 08:45:00 geoff * Rename default_state to mt_default_state, and make it global so that * the random-distribution code can use it. * * Revision 1.4 2001/04/07 23:24:11 geoff * My guess in the commentary for the last delta was right: it's faster * on a x86 to convert the two halves of the PRN to double, multiplying * them by the appropriate value to scale them, and then add them as * doubles. I suspect the reason is that there is no instruction to * convert a 64-bit value directly to a double, so the work of building * the long long (which isn't easy anyway, without assembly access) is * worse than wasted. So add support for MT_MACHINE_BITS, and only go * the via-long-long route on a true 64-bit machine. * * Revision 1.3 2001/04/07 23:09:38 geoff * Get rid of MT_INLINE. Convert all of the code to use preprocessor * macros for the guts of the PRNG code. Take advantage of the * conversion to get rid of unnecessary calls initialization tests. Also * clean up the generation of long-double pseudorandom numbers on * machines that have the long long type (by converting first to a long * long, then to a double, saving one floating-point operation). The * latter change might be a mistake on 32-bit machines. The code is now * much faster as a result of macro-izing. * * Revision 1.2 2001/04/07 22:21:41 geoff * Make the long-double code a hair faster by always having a 64-bit * conversion constant. Add commentary to the PRNG loop. * * Revision 1.1 2001/04/07 09:43:41 geoff * Initial revision * */ #ifdef _WIN32 #undef WIN32 #define WIN32 #endif /* _WIN32 */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #ifdef WIN32 #include <sys/timeb.h> #else /* WIN32 */ #include <sys/time.h> #endif /* WIN32 */ #include "mtwist.h" /* * Generate a random number in the range 0 to 2^32-1, inclusive, working * from a given state vector. * * The generator is optimized for speed. The primary optimization is that * the pseudorandom numbers are generated in batches of MT_STATE_SIZE. This * saves the cost of a modulus operation in the critical path. */ uint32_t mts_lrand( register mt_state* state) /* State for the PRNG */ { register uint32_t random_value; /* Pseudorandom value generated */ if (state->stateptr <= 0) mts_refresh(state); random_value = state->statevec[--state->stateptr]; MT_PRE_TEMPER(random_value); return MT_FINAL_TEMPER(random_value); } #ifdef UINT64_MAX /* * Generate a random number in the range 0 to 2^64-1, inclusive, working * from a given state vector. * * According to Matsumoto and Nishimura, such a number can be generated by * simply concatenating two 32-bit pseudorandom numbers. Who am I to argue? * * Note that there is a slight inefficiency here: if the 624-entry state is * recycled on the second call to mts_lrand, there will be an unnecessary * check to see if the state has been initialized. The cost of that check * seems small (since it happens only once every 624 random numbers, and * never if only 64-bit numbers are being generated), so I didn't bother to * optimize it out. Doing so would be messy, since it would require two * nearly-identical internal implementations of mts_lrand. */ uint64_t mts_llrand( register mt_state* state) /* State for the PRNG */ { register uint32_t random_value_1; /* 1st pseudorandom value generated */ register uint32_t random_value_2; /* 2nd pseudorandom value generated */ /* * For maximum speed, we'll handle the two overflow cases * together. That will save us one test in the common case, at * the expense of an extra one in the overflow case. */ if (--state->stateptr <= 0) { if (state->stateptr < 0) { mts_refresh(state); random_value_1 = state->statevec[--state->stateptr]; } else { random_value_1 = state->statevec[state->stateptr]; mts_refresh(state); } } else random_value_1 = state->statevec[state->stateptr]; MT_TEMPER(random_value_1); random_value_2 = state->statevec[--state->stateptr]; MT_PRE_TEMPER(random_value_2); return ((uint64_t) random_value_1 << 32) | (uint64_t) MT_FINAL_TEMPER(random_value_2); } #endif /* UINT64_MAX */ /* * Generate a double-precision random number between 0 (inclusive) and 1.0 * (exclusive). This function is optimized for speed, but it only generates * 32 bits of precision. Use mts_ldrand to get 64 bits of precision. */ double mts_drand( register mt_state* state) /* State for the PRNG */ { register uint32_t random_value; /* Pseudorandom value generated */ if (state->stateptr <= 0) mts_refresh(state); random_value = state->statevec[--state->stateptr]; MT_TEMPER(random_value); return random_value * mt_32_to_double; } /* * Generate a double-precision random number between 0 (inclusive) and 1.0 * (exclusive). This function generates 64 bits of precision. Use * mts_drand for more speed but less precision. */ double mts_ldrand( register mt_state* state) /* State for the PRNG */ { #ifdef UINT64_MAX uint64_t final_value; /* Final (integer) value */ #endif /* UINT64_MAX */ register uint32_t random_value_1; /* 1st pseudorandom value generated */ register uint32_t random_value_2; /* 2nd pseudorandom value generated */ /* * For maximum speed, we'll handle the two overflow cases * together. That will save us one test in the common case, at * the expense of an extra one in the overflow case. */ if (--state->stateptr <= 0) { if (state->stateptr < 0) { mts_refresh(state); random_value_1 = state->statevec[--state->stateptr]; } else { random_value_1 = state->statevec[state->stateptr]; mts_refresh(state); } } else random_value_1 = state->statevec[state->stateptr]; MT_TEMPER(random_value_1); random_value_2 = state->statevec[--state->stateptr]; MT_TEMPER(random_value_2); #ifdef UINT64_MAX final_value = ((uint64_t) random_value_1 << 32) | (uint64_t) random_value_2; return final_value * mt_64_to_double; #else /* UINT64_MAX */ return random_value_1 * mt_32_to_double + random_value_2 * mt_64_to_double; #endif /* UINT64_MAX */ } /* * Generate a random number in the range 0 to 2^32-1, inclusive, working * from the default state vector. * * See mts_lrand for full commentary. */ uint32_t mt_lrand(void) { register uint32_t random_value; /* Pseudorandom value generated */ if (mt_default_state.stateptr <= 0) mts_refresh(&mt_default_state); random_value = mt_default_state.statevec[--mt_default_state.stateptr]; MT_PRE_TEMPER(random_value); return MT_FINAL_TEMPER(random_value); } #ifdef UINT64_MAX /* * Generate a random number in the range 0 to 2^64-1, inclusive, working * from the default state vector. * * See mts_llrand for full commentary. */ uint64_t mt_llrand(void) { register uint32_t random_value_1; /* 1st pseudorandom value generated */ register uint32_t random_value_2; /* 2nd pseudorandom value generated */ /* * For maximum speed, we'll handle the two overflow cases * together. That will save us one test in the common case, at * the expense of an extra one in the overflow case. */ if (--mt_default_state.stateptr <= 0) { if (mt_default_state.stateptr < 0) { mts_refresh(&mt_default_state); random_value_1 = mt_default_state.statevec[--mt_default_state.stateptr]; } else { random_value_1 = mt_default_state.statevec[mt_default_state.stateptr]; mts_refresh(&mt_default_state); } } else random_value_1 = mt_default_state.statevec[mt_default_state.stateptr]; MT_TEMPER(random_value_1); random_value_2 = mt_default_state.statevec[--mt_default_state.stateptr]; MT_PRE_TEMPER(random_value_2); return ((uint64_t) random_value_1 << 32) | (uint64_t) MT_FINAL_TEMPER(random_value_2); } #endif /* UINT64_MAX */ /* * Generate a double-precision random number between 0 (inclusive) and 1.0 * (exclusive). This function is optimized for speed, but it only generates * 32 bits of precision. Use mt_ldrand to get 64 bits of precision. */ double mt_drand(void) { register uint32_t random_value; /* Pseudorandom value generated */ if (mt_default_state.stateptr <= 0) mts_refresh(&mt_default_state); random_value = mt_default_state.statevec[--mt_default_state.stateptr]; MT_TEMPER(random_value); return random_value * mt_32_to_double; } /* * Generate a double-precision random number between 0 (inclusive) and 1.0 * (exclusive). This function generates 64 bits of precision. Use * mts_drand for more speed but less precision. */ double mt_ldrand(void) { #ifdef UINT64_MAX uint64_t final_value; /* Final (integer) value */ #endif /* UINT64_MAX */ register uint32_t random_value_1; /* 1st pseudorandom value generated */ register uint32_t random_value_2; /* 2nd pseudorandom value generated */ /* * For maximum speed, we'll handle the two overflow cases * together. That will save us one test in the common case, at * the expense of an extra one in the overflow case. */ if (--mt_default_state.stateptr <= 0) { if (mt_default_state.stateptr < 0) { mts_refresh(&mt_default_state); random_value_1 = mt_default_state.statevec[--mt_default_state.stateptr]; } else { random_value_1 = mt_default_state.statevec[mt_default_state.stateptr]; mts_refresh(&mt_default_state); } } else random_value_1 = mt_default_state.statevec[mt_default_state.stateptr]; MT_TEMPER(random_value_1); random_value_2 = mt_default_state.statevec[--mt_default_state.stateptr]; MT_TEMPER(random_value_2); #ifdef UINT64_MAX final_value = ((uint64_t) random_value_1 << 32) | (uint64_t) random_value_2; return final_value * mt_64_to_double; #else /* UINT64_MAX */ return random_value_1 * mt_32_to_double + random_value_2 * mt_64_to_double; #endif /* UINT64_MAX */ } #ifdef __cplusplus /* * Save state to a stream. See mts_savestate. */ std::ostream& operator<<( std::ostream& stream, // Stream to save to const mt_prng& rng) // PRNG to save { for (int i = MT_STATE_SIZE; --i >= 0; ) { if (!(stream << rng.state.statevec[i] << ' ')) return stream; } return stream << rng.state.stateptr; } /* * Restore state from a stream. See mts_loadstate. */ std::istream& operator>>( std::istream& stream, // Stream to laod from mt_prng& rng) // PRNG to load { rng.state.initialized = rng.state.stateptr = 0; for (int i = MT_STATE_SIZE; --i >= 0; ) { if (!(stream >> rng.state.statevec[i])) return stream; } if (!(stream >> rng.state.stateptr)) { rng.state.stateptr = 0; return stream; } /* * If the state is invalid, all we can do is to make it uninitialized. */ if (rng.state.stateptr < 0 || rng.state.stateptr > MT_STATE_SIZE) { rng.state.stateptr = 0; return stream; } mts_mark_initialized(&rng.state); return stream; } #endif /* __cplusplus */ /* * Table of (non-global) contents: */ static uint32_t mts_devseed(mt_state* state, char* seed_dev); /* Choose seed from a device */ /* * The following values are fundamental parameters of the algorithm. * With the exception of the two masks, all of them were found * experimentally using methods described in Matsumoto and Nishimura's * paper. They are exceedingly magic; don't change them. */ /* MT_STATE_SIZE is defined in the header file. */ #define RECURRENCE_OFFSET 397 /* Offset into state space for the */ /* ..recurrence relation. The */ /* ..recurrence mashes together two */ /* ..values that are separated by */ /* ..this offset in the state */ /* ..space. */ #define MATRIX_A 0x9908b0df /* Constant vector A for the */ /* ..recurrence relation. The */ /* ..mashed-together value is */ /* ..multiplied by this vector to */ /* ..get a new value that will be */ /* ..stored into the state space. */ /* * Width of an unsigned int. Don't change this even if your ints are 64 bits. */ #define BIT_WIDTH 32 /* Work with 32-bit words */ /* * Masks for extracting the bits to be mashed together. The widths of these * masks are also fundamental parameters of the algorithm, determined * experimentally -- but of course the masks themselves are simply bit * selectors. */ #define UPPER_MASK 0x80000000 /* Most significant w-r bits */ #define LOWER_MASK 0x7fffffff /* Least significant r bits */ /* * Macro to simplify code in the generation loop. This function * combines the top bit of x with the bottom 31 bits of y. */ #define COMBINE_BITS(x, y) \ (((x) & UPPER_MASK) | ((y) & LOWER_MASK)) /* * Another generation-simplification macro. This one does the magic * scrambling function. */ #define MATRIX_MULTIPLY(original, new) \ ((original) ^ ((new) >> 1) \ ^ matrix_decider[(new) & 0x1]) /* * Parameters of Knuth's PRNG (Line 25, Table 1, p. 102 of "The Art of * Computer Programming, Vol. 2, 2nd ed, 1981). */ #define KNUTH_MULTIPLIER_OLD \ 69069 /* * Parameters of Knuth's PRNG (p. 106 of "The Art of Computer * Programming, Vol. 2, 3rd ed). */ #define KNUTH_MULTIPLIER_NEW \ 1812433253ul #define KNUTH_SHIFT 30 // Even on a 64-bit machine! /* * Default 32-bit random seed if mts_seed32 wasn't called */ #define DEFAULT_SEED32_OLD \ 4357 #define DEFAULT_SEED32_NEW \ 5489ul /* * Where to get random numbers */ #define DEVRANDOM "/dev/random" #define DEVURANDOM "/dev/urandom" /* * Many applications need only a single PRNG, so it's a nuisance to have to * specify a state. For those applications, we will provide a default * state, and functions to use it. */ mt_state mt_default_state; /* * To generate double-precision random numbers, we need to divide the result * of mts_lrand or mts_llrand by 2^32 or 2^64, respectively. The quickest * way to do that on most machines is to multiply by the inverses of those * numbers. However, I don't trust the compiler to correctly convert the * corresponding decimal constant. So we will compute the correct number at * run time as part of initialization, which will produce a nice exact * result. */ double mt_32_to_double; /* Multiplier to convert long to dbl */ double mt_64_to_double; /* Mult'r to cvt long long to dbl */ /* * In the recurrence relation, the new value is XORed with MATRIX_A only if * the lower bit is nonzero. Since most modern machines don't like to * branch, it's vastly faster to handle this decision by indexing into an * array. The chosen bit is used as an index into the following vector, * which produces either zero or MATRIX_A and thus the desired effect. */ static uint32_t matrix_decider[2] = {0x0, MATRIX_A}; /* * Mark a PRNG's state as having been initialized. This is the only * way to set that field nonzero; that way we can be sure that the * constants are set properly before the PRNG is used. * * As a side effect, set up some constants that the PRNG assumes are * valid. These are calculated at initialization time rather than * being written as decimal constants because I frankly don't trust * the compiler's ASCII conversion routines. */ void mts_mark_initialized( mt_state* state) /* State vector to mark initialized */ { int i; /* Power of 2 being calculated */ /* * Figure out the proper multiplier for long-to-double conversion. We * don't worry too much about efficiency, since the assumption is that * initialization is vastly rarer than generation of random numbers. */ mt_32_to_double = 1.0; for (i = 0; i < BIT_WIDTH; i++) mt_32_to_double /= 2.0; mt_64_to_double = mt_32_to_double; for (i = 0; i < BIT_WIDTH; i++) mt_64_to_double /= 2.0; state->initialized = 1; } /* * Initialize a Mersenne Twist PRNG from a 32-bit seed. * * According to Matsumoto and Nishimura's paper, the seed array needs to be * filled with nonzero values. (My own interpretation is that there needs * to be at least one nonzero value). They suggest using Knuth's PRNG from * Line 25, Table 1, p.102, "The Art of Computer Programming," Vol. 2 (2nd * ed.), 1981. I find that rather odd, since that particular PRNG is * sensitive to having an initial seed of zero (there are many other PRNGs * out there that have an additive component, so that a seed of zero does * not generate a repeating-zero sequence). However, one thing I learned * from reading Knuth is that you shouldn't second-guess mathematicians * about PRNGs. Also, by following M & N's approach, we will be compatible * with other implementations. So I'm going to stick with their version, * with the single addition that a zero seed will be changed to their * default seed. */ void mts_seed32( mt_state* state, /* State vector to initialize */ uint32_t seed) /* 32-bit seed to start from */ { int i; /* Loop index */ if (seed == 0) seed = DEFAULT_SEED32_OLD; /* * Fill the state vector using Knuth's PRNG. Be sure to mask down * to 32 bits in case we're running on a machine with 64-bit * ints. */ state->statevec[MT_STATE_SIZE - 1] = seed & 0xffffffff; for (i = MT_STATE_SIZE - 2; i >= 0; i--) state->statevec[i] = (KNUTH_MULTIPLIER_OLD * state->statevec[i + 1]) & 0xffffffff; state->stateptr = MT_STATE_SIZE; mts_mark_initialized(state); /* * Matsumoto and Nishimura's implementation refreshes the PRNG * immediately after running the Knuth algorithm. This is * probably a good thing, since Knuth's PRNG doesn't generate very * good numbers. */ mts_refresh(state); } /* * Initialize a Mersenne Twist PRNG from a 32-bit seed, using * Matsumoto and Nishimura's newer reference implementation (Jan. 9, * 2002). */ void mts_seed32new( mt_state* state, /* State vector to initialize */ uint32_t seed) /* 32-bit seed to start from */ { int i; /* Loop index */ uint32_t nextval; /* Next value being calculated */ /* * Fill the state vector using Knuth's PRNG. Be sure to mask down * to 32 bits in case we're running on a machine with 64-bit * ints. */ state->statevec[MT_STATE_SIZE - 1] = seed & 0xffffffffUL; for (i = MT_STATE_SIZE - 2; i >= 0; i--) { nextval = state->statevec[i + 1] >> KNUTH_SHIFT; nextval ^= state->statevec[i + 1]; nextval *= KNUTH_MULTIPLIER_NEW; nextval += (MT_STATE_SIZE - 1) - i; state->statevec[i] = nextval & 0xffffffffUL; } state->stateptr = MT_STATE_SIZE; mts_mark_initialized(state); /* * Matsumoto and Nishimura's implementation refreshes the PRNG * immediately after running the Knuth algorithm. This is * probably a good thing, since Knuth's PRNG doesn't generate very * good numbers. */ mts_refresh(state); } /* * Initialize a Mersenne Twist RNG from a 624-int seed. * * The 32-bit seeding routine given by Matsumoto and Nishimura has the * drawback that there are only 2^32 different PRNG sequences that can be * generated by calling that function. This function solves that problem by * allowing a full 624*32-bit state to be given. (Note that 31 bits of the * given state are ignored; see the paper for details.) * * Since an all-zero state would cause the PRNG to cycle, we detect * that case and abort the program (silently, since there is no * portable way to produce a message in both C and C++ environments). * An alternative would be to artificially force the state to some * known nonzero value. However, I feel that if the user is providing * a full state, it's a bug to provide all zeros and we we shouldn't * conceal the bug by generating apparently correct output. */ void mts_seedfull( mt_state* state, /* State vector to initialize */ uint32_t seeds[MT_STATE_SIZE]) /* Seed array to start from */ { int had_nz = 0; /* NZ if at least one NZ seen */ int i; /* Loop index */ for (i = 0; i < MT_STATE_SIZE; i++) { if (seeds[i] != 0) had_nz = 1; state->statevec[MT_STATE_SIZE - i - 1] = seeds[i]; } if (!had_nz) { /* * It would be nice to abort with a message. Unfortunately, fprintf * isn't compatible with all implementations of C++. In the * interest of C++ compatibility, therefore, we will simply abort * silently. It will unfortunately be up to a programmer to run * under a debugger (or examine the core dump) to discover the cause * of the abort. */ abort(); } state->stateptr = MT_STATE_SIZE; mts_mark_initialized(state); } /* * Choose a seed based on some moderately random input. Prefers * /dev/urandom as a source of random numbers, but uses the lower bits * of the current time if /dev/urandom is not available. In any case, * only provides 32 bits of entropy. */ uint32_t mts_seed( mt_state* state) /* State vector to seed */ { return mts_devseed(state, DEVURANDOM); } /* * Choose a seed based on some fairly random input. Prefers * /dev/random as a source of random numbers, but uses the lower bits * of the current time if /dev/random is not available. In any case, * only provides 32 bits of entropy. */ uint32_t mts_goodseed( mt_state* state) /* State vector to seed */ { return mts_devseed(state, DEVRANDOM); } /* * Choose a seed based on a random-number device given by the caller. * If that device can't be opened, use the lower 32 bits from the * current time. */ static uint32_t mts_devseed( mt_state* state, /* State vector to seed */ char* seed_dev) /* Device to seed from */ { int bytesread; /* Byte count read from device */ int nextbyte; /* Index of next byte to read */ FILE* ranfile; /* Access to device */ union { char ranbuffer[sizeof (uint32_t)]; /* Space for reading random int */ uint32_t randomvalue; /* Random value for initialization */ } randomunion; /* Union for reading random int */ #ifdef WIN32 struct _timeb tb; /* Time of day (Windows mode) */ #else /* WIN32 */ struct timeval tv; /* Time of day */ #endif /* WIN32 */ ranfile = fopen(seed_dev, "rb"); /* * Some machines have /dev/random but not /dev/urandom. On those * machines, /dev/random is nonblocking, so we'll try it before we * fall back to using the time. */ if (ranfile == NULL) ranfile = fopen(DEVRANDOM, "rb"); if (ranfile != NULL) { setbuf(ranfile, NULL); for (nextbyte = 0; nextbyte < (int)sizeof randomunion.ranbuffer; nextbyte += bytesread) { bytesread = fread(&randomunion.ranbuffer[nextbyte], (size_t)1, sizeof randomunion.ranbuffer - nextbyte, ranfile); if (bytesread == 0) break; } fclose(ranfile); if (nextbyte == sizeof randomunion.ranbuffer) { mts_seed32new(state, randomunion.randomvalue); return randomunion.randomvalue; } } /* * The device isn't available. Use the time. We will * assume that the time of day is accurate to microsecond * resolution, which is true on most modern machines. */ #ifdef WIN32 (void) _ftime (&tb); #else /* WIN32 */ (void) gettimeofday (&tv, NULL); #endif /* WIN32 */ /* * We just let the excess part of the seconds field overflow */ #ifdef WIN32 randomunion.randomvalue = tb.time * 1000 + tb.millitm; #else /* WIN32 */ randomunion.randomvalue = tv.tv_sec * 1000000 + tv.tv_usec; #endif /* WIN32 */ mts_seed32new(state, randomunion.randomvalue); return randomunion.randomvalue; } /* * Choose a seed based on the best random input available. Prefers * /dev/random as a source of random numbers, and reads the entire * 624-int state from that device. Because of this approach, the * function can take a long time (in real time) to complete, since * /dev/random may have to wait quite a while before it can provide * that much randomness. If /dev/random is unavailable, falls back to * calling mts_goodseed. */ void mts_bestseed( mt_state* state) /* State vector to seed */ { int bytesread; /* Byte count read from device */ int nextbyte; /* Index of next byte to read */ FILE* ranfile; /* Access to device */ ranfile = fopen("/dev/random", "rb"); if (ranfile == NULL) { mts_goodseed(state); return; } for (nextbyte = 0; nextbyte < (int)sizeof state->statevec; nextbyte += bytesread) { bytesread = fread((char *)&state->statevec[0] + nextbyte, (size_t)1, sizeof state->statevec - nextbyte, ranfile); if (bytesread == 0) { /* * Something went wrong. Fall back to time-based seeding. */ fclose(ranfile); mts_goodseed(state); return; } } fclose(ranfile); } /* * Generate 624 more random values. This function is called when the * state vector has been exhausted. It generates another batch of * pseudo-random values. The performance of this function is critical * to the performance of the Mersenne Twist PRNG, so it has been * highly optimized. */ void mts_refresh( register mt_state* state) /* State for the PRNG */ { register int i; /* Index into the state */ register uint32_t* state_ptr; /* Next place to get from state */ register uint32_t value1; /* Scratch val picked up from state */ register uint32_t value2; /* Scratch val picked up from state */ /* * Start by making sure a random seed has been set. If not, set * one. */ if (!state->initialized) { mts_seed32(state, DEFAULT_SEED32_OLD); return; /* Seed32 calls us recursively */ } /* * Now generate the new pseudorandom values by applying the * recurrence relation. We use two loops and a final * 2-statement sequence so that we can handle the wraparound * explicitly, rather than having to use the relatively slow * modulus operator. * * In essence, the recurrence relation concatenates bits * chosen from the current random value (last time around) * with the immediately preceding one. Then it * matrix-multiplies the concatenated bits with a value * RECURRENCE_OFFSET away and a constant matrix. The matrix * multiplication reduces to a shift and two XORs. * * Some comments on the optimizations are in order: * * Strictly speaking, none of the optimizations should be * necessary. All could conceivably be done by a really good * compiler. However, the compilers available to me aren't quite * smart enough, so hand optimization needs to be done. * * Shawn Cokus was the first to achieve a major speedup. In the * original code, the first value given to COMBINE_BITS (in my * characterization) was re-fetched from the state array, rather * than being carried in a scratch variable. Cokus noticed that * the first argument to COMBINE_BITS could be saved in a register * in the previous loop iteration, getting rid of the need for an * expensive memory reference. * * Cokus also switched to using pointers to access the state * array and broke the original loop into two so that he could * avoid using the expensive modulus operator. Cokus used three * pointers; Richard J. Wagner noticed that the offsets between * the three were constant, so that they could be collapsed into a * single pointer and constant-offset accesses. This is clearly * faster on x86 architectures, and is the same cost on RISC * machines. A secondary benefit is that Cokus' version was * register-starved on the x86, while Wagner's version was not. * * I made several smaller improvements to these observations. * First, I reversed the contents of the state vector. In the * current version of the code, this change doesn't directly * affect the performance of the refresh loop, but it has the nice * side benefit that an all-zero state structure represents an * uninitialized generator. It also slightly speeds up the * random-number routines, since they can compare the state * pointer against zero instead of against a constant (this makes * the biggest difference on RISC machines). * * Second, I returned to Matsumoto and Nishimura's original * technique of using a lookup table to decide whether to xor the * constant vector A (MATRIX_A in this code) with the newly * computed value. Cokus and Wagner had used the ?: operator, * which requires a test and branch. Modern machines don't like * branches, so the table lookup is faster. * * Third, in the Cokus and Wagner versions the loop ends with a * statement similar to "value1 = value2", which is necessary to * carry the fetched value into the next loop iteration. I * recognized that if the loop were unrolled so that it generates * two values per iteration, a bit of variable renaming would get * rid of that assignment. A nice side effect is that the * overhead of loop control becomes only half as large. * * It is possible to improve the code's performance somewhat * further. In particular, since the second loop's loop count * factors into 2*2*3*3*11, it could be unrolled yet further. * That's easy to do, too: just change the "/ 2" into a division * by whatever factor you choose, and then use cut-and-paste to * duplicate the code in the body. To remove a few more cycles, * fix the code to decrement state_ptr by the unrolling factor, and * adjust the various offsets appropriately. However, the payoff * will be small. At the moment, the x86 version of the loop is * 25 instructions, of which 3 are involved in loop control * (including the decrementing of state_ptr). Further unrolling by * a factor of 2 would thus produce only about a 6% speedup. * * The logical extension of the unrolling * approach would be to remove the loops and create 624 * appropriate copies of the body. However, I think that doing * the latter is a bit excessive! * * I suspect that a superior optimization would be to simplify the * mathematical operations involved in the recurrence relation. * However, I have no idea whether such a simplification is * feasible. */ state_ptr = &state->statevec[MT_STATE_SIZE - 1]; value1 = *state_ptr; for (i = (MT_STATE_SIZE - RECURRENCE_OFFSET) / 2; --i >= 0; ) { state_ptr -= 2; value2 = state_ptr[1]; value1 = COMBINE_BITS(value1, value2); state_ptr[2] = MATRIX_MULTIPLY(state_ptr[-RECURRENCE_OFFSET + 2], value1); value1 = state_ptr[0]; value2 = COMBINE_BITS(value2, value1); state_ptr[1] = MATRIX_MULTIPLY(state_ptr[-RECURRENCE_OFFSET + 1], value2); } value2 = *--state_ptr; value1 = COMBINE_BITS(value1, value2); state_ptr[1] = MATRIX_MULTIPLY(state_ptr[-RECURRENCE_OFFSET + 1], value1); for (i = (RECURRENCE_OFFSET - 1) / 2; --i >= 0; ) { state_ptr -= 2; value1 = state_ptr[1]; value2 = COMBINE_BITS(value2, value1); state_ptr[2] = MATRIX_MULTIPLY(state_ptr[MT_STATE_SIZE - RECURRENCE_OFFSET + 2], value2); value2 = state_ptr[0]; value1 = COMBINE_BITS(value1, value2); state_ptr[1] = MATRIX_MULTIPLY(state_ptr[MT_STATE_SIZE - RECURRENCE_OFFSET + 1], value1); } /* * The final entry in the table requires the "previous" value * to be gotten from the other end of the state vector, so it * must be handled specially. */ value1 = COMBINE_BITS(value2, state->statevec[MT_STATE_SIZE - 1]); *state_ptr = MATRIX_MULTIPLY(state_ptr[MT_STATE_SIZE - RECURRENCE_OFFSET], value1); /* * Now that refresh is complete, reset the state pointer to allow more * pseudorandom values to be fetched from the state array. */ state->stateptr = MT_STATE_SIZE; } /* * Save state to a file. The save format is compatible with Richard * J. Wagner's format, although the details are different. Returns NZ * if the save succeeded. Produces one very long line containing 625 * numbers. */ int mts_savestate( FILE* statefile, /* File to save to */ mt_state* state) /* State to be saved */ { int i; /* Next word to save */ if (!state->initialized) mts_seed32(state, DEFAULT_SEED32_OLD); /* * Ensure the state pointer is valid. */ if (state->stateptr < 0 || state->stateptr > MT_STATE_SIZE) { fprintf(stderr, "Mtwist internal: Trying to write invalid state pointer %d\n", state->stateptr); mts_refresh(state); } for (i = MT_STATE_SIZE; --i >= 0; ) { if (fprintf(statefile, "%" PRIu32 " ", state->statevec[i]) < 0) return 0; } if (fprintf(statefile, "%d\n", state->stateptr) < 0) return 0; return 1; } /* * Load state from a file. Returns NZ if the load succeeded. */ int mts_loadstate( FILE* statefile, /* File to load from */ mt_state* state) /* State to be loaded */ { int i; /* Next word to load */ /* * Set the state to "uninitialized" in case the load fails. */ state->initialized = state->stateptr = 0; for (i = MT_STATE_SIZE; --i >= 0; ) { if (fscanf(statefile, "%" SCNu32, &state->statevec[i]) != 1) return 0; } if (fscanf(statefile, "%d", &state->stateptr) != 1) return 0; /* * The only validity checking we can do is to insist that the * state pointer be valid. */ if (state->stateptr < 0 || state->stateptr > MT_STATE_SIZE) { state->stateptr = 0; return 0; } mts_mark_initialized(state); return 1; } /* * Initialize the default Mersenne Twist PRNG from a 32-bit seed. * * See mts_seed32 for full commentary. */ void mt_seed32( uint32_t seed) /* 32-bit seed to start from */ { mts_seed32(&mt_default_state, seed); } /* * Initialize the default Mersenne Twist PRNG from a 32-bit seed. * * See mts_seed32new for full commentary. */ void mt_seed32new( uint32_t seed) /* 32-bit seed to start from */ { mts_seed32new(&mt_default_state, seed); } /* * Initialize a Mersenne Twist RNG from a 624-int seed. * * See mts_seedfull for full commentary. */ void mt_seedfull( uint32_t seeds[MT_STATE_SIZE]) { mts_seedfull(&mt_default_state, seeds); } /* * Initialize the PRNG from random input. See mts_seed. */ uint32_t mt_seed(void) { return mts_seed(&mt_default_state); } /* * Initialize the PRNG from random input. See mts_goodseed. */ uint32_t mt_goodseed(void) { return mts_goodseed(&mt_default_state); } /* * Initialize the PRNG from random input. See mts_bestseed. */ void mt_bestseed(void) { mts_bestseed(&mt_default_state); } /* * Return a pointer to the current state of the PRNG. The purpose of * this function is to allow the state to be saved for later * restoration. The state should not be modified; instead, it should * be reused later as a parameter to one of the mts_xxx functions. */ mt_state* mt_getstate(void) { return &mt_default_state; } /* * Save state to a file. The save format is compatible with Richard * J. Wagner's format, although the details are different. */ int mt_savestate( FILE* statefile) /* File to save to */ { return mts_savestate(statefile, &mt_default_state); } /* * Load state from a file. */ int mt_loadstate( FILE* statefile) /* File to load from */ { return mts_loadstate(statefile, &mt_default_state); }
42,083
32.137008
80
c
filebench
filebench-master/cvars/mtwist/mtwist.h
#ifndef MTWIST_H #define MTWIST_H /* * $Id: mtwist.h,v 1.24 2012-12-31 22:22:03-08 geoff Exp $ * * Header file for C/C++ use of the Mersenne-Twist pseudo-RNG. See * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html for full * information. * * Author of this header file: Geoff Kuenning, March 18, 2001. * * IMPORTANT NOTE: this implementation assumes a modern compiler. In * particular, it assumes that the "inline" keyword is available, and * that the "stdint.h" header file is present. * * The variables above are defined in an inverted sense because I * expect that most modern compilers will support these features. By * inverting the sense, this common case will require no special * compiler flags. * * IMPORTANT NOTE: this software requires access to a 32-bit type. * The Mersenne Twist algorithms are not guaranteed to produce correct * results with a 64-bit type. * * The executable part of this software is based on LGPL-ed code by * Takuji Nishimura. The header file is therefore also distributed * under the LGPL: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. You should have * received a copy of the GNU Library General Public License along * with this library; if not, write to the Free Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Log: mtwist.h,v $ * Revision 1.24 2012-12-31 22:22:03-08 geoff * Fix the out-of-bounds bug in mt_llrand and mt_ldrand that were * overlooked because I assumed they used mts_*. * * Revision 1.23 2013-01-01 01:18:52-08 geoff * Fix a lot of compiler warnings. * * Revision 1.22 2012-12-30 16:24:49-08 geoff * Declare the new versions of the /dev/random and urandom seeding * functions, which now return the seed chosen. * * Revision 1.21 2012-09-23 23:15:40-07 geoff * Fix an array index violation found by valgrind and reported by David * Chapman; under some circumstances statevec[-1] could be accessed and * used in random-number generation. The bug only affects the *_llrand * and *_ldrand functions. * * Revision 1.20 2010-12-10 03:28:18-08 geoff * Add support for GENERATE_CODE_IN_HEADER. Fix the URL for the original * Web page. * * Revision 1.19 2010-06-24 20:53:59+12 geoff * Switch to using types from stdint.h. Get rid of all compilation * options. * * Revision 1.18 2010-06-24 00:29:38-07 geoff * Do a better job of auto-determining MT_MACHINE_BITS. * * Revision 1.17 2007-10-26 00:21:06-07 geoff * Introduce, document, and use the new mt_u32bit_t type so that the code * will compile and run on 64-bit platforms (although it does not * currently use the 64-bit Mersenne Twist algorithm). * * Revision 1.16 2005/11/11 08:21:39 geoff * If possible, try to infer MT_MACHINE_BITS from limits.h. * * Revision 1.15 2003/09/11 23:56:20 geoff * Allow stdio references in C++ files; it turns out that ANSI has * blessed it. Declare the various functions as external even if they're * inlined or being compiled directly (in mtwist.c). Get rid of a #ifdef * that can't ever be true. * * Revision 1.14 2003/09/11 05:50:53 geoff * Don't allow stdio references from C++, since they're not guaranteed to * work on all compilers. Disable inlining using the MT_INLINE keyword * rather than #defining inline, since doing the latter can affect other * files and functions than our own. * * Revision 1.13 2003/07/01 23:29:29 geoff * Refer to streams from the standard library using the correct namespace. * * Revision 1.12 2002/10/30 07:39:54 geoff * Declare the new seeding functions. * * Revision 1.11 2001/06/19 00:41:16 geoff * For consistency with other C++ types, don't put out a newline after * the saved data. * * Revision 1.10 2001/06/18 10:09:24 geoff * Fix some places where I forgot to set one of the result values. Make * the C++ state vector protected so the random-distributions package can * pass it to the C functions. * * Revision 1.9 2001/06/18 05:40:12 geoff * Prefix the compile options with MT_. * * Revision 1.8 2001/06/14 10:26:59 geoff * Invert the sense of the #define flags so that the default is the * normal case (if gcc is normal!). Also default MT_MACHINE_BITS to 32. * * Revision 1.7 2001/06/14 10:10:38 geoff * Move the critical-path PRNG code into the header file so that it can * be inlined. Add saving/loading of state. Add functions to seed based * on /dev/random or the time. Add the function-call operator in the C++ * code. * * Revision 1.6 2001/06/11 10:00:04 geoff * Add declarations of the refresh and /dev/random seeding functions. * Change getstate to return a complete state pointer, since knowing the * position in the state vector is critical to restoring the state. * * Revision 1.5 2001/04/23 08:36:03 geoff * Remember to zero the state pointer when constructing, since otherwise * proper initialization won't happen. * * Revision 1.4 2001/04/14 01:33:32 geoff * Clarify the license * * Revision 1.3 2001/04/14 01:04:54 geoff * Add a C++ class, mt_prng, that makes usage more convenient for C++ * programmers. * * Revision 1.2 2001/04/09 08:45:00 geoff * Fix the name in the #ifndef wrapper, and clean up some outdated comments. * * Revision 1.1 2001/04/07 09:43:41 geoff * Initial revision * */ #include <stdio.h> #ifdef __cplusplus #include <iostream> #endif /* __cplusplus */ #define __STDC_LIMIT_MACROS #include <stdint.h> /* * The following value is a fundamental parameter of the algorithm. * It was found experimentally using methods described in Matsumoto * and Nishimura's paper. It is exceedingly magic; don't change it. */ #define MT_STATE_SIZE 624 /* Size of the MT state vector */ /* * Internal state for an MT RNG. The user can keep multiple mt_state * structures around as a way of generating multiple streams of random * numbers. * * In Matsumoto and Nishimura's original paper, the state vector was * processed in a forward direction. I have reversed the state vector * in this implementation. The reason for the reversal is that it * allows the critical path to use a test against zero instead of a * test against 624 to detect the need to refresh the state. on most * machines, testing against zero is slightly faster. It also means * that a state that has been set to all zeros will be correctly * detected as needing initialization; this means that setting a state * vector to zero (either with memset or by statically allocating it) * will cause the RNG to operate properly. */ typedef struct { uint32_t statevec[MT_STATE_SIZE]; /* Vector holding current state */ int stateptr; /* Next state entry to be used */ int initialized; /* NZ if state was initialized */ } mt_state; #ifdef __cplusplus extern "C" { #endif /* * Functions for manipulating any generator (given a state pointer). */ extern void mts_mark_initialized(mt_state* state); /* Mark a PRNG state as initialized */ extern void mts_seed32(mt_state* state, uint32_t seed); /* Set random seed for any generator */ extern void mts_seed32new(mt_state* state, uint32_t seed); /* Set random seed for any generator */ extern void mts_seedfull(mt_state* state, uint32_t seeds[MT_STATE_SIZE]); /* Set complicated seed for any gen. */ extern uint32_t mts_seed(mt_state* state); /* Choose seed from random input. */ /* ..Prefers /dev/urandom; uses time */ /* ..if /dev/urandom unavailable. */ /* ..Only gives 32 bits of entropy. */ /* ..Returns seed usable with seed32 */ extern uint32_t mts_goodseed(mt_state* state); /* Choose seed from more random */ /* ..input than mts_seed. Prefers */ /* ../dev/random; uses time if that */ /* ..is unavailable. Only gives 32 */ /* ..bits of entropy. */ /* ..Returns seed usable with seed32 */ extern void mts_bestseed(mt_state* state); /* Choose seed from extremely random */ /* ..input (can be *very* slow). */ /* ..Prefers /dev/random and reads */ /* ..the entire state from there. */ /* ..If /dev/random is unavailable, */ /* ..falls back to mt_goodseed(). */ /* ..Not usually worth the cost. */ extern void mts_refresh(mt_state* state); /* Generate 624 more random values */ extern int mts_savestate(FILE* statefile, mt_state* state); /* Save state to a file (ASCII). */ /* ..Returns NZ if succeeded. */ extern int mts_loadstate(FILE* statefile, mt_state* state); /* Load state from a file (ASCII). */ /* ..Returns NZ if succeeded. */ /* * Functions for manipulating the default generator. */ extern void mt_seed32(uint32_t seed); /* Set random seed for default gen. */ extern void mt_seed32new(uint32_t seed); /* Set random seed for default gen. */ extern void mt_seedfull(uint32_t seeds[MT_STATE_SIZE]); /* Set complicated seed for default */ extern uint32_t mt_seed(void); /* Choose seed from random input. */ /* ..Prefers /dev/urandom; uses time */ /* ..if /dev/urandom unavailable. */ /* ..Only gives 32 bits of entropy. */ extern uint32_t mt_goodseed(void); /* Choose seed from more random */ /* ..input than mts_seed. Prefers */ /* ../dev/random; uses time if that */ /* ..is unavailable. Only gives 32 */ /* ..bits of entropy. */ extern void mt_bestseed(void); /* Choose seed from extremely random */ /* ..input (can be *very* slow). */ /* ..Prefers /dev/random and reads */ /* ..the entire state from there. */ /* ..If /dev/random is unavailable, */ /* ..falls back to mt_goodseed(). */ /* ..Not usually worth the cost. */ extern mt_state* mt_getstate(void); /* Get current state of default */ /* ..generator */ extern int mt_savestate(FILE* statefile); /* Save state to a file (ASCII) */ /* ..Returns NZ if succeeded. */ extern int mt_loadstate(FILE* statefile); /* Load state from a file (ASCII) */ /* ..Returns NZ if succeeded. */ #ifdef __cplusplus } #endif /* * Functions for generating random numbers. The actual code of the * functions is given in this file so that it can be declared inline. * For compilers that don't have the inline feature, mtwist.c will * incorporate this file with some clever #defining so that the code * actually gets compiled. In that case, however, "extern" * definitions will be needed here, so we give them. */ #ifdef __cplusplus #endif /* __cplusplus */ extern uint32_t mts_lrand(mt_state* state); /* Generate 32-bit value, any gen. */ #ifdef UINT64_MAX extern uint64_t mts_llrand(mt_state* state); /* Generate 64-bit value, any gen. */ #endif /* UINT64_MAX */ extern double mts_drand(mt_state* state); /* Generate floating value, any gen. */ /* Fast, with only 32-bit precision */ extern double mts_ldrand(mt_state* state); /* Generate floating value, any gen. */ /* Slower, with 64-bit precision */ extern uint32_t mt_lrand(void); /* Generate 32-bit random value */ #ifdef UINT64_MAX extern uint64_t mt_llrand(void); /* Generate 64-bit random value */ #endif /* UINT64_MAX */ extern double mt_drand(void); /* Generate floating value */ /* Fast, with only 32-bit precision */ extern double mt_ldrand(void); /* Generate floating value */ /* Slower, with 64-bit precision */ /* * Tempering parameters. These are perhaps the most magic of all the magic * values in the algorithm. The values are again experimentally determined. * The values generated by the recurrence relation (constants above) are not * equidistributed in 623-space. For some reason, the tempering process * produces that effect. Don't ask me why. Read the paper if you can * understand the math. Or just trust these magic numbers. */ #define MT_TEMPERING_MASK_B 0x9d2c5680 #define MT_TEMPERING_MASK_C 0xefc60000 #define MT_TEMPERING_SHIFT_U(y) \ (y >> 11) #define MT_TEMPERING_SHIFT_S(y) \ (y << 7) #define MT_TEMPERING_SHIFT_T(y) \ (y << 15) #define MT_TEMPERING_SHIFT_L(y) \ (y >> 18) /* * Macros to do the tempering. MT_PRE_TEMPER does all but the last step; * it's useful for situations where the final step can be incorporated * into a return statement. MT_FINAL_TEMPER does that final step (not as * an assignment). MT_TEMPER does the entire process. Note that * MT_PRE_TEMPER and MT_TEMPER both modify their arguments. */ #define MT_PRE_TEMPER(value) \ do \ { \ value ^= MT_TEMPERING_SHIFT_U(value); \ value ^= MT_TEMPERING_SHIFT_S(value) & MT_TEMPERING_MASK_B; \ value ^= MT_TEMPERING_SHIFT_T(value) & MT_TEMPERING_MASK_C; \ } \ while (0) #define MT_FINAL_TEMPER(value) \ ((value) ^ MT_TEMPERING_SHIFT_L(value)) #define MT_TEMPER(value) \ do \ { \ value ^= MT_TEMPERING_SHIFT_U(value); \ value ^= MT_TEMPERING_SHIFT_S(value) & MT_TEMPERING_MASK_B; \ value ^= MT_TEMPERING_SHIFT_T(value) & MT_TEMPERING_MASK_C; \ value ^= MT_TEMPERING_SHIFT_L(value); \ } \ while (0) /* * The Mersenne Twist PRNG makes it default state available as an * external variable. This feature is undocumented, but is useful to * use because it allows us to avoid implementing every randistr function * twice. (In fact, the feature was added to enable randistrs.c to be * written. It would be better to write in C++, where I could control * the access to the state.) */ extern mt_state mt_default_state; /* State of the default generator */ extern double mt_32_to_double; /* Multiplier to convert long to dbl */ extern double mt_64_to_double; /* Mult'r to cvt long long to dbl */ #ifdef __cplusplus /* * C++ interface to the Mersenne Twist PRNG. This class simply * provides a more C++-ish way to access the PRNG. Only state-based * functions are provided. All functions are inlined, both for speed * and so that the same implementation code can be used in C and C++. */ class mt_prng { friend class mt_empirical_distribution; public: /* * Constructors and destructors. The default constructor * leaves initialization (seeding) for later unless pickSeed * is true, in which case the seed is chosen based on either * /dev/urandom (if available) or the system time. The other * constructors accept either a 32-bit seed, or a full * 624-integer seed. */ mt_prng( // Default constructor bool pickSeed = false) // True to get seed from /dev/urandom // ..or time { state.stateptr = 0; state.initialized = 0; if (pickSeed) (void)mts_seed(&state); } mt_prng(uint32_t newseed) // Construct with 32-bit seeding { state.stateptr = 0; state.initialized = 0; mts_seed32(&state, newseed); } mt_prng(uint32_t seeds[MT_STATE_SIZE]) // Construct with full seeding { state.stateptr = 0; state.initialized = 0; mts_seedfull(&state, seeds); } ~mt_prng() { } /* * Copy and assignment are best left defaulted. */ /* * PRNG seeding functions. */ void seed32(uint32_t newseed) // Set 32-bit random seed { mts_seed32(&state, newseed); } void seed32new(uint32_t newseed) // Set 32-bit random seed { mts_seed32new(&state, newseed); } void seedfull(uint32_t seeds[MT_STATE_SIZE]) // Set complicated random seed { mts_seedfull(&state, seeds); } uint32_t seed() // Choose seed from random input { return mts_seed(&state); } uint32_t goodseed() // Choose better seed from random input { return mts_goodseed(&state); } void bestseed() // Choose best seed from random input { mts_bestseed(&state); } friend std::ostream& operator<<(std::ostream& stream, const mt_prng& rng); friend std::istream& operator>>(std::istream& stream, mt_prng& rng); /* * PRNG generation functions */ uint32_t lrand() // Generate 32-bit pseudo-random value { return mts_lrand(&state); } #ifdef UINT64_MAX uint64_t llrand() // Generate 64-bit pseudo-random value { return mts_llrand(&state); } #endif /* UINT64_MAX */ double drand() // Generate fast 32-bit floating value { return mts_drand(&state); } double ldrand() // Generate slow 64-bit floating value { return mts_ldrand(&state); } /* * Following Richard J. Wagner's example, we overload the * function-call operator to return a 64-bit floating value. * That allows the common use of the PRNG to be simplified as * in the following example: * * mt_prng ranno(true); * // ... * coinFlip = ranno() >= 0.5 ? heads : tails; */ double operator()() { return mts_drand(&state); } protected: /* * Protected data */ mt_state state; // Current state of the PRNG }; #endif /* __cplusplus */ #endif /* MTWIST_H */
17,513
34.168675
76
h
filebench
filebench-master/cvars/mtwist/randistrs.c
#ifndef lint #ifdef __GNUC__ #define ATTRIBUTE(attrs) __attribute__(attrs) #else #define ATTRIBUTE(attrs) #endif static char Rcs_Id[] ATTRIBUTE((used)) = "$Id: randistrs.c,v 1.12 2013-01-05 01:18:52-08 geoff Exp $"; #endif /* * C library functions for generating various random distributions * using the Mersenne Twist PRNG. See the header file for full * documentation. * * These functions were written by Geoff Kuenning, Claremont, CA. * * Unless otherwise specified, these algorithms are taken from Averill * M. Law and W. David Kelton, "Simulation Modeling and Analysis", * McGraw-Hill, 1991. * * IMPORTANT NOTE: By default, this code is reentrant. If you are * certain you don't need reentrancy, you can get a bit more speed by * defining MT_CACHING. * * Copyright 2001, 2002, 2010, Geoffrey H. Kuenning, Claremont, CA. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All modifications to the source code must be clearly marked as * such. Binary redistributions based on modified source code * must be clearly marked as modified versions in the documentation * and/or other materials provided with the distribution. * 4. The name of Geoff Kuenning may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $Log: randistrs.c,v $ * Revision 1.12 2013-01-05 01:18:52-08 geoff * Fix a lot of compiler warnings. Allow rd_empirical_setup to take * const arguments. * * Revision 1.11 2012-12-30 16:24:49-08 geoff * Use gcc attributes to suppress warnings on Rcs_Id. * * Revision 1.10 2010-12-10 03:28:19-08 geoff * Rewrite the empirical-distribution interface to run in O(1) time and * to provide a continuous approximation to empirical distributions. * * Revision 1.9 2010-06-24 20:53:59+12 geoff * Switch to using types from stdint.h. Make reentrancy the default. * * Revision 1.8 2008-07-25 16:34:01-07 geoff * Fix notation for intervals in commentary. * * Revision 1.7 2005/05/17 21:40:10 geoff * Fix a bug that caused rds_iuniform to generate off-by-one values if the * lower bound was negative. * * Revision 1.6 2002/10/30 00:50:44 geoff * Add a (BSD-style) license. Fix all places where logs are taken so * that there is no risk of unintentionally taking the log of zero. This * is a very low-probability occurrence, but it's better to have robust * code. * * Revision 1.5 2001/06/20 09:07:57 geoff * Fix a place where long long wasn't conditionalized. * * Revision 1.4 2001/06/19 00:41:17 geoff * Add the "l" versions of all functions. Add the MT_NO_CACHING option. * * Revision 1.3 2001/06/18 10:09:24 geoff * Add the iuniform functions to generate unbiased uniformly distributed * integers. * * Revision 1.2 2001/04/10 09:11:38 geoff * Make sure the Erlang distribution has a p of 1 or more. Fix a serious * bug in the Erlang calculation (the value returned was completely * wrong). * * Revision 1.1 2001/04/09 08:39:54 geoff * Initial revision * */ #include "mtwist.h" #include "randistrs.h" #include <math.h> #include <stdlib.h> /* * Threshold below which it is OK for uniform integer distributions to make * use of the double-precision code as a crutch. For ranges below * this value, a double-precision random value is generated and then * mapped to the given range. For a lower bound of zero, this is * equivalent to mapping a 32-bit integer into the range by using the * following formula: * * final = upper * mt_lrand() / (1 << 32); * * That formula can't be computed using integer arithmetic, since the * multiplication must precede the division and would cause overflow. * Double-precision calculations solve that problem. However the * formula will also produce biased results unless the range ("upper") * is exactly a power of 2. To see this, suppose mt_lrand produced * values from 0 to 7 (i.e., 8 values), and we asked for numbers in * the range [0, 7). The 8 values uniformly generated by mt_lrand * would be mapped into the 7 output values. Clearly, one output * value (in this case, 4) would occur twice as often as the others * * The amount of bias introduced by this approximation depends on the * relative sizes of the requested range and the range of values * produced by mt_lrand. If the ranges are almost equal, some values * will occur almost twice as often as they should. At the other * extreme, consider a requested range of 3 values (0 to 2, * inclusive). If the PRNG cycles through all 2^32 possible values, * two of the output values will be generated 1431655765 times and the * third will appear 1431655766 times. Clearly, the bias here is * within the expected limits of randomness. * * The exact amount of bias depends on the relative size of the range * compared to the width of the PRNG output. In general, for an * output range of r, no value will appear more than r/(2^32) extra * times using the simple integer algorithm. * * The threshold given below will produce a bias of under 0.01%. For * values above this threshold, a slower but 100% accurate algorithm * will be used. */ #ifndef RD_MAX_BIAS #define RD_MAX_BIAS 0.0001 #endif /* RD_MAX_BIAS */ #ifndef RD_UNIFORM_THRESHOLD #define RD_UNIFORM_THRESHOLD ((int)((double)(1u << 31) * 2.0 * RD_MAX_BIAS)) #endif /* RD_UNIFORM_THRESHOLD */ /* * Generate a uniform integer distribution on the open interval * [lower, upper). See comments above about RD_UNIFORM_THRESHOLD. If * we are above the threshold, this function is relatively expensive * because we may have to repeatedly draw random numbers to get a * one that works. */ int32_t rds_iuniform( mt_state * state, /* State of the MT PRNG to use */ int32_t lower, /* Lower limit of distribution */ int32_t upper) /* Upper limit of distribution */ { uint32_t range = upper - lower; /* Range of requested distribution */ if (range <= RD_UNIFORM_THRESHOLD) return lower + (int32_t)(mts_ldrand(state) * range); else { /* * Using the simple formula would produce too much bias. * Instead, draw numbers until we get one within the range. * To save time, we first calculate a mask so that we only * look at the number of bits we actually need. Since finding * the mask is expensive, we optionally do a bit of caching * here (note that the caching makes the code non-reentrant; * set MT_CACHING to turn on this misfeature). * * Incidentally, the astute reader will note that we use the * low-order bits of the PRNG output. If the PRNG were linear * congruential, using the low-order bits wouuld be a major * no-no. However, the Mersenne Twist PRNG doesn't have that * drawback. */ #ifdef MT_CACHING static uint32_t lastrange = 0; /* Range used last time */ static uint32_t rangemask = 0; /* Mask for range */ #else /* MT_CACHING */ uint32_t rangemask = 0; /* Mask for range */ #endif /* MT_CACHING */ register uint32_t ranval; /* Random value from mts_lrand */ #ifdef MT_CACHING if (range != lastrange) #endif /* MT_CACHING */ { /* * Range is different from last time, recalculate mask. * * A few iterations could be trimmed off of the loop if we * started rangemask at the next power of 2 above * RD_UNIFORM_THRESHOLD. However, I don't currently know * a formula for generating that value (though there is * probably one in HAKMEM). */ #ifdef MT_CACHING lastrange = range; #endif /* MT_CACHING */ for (rangemask = 1; rangemask < range && rangemask != 0; rangemask <<= 1) ; /* * If rangemask became zero, the range is over 2^31. In * that case, subtracting 1 from rangemask will produce a * full-word mask, which is what we need. */ rangemask -= 1; } /* * Draw random numbers until we get one in the requested range. */ do { ranval = mts_lrand(state) & rangemask; } while (ranval >= range); return lower + ranval; } } #ifdef INT64_MAX /* * Generate a uniform integer distribution on the half-open interval * [lower, upper). */ int64_t rds_liuniform( mt_state * state, /* State of the MT PRNG to use */ int64_t lower, /* Lower limit of distribution */ int64_t upper) /* Upper limit of distribution */ { uint64_t range = upper - lower; /* Range of requested distribution */ /* * Draw numbers until we get one within the range. To save time, * we first calculate a mask so that we only look at the number of * bits we actually need. Since finding the mask is expensive, we * optionally do a bit of caching here. See rds_iuniform for more * information. */ #ifdef MT_CACHING static uint32_t lastrange = 0; /* Range used last time */ static uint32_t rangemask = 0; /* Mask for range */ #else /* MT_CACHING */ uint32_t rangemask = 0; /* Mask for range */ #endif /* MT_CACHING */ register uint32_t ranval; /* Random value from mts_lrand */ #ifdef MT_CACHING if (range != lastrange) #endif /* MT_CACHING */ { /* * Range is different from last time, recalculate mask. */ #ifdef MT_CACHING lastrange = range; #endif /* MT_CACHING */ for (rangemask = 1; rangemask < range && rangemask != 0; rangemask <<= 1) ; /* * If rangemask became zero, the range is over 2^31. In * that case, subtracting 1 from rangemask will produce a * full-word mask, which is what we need. */ rangemask -= 1; } /* * Draw random numbers until we get one in the requested range. */ do { ranval = mts_llrand(state) & rangemask; } while (ranval >= range); return lower + ranval; } #endif /* INT64_MAX */ /* * Generate a uniform distribution on the half-open interval [lower, upper). */ double rds_uniform( mt_state * state, /* State of the MT PRNG to use */ double lower, /* Lower limit of distribution */ double upper) /* Upper limit of distribution */ { return lower + mts_drand(state) * (upper - lower); } /* * Generate a uniform distribution on the half-open interval [lower, upper). */ double rds_luniform( mt_state * state, /* State of the MT PRNG to use */ double lower, /* Lower limit of distribution */ double upper) /* Upper limit of distribution */ { return lower + mts_ldrand(state) * (upper - lower); } /* * Generate an exponential distribution with the given mean. */ double rds_exponential( mt_state * state, /* State of the MT PRNG to use */ double mean) /* Mean of generated distribution */ { double random_value; /* Random sample on [0,1) */ do random_value = mts_drand(state); while (random_value == 0.0); return -mean * log(random_value); } /* * Generate an exponential distribution with the given mean. */ double rds_lexponential( mt_state * state, /* State of the MT PRNG to use */ double mean) /* Mean of generated distribution */ { double random_value; /* Random sample on [0,1) */ do random_value = mts_ldrand(state); while (random_value == 0.0); return -mean * log(random_value); } /* * Generate a p-Erlang distribution with the given mean. */ double rds_erlang( mt_state * state, /* State of the MT PRNG to use */ int p, /* Order of distribution to generate */ double mean) /* Mean of generated distribution */ { int order; /* Order generated so far */ double random_value; /* Value generated so far */ do { if (p <= 1) p = 1; random_value = mts_drand(state); for (order = 1; order < p; order++) random_value *= mts_drand(state); } while (random_value == 0.0); return -mean * log(random_value) / p; } /* * Generate a p-Erlang distribution with the given mean. */ double rds_lerlang( mt_state * state, /* State of the MT PRNG to use */ int p, /* Order of distribution to generate */ double mean) /* Mean of generated distribution */ { int order; /* Order generated so far */ double random_value; /* Value generated so far */ do { if (p <= 1) p = 1; random_value = mts_ldrand(state); for (order = 1; order < p; order++) random_value *= mts_ldrand(state); } while (random_value == 0.0); return -mean * log(random_value) / p; } /* * Generate a Weibull distribution with the given shape and scale parameters. */ double rds_weibull( mt_state * state, /* State of the MT PRNG to use */ double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { double random_value; /* Random sample on [0,1) */ do random_value = mts_drand(state); while (random_value == 0.0); return scale * exp(log(-log(random_value)) / shape); } /* Weibull distribution */ /* * Generate a Weibull distribution with the given shape and scale parameters. */ double rds_lweibull( mt_state * state, /* State of the MT PRNG to use */ double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { double random_value; /* Random sample on [0,1) */ do random_value = mts_ldrand(state); while (random_value == 0.0); return scale * exp(log(-log(random_value)) / shape); } /* Weibull distribution */ /* * Generate a normal distribution with the given mean and standard * deviation. See Law and Kelton, p. 491. */ double rds_normal( mt_state * state, /* State of the MT PRNG to use */ double mean, /* Mean of generated distribution */ double sigma) /* Standard deviation to generate */ { double mag; /* Magnitude of (x,y) point */ double offset; /* Unscaled offset from mean */ double xranval; /* First random value on [-1,1) */ double yranval; /* Second random value on [-1,1) */ /* * Generating a normal distribution is a bit tricky. We may need * to make several attempts before we get a valid result. When we * are done, we will have two normally distributed values, one of * which we discard. */ do { xranval = 2.0 * mts_drand(state) - 1.0; yranval = 2.0 * mts_drand(state) - 1.0; mag = xranval * xranval + yranval * yranval; } while (mag > 1.0 || mag == 0.0); offset = sqrt((-2.0 * log(mag)) / mag); return mean + sigma * xranval * offset; /* * The second random variate is given by: * * mean + sigma * yranval * offset; * * If this were a C++ function, it could probably save that value * somewhere and return it in the next subsequent call. But * that's too hard to make bulletproof (and reentrant) in C. */ } /* * Generate a normal distribution with the given mean and standard * deviation. See Law and Kelton, p. 491. */ double rds_lnormal( mt_state * state, /* State of the MT PRNG to use */ double mean, /* Mean of generated distribution */ double sigma) /* Standard deviation to generate */ { double mag; /* Magnitude of (x,y) point */ double offset; /* Unscaled offset from mean */ double xranval; /* First random value on [-1,1) */ double yranval; /* Second random value on [-1,1) */ /* * Generating a normal distribution is a bit tricky. We may need * to make several attempts before we get a valid result. When we * are done, we will have two normally distributed values, one of * which we discard. */ do { xranval = 2.0 * mts_ldrand(state) - 1.0; yranval = 2.0 * mts_ldrand(state) - 1.0; mag = xranval * xranval + yranval * yranval; } while (mag > 1.0 || mag == 0.0); offset = sqrt((-2.0 * log(mag)) / mag); return mean + sigma * xranval * offset; /* * The second random variate is given by: * * mean + sigma * yranval * offset; * * If this were a C++ function, it could probably save that value * somewhere and return it in the next subsequent call. But * that's too hard to make bulletproof (and reentrant) in C. */ } /* * Generate a lognormal distribution with the given shape and scale * parameters. */ double rds_lognormal( mt_state * state, /* State of the MT PRNG to use */ double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { return exp(rds_normal(state, scale, shape)); } /* * Generate a lognormal distribution with the given shape and scale * parameters. */ double rds_llognormal( mt_state * state, /* State of the MT PRNG to use */ double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { return exp(rds_lnormal(state, scale, shape)); } /* * Generate a triangular distibution between given limits, with a * given mode. */ double rds_triangular( mt_state * state, /* State of the MT PRNG to use */ double lower, /* Lower limit of distribution */ double upper, /* Upper limit of distribution */ double mode) /* Highest point of distribution */ { double ran_value; /* Value generated by PRNG */ double scaled_mode; /* Scaled version of mode */ scaled_mode = (mode - lower) / (upper - lower); ran_value = mts_drand(state); if (ran_value <= scaled_mode) ran_value = sqrt(scaled_mode * ran_value); else ran_value = 1.0 - sqrt((1.0 - scaled_mode) * (1.0 - ran_value)); return lower + (upper - lower) * ran_value; } /* * Generate a triangular distibution between given limits, with a * given mode. */ double rds_ltriangular( mt_state * state, /* State of the MT PRNG to use */ double lower, /* Lower limit of distribution */ double upper, /* Upper limit of distribution */ double mode) /* Highest point of distribution */ { double ran_value; /* Value generated by PRNG */ double scaled_mode; /* Scaled version of mode */ scaled_mode = (mode - lower) / (upper - lower); ran_value = mts_ldrand(state); if (ran_value <= scaled_mode) ran_value = sqrt(scaled_mode * ran_value); else ran_value = 1.0 - sqrt((1.0 - scaled_mode) * (1.0 - ran_value)); return lower + (upper - lower) * ran_value; } /* * Generate a discrete integer empirical distribution given a set of * probability cutoffs. See rd_empirical_setup for full information. */ size_t rds_int_empirical( mt_state * state, /* State of the MT PRNG to use */ rd_empirical_control* control) /* Control from rd_empirical_setup */ { double ran_value; /* Value generated by PRNG */ size_t result; /* Result we'll return */ ran_value = mts_ldrand(state); ran_value *= control->n; /* Scale value to required range */ result = (size_t)ran_value; /* Integer part MIGHT be result */ if (ran_value < control->cutoff[result]) /* Correct probability? */ return result; /* Done! */ else return control->remap[result]; /* Nope, remap to correct result */ } /* * Generate a discrete floating-point empirical distribution given a * set of probability cutoffs. Use the result of rds_int_empirical to * choose a final value. */ double rds_double_empirical( mt_state * state, /* State of the MT PRNG to use */ rd_empirical_control* control) /* Control from rd_empirical_setup */ { return control->values[rds_int_empirical(state, control)]; } /* * Generate a continuous floating-point empirical distribution given a * set of probability cutoffs. Use the result of rds_int_empirical to * choose a pair of values, and then return a uniform distribution * between those two values. */ double rds_continuous_empirical( mt_state * state, /* State of the MT PRNG to use */ rd_empirical_control* control) /* Control from rd_empirical_setup */ { size_t index; /* Index into values table */ index = rds_int_empirical(state, control); return control->values[index] + mts_ldrand(state) * (control->values[index + 1] - control->values[index]); } /* * Generate a uniform integer distribution on the half-open interval * [lower, upper). See comments on rds_iuniform. */ int32_t rd_iuniform( int32_t lower, /* Lower limit of distribution */ int32_t upper) /* Upper limit of distribution */ { return rds_iuniform(&mt_default_state, lower, upper); } #ifdef INT64_MAX /* * Generate a uniform integer distribution on the open interval * [lower, upper). See comments on rds_iuniform. */ int64_t rd_liuniform( int64_t lower, /* Lower limit of distribution */ int64_t upper) /* Upper limit of distribution */ { return rds_liuniform(&mt_default_state, lower, upper); } #endif /* INT64_MAX */ /* * Generate a uniform distribution on the open interval [lower, upper). */ double rd_uniform( double lower, /* Lower limit of distribution */ double upper) /* Upper limit of distribution */ { return rds_uniform (&mt_default_state, lower, upper); } /* * Generate a uniform distribution on the open interval [lower, upper). */ double rd_luniform( double lower, /* Lower limit of distribution */ double upper) /* Upper limit of distribution */ { return rds_luniform (&mt_default_state, lower, upper); } /* * Generate an exponential distribution with the given mean. */ double rd_exponential( double mean) /* Mean of generated distribution */ { return rds_exponential (&mt_default_state, mean); } /* * Generate an exponential distribution with the given mean. */ double rd_lexponential( double mean) /* Mean of generated distribution */ { return rds_lexponential (&mt_default_state, mean); } /* * Generate a p-Erlang distribution with the given mean. */ double rd_erlang( int p, /* Order of distribution to generate */ double mean) /* Mean of generated distribution */ { return rds_erlang (&mt_default_state, p, mean); } /* * Generate a p-Erlang distribution with the given mean. */ double rd_lerlang( int p, /* Order of distribution to generate */ double mean) /* Mean of generated distribution */ { return rds_lerlang (&mt_default_state, p, mean); } /* * Generate a Weibull distribution with the given shape and scale parameters. */ double rd_weibull( double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { return rds_weibull (&mt_default_state, shape, scale); } /* * Generate a Weibull distribution with the given shape and scale parameters. */ double rd_lweibull( double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { return rds_lweibull (&mt_default_state, shape, scale); } /* * Generate a normal distribution with the given mean and standard * deviation. See Law and Kelton, p. 491. */ double rd_normal( double mean, /* Mean of generated distribution */ double sigma) /* Standard deviation to generate */ { return rds_normal (&mt_default_state, mean, sigma); } /* * Generate a normal distribution with the given mean and standard * deviation. See Law and Kelton, p. 491. */ double rd_lnormal( double mean, /* Mean of generated distribution */ double sigma) /* Standard deviation to generate */ { return rds_lnormal (&mt_default_state, mean, sigma); } /* * Generate a lognormal distribution with the given shape and scale * parameters. */ double rd_lognormal( double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { return rds_lognormal (&mt_default_state, shape, scale); } /* * Generate a lognormal distribution with the given shape and scale * parameters. */ double rd_llognormal( double shape, /* Shape of the distribution */ double scale) /* Scale of the distribution */ { return rds_llognormal (&mt_default_state, shape, scale); } /* * Generate a triangular distibution between given limits, with a * given mode. */ double rd_triangular( double lower, /* Lower limit of distribution */ double upper, /* Upper limit of distribution */ double mode) { return rds_triangular (&mt_default_state, lower, upper, mode); } /* * Generate a triangular distibution between given limits, with a * given mode. */ double rd_ltriangular( double lower, /* Lower limit of distribution */ double upper, /* Upper limit of distribution */ double mode) { return rds_ltriangular (&mt_default_state, lower, upper, mode); } /* * Set up to calculate an empirical distribution in O(1) time. The * method used is adapted from Alastair J. Walker, "An efficient * method for generating discrete random variables with general * distributions", ACM Transactions on Mathematical Software 3, * 253-256 (1977). Walker's algorithm required O(N^2) setup time; * this code uses the O(N) setup approach devised by James Theiler of * LANL, as documented in commentary ini the Gnu Scientific Library. * We also use a modification suggested by Donald E. Knuth, The Art of * Computer Programming, Volume 2 (Seminumerical algorithms), 3rd * edition, Addison-Wesley (1997), p120. * * The essence of Walker's approach is to observe that each empirical * probabilitiy is either above or below the uniform probability by * some amount. Suppose the probability pi of the i-th element is * smaller than the uniform probability (1/n). Then if we choose a * uniformly distributed random integer, i will appear too often; to * be precise, it will appear 1/n - pi too frequently. Walker's idea * is that there must be some other element, j, that has a probability * pj that is above uniform. So if we "push" the 1/n - pi "extra" * probability of element i onto element j, we will decrease the * probability of i appearing and increase the probability of j. We * can do this by selecting a "cutoff" value which is to be compared * to a random number x on [0,1); if x exceeds the cutoff, we remap to * element j. The cutoff is selected such that this happens exactly * (1/n - pi) / (1/n) = 1 - n*pi of the time, since that's the amount * of extra probability that needs to be pushed onto j. * * For example, suppose there are only two probabilities, 0.25 and * 0.75. Element 0 will be selected 0.5 of the time, so we must remap * half of those selections to j. The cutoff is chosen as 1 - 2*0.25 * = 0.5. Presto! * * In general, element j won't need precisely the amount of extra * stuff remapped from element i. If it needs more, that's OK; there * will be some other element k that has a probability below uniform, * and we can also map its extra onto j. If j needs *less* extra, * then we'll do a remap on it as well, pushing that extra onto yet * another element--but only if j was selected directly in the initial * uniform distribution. (All of these adjustments are done by * modifying the calculated difference between j's probability and the * uniform distribution.) This produces the rather odd result that j * both accepts and donates probability, but it all works out in the * end. * * The trick is then to calculate the cutoff and remap arrays. The * formula for the cutoff values was given above. At each step, * Walker scans the current probability array to find the elements * that are most "out of balance" on both the high and low ends; the * low one is then remapped to the high. The loop is repeated until * all probabilities differ from uniform by less than predetermined * threshold. This is an O(N^2) algorithm; it can also be troublesome * if the threshold is in appropriate for the data at hand. * * Theiler's improvement involves noting that if a probability is * below uniform ("small"), it will never become "large". That means * we can keep two tables, one each of small and large values. For * convenience, the tables are organized as stacks. At each step, a * value is popped from each stack, and the small one is remapped to * the large one by calculating a cutoff. The large value is then * placed back on the appropriate stack. (For efficiency, the * implementation doesn't pop from the large stack unless necessary.) * * Finally, Knuth's improvements: Walker's original paper suggested * drawing two uniform random numbers when generating from the * empirical distribution: one to select an element, and a second to * compare to the cutoff. Knuth points out that if the random numbers * have sufficient entropy (which is certainly true for the Mersenne * Twister), we can use the upper bits to choose a slot and the lower * ones to compare against the cutoff. This is done by taking s = n*r * (where r is the double-precision random value), and then using * int(s) as the slot and frac(s) as the cutoff. The final * improvement is that we can avoid calculating frac(s) if, when * setting the cutoff c, we store i + c instead of c, where i is the * slot number. */ rd_empirical_control* rd_empirical_setup( size_t n_probs, /* Number of probabilities provide */ const double* probs, /* Probability (weight) table */ const double* values) /* Value for floating distributions */ { rd_empirical_control* control; /* Control structure we'll build */ size_t i; /* General loop index */ size_t j; /* Element from stack_high */ size_t n_high; /* Current size of stack_high */ size_t n_low; /* Current size of stack_low */ size_t* stack_high; /* Stack of values above uniform */ size_t* stack_low; /* Stack of values below uniform */ double prob_total; /* Total of all weights */ control = (rd_empirical_control*)malloc(sizeof *control); if (control == NULL) return NULL; control->n = n_probs; control->cutoff = (double*)malloc(n_probs * sizeof (double)); control->remap = (size_t*)malloc(n_probs * sizeof (size_t)); control->values = (double*)malloc((n_probs + 1) * sizeof (double)); if (control->cutoff == NULL || control->remap == NULL || control->values == NULL) { rd_empirical_free(control); return NULL; } if (values != NULL) { /* * We could use memcpy here, but doing so is kind of * ugly...and a smart compiler will do it for us. * * Note that we're snagging one extra value, regardless of * whether it'll actually be needed. This can cause segfaults * if the caller isn't careful. */ for (i = 0; i <= n_probs; i++) control->values[i] = values[i]; } else { /* * Generate values in the range [0,1). */ for (i = 0; i <= n_probs; i++) control->values[i] = (double)i / n_probs; } stack_high = (size_t*)malloc(n_probs * sizeof (size_t)); if (stack_high == NULL) { rd_empirical_free(control); return NULL; } stack_low = (size_t*)malloc(n_probs * sizeof (size_t)); if (stack_low == NULL) { free(stack_high); rd_empirical_free(control); return NULL; } n_high = n_low = 0; /* * We're done with memory allocation, and we've snagged the values * array. Now it's time to generate the probability cutoffs and * the remap array, which form the heart of the algorithm. First, * we initialize the cutoffs array to the difference between the * desired probability and a uniform distribution. Elements that * are less probable than uniform go on stack_low; the rest go on * stack_high. */ for (i = 0, prob_total = 0.0; i < n_probs; i++) prob_total += probs[i]; for (i = 0; i < n_probs; i++) { control->remap[i] = i; control->cutoff[i] = probs[i] / prob_total - 1.0 / n_probs; if (control->cutoff[i] >= 0.0) stack_high[n_high++] = i; else stack_low[n_low++] = i; } /* * Now we adjust the cutoffs. For each item on stack_low, * generate a probabilistic remapping from it to the top element * on stack_high. Then adjust the top element of stack_high to * reflect that fact, if necessary moving it to stack_low. */ while (n_low > 0) { i = stack_low[--n_low]; /* i is the guy we'll adjust */ j = stack_high[n_high - 1]; /* * The cutoff for i is negative, and represents the difference * between the uniform distribution and how often this element * should occur. For example, if n_probs is 4, a uniform * distribution would generate each value 1/4 of the time. * Suppose element i instead has a probability of 0.20. Then * cutoffs[i] is -0.05. If a random choice picked us, we must * remap to some higher-probability event 0.05/0.25 = 0.05 / * (1/4) = 0.05 * n_probs = 20% of the time. This is done by * setting the cutoff to 1.0 + (-0.05) * n_probs = 1.0 - 0.20 * = 0.8. * * We also use a trick due to Knuth, which involves adding an * extra integer "i" to the cutoff. This saves us one step in * the random-number generation because we won't have to * separate out the fractional part of the result of * rds_ldrand (see rds_int_empirical). * * Because we are "transferring" part of the probability of i * to the top of stack_high, we must also adjust its * probability cutoff to reflect that fact. In the example * above, we are transferring 0.05 of the probability of i * onto stack_high, so we must subtract that amount from * stack_high. Since the cutoff is negative, "subtract" means * "add" here. */ control->cutoff[j] += control->cutoff[i]; control->cutoff[i] = i + 1.0 + control->cutoff[i] * n_probs; control->remap[i] = j; /* * If the stack_high cutoff became negative, move it to stack_low. */ if (control->cutoff[j] < 0.0) { stack_low[n_low++] = j; --n_high; } } /* * We're done; the cutoffs are all prepared. Note that there may * still be elements on stack_high; that's not a problem because * they're all (effectively) zero. Go through them and set their * cutoffs such that they'll never be remapped. */ for (i = 0; i < n_high; i++) { j = stack_high[i]; control->cutoff[j] = j + 1.0; } free(stack_high); free(stack_low); return control; } /* * Free an empirical-distribution control structure. */ void rd_empirical_free( rd_empirical_control* control) /* Structure to free */ { if (control == NULL) return; if (control->cutoff != NULL) free(control->cutoff); if (control->remap != NULL) free(control->remap); if (control->values != NULL) free(control->values); free(control); } /* * Generate a discrete integer empirical distribution given a set of * probability cutoffs. See rd_empirical_setup for full information. */ size_t rd_int_empirical( rd_empirical_control* control) /* Control from rd_empirical_setup */ { return rds_int_empirical(&mt_default_state, control); } /* * Generate a discrete floating-point empirical distribution given a * set of probability cutoffs. See rds_double_empirical. */ double rd_double_empirical( rd_empirical_control* control) /* Control from rd_empirical_setup */ { return rds_double_empirical(&mt_default_state, control); } /* * Generate a continuous floating-point empirical distribution given a * set of probability cutoffs. See rds_continuous_empirical. */ double rd_continuous_empirical( rd_empirical_control* control) /* Control from rd_empirical_setup */ { return rds_continuous_empirical(&mt_default_state, control); }
36,867
33.327747
78
c
filebench
filebench-master/cvars/mtwist/randistrs.h
#ifndef RANDISTRS_H #define RANDISTRS_H /* * $Id: randistrs.h,v 1.8 2013-01-05 01:18:52-08 geoff Exp $ * * Header file for C/C++ use of a generalized package that generates * random numbers in various distributions, using the Mersenne-Twist * pseudo-RNG. See mtwist.h and mtwist.c for documentation on the PRNG. * * Author of this header file: Geoff Kuenning, April 7, 2001. * * All of the functions provided by this package have three variants. * The rd_xxx versions use the default state vector provided by the MT * package. The rds_xxx versions use a state vector provided by the * caller. In general, the rds_xxx versions are preferred for serious * applications, since they allow random numbers used for different * purposes to be drawn from independent, uncorrelated streams. * Finally, the C++ interface provides a class "mt_distribution", * derived from mt_prng, with no-prefix ("xxx") versions of each * function. * * The summary below will describe only the rds_xxx functions. The * rd_xxx functions have identical specifications, except that the * "state" argument is omitted. In all cases, the "state" argument * has type mt_state, and must have been initialized either by calling * one of the Mersenne Twist seeding functions, or by being set to all * zeros. * * The "l" version of each function calls the 64-bit version of the * PRNG instead of the 32-bit version. In general, you shouldn't use * those functions unless your application is *very* sensitive to tiny * variations in the probability distribution. This is especially * true of the uniform and empirical distributions. * * Random-distribution functions: * * rds_iuniform(mt_state* state, long lower, long upper) * (Integer) uniform on the half-open interval [lower, upper). * rds_liuniform(mt_state* state, long long lower, long long upper) * (Integer) uniform on the half-open interval [lower, upper). * Don't use unless you need numbers bigger than a long! * rds_uniform(mt_state* state, double lower, double upper) * (Floating) uniform on the half-open interval [lower, upper). * rds_luniform(mt_state* state, double lower, double upper) * (Floating) uniform on the half-open interval [lower, upper). * Higher precision but slower than rds_uniform. * rds_exponential(mt_state* state, double mean) * Exponential with the given mean. * rds_lexponential(mt_state* state, double mean) * Exponential with the given mean. * Higher precision but slower than rds_exponential. * rds_erlang(mt_state* state, int p, double mean) * p-Erlang with the given mean. * rds_lerlang(mt_state* state, int p, double mean) * p-Erlang with the given mean. * Higher precision but slower than rds_erlang. * rds_weibull(mt_state* state, double shape, double scale) * Weibull with the given shape and scale parameters. * rds_lweibull(mt_state* state, double shape, double scale) * Weibull with the given shape and scale parameters. * Higher precision but slower than rds_weibull. * rds_normal(mt_state* state, double mean, double sigma) * Normal with the given mean and standard deviation. * rds_lnormal(mt_state* state, double mean, double sigma) * Normal with the given mean and standard deviation. * Higher precision but slower than rds_normal. * rds_lognormal(mt_state* state, double shape, double scale) * Lognormal with the given shape and scale parameters. * rds_llognormal(mt_state* state, double shape, double scale) * Lognormal with the given shape and scale parameters. * Higher precision but slower than rds_lognormal. * rds_triangular(mt_state* state, double lower, double upper, double mode) * Triangular on the closed interval (lower, upper) with * the given mode. * rds_ltriangular(mt_state* state, double lower, double upper, double mode) * Triangular on the closed interval (lower, upper) with * the given mode. * Higher precision but slower than rds_triangular. * rds_int_empirical(mt_state* state, rd_empirical_control* control) * Unsigned integer (actually a size_t) in the range [0, n) * with empirically determined probabilities. The * "control" argument is the return value from a previous * call to rd_emprical_setup; see documentation on that * function below for more information. * rds_double_empirical(mt_state* state, rd_empirical_control* control) * Double empirically selected from a list of values * given to rd_empirical_setup (q.v.). * rds_continuous_empirical(mt_state* state, rd_empirical_control* control) * Continuous empirical distribution. See rd_empirical_setup. * rd_iuniform(long lower, long upper) * rd_liuniform(long long lower, long long upper) * As above, using the default MT-PRNG. * rd_uniform(double lower, double upper) * rd_luniform(double lower, double upper) * As above, using the default MT-PRNG. * rd_exponential(double mean) * rd_lexponential(double mean) * As above, using the default MT-PRNG. * rd_erlang(int p, double mean) * rd_lerlang(int p, double mean) * As above, using the default MT-PRNG. * rd_weibull(double shape, double scale) * rd_lweibull(double shape, double scale) * As above, using the default MT-PRNG. * rd_normal(double mean, double sigma) * rd_lnormal(double mean, double sigma) * As above, using the default MT-PRNG. * rd_lognormal(double shape, double scale) * rd_llognormal(double shape, double scale) * As above, using the default MT-PRNG. * rd_triangular(double lower, double upper, double mode) * rd_ltriangular(double lower, double upper, double mode) * As above, using the default MT-PRNG. * rd_empirical_setup(int n_probs, double* probs, double* values) * Set up the control table for an empirical * distribution. Once set up, the returned control table * can be used with multiple independent generators, and * can be used with any of the three empirical * distribution functions; usage can even be intermixed. * In all cases, n_probs is the size of the probs array, * which gives relative weights for different empirically * observed values. The weights do not need to sum to 1; * if they do not, they will be normalized. (In the * following descriptions, normalized weights are assumed * for simplicity.) * For calls to int_empirical, the values array is * ignored. In this case, the return value is in the * range [0, n), where 0 is returned with probability * probs[0], 1 with probability probs[1], etc. * For calls to double_empirical, the value * calculated by int_empirical is used as an index into * the values array, so that values[0] is returned with * probability probs[0], values[1] with probability * probs[1], etc. * For calls to continuous_empirical, the values * array must contain n_probs+1 entries. It is best for * the values array to be sorted into ascending order; * however, this condition is not enforced. The return * value is uniformly distributed between values[0] and * values[1] with probability probs[0], between values[1] * and values[2] with probability probs[1], etc. The * effect will be to generate a piecewise linear * approximation to the empirically observed CDF. * If "values" is NULL, the setup function will * automatically generate an array of uniformly spaced * values in the range [0.0,1.0]. However, if a values * array is provided, n_probs+1 entries must be supplied * EVEN IF only double_empirical will be called. This is * because the setup function will be copying n_probs+1 * values, and there is a (small) possibility of a * segfault if fewer are provided. * rd_empirical_free(rd_empirical_control* control) * Free a structure allocated by rd_empirical_setup. * rd_int_empirical(rd_empirical_control* control) * rd_double_empirical(rd_empirical_control* control) * rd_continuous_empirical(rd_empirical_control* control) * As above, using the default MT-PRNG. * * $Log: randistrs.h,v $ * Revision 1.8 2013-01-05 01:18:52-08 geoff * Fix a lot of compiler warnings. Allow rd_empirical_setup to take * const arguments. * * Revision 1.7 2010-12-10 03:28:19-08 geoff * Support the new empirical_distribution interface. * * Revision 1.6 2010-06-24 20:53:59+12 geoff * Switch to using types from stdint.h. * * Revision 1.5 2008-07-25 16:34:01-07 geoff * Fix notation for intervals in commentary. * * Revision 1.4 2001/06/20 09:07:58 geoff * Fix a place where long long wasn't conditionalized. * * Revision 1.3 2001/06/19 00:41:17 geoff * Add the "l" versions of all functions. * * Revision 1.2 2001/06/18 10:09:24 geoff * Add the iuniform functions. Improve the header comments. Add a C++ * interface. Clean up some stylistic inconsistencies. * * Revision 1.1 2001/04/09 08:39:54 geoff * Initial revision * */ #include "mtwist.h" #ifdef __cplusplus #include <stdexcept> #include <vector> #endif /* * Internal structure used to support O(1) generation of empirical * distributions. */ typedef struct { size_t n; /* Number of probabilities given */ double* cutoff; /* Table of probability cutoffs */ /* ..this is NOT probabilities; see */ /* ..comments in the code */ size_t* remap; /* Table of where to remap to */ double* values; /* Float values to return */ } rd_empirical_control; #ifdef __cplusplus extern "C" { #endif /* * Functions that use a provided state. */ extern int32_t rds_iuniform(mt_state* state, int32_t lower, int32_t upper); /* (Integer) uniform distribution */ #ifdef INT64_MAX extern int64_t rds_liuniform(mt_state* state, int64_t lower, int64_t upper); /* (Integer) uniform distribution */ #endif /* INT64_MAX */ extern double rds_uniform(mt_state* state, double lower, double upper); /* (Floating) uniform distribution */ extern double rds_luniform(mt_state* state, double lower, double upper); /* (Floating) uniform distribution */ extern double rds_exponential(mt_state* state, double mean); /* Exponential distribution */ extern double rds_lexponential(mt_state* state, double mean); /* Exponential distribution */ extern double rds_erlang(mt_state* state, int p, double mean); /* p-Erlang distribution */ extern double rds_lerlang(mt_state* state, int p, double mean); /* p-Erlang distribution */ extern double rds_weibull(mt_state* state, double shape, double scale); /* Weibull distribution */ extern double rds_lweibull(mt_state* state, double shape, double scale); /* Weibull distribution */ extern double rds_normal(mt_state* state, double mean, double sigma); /* Normal distribution */ extern double rds_lnormal(mt_state* state, double mean, double sigma); /* Normal distribution */ extern double rds_lognormal(mt_state* state, double shape, double scale); /* Lognormal distribution */ extern double rds_llognormal(mt_state* state, double shape, double scale); /* Lognormal distribution */ extern double rds_triangular(mt_state* state, double lower, double upper, double mode); /* Triangular distribution */ extern double rds_ltriangular(mt_state* state, double lower, double upper, double mode); /* Triangular distribution */ extern size_t rds_int_empirical(mt_state* state, rd_empirical_control* control); /* Discrete integer empirical distr. */ extern double rds_double_empirical(mt_state* state, rd_empirical_control* control); /* Discrete float empirical distr. */ extern double rds_continuous_empirical(mt_state* state, rd_empirical_control* control); /* Continuous empirical distribution */ /* * Functions that use the default state of the PRNG. */ extern int32_t rd_iuniform(int32_t lower, int32_t upper); /* (Integer) uniform distribution */ #ifdef INT64_MAX extern int64_t rd_liuniform(int64_t lower, int64_t upper); /* (Integer) uniform distribution */ #endif /* INT64_MAX */ extern double rd_uniform(double lower, double upper); /* (Floating) uniform distribution */ extern double rd_luniform(double lower, double upper); /* (Floating) uniform distribution */ extern double rd_exponential(double mean); /* Exponential distribution */ extern double rd_lexponential(double mean); /* Exponential distribution */ extern double rd_erlang(int p, double mean); /* p-Erlang distribution */ extern double rd_lerlang(int p, double mean); /* p-Erlang distribution */ extern double rd_weibull(double shape, double scale); /* Weibull distribution */ extern double rd_lweibull(double shape, double scale); /* Weibull distribution */ extern double rd_normal(double mean, double sigma); /* Normal distribution */ extern double rd_lnormal(double mean, double sigma); /* Normal distribution */ extern double rd_lognormal(double shape, double scale); /* Lognormal distribution */ extern double rd_llognormal(double shape, double scale); /* Lognormal distribution */ extern double rd_triangular(double lower, double upper, double mode); /* Triangular distribution */ extern double rd_ltriangular(double lower, double upper, double mode); /* Triangular distribution */ extern rd_empirical_control* rd_empirical_setup(size_t n_probs, const double* probs, const double* values); /* Set up empirical distribution */ extern void rd_empirical_free(rd_empirical_control* control); /* Free empirical control structure */ extern size_t rd_int_empirical(rd_empirical_control* control); /* Discrete integer empirical distr. */ extern double rd_double_empirical(rd_empirical_control* control); /* Discrete float empirical distr. */ extern double rd_continuous_empirical(rd_empirical_control* control); /* Continuous empirical distribution */ #ifdef __cplusplus } #endif #ifdef __cplusplus /* * C++ interface to the random-distribution generators. This class is * little more than a wrapper for the C functions, but it fits a bit * more nicely with the mt_prng class. */ class mt_distribution : public mt_prng { public: /* * Constructors and destructors. All constructors and * destructors are the same as for mt_prng. */ mt_distribution( // Default constructor bool pickSeed = false) // True to get seed from /dev/urandom // ..or time : mt_prng(pickSeed) { } mt_distribution(uint32_t newseed) // Construct with 32-bit seeding : mt_prng(newseed) { } mt_distribution(uint32_t seeds[MT_STATE_SIZE]) // Construct with full seeding : mt_prng(seeds) { } ~mt_distribution() { } /* * Functions for generating distributions. These simply * invoke the C functions above. */ int32_t iuniform(int32_t lower, int32_t upper) /* Uniform distribution */ { return rds_iuniform(&state, lower, upper); } #ifdef INT64_MAX int64_t liuniform(int64_t lower, int64_t upper) /* Uniform distribution */ { return rds_liuniform(&state, lower, upper); } #endif /* INT64_MAX */ double uniform(double lower, double upper) /* Uniform distribution */ { return rds_uniform(&state, lower, upper); } double luniform(double lower, double upper) /* Uniform distribution */ { return rds_luniform(&state, lower, upper); } double exponential(double mean) /* Exponential distribution */ { return rds_exponential(&state, mean); } double lexponential(double mean) /* Exponential distribution */ { return rds_lexponential(&state, mean); } double erlang(int p, double mean) /* p-Erlang distribution */ { return rds_erlang(&state, p, mean); } double lerlang(int p, double mean) /* p-Erlang distribution */ { return rds_lerlang(&state, p, mean); } double weibull(double shape, double scale) /* Weibull distribution */ { return rds_weibull(&state, shape, scale); } double lweibull(double shape, double scale) /* Weibull distribution */ { return rds_lweibull(&state, shape, scale); } double normal(double mean, double sigma) /* Normal distribution */ { return rds_normal(&state, mean, sigma); } double lnormal(double mean, double sigma) /* Normal distribution */ { return rds_lnormal(&state, mean, sigma); } double lognormal(double shape, double scale) /* Lognormal distribution */ { return rds_lognormal(&state, shape, scale); } double llognormal(double shape, double scale) /* Lognormal distribution */ { return rds_llognormal(&state, shape, scale); } double triangular(double lower, double upper, double mode) /* Triangular distribution */ { return rds_triangular(&state, lower, upper, mode); } double ltriangular(double lower, double upper, double mode) /* Triangular distribution */ { return rds_ltriangular(&state, lower, upper, mode); } }; /* * Class for handing empirical distributions. This is necessary * because of the need to allocate and initialize extra parameters. * * BUG/WARNING: this code will only work on compilers where C * malloc/free can be freely intermixed with C++ new/delete. */ class mt_empirical_distribution { public: mt_empirical_distribution(const std::vector<double>& probs, const std::vector<double>& values) : c(NULL) { if (values.size() != probs.size() + 1) throw std::invalid_argument( "values must be one longer than probs"); c = rd_empirical_setup(probs.size(), &probs.front(), &values.front()); } mt_empirical_distribution(const std::vector<double>& probs) : c(rd_empirical_setup(probs.size(), &probs.front(), NULL)) { } ~mt_empirical_distribution() { rd_empirical_free(c); } size_t int_empirical(mt_prng& rng) /* Discrete integer empirical distr. */ { return rds_int_empirical(&rng.state, c); } double double_empirical(mt_prng& rng) /* Discrete double empirical distr. */ { return rds_double_empirical(&rng.state, c); } double continuous_empirical(mt_prng& rng) /* Continuous empirical distribution */ { return rds_continuous_empirical(&rng.state, c); } private: /* * Copying and assignment are not supported. (Implementing * them would either require reconstructing the * original weights, which is ugly, or doing C-style * allocation, which is equally ugly.) */ mt_empirical_distribution( const mt_empirical_distribution& source); mt_empirical_distribution& operator=( const mt_empirical_distribution& rhs); /* * Private Data. */ rd_empirical_control* c; /* C-style control structure */ }; #endif /* __cplusplus */ #endif /* RANDISTRS_H */
19,046
35.984466
76
h
filebench
filebench-master/cvars/mtwist/rdcctest.cc
#ifndef lint #ifdef __GNUC__ #define ATTRIBUTE(attrs) __attribute__(attrs) #else #define ATTRIBUTE(attrs) #endif static char Rcs_Id[] ATTRIBUTE((used)) = "$Id: rdcctest.cc,v 1.7 2012-12-30 16:24:49-08 geoff Exp $"; #endif /* * Test the random-distribution library. Usage: * * rdcctest seed how_many distribution [params...] * * where: * * seed is the random seed. If seed is zero, the package's * automatic seed generator is used. * how_many * is how many random numbers to generate. * distribution * is the distribution to draw from (see below). * params are the parameters to the distribution (see below). * * Distributions supported: * * iuniform A uniform distribution of integers on the interval [p1, p2). * uniform A uniform distribution on the interval [p1, p2). * exponential Exponential with mean p1, default 1. * erlang p1-Erlang with mean p2. * weibull Weibull with shape parameter p1 and scale parameter p2. * normal Normal with mean p1 and standard deviation p2. * lognormal Lognormal with scale parameter p1 and shape parameter p2. * triangular Triangular on the interval (p1, p2) with mode at p3. * empirical p1 with probability p2, p3 with probability p4, ..., * p(2n+1) with probability p(2n). Actually, the * "probabilities" are * weights, and do not need to sum to 1. * continuous_empirical * p1 to p3 with probability p2, p3 to p5 with * probability p4, ..., p(2n+1) to p(2n+2) with * probability p(2n). Actually, the "probabilities" are * weights, and do not need to sum to 1. * * $Log: rdcctest.cc,v $ * Revision 1.7 2012-12-30 16:24:49-08 geoff * Use gcc attributes to suppress warnings on Rcs_Id. * * Revision 1.6 2010-12-10 03:28:19-08 geoff * Support the new empirical_distribution interface. * * Revision 1.5 2010-06-24 19:29:38+12 geoff * Include string.h to get rid of some warnings. * * Revision 1.4 2008-07-25 16:34:01-07 geoff * Fix notation for intervals in commentary. * * Revision 1.3 2004/03/30 07:29:43 geoff * Document the program better, and allow the random seed to be * controlled for verification testing. * * Revision 1.2 2003/09/11 05:50:53 geoff * Use the standard namespace. * * Revision 1.1 2001/06/18 10:09:35 geoff * Initial revision * */ #include "randistrs.h" #include <iostream> #include <stdlib.h> #include <string.h> #include <vector> using namespace std; int main(int argc, char* argv[]); static void usage(); #define SEED_PARAM 1 /* Offset of seed param in argv */ #define COUNT_PARAM 2 /* Offset of count param in argv */ #define DISTR_PARAM 3 /* Offset of distr param in argv */ #define PARAM_OFFSET 4 /* Offset of params in argv */ int main( int argc, /* Argument count */ char* argv[]) /* Argument vector */ { if (argc <= PARAM_OFFSET) usage(); int seed = atoi (argv[SEED_PARAM]); size_t how_many = atoi(argv[COUNT_PARAM]); size_t n_params = argc - PARAM_OFFSET; double* params = new double[n_params]; mt_empirical_distribution* empirical = NULL; size_t needed_params = 0; /* Number of params needed by distr */ size_t n_probs = 0; /* Number of empirical probabilites */ for (size_t i = 0; i < n_params; i++) params[i] = atof(argv[i + PARAM_OFFSET]); if (strcmp(argv[DISTR_PARAM], "iuniform") == 0) needed_params = 2; else if (strcmp(argv[DISTR_PARAM], "uniform") == 0) needed_params = 2; else if (strcmp(argv[DISTR_PARAM], "exponential") == 0) needed_params = 1; else if (strcmp(argv[DISTR_PARAM], "erlang") == 0) { if (n_params < 2 || params[0] < 1.0) usage(); needed_params = 2; } else if (strcmp(argv[DISTR_PARAM], "weibull") == 0) needed_params = 2; else if (strcmp(argv[DISTR_PARAM], "normal") == 0) needed_params = 2; else if (strcmp(argv[DISTR_PARAM], "lognormal") == 0) needed_params = 2; else if (strcmp(argv[DISTR_PARAM], "triangular") == 0) needed_params = 3; else if (strcmp(argv[DISTR_PARAM], "empirical") == 0) { if (n_params % 2 != 0 || n_params < 4) usage(); n_probs = n_params / 2; vector<double> probs; vector<double> values; for (size_t i = 0; i < n_probs; i++) { values.push_back(params[i * 2]); probs.push_back(params[i * 2 + 1]); if (probs[i] < 0) { (void)fprintf(stderr, "rdcctest: negative probability given\n"); exit(2); } } values.push_back(0.0); needed_params = n_params; empirical = new mt_empirical_distribution(probs, values); } else if (strcmp(argv[DISTR_PARAM], "continuous_empirical") == 0) { if (n_params % 2 == 0 || n_params < 5) usage(); n_probs = (n_params - 1) / 2; vector<double> probs; vector<double> values; for (size_t i = 0; i < n_probs; i++) { values.push_back(params[i * 2]); probs.push_back(params[i * 2 + 1]); if (probs[i] < 0) { (void)fprintf(stderr, "rdcctest: negative probability given\n"); exit(2); } } values.push_back(params[n_probs * 2]); needed_params = n_params; empirical = new mt_empirical_distribution(probs, values); } else usage(); if (n_params != needed_params) usage(); /* * Create a generator and seed it. */ mt_distribution distr(seed == 0); if (seed != 0) distr.seed32(seed); for (size_t i = 0; i < how_many; i++) { double ran_value = 0.0; if (strcmp(argv[DISTR_PARAM], "iuniform") == 0) ran_value = distr.iuniform((long)params[0], (long)params[1]); else if (strcmp(argv[DISTR_PARAM], "uniform") == 0) ran_value = distr.uniform(params[0], params[1]); else if (strcmp(argv[DISTR_PARAM], "exponential") == 0) ran_value = distr.exponential(params[0]); else if (strcmp(argv[DISTR_PARAM], "erlang") == 0) ran_value = distr.erlang((int) params[0], params[1]); else if (strcmp(argv[DISTR_PARAM], "weibull") == 0) ran_value = distr.weibull(params[0], params[1]); else if (strcmp(argv[DISTR_PARAM], "normal") == 0) ran_value = distr.normal(params[0], params[1]); else if (strcmp(argv[DISTR_PARAM], "lognormal") == 0) ran_value = distr.lognormal(params[0], params[1]); else if (strcmp(argv[DISTR_PARAM], "triangular") == 0) ran_value = distr.triangular(params[0], params[1], params[2]); else if (strcmp(argv[DISTR_PARAM], "empirical") == 0) ran_value = empirical->double_empirical(distr); else if (strcmp(argv[DISTR_PARAM], "continuous_empirical") == 0) ran_value = empirical->continuous_empirical(distr); cout << ran_value << '\n'; } return 0; } static void usage() { cerr << "Usage: rdcctest count distribution p0 ...\n"; cerr << "Distributions:\n"; cerr << "\tiuniform lower upper\n"; cerr << "\tuniform lower upper\n"; cerr << "\texponential mean\n"; cerr << "\terlang p mean\n"; cerr << "\tweibull shape scale\n"; cerr << "\tnormal mean sigma\n"; cerr << "\tlognormal shape scale\n"; cerr << "\ttriangular lower upper mode\n"; cerr << "\tempirical v0 p0 v1 p1 ... vn-1 pn-1\n"; cerr << "\tcontinuous_empirical v0 p0 v1 p1 ... vn-1 pn-1 vn\n"; exit(2); }
7,117
30.082969
74
cc
filebench
filebench-master/cvars/mtwist/rdtest.c
#ifndef lint #ifdef __GNUC__ #define ATTRIBUTE(attrs) __attribute__(attrs) #else #define ATTRIBUTE(attrs) #endif static char Rcs_Id[] ATTRIBUTE((used)) = "$Id: rdtest.c,v 1.11 2013-01-05 01:18:52-08 geoff Exp $"; #endif /* * Test the random-distribution library. Usage: * * rdtest seed how_many distribution [params...] * * where: * * seed is the random seed. If seed is zero, the package's * automatic seed generator is used. * how_many * is how many random numbers to generate. * distribution * is the distribution to draw from (see below). * params are the parameters to the distribution (see below). * * Distributions supported: * * iuniform A uniform distribution of integers on the interval [p1, p2). * uniform A uniform distribution on the interval [p1, p2). * exponential Exponential with mean p1, default 1. * erlang p1-Erlang with mean p2. * weibull Weibull with shape parameter p1 and scale parameter p2. * normal Normal with mean p1 and standard deviation p2. * lognormal Lognormal with scale parameter p1 and shape parameter p2. * triangular Triangular on the interval (p1, p2) with mode at p3. * empirical p1 with probability p2, p3 with probability p4, ..., * p(2n+1) with probability p(2n). Actually, the * "probabilities" are * weights, and do not need to sum to 1. * continuous_empirical * p1 to p3 with probability p2, p3 to p5 with * probability p4, ..., p(2n+1) to p(2n+2) with * probability p(2n). Actually, the "probabilities" are * weights, and do not need to sum to 1. * * $Log: rdtest.c,v $ * Revision 1.11 2013-01-05 01:18:52-08 geoff * Fix a lot of compiler warnings. * * Revision 1.10 2012-12-30 16:24:49-08 geoff * Use gcc attributes to suppress warnings on Rcs_Id. * * Revision 1.9 2010-12-10 03:28:19-08 geoff * Support the new empirical_distribution interface. * * Revision 1.8 2008-07-26 11:34:01+12 geoff * Fix notation for intervals in commentary. * * Revision 1.7 2007/10/26 07:21:06 geoff * Fix the usage message to be correct. * * Revision 1.6 2004/03/30 07:29:43 geoff * Document the program better, and allow the random seed to be * controlled for verification testing. * * Revision 1.5 2003/09/11 05:50:53 geoff * Include string.h to get the declaration of strcmp. * * Revision 1.4 2001/06/18 10:09:24 geoff * Get rid of some warning messages. * * Revision 1.3 2001/04/10 09:11:38 geoff * Add a tiny bit of explanatory commentary. When testing the empirical * distribution, expect the parameters to give individual probabilities, * not running sums. In other words, calculate the running sums for the * user before generating the distribution. * * Revision 1.2 2001/04/09 08:47:19 geoff * Add RCS ID keywords. Give a name to a magic number I missed. * */ #include "randistrs.h" #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char * argv[]); static void usage(void); #define SEED_PARAM 1 /* Offset of seed param in argv */ #define COUNT_PARAM 2 /* Offset of count param in argv */ #define DISTR_PARAM 3 /* Offset of distr param in argv */ #define PARAM_OFFSET 4 /* Offset of params in argv */ int main( int argc, /* Argument count */ char * argv[]) /* Argument vector */ { rd_empirical_control* control = NULL; /* Control if empirical distr. */ size_t how_many; /* How many numbers to generate */ size_t i; /* Loop index */ size_t needed_params = 0; /* Number of params needed by distr */ size_t n_params; /* Number of parameters */ size_t n_probs = 0; /* Number of empirical probabilites */ double * params; /* Parameters of distribution */ double * probs = NULL; /* Probabilities for empirical */ double ran_value = 0.0; /* Value generated by PRNG */ uint32_t seed; /* Seed for PRNG */ double * values = NULL; /* Values for empirical */ if (argc <= PARAM_OFFSET) usage(); seed = atoi (argv[SEED_PARAM]); how_many = atoi (argv[COUNT_PARAM]); n_params = argc - PARAM_OFFSET; params = (double *) malloc (sizeof (double) * n_params); if (params == NULL) { (void) fprintf (stderr, "rdtest: can't malloc params\n"); return 1; } for (i = 0; i < n_params; i++) params[i] = atof (argv[i + PARAM_OFFSET]); if (strcmp (argv[DISTR_PARAM], "iuniform") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "uniform") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "exponential") == 0) needed_params = 1; else if (strcmp (argv[DISTR_PARAM], "erlang") == 0) { if (n_params < 2 || params[0] < 1.0) usage(); needed_params = 2; } else if (strcmp (argv[DISTR_PARAM], "weibull") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "normal") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "lognormal") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "triangular") == 0) needed_params = 3; else if (strcmp (argv[DISTR_PARAM], "empirical") == 0) { if (n_params % 2 != 0 || n_params < 4) usage(); n_probs = n_params / 2; probs = (double *) malloc (sizeof (double) * n_probs); values = (double *) malloc (sizeof (double) * (n_probs + 1)); if (probs == NULL || values == NULL) { (void) fprintf (stderr, "rdtest: can't malloc probs/values\n"); return 1; } for (i = 0; i < n_probs; i++) { values[i] = params[i * 2]; probs[i] = params[i * 2 + 1]; if (probs[i] < 0) { (void)fprintf(stderr, "rdtest: negative probability given\n"); exit(2); } } values[n_probs] = 0.0; /* Just for cleanliness */ needed_params = n_params; control = rd_empirical_setup(n_probs, probs, values); } else if (strcmp(argv[DISTR_PARAM], "continuous_empirical") == 0) { if (n_params % 2 == 0 || n_params < 5) usage(); n_probs = (n_params - 1) / 2; probs = (double *) malloc (sizeof (double) * n_probs); values = (double *) malloc (sizeof (double) * (n_probs + 1)); if (probs == NULL || values == NULL) { (void) fprintf (stderr, "rdtest: can't malloc probs/values\n"); return 1; } for (i = 0; i < n_probs; i++) { values[i] = params[i * 2]; probs[i] = params[i * 2 + 1]; if (probs[i] < 0) { (void)fprintf(stderr, "rdtest: negative probability given\n"); exit(2); } } values[n_probs] = params[n_probs * 2]; needed_params = n_params; control = rd_empirical_setup(n_probs, probs, values); } else usage(); if (n_params != needed_params) usage(); /* * Pick a seed */ if (seed == 0) mt_goodseed(); else mt_seed32(seed); for (i = 0; i < how_many; i++) { if (strcmp (argv[DISTR_PARAM], "iuniform") == 0) ran_value = rd_iuniform ((int32_t)params[0], (int32_t)params[1]); else if (strcmp (argv[DISTR_PARAM], "uniform") == 0) ran_value = rd_uniform (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "exponential") == 0) ran_value = rd_exponential (params[0]); else if (strcmp (argv[DISTR_PARAM], "erlang") == 0) ran_value = rd_erlang ((int) params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "weibull") == 0) ran_value = rd_weibull (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "normal") == 0) ran_value = rd_normal (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "lognormal") == 0) ran_value = rd_lognormal (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "triangular") == 0) ran_value = rd_triangular (params[0], params[1], params[2]); else if (strcmp (argv[DISTR_PARAM], "empirical") == 0) ran_value = rd_double_empirical (control); else if (strcmp (argv[DISTR_PARAM], "continuous_empirical") == 0) ran_value = rd_continuous_empirical (control); (void) printf ("%f\n", ran_value); } return 0; } static void usage(void) { (void) fprintf (stderr, "Usage: rdtest seed count distribution p0 ...\n"); (void) fprintf (stderr, "Distributions:\n"); (void) fprintf (stderr, "\tiuniform lower upper\n"); (void) fprintf (stderr, "\tuniform lower upper\n"); (void) fprintf (stderr, "\texponential mean\n"); (void) fprintf (stderr, "\terlang p mean\n"); (void) fprintf (stderr, "\tweibull shape scale\n"); (void) fprintf (stderr, "\tnormal mean sigma\n"); (void) fprintf (stderr, "\tlognormal shape scale\n"); (void) fprintf (stderr, "\ttriangular lower upper mode\n"); (void) fprintf (stderr, "\tempirical v0 p0 v1 p1 ... vn-1 pn-1\n"); (void) fprintf (stderr, "\tcontinuous_empirical v0 p0 v1 p1 ... vn-1 pn-1 vn\n"); exit(2); }
8,709
32.371648
78
c
filebench
filebench-master/cvars/test/sanity.c
/* * sanity.c * * Sanity checker for custom libraries. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #include <stdint.h> #include <fb_cvar.h> char *pgmname; void print_usage() { printf("Usage: %s <library name> <parameter string> " "<count>\n", pgmname); printf("Example: %s librand-triangular.so.1 " "'lower:1024;upper:4096;mode:4096'" " 10\n", pgmname); return; } int main(int argc, char *argv[]) { void *cvar_lib; void *cvar_handle; char *libname; char *parameters; int count; int ret; cvar_operations_t cvar_op; double d; /* Set the global program name. */ pgmname = argv[0]; if (argc < 4) { printf("Insufficient parameters.\n"); print_usage(); ret = -1; goto exit; } /* Load the library. */ libname = argv[1]; cvar_lib = dlopen(libname, RTLD_NOW | RTLD_GLOBAL); if (!cvar_lib) { printf("Unable to load library: %s.\n", dlerror()); ret = -2; goto exit; } /* Initialize the function pointers. */ cvar_op.cvar_module_init = dlsym(cvar_lib, FB_CVAR_MODULE_INIT); cvar_op.cvar_alloc_handle = dlsym(cvar_lib, FB_CVAR_ALLOC_HANDLE); if (!cvar_op.cvar_alloc_handle) { printf("Unable to find " FB_CVAR_ALLOC_HANDLE ": %s.\n", dlerror()); ret = -3; goto dlclose; } cvar_op.cvar_revalidate_handle = dlsym(cvar_lib, FB_CVAR_REVALIDATE_HANDLE); if (!cvar_op.cvar_revalidate_handle) { printf("Unable to find " FB_CVAR_ALLOC_HANDLE ": %s.\n", dlerror()); ret = -4; goto dlclose; } cvar_op.cvar_next_value = dlsym(cvar_lib, FB_CVAR_NEXT_VALUE); if (!cvar_op.cvar_next_value) { printf("Unable to find " FB_CVAR_NEXT_VALUE ": %s.\n", dlerror()); ret = -5; goto dlclose; } cvar_op.cvar_free_handle = dlsym(cvar_lib, FB_CVAR_FREE_HANDLE); if (!cvar_op.cvar_free_handle) { printf("Unable to find " FB_CVAR_FREE_HANDLE ": %s.\n", dlerror()); ret = -6; goto dlclose; } cvar_op.cvar_module_exit = dlsym(cvar_lib, FB_CVAR_MODULE_EXIT); cvar_op.cvar_usage = dlsym(cvar_lib, FB_CVAR_USAGE); cvar_op.cvar_version = dlsym(cvar_lib, FB_CVAR_VERSION); if (cvar_op.cvar_module_init) { ret = cvar_op.cvar_module_init(); if (ret) { printf("Custom variable module initialization failed.\n"); goto dlclose; } } if (cvar_op.cvar_version) printf("Variable: %s (%s)\n", libname, cvar_op.cvar_version()); else printf("Variable: %s\n", libname); if (cvar_op.cvar_usage) printf("%s\n", cvar_op.cvar_usage()); /* Allocate a new custom variable handle */ parameters = argv[2]; cvar_handle = cvar_op.cvar_alloc_handle(parameters, malloc, free); if (!cvar_handle) { printf("Custom variable handle allocation failed.\n"); ret = -7; goto cvar_free; } /* Try revalidating the handle. */ ret = cvar_op.cvar_revalidate_handle(cvar_handle); if (ret) { printf("Custom variable handle revalidation failed.\n"); ret = -10; goto cvar_free; } count = atoi(argv[3]); if (count > 0) { while (count > 1) { ret = cvar_op.cvar_next_value(cvar_handle, &d); if (ret) { printf("Unable to get the next value. Error %d.\n" ,ret); ret = -11; goto cvar_free; } printf("%lf,", d); count--; } ret = cvar_op.cvar_next_value(cvar_handle, &d); if (ret) { printf("Unable to get the next value. Error %d.\n" ,ret); ret = -11; goto cvar_free; } printf("%lf.\n", d); } ret = 0; printf("\nAll done.\n"); cvar_free: cvar_op.cvar_free_handle(cvar_handle, free); if (cvar_op.cvar_module_exit) cvar_op.cvar_module_exit(); dlclose: dlclose(cvar_lib); exit: return ret; }
3,594
21.055215
77
c
filebench
filebench-master/workloads/compflow_demo.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. set $dir=/tmp set $nfiles=700 set $meandirwidth=20 set $filesize=128k set $nthreads=10 set $meaniosize=16k define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=80, paralloc define fileset name=u2fileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=80, paralloc define fileset name=u3fileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=80, paralloc define flowop name=readwrite, $fileset { flowop openfile name=openfile4,filesetname=$fileset,fd=1 flowop openfile name=openfile5,filesetname=$fileset,fd=2 flowop readwholefile name=readfile1,fd=1 flowop writewholefile name=writefile1,fd=2,srcfd=1 flowop closefile name=closefile4,fd=1 flowop closefile name=closefile5,fd=2 } define flowop name=dowork, $filesetnm, $rwiters { flowop createfile name=createfile1,filesetname=$filesetnm,fd=1 flowop appendfilerand name=appendfilerand1,iosize=$meaniosize,fd=1 flowop closefile name=closefile1,fd=1 flowop readwrite name=rw1, iters=$rwiters, $fileset=$filesetnm flowop deletefile name=deletefile1,filesetname=$filesetnm flowop statfile name=statfile1,filesetname=$filesetnm } define process name=filereader1,instances=1 { thread name=user1,memsize=10m,instances=$nthreads { flowop dowork name=dowork1, iters=1, $rwiters=5, $filesetnm=bigfileset } thread name=user2,memsize=10m,instances=$nthreads { flowop dowork name=dowork2, iters=1, $rwiters=4, $filesetnm=u2fileset } thread name=user3,memsize=10m,instances=$nthreads { flowop dowork name=dowork3, iters=1, $rwiters=3, $filesetnm=u3fileset } } echo "CompFlow_Demo Version 1.1 personality successfully loaded"
2,625
33.103896
116
f
filebench
filebench-master/workloads/copyfiles.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $nfiles=1000 set $meandirwidth=20 set $meanfilesize=16k set $iosize=1m set $nthreads=1 set mode quit firstdone define fileset name=bigfileset,path=$dir,size=$meanfilesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=100,paralloc define fileset name=destfiles,path=$dir,size=$meanfilesize,entries=$nfiles,dirwidth=$meandirwidth define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop openfile name=openfile1,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile1,fd=1,iosize=$iosize flowop createfile name=createfile2,filesetname=destfiles,fd=2 flowop writewholefile name=writefile2,fd=2,srcfd=1,iosize=$iosize flowop closefile name=closefile1,fd=1 flowop closefile name=closefile2,fd=2 } } echo "Copyfiles Version 3.0 personality successfully loaded"
1,776
33.173077
120
f
filebench
filebench-master/workloads/createdelete-swing.f
# # GPL HEADER START # # This file is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # <http://www.gnu.org/licenses/>. # # GPL HEADER END # # Copyright 2012 Vasily Tarasov <tarasov@vasily.name> # # # Create-Delete Swing personality creates $nfiles, then # deletes them, then creates again, and so on until the # time is up or a user interrupts the run. # set $path=/tmp set $nfiles=1000 set $filesize=500k # We want a flat directory (i.e., no subdirectories), so we set the # mean directory equal to the number of files. In addition, we set # gamma parameter for the directory width distribution to 0 to avoid # deviation from the mean. set $meandirwidth=1000 set $dirgamma=0 # the rate should be set to an approriate value of required # creates/sec. 0 means not limit on the create rate. eventgen rate=0 # set the runtime set $runtime=60 define fileset name=manyfiles, path=$path, entries=$nfiles, size=$filesize, dirwidth=$meandirwidth, dirgamma=$dirgamma # a composite flowop that creates a file, then writes # to it, and closes a corresponding file descriptor. # The rate of this flowop is also throttled # by the eventgen rate (if set). define flowop name=createandclose { flowop createfile name=createfile, filesetname=manyfiles, fd=1 flowop writewholefile name=whritewholefile, filesetname=manyfiles, fd=1 flowop closefile name=closefile, fd=1 flowop eventlimit name=crlimit } # the process that creates $nfiles files, # wakes up a deletion process, and then blocks. define process name=crproc { thread name=crthread { flowop createandclose name=createandclose, iters=$nfiles flowop wakeup name=wakeupdelproc, target=delprocblock flowop block name=crprocblock } } # the process that deletes $nfiles files, # wakes up a creation process, and then blocks. define process name=delproc { thread name=delthread { flowop block name=delprocblock flowop deletefile name=dodelete, filesetname=manyfiles, iters=$nfiles flowop wakeup name=crprocwake, target=crprocblock } } echo "Create-Delete Swing personality Ver. 1.0 successfully loaded" run $runtime
2,736
24.820755
68
f
filebench
filebench-master/workloads/createfiles.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $nfiles=50000 set $meandirwidth=100 set $meanfilesize=16k set $iosize=1m set $nthreads=16 set mode quit firstdone define fileset name=bigfileset,path=$dir,size=$meanfilesize,entries=$nfiles,dirwidth=$meandirwidth define process name=filecreate,instances=1 { thread name=filecreatethread,memsize=10m,instances=$nthreads { flowop createfile name=createfile1,filesetname=bigfileset,fd=1 flowop writewholefile name=writefile1,fd=1,iosize=$iosize flowop closefile name=closefile1,fd=1 } } echo "Createfiles Version 3.0 personality successfully loaded"
1,489
30.041667
98
f
filebench
filebench-master/workloads/cvar_example.f
set $dir=/tmp set $filesize=100m set $iosize=cvar(type=cvar-uniform,parameters=lower:4096;upper:8192) define file name=singlefile,path=$dir,size=$filesize,prealloc define process name=filereader,instances=1 { thread name=filereader,memsize=1m,instances=1 { flowop openfile name=open1,filesetname=singlefile,fd=1 flowop read name=read1,fd=1,iosize=$iosize flowop closefile name=close1,fd=1 } } run 60
421
22.444444
68
f
filebench
filebench-master/workloads/filemicro_create.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Simple way to create a file. Start off with a zero length file, and issue # 1024 ($count) 1MB appends. set $dir=/tmp set $count=1024 set $iosize=1m set $nthreads=1 set $sync=false define file name=largefile,path=$dir,size=0,prealloc define process name=filecreater,instances=1 { thread name=filecreaterthread,memsize=10m,instances=$nthreads { flowop appendfile name=append-file,filename=largefile,dsync=$sync,iosize=$iosize flowop finishoncount name=finish,value=$count } } echo "FileMicro-Create Version 2.1 personality successfully loaded"
1,494
30.145833
84
f
filebench
filebench-master/workloads/filemicro_createfiles.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Creates a fileset with 20,000 entries ($nfiles), but only preallocates # 50% of the files. Each file's size is set via a gamma distribution with # a median size of 1KB ($filesize). # # The single thread then creates a new file and writes the whole file with # 1MB I/Os. The thread stops after 5000 files ($count/num of flowops) have # been created and written to. set $dir=/tmp set $count=15000 set $filesize=1k set $iosize=1m set $meandirwidth=100000 set $nfiles=20000 set $nthreads=1 define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=50 define process name=filecreate,instances=1 { thread name=filecreatethread,memsize=10m,instances=$nthreads { flowop createfile name=createfile1,filesetname=bigfileset,fd=1 flowop writewholefile name=writefile1,filesetname=bigfileset,fd=1,iosize=$iosize flowop closefile name=closefile1,fd=1 flowop finishoncount name=finish,value=$count } } echo "FileMicro-Createfiles Version 2.2 personality successfully loaded"
1,967
33.526316
106
f
filebench
filebench-master/workloads/filemicro_createrand.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single threaded asynchronous ($sync) random appends (random I/Os # in the range of [1B - 1MB]) to a 1GB file. # Does a fsync after 10 ($iters) appends. # Stops after 1GB ($bytes) has been appended/written. set $dir=/tmp set $bytes=1g set $iosize=1m set $iters=10 set $nthreads=1 set $sync=false define file name=largefile,path=$dir,size=0,prealloc define process name=filecreater,instances=1 { thread name=filecreaterthread,memsize=10m,instances=$nthreads { flowop appendfilerand name=append-file,filename=largefile,dsync=$sync,iosize=$iosize,iters=$iters flowop fsync name=sync flowop finishonbytes name=finish,value=$bytes } } echo "FileMicro-CreateRand Version 2.1 personality successfully loaded"
1,656
30.865385
101
f
filebench
filebench-master/workloads/filemicro_delete.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Create a fileset of 50,000 entries ($nfiles), where each file's size is set # via a gamma distribution with the median size of 16KB ($filesize). # Fire off 16 threads ($nthreads), where each thread stops after # deleting 1000 ($count) files. set $dir=/tmp set $count=1000 set $filesize=16k set $nfiles=5000 set $meandirwidth=100 set $nthreads=16 set mode quit firstdone define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=100,paralloc define process name=filedelete,instances=1 { thread name=filedeletethread,memsize=10m,instances=$nthreads { flowop deletefile name=deletefile1,filesetname=bigfileset flowop opslimit name=limit flowop finishoncount name=finish,value=$count } } echo "FileMicro-Delete Version 2.4 personality successfully loaded"
1,754
31.5
116
f
filebench
filebench-master/workloads/filemicro_rread.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single threaded random reads (2KB I/Os) on a 1GB file. # Stops after 128MB ($bytes) has been read. set $dir=/tmp set $bytes=128m set $cached=false set $filesize=1g set $iosize=2k set $iters=1 set $nthreads=1 define file name=bigfile1,path=$dir,size=$filesize,prealloc,reuse,cached=$cached define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop read name=write-file,filesetname=bigfile1,random,iosize=$iosize,iters=$iters flowop finishonbytes name=finish,value=$bytes } } echo "FileMicro-ReadRand Version 2.2 personality successfully loaded"
1,552
30.06
87
f
filebench
filebench-master/workloads/filemicro_rwrite.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single threaded asynchronous ($sync) random writes (2KB I/Os) on a 1GB file. # Stops when 128MB ($bytes) has been written. set $dir=/tmp set $bytes=128m set $cached=false set $filesize=1g set $iosize=2k set $iters=1 set $nthreads=1 set $sync=false define file name=bigfile1,path=$dir,size=$filesize,prealloc,reuse,cached=$cached define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=$nthreads { flowop write name=write-file,filename=bigfile1,random,dsync=$sync,iosize=$iosize,iters=$iters flowop finishonbytes name=finish,value=$bytes } } echo "FileMicro-WriteRand Version 2.1 personality successfully loaded"
1,603
30.45098
97
f
filebench
filebench-master/workloads/filemicro_rwritedsync.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single threaded synchronous (O_DSYNC) random writes (2KB I/Os) on a 1GB file. # Stops when 64K ($count) writes have been done. set $dir=/tmp set $count=65536 set $filesize=1g set $iosize=2k set $iters=1 set $nthreads=1 define file name=bigfile,path=$dir,size=$filesize,prealloc,reuse define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=$nthreads { flowop write name=write-file,filename=bigfile,random,dsync,iosize=$iosize,iters=$iters flowop finishoncount name=finish,value=$count } } echo "FileMicro-WriteRandDsync Version 2.1 personality successfully loaded"
1,556
30.77551
90
f
filebench
filebench-master/workloads/filemicro_rwritefsync.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single threaded asynchronous random writes (8KB I/Os) on a 1GB file. # A fsync is issued after 16K ($iters) worth of writes. # Stops after one ($count) fsync. set $dir=/tmp set $cached=false set $count=1 set $filesize=1g set $iosize=8k set $iters=16384 set $nthreads=1 define file name=bigfile,path=$dir,size=$filesize,prealloc,cached=$cached define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=$nthreads { flowop write name=write-file,filename=bigfile,random,iosize=$iosize,iters=$iters flowop fsync name=sync-file flowop finishoncount name=finish,value=$count } } echo "FileMicro-WriteRandFsync Version 2.1 personality successfully loaded"
1,641
30.576923
84
f
filebench
filebench-master/workloads/filemicro_seqread.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single threaded sequential reads (1MB I/Os) on a 1G file. set $dir=/tmp set $cached=false set $filesize=1g set $iosize=1m set $nthreads=1 define file name=largefile,path=$dir,size=$filesize,prealloc,reuse,cached=$cached define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop read name=seqread-file,filename=largefile,iosize=$iosize } } echo "FileMicro-SeqRead Version 2.1 personality successfully loaded"
1,412
29.717391
81
f
filebench
filebench-master/workloads/filemicro_seqwrite.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single threaded asynchronous ($sync) sequential writes (1MB I/Os) to # a 1GB file. # Stops after 1 series of 1024 ($count) writes has been done. set $dir=/tmp set $cached=false set $count=1024 set $iosize=1m set $nthreads=1 set $sync=false define file name=bigfile,path=$dir,size=0,prealloc,cached=$cached define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=$nthreads { flowop appendfile name=write-file,dsync=$sync,filename=bigfile,iosize=$iosize,iters=$count flowop finishoncount name=finish,value=1 } } echo "FileMicro-SeqWrite Version 2.2 personality successfully loaded"
1,571
30.44
94
f
filebench
filebench-master/workloads/filemicro_seqwriterand.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # Single threaded appends/writes (I/Os of random size in the range # of [1B - 8KB]) to a 1GB file. # Stops after 128K ($count) writes have been done. set $dir=/tmp set $cached=false set $count=128k set $iosize=8k set $nthreads=1 set $sync=false define file name=bigfile,path=$dir,size=0,prealloc,cached=$cached define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=$nthreads { flowop openfile name=open-file,filename=bigfile,fd=1 flowop appendfilerand name=appendrand-file,dsync=$sync,iosize=$iosize,fd=1,iters=$count flowop closefile name=close,fd=1 flowop finishoncount name=finish,value=1 } } echo "FileMicro-SeqWriteRand Version 2.2 personality successfully loaded"
1,638
31.78
91
f
filebench
filebench-master/workloads/filemicro_seqwriterandvargam.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # Sequential write() of a 1G file, size picked from a gamma distribution # min of 1k and a mean of 5.5K, followed by close(), cached. set $dir=/tmp set $nthreads=1 set $cached=false set $sync=false set $count=128k define randvar name=$iosize, type=gamma, min=1k, mean=5632, gamma=1500 define fileset name=bigfileset,path=$dir,size=0,entries=$nthreads,dirwidth=1024,prealloc=100,cached=$cached define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=$nthreads { flowop openfile name=open-file,filesetname=bigfileset,fd=1 flowop appendfile name=write-file,dsync=$sync,iosize=$iosize,fd=1,iters=$count flowop closefile name=close,fd=1 flowop finishoncount name=finish,value=1 } } echo "FileMicro-SeqWriteRandVarGam Version 1.1 personality successfully loaded"
1,726
32.211538
107
f
filebench
filebench-master/workloads/filemicro_seqwriterandvartab.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # Sequential write() of a 1G file, size picked from a table in # the [1K,64K] range with a mean of 5.5K, followed by close(), cached. set $dir=/tmp set $nthreads=1 set $cached=false set $sync=false set $count=128k define randvar name=$iosize, type=tabular, min=1k, randtable = {{ 80, 1k, 4k}, { 15, 4k, 16k}, { 05, 16k, 64k}} define fileset name=bigfileset,path=$dir,size=0,entries=$nthreads,dirwidth=1024,prealloc=100,cached=$cached define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=$nthreads { flowop openfile name=open-file,filesetname=bigfileset,fd=1 flowop appendfile name=write-file,dsync=$sync,iosize=$iosize,fd=1,iters=$count flowop closefile name=close,fd=1 flowop finishoncount name=finish,value=1 } } echo "FileMicro-SeqWriteRandVarTab Version 1.1 personality successfully loaded"
1,769
31.181818
107
f
filebench
filebench-master/workloads/filemicro_statfile.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # # Creates a fileset of $nfiles number of files, then loops through them # using $nthreads number of threads, doing "stat" calls on each file. # set $dir=/tmp set $nfiles=10000 set $meandirwidth=20 set $filesize=128k set $nthreads=20 define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=100 define process name=examinefiles,instances=1 { thread name=examinefilethread, memsize=10m,instances=$nthreads { flowop statfile name=statfile1,filesetname=bigfileset } } echo "Stat File Version 1.0 personality successfully loaded"
1,490
30.0625
107
f
filebench
filebench-master/workloads/filemicro_writefsync.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # Single-threaded writes to initially empty file. # I/O size is set to 8KB. After every 1024 writes # (i.e., 8MB written) fsync is called. # The run finishes after 1GB is fully written. set $dir=/tmp set $iosize=8k set $writeiters=1024 set $fsynccount=128 set mode quit firstdone define file name=bigfile,path=$dir,size=0,prealloc define process name=filewriter,instances=1 { thread name=filewriterthread,memsize=10m,instances=1 { flowop appendfile name=append-file,filename=bigfile,iosize=$iosize,iters=$writeiters flowop fsync name=sync-file flowop finishoncount name=finish,value=128,target=sync-file } } echo "FileMicro-WriteFsync Version 2.1 personality successfully loaded" run
1,640
29.388889
88
f
filebench
filebench-master/workloads/fileserver.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $nfiles=10000 set $meandirwidth=20 set $filesize=cvar(type=cvar-gamma,parameters=mean:131072;gamma:1.5) set $nthreads=50 set $iosize=1m set $meanappendsize=16k set $runtime=60 define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=80 define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop createfile name=createfile1,filesetname=bigfileset,fd=1 flowop writewholefile name=wrtfile1,srcfd=1,fd=1,iosize=$iosize flowop closefile name=closefile1,fd=1 flowop openfile name=openfile1,filesetname=bigfileset,fd=1 flowop appendfilerand name=appendfilerand1,iosize=$meanappendsize,fd=1 flowop closefile name=closefile2,fd=1 flowop openfile name=openfile2,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile1,fd=1,iosize=$iosize flowop closefile name=closefile3,fd=1 flowop deletefile name=deletefile1,filesetname=bigfileset flowop statfile name=statfile1,filesetname=bigfileset } } echo "File-server Version 3.0 personality successfully loaded" run $runtime
2,043
34.241379
106
f
filebench
filebench-master/workloads/fivestreamread.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=1g set $nthreads=1 set $iosize=1m define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse define file name=largefile2,path=$dir,size=$filesize,prealloc,reuse define file name=largefile3,path=$dir,size=$filesize,prealloc,reuse define file name=largefile4,path=$dir,size=$filesize,prealloc,reuse define file name=largefile5,path=$dir,size=$filesize,prealloc,reuse define process name=seqread,instances=1 { thread name=seqread1,memsize=10m,instances=$nthreads { flowop read name=seqread1,filename=largefile1,iosize=$iosize } thread name=seqread2,memsize=10m,instances=$nthreads { flowop read name=seqread2,filename=largefile2,iosize=$iosize } thread name=seqread3,memsize=10m,instances=$nthreads { flowop read name=seqread3,filename=largefile3,iosize=$iosize } thread name=seqread4,memsize=10m,instances=$nthreads { flowop read name=seqread4,filename=largefile4,iosize=$iosize } thread name=seqread5,memsize=10m,instances=$nthreads { flowop read name=seqread5,filename=largefile5,iosize=$iosize } } echo "Five Stream Read Version 3.0 personality successfully loaded"
2,059
32.225806
69
f
filebench
filebench-master/workloads/fivestreamreaddirect.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $nthreads=1 set $filesize=1g set $iosize=1m define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse define file name=largefile2,path=$dir,size=$filesize,prealloc,reuse define file name=largefile3,path=$dir,size=$filesize,prealloc,reuse define file name=largefile4,path=$dir,size=$filesize,prealloc,reuse define file name=largefile5,path=$dir,size=$filesize,prealloc,reuse define process name=seqread,instances=1 { thread name=seqread1,memsize=10m,instances=$nthreads { flowop read name=seqread1,filename=largefile1,iosize=$iosize,directio } thread name=seqread2,memsize=10m,instances=$nthreads { flowop read name=seqread2,filename=largefile2,iosize=$iosize,directio } thread name=seqread3,memsize=10m,instances=$nthreads { flowop read name=seqread3,filename=largefile3,iosize=$iosize,directio } thread name=seqread4,memsize=10m,instances=$nthreads { flowop read name=seqread4,filename=largefile4,iosize=$iosize,directio } thread name=seqread5,memsize=10m,instances=$nthreads { flowop read name=seqread5,filename=largefile5,iosize=$iosize,directio } } echo "Five Stream Direct Read Version 3.0 personality successfully loaded"
2,111
33.064516
75
f
filebench
filebench-master/workloads/fivestreamwrite.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=1g set $nthreads=1 set $iosize=1m define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse define file name=largefile2,path=$dir,size=$filesize,prealloc,reuse define file name=largefile3,path=$dir,size=$filesize,prealloc,reuse define file name=largefile4,path=$dir,size=$filesize,prealloc,reuse define file name=largefile5,path=$dir,size=$filesize,prealloc,reuse define process name=seqwrite,instances=1 { thread name=seqwrite1,memsize=10m,instances=$nthreads { flowop write name=seqwrite1,filename=largefile1,iosize=$iosize } thread name=seqwrite2,memsize=10m,instances=$nthreads { flowop write name=seqwrite2,filename=largefile2,iosize=$iosize } thread name=seqwrite3,memsize=10m,instances=$nthreads { flowop write name=seqwrite3,filename=largefile3,iosize=$iosize } thread name=seqwrite4,memsize=10m,instances=$nthreads { flowop write name=seqwrite4,filename=largefile4,iosize=$iosize } thread name=seqwrite5,memsize=10m,instances=$nthreads { flowop write name=seqwrite5,filename=largefile5,iosize=$iosize } } echo "Five Stream Write Version 3.0 personality successfully loaded"
2,076
32.5
69
f
filebench
filebench-master/workloads/fivestreamwritedirect.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=1g set $nthreads=1 set $iosize=1m define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse define file name=largefile2,path=$dir,size=$filesize,prealloc,reuse define file name=largefile3,path=$dir,size=$filesize,prealloc,reuse define file name=largefile4,path=$dir,size=$filesize,prealloc,reuse define file name=largefile5,path=$dir,size=$filesize,prealloc,reuse define process name=seqwrite,instances=1 { thread name=seqwrite1,memsize=10m,instances=$nthreads { flowop write name=seqwrite1,filename=largefile1,iosize=$iosize,directio } thread name=seqwrite2,memsize=10m,instances=$nthreads { flowop write name=seqwrite2,filename=largefile2,iosize=$iosize,directio } thread name=seqwrite3,memsize=10m,instances=$nthreads { flowop write name=seqwrite3,filename=largefile3,iosize=$iosize,directio } thread name=seqwrite4,memsize=10m,instances=$nthreads { flowop write name=seqwrite4,filename=largefile4,iosize=$iosize,directio } thread name=seqwrite5,memsize=10m,instances=$nthreads { flowop write name=seqwrite5,filename=largefile5,iosize=$iosize,directio } } echo "Five Stream Direct Write Version 3.0 personality successfully loaded"
2,128
33.33871
76
f
filebench
filebench-master/workloads/listdirs.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Creates a fileset with a fairly deep directory tree, then does readdir # operations on them for a specified amount of time # set $dir=/tmp set $nfiles=50000 set $meandirwidth=5 set $nthreads=16 define fileset name=bigfileset,path=$dir,size=0,entries=$nfiles,dirwidth=$meandirwidth,prealloc define process name=lsdir,instances=1 { thread name=dirlister,memsize=1m,instances=$nthreads { flowop listdir name=open1,filesetname=bigfileset } } echo "ListDirs Version 1.0 personality successfully loaded"
1,414
31.159091
95
f
filebench
filebench-master/workloads/makedirs.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Creates a directory with $ndirs potential leaf directories, than mkdir's them # set $dir=/tmp set $ndirs=10000 set $meandirwidth=100 set $nthreads=16 set mode quit firstdone define fileset name=bigfileset,path=$dir,size=0,leafdirs=$ndirs,dirwidth=$meandirwidth define process name=dirmake,instances=1 { thread name=dirmaker,memsize=1m,instances=$nthreads { flowop makedir name=mkdir1,filesetname=bigfileset } } echo "MakeDirs Version 1.0 personality successfully loaded"
1,388
29.866667
86
f
filebench
filebench-master/workloads/mongo.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" set $dir=/tmp set $nfiles=1000 set $dirwidth=20 set $filesize=16k set $nthreads=1 set $meaniosize=16k set $readiosize=1m set mode quit firstdone define fileset name=postset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$dirwidth,prealloc,paralloc define fileset name=postsetdel,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$dirwidth,prealloc,paralloc define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop openfile name=openfile1,filesetname=postset,fd=1 flowop appendfilerand name=appendfilerand1,iosize=$meaniosize,fd=1 flowop closefile name=closefile1,fd=1 flowop openfile name=openfile2,filesetname=postset,fd=1 flowop readwholefile name=readfile1,fd=1,iosize=$readiosize flowop closefile name=closefile2,fd=1 flowop deletefile name=deletefile1,filesetname=postsetdel } } echo "Mongo-like Version 2.3 personality successfully loaded"
1,876
33.127273
108
f
filebench
filebench-master/workloads/netsfs.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # $dir - directory for datafiles # $eventrate - event generator rate (0 == free run) # $nfiles - number of data files # $nthreads - number of worker threads set $dir=/tmp set $eventrate=10 set $meandirwidth=20 set $nthreads=1 set $nfiles=100000 set $sync=false eventgen rate=$eventrate set $wrtiosize = randvar(type=tabular, min=1k, round=1k, randtable = {{ 0, 1k, 7k}, {50, 9k, 15k}, {14, 17k, 23k}, {14, 33k, 39k}, {12, 65k, 71k}, {10, 129k, 135k} }) set $rdiosize = randvar(type=tabular, min=8k, round=1k, randtable = {{85, 8k, 8k}, { 8, 17k, 23k}, { 4, 33k, 39k}, { 2, 65k, 71k}, { 1, 129k, 135k} }) set $filesize = randvar(type=tabular, min=1k, round=1k, randtable = {{33, 1k, 1k}, {21, 1k, 3k}, {13, 3k, 5k}, {10, 5k, 11k}, {08, 11k, 21k}, {05, 21k, 43k}, {04, 43k, 85k}, {03, 85k, 171k}, {02, 171k, 341k}, {01, 341k, 1707k} }) set $fileidx = randvar(type=gamma, min=0, gamma=100) define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=60 define flowop name=rmw { flowop openfile name=openfile1,filesetname=bigfileset,indexed=$fileidx,fd=1 flowop readwholefile name=readfile1,iosize=$rdiosize,fd=1 flowop createfile name=newfile2,filesetname=bigfileset,indexed=$fileidx,fd=2 flowop writewholefile name=writefile2,fd=2,iosize=$wrtiosize,srcfd=1 flowop closefile name=closefile1,fd=1 flowop closefile name=closefile2,fd=2 flowop deletefile name=deletefile1,fd=1 } define flowop name=launch { flowop openfile name=openfile3,filesetname=bigfileset,indexed=$fileidx,fd=3 flowop readwholefile name=readfile3,iosize=$rdiosize,fd=3 flowop openfile name=openfile4,filesetname=bigfileset,indexed=$fileidx,fd=4 flowop readwholefile name=readfile4,iosize=$rdiosize,fd=4 flowop closefile name=closefile3,fd=3 flowop openfile name=openfile5,filesetname=bigfileset,indexed=$fileidx,fd=5 flowop readwholefile name=readfile5,iosize=$rdiosize,fd=5 flowop closefile name=closefile4,fd=4 flowop closefile name=closefile5,fd=5 } define flowop name=appnd { flowop openfile name=openfile6,filesetname=bigfileset,indexed=$fileidx,fd=6 flowop appendfilerand name=appendfilerand6,iosize=$wrtiosize,fd=6 flowop closefile name=closefile6,fd=6 } define process name=netclient,instances=1 { thread name=fileuser,memsize=10m,instances=$nthreads { flowop launch name=launch1, iters=1 flowop rmw name=rmw1, iters=6 flowop appnd name=appnd1, iters=3 flowop statfile name=statfile1,filesetname=bigfileset,indexed=$fileidx flowop eventlimit name=ratecontrol } } echo "NetworkFileServer Version 1.0 personality successfully loaded" run 60
3,611
29.610169
106
f
filebench
filebench-master/workloads/networkfs.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # $dir - directory for datafiles # $eventrate - event generator rate (0 == free run) # $nfiles - number of data files # $nthreads - number of worker threads set $dir=/tmp set $cached=false set $eventrate=10 set $meandirwidth=20 set $nthreads=1 set $nfiles=10000 set $sync=false set $totalfiles=$nfiles * $eventrate eventgen rate=$eventrate define randvar name=$wrtiosize, type=tabular, min=1k, round=1k, randtable = {{ 0, 1k, 7k}, {50, 9k, 15k}, {14, 17k, 23k}, {14, 33k, 39k}, {12, 65k, 71k}, {10, 129k, 135k} } define randvar name=$rdiosize, type=tabular, min=8k, round=1k, randtable = {{85, 8k, 8k}, { 8, 17k, 23k}, { 4, 33k, 39k}, { 2, 65k, 71k}, { 1, 129k, 135k} } define randvar name=$filesize, type=tabular, min=1k, round=1k, randtable = {{33, 1k, 1k}, {21, 1k, 3k}, {13, 3k, 5k}, {10, 5k, 11k}, {08, 11k, 21k}, {05, 21k, 43k}, {04, 43k, 85k}, {03, 85k, 171k}, {02, 171k, 341k}, {01, 341k, 1707k} } define randvar name=$fileidx, type=gamma, min=0, gamma=100 define fileset name=bigfileset,path=$dir,size=$filesize,entries=$totalfiles,dirwidth=$meandirwidth,prealloc=60,cached=$cached define flowop name=rmw, $filesetrmw { flowop openfile name=openfile1,filesetname=$filesetrmw,indexed=$fileidx,fd=1 flowop readwholefile name=readfile1,iosize=$rdiosize,fd=1 flowop createfile name=newfile2,filesetname=$filesetrmw,indexed=$fileidx,fd=2 flowop writewholefile name=writefile2,fd=2,iosize=$wrtiosize,srcfd=1 flowop closefile name=closefile1,fd=1 flowop closefile name=closefile2,fd=2 flowop deletefile name=deletefile1,fd=1 } define flowop name=launch, $filesetlch { flowop openfile name=openfile3,filesetname=$filesetlch,indexed=$fileidx,fd=3 flowop readwholefile name=readfile3,iosize=$rdiosize,fd=3 flowop openfile name=openfile4,filesetname=$filesetlch,indexed=$fileidx,fd=4 flowop readwholefile name=readfile4,iosize=$rdiosize,fd=4 flowop closefile name=closefile3,fd=3 flowop openfile name=openfile5,filesetname=$filesetlch,indexed=$fileidx,fd=5 flowop readwholefile name=readfile5,iosize=$rdiosize,fd=5 flowop closefile name=closefile4,fd=4 flowop closefile name=closefile5,fd=5 } define flowop name=appnd, $filesetapd { flowop openfile name=openfile6,filesetname=$filesetapd,indexed=$fileidx,fd=6 flowop appendfilerand name=appendfilerand6,iosize=$wrtiosize,fd=6 flowop closefile name=closefile6,fd=6 } define process name=netclient,instances=1 { thread name=fileuser,memsize=10m,instances=$nthreads { flowop launch name=launch1, iters=1, $filesetlch=bigfileset flowop rmw name=rmw1, iters=6, $filesetrmw=bigfileset flowop appnd name=appnd1, iters=3, $filesetapd=bigfileset flowop statfile name=statfile1,filesetname=bigfileset,indexed=$fileidx flowop eventlimit name=ratecontrol } } echo "NetworkFileServer Version 1.0 personality successfully loaded"
3,817
31.355932
125
f
filebench
filebench-master/workloads/oltp.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $eventrate=0 set $runtime=30 set $iosize=2k set $nshadows=200 set $ndbwriters=10 set $usermode=200000 set $filesize=10m set $memperthread=1m set $workingset=0 set $logfilesize=10m set $nfiles=10 set $nlogfiles=1 set $directio=0 eventgen rate = $eventrate # Define a datafile and logfile define fileset name=datafiles,path=$dir,size=$filesize,entries=$nfiles,dirwidth=1024,prealloc=100,reuse define fileset name=logfile,path=$dir,size=$logfilesize,entries=$nlogfiles,dirwidth=1024,prealloc=100,reuse define process name=lgwr,instances=1 { thread name=lgwr,memsize=$memperthread,useism { flowop aiowrite name=lg-write,filesetname=logfile, iosize=256k,random,directio=$directio,dsync flowop aiowait name=lg-aiowait flowop semblock name=lg-block,value=3200,highwater=1000 } } # Define database writer processes define process name=dbwr,instances=$ndbwriters { thread name=dbwr,memsize=$memperthread,useism { flowop aiowrite name=dbwrite-a,filesetname=datafiles, iosize=$iosize,workingset=$workingset,random,iters=100,opennext,directio=$directio,dsync flowop hog name=dbwr-hog,value=10000 flowop semblock name=dbwr-block,value=1000,highwater=2000 flowop aiowait name=dbwr-aiowait } } define process name=shadow,instances=$nshadows { thread name=shadow,memsize=$memperthread,useism { flowop read name=shadowread,filesetname=datafiles, iosize=$iosize,workingset=$workingset,random,opennext,directio=$directio flowop hog name=shadowhog,value=$usermode flowop sempost name=shadow-post-lg,value=1,target=lg-block,blocking flowop sempost name=shadow-post-dbwr,value=1,target=dbwr-block,blocking flowop eventlimit name=random-rate } } echo "OLTP Version 3.0 personality successfully loaded" run 60
2,701
30.057471
107
f
filebench
filebench-master/workloads/openfiles.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Creates a fileset with $nfiles empty files, then proceeds to open each one # and then close it. # set $dir=/tmp set $nfiles=50000 set $meandirwidth=100 set $nthreads=16 define fileset name=bigfileset,path=$dir,size=0,entries=$nfiles,dirwidth=$meandirwidth,prealloc define process name=fileopen,instances=1 { thread name=fileopener,memsize=1m,instances=$nthreads { flowop openfile name=open1,filesetname=bigfileset,fd=1 flowop closefile name=close1,fd=1 } } echo "Openfiles Version 1.0 personality successfully loaded"
1,438
30.977778
95
f
filebench
filebench-master/workloads/randomfileaccess.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Exercises the indexed attribute of the fileset_pick() function. # set $dir=/tmp set $cached=false set $meandirwidth=20 set $nthreads=5 set $nfiles=10000 set $sync=false define randvar name=$wrtiosize, min=512, round=512, type=gamma, mean=16k define randvar name=$rdiosize, type=tabular, min=8k, round=1k, randtable = {{85, 8k, 8k}, {15, 8k, 64k} } define randvar name=$filesize, type=tabular, min=1k, randtable = {{33, 1k, 1k}, {21, 1k, 3k}, {13, 3k, 5k}, {10, 5k, 11k}, {08, 11k, 21k}, {05, 21k, 43k}, {04, 43k, 85k}, {03, 85k, 171k}, {02, 171k, 341k}, {01, 341k, 1707k} } define randvar name=$fileidx, type=gamma, min=0, gamma=100 define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=100,cached=$cached define process name=netclient,instances=1 { thread name=fileuser,memsize=10m,instances=$nthreads { flowop openfile name=openfile1,filesetname=bigfileset,indexed=$fileidx,fd=1 flowop openfile name=openfile2,filesetname=bigfileset,indexed=$fileidx,fd=2 flowop openfile name=openfile3,filesetname=bigfileset,indexed=$fileidx,fd=3 flowop appendfilerand name=appendfilerand1,iosize=$wrtiosize,fd=1 flowop closefile name=closefile1,fd=1 flowop readwholefile name=readfile1,iosize=$rdiosize,fd=2 flowop readwholefile name=readfile2,iosize=$rdiosize,fd=3 flowop closefile name=closefile2,fd=2 flowop closefile name=closefile3,fd=3 } } echo "NetworkServer Version 1.1 personality successfully loaded"
2,447
31.64
122
f
filebench
filebench-master/workloads/randomread.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=5g set $iosize=8k set $nthreads=1 set $workingset=0 set $directio=0 define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse,paralloc define process name=rand-read,instances=1 { thread name=rand-thread,memsize=5m,instances=$nthreads { flowop read name=rand-read1,filename=largefile1,iosize=$iosize,random,workingset=$workingset,directio=$directio } } echo "Random Read Version 3.0 personality successfully loaded"
1,367
30.090909
115
f
filebench
filebench-master/workloads/randomrw.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=5g set $iosize=8k set $nthreads=1 set $workingset=0 set $directio=0 define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse,paralloc define process name=rand-rw,instances=1 { thread name=rand-r-thread,memsize=5m,instances=$nthreads { flowop read name=rand-read1,filename=largefile1,iosize=$iosize,random,workingset=$workingset,directio=$directio } thread name=rand-w-thread,memsize=5m,instances=$nthreads { flowop write name=rand-write1,filename=largefile1,iosize=$iosize,random,workingset=$workingset,directio=$directio } } echo "Random RW Version 3.0 personality successfully loaded"
1,550
31.3125
117
f
filebench
filebench-master/workloads/randomwrite.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=5g set $iosize=8k set $nthreads=1 set $workingset=0 set $directio=0 define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse,paralloc define process name=rand-write,instances=1 { thread name=rand-thread,memsize=5m,instances=$nthreads { flowop write name=rand-write1,filename=largefile1,iosize=$iosize,random,workingset=$workingset,directio=$directio } } echo "Random Write Version 3.0 personality successfully loaded"
1,371
30.181818
117
f
filebench
filebench-master/workloads/ratelimcopyfiles.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # RateLimCopyFiles.f uses the iopslimit flowop with the target attribute # set to the writewholefile flowop to limit the rate to one writewholefile # operation per event. Without the target attribute set, the limit will # be one writewholefile OR readwholefile operation per event, so in effect # it will run at half the rate. Without the target attribute, this workload # is identical to copyfiles.f. Set the event generator rate by setting # the $eventrate variable, for instance by typing: # set $eventrate=20 # at the filebench prompt to get twenty events per second. # # $dir - directory for datafiles # $eventrate - event generator rate (0 == free run) # $filesize - size of data file # $iosize - size of each I/O request # $nfiles - number of files in the fileset # $nthreads - number of worker threads set $dir=/tmp set $eventrate=10 set $dirwidth=20 set $filesize=16k set $iosize=1m set $nfiles=1000 set $nthreads=1 eventgen rate=$eventrate set mode quit firstdone define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$dirwidth,prealloc=100 define fileset name=destfiles,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$dirwidth define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop openfile name=openfile1,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile1,fd=1,iosize=$iosize flowop createfile name=createfile2,filesetname=destfiles,fd=2 flowop writewholefile name=writefile2,filesetname=destfiles,fd=2,srcfd=1,iosize=$iosize flowop closefile name=closefile1,fd=1 flowop closefile name=closefile2,fd=2 flowop iopslimit name=iopslim1, target=writefile2 } } echo "RateLimCopyFiles Version 1.1 personality successfully loaded"
2,685
35.794521
103
f
filebench
filebench-master/workloads/removedirs.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Creates a fileset with $ndirs empty leaf directories then rmdir's all of them # set $dir=/tmp set $ndirs=10000 set $meandirwidth=100 set $nthreads=16 set mode quit firstdone define fileset name=bigfileset,path=$dir,size=0,leafdirs=$ndirs,dirwidth=$meandirwidth,prealloc define process name=remdir,instances=1 { thread name=removedirectory,memsize=1m,instances=$nthreads { flowop removedir name=dirremover,filesetname=bigfileset } } echo "RemoveDir Version 1.0 personality successfully loaded"
1,410
30.355556
95
f
filebench
filebench-master/workloads/singlestreamread.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=5g set $nthreads=1 set $iosize=1m define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse define process name=seqread,instances=1 { thread name=seqread,memsize=10m,instances=$nthreads { flowop read name=seqread,filename=largefile1,iosize=$iosize } } echo "Single Stream Read Version 3.0 personality successfully loaded"
1,275
29.380952
70
f
filebench
filebench-master/workloads/singlestreamreaddirect.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $filesize=5g set $nthreads=1 set $iosize=1m define file name=largefile1,path=$dir,size=$filesize,prealloc,reuse define process name=seqread,instances=1 { thread name=seqread,memsize=10m,instances=$nthreads { flowop read name=seqread,filename=largefile1,iosize=$iosize,directio } } echo "Single Stream Direct Read Version 3.0 personality successfully loaded"
1,291
29.761905
77
f
filebench
filebench-master/workloads/singlestreamwrite.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $iosize=1m set $nthreads=1 define file name=largefile1,path=$dir,prealloc define process name=seqwrite,instances=1 { thread name=seqwrite,memsize=10m,instances=$nthreads { flowop write name=seqwrite,filename=largefile1,iosize=$iosize } } echo "Single Stream Write Version 3.0 personality successfully loaded"
1,242
29.317073
71
f
filebench
filebench-master/workloads/singlestreamwritedirect.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $iosize=1m set $nthreads=1 define file name=largefile1,path=$dir,prealloc define process name=seqwrite,instances=1 { thread name=seqwrite,memsize=10m,instances=$nthreads { flowop write name=seqwrite,filename=largefile1,iosize=$iosize,directio } } echo "Single Stream Direct Write Version 3.0 personality successfully loaded"
1,258
29.707317
78
f
filebench
filebench-master/workloads/tpcso.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # $dir - directory for datafiles # $eventrate - event generator rate (0 == free run) # $iosize - iosize for database block access # $nshadows - number of shadow processes # $ndbwriters - number of database writers set $dir=/tmp set $eventrate=0 set $iosize=2k set $nshadows=200 set $ndbwriters=10 set $runtime=30 set $usermode=20000 set $memperthread=1m debug 1 eventgen rate=$eventrate # Define a datafile and logfile define file name=aux.df,path=$dir,size=251m,reuse,prealloc,paralloc define file name=control_001,path=$dir,size=2m,reuse,prealloc,paralloc define file name=cust_0_0,path=$dir,size=6704m,reuse,prealloc,paralloc define file name=cust_0_1,path=$dir,size=6704m,reuse,prealloc,paralloc define file name=cust_0_2,path=$dir,size=6704m,reuse,prealloc,paralloc define file name=cust_0_3,path=$dir,size=6704m,reuse,prealloc,paralloc define file name=dist_0_0,path=$dir,size=31m,reuse,prealloc,paralloc define file name=hist_0_0,path=$dir,size=3002m,reuse,prealloc,paralloc define file name=icust1_0_0,path=$dir,size=4943m,reuse,prealloc,paralloc define file name=icust2_0_0,path=$dir,size=4943m,reuse,prealloc,paralloc define file name=idist_0_0,path=$dir,size=11m,reuse,prealloc,paralloc define file name=iitem_0_0,path=$dir,size=11m,reuse,prealloc,paralloc define file name=iordr2_0_0,path=$dir,size=1651m,reuse,prealloc,paralloc define file name=istok_0_0,path=$dir,size=2262m,reuse,prealloc,paralloc define file name=item_0_0,path=$dir,size=21m,reuse,prealloc,paralloc define file name=iware_0_0,path=$dir,size=11m,reuse,prealloc,paralloc define file name=nord_0_0,path=$dir,size=561m,reuse,prealloc,paralloc define file name=ordr_0_0,path=$dir,size=44301m,reuse,prealloc,paralloc define file name=roll1,path=$dir,size=2001m,reuse,prealloc,paralloc define file name=sp_0,path=$dir,size=1001m,reuse,prealloc,paralloc define file name=stok_0_0,path=$dir,size=8052m,reuse,prealloc,paralloc define file name=stok_0_1,path=$dir,size=8052m,reuse,prealloc,paralloc define file name=stok_0_2,path=$dir,size=8052m,reuse,prealloc,paralloc define file name=stok_0_3,path=$dir,size=8052m,reuse,prealloc,paralloc define file name=stok_0_4,path=$dir,size=8052m,reuse,prealloc,paralloc define file name=system_1,path=$dir,size=401m,reuse,prealloc,paralloc define file name=temp_0_0,path=$dir,size=4943m,reuse,prealloc,paralloc define file name=temp_0_1,path=$dir,size=4943m,reuse,prealloc,paralloc define file name=ware_0_0,path=$dir,size=11m,reuse,prealloc,paralloc define file name=log_1_1,path=$dir,size=1021m,reuse,prealloc,paralloc # Define database writer processes define process name=dbwr,instances=$ndbwriters { thread name=dbwr,memsize=$memperthread,useism { flowop aiowrite name=dbaiowrite-aux.df,filename=aux.df, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-control_001,filename=control_001, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-cust_0_0,filename=cust_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-cust_0_1,filename=cust_0_1, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-cust_0_2,filename=cust_0_2, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-cust_0_3,filename=cust_0_3, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-dist_0_0,filename=dist_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-hist_0_0,filename=hist_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-icust1_0_0,filename=icust1_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-icust2_0_0,filename=icust2_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-idist_0_0,filename=idist_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-iitem_0_0,filename=iitem_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-iordr2_0_0,filename=iordr2_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-istok_0_0,filename=istok_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-item_0_0,filename=item_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-iware_0_0,filename=iware_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-nord_0_0,filename=nord_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-ordr_0_0,filename=ordr_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-roll1,filename=roll1, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-sp_0,filename=sp_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-stok_0_0,filename=stok_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-stok_0_1,filename=stok_0_1, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-stok_0_2,filename=stok_0_2, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-stok_0_3,filename=stok_0_3, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-stok_0_4,filename=stok_0_4, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-system_1,filename=system_1, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-temp_0_0,filename=temp_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-temp_0_1,filename=temp_0_1, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop aiowrite name=dbaiowrite-ware_0_0,filename=ware_0_0, iosize=$iosize,workingset=10g,random,dsync,directio,iters=10 flowop hog name=dbwr-hog,value=10000 flowop semblock name=dbwr-block,value=100,highwater=10000 flowop aiowait name=dbwr-aiowait } } define process name=lgwr,instances=1 { thread name=lgwr,memsize=$memperthread,useism { flowop write name=lg-write,filename=log_1_1, iosize=256k,workingset=1g,random,dsync,directio # flowop delay name=lg-delay,value=1 flowop semblock name=lg-block,value=320,highwater=1000 } } define process name=shadow,instances=$nshadows { thread name=shadow,memsize=$memperthread,useism { flowop read name=shadowread-aux.df,filename=aux.df, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-control_001,filename=control_001, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-cust_0_0,filename=cust_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-cust_0_1,filename=cust_0_1, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-cust_0_2,filename=cust_0_2, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-cust_0_3,filename=cust_0_3, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-dist_0_0,filename=dist_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-hist_0_0,filename=hist_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-icust1_0_0,filename=icust1_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-icust2_0_0,filename=icust2_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-idist_0_0,filename=idist_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-iitem_0_0,filename=iitem_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-iordr2_0_0,filename=iordr2_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-istok_0_0,filename=istok_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-item_0_0,filename=item_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-iware_0_0,filename=iware_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-nord_0_0,filename=nord_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-ordr_0_0,filename=ordr_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-roll1,filename=roll1, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-sp_0,filename=sp_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-stok_0_0,filename=stok_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-stok_0_1,filename=stok_0_1, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-stok_0_2,filename=stok_0_2, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-stok_0_3,filename=stok_0_3, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-stok_0_4,filename=stok_0_4, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-system_1,filename=system_1, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-temp_0_0,filename=temp_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-temp_0_1,filename=temp_0_1, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-ware_0_0,filename=ware_0_0, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop read name=shadowread-log_1_1,filename=log_1_1, iosize=$iosize,workingset=10g,random,dsync,directio flowop hog name=shadowhog,value=$usermode flowop sempost name=shadow-post-lg,value=1,target=lg-block,blocking flowop sempost name=shadow-post-dbwr,value=1,target=dbwr-block,blocking flowop eventlimit name=random-rate } } echo "Tpcso Version 2.1 personality successfully loaded"
14,032
53.603113
76
f
filebench
filebench-master/workloads/varmail.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $nfiles=1000 set $meandirwidth=1000000 set $filesize=cvar(type=cvar-gamma,parameters=mean:16384;gamma:1.5) set $nthreads=16 set $iosize=1m set $meanappendsize=16k define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=80 define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop deletefile name=deletefile1,filesetname=bigfileset flowop createfile name=createfile2,filesetname=bigfileset,fd=1 flowop appendfilerand name=appendfilerand2,iosize=$meanappendsize,fd=1 flowop fsync name=fsyncfile2,fd=1 flowop closefile name=closefile2,fd=1 flowop openfile name=openfile3,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile3,fd=1,iosize=$iosize flowop appendfilerand name=appendfilerand3,iosize=$meanappendsize,fd=1 flowop fsync name=fsyncfile3,fd=1 flowop closefile name=closefile3,fd=1 flowop openfile name=openfile4,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile4,fd=1,iosize=$iosize flowop closefile name=closefile4,fd=1 } } echo "Varmail Version 3.0 personality successfully loaded" run 60
2,105
34.694915
106
f
filebench
filebench-master/workloads/videoserver.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # This workloads emulates a video server. It has two filesets, one of videos # being actively served, and one of videos availabe but currently inactive # (passive). However, one thread, vidwriter, is writing new videos to replace # no longer viewed videos in the passive set. Meanwhile $nthreads threads are # serving up videos from the activevids fileset. If the desired rate is R mb/s, # and $nthreads is set to T, then set the $srvbwrate to R * T to get the # desired rate per video stream. The video replacement rate of one video # file per replacement interval, is set by $repintval which defaults to # 10 seconds. Thus the write bandwidth will be set as $filesize/$repintval. # set $dir=/tmp set $eventrate=96 set $filesize=10g set $nthreads=48 set $numactivevids=32 set $numpassivevids=194 set $reuseit=false set $readiosize=256k set $writeiosize=1m set $passvidsname=passivevids set $actvidsname=activevids set $repintval=10 eventgen rate=$eventrate define fileset name=$actvidsname,path=$dir,size=$filesize,entries=$numactivevids,dirwidth=4,prealloc,paralloc,reuse=$reuseit define fileset name=$passvidsname,path=$dir,size=$filesize,entries=$numpassivevids,dirwidth=20,prealloc=50,paralloc,reuse=$reuseit define process name=vidwriter,instances=1 { thread name=vidwriter,memsize=10m,instances=1 { flowop deletefile name=vidremover,filesetname=$passvidsname flowop createfile name=wrtopen,filesetname=$passvidsname,fd=1 flowop writewholefile name=newvid,iosize=$writeiosize,fd=1,srcfd=1 flowop closefile name=wrtclose, fd=1 flowop delay name=replaceinterval, value=$repintval } } define process name=vidreaders,instances=1 { thread name=vidreaders,memsize=10m,instances=$nthreads { flowop read name=vidreader,filesetname=$actvidsname,iosize=$readiosize flowop bwlimit name=serverlimit, target=vidreader } } echo "Video Server Version 3.0 personality successfully loaded"
2,828
35.269231
130
f
filebench
filebench-master/workloads/webproxy.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $nfiles=10000 set $meandirwidth=1000000 set $meanfilesize=16k set $nthreads=100 set $meaniosize=16k set $iosize=1m define fileset name=bigfileset,path=$dir,size=$meanfilesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=80 define process name=proxycache,instances=1 { thread name=proxycache,memsize=10m,instances=$nthreads { flowop deletefile name=deletefile1,filesetname=bigfileset flowop createfile name=createfile1,filesetname=bigfileset,fd=1 flowop appendfilerand name=appendfilerand1,iosize=$meaniosize,fd=1 flowop closefile name=closefile1,fd=1 flowop openfile name=openfile2,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile2,fd=1,iosize=$iosize flowop closefile name=closefile2,fd=1 flowop openfile name=openfile3,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile3,fd=1,iosize=$iosize flowop closefile name=closefile3,fd=1 flowop openfile name=openfile4,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile4,fd=1,iosize=$iosize flowop closefile name=closefile4,fd=1 flowop openfile name=openfile5,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile5,fd=1,iosize=$iosize flowop closefile name=closefile5,fd=1 flowop openfile name=openfile6,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile6,fd=1,iosize=$iosize flowop closefile name=closefile6,fd=1 flowop opslimit name=limit } } echo "Web proxy-server Version 3.0 personality successfully loaded"
2,427
36.9375
110
f
filebench
filebench-master/workloads/webserver.f
# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # set $dir=/tmp set $nfiles=1000 set $meandirwidth=20 set $filesize=cvar(type=cvar-gamma,parameters=mean:16384;gamma:1.5) set $nthreads=100 set $iosize=1m set $meanappendsize=16k define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=100,readonly define fileset name=logfiles,path=$dir,size=$filesize,entries=1,dirwidth=$meandirwidth,prealloc define process name=filereader,instances=1 { thread name=filereaderthread,memsize=10m,instances=$nthreads { flowop openfile name=openfile1,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile1,fd=1,iosize=$iosize flowop closefile name=closefile1,fd=1 flowop openfile name=openfile2,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile2,fd=1,iosize=$iosize flowop closefile name=closefile2,fd=1 flowop openfile name=openfile3,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile3,fd=1,iosize=$iosize flowop closefile name=closefile3,fd=1 flowop openfile name=openfile4,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile4,fd=1,iosize=$iosize flowop closefile name=closefile4,fd=1 flowop openfile name=openfile5,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile5,fd=1,iosize=$iosize flowop closefile name=closefile5,fd=1 flowop openfile name=openfile6,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile6,fd=1,iosize=$iosize flowop closefile name=closefile6,fd=1 flowop openfile name=openfile7,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile7,fd=1,iosize=$iosize flowop closefile name=closefile7,fd=1 flowop openfile name=openfile8,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile8,fd=1,iosize=$iosize flowop closefile name=closefile8,fd=1 flowop openfile name=openfile9,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile9,fd=1,iosize=$iosize flowop closefile name=closefile9,fd=1 flowop openfile name=openfile10,filesetname=bigfileset,fd=1 flowop readwholefile name=readfile10,fd=1,iosize=$iosize flowop closefile name=closefile10,fd=1 flowop appendfilerand name=appendlog,filesetname=logfiles,iosize=$meanappendsize,fd=2 } } echo "Web-server Version 3.1 personality successfully loaded" run 60
3,226
40.371795
116
f
vim
vim-master/LICENSE.md
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
11,357
55.227723
77
md
vim
vim-master/README.md
# Official code for ViM: Out-Of-Distribution with Virtual-logit Matching [![🌊 - Project Page](https://img.shields.io/badge/🌊-Project_Page-blue)](http://ooddetection.github.io) [![🦢 - Paper](https://img.shields.io/badge/🦢-Paper-red)](https://arxiv.org/abs/2203.10807) https://user-images.githubusercontent.com/9464825/171095631-768127d5-8f21-4dcb-9ef3-5b9a210556fc.mp4 ## DataSets Dataset source can be downloaded here. - [ImageNet](https://www.image-net.org/). The ILSVRC 2012 dataset as In-distribution (ID) dataset. The training subset we used is [this file](datalists/imagenet2012_train_random_200k.txt). - [OpenImage-O](https://github.com/openimages/dataset/blob/main/READMEV3.md). The OpenImage-O dataset is a subset of the OpenImage-V3 testing set. The filelist is [here](datalists/openimage_o.txt). Please refer to [our paper of ViM](http://ooddetection.github.io) for details of dataset construction. - [Texture](https://www.robots.ox.ac.uk/~vgg/data/dtd/). We rule out four classes that coincides with ImageNet. The filelist used in the paper is [here](datalists/texture.txt). - [iNaturalist](https://arxiv.org/pdf/1707.06642.pdf). Follow the instructions in the [link](https://github.com/deeplearning-wisc/large_scale_ood) to prepare the iNaturalist OOD dataset. - [ImageNet-O](https://github.com/hendrycks/natural-adv-examples). Follow the guide to download the ImageNet-O OOD dataset. ```bash mkdir data cd data ln -s /path/to/imagenet imagenet ln -s /path/to/openimage_o openimage_o ln -s /path/to/texture texture ln -s /path/to/inaturalist inaturalist ln -s /path/to/imagenet_o imagenet_o cd .. ``` ## Pretrained Model Preparation ### VIT 1. install mmclassification 2. download checkpoint ```bash mkdir checkpoints cd checkpoints wget https://download.openmmlab.com/mmclassification/v0/vit/finetune/vit-base-p16_in21k-pre-3rdparty_ft-64xb64_in1k-384_20210928-98e8652b.pth cd .. ``` 3. extract features ```bash ./extract_feature_vit.py data/imagenet outputs/vit_imagenet_val.pkl --img_list datalists/imagenet2012_val_list.txt ./extract_feature_vit.py data/imagenet outputs/vit_train_200k.pkl --img_list datalists/imagenet2012_train_random_200k.txt ./extract_feature_vit.py data/openimage_o outputs/vit_openimage_o.pkl --img_list datalists/openimage_o.txt ./extract_feature_vit.py data/texture outputs/vit_texture.pkl --img_list datalists/texture.txt ./extract_feature_vit.py data/inaturalist outputs/vit_inaturalist.pkl ./extract_feature_vit.py data/imagenet_o outputs/vit_imagenet_o.pkl ``` 4. extract w and b in fc ```bash ./extract_feature_vit.py a b --fc_save_path outputs/vit_fc.pkl ``` 5. evaluation ```bash ./benchmark.py outputs/vit_fc.pkl outputs/vit_train_200k.pkl outputs/vit_imagenet_val.pkl outputs/vit_openimage_o.pkl outputs/vit_texture.pkl outputs/vit_inaturalist.pkl outputs/vit_imagenet_o.pkl ``` ### BIT 1. download checkpoint ```bash mkdir checkpoints cd checkpoints wget https://storage.googleapis.com/bit_models/BiT-S-R101x1.npz cd .. ``` 2. extract features ```bash ./extract_feature_bit.py data/imagenet outputs/bit_imagenet_val.pkl --img_list datalists/imagenet2012_val_list.txt ./extract_feature_bit.py data/imagenet outputs/bit_train_200k.pkl --img_list datalists/imagenet2012_train_random_200k.txt ./extract_feature_bit.py data/openimage_o outputs/bit_openimage_o.pkl --img_list datalists/openimage_o.txt ./extract_feature_bit.py data/texture outputs/bit_texture.pkl --img_list datalists/texture.txt ./extract_feature_bit.py data/inaturalist outputs/bit_inaturalist.pkl ./extract_feature_bit.py data/imagenet_o outputs/bit_imagenet_o.pkl ``` 3. extract w and b in fc ```bash ./extract_feature_bit.py a b --fc_save_path outputs/bit_fc.pkl ``` 4. evaluation ```bash ./benchmark.py outputs/bit_fc.pkl outputs/bit_train_200k.pkl outputs/bit_imagenet_val.pkl outputs/bit_openimage_o.pkl outputs/bit_texture.pkl outputs/bit_inaturalist.pkl outputs/bit_imagenet_o.pkl ``` ### RepVGG, Res50d, Swin, DeiT 1. extract features, use repvgg_b3, resnet50d, swin, deit as model ```bash # choose one of them export MODEL=repvgg_b3 && export NAME=repvgg export MODEL=resnet50d && export NAME=resnet50d export MODEL=swin_base_patch4_window7_224 && export NAME=swin export MODEL=deit_base_patch16_224 && export NAME=deit ./extract_feature_timm.py data/imagenet outputs/${NAME}_imagenet_val.pkl ${MODEL} --img_list datalists/imagenet2012_val_list.txt ./extract_feature_timm.py data/imagenet outputs/${NAME}_train_200k.pkl ${MODEL} --img_list datalists/imagenet2012_train_random_200k.txt ./extract_feature_timm.py data/openimage_o outputs/${NAME}_openimage_o.pkl ${MODEL} --img_list datalists/openimage_o.txt ./extract_feature_timm.py data/texture outputs/${NAME}_texture.pkl ${MODEL} --img_list datalists/texture.txt ./extract_feature_timm.py data/inaturalist outputs/${NAME}_inaturalist.pkl ${MODEL} ./extract_feature_timm.py data/imagenet_o outputs/${NAME}_imagenet_o.pkl ${MODEL} ``` 2. extract w and b in fc ```bash ./extract_feature_timm.py a b ${MODEL} --fc_save_path outputs/${NAME}_fc.pkl ``` 3. evaluation ```bash ./benchmark.py outputs/${NAME}_fc.pkl outputs/${NAME}_train_200k.pkl outputs/${NAME}_imagenet_val.pkl outputs/${NAME}_openimage_o.pkl outputs/${NAME}_texture.pkl outputs/${NAME}_inaturalist.pkl outputs/${NAME}_imagenet_o.pkl ``` Note: To reproduce ODIN baseline, please refer to [this repo](https://github.com/deeplearning-wisc/large_scale_ood). ## Citation ``` @inproceedings{haoqi2022vim, title = {ViM: Out-Of-Distribution with Virtual-logit Matching}, author = {Wang, Haoqi and Li, Zhizhong and Feng, Litong and Zhang, Wayne}, booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, year = {2022} } ``` ## Acknowledgement Part of the code is modified from [MOS](https://github.com/deeplearning-wisc/large_scale_ood) repo.
6,055
45.945736
300
md
vim
vim-master/benchmark.py
#!/usr/bin/env python import argparse import torch import numpy as np from tqdm import tqdm import mmcv from numpy.linalg import norm, pinv from scipy.special import softmax from sklearn import metrics from sklearn.metrics import pairwise_distances_argmin_min from sklearn.covariance import EmpiricalCovariance from os.path import basename, splitext from scipy.special import logsumexp import pandas as pd def parse_args(): parser = argparse.ArgumentParser(description='Say hello') parser.add_argument('fc', help='Path to config') parser.add_argument('id_train_feature', help='Path to data') parser.add_argument('id_val_feature', help='Path to output file') parser.add_argument('ood_features', nargs="+", help='Path to ood features') parser.add_argument('--train_label', default='datalists/imagenet2012_train_random_200k.txt', help='Path to train labels') parser.add_argument('--clip_quantile', default=0.99, help='Clip quantile to react') return parser.parse_args() #region Helper def num_fp_at_recall(ind_conf, ood_conf, tpr): num_ind = len(ind_conf) if num_ind == 0 and len(ood_conf) == 0: return 0, 0. if num_ind == 0: return 0, np.max(ood_conf) + 1 recall_num = int(np.floor(tpr * num_ind)) thresh = np.sort(ind_conf)[-recall_num] num_fp = np.sum(ood_conf >= thresh) return num_fp, thresh def fpr_recall(ind_conf, ood_conf, tpr): num_fp, thresh = num_fp_at_recall(ind_conf, ood_conf, tpr) num_ood = len(ood_conf) fpr = num_fp / max(1, num_ood) return fpr, thresh def auc(ind_conf, ood_conf): conf = np.concatenate((ind_conf, ood_conf)) ind_indicator = np.concatenate((np.ones_like(ind_conf), np.zeros_like(ood_conf))) fpr, tpr, _ = metrics.roc_curve(ind_indicator, conf) precision_in, recall_in, _ = metrics.precision_recall_curve( ind_indicator, conf) precision_out, recall_out, _ = metrics.precision_recall_curve( 1 - ind_indicator, 1 - conf) auroc = metrics.auc(fpr, tpr) aupr_in = metrics.auc(recall_in, precision_in) aupr_out = metrics.auc(recall_out, precision_out) return auroc, aupr_in, aupr_out def kl(p, q): return np.sum(np.where(p != 0, p * np.log(p / q), 0)) #endregion #region OOD def gradnorm(x, w, b): fc = torch.nn.Linear(*w.shape[::-1]) fc.weight.data[...] = torch.from_numpy(w) fc.bias.data[...] = torch.from_numpy(b) fc.cuda() x = torch.from_numpy(x).float().cuda() logsoftmax = torch.nn.LogSoftmax(dim=-1).cuda() confs = [] for i in tqdm(x): targets = torch.ones((1, 1000)).cuda() fc.zero_grad() loss = torch.mean(torch.sum(-targets * logsoftmax(fc(i[None])), dim=-1)) loss.backward() layer_grad_norm = torch.sum(torch.abs(fc.weight.grad.data)).cpu().numpy() confs.append(layer_grad_norm) return np.array(confs) #endregion def main(): args = parse_args() ood_names = [splitext(basename(ood))[0] for ood in args.ood_features] print(f"ood datasets: {ood_names}") w, b = mmcv.load(args.fc) print(f'{w.shape=}, {b.shape=}') train_labels = np.array([int(line.rsplit(' ', 1)[-1]) for line in mmcv.list_from_file(args.train_label)], dtype=int) recall = 0.95 print('load features') feature_id_train = mmcv.load(args.id_train_feature).squeeze() feature_id_val = mmcv.load(args.id_val_feature).squeeze() feature_oods = {name: mmcv.load(feat).squeeze() for name, feat in zip(ood_names, args.ood_features)} print(f'{feature_id_train.shape=}, {feature_id_val.shape=}') for name, ood in feature_oods.items(): print(f'{name} {ood.shape}') print('computing logits...') logit_id_train = feature_id_train @ w.T + b logit_id_val = feature_id_val @ w.T + b logit_oods = {name: feat @ w.T + b for name, feat in feature_oods.items()} print('computing softmax...') softmax_id_train = softmax(logit_id_train, axis=-1) softmax_id_val = softmax(logit_id_val, axis=-1) softmax_oods = {name: softmax(logit, axis=-1) for name, logit in logit_oods.items()} u = -np.matmul(pinv(w), b) df = pd.DataFrame(columns = ['method', 'oodset', 'auroc', 'fpr']) dfs = [] # --------------------------------------- method = 'MSP' print(f'\n{method}') result = [] score_id = softmax_id_val.max(axis=-1) for name, softmax_ood in softmax_oods.items(): score_ood = softmax_ood.max(axis=-1) auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'MaxLogit' print(f'\n{method}') result = [] score_id = logit_id_val.max(axis=-1) for name, logit_ood in logit_oods.items(): score_ood = logit_ood.max(axis=-1) auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'Energy' print(f'\n{method}') result = [] score_id = logsumexp(logit_id_val, axis=-1) for name, logit_ood in logit_oods.items(): score_ood = logsumexp(logit_ood, axis=-1) auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'Energy+React' print(f'\n{method}') result = [] clip = np.quantile(feature_id_train, args.clip_quantile) print(f'clip quantile {args.clip_quantile}, clip {clip:.4f}') logit_id_val_clip = np.clip(feature_id_val, a_min=None, a_max=clip) @ w.T + b score_id = logsumexp(logit_id_val_clip, axis=-1) for name, feature_ood in feature_oods.items(): logit_ood_clip = np.clip(feature_ood, a_min=None, a_max=clip) @ w.T + b score_ood = logsumexp(logit_ood_clip, axis=-1) auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'ViM' print(f'\n{method}') result = [] DIM = 1000 if feature_id_val.shape[-1] >= 2048 else 512 print(f'{DIM=}') print('computing principal space...') ec = EmpiricalCovariance(assume_centered=True) ec.fit(feature_id_train - u) eig_vals, eigen_vectors = np.linalg.eig(ec.covariance_) NS = np.ascontiguousarray((eigen_vectors.T[np.argsort(eig_vals * -1)[DIM:]]).T) print('computing alpha...') vlogit_id_train = norm(np.matmul(feature_id_train - u, NS), axis=-1) alpha = logit_id_train.max(axis=-1).mean() / vlogit_id_train.mean() print(f'{alpha=:.4f}') vlogit_id_val = norm(np.matmul(feature_id_val - u, NS), axis=-1) * alpha energy_id_val = logsumexp(logit_id_val, axis=-1) score_id = -vlogit_id_val + energy_id_val for name, logit_ood, feature_ood in zip(ood_names, logit_oods.values(), feature_oods.values()): energy_ood = logsumexp(logit_ood, axis=-1) vlogit_ood = norm(np.matmul(feature_ood - u, NS), axis=-1) * alpha score_ood = -vlogit_ood + energy_ood auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'Residual' print(f'\n{method}') result = [] DIM = 1000 if feature_id_val.shape[-1] >= 2048 else 512 print(f'{DIM=}') print('computing principal space...') ec = EmpiricalCovariance(assume_centered=True) ec.fit(feature_id_train - u) eig_vals, eigen_vectors = np.linalg.eig(ec.covariance_) NS = np.ascontiguousarray((eigen_vectors.T[np.argsort(eig_vals * -1)[DIM:]]).T) score_id = -norm(np.matmul(feature_id_val - u, NS), axis=-1) for name, logit_ood, feature_ood in zip(ood_names, logit_oods.values(), feature_oods.values()): score_ood = -norm(np.matmul(feature_ood - u, NS), axis=-1) auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'GradNorm' print(f'\n{method}') result = [] score_id = gradnorm(feature_id_val, w, b) for name, feature_ood in feature_oods.items(): score_ood = gradnorm(feature_ood, w, b) auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'Mahalanobis' print(f'\n{method}') result = [] print('computing classwise mean feature...') train_means = [] train_feat_centered = [] for i in tqdm(range(1000)): fs = feature_id_train[train_labels == i] _m = fs.mean(axis=0) train_means.append(_m) train_feat_centered.extend(fs - _m) print('computing precision matrix...') ec = EmpiricalCovariance(assume_centered=True) ec.fit(np.array(train_feat_centered).astype(np.float64)) print('go to gpu...') mean = torch.from_numpy(np.array(train_means)).cuda().float() prec = torch.from_numpy(ec.precision_).cuda().float() score_id = -np.array([(((f - mean)@prec) * (f - mean)).sum(axis=-1).min().cpu().item() for f in tqdm(torch.from_numpy(feature_id_val).cuda().float())]) for name, feature_ood in feature_oods.items(): score_ood = -np.array([(((f - mean)@prec) * (f - mean)).sum(axis=-1).min().cpu().item() for f in tqdm(torch.from_numpy(feature_ood).cuda().float())]) auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') # --------------------------------------- method = 'KL-Matching' print(f'\n{method}') result = [] print('computing classwise mean softmax...') pred_labels_train = np.argmax(softmax_id_train, axis=-1) mean_softmax_train = [softmax_id_train[pred_labels_train==i].mean(axis=0) for i in tqdm(range(1000))] score_id = -pairwise_distances_argmin_min(softmax_id_val, np.array(mean_softmax_train), metric=kl)[1] for name, softmax_ood in softmax_oods.items(): score_ood = -pairwise_distances_argmin_min(softmax_ood, np.array(mean_softmax_train), metric=kl)[1] auc_ood = auc(score_id, score_ood)[0] fpr_ood, _ = fpr_recall(score_id, score_ood, recall) result.append(dict(method=method, oodset=name, auroc=auc_ood, fpr=fpr_ood)) print(f'{method}: {name} auroc {auc_ood:.2%}, fpr {fpr_ood:.2%}') df = pd.DataFrame(result) dfs.append(df) print(f'mean auroc {df.auroc.mean():.2%}, {df.fpr.mean():.2%}') if __name__ == '__main__': main()
12,747
38.224615
157
py
vim
vim-master/extract_feature_bit.py
#!/usr/bin/env python import argparse import torch from list_dataset import ImageFilelist import numpy as np import pickle from tqdm import tqdm import mmcv from os.path import dirname import torchvision as tv import resnetv2 def parse_args(): parser = argparse.ArgumentParser(description='Say hello') parser.add_argument('data_root', help='Path to data') parser.add_argument('out_file', help='Path to output file') parser.add_argument('--model', default='BiT-S-R101x1', help='Bit model') parser.add_argument('--checkpoint', default='checkpoints/BiT-S-R101x1.npz', help='Path to checkpoint') parser.add_argument('--img_list', default=None, help='Path to image list') parser.add_argument('--batch', type=int, default=256, help='Path to data') parser.add_argument('--workers', type=int, default=4, help='Path to data') parser.add_argument('--fc_save_path', default=None, help='Path to save fc') return parser.parse_args() def main(): args = parse_args() torch.backends.cudnn.benchmark = True model = resnetv2.KNOWN_MODELS[args.model]() model.load_from(np.load(args.checkpoint)) model.cuda().eval() if args.fc_save_path is not None: mmcv.mkdir_or_exist(dirname(args.fc_save_path)) w = model.head.conv.weight.cpu().detach().squeeze().numpy() b = model.head.conv.bias.cpu().detach().squeeze().numpy() with open(args.fc_save_path, 'wb') as f: pickle.dump([w, b], f) return transform = tv.transforms.Compose([ tv.transforms.Resize((480, 480)), tv.transforms.ToTensor(), tv.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ]) if args.img_list is not None: dataset = ImageFilelist(args.data_root, args.img_list, transform) else: dataset = tv.datasets.ImageFolder(args.data_root, transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=args.batch, shuffle=False, num_workers=args.workers, pin_memory=True, drop_last=False) features = [] with torch.no_grad(): for x, _ in tqdm(dataloader): x = x.cuda() feat_batch = model(x, layer_index=5).cpu().numpy() features.append(feat_batch) features = np.concatenate(features, axis=0) mmcv.mkdir_or_exist(dirname(args.out_file)) with open(args.out_file, 'wb') as f: pickle.dump(features, f) if __name__ == '__main__': main()
2,462
31.84
106
py
vim
vim-master/extract_feature_timm.py
#!/usr/bin/env python import argparse import torch from list_dataset import ImageFilelist import numpy as np import pickle from tqdm import tqdm import mmcv from os.path import dirname import torchvision as tv import timm def parse_args(): parser = argparse.ArgumentParser(description='Say hello') parser.add_argument('data_root', help='Path to data') parser.add_argument('out_file', help='Path to output file') parser.add_argument('model', help='Path to config') parser.add_argument('--checkpoint', default='checkpoints/vit-base-p16_in21k-pre-3rdparty_ft-64xb64_in1k-384_20210928-98e8652b.pth', help='Path to checkpoint') parser.add_argument('--img_list', default=None, help='Path to image list') parser.add_argument('--batch', type=int, default=256, help='Path to data') parser.add_argument('--workers', type=int, default=4, help='Path to data') parser.add_argument('--fc_save_path', default=None, help='Path to save fc') return parser.parse_args() def main(): args = parse_args() torch.backends.cudnn.benchmark = True if args.fc_save_path is not None: model = timm.create_model(args.model, pretrained=True) mmcv.mkdir_or_exist(dirname(args.fc_save_path)) if args.model in ['repvgg_b3']: w = model.head.fc.weight.cpu().detach().numpy() b = model.head.fc.bias.cpu().detach().numpy() elif args.model in ['swin_base_patch4_window7_224', 'deit_base_patch16_224']: w = model.head.weight.cpu().detach().numpy() b = model.head.bias.cpu().detach().numpy() else: w = model.fc.weight.cpu().detach().numpy() b = model.fc.bias.cpu().detach().numpy() with open(args.fc_save_path, 'wb') as f: pickle.dump([w, b], f) return model = timm.create_model(args.model, pretrained=True, num_classes=0).cuda().eval() transform = tv.transforms.Compose([ tv.transforms.Resize((224, 224)), tv.transforms.ToTensor(), tv.transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) if args.img_list is not None: dataset = ImageFilelist(args.data_root, args.img_list, transform) else: dataset = tv.datasets.ImageFolder(args.data_root, transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=args.batch, shuffle=False, num_workers=args.workers, pin_memory=True, drop_last=False) features = [] with torch.no_grad(): for x, _ in tqdm(dataloader): x = x.cuda() feat_batch = model(x).cpu().numpy() features.append(feat_batch) features = np.concatenate(features, axis=0) mmcv.mkdir_or_exist(dirname(args.out_file)) with open(args.out_file, 'wb') as f: pickle.dump(features, f) if __name__ == '__main__': main()
2,866
34.8375
162
py
vim
vim-master/extract_feature_vit.py
#!/usr/bin/env python import argparse from mmcls.apis import init_model import torch from list_dataset import ImageFilelist import numpy as np import pickle from tqdm import tqdm import mmcv from os.path import dirname import torchvision as tv def parse_args(): parser = argparse.ArgumentParser(description='Say hello') parser.add_argument('data_root', help='Path to data') parser.add_argument('out_file', help='Path to output file') parser.add_argument('--cfg', default='vit-base-p16-384.py', help='Path to config') parser.add_argument('--checkpoint', default='checkpoints/vit-base-p16_in21k-pre-3rdparty_ft-64xb64_in1k-384_20210928-98e8652b.pth', help='Path to checkpoint') parser.add_argument('--img_list', default=None, help='Path to image list') parser.add_argument('--batch', type=int, default=256, help='Path to data') parser.add_argument('--workers', type=int, default=4, help='Path to data') parser.add_argument('--fc_save_path', default=None, help='Path to save fc') return parser.parse_args() def main(): args = parse_args() torch.backends.cudnn.benchmark = True cfg = mmcv.Config.fromfile(args.cfg) model = init_model(cfg, args.checkpoint, 0).cuda().eval() if args.fc_save_path is not None: mmcv.mkdir_or_exist(dirname(args.fc_save_path)) w = model.head.layers.head.weight.cpu().detach().numpy() b = model.head.layers.head.bias.cpu().detach().numpy() with open(args.fc_save_path, 'wb') as f: pickle.dump([w, b], f) return transform = tv.transforms.Compose([ tv.transforms.Resize((384, 384)), tv.transforms.ToTensor(), tv.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ]) if args.img_list is not None: dataset = ImageFilelist(args.data_root, args.img_list, transform) else: dataset = tv.datasets.ImageFolder(args.data_root, transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=args.batch, shuffle=False, num_workers=args.workers, pin_memory=True, drop_last=False) features = [] with torch.no_grad(): for x, _ in tqdm(dataloader): x = x.cuda() feat_batch = model.backbone(x)[0][-1].cpu().numpy() features.append(feat_batch) features = np.concatenate(features, axis=0) mmcv.mkdir_or_exist(dirname(args.out_file)) with open(args.out_file, 'wb') as f: pickle.dump(features, f) if __name__ == '__main__': main()
2,525
33.60274
162
py
vim
vim-master/list_dataset.py
import torch.utils.data as data from PIL import Image import os import os.path def default_loader(path): return Image.open(path).convert('RGB') def default_flist_reader(flist): """ flist format: impath label\nimpath label\n """ imlist = [] with open(flist, 'r') as rf: for line in rf.readlines(): data = line.strip().rsplit(maxsplit=1) if len(data) == 2: impath, imlabel = data else: impath, imlabel = data[0], 0 imlist.append( (impath, int(imlabel)) ) return imlist class ImageFilelist(data.Dataset): def __init__(self, root, flist, transform=None, target_transform=None, flist_reader=default_flist_reader, loader=default_loader): self.root = root self.imlist = flist_reader(flist) self.transform = transform self.target_transform = target_transform self.loader = loader def __getitem__(self, index): impath, target = self.imlist[index] img = self.loader(os.path.join(self.root,impath)) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target def __len__(self): return len(self.imlist)
1,157
23.638298
71
py
vim
vim-master/resnetv2.py
"""Bottleneck ResNet v2 with GroupNorm and Weight Standardization.""" from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import torch.nn as nn class Reshape(nn.Module): def __init__(self, *args): super(Reshape, self).__init__() self.shape = args def forward(self, x): return x.view(self.shape) class StdConv2d(nn.Conv2d): def forward(self, x): w = self.weight v, m = torch.var_mean(w, dim=[1, 2, 3], keepdim=True, unbiased=False) w = (w - m) / torch.sqrt(v + 1e-10) return F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups) def conv3x3(cin, cout, stride=1, groups=1, bias=False): return StdConv2d(cin, cout, kernel_size=3, stride=stride, padding=1, bias=bias, groups=groups) def conv1x1(cin, cout, stride=1, bias=False): return StdConv2d(cin, cout, kernel_size=1, stride=stride, padding=0, bias=bias) def tf2th(conv_weights): """Possibly convert HWIO to OIHW.""" if conv_weights.ndim == 4: conv_weights = conv_weights.transpose([3, 2, 0, 1]) return torch.from_numpy(conv_weights) class PreActBottleneck(nn.Module): """Pre-activation (v2) bottleneck block. Follows the implementation of "Identity Mappings in Deep Residual Networks": https://github.com/KaimingHe/resnet-1k-layers/blob/master/resnet-pre-act.lua Except it puts the stride on 3x3 conv when available. """ def __init__(self, cin, cout=None, cmid=None, stride=1): super().__init__() cout = cout or cin cmid = cmid or cout // 4 self.gn1 = nn.GroupNorm(32, cin) self.conv1 = conv1x1(cin, cmid) self.gn2 = nn.GroupNorm(32, cmid) self.conv2 = conv3x3(cmid, cmid, stride) # Original code has it on conv1!! self.gn3 = nn.GroupNorm(32, cmid) self.conv3 = conv1x1(cmid, cout) self.relu = nn.ReLU(inplace=True) if (stride != 1 or cin != cout): # Projection also with pre-activation according to paper. self.downsample = conv1x1(cin, cout, stride) def forward(self, x): out = self.relu(self.gn1(x)) # Residual branch residual = x if hasattr(self, 'downsample'): residual = self.downsample(out) # Unit's branch out = self.conv1(out) out = self.conv2(self.relu(self.gn2(out))) out = self.conv3(self.relu(self.gn3(out))) return out + residual def load_from(self, weights, prefix=''): convname = 'standardized_conv2d' with torch.no_grad(): self.conv1.weight.copy_(tf2th(weights[f'{prefix}a/{convname}/kernel'])) self.conv2.weight.copy_(tf2th(weights[f'{prefix}b/{convname}/kernel'])) self.conv3.weight.copy_(tf2th(weights[f'{prefix}c/{convname}/kernel'])) self.gn1.weight.copy_(tf2th(weights[f'{prefix}a/group_norm/gamma'])) self.gn2.weight.copy_(tf2th(weights[f'{prefix}b/group_norm/gamma'])) self.gn3.weight.copy_(tf2th(weights[f'{prefix}c/group_norm/gamma'])) self.gn1.bias.copy_(tf2th(weights[f'{prefix}a/group_norm/beta'])) self.gn2.bias.copy_(tf2th(weights[f'{prefix}b/group_norm/beta'])) self.gn3.bias.copy_(tf2th(weights[f'{prefix}c/group_norm/beta'])) if hasattr(self, 'downsample'): w = weights[f'{prefix}a/proj/{convname}/kernel'] self.downsample.weight.copy_(tf2th(w)) class ResNetV2(nn.Module): """Implementation of Pre-activation (v2) ResNet mode.""" def __init__(self, block_units, width_factor, head_size=1000, num_block_open=-1): super().__init__() wf = width_factor # shortcut 'cause we'll use it a lot. if num_block_open == -1: self.fix_parts = [] self.fix_gn1 = None elif num_block_open == 0: self.fix_parts = ['root', 'block1', 'block2', 'block3', 'block4', 'before_head'] self.fix_gn1 = None elif num_block_open == 1: self.fix_parts = ['root', 'block1', 'block2', 'block3'] self.fix_gn1 = 'block4' elif num_block_open == 2: self.fix_parts = ['root', 'block1', 'block2'] self.fix_gn1 = 'block3' elif num_block_open == 3: self.fix_parts = ['root', 'block1'] self.fix_gn1 = 'block2' elif num_block_open == 4: self.fix_parts = ['root'] self.fix_gn1 = 'block1' else: raise ValueError('Unexpected block number {}'.format(num_block_open)) self.root = nn.Sequential(OrderedDict([ ('conv', StdConv2d(3, 64 * wf, kernel_size=7, stride=2, padding=3, bias=False)), ('pad', nn.ConstantPad2d(1, 0)), ('pool', nn.MaxPool2d(kernel_size=3, stride=2, padding=0)), # The following is subtly not the same! # ('pool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), ])) self.body = nn.Sequential(OrderedDict([ ('block1', nn.Sequential(OrderedDict( [('unit01', PreActBottleneck(cin=64 * wf, cout=256 * wf, cmid=64 * wf))] + [(f'unit{i:02d}', PreActBottleneck(cin=256 * wf, cout=256 * wf, cmid=64 * wf)) for i in range(2, block_units[0] + 1)], ))), ('block2', nn.Sequential(OrderedDict( [('unit01', PreActBottleneck(cin=256 * wf, cout=512 * wf, cmid=128 * wf, stride=2))] + [(f'unit{i:02d}', PreActBottleneck(cin=512 * wf, cout=512 * wf, cmid=128 * wf)) for i in range(2, block_units[1] + 1)], ))), ('block3', nn.Sequential(OrderedDict( [('unit01', PreActBottleneck(cin=512 * wf, cout=1024 * wf, cmid=256 * wf, stride=2))] + [(f'unit{i:02d}', PreActBottleneck(cin=1024 * wf, cout=1024 * wf, cmid=256 * wf)) for i in range(2, block_units[2] + 1)], ))), ('block4', nn.Sequential(OrderedDict( [('unit01', PreActBottleneck(cin=1024 * wf, cout=2048 * wf, cmid=512 * wf, stride=2))] + [(f'unit{i:02d}', PreActBottleneck(cin=2048 * wf, cout=2048 * wf, cmid=512 * wf)) for i in range(2, block_units[3] + 1)], ))), ])) self.before_head = nn.Sequential(OrderedDict([ ('gn', nn.GroupNorm(32, 2048 * wf)), ('relu', nn.ReLU(inplace=True)), ('avg', nn.AdaptiveAvgPool2d(output_size=1)), ])) self.head = nn.Sequential(OrderedDict([ ('conv', nn.Conv2d(2048 * wf, head_size, kernel_size=1, bias=True)), ])) if 'root' in self.fix_parts: for param in self.root.parameters(): param.requires_grad = False for bname, block in self.body.named_children(): if bname in self.fix_parts: for param in block.parameters(): param.requires_grad = False elif bname == self.fix_gn1: for param in block.unit01.gn1.parameters(): param.requires_grad = False def intermediate_forward(self, x, layer_index=None): if layer_index == 'all': out_list = [] out = self.root(x) out_list.append(out) out = self.body.block1(out) out_list.append(out) out = self.body.block2(out) out_list.append(out) out = self.body.block3(out) out_list.append(out) out = self.body.block4(out) out_list.append(out) out = self.head(self.before_head(out)) return out[..., 0, 0], out_list out = self.root(x) if layer_index == 1: out = self.body.block1(out) elif layer_index == 2: out = self.body.block1(out) out = self.body.block2(out) elif layer_index == 3: out = self.body.block1(out) out = self.body.block2(out) out = self.body.block3(out) elif layer_index == 4: out = self.body.block1(out) out = self.body.block2(out) out = self.body.block3(out) out = self.body.block4(out) elif layer_index == 5: out = self.body.block1(out) out = self.body.block2(out) out = self.body.block3(out) out = self.body.block4(out) out = self.before_head(out) return out def forward(self, x, layer_index=None): if layer_index is not None: return self.intermediate_forward(x, layer_index) if 'root' in self.fix_parts: with torch.no_grad(): x = self.root(x) else: x = self.root(x) for bname, block in self.body.named_children(): if bname in self.fix_parts: with torch.no_grad(): x = block(x) else: x = block(x) if 'before_head' in self.fix_parts: with torch.no_grad(): x = self.before_head(x) else: x = self.before_head(x) x = self.head(x) assert x.shape[-2:] == (1, 1) # We should have no spatial shape left. return x[..., 0, 0] def load_state_dict_custom(self, state_dict): state_dict_new = {} for k, v in state_dict.items(): state_dict_new[k[len("module."):]] = v self.load_state_dict(state_dict_new, strict=True) def load_from(self, weights, prefix='resnet/'): with torch.no_grad(): self.root.conv.weight.copy_( tf2th(weights[f'{prefix}root_block/standardized_conv2d/kernel'])) # pylint: disable=line-too-long self.before_head.gn.weight.copy_(tf2th(weights[f'{prefix}group_norm/gamma'])) self.before_head.gn.bias.copy_(tf2th(weights[f'{prefix}group_norm/beta'])) self.head.conv.weight.copy_( tf2th(weights[f'{prefix}head/conv2d/kernel'])) # pylint: disable=line-too-long self.head.conv.bias.copy_(tf2th(weights[f'{prefix}head/conv2d/bias'])) for bname, block in self.body.named_children(): for uname, unit in block.named_children(): unit.load_from(weights, prefix=f'{prefix}{bname}/{uname}/') def train(self, mode=True): self.training = mode for module in self.children(): module.train(mode) self.head.train(mode) if 'root' in self.fix_parts: self.root.eval() else: self.root.train(mode) for bname, block in self.body.named_children(): if bname in self.fix_parts: block.eval() elif bname == self.fix_gn1: block.train(mode) block.unit01.gn1.eval() else: block.train(mode) if 'before_head' in self.fix_parts: self.before_head.eval() else: self.before_head.train(mode) return self KNOWN_MODELS = OrderedDict([ ('BiT-M-R50x1', lambda *a, **kw: ResNetV2([3, 4, 6, 3], 1, *a, **kw)), ('BiT-M-R50x3', lambda *a, **kw: ResNetV2([3, 4, 6, 3], 3, *a, **kw)), ('BiT-M-R101x1', lambda *a, **kw: ResNetV2([3, 4, 23, 3], 1, *a, **kw)), ('BiT-M-R101x3', lambda *a, **kw: ResNetV2([3, 4, 23, 3], 3, *a, **kw)), ('BiT-M-R152x2', lambda *a, **kw: ResNetV2([3, 8, 36, 3], 2, *a, **kw)), ('BiT-M-R152x4', lambda *a, **kw: ResNetV2([3, 8, 36, 3], 4, *a, **kw)), ('BiT-S-R50x1', lambda *a, **kw: ResNetV2([3, 4, 6, 3], 1, *a, **kw)), ('BiT-S-R50x3', lambda *a, **kw: ResNetV2([3, 4, 6, 3], 3, *a, **kw)), ('BiT-S-R101x1', lambda *a, **kw: ResNetV2([3, 4, 23, 3], 1, *a, **kw)), ('BiT-S-R101x3', lambda *a, **kw: ResNetV2([3, 4, 23, 3], 3, *a, **kw)), ('BiT-S-R152x2', lambda *a, **kw: ResNetV2([3, 8, 36, 3], 2, *a, **kw)), ('BiT-S-R152x4', lambda *a, **kw: ResNetV2([3, 8, 36, 3], 4, *a, **kw)), ])
12,199
38.354839
114
py
vim
vim-master/vit-base-p16-384.py
# model settings model = dict( type='ImageClassifier', backbone=dict( type='VisionTransformer', arch='b', img_size=384, patch_size=16, drop_rate=0.1, init_cfg=[ dict( type='Kaiming', layer='Conv2d', mode='fan_in', nonlinearity='linear') ]), neck=None, head=dict( type='VisionTransformerClsHead', num_classes=1000, in_channels=768, loss=dict( type='LabelSmoothLoss', label_smooth_val=0.1, mode='classy_vision'), ))
622
22.961538
57
py
vnncomp2022_results
vnncomp2022_results-master/README.md
# vnncomp2022_results This repo contains the results for VNN COMP 2022 for each tool, as well as scoring code in the `SCORING` directory. Links: * VNN COMP 2022 website: https://sites.google.com/view/vnn2022 * Benchmark list: https://github.com/ChristopherBrix/vnncomp2022_benchmarks * Online discussion of benchmarks / tools: https://github.com/stanleybak/vnncomp2022/issues
381
37.2
115
md
vnncomp2022_results
vnncomp2022_results-master/SCORING/counterexamples.py
""" code related to checking for counterexamples """ from pathlib import Path import gzip import datetime import numpy as np import onnx import onnxruntime as ort from vnnlib import read_vnnlib_simple, get_io_nodes from cachier import cachier from settings import Settings def predict_with_onnxruntime(model_def, *inputs): 'run an onnx model' sess = ort.InferenceSession(model_def.SerializeToString()) names = [i.name for i in sess.get_inputs()] inp = dict(zip(names, inputs)) res = sess.run(None, inp) #names = [o.name for o in sess.get_outputs()] return res[0] def read_ce_file(ce_path): """get file contents""" if ce_path.endswith('.gz'): with gzip.open(ce_path, 'rb') as f: content = f.read().decode('utf-8') else: with open(ce_path, 'r', encoding='utf-8') as f: content = f.read() content = content.replace('\n', ' ').strip() return content class CounterexampleResult: """enum for return value of is_correct_counterexample""" CORRECT = "correct" NO_CE = "no_ce" EXEC_DOESNT_MATCH = "exec_doesnt_match" SPEC_NOT_VIOLATED = "spec_not_violated" def is_correct_counterexample(ce_path, cat, net, prop): """is the counterexample correct? returns an element of CounterexampleResult """ print(f"Checking ce path: {ce_path}") benchmark_repo = Settings.BENCHMARK_REPO onnx_filename = f"{benchmark_repo}/benchmarks/{cat}/onnx/{net}.onnx" vnnlib_filename = f"{benchmark_repo}/benchmarks/{cat}/vnnlib/{prop}.vnnlib" if not Path(onnx_filename).is_file(): # try unzipping gz_path = f"{onnx_filename}.gz" if not Path(gz_path).is_file(): print(f"WARNING: onnx and gz path don't exist: {gz_path}") else: print(f"extracting from {gz_path} to {onnx_filename}") with gzip.open(gz_path, 'rb') as f: content = f.read() with open(onnx_filename, 'wb') as fout: fout.write(content) if not Path(vnnlib_filename).is_file(): # try unzipping gz_path = f"{vnnlib_filename}.gz" if Path(gz_path).is_file(): print(f"extracting from {gz_path} to {vnnlib_filename}") with gzip.open(gz_path, 'rb') as f: content = f.read() with open(vnnlib_filename, 'wb') as fout: fout.write(content) assert Path(onnx_filename).is_file(), f"onnx file '{onnx_filename}' not found. " + \ f"After cloning benchmarks did you run setup.sh in {Settings.BENCHMARK_REPO}?" assert Path(vnnlib_filename).is_file(), f"vnnlib file not found: {vnnlib_filename}" ################################################ res, msg = get_ce_diff(onnx_filename, vnnlib_filename, ce_path, Settings.COUNTEREXAMPLE_TOL) print(f"{res}: {msg}") return res @cachier(stale_after=datetime.timedelta(days=7)) def get_ce_diff(onnx_filename, vnnlib_filename, ce_path, tol): """get difference in execution""" content = read_ce_file(ce_path) if len(content) < 2: return CounterexampleResult.NO_CE, f"Note: no counter example provided in {ce_path}" #print(f"CE CONTENT:\n{content}") assert content[0] == '(' and content[-1] == ')' content = content[1:-1] x_list = [] y_list = [] parts = content.split(')') for part in parts: part = part.strip() if not part: continue assert part[0] == '(' part = part[1:] name, num = part.split(' ') assert name[0:2] in ['X_', 'Y_'] if name[0:2] == 'X_': assert int(name[2:]) == len(x_list) x_list.append(float(num)) else: assert int(name[2:]) == len(y_list) y_list.append(float(num)) onnx_model = onnx.load(onnx_filename) inp, _out, input_dtype = get_io_nodes(onnx_model) input_shape = tuple(d.dim_value if d.dim_value != 0 else 1 for d in inp.type.tensor_type.shape.dim) x_in = np.array(x_list, dtype=input_dtype) flatten_order = 'C' x_in = x_in.reshape(input_shape, order=flatten_order) output = predict_with_onnxruntime(onnx_model, x_in) flat_out = output.flatten(flatten_order) expected_y = np.array(y_list) diff = np.linalg.norm(flat_out - expected_y, ord=np.inf) #return diff, tuple(x_list), tuple(y_list) #diff, x_tup, y_tup = res msg = f"L-inf norm difference between onnx execution and CE file output: {diff} (limit: {tol})" rv = CounterexampleResult.CORRECT if diff > tol: rv = CounterexampleResult.EXEC_DOESNT_MATCH else: # output matched onnxruntime, also need to check that the spec file was obeyed is_vio, msg2 = is_specification_vio(onnx_filename, vnnlib_filename, tuple(x_list), tuple(y_list), tol) msg += "\n" + msg2 if not is_vio: msg += "\nNote: counterexample in file did not violate the specification and so was invalid!" rv = CounterexampleResult.SPEC_NOT_VIOLATED return rv, msg @cachier(stale_after=datetime.timedelta(days=7)) def is_specification_vio(onnx_filename, vnnlib_filename, x_list, expected_y, tol): """check that the spec file was obeyed""" msg = "Checking if spec was actually violated" onnx_model = onnx.load(onnx_filename) inp, out, _ = get_io_nodes(onnx_model) inp_shape = tuple(d.dim_value if d.dim_value != 0 else 1 for d in inp.type.tensor_type.shape.dim) out_shape = tuple(d.dim_value if d.dim_value != 0 else 1 for d in out.type.tensor_type.shape.dim) num_inputs = 1 num_outputs = 1 for n in inp_shape: num_inputs *= n for n in out_shape: num_outputs *= n box_spec_list = read_vnnlib_simple(vnnlib_filename, num_inputs, num_outputs) rv = False for i, box_spec in enumerate(box_spec_list): input_box, spec_list = box_spec assert len(input_box) == len(x_list), f"input box len: {len(input_box)}, x_in len: {len(x_list)}" inside_input_box = True for (lb, ub), x in zip(input_box, x_list): if x < lb - tol or x > ub + tol: inside_input_box = False break if inside_input_box: msg += f"\nCE input X was inside box #{i}" # check spec violated = False for j, (prop_mat, prop_rhs) in enumerate(spec_list): vec = prop_mat.dot(expected_y) sat = np.all(vec <= prop_rhs + tol) if sat: msg += f"\nprop #{j} violated:\n{vec - prop_rhs}" violated = True break if violated: rv = True break return rv, msg def test(): """test code""" ce_filename = "test_ce.txt" cat = "cifar100_tinyimagenet_resnet" net = "TinyImageNet_resnet_medium" prop = "TinyImageNet_resnet_medium_prop_idx_6461_sidx_2771_eps_0.0039" #ce_filename = "mnist-net_256x2_prop_1_0.03.counterexample.gz" #net = "mnist-net_256x2" #prop = "prop_1_0.03" #cat = "mnist_fc" res = is_correct_counterexample(ce_filename, cat, net, prop) if res: print("counter example is correct") else: print("counter example is NOT correct") if __name__ == "__main__": test()
7,514
28.241245
110
py
vnncomp2022_results
vnncomp2022_results-master/SCORING/merge_results_per_team.sh
for d in */; do cat $d/*/results.csv > $d/results.csv done
64
12
41
sh
vnncomp2022_results
vnncomp2022_results-master/SCORING/process_results.py
""" Process vnncomp results Stanley Bak """ from typing import Dict, List, Tuple, Union import glob import csv from pathlib import Path from collections import defaultdict import numpy as np from counterexamples import is_correct_counterexample, CounterexampleResult from settings import Settings class ToolResult: """Tool's result""" # columns CATEGORY = 0 NETWORK = 1 PROP = 2 PREPARE_TIME = 3 RESULT = 4 RUN_TIME = 5 all_categories = set() # stats num_verified = defaultdict(int) # number of benchmarks verified num_violated = defaultdict(int) num_holds = defaultdict(int) incorrect_results = defaultdict(int) num_categories = defaultdict(int) toolerror_counts = defaultdict(int) def __init__(self, scored, tool_name, csv_path, cpu_benchmarks, skip_benchmarks): assert "csv" in csv_path self.tool_name = tool_name self.category_to_list = defaultdict(list) # maps category -> list of results self.skip_benchmarks = skip_benchmarks self.cpu_benchmarks = cpu_benchmarks self.gpu_overhead = np.inf # default overhead self.cpu_overhead = np.inf # if using separate overhead for cpu self.max_prepare = 0.0 self.load(scored, csv_path) @staticmethod def reset(): """reset static variables""" ToolResult.all_categories = set() # stats ToolResult.num_verified = defaultdict(int) # number of benchmarks verified ToolResult.num_violated = defaultdict(int) ToolResult.num_holds = defaultdict(int) ToolResult.incorrect_results = defaultdict(int) ToolResult.num_categories = defaultdict(int) ToolResult.toolerror_counts = defaultdict(int) def result_instance_str(self, cat, index): """get a string representation of the instance for the given category and index""" row = self.category_to_list[cat][index] net = row[ToolResult.NETWORK] prop = row[ToolResult.PROP] return Path(net).stem + "-" + Path(prop).stem def single_result(self, cat, index): """get result_str, runtime of tool, after subtracting overhead""" row = self.category_to_list[cat][index] res = row[ToolResult.RESULT] t = float(row[ToolResult.RUN_TIME]) t -= self.cpu_overhead if cat in self.cpu_benchmarks else self.gpu_overhead # prevent 0 times as this messes up log plots t = max(Settings.PLOT_MIN_TIME, t) return res, t def load(self, scored, csv_path): """load data from file""" unexpected_results = set() with open(csv_path, newline='') as csvfile: for row in csv.reader(csvfile): # rename results #print(f"{csv_path}: {row}") row[ToolResult.RESULT] = row[ToolResult.RESULT].lower() substitutions = Settings.CSV_SUBSTITUTIONS for from_prefix, to_str in substitutions: if row[ToolResult.RESULT] == '': # don't use '' as prefix row[ToolResult.RESULT] = 'unknown' elif row[ToolResult.RESULT].startswith(from_prefix): row[ToolResult.RESULT] = to_str network = row[ToolResult.NETWORK] result = row[ToolResult.RESULT] cat = row[ToolResult.CATEGORY] prepare_time = float(row[ToolResult.PREPARE_TIME]) run_time = float(row[ToolResult.RUN_TIME]) # workaround to drop convBigRELU from cifar2020 if cat == 'cifar2020': if 'convBigRELU' in network: result = row[ToolResult.RESULT] = "unknown" if cat in self.skip_benchmarks or \ (scored and cat in Settings.UNSCORED_CATEGORIES) or \ (not scored and cat not in Settings.UNSCORED_CATEGORIES): result = row[ToolResult.RESULT] = "unknown" if result.startswith('timeout'): result = 'timeout' # fix for verapak "timeout(X_00 ..." if not ("test_nano" in network or "test_tiny" in network): self.category_to_list[cat].append(row) if result not in ["holds", "violated", "timeout", "error", "unknown"]: unexpected_results.add(result) print(f"Unexpected results: {unexpected_results}") exit(1) if result in ["holds", "violated"]: if cat in self.cpu_benchmarks: self.cpu_overhead = min(self.cpu_overhead, run_time) else: self.gpu_overhead = min(self.gpu_overhead, run_time) self.max_prepare = max(self.max_prepare, prepare_time) assert not unexpected_results, f"Unexpected results: {unexpected_results}" print(f"Loaded {self.tool_name}, default-overhead (gpu): {round(self.gpu_overhead, 1)}s," + \ f"cpu-overhead: {round(self.cpu_overhead, 1)}s, " + \ f"prepare time: {round(self.max_prepare, 1)}s") for skip_benchmark in self.skip_benchmarks: assert skip_benchmark in self.category_to_list, f"skip benchmark '{skip_benchmark}' not found in cat " + \ f"list: {list(self.category_to_list.keys())}" self.delete_empty_categories() def delete_empty_categories(self): """delete categories without successful measurements""" to_remove = [] #['acasxu', 'cifar2020'] # benchmarks to skip for key in self.category_to_list.keys(): rows = self.category_to_list[key] should_remove = True for row in rows: result = row[ToolResult.RESULT] if result in ('holds', 'violated'): should_remove = False break if should_remove: to_remove.append(key) elif key != "test": ToolResult.all_categories.add(key) for key in to_remove: if key in self.category_to_list: #print(f"empty category {key} in tool {self.tool_name}") del self.category_to_list[key] ToolResult.num_categories[self.tool_name] = len(self.category_to_list) class LongTableRow: """container object for longtable of results""" def __init__(self, cat: str, instance_id: int, result: str, tool_times_scores: Dict[str, Tuple[Union[str, float], int]]): self.cat = cat self.instance_id = instance_id assert result in ['sat', 'unsat', '-'], f"result was {result}" self.result = result self.tool_times_scores = tool_times_scores def compare_results(all_tool_names, gnuplot_tool_cat_times, result_list, single_overhead, scored): """compare results across tools""" min_percent = 0 # minimum percent for total score total_score = defaultdict(int) all_cats = {} tool_times = {} longtable_data: List[LongTableRow] = [] for tool in all_tool_names: tool_times[tool] = [] for cat in sorted(ToolResult.all_categories): print(f"\nCategory {cat}:") # maps tool_name -> [score, num_verified, num_falsified, num_fastest, num_errors] cat_score: Dict[str, List[int, int, int, int, int]] = {} all_cats[cat] = cat_score num_rows = 0 participating_tools = [] for tool_result in result_list: cat_dict = tool_result.category_to_list if not cat in cat_dict: continue rows = cat_dict[cat] assert num_rows == 0 or len(rows) == num_rows, f"tool {tool_result.tool_name}, cat {cat}, " + \ f"got {len(rows)} rows expected {num_rows}" if num_rows == 0: num_rows = len(rows) print(f"Category {cat} has {num_rows} (from {tool_result.tool_name})") participating_tools.append(tool_result) # work with participating tools only tool_names = [t.tool_name for t in participating_tools] print(f"{len(participating_tools)} participating tools: {tool_names}") table_rows = [] all_times = [] all_results = [] for index in range(num_rows): rand_gen_succeeded = False times_holds = [] tools_holds = [] times_violated = [] tools_violated = [] counterexamples_violated = [] correct_violations = {} table_row = [] table_rows.append(table_row) instance_str = participating_tools[0].result_instance_str(cat, index) table_row.append(instance_str) for t in participating_tools: res, secs = t.single_result(cat, index) if res == "unknown": table_row.append("-") continue if not res in ["holds", "violated"]: table_row.append(res) continue if res == "holds": times_holds.append(secs) tools_holds.append(t.tool_name) else: assert res == "violated" times_violated.append(secs) tools_violated.append(t.tool_name) # construct counterexample path row = t.category_to_list[cat][index] net = Path(row[ToolResult.NETWORK]).stem prop = Path(row[ToolResult.PROP]).stem ce_path = f"../{t.tool_name}/{cat}/{net}_{prop}.counterexample.gz" assert Path(ce_path).is_file(), f"CE path not found: {ce_path}" tup = ce_path, cat, net, prop counterexamples_violated.append(tup) table_row.append(f"{round(secs, 1)} ({res[0]})") if t.tool_name == "randgen": assert res == "violated" rand_gen_succeeded = True print() true_result = "-" if times_holds and not times_violated: true_result = 'unsat' elif times_violated and not times_holds: true_result = 'sat' elif times_holds and times_violated: print(f"WARNING: multiple results for index {index}. Violated: {len(times_violated)} " + f"({tools_violated}), Holds: {len(times_holds)} ({tools_holds})") table_row.append('*multiple results*') for tup, tool in zip(counterexamples_violated, tools_violated): print(f"\nchecking counterexample for {tool}") res = is_correct_counterexample(*tup) correct_violations[tool] = res print(f"were violated counterexamples valid?: {correct_violations}") if np.any([x == CounterexampleResult.CORRECT for x in correct_violations.values()]): ### HERE !! true_result = 'sat' else: true_result = 'unsat' print(f"Row: {table_row}") print(f"True Result: {true_result}") row_times = [] all_times.append(row_times) all_results.append(None) tool_times_scores: Dict[str, Tuple[Union[str, float], int]] = {} for t in participating_tools: res, secs = t.single_result(cat, index) score, is_verified, is_falsified, is_fastest, is_error = get_score(t.tool_name, res, secs, rand_gen_succeeded, times_holds, times_violated, correct_violations) print(f"{index}: {t.tool_name} score: {score}, is_ver: {is_verified}, is_fals: {is_falsified}, " + \ f"is_fastest: {is_fastest}") if is_verified or is_falsified: all_results[-1] = 'H' if is_verified else 'V' row_times.append(secs) tool_times_scores[t.tool_name] = (secs, score) else: row_times.append(None) if is_error: tool_times_scores[t.tool_name] = (secs, score) if t.tool_name in cat_score: tool_score_tup = cat_score[t.tool_name] else: tool_score_tup = [0, 0, 0, 0, 0] cat_score[t.tool_name] = tool_score_tup # [score, num_verified, num_falsified, num_fastest] tool_score_tup[0] += score tool_score_tup[1] += 1 if is_verified else 0 tool_score_tup[2] += 1 if is_falsified else 0 tool_score_tup[3] += 1 if is_fastest else 0 tool_score_tup[4] += 1 if is_error else 0 tool_score_tup = None # accumulate long table data longtable_data.append(LongTableRow(cat, index, true_result, tool_times_scores)) print("--------------------") num_holds = 0 num_violated = 0 num_unknown = 0 for i, (row_times, result) in enumerate(zip(all_times, all_results)): assert len(row_times) == len(tool_names) if result is None: num_unknown += 1 else: for t, tool in zip(row_times, tool_names): if t is not None: #assert t > 0, "time was zero?" tool_times[tool].append(t) gnuplot_tool_cat_times[tool][cat].append(t) gnuplot_tool_cat_times[tool]['all'].append(t) if result == 'V': num_violated += 1 elif result == 'H': num_holds += 1 print(f"Total Violated: {num_violated}") print(f"Total Holds: {num_holds}") print(f"Total Unknown: {num_unknown}") print("--------------------") print(", ".join(tool_names)) for table_row in table_rows: print(", ".join(table_row)) print(f"---------\nCategory {cat}:") if cat_score: max_score = max([t[0] for t in cat_score.values()]) for tool, score_tup in cat_score.items(): score = score_tup[0] percent = max(min_percent, 100 * score / max_score) print(f"{tool}: {score} ({round(percent, 2)}%)") total_score[tool] += percent print("\n###############") print("### Summary ###") print("###############") sorted_tools = [] with open(Settings.TOTAL_SCORE_LATEX, 'w', encoding='utf-8') as f: tee(f, "\n%Total Score:") res_list = [] print_table_header(f, "Overall Score", "tab:score", ["\\# ~", "Tool", "Score"]) for tool, score in total_score.items(): tool_latex = latex_tool_name(tool) desc = f"{tool_latex} & {round(score, 1)} \\\\" res_list.append((score, desc, tool)) for i, s in enumerate(reversed(sorted(res_list))): sorted_tools.append(s[2]) tee(f, f"{i+1} & {s[1]}") print_table_footer(f) add_image(f, f'all') ####### write_gnuplot_files(gnuplot_tool_cat_times, sorted_tools) ####### print("--------------------") for cat in sorted(all_cats.keys()): cat_score = all_cats[cat] if not cat_score: continue filename = Settings.UNSCORED_LATEX if cat in Settings.UNSCORED_CATEGORIES else Settings.SCORED_LATEX with open(filename, 'a', encoding='utf-8') as f: tee(f, f"\n% Category {cat} (single_overhead={single_overhead}):") res_list = [] max_score = max([t[0] for t in cat_score.values()]) cat_str = cat.replace('_', '-') print_table_header(f, f"Benchmark \\texttt{{{cat_str}}}", "tab:cat_{cat}", ("\\# ~", "Tool", "Verified", "Falsified", "Fastest", "Penalty", "Score", "Percent"), align='llllllrr') for tool, score_tup in cat_score.items(): score, num_verified, num_falsified, num_fastest, num_error = score_tup percent = max(min_percent, 100 * score / max_score) tool_latex = latex_tool_name(tool) #desc = f"{tool}: {score} ({round(percent, 2)}%)" desc = f"{tool_latex} & {num_verified} & {num_falsified} & {num_fastest} & {num_error} & {score} & {round(percent, 1)}\\% \\\\" res_list.append((percent, desc)) for i, s in enumerate(reversed(sorted(res_list))): tee(f, f"{i+1} & {s[1]}") print_table_footer(f) add_image(f, cat) ################ # print longtable_data with open(Settings.LONGTABLE_LATEX, 'w', encoding='utf-8') as f: tee(f, f"% Long table of all results\n\n") num_tools = len(sorted_tools) headers = ("Category", "Id", "Result") + tuple(f"{longtable_tool_name(t)}" for t in sorted_tools) caption = "Instance Runtimes. Fastest times are \\textcolor{blue}{blue}. " caption += "Second fastest are \\textcolor{second}{green}. Penalties are red crosses (" +\ f"\\textbf{{\\textcolor{{red}}{{\\ding{{55}}}}}}" + ")." print_longtable_header(f, caption, "tab:all_results", headers) last_cat = None for ltd in longtable_data: if ltd.cat != last_cat: if last_cat != None: tee(f, "\\midrule") last_cat = ltd.cat tool_results = "" for tool_index, tool in enumerate(sorted_tools): if tool_index > 0: tool_results += " & " if tool in ltd.tool_times_scores: t, score = ltd.tool_times_scores[tool] if isinstance(t, str): tool_results += t else: if score == 12: color = "blue" elif score == 11: # \definecolor{second}{HTML}{3C8031} color = "second" elif score == 10: color = "darkgray" elif score < 0: color = "red" if score < 0: # \ding{55} is from package pifont tool_results += f"~~\\textbf{{\\textcolor{{{color}}}{{\\ding{{55}}}}}}" else: tool_results += f"\\textcolor{{{color}}}{{{round_time(t)}}}" else: tool_results += "-" true_result = ltd.result # override true result manually for prefix, index, new_result in Settings.OVERRIDE_RESULTS: if ltd.cat.startswith(prefix) and ltd.instance_id == index: true_result = new_result pretty_res = f"~\\textsc{{{true_result}}}" if ltd.result != "-" else "~?" tee(f, f"{latex_cat_name(ltd.cat)} & {ltd.instance_id} & {pretty_res} & {tool_results} \\\\") print_longtable_footer(f) def round_time(t): """round time in table""" if t >= 99.9: rv = f"{t:.0f}" elif t < 0.01: rv = "$<$0.01" elif t >= 10: rv = f"{t:.1f}" else: rv = f"{t:.2f}" return rv def add_image(fout, prefix): """add latex code for an image with the given prefix.pdf""" title = "Unknown" for gps in Settings.gnuplot_data: if gps.prefix == prefix: title = gps.title tee(fout, """ \\begin{figure}[h] \\centerline{\\includegraphics[width=\\textwidth]{""" + f"{Settings.PLOT_FOLDER}/{prefix}" + """.pdf}} \\caption{Cactus Plot for """ + title + """.} \\label{fig:quantPic} \\end{figure} """) def tee(fout, line): """print to temrinal and a file""" print(line) fout.write(line + "\n") def print_table_header(f, title, label, columns, align=None): """print latex table header""" bold_columns = ["\\textbf{" + c + "}" for c in columns] if align is None: align = 'l' * len(columns) else: assert len(columns) == len(align) tee(f, '\n\\begin{table}[h]') tee(f, '\\begin{center}') tee(f, '\\caption{' + title + '} \\label{' + label + '}') tee(f, '{\\setlength{\\tabcolsep}{2pt}') tee(f, '\\begin{tabular}[h]{@{}' + align + '@{}}') tee(f, '\\toprule') tee(f, ' & '.join(bold_columns) + "\\\\") #\textbf{\# ~} & \textbf{Tool} & \textbf{Score} \\ tee(f, '\\midrule') def print_longtable_header(f, title, label, columns, align=None): """print latex table header""" bold_columns = ["\\textbf{" + c + "}" for c in columns] if align is None: align = 'l' * len(columns) else: assert len(columns) == len(align) tee(f, '''\\begin{center} {\\setlength{\\tabcolsep}{1pt} \\scriptsize \\begin{longtable}{@{}''' + align + '''@{}}''') tee(f, '\\caption{\\footnotesize ' + title + '} \\label{' + label + '} \\\\') #tee(f, '\\caption{\\footnotesize ' + title + '} \\\\') tee(f, '\\toprule') tee(f, ' & '.join(bold_columns) + " \\\\") #\textbf{\# ~} & \textbf{Tool} & \textbf{Score} \\ tee(f, '\\midrule') tee(f, '\\endhead') def print_table_footer(f): """print latex table footer""" tee(f, '''\\bottomrule \\end{tabular} } \\end{center} \\end{table}\n\n''') def print_longtable_footer(f): """print latex longtable footer""" tee(f, '''\\bottomrule \end{longtable} } \end{center}\n\n''') def get_score(tool_name, res, secs, rand_gen_succeded, times_holds, times_violated, ce_results): """Get the score for the given result Actually returns a 4-tuple: score, is_verified, is_falsified, is_fastest Correct hold: 10 points Correct violated (where random tests did not succeed): 10 points Correct violated (where random test succeeded): 1 point Incorrect result: -100 points Time bonus: The fastest tool for each solved instance will receive +2 points. The second fastest tool will receive +1 point. If two tools have runtimes within 0.2 seconds, we will consider them the same runtime. """ penalize_no_ce = False is_verified = False is_falsified = False is_fastest = False is_error = False num_holds = len(times_holds) num_violated = len(times_violated) #print(f"tool: {tool_name} {res}") valid_ce = False for ce_valid_res in ce_results.values(): if ce_valid_res == CounterexampleResult.CORRECT: valid_ce = True break assert not rand_gen_succeded, "VNNCOMP 2022 didn't use randgen" if res not in ["holds", "violated"]: score = 0 elif rand_gen_succeded: assert res == "violated" score = 1 ToolResult.num_verified[tool_name] += 1 ToolResult.num_violated[tool_name] += 1 is_falsified = True elif penalize_no_ce and num_holds > 0 and res == "violated" and not ce_results[tool_name]: # Rule: If a witness is not provided, for the purposes of scoring if there are # mismatches between tools we will count the tool without the witness as incorrect. score = -100 ToolResult.incorrect_results[tool_name] += 1 print(f"tool {tool_name} did not produce a valid counterexample and there are mismatching results") ToolResult.toolerror_counts[f'{tool_name}_no-ce-but-required'] += 1 is_error = True elif res == "violated" and num_holds > 0 and not valid_ce: score = -100 ToolResult.incorrect_results[tool_name] += 1 is_error = True ToolResult.toolerror_counts[f'{tool_name}_{ce_results[tool_name]}'] += 1 elif res == "holds" and valid_ce: score = -100 ToolResult.incorrect_results[tool_name] += 1 is_error = True ToolResult.toolerror_counts[f'{tool_name}_incorrect_unsat'] += 1 else: # correct result! ToolResult.num_verified[tool_name] += 1 if res == "holds": is_verified = True times = times_holds.copy() ToolResult.num_holds[tool_name] += 1 else: assert res == "violated" times = times_violated.copy() ToolResult.num_violated[tool_name] += 1 is_falsified = True score = 10 clamped_times = [max(t, Settings.SCORING_MIN_TIME) for t in times] secs = max(secs, Settings.SCORING_MIN_TIME) min_time = min(clamped_times) if secs < min_time + 0.2: score += 2 is_fastest = True else: clamped_times.remove(min_time) second_time = min(clamped_times) if secs < second_time + 0.2: score += 1 return score, is_verified, is_falsified, is_fastest, is_error def print_stats(result_list): """print stats about measurements""" with open(Settings.STATS_LATEX, 'w', encoding='utf-8') as f: tee(f, '\n%%%%%%%%%% Stats %%%%%%%%%%%') tee(f, "\n% Overhead:") olist = [] for r in result_list: olist.append((r.gpu_overhead, r.cpu_overhead, r.tool_name)) #print_table_header("Overhead", "tab:overhead", ["\\# ~", "Tool", "Seconds", "~~CPU Mode"], align='llrr') print_table_header(f, "Overhead", "tab:overhead", ["\\# ~", "Tool", "Seconds"], align='llr') for i, n in enumerate(sorted(olist)): #cpu_overhead = "-" if n[1] == np.inf else round(n[1], 1) #print(f"{i+1} & {n[2]} & {round(n[0], 1)} & {cpu_overhead} \\\\") tee(f, f"{i+1} & {latex_tool_name(n[2])} & {round(n[0], 1)} \\\\") print_table_footer(f) items = [("Num Benchmarks Participated", ToolResult.num_categories), ("Num Instances Verified", ToolResult.num_verified), ("Num SAT", ToolResult.num_violated), ("Num UNSAT", ToolResult.num_holds), ("Incorrect Results (or Missing CE)", ToolResult.incorrect_results), ] for index, (label, d) in enumerate(items): tee(f, f"\n% {label}:") tab_label = f"tab:stats{index}" print_table_header(f, label, tab_label, ["\\# ~", "Tool", "Count"], align='llr') l = [] for tool, count in d.items(): tool_latex = latex_tool_name(tool) l.append((count, tool_latex)) for i, s in enumerate(reversed(sorted(l))): tee(f, f"{i+1} & {s[1]} & {s[0]} \\\\") print_table_footer(f) print(ToolResult.toolerror_counts) def latex_cat_name(cat): """get latex version of category name""" subs = Settings.CAT_NAME_SUBS_LATEX found = False for old, new in subs: if cat == old: cat = new found = True break if not found: cat = cat.replace("_", " ") cat = ' '.join(e.capitalize() for e in cat.split()) return cat def longtable_tool_name(tool): """get latex version of tool name""" subs = Settings.TOOL_NAME_SUBS_LONGTABLE found = False for old, new in subs: if tool == old: tool = new found = True break #if not found: # tool = tool.capitalize() return tool def latex_tool_name(tool): """get latex version of tool name""" subs = Settings.TOOL_NAME_SUBS_LATEX found = False for old, new in subs: if tool == old: tool = new found = True break if not found: tool = tool.capitalize() return tool def gnuplot_tool_name(tool): """get fnuplot version of tool name""" subs = Settings.TOOL_NAME_SUBS_GNUPLOT found = False for old, new in subs: if tool == old: tool = new found = True break if not found: tool = tool.capitalize() return tool def write_gnuplot_files(gnuplot_tool_cat_times, sorted_tools): """write files with data for gnuplot cactus plots""" for gps in Settings.gnuplot_data: cat = gps.prefix for tool in gnuplot_tool_cat_times.keys(): times_list = gnuplot_tool_cat_times[tool][cat] times_list.sort() with open(Settings.PLOTS_DIR + f"/accumulated-{cat}-{tool}.txt", 'w', encoding='utf-8') as f: for i, t in enumerate(times_list): f.write(f"{t}\t{i+1}\n") with open(Settings.PLOTS_DIR + "/generated.gnuplot", 'w', encoding='utf-8') as f: ######################### # input_list f.write("input_list = \"") for gps in Settings.gnuplot_data: cat = gps.prefix f.write("'") for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if times_list: f.write(f"{cat}-{tool} ") f.write("' ") f.write("\"\n\n") ######################### # pretty_input_list f.write("pretty_input_list = \"") for gps in Settings.gnuplot_data: cat = gps.prefix f.write("\\\"") # sort tools by category for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if times_list: f.write(f"'{gnuplot_tool_name(tool)}' ") f.write("\\\" ") f.write("\"\n\n") ######################### # tool_index f.write("tool_index_list = \"") for gps in Settings.gnuplot_data: cat = gps.prefix f.write("'") # sort tools by category for i, tool in enumerate(sorted_tools): times_list = gnuplot_tool_cat_times[tool][cat] if times_list: f.write(f"{i} ") f.write("' ") f.write("\"\n\n") ########################## # title_list f.write("title_list = \"") for gps in Settings.gnuplot_data: f.write(f"'{gps.title}' ") f.write("\"\n\n") ########################## # outputs f.write("outputs = '") for i, gps in enumerate(Settings.gnuplot_data): f.write(f"{gps.prefix}.pdf ") f.write("'\n\n") ######################### # xmax_plot_list f.write("xmax_plot_list = '") for gps in Settings.gnuplot_data: cat = gps.prefix # sort tools by category max_times = 0 for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if len(times_list) > max_times: max_times = len(times_list) f.write(f"{1.05 * max_times} ") f.write("'\n\n") ######################### # ymin_list f.write(f"ymin_list = '") count = 10 for gps in Settings.gnuplot_data: cat = gps.prefix all_times = [] for tool in sorted_tools: all_times += gnuplot_tool_cat_times[tool][cat] all_times = np.array(all_times) if np.sum(all_times < 0.1) > count: min_time = 0.8 * 0.01 elif np.sum(all_times < 1.0) > count: min_time = 0.8 * 0.1 else: min_time = 0.8 * 1.0 f.write(f"{round(min_time, 4)} ") assert min_time > 0 f.write("'\n\n") ######################### # timeout_y_list f.write("timeout_y_list = '") for gps in Settings.gnuplot_data: cat = gps.prefix # sort tools by category max_time = 0 for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if times_list and times_list[-1] > max_time: max_time = times_list[-1] if max_time > 300: f.write("300 ") else: f.write("60 ") f.write("'\n\n") ######################### # timeout_str_list f.write("timeout_str_list = \"") for gps in Settings.gnuplot_data: cat = gps.prefix # sort tools by category max_time = 0 for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if times_list and times_list[-1] > max_time: max_time = times_list[-1] if max_time > 300: f.write("'Five Minutes' ") else: f.write("'One Minute' ") f.write("\"\n\n") ######################### # timeout_x_list f.write("timeout_x_list = '") for gps in Settings.gnuplot_data: cat = gps.prefix # sort tools by category max_times = 0 for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if len(times_list) > max_times: max_times = len(times_list) max_times = 1.05 * max_times f.write(f"{1 + 0.01 * max_times} ") f.write("'\n\n") ######################### # ymax_list f.write("ymax_list = '") for gps in Settings.gnuplot_data: cat = gps.prefix # sort tools by category max_time = 0 for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if times_list and times_list[-1] > max_time: max_time = times_list[-1] f.write(f"{1.5*max_time} ") f.write("'\n\n") ######################### # key_list f.write("key_list = \"") for gps in Settings.gnuplot_data: cat = gps.prefix # sort tools by category max_instances = 0 max_time = 0 for tool in sorted_tools: times_list = gnuplot_tool_cat_times[tool][cat] if len(times_list) > max_instances: max_instances = len(times_list) if times_list and times_list[-1] > max_time: max_time = times_list[-1] xplot_limit = 1.07 * max_instances yplot_limit = 1.5 * max_time f.write(f"'{1.05 * xplot_limit} {yplot_limit}' ") f.write("\"\n\n") def main(): """main entry point""" # use single overhead for all tools. False will have two different overheads for some tools depending # on if GPU needed to be initialized (manually entered) single_overhead = True print(f"using single_overhead={single_overhead}") #####################################3 #csv_list = glob.glob("results_csv/*.csv") csv_list = glob.glob(Settings.CSV_GLOB) csv_list.sort() # clear files so we can append to them with open(Settings.SCORED_LATEX, 'w', encoding='utf-8') as f: pass with open(Settings.UNSCORED_LATEX, 'w', encoding='utf-8') as f: pass if Settings.SKIP_TOOLS: new_csv_list = [] for csv_file in csv_list: skip_tool = False for skip in Settings.SKIP_TOOLS: if skip in csv_file: skip_tool = True break if not skip_tool: new_csv_list.append(csv_file) csv_list = new_csv_list tool_list = [c.split('/')[Settings.TOOL_LIST_GLOB_INDEX] for c in csv_list] cpu_benchmarks = {x: [] for x in tool_list} skip_benchmarks = {x: [] for x in tool_list} #skip_benchmarks['RPM'] = ['mnistfc'] for tool, benchmark in Settings.SKIP_BENCHMARK_TUPLES: assert tool in tool_list, f"{tool} not in tool list: {tool_list}" skip_benchmarks[tool].append(benchmark) if not single_overhead: # Define a dict with the cpu_only benchmarks for each tool #pass cpu_benchmarks["ERAN"] = ["acasxu", "eran"] gnuplot_tool_cat_times = {} # accumulate for both scored and unscored for tool in tool_list: gnuplot_tool_cat_times[tool] = defaultdict(list) for scored in [False, True]: result_list = [] ToolResult.reset() for csv_path, tool_name in zip(csv_list, tool_list): tr = ToolResult(scored, tool_name, csv_path, cpu_benchmarks[tool_name], skip_benchmarks[tool_name]) result_list.append(tr) # compare results across tools compare_results(tool_list, gnuplot_tool_cat_times, result_list, single_overhead, scored) if scored: print_stats(result_list) if Settings.SKIP_TOOLS: print(f"Note: tools were skipped: {Settings.SKIP_TOOLS}") if __name__ == "__main__": #from counterexamples import get_ce_diff #get_ce_diff.clear_cache() main()
38,077
29.957724
143
py
vnncomp2022_results
vnncomp2022_results-master/SCORING/run.sh
#!/bin/bash -e python3 process_results.py # run again, capturing output to file python3 process_results.py > results.txt && pushd plots && gnuplot make_plots.gnuplot && cp *.pdf ../latex/cactus && popd && pushd latex && make ; popd
236
25.333333
151
sh
vnncomp2022_results
vnncomp2022_results-master/SCORING/settings.py
''' vnn comp global settings ''' from pathlib import Path class GnuplotSettings: """settings for gnuplot""" def __init__(self, prefix, title): self.prefix = prefix self.title = title class Settings: '''static container for settings''' CSV_GLOB = "../*/results.csv" TOOL_LIST_GLOB_INDEX = 1 SCORING_MIN_TIME = 1.0 PLOT_MIN_TIME = 0 #0.01 UNSCORED_CATEGORIES = ['acasxu', 'cifar2020'] BENCHMARK_REPO = "/home/stan/repositories/vnncomp2022_benchmarks" COUNTEREXAMPLE_TOL = 1e-4 TOOL_NAME_SUBS_LATEX = [ ('alpha_beta_crown', '$\\alpha$,$\\beta$ Crown'), ('mn_bab', 'MN BaB') ] TOOL_NAME_SUBS_LONGTABLE = [ ('alpha_beta_crown', '$\\alpha$,$\\beta$-C'), ('mn_bab', 'MnB'), ('peregrinn', 'Pereg'), ('fastbatllnn', 'FastBaT'), ('verapak', 'Verap'), ('nnenum', 'nnen'), ('verinet', 'Verin'), ('averinn', 'Averi'), ('marabou', 'Marab'), ('debona', 'Debon'), ('cgdtest', 'CGD') ] TOOL_NAME_SUBS_GNUPLOT = [ ('alpha_beta_crown', 'AB-CROWN'), ('mn_bab', 'MN BaB') ] CAT_NAME_SUBS_LATEX = [ ('carvana_unet_2022', 'Carvana 2022'), ('cifar100_tinyimagenet_resnet', 'Cifar100 Tiny'), ('reach_prob_density', 'Reach Prob Den~') ] SKIP_TOOLS = [] #['marabou', 'verapak', 'cgdtest'] SKIP_BENCHMARK_TUPLES = [('marabou', 'sri_resnet_a'), ('marabou', 'sri_resnet_b')] PLOTS_DIR = "./plots" CSV_SUBSTITUTIONS = [('unsat', 'holds'), ('sat', 'violated'), ('no_result_in_file', 'unknown'), ('prepare_instance_error_', 'unknown'), ('run_instance_timeout', 'timeout'), ('prepare_instance_timeout', 'timeout'), ('error_exit_code_', 'error'), ('error_nonmaximal', 'unknown'), ] # list of triples to override result if manually determined incorrect: # (cat_prefix, index, desired_result) OVERRIDE_RESULTS = [('collins', 20, 'sat*')] # latex output files TOTAL_SCORE_LATEX = "latex/total.tex" SCORED_LATEX = "latex/scored.tex" UNSCORED_LATEX = "latex/unscored.tex" STATS_LATEX = "latex/stats.tex" LONGTABLE_LATEX = "latex/longtable.tex" # gnuplot information PLOT_FOLDER = "cactus" # folder containing the .pdfs gnuplot_data = ( GnuplotSettings('all', 'All Instances'), # GnuplotSettings('acasxu', 'ACAS Xu (Unscored)'), GnuplotSettings('cifar2020', 'CIFAR 2020 (Unscored)'), # GnuplotSettings('carvana_unet_2022', 'Carvana Unet 2022'), GnuplotSettings('cifar100_tinyimagenet_resnet', 'CIFAR100 Tiny ImageNet ResNet'), GnuplotSettings('cifar_biasfield', 'CIFAR Biasfield'), GnuplotSettings('collins_rul_cnn', 'Collins Rul CNN'), GnuplotSettings('mnist_fc', 'MNIST FC'), GnuplotSettings('nn4sys', 'NN4SYS'), GnuplotSettings('oval21', 'OVAL 21'), GnuplotSettings('reach_prob_density', 'Reachability Probability Density'), GnuplotSettings('rl_benchmarks', 'Reinforcement Learning Benchmarks'), GnuplotSettings('sri_resnet_a', 'SRI Resnet A'), GnuplotSettings('sri_resnet_b', 'SRI Resnet B'), GnuplotSettings('tllverifybench', 'Two-Level Lattice Verify Benchmark'), GnuplotSettings('vggnet16_2022', 'VGGNet16 2022'), ) assert Path(Settings.BENCHMARK_REPO).is_dir(), f"directory in Settings.BENCHMARK_REPO ('{Settings.BENCHMARK_REPO}') " + \ "doesn't exist. Please clone https://github.com/ChristopherBrix/vnncomp2022_benchmarks and edit " + \ "path in Settings.BENCHMARK_REPO in settings.py"
3,916
33.973214
121
py
vnncomp2022_results
vnncomp2022_results-master/SCORING/vnnlib.py
''' vnnlib simple utilities Stanley Bak June 2021 ''' from copy import deepcopy import re import numpy as np import onnxruntime as ort import onnx from cachier import cachier import datetime def read_statements(vnnlib_filename): '''process vnnlib and return a list of strings (statements) useful to get rid of comments and blank lines and combine multi-line statements ''' with open(vnnlib_filename, 'r') as f: lines = f.readlines() lines = [line.strip() for line in lines] assert len(lines) > 0 # combine lines if case a single command spans multiple lines open_parentheses = 0 statements = [] current_statement = '' for line in lines: comment_index = line.find(';') if comment_index != -1: line = line[:comment_index].rstrip() if not line: continue new_open = line.count('(') new_close = line.count(')') open_parentheses += new_open - new_close assert open_parentheses >= 0, "mismatched parenthesis in vnnlib file" # add space current_statement += ' ' if current_statement else '' current_statement += line if open_parentheses == 0: statements.append(current_statement) current_statement = '' if current_statement: statements.append(current_statement) # remove repeated whitespace characters statements = [" ".join(s.split()) for s in statements] # remove space after '(' statements = [s.replace('( ', '(') for s in statements] # remove space after ')' statements = [s.replace(') ', ')') for s in statements] return statements def update_rv_tuple(rv_tuple, op, first, second, num_inputs, num_outputs): 'update tuple from rv in read_vnnlib_simple, with the passed in constraint "(op first second)"' if first.startswith("X_"): # Input constraints index = int(first[2:]) assert not second.startswith("X") and not second.startswith("Y"), \ f"input constraints must be box ({op} {first} {second})" assert 0 <= index < num_inputs limits = rv_tuple[0][index] if op == "<=": limits[1] = min(float(second), limits[1]) else: limits[0] = max(float(second), limits[0]) assert limits[0] <= limits[1], f"{first} range is empty: {limits}" else: # output constraint if op == ">=": # swap order if op is >= first, second = second, first row = [0.0] * num_outputs rhs = 0.0 # assume op is <= if first.startswith("Y_") and second.startswith("Y_"): index1 = int(first[2:]) index2 = int(second[2:]) row[index1] = 1 row[index2] = -1 elif first.startswith("Y_"): index1 = int(first[2:]) row[index1] = 1 rhs = float(second) else: assert second.startswith("Y_") index2 = int(second[2:]) row[index2] = -1 rhs = -1 * float(first) mat, rhs_list = rv_tuple[1], rv_tuple[2] mat.append(row) rhs_list.append(rhs) def make_input_box_dict(num_inputs): 'make a dict for the input box' rv = {i: [-np.inf, np.inf] for i in range(num_inputs)} return rv def get_io_nodes(onnx_model): 'returns 3 -tuple: input node, output nodes, input dtype' sess = ort.InferenceSession(onnx_model.SerializeToString()) inputs = [i.name for i in sess.get_inputs()] assert len(inputs) == 1, f"expected single onnx network input, got: {inputs}" input_name = inputs[0] outputs = [o.name for o in sess.get_outputs()] assert len(outputs) == 1, f"expected single onnx network output, got: {outputs}" output_name = outputs[0] g = onnx_model.graph inp = [n for n in g.input if n.name == input_name][0] out = [n for n in g.output if n.name == output_name][0] input_type = g.input[0].type.tensor_type.elem_type assert input_type in [onnx.TensorProto.FLOAT, onnx.TensorProto.DOUBLE] dtype = np.float32 if input_type == onnx.TensorProto.FLOAT else np.float64 return inp, out, dtype def get_num_inputs_outputs(onnx_filename): 'get num inputs and outputs of an onnx file' onnx_model = onnx.load(onnx_filename) inp, out, _ = get_io_nodes(onnx_model) inp_shape = tuple(d.dim_value if d.dim_value != 0 else 1 for d in inp.type.tensor_type.shape.dim) out_shape = tuple(d.dim_value if d.dim_value != 0 else 1 for d in out.type.tensor_type.shape.dim) num_inputs = 1 num_outputs = 1 for n in inp_shape: num_inputs *= n for n in out_shape: num_outputs *= n @cachier(stale_after=datetime.timedelta(days=1)) def read_vnnlib_simple(vnnlib_filename, num_inputs, num_outputs): '''process in a vnnlib file. You can get num_inputs and num_outputs using get_num_inputs_outputs(). this is not a general parser, and assumes files are provided in a 'nice' format. Only a single disjunction is allowed output a list containing 2-tuples: 1. input ranges (box), list of pairs for each input variable 2. specification, provided as a list of pairs (mat, rhs), as in: mat * y <= rhs, where y is the output. Each element in the list is a term in a disjunction for the specification. ''' # example: "(declare-const X_0 Real)" regex_declare = re.compile(r"^\(declare-const (X|Y)_(\S+) Real\)$") # comparison sub-expression # example: "(<= Y_0 Y_1)" or "(<= Y_0 10.5)" comparison_str = r"\((<=|>=) (\S+) (\S+)\)" # example: "(and (<= Y_0 Y_2)(<= Y_1 Y_2))" dnf_clause_str = r"\(and (" + comparison_str + r")+\)" # example: "(assert (<= Y_0 Y_1))" regex_simple_assert = re.compile(r"^\(assert " + comparison_str + r"\)$") # disjunctive-normal-form # (assert (or (and (<= Y_3 Y_0)(<= Y_3 Y_1)(<= Y_3 Y_2))(and (<= Y_4 Y_0)(<= Y_4 Y_1)(<= Y_4 Y_2)))) regex_dnf = re.compile(r"^\(assert \(or (" + dnf_clause_str + r")+\)\)$") rv = [] # list of 3-tuples, (box-dict, mat, rhs) rv.append((make_input_box_dict(num_inputs), [], [])) lines = read_statements(vnnlib_filename) for line in lines: #print(f"Line: {line}") if len(regex_declare.findall(line)) > 0: continue groups = regex_simple_assert.findall(line) if groups: assert len(groups[0]) == 3, f"groups was {groups}: {line}" op, first, second = groups[0] for rv_tuple in rv: update_rv_tuple(rv_tuple, op, first, second, num_inputs, num_outputs) continue ################ groups = regex_dnf.findall(line) assert groups, f"failed parsing line: {line}" tokens = line.replace("(", " ").replace(")", " ").split() tokens = tokens[2:] # skip 'assert' and 'or' conjuncts = " ".join(tokens).split("and")[1:] old_rv = rv rv = [] for rv_tuple in old_rv: for c in conjuncts: rv_tuple_copy = deepcopy(rv_tuple) rv.append(rv_tuple_copy) c_tokens = [s for s in c.split(" ") if len(s) > 0] count = len(c_tokens) // 3 for i in range(count): op, first, second = c_tokens[3*i:3*(i+1)] update_rv_tuple(rv_tuple_copy, op, first, second, num_inputs, num_outputs) # merge elements of rv with the same input spec merged_rv = {} for rv_tuple in rv: boxdict = rv_tuple[0] matrhs = (rv_tuple[1], rv_tuple[2]) key = str(boxdict) # merge based on string representation of input box... accurate enough for now if key in merged_rv: merged_rv[key][1].append(matrhs) else: merged_rv[key] = (boxdict, [matrhs]) # finalize objects (convert dicts to lists and lists to np.array) final_rv = [] for rv_tuple in merged_rv.values(): box_dict = rv_tuple[0] box = [] for d in range(num_inputs): r = box_dict[d] assert r[0] != -np.inf and r[1] != np.inf, f"input X_{d} was unbounded: {r}" box.append(r) spec_list = [] for matrhs in rv_tuple[1]: mat = np.array(matrhs[0], dtype=float) rhs = np.array(matrhs[1], dtype=float) spec_list.append((mat, rhs)) final_rv.append((box, spec_list)) #for i, (box, spec_list) in enumerate(final_rv): # print(f"-----\n{i+1}. {box}\nspec:{spec_list}") return final_rv
8,796
29.023891
112
py
null
RotationCorrection-main/README.md
# Deep Rotation Correction without Angle Prior ([paper](https://arxiv.org/abs/2207.03054)) <p align="center">Lang Nie<sup>1</sup>, Chunyu Lin<sup>1 *</sup>, Kang Liao<sup>1</sup>, Shuaicheng Liu<sup>2</sup>, Yao Zhao<sup>1</sup></p> <p align="center"><sup>1</sup>Beijing Jiaotong University</p> <p align="center"><sup>2</sup>University of Electronic Science and Technology of China</p> <p align="center"><sup>{nielang, cylin, kang_liao, yzhao}@bjtu.edu.cn, liushuaicheng@uestc.edu.cn</sup></p> <div align=center> <img src="https://github.com/nie-lang/RotationCorrection/blob/main/fig1.jpg"/> </div> <p align="center"><sup>Fig.1. Different solutions to correct the tilted image. Our solution (e) can eliminate the tilt without angle prior, while the others (b)(c)(d)(f)(g)(h) require an accurate rotated angle. The red square denotes the cropping region, and the arrow highlights the distorted area. The horizontal and vertical dotted lines are drawn to help observe the slight tilt.</sup></p> ## Dataset (DRC-D) We build this dataset by He et al.'s content-aware rotation and further manual correction as follows: <div align=center> <img src="https://github.com/nie-lang/RotationCorrection/blob/main/dataset.jpg"/> </div> <p align="center"><sup>Fig.2. The process of dataset generation. We further correct the randomly rotated result generated from He et al.’ rotation. The red arrows in (c) indicate the manual adjustment of moving the mesh vertices. He et al.’s rotation neglects the rotation of the cross ((b) right), while our manual correction slightly rotates it to produce a more natural appearance ((c) right).</sup></p> Every example includes three items: a input image (a tilted image), a tilted angle and a label (a corrected image). For simplicity, we leverage the name of the input image to record the tilted angle, e.g., "00014_-7.1.jpg" indicates the input image has a tilt of -7.1°. Now, the dataset can be downloaded in in [Google Drive](https://drive.google.com/drive/folders/1y8964QKakL1zJsuzuivCx41_YkrsOKv_?usp=share_link) or [Baidu Cloud](https://pan.baidu.com/s/1WByNz64oNoSRbuzCgcnXGQ)(Extraction code: 1234). ## Requirement * python 3.6 * numpy 1.18.1 * tensorflow 1.13.1 More details about the environment can be found [here](https://github.com/nie-lang/DeepRectangling/issues/4). ## Training #### Step 1: Download the pretrained vgg19 model Download [VGG-19](https://www.vlfeat.org/matconvnet/pretrained/#downloading-the-pre-trained-models). Search imagenet-vgg-verydeep-19 in this page and download imagenet-vgg-verydeep-19.mat. Then please place it to 'Codes/vgg19/' folder. #### Step 2: Train the network Modify the 'Codes/constant.py' to set the 'TRAIN_FOLDER'/'ITERATIONS'/'GPU'. In our experiment, we set 'ITERATIONS' to 150,000. ``` python train.py ``` ## Testing #### Pretrained model for deep rotation correction Our pretrained rectangling model can be available at [Google Drive](https://drive.google.com/drive/folders/1CQ2usWn4qknAReSWrKeei_I86yMiq4tR?usp=sharing) or [Baidu Cloud](https://pan.baidu.com/s/1z66hGsCBmcI99ZP_p7blpw)(Extraction code: 1234). And place the four files to 'Codes/checkpoints/pretrained_model/' folder. #### Testing Modidy the 'Codes/constant.py'to set the 'TEST_FOLDER'/'GPU'. The path for the checkpoint file can be modified in 'Codes/inference.py'. ``` python inference.py ``` #### Testing with your own data We have specified the path for other datasets in 'Codes/constant.py'. You can collect your own tilted images and place it to 'Other_dataset/input/'. ``` python inference2.py ``` The corrected results can be found in 'Other_dataset/correction/'. ## Citation ``` @ARTICLE{10128955, author={Nie, Lang and Lin, Chunyu and Liao, Kang and Liu, Shuaicheng and Zhao, Yao}, journal={IEEE Transactions on Image Processing}, title={Deep Rotation Correction Without Angle Prior}, year={2023}, volume={32}, number={}, pages={2879-2888}, doi={10.1109/TIP.2023.3275869}} ``` ## References [1] Nie et al., “Depth-Aware Multi-Gird Deep Homogrpahy Estimation with Contextual Correlation,” TCSVT, 2021. [2] Nie et al., “Deep Rectangling for Image Stitching: A Learning Baseline,” CVPR, 2022.
4,187
55.594595
406
md
null
RotationCorrection-main/Codes/constant.py
#training dataset path TRAIN_FOLDER = '/data/cylin/nl/Data/DRC-D/training' #testing dataset path TEST_FOLDER = '/data/cylin/nl/Data/DRC-D/testing' #testing dataset path for other datasets TEST_OTHER_FOLDER = '../Other_dataset/' #GPU index GPU = '4' #batch size for training TRAIN_BATCH_SIZE = 4 #batch size for testing TEST_BATCH_SIZE = 1 #num of iters ITERATIONS = 150000 # checkpoints path SNAPSHOT_DIR = "./checkpoints" #sumary path SUMMARY_DIR = "./summary" # define the mesh resolution GRID_W = 8 GRID_H = 6
525
16.533333
51
py
null
RotationCorrection-main/Codes/inference.py
import tensorflow as tf import os import time import numpy as np import pickle import cv2 as cv from model import RotationCorrection from utils import load, save, DataLoader import skimage import imageio import constant os.environ['CUDA_DEVICES_ORDER'] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES'] = constant.GPU test_folder = constant.TEST_FOLDER batch_size = constant.TEST_BATCH_SIZE snapshot_dir = constant.SNAPSHOT_DIR + '/pretrained_model/model.ckpt-150000' #snapshot_dir = constant.SNAPSHOT_DIR + '/model.ckpt-150000' # define dataset with tf.name_scope('dataset'): test_inputs_clips_tensor = tf.placeholder(shape=[batch_size, None, None, 3 * 2], dtype=tf.float32) test_input = test_inputs_clips_tensor[...,0:3] test_gt = test_inputs_clips_tensor[...,3:6] print('test input = {}'.format(test_input)) print('test gt = {}'.format(test_gt)) # define testing RotationCorrection function with tf.variable_scope('generator', reuse=None): test_mesh, test_horizon, test_flow, test_horizon2 = RotationCorrection(test_input) print('testing = {}'.format(tf.get_variable_scope().name)) config = tf.ConfigProto() config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: # dataset input_loader = DataLoader(test_folder) # initialize weights sess.run(tf.global_variables_initializer()) print('Init global successfully!') # tf saver saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=None) restore_var = [v for v in tf.global_variables()] loader = tf.train.Saver(var_list=restore_var) def inference_func(ckpt): print("============") print(ckpt) load(loader, sess, ckpt) print("============") length = len(os.listdir(test_folder+"/input")) psnr_list = [] ssim_list = [] psnr_list2 = [] ssim_list2 = [] for i in range(0, length): input_clip = np.expand_dims(input_loader.get_data_clips(i), axis=0) #Attention: both inputs and outpus are the types of numpy mesh, rotation, flow, rotation2 = sess.run([test_mesh, test_horizon, test_flow, test_horizon2], feed_dict={test_inputs_clips_tensor: input_clip}) input_image = (input_clip[0,:,:,0:3]+1)/2*255 rotation_gt = (input_clip[0,:,:,3:6]+1)/2*255 rotation = (rotation[0]+1)*127.5 rotation2 = (rotation2[0]+1)*127.5 if not os.path.exists("../result_mesh/"): os.makedirs("../result_mesh/") path = "../result_mesh/" + str(i+1).zfill(5) + ".jpg" cv.imwrite(path, rotation) if not os.path.exists("../result_meshflow/"): os.makedirs("../result_meshflow/") path = "../result_meshflow/" + str(i+1).zfill(5) + ".jpg" cv.imwrite(path, rotation2) psnr = skimage.measure.compare_psnr(rotation, rotation_gt, 255) ssim = skimage.measure.compare_ssim(rotation, rotation_gt, data_range=255, multichannel=True) psnr_list.append(psnr) ssim_list.append(ssim) psnr2 = skimage.measure.compare_psnr(rotation2, rotation_gt, 255) ssim2 = skimage.measure.compare_ssim(rotation2, rotation_gt, data_range=255, multichannel=True) psnr_list2.append(psnr2) ssim_list2.append(ssim2) print('i = {} / {} psnr2 = {}'.format( i+1, length, psnr2)) print("===================Results Analysis==================") print("mesh:") print('average psnr:', np.mean(psnr_list)) print('average ssim:', np.mean(ssim_list)) print("--------------") print("mesh+flow:") print('average psnr2:', np.mean(psnr_list2)) print('average ssim2:', np.mean(ssim_list2)) inference_func(snapshot_dir)
3,998
32.605042
157
py
null
RotationCorrection-main/Codes/inference2.py
import tensorflow as tf import os import time import numpy as np import pickle import cv2 as cv from model import RotationCorrection2 from utils import load, save, DataLoader import skimage import imageio import glob import constant os.environ['CUDA_DEVICES_ORDER'] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES'] = constant.GPU test_other_folder = constant.TEST_OTHER_FOLDER batch_size = constant.TEST_BATCH_SIZE snapshot_dir = constant.SNAPSHOT_DIR + '/pretrained_model/model.ckpt-150000' #snapshot_dir = constant.SNAPSHOT_DIR + '/model.ckpt-150000' def create_gif(image_list, gif_name, duration=0.35): frames = [] for image_name in image_list: frames.append(image_name) imageio.mimsave(gif_name, frames, 'GIF', duration=0.5) return # define dataset with tf.name_scope('dataset'): test_inputs_clips_tensor = tf.placeholder(shape=[batch_size, None, None, 3], dtype=tf.float32) test_input = test_inputs_clips_tensor print('test input = {}'.format(test_input)) # define testing RotationCorrection function with tf.variable_scope('generator', reuse=None): test_final_result = RotationCorrection2(test_input) print('testing = {}'.format(tf.get_variable_scope().name)) config = tf.ConfigProto() config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: # initialize weights sess.run(tf.global_variables_initializer()) print('Init global successfully!') # tf saver saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=None) restore_var = [v for v in tf.global_variables()] loader = tf.train.Saver(var_list=restore_var) def inference_func(ckpt): print("============") print(ckpt) load(loader, sess, ckpt) print("============") # prepare data test_list = glob.glob(os.path.join(test_other_folder+"/input/", '*.jpg')) length = len(test_list) for i in range(0, length): # load image ori_img = cv.imread(test_list[i]) input_clip = ori_img.astype(dtype=np.float32) input_clip = (input_clip / 127.5) - 1.0 input_clip = np.expand_dims(input_clip, axis=0) #Attention: both inputs and outpus are the types of numpy final_result = sess.run(test_final_result, feed_dict={test_inputs_clips_tensor: input_clip}) final_result = (final_result[0]+1)*127.5 if not os.path.exists(test_other_folder+"/correction/"): os.makedirs(test_other_folder+"/correction/") path = test_other_folder+"/correction/" + str(i+1).zfill(5) + ".jpg" cv.imwrite(path, final_result) print('i = {} / {}'.format( i+1, length)) print("===================End==================") inference_func(snapshot_dir)
2,955
28.56
104
py
null
RotationCorrection-main/Codes/loss_functions.py
import tensorflow as tf import numpy as np def intensity_loss(gen_frames, gt_frames, l_num): """ Calculates the sum of lp losses between the predicted and ground truth frames. @param gen_frames: The predicted frames at each scale. @param gt_frames: The ground truth frames at each scale @param l_num: 1 or 2 for l1 and l2 loss, respectively). @return: The lp loss. """ return tf.reduce_mean(tf.abs((gen_frames - gt_frames) ** l_num))
476
20.681818
82
py
null
RotationCorrection-main/Codes/model.py
import tensorflow as tf import numpy as np import tensorflow.contrib.slim as slim from tensorflow.contrib.layers import conv2d, conv2d_transpose import tf_spatial_transform_local import math import tf_mesh2flow grid_w = 8 grid_h = 6 #------------- Warping layer for optical flow ------------------- def get_grid(x): batch_size, height, width, filters = tf.unstack(tf.shape(x)) Bg, Yg, Xg = tf.meshgrid(tf.range(batch_size), tf.range(height), tf.range(width), indexing = 'ij') # return indices volume indicate (batch, y, x) # return tf.stack([Bg, Yg, Xg], axis = 3) return Bg, Yg, Xg # return collectively for elementwise processing def nearest_warp(x, flow): grid_b, grid_y, grid_x = get_grid(x) flow = tf.cast(flow, tf.int32) warped_gy = tf.add(grid_y, flow[:,:,:,1]) # flow_y warped_gx = tf.add(grid_x, flow[:,:,:,0]) # flow_x # clip value by height/width limitation _, h, w, _ = tf.unstack(tf.shape(x)) warped_gy = tf.clip_by_value(warped_gy, 0, h-1) warped_gx = tf.clip_by_value(warped_gx, 0, w-1) warped_indices = tf.stack([grid_b, warped_gy, warped_gx], axis = 3) warped_x = tf.gather_nd(x, warped_indices) return warped_x def bilinear_warp(x, flow): _, h, w, _ = tf.unstack(tf.shape(x)) grid_b, grid_y, grid_x = get_grid(x) grid_b = tf.cast(grid_b, tf.float32) grid_y = tf.cast(grid_y, tf.float32) grid_x = tf.cast(grid_x, tf.float32) fx, fy = tf.unstack(flow, axis = -1) fx_0 = tf.floor(fx) fx_1 = fx_0+1 fy_0 = tf.floor(fy) fy_1 = fy_0+1 # warping indices h_lim = tf.cast(h-1, tf.float32) w_lim = tf.cast(w-1, tf.float32) gy_0 = tf.clip_by_value(grid_y + fy_0, 0., h_lim) gy_1 = tf.clip_by_value(grid_y + fy_1, 0., h_lim) gx_0 = tf.clip_by_value(grid_x + fx_0, 0., w_lim) gx_1 = tf.clip_by_value(grid_x + fx_1, 0., w_lim) g_00 = tf.cast(tf.stack([grid_b, gy_0, gx_0], axis = 3), tf.int32) g_01 = tf.cast(tf.stack([grid_b, gy_0, gx_1], axis = 3), tf.int32) g_10 = tf.cast(tf.stack([grid_b, gy_1, gx_0], axis = 3), tf.int32) g_11 = tf.cast(tf.stack([grid_b, gy_1, gx_1], axis = 3), tf.int32) # gather contents x_00 = tf.gather_nd(x, g_00) x_01 = tf.gather_nd(x, g_01) x_10 = tf.gather_nd(x, g_10) x_11 = tf.gather_nd(x, g_11) # coefficients c_00 = tf.expand_dims((fy_1 - fy)*(fx_1 - fx), axis = 3) c_01 = tf.expand_dims((fy_1 - fy)*(fx - fx_0), axis = 3) c_10 = tf.expand_dims((fy - fy_0)*(fx_1 - fx), axis = 3) c_11 = tf.expand_dims((fy - fy_0)*(fx - fx_0), axis = 3) return c_00*x_00 + c_01*x_01 + c_10*x_10 + c_11*x_11 #--------------------------------------------------------------------------------- def shift2mesh(mesh_shift, width, height): batch_size = tf.shape(mesh_shift)[0] h = height/grid_h w = width/grid_w ori_pt = [] for i in range(grid_h + 1): for j in range(grid_w + 1): ww = j * w hh = i * h p = tf.constant([ww, hh], shape=[2], dtype=tf.float32) ori_pt.append(tf.expand_dims(p, 0)) ori_pt = tf.concat(ori_pt, axis=0) ori_pt = tf.reshape(ori_pt, [grid_h+1, grid_w+1, 2]) ori_pt = tf.tile(tf.expand_dims(ori_pt, 0),[batch_size, 1, 1, 1]) tar_pt = ori_pt + mesh_shift return tar_pt def flow_resize_operation(flow_input, height, width): flow_tmp = tf.image.resize_images(flow_input, [height,width],method=1) flow_x = flow_tmp[:, :, :, 0] * tf.cast(width, tf.float32) /512. flow_y = flow_tmp[:, :, :, 1] * tf.cast(height, tf.float32) /384. flow_output = tf.stack([flow_x, flow_y], 3) return flow_output # rotation correction pipeline for DRC-D dataset def RotationCorrection(train_input, width=512., height=384.): batch_size = tf.shape(train_input)[0] mesh, rotation_mesh, residual_flow = build_model(train_input, is_reuse = None) flow = tf_mesh2flow.mesh2flow(mesh) + residual_flow rotation_flow = bilinear_warp(train_input, flow) return mesh, rotation_mesh, flow, rotation_flow # rotation correction pipeline for other datasets with arbitrary resolutions def RotationCorrection2(train_input): train_input_ori = train_input batch_size = tf.shape(train_input_ori)[0] height = tf.shape(train_input_ori)[1] width = tf.shape(train_input_ori)[2] train_input = tf.image.resize_images(train_input, [384,512],method=0) mesh, rotation_mesh, residual_flow = build_model(train_input, is_reuse = None) # final flow flow = tf_mesh2flow.mesh2flow(mesh) + residual_flow # scale the flows to original resolutions flow_ori = flow_resize_operation(flow, height, width) # warp final_result = bilinear_warp(train_input_ori, flow_ori) return final_result def _maxpool2d(x, kernel_size, stride): p = np.floor((kernel_size -1)/2).astype(np.int32) p_x = tf.pad(x, [[0, 0], [p, p], [p, p], [0, 0]]) return slim.max_pool2d(p_x, kernel_size, stride=stride) def feature_extractor(image_tf): feature = [] with tf.variable_scope('conv_block1'): # H conv1 = conv2d(inputs=image_tf, num_outputs=64, kernel_size=3, rate=1, activation_fn=tf.nn.relu) conv1 = conv2d(inputs=conv1, num_outputs=64, kernel_size=3, rate=1, activation_fn=tf.nn.relu) feature.append(conv1) maxpool1 = _maxpool2d(conv1, 2, 2) # H/2 with tf.variable_scope('conv_block2'): conv2 = conv2d(inputs=maxpool1, num_outputs=64, kernel_size=3, activation_fn=tf.nn.relu) conv2 = conv2d(inputs=conv2, num_outputs=64, kernel_size=3, activation_fn=tf.nn.relu) feature.append(conv2) maxpool2 = _maxpool2d(conv2, 2, 2) # H/4 with tf.variable_scope('conv_block3'): conv3 = conv2d(inputs=maxpool2, num_outputs=128, kernel_size=3, activation_fn=tf.nn.relu) conv3 = conv2d(inputs=conv3, num_outputs=128, kernel_size=3, activation_fn=tf.nn.relu) feature.append(conv3) maxpool3 = _maxpool2d(conv3, 2, 2) # H/8 with tf.variable_scope('conv_block4'): conv4 = conv2d(inputs=maxpool3, num_outputs=128, kernel_size=3, activation_fn=tf.nn.relu) conv4 = conv2d(inputs=conv4, num_outputs=128, kernel_size=3, activation_fn=tf.nn.relu) feature.append(conv4) maxpool4 = _maxpool2d(conv4, 2, 2) #32*24 with tf.variable_scope('conv_block5'): conv5 = conv2d(inputs=maxpool4, num_outputs=256, kernel_size=3, activation_fn=tf.nn.relu) conv5 = conv2d(inputs=conv5, num_outputs=256, kernel_size=3, activation_fn=tf.nn.relu) feature.append(conv5) return feature def regression_Net(feature): maxpool1 = _maxpool2d(feature, 2, 2) #16*12 conv2 = conv2d(inputs=maxpool1, num_outputs=256, kernel_size=3, activation_fn=tf.nn.relu) conv2 = conv2d(inputs=conv2, num_outputs=256, kernel_size=3, activation_fn=tf.nn.relu) maxpool2 = _maxpool2d(conv2, 2, 2) #8 conv3 = conv2d(inputs=maxpool2, num_outputs=512, kernel_size=3, activation_fn=tf.nn.relu) conv3 = conv2d(inputs=conv3, num_outputs=512, kernel_size=3, activation_fn=tf.nn.relu) maxpool3 = _maxpool2d(conv3, 2, 2) #4 fc1 = conv2d(inputs=maxpool3, num_outputs=2048, kernel_size=[3,4], activation_fn=tf.nn.relu, padding="VALID") fc2 = conv2d(inputs=fc1, num_outputs=1024, kernel_size=1, activation_fn=tf.nn.relu) fc3 = conv2d(inputs=fc2, num_outputs=(grid_w+1)*(grid_h+1)*2, kernel_size=1, activation_fn=None) mesh_motion = tf.reshape(fc3, (-1, grid_h+1, grid_w+1, 2)) return mesh_motion def decoder2(feature): h_deconv1 = conv2d_transpose(inputs=feature[-1], num_outputs=128, kernel_size=2, stride=2) h_deconv_concat1 = tf.concat([feature[-2], h_deconv1], axis=3) conv1 = conv2d(inputs=h_deconv_concat1, num_outputs=128, kernel_size=3) conv1 = conv2d(inputs=conv1, num_outputs=128, kernel_size=3) h_deconv2 = conv2d_transpose(inputs=conv1, num_outputs=128, kernel_size=2, stride=2) h_deconv_concat2 = tf.concat([feature[-3], h_deconv2], axis=3) conv2 = conv2d(inputs=h_deconv_concat2, num_outputs=128, kernel_size=3) conv2 = conv2d(inputs=conv2, num_outputs=128, kernel_size=3) h_deconv3 = conv2d_transpose(inputs=conv2, num_outputs=64, kernel_size=2, stride=2) h_deconv_concat3 = tf.concat([feature[-4], h_deconv3], axis=3) conv3 = conv2d(inputs=h_deconv_concat3, num_outputs=64, kernel_size=3) conv3 = conv2d(inputs=conv3, num_outputs=64, kernel_size=3) h_deconv4 = conv2d_transpose(inputs=conv3, num_outputs=64, kernel_size=2, stride=2) h_deconv_concat4 = tf.concat([feature[-5], h_deconv4], axis=3) conv4 = conv2d(inputs=h_deconv_concat4, num_outputs=64, kernel_size=3) conv4 = conv2d(inputs=conv4, num_outputs=64, kernel_size=3) flow = conv2d(inputs=conv4, num_outputs=2, kernel_size=1, activation_fn=None) return flow def build_model(train_input, is_reuse): with tf.variable_scope('model', reuse = is_reuse): batch_size = tf.shape(train_input)[0] with tf.variable_scope('feature_extract', reuse = None): feature = feature_extractor(train_input) with tf.variable_scope('regression', reuse = None): mesh_motion = regression_Net(feature[-1]) mesh = shift2mesh(mesh_motion, 512, 384) rotation_mesh = tf_spatial_transform_local.transformer(train_input, mesh) #mesh2flow = tf_mesh2flow.mesh2flow(mesh) #rotation_mesh = bilinear_warp(train_input, mesh2flow) with tf.variable_scope('feature_extract2', reuse = None): feature_rotation_mesh = feature_extractor(rotation_mesh) with tf.variable_scope('decoder2', reuse = None): residual_flow = decoder2(feature_rotation_mesh) return mesh, rotation_mesh, residual_flow
9,955
37.440154
113
py
null
RotationCorrection-main/Codes/tensorDLT_local.py
import tensorflow as tf import numpy as np ####################################################### # Auxiliary matrices used to solve DLT Aux_M1 = np.array([ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 ]], dtype=np.float64) Aux_M2 = np.array([ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ]], dtype=np.float64) Aux_M3 = np.array([ [0], [1], [0], [1], [0], [1], [0], [1]], dtype=np.float64) Aux_M4 = np.array([ [-1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 ,-1 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 ,-1 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 ,-1 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ]], dtype=np.float64) Aux_M5 = np.array([ [0 ,-1 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 ,-1 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ,-1 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 ,-1 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ]], dtype=np.float64) Aux_M6 = np.array([ [-1 ], [ 0 ], [-1 ], [ 0 ], [-1 ], [ 0 ], [-1 ], [ 0 ]], dtype=np.float64) Aux_M71 = np.array([ [0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 ], [1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 ], [0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ], [0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ], [0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 ]], dtype=np.float64) Aux_M72 = np.array([ [1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [-1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 ,-1 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 ,-1 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 ,-1 , 0 ]], dtype=np.float64) Aux_M8 = np.array([ [0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 ,-1 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 ,-1 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ,-1 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 ,-1 ]], dtype=np.float64) Aux_Mb = np.array([ [0 ,-1 , 0 , 0 , 0 , 0 , 0 , 0 ], [1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , -1 , 0 , 0 , 0 , 0 ], [0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ,-1 , 0 , 0 ], [0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 , 0 , 0 ,-1 ], [0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 ]], dtype=np.float64) ######################################################## def solve_DLT(orig_pt4, pred_pt4): batch_size = tf.shape(orig_pt4)[0] orig_pt4 = tf.expand_dims(orig_pt4, [2]) pred_pt4 = tf.expand_dims(pred_pt4, [2]) # Auxiliary tensors used to create Ax = b equation M1 = tf.constant(Aux_M1, tf.float32) M1_tensor = tf.expand_dims(M1, [0]) M1_tile = tf.tile(M1_tensor ,[batch_size ,1 ,1]) M2 = tf.constant(Aux_M2, tf.float32) M2_tensor = tf.expand_dims(M2, [0]) M2_tile = tf.tile(M2_tensor ,[batch_size ,1 ,1]) M3 = tf.constant(Aux_M3, tf.float32) M3_tensor = tf.expand_dims(M3, [0]) M3_tile = tf.tile(M3_tensor ,[batch_size ,1 ,1]) M4 = tf.constant(Aux_M4, tf.float32) M4_tensor = tf.expand_dims(M4, [0]) M4_tile = tf.tile(M4_tensor ,[batch_size ,1 ,1]) M5 = tf.constant(Aux_M5, tf.float32) M5_tensor = tf.expand_dims(M5, [0]) M5_tile = tf.tile(M5_tensor ,[batch_size ,1 ,1]) M6 = tf.constant(Aux_M6, tf.float32) M6_tensor = tf.expand_dims(M6, [0]) M6_tile = tf.tile(M6_tensor ,[batch_size ,1 ,1]) M71 = tf.constant(Aux_M71, tf.float32) M71_tensor = tf.expand_dims(M71, [0]) M71_tile = tf.tile(M71_tensor ,[batch_size ,1 ,1]) M72 = tf.constant(Aux_M72, tf.float32) M72_tensor = tf.expand_dims(M72, [0]) M72_tile = tf.tile(M72_tensor ,[batch_size ,1 ,1]) M8 = tf.constant(Aux_M8, tf.float32) M8_tensor = tf.expand_dims(M8, [0]) M8_tile = tf.tile(M8_tensor ,[batch_size ,1 ,1]) Mb = tf.constant(Aux_Mb, tf.float32) Mb_tensor = tf.expand_dims(Mb, [0]) Mb_tile = tf.tile(Mb_tensor ,[batch_size ,1 ,1]) # Form the equations Ax = b to compute H # Form A matrix A1 = tf.matmul(M1_tile, orig_pt4) # Column 1 A2 = tf.matmul(M2_tile, orig_pt4) # Column 2 A3 = M3_tile # Column 3 A4 = tf.matmul(M4_tile, orig_pt4) # Column 4 A5 = tf.matmul(M5_tile, orig_pt4) # Column 5 A6 = M6_tile # Column 6 A7 = tf.matmul(M71_tile, pred_pt4) * tf.matmul(M72_tile, orig_pt4 )# Column 7 A8 = tf.matmul(M71_tile, pred_pt4) * tf.matmul(M8_tile, orig_pt4 )# Column 8 # tmp = tf.reshape(A1, [-1, 8]) #batch_size * 8 # A_mat: batch_size * 8 * 8 A1-A8相当?*8中的每一? A_mat = tf.transpose(tf.stack([tf.reshape(A1 ,[-1 ,8]) ,tf.reshape(A2 ,[-1 ,8]), \ tf.reshape(A3 ,[-1 ,8]) ,tf.reshape(A4 ,[-1 ,8]), \ tf.reshape(A5 ,[-1 ,8]) ,tf.reshape(A6 ,[-1 ,8]), \ tf.reshape(A7 ,[-1 ,8]) ,tf.reshape(A8 ,[-1 ,8])] ,axis=1), perm=[0 ,2 ,1]) # BATCH_SIZE x 8 (A_i) x 8 print('--Shape of A_mat:', A_mat.get_shape().as_list()) # Form b matrix b_mat = tf.matmul(Mb_tile, pred_pt4) print('--shape of b:', b_mat.get_shape().as_list()) # Solve the Ax = b #print(tf.shape(A_mat)[0]) #A_mat = A_mat + tf.tile(tf.expand_dims(tf.eye(8) * 10e-4, [0]),[batch_size ,1 ,1]) H_8el = tf.matrix_solve(A_mat , b_mat) # BATCH_SIZE x 8. print('--shape of H_8el', H_8el) # Add ones to the last cols to reconstruct H for computing reprojection error h_ones = tf.ones([batch_size, 1, 1]) H_9el = tf.concat([H_8el ,h_ones] ,1) H_flat = tf.reshape(H_9el, [-1 ,9]) #H_mat = tf.reshape(H_flat ,[-1 ,3 ,3]) # BATCH_SIZE x 3 x 3 return H_flat
7,105
33.663415
137
py
null
RotationCorrection-main/Codes/tf_mesh2flow.py
import tensorflow as tf import numpy as np import math import tensorDLT_local from keras.layers import UpSampling2D import constant grid_w = constant.GRID_W grid_h = constant.GRID_H def mesh2flow(mesh, name='Mesh2Flow', **kwargs): """Spatial Transformer Layer Implements a spatial transformer layer as described in [1]_. Based on [2]_ and edited by David Dao for Tensorflow. Parameters ---------- U : float The output of a convolutional net should have the shape [num_batch, height, width, num_channels]. theta: float The output of the localisation network should be [num_batch, 6]. out_size: tuple of two ints The size of the output of the network (height, width) References ---------- .. [1] Spatial Transformer Networks Max Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu Submitted on 5 Jun 2015 .. [2] https://github.com/skaae/transformer_network/blob/master/transformerlayer.py Notes ----- To initialize the network to the identity transform init ``theta`` to : identity = np.array([[1., 0., 0.], [0., 1., 0.]]) identity = identity.flatten() theta = tf.Variable(initial_value=identity) """ def _repeat(x, n_repeats): with tf.variable_scope('_repeat'): rep = tf.transpose( tf.expand_dims(tf.ones(shape=tf.stack([n_repeats, ])), 1), [1, 0]) rep = tf.cast(rep, 'int32') x = tf.matmul(tf.reshape(x, (-1, 1)), rep) return tf.reshape(x, [-1]) def _interpolate(im, x, y, out_size): with tf.variable_scope('_interpolate'): # constants num_batch = tf.shape(im)[0] height = tf.shape(im)[1] width = tf.shape(im)[2] channels = tf.shape(im)[3] x = tf.cast(x, 'float32') y = tf.cast(y, 'float32') height_f = tf.cast(height, 'float32') width_f = tf.cast(width, 'float32') out_height = out_size[0] out_width = out_size[1] zero = tf.zeros([], dtype='int32') max_y = tf.cast(tf.shape(im)[1] - 1, 'int32') max_x = tf.cast(tf.shape(im)[2] - 1, 'int32') # scale indices from [-1, 1] to [0, width/height] #x = (x + 1.0)*(width_f) / 2.0 #y = (y + 1.0)*(height_f) / 2.0 # do sampling x0 = tf.cast(tf.floor(x), 'int32') x1 = x0 + 1 y0 = tf.cast(tf.floor(y), 'int32') y1 = y0 + 1 x0 = tf.clip_by_value(x0, zero, max_x) x1 = tf.clip_by_value(x1, zero, max_x) y0 = tf.clip_by_value(y0, zero, max_y) y1 = tf.clip_by_value(y1, zero, max_y) dim2 = width dim1 = width*height base = _repeat(tf.range(num_batch)*dim1, out_height*out_width) base_y0 = base + y0*dim2 base_y1 = base + y1*dim2 idx_a = base_y0 + x0 idx_b = base_y1 + x0 idx_c = base_y0 + x1 idx_d = base_y1 + x1 # use indices to lookup pixels in the flat image and restore # channels dim im_flat = tf.reshape(im, tf.stack([-1, channels])) im_flat = tf.cast(im_flat, 'float32') Ia = tf.gather(im_flat, idx_a) Ib = tf.gather(im_flat, idx_b) Ic = tf.gather(im_flat, idx_c) Id = tf.gather(im_flat, idx_d) # and finally calculate interpolated values x0_f = tf.cast(x0, 'float32') x1_f = tf.cast(x1, 'float32') y0_f = tf.cast(y0, 'float32') y1_f = tf.cast(y1, 'float32') wa = tf.expand_dims(((x1_f-x) * (y1_f-y)), 1) wb = tf.expand_dims(((x1_f-x) * (y-y0_f)), 1) wc = tf.expand_dims(((x-x0_f) * (y1_f-y)), 1) wd = tf.expand_dims(((x-x0_f) * (y-y0_f)), 1) output = tf.add_n([wa*Ia, wb*Ib, wc*Ic, wd*Id]) return output #input: batch_size*(grid_h+1)*(grid_w+1)*2 #output: batch_size*grid_h*grid_w*9 def get_Hs(theta, width, height): with tf.variable_scope('get_Hs'): num_batch = tf.shape(theta)[0] h = height / grid_h w = width / grid_w Hs = [] for i in range(grid_h): for j in range(grid_w): hh = i * h ww = j * w ori = tf.tile(tf.constant([ww, hh, ww + w, hh, ww, hh + h, ww + w, hh + h], shape=[1, 8], dtype=tf.float32), multiples=[num_batch, 1]) #id = i * (grid_w + 1) + grid_w tar = tf.concat([tf.slice(theta, [0, i, j, 0], [-1, 1, 1, -1]), tf.slice(theta, [0, i, j + 1, 0], [-1, 1, 1, -1]), tf.slice(theta, [0, i + 1, j, 0], [-1, 1, 1, -1]), tf.slice(theta, [0, i + 1, j + 1, 0], [-1, 1, 1, -1])], axis=1) tar = tf.reshape(tar, [num_batch, 8]) #tar = tf.Print(tar, [tf.slice(ori, [0, 0], [1, -1])],message="[ori--i:"+str(i)+",j:"+str(j)+"]:", summarize=100,first_n=5) #tar = tf.Print(tar, [tf.slice(tar, [0, 0], [1, -1])],message="[tar--i:"+str(i)+",j:"+str(j)+"]:", summarize=100,first_n=5) Hs.append(tf.reshape(tensorDLT_local.solve_DLT(ori, tar), [num_batch, 1, 9])) Hs = tf.reshape(tf.concat(Hs, axis=1), [num_batch, grid_h, grid_w, 9], name='Hs') return Hs def _meshgrid2(height, width, sh, eh, sw, ew): hn = eh - sh + 1 wn = ew - sw + 1 x_t = tf.matmul(tf.ones(shape=tf.stack([hn, 1])), tf.transpose(tf.expand_dims(tf.slice(tf.linspace(-1.0, 1.0, width), [sw], [wn]), 1), [1, 0])) y_t = tf.matmul(tf.expand_dims(tf.slice(tf.linspace(-1.0, 1.0, height), [sh], [hn]), 1), tf.ones(shape=tf.stack([1, wn]))) x_t_flat = tf.reshape(x_t, (1, -1)) y_t_flat = tf.reshape(y_t, (1, -1)) ones = tf.ones_like(x_t_flat) grid = tf.concat([x_t_flat, y_t_flat, ones], 0) return grid def _meshgrid(height, width): #x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])), # tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width), 1), [1, 0])) #y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1), # tf.ones(shape=tf.stack([1, width]))) x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])), tf.transpose(tf.expand_dims(tf.linspace(0., tf.cast(width, 'float32')-1.001, width), 1), [1, 0])) y_t = tf.matmul(tf.expand_dims(tf.linspace(0., tf.cast(height, 'float32')-1.001, height), 1), tf.ones(shape=tf.stack([1, width]))) x_t_flat = tf.reshape(x_t, (1, -1)) y_t_flat = tf.reshape(y_t, (1, -1)) ones = tf.ones_like(x_t_flat) grid = tf.concat([x_t_flat, y_t_flat, ones], 0) return grid def _transform3(theta): with tf.variable_scope('_transform'): num_batch = tf.shape(theta)[0] height = 384 width = 512 width_float = 512. height_float = 384. theta = tf.cast(theta, 'float32') Hs = get_Hs(theta, width_float, height_float) gh = tf.cast(height / grid_h, 'int32') gw =tf.cast(width / grid_w, 'int32') ########################################## print("Hs") print(Hs.shape) H_array = UpSampling2D(size=(384/grid_h, 512/grid_w))(Hs) H_array = tf.reshape(H_array, [-1, 3, 3]) ########################################## out_height = height out_width = width grid = _meshgrid(out_height, out_width) grid = tf.expand_dims(grid, 0) grid = tf.reshape(grid, [-1]) grid = tf.tile(grid, tf.stack([num_batch])) # stack num_batch grids grid = tf.reshape(grid, tf.stack([num_batch, 3, -1])) print("grid") print(grid.shape) ### [bs, 3, N] grid = tf.expand_dims(tf.transpose(grid, [0, 2, 1]),3) ### [bs, 3, N] -> [bs, N, 3] -> [bs, N, 3, 1] grid = tf.reshape(grid, [-1, 3, 1]) ### [bs*N, 3, 1] print("grid") print(grid.shape) grid_row = tf.reshape(grid, [-1, 3]) print("grid_row") print(grid_row.shape) x_s = tf.reduce_sum(tf.multiply(H_array[:,0,:], grid_row), 1) y_s = tf.reduce_sum(tf.multiply(H_array[:,1,:], grid_row), 1) t_s = tf.reduce_sum(tf.multiply(H_array[:,2,:], grid_row), 1) t_s_flat = tf.reshape(t_s, [-1]) t_1 = tf.ones(shape = tf.shape(t_s_flat)) t_0 = tf.zeros(shape = tf.shape(t_s_flat)) sign_t = tf.where(t_s_flat >= 0, t_1, t_0) * 2 - 1 t_s_flat = t_s_flat + sign_t*1e-8 x_s_flat = tf.reshape(x_s, [-1]) / t_s_flat y_s_flat = tf.reshape(y_s, [-1]) / t_s_flat print("x_s_flat") print(x_s_flat.shape) flow_x = x_s_flat - grid_row[:,0] flow_y = y_s_flat - grid_row[:,1] flow = tf.stack([flow_x, flow_y], 1) flow = tf.reshape(flow, tf.stack([num_batch, height, width, 2])) return flow with tf.variable_scope(name): flow = _transform3(mesh) return flow
9,924
37.02682
154
py
null
RotationCorrection-main/Codes/tf_spatial_transform_local.py
import tensorflow as tf import numpy as np import math import tensorDLT_local from keras.layers import UpSampling2D import constant grid_w = constant.GRID_W grid_h = constant.GRID_H def transformer(U, theta, name='SpatialTransformer', **kwargs): """Spatial Transformer Layer Implements a spatial transformer layer as described in [1]_. Based on [2]_ and edited by David Dao for Tensorflow. Parameters ---------- U : float The output of a convolutional net should have the shape [num_batch, height, width, num_channels]. theta: float The output of the localisation network should be [num_batch, 6]. out_size: tuple of two ints The size of the output of the network (height, width) References ---------- .. [1] Spatial Transformer Networks Max Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu Submitted on 5 Jun 2015 .. [2] https://github.com/skaae/transformer_network/blob/master/transformerlayer.py Notes ----- To initialize the network to the identity transform init ``theta`` to : identity = np.array([[1., 0., 0.], [0., 1., 0.]]) identity = identity.flatten() theta = tf.Variable(initial_value=identity) """ def _repeat(x, n_repeats): with tf.variable_scope('_repeat'): rep = tf.transpose( tf.expand_dims(tf.ones(shape=tf.stack([n_repeats, ])), 1), [1, 0]) rep = tf.cast(rep, 'int32') x = tf.matmul(tf.reshape(x, (-1, 1)), rep) return tf.reshape(x, [-1]) def _interpolate(im, x, y, out_size): with tf.variable_scope('_interpolate'): # constants num_batch = tf.shape(im)[0] height = tf.shape(im)[1] width = tf.shape(im)[2] channels = tf.shape(im)[3] x = tf.cast(x, 'float32') y = tf.cast(y, 'float32') height_f = tf.cast(height, 'float32') width_f = tf.cast(width, 'float32') out_height = out_size[0] out_width = out_size[1] zero = tf.zeros([], dtype='int32') max_y = tf.cast(tf.shape(im)[1] - 1, 'int32') max_x = tf.cast(tf.shape(im)[2] - 1, 'int32') # scale indices from [-1, 1] to [0, width/height] #x = (x + 1.0)*(width_f) / 2.0 #y = (y + 1.0)*(height_f) / 2.0 # do sampling x0 = tf.cast(tf.floor(x), 'int32') x1 = x0 + 1 y0 = tf.cast(tf.floor(y), 'int32') y1 = y0 + 1 x0 = tf.clip_by_value(x0, zero, max_x) x1 = tf.clip_by_value(x1, zero, max_x) y0 = tf.clip_by_value(y0, zero, max_y) y1 = tf.clip_by_value(y1, zero, max_y) dim2 = width dim1 = width*height base = _repeat(tf.range(num_batch)*dim1, out_height*out_width) base_y0 = base + y0*dim2 base_y1 = base + y1*dim2 idx_a = base_y0 + x0 idx_b = base_y1 + x0 idx_c = base_y0 + x1 idx_d = base_y1 + x1 # use indices to lookup pixels in the flat image and restore # channels dim im_flat = tf.reshape(im, tf.stack([-1, channels])) im_flat = tf.cast(im_flat, 'float32') Ia = tf.gather(im_flat, idx_a) Ib = tf.gather(im_flat, idx_b) Ic = tf.gather(im_flat, idx_c) Id = tf.gather(im_flat, idx_d) # and finally calculate interpolated values x0_f = tf.cast(x0, 'float32') x1_f = tf.cast(x1, 'float32') y0_f = tf.cast(y0, 'float32') y1_f = tf.cast(y1, 'float32') wa = tf.expand_dims(((x1_f-x) * (y1_f-y)), 1) wb = tf.expand_dims(((x1_f-x) * (y-y0_f)), 1) wc = tf.expand_dims(((x-x0_f) * (y1_f-y)), 1) wd = tf.expand_dims(((x-x0_f) * (y-y0_f)), 1) output = tf.add_n([wa*Ia, wb*Ib, wc*Ic, wd*Id]) return output #input: batch_size*(grid_h+1)*(grid_w+1)*2 #output: batch_size*grid_h*grid_w*9 def get_Hs(theta, width, height): with tf.variable_scope('get_Hs'): num_batch = tf.shape(theta)[0] h = height / grid_h w = width / grid_w Hs = [] for i in range(grid_h): for j in range(grid_w): hh = i * h ww = j * w ori = tf.tile(tf.constant([ww, hh, ww + w, hh, ww, hh + h, ww + w, hh + h], shape=[1, 8], dtype=tf.float32), multiples=[num_batch, 1]) #id = i * (grid_w + 1) + grid_w tar = tf.concat([tf.slice(theta, [0, i, j, 0], [-1, 1, 1, -1]), tf.slice(theta, [0, i, j + 1, 0], [-1, 1, 1, -1]), tf.slice(theta, [0, i + 1, j, 0], [-1, 1, 1, -1]), tf.slice(theta, [0, i + 1, j + 1, 0], [-1, 1, 1, -1])], axis=1) tar = tf.reshape(tar, [num_batch, 8]) #tar = tf.Print(tar, [tf.slice(ori, [0, 0], [1, -1])],message="[ori--i:"+str(i)+",j:"+str(j)+"]:", summarize=100,first_n=5) #tar = tf.Print(tar, [tf.slice(tar, [0, 0], [1, -1])],message="[tar--i:"+str(i)+",j:"+str(j)+"]:", summarize=100,first_n=5) Hs.append(tf.reshape(tensorDLT_local.solve_DLT(ori, tar), [num_batch, 1, 9])) Hs = tf.reshape(tf.concat(Hs, axis=1), [num_batch, grid_h, grid_w, 9], name='Hs') return Hs def _meshgrid2(height, width, sh, eh, sw, ew): hn = eh - sh + 1 wn = ew - sw + 1 x_t = tf.matmul(tf.ones(shape=tf.stack([hn, 1])), tf.transpose(tf.expand_dims(tf.slice(tf.linspace(-1.0, 1.0, width), [sw], [wn]), 1), [1, 0])) y_t = tf.matmul(tf.expand_dims(tf.slice(tf.linspace(-1.0, 1.0, height), [sh], [hn]), 1), tf.ones(shape=tf.stack([1, wn]))) x_t_flat = tf.reshape(x_t, (1, -1)) y_t_flat = tf.reshape(y_t, (1, -1)) ones = tf.ones_like(x_t_flat) grid = tf.concat([x_t_flat, y_t_flat, ones], 0) return grid def _meshgrid(height, width): #x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])), # tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width), 1), [1, 0])) #y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1), # tf.ones(shape=tf.stack([1, width]))) x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])), tf.transpose(tf.expand_dims(tf.linspace(0., tf.cast(width, 'float32')-1.001, width), 1), [1, 0])) y_t = tf.matmul(tf.expand_dims(tf.linspace(0., tf.cast(height, 'float32')-1.001, height), 1), tf.ones(shape=tf.stack([1, width]))) x_t_flat = tf.reshape(x_t, (1, -1)) y_t_flat = tf.reshape(y_t, (1, -1)) ones = tf.ones_like(x_t_flat) grid = tf.concat([x_t_flat, y_t_flat, ones], 0) return grid def _transform3(theta, input_dim): with tf.variable_scope('_transform'): num_batch = tf.shape(input_dim)[0] height = tf.shape(input_dim)[1] width = tf.shape(input_dim)[2] num_channels = tf.shape(input_dim)[3] #widthfff = 512. #height width_float = 512. height_float = 384. #M = np.array([[width_float / 2.0, 0., width_float / 2.0], # [0., height_float / 2.0, height_float / 2.0], # [0., 0., 1.]]).astype(np.float32) #M_tensor = tf.constant(M, tf.float32) #M_tile = tf.tile(tf.expand_dims(M_tensor, [0]), [num_batch, 1, 1]) #M_inv = np.linalg.inv(M) #M_tensor_inv = tf.constant(M_inv, tf.float32) #M_tile_inv = tf.tile(tf.expand_dims(M_tensor_inv, [0]), [num_batch, 1, 1]) theta = tf.cast(theta, 'float32') Hs = get_Hs(theta, width_float, height_float) gh = tf.cast(height / grid_h, 'int32') gw =tf.cast(width / grid_w, 'int32') ########################################## print("Hs") print(Hs.shape) H_array = UpSampling2D(size=(384/grid_h, 512/grid_w))(Hs) H_array = tf.reshape(H_array, [-1, 3, 3]) ########################################## out_height = height out_width = width grid = _meshgrid(out_height, out_width) grid = tf.expand_dims(grid, 0) grid = tf.reshape(grid, [-1]) grid = tf.tile(grid, tf.stack([num_batch])) # stack num_batch grids grid = tf.reshape(grid, tf.stack([num_batch, 3, -1])) print("grid") print(grid.shape) ### [bs, 3, N] grid = tf.expand_dims(tf.transpose(grid, [0, 2, 1]),3) ### [bs, 3, N] -> [bs, N, 3] -> [bs, N, 3, 1] grid = tf.reshape(grid, [-1, 3, 1]) ### [bs*N, 3, 1] grid_row = tf.reshape(grid, [-1, 3]) print("grid_row") print(grid_row.shape) x_s = tf.reduce_sum(tf.multiply(H_array[:,0,:], grid_row), 1) y_s = tf.reduce_sum(tf.multiply(H_array[:,1,:], grid_row), 1) t_s = tf.reduce_sum(tf.multiply(H_array[:,2,:], grid_row), 1) # The problem may be here as a general homo does not preserve the parallelism # while an affine transformation preserves it. t_s_flat = tf.reshape(t_s, [-1]) t_1 = tf.ones(shape = tf.shape(t_s_flat)) t_0 = tf.zeros(shape = tf.shape(t_s_flat)) sign_t = tf.where(t_s_flat >= 0, t_1, t_0) * 2 - 1 t_s_flat = t_s_flat + sign_t*1e-8 x_s_flat = tf.reshape(x_s, [-1]) / t_s_flat y_s_flat = tf.reshape(y_s, [-1]) / t_s_flat out_size = (height, width) input_transformed = _interpolate(input_dim, x_s_flat, y_s_flat, out_size) #mask_transformed = _interpolate(mask, x_s_flat, y_s_flat, out_size) warp_image = tf.reshape(input_transformed, tf.shape(input_dim), name='output_img') #warp_mask = tf.reshape(mask_transformed, tf.stack([num_batch, height, width, num_channels]), name='output_mask') return warp_image#, warp_mask with tf.variable_scope(name): U = U - 1. warp_image = _transform3(theta, U) warp_image = warp_image + 1. warp_image = tf.clip_by_value(warp_image, -1, 1) return warp_image
10,939
39.07326
154
py
null
RotationCorrection-main/Codes/train.py
import tensorflow as tf import os from model import RotationCorrection from loss_functions import intensity_loss from utils import load, save, DataLoader import constant from PIL import Image import numpy as np import scipy.io os.environ['CUDA_DEVICES_ORDER'] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES'] = constant.GPU train_folder = constant.TRAIN_FOLDER test_folder = constant.TEST_FOLDER batch_size = constant.TRAIN_BATCH_SIZE iterations = constant.ITERATIONS height, width = 384, 512 summary_dir = constant.SUMMARY_DIR snapshot_dir = constant.SNAPSHOT_DIR #-------------------- build VGG19 for perceptual loss -------------------------- def build_net(ntype,nin,nwb=None,name=None): if ntype=='conv': return tf.nn.relu(tf.nn.conv2d(nin,nwb[0],strides=[1,1,1,1],padding='SAME',name=name)+nwb[1]) elif ntype=='pool': return tf.nn.avg_pool(nin,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') def get_weight_bias(vgg_layers,i): weights=vgg_layers[i][0][0][2][0][0] weights=tf.constant(weights) bias=vgg_layers[i][0][0][2][0][1] bias=tf.constant(np.reshape(bias,(bias.size))) return weights,bias vgg_path=scipy.io.loadmat('./vgg19/imagenet-vgg-verydeep-19.mat') print("[i] Loaded pre-trained vgg19 parameters") # build VGG19 to load pre-trained parameters def build_vgg19(input,reuse=False): with tf.variable_scope("vgg19"): if reuse: tf.get_variable_scope().reuse_variables() net={} vgg_layers=vgg_path['layers'][0] net['input']=input-np.array([123.6800, 116.7790, 103.9390]).reshape((1,1,1,3)) net['conv1_1']=build_net('conv',net['input'],get_weight_bias(vgg_layers,0),name='vgg_conv1_1') net['conv1_2']=build_net('conv',net['conv1_1'],get_weight_bias(vgg_layers,2),name='vgg_conv1_2') net['pool1']=build_net('pool',net['conv1_2']) net['conv2_1']=build_net('conv',net['pool1'],get_weight_bias(vgg_layers,5),name='vgg_conv2_1') net['conv2_2']=build_net('conv',net['conv2_1'],get_weight_bias(vgg_layers,7),name='vgg_conv2_2') net['pool2']=build_net('pool',net['conv2_2']) net['conv3_1']=build_net('conv',net['pool2'],get_weight_bias(vgg_layers,10),name='vgg_conv3_1') net['conv3_2']=build_net('conv',net['conv3_1'],get_weight_bias(vgg_layers,12),name='vgg_conv3_2') net['conv3_3']=build_net('conv',net['conv3_2'],get_weight_bias(vgg_layers,14),name='vgg_conv3_3') net['conv3_4']=build_net('conv',net['conv3_3'],get_weight_bias(vgg_layers,16),name='vgg_conv3_4') net['pool3']=build_net('pool',net['conv3_4']) net['conv4_1']=build_net('conv',net['pool3'],get_weight_bias(vgg_layers,19),name='vgg_conv4_1') net['conv4_2']=build_net('conv',net['conv4_1'],get_weight_bias(vgg_layers,21),name='vgg_conv4_2') net['conv4_3']=build_net('conv',net['conv4_2'],get_weight_bias(vgg_layers,23),name='vgg_conv4_3') net['conv4_4']=build_net('conv',net['conv4_3'],get_weight_bias(vgg_layers,25),name='vgg_conv4_4') net['pool4']=build_net('pool',net['conv4_4']) net['conv5_1']=build_net('conv',net['pool4'],get_weight_bias(vgg_layers,28),name='vgg_conv5_1') net['conv5_2']=build_net('conv',net['conv5_1'],get_weight_bias(vgg_layers,30),name='vgg_conv5_2') print(type(net)) return net #-------------------- end -------------------------- # define dataset with tf.name_scope('dataset'): train_data_loader = DataLoader(train_folder) train_data_dataset = train_data_loader(batch_size=batch_size) train_data_it = train_data_dataset.make_one_shot_iterator() train_input_tensor = train_data_it.get_next() train_input_tensor.set_shape([batch_size, height, width, 6]) train_input = train_input_tensor[:,:,:,0:3] train_gt = train_input_tensor[:,:,:,3:6] print('train input = {}'.format(train_input)) print('train gt = {}'.format(train_gt)) # define training generator function with tf.variable_scope('generator', reuse=None): train_mesh, train_horizon, train_flow, train_horizon2 = RotationCorrection(train_input) print('training = {}'.format(tf.get_variable_scope().name)) # define loss functions # content term train_horizon_feature = build_vgg19((train_horizon+1)*127.5, reuse=False) train_horizon2_feature = build_vgg19((train_horizon2+1)*127.5, reuse=True) train_gt_feature = build_vgg19((train_gt+1)*127.5, reuse=True) lamda_content = 1 if lamda_content != 0: content_loss = intensity_loss(gen_frames=train_horizon_feature['conv4_3'], gt_frames=train_gt_feature['conv4_3'], l_num=2) + \ intensity_loss(gen_frames=train_horizon2_feature['conv4_3'], gt_frames=train_gt_feature['conv4_3'], l_num=2)*0.25 else: content_loss = tf.constant(0.0, dtype=tf.float32) # symmetry term lamda_symmetry = 0.1 if lamda_symmetry != 0: with tf.variable_scope('generator', reuse=True): train_mesh_sym, train_horizon_sym, train_flow_sym, train_horizon2_sym = RotationCorrection(tf.image.flip_left_right(train_input)) train_horizon_feature_sym_sym = build_vgg19((tf.image.flip_left_right(train_horizon_sym)+1)*127.5, reuse=True) train_horizon2_feature_sym_sym = build_vgg19((tf.image.flip_left_right(train_horizon2_sym)+1)*127.5, reuse=True) symmetry_loss = intensity_loss(gen_frames=train_horizon_feature['conv4_3'], gt_frames=train_horizon_feature_sym_sym['conv4_3'], l_num=2) + \ intensity_loss(gen_frames=train_horizon2_feature['conv4_3'], gt_frames=train_horizon2_feature_sym_sym['conv4_3'], l_num=2)*0.25 else: symmetry_loss = tf.constant(0.0, dtype=tf.float32) with tf.name_scope('training'): g_loss = tf.add_n([symmetry_loss * lamda_symmetry, content_loss * lamda_content], name='g_loss') g_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='g_step') g_lrate = tf.train.exponential_decay(0.0001, g_step, decay_steps=50000/4, decay_rate=0.96) g_optimizer = tf.train.AdamOptimizer(learning_rate=g_lrate, name='g_optimizer') g_vars = tf.get_collection(key=tf.GraphKeys.TRAINABLE_VARIABLES, scope='generator') grads = g_optimizer.compute_gradients(g_loss, var_list=g_vars) for i, (g, v) in enumerate(grads): if g is not None: grads[i] = (tf.clip_by_norm(g, 3), v) # clip gradients g_train_op = g_optimizer.apply_gradients(grads, global_step=g_step, name='g_train_op') # add all to summaries' #loss tf.summary.scalar(tensor=g_loss, name='g_loss') tf.summary.scalar(tensor=content_loss, name='content_loss') tf.summary.scalar(tensor=symmetry_loss, name='symmetry_loss') #images tf.summary.image(tensor=train_input, name='input') tf.summary.image(tensor=train_horizon, name='rotation') tf.summary.image(tensor=train_horizon2, name='rotation2') tf.summary.image(tensor=train_gt, name='gt') summary_op = tf.summary.merge_all() config = tf.ConfigProto() config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: # summaries summary_writer = tf.summary.FileWriter(summary_dir, graph=sess.graph) # initialize weights sess.run(tf.global_variables_initializer()) print('Init successfully!') # tf saver saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=None) restore_var = [v for v in tf.global_variables()] loader = tf.train.Saver(var_list=restore_var) print("snapshot_dir") print(snapshot_dir) if os.path.isdir(snapshot_dir): ckpt = tf.train.get_checkpoint_state(snapshot_dir) if ckpt and ckpt.model_checkpoint_path: load(loader, sess, ckpt.model_checkpoint_path) else: print('No checkpoint file found.') else: load(loader, sess, snapshot_dir) _step, _loss, _summaries = 0, None, None print("============starting training===========") while _step < iterations: try: print('Training generator...') _, _g_lr, _step, _content_loss, _symmetry_loss, _g_loss, _summaries = sess.run([g_train_op, g_lrate, g_step, content_loss, symmetry_loss, g_loss, summary_op]) if _step % 50 == 0: print('GeneratorModel : Step {}, lr = {:.8f}'.format(_step, _g_lr)) print(' Global Loss : ', _g_loss) print(' Content Loss : ({:.4f} * {:.4f} = {:.4f})'.format(_content_loss, lamda_content, _content_loss * lamda_content)) print(' Symmetry Loss : ({:.4f} * {:.4f} = {:.4f})'.format(_symmetry_loss, lamda_symmetry, _symmetry_loss * lamda_symmetry)) if _step % 200 == 0: summary_writer.add_summary(_summaries, global_step=_step) print('Save summaries...') if _step % 50000 == 0 :#or _step == 110000 or _step == 120000: save(saver, sess, snapshot_dir, _step) except tf.errors.OutOfRangeError: print('Finish successfully!') save(saver, sess, snapshot_dir, _step) break
9,044
42.071429
170
py
null
RotationCorrection-main/Codes/utils.py
import tensorflow as tf import numpy as np from collections import OrderedDict import os import glob import cv2 rng = np.random.RandomState(2022) class DataLoader(object): def __init__(self, video_folder): self.dir = video_folder self.videos = OrderedDict() self.setup() def __call__(self, batch_size): video_info_list = list(self.videos.values()) length = video_info_list[0]['length'] def video_clip_generator(): #frame_id = 0 while True: video_clip = [] #size_clip = [] frame_id = rng.randint(0, length-1) #######inputs video_clip.append(np_load_frame(video_info_list[1]['frame'][frame_id], 384, 512)) video_clip.append(np_load_frame(video_info_list[0]['frame'][frame_id], 384, 512)) video_clip = np.concatenate(video_clip, axis=2) #######size #size_clip.append(np_load_size(video_info_list[1]['frame'][frame_id])) #size_clip = np.concatenate(size_clip, axis=0) yield video_clip dataset = tf.data.Dataset.from_generator(generator=video_clip_generator, output_types=tf.float32, output_shapes=[384, 512, 6]) dataset = dataset.prefetch(buffer_size=128) dataset = dataset.shuffle(buffer_size=128).batch(batch_size) print('generator dataset, {}'.format(dataset)) return dataset def __getitem__(self, video_name): assert video_name in self.videos.keys(), 'video = {} is not in {}!'.format(video_name, self.videos.keys()) return self.videos[video_name] def setup(self): videos = glob.glob(os.path.join(self.dir, '*')) for video in sorted(videos): video_name = video.split('/')[-1] if video_name == 'input' or video_name == 'gt' : self.videos[video_name] = {} self.videos[video_name]['path'] = video self.videos[video_name]['frame'] = glob.glob(os.path.join(video, '*.jpg')) self.videos[video_name]['frame'].sort() self.videos[video_name]['length'] = len(self.videos[video_name]['frame']) print(self.videos.keys()) # for inference on DRC-D dataset def get_data_clips(self, index): batch = [] video_info_list = list(self.videos.values()) batch.append(np_load_frame(video_info_list[1]['frame'][index], 384, 512)) batch.append(np_load_frame(video_info_list[0]['frame'][index], 384, 512)) return np.concatenate(batch, axis=2) def np_load_frame(filename, resize_height, resize_width): image_decoded = cv2.imread(filename) image_resized = cv2.resize(image_decoded, (resize_width, resize_height)) image_resized = image_resized.astype(dtype=np.float32) image_resized = (image_resized / 127.5) - 1.0 return image_resized def load(saver, sess, ckpt_path): print(ckpt_path) saver.restore(sess, ckpt_path) print("Restored model parameters from {}".format(ckpt_path)) def save(saver, sess, logdir, step): model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, global_step=step) print('The checkpoint has been created.')
3,419
31.571429
134
py
Grid2Op
Grid2Op-master/.readthedocs.yml
version: 2 python: version: 3.8 install: - method: pip path: . extra_requirements: - docs
136
12.7
28
yml
Grid2Op
Grid2Op-master/LICENSE.md
Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
16,725
43.721925
72
md
Grid2Op
Grid2Op-master/LicensesInformation.md
Copyright (c) 2019-2020, RTE (https://www.rte-france.com) See [AUTHORS.txt](AUTHORS.txt) This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/. SPDX-License-Identifier: MPL-2.0 This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems. # Project dependencies In this file, we try to recap the licenses of the project on which grid2op depends on. This file is NOT a substitute for the [LICENSE](LICENSE.md) files that presents the terms of the MPLv2.0 license, license under which this project is released. ## Base package (required) | Package | License | |------------|:----------------:| | numpy | [BSD](https://numpy.org/license.html) | | scipy | [BSD-3-Clause "New"](https://www.scipy.org/scipylib/license.html) | | pandas | [BSD-3-Clause "New"](https://github.com/pandas-dev/pandas/blob/master/LICENSE) | | pandapower | [BSD 3-Clause "New"](https://pandapower.readthedocs.io/en/v1.4.1/about/license.html)| | tqdm | [MPL 2.0](https://github.com/tqdm/tqdm/blob/master/LICENCE) | | pathlib | [MIT](https://en.wikipedia.org/wiki/MIT_License) | | networkx | [BSD 3-Clause "New"](https://networkx.github.io/documentation/networkx-1.10/reference/legal.html) | | requests |[Apache License 2.0](https://github.com/psf/requests/blob/master/LICENSE)| | imageio | [BSD-2-Clause "Simplified"](https://github.com/imageio/imageio/blob/master/LICENSE) | | matplotlib | [PSF](https://matplotlib.org/3.2.1/users/license.html) | ## Optional packages ### Extra package (optional) | Package | License | |---------------|:----------------:| | nbformat | [BSD](https://fr.wikipedia.org/wiki/Licence_BSD) | | jupyter-client| [BSD 3-Clause "New"](https://github.com/jupyter/jupyter/blob/master/LICENSE) | | jyquickhelper | [MIT](https://github.com/sdpython/jyquickhelper/blob/master/LICENSE.txt) | ### Optional (optional) | Package | License | |------------|:----------------:| | numba | [BSD 2-Clause "Simplified"](https://github.com/numba/numba/blob/master/LICENSE) | | plotly | [MIT](https://github.com/plotly/plotly.js/blob/master/LICENSE) | | seaborn | [BSD 3-Clause "new"](https://github.com/mwaskom/seaborn/blob/master/LICENSE) | | pygifsicle | [MIT](https://en.wikipedia.org/wiki/MIT_License) | | psutil | [BSD 3-Clause "new"](https://github.com/giampaolo/psutil/blob/master/LICENSE)| ### deprecated (optional) | Package | License | |------------|:----------------:| | pygame | [GNU LGPL v2.1](https://www.gnu.org/copyleft/lesser.html) | | imageio-ffmpeg | [BSD 2-Clause "Simplified"](https://github.com/imageio/imageio-ffmpeg/blob/master/LICENSE)| ### doc (optional) | Package | License | |------------|:----------------:| | numpydoc | [BSD](https://github.com/numpy/numpydoc/blob/master/LICENSE.txt) | | sphinx | [BSD](https://github.com/sphinx-doc/sphinx/blob/3.x/LICENSE)| | sphinx-rtd-theme | [MIT](https://github.com/readthedocs/sphinx_rtd_theme/blob/master/LICENSE) | | sphinxcontrib-trio | [MIT or Apache 2](https://github.com/python-trio/sphinxcontrib-trio/blob/master/LICENSE) | | autodocsumm | [GPL v2](https://github.com/Chilipp/autodocsumm/blob/master/LICENSE)| ### challenge (optional) | Package | License | |------------|:----------------:| | tensorflow | [Apache License 2.0](https://github.com/tensorflow/tensorflow/blob/master/LICENSE) | | Keras | [MIT](https://github.com/keras-team/keras/blob/master/LICENSE) | | torch | [BSD 3-Clause "New"](https://github.com/intel/torch/blob/master/LICENSE.md)| | statsmodels | [BSD](https://github.com/statsmodels/statsmodels/blob/master/LICENSE.txt)| | scikit-learn | [BSD 3-clauses](https://fr.wikipedia.org/wiki/Licence_BSD) | | gym | [MIT](https://github.com/openai/gym/blob/master/LICENSE.md) |
4,131
48.783133
116
md
Grid2Op
Grid2Op-master/README.md
# Grid2Op [![Downloads](https://pepy.tech/badge/grid2op)](https://pepy.tech/project/grid2op) [![PyPi_Version](https://img.shields.io/pypi/v/grid2op.svg)](https://pypi.org/project/Grid2Op/) [![PyPi_Compat](https://img.shields.io/pypi/pyversions/grid2op.svg)](https://pypi.org/project/Grid2Op/) [![LICENSE](https://img.shields.io/pypi/l/grid2op.svg)](https://www.mozilla.org/en-US/MPL/2.0/) [![Documentation Status](https://readthedocs.org/projects/grid2op/badge/?version=latest)](https://grid2op.readthedocs.io/en/latest/?badge=latest) [![circleci](https://circleci.com/gh/rte-france/Grid2Op.svg?style=shield)](https://circleci.com/gh/rte-france/Grid2Op) [![discord](https://discord.com/api/guilds/698080905209577513/embed.png)]( https://discord.gg/cYsYrPT) [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/rte-france/Grid2Op/master) Grid2Op is a platform, built with modularity in mind, that allows to perform powergrid operation. And that's what it stands for: Grid To Operate. Grid2Op acts as a replacement of [pypownet](https://github.com/MarvinLer/pypownet) as a library used for the Learning To Run Power Network [L2RPN](https://l2rpn.chalearn.org/). This framework allows to perform most kind of powergrid operations, from modifying the setpoint of generators, to load shedding, performing maintenance operations or modifying the *topology* of a powergrid to solve security issues. Official documentation: the official documentation is available at [https://grid2op.readthedocs.io/](https://grid2op.readthedocs.io/). * [1 Installation](#installation) * [1.1 Setup a Virtualenv (optional)](#setup-a-virtualenv-optional) * [1.2 Install from source](#install-from-source) * [1.3 Install from PyPI](#install-from-pypi) * [1.4 Install for contributors](#install-for-contributors) * [1.5 Docker](#docker) * [2 Main features of Grid2Op](#main-features-of-grid2op) * [3 Getting Started](#getting-started) * [0 Basic features](getting_started/0_basic_functionalities.ipynb) * [1 BaseObservation Agents](getting_started/1_Observation_Agents.ipynb) * [2 BaseAction Grid Manipulation](getting_started/2_Action_GridManipulation.ipynb) * [3 Training An BaseAgent](getting_started/3_TrainingAnAgent.ipynb) * [4 Study Your BaseAgent](getting_started/4_StudyYourAgent.ipynb) * [4 Citing](#Citing) * [5 Documentation](#documentation) * [6 Contribute](#contributing) * [7 Test and known issues](#tests-and-known-issues) * [8 License information](#license-information) # Installation ## Requirements: * Python >= 3.6 ## Setup a Virtualenv (optional) ### Create a virtual environment ```commandline cd my-project-folder pip3 install -U virtualenv python3 -m virtualenv venv_grid2op ``` ### Enter virtual environment ```commandline source venv_grid2op/bin/activate ``` ## Install from PyPI ```commandline pip3 install grid2op ``` ## Install from source ```commandline git clone https://github.com/rte-france/Grid2Op.git cd Grid2Op pip3 install -U . cd .. ``` ## Install for contributors ```commandline git clone https://github.com/rte-france/Grid2Op.git cd Grid2Op pip3 install -e . pip3 install -e .[optional] pip3 install -e .[docs] ``` ## Docker Grid2Op docker containers are available on [dockerhub](https://hub.docker.com/r/bdonnot/grid2op/tags). To install the latest Grid2Op container locally, use the following: ```commandline docker pull bdonnot/grid2op:latest ``` # Main features of Grid2Op ## Core functionalities Built with modulartiy in mind, Grid2Op as a library used for the "Learning To Run Power Network" [L2RPN](https://l2rpn.chalearn.org/) competitions serie. It can also Its main features are: * emulates the behavior of a powergrid of any size at any format (provided that a *backend* is properly implemented) * allows for grid modifications (active and reactive load values, generator voltages setpoints, active production but most importantly grid topology beyond powerline connection / disconnection) * allows for maintenance operations and powergrid topological changes * can adopt any powergrid modeling, especially Alternating Current (AC) and Direct Current (DC) approximation to when performing the compitations * supports changes of powerflow solvers, actions, observations to better suit any need in performing power system operations modeling * has an RL-focused interface, compatible with [OpenAI-gym](https://gym.openai.com/): same interface for the Environment class. * parameters, game rules or type of actions are perfectly parametrizable * can adapt to any kind of input data, in various format (might require the rewriting of a class) ## Powerflow solver Grid2Op relies on an open source powerflow solver ([PandaPower](https://www.pandapower.org/)), but is also compatible with other *Backend*. If you have at your disposal another powerflow solver, the documentation of [grid2op/Backend](grid2op/Backend/Backend.py) can help you integrate it into a proper "Backend" and have Grid2Op using this powerflow instead of PandaPower. # Getting Started Some Jupyter notebook are provided as tutorials for the Grid2Op package. They are located in the [getting_started](getting_started) directories. TODO: this needs to be redone, refactorize and better explained for some of them. These notebooks will help you in understanding how this framework is used and cover the most interesting part of this framework: * [00_Introduction](getting_started/00_Introduction.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/00_Introduction.ipynb) and [00_SmallExample](getting_started/00_SmallExample.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/00_SmallExample.ipynb) describe what is adressed by the grid2op framework (with a tiny introductions to both power systems and reinforcement learning) and give and introductory example to a small powergrid manipulation. * [01_Grid2opFramework](getting_started/01_Grid2opFramework.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/01_Grid2opFramework.ipynb) covers the basics of the Grid2Op framework. It also covers how to create a valid environment and how to use the `Runner` class to assess how well an agent is performing rapidly. * [02_Observation](getting_started/02_Observation.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/02_Observation.ipynb) details how to create an "expert agent" that will take pre defined actions based on the observation it gets from the environment. This Notebook also covers the functioning of the BaseObservation class. * [03_Action](getting_started/03_Action.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/03_Action.ipynb) demonstrates how to use the BaseAction class and how to manipulate the powergrid. * [04_TrainingAnAgent](getting_started/04_TrainingAnAgent.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/04_TrainingAnAgent.ipynb) shows how to get started with reinforcement learning with the grid2op environment. It shows the basic on how to train a "PPO" model operating the grid relying on "stable baselines 3" PPO implementation. * [05_StudyYourAgent](getting_started/05_StudyYourAgent.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/05_StudyYourAgent.ipynb) shows how to study an BaseAgent, for example the methods to reload a saved experiment, or to plot the powergrid given an observation for example. This is an introductory notebook. More user friendly graphical interface should come soon. * [06_Redispatching_Curtailment](getting_started/06_Redispatching_Curtailment.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/06_Redispatching_Curtailment.ipynb) explains what is the "redispatching" and curtailment from the point of view of a company who's in charge of keeping the powergrid safe (aka a Transmission System Operator) and how to manipulate this concept in grid2op. Redispatching (and curtailment) allows you to perform **continuous** actions on the powergrid problem. * [07_MultiEnv](getting_started/07_MultiEnv.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/07_MultiEnv.ipynb) details how grid2op natively support a single agent interacting with multiple environments at the same time. This is particularly handy to train "asynchronous" agent in the Reinforcement Learning community for example. * [08_PlottingCapabilities](getting_started/08_PlottingCapabilities.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/08_PlottingCapabilities.ipynb) shows you the different ways with which you can represent (visually) the grid your agent interact with. A renderer is available like in many open AI gym environment. But you also have the possibility to post process an agent and make some movies out of it, and we also developed a Graphical User Interface (GUI) called "[grid2viz](https://github.com/mjothy/grid2viz)" that allows to perform in depth study of your agent's behaviour on different scenarios and even to compare it with baselines. * [09_EnvironmentModifications](getting_started/09_EnvironmentModifications.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/09_EnvironmentModifications.ipynb) elaborates on the maintenance, hazards and attacks. All three of these represents external events that can disconnect some powerlines. This notebook covers how to spot when such things happened and what can be done when the maintenance or the attack is over. * [10_StorageUnits](getting_started/10_StorageUnits.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/10_StorageUnits.ipynb) details the usage and behaviour of the storage units in grid2op. * [11_IntegrationWithExistingRLFrameworks](getting_started/11_IntegrationWithExistingRLFrameworks.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rte-france/Grid2Op/blob/master/getting_started/11_IntegrationWithExistingRLFrameworks.ipynb) explains how to use grid2op with other reinforcement learning framework. TODO: this needs to be redone Try them out in your own browser without installing anything with the help of mybinder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/rte-france/Grid2Op/master) Or thanks to google colab (all links are provided near the notebook description) # Citing If you use this package in one of your work, please cite: ``` @misc{grid2op, author = {B. Donnot}, title = {{Grid2op- A testbed platform to model sequential decision making in power systems. }}, year = {2020}, publisher = {GitHub}, journal = {GitHub repository}, howpublished = {\url{https://GitHub.com/rte-france/grid2op}}, } ``` # Documentation The official documentation is available at [https://grid2op.readthedocs.io/](https://grid2op.readthedocs.io/). ## Build the documentation locally A copy of the documentation can be built if the project is installed *from source*: you will need Sphinx, a Documentation building tool, and a nice-looking custom [Sphinx theme similar to the one of readthedocs.io](https://sphinx-rtd-theme.readthedocs.io/en/latest/). These can be installed with: ```commandline pip3 install -U grid2op[docs] ``` This installs both the Sphinx package and the custom template. Then, on systems where `make` is available (mainly gnu-linux and macos) the documentation can be built with the command: ```commandline make html ``` For windows, or systems where `make` is not available, the command: ```commandline sphinx-build -b html docs documentation ``` This will create a "documentation" subdirectory and the main entry point of the document will be located at [index.html](documentation/html/index.html). It is recommended to build this documentation locally, for convenience. For example, the "getting started" notebooks referenced some pages of the help. <!-- sphinx-build -b html docs documentation--> # Contributing We welcome contributions from everyone. They can take the form of pull requests for smaller changed. In case of a major change (or if you have a doubt on what is "a small change"), please open an issue first to discuss what you would like to change. To contribute to this code, you need to: 1. fork the repository located at https://github.com/rte-france/Grid2Op 2. synch your fork with the "latest developement branch of grid2op". For example, if the latest grid2op release on pypi is `1.6.5` you need to synch your repo with the branch named `dev_1.6.6` or `dev_1.7.0` (if the branch `dev_1.6.6` does not exist). It will be the highest number in the branches `dev_*` on grid2op official github repository. 3. implement your functionality / code your modifications or anything else 4. make sure to add tests and documentation if applicable 5. once it is developed, synch your repo with the last development branch again (see point 2 above) and make sure to solve any possible conflicts 6. write a pull request and make sure to target the right branch (the "last development branch") Code in the contribution should pass all the tests, have some dedicated tests for the new feature (if applicable) and documentation (if applicable). Before implementing any major feature, please write a github issue first. # Tests and known issues ## Tests performed currently Grid2op is currently tested on windows, linux and macos. The unit tests includes testing, on linux machines the correct integration of grid2op with: - python 3.8 - python 3.9 - python 3.10 - python 3.11 On all of these cases, we tested grid2op on all available numpy version >= 1.20 (**nb** available numpy versions depend on python version). The complete test suit is run on linux with the latest numpy version on python 3.8. ## Known issues Due to the underlying behaviour of the "multiprocessing" package on windows based python versions, the "multiprocessing" of the grid2op "Runner" is not supported on windows. This might change in the future, but it is currently not on our priorities. A quick fix that is known to work include to set the `experimental_read_from_local_dir` when creating the environment with `grid2op.make(..., experimental_read_from_local_dir=True)` (see doc for more information) ## Perform tests locally Provided that Grid2Op is installed *from source*: ### Install additional dependencies ```commandline pip3 install -U grid2op[optional] ``` ### Launch tests ```commandline cd grid2op/tests python3 -m unittest discover ``` # License information Copyright 2019-2020 RTE France RTE: http://www.rte-france.com This Source Code is subject to the terms of the Mozilla Public License (MPL) v2 also available [here](https://www.mozilla.org/en-US/MPL/2.0/)
16,183
50.70607
212
md
Grid2Op
Grid2Op-master/setup.py
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. # If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, # you can obtain one at http://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 # This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems. import sys import setuptools from setuptools import setup import unittest def my_test_suite(): test_loader = unittest.TestLoader() test_suite = test_loader.discover('grid2op/tests', pattern='test_*.py') return test_suite with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() pkgs = { "required": [ "numpy>=1.20", "scipy>=1.4.1", "pandas>=1.0.3", "pandapower>=2.2.2", "tqdm>=4.45.0", "networkx>=2.4", "requests>=2.23.0", "packaging" # because gym changes the way it uses numpy prng in version 0.26 and i need both gym before and after... ], "extras": { "optional": [ "nbformat>=5.0.4", "jupyter-client>=6.1.0", "jyquickhelper>=0.3.128", "numba>=0.48.0", "matplotlib>=3.2.1", "plotly>=4.5.4", "seaborn>=0.10.0", "imageio>=2.8.0", "pygifsicle>=1.0.1", "psutil>=5.7.0", "gymnasium", "lightsim2grid", ], "gym": [ "gym>=0.17.2", ], "gymnasium": [ "gymnasium", ], "docs": [ "numpydoc>=0.9.2", "sphinx>=2.4.4", "sphinx-rtd-theme>=0.4.3", "sphinxcontrib-trio>=1.1.0", "autodocsumm>=0.1.13", "gym>=0.17.2", "gymnasium", ], "api": [ "flask", "flask_wtf", "ujson" ], "plot": ["imageio"], "test": ["lightsim2grid", "numba", "gym>=0.26", "gymnasium" ], "chronix2grid": [ "ChroniX2Grid@https://github.com/BDonnot/ChroniX2Grid/tarball/ramp_forecast" ] } } pkgs["extras"]["test"] += pkgs["extras"]["optional"] pkgs["extras"]["test"] += pkgs["extras"]["plot"] pkgs["extras"]["test"] += pkgs["extras"]["chronix2grid"] pkgs["extras"]["test"] += pkgs["extras"]["gymnasium"] if sys.version_info.minor <= 7: # typing "Literal" not available on python 3.7 pkgs["required"].append("typing_extensions") pkgs["required"][3] = "pandapower>=2.2.2,<2.12" # importlib provided importlib.metadata as of python 3.8 pkgs["required"].append("importlib_metadata") setup(description='An gym compatible environment to model sequential decision making for powersystems', long_description=long_description, long_description_content_type="text/markdown", author='Benjamin DONNOT', author_email='benjamin.donnot@rte-france.com', python_requires='>=3.8', url="https://github.com/rte-france/Grid2Op", packages=setuptools.find_packages(), include_package_data=True, install_requires=pkgs["required"], extras_require=pkgs["extras"], zip_safe=False, entry_points={ 'console_scripts': [ 'grid2op.main=grid2op.command_line:main', 'grid2op.download=grid2op.command_line:download', 'grid2op.replay=grid2op.command_line:replay', 'grid2op.testinstall=grid2op.command_line:testinstall' ] }, test_suite='setup.my_test_suite' )
3,738
31.513043
125
py
Grid2Op
Grid2Op-master/.circleci/config.yml
version: 2.1 executors: grid2op-executor: docker: - image: bdonnot/grid2op:test working_directory: /Grid2Op python37: docker: - image: python:3.7-buster python38: docker: - image: python:3.8-buster python39: docker: - image: python:3.9-buster python310: docker: - image: python:3.10-buster python311: docker: - image: python:3.11-buster jobs: test: executor: grid2op-executor resource_class: medium parallelism: 4 steps: - checkout - run: apt-get install -y coinor-cbc - run: python -m pip install virtualenv - run: python -m virtualenv venv_test - run: command: | source venv_test/bin/activate pip install -U pip setuptools wheel - run: command: | source venv_test/bin/activate pip install -e .[test] export _GRID2OP_FORCE_TEST=1 cd grid2op/tests/ python3 helper_list_test.py | circleci tests split > /tmp/tests_run - run: cat /tmp/tests_run - run: command: | source venv_test/bin/activate cd grid2op/tests/ export _GRID2OP_FORCE_TEST=1 python3 -m unittest $(cat /tmp/tests_run) install36: executor: python36 resource_class: small steps: - checkout - run: command: | apt-get update apt-get install -y coinor-cbc - run: python -m pip install virtualenv - run: python -m virtualenv venv_test - run: command: | source venv_test/bin/activate pip install -U pip setuptools wheel - run: command: | source venv_test/bin/activate pip install -U numba pip install -U "numpy>=1.18,<1.19" pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate pip install -U "numpy>=1.19,<1.20" pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall install37: executor: python37 resource_class: small steps: - checkout - run: command: | apt-get update apt-get install -y coinor-cbc - run: python -m pip install virtualenv - run: python -m virtualenv venv_test - run: command: | source venv_test/bin/activate python -m pip install -U pip setuptools wheel - run: command: | source venv_test/bin/activate python -m pip install -U numba python -m pip install -U "numpy>=1.20,<1.21" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.21,<1.22" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall install38: executor: python38 resource_class: small steps: - checkout - run: command: | apt-get update apt-get install -y coinor-cbc - run: python -m pip install virtualenv - run: python -m virtualenv venv_test - run: command: | source venv_test/bin/activate python -m pip install -U pip setuptools wheel python -m pip install -U numba - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.20,<1.21" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.21,<1.22" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.22,<1.23" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.23,<1.24" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.24,<1.25" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall install39: executor: python39 resource_class: small steps: - checkout - run: command: | apt-get update apt-get install -y coinor-cbc - run: python -m pip install virtualenv - run: python -m virtualenv venv_test - run: command: | export _GRID2OP_FORCE_TEST=1 source venv_test/bin/activate python -m pip install -U pip setuptools wheel python -m pip install chronix2grid>="1.1.0.post1" python -m pip uninstall -y grid2op - run: command: | source venv_test/bin/activate python -m pip install -U numba python -m pip install -U .[test] - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.20,<1.21" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.21,<1.22" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.22,<1.23" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.23,<1.24" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.24,<1.25" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.25,<1.26" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall install310: executor: python310 resource_class: small steps: - checkout - run: command: | apt-get update apt-get install -y coinor-cbc - run: python -m pip install virtualenv - run: python -m virtualenv venv_test - run: command: | source venv_test/bin/activate python -m pip install -U pip setuptools wheel python -m pip install -U numba - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.21,<1.22" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.22,<1.23" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.23,<1.24" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.24,<1.25" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.25,<1.26" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall install311: executor: python311 resource_class: small steps: - checkout - run: command: | apt-get update apt-get install -y coinor-cbc - run: python -m pip install virtualenv - run: python -m virtualenv venv_test - run: command: | source venv_test/bin/activate python -m pip install -U pip setuptools wheel python -m pip install -U numba - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.23,<1.24" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.24,<1.25" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall - run: command: | source venv_test/bin/activate python -m pip install -U "numpy>=1.25,<1.26" python -m pip install -U .[test] export _GRID2OP_FORCE_TEST=1 grid2op.testinstall workflows: version: 2.1 test: jobs: - test install: jobs: - install38 - install39 - install310 - install311
12,174
35.561562
85
yml
Grid2Op
Grid2Op-master/.github/ISSUE_TEMPLATE/bug_report.md
--- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- ## Environment - Grid2op version: `0.x.x` - System: `windows, osx, ubuntu16.04, ...` - Additional system information ## Bug description <!--A clear and concise description of what the bug is.--> <!--A good method to find and fix bugs is explained here https://adv-r.hadley.nz/debugging.html#debugging-strategy (it's written for R, but this section is generic for most computer languages) --> <!--We cannot do steps 1, 2 and 3 for you, the closer you get to a concise piece of code highlighting the bug the less time we'll spenf understanding it, and fixing it. And the more robust will be the fix as we'll most likely write unit test to make sure the bug does not reappear in the future. This is why we insist on having "A clear and concise description of what the bug is"--> ## How to reproduce <!--Explain in detail how to reproduce your issue. The easier it will be for us to reproduce it, the faster we will be able to work on this.--> ### Command line <!--Ideally, if we execute the following command, the bug will directly be reproduced. Here put the command line we have to execute--> ```bash # command line used if any ``` ### Code snippet <!--Expose the python code you want us to test--> ```python import grid2op ... # Some code ``` ## Current output <!--Describe the output you have--> ``` The output of the code snippet above ``` ## Expected output <!--Describe the output you desire--> ``` The expected output and/or expected behavior description ```
1,587
26.37931
115
md
Grid2Op
Grid2Op-master/.github/ISSUE_TEMPLATE/documentation.md
--- name: Documentation about: Anything related to the documentation title: '' labels: documentation assignees: '' --- ## Documentation issue description <!--A description of what the problem/suggestion is.--> ## Suggested modifications <!--Be as concise and clear as possible. Ideally we could directly copy paste this code in grid2op documentation / notebook etc. --> ``` Please note: Documentation issues are low priority. Please provide your suggested modifications to increase processing speed. Thanks for your understanding. ``` ## Additional context <!--Add any other context here.-->
599
20.428571
87
md
Grid2Op
Grid2Op-master/.github/ISSUE_TEMPLATE/feature_request.md
--- name: Feature request about: Suggest an idea for this project title: '' labels: enhancement assignees: '' --- ## Is your feature request related to a problem? Please describe. <!--A clear and concise description of what the problem is.--> <!--Ex. I'm always frustrated when [...]--> <!-- Do not forget to include code you are currently running that is frustrating--> Ex. This is what i do: ```python import grid2op env_name = ... env = grid2op.make(env_name, ...) ... ``` ## Describe the solution you'd like <!--A clear and concise description of what you want to happen.--> <!--Don't forget to include the "code of your dream" --> Ex. This is how i would like it to be done: ```python import grid2op env_name = ... env = grid2op.make(env_name, ...) # give an example on how your awesome new feature would behave ``` ## Describe alternatives you've considered <!--A clear and concise description of any alternative solutions or features you've considered.--> ## Additional context <!--Add any other context about the feature request here.-->
1,055
24.142857
83
md
Grid2Op
Grid2Op-master/_profiling/average_time_in_step_no_redisp.py
""" Grid2op schematically does basically the following, during a “step”: 1) load the next productions / loads for all generators loads 2) compile the actions of the agents / loads modifications / opponent / maintenance / hazards into one “setpoint” for the backend 3) Ask the backend to be set to the “setpoint action” above (with “backend.apply_action”) 4) ask the backend to perform a simulation (with backend.next_grid_state which might trigger multiple times the backend.runpf function) 5) read back the internal state of the backend and convert it to an observation This script computes these times for different grid size and different backend """ import warnings import pdb import grid2op from grid2op.Parameters import Parameters from lightsim2grid import LightSimBackend from grid2op.Backend import PandaPowerBackend from tqdm import tqdm TABULATE_AVAIL = False try: from tabulate import tabulate TABULATE_AVAIL = True except ImportError: print("The tabulate package is not installed. Some output might not work properly") NB_TS = 1000 param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True res = {} res_ls = {} res_ls_solver = {} for env_nm in ["l2rpn_case14_sandbox", "l2rpn_neurips_2020_track1", "l2rpn_wcci_2022_dev"]: tmp_ = {} res_ls[env_nm] = {} res_ls_solver[env_nm] = {} for bk_cls, nm_ in zip([PandaPowerBackend, LightSimBackend], ["pandapower", "lightsim"]): tmpp_ = {} with warnings.catch_warnings(): warnings.filterwarnings("ignore") env = grid2op.make(env_nm, test=True, param=param, backend=bk_cls() ) obs = env.reset() env._time_create_bk_act = 0. # 1 and 2 env._time_apply_act = 0. # 1, 2, 3 env._time_powerflow = 0. # 4 env._time_extract_obs = 0. # 5 env._time_step = 0. # total total_ts = 0 ls_preproc = 0. ls_acpf = 0. ls_post_proc = 0. ls_solver = 0. with tqdm(total=NB_TS) as pbar: for i in range(NB_TS): obs, reward, done, info = env.step(env.action_space()) total_ts = i pbar.update() if done: break tmpp_["1_2"] = env._time_create_bk_act / total_ts tmpp_["3"] = (env._time_apply_act - env._time_create_bk_act) / total_ts tmpp_["4"] = (env._time_powerflow) / total_ts tmpp_["5"] = (env._time_extract_obs) / total_ts tmpp_["total"] = (env._time_step) / total_ts tmp_[nm_] = tmpp_ if isinstance(env.backend, LightSimBackend): # special case where I extract more information from LightSimBackend if hasattr(env.backend, "_timer_preproc"): ls_preproc += env.backend._timer_preproc ls_post_proc += env.backend._timer_postproc ls_solver += env.backend._timer_solver ls_acpf += env.backend.comp_time res_ls[env_nm][nm_] = [ls_preproc / total_ts, ls_solver / total_ts, ls_post_proc / total_ts] res_ls_solver[env_nm][nm_] = [ls_solver / total_ts, ls_acpf / total_ts] res[env_nm] = tmp_ tab = [] for env_nm, val in res.items(): for sol_nm, steps in val.items(): tmp_row = [env_nm, sol_nm, f'{1000. * steps["total"]:.1f}', f'{1000. * steps["1_2"]:.2f}', f'{1000. * steps["3"]:.3f}', f'{1000. * steps["4"]:.3f}', f'{1000. * steps["5"]:.3f}' ] tab.append(tmp_row) tab_ls = [] for env_nm, val in res_ls.items(): for sol_nm, steps in val.items(): _step1, _step2, _step3 = steps tmp_row = [env_nm, f'{1000. * _step1:.3f}', f'{1000. * _step2:.3f}', f'{1000. * _step3:.3f}' ] tab_ls.append(tmp_row) tab_ls_solver = [] for env_nm, val in res_ls_solver.items(): for sol_nm, steps in val.items(): _step1, _step2 = steps tmp_row = [env_nm, f'{1000. * _step1:.3f}', f'{1000. * _step2:.3f}' ] tab_ls_solver.append(tmp_row) hds = ["env name", "solver name", "total (ms)", "1&2 (ms)", "3 (ms)", "4 (ms)", "5 (ms)"] if TABULATE_AVAIL: res_github_readme = tabulate(tab, headers=hds, tablefmt="github") print(res_github_readme) else: print(tab) print() print() print() hds_ls = ["env name", "1 (ms)", "2 (ms)", "3 (ms)"] if TABULATE_AVAIL: res_github_readme = tabulate(tab_ls, headers=hds_ls, tablefmt="github") print(res_github_readme) else: print(tab_ls) print() print() print() hds_ls_solver = ["env name", "time solver (ms)", "time to solve (ms)"] if TABULATE_AVAIL: res_github_readme = tabulate(tab_ls_solver, headers=hds_ls_solver, tablefmt="github") print(res_github_readme) else: print(tab_ls_solver)
5,145
34.986014
135
py
Grid2Op
Grid2Op-master/_profiling/profiler_assessment.py
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. # If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, # you can obtain one at http://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 # This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems. """ This file should be used to assess the performance of grid2op in "runner" mode: the loading time are not studied, neither are the import times. Data are loaded only once, when the environment is "done" the programm stops. This corresponds to the situation: you have a trained agent, you want to assess its performance using the runner """ import numpy as np import os from grid2op import make from grid2op.Parameters import Parameters from grid2op.Converter import IdToAct from grid2op.Rules import AlwaysLegal from grid2op.Backend import PandaPowerBackend import cProfile from utils_benchmark import run_env, str2bool, ProfileAgent try: from lightsim2grid.LightSimBackend import LightSimBackend light_sim_avail = True except ImportError: light_sim_avail = False ENV_NAME = "rte_case5_example" ENV_NAME = "rte_case14_realistic" MAX_TS = 1000 class TestAgent(ProfileAgent): def __init__(self, action_space, env_name, action_space_converter=IdToAct, **kwargs_converter): ProfileAgent.__init__(self, action_space, env_name=env_name, action_space_converter=action_space_converter, **kwargs_converter) self.nb_act_done = 0 self.act_this = True def my_act(self, transformed_obs, reward, done=False): if self.act_this: res = self.nb_act_done self.nb_act_done += 1 self.nb_act_done %= len(self.action_space.all_actions) self.act_this = False else: res = -1 self.act_this = True return res def main(max_ts, name, use_lightsim=False, test_env=True): param = Parameters() if use_lightsim: if light_sim_avail: backend = LightSimBackend() else: raise RuntimeError("LightSimBackend not available") else: backend = PandaPowerBackend() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) env_klu = make(name, backend=backend, param=param, gamerules_class=AlwaysLegal, test=test_env) agent = TestAgent(action_space=env_klu.action_space, env_name=name) cp = cProfile.Profile() cp.enable() nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu = run_env(env_klu, max_ts, agent) cp.disable() nm_f, ext = os.path.splitext(__file__) nm_out = "{}_{}_{}.prof".format(nm_f, "lightsim" if use_ls else "pp", name) cp.dump_stats(nm_out) print("You can view profiling results with:\n\tsnakeviz {}".format(nm_out)) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Benchmark pyKLU and Pandapower Backend for an agent that takes every ' 'topological action possible') parser.add_argument('--name', default=ENV_NAME, type=str, help='Environment name to be used for the benchmark.') parser.add_argument('--number', type=int, default=MAX_TS, help='Maximum number of time steps for which the benchamark will be run.') parser.add_argument("--use_ls", type=str2bool, nargs='?', const=True, default=False, help="Use the LightSim2Grid Backend.") parser.add_argument("--no_test", type=str2bool, nargs='?', const=True, default=False, help="Do not use a test environment for the profiling (default to False: meaning you use a test env)") args = parser.parse_args() max_ts = int(args.number) name = str(args.name) use_ls = args.use_ls test_env = not args.no_test main(max_ts, name, use_lightsim=use_ls, test_env=test_env)
4,123
37.185185
126
py
Grid2Op
Grid2Op-master/_profiling/profiler_env_cpy.py
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. # If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, # you can obtain one at http://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 # This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems. """ This file aims at profiling a case where the "simulate" function is heavily used. """ import grid2op import warnings from tqdm import tqdm import os import cProfile import pdb from profiler_simulate import make_env, bk_cls, nm_bk_used def run_env(env, max_step=100): done = False step_cnt = 0 with tqdm(total=max_step) as pbar: while not done: act = env.action_space() obs, reward, done, info = env.step(act) if not done: copy_env(env) step_cnt += 1 if step_cnt > max_step: break pbar.update(1) def copy_env(env): res = env.copy() if __name__ == "__main__": env = make_env() cp = cProfile.Profile() cp.enable() run_env(env) cp.disable() nm_f, ext = os.path.splitext(__file__) nm_out = f"{nm_f}_{nm_bk_used}.prof" cp.dump_stats(nm_out) print("You can view profiling results with:\n\tsnakeviz {}".format(nm_out))
1,452
25.907407
112
py
Grid2Op
Grid2Op-master/_profiling/profiler_simulate.py
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. # If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, # you can obtain one at http://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 # This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems. """ This file aims at profiling a case where the "simulate" function is heavily used. """ import grid2op import warnings try: from lightsim2grid import LightSimBackend bk_cls = LightSimBackend nm_bk_used = "LightSimBackend" print("LightSimBackend used") except ImportError: from grid2op.Backend import PandaPowerBackend bk_cls = PandaPowerBackend nm_bk_used = "PandaPowerBackend" print("PandaPowerBackend used") import os import cProfile import pdb def make_env(): env_name = "l2rpn_icaps_2021" with warnings.catch_warnings(): warnings.filterwarnings("ignore") fake_env = grid2op.make(env_name, test=True) param = fake_env.parameters param.NO_OVERFLOW_DISCONNECTION = True env = grid2op.make(env_name+"_small", backend=LightSimBackend(), param=param) return env def run_env(env): done = False while not done: act = env.action_space() obs, reward, done, info = env.step(act) if not done: simulate(obs, env.action_space()) def simulate(obs, act): simobs, rim_r, sim_d, sim_info = obs.simulate(act) if __name__ == "__main__": env = make_env() cp = cProfile.Profile() cp.enable() run_env(env) cp.disable() nm_f, ext = os.path.splitext(__file__) nm_out = f"{nm_f}_{nm_bk_used}.prof" cp.dump_stats(nm_out) print("You can view profiling results with:\n\tsnakeviz {}".format(nm_out))
1,906
27.893939
112
py
Grid2Op
Grid2Op-master/_profiling/profiler_train.py
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. # If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, # you can obtain one at http://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 # This file is part of Grid2Op, Grid2Op a testbed platform to model sequential decision making in power systems. """ This file should be used to assess the performance of grid2op in "early training" mode: a random agent is used each time its game over the environment is reset """ import numpy as np import os from grid2op import make from grid2op.Chronics import GridStateFromFile from grid2op.Parameters import Parameters from grid2op.Converter import IdToAct from grid2op.Rules import AlwaysLegal from grid2op.Backend import PandaPowerBackend import cProfile from utils_benchmark import run_env_with_reset, str2bool, ProfileAgent try: from lightsim2grid.LightSimBackend import LightSimBackend light_sim_avail = True except ImportError: light_sim_avail = False ENV_NAME = "rte_case5_example" ENV_NAME = "rte_case14_realistic" MAX_TS = 1000 class TestAgent(ProfileAgent): def __init__(self, action_space, env_name, action_space_converter=IdToAct, nb_quiet=0, **kwargs_converter): ProfileAgent.__init__(self, action_space, env_name=env_name, action_space_converter=action_space_converter, **kwargs_converter) self.nb_act_done = 0 self.act_this = 0 self.nb_quiet = nb_quiet self._nb_quiet_1 = self.nb_quiet - 1 self.nb_act = len(self.action_space.all_actions) def my_act(self, transformed_obs, reward, done=False): if self.act_this % self.nb_quiet == self._nb_quiet_1: # do an action res = self.space_prng.randint(self.nb_act) else: # do nothing res = 0 self.act_this += 1 return res def main(max_ts, name, use_lightsim=False): param = Parameters() if use_lightsim: if light_sim_avail: backend = LightSimBackend() else: raise RuntimeError("LightSimBackend not available") else: backend = PandaPowerBackend() # param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) env_klu = make(name, backend=backend, param=param, gamerules_class=AlwaysLegal, test=True, data_feeding_kwargs={"chunk_size": 128, "max_iter": max_ts, "gridvalueClass": GridStateFromFile} ) agent = TestAgent(action_space=env_klu.action_space, env_name=name, nb_quiet=2) agent.seed(42) # nb_quiet = 2 : do a random action once every 2 timesteps agent.seed(42) cp = cProfile.Profile() cp.enable() nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu, reset_count = run_env_with_reset(env_klu, max_ts, agent, seed=69) cp.disable() nm_f, ext = os.path.splitext(__file__) nm_out = "{}_{}_{}.prof".format(nm_f, "lightsim" if use_ls else "pp", name) cp.dump_stats(nm_out) print("You can view profiling results with:\n\tsnakeviz {}".format(nm_out)) print("There were {} resets".format(reset_count)) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Benchmark pyKLU and Pandapower Backend for an agent that takes every ' 'topological action possible') parser.add_argument('--name', default=ENV_NAME, type=str, help='Environment name to be used for the benchmark.') parser.add_argument('--number', type=int, default=MAX_TS, help='Maximum number of time steps for which the benchamark will be run.') parser.add_argument("--use_ls", type=str2bool, nargs='?', const=True, default=False, help="Activate nice mode.") args = parser.parse_args() max_ts = int(args.number) name = str(args.name) use_ls = args.use_ls main(max_ts, name, use_lightsim=use_ls)
4,304
36.763158
120
py
Grid2Op
Grid2Op-master/_profiling/utils_benchmark.py
# Copyright (c) 2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0. # If a copy of the Mozilla Public License, version 2.0 was not distributed with this file, # you can obtain one at http://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 # This file is part of LightSim2grid, LightSim2grid a implements a c++ backend targeting the Grid2Op platform. import time import numpy as np from tqdm import tqdm import argparse from grid2op.Agent import AgentWithConverter from grid2op.Converter import IdToAct class ProfileAgent(AgentWithConverter): def __init__(self, action_space, env_name, action_space_converter=IdToAct, **kwargs_converter ): AgentWithConverter.__init__(self, action_space, action_space_converter=action_space_converter, **kwargs_converter) self.action_space.all_actions = [] # do nothing all_actions_tmp = [action_space()] # powerline switch: disconnection for i in range(action_space.n_line): if env_name == "rte_case14_realistic": if i == 18: continue elif env_name == "rte_case5_example": pass elif env_name == "rte_case118_example" or env_name.startswith("l2rpn_neurips_2020_track2"): if i == 6: continue if i == 26: continue if i == 72: continue if i == 73: continue if i == 80: continue if i == 129: continue if i == 140: continue if i == 176: continue if i == 177: continue elif env_name == "l2rpn_wcci_2020": if i == 2: continue all_actions_tmp.append(action_space.disconnect_powerline(line_id=i)) # other type of actions all_actions_tmp += action_space.get_all_unitary_topologies_set(action_space) # self.action_space.all_actions += action_space.get_all_unitary_redispatch(action_space) if env_name == "rte_case14_realistic": # remove action that makes the powerflow diverge breaking_acts = [action_space({"set_bus": {"lines_or_id": [(7,2), (8,1), (9,1)], "lines_ex_id": [(17,2)], "generators_id": [(2,2)], "loads_id": [(4,1)]}}), action_space({"set_bus": {"lines_or_id": [(10, 2), (11, 1), (19,2)], "lines_ex_id": [(16, 2)], "loads_id": [(5, 1)]}}), action_space({"set_bus": {"lines_or_id": [(5, 1)], "lines_ex_id": [(2, 2)], "generators_id": [(1, 2)], "loads_id": [(1, 1)]}}), action_space({"set_bus": {"lines_or_id": [(6, 2), (15, 2), (16, 1)], "lines_ex_id": [(3, 2), (5, 2)], "loads_id": [(2, 1)]}}), action_space({"set_bus": {"lines_or_id": [(18, 1)], "lines_ex_id": [(15, 2), (19, 2)], }}) ] elif env_name == "rte_case118_example" or env_name.startswith("l2rpn_neurips_2020_track2"): breaking_acts = [action_space({"set_bus": {"lines_or_id": [(100, 2), (129, 1), (173, 2)], # "lines_ex_id": [(17,2)], "generators_id": [(2, 2)], "loads_id": [(6, 1)] }}), action_space({"set_bus": {"lines_or_id": [(100, 2), (129, 1), (173, 2)], # "lines_ex_id": [(17,2)], "generators_id": [(2, 2)], "loads_id": [(6, 2)] }}), action_space({"set_bus": {"lines_or_id": [(100, 2), (129, 1), (173, 2)], # "lines_ex_id": [(17,2)], "generators_id": [(2, 1)], "loads_id": [(6, 1)] }}), action_space({"set_bus": {"lines_or_id": [(140, 1)], "lines_ex_id": [(129, 2)], # "generators_id": [(2, 1)], # "loads_id": [(6, 1)] }}), action_space({"set_bus": {"lines_or_id": [(57, 2), (80, 1), (83, 2)], "lines_ex_id": [(2, 2), (13, 2), (24, 2), (35, 2)], "generators_id": [(6, 2)], "loads_id": [(8, 2)] }}), action_space({"set_bus": {"lines_or_id": [(57, 2), (80, 1), (83, 2)], "lines_ex_id": [(2, 2), (13, 2), (24, 2), (35, 2)], "generators_id": [(6, 2)], "loads_id": [(8, 1)] }}), action_space({"set_bus": {"lines_or_id": [(57, 2), (80, 1), (83, 2)], "lines_ex_id": [(2, 2), (13, 2), (24, 2), (35, 2)], "generators_id": [(6, 1)], "loads_id": [(8, 2)] }}), action_space({"set_bus": {"lines_or_id": [(57, 2), (80, 1), (83, 2)], "lines_ex_id": [(2, 2), (13, 2), (24, 2), (35, 2)], "generators_id": [(6, 1)], "loads_id": [(8, 1)] }}), action_space({"set_bus": {"lines_or_id": [(100, 2), (129, 1), (173, 2)], # "lines_ex_id": [(2, 2), (13, 2), (24, 2), (35, 2)], "generators_id": [(2, 1)], "loads_id": [(6, 2)] }}), ] elif env_name == "l2rpn_wcci_2020": breaking_acts = [action_space({"set_bus": {"lines_or_id": [(5, 2), (6, 2)], "lines_ex_id": [(1, 2), (2, 1), (4, 2), (55, 2)], # "generators_id": [(2, 2)], # "loads_id": [(6, 1)] }}), ] else: breaking_acts = [action_space({"set_bus": {"lines_or_id": [(0,2), (1,2), (2,2), (3,1)], "generators_id": [(0,1)], "loads_id": [(0,1)]}}), ] # filter out actions that break everything all_actions = [] for el in all_actions_tmp: if not el in breaking_acts: all_actions.append(el) # set the action to the action space self.action_space.all_actions = all_actions # add the action "reset everything to bus 1" self.action_space.all_actions.append(action_space({"set_bus": np.ones(action_space.dim_topo, dtype=np.int), "set_line_status": np.ones(action_space.n_line, dtype=np.int)})) def print_res(env_klu, env_pp, nb_ts_klu, nb_ts_pp, time_klu, time_pp, aor_klu, aor_pp, gen_p_klu, gen_p_pp, gen_q_klu, gen_q_pp): print("Overall speed-up of KLU vs pandapower (for grid2opbackend) {:.2f}\n".format(time_pp / time_klu)) print("PyKLU Backend {} time steps in {}s ({:.2f} it/s)".format(nb_ts_klu, time_klu, nb_ts_klu/time_klu)) print("\tTime apply act: {:.2f}ms".format(1000. * env_klu._time_apply_act / nb_ts_klu)) print("\tTime powerflow: {:.2f}ms".format(1000. * env_klu._time_powerflow / nb_ts_klu)) print("\tTime extract observation: {:.2f}ms".format(1000. * env_klu._time_extract_obs / nb_ts_klu)) print("Pandapower Backend {} time steps in {}s ({:.2f} it/s)".format(nb_ts_pp, time_pp, nb_ts_pp/time_pp)) print("\tTime apply act: {:.2f}ms".format(1000. * env_pp._time_apply_act / nb_ts_pp)) print("\tTime powerflow: {:.2f}ms".format(1000. * env_pp._time_powerflow / nb_ts_pp)) print("\tTime extract observation: {:.2f}ms".format(1000. * env_pp._time_extract_obs / nb_ts_pp)) print("Absolute value of the difference for aor: {}".format(np.max(np.abs(aor_klu - aor_pp)))) print("Absolute value of the difference for gen_p: {}".format(np.max(np.abs(gen_p_klu - gen_p_pp)))) print("Absolute value of the difference for gen_q: {}".format(np.max(np.abs(gen_q_klu - gen_q_pp)))) def run_env(env, max_ts, agent): nb_rows = min(env.chronics_handler.max_timestep(), max_ts) aor = np.zeros((nb_rows, env.n_line)) gen_p = np.zeros((nb_rows, env.n_gen)) gen_q = np.zeros((nb_rows, env.n_gen)) obs = env.get_obs() done = False reward = env.reward_range[0] nb_ts = 0 prev_act = None beg_ = time.perf_counter() with tqdm(total=nb_rows) as pbar: while not done: act = agent.act(obs, reward, done) obs, reward, done, info = env.step(act) aor[nb_ts, :] = obs.a_or gen_p[nb_ts, :] = obs.prod_p gen_q[nb_ts, :] = obs.prod_q nb_ts += 1 pbar.update(1) if nb_ts >= max_ts: break # if np.sum(obs.line_status) < obs.n_line - 1 * (nb_ts % 2 == 1): # print("There is a bug following action; {}".format(act)) prev_act = act # if done: # print(act) end_ = time.perf_counter() total_time = end_ - beg_ return nb_ts, total_time, aor, gen_p, gen_q def run_env_with_reset(env, max_ts, agent, seed=None): nb_rows = min(env.chronics_handler.max_timestep(), max_ts) aor = np.zeros((nb_rows, env.n_line)) gen_p = np.zeros((nb_rows, env.n_gen)) gen_q = np.zeros((nb_rows, env.n_gen)) if seed is not None: env.seed(seed) obs = env.reset() done = False reward = env.reward_range[0] nb_ts = 0 beg_ = time.perf_counter() reset_count = 0 with tqdm(total=nb_rows) as pbar: while not done: act = agent.act(obs, reward, done) obs, reward, done, info = env.step(act) aor[nb_ts, :] = obs.a_or gen_p[nb_ts, :] = obs.prod_p gen_q[nb_ts, :] = obs.prod_q nb_ts += 1 pbar.update(1) if nb_ts >= max_ts: break if done: # I reset reward = env.reward_range[0] obs = env.reset() reset_count += 1 done = False end_ = time.perf_counter() total_time = end_ - beg_ return nb_ts, total_time, aor, gen_p, gen_q, reset_count def str2bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
13,078
49.693798
122
py
Grid2Op
Grid2Op-master/binder/environment.yml
name: grid2op-environment channels: - conda-forge dependencies: - python - numpy - keras - pip - pip: - grid2op[challenge] - l2rpn-baselines - jyquickhelper - numpy - numba - keras - seaborn - plotly - imageio - ray[rllib, default]
284
13.25
25
yml
Grid2Op
Grid2Op-master/docs/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../')) # -- Project information ----------------------------------------------------- project = 'Grid2Op' copyright = '2019, RTE France' author = 'Benjamin Donnot' # The full version, including alpha/beta/rc tags release = '1.9.1' version = '1.9' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.imgmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', # 'builder', 'sphinx.ext.extlinks', 'sphinx.ext.napoleon', 'sphinxcontrib_trio', "sphinx_rtd_theme", # toc of modules 'autodocsumm', # 'sphinx.ext.autosectionlabel', # 'details', #'exception_hierarchy', # for pdf # 'rst2pdf.pdfbuilder' ] # Add any paths that contain templates here, relative to this directory. templates_path = [] #'_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_experimental_html5_writer = True html_theme = "sphinx_rtd_theme" #"alabaster" #'basic' # 'alabaster' highlight_language = 'python3' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # for pdf pdf_documents = [('index', u'rst2pdf', u'Grid2op documentation', u'B. DONNOT'),] def setup(app): # app.add_javascript('custom.js') app.add_js_file('custom.js') if app.config.language == 'ja': app.config.intersphinx_mapping['py'] = ('https://docs.python.org/ja/3', None)
2,752
30.284091
85
py