3
3
* NiftyReg
4
4
* dcm2niix
5
5
"""
6
- import glob
7
6
import logging
8
7
import multiprocessing
9
8
import os
10
9
import platform
11
10
import re
12
11
import shutil
13
12
import sys
13
+ from os import fspath , path
14
+ from pathlib import Path
14
15
from subprocess import PIPE , CalledProcessError , check_output , run
15
16
from textwrap import dedent
16
17
18
+ from . import cudasetup as cs
19
+
17
20
if os .getenv ("DISPLAY" , False ):
18
21
from functools import wraps
19
22
from tkinter import Tk
20
23
from tkinter .filedialog import askdirectory as ask
21
24
22
25
@wraps (ask )
23
- def askdirectory ( * args , ** kwargs ):
26
+ def askdir ( title , initialdir ):
24
27
Tk ().withdraw ()
25
- res = ask (* args , ** kwargs )
28
+ res = ask (title = title , initialdir = initialdir )
26
29
Tk ().destroy ()
27
30
return res
28
31
29
32
30
33
else :
31
34
32
- def askdirectory (title = "Folder: " , initialdir = None , name = "" ):
33
- """
34
- decreasing precedence: os.environ[name], raw_input, initialdir
35
+ def askdir (title , initialdir ):
36
+ res = input ( title + ( f" [ { initialdir } ]: " if initialdir else ": " ))
37
+ return initialdir if res == "" else res
35
38
36
- Args:
37
- initialdir (str): default: ~
38
- """
39
- if initialdir is None :
40
- initialdir = os .path .expanduser ("~" )
41
- path = os .environ .get (name , None )
42
- if path is None :
43
- path = input (title )
44
- if path == "" :
45
- return initialdir
46
- return path
47
39
40
+ def askdirectory (title = "Folder" , initialdir = "~" , name = "" ):
41
+ """
42
+ Args:
43
+ initialdir (str): default: "~"
44
+ Returns (str):
45
+ one of (decreasing Precedence):
46
+ - `os.getenv(name)`
47
+ - `input()` or `tkinter.filedialog.askdirectory()`
48
+ - `initialdir`
49
+ """
50
+ initialdir = path .expanduser (initialdir )
51
+ res = os .getenv (name , None )
52
+ return askdir (title , initialdir ) if res is None else res
48
53
49
- from . import cudasetup as cs
50
54
51
55
log = logging .getLogger (__name__ )
52
56
@@ -81,7 +85,7 @@ def askdirectory(title="Folder: ", initialdir=None, name=""):
81
85
82
86
# source and build folder names
83
87
dirsrc = "_src"
84
- dirbld = "_bld"
88
+ dirbld = Path ( "_bld" )
85
89
86
90
# number of threads
87
91
ncpu = multiprocessing .cpu_count ()
@@ -209,8 +213,8 @@ def check_depends(git=1, cuda=1, cmake=1, ninja=1, **kwargs):
209
213
)
210
214
211
215
for bin in set (outdct ) - {"cuda" , "nvcc" , "git" , "cmake" , "ninja" }:
212
- # for p in os.getenv("PATH").split(os. path.pathsep):
213
- # if os. path.isfile(os. path.join(p, bin)):
216
+ # for p in os.getenv("PATH").split(path.pathsep):
217
+ # if path.isfile(path.join(p, bin)):
214
218
# outdct[bin] = True
215
219
# break
216
220
# else:
@@ -270,7 +274,7 @@ def check_version(Cnt, chcklst=None):
270
274
# hdw mu-map list
271
275
if "HMUDIR" in chcklst and "HMUDIR" in Cnt :
272
276
for hi in Cnt ["HMULIST" ]:
273
- if os . path .isfile (os . path .join (Cnt ["HMUDIR" ], hi )):
277
+ if path .isfile (path .join (Cnt ["HMUDIR" ], hi )):
274
278
output ["HMUDIR" ] = True
275
279
else :
276
280
output ["HMUDIR" ] = False
@@ -279,7 +283,7 @@ def check_version(Cnt, chcklst=None):
279
283
return output
280
284
281
285
282
- def download_dcm2niix (Cnt , path ):
286
+ def download_dcm2niix (Cnt , dest ):
283
287
log .info (
284
288
dedent (
285
289
"""\
@@ -291,11 +295,11 @@ def download_dcm2niix(Cnt, path):
291
295
)
292
296
293
297
# -create the installation folder
294
- if not os . path . isdir ( path ):
295
- os .mkdir (path )
296
- binpath = os . path . join ( path , "bin" )
297
- if not os . path . isdir ( binpath ):
298
- os .mkdir (binpath )
298
+ if not dest . is_dir ( ):
299
+ dest .mkdir ()
300
+ binpath = dest / "bin"
301
+ if not binpath . is_dir ( ):
302
+ binpath .mkdir ()
299
303
300
304
import urllib .error
301
305
import urllib .parse
@@ -304,13 +308,13 @@ def download_dcm2niix(Cnt, path):
304
308
305
309
http_dcm = {"Windows" : http_dcm_win , "Linux" : http_dcm_lin , "Darwin" : http_dcm_mac }
306
310
urllib .request .urlretrieve (
307
- http_dcm [platform .system ()], os . path . join ( path , "dcm2niix.zip" )
311
+ http_dcm [platform .system ()], fspath ( dest / "dcm2niix.zip" )
308
312
)
309
313
310
- zipf = zipfile .ZipFile (os . path . join ( path , "dcm2niix.zip" ), "r" )
311
- zipf .extractall (os . path . join ( path , "bin" ))
314
+ zipf = zipfile .ZipFile (fspath ( dest / "dcm2niix.zip" ), "r" )
315
+ zipf .extractall (fspath ( binpath ))
312
316
zipf .close ()
313
- Cnt ["DCM2NIIX" ] = glob . glob ( os . path . join ( os . path . join ( path , "bin" ), " dcm2niix*" ))[ 0 ]
317
+ Cnt ["DCM2NIIX" ] = fspath ( next ( binpath . glob ( " dcm2niix*" )))
314
318
# ensure the permissions are given to the executable
315
319
os .chmod (Cnt ["DCM2NIIX" ], 755 )
316
320
# update the resources.py file in ~/.niftypet
@@ -327,104 +331,86 @@ def install_tool(app, Cnt):
327
331
cwd = os .getcwd ()
328
332
329
333
# pick the target installation folder for tools
330
- if "PATHTOOLS" in Cnt and Cnt ["PATHTOOLS" ] != "" :
331
- path_tools = Cnt ["PATHTOOLS" ]
332
- elif "PATHTOOLS" not in Cnt or Cnt ["PATHTOOLS" ] != "" :
333
- if os .getenv ("DISPLAY" , False ) and platform .system () in ["Linux" , "Windows" ]:
334
- log .info ("DISPLAY: {}" .format (os .environ ["DISPLAY" ]))
335
- dircore = askdirectory (
336
- title = "choose a place for NiftyPET tools" ,
337
- initialdir = os .path .expanduser ("~" ),
338
- )
339
- # get the full (combined path)
340
- path_tools = os .path .join (dircore , Cnt ["DIRTOOLS" ])
341
- else :
342
- try :
343
- path_tools = askdirectory (
344
- title = "Enter path for NiftyPET tools (registration, etc): " ,
345
- name = "PATHTOOLS" ,
346
- )
347
- except Exception :
348
- log .warning (
349
- "manually enter the intended PATHTOOLS in resources.py"
350
- " located in ~/.niftypet/"
351
- )
352
- raise ValueError ("\n e> could not get the path for NiftyPET_tools \n " )
353
- Cnt ["PATHTOOLS" ] = path_tools
354
-
334
+ if Cnt .get ("PATHTOOLS" , None ):
335
+ path_tools = Path (Cnt ["PATHTOOLS" ])
336
+ if not path_tools .is_dir ():
337
+ path_tools .mkdir ()
355
338
else :
356
- if platform .system () == "Linux" :
357
- path_tools = os .path .join (os .path .expanduser ("~" ), Cnt ["DIRTOOLS" ])
358
- elif platform .system () == "Windows" :
359
- path_tools = os .path .join (os .getenv ("LOCALAPPDATA" ), Cnt ["DIRTOOLS" ])
360
- else :
361
- log .error (
339
+ path_tools = Path (
340
+ askdirectory (title = "Path to place NiftyPET tools" , name = "PATHTOOLS" )
341
+ )
342
+ if not path_tools .is_dir ():
343
+ path_tools .mkdir ()
344
+ if path_tools .name != Cnt ["DIRTOOLS" ]:
345
+ path_tools /= Cnt ["DIRTOOLS" ]
346
+ Cnt ["PATHTOOLS" ] = fspath (path_tools )
347
+ if platform .system () not in {"Linux" , "Windows" }:
348
+ raise SystemError (
349
+ dedent (
362
350
"""\
363
- \r =============================================================
364
- \r only Linux and Windows operating systems are supported
365
- \r for the additional tools installation!
366
- \r =============================================================
367
- """
351
+ =============================================================
352
+ Only Linux and Windows operating systems are supported
353
+ for installation of additional tools.
354
+ =============================================================
355
+ """
368
356
)
369
- raise SystemError ("OS not supported!" )
370
- Cnt ["PATHTOOLS" ] = path_tools
357
+ )
371
358
372
359
# create the main tools folder
373
- if not os . path . isdir ( path_tools ):
374
- os .mkdir (path_tools )
360
+ if not path_tools . is_dir ( ):
361
+ path_tools .mkdir ()
375
362
# identify the specific path for the requested app
376
363
if app == "niftyreg" :
377
364
repo = repo_reg
378
365
sha1 = sha1_reg
379
- path = os . path . join ( path_tools , "niftyreg" )
366
+ dest = path_tools / "niftyreg"
380
367
elif app == "dcm2niix" :
381
368
repo = repo_dcm
382
369
sha1 = sha1_dcm
383
- path = os . path . join ( path_tools , "dcm2niix" )
370
+ dest = path_tools / "dcm2niix"
384
371
385
372
if not Cnt ["CMPL_DCM2NIIX" ]:
386
373
# avoid installing from source, instead download the full version:
387
- Cnt = download_dcm2niix (Cnt , path )
374
+ Cnt = download_dcm2niix (Cnt , dest )
388
375
return Cnt
376
+ else :
377
+ raise ValueError (f"unknown tool:{ app } " )
389
378
390
379
# Check if the source folder exists and delete it, if it does
391
- if os .path .isdir (path ):
392
- shutil .rmtree (path )
393
- # Create an empty folder and enter it
394
- os .mkdir (path )
395
- os .chdir (path )
380
+ if dest .is_dir ():
381
+ shutil .rmtree (fspath (dest ))
382
+ dest .mkdir ()
383
+ os .chdir (dest )
396
384
397
385
# clone the git repository
398
386
run (["git" , "clone" , repo , dirsrc ])
399
387
os .chdir (dirsrc )
400
388
log .info ("checking out the specific git version of the software..." )
401
389
run (["git" , "checkout" , sha1 ])
402
- os .chdir ("../" )
390
+ os .chdir (cwd )
403
391
404
- # create the building folder
405
- if not os .path .isdir (dirbld ):
392
+ if not dirbld .is_dir ():
406
393
os .mkdir (dirbld )
407
- # go inside the build folder
408
394
os .chdir (dirbld )
409
-
410
395
# run cmake with arguments
411
396
if platform .system () == "Windows" :
412
- cmd = [
413
- "cmake" ,
414
- "../" + dirsrc ,
415
- "-DBUILD_ALL_DEP=ON" ,
416
- "-DCMAKE_INSTALL_PREFIX=" + path ,
417
- "-G" ,
418
- Cnt ["MSVC_VRSN" ],
419
- ]
420
- run (cmd )
397
+ run (
398
+ [
399
+ "cmake" ,
400
+ "../" + dirsrc ,
401
+ "-DBUILD_ALL_DEP=ON" ,
402
+ f"-DCMAKE_INSTALL_PREFIX={ dest } " ,
403
+ "-G" ,
404
+ Cnt ["MSVC_VRSN" ],
405
+ ]
406
+ )
421
407
run (["cmake" , "--build" , "./" , "--config" , "Release" , "--target" , "install" ])
422
408
elif platform .system () in ["Linux" , "Darwin" ]:
423
409
cmd = [
424
410
"cmake" ,
425
411
"../" + dirsrc ,
426
412
"-DBUILD_ALL_DEP=ON" ,
427
- "-DCMAKE_INSTALL_PREFIX=" + path ,
413
+ f "-DCMAKE_INSTALL_PREFIX={ dest } " ,
428
414
]
429
415
if Cnt ["CMAKE_TLS_PAR" ] != "" :
430
416
cmd .append (Cnt ["CMAKE_TLS_PAR" ])
@@ -449,13 +435,9 @@ def install_tool(app, Cnt):
449
435
450
436
if app == "niftyreg" :
451
437
try :
452
- Cnt ["RESPATH" ] = glob .glob (
453
- os .path .join (os .path .join (path , "bin" ), "reg_resample*" )
454
- )[0 ]
455
- Cnt ["REGPATH" ] = glob .glob (
456
- os .path .join (os .path .join (path , "bin" ), "reg_aladin*" )
457
- )[0 ]
458
- except IndexError :
438
+ Cnt ["RESPATH" ] = fspath (next ((dest / "bin" ).glob ("reg_resample*" )))
439
+ Cnt ["REGPATH" ] = fspath (next ((dest / "bin" ).glob ("reg_aladin*" )))
440
+ except StopIteration :
459
441
log .error ("NiftyReg has NOT been successfully installed." )
460
442
raise SystemError ("Failed Installation (NiftyReg)" )
461
443
# updated the file resources.py
@@ -465,19 +447,16 @@ def install_tool(app, Cnt):
465
447
if not all (chck_niftyreg .values ()):
466
448
log .error ("NiftyReg has NOT been successfully installed." )
467
449
raise SystemError ("Failed Installation (NiftyReg)" )
468
-
469
450
elif app == "dcm2niix" :
470
451
try :
471
- Cnt ["DCM2NIIX" ] = glob .glob (
472
- os .path .join (os .path .join (path , "bin" ), "dcm2niix*" )
473
- )[0 ]
474
- except IndexError :
452
+ Cnt ["DCM2NIIX" ] = fspath (next ((dest / "bin" ).glob ("dcm2niix*" )))
453
+ except StopIteration :
475
454
log .error ("dcm2niix has NOT been successfully installed." )
476
- Cnt = download_dcm2niix (Cnt , path )
455
+ Cnt = download_dcm2niix (Cnt , dest )
477
456
# check the installation:
478
457
if not check_version (Cnt , chcklst = ["DCM2NIIX" ]):
479
458
log .error ("dcm2niix has NOT been successfully compiled from github." )
480
- Cnt = download_dcm2niix (Cnt , path )
459
+ Cnt = download_dcm2niix (Cnt , dest )
481
460
return Cnt
482
461
483
462
@@ -488,10 +467,10 @@ def update_resources(Cnt):
488
467
489
468
# get the local path to NiftyPET resources.py
490
469
path_resources = cs .path_niftypet_local ()
491
- resources_file = os . path .join (path_resources , "resources.py" )
470
+ resources_file = path .join (path_resources , "resources.py" )
492
471
493
472
# update resources.py
494
- if os . path .isfile (resources_file ):
473
+ if path .isfile (resources_file ):
495
474
f = open (resources_file , "r" )
496
475
rsrc = f .read ()
497
476
f .close ()
0 commit comments