idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
26,300
def create_client ( self ) -> "google.cloud.storage.Client" : # Client should be imported here because grpc starts threads during import # and if you call fork after that, a child process will be hang during exit from google . cloud . storage import Client if self . credentials : client = Client . from_service_account_json ( self . credentials ) else : client = Client ( ) return client
Construct GCS API client .
86
6
26,301
def connect ( self ) -> "google.cloud.storage.Bucket" : log = self . _log log . info ( "Connecting to the bucket..." ) client = self . create_client ( ) return client . lookup_bucket ( self . bucket_name )
Connect to the assigned bucket .
58
6
26,302
def reset ( self , force ) : client = self . create_client ( ) bucket = client . lookup_bucket ( self . bucket_name ) if bucket is not None : if not force : self . _log . error ( "Bucket already exists, aborting." ) raise ExistingBackendError self . _log . info ( "Bucket already exists, deleting all content." ) for blob in bucket . list_blobs ( ) : self . _log . info ( "Deleting %s ..." % blob . name ) bucket . delete_blob ( blob . name ) else : client . create_bucket ( self . bucket_name )
Connect to the assigned bucket or create if needed . Clear all the blobs inside .
140
17
26,303
def upload_model ( self , path : str , meta : dict , force : bool ) : bucket = self . connect ( ) if bucket is None : raise BackendRequiredError blob = bucket . blob ( "models/%s/%s.asdf" % ( meta [ "model" ] , meta [ "uuid" ] ) ) if blob . exists ( ) and not force : self . _log . error ( "Model %s already exists, aborted." , meta [ "uuid" ] ) raise ModelAlreadyExistsError self . _log . info ( "Uploading %s from %s..." , meta [ "model" ] , os . path . abspath ( path ) ) def tracker ( data ) : return self . _Tracker ( data , self . _log ) make_transport = blob . _make_transport def make_transport_with_progress ( client ) : transport = make_transport ( client ) request = transport . request def request_with_progress ( method , url , data = None , headers = None , * * kwargs ) : return request ( method , url , data = tracker ( data ) , headers = headers , * * kwargs ) transport . request = request_with_progress return transport blob . _make_transport = make_transport_with_progress with open ( path , "rb" ) as fin : blob . upload_from_file ( fin , content_type = "application/x-yaml" ) blob . make_public ( ) return blob . public_url
Put the model to GCS .
331
7
26,304
def fetch_model ( self , source : str , file : Union [ str , BinaryIO ] , chunk_size : int = DEFAULT_DOWNLOAD_CHUNK_SIZE ) -> None : download_http ( source , file , self . _log , chunk_size )
Download the model from GCS .
59
7
26,305
def delete_model ( self , meta : dict ) : bucket = self . connect ( ) if bucket is None : raise BackendRequiredError blob_name = "models/%s/%s.asdf" % ( meta [ "model" ] , meta [ "uuid" ] ) self . _log . info ( blob_name ) try : self . _log . info ( "Deleting model ..." ) bucket . delete_blob ( blob_name ) except NotFound : self . _log . warning ( "Model %s already deleted." , meta [ "uuid" ] )
Delete the model from GCS .
127
7
26,306
def download_http ( source : str , file : Union [ str , BinaryIO ] , log : logging . Logger , chunk_size : int = DEFAULT_DOWNLOAD_CHUNK_SIZE ) -> None : log . info ( "Fetching %s..." , source ) r = requests . get ( source , stream = True ) if r . status_code != 200 : log . error ( "An error occurred while fetching the model, with code %s" % r . status_code ) raise ValueError if isinstance ( file , str ) : os . makedirs ( os . path . dirname ( file ) , exist_ok = True ) f = open ( file , "wb" ) else : f = file try : total_length = int ( r . headers . get ( "content-length" ) ) num_chunks = math . ceil ( total_length / chunk_size ) if num_chunks == 1 : f . write ( r . content ) else : for chunk in progress_bar ( r . iter_content ( chunk_size = chunk_size ) , log , expected_size = num_chunks ) : if chunk : f . write ( chunk ) finally : if isinstance ( file , str ) : f . close ( )
Download a file from an HTTP source .
273
8
26,307
def upload_model ( self , path : str , meta : dict , force : bool ) -> str : raise NotImplementedError
Put the given file to the remote storage .
28
9
26,308
def setup ( level : Union [ str , int ] , structured : bool , config_path : str = None ) : global logs_are_structured logs_are_structured = structured if not isinstance ( level , int ) : level = logging . _nameToLevel [ level ] def ensure_utf8_stream ( stream ) : if not isinstance ( stream , io . StringIO ) and hasattr ( stream , "buffer" ) : stream = codecs . getwriter ( "utf-8" ) ( stream . buffer ) stream . encoding = "utf-8" return stream sys . stdout , sys . stderr = ( ensure_utf8_stream ( s ) for s in ( sys . stdout , sys . stderr ) ) # basicConfig is only called to make sure there is at least one handler for the root logger. # All the output level setting is down right afterwards. logging . basicConfig ( ) logging . setLogRecordFactory ( NumpyLogRecord ) if config_path is not None and os . path . isfile ( config_path ) : with open ( config_path ) as fh : config = yaml . safe_load ( fh ) for key , val in config . items ( ) : logging . getLogger ( key ) . setLevel ( logging . _nameToLevel . get ( val , level ) ) root = logging . getLogger ( ) root . setLevel ( level ) if not structured : if not sys . stdin . closed and sys . stdout . isatty ( ) : handler = root . handlers [ 0 ] handler . setFormatter ( AwesomeFormatter ( ) ) else : root . handlers [ 0 ] = StructuredHandler ( level )
Make stdout and stderr unicode friendly in case of misconfigured \ environments initializes the logging structured logging and \ enables colored logs if it is appropriate .
366
34
26,309
def set_context ( context ) : try : handler = logging . getLogger ( ) . handlers [ 0 ] except IndexError : # logging is not initialized return if not isinstance ( handler , StructuredHandler ) : return handler . acquire ( ) try : handler . local . context = context finally : handler . release ( )
Assign the logging context - an abstract object - to the current thread .
68
15
26,310
def add_logging_args ( parser : argparse . ArgumentParser , patch : bool = True , erase_args : bool = True ) -> None : parser . add_argument ( "--log-level" , default = "INFO" , choices = logging . _nameToLevel , help = "Logging verbosity." ) parser . add_argument ( "--log-structured" , action = "store_true" , help = "Enable structured logging (JSON record per line)." ) parser . add_argument ( "--log-config" , help = "Path to the file which sets individual log levels of domains." ) # monkey-patch parse_args() # custom actions do not work, unfortunately, because they are not invoked if # the corresponding --flags are not specified def _patched_parse_args ( args = None , namespace = None ) -> argparse . Namespace : args = parser . _original_parse_args ( args , namespace ) setup ( args . log_level , args . log_structured , args . log_config ) if erase_args : for log_arg in ( "log_level" , "log_structured" , "log_config" ) : delattr ( args , log_arg ) return args if patch and not hasattr ( parser , "_original_parse_args" ) : parser . _original_parse_args = parser . parse_args parser . parse_args = _patched_parse_args
Add command line flags specific to logging .
312
8
26,311
def array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
Format numpy array as a string .
80
8
26,312
def getMessage ( self ) : if isinstance ( self . msg , numpy . ndarray ) : msg = self . array2string ( self . msg ) else : msg = str ( self . msg ) if self . args : a2s = self . array2string if isinstance ( self . args , Dict ) : args = { k : ( a2s ( v ) if isinstance ( v , numpy . ndarray ) else v ) for ( k , v ) in self . args . items ( ) } elif isinstance ( self . args , Sequence ) : args = tuple ( ( a2s ( a ) if isinstance ( a , numpy . ndarray ) else a ) for a in self . args ) else : raise TypeError ( "Unexpected input '%s' with type '%s'" % ( self . args , type ( self . args ) ) ) msg = msg % args return msg
Return the message for this LogRecord .
201
8
26,313
def formatMessage ( self , record : logging . LogRecord ) -> str : level_color = "0" text_color = "0" fmt = "" if record . levelno <= logging . DEBUG : fmt = "\033[0;37m" + logging . BASIC_FORMAT + "\033[0m" elif record . levelno <= logging . INFO : level_color = "1;36" lmsg = record . message . lower ( ) if self . GREEN_RE . search ( lmsg ) : text_color = "1;32" elif record . levelno <= logging . WARNING : level_color = "1;33" elif record . levelno <= logging . CRITICAL : level_color = "1;31" if not fmt : fmt = "\033[" + level_color + "m%(levelname)s\033[0m:%(rthread)s:%(name)s:\033[" + text_color + "m%(message)s\033[0m" fmt = _fest + fmt record . rthread = reduce_thread_id ( record . thread ) return fmt % record . __dict__
Convert the already filled log record to a string .
252
11
26,314
def emit ( self , record : logging . LogRecord ) : created = datetime . datetime . fromtimestamp ( record . created , timezone ) obj = { "level" : record . levelname . lower ( ) , "msg" : record . msg % record . args , "source" : "%s:%d" % ( record . filename , record . lineno ) , "time" : format_datetime ( created ) , "thread" : reduce_thread_id ( record . thread ) , } if record . exc_info is not None : obj [ "error" ] = traceback . format_exception ( * record . exc_info ) [ 1 : ] try : obj [ "context" ] = self . local . context except AttributeError : pass json . dump ( obj , sys . stdout , sort_keys = True ) sys . stdout . write ( "\n" ) sys . stdout . flush ( )
Print the log record formatted as JSON to stdout .
202
11
26,315
def register_model ( cls : Type [ Model ] ) : if not issubclass ( cls , Model ) : raise TypeError ( "model bust be a subclass of Model" ) if issubclass ( cls , GenericModel ) : raise TypeError ( "model must not be a subclass of GenericModel" ) __models__ . add ( cls ) return cls
Include the given model class into the registry .
80
10
26,316
def fetch ( self ) : os . makedirs ( os . path . dirname ( self . cached_repo ) , exist_ok = True ) if not os . path . exists ( self . cached_repo ) : self . _log . warning ( "Index not found, caching %s in %s" , self . repo , self . cached_repo ) git . clone ( self . remote_url , self . cached_repo , checkout = True ) else : self . _log . debug ( "Index is cached" ) if self . _are_local_and_remote_heads_different ( ) : self . _log . info ( "Cached index is not up to date, pulling %s" , self . repo ) git . pull ( self . cached_repo , self . remote_url ) with open ( os . path . join ( self . cached_repo , self . INDEX_FILE ) , encoding = "utf-8" ) as _in : self . contents = json . load ( _in )
Load from the associated Git repository .
224
7
26,317
def update_readme ( self , template_readme : Template ) : readme = os . path . join ( self . cached_repo , "README.md" ) if os . path . exists ( readme ) : os . remove ( readme ) links = { model_type : { } for model_type in self . models . keys ( ) } for model_type , model_uuids in self . models . items ( ) : for model_uuid in model_uuids : links [ model_type ] [ model_uuid ] = os . path . join ( "/" , model_type , "%s.md" % model_uuid ) with open ( readme , "w" ) as fout : fout . write ( template_readme . render ( models = self . models , meta = self . meta , links = links ) ) git . add ( self . cached_repo , [ readme ] ) self . _log . info ( "Updated %s" , readme )
Generate the new README file locally .
220
9
26,318
def reset ( self ) : paths = [ ] for filename in os . listdir ( self . cached_repo ) : if filename . startswith ( ".git" ) : continue path = os . path . join ( self . cached_repo , filename ) if os . path . isfile ( path ) : paths . append ( path ) elif os . path . isdir ( path ) : for model in os . listdir ( path ) : paths . append ( os . path . join ( path , model ) ) git . remove ( self . cached_repo , paths ) self . contents = { "models" : { } , "meta" : { } }
Initialize the remote Git repository .
143
7
26,319
def upload ( self , cmd : str , meta : dict ) : index = os . path . join ( self . cached_repo , self . INDEX_FILE ) if os . path . exists ( index ) : os . remove ( index ) self . _log . info ( "Writing the new index.json ..." ) with open ( index , "w" ) as _out : json . dump ( self . contents , _out ) git . add ( self . cached_repo , [ index ] ) message = self . COMMIT_MESSAGES [ cmd ] . format ( * * meta ) if self . signoff : global_conf_path = os . path . expanduser ( "~/.gitconfig" ) if os . path . exists ( global_conf_path ) : with open ( global_conf_path , "br" ) as _in : conf = ConfigFile . from_file ( _in ) try : name = conf . get ( b"user" , b"name" ) . decode ( ) email = conf . get ( b"user" , b"email" ) . decode ( ) message += self . DCO_MESSAGE . format ( name = name , email = email ) except KeyError : self . _log . warning ( "Did not find name or email in %s, committing without DCO." , global_conf_path ) else : self . _log . warning ( "Global git configuration file %s does not exist, " "committing without DCO." , global_conf_path ) else : self . _log . info ( "Committing the index without DCO." ) git . commit ( self . cached_repo , message = message ) self . _log . info ( "Pushing the updated index ..." ) # TODO: change when https://github.com/dulwich/dulwich/issues/631 gets addressed git . push ( self . cached_repo , self . remote_url , b"master" ) if self . _are_local_and_remote_heads_different ( ) : self . _log . error ( "Push has failed" ) raise ValueError ( "Push has failed" )
Push the current state of the registry to Git .
468
10
26,320
def load_template ( self , template : str ) -> Template : env = dict ( trim_blocks = True , lstrip_blocks = True , keep_trailing_newline = False ) jinja2_ext = ".jinja2" if not template . endswith ( jinja2_ext ) : self . _log . error ( "Template file name must end with %s" % jinja2_ext ) raise ValueError if not template [ : - len ( jinja2_ext ) ] . endswith ( ".md" ) : self . _log . error ( "Template file should be a Markdown file." ) raise ValueError if not os . path . isabs ( template ) : template = os . path . join ( os . path . dirname ( __file__ ) , template ) with open ( template , encoding = "utf-8" ) as fin : template_obj = Template ( fin . read ( ) , * * env ) template_obj . filename = template self . _log . info ( "Loaded %s" , template ) return template_obj
Load a Jinja2 template from the source directory .
237
11
26,321
def progress_bar ( enumerable , logger , * * kwargs ) : if not logger . isEnabledFor ( logging . INFO ) or sys . stdin . closed or not sys . stdin . isatty ( ) : return enumerable return progress . bar ( enumerable , * * kwargs )
Show the progress bar in the terminal if the logging level matches and we are interactive .
65
17
26,322
def collect_environment ( no_cache : bool = False ) -> dict : global _env if _env is None or no_cache : _env = collect_environment_without_packages ( ) _env [ "packages" ] = collect_loaded_packages ( ) return _env
Return the version of the Python executable the versions of the currently loaded packages \ and the running platform .
59
20
26,323
def collect_loaded_packages ( ) -> List [ Tuple [ str , str ] ] : dists = get_installed_distributions ( ) get_dist_files = DistFilesFinder ( ) file_table = { } for dist in dists : for file in get_dist_files ( dist ) : file_table [ file ] = dist used_dists = set ( ) # we greedily load all values to a list to avoid weird # "dictionary changed size during iteration" errors for module in list ( sys . modules . values ( ) ) : try : dist = file_table [ module . __file__ ] except ( AttributeError , KeyError ) : continue used_dists . add ( dist ) return sorted ( ( dist . project_name , dist . version ) for dist in used_dists )
Return the currently loaded package names and their versions .
177
10
26,324
def setup_blueprint ( self ) : # Register endpoints. self . blueprint . add_url_rule ( "/" , "status" , self . status ) self . blueprint . add_url_rule ( "/healthy" , "health" , self . healthy ) self . blueprint . add_url_rule ( "/ready" , "ready" , self . ready ) self . blueprint . add_url_rule ( "/threads" , "threads" , self . threads_bt )
Initialize the blueprint .
105
5
26,325
def _add_routes ( self ) : if self . app . has_static_folder : self . add_url_rule ( "/favicon.ico" , "favicon" , self . favicon ) self . add_url_rule ( "/" , "__default_redirect_to_status" , self . redirect_to_status )
Add some nice default routes .
80
6
26,326
def get_argparser ( parser = None ) : parser = parser or argparse . ArgumentParser ( ) parser . add_argument ( "--host" , default = "0.0.0.0" , help = "Host listen address" ) parser . add_argument ( "--port" , "-p" , default = 9050 , help = "Listen port" , type = int ) parser . add_argument ( "--debug" , "-d" , default = False , action = "store_true" , help = "Enable debug mode" , ) parser . add_argument ( "--log-level" , "-l" , default = "INFO" , help = "Log Level, empty string to disable." , ) parser . add_argument ( "--twisted" , default = False , action = "store_true" , help = "Use twisted to server requests." , ) parser . add_argument ( "--gunicorn" , default = False , action = "store_true" , help = "Use gunicorn to server requests." , ) parser . add_argument ( "--threads" , default = None , help = "Number of threads to use." , type = int ) parser . add_argument ( "--disable-embedded-logging" , default = False , action = "store_true" , help = "Disable embedded logging configuration" ) return parser
Customize a parser to get the correct options .
299
10
26,327
def setup_prometheus ( self , registry = None ) : kwargs = { } if registry : kwargs [ "registry" ] = registry self . metrics = PrometheusMetrics ( self . app , * * kwargs ) try : version = pkg_resources . require ( self . app . name ) [ 0 ] . version except pkg_resources . DistributionNotFound : version = "unknown" self . metrics . info ( "app_info" , "Application info" , version = version , appname = self . app . name ) self . app . logger . info ( "Prometheus is enabled." )
Setup Prometheus .
133
3
26,328
def add_url_rule ( self , route , endpoint , handler ) : self . app . add_url_rule ( route , endpoint , handler )
Add a new url route .
32
6
26,329
def healthy ( self ) : try : if self . is_healthy ( ) : return "OK" , 200 else : return "FAIL" , 500 except Exception as e : self . app . logger . exception ( e ) return str ( e ) , 500
Return 200 is healthy else 500 .
54
7
26,330
def ready ( self ) : try : if self . is_ready ( ) : return "OK" , 200 else : return "FAIL" , 500 except Exception as e : self . app . logger . exception ( ) return str ( e ) , 500
Return 200 is ready else 500 .
53
7
26,331
def threads_bt ( self ) : import threading import traceback threads = { } for thread in threading . enumerate ( ) : frames = sys . _current_frames ( ) . get ( thread . ident ) if frames : stack = traceback . format_stack ( frames ) else : stack = [ ] threads [ thread ] = "" . join ( stack ) return flask . render_template ( "gourde/threads.html" , threads = threads )
Display thread backtraces .
99
6
26,332
def run_with_werkzeug ( self , * * options ) : threaded = self . threads is not None and ( self . threads > 0 ) self . app . run ( host = self . host , port = self . port , debug = self . debug , threaded = threaded , * * options )
Run with werkzeug simple wsgi container .
65
12
26,333
def run_with_twisted ( self , * * options ) : from twisted . internet import reactor from twisted . python import log import flask_twisted twisted = flask_twisted . Twisted ( self . app ) if self . threads : reactor . suggestThreadPoolSize ( self . threads ) if self . log_level : log . startLogging ( sys . stderr ) twisted . run ( host = self . host , port = self . port , debug = self . debug , * * options )
Run with twisted .
106
4
26,334
def run_with_gunicorn ( self , * * options ) : import gunicorn . app . base from gunicorn . six import iteritems import multiprocessing class GourdeApplication ( gunicorn . app . base . BaseApplication ) : def __init__ ( self , app , options = None ) : self . options = options or { } self . application = app super ( GourdeApplication , self ) . __init__ ( ) def load_config ( self ) : config = dict ( [ ( key , value ) for key , value in iteritems ( self . options ) if key in self . cfg . settings and value is not None ] ) for key , value in iteritems ( config ) : self . cfg . set ( key . lower ( ) , value ) def load ( self ) : return self . application options = { 'bind' : '%s:%s' % ( self . host , self . port ) , 'workers' : self . threads or ( ( multiprocessing . cpu_count ( ) * 2 ) + 1 ) , 'debug' : self . debug , * * options , } GourdeApplication ( self . app , options ) . run ( )
Run with gunicorn .
260
6
26,335
def initialize_api ( flask_app ) : if not flask_restplus : return api = flask_restplus . Api ( version = "1.0" , title = "My Example API" ) api . add_resource ( HelloWorld , "/hello" ) blueprint = flask . Blueprint ( "api" , __name__ , url_prefix = "/api" ) api . init_app ( blueprint ) flask_app . register_blueprint ( blueprint )
Initialize an API .
98
5
26,336
def initialize_app ( flask_app , args ) : # Setup gourde with the args. gourde . setup ( args ) # Register a custom health check. gourde . is_healthy = is_healthy # Add an optional API initialize_api ( flask_app )
Initialize the App .
60
5
26,337
def quote ( text , limit = 1000 ) : lines = text . split ( '\n' ) found = _internal . find_quote_position ( lines , _patterns . MAX_WRAP_LINES , limit ) if found != None : return [ ( True , '\n' . join ( lines [ : found + 1 ] ) ) , ( False , '\n' . join ( lines [ found + 1 : ] ) ) ] return [ ( True , text ) ]
Takes a plain text message as an argument returns a list of tuples . The first argument of the tuple denotes whether the text should be expanded by default . The second argument is the unmodified corresponding text .
103
42
26,338
def extract_headers ( lines , max_wrap_lines ) : hdrs = { } header_name = None # Track overlong headers that extend over multiple lines extend_lines = 0 lines_processed = 0 for n , line in enumerate ( lines ) : if not line . strip ( ) : header_name = None continue match = HEADER_RE . match ( line ) if match : header_name , header_value = match . groups ( ) header_name = header_name . strip ( ) . lower ( ) extend_lines = 0 if header_name in HEADER_MAP : hdrs [ HEADER_MAP [ header_name ] ] = header_value . strip ( ) lines_processed = n + 1 else : extend_lines += 1 if extend_lines < max_wrap_lines and header_name in HEADER_MAP : hdrs [ HEADER_MAP [ header_name ] ] = join_wrapped_lines ( [ hdrs [ HEADER_MAP [ header_name ] ] , line . strip ( ) ] ) lines_processed = n + 1 else : # no more headers found break return hdrs , lines_processed
Extracts email headers from the given lines . Returns a dict with the detected headers and the amount of lines that were processed .
255
26
26,339
def trim_tree_after ( element , include_element = True ) : el = element for parent_el in element . iterancestors ( ) : el . tail = None if el != element or include_element : el = el . getnext ( ) while el is not None : remove_el = el el = el . getnext ( ) parent_el . remove ( remove_el ) el = parent_el
Removes the document tree following the given element . If include_element is True the given element is kept in the tree otherwise it is removed .
89
29
26,340
def trim_tree_before ( element , include_element = True , keep_head = True ) : el = element for parent_el in element . iterancestors ( ) : parent_el . text = None if el != element or include_element : el = el . getprevious ( ) else : parent_el . text = el . tail while el is not None : remove_el = el el = el . getprevious ( ) tag = remove_el . tag is_head = isinstance ( tag , string_class ) and tag . lower ( ) == 'head' if not keep_head or not is_head : parent_el . remove ( remove_el ) el = parent_el
Removes the document tree preceding the given element . If include_element is True the given element is kept in the tree otherwise it is removed .
151
29
26,341
def get_epsg ( self ) : cur = self . conn . cursor ( ) cur . execute ( "SELECT epsg_code FROM prj_epsg WHERE prjtext = ?" , ( self . prj , ) ) # prjtext has a unique constraint on it, we should only ever fetchone() result = cur . fetchone ( ) if not result and self . call_remote_api : return self . call_api ( ) elif result is not None : self . epsg_code = result [ 0 ] return self . epsg_code
Attempts to determine the EPSG code for a given PRJ file or other similar text - based spatial reference file .
124
23
26,342
def from_epsg ( self , epsg_code ) : self . epsg_code = epsg_code assert isinstance ( self . epsg_code , int ) cur = self . conn . cursor ( ) cur . execute ( "SELECT prjtext FROM prj_epsg WHERE epsg_code = ?" , ( self . epsg_code , ) ) result = cur . fetchone ( ) if result is not None : self . prj = result [ 0 ] return True return False
Loads self . prj by epsg_code . If prjtext not found returns False .
114
22
26,343
def to_prj ( self , filename ) : with open ( filename , "w" ) as fp : fp . write ( self . prj )
Saves prj WKT to given file .
34
10
26,344
def get_current_head_version ( graph ) : script_dir = ScriptDirectory ( "/" , version_locations = [ graph . metadata . get_path ( "migrations" ) ] ) return script_dir . get_current_head ( )
Returns the current head version .
56
6
26,345
def create_temporary_table ( from_table , name = None , on_commit = None ) : from_table = from_table . __table__ if hasattr ( from_table , "__table__" ) else from_table name = name or f"temporary_{from_table.name}" # copy the origin table into the metadata with the new name. temporary_table = copy_table ( from_table , name ) # change create clause to: CREATE TEMPORARY TABLE temporary_table . _prefixes = list ( from_table . _prefixes ) temporary_table . _prefixes . append ( "TEMPORARY" ) # change post create clause to: ON COMMIT DROP if on_commit : temporary_table . dialect_options [ "postgresql" ] . update ( on_commit = on_commit , ) temporary_table . insert_many = MethodType ( insert_many , temporary_table ) temporary_table . select_from = MethodType ( select_from , temporary_table ) temporary_table . upsert_into = MethodType ( upsert_into , temporary_table ) return temporary_table
Create a new temporary table from another table .
248
9
26,346
def get_current_head ( graph ) : session = new_session ( graph ) try : result = session . execute ( "SELECT version_num FROM alembic_version" ) except ProgrammingError : return None else : return result . scalar ( ) finally : session . close ( )
Get the current database head revision if any .
61
9
26,347
def flushing ( self ) : try : yield self . session . flush ( ) except ( FlushError , IntegrityError ) as error : error_message = str ( error ) # There ought to be a cleaner way to capture this condition if "duplicate" in error_message : raise DuplicateModelError ( error ) if "already exists" in error_message : raise DuplicateModelError ( error ) if "conflicts with" in error_message and "identity key" in error_message : raise DuplicateModelError ( error ) elif "still referenced" in error_message : raise ReferencedModelError ( error ) elif "is not present" in error_message : raise MissingDependencyError ( error ) else : raise ModelIntegrityError ( error )
Flush the current session handling common errors .
167
9
26,348
def create ( self , instance ) : with self . flushing ( ) : if instance . id is None : instance . id = self . new_object_id ( ) self . session . add ( instance ) return instance
Create a new model instance .
46
6
26,349
def retrieve ( self , identifier , * criterion ) : return self . _retrieve ( self . model_class . id == identifier , * criterion )
Retrieve a model by primary key and zero or more other criteria .
31
14
26,350
def count ( self , * criterion , * * kwargs ) : query = self . _query ( * criterion ) query = self . _filter ( query , * * kwargs ) return query . count ( )
Count the number of models matching some criterion .
46
9
26,351
def search ( self , * criterion , * * kwargs ) : query = self . _query ( * criterion ) query = self . _order_by ( query , * * kwargs ) query = self . _filter ( query , * * kwargs ) # NB: pagination must go last query = self . _paginate ( query , * * kwargs ) return query . all ( )
Return the list of models matching some criterion .
88
9
26,352
def search_first ( self , * criterion , * * kwargs ) : query = self . _query ( * criterion ) query = self . _order_by ( query , * * kwargs ) query = self . _filter ( query , * * kwargs ) # NB: pagination must go last query = self . _paginate ( query , * * kwargs ) return query . first ( )
Returns the first match based on criteria or None .
90
10
26,353
def _filter ( self , query , * * kwargs ) : query = self . _auto_filter ( query , * * kwargs ) return query
Filter a query with user - supplied arguments .
34
9
26,354
def _retrieve ( self , * criterion ) : try : return self . _query ( * criterion ) . one ( ) except NoResultFound as error : raise ModelNotFoundError ( "{} not found" . format ( self . model_class . __name__ , ) , error , )
Retrieve a model by some criteria .
62
8
26,355
def _delete ( self , * criterion ) : with self . flushing ( ) : count = self . _query ( * criterion ) . delete ( ) if count == 0 : raise ModelNotFoundError return True
Delete a model by some criterion .
44
7
26,356
def _query ( self , * criterion ) : return self . session . query ( self . model_class ) . filter ( * criterion )
Construct a query for the model .
29
7
26,357
def maybe_transactional ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : commit = kwargs . get ( "commit" , True ) with transaction ( commit = commit ) : return func ( * args , * * kwargs ) return wrapper
Variant of transactional that will not commit if there s an argument commit with a falsey value .
64
21
26,358
def make_alembic_config ( temporary_dir , migrations_dir ) : config = Config ( ) config . set_main_option ( "temporary_dir" , temporary_dir ) config . set_main_option ( "migrations_dir" , migrations_dir ) return config
Alembic uses the alembic . ini file to configure where it looks for everything else .
66
21
26,359
def make_script_directory ( cls , config ) : temporary_dir = config . get_main_option ( "temporary_dir" ) migrations_dir = config . get_main_option ( "migrations_dir" ) return cls ( dir = temporary_dir , version_locations = [ migrations_dir ] , )
Alembic uses a script directory to encapsulate its env . py file its migrations directory and its script . py . mako revision template .
76
30
26,360
def run_online_migration ( self ) : connectable = self . graph . postgres with connectable . connect ( ) as connection : context . configure ( connection = connection , # assumes that all models extend our base target_metadata = Model . metadata , * * get_alembic_environment_options ( self . graph ) , ) with context . begin_transaction ( ) : context . run_migrations ( )
Run an online migration using microcosm configuration .
91
10
26,361
def patch_script_directory ( graph ) : temporary_dir = mkdtemp ( ) from_config_original = getattr ( ScriptDirectory , "from_config" ) run_env_original = getattr ( ScriptDirectory , "run_env" ) # use a temporary directory for the revision template with open ( join ( temporary_dir , "script.py.mako" ) , "w" ) as file_ : file_ . write ( make_script_py_mako ( ) ) file_ . flush ( ) # monkey patch our script directory and migration logic setattr ( ScriptDirectory , "from_config" , classmethod ( make_script_directory ) ) setattr ( ScriptDirectory , "run_env" , run_online_migration ) setattr ( ScriptDirectory , "graph" , graph ) try : yield temporary_dir finally : # cleanup delattr ( ScriptDirectory , "graph" ) setattr ( ScriptDirectory , "run_env" , run_env_original ) setattr ( ScriptDirectory , "from_config" , from_config_original ) rmtree ( temporary_dir )
Monkey patch the ScriptDirectory class working around configuration assumptions .
239
12
26,362
def get_migrations_dir ( graph ) : try : migrations_dir = graph . migrations_dir except ( LockedGraphError , NotBoundError ) : migrations_dir = graph . metadata . get_path ( "migrations" ) if not isdir ( migrations_dir ) : raise Exception ( "Migrations dir must exist: {}" . format ( migrations_dir ) ) return migrations_dir
Resolve the migrations directory path .
93
8
26,363
def main ( graph , * args ) : migrations_dir = get_migrations_dir ( graph ) cli = CommandLine ( ) options = cli . parser . parse_args ( args if args else argv [ 1 : ] ) if not hasattr ( options , "cmd" ) : cli . parser . error ( "too few arguments" ) if options . cmd [ 0 ] . __name__ == "init" : cli . parser . error ( "Alembic 'init' command should not be used in the microcosm!" ) with patch_script_directory ( graph ) as temporary_dir : config = make_alembic_config ( temporary_dir , migrations_dir ) cli . run_cmd ( config , options )
Entry point for invoking Alembic s CommandLine .
164
11
26,364
def configure_sessionmaker ( graph ) : engine_routing_strategy = getattr ( graph , graph . config . sessionmaker . engine_routing_strategy ) if engine_routing_strategy . supports_multiple_binds : ScopedFactory . infect ( graph , "postgres" ) class RoutingSession ( Session ) : """ Route session bind to an appropriate engine. See: http://docs.sqlalchemy.org/en/latest/orm/persistence_techniques.html#partitioning-strategies """ def get_bind ( self , mapper = None , clause = None ) : return engine_routing_strategy . get_bind ( mapper , clause ) return sessionmaker ( class_ = RoutingSession )
Create the SQLAlchemy session class .
163
8
26,365
def clone ( instance , substitutions , ignore = ( ) ) : substitutions [ instance . id ] = new_object_id ( ) def substitute ( value ) : try : hash ( value ) except Exception : return value else : return substitutions . get ( value , value ) return instance . __class__ ( * * { key : substitute ( value ) for key , value in iter_items ( instance , ignore ) } ) . create ( )
Clone an instance of Model that uses IdentityMixin .
93
12
26,366
def configure_encryptor ( graph ) : encryptor = graph . multi_tenant_key_registry . make_encryptor ( graph ) # register the encryptor will each encryptable type for encryptable in EncryptableMixin . __subclasses__ ( ) : encryptable . register ( encryptor ) return encryptor
Create a MultiTenantEncryptor from configured keys .
71
12
26,367
def toposorted ( nodes , edges ) : incoming = defaultdict ( set ) outgoing = defaultdict ( set ) for edge in edges : incoming [ edge . to_id ] . add ( edge . from_id ) outgoing [ edge . from_id ] . add ( edge . to_id ) working_set = list ( nodes . values ( ) ) results = [ ] while working_set : remaining = [ ] for node in working_set : if incoming [ node . id ] : # node still has incoming edges remaining . append ( node ) continue results . append ( node ) for child in outgoing [ node . id ] : incoming [ child ] . remove ( node . id ) if len ( working_set ) == len ( remaining ) : raise Exception ( "Cycle detected" ) working_set = remaining return results
Perform a topological sort on the input resources .
172
11
26,368
def should_copy ( column ) : if not isinstance ( column . type , Serial ) : return True if column . nullable : return True if not column . server_default : return True # do not create temporary serial values; they will be defaulted on upsert/insert return False
Determine if a column should be copied .
60
10
26,369
def encrypt ( self , encryption_context_key : str , plaintext : str ) -> Tuple [ bytes , Sequence [ str ] ] : encryption_context = dict ( microcosm = encryption_context_key , ) cyphertext , header = encrypt ( source = plaintext , materials_manager = self . materials_manager , encryption_context = encryption_context , ) key_ids = [ self . unpack_key_id ( encrypted_data_key . key_provider ) for encrypted_data_key in header . encrypted_data_keys ] return cyphertext , key_ids
Encrypt a plaintext string value .
127
8
26,370
def on_init ( target : "EncryptableMixin" , args , kwargs ) : encryptor = target . __encryptor__ # encryption context may be nullable try : encryption_context_key = str ( kwargs [ target . __encryption_context_key__ ] ) except KeyError : return # do not encrypt targets that are not configured for it if encryption_context_key not in encryptor : return plaintext = target . plaintext_to_str ( kwargs . pop ( target . __plaintext__ ) ) # do not try to encrypt when plaintext is None if plaintext is None : return ciphertext , key_ids = encryptor . encrypt ( encryption_context_key , plaintext ) target . ciphertext = ( ciphertext , key_ids )
Intercept SQLAlchemy s instance init event .
171
10
26,371
def on_load ( target : "EncryptableMixin" , context ) : decrypt , plaintext = decrypt_instance ( target ) if decrypt : target . plaintext = plaintext
Intercept SQLAlchemy s instance load event .
39
10
26,372
def register ( cls , encryptor : Encryptor ) : # save the current encryptor statically cls . __encryptor__ = encryptor # NB: we cannot use the before_insert listener in conjunction with a foreign key relationship # for encrypted data; SQLAlchemy will warn about using 'related attribute set' operation so # late in its insert/flush process. listeners = dict ( init = on_init , load = on_load , ) for name , func in listeners . items ( ) : # If we initialize the graph multiple times (as in many unit testing scenarios), # we will accumulate listener functions -- with unpredictable results. As protection, # we need to remove existing listeners before adding new ones; this solution only # works if the id (e.g. memory address) of the listener does not change, which means # they cannot be closures around the `encryptor` reference. # # Hence the `__encryptor__` hack above... if contains ( cls , name , func ) : remove ( cls , name , func ) listen ( cls , name , func )
Register this encryptable with an encryptor .
230
9
26,373
def nodes_map ( self ) : dct = dict ( ) for node in self . nodes . values ( ) : cls = next ( base for base in getmro ( node . __class__ ) if "__tablename__" in base . __dict__ ) key = getattr ( cls , "__alias__" , underscore ( cls . __name__ ) ) dct . setdefault ( key , [ ] ) . append ( node ) return dct
Build a mapping from node type to a list of nodes .
102
12
26,374
def build_edges ( self ) : self . edges = [ edge if isinstance ( edge , Edge ) else Edge ( * edge ) for node in self . nodes . values ( ) for edge in getattr ( node , "edges" , [ ] ) if edge [ 0 ] in self . nodes and edge [ 1 ] in self . nodes ] return self
Build edges based on node edges property .
76
8
26,375
def clone ( self , ignore = ( ) ) : nodes = [ clone ( node , self . substitutions , ignore ) for node in toposorted ( self . nodes , self . edges ) ] return DAG ( nodes = nodes , substitutions = self . substitutions ) . build_edges ( )
Clone this dag using a set of substitutions .
64
11
26,376
def explain ( self , * * kwargs ) : root = self . retrieve_root ( * * kwargs ) children = self . iter_children ( root , * * kwargs ) dag = DAG . from_nodes ( root , * children ) return self . add_edges ( dag )
Generate a dry run DAG of that state that WILL be cloned .
67
16
26,377
def clone ( self , substitutions , * * kwargs ) : dag = self . explain ( * * kwargs ) dag . substitutions . update ( substitutions ) cloned_dag = dag . clone ( ignore = self . ignore ) return self . update_nodes ( self . add_edges ( cloned_dag ) )
Clone a DAG .
75
6
26,378
def choose_database_name ( metadata , config ) : if config . database_name is not None : # we allow -- but do not encourage -- database name configuration return config . database_name if metadata . testing : # by convention, we provision different databases for unit testing and runtime return f"{metadata.name}_test_db" return f"{metadata.name}_db"
Choose the database name to use .
82
7
26,379
def choose_username ( metadata , config ) : if config . username is not None : # we allow -- but do not encourage -- database username configuration return config . username if config . read_only : # by convention, we provision read-only username for every service return f"{metadata.name}_ro" return metadata . name
Choose the database username to use .
69
7
26,380
def choose_uri ( metadata , config ) : database_name = choose_database_name ( metadata , config ) driver = config . driver host , port = config . host , config . port username , password = choose_username ( metadata , config ) , config . password return f"{driver}://{username}:{password}@{host}:{port}/{database_name}"
Choose the database URI to use .
82
7
26,381
def choose_connect_args ( metadata , config ) : if not config . require_ssl and not config . verify_ssl : return dict ( sslmode = "prefer" , ) if config . require_ssl and not config . verify_ssl : return dict ( sslmode = "require" , ) if not config . ssl_cert_path : raise Exception ( "SSL certificate path (`ssl_cert_path`) must be configured for verification" ) return dict ( sslmode = "verify-full" , sslrootcert = config . ssl_cert_path , )
Choose the SSL mode and optional root cert for the connection .
129
12
26,382
def choose_args ( metadata , config ) : return dict ( connect_args = choose_connect_args ( metadata , config ) , echo = config . echo , max_overflow = config . max_overflow , pool_size = config . pool_size , pool_timeout = config . pool_timeout , )
Choose database connection arguments .
67
5
26,383
def _members ( self ) : return { key : value for key , value in self . __dict__ . items ( ) # NB: ignore internal SQLAlchemy state and nested relationships if not key . startswith ( "_" ) and not isinstance ( value , Model ) }
Return a dict of non - private members .
59
9
26,384
def insert_many ( self , items ) : return SessionContext . session . execute ( self . insert ( values = [ to_dict ( item , self . c ) for item in items ] ) , ) . rowcount
Insert many items at once into a temporary table .
46
10
26,385
def upsert_into ( self , table ) : return SessionContext . session . execute ( insert ( table ) . from_select ( self . c , self , ) . on_conflict_do_nothing ( ) , ) . rowcount
Upsert from a temporarty table into another table .
51
12
26,386
def configure_key_provider ( graph , key_ids ) : if graph . metadata . testing : # use static provider provider = StaticMasterKeyProvider ( ) provider . add_master_keys_from_list ( key_ids ) return provider # use AWS provider return KMSMasterKeyProvider ( key_ids = key_ids )
Configure a key provider .
71
6
26,387
def configure_materials_manager ( graph , key_provider ) : if graph . config . materials_manager . enable_cache : return CachingCryptoMaterialsManager ( cache = LocalCryptoMaterialsCache ( graph . config . materials_manager . cache_capacity ) , master_key_provider = key_provider , max_age = graph . config . materials_manager . cache_max_age , max_messages_encrypted = graph . config . materials_manager . cache_max_messages_encrypted , ) return DefaultCryptoMaterialsManager ( master_key_provider = key_provider )
Configure a crypto materials manager
132
6
26,388
def main ( graph ) : args = parse_args ( graph ) if args . drop : drop_all ( graph ) create_all ( graph )
Create and drop databases .
31
5
26,389
def get_lattice_type ( cryst ) : # Table of lattice types and correcponding group numbers dividing # the ranges. See get_lattice_type method for precise definition. lattice_types = [ [ 3 , "Triclinic" ] , [ 16 , "Monoclinic" ] , [ 75 , "Orthorombic" ] , [ 143 , "Tetragonal" ] , [ 168 , "Trigonal" ] , [ 195 , "Hexagonal" ] , [ 231 , "Cubic" ] ] sg = spg . get_spacegroup ( cryst ) m = re . match ( r'([A-Z].*\b)\s*\(([0-9]*)\)' , sg ) sg_name = m . group ( 1 ) sg_nr = int ( m . group ( 2 ) ) for n , l in enumerate ( lattice_types ) : if sg_nr < l [ 0 ] : bravais = l [ 1 ] lattype = n + 1 break return lattype , bravais , sg_name , sg_nr
Find the symmetry of the crystal using spglib symmetry finder .
248
14
26,390
def get_bulk_modulus ( cryst ) : if getattr ( cryst , 'bm_eos' , None ) is None : raise RuntimeError ( 'Missing B-M EOS data.' ) cryst . bulk_modulus = cryst . bm_eos [ 1 ] return cryst . bulk_modulus
Calculate bulk modulus using the Birch - Murnaghan equation of state .
68
17
26,391
def get_BM_EOS ( cryst , systems ) : pvdat = array ( [ [ r . get_volume ( ) , get_pressure ( r . get_stress ( ) ) , norm ( r . get_cell ( ) [ : , 0 ] ) , norm ( r . get_cell ( ) [ : , 1 ] ) , norm ( r . get_cell ( ) [ : , 2 ] ) ] for r in systems ] ) . T # Estimate the initial guess assuming b0p=1 # Limiting volumes v1 = min ( pvdat [ 0 ] ) v2 = max ( pvdat [ 0 ] ) # The pressure is falling with the growing volume p2 = min ( pvdat [ 1 ] ) p1 = max ( pvdat [ 1 ] ) b0 = ( p1 * v1 - p2 * v2 ) / ( v2 - v1 ) v0 = v1 * ( p1 + b0 ) / b0 # Initial guess p0 = [ v0 , b0 , 1 ] # Fitting try : p1 , succ = optimize . curve_fit ( BMEOS , pvdat [ 0 ] , pvdat [ 1 ] , p0 ) except ( ValueError , RuntimeError , optimize . OptimizeWarning ) as ex : raise RuntimeError ( 'Calculation failed' ) cryst . bm_eos = p1 cryst . pv = pvdat return cryst . bm_eos
Calculate Birch - Murnaghan Equation of State for the crystal .
316
16
26,392
def get_elementary_deformations ( cryst , n = 5 , d = 2 ) : # Deformation look-up table # Perhaps the number of deformations for trigonal # system could be reduced to [0,3] but better safe then sorry deform = { "Cubic" : [ [ 0 , 3 ] , regular ] , "Hexagonal" : [ [ 0 , 2 , 3 , 5 ] , hexagonal ] , "Trigonal" : [ [ 0 , 1 , 2 , 3 , 4 , 5 ] , trigonal ] , "Tetragonal" : [ [ 0 , 2 , 3 , 5 ] , tetragonal ] , "Orthorombic" : [ [ 0 , 1 , 2 , 3 , 4 , 5 ] , orthorombic ] , "Monoclinic" : [ [ 0 , 1 , 2 , 3 , 4 , 5 ] , monoclinic ] , "Triclinic" : [ [ 0 , 1 , 2 , 3 , 4 , 5 ] , triclinic ] } lattyp , brav , sg_name , sg_nr = get_lattice_type ( cryst ) # Decide which deformations should be used axis , symm = deform [ brav ] systems = [ ] for a in axis : if a < 3 : # tetragonal deformation for dx in linspace ( - d , d , n ) : systems . append ( get_cart_deformed_cell ( cryst , axis = a , size = dx ) ) elif a < 6 : # sheer deformation (skip the zero angle) for dx in linspace ( d / 10.0 , d , n ) : systems . append ( get_cart_deformed_cell ( cryst , axis = a , size = dx ) ) return systems
Generate elementary deformations for elastic tensor calculation .
386
11
26,393
def get_cart_deformed_cell ( base_cryst , axis = 0 , size = 1 ) : cryst = Atoms ( base_cryst ) uc = base_cryst . get_cell ( ) s = size / 100.0 L = diag ( ones ( 3 ) ) if axis < 3 : L [ axis , axis ] += s else : if axis == 3 : L [ 1 , 2 ] += s elif axis == 4 : L [ 0 , 2 ] += s else : L [ 0 , 1 ] += s uc = dot ( uc , L ) cryst . set_cell ( uc , scale_atoms = True ) # print(cryst.get_cell()) # print(uc) return cryst
Return the cell deformed along one of the cartesian directions
159
12
26,394
def get_strain ( cryst , refcell = None ) : if refcell is None : refcell = cryst du = cryst . get_cell ( ) - refcell . get_cell ( ) m = refcell . get_cell ( ) m = inv ( m ) u = dot ( m , du ) u = ( u + u . T ) / 2 return array ( [ u [ 0 , 0 ] , u [ 1 , 1 ] , u [ 2 , 2 ] , u [ 2 , 1 ] , u [ 2 , 0 ] , u [ 1 , 0 ] ] )
Calculate strain tensor in the Voight notation
124
11
26,395
def work_dir ( path ) : starting_directory = os . getcwd ( ) try : os . chdir ( path ) yield finally : os . chdir ( starting_directory )
Context menager for executing commands in some working directory . Returns to the previous wd when finished .
40
20
26,396
def prepare_calc_dir ( self ) : with open ( "vasprun.conf" , "w" ) as f : f . write ( 'NODES="nodes=%s:ppn=%d"\n' % ( self . nodes , self . ppn ) ) f . write ( 'BLOCK=%d\n' % ( self . block , ) ) if self . ncl : f . write ( 'NCL=%d\n' % ( 1 , ) )
Prepare the calculation directory for VASP execution . This needs to be re - implemented for each local setup . The following code reflects just my particular setup .
111
32
26,397
def calc_finished ( self ) : #print_stack(limit=5) if not self . calc_running : #print('Calc running:',self.calc_running) return True else : # The calc is marked as running check if this is still true # We do it by external scripts. You need to write these # scripts for your own system. # See examples/scripts directory for examples. with work_dir ( self . working_dir ) : o = check_output ( [ 'check-job' ] ) #print('Status',o) if o [ 0 ] in b'R' : # Still running - we do nothing to preserve the state return False else : # The job is not running maybe it finished maybe crashed # We hope for the best at this point ad pass to the # Standard update function return True
Check if the lockfile is in the calculation directory . It is removed by the script at the end regardless of the success of the calculation . This is totally tied to implementation and you need to implement your own scheme!
175
43
26,398
def run_calculation ( self , atoms = None , properties = [ 'energy' ] , system_changes = all_changes ) : self . calc . calculate ( self , atoms , properties , system_changes ) self . write_input ( self . atoms , properties , system_changes ) if self . command is None : raise RuntimeError ( 'Please configure Remote calculator!' ) olddir = os . getcwd ( ) errorcode = 0 try : os . chdir ( self . directory ) output = subprocess . check_output ( self . command , shell = True ) self . jobid = output . split ( ) [ 0 ] self . submited = True #print "Job %s submitted. Waiting for it." % (self.jobid) # Waiting loop. To be removed. except subprocess . CalledProcessError as e : errorcode = e . returncode finally : os . chdir ( olddir ) if errorcode : raise RuntimeError ( '%s returned an error: %d' % ( self . name , errorcode ) ) self . read_results ( )
Internal calculation executor . We cannot use FileIOCalculator directly since we need to support remote execution . This calculator is different from others . It prepares the directory launches the remote process and raises the exception to signal that we need to come back for results when the job is finished .
230
58
26,399
def gen ( ctx , num , lo , hi , size , struct ) : frmt = ctx . parent . params [ 'frmt' ] action = ctx . parent . params [ 'action' ] cryst = ase . io . read ( struct , format = frmt ) fn_tmpl = action if frmt == 'vasp' : fn_tmpl += '_%03d.POSCAR' kwargs = { 'vasp5' : True , 'direct' : True } elif frmt == 'abinit' : fn_tmpl += '_%03d.abinit' kwargs = { } if verbose : from elastic . elastic import get_lattice_type nr , brav , sg , sgn = get_lattice_type ( cryst ) echo ( '%s lattice (%s): %s' % ( brav , sg , cryst . get_chemical_formula ( ) ) ) if action == 'cij' : echo ( 'Generating {:d} deformations of {:.1f}(%/degs.) per axis' . format ( num , size ) ) elif action == 'eos' : echo ( 'Generating {:d} deformations from {:.3f} to {:.3f} of V0' . format ( num , lo , hi ) ) if action == 'cij' : systems = elastic . get_elementary_deformations ( cryst , n = num , d = size ) elif action == 'eos' : systems = elastic . scan_volumes ( cryst , n = num , lo = lo , hi = hi ) systems . insert ( 0 , cryst ) if verbose : echo ( 'Writing %d deformation files.' % len ( systems ) ) for n , s in enumerate ( systems ) : ase . io . write ( fn_tmpl % n , s , format = frmt , * * kwargs )
Generate deformed structures
423
5