1""" 2Global variables used to initialize AbiPy environment in notebooks. 3""" 4from monty.termcolor import cprint 5 6import os 7import tempfile 8 9 10__IN_NOTEBOOK = False 11 12 13def in_notebook(): 14 """True if we are running inside a jupyter notebook (and enable_notebook has been called).""" 15 return __IN_NOTEBOOK 16 17 18def disable_notebook(): 19 """Set ``in_notebook`` flag to False.""" 20 global __IN_NOTEBOOK 21 __IN_NOTEBOOK = False 22 23 24def enable_notebook(with_seaborn=True): 25 """ 26 Set ``in_notebook`` flag to True and activate seaborn settings for notebooks if ``with_seaborn``. 27 """ 28 global __IN_NOTEBOOK 29 __IN_NOTEBOOK = True 30 31 # Use seaborn settings for plots (optional) 32 if with_seaborn: 33 import seaborn as sns 34 sns.set(context='notebook', style='darkgrid', palette='deep', 35 font='sans-serif', font_scale=1, color_codes=False, rc=None) 36 37 38def get_abinb_workdir(): 39 """ 40 Return the absolute path of the scratch directory used to produce 41 and save temporary files when we are runnning inside a jupyter_ notebook. 42 43 .. note: 44 45 Due to web-browser policy, files used in the notebook must be within the current working directory. 46 """ 47 wdir = os.path.join(os.getcwd(), "__abinb_workdir__") 48 if not os.path.exists(wdir): os.mkdir(wdir) 49 return wdir 50 51 52def abinb_mkstemp(force_abinb_workdir=False, use_relpath=False, **kwargs): 53 """ 54 Invoke mkstep with kwargs, return the (fd, name) of the temporary file. 55 kwargs are passed to ``mkstemp`` except for ``dir`` if we are inside a jupyter notebook. 56 57 Args: 58 use_abipy_nbworkdir: 59 use_relpath: Return relative path (os.path.relpath) if True else absolute (default) 60 Relative paths are required if we are gonna use the temporary file in 61 notebooks or in web browers. 62 In this case, the caller is responsbile for calling the function with the correct flag. 63 64 .. example: 65 66 _, filename = abinb_mkstep(suffix="." + ext, text=True) 67 """ 68 if in_notebook() or force_abinb_workdir: 69 d = kwargs.pop("dir", None) 70 if d is not None: 71 cprint("Files should be created inside abipy_nbworkdir if we are inside jupyter or force_abinb_workdir", 72 "yellow") 73 fd, path = tempfile.mkstemp(dir=get_abinb_workdir(), **kwargs) 74 else: 75 fd, path = tempfile.mkstemp(**kwargs) 76 77 if use_relpath: 78 path = os.path.relpath(path) 79 80 return fd, path 81