id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
230,800
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_basis_notes
def get_basis_notes(name, data_dir=None): '''Return a string representing the notes about a specific basis set If the notes are not found, an empty string is returned ''' file_path = _basis_notes_path(name, data_dir) notes_str = fileio.read_notes_file(file_path) if notes_str is None: return "" ref_data = get_reference_data(data_dir) return notes.process_notes(notes_str, ref_data)
python
def get_basis_notes(name, data_dir=None): '''Return a string representing the notes about a specific basis set If the notes are not found, an empty string is returned ''' file_path = _basis_notes_path(name, data_dir) notes_str = fileio.read_notes_file(file_path) if notes_str is None: return "" ref_data = get_reference_data(data_dir) return notes.process_notes(notes_str, ref_data)
[ "def", "get_basis_notes", "(", "name", ",", "data_dir", "=", "None", ")", ":", "file_path", "=", "_basis_notes_path", "(", "name", ",", "data_dir", ")", "notes_str", "=", "fileio", ".", "read_notes_file", "(", "file_path", ")", "if", "notes_str", "is", "None...
Return a string representing the notes about a specific basis set If the notes are not found, an empty string is returned
[ "Return", "a", "string", "representing", "the", "notes", "about", "a", "specific", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L522-L535
230,801
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
has_basis_notes
def has_basis_notes(family, data_dir=None): '''Check if notes exist for a given basis set Returns True if they exist, false otherwise ''' file_path = _basis_notes_path(family, data_dir) return os.path.isfile(file_path)
python
def has_basis_notes(family, data_dir=None): '''Check if notes exist for a given basis set Returns True if they exist, false otherwise ''' file_path = _basis_notes_path(family, data_dir) return os.path.isfile(file_path)
[ "def", "has_basis_notes", "(", "family", ",", "data_dir", "=", "None", ")", ":", "file_path", "=", "_basis_notes_path", "(", "family", ",", "data_dir", ")", "return", "os", ".", "path", ".", "isfile", "(", "file_path", ")" ]
Check if notes exist for a given basis set Returns True if they exist, false otherwise
[ "Check", "if", "notes", "exist", "for", "a", "given", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L539-L546
230,802
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_schema
def get_schema(schema_type): '''Get a schema that can validate BSE JSON files The schema_type represents the type of BSE JSON file to be validated, and can be 'component', 'element', 'table', 'metadata', or 'references'. ''' schema_file = "{}-schema.json".format(schema_type) file_path = os.path.join(_default_schema_dir, schema_file) if not os.path.isfile(file_path): raise RuntimeError('Schema file \'{}\' does not exist, is not readable, or is not a file'.format(file_path)) return fileio.read_schema(file_path)
python
def get_schema(schema_type): '''Get a schema that can validate BSE JSON files The schema_type represents the type of BSE JSON file to be validated, and can be 'component', 'element', 'table', 'metadata', or 'references'. ''' schema_file = "{}-schema.json".format(schema_type) file_path = os.path.join(_default_schema_dir, schema_file) if not os.path.isfile(file_path): raise RuntimeError('Schema file \'{}\' does not exist, is not readable, or is not a file'.format(file_path)) return fileio.read_schema(file_path)
[ "def", "get_schema", "(", "schema_type", ")", ":", "schema_file", "=", "\"{}-schema.json\"", ".", "format", "(", "schema_type", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "_default_schema_dir", ",", "schema_file", ")", "if", "not", "os", "."...
Get a schema that can validate BSE JSON files The schema_type represents the type of BSE JSON file to be validated, and can be 'component', 'element', 'table', 'metadata', or 'references'.
[ "Get", "a", "schema", "that", "can", "validate", "BSE", "JSON", "files" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L549-L562
230,803
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/check.py
_cli_check_data_dir
def _cli_check_data_dir(data_dir): '''Checks that the data dir exists and contains METADATA.json''' if data_dir is None: return None data_dir = os.path.expanduser(data_dir) data_dir = os.path.expandvars(data_dir) if not os.path.isdir(data_dir): raise RuntimeError("Data directory '{}' does not exist or is not a directory".format(data_dir)) if not os.path.isfile(os.path.join(data_dir, 'METADATA.json')): raise RuntimeError("Data directory '{}' does not contain a METADATA.json file".format(data_dir)) return data_dir
python
def _cli_check_data_dir(data_dir): '''Checks that the data dir exists and contains METADATA.json''' if data_dir is None: return None data_dir = os.path.expanduser(data_dir) data_dir = os.path.expandvars(data_dir) if not os.path.isdir(data_dir): raise RuntimeError("Data directory '{}' does not exist or is not a directory".format(data_dir)) if not os.path.isfile(os.path.join(data_dir, 'METADATA.json')): raise RuntimeError("Data directory '{}' does not contain a METADATA.json file".format(data_dir)) return data_dir
[ "def", "_cli_check_data_dir", "(", "data_dir", ")", ":", "if", "data_dir", "is", "None", ":", "return", "None", "data_dir", "=", "os", ".", "path", ".", "expanduser", "(", "data_dir", ")", "data_dir", "=", "os", ".", "path", ".", "expandvars", "(", "data...
Checks that the data dir exists and contains METADATA.json
[ "Checks", "that", "the", "data", "dir", "exists", "and", "contains", "METADATA", ".", "json" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/check.py#L10-L23
230,804
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/check.py
_cli_check_format
def _cli_check_format(fmt): '''Checks that a basis set format exists and if not, raises a helpful exception''' if fmt is None: return None fmt = fmt.lower() if not fmt in api.get_formats(): errstr = "Format '" + fmt + "' does not exist.\n" errstr += "For a complete list of formats, use the 'bse list-formats' command" raise RuntimeError(errstr) return fmt
python
def _cli_check_format(fmt): '''Checks that a basis set format exists and if not, raises a helpful exception''' if fmt is None: return None fmt = fmt.lower() if not fmt in api.get_formats(): errstr = "Format '" + fmt + "' does not exist.\n" errstr += "For a complete list of formats, use the 'bse list-formats' command" raise RuntimeError(errstr) return fmt
[ "def", "_cli_check_format", "(", "fmt", ")", ":", "if", "fmt", "is", "None", ":", "return", "None", "fmt", "=", "fmt", ".", "lower", "(", ")", "if", "not", "fmt", "in", "api", ".", "get_formats", "(", ")", ":", "errstr", "=", "\"Format '\"", "+", "...
Checks that a basis set format exists and if not, raises a helpful exception
[ "Checks", "that", "a", "basis", "set", "format", "exists", "and", "if", "not", "raises", "a", "helpful", "exception" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/check.py#L26-L38
230,805
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/check.py
_cli_check_ref_format
def _cli_check_ref_format(fmt): '''Checks that a reference format exists and if not, raises a helpful exception''' if fmt is None: return None fmt = fmt.lower() if not fmt in api.get_reference_formats(): errstr = "Reference format '" + fmt + "' does not exist.\n" errstr += "For a complete list of formats, use the 'bse list-ref-formats' command" raise RuntimeError(errstr) return fmt
python
def _cli_check_ref_format(fmt): '''Checks that a reference format exists and if not, raises a helpful exception''' if fmt is None: return None fmt = fmt.lower() if not fmt in api.get_reference_formats(): errstr = "Reference format '" + fmt + "' does not exist.\n" errstr += "For a complete list of formats, use the 'bse list-ref-formats' command" raise RuntimeError(errstr) return fmt
[ "def", "_cli_check_ref_format", "(", "fmt", ")", ":", "if", "fmt", "is", "None", ":", "return", "None", "fmt", "=", "fmt", ".", "lower", "(", ")", "if", "not", "fmt", "in", "api", ".", "get_reference_formats", "(", ")", ":", "errstr", "=", "\"Reference...
Checks that a reference format exists and if not, raises a helpful exception
[ "Checks", "that", "a", "reference", "format", "exists", "and", "if", "not", "raises", "a", "helpful", "exception" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/check.py#L41-L53
230,806
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/check.py
_cli_check_role
def _cli_check_role(role): '''Checks that a basis set role exists and if not, raises a helpful exception''' if role is None: return None role = role.lower() if not role in api.get_roles(): errstr = "Role format '" + role + "' does not exist.\n" errstr += "For a complete list of roles, use the 'bse list-roles' command" raise RuntimeError(errstr) return role
python
def _cli_check_role(role): '''Checks that a basis set role exists and if not, raises a helpful exception''' if role is None: return None role = role.lower() if not role in api.get_roles(): errstr = "Role format '" + role + "' does not exist.\n" errstr += "For a complete list of roles, use the 'bse list-roles' command" raise RuntimeError(errstr) return role
[ "def", "_cli_check_role", "(", "role", ")", ":", "if", "role", "is", "None", ":", "return", "None", "role", "=", "role", ".", "lower", "(", ")", "if", "not", "role", "in", "api", ".", "get_roles", "(", ")", ":", "errstr", "=", "\"Role format '\"", "+...
Checks that a basis set role exists and if not, raises a helpful exception
[ "Checks", "that", "a", "basis", "set", "role", "exists", "and", "if", "not", "raises", "a", "helpful", "exception" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/check.py#L56-L68
230,807
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/check.py
_cli_check_basis
def _cli_check_basis(name, data_dir): '''Checks that a basis set exists and if not, raises a helpful exception''' if name is None: return None name = misc.transform_basis_name(name) metadata = api.get_metadata(data_dir) if not name in metadata: errstr = "Basis set '" + name + "' does not exist.\n" errstr += "For a complete list of basis sets, use the 'bse list-basis-sets' command" raise RuntimeError(errstr) return name
python
def _cli_check_basis(name, data_dir): '''Checks that a basis set exists and if not, raises a helpful exception''' if name is None: return None name = misc.transform_basis_name(name) metadata = api.get_metadata(data_dir) if not name in metadata: errstr = "Basis set '" + name + "' does not exist.\n" errstr += "For a complete list of basis sets, use the 'bse list-basis-sets' command" raise RuntimeError(errstr) return name
[ "def", "_cli_check_basis", "(", "name", ",", "data_dir", ")", ":", "if", "name", "is", "None", ":", "return", "None", "name", "=", "misc", ".", "transform_basis_name", "(", "name", ")", "metadata", "=", "api", ".", "get_metadata", "(", "data_dir", ")", "...
Checks that a basis set exists and if not, raises a helpful exception
[ "Checks", "that", "a", "basis", "set", "exists", "and", "if", "not", "raises", "a", "helpful", "exception" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/check.py#L71-L84
230,808
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/check.py
_cli_check_family
def _cli_check_family(family, data_dir): '''Checks that a basis set family exists and if not, raises a helpful exception''' if family is None: return None family = family.lower() if not family in api.get_families(data_dir): errstr = "Basis set family '" + family + "' does not exist.\n" errstr += "For a complete list of families, use the 'bse list-families' command" raise RuntimeError(errstr) return family
python
def _cli_check_family(family, data_dir): '''Checks that a basis set family exists and if not, raises a helpful exception''' if family is None: return None family = family.lower() if not family in api.get_families(data_dir): errstr = "Basis set family '" + family + "' does not exist.\n" errstr += "For a complete list of families, use the 'bse list-families' command" raise RuntimeError(errstr) return family
[ "def", "_cli_check_family", "(", "family", ",", "data_dir", ")", ":", "if", "family", "is", "None", ":", "return", "None", "family", "=", "family", ".", "lower", "(", ")", "if", "not", "family", "in", "api", ".", "get_families", "(", "data_dir", ")", "...
Checks that a basis set family exists and if not, raises a helpful exception
[ "Checks", "that", "a", "basis", "set", "family", "exists", "and", "if", "not", "raises", "a", "helpful", "exception" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/check.py#L87-L99
230,809
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/check.py
_cli_check_readfmt
def _cli_check_readfmt(readfmt): '''Checks that a file type exists and if not, raises a helpful exception''' if readfmt is None: return None readfmt = readfmt.lower() if not readfmt in curate.get_reader_formats(): errstr = "Reader for file type '" + readfmt + "' does not exist.\n" errstr += "For a complete list of file types, use the 'bsecurate get-reader-formats' command" raise RuntimeError(errstr) return readfmt
python
def _cli_check_readfmt(readfmt): '''Checks that a file type exists and if not, raises a helpful exception''' if readfmt is None: return None readfmt = readfmt.lower() if not readfmt in curate.get_reader_formats(): errstr = "Reader for file type '" + readfmt + "' does not exist.\n" errstr += "For a complete list of file types, use the 'bsecurate get-reader-formats' command" raise RuntimeError(errstr) return readfmt
[ "def", "_cli_check_readfmt", "(", "readfmt", ")", ":", "if", "readfmt", "is", "None", ":", "return", "None", "readfmt", "=", "readfmt", ".", "lower", "(", ")", "if", "not", "readfmt", "in", "curate", ".", "get_reader_formats", "(", ")", ":", "errstr", "=...
Checks that a file type exists and if not, raises a helpful exception
[ "Checks", "that", "a", "file", "type", "exists", "and", "if", "not", "raises", "a", "helpful", "exception" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/check.py#L102-L114
230,810
MolSSI-BSE/basis_set_exchange
basis_set_exchange/bundle.py
_create_readme
def _create_readme(fmt, reffmt): ''' Creates the readme file for the bundle Returns a str representing the readme file ''' now = datetime.datetime.utcnow() timestamp = now.strftime('%Y-%m-%d %H:%M:%S UTC') # yapf: disable outstr = _readme_str.format(timestamp=timestamp, bsever=api.version(), fmt=fmt, reffmt=reffmt) # yapf: enable return outstr
python
def _create_readme(fmt, reffmt): ''' Creates the readme file for the bundle Returns a str representing the readme file ''' now = datetime.datetime.utcnow() timestamp = now.strftime('%Y-%m-%d %H:%M:%S UTC') # yapf: disable outstr = _readme_str.format(timestamp=timestamp, bsever=api.version(), fmt=fmt, reffmt=reffmt) # yapf: enable return outstr
[ "def", "_create_readme", "(", "fmt", ",", "reffmt", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "timestamp", "=", "now", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S UTC'", ")", "# yapf: disable", "outstr", "=", "_readme_str", "....
Creates the readme file for the bundle Returns a str representing the readme file
[ "Creates", "the", "readme", "file", "for", "the", "bundle" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/bundle.py#L42-L58
230,811
MolSSI-BSE/basis_set_exchange
basis_set_exchange/bundle.py
_add_to_tbz
def _add_to_tbz(tfile, filename, data_str): ''' Adds string data to a tarfile ''' # Create a bytesio object for adding to a tarfile # https://stackoverflow.com/a/52724508 encoded_data = data_str.encode('utf-8') ti = tarfile.TarInfo(name=filename) ti.size = len(encoded_data) tfile.addfile(tarinfo=ti, fileobj=io.BytesIO(encoded_data))
python
def _add_to_tbz(tfile, filename, data_str): ''' Adds string data to a tarfile ''' # Create a bytesio object for adding to a tarfile # https://stackoverflow.com/a/52724508 encoded_data = data_str.encode('utf-8') ti = tarfile.TarInfo(name=filename) ti.size = len(encoded_data) tfile.addfile(tarinfo=ti, fileobj=io.BytesIO(encoded_data))
[ "def", "_add_to_tbz", "(", "tfile", ",", "filename", ",", "data_str", ")", ":", "# Create a bytesio object for adding to a tarfile", "# https://stackoverflow.com/a/52724508", "encoded_data", "=", "data_str", ".", "encode", "(", "'utf-8'", ")", "ti", "=", "tarfile", ".",...
Adds string data to a tarfile
[ "Adds", "string", "data", "to", "a", "tarfile" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/bundle.py#L79-L89
230,812
MolSSI-BSE/basis_set_exchange
basis_set_exchange/bundle.py
_bundle_generic
def _bundle_generic(bfile, addhelper, fmt, reffmt, data_dir): ''' Loop over all basis sets and add data to an archive Parameters ---------- bfile : object An object that gets passed through to the addhelper function addhelper : function A function that takes bfile and adds data to the bfile fmt : str Format of the basis set to create reffmt : str Format to use for the references data_dir : str Data directory with all the basis set information. Returns ------- None ''' ext = converters.get_format_extension(fmt) refext = refconverters.get_format_extension(reffmt) subdir = 'basis_set_bundle-' + fmt + '-' + reffmt readme_path = os.path.join(subdir, 'README.txt') addhelper(bfile, readme_path, _create_readme(fmt, reffmt)) for name, data, notes in _basis_data_iter(fmt, reffmt, data_dir): for ver, verdata in data.items(): filename = misc.basis_name_to_filename(name) basis_filepath = os.path.join(subdir, '{}.{}{}'.format(filename, ver, ext)) ref_filename = os.path.join(subdir, '{}.{}.ref{}'.format(filename, ver, refext)) bsdata, refdata = verdata addhelper(bfile, basis_filepath, bsdata) addhelper(bfile, ref_filename, refdata) if len(notes) > 0: notes_filename = os.path.join(subdir, filename + '.notes') addhelper(bfile, notes_filename, notes) for fam in api.get_families(data_dir): fam_notes = api.get_family_notes(fam, data_dir) if len(fam_notes) > 0: fam_notes_filename = os.path.join(subdir, fam + '.family_notes') addhelper(bfile, fam_notes_filename, fam_notes)
python
def _bundle_generic(bfile, addhelper, fmt, reffmt, data_dir): ''' Loop over all basis sets and add data to an archive Parameters ---------- bfile : object An object that gets passed through to the addhelper function addhelper : function A function that takes bfile and adds data to the bfile fmt : str Format of the basis set to create reffmt : str Format to use for the references data_dir : str Data directory with all the basis set information. Returns ------- None ''' ext = converters.get_format_extension(fmt) refext = refconverters.get_format_extension(reffmt) subdir = 'basis_set_bundle-' + fmt + '-' + reffmt readme_path = os.path.join(subdir, 'README.txt') addhelper(bfile, readme_path, _create_readme(fmt, reffmt)) for name, data, notes in _basis_data_iter(fmt, reffmt, data_dir): for ver, verdata in data.items(): filename = misc.basis_name_to_filename(name) basis_filepath = os.path.join(subdir, '{}.{}{}'.format(filename, ver, ext)) ref_filename = os.path.join(subdir, '{}.{}.ref{}'.format(filename, ver, refext)) bsdata, refdata = verdata addhelper(bfile, basis_filepath, bsdata) addhelper(bfile, ref_filename, refdata) if len(notes) > 0: notes_filename = os.path.join(subdir, filename + '.notes') addhelper(bfile, notes_filename, notes) for fam in api.get_families(data_dir): fam_notes = api.get_family_notes(fam, data_dir) if len(fam_notes) > 0: fam_notes_filename = os.path.join(subdir, fam + '.family_notes') addhelper(bfile, fam_notes_filename, fam_notes)
[ "def", "_bundle_generic", "(", "bfile", ",", "addhelper", ",", "fmt", ",", "reffmt", ",", "data_dir", ")", ":", "ext", "=", "converters", ".", "get_format_extension", "(", "fmt", ")", "refext", "=", "refconverters", ".", "get_format_extension", "(", "reffmt", ...
Loop over all basis sets and add data to an archive Parameters ---------- bfile : object An object that gets passed through to the addhelper function addhelper : function A function that takes bfile and adds data to the bfile fmt : str Format of the basis set to create reffmt : str Format to use for the references data_dir : str Data directory with all the basis set information. Returns ------- None
[ "Loop", "over", "all", "basis", "sets", "and", "add", "data", "to", "an", "archive" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/bundle.py#L109-L157
230,813
MolSSI-BSE/basis_set_exchange
basis_set_exchange/bundle.py
create_bundle
def create_bundle(outfile, fmt, reffmt, archive_type=None, data_dir=None): ''' Create a single archive file containing all basis sets in a given format Parameters ---------- outfile : str Path to the file to create. Existing files will be overwritten fmt : str Format of the basis set to archive (nwchem, turbomole, ...) reffmt : str Format of the basis set references to archive (nwchem, turbomole, ...) archive_type : str Type of archive to create. Can be 'zip' or 'tbz'. Default is None, which will autodetect based on the outfile name data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- None ''' if archive_type is None: outfile_lower = outfile.lower() for k, v in _bundle_types.items(): if outfile_lower.endswith(v['extension']): archive_type = k break else: raise RuntimeError("Cannot autodetect archive type from file name: {}".format(os.path.basename(outfile))) else: archive_type = archive_type.lower() if not archive_type in _bundle_types: raise RuntimeError("Archive type '{}' is not valid.") _bundle_types[archive_type]['handler'](outfile, fmt, reffmt, data_dir)
python
def create_bundle(outfile, fmt, reffmt, archive_type=None, data_dir=None): ''' Create a single archive file containing all basis sets in a given format Parameters ---------- outfile : str Path to the file to create. Existing files will be overwritten fmt : str Format of the basis set to archive (nwchem, turbomole, ...) reffmt : str Format of the basis set references to archive (nwchem, turbomole, ...) archive_type : str Type of archive to create. Can be 'zip' or 'tbz'. Default is None, which will autodetect based on the outfile name data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- None ''' if archive_type is None: outfile_lower = outfile.lower() for k, v in _bundle_types.items(): if outfile_lower.endswith(v['extension']): archive_type = k break else: raise RuntimeError("Cannot autodetect archive type from file name: {}".format(os.path.basename(outfile))) else: archive_type = archive_type.lower() if not archive_type in _bundle_types: raise RuntimeError("Archive type '{}' is not valid.") _bundle_types[archive_type]['handler'](outfile, fmt, reffmt, data_dir)
[ "def", "create_bundle", "(", "outfile", ",", "fmt", ",", "reffmt", ",", "archive_type", "=", "None", ",", "data_dir", "=", "None", ")", ":", "if", "archive_type", "is", "None", ":", "outfile_lower", "=", "outfile", ".", "lower", "(", ")", "for", "k", "...
Create a single archive file containing all basis sets in a given format Parameters ---------- outfile : str Path to the file to create. Existing files will be overwritten fmt : str Format of the basis set to archive (nwchem, turbomole, ...) reffmt : str Format of the basis set references to archive (nwchem, turbomole, ...) archive_type : str Type of archive to create. Can be 'zip' or 'tbz'. Default is None, which will autodetect based on the outfile name data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- None
[ "Create", "a", "single", "archive", "file", "containing", "all", "basis", "sets", "in", "a", "given", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/bundle.py#L174-L214
230,814
MolSSI-BSE/basis_set_exchange
basis_set_exchange/bundle.py
get_archive_types
def get_archive_types(): ''' Return information related to the types of archives available ''' ret = copy.deepcopy(_bundle_types) for k, v in ret.items(): v.pop('handler') return ret
python
def get_archive_types(): ''' Return information related to the types of archives available ''' ret = copy.deepcopy(_bundle_types) for k, v in ret.items(): v.pop('handler') return ret
[ "def", "get_archive_types", "(", ")", ":", "ret", "=", "copy", ".", "deepcopy", "(", "_bundle_types", ")", "for", "k", ",", "v", "in", "ret", ".", "items", "(", ")", ":", "v", ".", "pop", "(", "'handler'", ")", "return", "ret" ]
Return information related to the types of archives available
[ "Return", "information", "related", "to", "the", "types", "of", "archives", "available" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/bundle.py#L217-L224
230,815
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
merge_element_data
def merge_element_data(dest, sources, use_copy=True): """ Merges the basis set data for an element from multiple sources into dest. The destination is not modified, and a (shallow) copy of dest is returned with the data from sources added. If use_copy is True, then the data merged into dest will be a (deep) copy of that found in sources. Otherwise, data may be shared between dest and sources """ if dest is not None: ret = dest.copy() else: ret = {} if use_copy: sources = copy.deepcopy(sources) # Note that we are not copying notes/data_sources for s in sources: if 'electron_shells' in s: if 'electron_shells' not in ret: ret['electron_shells'] = [] ret['electron_shells'].extend(s['electron_shells']) if 'ecp_potentials' in s: if 'ecp_potentials' in ret: raise RuntimeError('Cannot overwrite existing ECP') ret['ecp_potentials'] = s['ecp_potentials'] ret['ecp_electrons'] = s['ecp_electrons'] if 'references' in s: if 'references' not in ret: ret['references'] = [] for ref in s['references']: if not ref in ret['references']: ret['references'].append(ref) return ret
python
def merge_element_data(dest, sources, use_copy=True): if dest is not None: ret = dest.copy() else: ret = {} if use_copy: sources = copy.deepcopy(sources) # Note that we are not copying notes/data_sources for s in sources: if 'electron_shells' in s: if 'electron_shells' not in ret: ret['electron_shells'] = [] ret['electron_shells'].extend(s['electron_shells']) if 'ecp_potentials' in s: if 'ecp_potentials' in ret: raise RuntimeError('Cannot overwrite existing ECP') ret['ecp_potentials'] = s['ecp_potentials'] ret['ecp_electrons'] = s['ecp_electrons'] if 'references' in s: if 'references' not in ret: ret['references'] = [] for ref in s['references']: if not ref in ret['references']: ret['references'].append(ref) return ret
[ "def", "merge_element_data", "(", "dest", ",", "sources", ",", "use_copy", "=", "True", ")", ":", "if", "dest", "is", "not", "None", ":", "ret", "=", "dest", ".", "copy", "(", ")", "else", ":", "ret", "=", "{", "}", "if", "use_copy", ":", "sources"...
Merges the basis set data for an element from multiple sources into dest. The destination is not modified, and a (shallow) copy of dest is returned with the data from sources added. If use_copy is True, then the data merged into dest will be a (deep) copy of that found in sources. Otherwise, data may be shared between dest and sources
[ "Merges", "the", "basis", "set", "data", "for", "an", "element", "from", "multiple", "sources", "into", "dest", "." ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L11-L50
230,816
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
prune_shell
def prune_shell(shell, use_copy=True): """ Removes exact duplicates of primitives, and condenses duplicate exponents into general contractions Also removes primitives if all coefficients are zero """ new_exponents = [] new_coefficients = [] exponents = shell['exponents'] nprim = len(exponents) # transpose of the coefficient matrix coeff_t = list(map(list, zip(*shell['coefficients']))) # Group by exponents ex_groups = [] for i in range(nprim): for ex in ex_groups: if float(exponents[i]) == float(ex[0]): ex[1].append(coeff_t[i]) break else: ex_groups.append((exponents[i], [coeff_t[i]])) # Now collapse within groups for ex in ex_groups: if len(ex[1]) == 1: # only add if there is a nonzero contraction coefficient if not all([float(x) == 0.0 for x in ex[1][0]]): new_exponents.append(ex[0]) new_coefficients.append(ex[1][0]) continue # ex[1] contains rows of coefficients. The length of ex[1] # is the number of times the exponent is duplicated. Columns represent general contractions. # We want to find the non-zero coefficient in each column, if it exists # The result is a single row with a length representing the number # of general contractions new_coeff_row = [] # so take yet another transpose. ex_coeff = list(map(list, zip(*ex[1]))) for g in ex_coeff: nonzero = [x for x in g if float(x) != 0.0] if len(nonzero) > 1: raise RuntimeError("Exponent {} is duplicated within a contraction".format(ex[0])) if len(nonzero) == 0: new_coeff_row.append(g[0]) else: new_coeff_row.append(nonzero[0]) # only add if there is a nonzero contraction coefficient anywhere for this exponent if not all([float(x) == 0.0 for x in new_coeff_row]): new_exponents.append(ex[0]) new_coefficients.append(new_coeff_row) # take the transpose again, putting the general contraction # as the slowest index new_coefficients = list(map(list, zip(*new_coefficients))) shell['exponents'] = new_exponents shell['coefficients'] = new_coefficients return shell
python
def prune_shell(shell, use_copy=True): new_exponents = [] new_coefficients = [] exponents = shell['exponents'] nprim = len(exponents) # transpose of the coefficient matrix coeff_t = list(map(list, zip(*shell['coefficients']))) # Group by exponents ex_groups = [] for i in range(nprim): for ex in ex_groups: if float(exponents[i]) == float(ex[0]): ex[1].append(coeff_t[i]) break else: ex_groups.append((exponents[i], [coeff_t[i]])) # Now collapse within groups for ex in ex_groups: if len(ex[1]) == 1: # only add if there is a nonzero contraction coefficient if not all([float(x) == 0.0 for x in ex[1][0]]): new_exponents.append(ex[0]) new_coefficients.append(ex[1][0]) continue # ex[1] contains rows of coefficients. The length of ex[1] # is the number of times the exponent is duplicated. Columns represent general contractions. # We want to find the non-zero coefficient in each column, if it exists # The result is a single row with a length representing the number # of general contractions new_coeff_row = [] # so take yet another transpose. ex_coeff = list(map(list, zip(*ex[1]))) for g in ex_coeff: nonzero = [x for x in g if float(x) != 0.0] if len(nonzero) > 1: raise RuntimeError("Exponent {} is duplicated within a contraction".format(ex[0])) if len(nonzero) == 0: new_coeff_row.append(g[0]) else: new_coeff_row.append(nonzero[0]) # only add if there is a nonzero contraction coefficient anywhere for this exponent if not all([float(x) == 0.0 for x in new_coeff_row]): new_exponents.append(ex[0]) new_coefficients.append(new_coeff_row) # take the transpose again, putting the general contraction # as the slowest index new_coefficients = list(map(list, zip(*new_coefficients))) shell['exponents'] = new_exponents shell['coefficients'] = new_coefficients return shell
[ "def", "prune_shell", "(", "shell", ",", "use_copy", "=", "True", ")", ":", "new_exponents", "=", "[", "]", "new_coefficients", "=", "[", "]", "exponents", "=", "shell", "[", "'exponents'", "]", "nprim", "=", "len", "(", "exponents", ")", "# transpose of t...
Removes exact duplicates of primitives, and condenses duplicate exponents into general contractions Also removes primitives if all coefficients are zero
[ "Removes", "exact", "duplicates", "of", "primitives", "and", "condenses", "duplicate", "exponents", "into", "general", "contractions" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L53-L121
230,817
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
prune_basis
def prune_basis(basis, use_copy=True): """ Removes primitives that have a zero coefficient, and removes duplicate primitives and shells This only finds EXACT duplicates, and is meant to be used after other manipulations If use_copy is True, the input basis set is not modified. """ if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue shells = el.pop('electron_shells') shells = [prune_shell(sh, False) for sh in shells] # Remove any duplicates el['electron_shells'] = [] for sh in shells: if sh not in el['electron_shells']: el['electron_shells'].append(sh) return basis
python
def prune_basis(basis, use_copy=True): if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue shells = el.pop('electron_shells') shells = [prune_shell(sh, False) for sh in shells] # Remove any duplicates el['electron_shells'] = [] for sh in shells: if sh not in el['electron_shells']: el['electron_shells'].append(sh) return basis
[ "def", "prune_basis", "(", "basis", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "basis", "=", "copy", ".", "deepcopy", "(", "basis", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ".", "items", "(", ")", ":", ...
Removes primitives that have a zero coefficient, and removes duplicate primitives and shells This only finds EXACT duplicates, and is meant to be used after other manipulations If use_copy is True, the input basis set is not modified.
[ "Removes", "primitives", "that", "have", "a", "zero", "coefficient", "and", "removes", "duplicate", "primitives", "and", "shells" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L124-L152
230,818
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
uncontract_spdf
def uncontract_spdf(basis, max_am=0, use_copy=True): """ Removes sp, spd, spdf, etc, contractions from a basis set The general contractions are replaced by uncontracted versions Contractions up to max_am will be left in place. For example, if max_am = 1, spd will be split into sp and d The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified. """ if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue newshells = [] for sh in el['electron_shells']: # am will be a list am = sh['angular_momentum'] coeff = sh['coefficients'] # if this is an sp, spd,... orbital if len(am) > 1: newsh = sh.copy() newsh['angular_momentum'] = [] newsh['coefficients'] = [] ngen = len(sh['coefficients']) for g in range(ngen): if am[g] > max_am: newsh2 = sh.copy() newsh2['angular_momentum'] = [am[g]] newsh2['coefficients'] = [coeff[g]] newshells.append(newsh2) else: newsh['angular_momentum'].append(am[g]) newsh['coefficients'].append(coeff[g]) newshells.insert(0, newsh) else: newshells.append(sh) el['electron_shells'] = newshells return basis
python
def uncontract_spdf(basis, max_am=0, use_copy=True): if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue newshells = [] for sh in el['electron_shells']: # am will be a list am = sh['angular_momentum'] coeff = sh['coefficients'] # if this is an sp, spd,... orbital if len(am) > 1: newsh = sh.copy() newsh['angular_momentum'] = [] newsh['coefficients'] = [] ngen = len(sh['coefficients']) for g in range(ngen): if am[g] > max_am: newsh2 = sh.copy() newsh2['angular_momentum'] = [am[g]] newsh2['coefficients'] = [coeff[g]] newshells.append(newsh2) else: newsh['angular_momentum'].append(am[g]) newsh['coefficients'].append(coeff[g]) newshells.insert(0, newsh) else: newshells.append(sh) el['electron_shells'] = newshells return basis
[ "def", "uncontract_spdf", "(", "basis", ",", "max_am", "=", "0", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "basis", "=", "copy", ".", "deepcopy", "(", "basis", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ...
Removes sp, spd, spdf, etc, contractions from a basis set The general contractions are replaced by uncontracted versions Contractions up to max_am will be left in place. For example, if max_am = 1, spd will be split into sp and d The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified.
[ "Removes", "sp", "spd", "spdf", "etc", "contractions", "from", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L155-L210
230,819
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
uncontract_general
def uncontract_general(basis, use_copy=True): """ Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified. """ if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue newshells = [] for sh in el['electron_shells']: # See if we actually have to uncontract # Also, don't uncontract sp, spd,.... orbitals # (leave that to uncontract_spdf) if len(sh['coefficients']) == 1 or len(sh['angular_momentum']) > 1: newshells.append(sh) else: if len(sh['angular_momentum']) == 1: for c in sh['coefficients']: # copy, them replace 'coefficients' newsh = sh.copy() newsh['coefficients'] = [c] newshells.append(newsh) el['electron_shells'] = newshells # If use_basis is True, we already made our deep copy return prune_basis(basis, False)
python
def uncontract_general(basis, use_copy=True): if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue newshells = [] for sh in el['electron_shells']: # See if we actually have to uncontract # Also, don't uncontract sp, spd,.... orbitals # (leave that to uncontract_spdf) if len(sh['coefficients']) == 1 or len(sh['angular_momentum']) > 1: newshells.append(sh) else: if len(sh['angular_momentum']) == 1: for c in sh['coefficients']: # copy, them replace 'coefficients' newsh = sh.copy() newsh['coefficients'] = [c] newshells.append(newsh) el['electron_shells'] = newshells # If use_basis is True, we already made our deep copy return prune_basis(basis, False)
[ "def", "uncontract_general", "(", "basis", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "basis", "=", "copy", ".", "deepcopy", "(", "basis", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ".", "items", "(", ")", ...
Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified.
[ "Removes", "the", "general", "contractions", "from", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L213-L251
230,820
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
uncontract_segmented
def uncontract_segmented(basis, use_copy=True): """ Removes the segmented contractions from a basis set This implicitly removes general contractions as well, but will leave sp, spd, ... orbitals alone The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified. """ if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue newshells = [] for sh in el['electron_shells']: exponents = sh['exponents'] nam = len(sh['angular_momentum']) for i in range(len(exponents)): newsh = sh.copy() newsh['exponents'] = [exponents[i]] newsh['coefficients'] = [["1.00000000"] * nam] # Remember to transpose the coefficients newsh['coefficients'] = list(map(list, zip(*newsh['coefficients']))) newshells.append(newsh) el['electron_shells'] = newshells return basis
python
def uncontract_segmented(basis, use_copy=True): if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue newshells = [] for sh in el['electron_shells']: exponents = sh['exponents'] nam = len(sh['angular_momentum']) for i in range(len(exponents)): newsh = sh.copy() newsh['exponents'] = [exponents[i]] newsh['coefficients'] = [["1.00000000"] * nam] # Remember to transpose the coefficients newsh['coefficients'] = list(map(list, zip(*newsh['coefficients']))) newshells.append(newsh) el['electron_shells'] = newshells return basis
[ "def", "uncontract_segmented", "(", "basis", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "basis", "=", "copy", ".", "deepcopy", "(", "basis", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ".", "items", "(", ")"...
Removes the segmented contractions from a basis set This implicitly removes general contractions as well, but will leave sp, spd, ... orbitals alone The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified.
[ "Removes", "the", "segmented", "contractions", "from", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L254-L294
230,821
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
make_general
def make_general(basis, use_copy=True): """ Makes one large general contraction for each angular momentum If use_copy is True, the input basis set is not modified. The output of this function is not pretty. If you want to make it nicer, use sort_basis afterwards. """ zero = '0.00000000' basis = uncontract_spdf(basis, 0, use_copy) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue # See what we have all_am = [] for sh in el['electron_shells']: if not sh['angular_momentum'] in all_am: all_am.append(sh['angular_momentum']) all_am = sorted(all_am) newshells = [] for am in all_am: newsh = { 'angular_momentum': am, 'exponents': [], 'coefficients': [], 'region': '', 'function_type': None, } # Do exponents first for sh in el['electron_shells']: if sh['angular_momentum'] != am: continue newsh['exponents'].extend(sh['exponents']) # Number of primitives in the new shell nprim = len(newsh['exponents']) cur_prim = 0 for sh in el['electron_shells']: if sh['angular_momentum'] != am: continue if newsh['function_type'] is None: newsh['function_type'] = sh['function_type'] # Make sure the shells we are merging have the same function types ft1 = newsh['function_type'] ft2 = sh['function_type'] # Check if one function type is the subset of another # (should handle gto/gto_spherical, etc) if ft1 not in ft2 and ft2 not in ft1: raise RuntimeError("Cannot make general contraction of different function types") ngen = len(sh['coefficients']) for g in range(ngen): coef = [zero] * cur_prim coef.extend(sh['coefficients'][g]) coef.extend([zero] * (nprim - len(coef))) newsh['coefficients'].append(coef) cur_prim += len(sh['exponents']) newshells.append(newsh) el['electron_shells'] = newshells return basis
python
def make_general(basis, use_copy=True): zero = '0.00000000' basis = uncontract_spdf(basis, 0, use_copy) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue # See what we have all_am = [] for sh in el['electron_shells']: if not sh['angular_momentum'] in all_am: all_am.append(sh['angular_momentum']) all_am = sorted(all_am) newshells = [] for am in all_am: newsh = { 'angular_momentum': am, 'exponents': [], 'coefficients': [], 'region': '', 'function_type': None, } # Do exponents first for sh in el['electron_shells']: if sh['angular_momentum'] != am: continue newsh['exponents'].extend(sh['exponents']) # Number of primitives in the new shell nprim = len(newsh['exponents']) cur_prim = 0 for sh in el['electron_shells']: if sh['angular_momentum'] != am: continue if newsh['function_type'] is None: newsh['function_type'] = sh['function_type'] # Make sure the shells we are merging have the same function types ft1 = newsh['function_type'] ft2 = sh['function_type'] # Check if one function type is the subset of another # (should handle gto/gto_spherical, etc) if ft1 not in ft2 and ft2 not in ft1: raise RuntimeError("Cannot make general contraction of different function types") ngen = len(sh['coefficients']) for g in range(ngen): coef = [zero] * cur_prim coef.extend(sh['coefficients'][g]) coef.extend([zero] * (nprim - len(coef))) newsh['coefficients'].append(coef) cur_prim += len(sh['exponents']) newshells.append(newsh) el['electron_shells'] = newshells return basis
[ "def", "make_general", "(", "basis", ",", "use_copy", "=", "True", ")", ":", "zero", "=", "'0.00000000'", "basis", "=", "uncontract_spdf", "(", "basis", ",", "0", ",", "use_copy", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ".", ...
Makes one large general contraction for each angular momentum If use_copy is True, the input basis set is not modified. The output of this function is not pretty. If you want to make it nicer, use sort_basis afterwards.
[ "Makes", "one", "large", "general", "contraction", "for", "each", "angular", "momentum" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L297-L373
230,822
MolSSI-BSE/basis_set_exchange
basis_set_exchange/manip.py
optimize_general
def optimize_general(basis, use_copy=True): """ Optimizes the general contraction using the method of Hashimoto et al .. seealso :: | T. Hashimoto, K. Hirao, H. Tatewaki | 'Comment on Dunning's correlation-consistent basis set' | Chemical Physics Letters v243, Issues 1-2, pp, 190-192 (1995) | https://doi.org/10.1016/0009-2614(95)00807-G """ if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue elshells = el.pop('electron_shells') el['electron_shells'] = [] for sh in elshells: exponents = sh['exponents'] coefficients = sh['coefficients'] nprim = len(exponents) nam = len(sh['angular_momentum']) if nam > 1 or len(coefficients) < 2: el['electron_shells'].append(sh) continue # First, find columns (general contractions) with a single non-zero value single_columns = [idx for idx, c in enumerate(coefficients) if _is_single_column(c)] # Find the corresponding rows that have a value in one of these columns # Note that at this stage, the row may have coefficients in more than one # column. That is ok, we are going to split it off anyway single_rows = [] for col_idx in single_columns: col = coefficients[col_idx] for row_idx in range(nprim): if float(col[row_idx]) != 0.0: single_rows.append(row_idx) # Split those out into new shells, and remove them from the # original shell new_shells_single = [] for row_idx in single_rows: newsh = copy.deepcopy(sh) newsh['exponents'] = [exponents[row_idx]] newsh['coefficients'] = [['1.00000000000']] new_shells_single.append(newsh) exponents = [x for idx, x in enumerate(exponents) if idx not in single_rows] coefficients = [x for idx, x in enumerate(coefficients) if idx not in single_columns] coefficients = [[x for idx, x in enumerate(col) if not idx in single_rows] for col in coefficients] # Remove Zero columns #coefficients = [ x for x in coefficients if not _is_zero_column(x) ] # Find contiguous rectanglar blocks new_shells = [] while len(exponents) > 0: block_rows, block_cols = _find_block(coefficients) # add as a new shell newsh = copy.deepcopy(sh) newsh['exponents'] = [exponents[i] for i in block_rows] newsh['coefficients'] = [[coefficients[colidx][i] for i in block_rows] for colidx in block_cols] new_shells.append(newsh) # Remove from the original exponent/coefficient set exponents = [x for idx, x in enumerate(exponents) if idx not in block_rows] coefficients = [x for idx, x in enumerate(coefficients) if idx not in block_cols] coefficients = [[x for idx, x in enumerate(col) if not idx in block_rows] for col in coefficients] # I do this order to mimic the output of the original BSE el['electron_shells'].extend(new_shells) el['electron_shells'].extend(new_shells_single) # Fix coefficients for completely uncontracted shells to 1.0 for sh in el['electron_shells']: if len(sh['coefficients']) == 1 and len(sh['coefficients'][0]) == 1: sh['coefficients'][0][0] = '1.0000000' return basis
python
def optimize_general(basis, use_copy=True): if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if not 'electron_shells' in el: continue elshells = el.pop('electron_shells') el['electron_shells'] = [] for sh in elshells: exponents = sh['exponents'] coefficients = sh['coefficients'] nprim = len(exponents) nam = len(sh['angular_momentum']) if nam > 1 or len(coefficients) < 2: el['electron_shells'].append(sh) continue # First, find columns (general contractions) with a single non-zero value single_columns = [idx for idx, c in enumerate(coefficients) if _is_single_column(c)] # Find the corresponding rows that have a value in one of these columns # Note that at this stage, the row may have coefficients in more than one # column. That is ok, we are going to split it off anyway single_rows = [] for col_idx in single_columns: col = coefficients[col_idx] for row_idx in range(nprim): if float(col[row_idx]) != 0.0: single_rows.append(row_idx) # Split those out into new shells, and remove them from the # original shell new_shells_single = [] for row_idx in single_rows: newsh = copy.deepcopy(sh) newsh['exponents'] = [exponents[row_idx]] newsh['coefficients'] = [['1.00000000000']] new_shells_single.append(newsh) exponents = [x for idx, x in enumerate(exponents) if idx not in single_rows] coefficients = [x for idx, x in enumerate(coefficients) if idx not in single_columns] coefficients = [[x for idx, x in enumerate(col) if not idx in single_rows] for col in coefficients] # Remove Zero columns #coefficients = [ x for x in coefficients if not _is_zero_column(x) ] # Find contiguous rectanglar blocks new_shells = [] while len(exponents) > 0: block_rows, block_cols = _find_block(coefficients) # add as a new shell newsh = copy.deepcopy(sh) newsh['exponents'] = [exponents[i] for i in block_rows] newsh['coefficients'] = [[coefficients[colidx][i] for i in block_rows] for colidx in block_cols] new_shells.append(newsh) # Remove from the original exponent/coefficient set exponents = [x for idx, x in enumerate(exponents) if idx not in block_rows] coefficients = [x for idx, x in enumerate(coefficients) if idx not in block_cols] coefficients = [[x for idx, x in enumerate(col) if not idx in block_rows] for col in coefficients] # I do this order to mimic the output of the original BSE el['electron_shells'].extend(new_shells) el['electron_shells'].extend(new_shells_single) # Fix coefficients for completely uncontracted shells to 1.0 for sh in el['electron_shells']: if len(sh['coefficients']) == 1 and len(sh['coefficients'][0]) == 1: sh['coefficients'][0][0] = '1.0000000' return basis
[ "def", "optimize_general", "(", "basis", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "basis", "=", "copy", ".", "deepcopy", "(", "basis", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ".", "items", "(", ")", ...
Optimizes the general contraction using the method of Hashimoto et al .. seealso :: | T. Hashimoto, K. Hirao, H. Tatewaki | 'Comment on Dunning's correlation-consistent basis set' | Chemical Physics Letters v243, Issues 1-2, pp, 190-192 (1995) | https://doi.org/10.1016/0009-2614(95)00807-G
[ "Optimizes", "the", "general", "contraction", "using", "the", "method", "of", "Hashimoto", "et", "al" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L438-L523
230,823
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare.py
_reldiff
def _reldiff(a, b): """ Computes the relative difference of two floating-point numbers rel = abs(a-b)/min(abs(a), abs(b)) If a == 0 and b == 0, then 0.0 is returned Otherwise if a or b is 0.0, inf is returned. """ a = float(a) b = float(b) aa = abs(a) ba = abs(b) if a == 0.0 and b == 0.0: return 0.0 elif a == 0 or b == 0.0: return float('inf') return abs(a - b) / min(aa, ba)
python
def _reldiff(a, b): a = float(a) b = float(b) aa = abs(a) ba = abs(b) if a == 0.0 and b == 0.0: return 0.0 elif a == 0 or b == 0.0: return float('inf') return abs(a - b) / min(aa, ba)
[ "def", "_reldiff", "(", "a", ",", "b", ")", ":", "a", "=", "float", "(", "a", ")", "b", "=", "float", "(", "b", ")", "aa", "=", "abs", "(", "a", ")", "ba", "=", "abs", "(", "b", ")", "if", "a", "==", "0.0", "and", "b", "==", "0.0", ":",...
Computes the relative difference of two floating-point numbers rel = abs(a-b)/min(abs(a), abs(b)) If a == 0 and b == 0, then 0.0 is returned Otherwise if a or b is 0.0, inf is returned.
[ "Computes", "the", "relative", "difference", "of", "two", "floating", "-", "point", "numbers" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare.py#L9-L29
230,824
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare.py
_compare_keys
def _compare_keys(element1, element2, key, compare_func, *args): """ Compares a specific key between two elements of a basis set If the key exists in one element but not the other, False is returned. If the key exists in neither element, True is returned. Parameters ---------- element1 : dict Basis info for an element element2 : dict Basis info for another element key : string Key to compare in the two elements compare_func : function Function that returns True if the data under the key is equivalent in both elements args Additional arguments to be passed to compare_Func """ if key in element1 and key in element2: if not compare_func(element1[key], element2[key], *args): return False elif key in element1 or key in element2: return False return True
python
def _compare_keys(element1, element2, key, compare_func, *args): if key in element1 and key in element2: if not compare_func(element1[key], element2[key], *args): return False elif key in element1 or key in element2: return False return True
[ "def", "_compare_keys", "(", "element1", ",", "element2", ",", "key", ",", "compare_func", ",", "*", "args", ")", ":", "if", "key", "in", "element1", "and", "key", "in", "element2", ":", "if", "not", "compare_func", "(", "element1", "[", "key", "]", ",...
Compares a specific key between two elements of a basis set If the key exists in one element but not the other, False is returned. If the key exists in neither element, True is returned. Parameters ---------- element1 : dict Basis info for an element element2 : dict Basis info for another element key : string Key to compare in the two elements compare_func : function Function that returns True if the data under the key is equivalent in both elements args Additional arguments to be passed to compare_Func
[ "Compares", "a", "specific", "key", "between", "two", "elements", "of", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare.py#L32-L60
230,825
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare.py
electron_shells_are_subset
def electron_shells_are_subset(subset, superset, compare_meta=False, rel_tol=0.0): ''' Determine if a list of electron shells is a subset of another If 'subset' is a subset of the 'superset', True is returned. The shells are compared approximately (exponents/coefficients are within a tolerance) If compare_meta is True, the metadata is also compared for exact equality. ''' for item1 in subset: for item2 in superset: if compare_electron_shells(item1, item2, compare_meta, rel_tol): break else: return False return True
python
def electron_shells_are_subset(subset, superset, compare_meta=False, rel_tol=0.0): ''' Determine if a list of electron shells is a subset of another If 'subset' is a subset of the 'superset', True is returned. The shells are compared approximately (exponents/coefficients are within a tolerance) If compare_meta is True, the metadata is also compared for exact equality. ''' for item1 in subset: for item2 in superset: if compare_electron_shells(item1, item2, compare_meta, rel_tol): break else: return False return True
[ "def", "electron_shells_are_subset", "(", "subset", ",", "superset", ",", "compare_meta", "=", "False", ",", "rel_tol", "=", "0.0", ")", ":", "for", "item1", "in", "subset", ":", "for", "item2", "in", "superset", ":", "if", "compare_electron_shells", "(", "i...
Determine if a list of electron shells is a subset of another If 'subset' is a subset of the 'superset', True is returned. The shells are compared approximately (exponents/coefficients are within a tolerance) If compare_meta is True, the metadata is also compared for exact equality.
[ "Determine", "if", "a", "list", "of", "electron", "shells", "is", "a", "subset", "of", "another" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare.py#L147-L166
230,826
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare.py
ecp_pots_are_subset
def ecp_pots_are_subset(subset, superset, compare_meta=False, rel_tol=0.0): ''' Determine if a list of ecp potentials is a subset of another If 'subset' is a subset of the 'superset', True is returned. The potentials are compared approximately (exponents/coefficients are within a tolerance) If compare_meta is True, the metadata is also compared for exact equality. ''' for item1 in subset: for item2 in superset: if compare_ecp_pots(item1, item2, compare_meta, rel_tol): break else: return False return True
python
def ecp_pots_are_subset(subset, superset, compare_meta=False, rel_tol=0.0): ''' Determine if a list of ecp potentials is a subset of another If 'subset' is a subset of the 'superset', True is returned. The potentials are compared approximately (exponents/coefficients are within a tolerance) If compare_meta is True, the metadata is also compared for exact equality. ''' for item1 in subset: for item2 in superset: if compare_ecp_pots(item1, item2, compare_meta, rel_tol): break else: return False return True
[ "def", "ecp_pots_are_subset", "(", "subset", ",", "superset", ",", "compare_meta", "=", "False", ",", "rel_tol", "=", "0.0", ")", ":", "for", "item1", "in", "subset", ":", "for", "item2", "in", "superset", ":", "if", "compare_ecp_pots", "(", "item1", ",", ...
Determine if a list of ecp potentials is a subset of another If 'subset' is a subset of the 'superset', True is returned. The potentials are compared approximately (exponents/coefficients are within a tolerance) If compare_meta is True, the metadata is also compared for exact equality.
[ "Determine", "if", "a", "list", "of", "ecp", "potentials", "is", "a", "subset", "of", "another" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare.py#L221-L240
230,827
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare.py
compare_elements
def compare_elements(element1, element2, compare_electron_shells_meta=False, compare_ecp_pots_meta=False, compare_meta=False, rel_tol=0.0): ''' Determine if the basis information for two elements is the same as another Exponents/coefficients are compared using a tolerance. Parameters ---------- element1 : dict Basis information for an element element2 : dict Basis information for another element compare_electron_shells_meta : bool Compare the metadata of electron shells compare_ecp_pots_meta : bool Compare the metadata of ECP potentials compare_meta : bool Compare the overall element metadata rel_tol : float Maximum relative error that is considered equal ''' if not _compare_keys(element1, element2, 'electron_shells', electron_shells_are_equal, compare_electron_shells_meta, rel_tol): return False if not _compare_keys(element1, element2, 'ecp_potentials', ecp_pots_are_equal, compare_ecp_pots_meta, rel_tol): return False if not _compare_keys(element1, element2, 'ecp_electrons', operator.eq): return False if compare_meta: if not _compare_keys(element1, element2, 'references', operator.eq): return False return True
python
def compare_elements(element1, element2, compare_electron_shells_meta=False, compare_ecp_pots_meta=False, compare_meta=False, rel_tol=0.0): ''' Determine if the basis information for two elements is the same as another Exponents/coefficients are compared using a tolerance. Parameters ---------- element1 : dict Basis information for an element element2 : dict Basis information for another element compare_electron_shells_meta : bool Compare the metadata of electron shells compare_ecp_pots_meta : bool Compare the metadata of ECP potentials compare_meta : bool Compare the overall element metadata rel_tol : float Maximum relative error that is considered equal ''' if not _compare_keys(element1, element2, 'electron_shells', electron_shells_are_equal, compare_electron_shells_meta, rel_tol): return False if not _compare_keys(element1, element2, 'ecp_potentials', ecp_pots_are_equal, compare_ecp_pots_meta, rel_tol): return False if not _compare_keys(element1, element2, 'ecp_electrons', operator.eq): return False if compare_meta: if not _compare_keys(element1, element2, 'references', operator.eq): return False return True
[ "def", "compare_elements", "(", "element1", ",", "element2", ",", "compare_electron_shells_meta", "=", "False", ",", "compare_ecp_pots_meta", "=", "False", ",", "compare_meta", "=", "False", ",", "rel_tol", "=", "0.0", ")", ":", "if", "not", "_compare_keys", "("...
Determine if the basis information for two elements is the same as another Exponents/coefficients are compared using a tolerance. Parameters ---------- element1 : dict Basis information for an element element2 : dict Basis information for another element compare_electron_shells_meta : bool Compare the metadata of electron shells compare_ecp_pots_meta : bool Compare the metadata of ECP potentials compare_meta : bool Compare the overall element metadata rel_tol : float Maximum relative error that is considered equal
[ "Determine", "if", "the", "basis", "information", "for", "two", "elements", "is", "the", "same", "as", "another" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare.py#L258-L299
230,828
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare.py
compare_basis
def compare_basis(bs1, bs2, compare_electron_shells_meta=False, compare_ecp_pots_meta=False, compare_elements_meta=False, compare_meta=False, rel_tol=0.0): ''' Determine if two basis set dictionaries are the same bs1 : dict Full basis information bs2 : dict Full basis information compare_electron_shells_meta : bool Compare the metadata of electron shells compare_ecp_pots_meta : bool Compare the metadata of ECP potentials compare_elements_meta : bool Compare the overall element metadata compare_meta: bool Compare the metadata for the basis set (name, description, etc) rel_tol : float Maximum relative error that is considered equal ''' els1 = sorted(list(bs1['elements'].keys())) els2 = sorted(list(bs2['elements'].keys())) if not els1 == els2: return False for el in els1: if not compare_elements( bs1['elements'][el], bs2['elements'][el], compare_electron_shells_meta=compare_electron_shells_meta, compare_ecp_pots_meta=compare_ecp_pots_meta, compare_meta=compare_elements_meta, rel_tol=rel_tol): print("Element failed:", el) return False if compare_meta: for k in ['name', 'family', 'description', 'revision_description', 'role', 'auxiliaries']: if not _compare_keys(bs1, bs2, k, operator.eq): return False return True
python
def compare_basis(bs1, bs2, compare_electron_shells_meta=False, compare_ecp_pots_meta=False, compare_elements_meta=False, compare_meta=False, rel_tol=0.0): ''' Determine if two basis set dictionaries are the same bs1 : dict Full basis information bs2 : dict Full basis information compare_electron_shells_meta : bool Compare the metadata of electron shells compare_ecp_pots_meta : bool Compare the metadata of ECP potentials compare_elements_meta : bool Compare the overall element metadata compare_meta: bool Compare the metadata for the basis set (name, description, etc) rel_tol : float Maximum relative error that is considered equal ''' els1 = sorted(list(bs1['elements'].keys())) els2 = sorted(list(bs2['elements'].keys())) if not els1 == els2: return False for el in els1: if not compare_elements( bs1['elements'][el], bs2['elements'][el], compare_electron_shells_meta=compare_electron_shells_meta, compare_ecp_pots_meta=compare_ecp_pots_meta, compare_meta=compare_elements_meta, rel_tol=rel_tol): print("Element failed:", el) return False if compare_meta: for k in ['name', 'family', 'description', 'revision_description', 'role', 'auxiliaries']: if not _compare_keys(bs1, bs2, k, operator.eq): return False return True
[ "def", "compare_basis", "(", "bs1", ",", "bs2", ",", "compare_electron_shells_meta", "=", "False", ",", "compare_ecp_pots_meta", "=", "False", ",", "compare_elements_meta", "=", "False", ",", "compare_meta", "=", "False", ",", "rel_tol", "=", "0.0", ")", ":", ...
Determine if two basis set dictionaries are the same bs1 : dict Full basis information bs2 : dict Full basis information compare_electron_shells_meta : bool Compare the metadata of electron shells compare_ecp_pots_meta : bool Compare the metadata of ECP potentials compare_elements_meta : bool Compare the overall element metadata compare_meta: bool Compare the metadata for the basis set (name, description, etc) rel_tol : float Maximum relative error that is considered equal
[ "Determine", "if", "two", "basis", "set", "dictionaries", "are", "the", "same" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare.py#L302-L347
230,829
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/metadata.py
create_metadata_file
def create_metadata_file(output_path, data_dir): '''Creates a METADATA.json file from a data directory The file is written to output_path ''' # Relative path to all (BASIS).metadata.json files meta_filelist, table_filelist, _, _ = get_all_filelist(data_dir) metadata = {} for meta_file_relpath in meta_filelist: # Read in the metadata for a single basis set meta_file_path = os.path.join(data_dir, meta_file_relpath) bs_metadata = read_json_basis(meta_file_path) # Base of the filename for table basis sets # Basename is something like '6-31G.', including the last period base_relpath, meta_filename = os.path.split(meta_file_relpath) base_filename = meta_filename.split('.')[0] + '.' # All the table files that correspond to this metadata file # (relative to data_dir) this_filelist = [ x for x in table_filelist if os.path.dirname(x) == base_relpath and os.path.basename(x).startswith(base_filename) ] # The 'versions' dict that will go into the metadata version_info = {} # Make sure function types are the same function_types = None # For each table basis, compose it for table_file in this_filelist: # Obtain just the filename of the table basis table_filename = os.path.basename(table_file) # Obtain the base filename and version from the filename # The base filename is the part before the first period # (filebase.ver.table.json) table_filebase, ver, _, _ = table_filename.split('.') # Fully compose the basis set from components bs = compose_table_basis(table_file, data_dir) # Elements for which this basis is defined defined_elements = sorted(list(bs['elements'].keys()), key=lambda x: int(x)) # Determine the types of functions contained in the basis # (gto, ecp, etc) if function_types is None: function_types = bs['function_types'] elif function_types != bs['function_types']: raise RuntimeError("Differing function types across versions for " + base_filename) # Create the metadata for this specific version # yapf: disable version_info[ver] = { 'file_relpath': table_file, 'revdesc': bs['revision_description'], 'elements': defined_elements } # yapf: enable # Sort the version dicts version_info = dict(sorted(version_info.items())) # Find the maximum version for this basis latest_ver = max(version_info.keys()) # Create the common metadata for this basis set # display_name and other_names are placeholders to keep order # yapf: disable common_md = { 'display_name': None, 'other_names': None, 'description': bs['description'], 'latest_version': latest_ver, 'basename': base_filename[:-1], # Strip off that trailing period 'relpath': base_relpath, 'family': bs['family'], 'role': bs['role'], 'functiontypes': function_types, 'auxiliaries': bs['auxiliaries'], 'versions': version_info } # yapf: enable # Loop through all the common names, translate them, and then add the data for bs_name in bs_metadata['names']: tr_name = transform_basis_name(bs_name) if tr_name in metadata: raise RuntimeError("Duplicate basis set name: " + tr_name) # Create a new entry, with all the common metadata # Also, store the other names for this basis other_names = bs_metadata['names'].copy() other_names.remove(bs_name) metadata[tr_name] = common_md.copy() metadata[tr_name]['display_name'] = bs_name metadata[tr_name]['other_names'] = other_names # Write out the metadata metadata = dict(sorted(metadata.items())) _write_plain_json(output_path, metadata)
python
def create_metadata_file(output_path, data_dir): '''Creates a METADATA.json file from a data directory The file is written to output_path ''' # Relative path to all (BASIS).metadata.json files meta_filelist, table_filelist, _, _ = get_all_filelist(data_dir) metadata = {} for meta_file_relpath in meta_filelist: # Read in the metadata for a single basis set meta_file_path = os.path.join(data_dir, meta_file_relpath) bs_metadata = read_json_basis(meta_file_path) # Base of the filename for table basis sets # Basename is something like '6-31G.', including the last period base_relpath, meta_filename = os.path.split(meta_file_relpath) base_filename = meta_filename.split('.')[0] + '.' # All the table files that correspond to this metadata file # (relative to data_dir) this_filelist = [ x for x in table_filelist if os.path.dirname(x) == base_relpath and os.path.basename(x).startswith(base_filename) ] # The 'versions' dict that will go into the metadata version_info = {} # Make sure function types are the same function_types = None # For each table basis, compose it for table_file in this_filelist: # Obtain just the filename of the table basis table_filename = os.path.basename(table_file) # Obtain the base filename and version from the filename # The base filename is the part before the first period # (filebase.ver.table.json) table_filebase, ver, _, _ = table_filename.split('.') # Fully compose the basis set from components bs = compose_table_basis(table_file, data_dir) # Elements for which this basis is defined defined_elements = sorted(list(bs['elements'].keys()), key=lambda x: int(x)) # Determine the types of functions contained in the basis # (gto, ecp, etc) if function_types is None: function_types = bs['function_types'] elif function_types != bs['function_types']: raise RuntimeError("Differing function types across versions for " + base_filename) # Create the metadata for this specific version # yapf: disable version_info[ver] = { 'file_relpath': table_file, 'revdesc': bs['revision_description'], 'elements': defined_elements } # yapf: enable # Sort the version dicts version_info = dict(sorted(version_info.items())) # Find the maximum version for this basis latest_ver = max(version_info.keys()) # Create the common metadata for this basis set # display_name and other_names are placeholders to keep order # yapf: disable common_md = { 'display_name': None, 'other_names': None, 'description': bs['description'], 'latest_version': latest_ver, 'basename': base_filename[:-1], # Strip off that trailing period 'relpath': base_relpath, 'family': bs['family'], 'role': bs['role'], 'functiontypes': function_types, 'auxiliaries': bs['auxiliaries'], 'versions': version_info } # yapf: enable # Loop through all the common names, translate them, and then add the data for bs_name in bs_metadata['names']: tr_name = transform_basis_name(bs_name) if tr_name in metadata: raise RuntimeError("Duplicate basis set name: " + tr_name) # Create a new entry, with all the common metadata # Also, store the other names for this basis other_names = bs_metadata['names'].copy() other_names.remove(bs_name) metadata[tr_name] = common_md.copy() metadata[tr_name]['display_name'] = bs_name metadata[tr_name]['other_names'] = other_names # Write out the metadata metadata = dict(sorted(metadata.items())) _write_plain_json(output_path, metadata)
[ "def", "create_metadata_file", "(", "output_path", ",", "data_dir", ")", ":", "# Relative path to all (BASIS).metadata.json files", "meta_filelist", ",", "table_filelist", ",", "_", ",", "_", "=", "get_all_filelist", "(", "data_dir", ")", "metadata", "=", "{", "}", ...
Creates a METADATA.json file from a data directory The file is written to output_path
[ "Creates", "a", "METADATA", ".", "json", "file", "from", "a", "data", "directory" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/metadata.py#L12-L116
230,830
MolSSI-BSE/basis_set_exchange
basis_set_exchange/refconverters/txt.py
write_txt
def write_txt(refs): '''Converts references to plain text format ''' full_str = '\n' lib_citation_desc, lib_citations = get_library_citation() # Add the refs for the libarary at the top full_str += '*' * 80 + '\n' full_str += lib_citation_desc full_str += '*' * 80 + '\n' for r in lib_citations.values(): ref_txt = reference_text(r) ref_txt = textwrap.indent(ref_txt, ' ' * 4) full_str += '{}\n\n'.format(ref_txt) full_str += '*' * 80 + '\n' full_str += "References for the basis set\n" full_str += '*' * 80 + '\n' for ref in refs: full_str += '{}\n'.format(compact_elements(ref['elements'])) for ri in ref['reference_info']: full_str += ' ## {}\n'.format(ri['reference_description']) refdata = ri['reference_data'] if len(refdata) == 0: full_str += ' (...no reference...)\n\n' for k, r in refdata: ref_txt = reference_text(r) ref_txt = textwrap.indent(ref_txt, ' ' * 4) full_str += '{}\n\n'.format(ref_txt) return full_str
python
def write_txt(refs): '''Converts references to plain text format ''' full_str = '\n' lib_citation_desc, lib_citations = get_library_citation() # Add the refs for the libarary at the top full_str += '*' * 80 + '\n' full_str += lib_citation_desc full_str += '*' * 80 + '\n' for r in lib_citations.values(): ref_txt = reference_text(r) ref_txt = textwrap.indent(ref_txt, ' ' * 4) full_str += '{}\n\n'.format(ref_txt) full_str += '*' * 80 + '\n' full_str += "References for the basis set\n" full_str += '*' * 80 + '\n' for ref in refs: full_str += '{}\n'.format(compact_elements(ref['elements'])) for ri in ref['reference_info']: full_str += ' ## {}\n'.format(ri['reference_description']) refdata = ri['reference_data'] if len(refdata) == 0: full_str += ' (...no reference...)\n\n' for k, r in refdata: ref_txt = reference_text(r) ref_txt = textwrap.indent(ref_txt, ' ' * 4) full_str += '{}\n\n'.format(ref_txt) return full_str
[ "def", "write_txt", "(", "refs", ")", ":", "full_str", "=", "'\\n'", "lib_citation_desc", ",", "lib_citations", "=", "get_library_citation", "(", ")", "# Add the refs for the libarary at the top", "full_str", "+=", "'*'", "*", "80", "+", "'\\n'", "full_str", "+=", ...
Converts references to plain text format
[ "Converts", "references", "to", "plain", "text", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/refconverters/txt.py#L11-L45
230,831
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/diff.py
diff_basis_dict
def diff_basis_dict(left_list, right_list): ''' Compute the difference between two sets of basis set dictionaries The result is a list of dictionaries that correspond to each dictionary in `left_list`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the dictionaries in `right_list`. This only works on the shell level, and will only subtract entire shells that are identical. ECP potentials are not affected. The return value contains deep copies of the input data Parameters ---------- left_list : list of dict Dictionaries to use as the base right_list : list of dict Dictionaries of basis data to subtract from each dictionary of `left_list` Returns ---------- list Each object in `left_list` containing data that does not appear in `right_list` ''' ret = [] for bs1 in left_list: res = copy.deepcopy(bs1) for bs2 in right_list: for el in res['elements'].keys(): if not el in bs2['elements']: continue # Element only exist in left eldata1 = res['elements'][el] eldata2 = bs2['elements'][el] s1 = eldata1['electron_shells'] s2 = eldata2['electron_shells'] eldata1['electron_shells'] = subtract_electron_shells(s1, s2) # Remove any empty elements res['elements'] = {k: v for k, v in res['elements'].items() if len(v['electron_shells']) > 0} ret.append(res) return ret
python
def diff_basis_dict(left_list, right_list): ''' Compute the difference between two sets of basis set dictionaries The result is a list of dictionaries that correspond to each dictionary in `left_list`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the dictionaries in `right_list`. This only works on the shell level, and will only subtract entire shells that are identical. ECP potentials are not affected. The return value contains deep copies of the input data Parameters ---------- left_list : list of dict Dictionaries to use as the base right_list : list of dict Dictionaries of basis data to subtract from each dictionary of `left_list` Returns ---------- list Each object in `left_list` containing data that does not appear in `right_list` ''' ret = [] for bs1 in left_list: res = copy.deepcopy(bs1) for bs2 in right_list: for el in res['elements'].keys(): if not el in bs2['elements']: continue # Element only exist in left eldata1 = res['elements'][el] eldata2 = bs2['elements'][el] s1 = eldata1['electron_shells'] s2 = eldata2['electron_shells'] eldata1['electron_shells'] = subtract_electron_shells(s1, s2) # Remove any empty elements res['elements'] = {k: v for k, v in res['elements'].items() if len(v['electron_shells']) > 0} ret.append(res) return ret
[ "def", "diff_basis_dict", "(", "left_list", ",", "right_list", ")", ":", "ret", "=", "[", "]", "for", "bs1", "in", "left_list", ":", "res", "=", "copy", ".", "deepcopy", "(", "bs1", ")", "for", "bs2", "in", "right_list", ":", "for", "el", "in", "res"...
Compute the difference between two sets of basis set dictionaries The result is a list of dictionaries that correspond to each dictionary in `left_list`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the dictionaries in `right_list`. This only works on the shell level, and will only subtract entire shells that are identical. ECP potentials are not affected. The return value contains deep copies of the input data Parameters ---------- left_list : list of dict Dictionaries to use as the base right_list : list of dict Dictionaries of basis data to subtract from each dictionary of `left_list` Returns ---------- list Each object in `left_list` containing data that does not appear in `right_list`
[ "Compute", "the", "difference", "between", "two", "sets", "of", "basis", "set", "dictionaries" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/diff.py#L28-L73
230,832
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/diff.py
diff_json_files
def diff_json_files(left_files, right_files): ''' Compute the difference between two sets of basis set JSON files The output is a set of files that correspond to each file in `left_files`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the files in `right_files`. This only works on the shell level, and will only subtract entire shells that are identical. ECP potentials are not affected. `left_files` and `right_files` are lists of file paths. The output is written to files with the same names as those in `left_files`, but with `.diff` added to the end. If those files exist, they are overwritten. Parameters ---------- left_files : list of str Paths to JSON files to use as the base right_files : list of str Paths to JSON files to subtract from each file of `left_files` Returns ---------- None ''' left_data = [fileio.read_json_basis(x) for x in left_files] right_data = [fileio.read_json_basis(x) for x in right_files] d = diff_basis_dict(left_data, right_data) for idx, diff_bs in enumerate(d): fpath = left_files[idx] fileio.write_json_basis(fpath + '.diff', diff_bs)
python
def diff_json_files(left_files, right_files): ''' Compute the difference between two sets of basis set JSON files The output is a set of files that correspond to each file in `left_files`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the files in `right_files`. This only works on the shell level, and will only subtract entire shells that are identical. ECP potentials are not affected. `left_files` and `right_files` are lists of file paths. The output is written to files with the same names as those in `left_files`, but with `.diff` added to the end. If those files exist, they are overwritten. Parameters ---------- left_files : list of str Paths to JSON files to use as the base right_files : list of str Paths to JSON files to subtract from each file of `left_files` Returns ---------- None ''' left_data = [fileio.read_json_basis(x) for x in left_files] right_data = [fileio.read_json_basis(x) for x in right_files] d = diff_basis_dict(left_data, right_data) for idx, diff_bs in enumerate(d): fpath = left_files[idx] fileio.write_json_basis(fpath + '.diff', diff_bs)
[ "def", "diff_json_files", "(", "left_files", ",", "right_files", ")", ":", "left_data", "=", "[", "fileio", ".", "read_json_basis", "(", "x", ")", "for", "x", "in", "left_files", "]", "right_data", "=", "[", "fileio", ".", "read_json_basis", "(", "x", ")",...
Compute the difference between two sets of basis set JSON files The output is a set of files that correspond to each file in `left_files`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the files in `right_files`. This only works on the shell level, and will only subtract entire shells that are identical. ECP potentials are not affected. `left_files` and `right_files` are lists of file paths. The output is written to files with the same names as those in `left_files`, but with `.diff` added to the end. If those files exist, they are overwritten. Parameters ---------- left_files : list of str Paths to JSON files to use as the base right_files : list of str Paths to JSON files to subtract from each file of `left_files` Returns ---------- None
[ "Compute", "the", "difference", "between", "two", "sets", "of", "basis", "set", "JSON", "files" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/diff.py#L76-L109
230,833
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare_report.py
shells_difference
def shells_difference(s1, s2): """ Computes and prints the differences between two lists of shells If the shells contain a different number primitives, or the lists are of different length, inf is returned. Otherwise, the maximum relative difference is returned. """ max_rdiff = 0.0 nsh = len(s1) if len(s2) != nsh: print("Different number of shells: {} vs {}".format(len(s1), len(s2))) return float('inf') shells1 = sort_shells(s1) shells2 = sort_shells(s2) for n in range(nsh): sh1 = shells1[n] sh2 = shells2[n] if sh1['angular_momentum'] != sh2['angular_momentum']: print("Different angular momentum for shell {}".format(n)) return float('inf') nprim = len(sh1['exponents']) if len(sh2['exponents']) != nprim: print("Different number of primitives for shell {}".format(n)) return float('inf') ngen = len(sh1['coefficients']) if len(sh2['coefficients']) != ngen: print("Different number of general contractions for shell {}".format(n)) return float('inf') for p in range(nprim): e1 = sh1['exponents'][p] e2 = sh2['exponents'][p] r = _reldiff(e1, e2) if r > 0.0: print(" Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r)) max_rdiff = max(max_rdiff, r) for g in range(ngen): c1 = sh1['coefficients'][g][p] c2 = sh2['coefficients'][g][p] r = _reldiff(c1, c2) if r > 0.0: print("Coefficient {:3}: {:20} {:20} -> {:16.8e}".format(p, c1, c2, r)) max_rdiff = max(max_rdiff, r) print() print("Max relative difference for these shells: {}".format(max_rdiff)) return max_rdiff
python
def shells_difference(s1, s2): max_rdiff = 0.0 nsh = len(s1) if len(s2) != nsh: print("Different number of shells: {} vs {}".format(len(s1), len(s2))) return float('inf') shells1 = sort_shells(s1) shells2 = sort_shells(s2) for n in range(nsh): sh1 = shells1[n] sh2 = shells2[n] if sh1['angular_momentum'] != sh2['angular_momentum']: print("Different angular momentum for shell {}".format(n)) return float('inf') nprim = len(sh1['exponents']) if len(sh2['exponents']) != nprim: print("Different number of primitives for shell {}".format(n)) return float('inf') ngen = len(sh1['coefficients']) if len(sh2['coefficients']) != ngen: print("Different number of general contractions for shell {}".format(n)) return float('inf') for p in range(nprim): e1 = sh1['exponents'][p] e2 = sh2['exponents'][p] r = _reldiff(e1, e2) if r > 0.0: print(" Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r)) max_rdiff = max(max_rdiff, r) for g in range(ngen): c1 = sh1['coefficients'][g][p] c2 = sh2['coefficients'][g][p] r = _reldiff(c1, c2) if r > 0.0: print("Coefficient {:3}: {:20} {:20} -> {:16.8e}".format(p, c1, c2, r)) max_rdiff = max(max_rdiff, r) print() print("Max relative difference for these shells: {}".format(max_rdiff)) return max_rdiff
[ "def", "shells_difference", "(", "s1", ",", "s2", ")", ":", "max_rdiff", "=", "0.0", "nsh", "=", "len", "(", "s1", ")", "if", "len", "(", "s2", ")", "!=", "nsh", ":", "print", "(", "\"Different number of shells: {} vs {}\"", ".", "format", "(", "len", ...
Computes and prints the differences between two lists of shells If the shells contain a different number primitives, or the lists are of different length, inf is returned. Otherwise, the maximum relative difference is returned.
[ "Computes", "and", "prints", "the", "differences", "between", "two", "lists", "of", "shells" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare_report.py#L25-L79
230,834
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare_report.py
potentials_difference
def potentials_difference(p1, p2): """ Computes and prints the differences between two lists of potentials If the shells contain a different number primitives, or the lists are of different length, inf is returned. Otherwise, the maximum relative difference is returned. """ max_rdiff = 0.0 np = len(p1) if len(p2) != np: print("Different number of potentials") return float('inf') pots1 = sort_potentials(p1) pots2 = sort_potentials(p2) for n in range(np): pot1 = pots1[n] pot2 = pots2[n] if pot1['angular_momentum'] != pot2['angular_momentum']: print("Different angular momentum for potential {}".format(n)) return float('inf') nprim = len(pot1['gaussian_exponents']) if len(pot2['gaussian_exponents']) != nprim: print("Different number of primitives for potential {}".format(n)) return float('inf') ngen = len(pot1['coefficients']) if len(pot2['coefficients']) != ngen: print("Different number of general contractions for potential {}".format(n)) return float('inf') for p in range(nprim): e1 = pot1['gaussian_exponents'][p] e2 = pot2['gaussian_exponents'][p] r = _reldiff(e1, e2) if r > 0.0: print(" Gaussian Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r)) max_rdiff = max(max_rdiff, r) e1 = pot1['r_exponents'][p] e2 = pot2['r_exponents'][p] r = _reldiff(e1, e2) if r > 0.0: print(" R Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r)) max_rdiff = max(max_rdiff, r) for g in range(ngen): c1 = pot1['coefficients'][g][p] c2 = pot2['coefficients'][g][p] r = _reldiff(c1, c2) if r > 0.0: print(" Coefficient {:3}: {:20} {:20} -> {:16.8e}".format(p, c1, c2, r)) max_rdiff = max(max_rdiff, r) print() print("Max relative difference for these potentials: {}".format(max_rdiff)) return max_rdiff
python
def potentials_difference(p1, p2): max_rdiff = 0.0 np = len(p1) if len(p2) != np: print("Different number of potentials") return float('inf') pots1 = sort_potentials(p1) pots2 = sort_potentials(p2) for n in range(np): pot1 = pots1[n] pot2 = pots2[n] if pot1['angular_momentum'] != pot2['angular_momentum']: print("Different angular momentum for potential {}".format(n)) return float('inf') nprim = len(pot1['gaussian_exponents']) if len(pot2['gaussian_exponents']) != nprim: print("Different number of primitives for potential {}".format(n)) return float('inf') ngen = len(pot1['coefficients']) if len(pot2['coefficients']) != ngen: print("Different number of general contractions for potential {}".format(n)) return float('inf') for p in range(nprim): e1 = pot1['gaussian_exponents'][p] e2 = pot2['gaussian_exponents'][p] r = _reldiff(e1, e2) if r > 0.0: print(" Gaussian Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r)) max_rdiff = max(max_rdiff, r) e1 = pot1['r_exponents'][p] e2 = pot2['r_exponents'][p] r = _reldiff(e1, e2) if r > 0.0: print(" R Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r)) max_rdiff = max(max_rdiff, r) for g in range(ngen): c1 = pot1['coefficients'][g][p] c2 = pot2['coefficients'][g][p] r = _reldiff(c1, c2) if r > 0.0: print(" Coefficient {:3}: {:20} {:20} -> {:16.8e}".format(p, c1, c2, r)) max_rdiff = max(max_rdiff, r) print() print("Max relative difference for these potentials: {}".format(max_rdiff)) return max_rdiff
[ "def", "potentials_difference", "(", "p1", ",", "p2", ")", ":", "max_rdiff", "=", "0.0", "np", "=", "len", "(", "p1", ")", "if", "len", "(", "p2", ")", "!=", "np", ":", "print", "(", "\"Different number of potentials\"", ")", "return", "float", "(", "'...
Computes and prints the differences between two lists of potentials If the shells contain a different number primitives, or the lists are of different length, inf is returned. Otherwise, the maximum relative difference is returned.
[ "Computes", "and", "prints", "the", "differences", "between", "two", "lists", "of", "potentials" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare_report.py#L82-L143
230,835
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare_report.py
basis_comparison_report
def basis_comparison_report(bs1, bs2, uncontract_general=False): ''' Compares two basis set dictionaries and prints a report about their differences ''' all_bs1 = list(bs1['elements'].keys()) if uncontract_general: bs1 = manip.uncontract_general(bs1) bs2 = manip.uncontract_general(bs2) not_in_bs1 = [] # Found in bs2, not in bs1 not_in_bs2 = all_bs1.copy() # Found in bs1, not in bs2 no_diff = [] # Elements for which there is no difference some_diff = [] # Elements that are different big_diff = [] # Elements that are substantially different for k, v in bs2['elements'].items(): if k not in all_bs1: not_in_bs1.append(k) continue print() print("-------------------------------------") print(" Element ", k) bs1_el = bs1['elements'][k] max_rdiff_el = 0.0 max_rdiff_ecp = 0.0 # Check to make sure that neither or both have ecp/electron shells if 'electron_shells' in v and 'electron_shells' not in bs1_el: print("bs2 has electron_shells, but bs1 does not") max_rdiff_el = float('inf') if 'electron_shells' in bs1_el and 'electron_shells' not in v: print("bs1 has electron_shells, but bs2 does not") max_rdiff_el = float('inf') if 'ecp_potentials' in v and 'ecp_potentials' not in bs1_el: print("bs2 has ecp_potentials, but bs1 does not") max_rdiff_ecp = float('inf') if 'ecp_potentials' in bs1_el and 'ecp_potentials' not in v: print("bs1 has ecp_potentials, but bs2 does not") max_rdiff_ecp = float('inf') if 'electron_shells' in v and 'electron_shells' in bs1_el: max_rdiff_el = max(max_rdiff_el, shells_difference(v['electron_shells'], bs1_el['electron_shells'])) if 'ecp_potentials' in v and 'ecp_potentials' in bs1_el: nel1 = v['ecp_electrons'] nel2 = bs1_el['ecp_electrons'] if int(nel1) != int(nel2): print('Different number of electrons replaced by ECP ({} vs {})'.format(nel1, nel2)) max_rdiff_ecp = float('inf') else: max_rdiff_ecp = max(max_rdiff_ecp, potentials_difference(v['ecp_potentials'], bs1_el['ecp_potentials'])) max_rdiff = max(max_rdiff_el, max_rdiff_ecp) # Handle some differences if max_rdiff == float('inf'): big_diff.append(k) elif max_rdiff == 0.0: no_diff.append(k) else: some_diff.append(k) not_in_bs2.remove(k) print() print(" Not in bs1: ", _print_list(not_in_bs1)) print(" Not in bs2: ", _print_list(not_in_bs2)) print(" No difference: ", _print_list(no_diff)) print("Some difference: ", _print_list(some_diff)) print(" BIG difference: ", _print_list(big_diff)) print() return (len(not_in_bs1) == 0 and len(not_in_bs2) == 0 and len(some_diff) == 0 and len(big_diff) == 0)
python
def basis_comparison_report(bs1, bs2, uncontract_general=False): ''' Compares two basis set dictionaries and prints a report about their differences ''' all_bs1 = list(bs1['elements'].keys()) if uncontract_general: bs1 = manip.uncontract_general(bs1) bs2 = manip.uncontract_general(bs2) not_in_bs1 = [] # Found in bs2, not in bs1 not_in_bs2 = all_bs1.copy() # Found in bs1, not in bs2 no_diff = [] # Elements for which there is no difference some_diff = [] # Elements that are different big_diff = [] # Elements that are substantially different for k, v in bs2['elements'].items(): if k not in all_bs1: not_in_bs1.append(k) continue print() print("-------------------------------------") print(" Element ", k) bs1_el = bs1['elements'][k] max_rdiff_el = 0.0 max_rdiff_ecp = 0.0 # Check to make sure that neither or both have ecp/electron shells if 'electron_shells' in v and 'electron_shells' not in bs1_el: print("bs2 has electron_shells, but bs1 does not") max_rdiff_el = float('inf') if 'electron_shells' in bs1_el and 'electron_shells' not in v: print("bs1 has electron_shells, but bs2 does not") max_rdiff_el = float('inf') if 'ecp_potentials' in v and 'ecp_potentials' not in bs1_el: print("bs2 has ecp_potentials, but bs1 does not") max_rdiff_ecp = float('inf') if 'ecp_potentials' in bs1_el and 'ecp_potentials' not in v: print("bs1 has ecp_potentials, but bs2 does not") max_rdiff_ecp = float('inf') if 'electron_shells' in v and 'electron_shells' in bs1_el: max_rdiff_el = max(max_rdiff_el, shells_difference(v['electron_shells'], bs1_el['electron_shells'])) if 'ecp_potentials' in v and 'ecp_potentials' in bs1_el: nel1 = v['ecp_electrons'] nel2 = bs1_el['ecp_electrons'] if int(nel1) != int(nel2): print('Different number of electrons replaced by ECP ({} vs {})'.format(nel1, nel2)) max_rdiff_ecp = float('inf') else: max_rdiff_ecp = max(max_rdiff_ecp, potentials_difference(v['ecp_potentials'], bs1_el['ecp_potentials'])) max_rdiff = max(max_rdiff_el, max_rdiff_ecp) # Handle some differences if max_rdiff == float('inf'): big_diff.append(k) elif max_rdiff == 0.0: no_diff.append(k) else: some_diff.append(k) not_in_bs2.remove(k) print() print(" Not in bs1: ", _print_list(not_in_bs1)) print(" Not in bs2: ", _print_list(not_in_bs2)) print(" No difference: ", _print_list(no_diff)) print("Some difference: ", _print_list(some_diff)) print(" BIG difference: ", _print_list(big_diff)) print() return (len(not_in_bs1) == 0 and len(not_in_bs2) == 0 and len(some_diff) == 0 and len(big_diff) == 0)
[ "def", "basis_comparison_report", "(", "bs1", ",", "bs2", ",", "uncontract_general", "=", "False", ")", ":", "all_bs1", "=", "list", "(", "bs1", "[", "'elements'", "]", ".", "keys", "(", ")", ")", "if", "uncontract_general", ":", "bs1", "=", "manip", "."...
Compares two basis set dictionaries and prints a report about their differences
[ "Compares", "two", "basis", "set", "dictionaries", "and", "prints", "a", "report", "about", "their", "differences" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare_report.py#L146-L222
230,836
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/compare_report.py
compare_basis_against_file
def compare_basis_against_file(basis_name, src_filepath, file_type=None, version=None, uncontract_general=False, data_dir=None): '''Compare a basis set in the BSE against a reference file''' src_data = read_formatted_basis(src_filepath, file_type) bse_data = get_basis(basis_name, version=version, data_dir=data_dir) return basis_comparison_report(src_data, bse_data, uncontract_general=uncontract_general)
python
def compare_basis_against_file(basis_name, src_filepath, file_type=None, version=None, uncontract_general=False, data_dir=None): '''Compare a basis set in the BSE against a reference file''' src_data = read_formatted_basis(src_filepath, file_type) bse_data = get_basis(basis_name, version=version, data_dir=data_dir) return basis_comparison_report(src_data, bse_data, uncontract_general=uncontract_general)
[ "def", "compare_basis_against_file", "(", "basis_name", ",", "src_filepath", ",", "file_type", "=", "None", ",", "version", "=", "None", ",", "uncontract_general", "=", "False", ",", "data_dir", "=", "None", ")", ":", "src_data", "=", "read_formatted_basis", "("...
Compare a basis set in the BSE against a reference file
[ "Compare", "a", "basis", "set", "in", "the", "BSE", "against", "a", "reference", "file" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/compare_report.py#L225-L235
230,837
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_list_basis_sets
def _bse_cli_list_basis_sets(args): '''Handles the list-basis-sets subcommand''' metadata = api.filter_basis_sets(args.substr, args.family, args.role, args.data_dir) if args.no_description: liststr = metadata.keys() else: liststr = format_columns([(k, v['description']) for k, v in metadata.items()]) return '\n'.join(liststr)
python
def _bse_cli_list_basis_sets(args): '''Handles the list-basis-sets subcommand''' metadata = api.filter_basis_sets(args.substr, args.family, args.role, args.data_dir) if args.no_description: liststr = metadata.keys() else: liststr = format_columns([(k, v['description']) for k, v in metadata.items()]) return '\n'.join(liststr)
[ "def", "_bse_cli_list_basis_sets", "(", "args", ")", ":", "metadata", "=", "api", ".", "filter_basis_sets", "(", "args", ".", "substr", ",", "args", ".", "family", ",", "args", ".", "role", ",", "args", ".", "data_dir", ")", "if", "args", ".", "no_descri...
Handles the list-basis-sets subcommand
[ "Handles", "the", "list", "-", "basis", "-", "sets", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L10-L19
230,838
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_list_formats
def _bse_cli_list_formats(args): '''Handles the list-formats subcommand''' all_formats = api.get_formats() if args.no_description: liststr = all_formats.keys() else: liststr = format_columns(all_formats.items()) return '\n'.join(liststr)
python
def _bse_cli_list_formats(args): '''Handles the list-formats subcommand''' all_formats = api.get_formats() if args.no_description: liststr = all_formats.keys() else: liststr = format_columns(all_formats.items()) return '\n'.join(liststr)
[ "def", "_bse_cli_list_formats", "(", "args", ")", ":", "all_formats", "=", "api", ".", "get_formats", "(", ")", "if", "args", ".", "no_description", ":", "liststr", "=", "all_formats", ".", "keys", "(", ")", "else", ":", "liststr", "=", "format_columns", "...
Handles the list-formats subcommand
[ "Handles", "the", "list", "-", "formats", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L28-L37
230,839
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_list_ref_formats
def _bse_cli_list_ref_formats(args): '''Handles the list-ref-formats subcommand''' all_refformats = api.get_reference_formats() if args.no_description: liststr = all_refformats.keys() else: liststr = format_columns(all_refformats.items()) return '\n'.join(liststr)
python
def _bse_cli_list_ref_formats(args): '''Handles the list-ref-formats subcommand''' all_refformats = api.get_reference_formats() if args.no_description: liststr = all_refformats.keys() else: liststr = format_columns(all_refformats.items()) return '\n'.join(liststr)
[ "def", "_bse_cli_list_ref_formats", "(", "args", ")", ":", "all_refformats", "=", "api", ".", "get_reference_formats", "(", ")", "if", "args", ".", "no_description", ":", "liststr", "=", "all_refformats", ".", "keys", "(", ")", "else", ":", "liststr", "=", "...
Handles the list-ref-formats subcommand
[ "Handles", "the", "list", "-", "ref", "-", "formats", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L40-L49
230,840
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_list_roles
def _bse_cli_list_roles(args): '''Handles the list-roles subcommand''' all_roles = api.get_roles() if args.no_description: liststr = all_roles.keys() else: liststr = format_columns(all_roles.items()) return '\n'.join(liststr)
python
def _bse_cli_list_roles(args): '''Handles the list-roles subcommand''' all_roles = api.get_roles() if args.no_description: liststr = all_roles.keys() else: liststr = format_columns(all_roles.items()) return '\n'.join(liststr)
[ "def", "_bse_cli_list_roles", "(", "args", ")", ":", "all_roles", "=", "api", ".", "get_roles", "(", ")", "if", "args", ".", "no_description", ":", "liststr", "=", "all_roles", ".", "keys", "(", ")", "else", ":", "liststr", "=", "format_columns", "(", "a...
Handles the list-roles subcommand
[ "Handles", "the", "list", "-", "roles", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L52-L61
230,841
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_lookup_by_role
def _bse_cli_lookup_by_role(args): '''Handles the lookup-by-role subcommand''' return api.lookup_basis_by_role(args.basis, args.role, args.data_dir)
python
def _bse_cli_lookup_by_role(args): '''Handles the lookup-by-role subcommand''' return api.lookup_basis_by_role(args.basis, args.role, args.data_dir)
[ "def", "_bse_cli_lookup_by_role", "(", "args", ")", ":", "return", "api", ".", "lookup_basis_by_role", "(", "args", ".", "basis", ",", "args", ".", "role", ",", "args", ".", "data_dir", ")" ]
Handles the lookup-by-role subcommand
[ "Handles", "the", "lookup", "-", "by", "-", "role", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L70-L72
230,842
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_get_basis
def _bse_cli_get_basis(args): '''Handles the get-basis subcommand''' return api.get_basis( name=args.basis, elements=args.elements, version=args.version, fmt=args.fmt, uncontract_general=args.unc_gen, uncontract_spdf=args.unc_spdf, uncontract_segmented=args.unc_seg, make_general=args.make_gen, optimize_general=args.opt_gen, data_dir=args.data_dir, header=not args.noheader)
python
def _bse_cli_get_basis(args): '''Handles the get-basis subcommand''' return api.get_basis( name=args.basis, elements=args.elements, version=args.version, fmt=args.fmt, uncontract_general=args.unc_gen, uncontract_spdf=args.unc_spdf, uncontract_segmented=args.unc_seg, make_general=args.make_gen, optimize_general=args.opt_gen, data_dir=args.data_dir, header=not args.noheader)
[ "def", "_bse_cli_get_basis", "(", "args", ")", ":", "return", "api", ".", "get_basis", "(", "name", "=", "args", ".", "basis", ",", "elements", "=", "args", ".", "elements", ",", "version", "=", "args", ".", "version", ",", "fmt", "=", "args", ".", "...
Handles the get-basis subcommand
[ "Handles", "the", "get", "-", "basis", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L75-L89
230,843
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_get_refs
def _bse_cli_get_refs(args): '''Handles the get-refs subcommand''' return api.get_references( basis_name=args.basis, elements=args.elements, version=args.version, fmt=args.reffmt, data_dir=args.data_dir)
python
def _bse_cli_get_refs(args): '''Handles the get-refs subcommand''' return api.get_references( basis_name=args.basis, elements=args.elements, version=args.version, fmt=args.reffmt, data_dir=args.data_dir)
[ "def", "_bse_cli_get_refs", "(", "args", ")", ":", "return", "api", ".", "get_references", "(", "basis_name", "=", "args", ".", "basis", ",", "elements", "=", "args", ".", "elements", ",", "version", "=", "args", ".", "version", ",", "fmt", "=", "args", ...
Handles the get-refs subcommand
[ "Handles", "the", "get", "-", "refs", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L92-L95
230,844
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_get_info
def _bse_cli_get_info(args): '''Handles the get-info subcommand''' bs_meta = api.get_metadata(args.data_dir)[args.basis] ret = [] ret.append('-' * 80) ret.append(args.basis) ret.append('-' * 80) ret.append(' Display Name: ' + bs_meta['display_name']) ret.append(' Description: ' + bs_meta['description']) ret.append(' Role: ' + bs_meta['role']) ret.append(' Family: ' + bs_meta['family']) ret.append(' Function Types: ' + ','.join(bs_meta['functiontypes'])) ret.append(' Latest Version: ' + bs_meta['latest_version']) ret.append('') aux = bs_meta['auxiliaries'] if len(aux) == 0: ret.append('Auxiliary Basis Sets: None') else: ret.append('Auxiliary Basis Sets:') ret.extend(format_columns(list(aux.items()), ' ')) ver = bs_meta['versions'] ret.append('') ret.append('Versions:') # Print 3 columns - version, elements, revision description version_lines = format_columns([(k, compact_elements(v['elements']), v['revdesc']) for k, v in ver.items()], ' ') ret.extend(version_lines) return '\n'.join(ret)
python
def _bse_cli_get_info(args): '''Handles the get-info subcommand''' bs_meta = api.get_metadata(args.data_dir)[args.basis] ret = [] ret.append('-' * 80) ret.append(args.basis) ret.append('-' * 80) ret.append(' Display Name: ' + bs_meta['display_name']) ret.append(' Description: ' + bs_meta['description']) ret.append(' Role: ' + bs_meta['role']) ret.append(' Family: ' + bs_meta['family']) ret.append(' Function Types: ' + ','.join(bs_meta['functiontypes'])) ret.append(' Latest Version: ' + bs_meta['latest_version']) ret.append('') aux = bs_meta['auxiliaries'] if len(aux) == 0: ret.append('Auxiliary Basis Sets: None') else: ret.append('Auxiliary Basis Sets:') ret.extend(format_columns(list(aux.items()), ' ')) ver = bs_meta['versions'] ret.append('') ret.append('Versions:') # Print 3 columns - version, elements, revision description version_lines = format_columns([(k, compact_elements(v['elements']), v['revdesc']) for k, v in ver.items()], ' ') ret.extend(version_lines) return '\n'.join(ret)
[ "def", "_bse_cli_get_info", "(", "args", ")", ":", "bs_meta", "=", "api", ".", "get_metadata", "(", "args", ".", "data_dir", ")", "[", "args", ".", "basis", "]", "ret", "=", "[", "]", "ret", ".", "append", "(", "'-'", "*", "80", ")", "ret", ".", ...
Handles the get-info subcommand
[ "Handles", "the", "get", "-", "info", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L98-L130
230,845
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_get_versions
def _bse_cli_get_versions(args): '''Handles the get-versions subcommand''' name = args.basis.lower() metadata = api.get_metadata(args.data_dir) if not name in metadata: raise KeyError( "Basis set {} does not exist. For a complete list of basis sets, use the 'list-basis-sets' command".format( name)) version_data = {k: v['revdesc'] for k, v in metadata[name]['versions'].items()} if args.no_description: liststr = version_data.keys() else: liststr = format_columns(version_data.items()) return '\n'.join(liststr)
python
def _bse_cli_get_versions(args): '''Handles the get-versions subcommand''' name = args.basis.lower() metadata = api.get_metadata(args.data_dir) if not name in metadata: raise KeyError( "Basis set {} does not exist. For a complete list of basis sets, use the 'list-basis-sets' command".format( name)) version_data = {k: v['revdesc'] for k, v in metadata[name]['versions'].items()} if args.no_description: liststr = version_data.keys() else: liststr = format_columns(version_data.items()) return '\n'.join(liststr)
[ "def", "_bse_cli_get_versions", "(", "args", ")", ":", "name", "=", "args", ".", "basis", ".", "lower", "(", ")", "metadata", "=", "api", ".", "get_metadata", "(", "args", ".", "data_dir", ")", "if", "not", "name", "in", "metadata", ":", "raise", "KeyE...
Handles the get-versions subcommand
[ "Handles", "the", "get", "-", "versions", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L143-L159
230,846
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bse_handlers.py
_bse_cli_create_bundle
def _bse_cli_create_bundle(args): '''Handles the create-bundle subcommand''' bundle.create_bundle(args.bundle_file, args.fmt, args.reffmt, args.archive_type, args.data_dir) return "Created " + args.bundle_file
python
def _bse_cli_create_bundle(args): '''Handles the create-bundle subcommand''' bundle.create_bundle(args.bundle_file, args.fmt, args.reffmt, args.archive_type, args.data_dir) return "Created " + args.bundle_file
[ "def", "_bse_cli_create_bundle", "(", "args", ")", ":", "bundle", ".", "create_bundle", "(", "args", ".", "bundle_file", ",", "args", ".", "fmt", ",", "args", ".", "reffmt", ",", "args", ".", "archive_type", ",", "args", ".", "data_dir", ")", "return", "...
Handles the create-bundle subcommand
[ "Handles", "the", "create", "-", "bundle", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bse_handlers.py#L167-L170
230,847
openatx/facebook-wda
wda/__init__.py
Client.wait_ready
def wait_ready(self, timeout=120): """ wait until WDA back to normal Returns: bool (if wda works) """ deadline = time.time() + timeout while time.time() < deadline: try: self.status() return True except: time.sleep(2) return False
python
def wait_ready(self, timeout=120): deadline = time.time() + timeout while time.time() < deadline: try: self.status() return True except: time.sleep(2) return False
[ "def", "wait_ready", "(", "self", ",", "timeout", "=", "120", ")", ":", "deadline", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "time", ".", "time", "(", ")", "<", "deadline", ":", "try", ":", "self", ".", "status", "(", ")", "re...
wait until WDA back to normal Returns: bool (if wda works)
[ "wait", "until", "WDA", "back", "to", "normal" ]
aa644204620c6d5c7705a9c7452d8c0cc39330d5
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L197-L211
230,848
openatx/facebook-wda
wda/__init__.py
Client.screenshot
def screenshot(self, png_filename=None, format='raw'): """ Screenshot with PNG format Args: png_filename(string): optional, save file name format(string): return format, pillow or raw(default) Returns: raw data or PIL.Image Raises: WDAError """ value = self.http.get('screenshot').value raw_value = base64.b64decode(value) png_header = b"\x89PNG\r\n\x1a\n" if not raw_value.startswith(png_header) and png_filename: raise WDAError(-1, "screenshot png format error") if png_filename: with open(png_filename, 'wb') as f: f.write(raw_value) if format == 'raw': return raw_value elif format == 'pillow': from PIL import Image buff = io.BytesIO(raw_value) return Image.open(buff) else: raise ValueError("unknown format")
python
def screenshot(self, png_filename=None, format='raw'): value = self.http.get('screenshot').value raw_value = base64.b64decode(value) png_header = b"\x89PNG\r\n\x1a\n" if not raw_value.startswith(png_header) and png_filename: raise WDAError(-1, "screenshot png format error") if png_filename: with open(png_filename, 'wb') as f: f.write(raw_value) if format == 'raw': return raw_value elif format == 'pillow': from PIL import Image buff = io.BytesIO(raw_value) return Image.open(buff) else: raise ValueError("unknown format")
[ "def", "screenshot", "(", "self", ",", "png_filename", "=", "None", ",", "format", "=", "'raw'", ")", ":", "value", "=", "self", ".", "http", ".", "get", "(", "'screenshot'", ")", ".", "value", "raw_value", "=", "base64", ".", "b64decode", "(", "value"...
Screenshot with PNG format Args: png_filename(string): optional, save file name format(string): return format, pillow or raw(default) Returns: raw data or PIL.Image Raises: WDAError
[ "Screenshot", "with", "PNG", "format" ]
aa644204620c6d5c7705a9c7452d8c0cc39330d5
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L307-L337
230,849
openatx/facebook-wda
wda/__init__.py
Session.tap_hold
def tap_hold(self, x, y, duration=1.0): """ Tap and hold for a moment Args: - x, y(int): position - duration(float): seconds of hold time [[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)], """ data = {'x': x, 'y': y, 'duration': duration} return self.http.post('/wda/touchAndHold', data=data)
python
def tap_hold(self, x, y, duration=1.0): data = {'x': x, 'y': y, 'duration': duration} return self.http.post('/wda/touchAndHold', data=data)
[ "def", "tap_hold", "(", "self", ",", "x", ",", "y", ",", "duration", "=", "1.0", ")", ":", "data", "=", "{", "'x'", ":", "x", ",", "'y'", ":", "y", ",", "'duration'", ":", "duration", "}", "return", "self", ".", "http", ".", "post", "(", "'/wda...
Tap and hold for a moment Args: - x, y(int): position - duration(float): seconds of hold time [[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
[ "Tap", "and", "hold", "for", "a", "moment" ]
aa644204620c6d5c7705a9c7452d8c0cc39330d5
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L450-L461
230,850
openatx/facebook-wda
wda/__init__.py
Session.screenshot
def screenshot(self): """ Take screenshot with session check Returns: PIL.Image """ b64data = self.http.get('/screenshot').value raw_data = base64.b64decode(b64data) from PIL import Image buff = io.BytesIO(raw_data) return Image.open(buff)
python
def screenshot(self): b64data = self.http.get('/screenshot').value raw_data = base64.b64decode(b64data) from PIL import Image buff = io.BytesIO(raw_data) return Image.open(buff)
[ "def", "screenshot", "(", "self", ")", ":", "b64data", "=", "self", ".", "http", ".", "get", "(", "'/screenshot'", ")", ".", "value", "raw_data", "=", "base64", ".", "b64decode", "(", "b64data", ")", "from", "PIL", "import", "Image", "buff", "=", "io",...
Take screenshot with session check Returns: PIL.Image
[ "Take", "screenshot", "with", "session", "check" ]
aa644204620c6d5c7705a9c7452d8c0cc39330d5
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L463-L474
230,851
openatx/facebook-wda
wda/__init__.py
Session.send_keys
def send_keys(self, value): """ send keys, yet I know not, todo function """ if isinstance(value, six.string_types): value = list(value) return self.http.post('/wda/keys', data={'value': value})
python
def send_keys(self, value): if isinstance(value, six.string_types): value = list(value) return self.http.post('/wda/keys', data={'value': value})
[ "def", "send_keys", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "list", "(", "value", ")", "return", "self", ".", "http", ".", "post", "(", "'/wda/keys'", ",", "data"...
send keys, yet I know not, todo function
[ "send", "keys", "yet", "I", "know", "not", "todo", "function" ]
aa644204620c6d5c7705a9c7452d8c0cc39330d5
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L530-L536
230,852
openatx/facebook-wda
wda/__init__.py
Selector.click_exists
def click_exists(self, timeout=0): """ Wait element and perform click Args: timeout (float): timeout for wait Returns: bool: if successfully clicked """ e = self.get(timeout=timeout, raise_error=False) if e is None: return False e.click() return True
python
def click_exists(self, timeout=0): e = self.get(timeout=timeout, raise_error=False) if e is None: return False e.click() return True
[ "def", "click_exists", "(", "self", ",", "timeout", "=", "0", ")", ":", "e", "=", "self", ".", "get", "(", "timeout", "=", "timeout", ",", "raise_error", "=", "False", ")", "if", "e", "is", "None", ":", "return", "False", "e", ".", "click", "(", ...
Wait element and perform click Args: timeout (float): timeout for wait Returns: bool: if successfully clicked
[ "Wait", "element", "and", "perform", "click" ]
aa644204620c6d5c7705a9c7452d8c0cc39330d5
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L855-L869
230,853
airspeed-velocity/asv
asv/plugins/regressions.py
_GraphDataFilter.get_graph_data
def get_graph_data(self, graph, benchmark): """ Iterator over graph data sets Yields ------ param_idx Flat index to parameter permutations for parameterized benchmarks. None if benchmark is not parameterized. entry_name Name for the data set. If benchmark is non-parameterized, this is the benchmark name. steps Steps to consider in regression detection. threshold User-specified threshold for regression detection. """ if benchmark.get('params'): param_iter = enumerate(zip(itertools.product(*benchmark['params']), graph.get_steps())) else: param_iter = [(None, (None, graph.get_steps()))] for j, (param, steps) in param_iter: if param is None: entry_name = benchmark['name'] else: entry_name = benchmark['name'] + '({0})'.format(', '.join(param)) start_revision = self._get_start_revision(graph, benchmark, entry_name) threshold = self._get_threshold(graph, benchmark, entry_name) if start_revision is None: # Skip detection continue steps = [step for step in steps if step[1] >= start_revision] yield j, entry_name, steps, threshold
python
def get_graph_data(self, graph, benchmark): if benchmark.get('params'): param_iter = enumerate(zip(itertools.product(*benchmark['params']), graph.get_steps())) else: param_iter = [(None, (None, graph.get_steps()))] for j, (param, steps) in param_iter: if param is None: entry_name = benchmark['name'] else: entry_name = benchmark['name'] + '({0})'.format(', '.join(param)) start_revision = self._get_start_revision(graph, benchmark, entry_name) threshold = self._get_threshold(graph, benchmark, entry_name) if start_revision is None: # Skip detection continue steps = [step for step in steps if step[1] >= start_revision] yield j, entry_name, steps, threshold
[ "def", "get_graph_data", "(", "self", ",", "graph", ",", "benchmark", ")", ":", "if", "benchmark", ".", "get", "(", "'params'", ")", ":", "param_iter", "=", "enumerate", "(", "zip", "(", "itertools", ".", "product", "(", "*", "benchmark", "[", "'params'"...
Iterator over graph data sets Yields ------ param_idx Flat index to parameter permutations for parameterized benchmarks. None if benchmark is not parameterized. entry_name Name for the data set. If benchmark is non-parameterized, this is the benchmark name. steps Steps to consider in regression detection. threshold User-specified threshold for regression detection.
[ "Iterator", "over", "graph", "data", "sets" ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/regressions.py#L230-L269
230,854
airspeed-velocity/asv
asv/plugins/regressions.py
_GraphDataFilter._get_start_revision
def _get_start_revision(self, graph, benchmark, entry_name): """ Compute the first revision allowed by asv.conf.json. Revisions correspond to linearized commit history and the regression detection runs on this order --- the starting commit thus corresponds to a specific starting revision. """ start_revision = min(six.itervalues(self.revisions)) if graph.params.get('branch'): branch_suffix = '@' + graph.params.get('branch') else: branch_suffix = '' for regex, start_commit in six.iteritems(self.conf.regressions_first_commits): if re.match(regex, entry_name + branch_suffix): if start_commit is None: # Disable regression detection completely return None if self.conf.branches == [None]: key = (start_commit, None) else: key = (start_commit, graph.params.get('branch')) if key not in self._start_revisions: spec = self.repo.get_new_range_spec(*key) start_hash = self.repo.get_hash_from_name(start_commit) for commit in [start_hash] + self.repo.get_hashes_from_range(spec): rev = self.revisions.get(commit) if rev is not None: self._start_revisions[key] = rev break else: # Commit not found in the branch --- warn and ignore. log.warning(("Commit {0} specified in `regressions_first_commits` " "not found in branch").format(start_commit)) self._start_revisions[key] = -1 start_revision = max(start_revision, self._start_revisions[key] + 1) return start_revision
python
def _get_start_revision(self, graph, benchmark, entry_name): start_revision = min(six.itervalues(self.revisions)) if graph.params.get('branch'): branch_suffix = '@' + graph.params.get('branch') else: branch_suffix = '' for regex, start_commit in six.iteritems(self.conf.regressions_first_commits): if re.match(regex, entry_name + branch_suffix): if start_commit is None: # Disable regression detection completely return None if self.conf.branches == [None]: key = (start_commit, None) else: key = (start_commit, graph.params.get('branch')) if key not in self._start_revisions: spec = self.repo.get_new_range_spec(*key) start_hash = self.repo.get_hash_from_name(start_commit) for commit in [start_hash] + self.repo.get_hashes_from_range(spec): rev = self.revisions.get(commit) if rev is not None: self._start_revisions[key] = rev break else: # Commit not found in the branch --- warn and ignore. log.warning(("Commit {0} specified in `regressions_first_commits` " "not found in branch").format(start_commit)) self._start_revisions[key] = -1 start_revision = max(start_revision, self._start_revisions[key] + 1) return start_revision
[ "def", "_get_start_revision", "(", "self", ",", "graph", ",", "benchmark", ",", "entry_name", ")", ":", "start_revision", "=", "min", "(", "six", ".", "itervalues", "(", "self", ".", "revisions", ")", ")", "if", "graph", ".", "params", ".", "get", "(", ...
Compute the first revision allowed by asv.conf.json. Revisions correspond to linearized commit history and the regression detection runs on this order --- the starting commit thus corresponds to a specific starting revision.
[ "Compute", "the", "first", "revision", "allowed", "by", "asv", ".", "conf", ".", "json", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/regressions.py#L271-L314
230,855
airspeed-velocity/asv
asv/plugins/regressions.py
_GraphDataFilter._get_threshold
def _get_threshold(self, graph, benchmark, entry_name): """ Compute the regression threshold in asv.conf.json. """ if graph.params.get('branch'): branch_suffix = '@' + graph.params.get('branch') else: branch_suffix = '' max_threshold = None for regex, threshold in six.iteritems(self.conf.regressions_thresholds): if re.match(regex, entry_name + branch_suffix): try: threshold = float(threshold) except ValueError: raise util.UserError("Non-float threshold in asv.conf.json: {!r}".format(threshold)) if max_threshold is None: max_threshold = threshold else: max_threshold = max(threshold, max_threshold) if max_threshold is None: max_threshold = 0.05 return max_threshold
python
def _get_threshold(self, graph, benchmark, entry_name): if graph.params.get('branch'): branch_suffix = '@' + graph.params.get('branch') else: branch_suffix = '' max_threshold = None for regex, threshold in six.iteritems(self.conf.regressions_thresholds): if re.match(regex, entry_name + branch_suffix): try: threshold = float(threshold) except ValueError: raise util.UserError("Non-float threshold in asv.conf.json: {!r}".format(threshold)) if max_threshold is None: max_threshold = threshold else: max_threshold = max(threshold, max_threshold) if max_threshold is None: max_threshold = 0.05 return max_threshold
[ "def", "_get_threshold", "(", "self", ",", "graph", ",", "benchmark", ",", "entry_name", ")", ":", "if", "graph", ".", "params", ".", "get", "(", "'branch'", ")", ":", "branch_suffix", "=", "'@'", "+", "graph", ".", "params", ".", "get", "(", "'branch'...
Compute the regression threshold in asv.conf.json.
[ "Compute", "the", "regression", "threshold", "in", "asv", ".", "conf", ".", "json", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/regressions.py#L316-L342
230,856
airspeed-velocity/asv
setup.py
sdist_checked.__check_submodules
def __check_submodules(self): """ Verify that the submodules are checked out and clean. """ if not os.path.exists('.git'): return with open('.gitmodules') as f: for l in f: if 'path' in l: p = l.split('=')[-1].strip() if not os.path.exists(p): raise ValueError('Submodule %s missing' % p) proc = subprocess.Popen(['git', 'submodule', 'status'], stdout=subprocess.PIPE) status, _ = proc.communicate() status = status.decode("ascii", "replace") for line in status.splitlines(): if line.startswith('-') or line.startswith('+'): raise ValueError('Submodule not clean: %s' % line)
python
def __check_submodules(self): if not os.path.exists('.git'): return with open('.gitmodules') as f: for l in f: if 'path' in l: p = l.split('=')[-1].strip() if not os.path.exists(p): raise ValueError('Submodule %s missing' % p) proc = subprocess.Popen(['git', 'submodule', 'status'], stdout=subprocess.PIPE) status, _ = proc.communicate() status = status.decode("ascii", "replace") for line in status.splitlines(): if line.startswith('-') or line.startswith('+'): raise ValueError('Submodule not clean: %s' % line)
[ "def", "__check_submodules", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "'.git'", ")", ":", "return", "with", "open", "(", "'.gitmodules'", ")", "as", "f", ":", "for", "l", "in", "f", ":", "if", "'path'", "in", "l", ...
Verify that the submodules are checked out and clean.
[ "Verify", "that", "the", "submodules", "are", "checked", "out", "and", "clean", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/setup.py#L57-L76
230,857
airspeed-velocity/asv
asv/step_detect.py
solve_potts_autogamma
def solve_potts_autogamma(y, w, beta=None, **kw): """Solve Potts problem with automatically determined gamma. The optimal value is determined by minimizing the information measure:: f(gamma) = beta J(x(gamma)) + log sum(abs(x(gamma) - y)**p) where x(gamma) is the solution to the Potts problem for a fixed gamma. The minimization is only performed rather roughly. Parameters ---------- beta : float or 'bic' Penalty parameter. Default is 4*ln(n)/n, similar to Bayesian information criterion for gaussian model with unknown variance assuming 4 DOF per breakpoint. """ n = len(y) if n == 0: return [], [], [], None mu_dist = get_mu_dist(y, w) mu, dist = mu_dist.mu, mu_dist.dist if beta is None: beta = 4 * math.log(n) / n gamma_0 = dist(0, n-1) if gamma_0 == 0: # Zero variance gamma_0 = 1.0 best_r = [None] best_v = [None] best_d = [None] best_obj = [float('inf')] best_gamma = [None] def f(x): gamma = gamma_0 * math.exp(x) r, v, d = solve_potts_approx(y, w, gamma=gamma, mu_dist=mu_dist, **kw) # MLE fit noise correlation def sigma_star(rights, values, rho): """ |E_0| + sum_{j>0} |E_j - rho E_{j-1}| """ l = 1 E_prev = y[0] - values[0] s = abs(E_prev) for r, v in zip(rights, values): for yv in y[l:r]: E = yv - v s += abs(E - rho*E_prev) E_prev = E l = r return s rho_best = golden_search(lambda rho: sigma_star(r, v, rho), -1, 1, xatol=0.05, expand_bounds=True) # Measurement noise floor if len(v) > 2: absdiff = [abs(v[j+1] - v[j]) for j in range(len(v) - 1)] sigma_0 = 0.1 * min(absdiff) else: absv = [abs(z) for z in v] sigma_0 = 0.001 * min(absv) sigma_0 = max(1e-300, sigma_0) # Objective function s = sigma_star(r, v, rho_best) obj = beta*len(r) + math.log(sigma_0 + s) # Done if obj < best_obj[0]: best_r[0] = r best_v[0] = v best_d[0] = d best_gamma[0] = gamma best_obj[0] = obj return obj # Try to find best gamma (golden section search on log-scale); we # don't need an accurate value for it however a = math.log(0.1/n) b = 0.0 golden_search(f, a, b, xatol=abs(a)*0.1, ftol=0, expand_bounds=True) return best_r[0], best_v[0], best_d[0], best_gamma[0]
python
def solve_potts_autogamma(y, w, beta=None, **kw): n = len(y) if n == 0: return [], [], [], None mu_dist = get_mu_dist(y, w) mu, dist = mu_dist.mu, mu_dist.dist if beta is None: beta = 4 * math.log(n) / n gamma_0 = dist(0, n-1) if gamma_0 == 0: # Zero variance gamma_0 = 1.0 best_r = [None] best_v = [None] best_d = [None] best_obj = [float('inf')] best_gamma = [None] def f(x): gamma = gamma_0 * math.exp(x) r, v, d = solve_potts_approx(y, w, gamma=gamma, mu_dist=mu_dist, **kw) # MLE fit noise correlation def sigma_star(rights, values, rho): """ |E_0| + sum_{j>0} |E_j - rho E_{j-1}| """ l = 1 E_prev = y[0] - values[0] s = abs(E_prev) for r, v in zip(rights, values): for yv in y[l:r]: E = yv - v s += abs(E - rho*E_prev) E_prev = E l = r return s rho_best = golden_search(lambda rho: sigma_star(r, v, rho), -1, 1, xatol=0.05, expand_bounds=True) # Measurement noise floor if len(v) > 2: absdiff = [abs(v[j+1] - v[j]) for j in range(len(v) - 1)] sigma_0 = 0.1 * min(absdiff) else: absv = [abs(z) for z in v] sigma_0 = 0.001 * min(absv) sigma_0 = max(1e-300, sigma_0) # Objective function s = sigma_star(r, v, rho_best) obj = beta*len(r) + math.log(sigma_0 + s) # Done if obj < best_obj[0]: best_r[0] = r best_v[0] = v best_d[0] = d best_gamma[0] = gamma best_obj[0] = obj return obj # Try to find best gamma (golden section search on log-scale); we # don't need an accurate value for it however a = math.log(0.1/n) b = 0.0 golden_search(f, a, b, xatol=abs(a)*0.1, ftol=0, expand_bounds=True) return best_r[0], best_v[0], best_d[0], best_gamma[0]
[ "def", "solve_potts_autogamma", "(", "y", ",", "w", ",", "beta", "=", "None", ",", "*", "*", "kw", ")", ":", "n", "=", "len", "(", "y", ")", "if", "n", "==", "0", ":", "return", "[", "]", ",", "[", "]", ",", "[", "]", ",", "None", "mu_dist"...
Solve Potts problem with automatically determined gamma. The optimal value is determined by minimizing the information measure:: f(gamma) = beta J(x(gamma)) + log sum(abs(x(gamma) - y)**p) where x(gamma) is the solution to the Potts problem for a fixed gamma. The minimization is only performed rather roughly. Parameters ---------- beta : float or 'bic' Penalty parameter. Default is 4*ln(n)/n, similar to Bayesian information criterion for gaussian model with unknown variance assuming 4 DOF per breakpoint.
[ "Solve", "Potts", "problem", "with", "automatically", "determined", "gamma", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/step_detect.py#L632-L723
230,858
airspeed-velocity/asv
asv/step_detect.py
merge_pieces
def merge_pieces(gamma, right, values, dists, mu_dist, max_size): """ Combine consecutive intervals in Potts model solution, if doing that reduces the cost function. """ mu, dist = mu_dist.mu, mu_dist.dist right = list(right) # Combine consecutive intervals, if it results to decrease of cost # function while True: min_change = 0 min_change_j = len(right) l = 0 for j in range(1, len(right)): if min_change_j < j - 2: break # Check whether merging consecutive intervals results to # decrease in the cost function change = dist(l, right[j]-1) - (dist(l, right[j-1]-1) + dist(right[j-1], right[j]-1) + gamma) if change <= min_change: min_change = change min_change_j = j-1 l = right[j-1] if min_change_j < len(right): del right[min_change_j] else: break # Check whether perturbing boundary positions leads to improvement # in the cost function. The restricted Potts minimization can # return sub-optimal boundaries due to the interval maximum size # restriction. l = 0 for j in range(1, len(right)): prev_score = dist(l, right[j-1]-1) + dist(right[j-1], right[j]-1) new_off = 0 for off in range(-max_size, max_size+1): if right[j-1] + off - 1 <= l or right[j-1] + off >= right[j] - 1 or off == 0: continue new_score = dist(l, right[j-1]+off-1) + dist(right[j-1]+off, right[j]-1) if new_score < prev_score: new_off = off prev_score = new_score if new_off != 0: right[j-1] += new_off l = right[j-1] # Rebuild values and dists lists l = 0 values = [] dists = [] for j in range(len(right)): dists.append(dist(l, right[j]-1)) values.append(mu(l, right[j]-1)) l = right[j] return right, values, dists
python
def merge_pieces(gamma, right, values, dists, mu_dist, max_size): mu, dist = mu_dist.mu, mu_dist.dist right = list(right) # Combine consecutive intervals, if it results to decrease of cost # function while True: min_change = 0 min_change_j = len(right) l = 0 for j in range(1, len(right)): if min_change_j < j - 2: break # Check whether merging consecutive intervals results to # decrease in the cost function change = dist(l, right[j]-1) - (dist(l, right[j-1]-1) + dist(right[j-1], right[j]-1) + gamma) if change <= min_change: min_change = change min_change_j = j-1 l = right[j-1] if min_change_j < len(right): del right[min_change_j] else: break # Check whether perturbing boundary positions leads to improvement # in the cost function. The restricted Potts minimization can # return sub-optimal boundaries due to the interval maximum size # restriction. l = 0 for j in range(1, len(right)): prev_score = dist(l, right[j-1]-1) + dist(right[j-1], right[j]-1) new_off = 0 for off in range(-max_size, max_size+1): if right[j-1] + off - 1 <= l or right[j-1] + off >= right[j] - 1 or off == 0: continue new_score = dist(l, right[j-1]+off-1) + dist(right[j-1]+off, right[j]-1) if new_score < prev_score: new_off = off prev_score = new_score if new_off != 0: right[j-1] += new_off l = right[j-1] # Rebuild values and dists lists l = 0 values = [] dists = [] for j in range(len(right)): dists.append(dist(l, right[j]-1)) values.append(mu(l, right[j]-1)) l = right[j] return right, values, dists
[ "def", "merge_pieces", "(", "gamma", ",", "right", ",", "values", ",", "dists", ",", "mu_dist", ",", "max_size", ")", ":", "mu", ",", "dist", "=", "mu_dist", ".", "mu", ",", "mu_dist", ".", "dist", "right", "=", "list", "(", "right", ")", "# Combine ...
Combine consecutive intervals in Potts model solution, if doing that reduces the cost function.
[ "Combine", "consecutive", "intervals", "in", "Potts", "model", "solution", "if", "doing", "that", "reduces", "the", "cost", "function", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/step_detect.py#L758-L821
230,859
airspeed-velocity/asv
asv/step_detect.py
weighted_median
def weighted_median(y, w): """ Compute weighted median of `y` with weights `w`. """ items = sorted(zip(y, w)) midpoint = sum(w) / 2 yvals = [] wsum = 0 for yy, ww in items: wsum += ww if wsum > midpoint: yvals.append(yy) break elif wsum == midpoint: yvals.append(yy) else: yvals = y return sum(yvals) / len(yvals)
python
def weighted_median(y, w): items = sorted(zip(y, w)) midpoint = sum(w) / 2 yvals = [] wsum = 0 for yy, ww in items: wsum += ww if wsum > midpoint: yvals.append(yy) break elif wsum == midpoint: yvals.append(yy) else: yvals = y return sum(yvals) / len(yvals)
[ "def", "weighted_median", "(", "y", ",", "w", ")", ":", "items", "=", "sorted", "(", "zip", "(", "y", ",", "w", ")", ")", "midpoint", "=", "sum", "(", "w", ")", "/", "2", "yvals", "=", "[", "]", "wsum", "=", "0", "for", "yy", ",", "ww", "in...
Compute weighted median of `y` with weights `w`.
[ "Compute", "weighted", "median", "of", "y", "with", "weights", "w", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/step_detect.py#L933-L953
230,860
airspeed-velocity/asv
asv/plugins/virtualenv.py
Virtualenv._find_python
def _find_python(python): """Find Python executable for the given Python version""" is_pypy = python.startswith("pypy") # Parse python specifier if is_pypy: executable = python if python == 'pypy': python_version = '2' else: python_version = python[4:] else: python_version = python executable = "python{0}".format(python_version) # Find Python executable on path try: return util.which(executable) except IOError: pass # Maybe the current one is correct? current_is_pypy = hasattr(sys, 'pypy_version_info') current_versions = ['{0[0]}'.format(sys.version_info), '{0[0]}.{0[1]}'.format(sys.version_info)] if is_pypy == current_is_pypy and python_version in current_versions: return sys.executable return None
python
def _find_python(python): is_pypy = python.startswith("pypy") # Parse python specifier if is_pypy: executable = python if python == 'pypy': python_version = '2' else: python_version = python[4:] else: python_version = python executable = "python{0}".format(python_version) # Find Python executable on path try: return util.which(executable) except IOError: pass # Maybe the current one is correct? current_is_pypy = hasattr(sys, 'pypy_version_info') current_versions = ['{0[0]}'.format(sys.version_info), '{0[0]}.{0[1]}'.format(sys.version_info)] if is_pypy == current_is_pypy and python_version in current_versions: return sys.executable return None
[ "def", "_find_python", "(", "python", ")", ":", "is_pypy", "=", "python", ".", "startswith", "(", "\"pypy\"", ")", "# Parse python specifier", "if", "is_pypy", ":", "executable", "=", "python", "if", "python", "==", "'pypy'", ":", "python_version", "=", "'2'",...
Find Python executable for the given Python version
[ "Find", "Python", "executable", "for", "the", "given", "Python", "version" ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/virtualenv.py#L60-L89
230,861
airspeed-velocity/asv
asv/plugins/virtualenv.py
Virtualenv.name
def name(self): """ Get a name to uniquely identify this environment. """ python = self._python if self._python.startswith('pypy'): # get_env_name adds py-prefix python = python[2:] return environment.get_env_name(self.tool_name, python, self._requirements)
python
def name(self): python = self._python if self._python.startswith('pypy'): # get_env_name adds py-prefix python = python[2:] return environment.get_env_name(self.tool_name, python, self._requirements)
[ "def", "name", "(", "self", ")", ":", "python", "=", "self", ".", "_python", "if", "self", ".", "_python", ".", "startswith", "(", "'pypy'", ")", ":", "# get_env_name adds py-prefix", "python", "=", "python", "[", "2", ":", "]", "return", "environment", ...
Get a name to uniquely identify this environment.
[ "Get", "a", "name", "to", "uniquely", "identify", "this", "environment", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/virtualenv.py#L92-L100
230,862
airspeed-velocity/asv
asv/plugins/virtualenv.py
Virtualenv._setup
def _setup(self): """ Setup the environment on disk using virtualenv. Then, all of the requirements are installed into it using `pip install`. """ log.info("Creating virtualenv for {0}".format(self.name)) util.check_call([ sys.executable, "-mvirtualenv", '--no-site-packages', "-p", self._executable, self._path]) log.info("Installing requirements for {0}".format(self.name)) self._install_requirements()
python
def _setup(self): log.info("Creating virtualenv for {0}".format(self.name)) util.check_call([ sys.executable, "-mvirtualenv", '--no-site-packages', "-p", self._executable, self._path]) log.info("Installing requirements for {0}".format(self.name)) self._install_requirements()
[ "def", "_setup", "(", "self", ")", ":", "log", ".", "info", "(", "\"Creating virtualenv for {0}\"", ".", "format", "(", "self", ".", "name", ")", ")", "util", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "\"-mvirtualenv\"", ",", "'--no-site-...
Setup the environment on disk using virtualenv. Then, all of the requirements are installed into it using `pip install`.
[ "Setup", "the", "environment", "on", "disk", "using", "virtualenv", ".", "Then", "all", "of", "the", "requirements", "are", "installed", "into", "it", "using", "pip", "install", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/virtualenv.py#L124-L140
230,863
airspeed-velocity/asv
asv/extern/asizeof.py
_basicsize
def _basicsize(t, base=0, heap=False, obj=None): '''Get non-zero basicsize of type, including the header sizes. ''' s = max(getattr(t, '__basicsize__', 0), base) # include gc header size if t != _Type_type: h = getattr(t, '__flags__', 0) & _Py_TPFLAGS_HAVE_GC elif heap: # type, allocated on heap h = True else: # None has no __flags__ attr h = getattr(obj, '__flags__', 0) & _Py_TPFLAGS_HEAPTYPE if h: s += _sizeof_CPyGC_Head # include reference counters return s + _sizeof_Crefcounts
python
def _basicsize(t, base=0, heap=False, obj=None): '''Get non-zero basicsize of type, including the header sizes. ''' s = max(getattr(t, '__basicsize__', 0), base) # include gc header size if t != _Type_type: h = getattr(t, '__flags__', 0) & _Py_TPFLAGS_HAVE_GC elif heap: # type, allocated on heap h = True else: # None has no __flags__ attr h = getattr(obj, '__flags__', 0) & _Py_TPFLAGS_HEAPTYPE if h: s += _sizeof_CPyGC_Head # include reference counters return s + _sizeof_Crefcounts
[ "def", "_basicsize", "(", "t", ",", "base", "=", "0", ",", "heap", "=", "False", ",", "obj", "=", "None", ")", ":", "s", "=", "max", "(", "getattr", "(", "t", ",", "'__basicsize__'", ",", "0", ")", ",", "base", ")", "# include gc header size", "if"...
Get non-zero basicsize of type, including the header sizes.
[ "Get", "non", "-", "zero", "basicsize", "of", "type", "including", "the", "header", "sizes", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L337-L352
230,864
airspeed-velocity/asv
asv/extern/asizeof.py
_derive_typedef
def _derive_typedef(typ): '''Return single, existing super type typedef or None. ''' v = [v for v in _values(_typedefs) if _issubclass(typ, v.type)] if len(v) == 1: return v[0] return None
python
def _derive_typedef(typ): '''Return single, existing super type typedef or None. ''' v = [v for v in _values(_typedefs) if _issubclass(typ, v.type)] if len(v) == 1: return v[0] return None
[ "def", "_derive_typedef", "(", "typ", ")", ":", "v", "=", "[", "v", "for", "v", "in", "_values", "(", "_typedefs", ")", "if", "_issubclass", "(", "typ", ",", "v", ".", "type", ")", "]", "if", "len", "(", "v", ")", "==", "1", ":", "return", "v",...
Return single, existing super type typedef or None.
[ "Return", "single", "existing", "super", "type", "typedef", "or", "None", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L354-L360
230,865
airspeed-velocity/asv
asv/extern/asizeof.py
_infer_dict
def _infer_dict(obj): '''Return True for likely dict object. ''' for ats in (('__len__', 'get', 'has_key', 'items', 'keys', 'values'), ('__len__', 'get', 'has_key', 'iteritems', 'iterkeys', 'itervalues')): for a in ats: # no all(<generator_expression>) in Python 2.2 if not _callable(getattr(obj, a, None)): break else: # all True return True return False
python
def _infer_dict(obj): '''Return True for likely dict object. ''' for ats in (('__len__', 'get', 'has_key', 'items', 'keys', 'values'), ('__len__', 'get', 'has_key', 'iteritems', 'iterkeys', 'itervalues')): for a in ats: # no all(<generator_expression>) in Python 2.2 if not _callable(getattr(obj, a, None)): break else: # all True return True return False
[ "def", "_infer_dict", "(", "obj", ")", ":", "for", "ats", "in", "(", "(", "'__len__'", ",", "'get'", ",", "'has_key'", ",", "'items'", ",", "'keys'", ",", "'values'", ")", ",", "(", "'__len__'", ",", "'get'", ",", "'has_key'", ",", "'iteritems'", ",", ...
Return True for likely dict object.
[ "Return", "True", "for", "likely", "dict", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L392-L402
230,866
airspeed-velocity/asv
asv/extern/asizeof.py
_isdictclass
def _isdictclass(obj): '''Return True for known dict objects. ''' c = getattr(obj, '__class__', None) return c and c.__name__ in _dict_classes.get(c.__module__, ())
python
def _isdictclass(obj): '''Return True for known dict objects. ''' c = getattr(obj, '__class__', None) return c and c.__name__ in _dict_classes.get(c.__module__, ())
[ "def", "_isdictclass", "(", "obj", ")", ":", "c", "=", "getattr", "(", "obj", ",", "'__class__'", ",", "None", ")", "return", "c", "and", "c", ".", "__name__", "in", "_dict_classes", ".", "get", "(", "c", ".", "__module__", ",", "(", ")", ")" ]
Return True for known dict objects.
[ "Return", "True", "for", "known", "dict", "objects", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L404-L408
230,867
airspeed-velocity/asv
asv/extern/asizeof.py
_lengstr
def _lengstr(obj): '''Object length as a string. ''' n = leng(obj) if n is None: # no len r = '' elif n > _len(obj): # extended r = ' leng %d!' % n else: r = ' leng %d' % n return r
python
def _lengstr(obj): '''Object length as a string. ''' n = leng(obj) if n is None: # no len r = '' elif n > _len(obj): # extended r = ' leng %d!' % n else: r = ' leng %d' % n return r
[ "def", "_lengstr", "(", "obj", ")", ":", "n", "=", "leng", "(", "obj", ")", "if", "n", "is", "None", ":", "# no len", "r", "=", "''", "elif", "n", ">", "_len", "(", "obj", ")", ":", "# extended", "r", "=", "' leng %d!'", "%", "n", "else", ":", ...
Object length as a string.
[ "Object", "length", "as", "a", "string", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L431-L441
230,868
airspeed-velocity/asv
asv/extern/asizeof.py
_objs_opts
def _objs_opts(objs, all=None, **opts): '''Return given or 'all' objects and the remaining options. ''' if objs: # given objects t = objs elif all in (False, None): t = () elif all is True: # 'all' objects ... # ... modules first, globals and stack # (may contain duplicate objects) t = tuple(_values(sys.modules)) + ( globals(), stack(sys.getrecursionlimit())[2:]) else: raise ValueError('invalid option: %s=%r' % ('all', all)) return t, opts
python
def _objs_opts(objs, all=None, **opts): '''Return given or 'all' objects and the remaining options. ''' if objs: # given objects t = objs elif all in (False, None): t = () elif all is True: # 'all' objects ... # ... modules first, globals and stack # (may contain duplicate objects) t = tuple(_values(sys.modules)) + ( globals(), stack(sys.getrecursionlimit())[2:]) else: raise ValueError('invalid option: %s=%r' % ('all', all)) return t, opts
[ "def", "_objs_opts", "(", "objs", ",", "all", "=", "None", ",", "*", "*", "opts", ")", ":", "if", "objs", ":", "# given objects", "t", "=", "objs", "elif", "all", "in", "(", "False", ",", "None", ")", ":", "t", "=", "(", ")", "elif", "all", "is...
Return given or 'all' objects and the remaining options.
[ "Return", "given", "or", "all", "objects", "and", "the", "remaining", "options", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L448-L463
230,869
airspeed-velocity/asv
asv/extern/asizeof.py
_p100
def _p100(part, total, prec=1): '''Return percentage as string. ''' r = float(total) if r: r = part * 100.0 / r return '%.*f%%' % (prec, r) return 'n/a'
python
def _p100(part, total, prec=1): '''Return percentage as string. ''' r = float(total) if r: r = part * 100.0 / r return '%.*f%%' % (prec, r) return 'n/a'
[ "def", "_p100", "(", "part", ",", "total", ",", "prec", "=", "1", ")", ":", "r", "=", "float", "(", "total", ")", "if", "r", ":", "r", "=", "part", "*", "100.0", "/", "r", "return", "'%.*f%%'", "%", "(", "prec", ",", "r", ")", "return", "'n/a...
Return percentage as string.
[ "Return", "percentage", "as", "string", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L465-L472
230,870
airspeed-velocity/asv
asv/extern/asizeof.py
_printf
def _printf(fmt, *args, **print3opts): '''Formatted print. ''' if print3opts: # like Python 3.0 f = print3opts.get('file', None) or sys.stdout if args: f.write(fmt % args) else: f.write(fmt) f.write(print3opts.get('end', linesep)) elif args: print(fmt % args) else: print(fmt)
python
def _printf(fmt, *args, **print3opts): '''Formatted print. ''' if print3opts: # like Python 3.0 f = print3opts.get('file', None) or sys.stdout if args: f.write(fmt % args) else: f.write(fmt) f.write(print3opts.get('end', linesep)) elif args: print(fmt % args) else: print(fmt)
[ "def", "_printf", "(", "fmt", ",", "*", "args", ",", "*", "*", "print3opts", ")", ":", "if", "print3opts", ":", "# like Python 3.0", "f", "=", "print3opts", ".", "get", "(", "'file'", ",", "None", ")", "or", "sys", ".", "stdout", "if", "args", ":", ...
Formatted print.
[ "Formatted", "print", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L496-L509
230,871
airspeed-velocity/asv
asv/extern/asizeof.py
_refs
def _refs(obj, named, *ats, **kwds): '''Return specific attribute objects of an object. ''' if named: for a in ats: # cf. inspect.getmembers() if hasattr(obj, a): yield _NamedRef(a, getattr(obj, a)) if kwds: # kwds are _dir2() args for a, o in _dir2(obj, **kwds): yield _NamedRef(a, o) else: for a in ats: # cf. inspect.getmembers() if hasattr(obj, a): yield getattr(obj, a) if kwds: # kwds are _dir2() args for _, o in _dir2(obj, **kwds): yield o
python
def _refs(obj, named, *ats, **kwds): '''Return specific attribute objects of an object. ''' if named: for a in ats: # cf. inspect.getmembers() if hasattr(obj, a): yield _NamedRef(a, getattr(obj, a)) if kwds: # kwds are _dir2() args for a, o in _dir2(obj, **kwds): yield _NamedRef(a, o) else: for a in ats: # cf. inspect.getmembers() if hasattr(obj, a): yield getattr(obj, a) if kwds: # kwds are _dir2() args for _, o in _dir2(obj, **kwds): yield o
[ "def", "_refs", "(", "obj", ",", "named", ",", "*", "ats", ",", "*", "*", "kwds", ")", ":", "if", "named", ":", "for", "a", "in", "ats", ":", "# cf. inspect.getmembers()", "if", "hasattr", "(", "obj", ",", "a", ")", ":", "yield", "_NamedRef", "(", ...
Return specific attribute objects of an object.
[ "Return", "specific", "attribute", "objects", "of", "an", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L511-L527
230,872
airspeed-velocity/asv
asv/extern/asizeof.py
_SI
def _SI(size, K=1024, i='i'): '''Return size as SI string. ''' if 1 < K < size: f = float(size) for si in iter('KMGPTE'): f /= K if f < K: return ' or %.1f %s%sB' % (f, si, i) return ''
python
def _SI(size, K=1024, i='i'): '''Return size as SI string. ''' if 1 < K < size: f = float(size) for si in iter('KMGPTE'): f /= K if f < K: return ' or %.1f %s%sB' % (f, si, i) return ''
[ "def", "_SI", "(", "size", ",", "K", "=", "1024", ",", "i", "=", "'i'", ")", ":", "if", "1", "<", "K", "<", "size", ":", "f", "=", "float", "(", "size", ")", "for", "si", "in", "iter", "(", "'KMGPTE'", ")", ":", "f", "/=", "K", "if", "f",...
Return size as SI string.
[ "Return", "size", "as", "SI", "string", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L542-L551
230,873
airspeed-velocity/asv
asv/extern/asizeof.py
_module_refs
def _module_refs(obj, named): '''Return specific referents of a module object. ''' # ignore this very module if obj.__name__ == __name__: return () # module is essentially a dict return _dict_refs(obj.__dict__, named)
python
def _module_refs(obj, named): '''Return specific referents of a module object. ''' # ignore this very module if obj.__name__ == __name__: return () # module is essentially a dict return _dict_refs(obj.__dict__, named)
[ "def", "_module_refs", "(", "obj", ",", "named", ")", ":", "# ignore this very module", "if", "obj", ".", "__name__", "==", "__name__", ":", "return", "(", ")", "# module is essentially a dict", "return", "_dict_refs", "(", "obj", ".", "__dict__", ",", "named", ...
Return specific referents of a module object.
[ "Return", "specific", "referents", "of", "a", "module", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L634-L641
230,874
airspeed-velocity/asv
asv/extern/asizeof.py
_len_frame
def _len_frame(obj): '''Length of a frame object. ''' c = getattr(obj, 'f_code', None) if c: n = _len_code(c) else: n = 0 return n
python
def _len_frame(obj): '''Length of a frame object. ''' c = getattr(obj, 'f_code', None) if c: n = _len_code(c) else: n = 0 return n
[ "def", "_len_frame", "(", "obj", ")", ":", "c", "=", "getattr", "(", "obj", ",", "'f_code'", ",", "None", ")", "if", "c", ":", "n", "=", "_len_code", "(", "c", ")", "else", ":", "n", "=", "0", "return", "n" ]
Length of a frame object.
[ "Length", "of", "a", "frame", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L726-L734
230,875
airspeed-velocity/asv
asv/extern/asizeof.py
_len_slice
def _len_slice(obj): '''Slice length. ''' try: return ((obj.stop - obj.start + 1) // obj.step) except (AttributeError, TypeError): return 0
python
def _len_slice(obj): '''Slice length. ''' try: return ((obj.stop - obj.start + 1) // obj.step) except (AttributeError, TypeError): return 0
[ "def", "_len_slice", "(", "obj", ")", ":", "try", ":", "return", "(", "(", "obj", ".", "stop", "-", "obj", ".", "start", "+", "1", ")", "//", "obj", ".", "step", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "return", "0" ]
Slice length.
[ "Slice", "length", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L788-L794
230,876
airspeed-velocity/asv
asv/extern/asizeof.py
_claskey
def _claskey(obj, style): '''Wrap an old- or new-style class object. ''' i = id(obj) k = _claskeys.get(i, None) if not k: _claskeys[i] = k = _Claskey(obj, style) return k
python
def _claskey(obj, style): '''Wrap an old- or new-style class object. ''' i = id(obj) k = _claskeys.get(i, None) if not k: _claskeys[i] = k = _Claskey(obj, style) return k
[ "def", "_claskey", "(", "obj", ",", "style", ")", ":", "i", "=", "id", "(", "obj", ")", "k", "=", "_claskeys", ".", "get", "(", "i", ",", "None", ")", "if", "not", "k", ":", "_claskeys", "[", "i", "]", "=", "k", "=", "_Claskey", "(", "obj", ...
Wrap an old- or new-style class object.
[ "Wrap", "an", "old", "-", "or", "new", "-", "style", "class", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L858-L865
230,877
airspeed-velocity/asv
asv/extern/asizeof.py
_typedef_both
def _typedef_both(t, base=0, item=0, leng=None, refs=None, kind=_kind_static, heap=False): '''Add new typedef for both data and code. ''' v = _Typedef(base=_basicsize(t, base=base), item=_itemsize(t, item), refs=refs, leng=leng, both=True, kind=kind, type=t) v.save(t, base=base, heap=heap) return v
python
def _typedef_both(t, base=0, item=0, leng=None, refs=None, kind=_kind_static, heap=False): '''Add new typedef for both data and code. ''' v = _Typedef(base=_basicsize(t, base=base), item=_itemsize(t, item), refs=refs, leng=leng, both=True, kind=kind, type=t) v.save(t, base=base, heap=heap) return v
[ "def", "_typedef_both", "(", "t", ",", "base", "=", "0", ",", "item", "=", "0", ",", "leng", "=", "None", ",", "refs", "=", "None", ",", "kind", "=", "_kind_static", ",", "heap", "=", "False", ")", ":", "v", "=", "_Typedef", "(", "base", "=", "...
Add new typedef for both data and code.
[ "Add", "new", "typedef", "for", "both", "data", "and", "code", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1101-L1108
230,878
airspeed-velocity/asv
asv/extern/asizeof.py
_typedef_code
def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False): '''Add new typedef for code only. ''' v = _Typedef(base=_basicsize(t, base=base), refs=refs, both=False, kind=kind, type=t) v.save(t, base=base, heap=heap) return v
python
def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False): '''Add new typedef for code only. ''' v = _Typedef(base=_basicsize(t, base=base), refs=refs, both=False, kind=kind, type=t) v.save(t, base=base, heap=heap) return v
[ "def", "_typedef_code", "(", "t", ",", "base", "=", "0", ",", "refs", "=", "None", ",", "kind", "=", "_kind_static", ",", "heap", "=", "False", ")", ":", "v", "=", "_Typedef", "(", "base", "=", "_basicsize", "(", "t", ",", "base", "=", "base", ")...
Add new typedef for code only.
[ "Add", "new", "typedef", "for", "code", "only", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1110-L1117
230,879
airspeed-velocity/asv
asv/extern/asizeof.py
_typedef
def _typedef(obj, derive=False, infer=False): '''Create a new typedef for an object. ''' t = type(obj) v = _Typedef(base=_basicsize(t, obj=obj), kind=_kind_dynamic, type=t) ##_printf('new %r %r/%r %s', t, _basicsize(t), _itemsize(t), _repr(dir(obj))) if ismodule(obj): # handle module like dict v.dup(item=_dict_typedef.item + _sizeof_CPyModuleObject, leng=_len_module, refs=_module_refs) elif isframe(obj): v.set(base=_basicsize(t, base=_sizeof_CPyFrameObject, obj=obj), item=_itemsize(t), leng=_len_frame, refs=_frame_refs) elif iscode(obj): v.set(base=_basicsize(t, base=_sizeof_CPyCodeObject, obj=obj), item=_sizeof_Cvoidp, leng=_len_code, refs=_co_refs, both=False) # code only elif _callable(obj): if isclass(obj): # class or type v.set(refs=_class_refs, both=False) # code only if obj.__module__ in _builtin_modules: v.set(kind=_kind_ignored) elif isbuiltin(obj): # function or method v.set(both=False, # code only kind=_kind_ignored) elif isfunction(obj): v.set(refs=_func_refs, both=False) # code only elif ismethod(obj): v.set(refs=_im_refs, both=False) # code only elif isclass(t): # callable instance, e.g. SCons, # handle like any other instance further below v.set(item=_itemsize(t), safe_len=True, refs=_inst_refs) # not code only! else: v.set(both=False) # code only elif _issubclass(t, dict): v.dup(kind=_kind_derived) elif _isdictclass(obj) or (infer and _infer_dict(obj)): v.dup(kind=_kind_inferred) elif getattr(obj, '__module__', None) in _builtin_modules: v.set(kind=_kind_ignored) else: # assume an instance of some class if derive: p = _derive_typedef(t) if p: # duplicate parent v.dup(other=p, kind=_kind_derived) return v if _issubclass(t, Exception): v.set(item=_itemsize(t), safe_len=True, refs=_exc_refs, kind=_kind_derived) elif isinstance(obj, Exception): v.set(item=_itemsize(t), safe_len=True, refs=_exc_refs) else: v.set(item=_itemsize(t), safe_len=True, refs=_inst_refs) return v
python
def _typedef(obj, derive=False, infer=False): '''Create a new typedef for an object. ''' t = type(obj) v = _Typedef(base=_basicsize(t, obj=obj), kind=_kind_dynamic, type=t) ##_printf('new %r %r/%r %s', t, _basicsize(t), _itemsize(t), _repr(dir(obj))) if ismodule(obj): # handle module like dict v.dup(item=_dict_typedef.item + _sizeof_CPyModuleObject, leng=_len_module, refs=_module_refs) elif isframe(obj): v.set(base=_basicsize(t, base=_sizeof_CPyFrameObject, obj=obj), item=_itemsize(t), leng=_len_frame, refs=_frame_refs) elif iscode(obj): v.set(base=_basicsize(t, base=_sizeof_CPyCodeObject, obj=obj), item=_sizeof_Cvoidp, leng=_len_code, refs=_co_refs, both=False) # code only elif _callable(obj): if isclass(obj): # class or type v.set(refs=_class_refs, both=False) # code only if obj.__module__ in _builtin_modules: v.set(kind=_kind_ignored) elif isbuiltin(obj): # function or method v.set(both=False, # code only kind=_kind_ignored) elif isfunction(obj): v.set(refs=_func_refs, both=False) # code only elif ismethod(obj): v.set(refs=_im_refs, both=False) # code only elif isclass(t): # callable instance, e.g. SCons, # handle like any other instance further below v.set(item=_itemsize(t), safe_len=True, refs=_inst_refs) # not code only! else: v.set(both=False) # code only elif _issubclass(t, dict): v.dup(kind=_kind_derived) elif _isdictclass(obj) or (infer and _infer_dict(obj)): v.dup(kind=_kind_inferred) elif getattr(obj, '__module__', None) in _builtin_modules: v.set(kind=_kind_ignored) else: # assume an instance of some class if derive: p = _derive_typedef(t) if p: # duplicate parent v.dup(other=p, kind=_kind_derived) return v if _issubclass(t, Exception): v.set(item=_itemsize(t), safe_len=True, refs=_exc_refs, kind=_kind_derived) elif isinstance(obj, Exception): v.set(item=_itemsize(t), safe_len=True, refs=_exc_refs) else: v.set(item=_itemsize(t), safe_len=True, refs=_inst_refs) return v
[ "def", "_typedef", "(", "obj", ",", "derive", "=", "False", ",", "infer", "=", "False", ")", ":", "t", "=", "type", "(", "obj", ")", "v", "=", "_Typedef", "(", "base", "=", "_basicsize", "(", "t", ",", "obj", "=", "obj", ")", ",", "kind", "=", ...
Create a new typedef for an object.
[ "Create", "a", "new", "typedef", "for", "an", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1360-L1425
230,880
airspeed-velocity/asv
asv/extern/asizeof.py
adict
def adict(*classes): '''Install one or more classes to be handled as dict. ''' a = True for c in classes: # if class is dict-like, add class # name to _dict_classes[module] if isclass(c) and _infer_dict(c): t = _dict_classes.get(c.__module__, ()) if c.__name__ not in t: # extend tuple _dict_classes[c.__module__] = t + (c.__name__,) else: # not a dict-like class a = False return a
python
def adict(*classes): '''Install one or more classes to be handled as dict. ''' a = True for c in classes: # if class is dict-like, add class # name to _dict_classes[module] if isclass(c) and _infer_dict(c): t = _dict_classes.get(c.__module__, ()) if c.__name__ not in t: # extend tuple _dict_classes[c.__module__] = t + (c.__name__,) else: # not a dict-like class a = False return a
[ "def", "adict", "(", "*", "classes", ")", ":", "a", "=", "True", "for", "c", "in", "classes", ":", "# if class is dict-like, add class", "# name to _dict_classes[module]", "if", "isclass", "(", "c", ")", "and", "_infer_dict", "(", "c", ")", ":", "t", "=", ...
Install one or more classes to be handled as dict.
[ "Install", "one", "or", "more", "classes", "to", "be", "handled", "as", "dict", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1962-L1975
230,881
airspeed-velocity/asv
asv/extern/asizeof.py
asizeof
def asizeof(*objs, **opts): '''Return the combined size in bytes of all objects passed as positional argments. The available options and defaults are the following. *align=8* -- size alignment *all=False* -- all current objects *clip=80* -- clip ``repr()`` strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics Set *align* to a power of 2 to align sizes. Any value less than 2 avoids size alignment. All current module, global and stack objects are sized if *all* is True and if no positional arguments are supplied. A positive *clip* value truncates all repr() strings to at most *clip* characters. The (byte)code size of callable objects like functions, methods, classes, etc. is included only if *code* is True. If *derive* is True, new types are handled like an existing (super) type provided there is one and only of those. By default certain base types like object, super, etc. are ignored. Set *ignored* to False to include those. If *infer* is True, new types are inferred from attributes (only implemented for dict types on callable attributes as get, has_key, items, keys and values). Set *limit* to a positive value to accumulate the sizes of the referents of each object, recursively up to the limit. Using *limit=0* returns the sum of the flat[4] sizes of the given objects. High *limit* values may cause runtime errors and miss objects for sizing. A positive value for *stats* prints up to 8 statistics, (1) a summary of the number of objects sized and seen, (2) a simple profile of the sized objects by type and (3+) up to 6 tables showing the static, dynamic, derived, ignored, inferred and dict types used, found resp. installed. The fractional part of the *stats* value (x100) is the cutoff percentage for simple profiles. [4] See the documentation of this module for the definition of flat size. ''' t, p = _objs_opts(objs, **opts) if t: _asizer.reset(**p) s = _asizer.asizeof(*t) _asizer.print_stats(objs=t, opts=opts) # show opts as _kwdstr _asizer._clear() else: s = 0 return s
python
def asizeof(*objs, **opts): '''Return the combined size in bytes of all objects passed as positional argments. The available options and defaults are the following. *align=8* -- size alignment *all=False* -- all current objects *clip=80* -- clip ``repr()`` strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics Set *align* to a power of 2 to align sizes. Any value less than 2 avoids size alignment. All current module, global and stack objects are sized if *all* is True and if no positional arguments are supplied. A positive *clip* value truncates all repr() strings to at most *clip* characters. The (byte)code size of callable objects like functions, methods, classes, etc. is included only if *code* is True. If *derive* is True, new types are handled like an existing (super) type provided there is one and only of those. By default certain base types like object, super, etc. are ignored. Set *ignored* to False to include those. If *infer* is True, new types are inferred from attributes (only implemented for dict types on callable attributes as get, has_key, items, keys and values). Set *limit* to a positive value to accumulate the sizes of the referents of each object, recursively up to the limit. Using *limit=0* returns the sum of the flat[4] sizes of the given objects. High *limit* values may cause runtime errors and miss objects for sizing. A positive value for *stats* prints up to 8 statistics, (1) a summary of the number of objects sized and seen, (2) a simple profile of the sized objects by type and (3+) up to 6 tables showing the static, dynamic, derived, ignored, inferred and dict types used, found resp. installed. The fractional part of the *stats* value (x100) is the cutoff percentage for simple profiles. [4] See the documentation of this module for the definition of flat size. ''' t, p = _objs_opts(objs, **opts) if t: _asizer.reset(**p) s = _asizer.asizeof(*t) _asizer.print_stats(objs=t, opts=opts) # show opts as _kwdstr _asizer._clear() else: s = 0 return s
[ "def", "asizeof", "(", "*", "objs", ",", "*", "*", "opts", ")", ":", "t", ",", "p", "=", "_objs_opts", "(", "objs", ",", "*", "*", "opts", ")", "if", "t", ":", "_asizer", ".", "reset", "(", "*", "*", "p", ")", "s", "=", "_asizer", ".", "asi...
Return the combined size in bytes of all objects passed as positional argments. The available options and defaults are the following. *align=8* -- size alignment *all=False* -- all current objects *clip=80* -- clip ``repr()`` strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics Set *align* to a power of 2 to align sizes. Any value less than 2 avoids size alignment. All current module, global and stack objects are sized if *all* is True and if no positional arguments are supplied. A positive *clip* value truncates all repr() strings to at most *clip* characters. The (byte)code size of callable objects like functions, methods, classes, etc. is included only if *code* is True. If *derive* is True, new types are handled like an existing (super) type provided there is one and only of those. By default certain base types like object, super, etc. are ignored. Set *ignored* to False to include those. If *infer* is True, new types are inferred from attributes (only implemented for dict types on callable attributes as get, has_key, items, keys and values). Set *limit* to a positive value to accumulate the sizes of the referents of each object, recursively up to the limit. Using *limit=0* returns the sum of the flat[4] sizes of the given objects. High *limit* values may cause runtime errors and miss objects for sizing. A positive value for *stats* prints up to 8 statistics, (1) a summary of the number of objects sized and seen, (2) a simple profile of the sized objects by type and (3+) up to 6 tables showing the static, dynamic, derived, ignored, inferred and dict types used, found resp. installed. The fractional part of the *stats* value (x100) is the cutoff percentage for simple profiles. [4] See the documentation of this module for the definition of flat size.
[ "Return", "the", "combined", "size", "in", "bytes", "of", "all", "objects", "passed", "as", "positional", "argments", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L2022-L2091
230,882
airspeed-velocity/asv
asv/extern/asizeof.py
asizesof
def asizesof(*objs, **opts): '''Return a tuple containing the size in bytes of all objects passed as positional argments using the following options. *align=8* -- size alignment *clip=80* -- clip ``repr()`` strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics See function **asizeof** for a description of the options. The length of the returned tuple equals the number of given objects. ''' if 'all' in opts: raise KeyError('invalid option: %s=%r' % ('all', opts['all'])) if objs: # size given objects _asizer.reset(**opts) t = _asizer.asizesof(*objs) _asizer.print_stats(objs, opts=opts, sizes=t) # show opts as _kwdstr _asizer._clear() else: t = () return t
python
def asizesof(*objs, **opts): '''Return a tuple containing the size in bytes of all objects passed as positional argments using the following options. *align=8* -- size alignment *clip=80* -- clip ``repr()`` strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics See function **asizeof** for a description of the options. The length of the returned tuple equals the number of given objects. ''' if 'all' in opts: raise KeyError('invalid option: %s=%r' % ('all', opts['all'])) if objs: # size given objects _asizer.reset(**opts) t = _asizer.asizesof(*objs) _asizer.print_stats(objs, opts=opts, sizes=t) # show opts as _kwdstr _asizer._clear() else: t = () return t
[ "def", "asizesof", "(", "*", "objs", ",", "*", "*", "opts", ")", ":", "if", "'all'", "in", "opts", ":", "raise", "KeyError", "(", "'invalid option: %s=%r'", "%", "(", "'all'", ",", "opts", "[", "'all'", "]", ")", ")", "if", "objs", ":", "# size given...
Return a tuple containing the size in bytes of all objects passed as positional argments using the following options. *align=8* -- size alignment *clip=80* -- clip ``repr()`` strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics See function **asizeof** for a description of the options. The length of the returned tuple equals the number of given objects.
[ "Return", "a", "tuple", "containing", "the", "size", "in", "bytes", "of", "all", "objects", "passed", "as", "positional", "argments", "using", "the", "following", "options", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L2093-L2127
230,883
airspeed-velocity/asv
asv/extern/asizeof.py
_typedefof
def _typedefof(obj, save=False, **opts): '''Get the typedef for an object. ''' k = _objkey(obj) v = _typedefs.get(k, None) if not v: # new typedef v = _typedef(obj, **opts) if save: _typedefs[k] = v return v
python
def _typedefof(obj, save=False, **opts): '''Get the typedef for an object. ''' k = _objkey(obj) v = _typedefs.get(k, None) if not v: # new typedef v = _typedef(obj, **opts) if save: _typedefs[k] = v return v
[ "def", "_typedefof", "(", "obj", ",", "save", "=", "False", ",", "*", "*", "opts", ")", ":", "k", "=", "_objkey", "(", "obj", ")", "v", "=", "_typedefs", ".", "get", "(", "k", ",", "None", ")", "if", "not", "v", ":", "# new typedef", "v", "=", ...
Get the typedef for an object.
[ "Get", "the", "typedef", "for", "an", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L2129-L2138
230,884
airspeed-velocity/asv
asv/extern/asizeof.py
_Typedef.args
def args(self): # as args tuple '''Return all attributes as arguments tuple. ''' return (self.base, self.item, self.leng, self.refs, self.both, self.kind, self.type)
python
def args(self): # as args tuple '''Return all attributes as arguments tuple. ''' return (self.base, self.item, self.leng, self.refs, self.both, self.kind, self.type)
[ "def", "args", "(", "self", ")", ":", "# as args tuple", "return", "(", "self", ".", "base", ",", "self", ".", "item", ",", "self", ".", "leng", ",", "self", ".", "refs", ",", "self", ".", "both", ",", "self", ".", "kind", ",", "self", ".", "type...
Return all attributes as arguments tuple.
[ "Return", "all", "attributes", "as", "arguments", "tuple", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L992-L996
230,885
airspeed-velocity/asv
asv/extern/asizeof.py
_Typedef.dup
def dup(self, other=None, **kwds): '''Duplicate attributes of dict or other typedef. ''' if other is None: d = _dict_typedef.kwds() else: d = other.kwds() d.update(kwds) self.reset(**d)
python
def dup(self, other=None, **kwds): '''Duplicate attributes of dict or other typedef. ''' if other is None: d = _dict_typedef.kwds() else: d = other.kwds() d.update(kwds) self.reset(**d)
[ "def", "dup", "(", "self", ",", "other", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "other", "is", "None", ":", "d", "=", "_dict_typedef", ".", "kwds", "(", ")", "else", ":", "d", "=", "other", ".", "kwds", "(", ")", "d", ".", "updat...
Duplicate attributes of dict or other typedef.
[ "Duplicate", "attributes", "of", "dict", "or", "other", "typedef", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L998-L1006
230,886
airspeed-velocity/asv
asv/extern/asizeof.py
_Typedef.flat
def flat(self, obj, mask=0): '''Return the aligned flat size. ''' s = self.base if self.leng and self.item > 0: # include items s += self.leng(obj) * self.item if _getsizeof: # _getsizeof prevails s = _getsizeof(obj, s) if mask: # align s = (s + mask) & ~mask return s
python
def flat(self, obj, mask=0): '''Return the aligned flat size. ''' s = self.base if self.leng and self.item > 0: # include items s += self.leng(obj) * self.item if _getsizeof: # _getsizeof prevails s = _getsizeof(obj, s) if mask: # align s = (s + mask) & ~mask return s
[ "def", "flat", "(", "self", ",", "obj", ",", "mask", "=", "0", ")", ":", "s", "=", "self", ".", "base", "if", "self", ".", "leng", "and", "self", ".", "item", ">", "0", ":", "# include items", "s", "+=", "self", ".", "leng", "(", "obj", ")", ...
Return the aligned flat size.
[ "Return", "the", "aligned", "flat", "size", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1008-L1018
230,887
airspeed-velocity/asv
asv/extern/asizeof.py
_Typedef.kwds
def kwds(self): '''Return all attributes as keywords dict. ''' # no dict(refs=self.refs, ..., kind=self.kind) in Python 2.0 return _kwds(base=self.base, item=self.item, leng=self.leng, refs=self.refs, both=self.both, kind=self.kind, type=self.type)
python
def kwds(self): '''Return all attributes as keywords dict. ''' # no dict(refs=self.refs, ..., kind=self.kind) in Python 2.0 return _kwds(base=self.base, item=self.item, leng=self.leng, refs=self.refs, both=self.both, kind=self.kind, type=self.type)
[ "def", "kwds", "(", "self", ")", ":", "# no dict(refs=self.refs, ..., kind=self.kind) in Python 2.0", "return", "_kwds", "(", "base", "=", "self", ".", "base", ",", "item", "=", "self", ".", "item", ",", "leng", "=", "self", ".", "leng", ",", "refs", "=", ...
Return all attributes as keywords dict.
[ "Return", "all", "attributes", "as", "keywords", "dict", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1031-L1037
230,888
airspeed-velocity/asv
asv/extern/asizeof.py
_Typedef.save
def save(self, t, base=0, heap=False): '''Save this typedef plus its class typedef. ''' c, k = _keytuple(t) if k and k not in _typedefs: # instance key _typedefs[k] = self if c and c not in _typedefs: # class key if t.__module__ in _builtin_modules: k = _kind_ignored # default else: k = self.kind _typedefs[c] = _Typedef(base=_basicsize(type(t), base=base, heap=heap), refs=_type_refs, both=False, kind=k, type=t) elif isbuiltin(t) and t not in _typedefs: # array, range, xrange in Python 2.x _typedefs[t] = _Typedef(base=_basicsize(t, base=base), both=False, kind=_kind_ignored, type=t) else: raise KeyError('asizeof typedef %r bad: %r %r' % (self, (c, k), self.both))
python
def save(self, t, base=0, heap=False): '''Save this typedef plus its class typedef. ''' c, k = _keytuple(t) if k and k not in _typedefs: # instance key _typedefs[k] = self if c and c not in _typedefs: # class key if t.__module__ in _builtin_modules: k = _kind_ignored # default else: k = self.kind _typedefs[c] = _Typedef(base=_basicsize(type(t), base=base, heap=heap), refs=_type_refs, both=False, kind=k, type=t) elif isbuiltin(t) and t not in _typedefs: # array, range, xrange in Python 2.x _typedefs[t] = _Typedef(base=_basicsize(t, base=base), both=False, kind=_kind_ignored, type=t) else: raise KeyError('asizeof typedef %r bad: %r %r' % (self, (c, k), self.both))
[ "def", "save", "(", "self", ",", "t", ",", "base", "=", "0", ",", "heap", "=", "False", ")", ":", "c", ",", "k", "=", "_keytuple", "(", "t", ")", "if", "k", "and", "k", "not", "in", "_typedefs", ":", "# instance key", "_typedefs", "[", "k", "]"...
Save this typedef plus its class typedef.
[ "Save", "this", "typedef", "plus", "its", "class", "typedef", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1039-L1057
230,889
airspeed-velocity/asv
asv/extern/asizeof.py
_Typedef.set
def set(self, safe_len=False, **kwds): '''Set one or more attributes. ''' if kwds: # double check d = self.kwds() d.update(kwds) self.reset(**d) if safe_len and self.item: self.leng = _len
python
def set(self, safe_len=False, **kwds): '''Set one or more attributes. ''' if kwds: # double check d = self.kwds() d.update(kwds) self.reset(**d) if safe_len and self.item: self.leng = _len
[ "def", "set", "(", "self", ",", "safe_len", "=", "False", ",", "*", "*", "kwds", ")", ":", "if", "kwds", ":", "# double check", "d", "=", "self", ".", "kwds", "(", ")", "d", ".", "update", "(", "kwds", ")", "self", ".", "reset", "(", "*", "*", ...
Set one or more attributes.
[ "Set", "one", "or", "more", "attributes", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1059-L1067
230,890
airspeed-velocity/asv
asv/extern/asizeof.py
_Typedef.reset
def reset(self, base=0, item=0, leng=None, refs=None, both=True, kind=None, type=None): '''Reset all specified attributes. ''' if base < 0: raise ValueError('invalid option: %s=%r' % ('base', base)) else: self.base = base if item < 0: raise ValueError('invalid option: %s=%r' % ('item', item)) else: self.item = item if leng in _all_lengs: # XXX or _callable(leng) self.leng = leng else: raise ValueError('invalid option: %s=%r' % ('leng', leng)) if refs in _all_refs: # XXX or _callable(refs) self.refs = refs else: raise ValueError('invalid option: %s=%r' % ('refs', refs)) if both in (False, True): self.both = both else: raise ValueError('invalid option: %s=%r' % ('both', both)) if kind in _all_kinds: self.kind = kind else: raise ValueError('invalid option: %s=%r' % ('kind', kind)) self.type = type
python
def reset(self, base=0, item=0, leng=None, refs=None, both=True, kind=None, type=None): '''Reset all specified attributes. ''' if base < 0: raise ValueError('invalid option: %s=%r' % ('base', base)) else: self.base = base if item < 0: raise ValueError('invalid option: %s=%r' % ('item', item)) else: self.item = item if leng in _all_lengs: # XXX or _callable(leng) self.leng = leng else: raise ValueError('invalid option: %s=%r' % ('leng', leng)) if refs in _all_refs: # XXX or _callable(refs) self.refs = refs else: raise ValueError('invalid option: %s=%r' % ('refs', refs)) if both in (False, True): self.both = both else: raise ValueError('invalid option: %s=%r' % ('both', both)) if kind in _all_kinds: self.kind = kind else: raise ValueError('invalid option: %s=%r' % ('kind', kind)) self.type = type
[ "def", "reset", "(", "self", ",", "base", "=", "0", ",", "item", "=", "0", ",", "leng", "=", "None", ",", "refs", "=", "None", ",", "both", "=", "True", ",", "kind", "=", "None", ",", "type", "=", "None", ")", ":", "if", "base", "<", "0", "...
Reset all specified attributes.
[ "Reset", "all", "specified", "attributes", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1069-L1097
230,891
airspeed-velocity/asv
asv/extern/asizeof.py
_Prof.update
def update(self, obj, size): '''Update this profile. ''' self.number += 1 self.total += size if self.high < size: # largest self.high = size try: # prefer using weak ref self.objref, self.weak = Weakref.ref(obj), True except TypeError: self.objref, self.weak = obj, False
python
def update(self, obj, size): '''Update this profile. ''' self.number += 1 self.total += size if self.high < size: # largest self.high = size try: # prefer using weak ref self.objref, self.weak = Weakref.ref(obj), True except TypeError: self.objref, self.weak = obj, False
[ "def", "update", "(", "self", ",", "obj", ",", "size", ")", ":", "self", ".", "number", "+=", "1", "self", ".", "total", "+=", "size", "if", "self", ".", "high", "<", "size", ":", "# largest", "self", ".", "high", "=", "size", "try", ":", "# pref...
Update this profile.
[ "Update", "this", "profile", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1468-L1478
230,892
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer._printf
def _printf(self, *args, **kwargs): '''Print to configured stream if any is specified and the file argument is not already set for this specific call. ''' if self._stream and not kwargs.get('file'): kwargs['file'] = self._stream _printf(*args, **kwargs)
python
def _printf(self, *args, **kwargs): '''Print to configured stream if any is specified and the file argument is not already set for this specific call. ''' if self._stream and not kwargs.get('file'): kwargs['file'] = self._stream _printf(*args, **kwargs)
[ "def", "_printf", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_stream", "and", "not", "kwargs", ".", "get", "(", "'file'", ")", ":", "kwargs", "[", "'file'", "]", "=", "self", ".", "_stream", "_printf", "...
Print to configured stream if any is specified and the file argument is not already set for this specific call.
[ "Print", "to", "configured", "stream", "if", "any", "is", "specified", "and", "the", "file", "argument", "is", "not", "already", "set", "for", "this", "specific", "call", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1538-L1544
230,893
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer._clear
def _clear(self): '''Clear state. ''' self._depth = 0 # recursion depth self._duplicate = 0 self._incl = '' # or ' (incl. code)' self._missed = 0 # due to errors self._profile = False self._profs = {} self._seen = {} self._total = 0 # total size for k in _keys(self._excl_d): self._excl_d[k] = 0
python
def _clear(self): '''Clear state. ''' self._depth = 0 # recursion depth self._duplicate = 0 self._incl = '' # or ' (incl. code)' self._missed = 0 # due to errors self._profile = False self._profs = {} self._seen = {} self._total = 0 # total size for k in _keys(self._excl_d): self._excl_d[k] = 0
[ "def", "_clear", "(", "self", ")", ":", "self", ".", "_depth", "=", "0", "# recursion depth", "self", ".", "_duplicate", "=", "0", "self", ".", "_incl", "=", "''", "# or ' (incl. code)'", "self", ".", "_missed", "=", "0", "# due to errors", "self", ".", ...
Clear state.
[ "Clear", "state", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1546-L1558
230,894
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer._prof
def _prof(self, key): '''Get _Prof object. ''' p = self._profs.get(key, None) if not p: self._profs[key] = p = _Prof() return p
python
def _prof(self, key): '''Get _Prof object. ''' p = self._profs.get(key, None) if not p: self._profs[key] = p = _Prof() return p
[ "def", "_prof", "(", "self", ",", "key", ")", ":", "p", "=", "self", ".", "_profs", ".", "get", "(", "key", ",", "None", ")", "if", "not", "p", ":", "self", ".", "_profs", "[", "key", "]", "=", "p", "=", "_Prof", "(", ")", "return", "p" ]
Get _Prof object.
[ "Get", "_Prof", "object", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1570-L1576
230,895
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer._sizer
def _sizer(self, obj, deep, sized): '''Size an object, recursively. ''' s, f, i = 0, 0, id(obj) # skip obj if seen before # or if ref of a given obj if i in self._seen: if deep: self._seen[i] += 1 if sized: s = sized(s, f, name=self._nameof(obj)) return s else: self._seen[i] = 0 try: k, rs = _objkey(obj), [] if k in self._excl_d: self._excl_d[k] += 1 else: v = _typedefs.get(k, None) if not v: # new typedef _typedefs[k] = v = _typedef(obj, derive=self._derive_, infer=self._infer_) if (v.both or self._code_) and v.kind is not self._ign_d: s = f = v.flat(obj, self._mask) # flat size if self._profile: # profile type self._prof(k).update(obj, s) # recurse, but not for nested modules if v.refs and deep < self._limit_ and not (deep and ismodule(obj)): # add sizes of referents r, z, d = v.refs, self._sizer, deep + 1 if sized and deep < self._detail_: # use named referents for o in r(obj, True): if isinstance(o, _NamedRef): t = z(o.ref, d, sized) t.name = o.name else: t = z(o, d, sized) t.name = self._nameof(o) rs.append(t) s += t.size else: # no sum(<generator_expression>) in Python 2.2 for o in r(obj, False): s += z(o, d, None) # recursion depth if self._depth < d: self._depth = d self._seen[i] += 1 except RuntimeError: # XXX RecursionLimitExceeded: self._missed += 1 if sized: s = sized(s, f, name=self._nameof(obj), refs=rs) return s
python
def _sizer(self, obj, deep, sized): '''Size an object, recursively. ''' s, f, i = 0, 0, id(obj) # skip obj if seen before # or if ref of a given obj if i in self._seen: if deep: self._seen[i] += 1 if sized: s = sized(s, f, name=self._nameof(obj)) return s else: self._seen[i] = 0 try: k, rs = _objkey(obj), [] if k in self._excl_d: self._excl_d[k] += 1 else: v = _typedefs.get(k, None) if not v: # new typedef _typedefs[k] = v = _typedef(obj, derive=self._derive_, infer=self._infer_) if (v.both or self._code_) and v.kind is not self._ign_d: s = f = v.flat(obj, self._mask) # flat size if self._profile: # profile type self._prof(k).update(obj, s) # recurse, but not for nested modules if v.refs and deep < self._limit_ and not (deep and ismodule(obj)): # add sizes of referents r, z, d = v.refs, self._sizer, deep + 1 if sized and deep < self._detail_: # use named referents for o in r(obj, True): if isinstance(o, _NamedRef): t = z(o.ref, d, sized) t.name = o.name else: t = z(o, d, sized) t.name = self._nameof(o) rs.append(t) s += t.size else: # no sum(<generator_expression>) in Python 2.2 for o in r(obj, False): s += z(o, d, None) # recursion depth if self._depth < d: self._depth = d self._seen[i] += 1 except RuntimeError: # XXX RecursionLimitExceeded: self._missed += 1 if sized: s = sized(s, f, name=self._nameof(obj), refs=rs) return s
[ "def", "_sizer", "(", "self", ",", "obj", ",", "deep", ",", "sized", ")", ":", "s", ",", "f", ",", "i", "=", "0", ",", "0", ",", "id", "(", "obj", ")", "# skip obj if seen before", "# or if ref of a given obj", "if", "i", "in", "self", ".", "_seen", ...
Size an object, recursively.
[ "Size", "an", "object", "recursively", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1583-L1636
230,896
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer.exclude_refs
def exclude_refs(self, *objs): '''Exclude any references to the specified objects from sizing. While any references to the given objects are excluded, the objects will be sized if specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**. ''' for o in objs: self._seen.setdefault(id(o), 0)
python
def exclude_refs(self, *objs): '''Exclude any references to the specified objects from sizing. While any references to the given objects are excluded, the objects will be sized if specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**. ''' for o in objs: self._seen.setdefault(id(o), 0)
[ "def", "exclude_refs", "(", "self", ",", "*", "objs", ")", ":", "for", "o", "in", "objs", ":", "self", ".", "_seen", ".", "setdefault", "(", "id", "(", "o", ")", ",", "0", ")" ]
Exclude any references to the specified objects from sizing. While any references to the given objects are excluded, the objects will be sized if specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**.
[ "Exclude", "any", "references", "to", "the", "specified", "objects", "from", "sizing", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1693-L1701
230,897
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer.exclude_types
def exclude_types(self, *objs): '''Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**. ''' for o in objs: for t in _keytuple(o): if t and t not in self._excl_d: self._excl_d[t] = 0
python
def exclude_types(self, *objs): '''Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**. ''' for o in objs: for t in _keytuple(o): if t and t not in self._excl_d: self._excl_d[t] = 0
[ "def", "exclude_types", "(", "self", ",", "*", "objs", ")", ":", "for", "o", "in", "objs", ":", "for", "t", "in", "_keytuple", "(", "o", ")", ":", "if", "t", "and", "t", "not", "in", "self", ".", "_excl_d", ":", "self", ".", "_excl_d", "[", "t"...
Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**.
[ "Exclude", "the", "specified", "object", "instances", "and", "types", "from", "sizing", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1703-L1713
230,898
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer.print_summary
def print_summary(self, w=0, objs=(), **print3opts): '''Print the summary statistics. *w=0* -- indentation for each line *objs=()* -- optional, list of objects *print3options* -- print options, as in Python 3.0 ''' self._printf('%*d bytes%s%s', w, self._total, _SI(self._total), self._incl, **print3opts) if self._mask: self._printf('%*d byte aligned', w, self._mask + 1, **print3opts) self._printf('%*d byte sizeof(void*)', w, _sizeof_Cvoidp, **print3opts) n = len(objs or ()) if n > 0: d = self._duplicate or '' if d: d = ', %d duplicate' % self._duplicate self._printf('%*d object%s given%s', w, n, _plural(n), d, **print3opts) t = _sum([1 for t in _values(self._seen) if t != 0]) # [] for Python 2.2 self._printf('%*d object%s sized', w, t, _plural(t), **print3opts) if self._excl_d: t = _sum(_values(self._excl_d)) self._printf('%*d object%s excluded', w, t, _plural(t), **print3opts) t = _sum(_values(self._seen)) self._printf('%*d object%s seen', w, t, _plural(t), **print3opts) if self._missed > 0: self._printf('%*d object%s missed', w, self._missed, _plural(self._missed), **print3opts) if self._depth > 0: self._printf('%*d recursion depth', w, self._depth, **print3opts)
python
def print_summary(self, w=0, objs=(), **print3opts): '''Print the summary statistics. *w=0* -- indentation for each line *objs=()* -- optional, list of objects *print3options* -- print options, as in Python 3.0 ''' self._printf('%*d bytes%s%s', w, self._total, _SI(self._total), self._incl, **print3opts) if self._mask: self._printf('%*d byte aligned', w, self._mask + 1, **print3opts) self._printf('%*d byte sizeof(void*)', w, _sizeof_Cvoidp, **print3opts) n = len(objs or ()) if n > 0: d = self._duplicate or '' if d: d = ', %d duplicate' % self._duplicate self._printf('%*d object%s given%s', w, n, _plural(n), d, **print3opts) t = _sum([1 for t in _values(self._seen) if t != 0]) # [] for Python 2.2 self._printf('%*d object%s sized', w, t, _plural(t), **print3opts) if self._excl_d: t = _sum(_values(self._excl_d)) self._printf('%*d object%s excluded', w, t, _plural(t), **print3opts) t = _sum(_values(self._seen)) self._printf('%*d object%s seen', w, t, _plural(t), **print3opts) if self._missed > 0: self._printf('%*d object%s missed', w, self._missed, _plural(self._missed), **print3opts) if self._depth > 0: self._printf('%*d recursion depth', w, self._depth, **print3opts)
[ "def", "print_summary", "(", "self", ",", "w", "=", "0", ",", "objs", "=", "(", ")", ",", "*", "*", "print3opts", ")", ":", "self", ".", "_printf", "(", "'%*d bytes%s%s'", ",", "w", ",", "self", ".", "_total", ",", "_SI", "(", "self", ".", "_tota...
Print the summary statistics. *w=0* -- indentation for each line *objs=()* -- optional, list of objects *print3options* -- print options, as in Python 3.0
[ "Print", "the", "summary", "statistics", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1801-L1830
230,899
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer.print_typedefs
def print_typedefs(self, w=0, **print3opts): '''Print the types and dict tables. *w=0* -- indentation for each line *print3options* -- print options, as in Python 3.0 ''' for k in _all_kinds: # XXX Python 3.0 doesn't sort type objects t = [(self._prepr(a), v) for a, v in _items(_typedefs) if v.kind == k and (v.both or self._code_)] if t: self._printf('%s%*d %s type%s: basicsize, itemsize, _len_(), _refs()', linesep, w, len(t), k, _plural(len(t)), **print3opts) for a, v in _sorted(t): self._printf('%*s %s: %s', w, '', a, v, **print3opts) # dict and dict-like classes t = _sum([len(v) for v in _values(_dict_classes)]) # [] for Python 2.2 if t: self._printf('%s%*d dict/-like classes:', linesep, w, t, **print3opts) for m, v in _items(_dict_classes): self._printf('%*s %s: %s', w, '', m, self._prepr(v), **print3opts)
python
def print_typedefs(self, w=0, **print3opts): '''Print the types and dict tables. *w=0* -- indentation for each line *print3options* -- print options, as in Python 3.0 ''' for k in _all_kinds: # XXX Python 3.0 doesn't sort type objects t = [(self._prepr(a), v) for a, v in _items(_typedefs) if v.kind == k and (v.both or self._code_)] if t: self._printf('%s%*d %s type%s: basicsize, itemsize, _len_(), _refs()', linesep, w, len(t), k, _plural(len(t)), **print3opts) for a, v in _sorted(t): self._printf('%*s %s: %s', w, '', a, v, **print3opts) # dict and dict-like classes t = _sum([len(v) for v in _values(_dict_classes)]) # [] for Python 2.2 if t: self._printf('%s%*d dict/-like classes:', linesep, w, t, **print3opts) for m, v in _items(_dict_classes): self._printf('%*s %s: %s', w, '', m, self._prepr(v), **print3opts)
[ "def", "print_typedefs", "(", "self", ",", "w", "=", "0", ",", "*", "*", "print3opts", ")", ":", "for", "k", "in", "_all_kinds", ":", "# XXX Python 3.0 doesn't sort type objects", "t", "=", "[", "(", "self", ".", "_prepr", "(", "a", ")", ",", "v", ")",...
Print the types and dict tables. *w=0* -- indentation for each line *print3options* -- print options, as in Python 3.0
[ "Print", "the", "types", "and", "dict", "tables", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1832-L1852