def test_abilab(self): """Testing abilab""" abilab.abiopen_ext2class_table() assert abilab.abifile_subclass_from_filename("GSR.nc") is not None assert len(abilab.dir2abifiles(top=abidata.dirpath)) assert len(abilab.dir2abifiles(top=abidata.dirpath, recurse=False)) == 1 with self.assertRaises(ValueError): abilab.abifile_subclass_from_filename("foobar") assert abilab.isabifile("foo_GSR.nc") assert not abilab.isabifile("foobar") import pandas df = pandas.DataFrame({"a": [1, 2], "b": [3, 4]}) abilab.print_dataframe(df, title="foo") d = abilab.software_stack() assert d assert not abilab.abicheck(verbose=1) abilab.abipy_logo1() abilab.abipy_logo2() abilab.abipy_logo3() assert not abilab.in_notebook() abilab.enable_notebook(with_seaborn=True) assert abilab.in_notebook() abilab.disable_notebook() assert not abilab.in_notebook()
def test_abilab(self): """Testing abilab""" abilab.abiopen_ext2class_table() assert abilab.abifile_subclass_from_filename("GSR.nc") is not None assert len(abilab.dir2abifiles(top=abidata.dirpath)) assert len(abilab.dir2abifiles(top=abidata.dirpath, recurse=False)) == 1 with self.assertRaises(ValueError): abilab.abifile_subclass_from_filename("foobar") assert abilab.isabifile("foo_GSR.nc") assert not abilab.isabifile("foobar") import pandas df = pandas.DataFrame({"a": [1, 2], "b": [3, 4]}) abilab.print_dataframe(df, title="foo") d = abilab.software_stack() assert d assert not abilab.abicheck(verbose=1) abilab.abipy_logo1() abilab.abipy_logo2() abilab.abipy_logo3() assert not abilab.in_notebook() abilab.enable_notebook(with_seaborn=True) assert abilab.in_notebook() abilab.disable_notebook() assert not abilab.in_notebook()
def from_filename(filename): """ Static factory function that instanciates the appropriate subclass of `NcFilePopupMenu` Returns None if the extesion of filename is not supported. """ # Find the AbinitNcFile subclass associated to files. try: file_class = abifile_subclass_from_filename(filename) except KeyError: if filename.endswith(".nc"): NcFilePopupMenu() return None # Check whether a subclass handles this file.. # Fallback to a simple PopupMenu if no match. def allsubclasses(cls): """Returns the set of subclasses of cls.""" children = [cls] for sc in cls.__subclasses__(): if sc.__subclasses__(): for k in sc.__subclasses__(): children.extend(allsubclasses(k)) else: children.append(sc) return set(children) for cls in allsubclasses(PopupMenu): if cls.handle_file_class(file_class): return cls() else: if filename.endswith(".nc"): NcFilePopupMenu() return PopupMenu()
def from_filename(filename): """ Static factory function that instanciates the appropriate subclass of `NcFilePopupMenu` Returns None if the extesion of filename is not supported. """ # Find the AbinitNcFile subclass associated to files. try: file_class = abifile_subclass_from_filename(filename) except KeyError: if filename.endswith(".nc"): NcFilePopupMenu() return None # Check whether a subclass handles this file.. # Fallback to a simple PopupMenu if no match. def allsubclasses(cls): """Returns the set of subclasses of cls.""" children = [cls] for sc in cls.__subclasses__(): if sc.__subclasses__(): for k in sc.__subclasses__(): children.extend(allsubclasses(k)) else: children.append(sc) return set(children) for cls in allsubclasses(PopupMenu): if cls.handle_file_class(file_class): return cls() else: if filename.endswith(".nc"): NcFilePopupMenu() return PopupMenu()
def test_abilab(self): """Testing abilab""" abilab.abiopen_ext2class_table() assert abilab.abifile_subclass_from_filename("GSR.nc") is not None assert len(abilab.dir2abifiles(top=abidata.dirpath)) assert len(abilab.dir2abifiles(top=abidata.dirpath, recurse=False)) == 1 with self.assertRaises(ValueError): abilab.abifile_subclass_from_filename("foobar") assert abilab.isabifile("foo_GSR.nc") assert not abilab.isabifile("foobar") import pandas df = pandas.DataFrame({"a": [1, 2], "b": [3, 4]}) abilab.print_dataframe(df, title="foo") d = abilab.software_stack() assert d filepath = self.get_tmpname(text=True, suffix=".json") data = {"foo": "bar"} abilab.mjson_write(data, filepath, indent=4) data = abilab.mjson_load(filepath) assert data["foo"] == "bar" same_data = abilab.mjson_loads(json.dumps(data)) assert len(same_data) == len(data) assert same_data["foo"] == data["foo"] assert not abilab.abicheck(verbose=1) abilab.abipy_logo1() abilab.abipy_logo2() abilab.abipy_logo3() assert not abilab.in_notebook() abilab.enable_notebook(with_seaborn=True) assert abilab.in_notebook() abilab.disable_notebook() assert not abilab.in_notebook() assert abilab.install_config_files(workdir=self.mkdtemp()) == 0
def test_abilab(self): """Testing abilab""" abilab.abiopen_ext2class_table() assert abilab.abifile_subclass_from_filename("GSR.nc") is not None assert len(abilab.dir2abifiles(top=abidata.dirpath)) with self.assertRaises(ValueError): abilab.abifile_subclass_from_filename("foobar") assert abilab.isabifile("foo_GSR.nc") assert not abilab.isabifile("foobar") d = abilab.software_stack() assert d assert not abilab.abicheck(verbose=1) abilab.abipy_logo1() abilab.abipy_logo2() abilab.abipy_logo3()
def main(): def show_examples_and_exit(err_msg=None, error_code=1): """Display the usage of the script.""" sys.stderr.write(get_epilog()) if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n") sys.exit(error_code) parser = get_parser(with_epilog=True) # Parse the command line. try: options = parser.parse_args() except Exception: show_examples_and_exit(error_code=1) # loglevel is bound to the string value obtained from the command line argument. # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug import logging numeric_level = getattr(logging, options.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.loglevel) logging.basicConfig(level=numeric_level) if options.verbose > 2: print(options) if not os.path.exists(options.filepath): raise RuntimeError("%s: no such file" % options.filepath) if not options.notebook: # Start ipython shell with namespace abifile = abilab.abiopen(options.filepath) if options.print: if hasattr(abifile, "to_string"): print(abifile.to_string(verbose=options.verbose)) else: print(abifile) return 0 import IPython # Use embed because I don't know how to show a header with start_ipython. IPython.embed( header= "The Abinit file is bound to the `abifile` variable.\nTry `print(abifile)`" ) else: # Call specialized method if the object is a NotebookWriter # else generate simple notebook by calling `make_and_open_notebook` cls = abilab.abifile_subclass_from_filename(options.filepath) if hasattr(cls, "make_and_open_notebook"): if hasattr(cls, "__exit__"): with abilab.abiopen(options.filepath) as abifile: return abifile.make_and_open_notebook( foreground=options.foreground) else: abifile = abilab.abiopen(options.filepath) return abifile.make_and_open_notebook( foreground=options.foreground) else: return make_and_open_notebook(options) return 0
def main(): def show_examples_and_exit(err_msg=None, error_code=1): """Display the usage of the script.""" sys.stderr.write(get_epilog()) if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n") sys.exit(error_code) parser = get_parser(with_epilog=True) # Parse the command line. try: options = parser.parse_args() except Exception: show_examples_and_exit(error_code=1) # loglevel is bound to the string value obtained from the command line argument. # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug import logging numeric_level = getattr(logging, options.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.loglevel) logging.basicConfig(level=numeric_level) if options.verbose > 2: print(options) if options.mpl_backend is not None: # Set matplotlib backend import matplotlib matplotlib.use(options.mpl_backend) if options.seaborn: # Use seaborn settings. import seaborn as sns sns.set(context=options.seaborn, style='darkgrid', palette='deep', font='sans-serif', font_scale=1, color_codes=False, rc=None) if not os.path.exists(options.filepath): raise RuntimeError("%s: no such file" % options.filepath) if not options.notebook: abifile = abilab.abiopen(options.filepath) if options.print: # Print object to terminal. if hasattr(abifile, "to_string"): print(abifile.to_string(verbose=options.verbose)) else: print(abifile) return 0 elif options.expose: # Generate matplotlib plots automatically. if hasattr(abifile, "to_string"): print(abifile.to_string(verbose=options.verbose)) else: print(abifile) if not hasattr(abifile, "expose"): raise TypeError("Object of type `%s` does not implement expose method" % type(abifile)) abifile.expose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) return 0 # Start ipython shell with namespace # Use embed because I don't know how to show a header with start_ipython. import IPython IPython.embed(header="The Abinit file is bound to the `abifile` variable.\nTry `print(abifile)`") else: # Call specialized method if the object is a NotebookWriter # else generate simple notebook by calling `make_and_open_notebook` cls = abilab.abifile_subclass_from_filename(options.filepath) if hasattr(cls, "make_and_open_notebook"): if hasattr(cls, "__exit__"): with abilab.abiopen(options.filepath) as abifile: return abifile.make_and_open_notebook(foreground=options.foreground) else: abifile = abilab.abiopen(options.filepath) return abifile.make_and_open_notebook(foreground=options.foreground) else: return make_and_open_notebook(options) return 0
def main(): def show_examples_and_exit(err_msg=None, error_code=1): """Display the usage of the script.""" sys.stderr.write(get_epilog()) if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n") sys.exit(error_code) parser = get_parser(with_epilog=True) # Parse the command line. try: options = parser.parse_args() except Exception: show_examples_and_exit(error_code=1) # loglevel is bound to the string value obtained from the command line argument. # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug import logging numeric_level = getattr(logging, options.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.loglevel) logging.basicConfig(level=numeric_level) if options.verbose > 2: print(options) if options.mpl_backend is not None: # Set matplotlib backend import matplotlib matplotlib.use(options.mpl_backend) if options.seaborn: # Use seaborn settings. import seaborn as sns sns.set(context=options.seaborn, style='darkgrid', palette='deep', font='sans-serif', font_scale=1, color_codes=False, rc=None) if not os.path.exists(options.filepath): raise RuntimeError("%s: no such file" % options.filepath) if not options.notebook: abifile = abilab.abiopen(options.filepath) if options.print: # Print object to terminal. if hasattr(abifile, "to_string"): print(abifile.to_string(verbose=options.verbose)) else: print(abifile) return 0 elif options.expose: # Generate matplotlib plots automatically. if hasattr(abifile, "to_string"): print(abifile.to_string(verbose=options.verbose)) else: print(abifile) if hasattr(abifile, "expose"): abifile.expose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) else: if not hasattr(abifile, "yield_figs"): raise TypeError( "Object of type `%s` does not implement (expose or yield_figs methods" % type(abifile)) from abipy.tools.plotting import MplExpose with MplExpose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) as e: e(abifile.yield_figs()) return 0 # Start ipython shell with namespace # Use embed because I don't know how to show a header with start_ipython. import IPython IPython.embed( header= "The Abinit file is bound to the `abifile` variable.\nTry `print(abifile)`" ) else: # Call specialized method if the object is a NotebookWriter # else generate simple notebook by calling `make_and_open_notebook` cls = abilab.abifile_subclass_from_filename(options.filepath) if hasattr(cls, "make_and_open_notebook"): if hasattr(cls, "__exit__"): with abilab.abiopen(options.filepath) as abifile: return abifile.make_and_open_notebook( foreground=options.foreground) else: abifile = abilab.abiopen(options.filepath) return abifile.make_and_open_notebook( foreground=options.foreground) else: return make_and_open_notebook(options) return 0
def main(): def str_examples(): s = """\ Usage example: abiopen.py out_GSR.nc abiopen.py out_DDB -nb # To generate jupyter notebook File extensions supported: """ return s + abilab.abiopen_ext2class_table() def show_examples_and_exit(err_msg=None, error_code=1): """Display the usage of the script.""" sys.stderr.write(str_examples()) if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n") sys.exit(error_code) parser = argparse.ArgumentParser( epilog=str_examples(), formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '--loglevel', default="ERROR", type=str, help= "Set the loglevel. Possible values: CRITICAL, ERROR (default), WARNING, INFO, DEBUG" ) parser.add_argument('-V', '--version', action='version', version="%(prog)s version " + abilab.__version__) #parser.add_argument('-v', '--verbose', default=0, action='count', # -vv --> verbose=2 # help='verbose, can be supplied multiple times to increase verbosity') parser.add_argument('-nb', '--notebook', action='store_true', default=False, help="Open file in jupyter notebook") parser.add_argument('--foreground', action='store_true', default=False, help="Run jupyter notebook in the foreground.") parser.add_argument('-p', '--print', action='store_true', default=False, help="Print python object and return.") parser.add_argument( "filepath", help= "File to open. See table below for the list of supported extensions.") # Parse the command line. try: options = parser.parse_args() except Exception: show_examples_and_exit(error_code=1) # loglevel is bound to the string value obtained from the command line argument. # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug import logging numeric_level = getattr(logging, options.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.loglevel) logging.basicConfig(level=numeric_level) options.filepath = os.path.abspath(options.filepath) if not os.path.exists(options.filepath): raise RuntimeError("%s: no such file" % options.filepath) if not options.notebook: # Start ipython shell with namespace abifile = abilab.abiopen(options.filepath) if options.print: print(abifile) return 0 import IPython # Use embed because I don't know how to show a header with start_ipython. IPython.embed( header= "The Abinit file is bound to the `abifile` variable.\nTry `print(abifile)`" ) #IPython.start_ipython(argv=options.argv, # user_ns={"abifile": abifile}, # banner="hello", # banner1="hello1", # header="hello_header", # ) # else: # Call specialized method if the object is a NotebookWriter # else generate simple notebook by calling `make_and_open_notebook` cls = abilab.abifile_subclass_from_filename(options.filepath) if hasattr(cls, "make_and_open_notebook"): if hasattr(cls, "__exit__"): with abilab.abiopen(options.filepath) as abifile: return abifile.make_and_open_notebook( foreground=options.foreground) else: abifile = abilab.abiopen(options.filepath) return abifile.make_and_open_notebook( foreground=options.foreground) else: return make_and_open_notebook(options) return 0