Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathinit.lua
More file actions
Latest commit
754 lines (702 loc) · 24 KB
/
Copy pathinit.lua
File metadata and controls
754 lines (702 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
----------------------------------------------------------------------
--
-- Copyright (c) 2011 Clement Farabet
-- (c) 2008 David Manura (for the OptionParser)
--
-- Permission is hereby granted, free of charge, to any person obtaining
-- a copy of this software and associated documentation files (the
-- "Software"), to deal in the Software without restriction, including
-- without limitation the rights to use, copy, modify, merge, publish,
-- distribute, sublicense, and/or sell copies of the Software, and to
-- permit persons to whom the Software is furnished to do so, subject to
-- the following conditions:
--
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--
----------------------------------------------------------------------
-- description:
-- xlua - a package that provides a better Lua prompt, and a few
-- methods to deal with the namespace, argument unpacking
-- and so on...
--
-- history:
-- July 7, 2011, 12:49AM - added OptionParser from D. Manura
-- June 30, 2011, 4:54PM - creation - Clement Farabet
----------------------------------------------------------------------
localos=require'os'
localsys=require'sys'
localio=require'io'
localmath=require'math'
localtorch=require'torch'
xlua= {}
local_protect_= {}
fork,vinpairs(_G) do
table.insert(_protect_, k)
end
-- extra files
require'xlua.OptionParser'
require'xlua.Profiler'
----------------------------------------------------------------------
-- better print function
----------------------------------------------------------------------
functionxlua.print(obj,...)
iftype(obj) =='table' then
localmt=getmetatable(obj)
ifmtandmt.__tostring__then
io.write(mt.__tostring__(obj))
else
localtos=tostring(obj)
localobj_w_usage=false
iftosandnotstring.find(tos,'table: ') then
ifobj.usageandtype(obj.usage) =='string' then
io.write(obj.usage)
io.write('\n\nFIELDS:\n')
obj_w_usage=true
else
io.write(tos..':\n')
end
end
io.write('{')
localtab=''
localidx=1
fork,vinpairs(obj) do
ifidx>1thenio.write(',\n') end
iftype(v) =='userdata' then
io.write(tab..'[' ..k..']' ..' = <userdata>')
else
localtostr=tostring(v):gsub('\n','\\n')
if#tostr>40then
localtostrshort=tostr:sub(1,40) ..sys.COLORS.none
io.write(tab..'[' ..tostring(k) ..']' ..' = ' ..tostrshort..' ... ')
else
io.write(tab..'[' ..tostring(k) ..']' ..' = ' ..tostr)
end
end
tab=''
idx=idx+1
end
io.write('}')
ifobj_w_usagethen
io.write('')
end
end
else
io.write(tostring(obj))
end
ifselect('#',...) >0then
io.write('')
print(...)
else
io.write('\n')
end
end
rawset(_G, 'xprint', xlua.print)
----------------------------------------------------------------------
-- log all session, by replicating stdout to a file
----------------------------------------------------------------------
functionxlua.log(file, append)
os.execute('mkdir ' .. (sys.uname() ~='windows' and'-p ' or'') ..' "' ..sys.dirname(file) ..'"')
localmode='w'
ifappendthenmode='a' end
localf=assert(io.open(file,mode))
io._write=io.write
_G._print=_G.print
_G.print=xlua.print
io.write=function(...)
io._write(...)
localarg= {...}
fori=1,select('#',...) do
f:write(arg[i])
end
f:flush()
end
end
----------------------------------------------------------------------
-- clear all globals
----------------------------------------------------------------------
functionxlua.clearall()
fork,vinpairs(_G) do
localprotected=false
locallib=false
fori,pinipairs(_protect_) do
ifk==pthenprotected=trueend
end
forpinpairs(package.loaded) do
ifk==pthenlib=trueend
end
ifnotprotectedthen
_G[k] =nil
iflibthenpackage.loaded[k] =nilend
end
end
collectgarbage()
end
----------------------------------------------------------------------
-- clear one variable
----------------------------------------------------------------------
functionxlua.clear(var)
_G[var] =nil
collectgarbage()
end
----------------------------------------------------------------------
-- prints globals
----------------------------------------------------------------------
functionxlua.who()
localuser= {}
locallibs= {}
fork,vinpairs(_G) do
localprotected=false
locallib=false
fori,pinipairs(_protect_) do
ifk==pthenprotected=trueend
end
forpinpairs(package.loaded) do
ifk==pandp~='_G' thenlib=trueend
end
iflibthen
table.insert(libs, k)
elseifnotprotectedthen
user[k] =_G[k]
end
end
xlua.print('')
xlua.print('Global Libs:')
xlua.print(libs)
xlua.print('')
xlua.print('Global Vars:')
xlua.print(user)
xlua.print('')
end
----------------------------------------------------------------------
-- time
----------------------------------------------------------------------
functionxlua.formatTime(seconds)
-- decompose:
localfloor=math.floor
localdays=floor(seconds/3600/24)
seconds=seconds-days*3600*24
localhours=floor(seconds/3600)
seconds=seconds-hours*3600
localminutes=floor(seconds/60)
seconds=seconds-minutes*60
localsecondsf=floor(seconds)
seconds=seconds-secondsf
localmillis=floor(seconds*1000)
-- string
localf=''
locali=1
ifdays>0thenf=f..days..'D' i=i+1end
ifhours>0andi<=2thenf=f..hours..'h' i=i+1end
ifminutes>0andi<=2thenf=f..minutes..'m' i=i+1end
ifsecondsf>0andi<=2thenf=f..secondsf..'s' i=i+1end
ifmillis>0andi<=2thenf=f..millis..'ms' i=i+1end
iff=='' thenf='0ms' end
-- return formatted time
returnf
end
localformatTime=xlua.formatTime
----------------------------------------------------------------------
-- progress bar
----------------------------------------------------------------------
do
localfunctiongetTermLength()
ifsys.uname() =='windows' thenreturn80end
localtputf=io.popen('tput cols', 'r')
localw=tonumber(tputf:read('*a'))
localrc= {tputf:close()}
ifrc[3] ==0thenreturnw
elsereturn80end
end
localbarDone=true
localprevious=-1
localtm=''
localtimer
localtimes
localindices
localtermLength=math.min(getTermLength(), 120)
functionxlua.progress(current, goal)
-- defaults:
localbarLength=termLength-34
localsmoothing=100
localmaxfps=10
-- Compute percentage
localpercent=math.floor(((current) *barLength) /goal)
-- start new bar
if (barDoneand ((previous==-1) or (percent<previous))) then
barDone=false
previous=-1
tm=''
timer=torch.Timer()
times= {timer:time().real}
indices= {current}
else
io.write('\r')
end
--if (percent ~= previous and not barDone) then
if (notbarDone) then
previous=percent
-- print bar
io.write(' [')
fori=1,barLengthdo
if (i<percent) thenio.write('=')
elseif (i==percent) thenio.write('>')
elseio.write('.') end
end
io.write('] ')
fori=1,termLength-barLength-4doio.write('') end
fori=1,termLength-barLength-4doio.write('\b') end
-- time stats
localelapsed=timer:time().real
localstep= (elapsed-times[1]) / (current-indices[1])
ifcurrent==indices[1] thenstep=0end
localremaining=math.max(0,(goal-current)*step)
table.insert(indices, current)
table.insert(times, elapsed)
if#indices>smoothingthen
indices=table.splice(indices)
times=table.splice(times)
end
-- Print remaining time when running or total time when done.
if (percent<barLength) then
tm=' ETA: ' ..formatTime(remaining)
else
tm=' Tot: ' ..formatTime(elapsed)
end
tm=tm..' | Step: ' ..formatTime(step)
io.write(tm)
-- go back to center of bar, and print progress
fori=1,5+#tm+barLength/2doio.write('\b') end
io.write('', current, '/', goal, '')
-- reset for next bar
if (percent==barLength) then
barDone=true
io.write('\n')
end
-- flush
io.write('\r')
io.flush()
end
end
end
--------------------------------------------------------------------------------
-- prints an error with nice formatting. If domain is provided, it is used as
-- following: <domain> msg
--------------------------------------------------------------------------------
functionxlua.error(message, domain, usage)
localc=sys.COLORS
ifdomainthen
message='<' ..domain..'> ' ..message
end
localcol_msg=c.Red..tostring(message) ..c.none
ifusagethen
col_msg=col_msg..'\n' ..usage
end
error(col_msg)
end
rawset(_G, 'xerror', xlua.error)
--------------------------------------------------------------------------------
-- provides standard try/catch functions
--------------------------------------------------------------------------------
functionxlua.trycatch(try,catch)
localok,err=pcall(try)
ifnotokthencatch(err) end
end
--------------------------------------------------------------------------------
-- returns true if package is installed, rather than crashing stupidly :-)
--------------------------------------------------------------------------------
functionxlua.installed(package)
localfound=false
localp=package.path..';' ..package.cpath
forpathinp:gfind('.-;') do
path=path:gsub(';',''):gsub('?',package)
ifsys.filep(path) then
found=true
p=path
break
end
end
returnfound,p
end
--------------------------------------------------------------------------------
-- try to load a package, and doesn't crash if not found !
-- optionally try to install it from luarocks, and then load it.
--
-- @param package package to load
-- @param luarocks if true, then try to install missing package with luarocks
-- @param server specify a luarocks server
--------------------------------------------------------------------------------
functionxlua.require(package,luarocks,server)
localloaded
localload=function() loaded=require(package) end
localok,err=pcall(load)
ifnotokthen
print(err)
print('warning: <' ..package..'> could not be loaded (is it installed?)')
returnfalse
end
returnloaded
end
rawset(_G, 'xrequire', xlua.require)
--http://lua-users.org/wiki/TableUtils
localfunctiontable_val_to_str ( v )
if"string" ==type( v ) then
v=string.gsub( v, "\n", "\\n" )
ifstring.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
return"'" ..v.."'"
end
return'"' ..string.gsub(v,'"', '\\"' ) ..'"'
else
return"table" ==type( v ) andxlua.table2string( v ) ortostring( v )
end
end
localfunctiontable_key_to_str ( k )
if"string" ==type( k ) andstring.match( k, "^[_%a][_%a%d]*$" ) then
returnk
else
return"[" ..table_val_to_str( k ) .."]"
end
end
functionxlua.table2string(tbl, newline)
localresult, done= {}, {}
fork, vinipairs( tbl ) do
table.insert( result, table_val_to_str( v ) )
done[ k ] =true
end
locals="="
ifnewlinethen
s=" : "
end
fork, vinpairs( tbl ) do
ifnotdone[ k ] then
localline=table_key_to_str( k ) ..s..table_val_to_str( v )
table.insert(result, line)
end
end
localres
ifnewlinethen
res="{\n" ..table.concat( result, "\n" ) .."\n}"
else
res="{" ..table.concat( result, "," ) .."}"
end
returnres
end
--------------------------------------------------------------------------------
-- standard usage function: used to display automated help for functions
--
-- @param funcname function name
-- @param description description of the function
-- @param example usage example
-- @param ... [optional] arguments
--------------------------------------------------------------------------------
functionxlua.usage(funcname, description, example, ...)
localc=sys.COLORS
localstyle= {
banner='+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++',
list=c.blue..'> ' ..c.none,
title=c.Magenta,
pre=c.cyan,
em=c.Black,
img=c.red,
link=c.red,
code=c.green,
none=c.none
}
localstr=style.banner..'\n'
str=str..style.title..funcname..style.none..'\n'
ifdescriptionthen
str=str..'\n' ..description..'\n'
end
str=str..'\n' ..style.list..'usage:\n' ..style.pre
-- named arguments:
localargs= {...}
ifargs[1].tabledthen
args=args[1].tabled
end
ifargs[1].argthen
str=str..funcname..'{\n'
fori,paraminipairs(args) do
localkey
ifparam.reqthen
key='' ..param.arg..' = ' ..param.type
else
key=' [' ..param.arg..' = ' ..param.type..']'
end
-- align:
whilekey:len() <40do
key=key..''
end
str=str..key..'-- ' ..param.help
iftype(param.default) =='table' then
str=str..' [default = ' ..xlua.table2string(param.default) ..']'
elseifparam.defaultorparam.default==falsethen
str=str..' [default = ' ..tostring(param.default) ..']'
elseifparam.defaultathen
str=str..' [default == ' ..param.defaulta..']'
end
str=str..'\n'
end
str=str..'}\n'
-- unnamed args:
else
localidx=1
whiletruedo
localparam
str=str..funcname..'(\n'
whiletruedo
param=args[idx]
idx=idx+1
ifnotparamorparam=='' thenbreakend
localkey
ifparam.reqthen
key='' ..param.type
else
key=' [' ..param.type..']'
end
-- align:
whilekey:len() <40do
key=key..''
end
str=str..key..'-- ' ..param.help..'\n'
end
str=str..')\n'
ifnotparamthenbreakend
end
end
str=str..style.none
ifexamplethen
str=str..'\n' ..style.pre..example..style.none..'\n'
end
str=str..style.banner
returnstr
end
--------------------------------------------------------------------------------
-- standard argument function: used to handle named arguments, and
-- display automated help for functions
--------------------------------------------------------------------------------
functionxlua.unpack(args, funcname, description, ...)
-- put args in table
localdefs= {...}
-- generate usage string as a closure:
-- this way the function only gets called when an error occurs
localfusage=function()
localexample
if#defs>1then
example=funcname..'{' ..defs[2].arg..'=' ..defs[2].type..', '
..defs[1].arg..'=' ..defs[1].type..'}\n'
example=example..funcname..'(' ..defs[1].type..',' ..' ...)'
end
returnxlua.usage(funcname, description, example, {tabled=defs})
end
localusage= {}
setmetatable(usage, {__tostring=fusage})
-- get args
localiargs= {}
if#args==0then
print(usage)
xlua.error('error')
elseif#args==1andtype(args[1]) =='table' and#args[1] ==0
andnot (torchandtorch.typename(args[1]) ~=nil) then
-- named args
iargs=args[1]
else
-- ordered args
fori=1,select('#',...) do
iargs[defs[i].arg] =args[i]
end
end
-- check/set arguments
localdargs= {}
fori=1,#defsdo
localdef=defs[i]
-- is value requested ?
ifdef.reqandiargs[def.arg] ==nilthen
localc=sys.COLORS
print(c.Red..'missing argument: ' ..def.arg..c.none)
print(usage)
xlua.error('error')
end
-- get value or default
dargs[def.arg] =iargs[def.arg]
ifdargs[def.arg] ==nilthen
dargs[def.arg] =def.default
end
ifdargs[def.arg] ==nilanddef.defaultathen
dargs[def.arg] =dargs[def.defaulta]
end
dargs[i] =dargs[def.arg]
end
-- return usage too
dargs.usage=usage
-- stupid lua bug: we return all args by hand
ifdargs[65] then
xlua.error('<xlua.unpack> oups, cant deal with more than 64 arguments :-)')
end
-- return modified args
returndargs,
dargs[1], dargs[2], dargs[3], dargs[4], dargs[5], dargs[6], dargs[7], dargs[8],
dargs[9], dargs[10], dargs[11], dargs[12], dargs[13], dargs[14], dargs[15], dargs[16],
dargs[17], dargs[18], dargs[19], dargs[20], dargs[21], dargs[22], dargs[23], dargs[24],
dargs[25], dargs[26], dargs[27], dargs[28], dargs[29], dargs[30], dargs[31], dargs[32],
dargs[33], dargs[34], dargs[35], dargs[36], dargs[37], dargs[38], dargs[39], dargs[40],
dargs[41], dargs[42], dargs[43], dargs[44], dargs[45], dargs[46], dargs[47], dargs[48],
dargs[49], dargs[50], dargs[51], dargs[52], dargs[53], dargs[54], dargs[55], dargs[56],
dargs[57], dargs[58], dargs[59], dargs[60], dargs[61], dargs[62], dargs[63], dargs[64]
end
--------------------------------------------------------------------------------
-- standard argument function for classes: used to handle named arguments, and
-- display automated help for functions
-- auto inits the self with usage
--------------------------------------------------------------------------------
functionxlua.unpack_class(object, args, funcname, description, ...)
localdargs=xlua.unpack(args, funcname, description, ...)
fork,vinpairs(dargs) do
iftype(k) ~='number' then
object[k] =v
end
end
end
--------------------------------------------------------------------------------
-- module help function
--
-- @param module module
-- @param name module name
-- @param description description of the module
--------------------------------------------------------------------------------
functionxlua.usage_module(module, name, description)
localc=sys.COLORS
localhasglobals=false
localstr=c.magenta
localstr=str..'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n'
str=str..'PACKAGE:\n' ..name..'\n'
ifdescriptionthen
str=str..'\nDESC:\n' ..description..'\n'
end
str=str..'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
str=str..c.none
-- register help
localmt=getmetatable(module) or {}
setmetatable(module,mt)
mt.__tostring=function() returnstrend
returnstr
end
--------------------------------------------------------------------------------
-- splicing: remove elements from a table
--------------------------------------------------------------------------------
functiontable.splice(tbl, start, length)
length=lengthor1
start=startor1
localendd=start+length
localspliced= {}
localremainder= {}
fori,eltinipairs(tbl) do
ifi<startori>=enddthen
table.insert(spliced, elt)
else
table.insert(remainder, elt)
end
end
returnspliced, remainder
end
--------------------------------------------------------------------------------
-- prune: remove duplicates from a table
-- if a hash function is provided, it is used to produce a unique hash for each
-- element in the input table.
-- if a merge function is provided, it defines how duplicate entries are merged,
-- otherwise, a random entry is picked.
--------------------------------------------------------------------------------
functiontable.prune(tbl, hashfunc, merge)
localhashes= {}
localhash=hashfuncorfunction(a) returnaend
ifmergethen
fori,vinipairs(tbl) do
ifnothashes[hash(v)] then
hashes[hash(v)] =v
else
hashes[hash(v)] =merge(v, hashes[hash(v)])
end
end
else
fori,vinipairs(tbl) do
hashes[hash(v)] =v
end
end
localntbl= {}
for_,vinpairs(hashes) do
table.insert(ntbl, v)
end
returnntbl
end
--------------------------------------------------------------------------------
-- split a string using a pattern
--------------------------------------------------------------------------------
functionstring.split(str, pat)
localt= {} -- NOTE: use {n = 0} in Lua-5.0
localfpat="(.-)" ..pat
locallast_end=1
locals, e, cap=str:find(fpat, 1)
whilesdo
ifs~=1orcap~="" then
table.insert(t,cap)
end
last_end=e+1
s, e, cap=str:find(fpat, last_end)
end
iflast_end<=#strthen
cap=str:sub(last_end)
table.insert(t, cap)
end
returnt
end
--------------------------------------------------------------------------------
-- eval: just a shortcut to parse strings into symbols
-- example:
-- assert( string.tosymbol('madgraph.Image.File') == madgraph.Image.File )
--------------------------------------------------------------------------------
functionstring.tosymbol(str)
localok,result=pcall(loadstring('return ' ..str))
ifnotokthen
error(result)
elseifnotresultthen
error('symbol "' ..str..'" does not exist')
else
returnresult
end
end
--------------------------------------------------------------------------------
-- parses arguments passed as ENV variables
-- example:
-- learningRate=1e-3 nesterov=false th train.lua
-- opt = xlua.envparams{learningRate=1e-2, nesterov=true}
--------------------------------------------------------------------------------
functionxlua.envparams(default)
localparams= {}
fork, vinpairs(default) do
params[k] =v
ifos.getenv(k) ~=nilthen
localv_new=os.getenv(k)
iftype(v) =="number" then
v_new=tonumber(v_new)
end
iftype(v) =="boolean" then
ifv_new=="false" orv_new=="False" then
v_new=false
elseifv_new=="true" orv_new=="True" then
v_new=true
end
end
assert(v_new~=nil)
params[k] =v_new
end
end
returnparams
end
returnxlua