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,700
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.proxy_route_request
def proxy_route_request(self, url, environ): """ Return the full url that this proxy request will be routed to The 'environ' PATH_INFO and REQUEST_URI will be modified based on the returned url Default is to use the 'proxy_prefix' to point to the proxy collection """ if self.proxy_default_timestamp: environ['pywb_proxy_default_timestamp'] = self.proxy_default_timestamp return self.proxy_prefix + url
python
def proxy_route_request(self, url, environ): if self.proxy_default_timestamp: environ['pywb_proxy_default_timestamp'] = self.proxy_default_timestamp return self.proxy_prefix + url
[ "def", "proxy_route_request", "(", "self", ",", "url", ",", "environ", ")", ":", "if", "self", ".", "proxy_default_timestamp", ":", "environ", "[", "'pywb_proxy_default_timestamp'", "]", "=", "self", ".", "proxy_default_timestamp", "return", "self", ".", "proxy_pr...
Return the full url that this proxy request will be routed to The 'environ' PATH_INFO and REQUEST_URI will be modified based on the returned url Default is to use the 'proxy_prefix' to point to the proxy collection
[ "Return", "the", "full", "url", "that", "this", "proxy", "request", "will", "be", "routed", "to", "The", "environ", "PATH_INFO", "and", "REQUEST_URI", "will", "be", "modified", "based", "on", "the", "returned", "url" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L582-L591
230,701
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.proxy_fetch
def proxy_fetch(self, env, url): """Proxy mode only endpoint that handles OPTIONS requests and COR fetches for Preservation Worker. Due to normal cross-origin browser restrictions in proxy mode, auto fetch worker cannot access the CSS rules of cross-origin style sheets and must re-fetch them in a manner that is CORS safe. This endpoint facilitates that by fetching the stylesheets for the auto fetch worker and then responds with its contents :param dict env: The WSGI environment dictionary :param str url: The URL of the resource to be fetched :return: WbResponse that is either response to an Options request or the results of fetching url :rtype: WbResponse """ if not self.is_proxy_enabled(env): # we are not in proxy mode so just respond with forbidden return WbResponse.text_response('proxy mode must be enabled to use this endpoint', status='403 Forbidden') if env.get('REQUEST_METHOD') == 'OPTIONS': return WbResponse.options_response(env) # ensure full URL request_url = env['REQUEST_URI'] # replace with /id_ so we do not get rewritten url = request_url.replace('/proxy-fetch', '/id_') # update WSGI environment object env['REQUEST_URI'] = self.proxy_coll + url env['PATH_INFO'] = env['PATH_INFO'].replace('/proxy-fetch', self.proxy_coll + '/id_') # make request using normal serve_content response = self.serve_content(env, self.proxy_coll, url) # for WR if isinstance(response, WbResponse): response.add_access_control_headers(env=env) return response
python
def proxy_fetch(self, env, url): if not self.is_proxy_enabled(env): # we are not in proxy mode so just respond with forbidden return WbResponse.text_response('proxy mode must be enabled to use this endpoint', status='403 Forbidden') if env.get('REQUEST_METHOD') == 'OPTIONS': return WbResponse.options_response(env) # ensure full URL request_url = env['REQUEST_URI'] # replace with /id_ so we do not get rewritten url = request_url.replace('/proxy-fetch', '/id_') # update WSGI environment object env['REQUEST_URI'] = self.proxy_coll + url env['PATH_INFO'] = env['PATH_INFO'].replace('/proxy-fetch', self.proxy_coll + '/id_') # make request using normal serve_content response = self.serve_content(env, self.proxy_coll, url) # for WR if isinstance(response, WbResponse): response.add_access_control_headers(env=env) return response
[ "def", "proxy_fetch", "(", "self", ",", "env", ",", "url", ")", ":", "if", "not", "self", ".", "is_proxy_enabled", "(", "env", ")", ":", "# we are not in proxy mode so just respond with forbidden", "return", "WbResponse", ".", "text_response", "(", "'proxy mode must...
Proxy mode only endpoint that handles OPTIONS requests and COR fetches for Preservation Worker. Due to normal cross-origin browser restrictions in proxy mode, auto fetch worker cannot access the CSS rules of cross-origin style sheets and must re-fetch them in a manner that is CORS safe. This endpoint facilitates that by fetching the stylesheets for the auto fetch worker and then responds with its contents :param dict env: The WSGI environment dictionary :param str url: The URL of the resource to be fetched :return: WbResponse that is either response to an Options request or the results of fetching url :rtype: WbResponse
[ "Proxy", "mode", "only", "endpoint", "that", "handles", "OPTIONS", "requests", "and", "COR", "fetches", "for", "Preservation", "Worker", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L593-L625
230,702
webrecorder/pywb
pywb/apps/frontendapp.py
MetadataCache.load
def load(self, coll): """Load and receive the metadata associated with a collection. If the metadata for the collection is not cached yet its metadata file is read in and stored. If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent than the cached time, the cache is updated and returned otherwise the cached version is returned. :param str coll: Name of a collection :return: The cached metadata for a collection :rtype: dict """ path = self.template_str.format(coll=coll) try: mtime = os.path.getmtime(path) obj = self.cache.get(path) except: return {} if not obj: return self.store_new(coll, path, mtime) cached_mtime, data = obj if mtime == cached_mtime == mtime: return obj return self.store_new(coll, path, mtime)
python
def load(self, coll): path = self.template_str.format(coll=coll) try: mtime = os.path.getmtime(path) obj = self.cache.get(path) except: return {} if not obj: return self.store_new(coll, path, mtime) cached_mtime, data = obj if mtime == cached_mtime == mtime: return obj return self.store_new(coll, path, mtime)
[ "def", "load", "(", "self", ",", "coll", ")", ":", "path", "=", "self", ".", "template_str", ".", "format", "(", "coll", "=", "coll", ")", "try", ":", "mtime", "=", "os", ".", "path", ".", "getmtime", "(", "path", ")", "obj", "=", "self", ".", ...
Load and receive the metadata associated with a collection. If the metadata for the collection is not cached yet its metadata file is read in and stored. If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent than the cached time, the cache is updated and returned otherwise the cached version is returned. :param str coll: Name of a collection :return: The cached metadata for a collection :rtype: dict
[ "Load", "and", "receive", "the", "metadata", "associated", "with", "a", "collection", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L641-L666
230,703
webrecorder/pywb
pywb/apps/frontendapp.py
MetadataCache.store_new
def store_new(self, coll, path, mtime): """Load a collections metadata file and store it :param str coll: The name of the collection the metadata is for :param str path: The path to the collections metadata file :param float mtime: The current mtime of the collections metadata file :return: The collections metadata :rtype: dict """ obj = load_yaml_config(path) self.cache[coll] = (mtime, obj) return obj
python
def store_new(self, coll, path, mtime): obj = load_yaml_config(path) self.cache[coll] = (mtime, obj) return obj
[ "def", "store_new", "(", "self", ",", "coll", ",", "path", ",", "mtime", ")", ":", "obj", "=", "load_yaml_config", "(", "path", ")", "self", ".", "cache", "[", "coll", "]", "=", "(", "mtime", ",", "obj", ")", "return", "obj" ]
Load a collections metadata file and store it :param str coll: The name of the collection the metadata is for :param str path: The path to the collections metadata file :param float mtime: The current mtime of the collections metadata file :return: The collections metadata :rtype: dict
[ "Load", "a", "collections", "metadata", "file", "and", "store", "it" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L668-L679
230,704
webrecorder/pywb
pywb/warcserver/index/zipnum.py
ZipNumIndexSource.load_blocks
def load_blocks(self, location, blocks, ranges, query): """ Load one or more blocks of compressed cdx lines, return a line iterator which decompresses and returns one line at a time, bounded by query.key and query.end_key """ if (logging.getLogger().getEffectiveLevel() <= logging.DEBUG): msg = 'Loading {b.count} blocks from {loc}:{b.offset}+{b.length}' logging.debug(msg.format(b=blocks, loc=location)) reader = self.blk_loader.load(location, blocks.offset, blocks.length) def decompress_block(range_): decomp = gzip_decompressor() buff = decomp.decompress(reader.read(range_)) for line in BytesIO(buff): yield line def iter_blocks(reader): try: for r in ranges: yield decompress_block(r) finally: reader.close() # iterate over all blocks iter_ = itertools.chain.from_iterable(iter_blocks(reader)) # start bound iter_ = linearsearch(iter_, query.key) # end bound iter_ = itertools.takewhile(lambda line: line < query.end_key, iter_) return iter_
python
def load_blocks(self, location, blocks, ranges, query): if (logging.getLogger().getEffectiveLevel() <= logging.DEBUG): msg = 'Loading {b.count} blocks from {loc}:{b.offset}+{b.length}' logging.debug(msg.format(b=blocks, loc=location)) reader = self.blk_loader.load(location, blocks.offset, blocks.length) def decompress_block(range_): decomp = gzip_decompressor() buff = decomp.decompress(reader.read(range_)) for line in BytesIO(buff): yield line def iter_blocks(reader): try: for r in ranges: yield decompress_block(r) finally: reader.close() # iterate over all blocks iter_ = itertools.chain.from_iterable(iter_blocks(reader)) # start bound iter_ = linearsearch(iter_, query.key) # end bound iter_ = itertools.takewhile(lambda line: line < query.end_key, iter_) return iter_
[ "def", "load_blocks", "(", "self", ",", "location", ",", "blocks", ",", "ranges", ",", "query", ")", ":", "if", "(", "logging", ".", "getLogger", "(", ")", ".", "getEffectiveLevel", "(", ")", "<=", "logging", ".", "DEBUG", ")", ":", "msg", "=", "'Loa...
Load one or more blocks of compressed cdx lines, return a line iterator which decompresses and returns one line at a time, bounded by query.key and query.end_key
[ "Load", "one", "or", "more", "blocks", "of", "compressed", "cdx", "lines", "return", "a", "line", "iterator", "which", "decompresses", "and", "returns", "one", "line", "at", "a", "time", "bounded", "by", "query", ".", "key", "and", "query", ".", "end_key" ...
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/zipnum.py#L330-L362
230,705
webrecorder/pywb
pywb/indexer/archiveindexer.py
ArchiveIndexEntryMixin.extract_mime
def extract_mime(self, mime, def_mime='unk'): """ Utility function to extract mimetype only from a full content type, removing charset settings """ self['mime'] = def_mime if mime: self['mime'] = self.MIME_RE.split(mime, 1)[0] self['_content_type'] = mime
python
def extract_mime(self, mime, def_mime='unk'): self['mime'] = def_mime if mime: self['mime'] = self.MIME_RE.split(mime, 1)[0] self['_content_type'] = mime
[ "def", "extract_mime", "(", "self", ",", "mime", ",", "def_mime", "=", "'unk'", ")", ":", "self", "[", "'mime'", "]", "=", "def_mime", "if", "mime", ":", "self", "[", "'mime'", "]", "=", "self", ".", "MIME_RE", ".", "split", "(", "mime", ",", "1", ...
Utility function to extract mimetype only from a full content type, removing charset settings
[ "Utility", "function", "to", "extract", "mimetype", "only", "from", "a", "full", "content", "type", "removing", "charset", "settings" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/indexer/archiveindexer.py#L37-L44
230,706
webrecorder/pywb
pywb/indexer/archiveindexer.py
ArchiveIndexEntryMixin.extract_status
def extract_status(self, status_headers): """ Extract status code only from status line """ self['status'] = status_headers.get_statuscode() if not self['status']: self['status'] = '-' elif self['status'] == '204' and 'Error' in status_headers.statusline: self['status'] = '-'
python
def extract_status(self, status_headers): self['status'] = status_headers.get_statuscode() if not self['status']: self['status'] = '-' elif self['status'] == '204' and 'Error' in status_headers.statusline: self['status'] = '-'
[ "def", "extract_status", "(", "self", ",", "status_headers", ")", ":", "self", "[", "'status'", "]", "=", "status_headers", ".", "get_statuscode", "(", ")", "if", "not", "self", "[", "'status'", "]", ":", "self", "[", "'status'", "]", "=", "'-'", "elif",...
Extract status code only from status line
[ "Extract", "status", "code", "only", "from", "status", "line" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/indexer/archiveindexer.py#L46-L53
230,707
webrecorder/pywb
pywb/indexer/archiveindexer.py
DefaultRecordParser.parse_warc_record
def parse_warc_record(self, record): """ Parse warc record """ entry = self._create_index_entry(record.rec_type) if record.rec_type == 'warcinfo': entry['url'] = record.rec_headers.get_header('WARC-Filename') entry['urlkey'] = entry['url'] entry['_warcinfo'] = record.raw_stream.read(record.length) return entry entry['url'] = record.rec_headers.get_header('WARC-Target-Uri') # timestamp entry['timestamp'] = iso_date_to_timestamp(record.rec_headers. get_header('WARC-Date')) # mime if record.rec_type == 'revisit': entry['mime'] = 'warc/revisit' elif self.options.get('minimal'): entry['mime'] = '-' else: def_mime = '-' if record.rec_type == 'request' else 'unk' entry.extract_mime(record.http_headers. get_header('Content-Type'), def_mime) # detected mime from WARC-Identified-Payload-Type entry['mime-detected'] = record.rec_headers.get_header( 'WARC-Identified-Payload-Type') # status -- only for response records (by convention): if record.rec_type == 'response' and not self.options.get('minimal'): entry.extract_status(record.http_headers) else: entry['status'] = '-' # digest digest = record.rec_headers.get_header('WARC-Payload-Digest') entry['digest'] = digest if digest and digest.startswith('sha1:'): entry['digest'] = digest[len('sha1:'):] elif not entry.get('digest'): entry['digest'] = '-' # optional json metadata, if present metadata = record.rec_headers.get_header('WARC-Json-Metadata') if metadata: entry['metadata'] = metadata return entry
python
def parse_warc_record(self, record): entry = self._create_index_entry(record.rec_type) if record.rec_type == 'warcinfo': entry['url'] = record.rec_headers.get_header('WARC-Filename') entry['urlkey'] = entry['url'] entry['_warcinfo'] = record.raw_stream.read(record.length) return entry entry['url'] = record.rec_headers.get_header('WARC-Target-Uri') # timestamp entry['timestamp'] = iso_date_to_timestamp(record.rec_headers. get_header('WARC-Date')) # mime if record.rec_type == 'revisit': entry['mime'] = 'warc/revisit' elif self.options.get('minimal'): entry['mime'] = '-' else: def_mime = '-' if record.rec_type == 'request' else 'unk' entry.extract_mime(record.http_headers. get_header('Content-Type'), def_mime) # detected mime from WARC-Identified-Payload-Type entry['mime-detected'] = record.rec_headers.get_header( 'WARC-Identified-Payload-Type') # status -- only for response records (by convention): if record.rec_type == 'response' and not self.options.get('minimal'): entry.extract_status(record.http_headers) else: entry['status'] = '-' # digest digest = record.rec_headers.get_header('WARC-Payload-Digest') entry['digest'] = digest if digest and digest.startswith('sha1:'): entry['digest'] = digest[len('sha1:'):] elif not entry.get('digest'): entry['digest'] = '-' # optional json metadata, if present metadata = record.rec_headers.get_header('WARC-Json-Metadata') if metadata: entry['metadata'] = metadata return entry
[ "def", "parse_warc_record", "(", "self", ",", "record", ")", ":", "entry", "=", "self", ".", "_create_index_entry", "(", "record", ".", "rec_type", ")", "if", "record", ".", "rec_type", "==", "'warcinfo'", ":", "entry", "[", "'url'", "]", "=", "record", ...
Parse warc record
[ "Parse", "warc", "record" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/indexer/archiveindexer.py#L241-L293
230,708
webrecorder/pywb
pywb/indexer/archiveindexer.py
DefaultRecordParser.parse_arc_record
def parse_arc_record(self, record): """ Parse arc record """ url = record.rec_headers.get_header('uri') url = url.replace('\r', '%0D') url = url.replace('\n', '%0A') # replace formfeed url = url.replace('\x0c', '%0C') # replace nulls url = url.replace('\x00', '%00') entry = self._create_index_entry(record.rec_type) entry['url'] = url # timestamp entry['timestamp'] = record.rec_headers.get_header('archive-date') if len(entry['timestamp']) > 14: entry['timestamp'] = entry['timestamp'][:14] if not self.options.get('minimal'): # mime entry.extract_mime(record.rec_headers.get_header('content-type')) # status entry.extract_status(record.http_headers) # digest entry['digest'] = '-' return entry
python
def parse_arc_record(self, record): url = record.rec_headers.get_header('uri') url = url.replace('\r', '%0D') url = url.replace('\n', '%0A') # replace formfeed url = url.replace('\x0c', '%0C') # replace nulls url = url.replace('\x00', '%00') entry = self._create_index_entry(record.rec_type) entry['url'] = url # timestamp entry['timestamp'] = record.rec_headers.get_header('archive-date') if len(entry['timestamp']) > 14: entry['timestamp'] = entry['timestamp'][:14] if not self.options.get('minimal'): # mime entry.extract_mime(record.rec_headers.get_header('content-type')) # status entry.extract_status(record.http_headers) # digest entry['digest'] = '-' return entry
[ "def", "parse_arc_record", "(", "self", ",", "record", ")", ":", "url", "=", "record", ".", "rec_headers", ".", "get_header", "(", "'uri'", ")", "url", "=", "url", ".", "replace", "(", "'\\r'", ",", "'%0D'", ")", "url", "=", "url", ".", "replace", "(...
Parse arc record
[ "Parse", "arc", "record" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/indexer/archiveindexer.py#L297-L326
230,709
jazzband/django-widget-tweaks
widget_tweaks/templatetags/widget_tweaks.py
render_field
def render_field(parser, token): """ Render a form field using given attribute-value pairs Takes form field as first argument and list of attribute-value pairs for all other arguments. Attribute-value pairs should be in the form of attribute=value or attribute="a value" for assignment and attribute+=value or attribute+="value" for appending. """ error_msg = '%r tag requires a form field followed by a list of attributes and values in the form attr="value"' % token.split_contents()[0] try: bits = token.split_contents() tag_name = bits[0] form_field = bits[1] attr_list = bits[2:] except ValueError: raise TemplateSyntaxError(error_msg) form_field = parser.compile_filter(form_field) set_attrs = [] append_attrs = [] for pair in attr_list: match = ATTRIBUTE_RE.match(pair) if not match: raise TemplateSyntaxError(error_msg + ": %s" % pair) dct = match.groupdict() attr, sign, value = \ dct['attr'], dct['sign'], parser.compile_filter(dct['value']) if sign == "=": set_attrs.append((attr, value)) else: append_attrs.append((attr, value)) return FieldAttributeNode(form_field, set_attrs, append_attrs)
python
def render_field(parser, token): error_msg = '%r tag requires a form field followed by a list of attributes and values in the form attr="value"' % token.split_contents()[0] try: bits = token.split_contents() tag_name = bits[0] form_field = bits[1] attr_list = bits[2:] except ValueError: raise TemplateSyntaxError(error_msg) form_field = parser.compile_filter(form_field) set_attrs = [] append_attrs = [] for pair in attr_list: match = ATTRIBUTE_RE.match(pair) if not match: raise TemplateSyntaxError(error_msg + ": %s" % pair) dct = match.groupdict() attr, sign, value = \ dct['attr'], dct['sign'], parser.compile_filter(dct['value']) if sign == "=": set_attrs.append((attr, value)) else: append_attrs.append((attr, value)) return FieldAttributeNode(form_field, set_attrs, append_attrs)
[ "def", "render_field", "(", "parser", ",", "token", ")", ":", "error_msg", "=", "'%r tag requires a form field followed by a list of attributes and values in the form attr=\"value\"'", "%", "token", ".", "split_contents", "(", ")", "[", "0", "]", "try", ":", "bits", "="...
Render a form field using given attribute-value pairs Takes form field as first argument and list of attribute-value pairs for all other arguments. Attribute-value pairs should be in the form of attribute=value or attribute="a value" for assignment and attribute+=value or attribute+="value" for appending.
[ "Render", "a", "form", "field", "using", "given", "attribute", "-", "value", "pairs" ]
f50ee92410d68e81528a7643a10544e7331af8fb
https://github.com/jazzband/django-widget-tweaks/blob/f50ee92410d68e81528a7643a10544e7331af8fb/widget_tweaks/templatetags/widget_tweaks.py#L138-L172
230,710
juanifioren/django-oidc-provider
oidc_provider/lib/endpoints/introspection.py
TokenIntrospectionEndpoint.response
def response(cls, dic, status=200): """ Create and return a response object. """ response = JsonResponse(dic, status=status) response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
python
def response(cls, dic, status=200): response = JsonResponse(dic, status=status) response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
[ "def", "response", "(", "cls", ",", "dic", ",", "status", "=", "200", ")", ":", "response", "=", "JsonResponse", "(", "dic", ",", "status", "=", "status", ")", "response", "[", "'Cache-Control'", "]", "=", "'no-store'", "response", "[", "'Pragma'", "]", ...
Create and return a response object.
[ "Create", "and", "return", "a", "response", "object", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/endpoints/introspection.py#L97-L105
230,711
juanifioren/django-oidc-provider
oidc_provider/lib/claims.py
ScopeClaims.create_response_dic
def create_response_dic(self): """ Generate the dic that will be jsonify. Checking scopes given vs registered. Returns a dic. """ dic = {} for scope in self.scopes: if scope in self._scopes_registered(): dic.update(getattr(self, 'scope_' + scope)()) dic = self._clean_dic(dic) return dic
python
def create_response_dic(self): dic = {} for scope in self.scopes: if scope in self._scopes_registered(): dic.update(getattr(self, 'scope_' + scope)()) dic = self._clean_dic(dic) return dic
[ "def", "create_response_dic", "(", "self", ")", ":", "dic", "=", "{", "}", "for", "scope", "in", "self", ".", "scopes", ":", "if", "scope", "in", "self", ".", "_scopes_registered", "(", ")", ":", "dic", ".", "update", "(", "getattr", "(", "self", ","...
Generate the dic that will be jsonify. Checking scopes given vs registered. Returns a dic.
[ "Generate", "the", "dic", "that", "will", "be", "jsonify", ".", "Checking", "scopes", "given", "vs", "registered", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/claims.py#L47-L62
230,712
juanifioren/django-oidc-provider
oidc_provider/lib/claims.py
ScopeClaims._scopes_registered
def _scopes_registered(self): """ Return a list that contains all the scopes registered in the class. """ scopes = [] for name in dir(self.__class__): if name.startswith('scope_'): scope = name.split('scope_')[1] scopes.append(scope) return scopes
python
def _scopes_registered(self): scopes = [] for name in dir(self.__class__): if name.startswith('scope_'): scope = name.split('scope_')[1] scopes.append(scope) return scopes
[ "def", "_scopes_registered", "(", "self", ")", ":", "scopes", "=", "[", "]", "for", "name", "in", "dir", "(", "self", ".", "__class__", ")", ":", "if", "name", ".", "startswith", "(", "'scope_'", ")", ":", "scope", "=", "name", ".", "split", "(", "...
Return a list that contains all the scopes registered in the class.
[ "Return", "a", "list", "that", "contains", "all", "the", "scopes", "registered", "in", "the", "class", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/claims.py#L64-L76
230,713
juanifioren/django-oidc-provider
oidc_provider/lib/claims.py
ScopeClaims._clean_dic
def _clean_dic(self, dic): """ Clean recursively all empty or None values inside a dict. """ aux_dic = dic.copy() for key, value in iter(dic.items()): if value is None or value == '': del aux_dic[key] elif type(value) is dict: cleaned_dict = self._clean_dic(value) if not cleaned_dict: del aux_dic[key] continue aux_dic[key] = cleaned_dict return aux_dic
python
def _clean_dic(self, dic): aux_dic = dic.copy() for key, value in iter(dic.items()): if value is None or value == '': del aux_dic[key] elif type(value) is dict: cleaned_dict = self._clean_dic(value) if not cleaned_dict: del aux_dic[key] continue aux_dic[key] = cleaned_dict return aux_dic
[ "def", "_clean_dic", "(", "self", ",", "dic", ")", ":", "aux_dic", "=", "dic", ".", "copy", "(", ")", "for", "key", ",", "value", "in", "iter", "(", "dic", ".", "items", "(", ")", ")", ":", "if", "value", "is", "None", "or", "value", "==", "''"...
Clean recursively all empty or None values inside a dict.
[ "Clean", "recursively", "all", "empty", "or", "None", "values", "inside", "a", "dict", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/claims.py#L78-L93
230,714
juanifioren/django-oidc-provider
oidc_provider/lib/endpoints/authorize.py
AuthorizeEndpoint.set_client_user_consent
def set_client_user_consent(self): """ Save the user consent given to a specific client. Return None. """ date_given = timezone.now() expires_at = date_given + timedelta( days=settings.get('OIDC_SKIP_CONSENT_EXPIRE')) uc, created = UserConsent.objects.get_or_create( user=self.request.user, client=self.client, defaults={ 'expires_at': expires_at, 'date_given': date_given, } ) uc.scope = self.params['scope'] # Rewrite expires_at and date_given if object already exists. if not created: uc.expires_at = expires_at uc.date_given = date_given uc.save()
python
def set_client_user_consent(self): date_given = timezone.now() expires_at = date_given + timedelta( days=settings.get('OIDC_SKIP_CONSENT_EXPIRE')) uc, created = UserConsent.objects.get_or_create( user=self.request.user, client=self.client, defaults={ 'expires_at': expires_at, 'date_given': date_given, } ) uc.scope = self.params['scope'] # Rewrite expires_at and date_given if object already exists. if not created: uc.expires_at = expires_at uc.date_given = date_given uc.save()
[ "def", "set_client_user_consent", "(", "self", ")", ":", "date_given", "=", "timezone", ".", "now", "(", ")", "expires_at", "=", "date_given", "+", "timedelta", "(", "days", "=", "settings", ".", "get", "(", "'OIDC_SKIP_CONSENT_EXPIRE'", ")", ")", "uc", ",",...
Save the user consent given to a specific client. Return None.
[ "Save", "the", "user", "consent", "given", "to", "a", "specific", "client", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/endpoints/authorize.py#L230-L255
230,715
juanifioren/django-oidc-provider
oidc_provider/lib/endpoints/authorize.py
AuthorizeEndpoint.client_has_user_consent
def client_has_user_consent(self): """ Check if already exists user consent for some client. Return bool. """ value = False try: uc = UserConsent.objects.get(user=self.request.user, client=self.client) if (set(self.params['scope']).issubset(uc.scope)) and not (uc.has_expired()): value = True except UserConsent.DoesNotExist: pass return value
python
def client_has_user_consent(self): value = False try: uc = UserConsent.objects.get(user=self.request.user, client=self.client) if (set(self.params['scope']).issubset(uc.scope)) and not (uc.has_expired()): value = True except UserConsent.DoesNotExist: pass return value
[ "def", "client_has_user_consent", "(", "self", ")", ":", "value", "=", "False", "try", ":", "uc", "=", "UserConsent", ".", "objects", ".", "get", "(", "user", "=", "self", ".", "request", ".", "user", ",", "client", "=", "self", ".", "client", ")", "...
Check if already exists user consent for some client. Return bool.
[ "Check", "if", "already", "exists", "user", "consent", "for", "some", "client", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/endpoints/authorize.py#L257-L271
230,716
juanifioren/django-oidc-provider
oidc_provider/lib/endpoints/authorize.py
AuthorizeEndpoint.get_scopes_information
def get_scopes_information(self): """ Return a list with the description of all the scopes requested. """ scopes = StandardScopeClaims.get_scopes_info(self.params['scope']) if settings.get('OIDC_EXTRA_SCOPE_CLAIMS'): scopes_extra = settings.get( 'OIDC_EXTRA_SCOPE_CLAIMS', import_str=True).get_scopes_info(self.params['scope']) for index_extra, scope_extra in enumerate(scopes_extra): for index, scope in enumerate(scopes[:]): if scope_extra['scope'] == scope['scope']: del scopes[index] else: scopes_extra = [] return scopes + scopes_extra
python
def get_scopes_information(self): scopes = StandardScopeClaims.get_scopes_info(self.params['scope']) if settings.get('OIDC_EXTRA_SCOPE_CLAIMS'): scopes_extra = settings.get( 'OIDC_EXTRA_SCOPE_CLAIMS', import_str=True).get_scopes_info(self.params['scope']) for index_extra, scope_extra in enumerate(scopes_extra): for index, scope in enumerate(scopes[:]): if scope_extra['scope'] == scope['scope']: del scopes[index] else: scopes_extra = [] return scopes + scopes_extra
[ "def", "get_scopes_information", "(", "self", ")", ":", "scopes", "=", "StandardScopeClaims", ".", "get_scopes_info", "(", "self", ".", "params", "[", "'scope'", "]", ")", "if", "settings", ".", "get", "(", "'OIDC_EXTRA_SCOPE_CLAIMS'", ")", ":", "scopes_extra", ...
Return a list with the description of all the scopes requested.
[ "Return", "a", "list", "with", "the", "description", "of", "all", "the", "scopes", "requested", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/endpoints/authorize.py#L273-L288
230,717
juanifioren/django-oidc-provider
oidc_provider/settings.py
get
def get(name, import_str=False): """ Helper function to use inside the package. """ value = None default_value = getattr(default_settings, name) try: value = getattr(settings, name) except AttributeError: if name in default_settings.required_attrs: raise Exception('You must set ' + name + ' in your settings.') if isinstance(default_value, dict) and value: default_value.update(value) value = default_value else: if value is None: value = default_value value = import_from_str(value) if import_str else value return value
python
def get(name, import_str=False): value = None default_value = getattr(default_settings, name) try: value = getattr(settings, name) except AttributeError: if name in default_settings.required_attrs: raise Exception('You must set ' + name + ' in your settings.') if isinstance(default_value, dict) and value: default_value.update(value) value = default_value else: if value is None: value = default_value value = import_from_str(value) if import_str else value return value
[ "def", "get", "(", "name", ",", "import_str", "=", "False", ")", ":", "value", "=", "None", "default_value", "=", "getattr", "(", "default_settings", ",", "name", ")", "try", ":", "value", "=", "getattr", "(", "settings", ",", "name", ")", "except", "A...
Helper function to use inside the package.
[ "Helper", "function", "to", "use", "inside", "the", "package", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/settings.py#L189-L210
230,718
juanifioren/django-oidc-provider
oidc_provider/settings.py
DefaultSettings.OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY
def OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY(self): """ OPTIONAL. Supply a fixed string to use as browser-state key for unauthenticated clients. """ # Memoize generated value if not self._unauthenticated_session_management_key: self._unauthenticated_session_management_key = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(100)) return self._unauthenticated_session_management_key
python
def OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY(self): # Memoize generated value if not self._unauthenticated_session_management_key: self._unauthenticated_session_management_key = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(100)) return self._unauthenticated_session_management_key
[ "def", "OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY", "(", "self", ")", ":", "# Memoize generated value", "if", "not", "self", ".", "_unauthenticated_session_management_key", ":", "self", ".", "_unauthenticated_session_management_key", "=", "''", ".", "join", "(", "random",...
OPTIONAL. Supply a fixed string to use as browser-state key for unauthenticated clients.
[ "OPTIONAL", ".", "Supply", "a", "fixed", "string", "to", "use", "as", "browser", "-", "state", "key", "for", "unauthenticated", "clients", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/settings.py#L90-L99
230,719
juanifioren/django-oidc-provider
oidc_provider/lib/utils/authorize.py
strip_prompt_login
def strip_prompt_login(path): """ Strips 'login' from the 'prompt' query parameter. """ uri = urlsplit(path) query_params = parse_qs(uri.query) prompt_list = query_params.get('prompt', '')[0].split() if 'login' in prompt_list: prompt_list.remove('login') query_params['prompt'] = ' '.join(prompt_list) if not query_params['prompt']: del query_params['prompt'] uri = uri._replace(query=urlencode(query_params, doseq=True)) return urlunsplit(uri)
python
def strip_prompt_login(path): uri = urlsplit(path) query_params = parse_qs(uri.query) prompt_list = query_params.get('prompt', '')[0].split() if 'login' in prompt_list: prompt_list.remove('login') query_params['prompt'] = ' '.join(prompt_list) if not query_params['prompt']: del query_params['prompt'] uri = uri._replace(query=urlencode(query_params, doseq=True)) return urlunsplit(uri)
[ "def", "strip_prompt_login", "(", "path", ")", ":", "uri", "=", "urlsplit", "(", "path", ")", "query_params", "=", "parse_qs", "(", "uri", ".", "query", ")", "prompt_list", "=", "query_params", ".", "get", "(", "'prompt'", ",", "''", ")", "[", "0", "]"...
Strips 'login' from the 'prompt' query parameter.
[ "Strips", "login", "from", "the", "prompt", "query", "parameter", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/authorize.py#L8-L21
230,720
juanifioren/django-oidc-provider
oidc_provider/lib/utils/common.py
get_site_url
def get_site_url(site_url=None, request=None): """ Construct the site url. Orders to decide site url: 1. valid `site_url` parameter 2. valid `SITE_URL` in settings 3. construct from `request` object """ site_url = site_url or settings.get('SITE_URL') if site_url: return site_url elif request: return '{}://{}'.format(request.scheme, request.get_host()) else: raise Exception('Either pass `site_url`, ' 'or set `SITE_URL` in settings, ' 'or pass `request` object.')
python
def get_site_url(site_url=None, request=None): site_url = site_url or settings.get('SITE_URL') if site_url: return site_url elif request: return '{}://{}'.format(request.scheme, request.get_host()) else: raise Exception('Either pass `site_url`, ' 'or set `SITE_URL` in settings, ' 'or pass `request` object.')
[ "def", "get_site_url", "(", "site_url", "=", "None", ",", "request", "=", "None", ")", ":", "site_url", "=", "site_url", "or", "settings", ".", "get", "(", "'SITE_URL'", ")", "if", "site_url", ":", "return", "site_url", "elif", "request", ":", "return", ...
Construct the site url. Orders to decide site url: 1. valid `site_url` parameter 2. valid `SITE_URL` in settings 3. construct from `request` object
[ "Construct", "the", "site", "url", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/common.py#L25-L42
230,721
juanifioren/django-oidc-provider
oidc_provider/lib/utils/common.py
get_issuer
def get_issuer(site_url=None, request=None): """ Construct the issuer full url. Basically is the site url with some path appended. """ site_url = get_site_url(site_url=site_url, request=request) path = reverse('oidc_provider:provider-info') \ .split('/.well-known/openid-configuration')[0] issuer = site_url + path return str(issuer)
python
def get_issuer(site_url=None, request=None): site_url = get_site_url(site_url=site_url, request=request) path = reverse('oidc_provider:provider-info') \ .split('/.well-known/openid-configuration')[0] issuer = site_url + path return str(issuer)
[ "def", "get_issuer", "(", "site_url", "=", "None", ",", "request", "=", "None", ")", ":", "site_url", "=", "get_site_url", "(", "site_url", "=", "site_url", ",", "request", "=", "request", ")", "path", "=", "reverse", "(", "'oidc_provider:provider-info'", ")...
Construct the issuer full url. Basically is the site url with some path appended.
[ "Construct", "the", "issuer", "full", "url", ".", "Basically", "is", "the", "site", "url", "with", "some", "path", "appended", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/common.py#L45-L55
230,722
juanifioren/django-oidc-provider
oidc_provider/lib/utils/common.py
get_browser_state_or_default
def get_browser_state_or_default(request): """ Determine value to use as session state. """ key = (request.session.session_key or settings.get('OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY')) return sha224(key.encode('utf-8')).hexdigest()
python
def get_browser_state_or_default(request): key = (request.session.session_key or settings.get('OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY')) return sha224(key.encode('utf-8')).hexdigest()
[ "def", "get_browser_state_or_default", "(", "request", ")", ":", "key", "=", "(", "request", ".", "session", ".", "session_key", "or", "settings", ".", "get", "(", "'OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY'", ")", ")", "return", "sha224", "(", "key", ".", "e...
Determine value to use as session state.
[ "Determine", "value", "to", "use", "as", "session", "state", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/common.py#L145-L151
230,723
juanifioren/django-oidc-provider
oidc_provider/lib/utils/common.py
cors_allow_any
def cors_allow_any(request, response): """ Add headers to permit CORS requests from any origin, with or without credentials, with any headers. """ origin = request.META.get('HTTP_ORIGIN') if not origin: return response # From the CORS spec: The string "*" cannot be used for a resource that supports credentials. response['Access-Control-Allow-Origin'] = origin patch_vary_headers(response, ['Origin']) response['Access-Control-Allow-Credentials'] = 'true' if request.method == 'OPTIONS': if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META: response['Access-Control-Allow-Headers'] \ = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' return response
python
def cors_allow_any(request, response): origin = request.META.get('HTTP_ORIGIN') if not origin: return response # From the CORS spec: The string "*" cannot be used for a resource that supports credentials. response['Access-Control-Allow-Origin'] = origin patch_vary_headers(response, ['Origin']) response['Access-Control-Allow-Credentials'] = 'true' if request.method == 'OPTIONS': if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META: response['Access-Control-Allow-Headers'] \ = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' return response
[ "def", "cors_allow_any", "(", "request", ",", "response", ")", ":", "origin", "=", "request", ".", "META", ".", "get", "(", "'HTTP_ORIGIN'", ")", "if", "not", "origin", ":", "return", "response", "# From the CORS spec: The string \"*\" cannot be used for a resource th...
Add headers to permit CORS requests from any origin, with or without credentials, with any headers.
[ "Add", "headers", "to", "permit", "CORS", "requests", "from", "any", "origin", "with", "or", "without", "credentials", "with", "any", "headers", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/common.py#L166-L186
230,724
juanifioren/django-oidc-provider
oidc_provider/lib/utils/token.py
create_token
def create_token(user, client, scope, id_token_dic=None): """ Create and populate a Token object. Return a Token object. """ token = Token() token.user = user token.client = client token.access_token = uuid.uuid4().hex if id_token_dic is not None: token.id_token = id_token_dic token.refresh_token = uuid.uuid4().hex token.expires_at = timezone.now() + timedelta( seconds=settings.get('OIDC_TOKEN_EXPIRE')) token.scope = scope return token
python
def create_token(user, client, scope, id_token_dic=None): token = Token() token.user = user token.client = client token.access_token = uuid.uuid4().hex if id_token_dic is not None: token.id_token = id_token_dic token.refresh_token = uuid.uuid4().hex token.expires_at = timezone.now() + timedelta( seconds=settings.get('OIDC_TOKEN_EXPIRE')) token.scope = scope return token
[ "def", "create_token", "(", "user", ",", "client", ",", "scope", ",", "id_token_dic", "=", "None", ")", ":", "token", "=", "Token", "(", ")", "token", ".", "user", "=", "user", "token", ".", "client", "=", "client", "token", ".", "access_token", "=", ...
Create and populate a Token object. Return a Token object.
[ "Create", "and", "populate", "a", "Token", "object", ".", "Return", "a", "Token", "object", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/token.py#L105-L123
230,725
juanifioren/django-oidc-provider
oidc_provider/lib/utils/token.py
create_code
def create_code(user, client, scope, nonce, is_authentication, code_challenge=None, code_challenge_method=None): """ Create and populate a Code object. Return a Code object. """ code = Code() code.user = user code.client = client code.code = uuid.uuid4().hex if code_challenge and code_challenge_method: code.code_challenge = code_challenge code.code_challenge_method = code_challenge_method code.expires_at = timezone.now() + timedelta( seconds=settings.get('OIDC_CODE_EXPIRE')) code.scope = scope code.nonce = nonce code.is_authentication = is_authentication return code
python
def create_code(user, client, scope, nonce, is_authentication, code_challenge=None, code_challenge_method=None): code = Code() code.user = user code.client = client code.code = uuid.uuid4().hex if code_challenge and code_challenge_method: code.code_challenge = code_challenge code.code_challenge_method = code_challenge_method code.expires_at = timezone.now() + timedelta( seconds=settings.get('OIDC_CODE_EXPIRE')) code.scope = scope code.nonce = nonce code.is_authentication = is_authentication return code
[ "def", "create_code", "(", "user", ",", "client", ",", "scope", ",", "nonce", ",", "is_authentication", ",", "code_challenge", "=", "None", ",", "code_challenge_method", "=", "None", ")", ":", "code", "=", "Code", "(", ")", "code", ".", "user", "=", "use...
Create and populate a Code object. Return a Code object.
[ "Create", "and", "populate", "a", "Code", "object", ".", "Return", "a", "Code", "object", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/token.py#L126-L148
230,726
juanifioren/django-oidc-provider
oidc_provider/lib/utils/token.py
get_client_alg_keys
def get_client_alg_keys(client): """ Takes a client and returns the set of keys associated with it. Returns a list of keys. """ if client.jwt_alg == 'RS256': keys = [] for rsakey in RSAKey.objects.all(): keys.append(jwk_RSAKey(key=importKey(rsakey.key), kid=rsakey.kid)) if not keys: raise Exception('You must add at least one RSA Key.') elif client.jwt_alg == 'HS256': keys = [SYMKey(key=client.client_secret, alg=client.jwt_alg)] else: raise Exception('Unsupported key algorithm.') return keys
python
def get_client_alg_keys(client): if client.jwt_alg == 'RS256': keys = [] for rsakey in RSAKey.objects.all(): keys.append(jwk_RSAKey(key=importKey(rsakey.key), kid=rsakey.kid)) if not keys: raise Exception('You must add at least one RSA Key.') elif client.jwt_alg == 'HS256': keys = [SYMKey(key=client.client_secret, alg=client.jwt_alg)] else: raise Exception('Unsupported key algorithm.') return keys
[ "def", "get_client_alg_keys", "(", "client", ")", ":", "if", "client", ".", "jwt_alg", "==", "'RS256'", ":", "keys", "=", "[", "]", "for", "rsakey", "in", "RSAKey", ".", "objects", ".", "all", "(", ")", ":", "keys", ".", "append", "(", "jwk_RSAKey", ...
Takes a client and returns the set of keys associated with it. Returns a list of keys.
[ "Takes", "a", "client", "and", "returns", "the", "set", "of", "keys", "associated", "with", "it", ".", "Returns", "a", "list", "of", "keys", "." ]
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/token.py#L151-L167
230,727
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/readers/gbasis.py
read_gbasis
def read_gbasis(basis_lines, fname): '''Reads gbasis-formatted file data and converts it to a dictionary with the usual BSE fields Note that the gbasis format does not store all the fields we have, so some fields are left blank ''' skipchars = '!#' basis_lines = [l for l in basis_lines if l and not l[0] in skipchars] bs_data = create_skel('component') i = 0 bs_name = None while i < len(basis_lines): line = basis_lines[i] lsplt = line.split(':') elementsym = lsplt[0] if bs_name is None: bs_name = lsplt[1] elif lsplt[1] != bs_name: raise RuntimeError("Multiple basis sets in a file") element_Z = lut.element_Z_from_sym(elementsym) element_Z = str(element_Z) if not element_Z in bs_data['elements']: bs_data['elements'][element_Z] = {} element_data = bs_data['elements'][element_Z] if not 'electron_shells' in element_data: element_data['electron_shells'] = [] i += 1 max_am = int(basis_lines[i].strip()) i += 1 for am in range(0, max_am + 1): lsplt = basis_lines[i].split() shell_am = lut.amchar_to_int(lsplt[0]) nprim = int(lsplt[1]) ngen = int(lsplt[2]) if shell_am[0] != am: raise RuntimeError("AM out of order in gbasis?") if max(shell_am) <= 1: func_type = 'gto' else: func_type = 'gto_spherical' shell = { 'function_type': func_type, 'region': '', 'angular_momentum': shell_am } exponents = [] coefficients = [] i += 1 for j in range(nprim): line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() if len(lsplt) != (ngen + 1): raise RuntimeError("Incorrect number of general contractions in gbasis") exponents.append(lsplt[0]) coefficients.append(lsplt[1:]) i += 1 shell['exponents'] = exponents # We need to transpose the coefficient matrix # (we store a matrix with primitives being the column index and # general contraction being the row index) shell['coefficients'] = list(map(list, zip(*coefficients))) element_data['electron_shells'].append(shell) return bs_data
python
def read_gbasis(basis_lines, fname): '''Reads gbasis-formatted file data and converts it to a dictionary with the usual BSE fields Note that the gbasis format does not store all the fields we have, so some fields are left blank ''' skipchars = '!#' basis_lines = [l for l in basis_lines if l and not l[0] in skipchars] bs_data = create_skel('component') i = 0 bs_name = None while i < len(basis_lines): line = basis_lines[i] lsplt = line.split(':') elementsym = lsplt[0] if bs_name is None: bs_name = lsplt[1] elif lsplt[1] != bs_name: raise RuntimeError("Multiple basis sets in a file") element_Z = lut.element_Z_from_sym(elementsym) element_Z = str(element_Z) if not element_Z in bs_data['elements']: bs_data['elements'][element_Z] = {} element_data = bs_data['elements'][element_Z] if not 'electron_shells' in element_data: element_data['electron_shells'] = [] i += 1 max_am = int(basis_lines[i].strip()) i += 1 for am in range(0, max_am + 1): lsplt = basis_lines[i].split() shell_am = lut.amchar_to_int(lsplt[0]) nprim = int(lsplt[1]) ngen = int(lsplt[2]) if shell_am[0] != am: raise RuntimeError("AM out of order in gbasis?") if max(shell_am) <= 1: func_type = 'gto' else: func_type = 'gto_spherical' shell = { 'function_type': func_type, 'region': '', 'angular_momentum': shell_am } exponents = [] coefficients = [] i += 1 for j in range(nprim): line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() if len(lsplt) != (ngen + 1): raise RuntimeError("Incorrect number of general contractions in gbasis") exponents.append(lsplt[0]) coefficients.append(lsplt[1:]) i += 1 shell['exponents'] = exponents # We need to transpose the coefficient matrix # (we store a matrix with primitives being the column index and # general contraction being the row index) shell['coefficients'] = list(map(list, zip(*coefficients))) element_data['electron_shells'].append(shell) return bs_data
[ "def", "read_gbasis", "(", "basis_lines", ",", "fname", ")", ":", "skipchars", "=", "'!#'", "basis_lines", "=", "[", "l", "for", "l", "in", "basis_lines", "if", "l", "and", "not", "l", "[", "0", "]", "in", "skipchars", "]", "bs_data", "=", "create_skel...
Reads gbasis-formatted file data and converts it to a dictionary with the usual BSE fields Note that the gbasis format does not store all the fields we have, so some fields are left blank
[ "Reads", "gbasis", "-", "formatted", "file", "data", "and", "converts", "it", "to", "a", "dictionary", "with", "the", "usual", "BSE", "fields" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/readers/gbasis.py#L5-L92
230,728
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/readers/molcas.py
read_molcas
def read_molcas(basis_lines, fname): '''Reads molcas-formatted file data and converts it to a dictionary with the usual BSE fields Note that the turbomole format does not store all the fields we have, so some fields are left blank ''' skipchars = '*#$' basis_lines = [l for l in basis_lines if l and not l[0] in skipchars] bs_data = create_skel('component') i = 0 while i < len(basis_lines): line = basis_lines[i] if not line.startswith('/'): raise RuntimeError("Expecting line starting with /") line_splt = line[1:].split('.') elementsym = line_splt[0] element_Z = lut.element_Z_from_sym(elementsym) element_Z = str(element_Z) if not element_Z in bs_data['elements']: bs_data['elements'][element_Z] = {} element_data = bs_data['elements'][element_Z] if "ecp" in line.lower(): raise NotImplementedError("MolCAS ECPs not supported") #if not 'ecp_potentials' in element_data: # element_data['ecp_potentials'] = [] #i += 1 #line = basis_lines[i] #lsplt = line.split('=') #maxam = int(lsplt[2]) #n_elec = int(lsplt[1].split()[0]) #amlist = [maxam] #amlist.extend(list(range(0, maxam))) #i += 1 #for shell_am in amlist: # shell_am2 = lut.amchar_to_int(basis_lines[i][0])[0] # if shell_am2 != shell_am: # raise RuntimeError("AM not in expected order?") # i += 1 # ecp_shell = { # 'ecp_type': 'scalar', # 'angular_momentum': [shell_am], # } # ecp_exponents = [] # ecp_rexponents = [] # ecp_coefficients = [] # while i < len(basis_lines) and basis_lines[i][0].isalpha() is False: # lsplt = basis_lines[i].split() # ecp_exponents.append(lsplt[2]) # ecp_rexponents.append(int(lsplt[1])) # ecp_coefficients.append(lsplt[0]) # i += 1 # ecp_shell['r_exponents'] = ecp_rexponents # ecp_shell['gaussian_exponents'] = ecp_exponents # ecp_shell['coefficients'] = [ecp_coefficients] # element_data['ecp_potentials'].append(ecp_shell) #element_data['ecp_electrons'] = n_elec else: if not 'electron_shells' in element_data: element_data['electron_shells'] = [] # Skip two comment lines (usually ref) i += 3 # Skip over an options block line = basis_lines[i] if line.lower() == 'options': while basis_lines[i].lower() != 'endoptions': i += 1 i += 1 lsplt = basis_lines[i].split() max_am = int(lsplt[1]) i += 1 for shell_am in range(max_am+1): lsplt = basis_lines[i].replace(',', ' ').split() nprim = int(lsplt[0]) ngen = int(lsplt[1]) i += 1 if shell_am <= 1: func_type = 'gto' else: func_type = 'gto_spherical' shell = { 'function_type': func_type, 'region': '', 'angular_momentum': [shell_am] } exponents = [] coefficients = [] j = 0 while j < nprim: line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() exponents.extend(lsplt) i += 1 j += len(lsplt) for j in range(nprim): line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() if len(lsplt) != ngen: print(fname) print(line) raise RuntimeError("Unexpected number of coefficients") coefficients.append(lsplt) i += 1 shell['exponents'] = exponents # We need to transpose the coefficient matrix # (we store a matrix with primitives being the column index and # general contraction being the row index) shell['coefficients'] = list(map(list, zip(*coefficients))) element_data['electron_shells'].append(shell) # Skip energies? to_skip = int(basis_lines[i].strip()) skipped = 0 i += 1 while skipped < to_skip: skipped += len(basis_lines[i].split()) i += 1 return bs_data
python
def read_molcas(basis_lines, fname): '''Reads molcas-formatted file data and converts it to a dictionary with the usual BSE fields Note that the turbomole format does not store all the fields we have, so some fields are left blank ''' skipchars = '*#$' basis_lines = [l for l in basis_lines if l and not l[0] in skipchars] bs_data = create_skel('component') i = 0 while i < len(basis_lines): line = basis_lines[i] if not line.startswith('/'): raise RuntimeError("Expecting line starting with /") line_splt = line[1:].split('.') elementsym = line_splt[0] element_Z = lut.element_Z_from_sym(elementsym) element_Z = str(element_Z) if not element_Z in bs_data['elements']: bs_data['elements'][element_Z] = {} element_data = bs_data['elements'][element_Z] if "ecp" in line.lower(): raise NotImplementedError("MolCAS ECPs not supported") #if not 'ecp_potentials' in element_data: # element_data['ecp_potentials'] = [] #i += 1 #line = basis_lines[i] #lsplt = line.split('=') #maxam = int(lsplt[2]) #n_elec = int(lsplt[1].split()[0]) #amlist = [maxam] #amlist.extend(list(range(0, maxam))) #i += 1 #for shell_am in amlist: # shell_am2 = lut.amchar_to_int(basis_lines[i][0])[0] # if shell_am2 != shell_am: # raise RuntimeError("AM not in expected order?") # i += 1 # ecp_shell = { # 'ecp_type': 'scalar', # 'angular_momentum': [shell_am], # } # ecp_exponents = [] # ecp_rexponents = [] # ecp_coefficients = [] # while i < len(basis_lines) and basis_lines[i][0].isalpha() is False: # lsplt = basis_lines[i].split() # ecp_exponents.append(lsplt[2]) # ecp_rexponents.append(int(lsplt[1])) # ecp_coefficients.append(lsplt[0]) # i += 1 # ecp_shell['r_exponents'] = ecp_rexponents # ecp_shell['gaussian_exponents'] = ecp_exponents # ecp_shell['coefficients'] = [ecp_coefficients] # element_data['ecp_potentials'].append(ecp_shell) #element_data['ecp_electrons'] = n_elec else: if not 'electron_shells' in element_data: element_data['electron_shells'] = [] # Skip two comment lines (usually ref) i += 3 # Skip over an options block line = basis_lines[i] if line.lower() == 'options': while basis_lines[i].lower() != 'endoptions': i += 1 i += 1 lsplt = basis_lines[i].split() max_am = int(lsplt[1]) i += 1 for shell_am in range(max_am+1): lsplt = basis_lines[i].replace(',', ' ').split() nprim = int(lsplt[0]) ngen = int(lsplt[1]) i += 1 if shell_am <= 1: func_type = 'gto' else: func_type = 'gto_spherical' shell = { 'function_type': func_type, 'region': '', 'angular_momentum': [shell_am] } exponents = [] coefficients = [] j = 0 while j < nprim: line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() exponents.extend(lsplt) i += 1 j += len(lsplt) for j in range(nprim): line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() if len(lsplt) != ngen: print(fname) print(line) raise RuntimeError("Unexpected number of coefficients") coefficients.append(lsplt) i += 1 shell['exponents'] = exponents # We need to transpose the coefficient matrix # (we store a matrix with primitives being the column index and # general contraction being the row index) shell['coefficients'] = list(map(list, zip(*coefficients))) element_data['electron_shells'].append(shell) # Skip energies? to_skip = int(basis_lines[i].strip()) skipped = 0 i += 1 while skipped < to_skip: skipped += len(basis_lines[i].split()) i += 1 return bs_data
[ "def", "read_molcas", "(", "basis_lines", ",", "fname", ")", ":", "skipchars", "=", "'*#$'", "basis_lines", "=", "[", "l", "for", "l", "in", "basis_lines", "if", "l", "and", "not", "l", "[", "0", "]", "in", "skipchars", "]", "bs_data", "=", "create_ske...
Reads molcas-formatted file data and converts it to a dictionary with the usual BSE fields Note that the turbomole format does not store all the fields we have, so some fields are left blank
[ "Reads", "molcas", "-", "formatted", "file", "data", "and", "converts", "it", "to", "a", "dictionary", "with", "the", "usual", "BSE", "fields" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/readers/molcas.py#L5-L159
230,729
MolSSI-BSE/basis_set_exchange
basis_set_exchange/fileio.py
_read_plain_json
def _read_plain_json(file_path, check_bse): """ Reads a JSON file A simple wrapper around json.load that only takes the file name If the file does not exist, an exception is thrown. If the file does exist, but there is a problem with the JSON formatting, the filename is added to the exception information. If check_bse is True, this function also make sure the 'molssi_bse_schema' key exists in the file. Parameters ---------- file_path : str Full path to the file to read check_bse: bool If True, check to make sure the bse schema information is included. If not found, an exception is raised """ if not os.path.isfile(file_path): raise FileNotFoundError('JSON file \'{}\' does not exist, is not ' 'readable, or is not a file'.format(file_path)) try: if file_path.endswith('.bz2'): with bz2.open(file_path, 'rt', encoding=_default_encoding) as f: js = json.load(f) else: with open(file_path, 'r', encoding=_default_encoding) as f: js = json.load(f) except json.decoder.JSONDecodeError as ex: raise RuntimeError("File {} contains JSON errors".format(file_path)) from ex if check_bse is True: # Check for molssi_bse_schema key if 'molssi_bse_schema' not in js: raise RuntimeError('File {} does not appear to be a BSE JSON file'.format(file_path)) return js
python
def _read_plain_json(file_path, check_bse): if not os.path.isfile(file_path): raise FileNotFoundError('JSON file \'{}\' does not exist, is not ' 'readable, or is not a file'.format(file_path)) try: if file_path.endswith('.bz2'): with bz2.open(file_path, 'rt', encoding=_default_encoding) as f: js = json.load(f) else: with open(file_path, 'r', encoding=_default_encoding) as f: js = json.load(f) except json.decoder.JSONDecodeError as ex: raise RuntimeError("File {} contains JSON errors".format(file_path)) from ex if check_bse is True: # Check for molssi_bse_schema key if 'molssi_bse_schema' not in js: raise RuntimeError('File {} does not appear to be a BSE JSON file'.format(file_path)) return js
[ "def", "_read_plain_json", "(", "file_path", ",", "check_bse", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "raise", "FileNotFoundError", "(", "'JSON file \\'{}\\' does not exist, is not '", "'readable, or is not a file'", ".", ...
Reads a JSON file A simple wrapper around json.load that only takes the file name If the file does not exist, an exception is thrown. If the file does exist, but there is a problem with the JSON formatting, the filename is added to the exception information. If check_bse is True, this function also make sure the 'molssi_bse_schema' key exists in the file. Parameters ---------- file_path : str Full path to the file to read check_bse: bool If True, check to make sure the bse schema information is included. If not found, an exception is raised
[ "Reads", "a", "JSON", "file" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/fileio.py#L17-L59
230,730
MolSSI-BSE/basis_set_exchange
basis_set_exchange/fileio.py
_write_plain_json
def _write_plain_json(file_path, js): """ Write information to a JSON file This makes sure files are created with the proper encoding and consistent indenting Parameters ---------- file_path : str Full path to the file to write to. It will be overwritten if it exists js : dict JSON information to write """ # Disable ascii in the json - this prevents the json writer # from escaping everything if file_path.endswith('.bz2'): with bz2.open(file_path, 'wt', encoding=_default_encoding) as f: json.dump(js, f, indent=2, ensure_ascii=False) else: with open(file_path, 'w', encoding=_default_encoding) as f: json.dump(js, f, indent=2, ensure_ascii=False)
python
def _write_plain_json(file_path, js): # Disable ascii in the json - this prevents the json writer # from escaping everything if file_path.endswith('.bz2'): with bz2.open(file_path, 'wt', encoding=_default_encoding) as f: json.dump(js, f, indent=2, ensure_ascii=False) else: with open(file_path, 'w', encoding=_default_encoding) as f: json.dump(js, f, indent=2, ensure_ascii=False)
[ "def", "_write_plain_json", "(", "file_path", ",", "js", ")", ":", "# Disable ascii in the json - this prevents the json writer", "# from escaping everything", "if", "file_path", ".", "endswith", "(", "'.bz2'", ")", ":", "with", "bz2", ".", "open", "(", "file_path", "...
Write information to a JSON file This makes sure files are created with the proper encoding and consistent indenting Parameters ---------- file_path : str Full path to the file to write to. It will be overwritten if it exists js : dict JSON information to write
[ "Write", "information", "to", "a", "JSON", "file" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/fileio.py#L62-L84
230,731
MolSSI-BSE/basis_set_exchange
basis_set_exchange/fileio.py
read_notes_file
def read_notes_file(file_path): """ Returns the contents of a notes file. If the notes file does not exist, None is returned """ if not os.path.isfile(file_path): return None with open(file_path, 'r', encoding=_default_encoding) as f: return f.read()
python
def read_notes_file(file_path): if not os.path.isfile(file_path): return None with open(file_path, 'r', encoding=_default_encoding) as f: return f.read()
[ "def", "read_notes_file", "(", "file_path", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "None", "with", "open", "(", "file_path", ",", "'r'", ",", "encoding", "=", "_default_encoding", ")", "as", "f", ...
Returns the contents of a notes file. If the notes file does not exist, None is returned
[ "Returns", "the", "contents", "of", "a", "notes", "file", "." ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/fileio.py#L232-L243
230,732
MolSSI-BSE/basis_set_exchange
basis_set_exchange/compose.py
_whole_basis_types
def _whole_basis_types(basis): ''' Get a list of all the types of features in this basis set. ''' all_types = set() for v in basis['elements'].values(): if 'electron_shells' in v: for sh in v['electron_shells']: all_types.add(sh['function_type']) if 'ecp_potentials' in v: for pot in v['ecp_potentials']: all_types.add(pot['ecp_type']) return sorted(list(all_types))
python
def _whole_basis_types(basis): ''' Get a list of all the types of features in this basis set. ''' all_types = set() for v in basis['elements'].values(): if 'electron_shells' in v: for sh in v['electron_shells']: all_types.add(sh['function_type']) if 'ecp_potentials' in v: for pot in v['ecp_potentials']: all_types.add(pot['ecp_type']) return sorted(list(all_types))
[ "def", "_whole_basis_types", "(", "basis", ")", ":", "all_types", "=", "set", "(", ")", "for", "v", "in", "basis", "[", "'elements'", "]", ".", "values", "(", ")", ":", "if", "'electron_shells'", "in", "v", ":", "for", "sh", "in", "v", "[", "'electro...
Get a list of all the types of features in this basis set.
[ "Get", "a", "list", "of", "all", "the", "types", "of", "features", "in", "this", "basis", "set", "." ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/compose.py#L9-L26
230,733
MolSSI-BSE/basis_set_exchange
basis_set_exchange/compose.py
compose_elemental_basis
def compose_elemental_basis(file_relpath, data_dir): """ Creates an 'elemental' basis from an elemental json file This function reads the info from the given file, and reads all the component basis set information from the files listed therein. It then composes all the information together into one 'elemental' basis dictionary """ # Do a simple read of the json el_bs = fileio.read_json_basis(os.path.join(data_dir, file_relpath)) # construct a list of all files to read component_files = set() for k, v in el_bs['elements'].items(): component_files.update(set(v['components'])) # Read all the data from these files into a big dictionary component_map = {k: fileio.read_json_basis(os.path.join(data_dir, k)) for k in component_files} # Use the basis_set_description for the reference description for k, v in component_map.items(): for el, el_data in v['elements'].items(): el_data['references'] = [{ 'reference_description': v['description'], 'reference_keys': el_data['references'] }] # Compose on a per-element basis for k, v in el_bs['elements'].items(): components = v.pop('components') # all of the component data for this element el_comp_data = [] for c in components: centry = component_map[c]['elements'] if k not in centry: raise RuntimeError('File {} does not contain element {}'.format(c, k)) el_comp_data.append(centry[k]) # merge all the data v = manip.merge_element_data(None, el_comp_data) el_bs['elements'][k] = v return el_bs
python
def compose_elemental_basis(file_relpath, data_dir): # Do a simple read of the json el_bs = fileio.read_json_basis(os.path.join(data_dir, file_relpath)) # construct a list of all files to read component_files = set() for k, v in el_bs['elements'].items(): component_files.update(set(v['components'])) # Read all the data from these files into a big dictionary component_map = {k: fileio.read_json_basis(os.path.join(data_dir, k)) for k in component_files} # Use the basis_set_description for the reference description for k, v in component_map.items(): for el, el_data in v['elements'].items(): el_data['references'] = [{ 'reference_description': v['description'], 'reference_keys': el_data['references'] }] # Compose on a per-element basis for k, v in el_bs['elements'].items(): components = v.pop('components') # all of the component data for this element el_comp_data = [] for c in components: centry = component_map[c]['elements'] if k not in centry: raise RuntimeError('File {} does not contain element {}'.format(c, k)) el_comp_data.append(centry[k]) # merge all the data v = manip.merge_element_data(None, el_comp_data) el_bs['elements'][k] = v return el_bs
[ "def", "compose_elemental_basis", "(", "file_relpath", ",", "data_dir", ")", ":", "# Do a simple read of the json", "el_bs", "=", "fileio", ".", "read_json_basis", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", "file_relpath", ")", ")", "# construct a ...
Creates an 'elemental' basis from an elemental json file This function reads the info from the given file, and reads all the component basis set information from the files listed therein. It then composes all the information together into one 'elemental' basis dictionary
[ "Creates", "an", "elemental", "basis", "from", "an", "elemental", "json", "file" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/compose.py#L29-L76
230,734
MolSSI-BSE/basis_set_exchange
basis_set_exchange/compose.py
compose_table_basis
def compose_table_basis(file_relpath, data_dir): """ Creates a 'table' basis from an table json file This function reads the info from the given file, and reads all the elemental basis set information from the files listed therein. It then composes all the information together into one 'table' basis dictionary Note that the data returned from this function will not be shared, even if the function is called again with the same arguments. """ # Do a simple read of the json file_path = os.path.join(data_dir, file_relpath) table_bs = fileio.read_json_basis(file_path) # construct a list of all elemental files to read element_files = set(table_bs['elements'].values()) # Create a map of the elemental basis data # (maps file path to data contained in that file) element_map = {k: compose_elemental_basis(k, data_dir) for k in element_files} # Replace the basis set for all elements in the table basis with the data # from the elemental basis for k, entry in table_bs['elements'].items(): data = element_map[entry] if k not in data['elements']: raise KeyError('File {} does not contain element {}'.format(entry, k)) table_bs['elements'][k] = data['elements'][k] # Add the version to the dictionary file_base = os.path.basename(file_relpath) table_bs['version'] = file_base.split('.')[-3] # Add whether the entire basis is spherical or cartesian table_bs['function_types'] = _whole_basis_types(table_bs) # Read and merge in the metadata # This file must be in the same location as the table file meta_dirpath, table_filename = os.path.split(file_path) meta_filename = table_filename.split('.')[0] + '.metadata.json' meta_filepath = os.path.join(meta_dirpath, meta_filename) bs_meta = fileio.read_json_basis(meta_filepath) table_bs.update(bs_meta) # Remove the molssi schema (which isn't needed here) table_bs.pop('molssi_bse_schema') return table_bs
python
def compose_table_basis(file_relpath, data_dir): # Do a simple read of the json file_path = os.path.join(data_dir, file_relpath) table_bs = fileio.read_json_basis(file_path) # construct a list of all elemental files to read element_files = set(table_bs['elements'].values()) # Create a map of the elemental basis data # (maps file path to data contained in that file) element_map = {k: compose_elemental_basis(k, data_dir) for k in element_files} # Replace the basis set for all elements in the table basis with the data # from the elemental basis for k, entry in table_bs['elements'].items(): data = element_map[entry] if k not in data['elements']: raise KeyError('File {} does not contain element {}'.format(entry, k)) table_bs['elements'][k] = data['elements'][k] # Add the version to the dictionary file_base = os.path.basename(file_relpath) table_bs['version'] = file_base.split('.')[-3] # Add whether the entire basis is spherical or cartesian table_bs['function_types'] = _whole_basis_types(table_bs) # Read and merge in the metadata # This file must be in the same location as the table file meta_dirpath, table_filename = os.path.split(file_path) meta_filename = table_filename.split('.')[0] + '.metadata.json' meta_filepath = os.path.join(meta_dirpath, meta_filename) bs_meta = fileio.read_json_basis(meta_filepath) table_bs.update(bs_meta) # Remove the molssi schema (which isn't needed here) table_bs.pop('molssi_bse_schema') return table_bs
[ "def", "compose_table_basis", "(", "file_relpath", ",", "data_dir", ")", ":", "# Do a simple read of the json", "file_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "file_relpath", ")", "table_bs", "=", "fileio", ".", "read_json_basis", "(", "...
Creates a 'table' basis from an table json file This function reads the info from the given file, and reads all the elemental basis set information from the files listed therein. It then composes all the information together into one 'table' basis dictionary Note that the data returned from this function will not be shared, even if the function is called again with the same arguments.
[ "Creates", "a", "table", "basis", "from", "an", "table", "json", "file" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/compose.py#L80-L131
230,735
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/skel.py
create_skel
def create_skel(role): ''' Create the skeleton of a dictionary or JSON file A dictionary is returned that contains the "molssi_bse_schema" key and other required keys, depending on the role role can be either 'component', 'element', or 'table' ''' role = role.lower() if not role in _skeletons: raise RuntimeError("Role {} not found. Should be 'component', 'element', 'table', or 'metadata'") return copy.deepcopy(_skeletons[role])
python
def create_skel(role): ''' Create the skeleton of a dictionary or JSON file A dictionary is returned that contains the "molssi_bse_schema" key and other required keys, depending on the role role can be either 'component', 'element', or 'table' ''' role = role.lower() if not role in _skeletons: raise RuntimeError("Role {} not found. Should be 'component', 'element', 'table', or 'metadata'") return copy.deepcopy(_skeletons[role])
[ "def", "create_skel", "(", "role", ")", ":", "role", "=", "role", ".", "lower", "(", ")", "if", "not", "role", "in", "_skeletons", ":", "raise", "RuntimeError", "(", "\"Role {} not found. Should be 'component', 'element', 'table', or 'metadata'\"", ")", "return", "c...
Create the skeleton of a dictionary or JSON file A dictionary is returned that contains the "molssi_bse_schema" key and other required keys, depending on the role role can be either 'component', 'element', or 'table'
[ "Create", "the", "skeleton", "of", "a", "dictionary", "or", "JSON", "file" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/skel.py#L49-L63
230,736
MolSSI-BSE/basis_set_exchange
basis_set_exchange/notes.py
process_notes
def process_notes(notes, ref_data): '''Add reference information to the bottom of a notes file `:ref:` tags are removed and the actual reference data is appended ''' ref_keys = ref_data.keys() found_refs = set() for k in ref_keys: if k in notes: found_refs.add(k) # The block to append reference_sec = '\n\n' reference_sec += '-------------------------------------------------\n' reference_sec += ' REFERENCES MENTIONED ABOVE\n' reference_sec += ' (not necessarily references for the basis sets)\n' reference_sec += '-------------------------------------------------\n' # Add reference data if len(found_refs) == 0: return notes for r in sorted(found_refs): rtxt = references.reference_text(ref_data[r]) reference_sec += r + '\n' reference_sec += textwrap.indent(rtxt, ' ' * 4) reference_sec += '\n\n' return notes + reference_sec
python
def process_notes(notes, ref_data): '''Add reference information to the bottom of a notes file `:ref:` tags are removed and the actual reference data is appended ''' ref_keys = ref_data.keys() found_refs = set() for k in ref_keys: if k in notes: found_refs.add(k) # The block to append reference_sec = '\n\n' reference_sec += '-------------------------------------------------\n' reference_sec += ' REFERENCES MENTIONED ABOVE\n' reference_sec += ' (not necessarily references for the basis sets)\n' reference_sec += '-------------------------------------------------\n' # Add reference data if len(found_refs) == 0: return notes for r in sorted(found_refs): rtxt = references.reference_text(ref_data[r]) reference_sec += r + '\n' reference_sec += textwrap.indent(rtxt, ' ' * 4) reference_sec += '\n\n' return notes + reference_sec
[ "def", "process_notes", "(", "notes", ",", "ref_data", ")", ":", "ref_keys", "=", "ref_data", ".", "keys", "(", ")", "found_refs", "=", "set", "(", ")", "for", "k", "in", "ref_keys", ":", "if", "k", "in", "notes", ":", "found_refs", ".", "add", "(", ...
Add reference information to the bottom of a notes file `:ref:` tags are removed and the actual reference data is appended
[ "Add", "reference", "information", "to", "the", "bottom", "of", "a", "notes", "file" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/notes.py#L10-L40
230,737
MolSSI-BSE/basis_set_exchange
basis_set_exchange/validator.py
_validate_extra_component
def _validate_extra_component(bs_data): '''Extra checks for component basis files''' assert len(bs_data['elements']) > 0 # Make sure size of the coefficient matrix matches the number of exponents for el in bs_data['elements'].values(): if not 'electron_shells' in el: continue for s in el['electron_shells']: nprim = len(s['exponents']) if nprim <= 0: raise RuntimeError("Invalid number of primitives: {}".format(nprim)) for g in s['coefficients']: if nprim != len(g): raise RuntimeError("Number of coefficients doesn't match number of primitives ({} vs {}".format( len(g), nprim)) # If more than one AM is given, that should be the number of # general contractions nam = len(s['angular_momentum']) if nam > 1: ngen = len(s['coefficients']) if ngen != nam: raise RuntimeError("Number of general contractions doesn't match combined AM ({} vs {}".format( ngen, nam))
python
def _validate_extra_component(bs_data): '''Extra checks for component basis files''' assert len(bs_data['elements']) > 0 # Make sure size of the coefficient matrix matches the number of exponents for el in bs_data['elements'].values(): if not 'electron_shells' in el: continue for s in el['electron_shells']: nprim = len(s['exponents']) if nprim <= 0: raise RuntimeError("Invalid number of primitives: {}".format(nprim)) for g in s['coefficients']: if nprim != len(g): raise RuntimeError("Number of coefficients doesn't match number of primitives ({} vs {}".format( len(g), nprim)) # If more than one AM is given, that should be the number of # general contractions nam = len(s['angular_momentum']) if nam > 1: ngen = len(s['coefficients']) if ngen != nam: raise RuntimeError("Number of general contractions doesn't match combined AM ({} vs {}".format( ngen, nam))
[ "def", "_validate_extra_component", "(", "bs_data", ")", ":", "assert", "len", "(", "bs_data", "[", "'elements'", "]", ")", ">", "0", "# Make sure size of the coefficient matrix matches the number of exponents", "for", "el", "in", "bs_data", "[", "'elements'", "]", "....
Extra checks for component basis files
[ "Extra", "checks", "for", "component", "basis", "files" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/validator.py#L26-L53
230,738
MolSSI-BSE/basis_set_exchange
basis_set_exchange/validator.py
validate_data
def validate_data(file_type, bs_data): """ Validates json basis set data against a schema Parameters ---------- file_type : str Type of file to read. May be 'component', 'element', 'table', or 'references' bs_data: Data to be validated Raises ------ RuntimeError If the file_type is not valid (and/or a schema doesn't exist) ValidationError If the given file does not pass validation FileNotFoundError If the file given by file_path doesn't exist """ if file_type not in _validate_map: raise RuntimeError("{} is not a valid file_type".format(file_type)) schema = api.get_schema(file_type) jsonschema.validate(bs_data, schema) _validate_map[file_type](bs_data)
python
def validate_data(file_type, bs_data): if file_type not in _validate_map: raise RuntimeError("{} is not a valid file_type".format(file_type)) schema = api.get_schema(file_type) jsonschema.validate(bs_data, schema) _validate_map[file_type](bs_data)
[ "def", "validate_data", "(", "file_type", ",", "bs_data", ")", ":", "if", "file_type", "not", "in", "_validate_map", ":", "raise", "RuntimeError", "(", "\"{} is not a valid file_type\"", ".", "format", "(", "file_type", ")", ")", "schema", "=", "api", ".", "ge...
Validates json basis set data against a schema Parameters ---------- file_type : str Type of file to read. May be 'component', 'element', 'table', or 'references' bs_data: Data to be validated Raises ------ RuntimeError If the file_type is not valid (and/or a schema doesn't exist) ValidationError If the given file does not pass validation FileNotFoundError If the file given by file_path doesn't exist
[ "Validates", "json", "basis", "set", "data", "against", "a", "schema" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/validator.py#L77-L103
230,739
MolSSI-BSE/basis_set_exchange
basis_set_exchange/validator.py
validate_file
def validate_file(file_type, file_path): """ Validates a file against a schema Parameters ---------- file_type : str Type of file to read. May be 'component', 'element', 'table', or 'references' file_path: Full path to the file to be validated Raises ------ RuntimeError If the file_type is not valid (and/or a schema doesn't exist) ValidationError If the given file does not pass validation FileNotFoundError If the file given by file_path doesn't exist """ file_data = fileio._read_plain_json(file_path, False) validate_data(file_type, file_data)
python
def validate_file(file_type, file_path): file_data = fileio._read_plain_json(file_path, False) validate_data(file_type, file_data)
[ "def", "validate_file", "(", "file_type", ",", "file_path", ")", ":", "file_data", "=", "fileio", ".", "_read_plain_json", "(", "file_path", ",", "False", ")", "validate_data", "(", "file_type", ",", "file_data", ")" ]
Validates a file against a schema Parameters ---------- file_type : str Type of file to read. May be 'component', 'element', 'table', or 'references' file_path: Full path to the file to be validated Raises ------ RuntimeError If the file_type is not valid (and/or a schema doesn't exist) ValidationError If the given file does not pass validation FileNotFoundError If the file given by file_path doesn't exist
[ "Validates", "a", "file", "against", "a", "schema" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/validator.py#L106-L128
230,740
MolSSI-BSE/basis_set_exchange
basis_set_exchange/validator.py
validate_data_dir
def validate_data_dir(data_dir): """ Validates all files in a data_dir """ all_meta, all_table, all_element, all_component = fileio.get_all_filelist(data_dir) for f in all_meta: full_path = os.path.join(data_dir, f) validate_file('metadata', full_path) for f in all_table: full_path = os.path.join(data_dir, f) validate_file('table', full_path) for f in all_element: full_path = os.path.join(data_dir, f) validate_file('element', full_path) for f in all_component: full_path = os.path.join(data_dir, f) validate_file('component', full_path)
python
def validate_data_dir(data_dir): all_meta, all_table, all_element, all_component = fileio.get_all_filelist(data_dir) for f in all_meta: full_path = os.path.join(data_dir, f) validate_file('metadata', full_path) for f in all_table: full_path = os.path.join(data_dir, f) validate_file('table', full_path) for f in all_element: full_path = os.path.join(data_dir, f) validate_file('element', full_path) for f in all_component: full_path = os.path.join(data_dir, f) validate_file('component', full_path)
[ "def", "validate_data_dir", "(", "data_dir", ")", ":", "all_meta", ",", "all_table", ",", "all_element", ",", "all_component", "=", "fileio", ".", "get_all_filelist", "(", "data_dir", ")", "for", "f", "in", "all_meta", ":", "full_path", "=", "os", ".", "path...
Validates all files in a data_dir
[ "Validates", "all", "files", "in", "a", "data_dir" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/validator.py#L131-L149
230,741
MolSSI-BSE/basis_set_exchange
basis_set_exchange/sort.py
sort_basis_dict
def sort_basis_dict(bs): """Sorts a basis set dictionary into a standard order This, for example, allows the written file to be more easily read by humans by, for example, putting the name and description before more detailed fields. This is generally for cosmetic reasons. However, users will generally like things in a consistent order """ # yapf: disable _keyorder = [ # Schema stuff 'molssi_bse_schema', 'schema_type', 'schema_version', # Auxiliary block 'jkfit', 'jfit', 'rifit', 'admmfit', 'dftxfit', 'dftjfit', # Basis set metadata 'name', 'names', 'aliases', 'flags', 'family', 'description', 'role', 'auxiliaries', 'notes', 'function_types', # Reference stuff 'reference_description', 'reference_keys', # Version metadata 'version', 'revision_description', # Sources of components 'data_source', # Elements and data 'elements', 'references', 'ecp_electrons', 'electron_shells', 'ecp_potentials', 'components', # Shell information 'function_type', 'region', 'angular_momentum', 'exponents', 'coefficients', 'ecp_type', 'angular_momentum', 'r_exponents', 'gaussian_exponents', 'coefficients' ] # yapf: enable # Add integers for the elements (being optimistic that element 150 will be found someday) _keyorder.extend([str(x) for x in range(150)]) bs_sorted = sorted(bs.items(), key=lambda x: _keyorder.index(x[0])) if _use_odict: bs_sorted = OrderedDict(bs_sorted) else: bs_sorted = dict(bs_sorted) for k, v in bs_sorted.items(): # If this is a dictionary, sort recursively # If this is a list, sort each element but DO NOT sort the list itself. if isinstance(v, dict): bs_sorted[k] = sort_basis_dict(v) elif isinstance(v, list): # Note - the only nested list is with coeffs, which shouldn't be sorted # (so we don't have to recurse into lists of lists) bs_sorted[k] = [sort_basis_dict(x) if isinstance(x, dict) else x for x in v] return bs_sorted
python
def sort_basis_dict(bs): # yapf: disable _keyorder = [ # Schema stuff 'molssi_bse_schema', 'schema_type', 'schema_version', # Auxiliary block 'jkfit', 'jfit', 'rifit', 'admmfit', 'dftxfit', 'dftjfit', # Basis set metadata 'name', 'names', 'aliases', 'flags', 'family', 'description', 'role', 'auxiliaries', 'notes', 'function_types', # Reference stuff 'reference_description', 'reference_keys', # Version metadata 'version', 'revision_description', # Sources of components 'data_source', # Elements and data 'elements', 'references', 'ecp_electrons', 'electron_shells', 'ecp_potentials', 'components', # Shell information 'function_type', 'region', 'angular_momentum', 'exponents', 'coefficients', 'ecp_type', 'angular_momentum', 'r_exponents', 'gaussian_exponents', 'coefficients' ] # yapf: enable # Add integers for the elements (being optimistic that element 150 will be found someday) _keyorder.extend([str(x) for x in range(150)]) bs_sorted = sorted(bs.items(), key=lambda x: _keyorder.index(x[0])) if _use_odict: bs_sorted = OrderedDict(bs_sorted) else: bs_sorted = dict(bs_sorted) for k, v in bs_sorted.items(): # If this is a dictionary, sort recursively # If this is a list, sort each element but DO NOT sort the list itself. if isinstance(v, dict): bs_sorted[k] = sort_basis_dict(v) elif isinstance(v, list): # Note - the only nested list is with coeffs, which shouldn't be sorted # (so we don't have to recurse into lists of lists) bs_sorted[k] = [sort_basis_dict(x) if isinstance(x, dict) else x for x in v] return bs_sorted
[ "def", "sort_basis_dict", "(", "bs", ")", ":", "# yapf: disable", "_keyorder", "=", "[", "# Schema stuff", "'molssi_bse_schema'", ",", "'schema_type'", ",", "'schema_version'", ",", "# Auxiliary block", "'jkfit'", ",", "'jfit'", ",", "'rifit'", ",", "'admmfit'", ","...
Sorts a basis set dictionary into a standard order This, for example, allows the written file to be more easily read by humans by, for example, putting the name and description before more detailed fields. This is generally for cosmetic reasons. However, users will generally like things in a consistent order
[ "Sorts", "a", "basis", "set", "dictionary", "into", "a", "standard", "order" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L16-L78
230,742
MolSSI-BSE/basis_set_exchange
basis_set_exchange/sort.py
sort_shell
def sort_shell(shell, use_copy=True): """ Sort a basis set shell into a standard order If use_copy is True, the input shells are not modified. """ if use_copy: shell = copy.deepcopy(shell) # Transpose of coefficients tmp_c = list(map(list, zip(*shell['coefficients']))) # For each primitive, find the index of the first nonzero coefficient nonzero_idx = [next((i for i, x in enumerate(c) if float(x) != 0.0), None) for c in tmp_c] # Zip together exponents and coeffs for sorting tmp = zip(shell['exponents'], tmp_c, nonzero_idx) # Sort by decreasing value of exponent tmp = sorted(tmp, key=lambda x: -float(x[0])) # Now (stable) sort by first non-zero coefficient tmp = sorted(tmp, key=lambda x: int(x[2])) # Unpack, and re-transpose the coefficients tmp_c = [x[1] for x in tmp] shell['exponents'] = [x[0] for x in tmp] # Now sort the columns of the coefficient by index of first nonzero coefficient tmp_c = list(map(list, zip(*tmp_c))) nonzero_idx = [next((i for i, x in enumerate(c) if float(x) != 0.0), None) for c in tmp_c] tmp = zip(tmp_c, nonzero_idx) tmp = sorted(tmp, key=lambda x: int(x[1])) tmp_c = [x[0] for x in tmp] shell['coefficients'] = tmp_c return shell
python
def sort_shell(shell, use_copy=True): if use_copy: shell = copy.deepcopy(shell) # Transpose of coefficients tmp_c = list(map(list, zip(*shell['coefficients']))) # For each primitive, find the index of the first nonzero coefficient nonzero_idx = [next((i for i, x in enumerate(c) if float(x) != 0.0), None) for c in tmp_c] # Zip together exponents and coeffs for sorting tmp = zip(shell['exponents'], tmp_c, nonzero_idx) # Sort by decreasing value of exponent tmp = sorted(tmp, key=lambda x: -float(x[0])) # Now (stable) sort by first non-zero coefficient tmp = sorted(tmp, key=lambda x: int(x[2])) # Unpack, and re-transpose the coefficients tmp_c = [x[1] for x in tmp] shell['exponents'] = [x[0] for x in tmp] # Now sort the columns of the coefficient by index of first nonzero coefficient tmp_c = list(map(list, zip(*tmp_c))) nonzero_idx = [next((i for i, x in enumerate(c) if float(x) != 0.0), None) for c in tmp_c] tmp = zip(tmp_c, nonzero_idx) tmp = sorted(tmp, key=lambda x: int(x[1])) tmp_c = [x[0] for x in tmp] shell['coefficients'] = tmp_c return shell
[ "def", "sort_shell", "(", "shell", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "shell", "=", "copy", ".", "deepcopy", "(", "shell", ")", "# Transpose of coefficients", "tmp_c", "=", "list", "(", "map", "(", "list", ",", "zip", "(", "...
Sort a basis set shell into a standard order If use_copy is True, the input shells are not modified.
[ "Sort", "a", "basis", "set", "shell", "into", "a", "standard", "order" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L81-L120
230,743
MolSSI-BSE/basis_set_exchange
basis_set_exchange/sort.py
sort_shells
def sort_shells(shells, use_copy=True): """ Sort a list of basis set shells into a standard order The order within a shell is by decreasing value of the exponent. The order of the shell list is in increasing angular momentum, and then by decreasing number of primitives, then decreasing value of the largest exponent. If use_copy is True, the input shells are not modified. """ if use_copy: shells = copy.deepcopy(shells) # Sort primitives within a shell # (copying already handled above) shells = [sort_shell(sh, False) for sh in shells] # Sort the list by increasing AM, then general contraction level, then decreasing highest exponent return list( sorted( shells, key=lambda x: (max(x['angular_momentum']), -len(x['exponents']), -len(x['coefficients']), -float( max(x['exponents'])))))
python
def sort_shells(shells, use_copy=True): if use_copy: shells = copy.deepcopy(shells) # Sort primitives within a shell # (copying already handled above) shells = [sort_shell(sh, False) for sh in shells] # Sort the list by increasing AM, then general contraction level, then decreasing highest exponent return list( sorted( shells, key=lambda x: (max(x['angular_momentum']), -len(x['exponents']), -len(x['coefficients']), -float( max(x['exponents'])))))
[ "def", "sort_shells", "(", "shells", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "shells", "=", "copy", ".", "deepcopy", "(", "shells", ")", "# Sort primitives within a shell", "# (copying already handled above)", "shells", "=", "[", "sort_shell...
Sort a list of basis set shells into a standard order The order within a shell is by decreasing value of the exponent. The order of the shell list is in increasing angular momentum, and then by decreasing number of primitives, then decreasing value of the largest exponent. If use_copy is True, the input shells are not modified.
[ "Sort", "a", "list", "of", "basis", "set", "shells", "into", "a", "standard", "order" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L123-L147
230,744
MolSSI-BSE/basis_set_exchange
basis_set_exchange/sort.py
sort_potentials
def sort_potentials(potentials, use_copy=True): """ Sort a list of ECP potentials into a standard order The order within a potential is not modified. The order of the shell list is in increasing angular momentum, with the largest angular momentum being moved to the front. If use_copy is True, the input potentials are not modified. """ if use_copy: potentials = copy.deepcopy(potentials) # Sort by increasing AM, then move the last element to the front potentials = list(sorted(potentials, key=lambda x: x['angular_momentum'])) potentials.insert(0, potentials.pop()) return potentials
python
def sort_potentials(potentials, use_copy=True): if use_copy: potentials = copy.deepcopy(potentials) # Sort by increasing AM, then move the last element to the front potentials = list(sorted(potentials, key=lambda x: x['angular_momentum'])) potentials.insert(0, potentials.pop()) return potentials
[ "def", "sort_potentials", "(", "potentials", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "potentials", "=", "copy", ".", "deepcopy", "(", "potentials", ")", "# Sort by increasing AM, then move the last element to the front", "potentials", "=", "list...
Sort a list of ECP potentials into a standard order The order within a potential is not modified. The order of the shell list is in increasing angular momentum, with the largest angular momentum being moved to the front. If use_copy is True, the input potentials are not modified.
[ "Sort", "a", "list", "of", "ECP", "potentials", "into", "a", "standard", "order" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L150-L168
230,745
MolSSI-BSE/basis_set_exchange
basis_set_exchange/sort.py
sort_basis
def sort_basis(basis, use_copy=True): """ Sorts all the information in a basis set into a standard order 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 'electron_shells' in el: el['electron_shells'] = sort_shells(el['electron_shells'], False) if 'ecp_potentials' in el: el['ecp_potentials'] = sort_potentials(el['ecp_potentials'], False) return sort_basis_dict(basis)
python
def sort_basis(basis, use_copy=True): if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if 'electron_shells' in el: el['electron_shells'] = sort_shells(el['electron_shells'], False) if 'ecp_potentials' in el: el['ecp_potentials'] = sort_potentials(el['ecp_potentials'], False) return sort_basis_dict(basis)
[ "def", "sort_basis", "(", "basis", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "basis", "=", "copy", ".", "deepcopy", "(", "basis", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ".", "items", "(", ")", ":", ...
Sorts all the information in a basis set into a standard order If use_copy is True, the input basis set is not modified.
[ "Sorts", "all", "the", "information", "in", "a", "basis", "set", "into", "a", "standard", "order" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L171-L187
230,746
MolSSI-BSE/basis_set_exchange
basis_set_exchange/sort.py
sort_single_reference
def sort_single_reference(ref_entry): """Sorts a dictionary containing data for a single reference into a standard order """ # yapf: disable _keyorder = [ # Schema stuff # This function gets called on the schema 'entry', too 'schema_type', 'schema_version', # Type of the entry 'type', # Actual publication info 'authors', 'title', 'booktitle', 'series', 'editors', 'journal', 'institution', 'volume', 'number', 'page', 'year', 'note', 'publisher', 'address', 'isbn', 'doi' ] # yapf: enable sorted_entry = sorted(ref_entry.items(), key=lambda x: _keyorder.index(x[0])) if _use_odict: return OrderedDict(sorted_entry) else: return dict(sorted_entry)
python
def sort_single_reference(ref_entry): # yapf: disable _keyorder = [ # Schema stuff # This function gets called on the schema 'entry', too 'schema_type', 'schema_version', # Type of the entry 'type', # Actual publication info 'authors', 'title', 'booktitle', 'series', 'editors', 'journal', 'institution', 'volume', 'number', 'page', 'year', 'note', 'publisher', 'address', 'isbn', 'doi' ] # yapf: enable sorted_entry = sorted(ref_entry.items(), key=lambda x: _keyorder.index(x[0])) if _use_odict: return OrderedDict(sorted_entry) else: return dict(sorted_entry)
[ "def", "sort_single_reference", "(", "ref_entry", ")", ":", "# yapf: disable", "_keyorder", "=", "[", "# Schema stuff", "# This function gets called on the schema 'entry', too", "'schema_type'", ",", "'schema_version'", ",", "# Type of the entry", "'type'", ",", "# Actual publi...
Sorts a dictionary containing data for a single reference into a standard order
[ "Sorts", "a", "dictionary", "containing", "data", "for", "a", "single", "reference", "into", "a", "standard", "order" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L190-L215
230,747
MolSSI-BSE/basis_set_exchange
basis_set_exchange/sort.py
sort_references_dict
def sort_references_dict(refs): """Sorts a reference dictionary into a standard order The keys of the references are also sorted, and the keys for the data for each reference are put in a more canonical order. """ if _use_odict: refs_sorted = OrderedDict() else: refs_sorted = dict() # We insert this first, That is ok - it will be overwritten # with the sorted version later refs_sorted['molssi_bse_schema'] = refs['molssi_bse_schema'] # This sorts the entries by reference key (author1985a, etc) for k, v in sorted(refs.items()): refs_sorted[k] = sort_single_reference(v) return refs_sorted
python
def sort_references_dict(refs): if _use_odict: refs_sorted = OrderedDict() else: refs_sorted = dict() # We insert this first, That is ok - it will be overwritten # with the sorted version later refs_sorted['molssi_bse_schema'] = refs['molssi_bse_schema'] # This sorts the entries by reference key (author1985a, etc) for k, v in sorted(refs.items()): refs_sorted[k] = sort_single_reference(v) return refs_sorted
[ "def", "sort_references_dict", "(", "refs", ")", ":", "if", "_use_odict", ":", "refs_sorted", "=", "OrderedDict", "(", ")", "else", ":", "refs_sorted", "=", "dict", "(", ")", "# We insert this first, That is ok - it will be overwritten", "# with the sorted version later",...
Sorts a reference dictionary into a standard order The keys of the references are also sorted, and the keys for the data for each reference are put in a more canonical order.
[ "Sorts", "a", "reference", "dictionary", "into", "a", "standard", "order" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/sort.py#L218-L238
230,748
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/readers/dalton.py
read_dalton
def read_dalton(basis_lines, fname): '''Reads Dalton-formatted file data and converts it to a dictionary with the usual BSE fields Note that the nwchem format does not store all the fields we have, so some fields are left blank ''' skipchars = '$' basis_lines = [l for l in basis_lines if l and not l[0] in skipchars] bs_data = create_skel('component') i = 0 while i < len(basis_lines): line = basis_lines[i] if line.lower().startswith('a '): element_Z = line.split()[1] i += 1 # Shell am is strictly increasing (I hope) shell_am = 0 while i < len(basis_lines) and not basis_lines[i].lower().startswith('a '): line = basis_lines[i] nprim, ngen = line.split() if not element_Z in bs_data['elements']: bs_data['elements'][element_Z] = {} if not 'electron_shells' in bs_data['elements'][element_Z]: bs_data['elements'][element_Z]['electron_shells'] = [] element_data = bs_data['elements'][element_Z] if shell_am <= 1: func_type = 'gto' else: func_type = 'gto_spherical' shell = { 'function_type': func_type, 'region': '', 'angular_momentum': [shell_am] } exponents = [] coefficients = [] i += 1 for _ in range(int(nprim)): line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() exponents.append(lsplt[0]) coefficients.append(lsplt[1:]) i += 1 shell['exponents'] = exponents # We need to transpose the coefficient matrix # (we store a matrix with primitives being the column index and # general contraction being the row index) shell['coefficients'] = list(map(list, zip(*coefficients))) # Make sure the number of general contractions is >0 # (This error was found in some bad files) if int(ngen) <= 0: raise RuntimeError("Number of general contractions is not greater than zero for element " + str(element_Z)) # Make sure the number of general contractions match the heading line if len(shell['coefficients']) != int(ngen): raise RuntimeError("Number of general contractions does not equal what was given for element " + str(element_Z)) element_data['electron_shells'].append(shell) shell_am += 1 return bs_data
python
def read_dalton(basis_lines, fname): '''Reads Dalton-formatted file data and converts it to a dictionary with the usual BSE fields Note that the nwchem format does not store all the fields we have, so some fields are left blank ''' skipchars = '$' basis_lines = [l for l in basis_lines if l and not l[0] in skipchars] bs_data = create_skel('component') i = 0 while i < len(basis_lines): line = basis_lines[i] if line.lower().startswith('a '): element_Z = line.split()[1] i += 1 # Shell am is strictly increasing (I hope) shell_am = 0 while i < len(basis_lines) and not basis_lines[i].lower().startswith('a '): line = basis_lines[i] nprim, ngen = line.split() if not element_Z in bs_data['elements']: bs_data['elements'][element_Z] = {} if not 'electron_shells' in bs_data['elements'][element_Z]: bs_data['elements'][element_Z]['electron_shells'] = [] element_data = bs_data['elements'][element_Z] if shell_am <= 1: func_type = 'gto' else: func_type = 'gto_spherical' shell = { 'function_type': func_type, 'region': '', 'angular_momentum': [shell_am] } exponents = [] coefficients = [] i += 1 for _ in range(int(nprim)): line = basis_lines[i].replace('D', 'E') line = line.replace('d', 'E') lsplt = line.split() exponents.append(lsplt[0]) coefficients.append(lsplt[1:]) i += 1 shell['exponents'] = exponents # We need to transpose the coefficient matrix # (we store a matrix with primitives being the column index and # general contraction being the row index) shell['coefficients'] = list(map(list, zip(*coefficients))) # Make sure the number of general contractions is >0 # (This error was found in some bad files) if int(ngen) <= 0: raise RuntimeError("Number of general contractions is not greater than zero for element " + str(element_Z)) # Make sure the number of general contractions match the heading line if len(shell['coefficients']) != int(ngen): raise RuntimeError("Number of general contractions does not equal what was given for element " + str(element_Z)) element_data['electron_shells'].append(shell) shell_am += 1 return bs_data
[ "def", "read_dalton", "(", "basis_lines", ",", "fname", ")", ":", "skipchars", "=", "'$'", "basis_lines", "=", "[", "l", "for", "l", "in", "basis_lines", "if", "l", "and", "not", "l", "[", "0", "]", "in", "skipchars", "]", "bs_data", "=", "create_skel"...
Reads Dalton-formatted file data and converts it to a dictionary with the usual BSE fields Note that the nwchem format does not store all the fields we have, so some fields are left blank
[ "Reads", "Dalton", "-", "formatted", "file", "data", "and", "converts", "it", "to", "a", "dictionary", "with", "the", "usual", "BSE", "fields" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/readers/dalton.py#L4-L82
230,749
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/common.py
find_range
def find_range(coeffs): ''' Find the range in a list of coefficients where the coefficient is nonzero ''' coeffs = [float(x) != 0 for x in coeffs] first = coeffs.index(True) coeffs.reverse() last = len(coeffs) - coeffs.index(True) - 1 return first, last
python
def find_range(coeffs): ''' Find the range in a list of coefficients where the coefficient is nonzero ''' coeffs = [float(x) != 0 for x in coeffs] first = coeffs.index(True) coeffs.reverse() last = len(coeffs) - coeffs.index(True) - 1 return first, last
[ "def", "find_range", "(", "coeffs", ")", ":", "coeffs", "=", "[", "float", "(", "x", ")", "!=", "0", "for", "x", "in", "coeffs", "]", "first", "=", "coeffs", ".", "index", "(", "True", ")", "coeffs", ".", "reverse", "(", ")", "last", "=", "len", ...
Find the range in a list of coefficients where the coefficient is nonzero
[ "Find", "the", "range", "in", "a", "list", "of", "coefficients", "where", "the", "coefficient", "is", "nonzero" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/common.py#L6-L15
230,750
MolSSI-BSE/basis_set_exchange
basis_set_exchange/refconverters/bib.py
_ref_bib
def _ref_bib(key, ref): '''Convert a single reference to bibtex format ''' s = '' s += '@{}{{{},\n'.format(ref['type'], key) entry_lines = [] for k, v in ref.items(): if k == 'type': continue # Handle authors/editors if k == 'authors': entry_lines.append(' author = {{{}}}'.format(' and '.join(v))) elif k == 'editors': entry_lines.append(' editor = {{{}}}'.format(' and '.join(v))) else: entry_lines.append(' {} = {{{}}}'.format(k, v)) s += ',\n'.join(entry_lines) s += '\n}' return s
python
def _ref_bib(key, ref): '''Convert a single reference to bibtex format ''' s = '' s += '@{}{{{},\n'.format(ref['type'], key) entry_lines = [] for k, v in ref.items(): if k == 'type': continue # Handle authors/editors if k == 'authors': entry_lines.append(' author = {{{}}}'.format(' and '.join(v))) elif k == 'editors': entry_lines.append(' editor = {{{}}}'.format(' and '.join(v))) else: entry_lines.append(' {} = {{{}}}'.format(k, v)) s += ',\n'.join(entry_lines) s += '\n}' return s
[ "def", "_ref_bib", "(", "key", ",", "ref", ")", ":", "s", "=", "''", "s", "+=", "'@{}{{{},\\n'", ".", "format", "(", "ref", "[", "'type'", "]", ",", "key", ")", "entry_lines", "=", "[", "]", "for", "k", ",", "v", "in", "ref", ".", "items", "(",...
Convert a single reference to bibtex format
[ "Convert", "a", "single", "reference", "to", "bibtex", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/refconverters/bib.py#L10-L33
230,751
MolSSI-BSE/basis_set_exchange
basis_set_exchange/refconverters/bib.py
write_bib
def write_bib(refs): '''Converts references to bibtex ''' full_str = '' lib_citation_desc, lib_citations = get_library_citation() full_str += '%' * 80 + '\n' full_str += textwrap.indent(lib_citation_desc, '% ') full_str += '%' * 80 + '\n\n' for k, r in lib_citations.items(): full_str += _ref_bib(k, r) + '\n\n' full_str += '%' * 80 + '\n' full_str += "% References for the basis set\n" full_str += '%' * 80 + '\n' # First, write out the element, description -> key mapping # Also make a dict of unique reference to output unique_refs = {} 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' else: rkeys = [x[0] for x in ri['reference_data']] full_str += '% {}\n%\n'.format(' '.join(rkeys)) for k, r in refdata: unique_refs[k] = r full_str += '\n\n' # Go through them sorted alphabetically by key for k, r in sorted(unique_refs.items(), key=lambda x: x[0]): full_str += '{}\n\n'.format(_ref_bib(k, r)) return full_str
python
def write_bib(refs): '''Converts references to bibtex ''' full_str = '' lib_citation_desc, lib_citations = get_library_citation() full_str += '%' * 80 + '\n' full_str += textwrap.indent(lib_citation_desc, '% ') full_str += '%' * 80 + '\n\n' for k, r in lib_citations.items(): full_str += _ref_bib(k, r) + '\n\n' full_str += '%' * 80 + '\n' full_str += "% References for the basis set\n" full_str += '%' * 80 + '\n' # First, write out the element, description -> key mapping # Also make a dict of unique reference to output unique_refs = {} 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' else: rkeys = [x[0] for x in ri['reference_data']] full_str += '% {}\n%\n'.format(' '.join(rkeys)) for k, r in refdata: unique_refs[k] = r full_str += '\n\n' # Go through them sorted alphabetically by key for k, r in sorted(unique_refs.items(), key=lambda x: x[0]): full_str += '{}\n\n'.format(_ref_bib(k, r)) return full_str
[ "def", "write_bib", "(", "refs", ")", ":", "full_str", "=", "''", "lib_citation_desc", ",", "lib_citations", "=", "get_library_citation", "(", ")", "full_str", "+=", "'%'", "*", "80", "+", "'\\n'", "full_str", "+=", "textwrap", ".", "indent", "(", "lib_citat...
Converts references to bibtex
[ "Converts", "references", "to", "bibtex" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/refconverters/bib.py#L36-L82
230,752
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/turbomole.py
write_turbomole
def write_turbomole(basis): '''Converts a basis set to Gaussian format ''' s = '$basis\n' s += '*\n' # TM basis sets are completely uncontracted basis = manip.uncontract_general(basis, True) basis = manip.uncontract_spdf(basis, 0, False) basis = sort.sort_basis(basis, False) # Elements for which we have electron basis electron_elements = [k for k, v in basis['elements'].items() if 'electron_shells' in v] # Elements for which we have ECP ecp_elements = [k for k, v in basis['elements'].items() if 'ecp_potentials' in v] # Electron Basis if len(electron_elements) > 0: for z in electron_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z, False) s += '{} {}\n'.format(sym, basis['name']) s += '*\n' for shell in data['electron_shells']: exponents = shell['exponents'] coefficients = shell['coefficients'] ncol = len(coefficients) + 1 nprim = len(exponents) am = shell['angular_momentum'] amchar = lut.amint_to_char(am, hij=True) s += ' {} {}\n'.format(nprim, amchar) point_places = [8 * i + 15 * (i - 1) for i in range(1, ncol + 1)] s += printing.write_matrix([exponents, *coefficients], point_places, convert_exp=True) s += '*\n' # Write out ECP if len(ecp_elements) > 0: s += '$ecp\n' s += '*\n' for z in ecp_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z) s += '{} {}-ecp\n'.format(sym, basis['name']) s += '*\n' max_ecp_am = max([x['angular_momentum'][0] for x in data['ecp_potentials']]) max_ecp_amchar = lut.amint_to_char([max_ecp_am], hij=True) # Sort lowest->highest, then put the highest at the beginning ecp_list = sorted(data['ecp_potentials'], key=lambda x: x['angular_momentum']) ecp_list.insert(0, ecp_list.pop()) s += ' ncore = {} lmax = {}\n'.format(data['ecp_electrons'], max_ecp_am) for pot in ecp_list: rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] am = pot['angular_momentum'] amchar = lut.amint_to_char(am, hij=True) if am[0] == max_ecp_am: s += '{}\n'.format(amchar) else: s += '{}-{}\n'.format(amchar, max_ecp_amchar) point_places = [9, 23, 32] s += printing.write_matrix([*coefficients, rexponents, gexponents], point_places, convert_exp=True) s += '*\n' s += '$end\n' return s
python
def write_turbomole(basis): '''Converts a basis set to Gaussian format ''' s = '$basis\n' s += '*\n' # TM basis sets are completely uncontracted basis = manip.uncontract_general(basis, True) basis = manip.uncontract_spdf(basis, 0, False) basis = sort.sort_basis(basis, False) # Elements for which we have electron basis electron_elements = [k for k, v in basis['elements'].items() if 'electron_shells' in v] # Elements for which we have ECP ecp_elements = [k for k, v in basis['elements'].items() if 'ecp_potentials' in v] # Electron Basis if len(electron_elements) > 0: for z in electron_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z, False) s += '{} {}\n'.format(sym, basis['name']) s += '*\n' for shell in data['electron_shells']: exponents = shell['exponents'] coefficients = shell['coefficients'] ncol = len(coefficients) + 1 nprim = len(exponents) am = shell['angular_momentum'] amchar = lut.amint_to_char(am, hij=True) s += ' {} {}\n'.format(nprim, amchar) point_places = [8 * i + 15 * (i - 1) for i in range(1, ncol + 1)] s += printing.write_matrix([exponents, *coefficients], point_places, convert_exp=True) s += '*\n' # Write out ECP if len(ecp_elements) > 0: s += '$ecp\n' s += '*\n' for z in ecp_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z) s += '{} {}-ecp\n'.format(sym, basis['name']) s += '*\n' max_ecp_am = max([x['angular_momentum'][0] for x in data['ecp_potentials']]) max_ecp_amchar = lut.amint_to_char([max_ecp_am], hij=True) # Sort lowest->highest, then put the highest at the beginning ecp_list = sorted(data['ecp_potentials'], key=lambda x: x['angular_momentum']) ecp_list.insert(0, ecp_list.pop()) s += ' ncore = {} lmax = {}\n'.format(data['ecp_electrons'], max_ecp_am) for pot in ecp_list: rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] am = pot['angular_momentum'] amchar = lut.amint_to_char(am, hij=True) if am[0] == max_ecp_am: s += '{}\n'.format(amchar) else: s += '{}-{}\n'.format(amchar, max_ecp_amchar) point_places = [9, 23, 32] s += printing.write_matrix([*coefficients, rexponents, gexponents], point_places, convert_exp=True) s += '*\n' s += '$end\n' return s
[ "def", "write_turbomole", "(", "basis", ")", ":", "s", "=", "'$basis\\n'", "s", "+=", "'*\\n'", "# TM basis sets are completely uncontracted", "basis", "=", "manip", ".", "uncontract_general", "(", "basis", ",", "True", ")", "basis", "=", "manip", ".", "uncontra...
Converts a basis set to Gaussian format
[ "Converts", "a", "basis", "set", "to", "Gaussian", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/turbomole.py#L8-L86
230,753
MolSSI-BSE/basis_set_exchange
basis_set_exchange/references.py
compact_references
def compact_references(basis_dict, ref_data): """ Creates a mapping of elements to reference keys A list is returned, with each element of the list being a dictionary with entries 'reference_info' containing data for (possibly) multiple references, and 'elements' which is a list of element Z numbers that those references apply to Parameters ---------- basis_dict : dict Dictionary containing basis set information ref_data : dict Dictionary containing all reference information """ element_refs = [] # Create a mapping of elements -> reference information # (sort by Z first, keeping in mind Z is a string) sorted_el = sorted(basis_dict['elements'].items(), key=lambda x: int(x[0])) for el, eldata in sorted_el: # elref is a list of dict # dict is { 'reference_description': str, 'reference_keys': [keys] } elref = eldata['references'] for x in element_refs: if x['reference_info'] == elref: x['elements'].append(el) break else: element_refs.append({'reference_info': elref, 'elements': [el]}) for item in element_refs: # Loop over a list of dictionaries for this group of elements and add the # actual reference data # Since we store the keys with the data, we don't need it anymore for elref in item['reference_info']: elref['reference_data'] = [(k, ref_data[k]) for k in elref['reference_keys']] elref.pop('reference_keys') return element_refs
python
def compact_references(basis_dict, ref_data): element_refs = [] # Create a mapping of elements -> reference information # (sort by Z first, keeping in mind Z is a string) sorted_el = sorted(basis_dict['elements'].items(), key=lambda x: int(x[0])) for el, eldata in sorted_el: # elref is a list of dict # dict is { 'reference_description': str, 'reference_keys': [keys] } elref = eldata['references'] for x in element_refs: if x['reference_info'] == elref: x['elements'].append(el) break else: element_refs.append({'reference_info': elref, 'elements': [el]}) for item in element_refs: # Loop over a list of dictionaries for this group of elements and add the # actual reference data # Since we store the keys with the data, we don't need it anymore for elref in item['reference_info']: elref['reference_data'] = [(k, ref_data[k]) for k in elref['reference_keys']] elref.pop('reference_keys') return element_refs
[ "def", "compact_references", "(", "basis_dict", ",", "ref_data", ")", ":", "element_refs", "=", "[", "]", "# Create a mapping of elements -> reference information", "# (sort by Z first, keeping in mind Z is a string)", "sorted_el", "=", "sorted", "(", "basis_dict", "[", "'ele...
Creates a mapping of elements to reference keys A list is returned, with each element of the list being a dictionary with entries 'reference_info' containing data for (possibly) multiple references, and 'elements' which is a list of element Z numbers that those references apply to Parameters ---------- basis_dict : dict Dictionary containing basis set information ref_data : dict Dictionary containing all reference information
[ "Creates", "a", "mapping", "of", "elements", "to", "reference", "keys" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/references.py#L8-L52
230,754
MolSSI-BSE/basis_set_exchange
basis_set_exchange/references.py
reference_text
def reference_text(ref): '''Convert a single reference to plain text format Parameters ---------- ref : dict Information about a single reference ''' ref_wrap = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 8) s = '' if ref['type'] == 'unpublished': s += ref_wrap.fill(', '.join(ref['authors'])) + '\n' s += ref_wrap.fill(ref['title']) + '\n' s += ref_wrap.fill(ref['note']) + '\n' elif ref['type'] == 'article': s += ref_wrap.fill(', '.join(ref['authors'])) + '\n' s += ref_wrap.fill(ref['title']) + '\n' s += '{}, {}, {} ({})'.format(ref['journal'], ref['volume'], ref['page'], ref['year']) s += '\n' + ref['doi'] elif ref['type'] == 'incollection': s += ref_wrap.fill(', '.join(ref['authors'])) s += ref_wrap.fill('\n{}'.format(ref['title'])) s += ref_wrap.fill('\nin \'{}\''.format(ref['booktitle'])) if 'editors' in ref: s += ref_wrap.fill('\ned. ' + ', '.join(ref['editors'])) if 'series' in ref: s += '\n{}, {}, {} ({})'.format(ref['series'], ref['volume'], ref['page'], ref['year']) if 'doi' in ref: s += '\n' + ref['doi'] elif ref['type'] == 'techreport': s += ref_wrap.fill(', '.join(ref['authors'])) s += ref_wrap.fill('\n{}'.format(ref['title'])) s += '\n\'{}\''.format(ref['institution']) s += '\nTechnical Report {}'.format(ref['number']) s += '\n{}'.format(ref['year']) if 'doi' in ref: s += '\n' + ref['doi'] elif ref['type'] == 'misc': s += ref_wrap.fill(', '.join(ref['authors'])) + '\n' s += ref_wrap.fill(ref['title']) if 'note' in ref: s += '\n' + ref['note'] if 'doi' in ref: s += '\n' + ref['doi'] else: raise RuntimeError('Cannot handle reference type {}'.format(ref['type'])) return s
python
def reference_text(ref): '''Convert a single reference to plain text format Parameters ---------- ref : dict Information about a single reference ''' ref_wrap = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 8) s = '' if ref['type'] == 'unpublished': s += ref_wrap.fill(', '.join(ref['authors'])) + '\n' s += ref_wrap.fill(ref['title']) + '\n' s += ref_wrap.fill(ref['note']) + '\n' elif ref['type'] == 'article': s += ref_wrap.fill(', '.join(ref['authors'])) + '\n' s += ref_wrap.fill(ref['title']) + '\n' s += '{}, {}, {} ({})'.format(ref['journal'], ref['volume'], ref['page'], ref['year']) s += '\n' + ref['doi'] elif ref['type'] == 'incollection': s += ref_wrap.fill(', '.join(ref['authors'])) s += ref_wrap.fill('\n{}'.format(ref['title'])) s += ref_wrap.fill('\nin \'{}\''.format(ref['booktitle'])) if 'editors' in ref: s += ref_wrap.fill('\ned. ' + ', '.join(ref['editors'])) if 'series' in ref: s += '\n{}, {}, {} ({})'.format(ref['series'], ref['volume'], ref['page'], ref['year']) if 'doi' in ref: s += '\n' + ref['doi'] elif ref['type'] == 'techreport': s += ref_wrap.fill(', '.join(ref['authors'])) s += ref_wrap.fill('\n{}'.format(ref['title'])) s += '\n\'{}\''.format(ref['institution']) s += '\nTechnical Report {}'.format(ref['number']) s += '\n{}'.format(ref['year']) if 'doi' in ref: s += '\n' + ref['doi'] elif ref['type'] == 'misc': s += ref_wrap.fill(', '.join(ref['authors'])) + '\n' s += ref_wrap.fill(ref['title']) if 'note' in ref: s += '\n' + ref['note'] if 'doi' in ref: s += '\n' + ref['doi'] else: raise RuntimeError('Cannot handle reference type {}'.format(ref['type'])) return s
[ "def", "reference_text", "(", "ref", ")", ":", "ref_wrap", "=", "textwrap", ".", "TextWrapper", "(", "initial_indent", "=", "''", ",", "subsequent_indent", "=", "' '", "*", "8", ")", "s", "=", "''", "if", "ref", "[", "'type'", "]", "==", "'unpublished'",...
Convert a single reference to plain text format Parameters ---------- ref : dict Information about a single reference
[ "Convert", "a", "single", "reference", "to", "plain", "text", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/references.py#L55-L103
230,755
MolSSI-BSE/basis_set_exchange
basis_set_exchange/printing.py
_determine_leftpad
def _determine_leftpad(column, point_place): '''Find how many spaces to put before a column of numbers so that all the decimal points line up This function takes a column of decimal numbers, and returns a vector containing the number of spaces to place before each number so that (when possible) the decimal points line up. Parameters ---------- column : list Numbers that will be printed as a column point_place : int Number of the character column to put the decimal point ''' # Find the number of digits before the decimal ndigits_left = [_find_point(x) for x in column] # find the padding per entry, filtering negative numbers return [max((point_place - 1) - x, 0) for x in ndigits_left]
python
def _determine_leftpad(column, point_place): '''Find how many spaces to put before a column of numbers so that all the decimal points line up This function takes a column of decimal numbers, and returns a vector containing the number of spaces to place before each number so that (when possible) the decimal points line up. Parameters ---------- column : list Numbers that will be printed as a column point_place : int Number of the character column to put the decimal point ''' # Find the number of digits before the decimal ndigits_left = [_find_point(x) for x in column] # find the padding per entry, filtering negative numbers return [max((point_place - 1) - x, 0) for x in ndigits_left]
[ "def", "_determine_leftpad", "(", "column", ",", "point_place", ")", ":", "# Find the number of digits before the decimal", "ndigits_left", "=", "[", "_find_point", "(", "x", ")", "for", "x", "in", "column", "]", "# find the padding per entry, filtering negative numbers", ...
Find how many spaces to put before a column of numbers so that all the decimal points line up This function takes a column of decimal numbers, and returns a vector containing the number of spaces to place before each number so that (when possible) the decimal points line up. Parameters ---------- column : list Numbers that will be printed as a column point_place : int Number of the character column to put the decimal point
[ "Find", "how", "many", "spaces", "to", "put", "before", "a", "column", "of", "numbers", "so", "that", "all", "the", "decimal", "points", "line", "up" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/printing.py#L16-L37
230,756
MolSSI-BSE/basis_set_exchange
basis_set_exchange/printing.py
electron_shell_str
def electron_shell_str(shell, shellidx=None): '''Return a string representing the data for an electron shell If shellidx (index of the shell) is not None, it will also be printed ''' am = shell['angular_momentum'] amchar = lut.amint_to_char(am) amchar = amchar.upper() shellidx_str = '' if shellidx is not None: shellidx_str = 'Index {} '.format(shellidx) exponents = shell['exponents'] coefficients = shell['coefficients'] ncol = len(coefficients) + 1 point_places = [8 * i + 15 * (i - 1) for i in range(1, ncol + 1)] s = "Shell: {}Region: {}: AM: {}\n".format(shellidx_str, shell['region'], amchar) s += "Function: {}\n".format(shell['function_type']) s += write_matrix([exponents, *coefficients], point_places) return s
python
def electron_shell_str(shell, shellidx=None): '''Return a string representing the data for an electron shell If shellidx (index of the shell) is not None, it will also be printed ''' am = shell['angular_momentum'] amchar = lut.amint_to_char(am) amchar = amchar.upper() shellidx_str = '' if shellidx is not None: shellidx_str = 'Index {} '.format(shellidx) exponents = shell['exponents'] coefficients = shell['coefficients'] ncol = len(coefficients) + 1 point_places = [8 * i + 15 * (i - 1) for i in range(1, ncol + 1)] s = "Shell: {}Region: {}: AM: {}\n".format(shellidx_str, shell['region'], amchar) s += "Function: {}\n".format(shell['function_type']) s += write_matrix([exponents, *coefficients], point_places) return s
[ "def", "electron_shell_str", "(", "shell", ",", "shellidx", "=", "None", ")", ":", "am", "=", "shell", "[", "'angular_momentum'", "]", "amchar", "=", "lut", ".", "amint_to_char", "(", "am", ")", "amchar", "=", "amchar", ".", "upper", "(", ")", "shellidx_...
Return a string representing the data for an electron shell If shellidx (index of the shell) is not None, it will also be printed
[ "Return", "a", "string", "representing", "the", "data", "for", "an", "electron", "shell" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/printing.py#L66-L87
230,757
MolSSI-BSE/basis_set_exchange
basis_set_exchange/printing.py
ecp_pot_str
def ecp_pot_str(pot): '''Return a string representing the data for an ECP potential ''' am = pot['angular_momentum'] amchar = lut.amint_to_char(am) rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] point_places = [0, 10, 33] s = 'Potential: {} potential\n'.format(amchar) s += 'Type: {}\n'.format(pot['ecp_type']) s += write_matrix([rexponents, gexponents, *coefficients], point_places) return s
python
def ecp_pot_str(pot): '''Return a string representing the data for an ECP potential ''' am = pot['angular_momentum'] amchar = lut.amint_to_char(am) rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] point_places = [0, 10, 33] s = 'Potential: {} potential\n'.format(amchar) s += 'Type: {}\n'.format(pot['ecp_type']) s += write_matrix([rexponents, gexponents, *coefficients], point_places) return s
[ "def", "ecp_pot_str", "(", "pot", ")", ":", "am", "=", "pot", "[", "'angular_momentum'", "]", "amchar", "=", "lut", ".", "amint_to_char", "(", "am", ")", "rexponents", "=", "pot", "[", "'r_exponents'", "]", "gexponents", "=", "pot", "[", "'gaussian_exponen...
Return a string representing the data for an ECP potential
[ "Return", "a", "string", "representing", "the", "data", "for", "an", "ECP", "potential" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/printing.py#L90-L105
230,758
MolSSI-BSE/basis_set_exchange
basis_set_exchange/printing.py
element_data_str
def element_data_str(z, eldata): '''Return a string with all data for an element This includes shell and ECP potential data Parameters ---------- z : int or str Element Z-number eldata: dict Data for the element to be printed ''' sym = lut.element_sym_from_Z(z, True) cs = contraction_string(eldata) if cs == '': cs = '(no electron shells)' s = '\nElement: {} : {}\n'.format(sym, cs) if 'electron_shells' in eldata: for shellidx, shell in enumerate(eldata['electron_shells']): s += electron_shell_str(shell, shellidx) + '\n' if 'ecp_potentials' in eldata: s += 'ECP: Element: {} Number of electrons: {}\n'.format(sym, eldata['ecp_electrons']) for pot in eldata['ecp_potentials']: s += ecp_pot_str(pot) + '\n' return s
python
def element_data_str(z, eldata): '''Return a string with all data for an element This includes shell and ECP potential data Parameters ---------- z : int or str Element Z-number eldata: dict Data for the element to be printed ''' sym = lut.element_sym_from_Z(z, True) cs = contraction_string(eldata) if cs == '': cs = '(no electron shells)' s = '\nElement: {} : {}\n'.format(sym, cs) if 'electron_shells' in eldata: for shellidx, shell in enumerate(eldata['electron_shells']): s += electron_shell_str(shell, shellidx) + '\n' if 'ecp_potentials' in eldata: s += 'ECP: Element: {} Number of electrons: {}\n'.format(sym, eldata['ecp_electrons']) for pot in eldata['ecp_potentials']: s += ecp_pot_str(pot) + '\n' return s
[ "def", "element_data_str", "(", "z", ",", "eldata", ")", ":", "sym", "=", "lut", ".", "element_sym_from_Z", "(", "z", ",", "True", ")", "cs", "=", "contraction_string", "(", "eldata", ")", "if", "cs", "==", "''", ":", "cs", "=", "'(no electron shells)'",...
Return a string with all data for an element This includes shell and ECP potential data Parameters ---------- z : int or str Element Z-number eldata: dict Data for the element to be printed
[ "Return", "a", "string", "with", "all", "data", "for", "an", "element" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/printing.py#L108-L138
230,759
MolSSI-BSE/basis_set_exchange
basis_set_exchange/printing.py
component_basis_str
def component_basis_str(basis, elements=None): '''Print a component basis set If elements is not None, only the specified elements will be printed (see :func:`bse.misc.expand_elements`) ''' s = "Description: " + basis['description'] + '\n' eldata = basis['elements'] # Filter to the given elements if elements is None: elements = list(eldata.keys()) else: elements = expand_elements(elements, True) # Add the str for each element for z in elements: s += element_data_str(z, eldata[z]) + '\n' return s
python
def component_basis_str(basis, elements=None): '''Print a component basis set If elements is not None, only the specified elements will be printed (see :func:`bse.misc.expand_elements`) ''' s = "Description: " + basis['description'] + '\n' eldata = basis['elements'] # Filter to the given elements if elements is None: elements = list(eldata.keys()) else: elements = expand_elements(elements, True) # Add the str for each element for z in elements: s += element_data_str(z, eldata[z]) + '\n' return s
[ "def", "component_basis_str", "(", "basis", ",", "elements", "=", "None", ")", ":", "s", "=", "\"Description: \"", "+", "basis", "[", "'description'", "]", "+", "'\\n'", "eldata", "=", "basis", "[", "'elements'", "]", "# Filter to the given elements", "if", "e...
Print a component basis set If elements is not None, only the specified elements will be printed (see :func:`bse.misc.expand_elements`)
[ "Print", "a", "component", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/printing.py#L141-L162
230,760
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/molpro.py
write_molpro
def write_molpro(basis): '''Converts a basis set to Molpro format ''' # Uncontract all, and make as generally-contracted as possible basis = manip.uncontract_spdf(basis, 0, True) basis = manip.make_general(basis, False) basis = sort.sort_basis(basis, True) s = '' # Elements for which we have electron basis electron_elements = [k for k, v in basis['elements'].items() if 'electron_shells' in v] # Elements for which we have ECP ecp_elements = [k for k, v in basis['elements'].items() if 'ecp_potentials' in v] if len(electron_elements) > 0: # basis set starts with a string s += 'basis={\n' # Electron Basis for z in electron_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z).upper() s += '!\n' s += '! {:20} {}\n'.format(lut.element_name_from_Z(z), misc.contraction_string(data)) for shell in data['electron_shells']: exponents = shell['exponents'] coefficients = shell['coefficients'] am = shell['angular_momentum'] amchar = lut.amint_to_char(am).lower() s += '{}, {} , {}\n'.format(amchar, sym, ', '.join(exponents)) for c in coefficients: first, last = find_range(c) s += 'c, {}.{}, {}\n'.format(first + 1, last + 1, ', '.join(c[first:last + 1])) s += '}\n' # Write out ECP if len(ecp_elements) > 0: s += '\n\n! Effective core Potentials\n' for z in ecp_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z).lower() max_ecp_am = max([x['angular_momentum'][0] for x in data['ecp_potentials']]) # Sort lowest->highest, then put the highest at the beginning ecp_list = sorted(data['ecp_potentials'], key=lambda x: x['angular_momentum']) ecp_list.insert(0, ecp_list.pop()) s += 'ECP, {}, {}, {} ;\n'.format(sym, data['ecp_electrons'], max_ecp_am) for pot in ecp_list: rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] am = pot['angular_momentum'] amchar = lut.amint_to_char(am).lower() s += '{};'.format(len(rexponents)) if am[0] == max_ecp_am: s += ' ! ul potential\n' else: s += ' ! {}-ul potential\n'.format(amchar) for p in range(len(rexponents)): s += '{},{},{};\n'.format(rexponents[p], gexponents[p], coefficients[0][p]) return s
python
def write_molpro(basis): '''Converts a basis set to Molpro format ''' # Uncontract all, and make as generally-contracted as possible basis = manip.uncontract_spdf(basis, 0, True) basis = manip.make_general(basis, False) basis = sort.sort_basis(basis, True) s = '' # Elements for which we have electron basis electron_elements = [k for k, v in basis['elements'].items() if 'electron_shells' in v] # Elements for which we have ECP ecp_elements = [k for k, v in basis['elements'].items() if 'ecp_potentials' in v] if len(electron_elements) > 0: # basis set starts with a string s += 'basis={\n' # Electron Basis for z in electron_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z).upper() s += '!\n' s += '! {:20} {}\n'.format(lut.element_name_from_Z(z), misc.contraction_string(data)) for shell in data['electron_shells']: exponents = shell['exponents'] coefficients = shell['coefficients'] am = shell['angular_momentum'] amchar = lut.amint_to_char(am).lower() s += '{}, {} , {}\n'.format(amchar, sym, ', '.join(exponents)) for c in coefficients: first, last = find_range(c) s += 'c, {}.{}, {}\n'.format(first + 1, last + 1, ', '.join(c[first:last + 1])) s += '}\n' # Write out ECP if len(ecp_elements) > 0: s += '\n\n! Effective core Potentials\n' for z in ecp_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z).lower() max_ecp_am = max([x['angular_momentum'][0] for x in data['ecp_potentials']]) # Sort lowest->highest, then put the highest at the beginning ecp_list = sorted(data['ecp_potentials'], key=lambda x: x['angular_momentum']) ecp_list.insert(0, ecp_list.pop()) s += 'ECP, {}, {}, {} ;\n'.format(sym, data['ecp_electrons'], max_ecp_am) for pot in ecp_list: rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] am = pot['angular_momentum'] amchar = lut.amint_to_char(am).lower() s += '{};'.format(len(rexponents)) if am[0] == max_ecp_am: s += ' ! ul potential\n' else: s += ' ! {}-ul potential\n'.format(amchar) for p in range(len(rexponents)): s += '{},{},{};\n'.format(rexponents[p], gexponents[p], coefficients[0][p]) return s
[ "def", "write_molpro", "(", "basis", ")", ":", "# Uncontract all, and make as generally-contracted as possible", "basis", "=", "manip", ".", "uncontract_spdf", "(", "basis", ",", "0", ",", "True", ")", "basis", "=", "manip", ".", "make_general", "(", "basis", ",",...
Converts a basis set to Molpro format
[ "Converts", "a", "basis", "set", "to", "Molpro", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/molpro.py#L9-L80
230,761
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/convert.py
convert_basis
def convert_basis(basis_dict, fmt, header=None): ''' Returns the basis set data as a string representing the data in the specified output format ''' # make converters case insensitive fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown basis set format "{}"'.format(fmt)) converter = _converter_map[fmt] # Determine if the converter supports all the types in the basis_dict if converter['valid'] is not None: ftypes = set(basis_dict['function_types']) if ftypes > converter['valid']: raise RuntimeError('Converter {} does not support all function types: {}'.format(fmt, str(ftypes))) # Actually do the conversion ret_str = converter['function'](basis_dict) if header is not None and fmt != 'json': comment_str = _converter_map[fmt]['comment'] header_str = comment_str + comment_str.join(header.splitlines(True)) ret_str = header_str + '\n\n' + ret_str # HACK - Psi4 requires the first non-comment line be spherical/cartesian # so we have to add that before the header if fmt == 'psi4': types = basis_dict['function_types'] harm_type = 'spherical' if 'spherical_gto' in types else 'cartesian' ret_str = harm_type + '\n\n' + ret_str return ret_str
python
def convert_basis(basis_dict, fmt, header=None): ''' Returns the basis set data as a string representing the data in the specified output format ''' # make converters case insensitive fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown basis set format "{}"'.format(fmt)) converter = _converter_map[fmt] # Determine if the converter supports all the types in the basis_dict if converter['valid'] is not None: ftypes = set(basis_dict['function_types']) if ftypes > converter['valid']: raise RuntimeError('Converter {} does not support all function types: {}'.format(fmt, str(ftypes))) # Actually do the conversion ret_str = converter['function'](basis_dict) if header is not None and fmt != 'json': comment_str = _converter_map[fmt]['comment'] header_str = comment_str + comment_str.join(header.splitlines(True)) ret_str = header_str + '\n\n' + ret_str # HACK - Psi4 requires the first non-comment line be spherical/cartesian # so we have to add that before the header if fmt == 'psi4': types = basis_dict['function_types'] harm_type = 'spherical' if 'spherical_gto' in types else 'cartesian' ret_str = harm_type + '\n\n' + ret_str return ret_str
[ "def", "convert_basis", "(", "basis_dict", ",", "fmt", ",", "header", "=", "None", ")", ":", "# make converters case insensitive", "fmt", "=", "fmt", ".", "lower", "(", ")", "if", "fmt", "not", "in", "_converter_map", ":", "raise", "RuntimeError", "(", "'Unk...
Returns the basis set data as a string representing the data in the specified output format
[ "Returns", "the", "basis", "set", "data", "as", "a", "string", "representing", "the", "data", "in", "the", "specified", "output", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/convert.py#L82-L116
230,762
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/convert.py
get_formats
def get_formats(function_types=None): ''' Returns the available formats mapped to display name. This is returned as an ordered dictionary, with the most common at the top, followed by the rest in alphabetical order If a list is specified for function_types, only those formats supporting the given function types will be returned. ''' if function_types is None: return {k: v['display'] for k, v in _converter_map.items()} ftypes = [x.lower() for x in function_types] ftypes = set(ftypes) ret = [] for fmt, v in _converter_map.items(): if v['valid'] is None or ftypes <= v['valid']: ret.append(fmt) return ret
python
def get_formats(function_types=None): ''' Returns the available formats mapped to display name. This is returned as an ordered dictionary, with the most common at the top, followed by the rest in alphabetical order If a list is specified for function_types, only those formats supporting the given function types will be returned. ''' if function_types is None: return {k: v['display'] for k, v in _converter_map.items()} ftypes = [x.lower() for x in function_types] ftypes = set(ftypes) ret = [] for fmt, v in _converter_map.items(): if v['valid'] is None or ftypes <= v['valid']: ret.append(fmt) return ret
[ "def", "get_formats", "(", "function_types", "=", "None", ")", ":", "if", "function_types", "is", "None", ":", "return", "{", "k", ":", "v", "[", "'display'", "]", "for", "k", ",", "v", "in", "_converter_map", ".", "items", "(", ")", "}", "ftypes", "...
Returns the available formats mapped to display name. This is returned as an ordered dictionary, with the most common at the top, followed by the rest in alphabetical order If a list is specified for function_types, only those formats supporting the given function types will be returned.
[ "Returns", "the", "available", "formats", "mapped", "to", "display", "name", "." ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/convert.py#L119-L140
230,763
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/convert.py
get_format_extension
def get_format_extension(fmt): ''' Returns the recommended extension for a given format ''' if fmt is None: return 'dict' fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown basis set format "{}"'.format(fmt)) return _converter_map[fmt]['extension']
python
def get_format_extension(fmt): ''' Returns the recommended extension for a given format ''' if fmt is None: return 'dict' fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown basis set format "{}"'.format(fmt)) return _converter_map[fmt]['extension']
[ "def", "get_format_extension", "(", "fmt", ")", ":", "if", "fmt", "is", "None", ":", "return", "'dict'", "fmt", "=", "fmt", ".", "lower", "(", ")", "if", "fmt", "not", "in", "_converter_map", ":", "raise", "RuntimeError", "(", "'Unknown basis set format \"{}...
Returns the recommended extension for a given format
[ "Returns", "the", "recommended", "extension", "for", "a", "given", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/convert.py#L143-L155
230,764
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/graph.py
_make_graph
def _make_graph(bsname, version=None, data_dir=None): ''' Create a DOT graph file of the files included in a basis set ''' if not graphviz_avail: raise RuntimeError("graphviz package is not installed") data_dir = api.fix_data_dir(data_dir) md = api._get_basis_metadata(bsname, data_dir) if version is None: version = md['latest_version'] else: version = str(version) if not version in md['versions']: raise RuntimeError("Version {} of {} doesn't exist".format(version, bsname)) gr = graphviz.Digraph(comment='Basis Set Graph: ' + bsname) # Read the table file table_path = os.path.join(data_dir, md['versions'][version]['file_relpath']) table_data = fileio.read_json_basis(table_path) table_edges = {} for el, entry in table_data['elements'].items(): if entry not in table_edges: table_edges[entry] = [] table_edges[entry].append(el) for k, v in table_edges.items(): gr.edge(bsname, k, label=compact_elements(v)) # Element file for elfile in table_edges.keys(): element_path = os.path.join(data_dir, elfile) element_data = fileio.read_json_basis(element_path) element_edges = {} for el, components in element_data['elements'].items(): components = components['components'] components_str = '\n'.join(components) # skip if this element for the table basis doesn't come from this file if el not in table_data['elements']: continue if table_data['elements'][el] != elfile: continue if components_str not in element_edges: element_edges[components_str] = [] element_edges[components_str].append(el) for k, v in element_edges.items(): if len(v): gr.edge(elfile, k, label=compact_elements(v)) return gr
python
def _make_graph(bsname, version=None, data_dir=None): ''' Create a DOT graph file of the files included in a basis set ''' if not graphviz_avail: raise RuntimeError("graphviz package is not installed") data_dir = api.fix_data_dir(data_dir) md = api._get_basis_metadata(bsname, data_dir) if version is None: version = md['latest_version'] else: version = str(version) if not version in md['versions']: raise RuntimeError("Version {} of {} doesn't exist".format(version, bsname)) gr = graphviz.Digraph(comment='Basis Set Graph: ' + bsname) # Read the table file table_path = os.path.join(data_dir, md['versions'][version]['file_relpath']) table_data = fileio.read_json_basis(table_path) table_edges = {} for el, entry in table_data['elements'].items(): if entry not in table_edges: table_edges[entry] = [] table_edges[entry].append(el) for k, v in table_edges.items(): gr.edge(bsname, k, label=compact_elements(v)) # Element file for elfile in table_edges.keys(): element_path = os.path.join(data_dir, elfile) element_data = fileio.read_json_basis(element_path) element_edges = {} for el, components in element_data['elements'].items(): components = components['components'] components_str = '\n'.join(components) # skip if this element for the table basis doesn't come from this file if el not in table_data['elements']: continue if table_data['elements'][el] != elfile: continue if components_str not in element_edges: element_edges[components_str] = [] element_edges[components_str].append(el) for k, v in element_edges.items(): if len(v): gr.edge(elfile, k, label=compact_elements(v)) return gr
[ "def", "_make_graph", "(", "bsname", ",", "version", "=", "None", ",", "data_dir", "=", "None", ")", ":", "if", "not", "graphviz_avail", ":", "raise", "RuntimeError", "(", "\"graphviz package is not installed\"", ")", "data_dir", "=", "api", ".", "fix_data_dir",...
Create a DOT graph file of the files included in a basis set
[ "Create", "a", "DOT", "graph", "file", "of", "the", "files", "included", "in", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/graph.py#L15-L75
230,765
MolSSI-BSE/basis_set_exchange
basis_set_exchange/refconverters/common.py
get_library_citation
def get_library_citation(): '''Return a descriptive string and reference data for what users of the library should cite''' all_ref_data = api.get_reference_data() lib_refs_data = {k: all_ref_data[k] for k in _lib_refs} return (_lib_refs_desc, lib_refs_data)
python
def get_library_citation(): '''Return a descriptive string and reference data for what users of the library should cite''' all_ref_data = api.get_reference_data() lib_refs_data = {k: all_ref_data[k] for k in _lib_refs} return (_lib_refs_desc, lib_refs_data)
[ "def", "get_library_citation", "(", ")", ":", "all_ref_data", "=", "api", ".", "get_reference_data", "(", ")", "lib_refs_data", "=", "{", "k", ":", "all_ref_data", "[", "k", "]", "for", "k", "in", "_lib_refs", "}", "return", "(", "_lib_refs_desc", ",", "li...
Return a descriptive string and reference data for what users of the library should cite
[ "Return", "a", "descriptive", "string", "and", "reference", "data", "for", "what", "users", "of", "the", "library", "should", "cite" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/refconverters/common.py#L11-L16
230,766
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/common.py
format_columns
def format_columns(lines, prefix=''): ''' Create a simple column output Parameters ---------- lines : list List of lines to format. Each line is a tuple/list with each element corresponding to a column prefix : str Characters to insert at the beginning of each line Returns ------- str Columnated output as one big string ''' if len(lines) == 0: return '' ncols = 0 for l in lines: ncols = max(ncols, len(l)) if ncols == 0: return '' # We only find the max strlen for all but the last col maxlen = [0] * (ncols - 1) for l in lines: for c in range(ncols - 1): maxlen[c] = max(maxlen[c], len(l[c])) fmtstr = prefix + ' '.join(['{{:{x}}}'.format(x=x) for x in maxlen]) fmtstr += ' {}' return [fmtstr.format(*l) for l in lines]
python
def format_columns(lines, prefix=''): ''' Create a simple column output Parameters ---------- lines : list List of lines to format. Each line is a tuple/list with each element corresponding to a column prefix : str Characters to insert at the beginning of each line Returns ------- str Columnated output as one big string ''' if len(lines) == 0: return '' ncols = 0 for l in lines: ncols = max(ncols, len(l)) if ncols == 0: return '' # We only find the max strlen for all but the last col maxlen = [0] * (ncols - 1) for l in lines: for c in range(ncols - 1): maxlen[c] = max(maxlen[c], len(l[c])) fmtstr = prefix + ' '.join(['{{:{x}}}'.format(x=x) for x in maxlen]) fmtstr += ' {}' return [fmtstr.format(*l) for l in lines]
[ "def", "format_columns", "(", "lines", ",", "prefix", "=", "''", ")", ":", "if", "len", "(", "lines", ")", "==", "0", ":", "return", "''", "ncols", "=", "0", "for", "l", "in", "lines", ":", "ncols", "=", "max", "(", "ncols", ",", "len", "(", "l...
Create a simple column output Parameters ---------- lines : list List of lines to format. Each line is a tuple/list with each element corresponding to a column prefix : str Characters to insert at the beginning of each line Returns ------- str Columnated output as one big string
[ "Create", "a", "simple", "column", "output" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/common.py#L5-L40
230,767
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/nwchem.py
write_nwchem
def write_nwchem(basis): '''Converts a basis set to NWChem format ''' # Uncontract all but SP basis = manip.uncontract_spdf(basis, 1, True) basis = sort.sort_basis(basis, True) s = '' # Elements for which we have electron basis electron_elements = [k for k, v in basis['elements'].items() if 'electron_shells' in v] # Elements for which we have ECP ecp_elements = [k for k, v in basis['elements'].items() if 'ecp_potentials' in v] if len(electron_elements) > 0: # basis set starts with a string s += 'BASIS "ao basis" PRINT\n' # Electron Basis for z in electron_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z, True) s += '#BASIS SET: {}\n'.format(misc.contraction_string(data)) for shell in data['electron_shells']: exponents = shell['exponents'] coefficients = shell['coefficients'] ncol = len(coefficients) + 1 am = shell['angular_momentum'] amchar = lut.amint_to_char(am).upper() s += '{} {}\n'.format(sym, amchar) point_places = [8 * i + 15 * (i - 1) for i in range(1, ncol + 1)] s += printing.write_matrix([exponents, *coefficients], point_places) s += 'END\n' # Write out ECP if len(ecp_elements) > 0: s += '\n\nECP\n' for z in ecp_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z, True) max_ecp_am = max([x['angular_momentum'][0] for x in data['ecp_potentials']]) # Sort lowest->highest, then put the highest at the beginning ecp_list = sorted(data['ecp_potentials'], key=lambda x: x['angular_momentum']) ecp_list.insert(0, ecp_list.pop()) s += '{} nelec {}\n'.format(sym, data['ecp_electrons']) for pot in ecp_list: rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] am = pot['angular_momentum'] amchar = lut.amint_to_char(am).upper() if am[0] == max_ecp_am: s += '{} ul\n'.format(sym) else: s += '{} {}\n'.format(sym, amchar) point_places = [0, 10, 33] s += printing.write_matrix([rexponents, gexponents, *coefficients], point_places) s += 'END\n' return s
python
def write_nwchem(basis): '''Converts a basis set to NWChem format ''' # Uncontract all but SP basis = manip.uncontract_spdf(basis, 1, True) basis = sort.sort_basis(basis, True) s = '' # Elements for which we have electron basis electron_elements = [k for k, v in basis['elements'].items() if 'electron_shells' in v] # Elements for which we have ECP ecp_elements = [k for k, v in basis['elements'].items() if 'ecp_potentials' in v] if len(electron_elements) > 0: # basis set starts with a string s += 'BASIS "ao basis" PRINT\n' # Electron Basis for z in electron_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z, True) s += '#BASIS SET: {}\n'.format(misc.contraction_string(data)) for shell in data['electron_shells']: exponents = shell['exponents'] coefficients = shell['coefficients'] ncol = len(coefficients) + 1 am = shell['angular_momentum'] amchar = lut.amint_to_char(am).upper() s += '{} {}\n'.format(sym, amchar) point_places = [8 * i + 15 * (i - 1) for i in range(1, ncol + 1)] s += printing.write_matrix([exponents, *coefficients], point_places) s += 'END\n' # Write out ECP if len(ecp_elements) > 0: s += '\n\nECP\n' for z in ecp_elements: data = basis['elements'][z] sym = lut.element_sym_from_Z(z, True) max_ecp_am = max([x['angular_momentum'][0] for x in data['ecp_potentials']]) # Sort lowest->highest, then put the highest at the beginning ecp_list = sorted(data['ecp_potentials'], key=lambda x: x['angular_momentum']) ecp_list.insert(0, ecp_list.pop()) s += '{} nelec {}\n'.format(sym, data['ecp_electrons']) for pot in ecp_list: rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] am = pot['angular_momentum'] amchar = lut.amint_to_char(am).upper() if am[0] == max_ecp_am: s += '{} ul\n'.format(sym) else: s += '{} {}\n'.format(sym, amchar) point_places = [0, 10, 33] s += printing.write_matrix([rexponents, gexponents, *coefficients], point_places) s += 'END\n' return s
[ "def", "write_nwchem", "(", "basis", ")", ":", "# Uncontract all but SP", "basis", "=", "manip", ".", "uncontract_spdf", "(", "basis", ",", "1", ",", "True", ")", "basis", "=", "sort", ".", "sort_basis", "(", "basis", ",", "True", ")", "s", "=", "''", ...
Converts a basis set to NWChem format
[ "Converts", "a", "basis", "set", "to", "NWChem", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/nwchem.py#L8-L81
230,768
MolSSI-BSE/basis_set_exchange
basis_set_exchange/misc.py
contraction_string
def contraction_string(element): """ Forms a string specifying the contractions for an element ie, (16s,10p) -> [4s,3p] """ # Does not have electron shells (ECP only?) if 'electron_shells' not in element: return "" cont_map = dict() for sh in element['electron_shells']: nprim = len(sh['exponents']) ngeneral = len(sh['coefficients']) # is a combined general contraction (sp, spd, etc) is_spdf = len(sh['angular_momentum']) > 1 for am in sh['angular_momentum']: # If this a general contraction (and not combined am), then use that ncont = ngeneral if not is_spdf else 1 if am not in cont_map: cont_map[am] = (nprim, ncont) else: cont_map[am] = (cont_map[am][0] + nprim, cont_map[am][1] + ncont) primstr = "" contstr = "" for am in sorted(cont_map.keys()): nprim, ncont = cont_map[am] if am != 0: primstr += ',' contstr += ',' primstr += str(nprim) + lut.amint_to_char([am]) contstr += str(ncont) + lut.amint_to_char([am]) return "({}) -> [{}]".format(primstr, contstr)
python
def contraction_string(element): # Does not have electron shells (ECP only?) if 'electron_shells' not in element: return "" cont_map = dict() for sh in element['electron_shells']: nprim = len(sh['exponents']) ngeneral = len(sh['coefficients']) # is a combined general contraction (sp, spd, etc) is_spdf = len(sh['angular_momentum']) > 1 for am in sh['angular_momentum']: # If this a general contraction (and not combined am), then use that ncont = ngeneral if not is_spdf else 1 if am not in cont_map: cont_map[am] = (nprim, ncont) else: cont_map[am] = (cont_map[am][0] + nprim, cont_map[am][1] + ncont) primstr = "" contstr = "" for am in sorted(cont_map.keys()): nprim, ncont = cont_map[am] if am != 0: primstr += ',' contstr += ',' primstr += str(nprim) + lut.amint_to_char([am]) contstr += str(ncont) + lut.amint_to_char([am]) return "({}) -> [{}]".format(primstr, contstr)
[ "def", "contraction_string", "(", "element", ")", ":", "# Does not have electron shells (ECP only?)", "if", "'electron_shells'", "not", "in", "element", ":", "return", "\"\"", "cont_map", "=", "dict", "(", ")", "for", "sh", "in", "element", "[", "'electron_shells'",...
Forms a string specifying the contractions for an element ie, (16s,10p) -> [4s,3p]
[ "Forms", "a", "string", "specifying", "the", "contractions", "for", "an", "element" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/misc.py#L16-L55
230,769
MolSSI-BSE/basis_set_exchange
basis_set_exchange/misc.py
expand_elements
def expand_elements(compact_el, as_str=False): """ Create a list of integers given a string or list of compacted elements This is partly the opposite of compact_elements, but is more flexible. compact_el can be a list or a string. If compact_el is a list, each element is processed individually as a string (meaning list elements can contain commas, ranges, etc) If compact_el is a string, it is split by commas and then each section is processed. In all cases, element symbols (case insensitive) and Z numbers (as integers or strings) can be used interchangeably. Ranges are also allowed in both lists and strings. Some examples: "H-Li,C-O,Ne" will return [1, 2, 3, 6, 7, 8, 10] "H-N,8,Na-12" will return [1, 2, 3, 4, 5, 6, 7, 8, 11, 12] ['C', 'Al-15,S', 17, '18'] will return [6, 13, 14, 15, 16, 17, 18] If as_str is True, the list will contain strings of the integers (ie, the first example above will return ['1', '2', '3', '6', '7', '8', '10'] """ # If an integer, just return it if isinstance(compact_el, int): if as_str is True: return [str(compact_el)] else: return [compact_el] # If compact_el is a list, make it a comma-separated string if isinstance(compact_el, list): compact_el = [str(x) for x in compact_el] compact_el = [x for x in compact_el if len(x) > 0] compact_el = ','.join(compact_el) # Find multiple - or , # Also replace all whitespace with spaces compact_el = re.sub(r',+', ',', compact_el) compact_el = re.sub(r'-+', '-', compact_el) compact_el = re.sub(r'\s+', '', compact_el) # Find starting with or ending with comma and strip them compact_el = compact_el.strip(',') # Check if I was passed an empty string or list if len(compact_el) == 0: return [] # Find some erroneous patterns # -, and ,- if '-,' in compact_el: raise RuntimeError("Malformed element string") if ',-' in compact_el: raise RuntimeError("Malformed element string") # Strings ends or begins with - if compact_el.startswith('-') or compact_el.endswith('-'): raise RuntimeError("Malformed element string") # x-y-z if re.search(r'\w+-\w+-\w+', compact_el): raise RuntimeError("Malformed element string") # Split on commas tmp_list = compact_el.split(',') # Now go over each one and replace elements with ints el_list = [] for el in tmp_list: if not '-' in el: el_list.append(_Z_from_str(el)) else: begin, end = el.split('-') begin = _Z_from_str(begin) end = _Z_from_str(end) el_list.extend(list(range(begin, end + 1))) if as_str is True: return [str(x) for x in el_list] else: return el_list
python
def expand_elements(compact_el, as_str=False): # If an integer, just return it if isinstance(compact_el, int): if as_str is True: return [str(compact_el)] else: return [compact_el] # If compact_el is a list, make it a comma-separated string if isinstance(compact_el, list): compact_el = [str(x) for x in compact_el] compact_el = [x for x in compact_el if len(x) > 0] compact_el = ','.join(compact_el) # Find multiple - or , # Also replace all whitespace with spaces compact_el = re.sub(r',+', ',', compact_el) compact_el = re.sub(r'-+', '-', compact_el) compact_el = re.sub(r'\s+', '', compact_el) # Find starting with or ending with comma and strip them compact_el = compact_el.strip(',') # Check if I was passed an empty string or list if len(compact_el) == 0: return [] # Find some erroneous patterns # -, and ,- if '-,' in compact_el: raise RuntimeError("Malformed element string") if ',-' in compact_el: raise RuntimeError("Malformed element string") # Strings ends or begins with - if compact_el.startswith('-') or compact_el.endswith('-'): raise RuntimeError("Malformed element string") # x-y-z if re.search(r'\w+-\w+-\w+', compact_el): raise RuntimeError("Malformed element string") # Split on commas tmp_list = compact_el.split(',') # Now go over each one and replace elements with ints el_list = [] for el in tmp_list: if not '-' in el: el_list.append(_Z_from_str(el)) else: begin, end = el.split('-') begin = _Z_from_str(begin) end = _Z_from_str(end) el_list.extend(list(range(begin, end + 1))) if as_str is True: return [str(x) for x in el_list] else: return el_list
[ "def", "expand_elements", "(", "compact_el", ",", "as_str", "=", "False", ")", ":", "# If an integer, just return it", "if", "isinstance", "(", "compact_el", ",", "int", ")", ":", "if", "as_str", "is", "True", ":", "return", "[", "str", "(", "compact_el", ")...
Create a list of integers given a string or list of compacted elements This is partly the opposite of compact_elements, but is more flexible. compact_el can be a list or a string. If compact_el is a list, each element is processed individually as a string (meaning list elements can contain commas, ranges, etc) If compact_el is a string, it is split by commas and then each section is processed. In all cases, element symbols (case insensitive) and Z numbers (as integers or strings) can be used interchangeably. Ranges are also allowed in both lists and strings. Some examples: "H-Li,C-O,Ne" will return [1, 2, 3, 6, 7, 8, 10] "H-N,8,Na-12" will return [1, 2, 3, 4, 5, 6, 7, 8, 11, 12] ['C', 'Al-15,S', 17, '18'] will return [6, 13, 14, 15, 16, 17, 18] If as_str is True, the list will contain strings of the integers (ie, the first example above will return ['1', '2', '3', '6', '7', '8', '10']
[ "Create", "a", "list", "of", "integers", "given", "a", "string", "or", "list", "of", "compacted", "elements" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/misc.py#L110-L190
230,770
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/misc.py
elements_in_files
def elements_in_files(filelist): '''Get a list of what elements exist in JSON files This works on table, element, and component data files Parameters ---------- filelist : list A list of paths to json files Returns ------- dict Keys are the file path, value is a compacted element string of what elements are in that file ''' ret = {} for fpath in filelist: filedata = fileio.read_json_basis(fpath) els = list(filedata['elements'].keys()) ret[fpath] = misc.compact_elements(els) return ret
python
def elements_in_files(filelist): '''Get a list of what elements exist in JSON files This works on table, element, and component data files Parameters ---------- filelist : list A list of paths to json files Returns ------- dict Keys are the file path, value is a compacted element string of what elements are in that file ''' ret = {} for fpath in filelist: filedata = fileio.read_json_basis(fpath) els = list(filedata['elements'].keys()) ret[fpath] = misc.compact_elements(els) return ret
[ "def", "elements_in_files", "(", "filelist", ")", ":", "ret", "=", "{", "}", "for", "fpath", "in", "filelist", ":", "filedata", "=", "fileio", ".", "read_json_basis", "(", "fpath", ")", "els", "=", "list", "(", "filedata", "[", "'elements'", "]", ".", ...
Get a list of what elements exist in JSON files This works on table, element, and component data files Parameters ---------- filelist : list A list of paths to json files Returns ------- dict Keys are the file path, value is a compacted element string of what elements are in that file
[ "Get", "a", "list", "of", "what", "elements", "exist", "in", "JSON", "files" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/misc.py#L9-L32
230,771
MolSSI-BSE/basis_set_exchange
basis_set_exchange/curate/readers/read.py
_fix_uncontracted
def _fix_uncontracted(basis): ''' Forces the contraction coefficient of uncontracted shells to 1.0 ''' for el in basis['elements'].values(): if 'electron_shells' not in el: continue for sh in el['electron_shells']: if len(sh['coefficients']) == 1 and len(sh['coefficients'][0]) == 1: sh['coefficients'][0][0] = '1.0000000' # Some uncontracted shells don't have a coefficient if len(sh['coefficients']) == 0: sh['coefficients'].append(['1.0000000']) return basis
python
def _fix_uncontracted(basis): ''' Forces the contraction coefficient of uncontracted shells to 1.0 ''' for el in basis['elements'].values(): if 'electron_shells' not in el: continue for sh in el['electron_shells']: if len(sh['coefficients']) == 1 and len(sh['coefficients'][0]) == 1: sh['coefficients'][0][0] = '1.0000000' # Some uncontracted shells don't have a coefficient if len(sh['coefficients']) == 0: sh['coefficients'].append(['1.0000000']) return basis
[ "def", "_fix_uncontracted", "(", "basis", ")", ":", "for", "el", "in", "basis", "[", "'elements'", "]", ".", "values", "(", ")", ":", "if", "'electron_shells'", "not", "in", "el", ":", "continue", "for", "sh", "in", "el", "[", "'electron_shells'", "]", ...
Forces the contraction coefficient of uncontracted shells to 1.0
[ "Forces", "the", "contraction", "coefficient", "of", "uncontracted", "shells", "to", "1", ".", "0" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/readers/read.py#L48-L65
230,772
MolSSI-BSE/basis_set_exchange
basis_set_exchange/converters/bsedebug.py
write_bsedebug
def write_bsedebug(basis): '''Converts a basis set to BSE Debug format ''' s = '' for el, eldata in basis['elements'].items(): s += element_data_str(el, eldata) return s
python
def write_bsedebug(basis): '''Converts a basis set to BSE Debug format ''' s = '' for el, eldata in basis['elements'].items(): s += element_data_str(el, eldata) return s
[ "def", "write_bsedebug", "(", "basis", ")", ":", "s", "=", "''", "for", "el", ",", "eldata", "in", "basis", "[", "'elements'", "]", ".", "items", "(", ")", ":", "s", "+=", "element_data_str", "(", "el", ",", "eldata", ")", "return", "s" ]
Converts a basis set to BSE Debug format
[ "Converts", "a", "basis", "set", "to", "BSE", "Debug", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/converters/bsedebug.py#L8-L16
230,773
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_get_reader_formats
def _bsecurate_cli_get_reader_formats(args): '''Handles the get-file-types subcommand''' all_formats = curate.get_reader_formats() if args.no_description: liststr = all_formats.keys() else: liststr = format_columns(all_formats.items()) return '\n'.join(liststr)
python
def _bsecurate_cli_get_reader_formats(args): '''Handles the get-file-types subcommand''' all_formats = curate.get_reader_formats() if args.no_description: liststr = all_formats.keys() else: liststr = format_columns(all_formats.items()) return '\n'.join(liststr)
[ "def", "_bsecurate_cli_get_reader_formats", "(", "args", ")", ":", "all_formats", "=", "curate", ".", "get_reader_formats", "(", ")", "if", "args", ".", "no_description", ":", "liststr", "=", "all_formats", ".", "keys", "(", ")", "else", ":", "liststr", "=", ...
Handles the get-file-types subcommand
[ "Handles", "the", "get", "-", "file", "-", "types", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L9-L19
230,774
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_elements_in_files
def _bsecurate_cli_elements_in_files(args): '''Handles the elements-in-files subcommand''' data = curate.elements_in_files(args.files) return '\n'.join(format_columns(data.items()))
python
def _bsecurate_cli_elements_in_files(args): '''Handles the elements-in-files subcommand''' data = curate.elements_in_files(args.files) return '\n'.join(format_columns(data.items()))
[ "def", "_bsecurate_cli_elements_in_files", "(", "args", ")", ":", "data", "=", "curate", ".", "elements_in_files", "(", "args", ".", "files", ")", "return", "'\\n'", ".", "join", "(", "format_columns", "(", "data", ".", "items", "(", ")", ")", ")" ]
Handles the elements-in-files subcommand
[ "Handles", "the", "elements", "-", "in", "-", "files", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L22-L25
230,775
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_component_file_refs
def _bsecurate_cli_component_file_refs(args): '''Handles the component-file-refs subcommand''' data = curate.component_file_refs(args.files) s = '' for cfile, cdata in data.items(): s += cfile + '\n' rows = [] for el, refs in cdata: rows.append((' ' + el, ' '.join(refs))) s += '\n'.join(format_columns(rows)) + '\n\n' return s
python
def _bsecurate_cli_component_file_refs(args): '''Handles the component-file-refs subcommand''' data = curate.component_file_refs(args.files) s = '' for cfile, cdata in data.items(): s += cfile + '\n' rows = [] for el, refs in cdata: rows.append((' ' + el, ' '.join(refs))) s += '\n'.join(format_columns(rows)) + '\n\n' return s
[ "def", "_bsecurate_cli_component_file_refs", "(", "args", ")", ":", "data", "=", "curate", ".", "component_file_refs", "(", "args", ".", "files", ")", "s", "=", "''", "for", "cfile", ",", "cdata", "in", "data", ".", "items", "(", ")", ":", "s", "+=", "...
Handles the component-file-refs subcommand
[ "Handles", "the", "component", "-", "file", "-", "refs", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L28-L41
230,776
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_print_component_file
def _bsecurate_cli_print_component_file(args): '''Handles the print-component-file subcommand''' data = fileio.read_json_basis(args.file) return printing.component_basis_str(data, elements=args.elements)
python
def _bsecurate_cli_print_component_file(args): '''Handles the print-component-file subcommand''' data = fileio.read_json_basis(args.file) return printing.component_basis_str(data, elements=args.elements)
[ "def", "_bsecurate_cli_print_component_file", "(", "args", ")", ":", "data", "=", "fileio", ".", "read_json_basis", "(", "args", ".", "file", ")", "return", "printing", ".", "component_basis_str", "(", "data", ",", "elements", "=", "args", ".", "elements", ")"...
Handles the print-component-file subcommand
[ "Handles", "the", "print", "-", "component", "-", "file", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L44-L48
230,777
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_compare_basis_sets
def _bsecurate_cli_compare_basis_sets(args): '''Handles compare-basis-sets subcommand''' ret = curate.compare_basis_sets(args.basis1, args.basis2, args.version1, args.version2, args.uncontract_general, args.data_dir, args.data_dir) if ret: return "No difference found" else: return "DIFFERENCES FOUND. SEE ABOVE"
python
def _bsecurate_cli_compare_basis_sets(args): '''Handles compare-basis-sets subcommand''' ret = curate.compare_basis_sets(args.basis1, args.basis2, args.version1, args.version2, args.uncontract_general, args.data_dir, args.data_dir) if ret: return "No difference found" else: return "DIFFERENCES FOUND. SEE ABOVE"
[ "def", "_bsecurate_cli_compare_basis_sets", "(", "args", ")", ":", "ret", "=", "curate", ".", "compare_basis_sets", "(", "args", ".", "basis1", ",", "args", ".", "basis2", ",", "args", ".", "version1", ",", "args", ".", "version2", ",", "args", ".", "uncon...
Handles compare-basis-sets subcommand
[ "Handles", "compare", "-", "basis", "-", "sets", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L51-L58
230,778
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_compare_basis_files
def _bsecurate_cli_compare_basis_files(args): '''Handles compare-basis-files subcommand''' ret = curate.compare_basis_files(args.file1, args.file2, args.readfmt1, args.readfmt2, args.uncontract_general) if ret: return "No difference found" else: return "DIFFERENCES FOUND. SEE ABOVE"
python
def _bsecurate_cli_compare_basis_files(args): '''Handles compare-basis-files subcommand''' ret = curate.compare_basis_files(args.file1, args.file2, args.readfmt1, args.readfmt2, args.uncontract_general) if ret: return "No difference found" else: return "DIFFERENCES FOUND. SEE ABOVE"
[ "def", "_bsecurate_cli_compare_basis_files", "(", "args", ")", ":", "ret", "=", "curate", ".", "compare_basis_files", "(", "args", ".", "file1", ",", "args", ".", "file2", ",", "args", ".", "readfmt1", ",", "args", ".", "readfmt2", ",", "args", ".", "uncon...
Handles compare-basis-files subcommand
[ "Handles", "compare", "-", "basis", "-", "files", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L61-L68
230,779
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_view_graph
def _bsecurate_cli_view_graph(args): '''Handles the view-graph subcommand''' curate.view_graph(args.basis, args.version, args.data_dir) return ''
python
def _bsecurate_cli_view_graph(args): '''Handles the view-graph subcommand''' curate.view_graph(args.basis, args.version, args.data_dir) return ''
[ "def", "_bsecurate_cli_view_graph", "(", "args", ")", ":", "curate", ".", "view_graph", "(", "args", ".", "basis", ",", "args", ".", "version", ",", "args", ".", "data_dir", ")", "return", "''" ]
Handles the view-graph subcommand
[ "Handles", "the", "view", "-", "graph", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L78-L82
230,780
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
_bsecurate_cli_make_graph_file
def _bsecurate_cli_make_graph_file(args): '''Handles the make-graph-file subcommand''' curate.make_graph_file(args.basis, args.outfile, args.render, args.version, args.data_dir) return ''
python
def _bsecurate_cli_make_graph_file(args): '''Handles the make-graph-file subcommand''' curate.make_graph_file(args.basis, args.outfile, args.render, args.version, args.data_dir) return ''
[ "def", "_bsecurate_cli_make_graph_file", "(", "args", ")", ":", "curate", ".", "make_graph_file", "(", "args", ".", "basis", ",", "args", ".", "outfile", ",", "args", ".", "render", ",", "args", ".", "version", ",", "args", ".", "data_dir", ")", "return", ...
Handles the make-graph-file subcommand
[ "Handles", "the", "make", "-", "graph", "-", "file", "subcommand" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L85-L89
230,781
MolSSI-BSE/basis_set_exchange
basis_set_exchange/lut.py
element_data_from_Z
def element_data_from_Z(Z): '''Obtain elemental data given a Z number An exception is thrown if the Z number is not found ''' # Z may be a str if isinstance(Z, str) and Z.isdecimal(): Z = int(Z) if Z not in _element_Z_map: raise KeyError('No element data for Z = {}'.format(Z)) return _element_Z_map[Z]
python
def element_data_from_Z(Z): '''Obtain elemental data given a Z number An exception is thrown if the Z number is not found ''' # Z may be a str if isinstance(Z, str) and Z.isdecimal(): Z = int(Z) if Z not in _element_Z_map: raise KeyError('No element data for Z = {}'.format(Z)) return _element_Z_map[Z]
[ "def", "element_data_from_Z", "(", "Z", ")", ":", "# Z may be a str", "if", "isinstance", "(", "Z", ",", "str", ")", "and", "Z", ".", "isdecimal", "(", ")", ":", "Z", "=", "int", "(", "Z", ")", "if", "Z", "not", "in", "_element_Z_map", ":", "raise", ...
Obtain elemental data given a Z number An exception is thrown if the Z number is not found
[ "Obtain", "elemental", "data", "given", "a", "Z", "number" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/lut.py#L83-L95
230,782
MolSSI-BSE/basis_set_exchange
basis_set_exchange/lut.py
element_data_from_sym
def element_data_from_sym(sym): '''Obtain elemental data given an elemental symbol The given symbol is not case sensitive An exception is thrown if the symbol is not found ''' sym_lower = sym.lower() if sym_lower not in _element_sym_map: raise KeyError('No element data for symbol \'{}\''.format(sym)) return _element_sym_map[sym_lower]
python
def element_data_from_sym(sym): '''Obtain elemental data given an elemental symbol The given symbol is not case sensitive An exception is thrown if the symbol is not found ''' sym_lower = sym.lower() if sym_lower not in _element_sym_map: raise KeyError('No element data for symbol \'{}\''.format(sym)) return _element_sym_map[sym_lower]
[ "def", "element_data_from_sym", "(", "sym", ")", ":", "sym_lower", "=", "sym", ".", "lower", "(", ")", "if", "sym_lower", "not", "in", "_element_sym_map", ":", "raise", "KeyError", "(", "'No element data for symbol \\'{}\\''", ".", "format", "(", "sym", ")", "...
Obtain elemental data given an elemental symbol The given symbol is not case sensitive An exception is thrown if the symbol is not found
[ "Obtain", "elemental", "data", "given", "an", "elemental", "symbol" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/lut.py#L98-L109
230,783
MolSSI-BSE/basis_set_exchange
basis_set_exchange/lut.py
element_data_from_name
def element_data_from_name(name): '''Obtain elemental data given an elemental name The given name is not case sensitive An exception is thrown if the name is not found ''' name_lower = name.lower() if name_lower not in _element_name_map: raise KeyError('No element data for name \'{}\''.format(name)) return _element_name_map[name_lower]
python
def element_data_from_name(name): '''Obtain elemental data given an elemental name The given name is not case sensitive An exception is thrown if the name is not found ''' name_lower = name.lower() if name_lower not in _element_name_map: raise KeyError('No element data for name \'{}\''.format(name)) return _element_name_map[name_lower]
[ "def", "element_data_from_name", "(", "name", ")", ":", "name_lower", "=", "name", ".", "lower", "(", ")", "if", "name_lower", "not", "in", "_element_name_map", ":", "raise", "KeyError", "(", "'No element data for name \\'{}\\''", ".", "format", "(", "name", ")"...
Obtain elemental data given an elemental name The given name is not case sensitive An exception is thrown if the name is not found
[ "Obtain", "elemental", "data", "given", "an", "elemental", "name" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/lut.py#L112-L123
230,784
MolSSI-BSE/basis_set_exchange
basis_set_exchange/lut.py
element_name_from_Z
def element_name_from_Z(Z, normalize=False): '''Obtain an element's name from its Z number An exception is thrown if the Z number is not found If normalize is True, the first letter will be capitalized ''' r = element_data_from_Z(Z)[2] if normalize: return r.capitalize() else: return r
python
def element_name_from_Z(Z, normalize=False): '''Obtain an element's name from its Z number An exception is thrown if the Z number is not found If normalize is True, the first letter will be capitalized ''' r = element_data_from_Z(Z)[2] if normalize: return r.capitalize() else: return r
[ "def", "element_name_from_Z", "(", "Z", ",", "normalize", "=", "False", ")", ":", "r", "=", "element_data_from_Z", "(", "Z", ")", "[", "2", "]", "if", "normalize", ":", "return", "r", ".", "capitalize", "(", ")", "else", ":", "return", "r" ]
Obtain an element's name from its Z number An exception is thrown if the Z number is not found If normalize is True, the first letter will be capitalized
[ "Obtain", "an", "element", "s", "name", "from", "its", "Z", "number" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/lut.py#L126-L138
230,785
MolSSI-BSE/basis_set_exchange
basis_set_exchange/lut.py
element_sym_from_Z
def element_sym_from_Z(Z, normalize=False): '''Obtain an element's symbol from its Z number An exception is thrown if the Z number is not found If normalize is True, the first letter will be capitalized ''' r = element_data_from_Z(Z)[0] if normalize: return r.capitalize() else: return r
python
def element_sym_from_Z(Z, normalize=False): '''Obtain an element's symbol from its Z number An exception is thrown if the Z number is not found If normalize is True, the first letter will be capitalized ''' r = element_data_from_Z(Z)[0] if normalize: return r.capitalize() else: return r
[ "def", "element_sym_from_Z", "(", "Z", ",", "normalize", "=", "False", ")", ":", "r", "=", "element_data_from_Z", "(", "Z", ")", "[", "0", "]", "if", "normalize", ":", "return", "r", ".", "capitalize", "(", ")", "else", ":", "return", "r" ]
Obtain an element's symbol from its Z number An exception is thrown if the Z number is not found If normalize is True, the first letter will be capitalized
[ "Obtain", "an", "element", "s", "symbol", "from", "its", "Z", "number" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/lut.py#L141-L153
230,786
MolSSI-BSE/basis_set_exchange
basis_set_exchange/refconverters/convert.py
convert_references
def convert_references(ref_data, fmt): ''' Returns the basis set references as a string representing the data in the specified output format ''' # Make fmt case insensitive fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown reference format "{}"'.format(fmt)) # Sort the data for all references for elref in ref_data: for rinfo in elref['reference_info']: rdata = rinfo['reference_data'] rinfo['reference_data'] = [(k, sort.sort_single_reference(v)) for k, v in rdata] # Actually do the conversion ret_str = _converter_map[fmt]['function'](ref_data) return ret_str
python
def convert_references(ref_data, fmt): ''' Returns the basis set references as a string representing the data in the specified output format ''' # Make fmt case insensitive fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown reference format "{}"'.format(fmt)) # Sort the data for all references for elref in ref_data: for rinfo in elref['reference_info']: rdata = rinfo['reference_data'] rinfo['reference_data'] = [(k, sort.sort_single_reference(v)) for k, v in rdata] # Actually do the conversion ret_str = _converter_map[fmt]['function'](ref_data) return ret_str
[ "def", "convert_references", "(", "ref_data", ",", "fmt", ")", ":", "# Make fmt case insensitive", "fmt", "=", "fmt", ".", "lower", "(", ")", "if", "fmt", "not", "in", "_converter_map", ":", "raise", "RuntimeError", "(", "'Unknown reference format \"{}\"'", ".", ...
Returns the basis set references as a string representing the data in the specified output format
[ "Returns", "the", "basis", "set", "references", "as", "a", "string", "representing", "the", "data", "in", "the", "specified", "output", "format" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/refconverters/convert.py#L32-L52
230,787
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
_get_basis_metadata
def _get_basis_metadata(name, data_dir): '''Get metadata for a single basis set If the basis doesn't exist, an exception is raised ''' # Transform the name into an internal representation tr_name = misc.transform_basis_name(name) # Get the metadata for all basis sets metadata = get_metadata(data_dir) if not tr_name in metadata: raise KeyError("Basis set {} does not exist".format(name)) return metadata[tr_name]
python
def _get_basis_metadata(name, data_dir): '''Get metadata for a single basis set If the basis doesn't exist, an exception is raised ''' # Transform the name into an internal representation tr_name = misc.transform_basis_name(name) # Get the metadata for all basis sets metadata = get_metadata(data_dir) if not tr_name in metadata: raise KeyError("Basis set {} does not exist".format(name)) return metadata[tr_name]
[ "def", "_get_basis_metadata", "(", "name", ",", "data_dir", ")", ":", "# Transform the name into an internal representation", "tr_name", "=", "misc", ".", "transform_basis_name", "(", "name", ")", "# Get the metadata for all basis sets", "metadata", "=", "get_metadata", "("...
Get metadata for a single basis set If the basis doesn't exist, an exception is raised
[ "Get", "metadata", "for", "a", "single", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L41-L56
230,788
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
_header_string
def _header_string(basis_dict): '''Creates a header with information about a basis set Information includes description, revision, etc, but not references ''' tw = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 20) header = '-' * 70 + '\n' header += ' Basis Set Exchange\n' header += ' Version ' + version() + '\n' header += ' ' + _main_url + '\n' header += '-' * 70 + '\n' header += ' Basis set: ' + basis_dict['name'] + '\n' header += tw.fill(' Description: ' + basis_dict['description']) + '\n' header += ' Role: ' + basis_dict['role'] + '\n' header += tw.fill(' Version: {} ({})'.format(basis_dict['version'], basis_dict['revision_description'])) + '\n' header += '-' * 70 + '\n' return header
python
def _header_string(basis_dict): '''Creates a header with information about a basis set Information includes description, revision, etc, but not references ''' tw = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 20) header = '-' * 70 + '\n' header += ' Basis Set Exchange\n' header += ' Version ' + version() + '\n' header += ' ' + _main_url + '\n' header += '-' * 70 + '\n' header += ' Basis set: ' + basis_dict['name'] + '\n' header += tw.fill(' Description: ' + basis_dict['description']) + '\n' header += ' Role: ' + basis_dict['role'] + '\n' header += tw.fill(' Version: {} ({})'.format(basis_dict['version'], basis_dict['revision_description'])) + '\n' header += '-' * 70 + '\n' return header
[ "def", "_header_string", "(", "basis_dict", ")", ":", "tw", "=", "textwrap", ".", "TextWrapper", "(", "initial_indent", "=", "''", ",", "subsequent_indent", "=", "' '", "*", "20", ")", "header", "=", "'-'", "*", "70", "+", "'\\n'", "header", "+=", "' Bas...
Creates a header with information about a basis set Information includes description, revision, etc, but not references
[ "Creates", "a", "header", "with", "information", "about", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L59-L79
230,789
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_basis
def get_basis(name, elements=None, version=None, fmt=None, uncontract_general=False, uncontract_spdf=False, uncontract_segmented=False, make_general=False, optimize_general=False, data_dir=None, header=True): '''Obtain a basis set This is the main function for getting basis set information. This function reads in all the basis data and returns it either as a string or as a python dictionary. Parameters ---------- name : str Name of the basis set. This is not case sensitive. elements : str or list List of elements that you want the basis set for. Elements can be specified by Z-number (int or str) or by symbol (str). If this argument is a str (ie, '1-3,7-10'), it is expanded into a list. Z numbers and symbols (case insensitive) can be used interchangeably (see :func:`bse.misc.expand_elements`) If an empty string or list is passed, or if None is passed (the default), all elements for which the basis set is defined are included. version : int or str Obtain a specific version of this basis set. By default, the latest version is returned. fmt: str The desired output format of the basis set. By default, basis set information is returned as a python dictionary. Otherwise, if a format is specified, a string is returned. Use :func:`bse.api.get_formats` to programmatically obtain the available formats. The `fmt` argument is not case sensitive. Available formats are * nwchem * gaussian94 * psi4 * gamess_us * turbomole * json uncontract_general : bool If True, remove general contractions by duplicating the set of primitive exponents with each vector of coefficients. Primitives with zero coefficient are removed, as are duplicate shells. uncontract_spdf : bool If True, remove general contractions with combined angular momentum (sp, spd, etc) by duplicating the set of primitive exponents with each vector of coefficients. Primitives with zero coefficient are removed, as are duplicate shells. uncontract_segmented : bool If True, remove segmented contractions by duplicating each primitive into new shells. Each coefficient is set to 1.0 make_general : bool If True, make the basis set as generally-contracted as possible. There will be one shell per angular momentum (for each element) optimize_general : bool Optimize by removing general contractions that contain uncontracted functions (see :func:`bse.manip.optimize_general`) data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- str or dict The basis set in the desired format. If `fmt` is **None**, this will be a python dictionary. Otherwise, it will be a string. ''' data_dir = fix_data_dir(data_dir) bs_data = _get_basis_metadata(name, data_dir) # If version is not specified, use the latest if version is None: version = bs_data['latest_version'] else: version = str(version) # Version may be an int if not version in bs_data['versions']: raise KeyError("Version {} does not exist for basis {}".format(version, name)) # Compose the entire basis set (all elements) file_relpath = bs_data['versions'][version]['file_relpath'] basis_dict = compose.compose_table_basis(file_relpath, data_dir) # Set the name (from the global metadata) # Only the list of all names will be returned from compose_table_basis basis_dict['name'] = bs_data['display_name'] # Handle optional arguments if elements is not None: # Convert to purely a list of strings that represent integers elements = misc.expand_elements(elements, True) # Did the user pass an empty string or empty list? If so, include # all elements if len(elements) != 0: bs_elements = basis_dict['elements'] # Are elements part of this basis set? for el in elements: if not el in bs_elements: elsym = lut.element_sym_from_Z(el) raise KeyError("Element {} (Z={}) not found in basis {} version {}".format( elsym, el, name, version)) # Set to only the elements we want basis_dict['elements'] = {k: v for k, v in bs_elements.items() if k in elements} # Note that from now on, the pipleline is going to modify basis_dict. That is ok, # since we are returned a unique instance from compose_table_basis needs_pruning = False if optimize_general: basis_dict = manip.optimize_general(basis_dict, False) needs_pruning = True # uncontract_segmented implies uncontract_general if uncontract_segmented: basis_dict = manip.uncontract_segmented(basis_dict, False) needs_pruning = True elif uncontract_general: basis_dict = manip.uncontract_general(basis_dict, False) needs_pruning = True if uncontract_spdf: basis_dict = manip.uncontract_spdf(basis_dict, 0, False) needs_pruning = True if make_general: basis_dict = manip.make_general(basis_dict, False) needs_pruning = True # Remove dead and duplicate shells if needs_pruning: basis_dict = manip.prune_basis(basis_dict, False) # If fmt is not specified, return as a python dict if fmt is None: return basis_dict if header: header_str = _header_string(basis_dict) else: header_str = None return converters.convert_basis(basis_dict, fmt, header_str)
python
def get_basis(name, elements=None, version=None, fmt=None, uncontract_general=False, uncontract_spdf=False, uncontract_segmented=False, make_general=False, optimize_general=False, data_dir=None, header=True): '''Obtain a basis set This is the main function for getting basis set information. This function reads in all the basis data and returns it either as a string or as a python dictionary. Parameters ---------- name : str Name of the basis set. This is not case sensitive. elements : str or list List of elements that you want the basis set for. Elements can be specified by Z-number (int or str) or by symbol (str). If this argument is a str (ie, '1-3,7-10'), it is expanded into a list. Z numbers and symbols (case insensitive) can be used interchangeably (see :func:`bse.misc.expand_elements`) If an empty string or list is passed, or if None is passed (the default), all elements for which the basis set is defined are included. version : int or str Obtain a specific version of this basis set. By default, the latest version is returned. fmt: str The desired output format of the basis set. By default, basis set information is returned as a python dictionary. Otherwise, if a format is specified, a string is returned. Use :func:`bse.api.get_formats` to programmatically obtain the available formats. The `fmt` argument is not case sensitive. Available formats are * nwchem * gaussian94 * psi4 * gamess_us * turbomole * json uncontract_general : bool If True, remove general contractions by duplicating the set of primitive exponents with each vector of coefficients. Primitives with zero coefficient are removed, as are duplicate shells. uncontract_spdf : bool If True, remove general contractions with combined angular momentum (sp, spd, etc) by duplicating the set of primitive exponents with each vector of coefficients. Primitives with zero coefficient are removed, as are duplicate shells. uncontract_segmented : bool If True, remove segmented contractions by duplicating each primitive into new shells. Each coefficient is set to 1.0 make_general : bool If True, make the basis set as generally-contracted as possible. There will be one shell per angular momentum (for each element) optimize_general : bool Optimize by removing general contractions that contain uncontracted functions (see :func:`bse.manip.optimize_general`) data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- str or dict The basis set in the desired format. If `fmt` is **None**, this will be a python dictionary. Otherwise, it will be a string. ''' data_dir = fix_data_dir(data_dir) bs_data = _get_basis_metadata(name, data_dir) # If version is not specified, use the latest if version is None: version = bs_data['latest_version'] else: version = str(version) # Version may be an int if not version in bs_data['versions']: raise KeyError("Version {} does not exist for basis {}".format(version, name)) # Compose the entire basis set (all elements) file_relpath = bs_data['versions'][version]['file_relpath'] basis_dict = compose.compose_table_basis(file_relpath, data_dir) # Set the name (from the global metadata) # Only the list of all names will be returned from compose_table_basis basis_dict['name'] = bs_data['display_name'] # Handle optional arguments if elements is not None: # Convert to purely a list of strings that represent integers elements = misc.expand_elements(elements, True) # Did the user pass an empty string or empty list? If so, include # all elements if len(elements) != 0: bs_elements = basis_dict['elements'] # Are elements part of this basis set? for el in elements: if not el in bs_elements: elsym = lut.element_sym_from_Z(el) raise KeyError("Element {} (Z={}) not found in basis {} version {}".format( elsym, el, name, version)) # Set to only the elements we want basis_dict['elements'] = {k: v for k, v in bs_elements.items() if k in elements} # Note that from now on, the pipleline is going to modify basis_dict. That is ok, # since we are returned a unique instance from compose_table_basis needs_pruning = False if optimize_general: basis_dict = manip.optimize_general(basis_dict, False) needs_pruning = True # uncontract_segmented implies uncontract_general if uncontract_segmented: basis_dict = manip.uncontract_segmented(basis_dict, False) needs_pruning = True elif uncontract_general: basis_dict = manip.uncontract_general(basis_dict, False) needs_pruning = True if uncontract_spdf: basis_dict = manip.uncontract_spdf(basis_dict, 0, False) needs_pruning = True if make_general: basis_dict = manip.make_general(basis_dict, False) needs_pruning = True # Remove dead and duplicate shells if needs_pruning: basis_dict = manip.prune_basis(basis_dict, False) # If fmt is not specified, return as a python dict if fmt is None: return basis_dict if header: header_str = _header_string(basis_dict) else: header_str = None return converters.convert_basis(basis_dict, fmt, header_str)
[ "def", "get_basis", "(", "name", ",", "elements", "=", "None", ",", "version", "=", "None", ",", "fmt", "=", "None", ",", "uncontract_general", "=", "False", ",", "uncontract_spdf", "=", "False", ",", "uncontract_segmented", "=", "False", ",", "make_general"...
Obtain a basis set This is the main function for getting basis set information. This function reads in all the basis data and returns it either as a string or as a python dictionary. Parameters ---------- name : str Name of the basis set. This is not case sensitive. elements : str or list List of elements that you want the basis set for. Elements can be specified by Z-number (int or str) or by symbol (str). If this argument is a str (ie, '1-3,7-10'), it is expanded into a list. Z numbers and symbols (case insensitive) can be used interchangeably (see :func:`bse.misc.expand_elements`) If an empty string or list is passed, or if None is passed (the default), all elements for which the basis set is defined are included. version : int or str Obtain a specific version of this basis set. By default, the latest version is returned. fmt: str The desired output format of the basis set. By default, basis set information is returned as a python dictionary. Otherwise, if a format is specified, a string is returned. Use :func:`bse.api.get_formats` to programmatically obtain the available formats. The `fmt` argument is not case sensitive. Available formats are * nwchem * gaussian94 * psi4 * gamess_us * turbomole * json uncontract_general : bool If True, remove general contractions by duplicating the set of primitive exponents with each vector of coefficients. Primitives with zero coefficient are removed, as are duplicate shells. uncontract_spdf : bool If True, remove general contractions with combined angular momentum (sp, spd, etc) by duplicating the set of primitive exponents with each vector of coefficients. Primitives with zero coefficient are removed, as are duplicate shells. uncontract_segmented : bool If True, remove segmented contractions by duplicating each primitive into new shells. Each coefficient is set to 1.0 make_general : bool If True, make the basis set as generally-contracted as possible. There will be one shell per angular momentum (for each element) optimize_general : bool Optimize by removing general contractions that contain uncontracted functions (see :func:`bse.manip.optimize_general`) data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- str or dict The basis set in the desired format. If `fmt` is **None**, this will be a python dictionary. Otherwise, it will be a string.
[ "Obtain", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L91-L246
230,790
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
lookup_basis_by_role
def lookup_basis_by_role(primary_basis, role, data_dir=None): '''Lookup the name of an auxiliary basis set given a primary basis set and role Parameters ---------- primary_basis : str The primary (orbital) basis set that we want the auxiliary basis set for. This is not case sensitive. role: str Desired role/type of auxiliary basis set. Use :func:`bse.api.get_roles` to programmatically obtain the available formats. The `fmt` argument is not case sensitive. Available roles are * jfit * jkfit * rifit * admmfit data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- str The name of the auxiliary basis set for the given primary basis and role. ''' data_dir = fix_data_dir(data_dir) role = role.lower() if not role in get_roles(): raise RuntimeError("Role {} is not a valid role".format(role)) bs_data = _get_basis_metadata(primary_basis, data_dir) auxdata = bs_data['auxiliaries'] if not role in auxdata: raise RuntimeError("Role {} doesn't exist for {}".format(role, primary_basis)) return auxdata[role]
python
def lookup_basis_by_role(primary_basis, role, data_dir=None): '''Lookup the name of an auxiliary basis set given a primary basis set and role Parameters ---------- primary_basis : str The primary (orbital) basis set that we want the auxiliary basis set for. This is not case sensitive. role: str Desired role/type of auxiliary basis set. Use :func:`bse.api.get_roles` to programmatically obtain the available formats. The `fmt` argument is not case sensitive. Available roles are * jfit * jkfit * rifit * admmfit data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- str The name of the auxiliary basis set for the given primary basis and role. ''' data_dir = fix_data_dir(data_dir) role = role.lower() if not role in get_roles(): raise RuntimeError("Role {} is not a valid role".format(role)) bs_data = _get_basis_metadata(primary_basis, data_dir) auxdata = bs_data['auxiliaries'] if not role in auxdata: raise RuntimeError("Role {} doesn't exist for {}".format(role, primary_basis)) return auxdata[role]
[ "def", "lookup_basis_by_role", "(", "primary_basis", ",", "role", ",", "data_dir", "=", "None", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "role", "=", "role", ".", "lower", "(", ")", "if", "not", "role", "in", "get_roles", "(", ")"...
Lookup the name of an auxiliary basis set given a primary basis set and role Parameters ---------- primary_basis : str The primary (orbital) basis set that we want the auxiliary basis set for. This is not case sensitive. role: str Desired role/type of auxiliary basis set. Use :func:`bse.api.get_roles` to programmatically obtain the available formats. The `fmt` argument is not case sensitive. Available roles are * jfit * jkfit * rifit * admmfit data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- str The name of the auxiliary basis set for the given primary basis and role.
[ "Lookup", "the", "name", "of", "an", "auxiliary", "basis", "set", "given", "a", "primary", "basis", "set", "and", "role" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L249-L293
230,791
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_metadata
def get_metadata(data_dir=None): '''Obtain the metadata for all basis sets The metadata includes information such as the display name of the basis set, its versions, and what elements are included in the basis set The data is read from the METADATA.json file in the `data_dir` directory. Parameters ---------- data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. ''' data_dir = fix_data_dir(data_dir) metadata_file = os.path.join(data_dir, "METADATA.json") return fileio.read_metadata(metadata_file)
python
def get_metadata(data_dir=None): '''Obtain the metadata for all basis sets The metadata includes information such as the display name of the basis set, its versions, and what elements are included in the basis set The data is read from the METADATA.json file in the `data_dir` directory. Parameters ---------- data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. ''' data_dir = fix_data_dir(data_dir) metadata_file = os.path.join(data_dir, "METADATA.json") return fileio.read_metadata(metadata_file)
[ "def", "get_metadata", "(", "data_dir", "=", "None", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "metadata_file", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "\"METADATA.json\"", ")", "return", "fileio", ".", "read_metadat...
Obtain the metadata for all basis sets The metadata includes information such as the display name of the basis set, its versions, and what elements are included in the basis set The data is read from the METADATA.json file in the `data_dir` directory. Parameters ---------- data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project.
[ "Obtain", "the", "metadata", "for", "all", "basis", "sets" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L297-L314
230,792
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_reference_data
def get_reference_data(data_dir=None): '''Obtain information for all stored references This is a nested dictionary with all the data for all the references The reference data is read from the REFERENCES.json file in the given `data_dir` directory. ''' data_dir = fix_data_dir(data_dir) reffile_path = os.path.join(data_dir, 'REFERENCES.json') return fileio.read_references(reffile_path)
python
def get_reference_data(data_dir=None): '''Obtain information for all stored references This is a nested dictionary with all the data for all the references The reference data is read from the REFERENCES.json file in the given `data_dir` directory. ''' data_dir = fix_data_dir(data_dir) reffile_path = os.path.join(data_dir, 'REFERENCES.json') return fileio.read_references(reffile_path)
[ "def", "get_reference_data", "(", "data_dir", "=", "None", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "reffile_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'REFERENCES.json'", ")", "return", "fileio", ".", "read_re...
Obtain information for all stored references This is a nested dictionary with all the data for all the references The reference data is read from the REFERENCES.json file in the given `data_dir` directory.
[ "Obtain", "information", "for", "all", "stored", "references" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L318-L330
230,793
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_basis_family
def get_basis_family(basis_name, data_dir=None): '''Lookup a family by a basis set name ''' data_dir = fix_data_dir(data_dir) bs_data = _get_basis_metadata(basis_name, data_dir) return bs_data['family']
python
def get_basis_family(basis_name, data_dir=None): '''Lookup a family by a basis set name ''' data_dir = fix_data_dir(data_dir) bs_data = _get_basis_metadata(basis_name, data_dir) return bs_data['family']
[ "def", "get_basis_family", "(", "basis_name", ",", "data_dir", "=", "None", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "bs_data", "=", "_get_basis_metadata", "(", "basis_name", ",", "data_dir", ")", "return", "bs_data", "[", "'family'", "...
Lookup a family by a basis set name
[ "Lookup", "a", "family", "by", "a", "basis", "set", "name" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L398-L404
230,794
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_families
def get_families(data_dir=None): '''Return a list of all basis set families''' data_dir = fix_data_dir(data_dir) metadata = get_metadata(data_dir) families = set() for v in metadata.values(): families.add(v['family']) return sorted(list(families))
python
def get_families(data_dir=None): '''Return a list of all basis set families''' data_dir = fix_data_dir(data_dir) metadata = get_metadata(data_dir) families = set() for v in metadata.values(): families.add(v['family']) return sorted(list(families))
[ "def", "get_families", "(", "data_dir", "=", "None", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "metadata", "=", "get_metadata", "(", "data_dir", ")", "families", "=", "set", "(", ")", "for", "v", "in", "metadata", ".", "values", "(...
Return a list of all basis set families
[ "Return", "a", "list", "of", "all", "basis", "set", "families" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L408-L417
230,795
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
filter_basis_sets
def filter_basis_sets(substr=None, family=None, role=None, data_dir=None): '''Filter basis sets by some criteria All parameters are ANDed together and are not case sensitive. Parameters ---------- substr : str Substring to search for in the basis set name family : str Family the basis set belongs to role : str Role of the basis set data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- dict Basis set metadata that matches the search criteria ''' data_dir = fix_data_dir(data_dir) metadata = get_metadata(data_dir) # family and role are required to be lowercase (via schema and validation functions) if family: family = family.lower() if not family in get_families(data_dir): raise RuntimeError("Family '{}' is not a valid family".format(family)) metadata = {k: v for k, v in metadata.items() if v['family'] == family} if role: role = role.lower() if not role in get_roles(): raise RuntimeError("Role '{}' is not a valid role".format(role)) metadata = {k: v for k, v in metadata.items() if v['role'] == role} if substr: substr = substr.lower() metadata = {k: v for k, v in metadata.items() if substr in k or substr in v['display_name']} return metadata
python
def filter_basis_sets(substr=None, family=None, role=None, data_dir=None): '''Filter basis sets by some criteria All parameters are ANDed together and are not case sensitive. Parameters ---------- substr : str Substring to search for in the basis set name family : str Family the basis set belongs to role : str Role of the basis set data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- dict Basis set metadata that matches the search criteria ''' data_dir = fix_data_dir(data_dir) metadata = get_metadata(data_dir) # family and role are required to be lowercase (via schema and validation functions) if family: family = family.lower() if not family in get_families(data_dir): raise RuntimeError("Family '{}' is not a valid family".format(family)) metadata = {k: v for k, v in metadata.items() if v['family'] == family} if role: role = role.lower() if not role in get_roles(): raise RuntimeError("Role '{}' is not a valid role".format(role)) metadata = {k: v for k, v in metadata.items() if v['role'] == role} if substr: substr = substr.lower() metadata = {k: v for k, v in metadata.items() if substr in k or substr in v['display_name']} return metadata
[ "def", "filter_basis_sets", "(", "substr", "=", "None", ",", "family", "=", "None", ",", "role", "=", "None", ",", "data_dir", "=", "None", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "metadata", "=", "get_metadata", "(", "data_dir", ...
Filter basis sets by some criteria All parameters are ANDed together and are not case sensitive. Parameters ---------- substr : str Substring to search for in the basis set name family : str Family the basis set belongs to role : str Role of the basis set data_dir : str Data directory with all the basis set information. By default, it is in the 'data' subdirectory of this project. Returns ------- dict Basis set metadata that matches the search criteria
[ "Filter", "basis", "sets", "by", "some", "criteria" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L420-L462
230,796
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
_family_notes_path
def _family_notes_path(family, data_dir): '''Form a path to the notes for a family''' data_dir = fix_data_dir(data_dir) family = family.lower() if not family in get_families(data_dir): raise RuntimeError("Family '{}' does not exist".format(family)) file_name = 'NOTES.' + family.lower() file_path = os.path.join(data_dir, file_name) return file_path
python
def _family_notes_path(family, data_dir): '''Form a path to the notes for a family''' data_dir = fix_data_dir(data_dir) family = family.lower() if not family in get_families(data_dir): raise RuntimeError("Family '{}' does not exist".format(family)) file_name = 'NOTES.' + family.lower() file_path = os.path.join(data_dir, file_name) return file_path
[ "def", "_family_notes_path", "(", "family", ",", "data_dir", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "family", "=", "family", ".", "lower", "(", ")", "if", "not", "family", "in", "get_families", "(", "data_dir", ")", ":", "raise", ...
Form a path to the notes for a family
[ "Form", "a", "path", "to", "the", "notes", "for", "a", "family" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L466-L477
230,797
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
_basis_notes_path
def _basis_notes_path(name, data_dir): '''Form a path to the notes for a basis set''' data_dir = fix_data_dir(data_dir) bs_data = _get_basis_metadata(name, data_dir) # the notes file is the same as the base file name, with a .notes extension filebase = bs_data['basename'] file_path = os.path.join(data_dir, filebase + '.notes') return file_path
python
def _basis_notes_path(name, data_dir): '''Form a path to the notes for a basis set''' data_dir = fix_data_dir(data_dir) bs_data = _get_basis_metadata(name, data_dir) # the notes file is the same as the base file name, with a .notes extension filebase = bs_data['basename'] file_path = os.path.join(data_dir, filebase + '.notes') return file_path
[ "def", "_basis_notes_path", "(", "name", ",", "data_dir", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "bs_data", "=", "_get_basis_metadata", "(", "name", ",", "data_dir", ")", "# the notes file is the same as the base file name, with a .notes extensio...
Form a path to the notes for a basis set
[ "Form", "a", "path", "to", "the", "notes", "for", "a", "basis", "set" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L481-L490
230,798
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
get_family_notes
def get_family_notes(family, data_dir=None): '''Return a string representing the notes about a basis set family If the notes are not found, an empty string is returned ''' file_path = _family_notes_path(family, data_dir) notes_str = fileio.read_notes_file(file_path) if notes_str is None: notes_str = "" ref_data = get_reference_data(data_dir) return notes.process_notes(notes_str, ref_data)
python
def get_family_notes(family, data_dir=None): '''Return a string representing the notes about a basis set family If the notes are not found, an empty string is returned ''' file_path = _family_notes_path(family, data_dir) notes_str = fileio.read_notes_file(file_path) if notes_str is None: notes_str = "" ref_data = get_reference_data(data_dir) return notes.process_notes(notes_str, ref_data)
[ "def", "get_family_notes", "(", "family", ",", "data_dir", "=", "None", ")", ":", "file_path", "=", "_family_notes_path", "(", "family", ",", "data_dir", ")", "notes_str", "=", "fileio", ".", "read_notes_file", "(", "file_path", ")", "if", "notes_str", "is", ...
Return a string representing the notes about a basis set family If the notes are not found, an empty string is returned
[ "Return", "a", "string", "representing", "the", "notes", "about", "a", "basis", "set", "family" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L494-L507
230,799
MolSSI-BSE/basis_set_exchange
basis_set_exchange/api.py
has_family_notes
def has_family_notes(family, data_dir=None): '''Check if notes exist for a given family Returns True if they exist, false otherwise ''' file_path = _family_notes_path(family, data_dir) return os.path.isfile(file_path)
python
def has_family_notes(family, data_dir=None): '''Check if notes exist for a given family Returns True if they exist, false otherwise ''' file_path = _family_notes_path(family, data_dir) return os.path.isfile(file_path)
[ "def", "has_family_notes", "(", "family", ",", "data_dir", "=", "None", ")", ":", "file_path", "=", "_family_notes_path", "(", "family", ",", "data_dir", ")", "return", "os", ".", "path", ".", "isfile", "(", "file_path", ")" ]
Check if notes exist for a given family Returns True if they exist, false otherwise
[ "Check", "if", "notes", "exist", "for", "a", "given", "family" ]
e79110aaeb65f392ed5032420322dee3336948f7
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L511-L518