text
stringlengths
12
1.05M
repo_name
stringlengths
5
86
path
stringlengths
4
191
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
12
1.05M
keyword
listlengths
1
23
text_hash
stringlengths
64
64
from WebAppDIRAC.Lib.WebHandler import WebHandler, asyncGen from DIRAC.Core.DISET.RPCClient import RPCClient from DIRAC.ResourceStatusSystem.PolicySystem.StateMachine import RSSMachine from DIRAC.Core.Utilities import Time from DIRAC import gLogger import collections import json class ResourceSummaryHandler( WebHandler ): AUTH_PROPS = "all" @asyncGen def web_getSelectionData( self ): '''It returns the possible selection data ''' callback = { 'name' : set(), 'elementType' : set(), 'status' : set(), 'statusType' : set(), 'tokenOwner' : set() } pub = RPCClient( 'ResourceStatus/Publisher' ) gLogger.info( self.request.arguments ) elementStatuses = yield self.threadTask( pub.getElementStatuses, 'Resource', None, None, None, None, None ) if elementStatuses[ 'OK' ]: for elementStatus in elementStatuses[ 'Value' ]: callback[ 'status' ].add( elementStatus[ 2 ] ) callback[ 'name' ].add( elementStatus[ 0 ] ) callback[ 'elementType' ].add( elementStatus[ 6 ] ) callback[ 'statusType' ].add( elementStatus[ 1 ] ) callback[ 'tokenOwner' ].add( elementStatus[ 8 ] ) for key, value in callback.items(): callback[ key ] = [ [ item ] for item in list( value ) ] callback[ key ].sort() callback[ key ] = [ [ 'All' ] ] + callback[ key ] self.finish( callback ) @asyncGen def web_getResourceSummaryData( self ): '''This method returns the data required to fill the grid. ''' requestParams = self.__requestParams() gLogger.info( requestParams ) pub = RPCClient( 'ResourceStatus/Publisher' ) elementStatuses = yield self.threadTask( pub.getElementStatuses, 'Resource', requestParams[ 'name' ], requestParams[ 'elementType' ], requestParams[ 'statusType' ], requestParams[ 'status' ], requestParams[ 'tokenOwner' ] ) if not elementStatuses[ 'OK' ]: self.finish( { 'success' : 'false', 'error' : elementStatuses[ 'Message' ] } ) elementTree = collections.defaultdict( list ) for element in elementStatuses[ 'Value' ]: elementDict = dict( zip( elementStatuses[ 'Columns' ], element ) ) elementDict[ 'DateEffective' ] = str( elementDict[ 'DateEffective' ] ) elementDict[ 'LastCheckTime' ] = str( elementDict[ 'LastCheckTime' ] ) elementDict[ 'TokenExpiration' ] = str( elementDict[ 'TokenExpiration' ] ) elementTree[ elementDict[ 'Name' ] ].append( elementDict ) elementList = [] for elementValues in elementTree.values(): if len( elementValues ) == 1: elementList.append( elementValues[ 0 ] ) else: elementList.append( self.combine( elementValues ) ) rssMachine = RSSMachine( None ) yield self.threadTask( rssMachine.orderPolicyResults, elementList ) timestamp = Time.dateTime().strftime( "%Y-%m-%d %H:%M [UTC]" ) self.finish( { 'success': 'true', 'result': elementList, 'total': len( elementList ), "date":timestamp } ) def combine( self, elementValues ): statuses = [ element[ 'Status' ] for element in elementValues ] statusSet = set( statuses ) if len( statusSet ) == 1: status = statusSet.pop() reason = 'All %s' % status else: if set( [ 'Active', 'Degraded' ] ) & set( statusSet ): status = 'Degraded' reason = 'Not completely active' else: status = 'Banned' reason = 'Not usable' # if set( [ 'Unknown','Active', 'Degraded' ] ) & set( statusSet ): # for upStatus in [ 'Active', 'Degraded' ]: # if upStatus in statusSet: # status = upStatus # reason = '%d %s' % ( statuses.count( upStatus ), upStatus ) # break # else: # for downStatus in [ 'Unknown','Probing','Banned','Error' ]: # if downStatus in statusSet: # status = downStatus # reason = '%d %s' % ( statuses.count( downStatus ), downStatus ) # break # Make a copy combined = {} combined.update( elementValues[ 0 ] ) combined[ 'StatusType' ] = '%d elements' % len( statuses ) combined[ 'Status' ] = status combined[ 'Reason' ] = reason combined[ 'DateEffective' ] = '' combined[ 'LastCheckTime' ] = '' combined[ 'TokenOwner' ] = '' combined[ 'TokenExpiration' ] = '' return combined @asyncGen def web_expand( self ): ''' This method handles the POST requests ''' requestParams = self.__requestParams() gLogger.info( requestParams ) pub = RPCClient( 'ResourceStatus/Publisher' ) elements = yield self.threadTask( pub.getElementStatuses, 'Resource', requestParams[ 'name' ], None, None, None, None ) if not elements[ 'OK' ]: self.finish( { 'success' : 'false', 'error' : elements[ 'Message' ] } ) elementList = [ dict( zip( elements[ 'Columns' ], element ) ) for element in elements[ 'Value' ] ] for element in elementList: element[ 'DateEffective' ] = str( element[ 'DateEffective' ] ) element[ 'LastCheckTime' ] = str( element[ 'LastCheckTime' ] ) element[ 'TokenExpiration' ] = str( element[ 'TokenExpiration' ] ) self.finish( { 'success': 'true', 'result': elementList, 'total': len( elementList ) } ) @asyncGen def web_action( self ): requestParams = self.__requestParams() if 'action' in requestParams and requestParams[ 'action' ]: actionName = requestParams[ 'action' ][ 0 ] methodName = actionName if not actionName.startswith( 'set' ): methodName = '_get%s' % actionName try: return getattr( self, methodName )( requestParams ) except AttributeError: result = { 'success' : 'false', 'error' : 'bad action %s' % actionName } else: result = { 'success' : 'false', 'error' : 'Missing action' } self.finish( result ) def setToken( self, requestParams ): sData = self.getSessionData() username = sData["user"]["username"] if username == 'anonymous': self.finish( { 'success' : 'false', 'error' : 'Cannot perform this operation as anonymous' } ) elif not 'SiteManager' in sData['user']['properties']: self.finish( { 'success' : 'false', 'error' : 'Not authorized' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.setToken, 'Resource', str( requestParams[ 'name' ][ 0 ] ), str( requestParams[ 'statusType' ][ 0 ] ), str( requestParams[ 'status' ][ 0 ] ), str( requestParams[ 'elementType' ][ 0 ] ), username, str( requestParams[ 'lastCheckTime' ][ 0 ] ) ) if not res[ 'OK' ]: self.finish( { 'success' : 'false', 'error' : res[ 'Message' ] } ) self.finish( { 'success' : 'true', 'result' : res[ 'Value' ] } ) def setStatus( self, requestParams ): sData = self.getSessionData() username = sData["user"]["username"] if username == 'anonymous': self.finish( { 'success' : 'false', 'error' : 'Cannot perform this operation as anonymous' } ) elif not 'SiteManager' in sData['user']['properties']: self.finish( { 'success' : 'false', 'error' : 'Not authorized' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.setStatus, 'Resource', str( requestParams[ 'name' ][ 0 ] ), str( requestParams[ 'statusType' ][ 0 ] ), str( requestParams[ 'status' ][ 0 ] ), str( requestParams[ 'elementType' ][ 0 ] ), username, str( requestParams[ 'lastCheckTime' ][ 0 ] ) ) if not res[ 'OK' ]: self.finish( { 'success' : 'false', 'error' : res[ 'Message' ] } ) self.finish( { 'success' : 'true', 'result' : res[ 'Value' ] } ) def _getHistory( self, requestParams ): # Sanitize if not 'name' in requestParams or not requestParams[ 'name' ]: self.finish( { 'success' : 'false', 'error' : 'Missing name' } ) if not 'elementType' in requestParams or not requestParams[ 'elementType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing elementType' } ) if not 'statusType' in requestParams or not requestParams[ 'statusType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing statusType' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.getElementHistory, 'Resource', requestParams[ 'name' ], requestParams[ 'elementType' ], requestParams[ 'statusType' ] ) if not res[ 'OK' ]: gLogger.error( res[ 'Message' ] ) self.finish( { 'success' : 'false', 'error' : 'error getting history' } ) history = [ [ r[0], str( r[1] ), r[2] ] for r in res[ 'Value' ] ] gLogger.debug("History:" + str(history)) self.finish( { 'success' : 'true', 'result' : history, 'total' : len( history ) } ) def _getPolicies( self, requestParams ): # Sanitize if not 'name' in requestParams or not requestParams[ 'name' ]: self.finish( { 'success' : 'false', 'error' : 'Missing name' } ) if not 'statusType' in requestParams or not requestParams[ 'statusType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing statusType' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.getElementPolicies, 'Resource', requestParams[ 'name' ], requestParams[ 'statusType' ] ) if not res[ 'OK' ]: gLogger.error( res[ 'Message' ] ) self.finish( { 'success' : 'false', 'error' : 'error getting policies' } ) policies = [ [ r[0], r[1], str( r[2] ), str( r[3] ), r[4] ] for r in res[ 'Value' ] ] self.finish( { 'success' : 'true', 'result' : policies, 'total' : len( policies ) } ) def _getDowntime( self, requestParams ): # Sanitize if not 'name' in requestParams or not requestParams[ 'name' ]: self.finish( { 'success' : 'false', 'error' : 'Missing name' } ) if not 'elementType' in requestParams or not requestParams[ 'elementType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing elementType' } ) if not 'statusType' in requestParams or not requestParams[ 'statusType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing statusType' } ) if not 'element' in requestParams or not requestParams['element']: self.finish( { 'success' : 'false', 'error' : 'Missing element' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.getDowntimes, str( requestParams[ 'element' ][-1] ), str( requestParams[ 'elementType'][-1] ), str( requestParams[ 'name' ][-1] ) ) if not res[ 'OK' ]: gLogger.error( res[ 'Message' ] ) self.finish( { 'success' : 'false', 'error' : 'error getting downtimes' } ) downtimes = [ [ str( dt[0] ), str( dt[1] ), dt[2], dt[3], dt[4] ] for dt in res[ 'Value' ] ] self.finish( { 'success' : 'true', 'result' : downtimes, 'total' : len( downtimes ) } ) def _getTimeline( self, requestParams ): # Sanitize if not 'name' in requestParams or not requestParams[ 'name' ]: self.finish( { 'success' : 'false', 'error' : 'Missing name' } ) if not 'elementType' in requestParams or not requestParams[ 'elementType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing elementType' } ) if not 'statusType' in requestParams or not requestParams[ 'statusType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing statusType' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.getElementHistory, 'Resource', str( requestParams[ 'name' ][-1] ), str( requestParams[ 'elementType' ][-1] ), str( requestParams[ 'statusType' ][-1] ) ) if not res[ 'OK' ]: gLogger.error( res[ 'Message' ] ) self.finish( { 'success' : 'false', 'error' : 'error getting history' } ) history = [] for status, dateEffective, reason in res[ 'Value' ]: # history.append( [ history[ -1 ][ 0 ], str( dateEffective - timedelta( seconds = 1 ) ), '' ] ) history.append( [ status, str( dateEffective ), reason ] ) self.finish( { 'success' : 'true', 'result' : history, 'total' : len( history ) } ) def _getTree( self, requestParams ): if not 'name' in requestParams or not requestParams[ 'name' ]: self.finish( { 'success' : 'false', 'error' : 'Missing name' } ) if not 'elementType' in requestParams or not requestParams[ 'elementType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing elementType' } ) if not 'statusType' in requestParams or not requestParams[ 'statusType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing statusType' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.getTree, 'Resource', str( requestParams[ 'elementType' ][-1] ), str( requestParams[ 'name' ][-1] ) ) if not res[ 'OK' ]: gLogger.error( res[ 'Message' ] ) self.finish( { 'success' : 'false', 'error' : 'error getting tree' } ) res = res[ 'Value' ] siteName = res.keys()[ 0 ] tree = [ [ siteName, None, None, None ] ] for k, v in res[ siteName ][ 'statusTypes' ].items(): tree.append( [ None, k, v, siteName ] ) tree.append( [ 'ces', None, None, siteName ] ) for ce, ceDict in res[ siteName ][ 'ces' ].items(): tree.append( [ ce, None, None, 'ces' ] ) for k, v in ceDict.items(): tree.append( [ None, k, v, ce ] ) tree.append( [ 'ses', None, None, siteName ] ) for se, seDict in res[ siteName ][ 'ses' ].items(): tree.append( [ se, None, None, 'ses' ] ) for k, v in seDict.items(): tree.append( [ None, k, v, se ] ) self.finish( { 'success' : 'true', 'result' : tree, 'total' : len( tree ) } ) def _getInfo( self, requestParams ): if not 'name' in requestParams or not requestParams[ 'name' ]: self.finish( { 'success' : 'false', 'error' : 'Missing name' } ) if not 'elementType' in requestParams or not requestParams[ 'elementType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing elementType' } ) if not 'statusType' in requestParams or not requestParams[ 'statusType' ]: self.finish( { 'success' : 'false', 'error' : 'Missing statusType' } ) if not 'element' in requestParams or not requestParams['element']: self.finish( { 'success' : 'false', 'error' : 'Missing element' } ) pub = RPCClient( 'ResourceStatus/Publisher' ) res = yield self.threadTask( pub.getElementStatuses, str( requestParams[ 'element' ][-1] ), str( requestParams[ 'name' ][-1] ), str( requestParams[ 'elementType' ][-1] ), str( requestParams[ 'statusType' ][-1] ), None, None ) if not res[ 'OK' ]: self.finish( { 'success' : 'false', 'error' : res["Message"] } ) else: columns = res[ 'Columns' ] res = dict( zip( columns, res[ 'Value' ][ 0 ] ) ) res[ 'DateEffective' ] = str( res[ 'DateEffective' ] ) res[ 'LastCheckTime' ] = str( res[ 'LastCheckTime' ] ) res[ 'TokenExpiration' ] = str( res[ 'TokenExpiration' ] ) self.finish( { 'success' : 'true', 'result' : res, 'total' : len( res ) } ) def __requestParams( self ): ''' We receive the request and we parse it, in this case, we are doing nothing, but it can be certainly more complex. ''' gLogger.always( "!!! PARAMS: ", str( self.request.arguments ) ) responseParams = { 'element' : None, 'name' : None, 'elementType' : None, 'statusType' : None, 'status' : None, 'tokenOwner' : None, 'lastCheckTime' : None, 'action' : None } for key in responseParams: if key in self.request.arguments and str( self.request.arguments[ key ][-1] ): responseParams[ key ] = list( json.loads( self.request.arguments[ key ][-1] ) ) return responseParams
zmathe/WebAppDIRAC
WebApp/handler/ResourceSummaryHandler.py
Python
gpl-3.0
16,917
[ "DIRAC" ]
e7dc37a324c9c2c7626f25cebd04fd77a2d29e662feba96885bb16f7633093a5
''' Modules for Numerical Relativity Simulation Catalog: * catalog: builds catalog given a cinfiguration file, or directory containing many configuration files. * scentry: class for simulation catalog entry (should include io) ''' # from nrutils.core import settings as gconfig from nrutils.core.basics import * from nrutils.core import M_RELATIVE_SIGN_CONVENTION import warnings,sys # Class representation of configuration files. The contents of these files define where the metadata for each simulation is stored, and where the related NR data is stored. class scconfig(smart_object): # Create scconfig object from configuration file location def __init__(this,config_file_location=None,overwrite=True): # Required fields from smart_object this.source_file_path = [] this.source_dir = [] this.overwrite = overwrite # call wrapper for constructor this.config_file_location = config_file_location this.reconfig() # The actual constructor: this will be called within utility functions so that scentry objects are configured with local settings. def reconfig(this): # if this.config_file_location is None: msg = '(!!) scconfig objects cannot be initialted/reconfigured without a defined "config_file_location" location property (i.e. string where the related config file lives)' raise ValueError(msg) # learn the contents of the configuration file if os.path.exists( this.config_file_location ): this.learn_file( this.config_file_location, comment=[';','#'] ) # validate the information learned from the configuration file against minimal standards this.validate() this.config_exists = True else: msg = 'There is a simulation catalog entry (scentry) object which references \"%s\", however such a file cannot be found by the OS. The related scentry object will be marked as invalid.'%cyan(this.config_file_location) this.config_exists = False warning(msg,'scconfig.reconfig') # In some cases, it is useful to have this function return this return this # Validate the config file against a minimal set of required fields. def validate(this): # Import useful things from os.path import expanduser # Create a string with the current process name thisfun = inspect.stack()[0][3] # each scconfig object (and the realted file) MUST have the following attributes required_attrs = [ 'institute', # school or collaboration authoring run 'metadata_id', # unique string that defines metadata files 'catalog_dir', # local directory where all simulation folders are stored # this directory allows catalog files to be portable 'data_file_name_format', # formatting string for referencing l m and extraction parameter 'handler_location', # location of python script which contains validator and # learn_metadata functions 'is_extrapolated', # users should set this to true if waveform is extrapolated # to infinity 'is_rscaled', # Boolean for whether waveform data are scaled by extraction radius (ie rPsi4) 'default_par_list' ] # list of default parameters for loading: default_extraction_parameter, default_level. NOTE that list must be of length 2 # Make sure that each required attribute is a member of this objects dictionary representation. If it's not, throw an error. for attr in required_attrs: if not ( attr in this.__dict__ ): msg = '(!!) Error -- config file at %s does NOT contain required field %s' % ( magenta(this.config_file_location), attr ) raise ValueError(msg) # Make sure that data_file_name_format is list of strings. The intention is to give the user the ability to define multiple formats for loading. For example, the GT dataset may have files that begin with Ylm_Weyl... and others that begin with mp_Weylscalar... . if isinstance( this.data_file_name_format, str ): this.data_file_name_format = [this.data_file_name_format] elif isinstance(this.data_file_name_format,list): for k in this.data_file_name_format: if not isinstance(k,str): msg = '(!!) Error in %s: each element of data_file_name_format must be character not numeric. Found data_file_name_format = %s' % (magenta(this.config_file_location),k) raise ValueError(msg) if False: # NOTE that this is turned off becuase it is likely not the appropriate way to check. More thought needed. Original line: len( k.split('%i') ) != 4: msg = '(!!) Error in %s: All elements of data_file_name_format must have three integer formatting tags (%%i). The offending entry is %s.' % ( magenta(this.config_file_location), red(k) ) raise ValueError(msg) else: msg = '(!!) Error in %s: data_file_name_format must be comma separated list.' % magenta(this.config_file_location) # Make sure that catalog_dir is string if not isinstance( this.catalog_dir, str ): msg = 'catalog_dir values must be string' error(red(msg),thisfun) if 2 != len(this.default_par_list): msg = '(!!) Error in %s: default_par_list must be list containing default extraction parameter (Numeric value) and default level (also Numeric in value). Invalide case found: %s' % (magenta(this.config_file_location),list(this.default_par_list)) raise ValueError(msg) # Make sure that all directories end with a forward slash for attr in this.__dict__: if 'dir' in attr: if this.__dict__[attr][-1] != '/': this.__dict__[attr] += '/' # Make sure that user symbols (~) are expanded for attr in this.__dict__: if ('dir' in attr) or ('location' in attr): if isinstance(this.__dict__[attr],str): this.__dict__[attr] = expanduser( this.__dict__[attr] ) elif isinstance(this.__dict__[attr],list): for k in this.__dict__[attr]: if isinstance(k,str): k = expanduser(k) # Class for simulation catalog e. class scentry: # Create scentry object given location of metadata file def __init__( this, config_obj, metadata_file_location, verbose=False ): # Keep an internal log for each scentry created this.log = '[Log for %s] The file is "%s".' % (this,metadata_file_location) # Store primary inputs as object attributes this.config = config_obj this.metadata_file_location = metadata_file_location # Validate the location of the metadata file: does it contain waveform information? is the file empty? etc this.isvalid = this.validate() # this.verbose = verbose # If valid, learn metadata. Note that metadata property are defined as none otherise. Also NOTE that the standard metadata is stored directly to this object's attributes. this.raw_metadata = None if this.isvalid is True: # print '## Working: %s' % cyan(metadata_file_location) this.log += ' This entry\'s metadata file is valid.' # i.e. learn the meta_data_file # this.learn_metadata(); raise(TypeError,'This line should only be uncommented when debugging.') # this.label = sclabel( this ) try: this.learn_metadata() this.label = sclabel( this ) except: emsg = sys.exc_info()[1].message this.log += '%80s'%' [FATALERROR] The metadata failed to be read. There may be an external formatting inconsistency. It is being marked as invalid with None. The system says: %s'%emsg warning( 'The following error message will be logged: '+red(emsg),'scentry') this.isvalid = None # An external program may use this to do something this.label = 'invalid!' elif this.isvalid is False: print '## The following is '+red('invalid')+': %s' % cyan(metadata_file_location) this.log += ' This entry\'s metadta file is invalid.' # Method to load handler module def loadhandler(this): # Import the module from imp import load_source handler_module = load_source( '', this.config.handler_location ) # Validate the handler module: it has to have a few requried methods required_methods = [ 'learn_metadata', 'validate', 'extraction_map' ] for m in required_methods: if not ( m in handler_module.__dict__ ): msg = 'Handler module must contain a method of the name %s, but no such method was found'%(cyan(m)) error(msg,'scentry.validate') # Return the module return handler_module # Validate the metadata file using the handler's validation function def validate(this): # import validation function given in config file # Name the function representation that will be used to load the metadata file, and convert it to raw and standardized metadata validator = this.loadhandler().validate # vet the directory where the metadata file lives for: waveform and additional metadata status = validator( this.metadata_file_location, config = this.config ) # return status # Standardize metadata def learn_metadata(this): # from numpy import allclose # Load the handler for this entry. It will be used multiple times below. handler = this.loadhandler() # Name the function representation that will be used to load the metadata file, and convert it to raw and standardized metadata learn_institute_metadata = handler.learn_metadata # Eval and store standard metadata [standard_metadata, this.raw_metadata] = learn_institute_metadata( this.metadata_file_location ) # Validate the standard metadata required_attrs = [ 'date_number', # creation date (number!) of metadata file 'note', # informational note relating to metadata 'madm', # initial ADM mass = m1+m2 - initial binding energy 'b', # initial orbital separation (scalar: M) 'R1', 'R2', # initial component masses (scalars: M = m1+m2) 'm1', 'm2', # initial component masses (scalars: M = m1+m2) 'P1', 'P2', # initial component linear momenta (Vectors ~ M ) 'L1', 'L2', # initial component angular momental (Vectors ~ M) 'S1', 'S2', # initial component spins (Vectors ~ M*M) 'mf', 'Sf', # Final mass (~M) and final dimensionful spin (~M*M) 'Xf', 'xf' ] # Final dimensionless spin: Vector,Xf, and *Magnitude*: xf = sign(Sf_z)*|Sf|/(mf*mf) (NOTE the definition) for attr in required_attrs: if attr not in standard_metadata.__dict__: msg = '(!!) Error -- Output of %s does NOT contain required field %s' % ( this.config.handler_location, attr ) raise ValueError(msg) # Confer the required attributes to this object for ease of referencing for attr in standard_metadata.__dict__.keys(): setattr( this, attr, standard_metadata.__dict__[attr] ) # tag this entry with its inferred setname this.setname = this.raw_metadata.source_dir[-1].split( this.config.catalog_dir )[-1].split('/')[0] # tag this entry with its inferred simname this.simname = this.raw_metadata.source_dir[-1].split('/')[-1] if this.raw_metadata.source_dir[-1][-1]!='/' else this.raw_metadata.source_dir[-1].split('/')[-2] # tag this entry with the directory location of the metadata file. NOTE that the waveform data must be reference relative to this directory via config.data_file_name_format this.relative_simdir = this.raw_metadata.source_dir[-1].split( this.config.catalog_dir )[-1] # NOTE that is is here that we may infer the default extraction parameter and related extraction radius # Load default values for extraction_parameter and level (e.g. resolution level) # NOTE that the special method defined below must take in an scentry object, and output extraction_parameter and level special_method = 'infer_default_level_and_extraction_parameter' if special_method in handler.__dict__: # Let the people know if this.verbose: msg = 'The handler is found to have a "%s" method. Rather than the config file, this method will be used to determine the default extraction parameter and level.' % green(special_method) alert(msg,'scentry.learn_metadata') # Estimate a good extraction radius and level for an input scentry object from the BAM catalog this.default_extraction_par,this.default_level,this.extraction_radius_map = handler.__dict__[special_method](this) # NOTE that and extraction_radius_map is also defined here, which allows referencing between extraction parameter and extaction radius else: # NOTE that otherwise, values from the configuration file will be used this.default_extraction_par = this.config.default_par_list[0] this.default_level = this.config.default_par_list[1] this.extraction_radius_map = None # NOTE that and extraction_radius_map is also defined here, which allows referencing between extraction parameter and extaction radius, the dault value is currently None # Basic sanity check for standard attributes. NOTE this section needs to be completed and perhaps externalized to the current function. # Check that initial binary separation is float if not isinstance( this.b , float ) : msg = 'b = %g' % this.b raise ValueError(msg) # Check that final mass is float if not isinstance( this.mf , float ) : msg = 'final mass must be float, but %s found' % type(this.mf).__name__ raise ValueError(msg) # Check that inital mass1 is float if not isinstance( this.m1 , float ) : msg = 'm1 must be float but %s found' % type(this.m1).__name__ raise ValueError(msg) # Check that inital mass2 is float if not isinstance( this.m2 , float ) : msg = 'm2 must be float but %s found' % type(this.m2).__name__ raise ValueError(msg) # Enfore m1>m2 convention. satisfies_massratio_convetion = lambda e: (not e.m1 > e.m2) and (not allclose(e.m1,e.m2,atol=1e-4)) if satisfies_massratio_convetion(this): this.flip() if satisfies_massratio_convetion(this): msg = 'Mass ratio convention m1>m2 must be used. Check scentry.flip(). It should have corrected this! \n>> m1 = %g, m2 = %g' % (this.m1,this.m2) raise ValueError(msg) # Create dynamic function that references the user's current configuration to construct the simulation directory of this run. def simdir(this): ans = this.config.reconfig().catalog_dir + this.relative_simdir if not this.config.config_exists: msg = 'The current object has been marked as '+red('non-existent')+', likely by reconfig(). Please verify that the ini file for the related run exists. You may see this message for other (yet unpredicted) reasons.' error(msg,'scentry.simdir()') return ans # Flip 1->2 associations. def flip(this): # from numpy import array,double # Store the flippoed variables to placeholders R1 = array(this.R2); R2 = array(this.R1); m1 = double(this.m2); m2 = double(this.m1); P1 = array(this.P2); P2 = array(this.P1); L1 = array(this.L2); L2 = array(this.L1); S1 = array(this.S2); S2 = array(this.S1); # Apply the flip to the current object this.R1 = R1; this.R2 = R2 this.m1 = m1; this.m2 = m2 this.P1 = P1; this.P2 = P2 this.L1 = L1; this.L2 = L2 this.S1 = S1; this.S2 = S2 # Compare this scentry object to another using initial parameter fields. Return true false statement def compare2( this, that, atol=1e-3 ): # from numpy import allclose,hstack,double # Calculate an array of initial parameter values (the first element is 0 or 1 describing quasi-circularity) def param_array( entry ): # List of fields to add to array: initial parameters that are independent of initial separation field_list = [ 'm1', 'm2', 'S1', 'S2' ] # a = double( 'qc' in entry.label ) for f in field_list: a = hstack( [a, entry.__dict__[f] ] ) # return a # Perform comparison and return return allclose( param_array(this), param_array(that), atol=atol ) # Create the catalog database, and store it as a pickled file. def scbuild(keyword=None,save=True): # Load useful packages from commands import getstatusoutput as bash from os.path import realpath, abspath, join, splitext, basename from os import pardir,system,popen import pickle # Create a string with the current process name thisfun = inspect.stack()[0][3] # Look for config files cpath_list = glob.glob( gconfig.config_path+'*.ini' ) # If a keyword is give, filter against found config files if isinstance(keyword,(str,unicode)): msg = 'Filtering ini files for \"%s\"'%cyan(keyword) alert(msg,'scbuild') cpath_list = filter( lambda path: keyword in path, cpath_list ) # if not cpath_list: msg = 'Cannot find configuration files (*.ini) in %s' % gconfig.config_path error(msg,thisfun) # Create config objects from list of config files configs = [ scconfig( config_path ) for config_path in cpath_list ] # For earch config for config in configs: # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # # Create streaming log file # logfstr = gconfig.database_path + '/' + splitext(basename(config.config_file_location))[0] + '.log' msg = 'Opening log file in: '+cyan(logfstr) alert(msg,thisfun) logfid = open(logfstr, 'w') # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # # Search recurssively within the config's catalog_dir for files matching the config's metadata_id msg = 'Searching for %s in %s.' % ( cyan(config.metadata_id), cyan(config.catalog_dir) ) + yellow(' This may take a long time if the folder being searched is mounted from a remote drive.') alert(msg,thisfun) mdfile_list = rfind(config.catalog_dir,config.metadata_id,verbose=True) alert('done.',thisfun) # (try to) Create a catalog entry for each valid metadata file catalog = [] h = -1 for mdfile in mdfile_list: # Create tempoary scentry object entry = scentry(config,mdfile,verbose=True) # Write to the master log file h+=1 logfid.write( '%5i\t%s\n'% (h,entry.log) ) # If the obj is valid, add it to the catalog list, else ignore if entry.isvalid: catalog.append( entry ) else: del entry # Store the catalog to the database_path if save: db = gconfig.database_path + '/' + splitext(basename(config.config_file_location))[0] + '.' + gconfig.database_ext msg = 'Saving database file to %s'%cyan(db) alert(msg,'scbuild') with open(db, 'wb') as dbf: pickle.dump( catalog , dbf, pickle.HIGHEST_PROTOCOL ) # Close the log file logfid.close() # wave_train = ''#'~~~~<vvvvvvvvvvvvvWw>~~~~' hline = wave_train*3 msg = '\n\n#%s#\n%s with \"%s\". The related log file is at \"%s\".\n#%s#'%(hline,hlblack('Done'),green(config.catalog_dir),green(logfstr),hline) alert(msg,'scbuild') # Function for searching through catalog files. def scsearch( catalog = None, # Manually input list of scentry objects to search through q = None, # RANGE of mass ratios (>=1) to search for nonspinning = None, # Non-spinning initially spinaligned = None, # spin-aligned with L AND no in-plane spin INITIALLY spinantialigned = None, # spin-anti-aligned with L AND no in-plane spin INITIALLY precessing = None, # not spin aligned nonprecessing = None, # not precessing equalspin = None, # equal spin magnitudes unequalspin = None, # not equal spin magnitudes antialigned = None, # spin is in opposite direction of L setname = None, # name of simulation set notsetname = None, # list of setnames to ignore institute = None, # list of institutes to accept keyword = None, # list of keywords to accept (based on metadata directory string) notkeyword = None, # list of keywords to not accept (based on metadata # directory string unique = None, # if true, only simulations with unique initial conditions will be used plot = None, # whether or not to show a plot of results exists=None, # Test whether data directory related to scentry and ini file exist (True/False) validate_remnant=False, # If true, ensure that final mass adn spin are well defined verbose = None): # be verbose # Print non None inputs to screen thisfun = inspect.stack()[0][3] if verbose is not None: for k in dir(): if (eval(k) is not None) and (k != 'thisfun'): print '[%s]>> Found %s (=%r) keyword.' % (thisfun,textul(k),eval(k)) ''' Handle individual cases in serial ''' # from os.path import realpath, abspath, join from os import pardir from numpy.linalg import norm from numpy import allclose,dot import pickle, glob # absolute tolerance for num comparisons tol = 1e-6 # Handle the catalog input if catalog is None: # Get a list of all catalog database files. NOTE that .cat files are either placed in database_path directly, or by scbuild() dblist = glob.glob( gconfig.database_path+'*.'+gconfig.database_ext ) # Load the catalog file(s) catalog = [] for db in dblist: with open( db , 'rb') as dbf: catalog = catalog + pickle.load( dbf ) # Determine whether remnant properties are already stored if validate_remnant is True: from numpy import isnan,sum test = lambda k: (sum(isnan( k.xf ))==0) and (isnan(k.mf)==0) catalog = filter( test, catalog ) # mass-ratio qtol = 1e-3 if q is not None: # handle int of float input if isinstance(q,(int,float)): q = [q-qtol,q+qtol] # NOTE: this could use error checking test = lambda k: k.m1/k.m2 >= min(q) and k.m1/k.m2 <= max(q) catalog = filter( test, catalog ) # nonspinning if nonspinning is True: test = lambda k: norm(k.S1)+norm(k.S2) < tol catalog = filter( test, catalog ) # spin aligned with orbital angular momentum if spinaligned is True: test = lambda k: allclose( dot(k.S1,k.L1+k.L2) , norm(k.S1)*norm(k.L1+k.L2) , atol=tol ) and allclose( dot(k.S2,k.L1+k.L2) , norm(k.S2)*norm(k.L1+k.L2) , atol=tol ) and not allclose( norm(k.S1)+norm(k.S2), 0.0, atol=tol ) catalog = filter( test, catalog ) # spin anti-aligned with orbital angular momentum if spinantialigned is True: test = lambda k: allclose( dot(k.S1,k.L1+k.L2) , -norm(k.S1)*norm(k.L1+k.L2) , atol=tol ) and allclose( dot(k.S2,k.L1+k.L2) , -norm(k.S2)*norm(k.L1+k.L2) , atol=tol ) and not allclose( norm(k.S1)+norm(k.S2), 0.0, atol=tol ) catalog = filter( test, catalog ) # precessing if precessing is True: test = lambda k: not allclose( abs(dot(k.S1+k.S2,k.L1+k.L2)), norm(k.L1+k.L2)*norm(k.S1+k.S2) , atol = tol ) catalog = filter( test, catalog ) # non-precessing, same as spinaligned & spin anti aligned nptol = 1e-4 if nonprecessing is True: test = lambda k: allclose( abs(dot(k.S1+k.S2,k.L1+k.L2)), norm(k.L1+k.L2)*norm(k.S1+k.S2) , atol = nptol ) catalog = filter( test, catalog ) # spins have equal magnitude if equalspin is True: test = lambda k: allclose( norm(k.S1), norm(k.S2), atol = tol ) catalog = filter( test, catalog ) # spins have unequal magnitude if unequalspin is True: test = lambda k: not allclose( norm(k.S1), norm(k.S2), atol = tol ) catalog = filter( test, catalog ) # if antialigned is True: test = lambda k: allclose( dot(k.S1+k.S2,k.L1+k.L2)/(norm(k.S1+k.S2)*norm(k.L1+k.L2)), -1.0, atol = tol ) catalog = filter( test, catalog ) # Compare setname strings if setname is not None: if isinstance( setname, str ): setname = [setname] setname = filter( lambda s: isinstance(s,str), setname ) setname = [ k.lower() for k in setname ] if isinstance( setname, list ) and len(setname)>0: test = lambda k: k.setname.lower() in setname catalog = filter( test, catalog ) else: msg = '[%s]>> setname input must be nonempty string or list.' % thisfun raise ValueError(msg) # Compare not setname strings if notsetname is not None: if isinstance( notsetname, str ): notsetname = [notsetname] notsetname = filter( lambda s: isinstance(s,str), notsetname ) notsetname = [ k.lower() for k in notsetname ] if isinstance( notsetname, list ) and len(notsetname)>0: test = lambda k: not ( k.setname.lower() in notsetname ) catalog = filter( test, catalog ) else: msg = '[%s]>> notsetname input must be nonempty string or list.' % thisfun raise ValueError(msg) # Compare institute strings if institute is not None: if isinstance( institute, str ): institute = [institute] institute = filter( lambda s: isinstance(s,str), institute ) institute = [ k.lower() for k in institute ] if isinstance( institute, list ) and len(institute)>0: test = lambda k: k.config.institute.lower() in institute catalog = filter( test, catalog ) else: msg = '[%s]>> institute input must be nonempty string or list.' % thisfun raise ValueError(msg) # Compare keyword if keyword is not None: # If string, make list if isinstance( keyword, str ): keyword = [keyword] keyword = filter( lambda s: isinstance(s,str), keyword ) # Determine whether to use AND or OR based on type if isinstance( keyword, list ): allkeys = True if verbose: msg = 'List of keywords or string keyword found: '+cyan('ALL scentry objects matching will be passed.')+' To pass ANY entries matching the keywords, input the keywords using an iterable of not of type list.' alert(msg,'scsearch') else: allkeys = False # NOTE that this means: ANY keys will be passed if verbose: msg = 'List of keywords found: '+cyan('ANY scentry objects matching will be passed.')+' To pass ALL entries matching the keywords, input the kwywords using a list object.' alert(msg,'scsearch') # Always lower keyword = [ k.lower() for k in keyword ] # Handle two cases if allkeys: # Treat different keys with AND for key in keyword: test = lambda k: key in k.metadata_file_location.lower() catalog = filter( test, catalog ) else: # Treat different keys with OR temp_catalogs = [ catalog for w in keyword ] new_catalog = [] for j,key in enumerate(keyword): test = lambda k: key in k.metadata_file_location.lower() new_catalog += filter( test, temp_catalogs[j] ) catalog = list(set(new_catalog)) # Compare not keyword if notkeyword is not None: if isinstance( notkeyword, str ): notkeyword = [notkeyword] notkeyword = filter( lambda s: isinstance(s,str), notkeyword ) notkeyword = [ k.lower() for k in notkeyword ] for w in notkeyword: test = lambda k: not ( w in k.metadata_file_location.lower() ) catalog = filter( test, catalog ) # Validate the existance of the related config files and simulation directories # NOTE that this effectively requires two reconfigure instances and is surely suboptimal if not ( exists is None ): def isondisk(e): ans = (e.config).reconfig().config_exists and os.path.isdir(e.simdir()) if not ans: msg = 'Ignoring entry at %s becuase its config file cannot be found and/or its simulation directory cannot be found.' % cyan(e.simdir()) warning(msg,'scsearch') return ans if catalog is not None: catalog = filter( isondisk , catalog ) # Filter out physically degenerate simuations within a default tolerance output_descriptor = magenta(' possibly degenerate') if unique: catalog = scunique(catalog,verbose=False) output_descriptor = green(' unique') # Sort by date catalog = sorted( catalog, key = lambda e: e.date_number, reverse = True ) # if verbose: if len(catalog)>0: print '## Found %s%s simulations:' % ( bold(str(len(catalog))), output_descriptor ) for k,entry in enumerate(catalog): # tag this entry with its inferred simname simname = entry.raw_metadata.source_dir[-1].split('/')[-1] if entry.raw_metadata.source_dir[-1][-1]!='/' else entry.raw_metadata.source_dir[-1].split('/')[-2] print '[%04i][%s] %s: %s\t(%s)' % ( k+1, green(entry.config.config_file_location.split('/')[-1].split('.')[0]), cyan(entry.setname), entry.label, cyan(simname ) ) else: print red('!! Found %s simulations.' % str(len(catalog))) print '' # return catalog # Given list of scentry objects, make a list unique in initial parameters def scunique( catalog = None, tol = 1e-3, verbose = False ): # import useful things from numpy import ones,argmax,array # This mask will be augmented such that only unique indeces are true umap = ones( len(catalog), dtype=bool ) # Keep track of which items have been compared using another map tested_map = ones( len(catalog), dtype=bool ) # For each entry in catalog for d,entry in enumerate(catalog): # if tested_map[d]: # Let the people know. if verbose: alert( '[%i] %s:%s' % (d,entry.setname,entry.label), 'scunique' ) # Create a map of all simulations with matching initial parameters (independently of initial setaration) # 1. Filter out all matching objects. NOTE that this subset include the current object subset = filter( lambda k: entry.compare2(k,atol=tol), catalog ) # 2. Find index locations of subset subdex = [ catalog.index(k) for k in subset ] # 3. By default, select longest run to keep. maxdex is the index in subset where b takes on its largest value. maxdex = argmax( [ e.b for e in subset ] ) # recall that b is initial separation # Let the people know. for ind,k in enumerate(subset): tested_map[ subdex[ind] ] = False if k is subset[maxdex]: if verbose: print '>> Keeping: [%i] %s:%s' % (catalog.index(k),k.setname,k.label) else: umap[ subdex[ind] ] = False if verbose: print '## Removing:[%i] %s:%s' % (catalog.index(k),k.setname,k.label) else: if verbose: print magenta('[%i] Skipping %s:%s. It has already been checked.' % (d,entry.setname,entry.label) ) # Create the unique catalog using umap unique_catalog = list( array(catalog)[ umap ] ) # Let the people know. if verbose: print green('Note that %i physically degenerate simulations were removed.' % (len(catalog)-len(unique_catalog)) ) print green( 'Now %i physically unique entries remain:' % len(unique_catalog) ) for k,entry in enumerate(unique_catalog): print green( '>> [%i] %s: %s' % ( k+1, entry.setname, entry.label ) ) print '' # return the unique subset of runs return unique_catalog # Construct string label for members of the scentry class def sclabel( entry, # scentry object use_q = True ): # if True, mass ratio will be used in the label # def sclabel_many( entry = None, use_q = None ): # from numpy import sign # tag_list = [] for e in entry: # _,tg = sclabel_single( entry = e, use_q = use_q ) tg = e.label.split('-') tag_list.append(tg) # common_tag_set = set(tag_list[0]) for k in range(2,len(tag_list)): common_tag_set &= set(tag_list[k]) # common_tag = [ k for k in tag_list[0] if k in common_tag_set ] # single_q = False for tg in common_tag: single_q = single_q or ( ('q' in tg) and (tg!='qc') ) # tag = common_tag # if not single_q: tag .append('vq') # variable q # concat tags together to make label label = '' for k in range(len(tag)): label += sign(k)*'-' + tag[k] # return label # def sclabel_single( entry = None, use_q = None ): # from numpy.linalg import norm from numpy import allclose,dot,sign # if not isinstance( entry, scentry ): msg = '(!!) First input must be member of scentry class.' raise ValueError(msg) # Initiate list to hold label parts tag = [] # tol = 1e-4 # shorthand for entry e = entry # Calculate the entry's net spin and oribal angular momentum S = e.S1+e.S2; L = e.L1+e.L2 # Run is quasi-circular if momenta are perpindicular to separation vector R = e.R2 - e.R1 if allclose( dot(e.P1,R), 0.0 , atol=tol ) and allclose( dot(e.P2,R), 0.0 , atol=tol ): tag.append('qc') # Run is nonspinning if both spin magnitudes are close to zero if allclose( norm(e.S1) + norm(e.S2) , 0.0 , atol=tol ): tag.append('ns') # Label by spin on BH1 if spinning if not allclose( norm(e.S1), 0.0, atol=tol ) : tag.append( '1chi%1.2f' % ( norm(e.S1)/e.m1**2 ) ) # Label by spin on BH2 if spinning if not allclose( norm(e.S2), 0.0, atol=tol ) : tag.append( '2chi%1.2f' % ( norm(e.S2)/e.m2**2 ) ) # Run is spin aligned if net spin is parallel to net L if allclose( dot(e.S1,L) , norm(e.S1)*norm(L) , atol=tol ) and allclose( dot(e.S2,L) , norm(e.S2)*norm(L) , atol=tol ) and (not 'ns' in tag): tag.append('sa') # Run is spin anti-aligned if net spin is anti-parallel to net L if allclose( dot(e.S1,L) , -norm(e.S1)*norm(L) , atol=tol ) and allclose( dot(e.S2,L) , -norm(e.S2)*norm(L) , atol=tol ) and (not 'ns' in tag): tag.append('saa') # Run is precessing if component spins are not parallel with L if (not 'sa' in tag) and (not 'saa' in tag) and (not 'ns' in tag): tag.append('p') # mass ratio if use_q: tag.append( 'q%1.2f' % (e.m1/e.m2) ) # concat tags together to make label label = '' for k in range(len(tag)): label += sign(k)*'-' + tag[k] # return label, tag # if isinstance( entry, list ): label = sclabel_many( entry = entry, use_q = use_q ) elif isinstance( entry, scentry ): label,_ = sclabel_single( entry = entry, use_q = use_q ) else: msg = 'input must be list scentry objects, or single scentry' raise ValueError(msg) # return label # Lowest level class for gravitational waveform data class gwf: # Class constructor def __init__( this, # The object to be created wfarr=None, # umpy array of waveform data in to format [time plus imaginary] dt = None, # If given, the waveform array will be interpolated to this # timestep if needed ref_scentry = None, # reference scentry object l = None, # Optional polar index (an eigenvalue of a differential eq) m = None, # Optional azimuthal index (an eigenvalue of a differential eq) extraction_parameter = None, # Optional extraction parameter ( a map to an extraction radius ) kind = None, # strain or psi4 friend = None, # gwf object from which to clone fields mf = None, # Optional remnant mass input xf = None, # Optional remnant spin input m1=None,m2=None, # Optional masses label = None, # Optional label input (see gwylm) preinspiral = None, # Holder for information about the raw waveform's turn-on postringdown = None, # Holder for information about the raw waveform's turn-off verbose = False ): # Verbosity toggle # this.dt = dt # The kind of obejct to be created : e.g. psi4 or strain if kind is None: kind = r'$y$' this.kind = kind # Optional field to be set externally if needed source_location = None # Set optional fields to none as default. These will be set externally is they are of use. this.l = l this.m = m this.extraction_parameter = extraction_parameter # this.verbose = verbose # Fix nans, nonmonotinicities and jumps in time series waveform array wfarr = straighten_wfarr( wfarr, verbose=this.verbose ) # use the raw waveform data to define all fields this.wfarr = wfarr # optional component masses this.m1,this.m2 = m1,m2 # Optional Holders for remnant mass and spin this.mf = mf this.xf = xf # Optional label input (see gwylm) this.label = label # this.preinspiral = preinspiral this.postringdown = postringdown # this.ref_scentry = ref_scentry this.setfields(wfarr=wfarr,dt=dt) # If desired, Copy fields from related gwf object. if type(friend).__name__ == 'gwf' : this.meet( friend ) elif friend is not None: msg = 'value of "friend" keyword must be a member of the gwf class' error(mgs,'gwf') # Store wfarr in a field that will not be touched beyond this point. This is useful because # the properties defined in "setfields" may change as the waveform is manipulated (e.g. windowed, # scaled, phase shifted), and after any of these changes, we may want to reaccess the initial waveform # though the "reset" method (i.e. this.reset) this.__rawgwfarr__ = wfarr # Tag for whether the wavform has been low pass filtered since creation this.__lowpassfiltered__ = False # set fields of standard wf object def setfields(this, # The current object wfarr=None, # The waveform array to apply to the current object dt=None): # The time spacing to apply to the current object # If given dt, then interpolote waveform array accordingly if dt is not None: if this.verbose: msg = 'Interpolating data to '+cyan('dt=%f'%dt) alert(msg,'gwylm.setfields') wfarr = intrp_wfarr(wfarr,delta=dt) # Alert the use if improper input is given if (wfarr is None) and (this.wfarr is None): msg = 'waveform array input (wfarr=) must be given' raise ValueError(msg) elif wfarr is not None: this.wfarr = wfarr elif (wfarr is None) and not (this.wfarr is None): wfarr = this.wfarr else: msg = 'unhandled waveform array configuration: input wfarr is %s and this.wfarr is %s'%(wfarr,this.wfarr) error(msg,'gwf.setfields') ########################################################## # Make sure that waveform array is in t-plus-cross format # ########################################################## # Imports from numpy import abs,sign,linspace,exp,arange,angle,diff,ones,isnan,pi from numpy import vstack,sqrt,unwrap,arctan,argmax,mod,floor,logical_not from scipy.interpolate import InterpolatedUnivariateSpline from scipy.fftpack import fft, fftfreq, fftshift, ifft # Time domain attributes this.t = None # Time vals this.plus = None # Plus part this.cross = None # Cross part this.y = None # Complex =(def) plus + 1j*cross this.amp = None # Amplitude = abs(y) this.phi = None # Complex argument this.dphi = None # Time rate of complex argument this.k_amp_max = None # Index location of amplitude max this.window = None # The time domain window function applid to the original waveform. This # initiated as all ones, but changed in the taper method (if it is called) # Frequency domain attributes. NOTE that this will not currently be set by default. # Instead, the current approach will be to set these fields once gwf.fft() has been called. this.f = None # double sided frequency range this.w = None # double sided angular frequency range this.fd_plus = None # fourier transform of time domain plus part this.fd_cross = None # fourier transform of time domain cross part this.fd_y = None # both polarisations (i.e. plus + ij*cross) this.fd_wfarr = None # frequency domain waveform array this.fd_amp = None # total frequency domain amplitude: abs(right+left) this.fd_phi = None # total frequency domain phase: arg(right+left) this.fd_dphi = None # frequency derivative of fdphi this.fd_k_amp_max = None # index location of fd amplitude max # Domain independent attributes this.n = None # length of arrays this.fs = None # samples per unit time this.df = None # frequnecy domain spacing # Validate time step. Interpolate for constant time steo if needed. this.__validatet__() # Determine formatting of wfarr t = this.wfarr[:,0]; A = this.wfarr[:,1]; B = this.wfarr[:,2]; # if all elements of A are greater than zero if (A>0).all() : typ = 'amp-phase' elif ((abs(A.imag)>0).any() or (abs(B.imag)>0).any()): # else if A or B are complex # msg = 'The current code version only works with plus valued time domain inputs to gwf().' raise ValueError(msg) else: typ = 'plus-imag' # from here on, we are to work with the plus-cross format if typ == 'amp-phase': C = A*exp(1j*B) this.wfarr = vstack( [ t, C.real, C.imag ] ).T this.__validatewfarr__() # --------------------------------------------------- # # Set time domain properties # --------------------------------------------------- # # NOTE that it will always be assumed that the complex waveform is plus+j*imag # Here, we trust the user to know that if one of these quantities is changed, then it will affect the other, and # that to have all quantities consistent, then one should modify wfarr, and then perform this.setfields() # (and not modify e.g. amp and phase). All functions on gwf objects will respect this. # Time domain attributed this.t = this.wfarr[:,0] # Time this.plus = this.wfarr[:,1] # Real part this.cross = this.wfarr[:,2] # Imaginary part this.y = this.plus + 1j*this.cross # Complex waveform this.amp = abs( this.y ) # Amplitude phi_ = unwrap( angle( this.y ) ) # Phase: NOTE, here we make the phase constant where the amplitude is zero # print find( (this.amp > 0) * (this.amp<max(this.amp)) ) # k = find( (this.amp > 0) * (this.amp<max(this.amp)) )[0] # phi_[0:k] = phi_[k] this.phi = phi_ this.dphi = intrp_diff( this.t, this.phi ) # Derivative of phase, last point interpolated to preserve length # this.dphi = diff( this.phi )/this.dt # Derivative of phase, last point interpolated to preserve length this.k_amp_max = argmax(this.amp) # index location of max ampitude this.intrp_t_amp_max = intrp_argmax(this.amp,domain=this.t) # Interpolated time coordinate of max # this.n = len(this.t) # Number of time samples this.window = ones( this.n ) # initial state of time domain window this.fs = 1.0/this.dt # Sampling rate this.df = this.fs/this.n # freq resolution # --------------------------------------------------- # # Always calculate frequency domain data # --------------------------------------------------- # # compute the frequency domain this.f = fftshift(fftfreq( this.n, this.dt )) this.w = 2*pi*this.f # compute fourier transform values this.fd_plus = fftshift(fft( this.plus )) * this.dt # fft of plus this.fd_cross = fftshift(fft( this.cross )) * this.dt # fft of cross this.fd_y = this.fd_plus + 1j*this.fd_cross # full fft this.fd_amp = abs( this.fd_y ) # amp of full fft this.fd_phi = unwrap( angle( this.fd_y ) ) # phase of full fft # this.fd_dphi = diff( this.fd_phi )/this.df # phase rate: dphi/df this.fd_dphi = intrp_diff( this.f, this.fd_phi ) # phase rate: dphi/df this.fd_k_amp_max = argmax( this.fd_amp ) # Starting frequency in rad/sec this.wstart = None # Copy attrributed from friend. def meet(this,friend,init=False,verbose=False): # If wrong type input, let the people know. if not isinstance(friend,gwf): msg = '1st input must be of type ' + bold(type(this).__name__)+'.' error( msg, fname=inspect.stack()[0][3] ) # Copy attrributed from friend. If init, then do not check if attribute already exists in this. for attr in friend.__dict__: proceed = (attr in this.__dict__) proceed = proceed and type(friend.__dict__[attr]).__name__ in ('int','int64','float','scentry', 'string') # msg = '%s is %s and %s' % (attr,type(friend.__dict__[attr]).__name__,magenta('proceed=%r'%proceed)) # alert(msg) if proceed or init: if verbose: print '\t that.%s --> this.%s (%s)' % (attr,attr,type(friend.__dict__[attr]).__name__) setattr( this, attr, friend.__dict__[attr] ) # dir(this) return this # validate whether there is a constant time step def __validatet__(this): # from numpy import diff,var,allclose,vstack,mean,linspace,diff,amin,allclose from numpy import arange,array,double,isnan,nan,logical_not,hstack from scipy.interpolate import InterpolatedUnivariateSpline # # Look for and remove nans # t,A,B = this.wfarr[:,0],this.wfarr[:,1],this.wfarr[:,2] # nan_mask = logical_not( isnan(t) ) * logical_not( isnan(A) ) * logical_not( isnan(B) ) # if logical_not(nan_mask).any(): # msg = red('There are NANs in the data which mill be masked away.') # warning(msg,'gwf.setfields') # this.wfarr = this.wfarr[nan_mask,:] # t = this.wfarr[:,0]; A = this.wfarr[:,1]; B = this.wfarr[:,2]; # Note the shape convention t = this.wfarr[:,0] # check whether t is monotonically increasing isincreasing = allclose( t, sorted(t), 1e-6 ) if not isincreasing: # Let the people know msg = red('The time series has been found to be non-monotonic. We will sort the data to enforce monotinicity.') warning(msg,'gwf.__validatet__') # In this case, we must sort the data and time array map_ = arange( len(t) ) map_ = sorted( map_, key = lambda x: t[x] ) this.wfarr = this.wfarr[ map_, : ] t = this.wfarr[:,0] # Look for duplicate time data hasduplicates = 0 == amin( diff(t) ) if hasduplicates: # Let the people know msg = red('The time series has been found to have duplicate data. We will delete the corresponding rows.') warning(msg,'gwf.__validatet__') # delete the offending rows dup_mask = hstack( [True, diff(t)!=0] ) this.wfarr = this.wfarr[dup_mask,:] t = this.wfarr[:,0] # if there is a non-uniform timestep, or if the input dt is not None and not equal to the given dt NONUNIFORMT = not isunispaced(t) INPUTDTNOTGIVENDT = this.dt is None if NONUNIFORMT and (not INPUTDTNOTGIVENDT): msg = '(**) Waveform not uniform in time-step. Interpolation will be applied.' if verbose: print magenta(msg) if NONUNIFORMT and INPUTDTNOTGIVENDT: # if dt is not defined and not none, assume smallest dt if this.dt is None: this.dt = diff(lim(t))/len(t) msg = '(**) Warning: No dt given to gwf(). We will assume that the input waveform array is in geometric units, and that dt = %g will more than suffice.' % this.dt if this.verbose: print magenta(msg) # Interpolate waveform array intrp_t = arange( min(t), max(t), this.dt ) intrp_R = InterpolatedUnivariateSpline( t, this.wfarr[:,1] )( intrp_t ) intrp_I = InterpolatedUnivariateSpline( t, this.wfarr[:,2] )( intrp_t ) # create final waveform array this.wfarr = vstack([intrp_t,intrp_R,intrp_I]).T else: # otherwise, set dt automatically this.dt = mean(diff(t)) # validate shape of waveform array def __validatewfarr__(this): # check shape width if this.wfarr.shape[-1] != 3 : msg = '(!!) Waveform arr should have 3 columns' raise ValueError(msg) # check shape depth if len(this.wfarr.shape) != 2 : msg = '(!!) Waveform array should have two dimensions' raise ValueError(msg) # General plotting def plot( this, show=False, fig = None, title = None, ref_gwf = None, labels = None, domain = None): # Handle which default domain to plot if domain is None: domain = 'time' elif not ( domain in ['time','freq'] ): msg = 'Error: domain keyword must be either "%s" or "%s".' % (cyan('time'),cyan('freq')) error(msg,'gwylm.plot') # Plot selected domain. if domain == 'time': ax = this.plottd( show=show,fig=fig,title=title, ref_gwf=ref_gwf, labels=labels ) elif domain == 'freq': ax = this.plotfd( show=show,fig=fig,title=title, ref_gwf=ref_gwf, labels=labels ) # from matplotlib.pyplot import gcf # return ax,gcf() # Plot frequency domain def plotfd( this, show = False, fig = None, title = None, ref_gwf = None, labels = None, verbose = False ): # from matplotlib.pyplot import plot,subplot,figure,tick_params,subplots_adjust from matplotlib.pyplot import grid,setp,tight_layout,margins,xlabel,legend from matplotlib.pyplot import show as shw from matplotlib.pyplot import ylabel as yl from matplotlib.pyplot import title as ttl from numpy import ones,sqrt,hstack,array # if ref_gwf: that = ref_gwf # if fig is None: fig = figure(figsize = 1.1*array([8,7.2])) fig.set_facecolor("white") # kind = this.kind # clr = rgb(3) grey = 0.9*ones(3) lwid = 1 txclr = 'k' fs = 18 font_family = 'serif' gclr = '0.9' # ax = [] # xlim = lim(this.t) # [-400,this.t[-1]] # pos_mask = this.f>0 if ref_gwf: that_pos_mask = that.f>0 that_lwid = 4 that_alpha = 0.22 # set_legend = False if not labels: labels = ('','') else: set_legend=True # ------------------------------------------------------------------- # # Amplitude # ------------------------------------------------------------------- # ax.append( subplot(3,1,1) ); grid(color=gclr, linestyle='-') setp(ax[-1].get_xticklabels(), visible=False) ax[-1].set_xscale('log', nonposx='clip') ax[-1].set_yscale('log', nonposy='clip') # plot( this.f[pos_mask], this.fd_amp[pos_mask], color=clr[0], label=labels[0] ) if ref_gwf: plot( that.f[that_pos_mask], that.fd_amp[that_pos_mask], color=clr[0], linewidth=that_lwid, alpha=that_alpha, label=labels[-1] ) pylim( this.f[pos_mask], this.fd_amp[pos_mask], pad_y=10 ) # yl('$|$'+kind+'$|(f)$',fontsize=fs,color=txclr, family=font_family ) if set_legend: legend(frameon=False) # ------------------------------------------------------------------- # # Total Phase # ------------------------------------------------------------------- # ax.append( subplot(3,1,2, sharex=ax[0]) ); grid(color=gclr, linestyle='-') setp(ax[-1].get_xticklabels(), visible=False) ax[-1].set_xscale('log', nonposx='clip') # plot( this.f[pos_mask], this.fd_phi[pos_mask], color=1-clr[0] ) if ref_gwf: plot( that.f[that_pos_mask], that.fd_phi[that_pos_mask], color=1-clr[0], linewidth=that_lwid, alpha=that_alpha ) pylim( this.f[pos_mask], this.fd_phi[pos_mask] ) # yl(r'$\phi = \mathrm{arg}($'+kind+'$)$',fontsize=fs,color=txclr, family=font_family ) # ------------------------------------------------------------------- # # Total Phase Rate # ------------------------------------------------------------------- # ax.append( subplot(3,1,3, sharex=ax[0]) ); grid(color=gclr, linestyle='-') ax[-1].set_xscale('log', nonposx='clip') # plot( this.f[pos_mask], this.fd_dphi[pos_mask], color=sqrt(clr[0]) ) if ref_gwf: plot( that.f[that_pos_mask], that.fd_dphi[that_pos_mask], color=sqrt(clr[0]), linewidth=that_lwid, alpha=that_alpha ) pylim( this.f[pos_mask], this.fd_dphi[pos_mask] ) # yl(r'$\mathrm{d}{\phi}/\mathrm{d}f$',fontsize=fs,color=txclr, family=font_family) # ------------------------------------------------------------------- # # Full figure settings # ------------------------------------------------------------------- # if title is not None: ax[0].set_title( title, family=font_family ) # Set axis lines (e.g. grid lines) below plot lines for a in ax: a.set_axisbelow(True) # Ignore renderer warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") tight_layout(pad=2, w_pad=1.2) subplots_adjust(hspace = .001) # xlabel(r'$f$',fontsize=fs,color=txclr) # if show: shw() # return ax # Plot time domain def plottd( this, show=False, fig = None, ref_gwf = None, labels = None, title = None): # import warnings from numpy import array # from matplotlib.pyplot import plot,subplot,figure,tick_params,subplots_adjust from matplotlib.pyplot import grid,setp,tight_layout,margins,xlabel,legend from matplotlib.pyplot import show as shw from matplotlib.pyplot import ylabel as yl from matplotlib.pyplot import title as ttl from numpy import ones,sqrt,hstack # if fig is None: fig = figure(figsize = 1.1*array([8,7.2])) fig.set_facecolor("white") # clr = rgb(3) grey = 0.9*ones(3) lwid = 1 txclr = 'k' fs = 18 font_family = 'serif' gclr = '0.9' # ax = [] xlim = lim(this.t) # [-400,this.t[-1]] # if ref_gwf: that = ref_gwf that_lwid = 4 that_alpha = 0.22 # set_legend = False if not labels: labels = ('','') else: set_legend=True # Time domain plus and cross parts ax.append( subplot(3,1,1) ); grid(color=gclr, linestyle='-') setp(ax[-1].get_xticklabels(), visible=False) # actual plotting plot( this.t, this.plus, linewidth=lwid, color=0.8*grey ) plot( this.t, this.cross, linewidth=lwid, color=0.5*grey ) plot( this.t, this.amp, linewidth=lwid, color=clr[0], label=labels[0] ) plot( this.t,-this.amp, linewidth=lwid, color=clr[0] ) if ref_gwf: plot( that.t, that.plus, linewidth=that_lwid, color=0.8*grey, alpha=that_alpha ) plot( that.t, that.cross, linewidth=that_lwid, color=0.5*grey, alpha=that_alpha ) plot( that.t, that.amp, linewidth=that_lwid, color=clr[0], alpha=that_alpha, label=labels[-1] ) plot( that.t,-that.amp, linewidth=that_lwid, color=clr[0], alpha=that_alpha ) if set_legend: legend(frameon=False) # Ignore renderer warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") tight_layout(pad=2, w_pad=1.2) subplots_adjust(hspace = .001) # pylim( this.t, this.amp, domain=xlim, symmetric=True ) kind = this.kind yl(kind,fontsize=fs,color=txclr, family=font_family ) # Time domain phase ax.append( subplot(3,1,2, sharex=ax[0]) ); grid(color=gclr, linestyle='-') setp(ax[-1].get_xticklabels(), visible=False) # actual plotting plot( this.t, this.phi, linewidth=lwid, color=1-clr[0] ) if ref_gwf: plot( that.t, that.phi, linewidth=that_lwid, color=1-clr[0], alpha=that_alpha ) pylim( this.t, this.phi, domain=xlim ) yl( r'$\phi = \mathrm{arg}(%s)$' % kind.replace('$','') ,fontsize=fs,color=txclr, family=font_family) # Time domain frequency ax.append( subplot(3,1,3, sharex=ax[0]) ); grid(color=gclr, linestyle='-') # Actual plotting plot( this.t, this.dphi, linewidth=lwid, color=sqrt(clr[0]) ) if ref_gwf: plot( that.t, that.dphi, linewidth=that_lwid, color=sqrt(clr[0]), alpha=that_alpha ) pylim( this.t, this.dphi, domain=xlim ) yl(r'$\mathrm{d}{\phi}/\mathrm{d}t$',fontsize=fs,color=txclr, family=font_family) # Full figure settings ax[0].set_xlim(lim(this.t)) if title is not None: ax[0].set_title( title, family=font_family ) # Set axis lines (e.g. grid lines) below plot lines for a in ax: a.set_axisbelow(True) # xlabel(r'$t$',fontsize=fs,color=txclr) # if show: shw() # return ax # Apply a time domain window to the waveform. Either the window vector OR a set of indeces to be tapered is given as input. NOTE that while this method modifies the current object, one can revert to object's original state by using the reset() method. OR one can make a backup of the current object by using the clone() method. def apply_window( this, # gwf object to be windowed state = None, # Index values defining region to be tapered: # For state=[a,b], if a>b then the taper is 1 at b and 0 at a # If a<b, then the taper is 1 at a and 0 at b. window = None): # optional input: use known taper/window # Store the initial state of the waveform array just in case the user wishes to undo the window this.__prevarr__ = this.wfarr # Use low level function if (state is not None) and (window is None): window = maketaper( this.t, state) elif (state is None) and (window is None): msg = '(!!) either "state" or "window" keyword arguments must be given and not None.' error(msg,'gwf.taper') # Set this object's window this.window = this.window * window # wfarr = this.wfarr wfarr[:,1] = this.window * this.wfarr[:,1] wfarr[:,2] = this.window * this.wfarr[:,2] # NOTE that objects cannot be redefined within their methods, but their properties can be changed. For this reason, the line below uses setfields() rather than gwf() to apply the taper. this = this.setfields( wfarr=wfarr ) # Apply mask def apply_mask( this, mask=None ): # if mask is None: error('the mask input must be given, and it must be index or boolean ') # this.setfields( this.wfarr[mask,:] ) # If desired, reset the waveform object to its original state (e.g. it's state just afer loading). # Note that after this methed is called, the current object will occupy a different address in memory. def reset(this): this.setfields( this.__rawgwfarr__ ) # return a copy of the current object def copy(this): # from copy import deepcopy as copy return copy(this) # RETURN a clone the current waveform object. NOTE that the copy package may also be used here def clone(this): return gwf(this.wfarr).meet(this) # Interpolate the current object def interpolate(this,dt=None,domain=None): # Validate inputs if (dt is None) and (domain is None): msg = red('First "dt" or "domain" must be given. See traceback above.') error(msg,'gwf.interpolate') if (dt is not None) and (domain is not None): msg = red('Either "dt" or "domain" must be given, not both. See traceback above.') error(msg,'gwf.interpolate') # Create the new wfarr by interpolating if domain is None: wfarr = intrp_wfarr(this.wfarr,delta=dt) else: wfarr = intrp_wfarr(this.wfarr,domain=domain) # Set the current object to its new state this.setfields(wfarr) # Pad this waveform object in the time domain with zeros def pad(this,new_length=None,where=None): # Pad this waveform object to the left and right with zeros ans = this.copy() if new_length is not None: # Create the new wfarr wfarr = pad_wfarr( this.wfarr, new_length,where=where ) # Confer to the current object ans.setfields(wfarr) return ans # Analog of the numpy ndarray conj() def conj(this): this.wfarr[:,2] *= -1 this.setfields() return this # Align the gwf with a reference gwf using a desired method def align( this, that, # The reference gwf object method=None, # The alignment type e.g. phase options=None, # Addtional options for subroutines mask=None, # Boolean mask to apply for alignment (useful e.g. for average-phase alignment) verbose=False ): # if not isinstance(that,gwf): msg = 'first input must be gwf -- the gwf object to alignt the current object to' error(msg,'gwf.align') # Set default method if method is None: msg = 'No method chosen. We will proceed by aligning the waveform\'s initial phase.' warning(msg,'gwf.align') memthod = ['initial-phase'] # Make sure method is list or tuple if not isinstance(method,(list,tuple)): method = [method] # Make sure all methods are strings for k in method: if not isinstance(k,str): msg = 'non-string method type found: %s'%k error(msg,'gwf.align') # Check for handled methods handled_methods = [ 'initial-phase','average-phase' ] for k in method: if not ( k in handled_methods ): msg = 'non-handled method input: %s. Handled methods include %s'%(red(k),handled_methods) error(msg,'gwf.align') # Look for phase-alignement if 'initial-phase' in method: this.wfarr = align_wfarr_initial_phase( this.wfarr, that.wfarr ) this.setfields() if 'average-phase' in method: this.wfarr = align_wfarr_average_phase( this.wfarr, that.wfarr, mask=mask, verbose=verbose) this.setfields() # return this # Shift the waveform phase def shift_phase(this, dphi, fromraw=False, # If True, rotate the wavefor relative to its default wfarr (i.e. __rawgwfarr__) verbose=False): # if not isinstance(dphi,(float,int)): error('input must of float or int real valued','gwf.shift_phase') if not fromraw: wfarr = this.__rawgwfarr__ else: wfarr = this.wfarr # msg = 'This function could be spead up by manually aligning relevant fields, rather than regenerating all fields which includes taking an FFT.' warning(msg,'gwf.shift_phase') # this.wfarr = shift_wfarr_phase( wfarr, dphi ) this.setfields() # frequency domain filter the waveform given a window state for the frequency domain def fdfilter(this,window): # from scipy.fftpack import fft, fftfreq, fftshift, ifft from numpy import floor,array,log from matplotlib.pyplot import plot,show # if this.__lowpassfiltered__: msg = 'wavform already low pass filtered' warning(msg,'gwf.lowpass') else: # fd_y = this.fd_y * window plot( log(this.f), log( abs(this.fd_y) ) ) plot( log(this.f), log( abs(fd_y) ) ) show() # y = ifft( fftshift( fd_y ) ) this.wfarr[:,1],this.wfarr[:,2] = y.real,y.imag # this.setfields() # this.__lowpassfiltered__ = True # Class for waveforms: Psi4 multipoles, strain multipoles (both spin weight -2), recomposed waveforms containing h+ and hx. NOTE that detector response waveforms will be left to pycbc to handle class gwylm: ''' Class to hold spherical multipoles of gravitaiton wave radiation from NR simulations. A simulation catalog entry obejct (of the scentry class) as well as the l and m eigenvalue for the desired multipole (aka mode) is needed. ''' # Class constructor def __init__( this, # reference for the object to be created scentry_obj, # member of the scentry class lm = None, # iterable of length 2 containing multipolr l and m lmax = None, # if set, multipoles with all |m| up to lmax will be loaded. # This input is not compatible with the lm tag dt = None, # if given, the waveform array will beinterpolated to # this timestep load = None, # IF true, we will try to load data from the scentry_object clean = None, # Toggle automatic tapering extraction_parameter = None, # Extraction parameter labeling extraction zone/radius for run level = None, # Opional refinement level for simulation. NOTE that not all NR groups use this specifier. In such cases, this input has no effect on loading. w22 = None, # Optional input for lowest physical frequency in waveform; by default an wstart value is calculated from the waveform itself and used in place of w22 lowpass=None, # Toggle to lowpass filter waveform data upon load using "romline" (in basics.py) routine to define window calcstrain = None, # If True, strain will be calculated upon loading verbose = None ): # be verbose # NOTE that this method is setup to print the value of each input if verbose is true. # NOTE that default input values are handled just below # Print non None inputs to screen thisfun = this.__class__.__name__ if not ( verbose in (None,False) ): for k in dir(): if (eval(k) is not None) and (eval(k) is not False) and not ('this' in k): msg = 'Found %s (=%r) keyword.' % (textul(k),eval(k)) alert( msg, 'gwylm' ) # Handle default values load = True if load is None else load clean = False if clean is None else clean calcstrain = True if calcstrain is None else calcstrain # Validate the lm input this.__valinputs__(thisfun,lm=lm,lmax=lmax,scentry_obj=scentry_obj) # Confer the scentry_object's attributes to this object for ease of referencing for attr in scentry_obj.__dict__.keys(): setattr( this, attr, scentry_obj.__dict__[attr] ) # NOTE that we don't want the scentry's verbose property to overwrite the input above, so we definte this.verbose at this point, not before. this.verbose = verbose # Store the scentry object to optionally access its methods this.__scentry__ = scentry_obj ''' Explicitely reconfigure the scentry object for the current user. ''' # this.config.reconfig() # NOTE that this line is commented out because scentry_obj.simdir() below calls the reconfigure function internally. # Tag this object with the simulation location of the given scentry_obj. NOTE that the right hand side of this assignment depends on the user's configuration file. Also NOTE that the configuration object is reconfigured to the system's settings within simdir() this.simdir = scentry_obj.simdir() # If no extraction parameter is given, retrieve default. NOTE that this depends on the current user's configuration. # NOTE that the line below is commented out becuase the line above (i.e. ... simdir() ) has already reconfigured the config object # scentry_obj.config.reconfig() # This line ensures that values from the user's config are taken if extraction_parameter is None: extraction_parameter = scentry_obj.default_extraction_par if level is None: level = scentry_obj.default_level # config_extraction_parameter = scentry_obj.config.default_par_list[0] config_level = scentry_obj.config.default_par_list[1] if (config_extraction_parameter,config_level) != (extraction_parameter,level): msg = 'The (%s,%s) is (%s,%s), which differs from the config values of (%s,%s). You have either manually input the non-config values, or the handler has set them by looking at the contents of the simulation directory. '%(magenta('extraction_parameter'),green('level'),magenta(str(extraction_parameter)),green(str(level)),str(config_extraction_parameter),str(config_level)) if this.verbose: alert( msg, 'gwylm' ) # Store the extraction parameter and level this.extraction_parameter = extraction_parameter this.level = level # Store the extraction radius if a map is provided in the handler file special_method,handler = 'extraction_map',scentry_obj.loadhandler() if special_method in handler.__dict__: this.extraction_radius = handler.__dict__[special_method]( scentry_obj, this.extraction_parameter ) else: this.extraction_radius = None # These fields are initiated here for visiility, but they are filled as lists of gwf object in load() this.ylm,this.hlm,this.flm = [],[],[] # psi4 (loaded), strain(calculated by default), news(optional non-default) # time step this.dt = dt # Load the waveform data if load==True: this.__load__(lmax=lmax,lm=lm,dt=dt) # Characterize the waveform's start and store related information to this.preinspiral this.preinspiral = None # In charasterize_start(), the information about the start of the waveform is actually stored to "starting". Here this field is inintialized for visibility. this.characterize_start_end() # If w22 is input, then use the input value for strain calculation. Otherwise, use the algorithmic estimate. if w22 is None: w22 = this.wstart_pn if verbose: # msg = 'Using w22 from '+bold(magenta('algorithmic estimate'))+' to calculate strain multipoles.' msg = 'Storing w22 from a '+bold(magenta('PN estimate'))+'[see pnw0 in basics.py, and/or arxiv:1310.1528v4]. This will be the frequency parameter used if strain is to be calculated.' alert( msg, 'gwylm' ) else: if verbose: msg = 'Storing w22 from '+bold(magenta('user input'))+'. This will be the frequency parameter used if strain is to be calculated.' alert( msg, 'gwylm' ) # Low-pass filter waveform (Psi4) data using "romline" routine in basics.py to determin windowed region this.__lowpassfiltered__ = False if lowpass: this.lowpass() # Calculate strain if calcstrain: this.calchlm(w22=w22) # Clean the waveforms of junk radiation if desired this.__isclean__ = False if clean: this.clean() # Set some boolean tags this.__isringdownonly__ = False # will switch to True if, ringdown is cropped. See gwylm.ringdown(). # Create a dictionary representation of the mutlipoles this.__curate__() # Create a dictionary representation of the mutlipoles def __curate__(this): '''Create a dictionary representation of the mutlipoles''' # NOTE that this method should be called every time psi4, strain and/or news is loaded. # NOTE that the related methods are: __load__, calchlm and calcflm # Initiate the dictionary this.lm = {} for l,m in this.__lmlist__: this.lm[l,m] = {} # Seed the dictionary with psi4 gwf objects for y in this.ylm: this.lm[(y.l,y.m)]['psi4'] = y # Seed the dictionary with strain gwf objects for h in this.hlm: this.lm[(h.l,h.m)]['strain'] = h # Seed the dictionary with strain gwf objects for f in this.flm: this.lm[(f.l,f.m)]['news'] = f # Validate inputs to constructor def __valinputs__(this,thisfun,lm=None,lmax=None,scentry_obj=None): from numpy import shape # Raise error upon nonsensical multipolar input if (lm is not None) and (lmax is not None) and load: msg = 'lm input is mutually exclusive with the lmax input' raise NameError(msg) # Default multipolar values if (lm is None) and (lmax is None): lm = [2,2] # Determine whether the lm input is a songle mode (e.g. [2,2]) or a list of modes (e.g. [[2,2],[3,3]] ) if len( shape(lm) ) == 2 : if shape(lm)[1] != 2 : # raise error msg = '"lm" input must be iterable of length 2 (e.g. lm=[2,2]), or iterable of shape (X,2) (e.g. [[2,2],[3,3],[4,4]])' error(msg,thisfun) # Raise error upon nonsensical multipolar input if not isinstance(lmax,int) and lm is None: msg = '(!!) lmax must be non-float integer.' raise ValueError(msg) # Make sure that only one scentry in instput (could be updated later) if not isinstance(scentry_obj,scentry): msg = 'First input must be member of scentry class (e.g. as returned from scsearch() ).' error(msg,thisfun) # Make a list of lm values related to this gwylm object def __make_lmlist__( this, lm, lmax ): # from numpy import shape # this.__lmlist__ = [] # If if an lmax value is given. if lmax is not None: # Then load all multipoles within lmax for l in range(2,lmax+1): # for m in range(-l,l+1): # this.__lmlist__.append( (l,m) ) else: # Else, load the given lis of lm values # If lm is a list of specific multipole indeces if isinstance(lm[0],(list,tuple)): # for k in lm: if len(k)==2: l,m = k this.__lmlist__.append( (l,m) ) else: msg = '(__make_lmlist__) Found list of multipole indeces (e.g. [[2,2],[3,3]]), but length of one of the index values is not two. Please check your lm input.' error(msg) else: # Else, if lm is a single mode index # l,m = lm this.__lmlist__.append( (l,m) ) # Store the input lm list this.__input_lmlist__ = list(this.__lmlist__) # Always load the m=l=2 waveform if not ( (2,2) in this.__lmlist__ ): msg = 'The l=m=2 multipole will be loaded in order to determine important characteristice of all modes such as noise floor and junk radiation location.' warning(msg,'gwylm') this.__lmlist__.append( (2,2) ) # Let the people know if this.verbose: alert('The following spherical multipoles will be loaded:%s'%cyan(str(this.__lmlist__))) # Wrapper for core load function. NOTE that the extraction parameter input is independent of the usage in the class constructor. def __load__( this, # The current object lmax=None, # max l to use lm=None, # (l,m) pair or list of pairs to use extraction_parameter=None, # the label for different extraction zones/radii level = None, # Simulation resolution level (Optional and not supported for all groups ) dt=None, verbose=None ): # from numpy import shape # Make a list of l,m values and store it to the current object as __lmlist__ this.__make_lmlist__( lm, lmax ) # Load all values in __lmlist__ for lm in this.__lmlist__: this.load(lm=lm,dt=dt,extraction_parameter=extraction_parameter,level=level,verbose=verbose) # Ensuer that all modes are the same length this.__valpsi4multipoles__() # Create a dictionary representation of the mutlipoles this.__curate__() # Validate individual multipole against the l=m=2 multipole: e.g. test lengths are same def __valpsi4multipoles__(this): # this.__curate__() # t22 = this.lm[2,2]['psi4'].t n22 = len(t22) # for lm in this.lm: if lm != (2,2): ylm = this.lm[lm]['psi4'] if len(ylm.t) != n22: # if True: #this.verbose: warning('[valpsi4multipoles] The (l,m)=(%i,%i) multipole was found to not have the same length as its (2,2) counterpart. The offending waveform will be interpolated on the l=m=2 time series.'%lm,'gwylm') # Interpolate the mode at t22, and reset fields wfarr = intrp_wfarr(ylm.wfarr,domain=t22) # Reset the fields ylm.setfields(wfarr=wfarr) #Given an extraction parameter, use the handler's extraction_map to determine extraction radius def __r__(this,extraction_parameter): # return this.__scentry__.loadhandler().extraction_map(this,extraction_parameter) # load the waveform data def load(this, # The current object lm=None, # the l amd m values of the multipole to load file_location=None, # (Optional) is give, this file string will be used to load the file, # otherwise the function determines teh file string automatically. dt = None, # Time step to enforce for data extraction_parameter=None, level=None, # (Optional) Level specifyer for simulation. Not all simulation groups use this! output=False, # Toggle whether to store data to the current object, or output it verbose=None): # Import useful things from os.path import isfile,basename from numpy import sign,diff,unwrap,angle,amax,isnan,amin from scipy.stats.mstats import mode from scipy.version import version as scipy_version thisfun=inspect.stack()[0][3] # Default multipolar values if lm is None: lm = [2,2] # Raise error upon nonsensical multipolar input if lm is not None: if len(lm) != 2 : msg = '(!!) lm input must contain iterable of length two containing multipolar indeces' raise ValueError(msg) if abs(lm[1]) > lm[0]: msg = '(!!) Note that m=lm[1], and it must be maintained that abs(m) <= lm[0]=l. Instead (l,m)=(%i,%i).' % (lm[0],lm[1]) raise ValueError(msg) # If file_location is not string, then let the people know. if not isinstance( file_location, (str,type(None)) ): msg = '(!!) '+yellow('Error. ')+'Input file location is type %s, but must instead be '+green('str')+'.' % magenta(type(file_location).__name__) raise ValueError(msg) # NOTE that l,m and extraction_parameter MUST be defined for the correct file location string to be created. l = lm[0]; m = lm[1] # Load default file name parameters: extraction_parameter,l,m,level if extraction_parameter is None: # Use the default value extraction_parameter = this.extraction_parameter if verbose: alert('Using the '+cyan('default')+' extraction_parameter of %g' % extraction_parameter) else: # Use the input value this.extraction_parameter = extraction_parameter if verbose: alert('Using the '+cyan('input')+' extraction_parameter of '+cyan('%g' % extraction_parameter)) if level is None: # Use the default value level = this.level if verbose: alert('Using the '+cyan('default')+' level of %g' % level) else: # Use the input value this.level = level if verbose: alert('Using the '+cyan('input')+' level of '+cyan('%g' % level)) # This boolean will be set to true if the file location to load is found to exist proceed = False # Construct the string location of the waveform data. NOTE that config is inhereted indirectly from the scentry_obj. See notes in the constructor. if file_location is None: # Find file_location automatically. Else, it must be input # file_location = this.config.make_datafilename( extraction_parameter, l,m ) # For all formatting possibilities in the configuration file # NOTE standard parameter order for every simulation catalog # extraction_parameter l m level for fmt in this.config.data_file_name_format : # NOTE the ordering here, and that the filename format in the config file has to be consistent with: extraction_parameter, l, m, level file_location = (this.simdir + fmt).format( extraction_parameter, l, m, level ) # OLD Formatting Style: # file_location = this.simdir + fmt % ( extraction_parameter, l, m, level ) # test whether the file exists if isfile( file_location ): break # If the file location exists, then proceed. If not, then this error is handled below. if isfile( file_location ): proceed = True # If the file to be loaded exists, then load it. Otherwise raise error. if proceed: # load array data from file if this.verbose: alert('Loading: %s' % cyan(basename(file_location)) ) wfarr,_ = smart_load( file_location, verbose=this.verbose ) # Handle extraction radius scaling if not this.config.is_rscaled: # If the data is not in the format r*Psi4, then multiply by r (units M) to make it so extraction_radius = this.__r__(extraction_parameter) wfarr[:,1:3] *= extraction_radius # Fix nans, nonmonotinicities and jumps in time series waveform array # NOTE that the line below is applied within the gwf constructor # wfarr = straighten_wfarr( wfarr ) # Initiate waveform object and check that sign convetion is in accordance with core settings def mkgwf(wfarr_): return gwf( wfarr_, l=l, m=m, extraction_parameter=extraction_parameter, dt=dt, verbose=this.verbose, mf = this.mf, m1 = this.m1, m2 = this.m2, xf = this.xf, label = this.label, ref_scentry = this.__scentry__, kind='$rM\psi_{%i%i}$'%(l,m) ) # y_ = mkgwf(wfarr) # ---------------------------------------------------- # # Enforce internal sign convention for Psi4 multipoles # ---------------------------------------------------- # msk_ = y_.amp > 0.01*amax(y_.amp) if int(scipy_version.split('.')[1])<16: # Account for old scipy functionality external_sign_convention = sign(m) * mode( sign( y_.dphi[msk_] ) )[0][0] else: # Account for modern scipy functionality external_sign_convention = sign(m) * mode( sign( y_.dphi[msk_] ) ).mode[0] if M_RELATIVE_SIGN_CONVENTION != external_sign_convention: wfarr[:,2] = -wfarr[:,2] y_ = mkgwf(wfarr) # Let the people know what is happening. msg = yellow('Re-orienting waveform phase')+' to be consistent with internal sign convention for Psi4, where sign(dPhi/dt)=%i*sign(m).' % M_RELATIVE_SIGN_CONVENTION + ' Note that the internal sign convention is defined in ... nrutils/core/__init__.py as "M_RELATIVE_SIGN_CONVENTION". This message has appeared becuase the waveform is determioned to obey and sign convention: sign(dPhi/dt)=%i*sign(m).'%(external_sign_convention) thisfun=inspect.stack()[0][3] if verbose: alert( msg ) # use array data to construct gwf object with multipolar fields if not output: this.ylm.append( y_ ) else: return y_ else: # There has been an error. Let the people know. msg = '(!!) Cannot find "%s". Please check that catalog_dir and data_file_name_format in %s are as desired. Also be sure that input l and m are within ranges that are actually present on disk.' % ( red(file_location), magenta(this.config.config_file_location) ) raise NameError(msg) # Plotting function for class: plot plus cross amp phi of waveforms USING the plot function of gwf() def plot(this,show=False,fig=None,kind=None,verbose=False,domain=None): # from matplotlib.pyplot import show as shw from matplotlib.pyplot import figure from numpy import array,diff,pi # Handle default kind of waveform to plot if kind is None: kind = 'both' # Handle which default domain to plot if domain is None: domain = 'time' elif not ( domain in ['time','freq'] ): msg = 'Error: domain keyword must be either "%s" or "%s".' % (cyan('time'),cyan('freq')) error(msg,'gwylm.plot') # If the plotting of only psi4 or only strain is desired. if kind != 'both': # Handle kind options if kind in ['psi4','y4','psilm','ylm','psi4lm','y4lm']: wflm = this.ylm elif kind in ['hlm','h','strain']: # Determine whether to calc strain here. If so, then let the people know. if len(this.hlm) == 0: msg = '(**) You have requested that strain be plotted before having explicitelly called MMRDNSlm.calchlm(). I will now call calchlm() for you.' print magenta(msg) this.calchlm() # Assign strain to the general placeholder. wflm = this.hlm # Plot waveform data for y in wflm: # fig = figure( figsize = 1.1*array([8,7.2]) ) fig.set_facecolor("white") ax,_ = y.plot(fig=fig,title='%s: %s, (l,m)=(%i,%i)' % (this.setname,this.label,y.l,y.m),domain=domain) # If there is start characterization, plot some of it if 'starting' in this.__dict__: clr = 0.4*array([1./0.6,1./0.6,1]) dy = 100*diff( ax[0].get_ylim() ) for a in ax: dy = 100*diff( a.get_ylim() ) if domain == 'time': a.plot( wflm[0].t[this.startindex]*array([1,1]) , [-dy,dy], ':', color=clr ) if domain == 'freq': a.plot( this.wstart*array([1,1])/(2*pi) , [-dy,dy], ':', color=clr ) # if show: # Let the people know what is being plotted. if verbose: print cyan('>>')+' Plotting '+darkcyan('%s'%kind) shw() else: # Else, if both are desired # Plot both psi4 and strain for kind in ['psi4lm','hlm']: ax = this.plot(show=show,kind=kind,domain=domain) # return ax # Strain via ffi method def calchlm(this,w22=None): # Calculate strain according to the fixed frequency method of http://arxiv.org/pdf/1006.1632v3 # from numpy import array,double # If there is no w22 given, then use the internally defined value of wstart if w22 is None: # w22 = this.wstart # NOTE: here we choose to use the ORBITAL FREQUENCY as a lower bound for the l=m=2 mode. w22 = this.wstart_pn # Reset this.hlm = [] for y in this.ylm: # Calculate the strain for each part of psi4. NOTE that there is currently NO special sign convention imposed beyond that used for psi4. w0 = w22 * double(y.m)/2.0 # NOTE that wstart is defined in characterize_start_end() using the l=m=2 Psi4 multipole. # Here, m=0 is a special case if 0==y.m: w0 = w22 # Let the people know if this.verbose: alert( magenta('w0(w22) = %f' % w0)+yellow(' (this is the lower frequency used for FFI method [arxiv:1006.1632v3])') ) # Create the core waveform information t = y.t h_plus = ffintegrate( y.t, y.plus, w0, 2 ) h_cross = ffintegrate( y.t, y.cross, w0, 2 ) #%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%# # NOTE that there is NOT a minus sign above which is INconsistent with equation 3.4 of # arxiv:0707.4654v3. Here we choose to be consistent with eq 4 of arxiv:1006.1632 and not add a # minus sign. if this.verbose: msg = yellow('The user should note that there is no minus sign used in front of the double time integral for strain (i.e. Eq 4 of arxiv:1006.1632). This differs from Eq 3.4 of arxiv:0707.4654v3. The net effect is a rotation of the overall polarization of pi degrees. The user should also note that there is no minus sign applied to h_cross meaning that the user must be mindful to write h_pluss-1j*h_cross when appropriate.') alert(msg,'gwylm.calchlm') #%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%.%%# # Constrcut the waveform array for the new strain object wfarr = array( [ t, h_plus, h_cross ] ).T # Add the new strain multipole to this object's list of multipoles this.hlm.append( gwf( wfarr, l=y.l, m=y.m, mf=this.mf, xf=this.xf, kind='$rh_{%i%i}/M$'%(y.l,y.m) ) ) # Create a dictionary representation of the mutlipoles this.__curate__() # NOTE that this is the end of the calchlm method # Characterise the start of the waveform using the l=m=2 psi4 multipole def characterize_start_end(this): # Look for the l=m=2 psi4 multipole y22_list = filter( lambda y: y.l==y.m==2, this.ylm ) # If it doesnt exist in this.ylm, then load it if 0==len(y22_list): y22 = this.load(lm=[2,2],output=True,dt=this.dt) else: y22 = y22_list[0] #%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&# # Characterize the START of the waveform (pre-inspiral) # #%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&# # Use the l=m=2 psi4 multipole to determine the waveform start # store information about the start of the waveform to the current object this.preinspiral = gwfcharstart( y22 ) # store the expected min frequency in the waveform to this object as: this.wstart = this.preinspiral.left_dphi this.startindex = this.preinspiral.left_index # Estimate the smallest orbital frequency relevant for this waveform using a PN formula. safety_factor = 0.90 this.wstart_pn = safety_factor*2.0*pnw0(this.m1,this.m2,this.b) #%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&# # Characterize the END of the waveform (post-ringdown) # #%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&%%&# this.postringdown = gwfcharend( y22 ) # After endindex, the data is dominated by noise this.noiseindex = this.postringdown.left_index this.endindex = this.postringdown.right_index # Clean the time domain waveform by removing junk radiation. def clean( this, method=None, crop_time=None ): # Default cleaning method will be smooth windowing if method is None: method = 'window' # ---------------------------------------------------------------------- # # A. Clean the start and end of the waveform using information from the # characterize_start_end method # ---------------------------------------------------------------------- # if not this.__isclean__ : if method.lower() == 'window': # Look for the l=m=2 psi4 multipole y22_list = filter( lambda y: y.l==y.m==2, this.ylm ) # If it doesnt exist in this.ylm, then load it if 0==len(y22_list): y22 = this.load(lm=[2,2],output=True,dt=this.dt) else: y22 = y22_list[0] # Calculate the window to be applied using the starting information. The window nwill be aplied equally to all multipole moments. NOTE: language disambiguation -- a taper is the part of a window that varies from zero to 1 (or 1 to zero); a window may contain many tapers. Also NOTE that the usage of this4[0].ylm[0].t below is an arbitration -- any array of the dame dimentions could be used. # -- The above is calculated in the gwfcharstart class -- # # Extract the post-ringdown window preinspiral_window = this.preinspiral.window # Extract the post-ringdown window (calculated in the gwfcharend class) postringdown_window = this.postringdown.window # Construct the combined window window = preinspiral_window * postringdown_window # Apply this window to both the psi4 and strain multipole moments. The function, taper(), is a method of the gwf class. for y in this.ylm: y.apply_window( window=window ) for h in this.hlm: h.apply_window( window=window ) elif method.lower() == 'crop': # Crop such that the waveform daya starts abruptly from numpy import arange,double if not (crop_time is None): # If there is no crop time given, then use the low frequency value given by the nrutils start characterization time mask = arange( this.startindex, this.ylm[0].n ) elif isinstance(crop_time,(double,int,float)): # Otherwise, use an input starting time mask = this.ylm[0].raw[:,0] > crop_time for y in this.ylm: y.apply_mask( mask ) for h in this.hlm: h.apply_mask( mask ) # this.__isclean__ = True # Reset each multipole object to its original state def reset(this): # for y in this.ylm: y.reset() for h in this.hlm: h.reset() # return a copy of the current object def copy(this): # from copy import deepcopy as copy return copy(this) #--------------------------------------------------------------------------------# # Calculate the luminosity if needed (NOTE that this could be calculated by default during calcstrain but isnt) #--------------------------------------------------------------------------------# def calcflm(this, # The current object w22=None, # Frequency used for FFI integration force=False, # Force the calculation if it has already been performed verbose=False): # Let the people know # Make sure that the l=m=2 multipole exists if not ( (2,2) in this.lm.keys() ): msg = 'There must be a l=m=2 multipole prewsent to estimate the waveform\'s ringdown part.' error(msg,'gwylm.ringdown') # Determine whether or not to proceed with the calculation # Only proceed if the calculation has not been performed before and if the force option is False proceed = (not this.flm) or force if proceed: # Import useful things from numpy import array,double # If there is no w22 given, then use the internally defined value of wstart if w22 is None: # w22 = this.wstart # NOTE: here we choose to use the ORBITAL FREQUENCY as a lower bound for the l=m=2 mode. w22 = this.wstart_pn # Calculate the luminosity for all multipoles flm = [] proceed = True for y in this.ylm: # Calculate the strain for each part of psi4. NOTE that there is currently NO special sign convention imposed beyond that used for psi4. w0 = w22 * double(y.m)/2.0 # NOTE that wstart is defined in characterize_start_end() using the l=m=2 Psi4 multipole. # Here, m=0 is a special case if 0==y.m: w0 = w22 # Let the people know if this.verbose: alert( magenta('w0(w22) = %f' % w0)+yellow(' (this is the lower frequency used for FFI method [arxiv:1006.1632v3])') ) # Create the core waveform information t = y.t l_plus = ffintegrate( y.t, y.plus, w0, 1 ) l_cross = ffintegrate( y.t, y.cross, w0, 1 ) # Constrcut the waveform array for the news object wfarr = array( [ t, l_plus, l_cross ] ).T # Add the news multipole to this object's list of multipoles flm.append( gwf( wfarr, l=y.l, m=y.m, kind='$r\dot{h}_{%i%i}$'%(y.l,y.m) ) ) else: msg = 'flm, the first integral of Psi4, will not be calculated because it has already been calculated for the current object' if verbose: warning(msg,'gwylm.calcflm') # Store the flm list to the current object this.flm = flm # Create a dictionary representation of the mutlipoles this.__curate__() # NOTE that this is the end of the calcflm method #--------------------------------------------------------------------------------# # Get a gwylm object that only contains ringdown #--------------------------------------------------------------------------------# def ringdown(this, # The current object T0 = 10, # Starting time relative to peak luminosity of the l=m=2 multipole T1 = None, # Maximum time df = None, # Optional df in frequency domain (determines time domain padding) use_peak_strain = False, # Toggle to use peak of strain rather than the peak of the luminosity verbose = None): # from numpy import linspace,array from scipy.interpolate import InterpolatedUnivariateSpline as spline # Make sure that the l=m=2 multipole exists if not ( (2,2) in this.lm.keys() ): msg = 'There must be a l=m=2 multipole prewsent to estimate the waveform\'s ringdown part.' error(msg,'gwylm.ringdown') # Let the people know (about which peak will be used) if this.verbose or verbose: alert('Time will be listed relative to the peak of %s.'%cyan('strain' if use_peak_strain else 'luminosity')) # Use the l=m=2 multipole to estimate the peak location if use_peak_strain: # Only calculate strain if its not there already if (not this.hlm) : this.calchlm() else: # Redundancy checking (see above for strain) is handled within calcflm this.calcflm() # Retrieve the l=m=2 component ref_gwf = this.lm[2,2][ 'strain' if use_peak_strain else 'news' ] # ref_gwf = [ a for a in (this.hlm if use_peak_strain else this.flm) if a.l==a.m==2 ][0] # peak_time = ref_gwf.t[ ref_gwf.k_amp_max ] # peak_time = ref_gwf.intrp_t_amp_max # Handle T1 Input if T1 is None: # NOTE that we will set T1 to be *just before* the noise floor estimate T_noise_floor = ref_gwf.t[this.postringdown.left_index] - peak_time # "Just before" means 95% of the way between T0 and T_noise_floor safety_factor = 0.45 # NOTE that this is quite a low safetey factor -- we wish to definitely avoid noise if possible. T1_min is implemented below just in case this is too strong of a safetey factor. T1 = T0 + safety_factor * ( T_noise_floor - T0 ) # Make sure that T1 is at least T1_min T1_min = 60 T1 = max(T1,T1_min) # NOTE that there is a chance that T1 chould be "too close" to T0 # Validate T1 Value if T1<T0: msg = 'T1=%f which is less than T0=%f. This doesnt make sense: the fitting region cannot end before it begins under the working perspective.'%(T1,T0) error(msg,'gwylm.ringdown') if T1 > (ref_gwf.t[-1] - peak_time) : msg = 'Input value of T1=%i extends beyond the end of the waveform. We will stop at the last value of the waveform, not at the requested T1.'%T1 warning(msg,'gwylm.ringdown') T1 = ref_gwf.t[-1] - peak_time # Use its time series to define a mask a = peak_time + T0 b = peak_time + T1 n = abs(float(b-a))/ref_gwf.dt t = linspace(a,b,n) # that = this.copy() that.__isringdownonly__ = True that.T0 = T0 that.T1 = T1 # def __ringdown__(wlm): # xlm = [] for k,y in enumerate(wlm): # Create interpolated plus and cross parts plus = spline(y.t,y.plus)(t) cross = spline(y.t,y.cross)(t) # Create waveform array wfarr = array( [t-peak_time,plus,cross] ).T # Create gwf object xlm.append( gwf(wfarr,l=y.l,m=y.m,mf=this.mf,xf=this.xf,kind=y.kind,label=this.label,m1=this.m1,m2=this.m2,ref_scentry = this.__scentry__) ) # return xlm # that.ylm = __ringdown__( this.ylm ) that.flm = __ringdown__( this.flm ) that.hlm = __ringdown__( this.hlm ) # Create a dictionary representation of the mutlipoles that.__curate__() # return that # pad each mode to a new_length def pad(this,new_length=None): # Pad each mode for y in this.ylm: y.pad( new_length=new_length ) for h in this.hlm: h.pad( new_length=new_length ) # Recompose the waveforms at a sky position about the source # NOTE that this function returns a gwf object def recompose( this, # The current object theta, # The polar angle phi, # The anzimuthal angle kind=None, verbose=False ): # from numpy import dot,array,zeros # if kind is None: msg = 'no kind specified for recompose calculation. We will proceed assuming that you desire recomposed strain. Please specify the desired kind (e.g. strain, psi4 or news) you wishe to be output as a keyword (e.g. kind=news)' warning( msg, 'gwylm.recompose' ) kind = 'strain' # Create Matrix of Multipole time series def __recomp__(alm,kind=None): M = zeros( [ alm[0].n, len(this.__input_lmlist__) ], dtype=complex ) Y = zeros( [ len(this.__input_lmlist__), 1 ], dtype=complex ) # Seed the matrix as well as the vector of spheroical harmonic values for k,a in enumerate(alm): if (a.l,a.m) in this.__input_lmlist__: M[:,k] = a.y Y[k] = sYlm(-2,a.l,a.m,theta,phi) # Perform the matrix multiplication and create the output gwf object Z = dot( M,Y )[:,0] wfarr = array( [ alm[0].t, Z.real, Z.imag ] ).T # return the ouput return gwf( wfarr, kind=kind, ref_scentry = this.__scentry__ ) # if kind=='psi4': y = __recomp__( this.ylm, kind=r'$rM\,\psi_4(t,\theta,\phi)$' ) elif kind=='strain': y = __recomp__( this.hlm, kind=r'$r\,h(t,\theta,\phi)/M$' ) elif kind=='news': y = __recomp__( this.flm, kind=r'$r\,\dot{h}(t,\theta,\phi)/M$' ) # return y # Extrapolate to infinite radius: http://arxiv.org/pdf/1503.00718.pdf def extrapolate(this,method=None): msg = 'This method is under development and cannot currently be used.' error(msg) # If the simulation is already extrapolated, then do nothing if this.__isextrapolated__: # Do nothing print else: # Else, extrapolate # Use radius only scaling print return None # Estimate Remnant BH mass and spin from gwylm object. This is done by "brute" force here (i.e. an actual calculation), but NOTE that values for final mass and spin are Automatically loaded within each scentry; However!, some of these values may be incorrect -- especially for BAM sumulations. Here we make a rough estimate of the remnant mass and spin based on a ringdown fit. def brute_masspin( this, # IMR gwylm object T0 = 10, # Time relative to peak luminosity to start ringdown T1 = None, # Time relative to peak lum where ringdown ends (if None, gwylm.ringdown sets its value to the end of the waveform approx at noise floor) apply_result = False, # If true, apply result to input this object verbose = False ): # Let the people know '''Estimate Remnant BH mass and spin from gwylm object. This is done by "brute" force here (i.e. an actual calculation), but NOTE that values for final mass and spin are Automatically loaded within each scentry; However!, some of these values may be incorrect -- especially for BAM sumulations. Here we make a rough estimate of the remnant mass and spin based on a ringdown fit.''' # Import useful things thisfun='gwylm.brute_masspin' from scipy.optimize import minimize from nrutils import FinalSpin0815,EradRational0815 from kerr import qnmfit # Validate first input type is_number = isinstance(this,(float,int)) is_gwylm = False if is_number else 'gwylm'==this.__class__.__name__ if not is_gwylm: msg = 'First input must be member of gwylm class from nrutils.' error(msg) # Get the ringdown part starting from 20M after the peak luminosity g = this.ringdown(T0=T0,T1=T1) # Define a work function def action( Mfxf ): # NOTE that the first psi4 multipole is referenced below. # There was only one loaded here, s it has to be for l=m=2 f = qnmfit(g.lm[2,2]['psi4'],Mfxf=Mfxf) # f = qnmfit(g.ylm[0],Mfxf=Mfxf) return f.frmse # Use PhenomD fit for guess eta = this.m1*this.m2/((this.m1+this.m2)**2) chi1, chi2 = this.S1[-1]/(this.m1**2), this.S2[-1]/(this.m2**2) guess_xf = FinalSpin0815( eta, chi2, chi1 ) guess_Mf = 1-EradRational0815(eta, chi2, chi1 ) guess = (guess_Mf,guess_xf) # perform the minization # NOTE that mass is bound on (0,1) and spin on (-1,1) Q = minimize( action,guess, bounds=[(1-0.999,1),(-0.999,0.999)] ) # Extract the solution mf,xf = Q.x # Apply to the input gwylm object if requested if apply_result: this.mf = mf this.xf = xf this.Xf = this.Sf / (mf*mf) attr = [ 'ylm', 'hlm', 'flm' ] for atr in attr: for y in this.__dict__[atr]: y.mf, y.xf = mf, xf if ('Sf' in y.__dict__) and ('Xf' in y.__dict__): y.Xf = y.Sf / (mf*mf) # Return stuff, including the fit object return mf,xf,Q # Los pass filter using romline in basics.py to determine window region def lowpass(this): # msg = 'Howdy, partner! This function is experimental and should NOT be used.' error(msg,'lowpass') # from numpy import log,ones from matplotlib.pyplot import plot,show,axvline # for y in this.ylm: N = 8 if y.m>=0: mask = y.f>0 lf = log( y.f[ mask ] ) lamp = log( y.fd_amp[ mask ] ) knots,_ = romline(lf,lamp,N,positive=True,verbose=True) a,b = 0,1 state = knots[[a,b]] window = ones( y.f.shape ) window[ mask ] = maketaper( lf, state ) elif y.m<0: mask = y.f<=0 lf = log( y.f[ mask ] ) lamp = log( y.fd_amp[ mask ] ) knots,_ = romline(lf,lamp,N,positive=True,verbose=True) a,b = -1,-2 state = knots[[a,b]] window = ones( y.f.shape ) window[ mask ] = maketaper( lf, state ) plot( lf, lamp ) plot( lf, log(window[mask])+lamp, 'k', alpha=0.5 ) plot( lf[knots], lamp[knots], 'o', mfc='none', ms=12 ) axvline(x=lf[knots[a]],color='r') axvline(x=lf[knots[b]],color='r') show() # plot(y.f,y.fd_amp) # show() plot( window ) axvline(x=knots[a],color='r') axvline(x=knots[b],color='r') show() y.fdfilter( window ) # this.__lowpassfiltered__ = True # Time Domain LALSimulation Waveform Approximant h_pluss and cross, but using nrutils data conventions def lswfa( apx ='IMRPhenomPv2', # Approximant name; must be compatible with lal convenions eta = None, # symmetric mass ratio chi1 = None, # spin1 iterable (Dimensionless) chi2 = None, # spin2 iterable (Dimensionless) fmin_hz = 30.0, # phys starting freq in Hz verbose = False ): # boolean toggle for verbosity # from numpy import array,linspace,double import lalsimulation as lalsim from nrutils import eta2q import lal # Standardize input mass ratio and convert to component masses M = 70.0 q = eta2q(eta) q = double(q) q = max( [q,1.0/q] ) m2 = M * 1.0 / (1.0+q) m1 = float(q) * m2 # NOTE IS THIS CORRECT???? S1 = array(chi1) S2 = array(chi2) # fmin_phys = fmin_hz M_total_phys = (m1+m2) * lal.MSUN_SI # TD_arguments = {'phiRef': 0.0, 'deltaT': 1.0 * M_total_phys * lal.MTSUN_SI / lal.MSUN_SI, 'f_min': fmin_phys, 'm1': m1 * lal.MSUN_SI, 'm2' : m2 * lal.MSUN_SI, 'S1x' : S1[0], 'S1y' : S1[1], 'S1z' : S1[2], 'S2x' : S2[0], 'S2y' : S2[1], 'S2z' : S2[2], 'f_ref': 100.0, 'r': lal.PC_SI, 'z': 0, 'i': 0, 'lambda1': 0, 'lambda2': 0, 'waveFlags': None, 'nonGRparams': None, 'amplitudeO': -1, 'phaseO': -1, 'approximant': lalsim.SimInspiralGetApproximantFromString(apx)} # # Use lalsimulation to calculate plus and cross in lslsim dataformat hp, hc = lalsim.SimInspiralTD(**TD_arguments) # Convert the lal datatype to a gwf object D = 1e-6 * TD_arguments['r']/lal.PC_SI y = lalsim2gwf( hp,hc,m1+m2, D ) # return y # Characterize END of time domain waveform (POST RINGDOWN) class gwfcharend: def __init__(this,ylm): # Import useful things from numpy import log # ROM (Ruduce order model) the post-peak as two lines la = log( ylm.amp[ ylm.k_amp_max: ]) tt = ylm.t[ ylm.k_amp_max: ] knots,rl = romline(tt,la,2) # Check for lack of noise floor (in the case of sims stopped before noise floor reached) # NOTE that in this case no effective windowing is applied this.nonoisefloor = knots[-1]+1 == len(tt) if this.nonoisefloor: msg = 'No noise floor found. This simulation may have been stopped before the numerical noise floor was reached.' warning(msg,'gwfcharend') # Define the start and end of the region to be windowed this.left_index = ylm.k_amp_max + knots[-1] this.right_index = ylm.k_amp_max + knots[-1]+(len(tt)-knots[-1])*6/10 # Calculate the window and store to the current object this.window_state = [ this.right_index, this.left_index ] this.window = maketaper( ylm.t, this.window_state ) # Characterize the START of a time domain waveform (PRE INSPIRAL) class gwfcharstart: # def __init__( this, # the object to be created y, # input gwf object who'se start behavior will be characterised shift = 2, # The size of the turn on region in units of waveform cycles. verbose = False ): # from numpy import arange,diff,where,array,ceil,mean from numpy import histogram as hist thisfun=this.__class__.__name__ # Take notes on what happens notes = [] # This algorithm estimates the start of the gravitational waveform -- after the initial junk radiation that is present within most raw NR output. The algorithm proceeds in the manner consistent with a time domain waveform. # Validate inputs if not isinstance(y,gwf): msg = 'First imput must be a '+cyan('gwf')+' object. Type %s found instead.' % type(y).__name__ error(msg,thisfun) # 1. Find the pre-peak portion of the waveform. val_mask = arange( y.k_amp_max ) # 2. Find the peak locations of the plus part. pks,pk_mask = findpeaks( y.cross[ val_mask ] ) pk_mask = pk_mask[ pks > y.amp[y.k_amp_max]*5e-4 ] # 3. Find the difference between the peaks D = diff(pk_mask) # If the waveform starts at its peak (e.g. in the case of ringdown) if len(D)==0: # this.left_index = 0 this.right_index = 0 this.left_dphi=this.center_dphi=this.right_dphi = y.dphi[this.right_index] this.peak_mask = [0] else: # 4. Find location of the first peak that is separated from its adjacent by greater than the largest value. This location is stored to start_map. start_map = find( D >= max(D) )[0] # 5. Determine the with of waveform turn on in indeces based on the results above. NOTE that the width is bound below by half the difference betwen the wf start and the wf peak locations. index_width = min( [ 1+pk_mask[start_map+shift]-pk_mask[start_map], 0.5*(1+y.k_amp_max-pk_mask[ start_map ]) ] ) # 6. Estimate where the waveform begins to turn on. This is approximately where the junk radiation ends. Note that this area will be very depressed upon windowing, so is can be j_id = pk_mask[ start_map ] # 7. Use all results thus far to construct this object this.left_index = int(j_id) # Where the initial junk radiation is thought to end this.right_index = int(j_id + index_width - 1) # If tapering is desired, then this index will be # the end of the tapered region. this.left_dphi = y.dphi[ this.left_index ] # A lowerbound estimate for the min frequency within # the waveform. this.right_dphi = y.dphi[ this.right_index ] # An upperbound estimate for the min frequency within # the waveform this.center_dphi = mean(y.dphi[ this.left_index:this.right_index ]) # A moderate estimate for the min frequency within they # waveform this.peak_mask = pk_mask # Construct related window this.window_state = [this.left_index,this.right_index] this.window = maketaper( y.t, this.window_state ) # Characterize the END of a time domain waveform: Where is the noise floor? def gwfend(): # return None # Function which converts lalsim waveform to gwf object def lalsim2gwf( hp,hc,M,D ): # from numpy import linspace,array,double,sqrt,hstack,zeros from nrutils.tools.unit.conversion import codeh # Extract plus and cross data. Divide out contribution from spherical harmonic towards NR scaling x = sYlm(-2,2,2,0,0) h_plus = hp.data.data/x h_cross = hc.data.data/x # Create time series data t = linspace( 0.0, (h_plus.size-1.0)*hp.deltaT, int(h_plus.size) ) # Create waveform harr = array( [t,h_plus,h_cross] ).T # Convert to code units, where Mtotal=1 harr = codeh( harr,M,D ) # Create gwf object h = gwf( harr, kind=r'$h^{\mathrm{lal}}_{22}$' ) # return h # Taper a waveform object def gwftaper( y, # gwf object to be windowed state, # Index values defining region to be tapered: # For state=[a,b], if a>b then the taper is 1 at b and 0 at a # if a<b, then the taper is 1 at a and 0 at b. plot = False, verbose = False): # Import useful things from numpy import ones from numpy import hanning as hann # Parse taper state a = state[0] b = state[-1] # Only proceed if a valid window is given proceed = True true_width = abs(b-a) twice_hann = hann( 2*true_width ) if b>a: true_hann = twice_hann[ :true_width ] elif a<b: true_hann = twice_hann[ true_width: ] else: proceed = False # Proceed (or not) with windowing window = ones( y.n ) if proceed: # Make the window window[ :min(state) ] = 0 window[ min(state) : max(state) ] = true_hann # Apply the window to the data and reset fields y.wfarr[:,1] *= window y.wfarr[:,2] *= window y.setfields() # return window
Cyberface/nrutils_dev
nrutils/core/nrsc.py
Python
mit
126,535
[ "Psi4" ]
f6afb9188450e2f026a9b84e412c74e42099800fb3014acbac9cb32bc2baac16
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """ Unit tests for the :class:`iris.experimental.ugrid.cf.CFUGridConnectivityVariable` class. todo: fold these tests into cf tests when experimental.ugrid is folded into standard behaviour. """ # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests # isort:skip import numpy as np from iris.experimental.ugrid.cf import CFUGridConnectivityVariable, logger from iris.experimental.ugrid.mesh import Connectivity from iris.tests.unit.experimental.ugrid.cf.test_CFUGridReader import ( netcdf_ugrid_variable, ) def named_variable(name): # Don't need to worry about dimensions or dtype for these tests. return netcdf_ugrid_variable(name, "", int) class TestIdentify(tests.IrisTest): def test_cf_identities(self): subject_name = "ref_subject" ref_subject = named_variable(subject_name) vars_common = { subject_name: ref_subject, "ref_not_subject": named_variable("ref_not_subject"), } # ONLY expecting ref_subject, excluding ref_not_subject. expected = { subject_name: CFUGridConnectivityVariable( subject_name, ref_subject ) } for identity in Connectivity.UGRID_CF_ROLES: ref_source = named_variable("ref_source") setattr(ref_source, identity, subject_name) vars_all = dict({"ref_source": ref_source}, **vars_common) result = CFUGridConnectivityVariable.identify(vars_all) self.assertDictEqual(expected, result) def test_duplicate_refs(self): subject_name = "ref_subject" ref_subject = named_variable(subject_name) ref_source_vars = { name: named_variable(name) for name in ("ref_source_1", "ref_source_2") } for var in ref_source_vars.values(): setattr(var, Connectivity.UGRID_CF_ROLES[0], subject_name) vars_all = dict( { subject_name: ref_subject, "ref_not_subject": named_variable("ref_not_subject"), }, **ref_source_vars, ) # ONLY expecting ref_subject, excluding ref_not_subject. expected = { subject_name: CFUGridConnectivityVariable( subject_name, ref_subject ) } result = CFUGridConnectivityVariable.identify(vars_all) self.assertDictEqual(expected, result) def test_two_cf_roles(self): subject_names = ("ref_subject_1", "ref_subject_2") ref_subject_vars = { name: named_variable(name) for name in subject_names } ref_source_vars = { name: named_variable(name) for name in ("ref_source_1", "ref_source_2") } for ix, var in enumerate(ref_source_vars.values()): setattr(var, Connectivity.UGRID_CF_ROLES[ix], subject_names[ix]) vars_all = dict( {"ref_not_subject": named_variable("ref_not_subject")}, **ref_subject_vars, **ref_source_vars, ) # Not expecting ref_not_subject. expected = { name: CFUGridConnectivityVariable(name, var) for name, var in ref_subject_vars.items() } result = CFUGridConnectivityVariable.identify(vars_all) self.assertDictEqual(expected, result) def test_two_part_ref_ignored(self): # Not expected to handle more than one variable for a connectivity # cf role - invalid UGRID. subject_name = "ref_subject" ref_source = named_variable("ref_source") setattr( ref_source, Connectivity.UGRID_CF_ROLES[0], subject_name + " foo" ) vars_all = { subject_name: named_variable(subject_name), "ref_not_subject": named_variable("ref_not_subject"), "ref_source": ref_source, } result = CFUGridConnectivityVariable.identify(vars_all) self.assertDictEqual({}, result) def test_string_type_ignored(self): subject_name = "ref_subject" ref_source = named_variable("ref_source") setattr(ref_source, Connectivity.UGRID_CF_ROLES[0], subject_name) vars_all = { subject_name: netcdf_ugrid_variable(subject_name, "", np.bytes_), "ref_not_subject": named_variable("ref_not_subject"), "ref_source": ref_source, } result = CFUGridConnectivityVariable.identify(vars_all) self.assertDictEqual({}, result) def test_ignore(self): subject_names = ("ref_subject_1", "ref_subject_2") ref_subject_vars = { name: named_variable(name) for name in subject_names } ref_source_vars = { name: named_variable(name) for name in ("ref_source_1", "ref_source_2") } for ix, var in enumerate(ref_source_vars.values()): setattr(var, Connectivity.UGRID_CF_ROLES[0], subject_names[ix]) vars_all = dict( {"ref_not_subject": named_variable("ref_not_subject")}, **ref_subject_vars, **ref_source_vars, ) # ONLY expect the subject variable that hasn't been ignored. expected_name = subject_names[0] expected = { expected_name: CFUGridConnectivityVariable( expected_name, ref_subject_vars[expected_name] ) } result = CFUGridConnectivityVariable.identify( vars_all, ignore=subject_names[1] ) self.assertDictEqual(expected, result) def test_target(self): subject_names = ("ref_subject_1", "ref_subject_2") ref_subject_vars = { name: named_variable(name) for name in subject_names } source_names = ("ref_source_1", "ref_source_2") ref_source_vars = {name: named_variable(name) for name in source_names} for ix, var in enumerate(ref_source_vars.values()): setattr(var, Connectivity.UGRID_CF_ROLES[0], subject_names[ix]) vars_all = dict( {"ref_not_subject": named_variable("ref_not_subject")}, **ref_subject_vars, **ref_source_vars, ) # ONLY expect the variable referenced by the named ref_source_var. expected_name = subject_names[0] expected = { expected_name: CFUGridConnectivityVariable( expected_name, ref_subject_vars[expected_name] ) } result = CFUGridConnectivityVariable.identify( vars_all, target=source_names[0] ) self.assertDictEqual(expected, result) def test_warn(self): subject_name = "ref_subject" ref_source = named_variable("ref_source") setattr(ref_source, Connectivity.UGRID_CF_ROLES[0], subject_name) vars_all = { "ref_not_subject": named_variable("ref_not_subject"), "ref_source": ref_source, } # The warn kwarg and expected corresponding log level. warn_and_level = {True: "WARNING", False: "DEBUG"} # Missing warning. log_regex = rf"Missing CF-UGRID connectivity variable {subject_name}.*" for warn, level in warn_and_level.items(): with self.assertLogs(logger, level=level, msg_regex=log_regex): result = CFUGridConnectivityVariable.identify( vars_all, warn=warn ) self.assertDictEqual({}, result) # String variable warning. log_regex = r".*is a CF-netCDF label variable.*" for warn, level in warn_and_level.items(): with self.assertLogs(logger, level=level, msg_regex=log_regex): vars_all[subject_name] = netcdf_ugrid_variable( subject_name, "", np.bytes_ ) result = CFUGridConnectivityVariable.identify( vars_all, warn=warn ) self.assertDictEqual({}, result)
SciTools/iris
lib/iris/tests/unit/experimental/ugrid/cf/test_CFUGridConnectivityVariable.py
Python
lgpl-3.0
8,277
[ "NetCDF" ]
51e28dbd815c1d27127c915f791ea60f00b5ad978dc2d4f9c7d3b47d675a2d3a
#!/usr/bin/env python2 # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import inspect, time from io import BytesIO from repr import repr from functools import partial from operator import itemgetter from calibre.db.tests.base import BaseTest # Utils {{{ class ET(object): def __init__(self, func_name, args, kwargs={}, old=None, legacy=None): self.func_name = func_name self.args, self.kwargs = args, kwargs self.old, self.legacy = old, legacy def __call__(self, test): old = self.old or test.init_old(test.cloned_library) legacy = self.legacy or test.init_legacy(test.cloned_library) oldres = getattr(old, self.func_name)(*self.args, **self.kwargs) newres = getattr(legacy, self.func_name)(*self.args, **self.kwargs) test.assertEqual(oldres, newres, 'Equivalence test for %s with args: %s and kwargs: %s failed' % ( self.func_name, repr(self.args), repr(self.kwargs))) self.retval = newres return newres def compare_argspecs(old, new, attr): # We dont compare the names of the non-keyword arguments as they are often # different and they dont affect the usage of the API. num = len(old.defaults or ()) ok = len(old.args) == len(new.args) and old.defaults == new.defaults and (num == 0 or old.args[-num:] == new.args[-num:]) if not ok: raise AssertionError('The argspec for %s does not match. %r != %r' % (attr, old, new)) def run_funcs(self, db, ndb, funcs): for func in funcs: meth, args = func[0], func[1:] if callable(meth): meth(*args) else: fmt = lambda x:x if meth[0] in {'!', '@', '#', '+', '$', '-', '%'}: if meth[0] != '+': fmt = {'!':dict, '@':lambda x:frozenset(x or ()), '#':lambda x:set((x or '').split(',')), '$':lambda x:set(tuple(y) for y in x), '-':lambda x:None, '%':lambda x: set((x or '').split(','))}[meth[0]] else: fmt = args[-1] args = args[:-1] meth = meth[1:] res1, res2 = fmt(getattr(db, meth)(*args)), fmt(getattr(ndb, meth)(*args)) self.assertEqual(res1, res2, 'The method: %s() returned different results for argument %s' % (meth, args)) # }}} class LegacyTest(BaseTest): ''' Test the emulation of the legacy interface. ''' def test_library_wide_properties(self): # {{{ 'Test library wide properties' def to_unicode(x): if isinstance(x, bytes): return x.decode('utf-8') if isinstance(x, dict): # We ignore the key rec_index, since it is not stable for # custom columns (it is created by iterating over a dict) return {k.decode('utf-8') if isinstance(k, bytes) else k:to_unicode(v) for k, v in x.iteritems() if k != 'rec_index'} return x def get_props(db): props = ('user_version', 'is_second_db', 'library_id', 'field_metadata', 'custom_column_label_map', 'custom_column_num_map', 'library_path', 'dbpath') fprops = ('last_modified', ) ans = {x:getattr(db, x) for x in props} ans.update({x:getattr(db, x)() for x in fprops}) ans['all_ids'] = frozenset(db.all_ids()) return to_unicode(ans) old = self.init_old() oldvals = get_props(old) old.close() del old db = self.init_legacy() newvals = get_props(db) self.assertEqual(oldvals, newvals) db.close() # }}} def test_get_property(self): # {{{ 'Test the get_property interface for reading data' def get_values(db): ans = {} for label, loc in db.FIELD_MAP.iteritems(): if isinstance(label, int): label = '#'+db.custom_column_num_map[label]['label'] label = type('')(label) ans[label] = tuple(db.get_property(i, index_is_id=True, loc=loc) for i in db.all_ids()) if label in ('id', 'title', '#tags'): with self.assertRaises(IndexError): db.get_property(9999, loc=loc) with self.assertRaises(IndexError): db.get_property(9999, index_is_id=True, loc=loc) if label in {'tags', 'formats'}: # Order is random in the old db for these ans[label] = tuple(set(x.split(',')) if x else x for x in ans[label]) if label == 'series_sort': # The old db code did not take book language into account # when generating series_sort values (the first book has # lang=deu) ans[label] = ans[label][1:] return ans old = self.init_old() old_vals = get_values(old) old.close() old = None db = self.init_legacy() new_vals = get_values(db) db.close() self.assertEqual(old_vals, new_vals) # }}} def test_refresh(self): # {{{ ' Test refreshing the view after a change to metadata.db ' db = self.init_legacy() db2 = self.init_legacy() # Ensure that the following change will actually update the timestamp # on filesystems with one second resolution (OS X) time.sleep(1) self.assertEqual(db2.data.cache.set_field('title', {1:'xxx'}), set([1])) db2.close() del db2 self.assertNotEqual(db.title(1, index_is_id=True), 'xxx') db.check_if_modified() self.assertEqual(db.title(1, index_is_id=True), 'xxx') # }}} def test_legacy_getters(self): # {{{ ' Test various functions to get individual bits of metadata ' old = self.init_old() getters = ('path', 'abspath', 'title', 'title_sort', 'authors', 'series', 'publisher', 'author_sort', 'authors', 'comments', 'comment', 'publisher', 'rating', 'series_index', 'tags', 'timestamp', 'uuid', 'pubdate', 'ondevice', 'metadata_last_modified', 'languages') oldvals = {g:tuple(getattr(old, g)(x) for x in xrange(3)) + tuple(getattr(old, g)(x, True) for x in (1,2,3)) for g in getters} old_rows = {tuple(r)[:5] for r in old} old.close() db = self.init_legacy() newvals = {g:tuple(getattr(db, g)(x) for x in xrange(3)) + tuple(getattr(db, g)(x, True) for x in (1,2,3)) for g in getters} new_rows = {tuple(r)[:5] for r in db} for x in (oldvals, newvals): x['tags'] = tuple(set(y.split(',')) if y else y for y in x['tags']) self.assertEqual(oldvals, newvals) self.assertEqual(old_rows, new_rows) # }}} def test_legacy_direct(self): # {{{ 'Test read-only methods that are directly equivalent in the old and new interface' from calibre.ebooks.metadata.book.base import Metadata from datetime import timedelta ndb = self.init_legacy(self.cloned_library) db = self.init_old() newstag = ndb.new_api.get_item_id('tags', 'news') self.assertEqual(dict(db.prefs), dict(ndb.prefs)) for meth, args in { 'find_identical_books': [(Metadata('title one', ['author one']),), (Metadata('unknown'),), (Metadata('xxxx'),)], 'get_books_for_category': [('tags', newstag), ('#formats', 'FMT1')], 'get_next_series_num_for': [('A Series One',)], 'get_id_from_uuid':[('ddddd',), (db.uuid(1, True),)], 'cover':[(0,), (1,), (2,)], 'get_author_id': [('author one',), ('unknown',), ('xxxxx',)], 'series_id': [(0,), (1,), (2,)], 'publisher_id': [(0,), (1,), (2,)], '@tags_older_than': [ ('News', None), ('Tag One', None), ('xxxx', None), ('Tag One', None, 'News'), ('News', None, 'xxxx'), ('News', None, None, ['xxxxxxx']), ('News', None, 'Tag One', ['Author Two', 'Author One']), ('News', timedelta(0), None, None), ('News', timedelta(100000)), ], 'format':[(1, 'FMT1', True), (2, 'FMT1', True), (0, 'xxxxxx')], 'has_format':[(1, 'FMT1', True), (2, 'FMT1', True), (0, 'xxxxxx')], 'sizeof_format':[(1, 'FMT1', True), (2, 'FMT1', True), (0, 'xxxxxx')], '@format_files':[(0,),(1,),(2,)], 'formats':[(0,),(1,),(2,)], 'max_size':[(0,),(1,),(2,)], 'format_hash':[(1, 'FMT1'),(1, 'FMT2'), (2, 'FMT1')], 'author_sort_from_authors': [(['Author One', 'Author Two', 'Unknown'],)], 'has_book':[(Metadata('title one'),), (Metadata('xxxx1111'),)], 'has_id':[(1,), (2,), (3,), (9999,)], 'id':[(1,), (2,), (0,),], 'index':[(1,), (2,), (3,), ], 'row':[(1,), (2,), (3,), ], 'is_empty':[()], 'count':[()], 'all_author_names':[()], 'all_tag_names':[()], 'all_series_names':[()], 'all_publisher_names':[()], '!all_authors':[()], '!all_tags2':[()], '@all_tags':[()], '@get_all_identifier_types':[()], '!all_publishers':[()], '!all_titles':[()], '!all_series':[()], 'standard_field_keys':[()], 'all_field_keys':[()], 'searchable_fields':[()], 'search_term_to_field_key':[('author',), ('tag',)], 'metadata_for_field':[('title',), ('tags',)], 'sortable_field_keys':[()], 'custom_field_keys':[(True,), (False,)], '!get_usage_count_by_id':[('authors',), ('tags',), ('series',), ('publisher',), ('#tags',), ('languages',)], 'get_field':[(1, 'title'), (2, 'tags'), (0, 'rating'), (1, 'authors'), (2, 'series'), (1, '#tags')], 'all_formats':[()], 'get_authors_with_ids':[()], '!get_tags_with_ids':[()], '!get_series_with_ids':[()], '!get_publishers_with_ids':[()], '!get_ratings_with_ids':[()], '!get_languages_with_ids':[()], 'tag_name':[(3,)], 'author_name':[(3,)], 'series_name':[(3,)], 'authors_sort_strings':[(0,), (1,), (2,)], 'author_sort_from_book':[(0,), (1,), (2,)], 'authors_with_sort_strings':[(0,), (1,), (2,)], 'book_on_device_string':[(1,), (2,), (3,)], 'books_in_series_of':[(0,), (1,), (2,)], 'books_with_same_title':[(Metadata(db.title(0)),), (Metadata(db.title(1)),), (Metadata('1234'),)], }.iteritems(): fmt = lambda x: x if meth[0] in {'!', '@'}: fmt = {'!':dict, '@':frozenset}[meth[0]] meth = meth[1:] elif meth == 'get_authors_with_ids': fmt = lambda val:{x[0]:tuple(x[1:]) for x in val} for a in args: self.assertEqual(fmt(getattr(db, meth)(*a)), fmt(getattr(ndb, meth)(*a)), 'The method: %s() returned different results for argument %s' % (meth, a)) def f(x, y): # get_top_level_move_items is broken in the old db on case-insensitive file systems x.discard('metadata_db_prefs_backup.json') return x, y self.assertEqual(f(*db.get_top_level_move_items()), f(*ndb.get_top_level_move_items())) d1, d2 = BytesIO(), BytesIO() db.copy_cover_to(1, d1, True) ndb.copy_cover_to(1, d2, True) self.assertTrue(d1.getvalue() == d2.getvalue()) d1, d2 = BytesIO(), BytesIO() db.copy_format_to(1, 'FMT1', d1, True) ndb.copy_format_to(1, 'FMT1', d2, True) self.assertTrue(d1.getvalue() == d2.getvalue()) old = db.get_data_as_dict(prefix='test-prefix') new = ndb.get_data_as_dict(prefix='test-prefix') for o, n in zip(old, new): o = {type('')(k) if isinstance(k, bytes) else k:set(v) if isinstance(v, list) else v for k, v in o.iteritems()} n = {k:set(v) if isinstance(v, list) else v for k, v in n.iteritems()} self.assertEqual(o, n) ndb.search('title:Unknown') db.search('title:Unknown') self.assertEqual(db.row(3), ndb.row(3)) self.assertRaises(ValueError, ndb.row, 2) self.assertRaises(ValueError, db.row, 2) db.close() # }}} def test_legacy_conversion_options(self): # {{{ 'Test conversion options API' ndb = self.init_legacy() db = self.init_old() all_ids = ndb.new_api.all_book_ids() op1 = {'xx':'yy'} for x in ( ('has_conversion_options', all_ids), ('conversion_options', 1, 'PIPE'), ('set_conversion_options', 1, 'PIPE', op1), ('has_conversion_options', all_ids), ('conversion_options', 1, 'PIPE'), ('delete_conversion_options', 1, 'PIPE'), ('has_conversion_options', all_ids), ): meth, args = x[0], x[1:] self.assertEqual((getattr(db, meth)(*args)), (getattr(ndb, meth)(*args)), 'The method: %s() returned different results for argument %s' % (meth, args)) db.close() # }}} def test_legacy_delete_using(self): # {{{ 'Test delete_using() API' ndb = self.init_legacy() db = self.init_old() cache = ndb.new_api tmap = cache.get_id_map('tags') t = next(tmap.iterkeys()) pmap = cache.get_id_map('publisher') p = next(pmap.iterkeys()) run_funcs(self, db, ndb, ( ('delete_tag_using_id', t), ('delete_publisher_using_id', p), (db.refresh,), ('all_tag_names',), ('tags', 0), ('tags', 1), ('tags', 2), ('all_publisher_names',), ('publisher', 0), ('publisher', 1), ('publisher', 2), )) db.close() # }}} def test_legacy_adding_books(self): # {{{ 'Test various adding/deleting books methods' from calibre.ebooks.metadata.book.base import Metadata from calibre.ptempfile import TemporaryFile legacy, old = self.init_legacy(self.cloned_library), self.init_old(self.cloned_library) mi = Metadata('Added Book0', authors=('Added Author',)) with TemporaryFile(suffix='.aff') as name: with open(name, 'wb') as f: f.write(b'xxx') T = partial(ET, 'add_books', ([name], ['AFF'], [mi]), old=old, legacy=legacy) T()(self) book_id = T(kwargs={'return_ids':True})(self)[1][0] self.assertEqual(legacy.new_api.formats(book_id), ('AFF',)) T(kwargs={'add_duplicates':False})(self) mi.title = 'Added Book1' mi.uuid = 'uuu' T = partial(ET, 'import_book', (mi,[name]), old=old, legacy=legacy) book_id = T()(self) self.assertNotEqual(legacy.uuid(book_id, index_is_id=True), old.uuid(book_id, index_is_id=True)) book_id = T(kwargs={'preserve_uuid':True})(self) self.assertEqual(legacy.uuid(book_id, index_is_id=True), old.uuid(book_id, index_is_id=True)) self.assertEqual(legacy.new_api.formats(book_id), ('AFF',)) T = partial(ET, 'add_format', old=old, legacy=legacy) T((0, 'AFF', BytesIO(b'fffff')))(self) T((0, 'AFF', BytesIO(b'fffff')))(self) T((0, 'AFF', BytesIO(b'fffff')), {'replace':True})(self) with TemporaryFile(suffix='.opf') as name: with open(name, 'wb') as f: f.write(b'zzzz') T = partial(ET, 'import_book', (mi,[name]), old=old, legacy=legacy) book_id = T()(self) self.assertFalse(legacy.new_api.formats(book_id)) mi.title = 'Added Book2' T = partial(ET, 'create_book_entry', (mi,), old=old, legacy=legacy) T() T({'add_duplicates':False}) T({'force_id':1000}) with TemporaryFile(suffix='.txt') as name: with open(name, 'wb') as f: f.write(b'tttttt') bid = legacy.add_catalog(name, 'My Catalog') self.assertEqual(old.add_catalog(name, 'My Catalog'), bid) cache = legacy.new_api self.assertEqual(cache.formats(bid), ('TXT',)) self.assertEqual(cache.field_for('title', bid), 'My Catalog') self.assertEqual(cache.field_for('authors', bid), ('calibre',)) self.assertEqual(cache.field_for('tags', bid), (_('Catalog'),)) self.assertTrue(bid < legacy.add_catalog(name, 'Something else')) self.assertEqual(legacy.add_catalog(name, 'My Catalog'), bid) self.assertEqual(old.add_catalog(name, 'My Catalog'), bid) bid = legacy.add_news(name, {'title':'Events', 'add_title_tag':True, 'custom_tags':('one', 'two')}) self.assertEqual(cache.formats(bid), ('TXT',)) self.assertEqual(cache.field_for('authors', bid), ('calibre',)) self.assertEqual(cache.field_for('tags', bid), (_('News'), 'Events', 'one', 'two')) self.assertTrue(legacy.cover(1, index_is_id=True)) origcov = legacy.cover(1, index_is_id=True) self.assertTrue(legacy.has_cover(1)) legacy.remove_cover(1) self.assertFalse(legacy.has_cover(1)) self.assertFalse(legacy.cover(1, index_is_id=True)) legacy.set_cover(3, origcov) self.assertEqual(legacy.cover(3, index_is_id=True), origcov) self.assertTrue(legacy.has_cover(3)) self.assertTrue(legacy.format(1, 'FMT1', index_is_id=True)) legacy.remove_format(1, 'FMT1', index_is_id=True) self.assertIsNone(legacy.format(1, 'FMT1', index_is_id=True)) legacy.delete_book(1) old.delete_book(1) self.assertNotIn(1, legacy.all_ids()) legacy.dump_metadata((2,3)) old.close() # }}} def test_legacy_coverage(self): # {{{ ' Check that the emulation of the legacy interface is (almost) total ' cl = self.cloned_library db = self.init_old(cl) ndb = self.init_legacy() SKIP_ATTRS = { 'TCat_Tag', '_add_newbook_tag', '_clean_identifier', '_library_id_', '_set_authors', '_set_title', '_set_custom', '_update_author_in_cache', # Feeds are now stored in the config folder 'get_feeds', 'get_feed', 'update_feed', 'remove_feeds', 'add_feed', 'set_feeds', # Obsolete/broken methods 'author_id', # replaced by get_author_id 'books_for_author', # broken 'books_in_old_database', 'sizeof_old_database', # unused 'migrate_old', # no longer supported 'remove_unused_series', # superseded by clean API 'move_library_to', # API changed, no code uses old API # Internal API 'clean_user_categories', 'cleanup_tags', 'books_list_filter', 'conn', 'connect', 'construct_file_name', 'construct_path_name', 'clear_dirtied', 'initialize_database', 'initialize_dynamic', 'run_import_plugins', 'vacuum', 'set_path', 'row_factory', 'rows', 'rmtree', 'series_index_pat', 'import_old_database', 'dirtied_lock', 'dirtied_cache', 'dirty_books_referencing', 'windows_check_if_files_in_use', 'get_metadata_for_dump', 'get_a_dirtied_book', 'dirtied_sequence', 'format_filename_cache', 'format_metadata_cache', 'filter', 'create_version1', 'normpath', 'custom_data_adapters', 'custom_table_names', 'custom_columns_in_meta', 'custom_tables', } SKIP_ARGSPEC = { '__init__', } missing = [] try: total = 0 for attr in dir(db): if attr in SKIP_ATTRS or attr.startswith('upgrade_version'): continue total += 1 if not hasattr(ndb, attr): missing.append(attr) continue obj, nobj = getattr(db, attr), getattr(ndb, attr) if attr not in SKIP_ARGSPEC: try: argspec = inspect.getargspec(obj) nargspec = inspect.getargspec(nobj) except TypeError: pass else: compare_argspecs(argspec, nargspec, attr) finally: for db in (ndb, db): db.close() db.break_cycles() if missing: pc = len(missing)/total raise AssertionError('{0:.1%} of API ({2} attrs) are missing: {1}'.format(pc, ', '.join(missing), len(missing))) # }}} def test_legacy_custom_data(self): # {{{ 'Test the API for custom data storage' legacy, old = self.init_legacy(self.cloned_library), self.init_old(self.cloned_library) for name in ('name1', 'name2', 'name3'): T = partial(ET, 'add_custom_book_data', old=old, legacy=legacy) T((1, name, 'val1'))(self) T((2, name, 'val2'))(self) T((3, name, 'val3'))(self) T = partial(ET, 'get_ids_for_custom_book_data', old=old, legacy=legacy) T((name,))(self) T = partial(ET, 'get_custom_book_data', old=old, legacy=legacy) T((1, name, object())) T((9, name, object())) T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy) T((name, object())) T((name+'!', object())) T = partial(ET, 'delete_custom_book_data', old=old, legacy=legacy) T((name, 1)) T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy) T((name, object())) T = partial(ET, 'delete_all_custom_book_data', old=old, legacy=legacy) T((name)) T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy) T((name, object())) T = partial(ET, 'add_multiple_custom_book_data', old=old, legacy=legacy) T(('n', {1:'val1', 2:'val2'}))(self) T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy) T(('n', object())) old.close() # }}} def test_legacy_setters(self): # {{{ 'Test methods that are directly equivalent in the old and new interface' from calibre.ebooks.metadata.book.base import Metadata from calibre.utils.date import now n = now() ndb = self.init_legacy(self.cloned_library) amap = ndb.new_api.get_id_map('authors') sorts = [(aid, 's%d' % aid) for aid in amap] db = self.init_old(self.cloned_library) run_funcs(self, db, ndb, ( ('+format_metadata', 1, 'FMT1', itemgetter('size')), ('+format_metadata', 1, 'FMT2', itemgetter('size')), ('+format_metadata', 2, 'FMT1', itemgetter('size')), ('get_tags', 0), ('get_tags', 1), ('get_tags', 2), ('is_tag_used', 'News'), ('is_tag_used', 'xchkjgfh'), ('bulk_modify_tags', (1,), ['t1'], ['News']), ('bulk_modify_tags', (2,), ['t1'], ['Tag One', 'Tag Two']), ('bulk_modify_tags', (3,), ['t1', 't2', 't3']), (db.clean,), ('@all_tags',), ('@tags', 0), ('@tags', 1), ('@tags', 2), ('unapply_tags', 1, ['t1']), ('unapply_tags', 2, ['xxxx']), ('unapply_tags', 3, ['t2', 't3']), (db.clean,), ('@all_tags',), ('@tags', 0), ('@tags', 1), ('@tags', 2), ('update_last_modified', (1,), True, n), ('update_last_modified', (3,), True, n), ('metadata_last_modified', 1, True), ('metadata_last_modified', 3, True), ('set_sort_field_for_author', sorts[0][0], sorts[0][1]), ('set_sort_field_for_author', sorts[1][0], sorts[1][1]), ('set_sort_field_for_author', sorts[2][0], sorts[2][1]), ('set_link_field_for_author', sorts[0][0], sorts[0][1]), ('set_link_field_for_author', sorts[1][0], sorts[1][1]), ('set_link_field_for_author', sorts[2][0], sorts[2][1]), (db.refresh,), ('author_sort', 0), ('author_sort', 1), ('author_sort', 2), )) omi = [db.get_metadata(x) for x in (0, 1, 2)] nmi = [ndb.get_metadata(x) for x in (0, 1, 2)] self.assertEqual([x.author_sort_map for x in omi], [x.author_sort_map for x in nmi]) self.assertEqual([x.author_link_map for x in omi], [x.author_link_map for x in nmi]) db.close() ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) run_funcs(self, db, ndb, ( ('set_authors', 1, ('author one',),), ('set_authors', 2, ('author two',), True, True, True), ('set_author_sort', 3, 'new_aus'), ('set_comment', 1, ''), ('set_comment', 2, None), ('set_comment', 3, '<p>a comment</p>'), ('set_has_cover', 1, True), ('set_has_cover', 2, True), ('set_has_cover', 3, 1), ('set_identifiers', 2, {'test':'', 'a':'b'}), ('set_identifiers', 3, {'id':'1', 'isbn':'9783161484100'}), ('set_identifiers', 1, {}), ('set_languages', 1, ('en',)), ('set_languages', 2, ()), ('set_languages', 3, ('deu', 'spa', 'fra')), ('set_pubdate', 1, None), ('set_pubdate', 2, '2011-1-7'), ('set_series', 1, 'a series one'), ('set_series', 2, 'another series [7]'), ('set_series', 3, 'a third series'), ('set_publisher', 1, 'publisher two'), ('set_publisher', 2, None), ('set_publisher', 3, 'a third puB'), ('set_rating', 1, 2.3), ('set_rating', 2, 0), ('set_rating', 3, 8), ('set_timestamp', 1, None), ('set_timestamp', 2, '2011-1-7'), ('set_uuid', 1, None), ('set_uuid', 2, 'a test uuid'), ('set_title', 1, 'title two'), ('set_title', 2, None), ('set_title', 3, 'The Test Title'), ('set_tags', 1, ['a1', 'a2'], True), ('set_tags', 2, ['b1', 'tag one'], False, False, False, True), ('set_tags', 3, ['A1']), (db.refresh,), ('title', 0), ('title', 1), ('title', 2), ('title_sort', 0), ('title_sort', 1), ('title_sort', 2), ('authors', 0), ('authors', 1), ('authors', 2), ('author_sort', 0), ('author_sort', 1), ('author_sort', 2), ('has_cover', 3), ('has_cover', 1), ('has_cover', 2), ('get_identifiers', 0), ('get_identifiers', 1), ('get_identifiers', 2), ('pubdate', 0), ('pubdate', 1), ('pubdate', 2), ('timestamp', 0), ('timestamp', 1), ('timestamp', 2), ('publisher', 0), ('publisher', 1), ('publisher', 2), ('rating', 0), ('+rating', 1, lambda x: x or 0), ('rating', 2), ('series', 0), ('series', 1), ('series', 2), ('series_index', 0), ('series_index', 1), ('series_index', 2), ('uuid', 0), ('uuid', 1), ('uuid', 2), ('isbn', 0), ('isbn', 1), ('isbn', 2), ('@tags', 0), ('@tags', 1), ('@tags', 2), ('@all_tags',), ('@get_all_identifier_types',), ('set_title_sort', 1, 'Title Two'), ('set_title_sort', 2, None), ('set_title_sort', 3, 'The Test Title_sort'), ('set_series_index', 1, 2.3), ('set_series_index', 2, 0), ('set_series_index', 3, 8), ('set_identifier', 1, 'moose', 'val'), ('set_identifier', 2, 'test', ''), ('set_identifier', 3, '', ''), (db.refresh,), ('series_index', 0), ('series_index', 1), ('series_index', 2), ('title_sort', 0), ('title_sort', 1), ('title_sort', 2), ('get_identifiers', 0), ('get_identifiers', 1), ('get_identifiers', 2), ('@get_all_identifier_types',), ('set_metadata', 1, Metadata('title', ('a1',)), False, False, False, True, True), ('set_metadata', 3, Metadata('title', ('a1',))), (db.refresh,), ('title', 0), ('title', 1), ('title', 2), ('title_sort', 0), ('title_sort', 1), ('title_sort', 2), ('authors', 0), ('authors', 1), ('authors', 2), ('author_sort', 0), ('author_sort', 1), ('author_sort', 2), ('@tags', 0), ('@tags', 1), ('@tags', 2), ('@all_tags',), ('@get_all_identifier_types',), )) db.close() ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) run_funcs(self, db, ndb, ( ('set', 0, 'title', 'newtitle'), ('set', 0, 'tags', 't1,t2,tag one', True), ('set', 0, 'authors', 'author one & Author Two', True), ('set', 0, 'rating', 3.2), ('set', 0, 'publisher', 'publisher one', False), (db.refresh,), ('title', 0), ('rating', 0), ('#tags', 0), ('#tags', 1), ('#tags', 2), ('authors', 0), ('authors', 1), ('authors', 2), ('publisher', 0), ('publisher', 1), ('publisher', 2), ('delete_tag', 'T1'), ('delete_tag', 'T2'), ('delete_tag', 'Tag one'), ('delete_tag', 'News'), (db.clean,), (db.refresh,), ('@all_tags',), ('#tags', 0), ('#tags', 1), ('#tags', 2), )) db.close() ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) run_funcs(self, db, ndb, ( ('remove_all_tags', (1, 2, 3)), (db.clean,), ('@all_tags',), ('@tags', 0), ('@tags', 1), ('@tags', 2), )) db.close() ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) a = {v:k for k, v in ndb.new_api.get_id_map('authors').iteritems()}['Author One'] t = {v:k for k, v in ndb.new_api.get_id_map('tags').iteritems()}['Tag One'] s = {v:k for k, v in ndb.new_api.get_id_map('series').iteritems()}['A Series One'] p = {v:k for k, v in ndb.new_api.get_id_map('publisher').iteritems()}['Publisher One'] run_funcs(self, db, ndb, ( ('rename_author', a, 'Author Two'), ('rename_tag', t, 'News'), ('rename_series', s, 'ss'), ('rename_publisher', p, 'publisher one'), (db.clean,), (db.refresh,), ('@all_tags',), ('tags', 0), ('tags', 1), ('tags', 2), ('series', 0), ('series', 1), ('series', 2), ('publisher', 0), ('publisher', 1), ('publisher', 2), ('series_index', 0), ('series_index', 1), ('series_index', 2), ('authors', 0), ('authors', 1), ('authors', 2), ('author_sort', 0), ('author_sort', 1), ('author_sort', 2), )) db.close() # }}} def test_legacy_custom(self): # {{{ 'Test the legacy API for custom columns' ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) # Test getting run_funcs(self, db, ndb, ( ('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'rating'), ('all_custom', 'authors'), ('all_custom', None, 7), ('get_next_cc_series_num_for', 'My Series One', 'series'), ('get_next_cc_series_num_for', 'My Series Two', 'series'), ('is_item_used_in_multiple', 'My Tag One', 'tags'), ('is_item_used_in_multiple', 'My Series One', 'series'), ('$get_custom_items_with_ids', 'series'), ('$get_custom_items_with_ids', 'tags'), ('$get_custom_items_with_ids', 'float'), ('$get_custom_items_with_ids', 'rating'), ('$get_custom_items_with_ids', 'authors'), ('$get_custom_items_with_ids', None, 7), )) for label in ('tags', 'series', 'authors', 'comments', 'rating', 'date', 'yesno', 'isbn', 'enum', 'formats', 'float', 'comp_tags'): for func in ('get_custom', 'get_custom_extra', 'get_custom_and_extra'): run_funcs(self, db, ndb, [(func, idx, label) for idx in range(3)]) # Test renaming/deleting t = {v:k for k, v in ndb.new_api.get_id_map('#tags').iteritems()}['My Tag One'] t2 = {v:k for k, v in ndb.new_api.get_id_map('#tags').iteritems()}['My Tag Two'] a = {v:k for k, v in ndb.new_api.get_id_map('#authors').iteritems()}['My Author Two'] a2 = {v:k for k, v in ndb.new_api.get_id_map('#authors').iteritems()}['Custom One'] s = {v:k for k, v in ndb.new_api.get_id_map('#series').iteritems()}['My Series One'] run_funcs(self, db, ndb, ( ('delete_custom_item_using_id', t, 'tags'), ('delete_custom_item_using_id', a, 'authors'), ('rename_custom_item', t2, 't2', 'tags'), ('rename_custom_item', a2, 'custom one', 'authors'), ('rename_custom_item', s, 'My Series Two', 'series'), ('delete_item_from_multiple', 'custom two', 'authors'), (db.clean,), (db.refresh,), ('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'authors'), )) for label in ('tags', 'authors', 'series'): run_funcs(self, db, ndb, [('get_custom_and_extra', idx, label) for idx in range(3)]) db.close() ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) # Test setting run_funcs(self, db, ndb, ( ('-set_custom', 1, 't1 & t2', 'authors'), ('-set_custom', 1, 't3 & t4', 'authors', None, True), ('-set_custom', 3, 'test one & test Two', 'authors'), ('-set_custom', 1, 'ijfkghkjdf', 'enum'), ('-set_custom', 3, 'One', 'enum'), ('-set_custom', 3, 'xxx', 'formats'), ('-set_custom', 1, 'my tag two', 'tags', None, False, False, None, True, True), (db.clean,), (db.refresh,), ('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'authors'), )) for label in ('tags', 'series', 'authors', 'comments', 'rating', 'date', 'yesno', 'isbn', 'enum', 'formats', 'float', 'comp_tags'): for func in ('get_custom', 'get_custom_extra', 'get_custom_and_extra'): run_funcs(self, db, ndb, [(func, idx, label) for idx in range(3)]) db.close() ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) # Test setting bulk run_funcs(self, db, ndb, ( ('set_custom_bulk', (1,2,3), 't1 & t2', 'authors'), ('set_custom_bulk', (1,2,3), 'a series', 'series', None, False, False, (9, 10, 11)), ('set_custom_bulk', (1,2,3), 't1', 'tags', None, True), (db.clean,), (db.refresh,), ('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'authors'), )) for label in ('tags', 'series', 'authors', 'comments', 'rating', 'date', 'yesno', 'isbn', 'enum', 'formats', 'float', 'comp_tags'): for func in ('get_custom', 'get_custom_extra', 'get_custom_and_extra'): run_funcs(self, db, ndb, [(func, idx, label) for idx in range(3)]) db.close() ndb = self.init_legacy(self.cloned_library) db = self.init_old(self.cloned_library) # Test bulk multiple run_funcs(self, db, ndb, ( ('set_custom_bulk_multiple', (1,2,3), ['t1'], ['My Tag One'], 'tags'), (db.clean,), (db.refresh,), ('all_custom', 'tags'), ('get_custom', 0, 'tags'), ('get_custom', 1, 'tags'), ('get_custom', 2, 'tags'), )) db.close() o = self.cloned_library n = self.cloned_library ndb, db = self.init_legacy(n), self.init_old(o) ndb.create_custom_column('created', 'Created', 'text', True, True, {'moose':'cat'}) db.create_custom_column('created', 'Created', 'text', True, True, {'moose':'cat'}) db.close() ndb, db = self.init_legacy(n), self.init_old(o) self.assertEqual(db.custom_column_label_map['created'], ndb.backend.custom_field_metadata('created')) num = db.custom_column_label_map['created']['num'] ndb.set_custom_column_metadata(num, is_editable=False, name='Crikey', display={}) db.set_custom_column_metadata(num, is_editable=False, name='Crikey', display={}) db.close() ndb, db = self.init_legacy(n), self.init_old(o) self.assertEqual(db.custom_column_label_map['created'], ndb.backend.custom_field_metadata('created')) db.close() ndb = self.init_legacy(n) ndb.delete_custom_column('created') ndb = self.init_legacy(n) self.assertRaises(KeyError, ndb.custom_field_name, num=num) # Test setting custom series ndb = self.init_legacy(self.cloned_library) ndb.set_custom(1, 'TS [9]', label='series') self.assertEqual(ndb.new_api.field_for('#series', 1), 'TS') self.assertEqual(ndb.new_api.field_for('#series_index', 1), 9) # }}} def test_legacy_original_fmt(self): # {{{ db, ndb = self.init_old(), self.init_legacy() run_funcs(self, db, ndb, ( ('original_fmt', 1, 'FMT1'), ('save_original_format', 1, 'FMT1'), ('original_fmt', 1, 'FMT1'), ('restore_original_format', 1, 'ORIGINAL_FMT1'), ('original_fmt', 1, 'FMT1'), ('%formats', 1, True), )) db.close() # }}} def test_legacy_saved_search(self): # {{{ ' Test legacy saved search API ' db, ndb = self.init_old(), self.init_legacy() run_funcs(self, db, ndb, ( ('saved_search_set_all', {'one':'a', 'two':'b'}), ('saved_search_names',), ('saved_search_lookup', 'one'), ('saved_search_lookup', 'two'), ('saved_search_lookup', 'xxx'), ('saved_search_rename', 'one', '1'), ('saved_search_names',), ('saved_search_lookup', '1'), ('saved_search_delete', '1'), ('saved_search_names',), ('saved_search_add', 'n', 'm'), ('saved_search_names',), ('saved_search_lookup', 'n'), )) db.close() # }}}
hazrpg/calibre
src/calibre/db/tests/legacy.py
Python
gpl-3.0
38,815
[ "MOOSE" ]
4df5b3610b9efc168792521389fbd69c43aa39bda775b403463e24f6ed74931b
#!/usr/bin/env python """A kernel that creates a new ASCII file with a given size and name. """ __author__ = "The ExTASY project <vivek.balasubramanian@rutgers.edu>" __copyright__ = "Copyright 2015, http://www.extasy-project.org/" __license__ = "MIT" from copy import deepcopy from radical.ensemblemd.exceptions import ArgumentError from radical.ensemblemd.exceptions import NoKernelConfigurationError from radical.ensemblemd.engine import get_engine from radical.ensemblemd.kernel_plugins.kernel_base import KernelBase # ------------------------------------------------------------------------------ _KERNEL_INFO = { "name": "custom.amber", "description": "Molecular Dynamics with Amber software package http://ambermd.org/", "arguments": {"--mininfile=": { "mandatory": False, "description": "Input parameter filename" }, "--mdinfile=": { "mandatory": False, "description": "Input parameter filename" }, "--topfile=": { "mandatory": False, "description": "Input topology filename" }, "--crdfile=": { "mandatory": False, "description": "Input coordinate filename" }, "--cycle=": { "mandatory": False, "description": "Cycle number" } }, "machine_configs": { "xsede.stampede": { "environment" : {}, "pre_exec" : ["module load TACC", "module load amber/12.0"], "executable" : ["/opt/apps/intel13/mvapich2_1_9/amber/12.0/bin/sander"], "uses_mpi" : False }, "epsrc.archer": { "environment" : {}, "pre_exec" : ["module load packages-archer","module load amber"], "executable" : ["pmemd"], "uses_mpi" : True }, } } # ------------------------------------------------------------------------------ # class kernel_amber(KernelBase): def __init__(self): super(kernel_amber, self).__init__(_KERNEL_INFO) """Le constructor.""" # -------------------------------------------------------------------------- # @staticmethod def get_name(): return _KERNEL_INFO["name"] def _bind_to_resource(self, resource_key): if resource_key not in _KERNEL_INFO["machine_configs"]: if "*" in _KERNEL_INFO["machine_configs"]: # Fall-back to generic resource key resource_key = "*" else: raise NoKernelConfigurationError(kernel_name=_KERNEL_INFO["name"], resource_key=resource_key) cfg = _KERNEL_INFO["machine_configs"][resource_key] #change to pmemd.MPI by splitting into two kernels if self.get_arg("--mininfile=") is not None: arguments = [ '-O', '-i',self.get_arg("--mininfile="), '-o','min%s.out'%self.get_arg("--cycle="), '-inf','min%s.inf'%self.get_arg("--cycle="), '-r','md%s.crd'%self.get_arg("--cycle="), '-p',self.get_arg("--topfile="), '-c',self.get_arg("--crdfile="), '-ref','min%s.crd'%self.get_arg("--cycle=") ] else: arguments = [ '-O', '-i',self.get_arg("--mdinfile="), '-o','md%s.out'%self.get_arg("--cycle="), '-inf','md%s.inf'%self.get_arg("--cycle="), '-x','md%s.ncdf'%self.get_arg("--cycle="), '-r','md%s.rst'%self.get_arg("--cycle="), '-p',self.get_arg("--topfile="), '-c','md%s.crd'%self.get_arg("--cycle="), ] self._executable = cfg["executable"] self._arguments = arguments self._environment = cfg["environment"] self._uses_mpi = False self._pre_exec = cfg["pre_exec"] # ------------------------------------------------------------------------------
radical-cybertools/ExTASY
examples/coam-on-stampede/kernel_defs/amber.py
Python
mit
4,751
[ "Amber" ]
b314fc602f4c55f71f01df85c814fa53349928b5a975d8ec14bdca2524b25ffe
import librosa from functools import partial import numpy as np from librosa.core.spectrum import stft PADDING = 0.1 def load_waveform(file_path, begin=None, end=None): """ Load a waveform segment from an audio file Parameters ---------- file_path : str Path to audio file begin : float Time stamp of beginning of segment end : float Time stamp of end of segment Returns ------- numpy.array Signal data int Sample rate """ if begin is None: begin = 0.0 duration = None if end is not None: duration = end - begin signal, sr = librosa.load(file_path, sr=None, offset=begin, duration=duration) signal = lfilter([1., -0.95], 1, signal, axis=0) return signal, sr def generate_spectrogram(signal, sr, log_color_scale=True): """ Generate a spectrogram Parameters ---------- signal : numpy.array Signal to generate spectrogram from sr : int Sample rate of the signal log_color_scale : bool Flag to make the color scale logarithmic Returns ------- numpy.array Spectrogram data float Time step between frames float Frequency step between bins """ from scipy.signal import lfilter from scipy.signal import gaussian n_fft = 256 # if len(self._signal) / self._sr > 30: window_length = 0.005 win_len = int(window_length * sr) if win_len > n_fft: n_fft = win_len num_steps = 500 if len(signal) < num_steps: num_steps = len(signal) step_samp = int(len(signal) / num_steps) time_step = step_samp / sr freq_step = sr / n_fft # if step_samp < 28: # step_samp = 28 # step = step_samp / self._sr # self._n_fft = 512 # window = partial(gaussian, std = 250/12) window = 'gaussian' # win_len = None if window == 'gaussian': window = partial(gaussian, std=0.45 * win_len / 2) data = stft(signal, n_fft, step_samp, center=True, win_length=win_len, window=window) data = np.abs(data) if log_color_scale: data = 20 * np.log10(data) return data, time_step, freq_step def make_path_safe(path): """ Make a path safe for use in Cypher Parameters ---------- path : str Path to sanitize Returns ------- str Cypher-safe path """ return path.replace('\\', '/').replace(' ', '%20')
PhonologicalCorpusTools/PolyglotDB
polyglotdb/acoustics/utils.py
Python
mit
2,476
[ "Gaussian" ]
ad24a8825922a433c5632d10f0ef0aeedd413a9220ddb4f0dffbfe71323dc61e
# # dnfhelper.py # # Copyright (C) 2010-2015 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Red Hat Author(s): Martin Gracik <mgracik@redhat.com> # Brian C. Lane <bcl@redhat.com> # import logging logger = logging.getLogger("pylorax.dnfhelper") import dnf import collections import time import pylorax.output as output __all__ = ['LoraxDownloadCallback', 'LoraxRpmCallback'] def _paced(fn): """Execute `fn` no more often then every 2 seconds.""" def paced_fn(self, *args): now = time.time() if now - self.last_time < 2: return self.last_time = now return fn(self, *args) return paced_fn class LoraxDownloadCallback(dnf.callback.DownloadProgress): def __init__(self): self.downloads = collections.defaultdict(int) self.last_time = time.time() self.total_files = 0 self.total_size = 0 self.pkgno = 0 self.total = 0 self.output = output.LoraxOutput() @_paced def _update(self): msg = "Downloading %(pkgno)s / %(total_files)s RPMs, " \ "%(downloaded)s / %(total_size)s (%(percent)d%%) done.\n" downloaded = sum(self.downloads.values()) vals = { 'downloaded' : downloaded, 'percent' : int(100 * downloaded/self.total_size), 'pkgno' : self.pkgno, 'total_files' : self.total_files, 'total_size' : self.total_size } self.output.write(msg % vals) def end(self, payload, status, msg): nevra = str(payload) if status is dnf.callback.STATUS_OK: self.downloads[nevra] = payload.download_size self.pkgno += 1 self._update() return logger.critical("Failed to download '%s': %d - %s", nevra, status, msg) def progress(self, payload, done): nevra = str(payload) self.downloads[nevra] = done self._update() # dnf 2.5.0 adds a new argument, accept it if it is passed # pylint: disable=arguments-differ def start(self, total_files, total_size, total_drpms=0): self.total_files = total_files self.total_size = total_size class LoraxRpmCallback(dnf.callback.TransactionProgress): def __init__(self): super(LoraxRpmCallback, self).__init__() self._last_ts = None def progress(self, package, action, ti_done, ti_total, ts_done, ts_total): if action == self.PKG_INSTALL: # do not report same package twice if self._last_ts == ts_done: return self._last_ts = ts_done msg = '(%d/%d) %s' % (ts_done, ts_total, package) logger.info(msg) elif action == self.TRANS_POST: msg = "Performing post-installation setup tasks" logger.info(msg) def error(self, message): logger.warning(message)
maxamillion/lorax
src/pylorax/dnfhelper.py
Python
gpl-2.0
3,533
[ "Brian" ]
97f9e164791f9e7698137e16be8d1484eba7ae5a9ae5286c83cfc8624596fcd6
import sip import os from PyQt5.QtWidgets import QTabWidget, QWidget, QGridLayout, QLabel, QPushButton, QComboBox, QLineEdit, QCheckBox, \ QFileDialog from PyQt5.QtCore import pyqtSignal from .Plotters import * from .ErrorBox import ErrorBox from .ErrorMessages import ErrorMessages class ExportTabWidget(QTabWidget): """Widget for data exporting purposes.""" valueUpdated = pyqtSignal(str, str) def __init__(self, parent=None): super(ExportTabWidget, self).__init__(parent) self.checkboxes = [] self.keys = [] self.checkboxdict = [] self.tab1 = QWidget() self.tab2 = QWidget() self.tab3 = QWidget() self.tab4 = QWidget() self.tab5 = QWidget() self.grid1 = QGridLayout() self.grid2 = QGridLayout() self.grid3 = QGridLayout() self.grid4 = QGridLayout() self.addTab(self.tab1, "View") self.addTab(self.tab2, "Histogram") self.addTab(self.tab3, "Contact Map") self.addTab(self.tab4, "VMD") self.addTab(self.tab5, "Plain Text") self.tab1UI() self.tab2UI() self.tab3UI() self.tab4UI() self.tab5UI() self.setWindowTitle("Export") self.contacts = [] self.threshold = 0 self.nsPerFrame = 0 self.map1 = None self.map2 = None self.label1 = "" self.label2 = "" self.psf = "" self.dcd = "" def setThresholdAndNsPerFrame(self, currentThreshold, currentNsPerFrame): self.threshold = currentThreshold self.nsPerFrame = currentNsPerFrame def tab1UI(self): """Tab where the current view can be exported to file.""" grid = QGridLayout() self.tab1.setLayout(grid) self.tab1.exportLabel = QLabel("Export current view: ") self.tab1.saveButton = QPushButton("Export") self.tab1.saveButton.setAutoDefault(False) self.tab1.saveButton.clicked.connect(self.pushSave) self.tab1.formatBox = QComboBox() self.tab1.formatBox.addItem("PNG") self.tab1.formatBox.addItem("SVG") grid.addWidget(self.tab1.exportLabel, 0, 0) grid.addWidget(self.tab1.saveButton, 0, 1) grid.addWidget(self.tab1.formatBox, 2, 0) def tab2UI(self): """Tab where analyzed data can be visualized and exported as histograms.""" self.tab2.setLayout(self.grid1) self.tab2.histPlot = HistPlotter(None, width=8, height=5, dpi=60) self.grid1.addWidget(self.tab2.histPlot, 3, 0, 1, 4) self.tab2.histTypeBox = QComboBox() self.tab2.histTypeBox.addItem("General Histogram") self.tab2.histTypeBox.addItem("Bin per Contact") self.grid1.addWidget(self.tab2.histTypeBox, 0, 3) self.tab2.attributeBox = QComboBox() self.tab2.attributeBox.addItem("Mean Score") self.tab2.attributeBox.addItem("Median Score") self.tab2.attributeBox.addItem("Mean Lifetime") self.tab2.attributeBox.addItem("Median Lifetime") self.tab2.attributeBox.addItem("Hbond percentage") self.grid1.addWidget(self.tab2.attributeBox, 1, 3) self.tab2.plotButton = QPushButton("Show Preview") self.tab2.plotButton.setAutoDefault(False) self.tab2.plotButton.clicked.connect(self.pushPlot) self.grid1.addWidget(self.tab2.plotButton, 0, 0, 1, 3) self.tab2.saveButton = QPushButton("Save Histogram") self.tab2.saveButton.setAutoDefault(False) self.tab2.saveButton.clicked.connect(self.saveHist) self.grid1.addWidget(self.tab2.saveButton, 1, 0, 1, 1) self.tab2.formatLabel = QLabel("Format: ") self.grid1.addWidget(self.tab2.formatLabel, 1, 1) self.tab2.xTicksFontSizeLabel = QLabel("bin per contact font size: ") self.grid1.addWidget(self.tab2.xTicksFontSizeLabel, 2, 0) self.tab2.xTicksFontSizeField = QLineEdit("11") self.grid1.addWidget(self.tab2.xTicksFontSizeField, 2, 1) self.tab2.formatBox = QComboBox() self.tab2.formatBox.addItem("pdf") self.tab2.formatBox.addItem("png") self.tab2.formatBox.addItem("svg") self.tab2.formatBox.addItem("eps") self.grid1.addWidget(self.tab2.formatBox, 1, 2) def tab3UI(self): """Tab where the contact map can be generated and exported.""" self.tab3.setLayout(self.grid2) self.tab3.mapPlot = AnimateMapPlotter(None, width=8, height=5, dpi=60) self.grid2.addWidget(self.tab3.mapPlot, 3, 0, 1, 4) self.tab3.plotMapButton = QPushButton("Show Preview") self.tab3.plotMapButton.setAutoDefault(False) self.tab3.plotMapButton.clicked.connect(self.pushMapPlot) self.grid2.addWidget(self.tab3.plotMapButton, 0, 0, 1, 1) self.tab3.formatBox = QComboBox() self.tab3.formatBox.addItem("pdf") self.tab3.formatBox.addItem("png") self.tab3.formatBox.addItem("svg") self.tab3.formatBox.addItem("eps") self.grid2.addWidget(self.tab3.formatBox, 0, 2, 1, 1) self.tab3.saveButton = QPushButton("Save Map") self.tab3.saveButton.setAutoDefault(False) self.tab3.saveButton.clicked.connect(self.saveMap) self.grid2.addWidget(self.tab3.saveButton, 0, 3, 1, 1) self.tab3.attributeBox = QComboBox() self.tab3.attributeBox.addItem("Mean Score") self.tab3.attributeBox.addItem("Median Score") self.tab3.attributeBox.addItem("Mean Lifetime") self.tab3.attributeBox.addItem("Median Lifetime") self.tab3.attributeBox.addItem("Hbond percentage") self.grid2.addWidget(self.tab3.attributeBox, 0, 1) def tab4UI(self): """Tab where selected data can be visualized in VMD via a Tcl script generation.""" self.tab4.setLayout(self.grid3) label = QLabel("Split selections for each contact") self.tab4.splitVisCheckbox = QCheckBox() self.grid3.addWidget(label, 0, 0) self.grid3.addWidget(self.tab4.splitVisCheckbox, 0, 1) self.tab4.additionalText1 = QLineEdit() self.tab4.additionalText2 = QLineEdit() additionalTextLabel1 = QLabel("Additional seltext for selection 1") additionalTextLabel2 = QLabel("Additional seltext for selection 2") self.tab4.button = QPushButton("Create tcl script") self.tab4.button.clicked.connect(self.createTclScriptVis) self.grid3.addWidget(self.tab4.button, 3, 0, 1, 2) self.grid3.addWidget(additionalTextLabel1, 1, 0) self.grid3.addWidget(additionalTextLabel2, 2, 0) self.grid3.addWidget(self.tab4.additionalText1, 1, 1) self.grid3.addWidget(self.tab4.additionalText2, 2, 1) def tab5UI(self): """Tab where the raw data can be exported to a text file.""" self.tab5.setLayout(self.grid4) self.checkboxdict = {"mean_score": "Mean Score", "hbond_percentage": "HBond Percentage", "median_score": "Median Score", "contactTypeAsShortcut": "Contact Type", "getScoreArray": "Score List", "hbondFramesScan": "Hydrogen Bond Frames"} # let's define the key order ourselves self.keys = ["contactTypeAsShortcut", "mean_score", "median_score", "hbond_percentage", "getScoreArray", "hbondFramesScan"] propertyLabel = QLabel("Select properties to export") self.grid4.addWidget(propertyLabel, 0, 0) startLine = 1 for box in self.keys: checkBox = QCheckBox() checkBox.setChecked(True) boxLabel = QLabel(self.checkboxdict[box]) self.grid4.addWidget(boxLabel, startLine, 0) self.grid4.addWidget(checkBox, startLine, 1) self.checkboxes.append(checkBox) startLine += 1 self.tab5.button = QPushButton("Export to text") self.tab5.button.clicked.connect(self.saveText) self.grid4.addWidget(self.tab5.button, startLine, 5) def saveText(self): """Executes the conversion of the analysis results to raw text data.""" fileName = QFileDialog.getSaveFileName(self, 'Export Path') if len(fileName[0]) > 0: path, file_extension = os.path.splitext(fileName[0]) boxIndex = 0 requestedParameters = [] for box in self.checkboxes: if box.isChecked(): requestedParameters.append(self.keys[boxIndex]) boxIndex += 1 tableHeadings = [] for par in requestedParameters: tableHeadings.append(self.checkboxdict[par]) f = open(path + ".txt", "w") row_format = " {:>20} " * (len(requestedParameters) + 1) f.write(row_format.format("", *tableHeadings)) f.write("\n") for c in self.contacts: row_format = " {:>20} " currentContactProperties = [] for p in requestedParameters: if not hasattr(c, p): continue propertyToAdd = getattr(c, p)() if isinstance(propertyToAdd, float): propertyToAdd = "{0:.3f}".format(propertyToAdd) currentContactProperties.append(propertyToAdd) if isinstance(propertyToAdd, list): row_format += " {} " else: row_format += " {:>20} " f.write(row_format.format(c.human_readable_title(), *currentContactProperties)) f.write("\n") f.close() def saveHist(self): """Saves the histogram to the picked file path.""" self.plotHist() fileName = QFileDialog.getSaveFileName(self, 'Export Path') if len(fileName[0]) > 0: path, file_extension = os.path.splitext(fileName[0]) if file_extension == "": file_extension = "." + self.tab2.formatBox.currentText().lower() path += file_extension self.tab2.histPlot.saveFigure(path, self.tab2.formatBox.currentText()) def saveMap(self): """Saves the contact map to the picked file path.""" self.plotMap() fileName = QFileDialog.getSaveFileName(self, 'Export Path') if len(fileName[0]) > 0: path, file_extension = os.path.splitext(fileName[0]) self.tab3.mapPlot.saveFigure(path, self.tab3.formatBox.currentText()) def pushPlot(self): """Triggers the histogram plotter.""" self.plotHist() def pushMapPlot(self): """Triggers the contact map plotter.""" self.plotMap() def plotHist(self): """Plots the histogram.""" sip.delete(self.tab2.histPlot) self.tab2.histPlot = HistPlotter(None, width=8, height=5, dpi=60) self.grid1.addWidget(self.tab2.histPlot, 3, 0, 1, 4) if self.tab2.histTypeBox.currentText() == "General Histogram": self.tab2.histPlot.plotGeneralHist(self.contacts, self.tab2.attributeBox.currentText(), self.threshold, self.nsPerFrame) elif self.tab2.histTypeBox.currentText() == "Bin per Contact": self.tab2.histPlot.plotContactHist(self.contacts, self.tab2.attributeBox.currentText(), self.threshold, self.nsPerFrame, int(self.tab2.xTicksFontSizeField.text())) self.tab2.histPlot.update() def plotMap(self): """Plots the contact map.""" sip.delete(self.tab3.mapPlot) self.tab3.mapPlot = MapPlotter(None, width=8, height=5, dpi=60) self.grid2.addWidget(self.tab3.mapPlot, 3, 0, 1, 4) if self.map1 is None or self.map2 is None or self.contacts is None or len(self.contacts) == 0: box = ErrorBox(ErrorMessages.RESID_REQUIRED) box.exec_() return res = self.tab3.mapPlot.plotMap(self.contacts, self.map1, self.map2, self.label1, self.label2, self.tab3.attributeBox.currentText(), self.threshold, self.nsPerFrame) if res == -1: box = ErrorBox(ErrorMessages.RESID_REQUIRED) box.exec_() self.tab3.mapPlot.update() def pushSave(self): """Saves the current view.""" fileName = QFileDialog.getSaveFileName(self, 'Export Path') path, file_extension = os.path.splitext(fileName[0]) if file_extension == "": file_extension = "." + self.tab1.formatBox.currentText().lower() path += file_extension self.valueUpdated.emit(path, self.tab1.formatBox.currentText()) def setContacts(self, currentContacts): self.contacts = currentContacts def setFilePaths(self, *argv): """Sets the current trajectory paths from the main view.""" self.psf = argv[0][0] self.dcd = argv[0][1] def setMaps(self, map1, map2): self.map1 = map1 self.map2 = map2 # labels for the contact map def setMapLabels(self, label1, label2): self.label1 = label1 self.label2 = label2 def createTclScriptVis(self): """Creates the Tcl script for VMD visualization of the selections.""" if len(self.contacts) == 0: box = ErrorBox(ErrorMessages.NOCONTACTS) box.exec_() return fileName = QFileDialog.getSaveFileName(self, 'Save Path') if len(fileName[0]) > 0: path, file_extension = os.path.splitext(fileName[0]) if file_extension != ".tcl": file_extension = ".tcl" path += file_extension f = open(path, 'w') f.write('mol new %s \n' % self.psf) f.write('mol addfile %s \n' % self.dcd) f.write('mol delrep 0 top \n') f.write('mol representation NewCartoon \n') f.write('mol Color ColorID 3 \n') f.write('mol selection {all} \n') f.write('mol addrep top \n') if self.tab4.splitVisCheckbox.isChecked(): for cont in self.contacts: currentSel1 = [] index = 0 for item in cont.key1: if item != "none": currentSel1.append(AccumulationMapIndex.vmdsel[index] + " " + item) index += 1 currentSel1String = " and ".join(currentSel1) currentSel2 = [] index = 0 for item in cont.key2: if item != "none": currentSel2.append(AccumulationMapIndex.vmdsel[index] + " " + item) index += 1 currentSel2String = " and ".join(currentSel2) add1 = ("" if self.tab4.additionalText1.text() == "" else (" and " + self.tab4.additionalText1.text())) add2 = ("" if self.tab4.additionalText2.text() == "" else (" and " + self.tab4.additionalText2.text())) sel = "("+currentSel1String + add1 + ") or (" + currentSel2String + add2 + ")" f.write('mol representation Licorice \n') f.write('mol Color Name \n') f.write('mol selection {%s} \n' % sel) f.write('mol addrep top \n') else: total = [] for cont in self.contacts: currentSel1 = [] index = 0 for item in cont.key1: if item != "none": currentSel1.append(AccumulationMapIndex.vmdsel[index] + " " + item) index += 1 currentSel1String = " and ".join(currentSel1) currentSel2 = [] index = 0 for item in cont.key2: if item != "none": currentSel2.append(AccumulationMapIndex.vmdsel[index] + " " + item) index += 1 currentSel2String = " and ".join(currentSel2) add1 = ("" if self.tab4.additionalText1.text() == "" else (" and " + self.tab4.additionalText1.text())) add2 = ("" if self.tab4.additionalText2.text() == "" else (" and " + self.tab4.additionalText2.text())) sel = "(" + currentSel1String + add1 + ") or (" + currentSel2String + add2 + ")" total.append(sel) seltext = " or ".join(total) f.write('mol representation Licorice \n') f.write('mol Color Name \n') f.write('mol selection {%s} \n' % seltext) f.write('mol addrep top \n') f.close()
maxscheurer/pycontact
PyContact/gui/ExportTabWidget.py
Python
gpl-3.0
16,959
[ "VMD" ]
dc8f74a90b2ac39c09a3d65b3e8bfe75a7ed9208b82f2f926f304772abfc3c68
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2007 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., or visit: http://www.gnu.org/. ## ## Author(s): Stoq Team <stoq-devel@async.com.br> ## ## import locale from kiwi.python import namedAny from stoqlib.lib.cardinals import generic def get_cardinal_module(): lang = locale.getlocale()[0] if not lang: # For tests return generic # First try the full LANG, like 'pt_BR', 'en_US', etc path = 'stoqlib.lib.cardinals.%s' % (lang, ) try: return namedAny(path) except (ImportError, AttributeError): # Then base lang, 'pt', 'en', etc base_lang = lang[:2] path = 'stoqlib.lib.cardinals.%s' % (base_lang, ) try: return namedAny(path) except (ImportError, AttributeError): return generic def get_cardinal_function(func_name): module = get_cardinal_module() function = getattr(module, func_name, None) if not function: function = getattr(generic, func_name) assert function assert callable(function) return function
andrebellafronte/stoq
stoqlib/lib/cardinals/cardinals.py
Python
gpl-2.0
1,824
[ "VisIt" ]
376ec232c486591a3882c0a8792536113943f74ec8d5f6701c78baf5f708bfdf
# -*- coding: utf-8 -*- { "'Cancel' will indicate an asset log entry did not occur": "'Hủy' sẽ chỉ dẫn một lệnh nhập không thực hiện được", "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": "Một địa điểm chứa các đặc tính địa lý cho vùng đó. Đó có thể là một địa điểm theo đơn vị hành chính hay 'địa điểm nhóm' hay một địa điểm có đường ranh giới cho vùng đó.", "A volunteer is defined as active if they've participated in an average of 8 or more hours of Program work or Trainings per month in the last year": 'Tình nguyện viên hoạt động tích cực là những người tham gia trung bình từ 8 tiếng hoặc hơn vào các hoạt động của chương trình hay tập huấn một tháng trong năm trước.', "Acronym of the organization's name, eg. IFRC.": 'Từ viết tắt của tên tổ chức, vd IFRC.', "Add Person's Details": 'Thêm thông tin cá nhân', "Address of an image to use for this Layer in the Legend. This allows use of a controlled static image rather than querying the server automatically for what it provides (which won't work through GeoWebCache anyway).": 'Địa chỉ của hình ảnh sử dụng cho Lớp này nằm trong phần ghi chú. Việc này giúp việc sử dụng hình ảnh ổn định được kiểm soát tránh báo cáo tự động gửi tới máy chủ yêu cầu giải thích về nội dung cung cấp (chức năng này không hoạt động thông qua GeoWebCach).', "Authenticate system's Twitter account": 'Xác thực tài khoản Twitter thuộc hệ thống', "Can't import tweepy": 'Không thể nhập khẩu tweepy', "Cancel' will indicate an asset log entry did not occur": "Hủy' có nghĩa là ghi chép nhật ký tài sản không được lưu", "Caution: doesn't respect the framework rules!": 'Cảnh báo: Không tôn trọng các qui đinh khung chương trình', "Click 'Start' to synchronize with this repository now:": "Bấm nút 'Bắt đầu' để đồng bộ hóa kho dữ liệu bầy giờ", "Click on questions below to select them, then click 'Display Selected Questions' button to view the selected questions for all Completed Assessment Forms": "Bấm vào các câu hỏi phía dưới để chọn, sau đó bấm nút 'Hiển thị các câu hỏi đã chọn' để xem các câu hỏi đã chọn cho tất cả các mẫu Đánh giá hoàn chỉnh", "Don't Know": 'Không biết', "Edit Person's Details": 'Chỉnh sửa thông tin cá nhân', "Enter a name to search for. You may use % as wildcard. Press 'Search' without input to list all items.": "Nhập tên để tìm kiếm. Bạn có thể sử dụng % như là ký tự đặc biệt. Ấn 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả mặt hàng", "Error No Job ID's provided": 'Lỗi mã nhận dạng công việc không được cung cấp', "Framework added, awaiting administrator's approval": 'Khung chương trình đã được thêm mới, đang chờ phê duyệt của quản trị viên', "Go to %(url)s, sign up & then register your application. You can put any URL in & you only need to select the 'modify the map' permission.": "Đến trang %(url)s, đăng ký & sau đó đăng ký ứng dụng của bạn. Bạn có thể dùng bất cứ đường dẫn URL & chỉ cần chọn 'chức năng cho phép sửa bản đồ'.", "If selected, then this Asset's Location will be updated whenever the Person's Location is updated.": 'Nếu chọn, thì sau đó vị trí tài sản sẽ được cập nhật ngay khi vị trí của người đó được cập nhật.', "If this configuration is displayed on the GIS config menu, give it a name to use in the menu. The name for a personal map configuration will be set to the user's name.": 'Nếu cấu hình này được thể hiện trên danh mục cấu hình GIS, đặt tên cho cấu hình để sử dụng trên danh mục. Tên cấu hình bản đồ của cá nhân sẽ được gắn với tên người sử dụng.', "If this field is populated then a user who specifies this Organization when signing up will be assigned as a Staff of this Organization unless their domain doesn't match the domain field.": 'Nếu trường này đã nhiều người khi đó người dùng sẽ chi tiết tổ chức lúc đó việc đăng ký sẽ được phân bổ như là Cán bộ của tổ chức trừ phi chức năng đó không phù hợp.', "If you don't see the Cluster in the list, you can add a new one by clicking link 'Create Cluster'.": "Nếu bạn không tìm thấy tên Nhóm trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm nhóm'", "If you don't see the Organization in the list, you can add a new one by clicking link 'Create Organization'.": "Nếu bạn không tìm thấy tên Tổ chức trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm tổ chức'", "If you don't see the Sector in the list, you can add a new one by clicking link 'Create Sector'.": "Nếu bạn không tìm thấy Lĩnh vực trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm lĩnh vực'", "If you don't see the Type in the list, you can add a new one by clicking link 'Create Office Type'.": "Nếu bạn không tìm thấy Loại hình văn phòng trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm loại hình văn phòng'", "If you don't see the Type in the list, you can add a new one by clicking link 'Create Organization Type'.": "Nếu bạn không tìm thấy tên Loại hình tổ chức trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm loại hình tổ chức'", "If you don't see the activity in the list, you can add a new one by clicking link 'Create Activity'.": "Nếu bạn không tìm thấy hoạt động trong danh sách, bạn có thể thêm một bằng cách ấn nút 'Thêm hoạt động'", "If you don't see the asset in the list, you can add a new one by clicking link 'Create Asset'.": "Nếu bạn không tìm thấy tài sản trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm tài sản'", "If you don't see the beneficiary in the list, you can add a new one by clicking link 'Add Beneficiary'.": "Nếu bạn không tìm thấy tên người hưởng lợi trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm người hưởng lợi'", "If you don't see the community in the list, you can add a new one by clicking link 'Create Community'.": "Nếu bạn không thấy Cộng đồng trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm cộng đồng'", "If you don't see the location in the list, you can add a new one by clicking link 'Create Location'.": "Nếu bạn không thấy Địa điểm trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm địa điểm'", "If you don't see the project in the list, you can add a new one by clicking link 'Create Project'.": "Nếu bạn không thấy dự án trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm dự án'", "If you don't see the type in the list, you can add a new one by clicking link 'Create Activity Type'.": "Nếu bạn không thấy loại hình hoạt động trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm loại hình hoạt động'", "If you don't see the vehicle in the list, you can add a new one by clicking link 'Add Vehicle'.": "Nếu bạn không thấy phương tiện vận chuyển trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm phương tiện vận chuyển'", "If you enter a foldername then the layer will appear in this folder in the Map's layer switcher.": 'Nếu bạn nhập tên thư mục sau đó lớp đó sẽ hiện ra trong thư mục trong nút chuyển lớp Bản đồ.', "Last Week's Work": 'Công việc của tuấn trước', "Level is higher than parent's": 'Cấp độ cao hơn cấp độ gốc', "List Persons' Details": 'Liệt kê thông tin cá nhân', "Need a 'url' argument!": "Cần đối số cho 'url'!", "No UTC offset found. Please set UTC offset in your 'User Profile' details. Example: UTC+0530": "Không có thời gian bù UTC được tìm thấy. Cài đặt thời gian bù UTC trong thông tin 'Hồ sơ người sử dụng' của bạn. Ví dụ: UTC+0530", "Only Categories of type 'Vehicle' will be seen in the dropdown.": "Chỉ những hạng mục thuộc 'Xe cộ' được thể hiện trong danh sách thả xuống", "Optional. The name of the geometry column. In PostGIS this defaults to 'the_geom'.": "Tùy chọn. Tên của cột hình dạng. Trong PostGIS tên này được mặc định là 'the_geom'.", "Parent level should be higher than this record's level. Parent level is": 'Mức độ cấp trên phải cao hơn mức độ của bản lưu này. Mức độ cấp trên là', "Password fields don't match": 'Trường mật khẩu không tương thích', "Person's Details added": 'Thông tin được thêm vào của cá nhân', "Person's Details deleted": 'Thông tin đã xóa của cá nhân', "Person's Details updated": 'Thông tin được cập nhật của cá nhân', "Person's Details": 'Thông tin cá nhân', "Persons' Details": 'Thông tin cá nhân', "Phone number to donate to this organization's relief efforts.": 'Số điện thoại để ủng hộ cho những nỗ lực cứu trợ của tổ chức này', "Please come back after sometime if that doesn't help.": 'Xin vui lòng quay trở lại sau nếu điều đó không giúp ích bạn.', "Please provide as much detail as you can, including the URL(s) where the bug occurs or you'd like the new feature to go.": 'Xin vui lòng cung cấp thông tin chi tiết nhất có thể, bao gồm những đường dẫn URL chứa các lỗi kỹ thuật hay bạn muốn thực hiện chức năng mới.', "Quantity in %s's Warehouse": 'Số lượng trong %s Nhà kho', "Search Person's Details": 'Tìm kiếm thông tin cá nhân', "Select a Facility Type from the list or click 'Create Facility Type'": "Chọn loại hình bộ phận từ danh sách hoặc bấm 'Thêm loại hình bộ phận'", "Select a Room from the list or click 'Create Room'": "Chọn một Phòng từ danh sách hay bấm 'Thêm Phòng'", "Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.": "Chọn nó nếu tất cả các điểm cụ thể cần lớp cao nhất trong hệ thống hành chính các địa điểm. Ví dụ, nếu 'là lớp huyện' là phân chia nhỏ nhất trong hệ thống, do vậy các địa điểm cụ thể sẽ yêu cầu có lớp huyện là lớp trên.", "Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area.": 'Chọn nó nếu tất cả các điểm cụ thể cần lớp trên trong hệ thống hành chính các địa điểm. Nó có thể giúp lập nên một vùng diện cho một vùng bị ảnh hưởng. ', "Sorry, things didn't get done on time.": 'Xin lỗi, công việc đã không được làm đúng lúc.', "Sorry, we couldn't find that page.": 'Xin lỗi, chúng tôi không thể tìm thấy trang đó', "Status 'assigned' requires the %(fieldname)s to not be blank": "Tình trạng 'được bổ nhiệm' đòi hỏi %(fieldname)s không được bỏ trống", "System's Twitter account updated": 'Tài khoản Twitter của Hệ thống được cập nhật', "The Project module can be used to record Project Information and generate Who's Doing What Where reports.": 'Mô đun Dự án có thể được sử dụng để ghi lại Thông tin Dự án và cho ra các báo cáo Ai Đang làm Điều gì Ở đâu.', "The URL of the image file. If you don't upload an image file, then you must specify its location here.": 'Đường dẫn URL của tệp tin hình ảnh. Nếu bạn không tải tệp tin hình ảnh lên, thì bạn phải đưa đường dẫn tới vị trí của tệp tin đó tại đây.', "The person's manager within this Office/Project.": 'Quản lý của một cá nhân trong Văn phòng/Dự án', "The staff member's official job title": 'Chức vụ chính thức của cán bộ', "The volunteer's role": 'Vai trò của tình nguyện viên', "There are no details for this person yet. Add Person's Details.": 'Chưa có thông tin về người này. Hãy thêm Thông tin.', "To search for a hospital, enter any part of the name or ID. You may use % as wildcard. Press 'Search' without input to list all hospitals.": 'Để tìm kiếm một bệnh viện, nhập một phần tên hoặc ID. Có thể sử dụng % như một ký tự thay thế cho một nhóm ký tự. Nhấn "Tìm kiếm" mà không nhập thông tin, sẽ hiển thị toàn bộ các bệnh viện.', "To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations.": "Dể tìm kiếm địa điểm, nhập tên của địa điểm đó. Bản có thể sử dụng ký tự % như là ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập tên địa điểm để liệt kê toàn bộ địa điểm.", "To search for a member, enter any portion of the name of the person or group. You may use % as wildcard. Press 'Search' without input to list all members": "Để tìm thành viên, nhập tên của thành viên hoặc nhóm. Bạn có thể sử dụng % như là ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập tên để liệt toàn bộ thành viên", "To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Để tìm kiếm người, nhập bất kỳ tên, tên đệm hoặc tên họ và/ hoặc số nhận dạng cá nhân của người đó, tách nhau bởi dấu cách. Ấn nút 'Tìm kiếm' mà không nhập tên người để liệt kê toàn bộ người.", "Type the first few characters of one of the Participant's names.": 'Nhập những ký tự đầu tiên trong tên của một Người tham dự.', "Type the first few characters of one of the Person's names.": 'Nhập những ký tự đầu tiên trong tên của một Người.', "Type the name of an existing catalog item OR Click 'Create Item' to add an item which is not in the catalog.": "Nhập tên của một mặt hàng trong danh mục đang tồn tại HOẶC Nhấn 'Thêm mặt hàng mới' để thêm một mặt hàng chưa có trong danh mục.", "Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field.": 'Tải lên file hình ảnh tại đây. Nếu bạn không đăng tải được file hình ảnh, bạn phải chỉ đường dẫn chính xác tới vị trí của file trong trường URL.', "Uploaded file(s) are not Image(s). Supported image formats are '.png', '.jpg', '.bmp', '.gif'.": "File được tải không phải là hình ảnh. Định dạng hình ảnh hỗ trợ là '.png', '.jpg', '.bmp', '.gif'", "View and/or update details of the person's record": 'Xem và/hoặc cập nhật chi tiết mục ghi cá nhân', """Welcome to %(system_name)s - You can start using %(system_name)s at: %(url)s - To edit your profile go to: %(url)s%(profile)s Thank you""": """Chào mừng anh/chị truy cập %(system_name)s Anh/chị có thể bắt đầu sử dụng %(system_name)s tại %(url)s Để chỉnh sửa hồ sơ của anh/chị, xin vui lòng truy cập %(url)s%(profile)s Cảm ơn""", "Yes, No, Don't Know": 'Có, Không, Không biết', "You can search by asset number, item description or comments. You may use % as wildcard. Press 'Search' without input to list all assets.": "Bạn có thể tìm kiếm theo mã số tài sản, mô tả mặt hàng hoặc các bình luận. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả tài sản.", "You can search by course name, venue name or event comments. You may use % as wildcard. Press 'Search' without input to list all events.": "Bạn có thể tìm kiếm theo tên khóa học, tên địa điểm tổ chức hoặc bình luận về khóa học. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả khóa học.", "You can search by description. You may use % as wildcard. Press 'Search' without input to list all incidents.": "Bạn có thể tìm kiếm theo mô tả. Bạn có thể sử dụng % làm ký tự đại diện. Không nhập thông tin và nhấn 'Tìm kiếm' để liệt kê tất cả các sự kiện.", "You can search by job title or person name - enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Bạn có thể tìm kiếm theo chức vụ nghề nghiệp hoặc theo tên đối tượng - nhập bất kỳ tên nào trong tên chính, tên đệm hay họ, tách nhau bởi dấu cách. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả đối tượng.", "You can search by person name - enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Bạn có thể tìm kiếm theo tên người - nhập bất kỳ tên, tên đệm hay tên họ, tách nhau bởi dấu cách. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả số người.", "You can search by trainee name, course name or comments. You may use % as wildcard. Press 'Search' without input to list all trainees.": "Bạn có thể tìm kiếm bằng tên người được tập huấn, tên khóa học hoặc các bình luận. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả người được tập huấn.", "You have personalised settings, so changes made here won't be visible to you. To change your personalised settings, click ": 'Bạn đã thiết lập các cài đặt cá nhân, vì vậy bạn không xem được các thay đổi ở đây.Để thiết lập lại, nhấp chuột vào', "You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.": "Bạn chưa lưu các thay đổi. Ấn 'Hủy bỏ' bây giờ, sau đó ấn 'Lưu' để lưu lại. Ấn OK bây giờ để bỏ các thay đổi", '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"cập nhật" là một lựa chọn như "Thực địa1=\'giá trị mới\'". Bạn không thể cập nhật hay xóa các kết quả của một NHÓM', '# of Houses Damaged': 'Số nóc nhà bị phá hủy', '# of Houses Destroyed': 'Số căn nhà bị phá hủy', '# of International Staff': 'số lượng cán bộ quốc tế', '# of National Staff': 'số lượng cán bộ trong nước', '# of People Affected': 'Số người bị ảnh hưởng', '# of People Injured': 'Số lượng người bị thương', '%(GRN)s Number': '%(GRN)s Số', '%(GRN)s Status': '%(GRN)s Tình trạng', '%(PO)s Number': '%(PO)s Số', '%(REQ)s Number': '%(REQ)s Số', '%(app)s not installed. Ask the Server Administrator to install on Server.': '%(app)s dụng chưa được cài. Liên hệ với ban quản trị máy chủ để cài ứng dụng trên máy chủ', '%(count)s Entries Found': '%(count)s Hồ sơ được tìm thấy', '%(count)s Roles of the user removed': '%(count)s Đã gỡ bỏ chức năng của người sử dụng', '%(count)s Users removed from Role': '%(count)s Đã xóa người sử dụng khỏi chức năng', '%(count_of)d translations have been imported to the %(language)s language file': '%(count_of)d bản dịch được nhập liệu trong %(language)s file ngôn ngữ', '%(item)s requested from %(site)s': '%(item)s đề nghị từ %(site)s', '%(module)s not installed': '%(module)s chưa được cài đặt', '%(pe)s in %(location)s': '%(pe)s tại %(location)s', '%(quantity)s in stock': '%(quantity)s hàng lưu kho', '%(system_name)s has sent an email to %(email)s to verify your email address.\nPlease check your email to verify this address. If you do not receive this email please check you junk email or spam filters.': '%(system_name)s đã gửi email đến %(email)s để kiểm tra địa chỉ email của bạn.\nĐề nghị kiểm tra email để xác nhận. Nếu bạn không nhận được hãy kiểm tra hộp thư rác hay bộ lọc thư rác.', '%s items are attached to this shipment': '%s hàng hóa được chuyển trong đợt xuất hàng này', '& then click on the map below to adjust the Lat/Lon fields': '& sau đó chọn trên bản đồ để chính sửa số kinh/vĩ độ', '(filtered from _MAX_ total entries)': '(lọc từ _MAX_ toàn bộ hồ sơ)', '* Required Fields': '* Bắt buộc phải điền', '...or add a new bin': '…hoặc thêm một ngăn mới', '1 Assessment': '1 Đánh giá', '1 location, shorter time, can contain multiple Tasks': '1 địa điểm, thời gian ngắn hơn, có thể bao gồm nhiều nhiệm vụ khác nhau', '1. Fill the necessary fields in BLOCK CAPITAL letters.': '1. Điền nội dung vào các ô cần thiết bằng CHỮ IN HOA.', '2. Always use one box per letter and leave one box space to separate words.': '2. Luôn sử dụng một ô cho một chữ cái và để một ô trống để cách giữa các từ', '3. Fill in the circles completely.': '3. Điền đầy đủ vào các ô tròn', '3W Report': 'Báo cáo 3W', 'A Marker assigned to an individual Location is set if there is a need to override the Marker assigned to the Feature Class.': 'Một đánh dấu cho một vị trí đơn lẻ nếu cần thiết để thay thế một Đánh dấu theo chức năng.', 'A brief description of the group (optional)': 'Mô tả ngắn gọn nhóm đánh giá (không bắt buộc)', 'A catalog of different Assessment Templates including summary information': 'Danh mục các biểu mẫu đánh giá khác nhau bao gồm cả thông tin tóm tắt', 'A file in GPX format taken from a GPS.': 'file định dạng GPX từ máy định vị GPS.', 'A place within a Site like a Shelf, room, bin number etc.': 'Một nơi trên site như số ngăn ,số phòng,số thùng v.v', 'A project milestone marks a significant date in the calendar which shows that progress towards the overall objective is being made.': 'Một mốc quan trọng của dự án đánh dấu ngày quan trọng trong lịch để chỉ ra tiến độ đạt được mục tổng quát của dự án.', 'A snapshot of the location or additional documents that contain supplementary information about the Site can be uploaded here.': 'Upload ảnh chụp vị trí hoặc tài liệu bổ sung chứa thông tin bổ sung về trang web tại đây', 'A staff member may have multiple roles in addition to their formal job title.': 'Một cán bộ có thể có nhiều chức năng nhiệm vụ bổ sung thêm vào chức năng nhiệm vụ chính.', 'A strict location hierarchy cannot have gaps.': 'Thứ tự vi trí đúng không thể có khoảng cách.', 'A survey series with id %s does not exist. Please go back and create one.': 'Chuỗi khảo sát số %s không tồn tai.Vui lòng quay lại và tạo mới', 'A task is a piece of work that an individual or team can do in 1-2 days.': 'Nhiệm vụ là công việc mà một cá nhân hoặc nhóm có thể thực hiện trong 1-2 ngày.', 'A volunteer may have multiple roles in addition to their formal job title.': 'Một tình nguyện viên có thể có nhiều chức năng nhiệm vụ bổ sung thêm vào chức năng nhiệm vụ chính.', 'ABOUT CALCULATIONS': 'TẠM TÍNH', 'ABOUT THIS MODULE': 'Giới thiệu Module này', 'ABSOLUTE%(br)sDEVIATION': 'HOÀN TOÀN%(br)sCHỆCH HƯỚNG', 'ACTION REQUIRED': 'HÀNH ĐỘNG ĐƯỢC YÊU CẦU', 'ALL REPORTS': 'TẤT CẢ BÁO CÁO', 'ALL': 'Tất cả', 'ANY': 'BẤT KỲ', 'API is documented here': 'API được lưu trữ ở đây', 'APPROVE REPORTS': 'PHÊ DUYỆT BÁO CÁO', 'AUTH TOKEN': 'THẺ XÁC THỰC', 'Abbreviation': 'Từ viết tắt', 'Ability to customize the list of human resource tracked at a Shelter': 'Khả năng tùy chỉnh danh sách nguồn nhân lực theo dõi tại nơi cư trú', 'Ability to customize the list of important facilities needed at a Shelter': 'Khả năng tùy chỉnh danh sách các điều kiện quan trọng cần thiết tại một cơ sở cư trú', 'Able to Respond?': 'Có khả năng ứng phó không?', 'About Us': 'Giới thiệu', 'About': 'Khoảng', 'Accept Push': 'Chấp nhận Đẩy', 'Accept unsolicited data transmissions from the repository.': 'Chấp nhận truyền các dữ liệu chưa tổng hợp từ kho dữ liệu.', 'Access denied': 'Từ chối truy cập', 'Account Name': 'Tên tài khoản', 'Account Registered - Please Check Your Email': 'Tài khoản đã được đăng ký- Kiểm tra email của bạn', 'Achieved': 'Thành công', 'Acronym': 'Từ viết tắt', 'Action': 'Hành động', 'Actioning officer': 'Cán bộ hành động', 'Actions taken as a result of this request.': 'Hành động được thực hiện như là kết quả của yêu cầu này.', 'Actions': 'Hành động', 'Activate': 'Kích hoạt', 'Active Problems': 'Có vấn đề kích hoạt', 'Active': 'Đang hoạt động', 'Active?': 'Đang hoạt động?', 'Activities matching Assessments': 'Hoạt động phù hợp với Đánh giá', 'Activities': 'Hoạt động', 'Activity Added': 'Hoạt động đã được thêm mới', 'Activity Deleted': 'Hoạt động đã được xóa', 'Activity Details': 'Chi tiết hoạt động', 'Activity Report': 'Báo cáo hoạt động', 'Activity Type Added': 'Loại hình hoạt động đã được thêm mới', 'Activity Type Deleted': 'Loại hình hoạt động đã được xóa', 'Activity Type Sectors': 'Lĩnh vực của loại hình hoạt động', 'Activity Type Updated': 'Loại hình hoạt động đã được cập nhật', 'Activity Type': 'Loại hình Hoạt động', 'Activity Types': 'Loại hình Hoạt động', 'Activity Updated': 'Hoạt động đã được cập nhật', 'Activity': 'Hoạt động', 'Add Address': 'Thêm địa chỉ', 'Add Affiliation': 'Thêm liên kết', 'Add Aid Request': 'Thêm yêu cầu cứu trợ', 'Add Alternative Item': 'Thêm mặt hàng thay thế', 'Add Annual Budget': 'Ngân sách hàng năm mới', 'Add Assessment Answer': 'Thêm câu trả lời đánh giá', 'Add Assessment Templates': 'Thêm biểu mẫu đánh giá', 'Add Assessment': 'Thêm đợt đánh giá', 'Add Beneficiaries': 'Thêm người hưởng lợi', 'Add Branch Organization': 'Thêm tổ chức cấp tỉnh/ huyện/ xã', 'Add Certificate for Course': 'Thêm chứng nhận khóa tập huấn', 'Add Certification': 'Thêm bằng cấp', 'Add Contact Information': 'Thêm thông tin liên hệ', 'Add Credential': 'Thêm thư ủy nhiệm', 'Add Data to Theme Layer': 'Thêm dữ liệu vào lớp chủ đề', 'Add Demographic Data': 'Thêm số liệu dân số', 'Add Demographic Source': 'Thêm nguồn thông tin dân số', 'Add Demographic': 'Thêm dữ liệu nhân khẩu', 'Add Distribution': 'Thêm thông tin hàng hóa đóng góp', 'Add Donor': 'Thêm tên người quyên góp vào danh sách', 'Add Education': 'Thêm trình độ học vấn', 'Add Email Settings': 'Thêm cài đặt email', 'Add Framework': 'Thêm khung chương trình', 'Add Group Member': 'Thêm thành viên nhóm', 'Add Hours': 'Thêm thời gian hoạt động', 'Add Identity': 'Thêm nhận dạng', 'Add Image': 'Thêm hình ảnh', 'Add Item Catalog': 'Thêm danh mục hàng hóa', 'Add Item to Catalog': 'Thêm hàng hóa vào danh mục', 'Add Item to Commitment': 'Thêm hàng hóa vào cam kết', 'Add Item to Request': 'Thêm hàng hóa mới để yêu cầu', 'Add Item to Shipment': 'Thêm hàng hóa vào lô hàng chuyển đi', 'Add Item to Stock': 'Thêm mặt hàng lưu kho', 'Add Item': 'Thêm hàng hóa', 'Add Job Role': 'Thêm chức năng công việc', 'Add Key': 'Thêm từ khóa', 'Add Kit': 'Thêm Kit', 'Add Layer from Catalog': 'Thêm lớp từ danh mục', 'Add Layer to this Profile': 'Thêm lớp vào hồ sơ này', 'Add Line': 'Thêm dòng', 'Add Locations': 'Thêm địa điểm mới', 'Add Log Entry': 'Thêm ghi chép nhật ký', 'Add Member': 'Thêm hội viên', 'Add Membership': 'Thêm nhóm hội viên', 'Add Message': 'Thêm tin nhắn', 'Add New Aid Request': 'Thêm yêu cầu cứu trợ mới', 'Add New Beneficiaries': 'Thêm người hưởng lợi mới', 'Add New Beneficiary Type': 'Thêm loại người hưởng lợi mới', 'Add New Branch': 'Thêm chi nhánh mới', 'Add New Cluster': 'Thêm nhóm mới', 'Add New Commitment Item': 'Thêm hàng hóa cam kết mới', 'Add New Community': 'Thêm cộng đồng mới', 'Add New Config': 'Thêm cấu hình mới', 'Add New Demographic Data': 'Thêm số liệu dân số mới', 'Add New Demographic Source': 'Thêm nguồn số liệu dân số mới', 'Add New Demographic': 'Thêm dữ liệu nhân khẩu mới', 'Add New Document': 'Thêm tài liệu mới', 'Add New Donor': 'Thêm nhà tài trợ mới', 'Add New Entry': 'Thêm hồ sơ mới', 'Add New Flood Report': 'Thêm báo cáo lũ lụt mới', 'Add New Framework': 'Thêm khung chương trình mới', 'Add New Image': 'Thêm hình ảnh mới', 'Add New Item to Stock': 'Thêm hàng hóa mới để lưu trữ', 'Add New Job Role': 'Thêm chức năng công việc mới', 'Add New Key': 'Thêm Key mới', 'Add New Layer to Symbology': 'Thêm lớp mới vào các mẫu biểu tượng', 'Add New Mailing List': 'Thêm danh sách gửi thư mới', 'Add New Member': 'Thêm hội viên mới', 'Add New Membership Type': 'Thêm loại nhóm hội viên mới', 'Add New Membership': 'Thêm nhóm hội viên mới', 'Add New Organization Domain': 'Thêm lĩnh vực hoạt động mới của tổ chức', 'Add New Output': 'Thêm kết quả đầu ra mới', 'Add New Participant': 'Thêm người tham dự mới', 'Add New Problem': 'Thêm vấn đề mới', 'Add New Profile Configuration': 'Thêm định dạng hồ sơ tiểu sử mới', 'Add New Record': 'Thêm hồ sơ mới', 'Add New Report': 'Thêm báo cáo mới', 'Add New Request Item': 'Thêm yêu cầu hàng hóa mới', 'Add New Request': 'Thêm yêu cầu mới', 'Add New Response': 'Thêm phản hồi mới', 'Add New Role to User': 'Gán vai trò mới cho người dùng', 'Add New Shipment Item': 'Thêm mặt hàng mới được vận chuyển', 'Add New Site': 'Thêm trang web mới', 'Add New Solution': 'Thêm giải pháp mới', 'Add New Staff Assignment': 'Thêm nhiệm vụ mới cho cán bộ', 'Add New Staff': 'Thêm bộ phận nhân viên', 'Add New Storage Location': 'Thêm Vị trí kho lưu trữ mới', 'Add New Survey Template': 'Thêm mẫu khảo sát mới', 'Add New Team Member': 'Thêm thành viên mới', 'Add New Team': 'Thêm Đội/Nhóm mới', 'Add New Unit': 'Thêm đơn vị mới', 'Add New Vehicle Assignment': 'Thêm phân công mới cho phương tiện vận chuyển', 'Add New Vulnerability Aggregated Indicator': 'Thêm chỉ số gộp mới đánh giá tình trạng dễ bị tổn thương', 'Add New Vulnerability Data': 'Thêm dữ liệu mới về tình trạng dễ bị tổn thương', 'Add New Vulnerability Indicator Sources': 'Thêm nguồn chỉ số mới đánh giá tình trạng dễ bị tổn thương', 'Add New Vulnerability Indicator': 'Thêm chỉ số mới đánh giá tình trạng dễ bị tổn thương', 'Add Order': 'Thêm đơn đặt hàng', 'Add Organization Domain': 'Thêm lĩnh vực hoạt động của tổ chức', 'Add Organization to Project': 'Thêm tổ chức tham gia dự án', 'Add Parser Settings': 'Thêm cài đặt cú pháp', 'Add Participant': 'Thêm người tham dự', 'Add Partner Organization': 'Thêm tổ chức đối tác', 'Add Partner Organizations': 'Thêm tổ chức đối tác', 'Add Person to Commitment': 'Thêm đối tượng cam kết', 'Add Person': 'Thêm họ tên', 'Add Photo': 'Thêm ảnh', 'Add Point': 'Thêm điểm', 'Add Polygon': 'Thêm đường chuyền', 'Add Professional Experience': 'Thêm kinh nghiệm nghề nghiệp', 'Add Profile Configuration for this Layer': 'Thêm định dạng hồ sơ tiểu sử cho lớp này', 'Add Profile Configuration': 'Thêm hồ sơ tiểu sử', 'Add Program Hours': 'Thêm thời gian tham gia chương trình', 'Add Recipient': 'Thêm người nhận viện trợ', 'Add Record': 'Thêm hồ sơ', 'Add Request Detail': 'thêm chi tiết yêu cầu', 'Add Request Item': 'Thêm yêu cầu hàng hóa', 'Add Request': 'Thêm yêu cầu', 'Add Sender Organization': 'Thêm tổ chức gửi', 'Add Setting': 'Thêm cài đặt', 'Add Site': 'Thêm site', 'Add Skill Equivalence': 'Thêm kỹ năng tương đương', 'Add Skill Types': 'Thêm loại kỹ năng', 'Add Skill to Request': 'Thêm kỹ năng để yêu cầu', 'Add Staff Assignment': 'Thêm nhiệm vụ cho cán bộ', 'Add Staff Member to Project': 'Thêm cán bộ thực hiện dự án', 'Add Stock to Warehouse': 'Thêm hàng vào kho', 'Add Storage Location ': 'Thêm vị trí lưu trữ', 'Add Storage Location': 'Thêm vị trí lưu trữ', 'Add Sub-Category': 'Thêm danh mục cấp dưới', 'Add Supplier': 'Thêm nhà cung cấp', 'Add Suppliers': 'Thêm nhà cung cấp', 'Add Survey Answer': 'Thêm trả lời khảo sát', 'Add Survey Question': 'Thêm câu hỏi khảo sát', 'Add Survey Section': 'Thêm phần Khảo sát', 'Add Survey Series': 'Thêm chuỗi khảo sát', 'Add Survey Template': 'Thêm mẫu khảo sát', 'Add Symbology to Layer': 'Thêm biểu tượng cho lớp', 'Add Team Member': 'Thêm thành viên Đội/Nhóm', 'Add Team': 'Thêm Đội/Nhóm', 'Add Template Section': 'Thêm nội dung vào biểu mẫu', 'Add Training': 'Thêm tập huấn', 'Add Translation Language': 'Thêm ngôn ngữ biên dịch mới', 'Add Twilio Settings': 'Thêm cài đặt Twilio', 'Add Unit': 'Thêm đơn vị', 'Add Vehicle Assignment': 'Thêm phân công cho phương tiện vận chuyển', 'Add Vehicle': 'Thêm phương tiện vận chuyển', 'Add Volunteer Registration': 'Thêm Đăng ký tình nguyện viên', 'Add Volunteer Role': 'Thêm vai trò của tình nguyện viên', 'Add Volunteer to Project': 'Thêm tình nguyện viên hoạt động trong dự án', 'Add Vulnerability Aggregated Indicator': 'Thêm chỉ số gộp đánh giá tình trạng dễ bị tổn thương', 'Add Vulnerability Data': 'Thêm dữ liệu về tình trạng dễ bị tổn thương', 'Add Vulnerability Indicator Source': 'Thêm nguồn chỉ số đánh giá tình trạng dễ bị tổn thương', 'Add Vulnerability Indicator': 'Thêm chỉ số đánh giá tình trạng dễ bị tổn thương', 'Add a description': 'Thêm miêu tả', 'Add a new Assessment Answer': 'Thêm câu trả lời mới trong mẫu đánh giá', 'Add a new Assessment Question': 'Thêm câu hỏi mới trong mẫu đánh giá', 'Add a new Assessment Template': 'Thêm biểu mẫu đánh giá mới', 'Add a new Completed Assessment Form': 'Thêm mẫu đánh giá được hoàn thiện mới', 'Add a new Disaster Assessment': 'Thêm báo cáo đánh giá thảm họa mới', 'Add a new Site from where the Item is being sent.': 'Thêm Site nơi gửi hàng hóa đến ', 'Add a new Template Section': 'Thêm nội dung mới vào biểu mẫu', 'Add a new certificate to the catalog.': 'Thêm chứng chỉ mới vào danh mục', 'Add a new competency rating to the catalog.': 'Thêm xếp loại năng lực mới vào danh mục', 'Add a new membership type to the catalog.': 'Thêm loại hình nhóm hội viên mới vào danh mục', 'Add a new programme to the catalog.': 'Thêm chương trình mới vào danh mục', 'Add a new skill type to the catalog.': 'Thêm loại kỹ năng mới vào danh mục', 'Add all organizations which are involved in different roles in this project': 'Thêm tất cả tổ chức đang tham gia vào dự án với vai trò khác nhau', 'Add all': 'Thêm tất cả', 'Add new Group': 'Thêm nhóm mới', 'Add new Question Meta-Data': 'Thêm siêu dữ liệu câu hỏi mới', 'Add new and manage existing members.': 'Thêm mới và quản lý hội viên.', 'Add new and manage existing staff.': 'Thêm mới và quản lý cán bộ.', 'Add new and manage existing volunteers.': 'Thêm mới và quản lý tình nguyện viên.', 'Add new position.': 'Thêm địa điểm mới', 'Add new project.': 'Thêm dự án mới', 'Add new staff role.': 'Thêm vai trò nhân viên mới', 'Add saved search': 'Thêm tìm kiếm đã lưu', 'Add strings manually through a text file': 'Thêm chuỗi ký tự thủ công bằng file văn bản', 'Add strings manually': 'Thêm chuỗi ký tự thủ công', 'Add the Storage Location where this this Bin belongs to.': 'Thêm vị trí kho lưu trữ chứa Bin này', 'Add the main Warehouse/Site information where this Item is to be added.': 'Thêm thông tin Nhà kho/Site chứa hàng hóa đã được nhập thông tin', 'Add this entry': 'Thêm hồ sơ này', 'Add to Bin': 'Thêm vào thùng', 'Add': 'Thêm', 'Add...': 'Thêm…', 'Add/Edit/Remove Layers': 'Thêm/Sửa/Xóa các lớp', 'Added to Group': 'Nhóm hội viên đã được thêm', 'Added to Team': 'Nhóm hội viên đã được thêm', 'Address Details': 'Chi tiết địa chỉ', 'Address Type': 'Loại địa chỉ', 'Address added': 'Địa chỉ đã được thêm', 'Address deleted': 'Địa chỉ đã được xóa', 'Address updated': 'Địa chỉ đã được cập nhật', 'Address': 'Địa chỉ', 'Addresses': 'Địa chỉ', 'Adjust Item Quantity': 'Chỉnh sửa số lượng mặt hàng', 'Adjust Stock Item': 'Chỉnh sửa mặt hàng lưu kho', 'Adjust Stock Levels': 'Điều chỉnh cấp độ hàng lưu kho', 'Adjust Stock': 'Chỉnh sửa hàng lưu kho', 'Adjustment created': 'Chỉnh sửa đã được tạo', 'Adjustment deleted': 'Chỉnh sửa đã đươc xóa', 'Adjustment modified': 'Chỉnh sửa đã được thay đổi', 'Admin Email': 'Email của quản trị viên', 'Admin Name': 'Tên quản trị viên', 'Admin Tel': 'Số điện thoại của Quản trị viên', 'Admin': 'Quản trị', 'Administration': 'Quản trị', 'Administrator': 'Quản trị viên', 'Adolescent (12-20)': 'Vị thành niên (12-20)', 'Adult (21-50)': 'Người trưởng thành (21-50)', 'Adult Psychiatric': 'Bệnh nhân tâm thần', 'Adult female': 'Nữ giới', 'Adult male': 'Đối tượng người lớn là nam ', 'Advanced Catalog Search': 'Tìm kiếm danh mục nâng cao', 'Advanced Category Search': 'Tìm kiếm danh mục nâng cao', 'Advanced Location Search': 'Tìm kiếm vị trí nâng cao', 'Advanced Search': 'Tìm kiếm nâng cao', 'Advanced Site Search': 'Tìm kiếm website nâng cao', 'Affected Persons': 'Người bị ảnh hưởng', 'Affiliation Details': 'Chi tiết liên kết', 'Affiliation added': 'Liên kết đã được thêm', 'Affiliation deleted': 'Liên kết đã được xóa', 'Affiliation updated': 'Liên kết đã được cập nhật', 'Affiliations': 'Liên kết', 'Age Group (Count)': 'Nhóm tuổi (Số lượng)', 'Age Group': 'Nhóm tuổi', 'Age group does not match actual age.': 'Nhóm tuổi không phù hợp với tuổi hiện tại', 'Aid Request Details': 'Chi tiết yêu cầu cứu trợ', 'Aid Request added': 'Đã thêm yêu cầu viện trợ', 'Aid Request deleted': 'Đã xóa yêu cầu cứu trợ', 'Aid Request updated': 'Đã cập nhật Yêu cầu cứu trợ', 'Aid Request': 'Yêu cầu cứu trợ', 'Aid Requests': 'yêu cầu cứu trợ', 'Aircraft Crash': 'Tại nạn máy bay', 'Aircraft Hijacking': 'Bắt cóc máy bay', 'Airport Closure': 'Đóng cửa sân bay', 'Airport': 'Sân bay', 'Airports': 'Sân bay', 'Airspace Closure': 'Đóng cửa trạm không gian', 'Alcohol': 'Chất cồn', 'Alerts': 'Cảnh báo', 'All Entities': 'Tất cả đối tượng', 'All Inbound & Outbound Messages are stored here': 'Tất cả tin nhắn gửi và nhận được lưu ở đây', 'All Open Tasks': 'Tất cả nhiệm vụ công khai', 'All Records': 'Tất cả hồ sơ', 'All Requested Items': 'Hàng hóa được yêu cầu', 'All Resources': 'Tất cả nguồn lực', 'All Tasks': 'Tất cả nhiệm vụ', 'All reports': 'Tất cả báo cáo', 'All selected': 'Tất cả', 'All': 'Tất cả', 'Allowed to push': 'Cho phép bấm nút', 'Allows authorized users to control which layers are available to the situation map.': 'Cho phép người dùng đã đăng nhập kiểm soát layer nào phù hợp với bản đồ tình huống', 'Alternative Item Details': 'Chi tiết mặt hàng thay thế', 'Alternative Item added': 'Mặt hàng thay thế đã được thêm', 'Alternative Item deleted': 'Mặt hàng thay thế đã được xóa', 'Alternative Item updated': 'Mặt hàng thay thế đã được cập nhật', 'Alternative Items': 'Mặt hàng thay thế', 'Ambulance Service': 'Dịch vụ xe cứu thương', 'Amount': 'Số lượng', 'An Assessment Template can be selected to create a Disaster Assessment. Within a Disaster Assessment, responses can be collected and results can analyzed as tables, charts and maps': 'Mẫu đánh giá có thể được chọn để tạo ra một Đánh giá tình hình Thảm họa. Trong Đánh giá tình hình Thảm họa, các hoạt động ứng phó có thể được tổng hợp và kết quả có thể được phân tích dưới dạng bảng, biểu đồ và bản đồ', 'An Item Category must have a Code OR a Name.': 'Danh mục hàng hóa phải có Mã hay Tên.', 'Analysis': 'Phân tích', 'Animal Die Off': 'Động vật tuyệt chủng', 'Animal Feed': 'Thức ăn động vật', 'Annual Budget deleted': 'Ngân sách năm đã được xóa', 'Annual Budget updated': 'Ngân sách năm đã được cập nhật', 'Annual Budget': 'Ngân sách năm', 'Annual Budgets': 'Ngân sách năm', 'Anonymous': 'Ẩn danh', 'Answer Choices (One Per Line)': 'Chọn câu trả lời', 'Any available Metadata in the files will be read automatically, such as Timestamp, Author, Latitude & Longitude.': 'Thông tin có sẵn trong file như Timestamp,Tác giả, Kinh độ, Vĩ độ sẽ được đọc tự động', 'Any': 'Bất cứ', 'Applicable to projects in Pacific countries only': 'Chỉ áp dụng cho dự án trong các nước thuộc khu vực Châu Á - Thái Bình Dương', 'Application Permissions': 'Chấp nhận đơn đăng ký', 'Application': 'Đơn đăng ký', 'Apply changes': 'Lưu thay đổi', 'Approval pending': 'Đang chờ phê duyệt', 'Approval request submitted': 'Yêu cầu phê duyệt đã được gửi', 'Approve': 'Phê duyệt', 'Approved By': 'Được phê duyệt bởi', 'Approved by %(first_initial)s.%(last_initial)s': 'Được phê duyệt bởi %(first_initial)s.%(last_initial)s', 'Approved': 'Đã phê duyệt', 'Approver': 'Người phê duyệt', 'ArcGIS REST Layer': 'Lớp ArcGIS REST', 'Archive not Delete': 'Bản lưu không xóa', 'Arctic Outflow': 'Dòng chảy từ Bắc Cực', 'Are you sure you want to delete this record?': 'Bạn có chắc bạn muốn xóa hồ sơ này?', 'Arrived': 'Đã đến', 'As of yet, no sections have been added to this template.': 'Chưa hoàn thành, không mục nào được thêm vào mẫu này', 'Assessment Answer Details': 'Nội dung câu trả lời trong mẫu đánh giá', 'Assessment Answer added': 'Câu trả lời trong mẫu đánh giá đã được thêm', 'Assessment Answer deleted': 'Câu trả lời trong mẫu đánh giá đã được xóa', 'Assessment Answer updated': 'Câu trả lời trong mẫu đánh giá đã được cập nhật', 'Assessment Answers': 'Câu trả lời trong mẫu đánh', 'Assessment Question Details': 'Nội dung câu trả hỏi trong mẫu đánh giá', 'Assessment Question added': 'Câu trả hỏi trong mẫu đánh giá đã được thêm', 'Assessment Question deleted': 'Câu trả hỏi trong mẫu đánh giá đã được xóa', 'Assessment Question updated': 'Câu trả hỏi trong mẫu đánh giá đã được cập nhật', 'Assessment Questions': 'Câu trả hỏi trong mẫu đánh', 'Assessment Template Details': 'Nội dung biểu mẫu đánh giá', 'Assessment Template added': 'Biểu mẫu đánh giá đã được thêm', 'Assessment Template deleted': 'Biểu mẫu đánh giá đã được xóa', 'Assessment Template updated': 'Biểu mẫu đánh giá đã được cập nhật', 'Assessment Templates': 'Biểu mẫu đánh giá', 'Assessment admin level': 'Cấp quản lý đánh giá', 'Assessment timeline': 'Khung thời gian đánh giá', 'Assessment updated': 'Đã cập nhật Trị giá tính thuế', 'Assessment': 'Đánh giá', 'Assessments': 'Đánh giá', 'Asset Details': 'Thông tin tài sản', 'Asset Log Details': 'Chi tiết nhật ký tài sản', 'Asset Log Empty': 'Xóa nhật ký tài sản', 'Asset Log Entry deleted': 'Ghi chép nhật ký tài sản đã được xóa', 'Asset Log Entry updated': 'Ghi chép nhật ký tài sản đã được cập nhật', 'Asset Log': 'Nhật ký tài sản', 'Asset Number': 'Số tài sản', 'Asset added': 'Tài sản đã được thêm', 'Asset deleted': 'Tài sản đã được xóa', 'Asset updated': 'Tài sản đã được cập nhật', 'Asset': 'Tài sản', 'Assets are resources which are not consumable but are expected back, so they need tracking.': 'Tài sản là các nguồn lực không tiêu hao và có thể được hoàn trả nên cần theo dõi tài sản', 'Assets': 'Tài sản', 'Assign Asset': 'Giao tài sản', 'Assign Human Resource': 'Phân chia nguồn nhân lực', 'Assign New Human Resource': 'Phân chia nguồn nhân lực mới', 'Assign Role to a User': 'Phân công vai trò cho người sử dụng', 'Assign Roles': 'Phân công vai trò', 'Assign Staff': 'Phân công cán bộ', 'Assign Vehicle': 'Phân công phương tiện vận chuyển', 'Assign another Role': 'Phân công vai trò khác', 'Assign to Facility/Site': 'Phân công tới Bộ phân/ Địa bàn', 'Assign to Organization': 'Phân công tới Tổ chức', 'Assign to Person': 'Phân công tới đối tượng', 'Assign': 'Phân công', 'Assigned By': 'Được phân công bởi', 'Assigned Roles': 'Vai trò được phân công', 'Assigned To': 'Được phân công tới', 'Assigned to Facility/Site': 'Được phân công tới Bộ phân/ Địa bàn', 'Assigned to Organization': 'Được phân công tới Tổ chức', 'Assigned to Person': 'Được phân công tới đối tượng', 'Assigned to': 'Được phân công tới', 'Assigned': 'Được phân công', 'Association': 'Liên hiệp', 'At or below %s': 'Tại đây hoặc phí dưới %s', 'At/Visited Location (not virtual)': 'Địa điêm ở/đã đến (không ảo)', 'Attachments': 'Đính kèm', 'Attribution': 'Quyền hạn', 'Australian Dollars': 'Đô la Úc', 'Authentication Required': 'Xác thực được yêu cầu', 'Author': 'Tác giả', 'Availability': 'Thời gian có thể tham gia', 'Available Alternative Inventories': 'Hàng tồn kho thay thế sẵn có', 'Available Forms': 'Các mẫu có sẵn', 'Available Inventories': 'Hàng tồn kho sẵn có', 'Available databases and tables': 'Cơ sở dữ liệu và bảng biểu sẵn có', 'Available in Viewer?': 'Sẵn có để xem', 'Available until': 'Sẵn sàng cho đến khi', 'Avalanche': 'Băng tuyết', 'Average': 'Trung bình', 'Award': 'Khen thưởng', 'Awards': 'Khen thưởng', 'BACK TO %(system_name_short)s': 'TRỞ LẠI %(system_name_short)s', 'BACK TO MAP VIEW': 'TRỞ LẠI XEM BẢN ĐỒ', 'BROWSE OTHER REGIONS': 'LỰA CHỌN CÁC VÙNG KHÁC', 'Baby And Child Care': 'Chăm sóc trẻ em', 'Back to Roles List': 'Quay trở lại danh sách vai trò', 'Back to Users List': 'Quay trở lại danh sách người sử dụng', 'Back to the main screen': 'Trở lại màn hình chính', 'Back': 'Trở lại', 'Background Color': 'Màu nền', 'Baldness': 'Cây trụi lá', 'Bank/micro finance': 'Tài chính Ngân hàng', 'Base %(facility)s Set': 'Tập hợp %(facility)s nền tảng', 'Base Facility/Site Set': 'Tập hợp Bộ phận/ Địa bàn nền tảng', 'Base Layer?': 'Lớp bản đồ cơ sở?', 'Base Layers': 'Lớp bản đồ cơ sở', 'Base Location': 'Địa điểm nền tảng', 'Base URL of the remote Sahana Eden instance including application path, e.g. http://www.example.org/eden': 'Đường dẫn Cơ bản của Hệ thống Sahana Eden từ xa bao gồm đường dẫn ứng dụng như http://www.example.org/eden', 'Base Unit': 'Đơn vị cơ sở', 'Basic Details': 'Chi tiết cơ bản', 'Basic information on the requests and donations, such as category, the units, contact details and the status.': 'Thông tin cơ bản về các yêu cầu và quyên góp như thể loại, tên đơn vị, chi tiết liên lạc và tình trạng', 'Basic reports on the Shelter and drill-down by region': 'Báo cáo cơ bản về nơi cư trú và báo cáo chi tiết theo vùng', 'Baud rate to use for your modem - The default is safe for most cases': 'Tốc độ truyền sử dụng cho mô đem của bạn - Chế độ mặc định là an toàn trong hầu hết các trường hợp', 'Bed Type': 'Loại Giường', 'Beneficiaries Added': 'Người hưởng lợi đã được thêm', 'Beneficiaries Deleted': 'Người hưởng lợi đã được xóa', 'Beneficiaries Details': 'Thông tin của người hưởng lợi', 'Beneficiaries Updated': 'Người hưởng lợi đã được cập nhật', 'Beneficiaries': 'Người hưởng lợi', 'Beneficiary Report': 'Báo cáo người hưởng lợi', 'Beneficiary Type Added': 'Loại người hưởng lợi đã được thêm', 'Beneficiary Type Deleted': 'Loại người hưởng lợi đã được xóa', 'Beneficiary Type Updated': 'Loại người hưởng lợi đã được cập nhật', 'Beneficiary Type': 'Loại người hưởng lợi', 'Beneficiary Types': 'Loại người hưởng lợi', 'Beneficiary': 'Người Hưởng lợi', 'Bin': 'Thùng rác', 'Bing Layer': 'Lớp thừa', 'Biological Hazard': 'Hiểm họa sinh học', 'Biscuits': 'Bánh quy', 'Blizzard': 'Bão tuyết', 'Blocked': 'Bị chặn', 'Blood Donation and Services': 'Hiến máu nhân đạo và Dịch vụ về máu', 'Blood Type (AB0)': 'Nhóm máu (ABO)', 'Blowing Snow': 'Tuyết lở', 'Body Recovery Requests': 'Yêu cầu phục hồi cơ thể', 'Body Recovery': 'Phục hồi thân thể', 'Body': 'Thân thể', 'Bomb Explosion': 'Nổ bom', 'Bomb Threat': 'Nguy cơ nổ bom', 'Bomb': 'Bom', 'Border Color for Text blocks': 'Màu viền cho khối văn bản', 'Both': 'Cả hai', 'Branch Capacity Development': 'Phát triển năng lực cho Tỉnh/ thành Hội', 'Branch Organization Details': 'Thông tin tổ chức cơ sở', 'Branch Organization added': 'Tổ chức cơ sở đã được thêm', 'Branch Organization deleted': 'Tổ chức cơ sở đã được xóa', 'Branch Organization updated': 'Tổ chức cơ sở đã được cập nhật', 'Branch Organizations': 'Tổ chức cơ sở', 'Branch': 'Cơ sở', 'Branches': 'Cơ sở', 'Brand Details': 'Thông tin nhãn hiệu', 'Brand added': 'Nhãn hiệu đã được thêm', 'Brand deleted': 'Nhãn hiệu đã được xóa', 'Brand updated': 'Nhãn hiệu đã được cập nhật', 'Brand': 'Nhãn hiệu', 'Brands': 'Nhãn hiệu', 'Breakdown': 'Chi tiết theo', 'Bridge Closed': 'Cầu đã bị đóng', 'Buddhist': 'Tín đồ Phật giáo', 'Budget Updated': 'Cập nhât ngân sách', 'Budget deleted': 'Đã xóa ngân sách', 'Budget': 'Ngân sách', 'Budgets': 'Ngân sách', 'Buffer': 'Đệm', 'Bug': 'Lỗi', 'Building Collapsed': 'Nhà bị sập', 'Building Name': 'Tên tòa nhà', 'Bulk Uploader': 'Công cụ đê tải lên số lượng lớn thông tin', 'Bundle Updated': 'Cập nhật Bundle', 'Bundles': 'Bó', 'By Warehouse': 'Bằng Kho hàng', 'By Warehouse/Facility/Office': 'Bằng Kho hàng/ Bộ phận/ Văn phòng', 'By selecting this you agree that we may contact you.': 'Bằng việc lựa chọn bạn đồng ý chúng tôi có thể liên lạc với bạn', 'CATALOGS': 'DANH MỤC', 'COPY': 'Sao chép', 'CREATE': 'TẠO', 'CSS file %s not writable - unable to apply theme!': 'không viết được file CSS %s - không thể áp dụng chủ đề', 'CV': 'Quá trình công tác', 'Calculate': 'Tính toán', 'Calculation': 'Tính toán', 'Calendar': 'Lịch', 'Camp': 'Trạm/chốt tập trung', 'Can only approve 1 record at a time!': 'Chỉ có thể phê duyệt 1 hồ sơ mỗi lần', 'Can only disable 1 record at a time!': 'Chỉ có thể vô hiệu 1 hồ sơ mỗi lần', 'Can only update 1 record at a time!': 'Chỉ có thể cập nhật 1 hồ sơ mỗi lần', 'Can read PoIs either from an OpenStreetMap file (.osm) or mirror.': 'Có thể đọc PoIs từ cả định dạng file OpenStreetMap (.osm) hoặc mirror.', 'Canadian Dollars': 'Đô la Canada', 'Cancel Log Entry': 'Hủy ghi chép nhật ký', 'Cancel Shipment': 'Hủy lô hàng vận chuyển', 'Cancel editing': 'Hủy chỉnh sửa', 'Cancel': 'Hủy', 'Canceled': 'Đã hủy', 'Cancelled': 'Đã xóa', 'Cannot delete whilst there are linked records. Please delete linked records first.': 'Không xóa được khi đang có bản thu liên quan.Hãy xóa bản thu trước', 'Cannot disable your own account!': 'Không thể vô hiệu tài khoản của chính bạn', 'Cannot make an Organization a branch of itself!': 'Không thể tạo ra tổ chức là tổ chức cơ sở của chính nó', 'Cannot open created OSM file!': 'Không thể mở file OSM đã tạo', 'Cannot read from file: %(filename)s': 'Không thể đọc file: %(filename)s', 'Cannot send messages if Messaging module disabled': 'Không thể gửi tin nhắn nếu chức năng nhắn tin bị tắt', 'Capacity Development': 'Nâng cao năng lực', 'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)': 'Nắm bắt thông tin của các nạn nhân chịu ảnh hưởng của thiên tai(Khách du lịch,Gia đình...)', 'Cardiology': 'Bệnh tim mạch', 'Cases': 'Trường hợp', 'Casual Labor': 'Nhân công thời vụ', 'Catalog Details': 'Thông tin danh mục', 'Catalog Item added': 'Mặt hàng trong danh mục đã được thêm', 'Catalog Item deleted': 'Mặt hàng trong danh mục đã được xóa', 'Catalog Item updated': 'Mặt hàng trong danh mục đã được cập nhật', 'Catalog Items': 'Mặt hàng trong danh mục', 'Catalog added': 'Danh mục đã được thêm', 'Catalog deleted': 'Danh mục đã được xóa', 'Catalog updated': 'Danh mục đã được cập nhật', 'Catalog': 'Danh mục', 'Catalogs': 'Danh mục', 'Categories': 'Chủng loại', 'Category': 'Chủng loại', 'Certificate Catalog': 'Danh mục chứng nhận', 'Certificate Details': 'Thông tin chứng nhận', 'Certificate List': 'Danh sách chứng nhận', 'Certificate Status': 'Tình trạng của chứng nhận', 'Certificate added': 'Chứng nhận đã được thêm', 'Certificate deleted': 'Chứng nhận đã được xóa', 'Certificate updated': 'Chứng nhận đã được cập nhật', 'Certificate': 'Chứng nhận', 'Certificates': 'Chứng nhận', 'Certification Details': 'Thông tin bằng cấp', 'Certification added': 'Bằng cấp đã được thêm', 'Certification deleted': 'Bằng cấp đã được xóa', 'Certification updated': 'Bằng cấp đã được cập nhật', 'Certifications': 'Bằng cấp', 'Certifying Organization': 'Tổ chức xác nhận', 'Change Password': 'Thay đổi mật khẩu', 'Chart': 'Biểu đồ', 'Check Request': 'Kiểm tra yêu cầu', 'Check for errors in the URL, maybe the address was mistyped.': 'Kiểm tra lỗi đường dẫn URL, địa chỉ có thể bị đánh sai', 'Check if the URL is pointing to a directory instead of a webpage.': 'Kiểm tra nếu đường dẫn URL chỉ dẫn đến danh bạ chứ không phải đến trang web', 'Check outbox for the message status': 'Kiểm tra hộp thư đi để xem tình trạng thư gửi đi', 'Check this to make your search viewable by others.': 'Chọn ô này để người khác có thể xem được tìm kiếm của bạn', 'Check': 'Kiểm tra', 'Check-In': 'Đăng ký', 'Check-Out': 'Thanh toán', 'Checked': 'Đã kiểm tra', 'Checking your file...': 'Kiểm tra file của bạn', 'Checklist of Operations': 'Danh sách kiểm tra các hoạt động', 'Chemical Hazard': 'Hiểm họa óa học', 'Child (2-11)': 'Trẻ em (2-11)', 'Child Abduction Emergency': 'Tình trạng khẩn cấp về lạm dụng trẻ em', 'Children (2-5 years)': 'Trẻ em (từ 2-5 tuổi)', 'Children (< 2 years)': 'Trẻ em (dưới 2 tuổi)', 'Choose Country': 'Lựa chọn quốc gia', 'Choose File': 'Chọn file', 'Choose country': 'Lựa chọn quốc gia', 'Choose': 'Lựa chọn', 'Christian': 'Tín đồ Cơ-đốc giáo', 'Church': 'Nhà thờ', 'Circumstances of disappearance, other victims/witnesses who last saw the missing person alive.': 'Hoàn cảnh mất tích, những nhân chứng nhìn thấy lần gần đây nhất nạn nhân còn sống', 'City / Town / Village': 'Phường/ Xã', 'Civil Emergency': 'Tình trạng khẩn cấp dân sự', 'Civil Society/NGOs': 'Tổ chức xã hội/NGOs', 'Clear filter': 'Xóa', 'Clear selection': 'Xóa lựa chọn', 'Clear': 'Xóa', 'Click anywhere on the map for full functionality': 'Bấm vào vị trí bất kỳ trên bản đồ để có đầy đủ chức năng', 'Click on a marker to see the Completed Assessment Form': 'Bấm vào nút đánh dấu để xem Mẫu đánh giá đã hoàn chỉnh', 'Click on the chart to show/hide the form.': 'Bấm vào biểu đồ để hiển thị/ ẩn mẫu', 'Click on the link %(url)s to reset your password': 'Bấm vào đường dẫn %(url)s khởi tạo lại mật khẩu của bạn', 'Click on the link %(url)s to verify your email': 'Bấm vào đường dẫn %(url)s để kiểm tra địa chỉ email của bạn', 'Click to dive in to regions or rollover to see more': 'Bấm để dẫn tới vùng hoặc cuộn chuột để xem gần hơn', 'Click where you want to open Streetview': 'Bấm vào chỗ bạn muốn xem ở chế độ Đường phố', 'Climate Change': 'Biến đổi khí hậu', 'Clinical Laboratory': 'Phòng thí nghiệm lâm sàng', 'Close Adjustment': 'Đóng điều chỉnh', 'Close map': 'Đóng bản đồ', 'Close': 'Đóng', 'Closed': 'Đã đóng', 'Closed?': 'Đã Đóng?', 'Cluster Details': 'Thông tin nhóm', 'Cluster Distance': 'Khoảng cách các nhóm', 'Cluster Threshold': 'Ngưỡng của mỗi nhóm', 'Cluster added': 'Nhóm đã được thêm', 'Cluster deleted': 'Nhóm đã được xóa', 'Cluster updated': 'Nhóm đã được cập nhật', 'Cluster': 'Nhóm', 'Cluster(s)': 'Nhóm', 'Clusters': 'Nhóm', 'Code Share': 'Chia sẻ mã', 'Code': 'Mã', 'Cold Wave': 'Không khí lạnh', 'Collect PIN from Twitter': 'Thu thập mã PIN từ Twitter', 'Color of selected Input fields': 'Màu của trường đã được chọn', 'Column Choices (One Per Line': 'Chọn cột', 'Columns': 'Cột', 'Combined Method': 'phương pháp được kết hợp', 'Come back later. Everyone visiting this site is probably experiencing the same problem as you.': 'Quay lại sau. Mọi người ghé thăm trang này đều gặp vấn đề giống bạn.', 'Come back later.': 'Quay lại sau.', 'Comment': 'Ghi chú', 'Comments': 'Ghi chú', 'Commit Date': 'Thời điểm cam kết', 'Commit': 'Cam kết', 'Commit. Status': 'Tình trạng cam kết', 'Commitment Added': 'Cam kết đã được thêm', 'Commitment Canceled': 'Cam kết đã được hủy', 'Commitment Details': 'Thông tin của cam kết', 'Commitment Item Details': 'Thông tin mặt hàng cam kết', 'Commitment Item added': 'Mặt hàng cam kết đã được thêm', 'Commitment Item deleted': 'Mặt hàng cam kết đã được xóa', 'Commitment Item updated': 'Mặt hàng cam kết đã được cập nhật', 'Commitment Items': 'Mặt hàng cam kết', 'Commitment Updated': 'Cam kết đã được cập nhật', 'Commitment': 'Cam kết', 'Commitments': 'Cam kết', 'Committed By': 'Cam kết bởi', 'Committed People': 'Người đã Cam kết', 'Committed Person Details': 'Thông tin người đã cam kết', 'Committed Person updated': 'Người cam kết đã được cập nhật', 'Committed': 'Đã Cam kết', 'Committing Organization': 'Tổ chức cam kết', 'Committing Person': 'Người đang cam Kết', 'Committing Warehouse': 'Kho hàng đang cam kết', 'Commodities Loaded': 'Hàng hóa được đưa lên xe', 'Commune Name': 'Tên xã', 'Commune': 'Phường/ Xã', 'Communicable Diseases': 'Bệnh dịch lây truyền', 'Communities': 'Cộng đồng', 'Community Added': 'Công đồng đã được thêm', 'Community Contacts': 'Thông tin liên hệ của cộng đồng', 'Community Deleted': 'Công đồng đã được xóa', 'Community Details': 'Thông tin về cộng đồng', 'Community Health Center': 'Trung tâm sức khỏe cộng đồng', 'Community Health': 'Chăm sóc sức khỏe cộng đồng', 'Community Member': 'Thành viên cộng đồng', 'Community Updated': 'Công đồng đã được cập nhật', 'Community': 'Cộng đồng', 'Community-based DRR': 'GTRRTH dựa vào cộng đồng', 'Company': 'Công ty', 'Competency Rating Catalog': 'Danh mục xếp hạng năng lực', 'Competency Rating Details': 'Thông tin xếp hạng năng lực', 'Competency Rating added': 'Xếp hạng năng lực đã được thêm', 'Competency Rating deleted': 'Xếp hạng năng lực đã được xóa', 'Competency Rating updated': 'Xếp hạng năng lực đã được cập nhật', 'Competency Rating': 'Xếp hạng năng lực', 'Competency': 'Cấp độ thành thục', 'Complete Returns': 'Quay lại hoàn toàn', 'Complete Unit Label for e.g. meter for m.': 'Nhãn đơn vị đầy đủ. Ví dụ mét cho m.', 'Complete': 'Hoàn thành', 'Completed Assessment Form Details': 'Thông tin biểu mẫu đánh giá đã hoàn thiện', 'Completed Assessment Form deleted': 'Biểu mẫu đánh giá đã hoàn thiện đã được thêm', 'Completed Assessment Form entered': 'Biểu mẫu đánh giá đã hoàn thiện đã được nhập', 'Completed Assessment Form updated': 'Biểu mẫu đánh giá đã hoàn thiện đã được cập nhật', 'Completed Assessment Forms': 'Biểu mẫu đánh giá đã hoàn thiện', 'Completed Assessments': 'Các Đánh giá đã Hoàn thành', 'Completed': 'Đã hoàn thành', 'Completion Question': 'Câu hỏi hoàn thành', 'Complex Emergency': 'Tình huống khẩn cấp phức tạp', 'Complexion': 'Cục diện', 'Compose': 'Soạn thảo', 'Condition': 'Điều kiện', 'Conduct a Disaster Assessment': 'Thực hiện đánh giá thảm họa', 'Config added': 'Cấu hình đã được thêm', 'Config updated': 'Cập nhật tùy chỉnh', 'Config': 'Tùy chỉnh', 'Configs': 'Cấu hình', 'Configuration': 'Cấu hình', 'Configure Layer for this Symbology': 'Thiết lập cấu hình lớp cho biểu tượng này', 'Configure Run-time Settings': 'Thiết lập cấu hình cho cài đặt thời gian hoạt động', 'Configure connection details and authentication': 'Thiêt lập cấu hình cho thông tin kết nối và xác thực', 'Configure resources to synchronize, update methods and policies': 'Cài đặt cấu hình các nguồn lực để đồng bộ, cập nhật phương pháp và chính sách', 'Configure the default proxy server to connect to remote repositories': 'Thiết lập cấu hình cho máy chủ mặc định để kết nối tới khu vực lưu trữ từ xa', 'Configure/Monitor Synchonization': 'Thiêt lập cấu hình/ giám sát đồng bộ hóa', 'Confirm Shipment Received': 'Xác nhận lô hàng đã nhận', 'Confirm that some items were returned from a delivery to beneficiaries and they will be accepted back into stock.': 'Xác nhận một số mặt hàng đã được trả lại từ bên vận chuyển tới người hưởng lợi và các mặt hàng này sẽ được chấp thuân nhập trở lại kho.', 'Confirm that the shipment has been received by a destination which will not record the shipment directly into the system and confirmed as received.': 'Xác nhận lô hàng đã nhận đến điểm gửi mà không biên nhập lô hàng trực tiếp vào hệ thống và đã xác nhận việc nhận hàng', 'Confirmed': 'Đã xác nhận', 'Confirming Organization': 'Tổ chức xác nhận', 'Conflict Policy': 'Xung đột Chính sách', 'Consumable': 'Có thể tiêu dùng được', 'Contact Added': 'Thông tin liên hệ đã được thêm', 'Contact Data': 'Dữ liệu thông tin liên hệ', 'Contact Deleted': 'Thông tin liên hệ đã được xóa', 'Contact Details': 'Chi tiết thông tin liên hệ', 'Contact Info': 'Thông tin liên hệ', 'Contact Information Added': 'Thông tin liên hệ đã được thêm', 'Contact Information Deleted': 'Thông tin liên hệ đã được xóa', 'Contact Information Updated': 'Thông tin liên hệ đã được cập nhật', 'Contact Information': 'Thông tin liên hệ', 'Contact Method': 'Phương pháp liên hệ', 'Contact People': 'Người liên hệ', 'Contact Person': 'Người liên hệ', 'Contact Persons': 'Người liên hệ', 'Contact Updated': 'Thông tin liên hệ đã được cập nhật', 'Contact us': 'Liên hệ chúng tôi', 'Contact': 'Thông tin liên hệ', 'Contacts': 'Thông tin liên hệ', 'Contents': 'Nội dung', 'Context': 'Bối cảnh', 'Contract End Date': 'Ngày kết thúc hợp đồng', 'Contributor': 'Người đóng góp', 'Controller': 'Người kiểm soát', 'Conversion Tool': 'Công cụ chuyển đổi', 'Coordinate Layer': 'Lớp điều phối', 'Copy': 'Sao chép', 'Corn': 'Ngũ cốc', 'Corporate Entity': 'Thực thể công ty', 'Could not add person record': 'Không thêm được hồ sơ cá nhân', 'Could not auto-register at the repository, please register manually.': 'Không thể đăng ký tự động vào kho dữ liệu, đề nghị đăng ký thủ công', 'Could not create record.': 'Không tạo được hồ sơ', 'Could not generate report': 'Không tạo được báo cáo', 'Could not initiate manual synchronization.': 'Không thể bắt đầu việc đồng bộ hóa thủ công', 'Count of Question': 'Số lượng câu Hỏi', 'Count': 'Số lượng', 'Countries': 'Quốc gia', 'Country Code': 'Quốc gia cấp', 'Country in': 'Quốc gia ở', 'Country is required!': 'Quốc gia bắt buộc điền!', 'Country': 'Quốc gia', 'County / District (Count)': 'Quận / Huyện (số lượng)', 'County / District': 'Quận/ Huyện', 'Course Catalog': 'Danh mục khóa tập huấn', 'Course Certificate Details': 'Thông tin chứng nhận khóa tập huấn', 'Course Certificate added': 'Chứng nhận khóa tập huấn đã được thêm', 'Course Certificate deleted': 'Chứng nhận khóa tập huấn đã được xóa', 'Course Certificate updated': 'Chứng nhận khóa tập huấn đã được cập nhật', 'Course Certificates': 'Chứng chỉ khóa học', 'Course Details': 'Thông tin khóa tập huấn', 'Course added': 'Khóa tập huấn đã được thêm', 'Course deleted': 'Khóa tập huấn đã được xóa', 'Course updated': 'Khóa tập huấn đã được cập nhật', 'Course': 'Khóa tập huấn', 'Create': 'Thêm', 'Create & manage Distribution groups to receive Alerts': 'Tạo & quản lý nhóm phân phát để nhận cảnh báo', 'Create Activity Type': 'Thêm loại hình hoạt động', 'Create Activity': 'Thêm hoạt động', 'Create Assessment Template': 'Thêm biểu mẫu đánh giá', 'Create Asset': 'Thêm tài sản', 'Create Award': 'Thêm khen thưởng', 'Create Beneficiary Type': 'Thêm loại người hưởng lợi', 'Create Brand': 'Thêm nhãn hàng', 'Create Catalog Item': 'Thêm mặt hàng vào danh mục', 'Create Catalog': 'Thêm danh mục', 'Create Certificate': 'Thêm chứng nhận', 'Create Cluster': 'Thêm nhóm', 'Create Community': 'Thêm cộng đồng', 'Create Competency Rating': 'Thêm xếp loại năng lực', 'Create Contact': 'Thêm liên lạc', 'Create Course': 'Thêm khóa tập huấn', 'Create Department': 'Thêm phòng/ban', 'Create Disaster Assessment': 'Thêm báo cáo đánh giá thảm họa', 'Create Facility Type': 'Thêm loại hình bộ phận', 'Create Facility': 'Thêm bộ phận', 'Create Feature Layer': 'Thêm lớp chức năng', 'Create Group Entry': 'Tạo ghi chép nhóm', 'Create Group': 'Thêm nhóm', 'Create Hazard': 'Thêm hiểm họa', 'Create Hospital': 'Thêm Bệnh viện', 'Create Incident Report': 'Thêm báo cáo sự cố', 'Create Incident': 'Thêm sự kiện', 'Create Item Category': 'Thêm loại hàng hóa', 'Create Item Pack': 'Thêm gói hàng hóa', 'Create Item': 'Tạo mặt hàng mới', 'Create Item': 'Thêm hàng hóa', 'Create Job Title': 'Thêm chức danh công việc', 'Create Job': 'Thêm công việc', 'Create Kit': 'Thêm dụng cụ', 'Create Layer': 'Thêm lớp', 'Create Location Hierarchy': 'Thêm thứ tự địa điểm', 'Create Location': 'Thêm địa điểm', 'Create Mailing List': 'Thêm danh sách gửi thư', 'Create Map Configuration': 'Thêm cài đặt cấu hình bản đồ', 'Create Marker': 'Thêm công cụ đánh dấu', 'Create Membership Type': 'Thêm loại hội viên', 'Create Milestone': 'Thêm mốc quan trọng', 'Create National Society': 'Thêm Hội Quốc gia', 'Create Office Type': 'Thêm loại hình văn phòng mới', 'Create Office': 'Thêm văn phòng', 'Create Organization Type': 'Thêm loại hình tổ chức', 'Create Organization': 'Thêm tổ chức', 'Create PDF': 'Tạo PDF', 'Create Program': 'Thêm chương trình', 'Create Project': 'Thêm dự án', 'Create Projection': 'Thêm dự đoán', 'Create Question Meta-Data': 'Thêm siêu dữ liệu câu hỏi', 'Create Reference Document': 'Thêm tài liệu tham chiếu', 'Create Repository': 'Thêm kho chứa', 'Create Request': 'Khởi tạo yêu cầu', 'Create Resource': 'Thêm nguồn lực', 'Create Role': 'Thêm vai trò', 'Create Room': 'Thêm phòng', 'Create Sector': 'Thêm lĩnh vực', 'Create Shelter': 'Thêm Nơi cư trú mới', 'Create Skill Type': 'Thêm loại kỹ năng', 'Create Skill': 'Thêm kỹ năng', 'Create Staff Member': 'Thêm cán bộ', 'Create Status': 'Thêm trạng thái', 'Create Symbology': 'Thêm biểu tượng', 'Create Task': 'Thêm nhiệm vụ', 'Create Team': 'Tạo đội TNV', 'Create Theme': 'Thêm chủ đề', 'Create Training Event': 'Thêm khóa tập huấn', 'Create User': 'Thêm người dùng', 'Create Volunteer Cluster Position': 'Thêm vi trí của nhóm tình nguyện viên', 'Create Volunteer Cluster Type': 'Thêm loại hình nhóm tình nguyện viên', 'Create Volunteer Cluster': 'Thêm nhóm tình nguyện viên', 'Create Volunteer': 'Thêm tình nguyện viên', 'Create Warehouse': 'Thêm kho hàng', 'Create a Person': 'Thêm họ tên', 'Create a group entry in the registry.': 'Tạo ghi chép nhóm trong hồ sơ đăng ký', 'Create a new Team': 'Tạo đội TNV mới', 'Create a new facility or ensure that you have permissions for an existing facility.': 'Tạo tiện ích mới hoặc đảm bảo rằng bạn có quyền truy cập vào tiện ích sẵn có', 'Create a new organization or ensure that you have permissions for an existing organization.': 'Tạo tổ chức mới hoặc đảm bảo rằng bạn có quyền truy cập vào một tổ chức có sẵn', 'Create alert': 'Tạo cảnh báo', 'Create an Assessment Question': 'Thêm câu hỏi trong mẫu đánh giá', 'Create search': 'Thêm tìm kiếm', 'Create template': 'Tạo mẫu biểu', 'Created By': 'Tạo bởi', 'Created by': 'Tạo bởi', 'Credential Details': 'Thông tin thư ủy nhiệm', 'Credential added': 'Thư ủy nhiệm đã được thêm', 'Credential deleted': 'Thư ủy nhiệm đã được xóa', 'Credential updated': 'Thư ủy nhiệm đã được cập nhật', 'Credentialling Organization': 'Tổ chức ủy nhiệm', 'Credentials': 'Thư ủy nhiệm', 'Crime': 'Tội phạm', 'Criteria': 'Tiêu chí', 'Critical Infrastructure': 'Cở sở hạ tầng trọng yếu', 'Currency': 'Tiền tệ', 'Current Group Members': 'Nhóm thành viên hiện tại', 'Current Home Address': 'Địa chỉ nhà riêng hiện tại', 'Current Identities': 'Nhận dạng hiện tại', 'Current Location': 'Vị trí hiện tại', 'Current Memberships': 'Thành viên hiện tại', 'Current Owned By (Organization/Branch)': 'Hiện tại đang được sở hữu bởi (Tổ chức/ cơ sở)', 'Current Status': 'Trạng thái hiện tại', 'Current Twitter account': 'Tài khoản Twitter hiện tại', 'Current request': 'Yêu cầu hiện tại', 'Current response': 'Hoạt động ưng phó hiện tại', 'Current session': 'Phiên họp hiện tại', 'Current': 'Đang thực hiện', 'Currently no Certifications registered': 'Hiện tại chưa có chứng nhận nào được đăng ký', 'Currently no Course Certificates registered': 'Hiện tại chưa có chứng nhận khóa tập huấn nào được đăng ký', 'Currently no Credentials registered': 'Hiện tại chưa có thư ủy nhiệm nào được đăng ký', 'Currently no Participants registered': 'Hiện tại chưa có người tham dự nào đăng ký', 'Currently no Professional Experience entered': 'Hiện tại chưa có kinh nghiệm nghề nghiệp nào được nhập', 'Currently no Skill Equivalences registered': 'Hiện tại chưa có kỹ năng tương đương nào được đăng ký', 'Currently no Skills registered': 'Hiện tại chưa có kỹ năng nào được đăng ký', 'Currently no Trainings registered': 'Hiện tại chưa có khóa tập huấn nào được đăng ký', 'Currently no entries in the catalog': 'Hiện chưa có hồ sơ nào trong danh mục', 'Currently no hours recorded for this volunteer': 'Hiện tại chưa có thời gian hoạt động được ghi cho tình nguyện viên này', 'Currently no programmes registered': 'Hiện tại chưa có chương trình nào được đăng ký', 'Currently no staff assigned': 'Hiện tại chưa có cán bộ nào được phân công', 'Currently no training events registered': 'Hiện tại chưa có khóa tập huấn nào được đăng ký', 'Customer': 'Khách hàng', 'Customisable category of aid': 'Các tiêu chí cứu trợ có thể tùy chỉnh', 'Cyclone': 'Gió xoáy', 'DATA QUALITY': 'CHẤT LƯỢNG DỮ LIỆU', 'DATA/REPORT': 'DỮ LIỆU/BÁO CÁO', 'DECIMAL_SEPARATOR': 'Ngăn cách bằng dấu phẩy', 'DELETE': 'XÓA', 'DRR': 'GTRRTH', 'DRRPP Extensions': 'Gia hạn DRRPP', 'Daily Work': 'Công việc hàng ngày', 'Daily': 'Hàng ngày', 'Dam Overflow': 'Tràn đập', 'Damaged': 'Thiệt hại', 'Dangerous Person': 'Người nguy hiểm', 'Dashboard': 'Bảng điều khiển', 'Data Quality': 'Chất lượng Dữ liệu', 'Data Source': 'Nguồn Dữ liệu', 'Data Type': 'Loại dữ liệu', 'Data added to Theme Layer': 'Dữ liệu đã được thêm vào lớp chủ đề', 'Data import error': 'Lỗi nhập khẩu dữ liệu', 'Data uploaded': 'Dữ liệu đã được tải lên', 'Data': 'Dữ liệu', 'Data/Reports': 'Dữ liệu/Báo cáo', 'Database': 'Cơ sở Dữ liệu', 'Date Available': 'Ngày rãnh rỗi', 'Date Created': 'Ngày đã được tạo', 'Date Due': 'Ngày đến hạn', 'Date Expected': 'Ngày được mong muốn', 'Date Joined': 'Ngày tham gia', 'Date Needed By': 'Ngày cần bởi', 'Date Published': 'Ngày xuất bản', 'Date Question': 'Hỏi Ngày', 'Date Range': 'Khoảng thời gian', 'Date Received': 'Ngày Nhận được', 'Date Released': 'Ngày Xuất ra', 'Date Repacked': 'Ngày Đóng gói lại', 'Date Requested': 'Ngày Đề nghị', 'Date Required Until': 'Trước Ngày Đòi hỏi ', 'Date Required': 'Ngày Đòi hỏi', 'Date Sent': 'Ngày gửi', 'Date Taken': 'Ngày Nhận được', 'Date Until': 'Trước Ngày', 'Date and Time of Goods receipt. By default shows the current time but can be modified by editing in the drop down list.': 'Ngày giờ nhận hàng hóa.Hiển thị thời gian theo mặc định nhưng vẫn có thể chỉnh sửa', 'Date and Time': 'Ngày và giờ', 'Date must be %(max)s or earlier!': 'Ngày phải %(max)s hoặc sớm hơn!', 'Date must be %(min)s or later!': 'Ngày phải %(min)s hoặc muộn hơn!', 'Date must be between %(min)s and %(max)s!': 'Ngày phải trong khoản %(min)s và %(max)s!', 'Date of Birth': 'Ngày Sinh', 'Date of Report': 'Ngày báo cáo', 'Date of adjustment': 'Điều chỉnh ngày', 'Date of submission': 'Ngày nộp', 'Date resigned': 'Ngày từ nhiệm', 'Date': 'Ngày bắt đầu', 'Date/Time of Alert': 'Ngày/Giờ Cảnh báo', 'Date/Time of Dispatch': 'Ngày/Giờ Gửi', 'Date/Time of Find': 'Ngày giờ tìm kiếm', 'Date/Time': 'Ngày/Giờ', 'Day': 'Ngày', 'De-duplicator': 'Bộ chống trùng', 'Dead Bodies': 'Các xác chết', 'Dead Body Reports': 'Báo cáo thiệt hại về người', 'Dead Body': 'Xác chết', 'Deaths/24hrs': 'Số người chết/24h', 'Deceased': 'Đã chết', 'Decimal Degrees': 'Độ âm', 'Decision': 'Quyết định', 'Decline failed': 'Thất bại trong việc giảm', 'Default Base layer?': 'Lớp bản đồ cơ sở mặc định', 'Default Location': 'Địa điểm mặc định', 'Default Marker': 'Đánh dấu mặc định', 'Default Realm = All Entities the User is a Staff Member of': 'Realm mặc định=tất cả các đơn vị, người Sử dụng là cán bộ thành viên của', 'Default Realm': 'Realm mặc định', 'Default map question': 'Câu hỏi bản đồ mặc định', 'Default synchronization policy': 'Chính sách đồng bộ hóa mặc định', 'Default': 'Mặc định', 'Defaults': 'Mặc định', 'Defines the icon used for display of features on handheld GPS.': 'Định nghĩa biểu tượng được sử dụng để miêu tả các chức năng trên máy GPS cầm tay.', 'Defines the icon used for display of features on interactive map & KML exports.': 'Định nghĩa biểu tượng được sử dụng để miêu tả các chức năng trên bản đồ tương tác và chiết xuất KML.', 'Degrees in a latitude must be between -90 to 90.': 'Giá trị vĩ độ phải trong khoảng -90 tới 90', 'Degrees in a longitude must be between -180 to 180.': 'Giá trị kinh độ phải nằm giữa -180 tới 180', 'Degrees must be a number.': 'Độ: phải hiển thị bằng số', 'Delete Affiliation': 'Xóa liên kết', 'Delete Aid Request': 'Xóa yêu cầu cứu trợ', 'Delete Alternative Item': 'Xóa mặt hàng thay thế', 'Delete Asset Log Entry': 'Xóa ghi chép nhật ký tài sản', 'Delete Asset': 'Xóa tài sản', 'Delete Branch': 'Xóa tổ chức cơ sở', 'Delete Brand': 'Xóa nhãn hiệu', 'Delete Budget': 'Xóa ngân sách', 'Delete Catalog Item': 'Xóa mặt hang trong danh mục', 'Delete Catalog': 'Xóa danh mục', 'Delete Certificate': 'Xóa chứng chỉ', 'Delete Certification': 'Xóa bằng cấp', 'Delete Cluster': 'Xóa nhóm', 'Delete Commitment Item': 'Xóa mặt hàng cam kết', 'Delete Commitment': 'Xóa cam kết', 'Delete Competency Rating': 'Xóa xếp loại năng lực', 'Delete Config': 'Xóa cấu hình', 'Delete Contact Information': 'Xóa thông tin liên hệ', 'Delete Course Certificate': 'Xóa chứng chỉ khóa học', 'Delete Course': 'Xóa khóa học', 'Delete Credential': 'Xóa thư ủy nhiệm', 'Delete Data from Theme layer': 'Xoá dữ liệu khỏi lớp chủ đề', 'Delete Department': 'Xóa phòng/ban', 'Delete Document': 'Xóa tài liệu', 'Delete Donor': 'Xóa nhà tài trợ', 'Delete Facility Type': 'Xóa loại hinh bộ phận', 'Delete Facility': 'Xóa bộ phận', 'Delete Feature Layer': 'Xóa lớp chức năng', 'Delete Group': 'Xóa nhóm', 'Delete Hazard': 'Xóa hiểm họa', 'Delete Hospital': 'Xóa Bệnh viện', 'Delete Hours': 'Xóa thời gian hoạt động', 'Delete Image': 'Xóa hình ảnh', 'Delete Incident Report': 'Xóa báo cáo sự kiện', 'Delete Inventory Store': 'Xóa kho lưu trữ', 'Delete Item Category': 'Xóa danh mục hàng hóa', 'Delete Item Pack': 'Xóa gói hàng', 'Delete Item from Request': 'Xóa mặt hàng từ yêu cầu', 'Delete Item': 'Xóa mặt hàng', 'Delete Job Role': 'Xóa vai trò công việc', 'Delete Job Title': 'Xóa chức danh', 'Delete Kit': 'Xóa dụng cụ', 'Delete Layer': 'Xóa lớp', 'Delete Location Hierarchy': 'Xóa thứ tự địa điểm', 'Delete Location': 'Xóa địa điểm', 'Delete Mailing List': 'Xóa danh sách gửi thư', 'Delete Map Configuration': 'Xóa cài đặt cấu hình bản đồ', 'Delete Marker': 'Xóa công cụ đánh dấu', 'Delete Member': 'Xóa hội viên', 'Delete Membership Type': 'Xóa loại hình nhóm hội viên', 'Delete Membership': 'Xóa nhóm hội viên', 'Delete Message': 'Xóa tin nhắn', 'Delete Metadata': 'Xóa siêu dữ liệu', 'Delete National Society': 'Xóa Hội Quốc gia', 'Delete Office Type': 'Xóa loại hình văn phòng', 'Delete Office': 'Xóa văn phòng', 'Delete Order': 'Xóa đơn đặt hàng', 'Delete Organization Domain': 'Xóa lĩnh vực hoạt động của tổ chức', 'Delete Organization Type': 'Xóa loại hình tổ chức', 'Delete Organization': 'Xóa tổ chức', 'Delete Participant': 'Xóa người tham dự', 'Delete Partner Organization': 'Xóa tổ chức đối tác', 'Delete Person': 'Xóa đối tượng', 'Delete Photo': 'Xóa ảnh', 'Delete Professional Experience': 'Xóa kinh nghiệm nghề nghiệp', 'Delete Program': 'Xóa chương trình', 'Delete Project': 'Xóa dự án', 'Delete Projection': 'Xóa dự đoán', 'Delete Received Shipment': 'Xóa lô hàng đã nhận', 'Delete Record': 'Xóa hồ sơ', 'Delete Report': 'Xóa báo cáo', 'Delete Request Item': 'Xóa yêu cầu hàng hóa', 'Delete Request': 'Xóa yêu cầu', 'Delete Role': 'Xóa vai trò', 'Delete Room': 'Xóa phòng', 'Delete Sector': 'Xóa lĩnh vực', 'Delete Sent Shipment': 'Xóa lô hàng đã gửi', 'Delete Service Profile': 'Xóa hồ sơ đăng ký dịch vụ', 'Delete Shipment Item': 'Xóa mặt hàng trong lô hàng', 'Delete Skill Equivalence': 'Xóa kỹ năng tương đương', 'Delete Skill Type': 'Xóa loại kỹ năng', 'Delete Skill': 'Xóa kỹ năng', 'Delete Staff Assignment': 'Xóa phân công cho cán bộ', 'Delete Staff Member': 'Xóa cán bộ', 'Delete Status': 'Xóa tình trạng', 'Delete Stock Adjustment': 'Xóa điều chỉnh hàng lưu kho', 'Delete Supplier': 'Xóa nhà cung cấp', 'Delete Survey Question': 'Xóa câu hỏi khảo sát', 'Delete Survey Template': 'Xóa mẫu khảo sát', 'Delete Symbology': 'Xóa biểu tượng', 'Delete Theme': 'Xóa chủ đề', 'Delete Training Event': 'Xóa sự kiện tập huấn', 'Delete Training': 'Xóa tập huấn', 'Delete Unit': 'Xóa đơn vị', 'Delete User': 'Xóa người dùng', 'Delete Volunteer Cluster Position': 'Xóa vị trí nhóm tình nguyện viên', 'Delete Volunteer Cluster Type': 'Xóa loại hình nhóm tình nguyện viên', 'Delete Volunteer Cluster': 'Xóa nhóm tình nguyện viên', 'Delete Volunteer Role': 'Xóa vai trò của tình nguyện viên', 'Delete Volunteer': 'Xóa tình nguyện viên', 'Delete Warehouse': 'Xóa kho hàng', 'Delete all data of this type which the user has permission to before upload. This is designed for workflows where the data is maintained in an offline spreadsheet and uploaded just for Reads.': 'Xóa tất cả dữ liệu loại này mà người dùng có quyền truy cập trước khi tải lên. Việc này được thiết kế cho chu trình làm việc mà dữ liệu được quản lý trên excel ngoại tuyến và được tải lên chỉ để đọc.', 'Delete from Server?': 'Xóa khỏi máy chủ', 'Delete saved search': 'Xóa tìm kiếm đã lưu', 'Delete this Assessment Answer': 'Xóa câu trả lời này trong mẫu đánh giá', 'Delete this Assessment Question': 'Xóa câu hỏi này trong mẫu đánh giá', 'Delete this Assessment Template': 'Xóa biểu mẫu đánh giá này', 'Delete this Completed Assessment Form': 'Xóa biểu mẫu đánh giá đã được hoàn thiện này', 'Delete this Disaster Assessment': 'Xóa đánh giá thảm họa này', 'Delete this Question Meta-Data': 'Xóa siêu dữ liệu câu hỏi này', 'Delete this Template Section': 'Xóa nội dung này trong biểu mẫu', 'Delete': 'Xóa', 'Deliver To': 'Gửi tới', 'Delivered By': 'Được bởi', 'Delivered To': 'Đã gửi tới', 'Demographic Data Details': 'Thông tin số liệu dân số', 'Demographic Data added': 'Số liệu dân số đã được thêm', 'Demographic Data deleted': 'Số liệu dân số đã được xóa', 'Demographic Data updated': 'Số liệu dân số đã được cập nhật', 'Demographic Data': 'Số liệu dân số', 'Demographic Details': 'Thông tin dân số', 'Demographic Source Details': 'Thông tin về nguồn dữ liệu dân số', 'Demographic Sources': 'Nguồn dữ liệu dân số', 'Demographic added': 'Dữ liệu nhân khẩu đã được thêm', 'Demographic data': 'Số liệu dân số', 'Demographic deleted': 'Dữ liệu nhân khẩu đã được xóa', 'Demographic source added': 'Nguồn số liệu dân số đã được thêm', 'Demographic source deleted': 'Nguồn số liệu dân số đã được xóa', 'Demographic source updated': 'Nguồn số liệu dân số đã được cập nhật', 'Demographic updated': 'Dữ liệu nhân khẩu đã được cập nhật', 'Demographic': 'Nhân khẩu', 'Demographics': 'Nhân khẩu', 'Demonstrations': 'Trình diễn', 'Dental Examination': 'Khám nha khoa', 'Dental Profile': 'Hồ sơ khám răng', 'Department / Unit': 'Ban / Đơn vị', 'Department Catalog': 'Danh mục phòng/ban', 'Department Details': 'Thông tin phòng/ban', 'Department added': 'Phòng ban đã được thêm', 'Department deleted': 'Phòng ban đã được xóa', 'Department updated': 'Phòng ban đã được cập nhật', 'Deployment Location': 'Địa điểm điều động', 'Deployment Request': 'Yêu cầu điều động', 'Deployment': 'Triển khai', 'Describe the condition of the roads to your hospital.': 'Mô tả tình trạng các con đường tới bệnh viện.', 'Describe the procedure which this record relates to (e.g. "medical examination")': 'Mô tả qui trình liên quan tới hồ sơ này (ví dụ: "kiểm tra sức khỏe")', 'Description of Contacts': 'Mô tả thông tin mối liên lạc', 'Description of defecation area': 'Mo tả khu vực defecation', 'Description': 'Mô tả', 'Design, deploy & analyze surveys.': 'Thiết kế, triển khai và phân tích đánh giá.', 'Destination': 'Điểm đến', 'Destroyed': 'Bị phá hủy', 'Detailed Description/URL': 'Mô tả chi tiêt/URL', 'Details field is required!': 'Ô Thông tin chi tiết là bắt buộc!', 'Details of Disaster Assessment': 'Thông tin chi tiết về đánh giá thảm họa', 'Details of each question in the Template': 'Chi tiết về mỗi câu hỏi trong biểu mẫu', 'Details': 'Chi tiết', 'Dignitary Visit': 'Chuyến thăm cấp cao', 'Direction': 'Định hướng', 'Disable': 'Vô hiệu', 'Disabled': 'Đã tắt', 'Disaster Assessment Chart': 'Biểu đồ đánh giá thảm họa', 'Disaster Assessment Map': 'Bản đồ đánh giá thảm họa', 'Disaster Assessment Summary': 'Tóm tắt đánh giá thảm họa', 'Disaster Assessment added': 'Báo cáo đánh giá thảm họa đã được thêm', 'Disaster Assessment deleted': 'Báo cáo đánh giá thảm họa đã được xóa', 'Disaster Assessment updated': 'Báo cáo đánh giá thảm họa đã được cập nhật', 'Disaster Assessments': 'Đánh giá thảm họa', 'Disaster Risk Management': 'Quản lý rủi ro thảm họa', 'Disaster Victim Identification': 'Nhận dạng nạn nhân trong thảm họa', 'Discussion Forum': 'Diễn đàn thảo luận', 'Dispatch Time': 'Thời gian gửi đi', 'Dispatch': 'Gửi đi', 'Dispensary': 'Y tế dự phòng', 'Displaced Populations': 'Dân cư bị sơ tán', 'Display Chart': 'Hiển thị biểu đồ', 'Display Polygons?': 'Hiển thị hình đa giác?', 'Display Question on Map': 'Hiển thị câu hỏi trên bản đồ', 'Display Routes?': 'Hiển thị tuyến đường?', 'Display Selected Questions': 'Hiển thị câu hỏi được lựa chọn', 'Display Tracks?': 'Hiển thị dấu vết?', 'Display Waypoints?': 'Hiển thị các cột báo trên đường?', 'Display': 'Hiển thị', 'Distance from %s:': 'Khoảng cách từ %s:', 'Distribution Item Details': 'Chi tiết hàng hóa cứu trợ ', 'Distribution Item': 'Hàng hóa đóng góp', 'Distribution groups': 'Nhóm cấp phát', 'Distribution': 'Cấp phát', 'District': 'Quận/ Huyện', 'Diversifying Livelihoods': 'Đa dạng nguồn sinh kế', 'Divorced': 'Ly hôn', 'Do you really want to approve this record?': 'Bạn có thực sự muốn chấp thuân hồ sơ này không?', 'Do you really want to delete these records?': 'Bạn có thực sự muốn xóa các hồ sơ này không?', 'Do you really want to delete this record? (This action can not be reversed)': 'Bạn có thực sự muốn xóa hồ sơ này không? (Hồ sơ không thể khôi phục lại sau khi xóa)', 'Do you want to cancel this received shipment? The items will be removed from the Warehouse. This action CANNOT be undone!': 'Bạn có muốn hủy lô hàng đã nhận được này không? Hàng hóa này sẽ bị xóa khỏi Kho hàng. Dữ liệu không thể khôi phục lại sau khi xóa!', 'Do you want to cancel this sent shipment? The items will be returned to the Warehouse. This action CANNOT be undone!': 'Bạn có muốn hủy Lô hàng đã nhận được này không? Hàng hóa này sẽ được trả lại Kho hàng. Dữ liệu không thể khôi phục lại sau khi xóa!', 'Do you want to close this adjustment?': 'Bạn có muốn đóng điều chỉnh này lại?', 'Do you want to complete the return process?': 'Bạn có muốn hoàn thành quá trình trả lại hàng này?', 'Do you want to over-write the file metadata with new default values?': 'Bạn có muốn thay dữ liệu file bằng giá trị mặc định mới không?', 'Do you want to receive this shipment?': 'Bạn có muốn nhận lô hàng này?', 'Do you want to send this shipment?': 'Bạn có muốn gửi lô hàng này?', 'Document Details': 'Chi tiết tài liệu', 'Document Scan': 'Quyét Tài liệu', 'Document added': 'Tài liệu đã được thêm', 'Document deleted': 'Tài liệu đã được xóa', 'Document updated': 'Tài liệu đã được cập nhật', 'Document': 'Tài liệu', 'Documents': 'Tài liệu', 'Doing nothing (no structured activity)': 'Không làm gì (không có hoạt động theo kế hoạch', 'Domain': 'Phạm vi hoạt động', 'Domestic chores': 'Công việc nội trợ', 'Donated': 'Đã tài trợ', 'Donating Organization': 'Tổ chức tài trợ', 'Donation Phone #': 'Số điện thoại để ủng hộ', 'Donation': 'Ủng hộ', 'Donor Details': 'Thông tin nhà tài trợ', 'Donor Driven Housing Reconstruction': 'Xây dựng lại nhà cửa theo yêu cầu nhà tài trợ', 'Donor added': 'Nhà tài trợ đã được thêm', 'Donor deleted': 'Nhà tài trợ đã được xóa', 'Donor updated': 'Nhà tài trợ đã được cập nhật', 'Donor': 'Nhà Tài trợ', 'Donor(s)': 'Nhà tài trợ', 'Donors Report': 'Báo cáo nhà tài trợ', 'Download Assessment Form Document': 'Biểu mẫu đánh giá đã dạng văn bản được tải về', 'Download Assessment Form Spreadsheet': 'Biểu mẫu đánh giá đã dạng excel được tải về', 'Download OCR-able PDF Form': 'Tải về biểu mẫu định dạng OCR-able PDF', 'Download Template': 'Tải Mẫu nhập liệu', 'Download last build': 'Tải về bộ tài liệu cập nhật nhất', 'Download': 'Tải về', 'Download.CSV formatted Template': 'Tải về biểu mẫu định dạng CSV', 'Draft Features': 'Chức năng dự thảo', 'Draft': 'Dự thảo', 'Drainage': 'Hệ thống thoát nước', 'Draw a square to limit the results to just those within the square.': 'Vẽ một ô vuông để giới hạn kết quả tìm kiếm chỉ nằm trong ô vuông đó', 'Driving License': 'Giấy phép lái xe', 'Drought': 'Hạn hán', 'Drugs': 'Thuốc', 'Due %(date)s': 'hết hạn %(date)s', 'Dug Well': 'Đào giếng', 'Dump': 'Trút xuống', 'Duplicate Locations': 'Nhân đôi các vị trí', 'Duplicate label selected': 'Nhân đôi biểu tượng đã chọn', 'Duplicate': 'Nhân đôi', 'Duration (months)': 'Khoảng thời gian (tháng)', 'Dust Storm': 'Bão cát', 'EMS Status': 'Tình trạng EMS', 'Early Warning': 'Cảnh báo sớm', 'Earthquake': 'Động đất', 'Economics of DRR': 'Kinh tế học GTRRTH', 'Edit Activity Type': 'Chỉnh sửa loại hình hoạt động', 'Edit Activity': 'Chỉnh sửa hoạt động', 'Edit Address': 'Chỉnh sửa địa chỉ', 'Edit Adjustment': 'Chỉnh sửa điều chỉnh', 'Edit Affiliation': 'Chỉnh sửa liên kết', 'Edit Aid Request': 'Chỉnh sửa Yêu cầu cứu trợ', 'Edit Alternative Item': 'Chỉnh sửa mặt hàng thay thê', 'Edit Annual Budget': 'Chỉnh sửa ngân sách năm', 'Edit Assessment Answer': 'Chỉnh sửa câu trả lời trong mẫu đánh giá', 'Edit Assessment Question': 'Chỉnh sửa câu trả hỏi trong mẫu đánh giá', 'Edit Assessment Template': 'Chỉnh sửa biểu mẫu đánh giá', 'Edit Assessment': 'Chỉnh sửa Đánh giá', 'Edit Asset Log Entry': 'Chỉnh sửa ghi chép nhật ký tài sản', 'Edit Asset': 'Chỉnh sửa tài sản', 'Edit Beneficiaries': 'Chỉnh sửa người hưởng lợi', 'Edit Beneficiary Type': 'Chỉnh sửa loại người hưởng lợi', 'Edit Branch Organization': 'Chỉnh sửa tổ chức cơ sở', 'Edit Brand': 'Chỉnh sửa nhãn hiệu', 'Edit Catalog Item': 'Chỉnh sửa mặt hàng trong danh mục', 'Edit Catalog': 'Chỉnh sửa danh mục hàng hóa', 'Edit Certificate': 'Chỉnh sửa chứng chỉ', 'Edit Certification': 'Chỉnh sửa bằng cấp', 'Edit Cluster': 'Chỉnh sửa nhóm', 'Edit Commitment Item': 'Chỉnh sửa mặt hàng cam kết', 'Edit Commitment': 'Chỉnh sửa cam kết', 'Edit Committed Person': 'Chỉnh sửa đối tượng cam kết', 'Edit Community Details': 'Chỉnh sửa thông tin về cộng đồng', 'Edit Competency Rating': 'Chỉnh sửa xếp hạng năng lực', 'Edit Completed Assessment Form': 'Chỉnh sửa biểu mẫu đánh giá đã hoàn thiện', 'Edit Contact Details': 'Chỉnh sửa thông tin liên hệ', 'Edit Contact Information': 'Chỉnh sửa thông tin liên hệ', 'Edit Course Certificate': 'Chỉnh sửa chứng chỉ khóa học', 'Edit Course': 'Chỉnh sửa khóa học', 'Edit Credential': 'Chỉnh sửa thư ủy nhiệm', 'Edit DRRPP Extensions': 'Chỉnh sửa gia hạn DRRPP', 'Edit Defaults': 'Chỉnh sửa mặc định', 'Edit Demographic Data': 'Chỉnh sửa số liệu dân số', 'Edit Demographic Source': 'Chỉnh sửa nguồn số liệu dân số', 'Edit Demographic': 'Chỉnh sửa dữ liệu nhân khẩu', 'Edit Department': 'Chỉnh sửa phòng/ban', 'Edit Description': 'Chỉnh sửa mô tả', 'Edit Details': 'Chỉnh sửa thông tin chi tiết', 'Edit Disaster Victims': 'Chỉnh sửa thông tin nạn nhân trong thiên tai', 'Edit Distribution': 'Chỉnh sửa Quyên góp', 'Edit Document': 'Chỉnh sửa tài liệu', 'Edit Donor': 'Chỉnh sửa nhà tài trợ', 'Edit Education Details': 'Chỉnh sửa thông tin về trình độ học vấn', 'Edit Email Settings': 'Chỉnh sửa cài đặt email', 'Edit Entry': 'Chỉnh sửa hồ sơ', 'Edit Facility Type': 'Chỉnh sửa loại hình bộ phận', 'Edit Facility': 'Chỉnh sửa bộ phận', 'Edit Feature Layer': 'Chỉnh sửa lớp chức năng', 'Edit Framework': 'Chỉnh sửa khung chương trình', 'Edit Group': 'Chỉnh sửa nhóm', 'Edit Hazard': 'Chỉnh sửa hiểm họa', 'Edit Hospital': 'Chỉnh sửa Bệnh viện', 'Edit Hours': 'Chỉnh sửa thời gian hoạt động', 'Edit Human Resource': 'Chỉnh sửa nguồn nhân lực', 'Edit Identification Report': 'Chỉnh sửa báo cáo định dạng', 'Edit Identity': 'Chỉnh sửa nhận dạng', 'Edit Image Details': 'Chỉnh sửa thông tin hình ảnh', 'Edit Image': 'Chỉnh sửa ảnh', 'Edit Incident Report': 'Chỉnh sửa báo cáo sự cố', 'Edit Incident': 'Chỉnh sửa Các sự việc xảy ra', 'Edit Item Catalog Categories': 'Chỉnh sửa danh mục hàng hóa', 'Edit Item Category': 'Chỉnh sửa danh mục hàng hóa', 'Edit Item Pack': 'Chỉnh sửa gói hàng', 'Edit Item in Request': 'Chỉnh sửa mặt hàng đang được yêu cầu', 'Edit Item': 'Chỉnh sửa mặt hàng', 'Edit Job Role': 'Chỉnh sửa chức năng nhiệm vụ', 'Edit Job Title': 'Chỉnh sửa chức danh', 'Edit Job': 'Chỉnh sửa công việc', 'Edit Key': 'Chỉnh sửa Key', 'Edit Layer': 'Chỉnh sửa lớp', 'Edit Level %d Locations?': 'Chỉnh sửa cấp độ %d địa điểm?', 'Edit Location Details': 'Chỉnh sửa chi tiết địa điểm', 'Edit Location Hierarchy': 'Chỉnh sửa thứ tự địa điểm', 'Edit Location': 'Chỉnh sửa địa điểm', 'Edit Log Entry': 'Chỉnh sửa ghi chép nhật ký', 'Edit Logged Time': 'Chỉnh sửa thời gian đăng nhập', 'Edit Mailing List': 'Chỉnh sửa danh sách gửi thư', 'Edit Map Configuration': 'Chỉnh sửa cài đặt cấu hình bản đồ', 'Edit Map Services': 'Chỉnh sửa dịch vụ bản đồ', 'Edit Marker': 'Chỉnh sửa công cụ đánh dấu', 'Edit Member': 'Chỉnh sửa hội viên', 'Edit Membership Type': 'Chỉnh sửa loại hình nhóm hội viên', 'Edit Membership': 'Chỉnh sửa nhóm hội viên', 'Edit Message': 'Chỉnh sửa tin nhắn', 'Edit Messaging Settings': 'Chỉnh sửa thiết lập tin nhắn', 'Edit Metadata': 'Chỉnh sửa dữ liệu', 'Edit Milestone': 'Chỉnh sửa mốc thời gian quan trọng', 'Edit Modem Settings': 'Chỉnh sửa cài đặt Modem', 'Edit National Society': 'Chỉnh sửa Hội Quốc gia', 'Edit Office Type': 'Chỉnh sửa loại hình văn phòng', 'Edit Office': 'Chỉnh sửa văn phòng', 'Edit Options': 'Chỉnh sửa lựa chọn', 'Edit Order': 'Chỉnh sửa lệnh', 'Edit Organization Domain': 'Chỉnh sửa lĩnh vực hoạt động của tổ chức', 'Edit Organization Type': 'Chỉnh sửa loại hình tổ chức', 'Edit Organization': 'Chỉnh sửa tổ chức', 'Edit Output': 'Chỉnh sửa kết quả đầu ra', 'Edit Parser Settings': 'Chỉnh sửa cài đặt cú pháp', 'Edit Participant': 'Chỉnh sửa người tham dự', 'Edit Partner Organization': 'Chỉnh sửa tổ chức đối tác', 'Edit Peer Details': 'Chỉnh sửa chi tiết nhóm người', 'Edit Permissions for %(role)s': 'Chỉnh sửa quyền truy cập cho %(role)s', 'Edit Person Details': 'Chỉnh sửa thông tin cá nhân', 'Edit Photo': 'Chỉnh sửa ảnh', 'Edit Problem': 'Chỉnh sửa Vấn đề', 'Edit Professional Experience': 'Chỉnh sửa kinh nghiệm nghề nghiệp', 'Edit Profile Configuration': 'Chỉnh sửa định dạng hồ sơ tiểu sử', 'Edit Program': 'Chỉnh sửa chương trình', 'Edit Project Organization': 'Chỉnh sửa tổ chức thực hiện dự án', 'Edit Project': 'Chỉnh sửa dự án', 'Edit Projection': 'Chỉnh sửa dự đoán', 'Edit Question Meta-Data': 'Chỉnh sửa siêu dữ liệu câu hỏi', 'Edit Record': 'Chỉnh sửa hồ sơ', 'Edit Recovery Details': 'Chỉnh sửa chi tiết khôi phục', 'Edit Report': 'Chỉnh sửa báo cáo', 'Edit Repository Configuration': 'Chỉnh sửa định dạng lưu trữ', 'Edit Request Item': 'Chỉnh sửa yêu cầu hàng hóa', 'Edit Request': 'Chỉnh sửa yêu cầu', 'Edit Requested Skill': 'Chỉnh sửa kỹ năng được yêu cầu', 'Edit Resource Configuration': 'Chỉnh sửa định dạng nguồn', 'Edit Resource': 'Chỉnh sửa tài nguyên', 'Edit Response': 'Chỉnh sửa phản hồi', 'Edit Role': 'Chỉnh sửa vai trò', 'Edit Room': 'Chỉnh sửa phòng', 'Edit SMS Message': 'Chỉnh sửa tin nhắn SMS', 'Edit SMS Settings': 'Chỉnh sửa cài đặt tin nhắn SMS', 'Edit SMTP to SMS Settings': 'Chỉnh sửa SMTP sang cài đặt SMS', 'Edit Sector': 'Chỉnh sửa lĩnh vực', 'Edit Setting': 'Chỉnh sửa cài đặt', 'Edit Settings': 'Thay đổi thiết lập', 'Edit Shelter Service': 'Chỉnh sửa dịch vụ cư trú', 'Edit Shelter': 'Chỉnh sửa thông tin cư trú', 'Edit Shipment Item': 'Chỉnh sửa hàng hóa trong lô hàng vận chuyển', 'Edit Site': 'Chỉnh sửa thông tin trên website ', 'Edit Skill Equivalence': 'Chỉnh sửa kỹ năng tương đương', 'Edit Skill Type': 'Chỉnh sửa loại kỹ năng', 'Edit Skill': 'Chỉnh sửa kỹ năng', 'Edit Staff Assignment': 'Chỉnh sửa phân công cán bộ', 'Edit Staff Member Details': 'Chỉnh sửa thông tin chi tiết của cán bộ', 'Edit Status': 'Chỉnh sửa tình trạng', 'Edit Supplier': 'Chỉnh sửa nhà cung cấp', 'Edit Survey Answer': 'Chỉnh sửa trả lời khảo sát', 'Edit Survey Series': 'Chỉnh sửa chuỗi khảo sát', 'Edit Survey Template': 'Chỉnh sửa mẫu điều tra', 'Edit Symbology': 'Chỉnh sửa biểu tượng', 'Edit Synchronization Settings': 'Chỉnh sửa cài đặt đồng bộ hóa', 'Edit Task': 'Chỉnh sửa nhiệm vụ', 'Edit Team': 'Chỉnh sửa Đội/Nhóm', 'Edit Template Section': 'Chỉnh sửa nội dung trong biểu mẫu', 'Edit Theme Data': 'Chỉnh sửa dữ liệu chủ đề', 'Edit Theme': 'Chỉnh sửa chủ đề', 'Edit Training Event': 'Chỉnh sửa sự kiện tập huấn', 'Edit Training': 'Chỉnh sửa tập huấn', 'Edit Tropo Settings': 'Chỉnh sửa cài đặt Tropo', 'Edit Twilio Settings': 'Chỉnh sửa cài đặt Twilio', 'Edit User': 'Chỉnh sửa người sử dụng', 'Edit Vehicle Assignment': 'Chỉnh sửa phân công phương tiện vận chuyển', 'Edit Volunteer Cluster Position': 'Chỉnh sửa vị trí nhóm tình nguyện viên', 'Edit Volunteer Cluster Type': 'Chỉnh sửa loại hình nhóm tình nguyện viên', 'Edit Volunteer Cluster': 'Chỉnh sửa nhóm tình nguyện viên', 'Edit Volunteer Details': 'Chỉnh sửa thông tin tình nguyện viên', 'Edit Volunteer Registration': 'Chỉnh sửa đăng ký tình nguyện viên', 'Edit Volunteer Role': 'Chỉnh sửa vai trò tình nguyện viên', 'Edit Vulnerability Aggregated Indicator': 'Chỉnh sửa chỉ số gộp đánh giá tình trạng dễ bị tổn thương', 'Edit Vulnerability Data': 'Chỉnh sửa dữ liệu về tình trạng dễ bị tổn thương', 'Edit Vulnerability Indicator Sources': 'Chỉnh sửa nguồn chỉ số đánh giá tình trạng dễ bị tổn thương', 'Edit Vulnerability Indicator': 'Chỉnh sửa chỉ số đánh giá tình trạng dễ bị tổn thương', 'Edit Warehouse Stock': 'Chỉnh sửa hàng lưu kho', 'Edit Warehouse': 'Chỉnh sửa kho hàng', 'Edit Web API Settings': 'Chỉnh sửa Cài đặt Web API', 'Edit current record': 'Chỉnh sửa hồ sơ hiện tại', 'Edit message': 'Chỉnh sửa tin nhắn', 'Edit saved search': 'Chỉnh sửa tìm kiếm đã lưu', 'Edit the Application': 'Chỉnh sửa ứng dụng', 'Edit the OpenStreetMap data for this area': 'Chỉnh sửa dữ liệu bản đồ OpenStreetMap cho vùng này', 'Edit this Disaster Assessment': 'Chỉnh sửa báo cáo đánh giá thảm họa này', 'Edit this entry': 'Chỉnh sửa hồ sơ này', 'Edit': 'Chỉnh sửa', 'Editable?': 'Có thể chỉnh sửa', 'Education & School Safety': 'Giáo dục & An toàn trong trường học', 'Education Details': 'Thông tin về trình độ học vấn', 'Education details added': 'Thông tin về trình độ học vấn đã được thêm', 'Education details deleted': 'Thông tin về trình độ học vấn đã được xóa', 'Education details updated': 'Thông tin về trình độ học vấn đã được cập nhật', 'Education materials received': 'Đã nhận được tài liệu, dụng cụ phục vụ học tập', 'Education materials, source': 'Dụng cụ học tập, nguồn', 'Education': 'Trình độ học vấn', 'Either a shelter or a location must be specified': 'Nhà tạm hoặc vị trí đều cần được nêu rõ', 'Either file upload or document URL required.': 'File để tải lên hoặc được dẫn tới tài liệu đều được yêu cầu.', 'Either file upload or image URL required.': 'File để tải lên hoặc được dẫn tới hình ảnh đều được yêu cầu.', 'Elevated': 'Nâng cao lên', 'Email Address to which to send SMS messages. Assumes sending to phonenumber@address': 'Địa chỉ email để gửi tin nhắn SMS. Giả định gửi đến số điện thoại', 'Email Address': 'Địa chỉ email', 'Email Details': 'Thông tin về địa chỉ email', 'Email InBox': 'Hộp thư đến trong email', 'Email Setting Details': 'Thông tin cài đặt email', 'Email Setting deleted': 'Cài đặt email đã được xóa', 'Email Settings': 'Cài đặt email', 'Email address verified, however registration is still pending approval - please wait until confirmation received.': 'Địa chỉ email đã được xác nhận, tuy nhiên đăng ký vẫn còn chờ duyệt - hãy đợi đến khi nhận được phê chuẩn', 'Email deleted': 'Email đã được xóa', 'Email settings updated': 'Cài đặt email đã được cập nhật', 'Emergency Contact': 'Thông tin liên hệ trong trường hợp khẩn cấp', 'Emergency Contacts': 'Thông tin liên hệ trong trường hợp khẩn cấp', 'Emergency Department': 'Bộ phận cấp cứu', 'Emergency Health': 'Chăm sóc sức khỏe trong tình huống khẩn cấp', 'Emergency Shelter': 'Nhà tạm trong tình huống khẩn cấp', 'Emergency Support Facility': 'Bộ phận hỗ trợ khẩn cấp', 'Emergency Support Service': 'Dịch vụ hỗ trợ khẩn cấp', 'Emergency Telecommunication': 'Truyền thông trong tình huống khẩn cấp', 'Emergency Telecommunications': 'Truyền thông trong tình huống khẩn cấp', 'Emergency contacts': 'Thông tin liên hệ khẩn cấp', 'Enable in Default Config?': 'Cho phép ở cấu hình mặc định?', 'Enable': 'Cho phép', 'Enable/Disable Layers': 'Kích hoạt/Tắt Layer', 'Enabled': 'Được cho phép', 'End Date': 'Ngày kết thúc', 'End date': 'Ngày kết thúc', 'Enter Completed Assessment Form': 'Nhập biểu mẫu đánh giá đã hoàn thiện', 'Enter Completed Assessment': 'Nhập báo cáo đánh giá đã hoàn thiện', 'Enter Coordinates in Deg Min Sec': 'Nhập tọa độ ở dạng Độ,Phút,Giây', 'Enter a name for the spreadsheet you are uploading (mandatory).': 'Nhập tên cho bảng tính bạn đang tải lên(bắt buộc)', 'Enter a new support request.': 'Nhập một yêu cầu hỗ trợ mới', 'Enter a summary of the request here.': 'Nhập tóm tắt các yêu cầu ở đây', 'Enter a valid email': 'Nhập địa chỉ email có giá trị', 'Enter a value carefully without spelling mistakes, this field will be crosschecked.': 'Nhập giá trị cẩn thận tránh các lỗi chính tả, nội dung này sẽ được kiểm tra chéo', 'Enter indicator ratings': 'Nhập xếp hạng chỉ số', 'Enter keywords': 'Từ khóa tìm kiếm', 'Enter some characters to bring up a list of possible matches': 'Nhập một vài ký tự để hiện ra danh sách có sẵn', 'Enter the same password as above': 'Nhập lại mật khẩu giống như trên', 'Enter your first name': 'Nhập tên của bạn', 'Enter your organization': 'Nhập tên tổ chức của bạn', 'Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages.': 'Nhập số điện thoại là không bắt buộc, tuy nhiên nếu nhập số điện thoại bạn sẽ có thể nhận được các tin nhắn', 'Entity': 'Pháp nhân', 'Entry added to Asset Log': 'Ghi chép đã được thêm vào nhật ký tài sản', 'Environment': 'Môi trường', 'Epidemic': 'Dịch bệnh', 'Epidemic/Pandemic Preparedness': 'Phòng ngừa bệnh dịch', 'Error File missing': 'Lỗi không tìm thấy file', 'Error in message': 'Lỗi trong tin nhắn', 'Error logs for "%(app)s"': 'Báo cáo lỗi cho "%(app)s"', 'Errors': 'Lỗi', 'Essential Staff?': 'Cán bộ Chủ chốt?', 'Estimated # of households who are affected by the emergency': 'Ước tính # số hộ chịu ảnh hưởng từ thiên tai', 'Estimated Delivery Date': 'Thời gian giao hàng dự kiến', 'Estimated Value per Pack': 'Giá trị dự tính mỗi gói', 'Ethnicity': 'Dân tộc', 'Euros': 'Đồng Euro', 'Evaluate the information in this message. (This value SHOULD NOT be used in public warning applications.)': 'Đánh giá thông tin trong thư. (giá trị này KHÔNG NÊN sử dụng trong các ứng dụng cảnh báo công cộng)', 'Event Type': 'Loại Sự kiện', 'Event type': 'Loại sự kiện ', 'Events': 'Sự kiện', 'Example': 'Ví dụ', 'Excellent': 'Tuyệt vời', 'Excreta Disposal': 'Xử lý chất thải', 'Expected Out': 'Theo dự kiến', 'Experience': 'Kinh nghiệm', 'Expiration Date': 'Ngày hết hạn', 'Expiration Details': 'Thông tin về hết hạn', 'Expiration Report': 'Báo cáo hết hạn', 'Expired': 'Đã hết hạn', 'Expiring Staff Contracts Report': 'Báo cáo hợp đồng lao động sắp hết hạn', 'Expiry (months)': 'Hết hạn (tháng)', 'Expiry Date': 'Ngày hết hạn', 'Expiry Date/Time': 'Ngày/Giờ hết hạn', 'Expiry Time': 'Hạn sử dụng ', 'Explanation about this view': 'Giải thích về quan điểm này', 'Explosive Hazard': 'Hiểm họa cháy nổ', 'Export Data': 'Xuất dữ liệu', 'Export all Completed Assessment Data': 'Chiết xuất toàn bộ dữ liệu đánh giá đã hoàn thiện', 'Export as Pootle (.po) file (Excel (.xls) is default)': 'Chiết xuất định dạng file Pootle (.po) (định dạng excel là mặc định)', 'Export as': 'Chiết suất tới', 'Export in EDXL-HAVE format': 'Chiết suất ra định dạng EDXL-HAVE ', 'Export in GPX format': 'Chiết xuất định dạng file GPX', 'Export in HAVE format': 'Chiết suất định dạng HAVE', 'Export in KML format': 'Chiết suất định dạng KML', 'Export in OSM format': 'Chiết xuất định dạng OSM', 'Export in PDF format': 'Chiết suất định dạng PDF', 'Export in RSS format': 'Chiết suất định dạng RSS', 'Export in XLS format': 'Chiết suất định dạng XLS', 'Export to': 'Chiết suất tới', 'Eye Color': 'Màu mắt', 'FAIR': 'CÔNG BẰNG', 'FROM': 'TỪ', 'Facial hair, color': 'Màu râu', 'Facial hair, length': 'Độ dài râu', 'Facial hair, type': 'Kiểu râu', 'Facilities': 'Bộ phận', 'Facility Contact': 'Thông tin liên hệ của bộ phận', 'Facility Details': 'Thông tin về bộ phận', 'Facility Type Details': 'Thông tin về loại hình bộ phận', 'Facility Type added': 'Loại hình bộ phận đã được thêm', 'Facility Type deleted': 'Loại hình bộ phận đã được xóa', 'Facility Type updated': 'Loại hình bộ phận đã được cập nhật', 'Facility Types': 'Loại hình bộ phận', 'Facility added': 'Bộ phận đã được thêm', 'Facility deleted': 'Bộ phận đã được xóa', 'Facility updated': 'Bộ phận đã được cập nhật', 'Facility': 'Bộ phận', 'Fail': 'Thất bại', 'Failed to approve': 'Không phê duyệt thành công', 'Fair': 'công bằng', 'Falling Object Hazard': 'Hiểm họa vật thể rơi từ trên cao', 'Family': 'Gia đình', 'Family/friends': 'Gia đình/Bạn bè', 'Feature Info': 'Thông tin chức năng', 'Feature Layer Details': 'Thông tin về lớp chức năng', 'Feature Layer added': 'Lớp chức năng đã được thêm', 'Feature Layer deleted': 'Lớp chức năng đã được xóa', 'Feature Layer updated': 'Lớp chức năng đã được cập nhật', 'Feature Layer': 'Lớp Chức năng', 'Feature Layers': 'Lớp Chức năng', 'Feature Namespace': 'Vùng tên chức năng', 'Feature Request': 'Yêu cầu chức năng', 'Feature Type': 'Loại chức năng', 'Features Include': 'Chức năng bao gồm', 'Feedback': 'Phản hồi', 'Female headed households': 'Phụ nữ đảm đương công việc nội trợ', 'Female': 'Nữ', 'Few': 'Một vài', 'File Uploaded': 'File đã được tải lên', 'File uploaded': 'File đã được tải lên', 'Fill out online below or ': 'Điền thông tin trực tuyến vào phía dưới hoặc', 'Filter Field': 'Ô lọc thông tin', 'Filter Options': 'Lựa chọn lọc', 'Filter Value': 'Giá trị lọc', 'Filter by Category': 'Lọc theo danh mục', 'Filter by Country': 'Lọc theo quốc gia', 'Filter by Organization': 'Lọc theo tổ chức', 'Filter by Status': 'Lọc theo tình trạng', 'Filter type ': 'Loại lọc', 'Filter': 'Bộ lọc', 'Financial System Development': 'Phát triển hệ thống tài chính', 'Find Recovery Report': 'Tìm Báo cáo phục hồi', 'Find by Name': 'Tìm theo tên', 'Find': 'Tìm', 'Fingerprint': 'Vân tay', 'Fingerprinting': 'Dấu vân tay', 'Fire Station': 'Trạm chữa cháy', 'Fire Stations': 'Trạm chữa cháy', 'Fire': 'Hỏa hoạn', 'First Name': 'Tên', 'First': 'Trang đầu', 'Flash Flood': 'Lũ Quét', 'Flash Freeze': 'Lạnh cóng đột ngột', 'Flood Alerts': 'Báo động lũ', 'Flood Report Details': 'Chi tiết báo cáo tình hình lũ lụt', 'Flood Report added': 'Báo cáo lũ lụt đã được thêm', 'Flood Report updated': 'Đã cập nhật báo cáo tình hình lũ lụt ', 'Flood': 'Lũ lụt', 'Focal Point': 'Tiêu điểm', 'Fog': 'Sương mù', 'Food Security': 'An ninh lương thực', 'Food': 'Thực phẩm', 'For Entity': 'Đối với đơn vị', 'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).': 'Đối với POP-3 thường sử dụng 110 (995 cho SSL), đối với IMAP thường sử dụng 143 (993 cho IMAP).', 'For each sync partner, there is a default sync job that runs after a specified interval of time. You can also set up more sync jobs which could be customized on your needs. Click the link on the right to get started.': 'Đối với mỗi đối tác đồng bộ, có một công việc đồng bộ mặc định chạy sau một khoảng thời gian nhất định. Bạn cũng có thể thiết lập thêm công việc đồng bộ hơn nữa để có thể tùy biến theo nhu cầu. Nhấp vào liên kết bên phải để bắt đầu', 'For live help from the Sahana community on using this application, go to': 'Để được giúp đỡ trực tuyến từ cộng đồng Sahana về sử dụng phần mềm ứng dụng, mời đến', 'For more details on the Sahana Eden system, see the': 'Chi tiết hệ thống Sahana Eden xem tại', 'Forest Fire': 'Cháy rừng', 'Form Settings': 'Cài đặt biểu mẫu', 'Formal camp': 'Trại chính thức', 'Format': 'Định dạng', 'Found': 'Tìm thấy', 'Framework added': 'Khung chương trình đã được thêm', 'Framework deleted': 'Khung chương trình đã được xóa', 'Framework updated': 'Khung chương trình đã được cập nhật', 'Framework': 'Khung chương trình', 'Frameworks': 'Khung chương trình', 'Freezing Drizzle': 'Mưa bụi lạnh cóng', 'Freezing Rain': 'Mưa lạnh cóng', 'Freezing Spray': 'Mùa phùn lạnh cóng', 'Frequency': 'Tần suất', 'From Facility': 'Từ bộ phận', 'From Warehouse/Facility/Office': 'Từ Kho hàng/Bộ phận/Văn phòng', 'From': 'Từ', 'Frost': 'Băng giá', 'Fulfil. Status': 'Điền đầy đủ tình trạng', 'Full beard': 'Râu rậm', 'Fullscreen Map': 'Bản đồ cỡ lớn', 'Function Permissions': 'Chức năng cho phép', 'Function for Value': 'Chức năng cho giá trị', 'Function': 'Chức năng', 'Functions available': 'Chức năng sẵn có', 'Funding Report': 'Báo cáo tài trợ', 'Funding': 'Kinh phí', 'Funds Contributed by this Organization': 'Tài trợ đóng góp bởi tổ chức này', 'Funds Contributed': 'Kinh phí được tài trợ', 'GIS & Mapping': 'GIS & Vẽ bản đồ', 'GO TO ANALYSIS': 'ĐẾN MỤC PHÂN TÍCH', 'GO TO THE REGION': 'ĐẾN KHU VỰC', 'GPS Data': 'Dữ liệu GPS', 'GPS Marker': 'Dụng cụ đánh dấu GPS', 'GPS Track File': 'File vẽ GPS', 'GPS Track': 'Đường vẽ GPS', 'GPX Layer': 'Lớp GPX', 'Gale Wind': 'Gió mạnh', 'Gap Analysis Map': 'Bản đồ phân tích thiếu hụt', 'Gap Analysis Report': 'Báo cáo phân tích thiếu hụt', 'Gauges': 'Máy đo', 'Gender': 'Giới', 'Generate portable application': 'Tạo ứng dụng cầm tay', 'Generator': 'Bộ sinh', 'GeoJSON Layer': 'Lớp GeoJSON', 'GeoRSS Layer': 'Lớp GeoRSS', 'Geocoder Selection': 'Lựa chọn các mã địa lý', 'Geometry Name': 'Tên trúc hình', 'Get Feature Info': 'Lấy thông tin về chức năng', 'Give a brief description of the image, e.g. what can be seen where on the picture (optional).': 'Đưa ra chú thích hình ảnh ngắn gọn, vd: có thể xem gì ở đâu trên bức hình này (không bắt buộc).', 'Global Messaging Settings': 'Cài đặt hộp thư tin nhắn toàn cầu', 'Go to Functional Map': 'Tới bản đồ chức năng', 'Go to Request': 'Đến mục yêu cầu', 'Go to the': 'Đến', 'Go': 'Thực hiện', 'Goatee': 'Chòm râu dê', 'Good Condition': 'Điều kiện tốt', 'Good': 'Tốt', 'Goods Received Note': 'Giấy nhận Hàng hóa', 'Google Layer': 'Lớp Google', 'Governance': 'Quản trị', 'Grade': 'Tốt nghiệp hạng', 'Graph': 'Đường vẽ', 'Great British Pounds': 'Bảng Anh', 'Greater than 10 matches. Please refine search further': 'Tìm thấy nhiều hơn 10 kết quả. Hãy nhập lại từ khóa', 'Grid': 'Hiển thị dạng lưới', 'Group Description': 'Mô tả về nhóm', 'Group Details': 'Thông tin về nhóm', 'Group Head': 'Trưởng Nhóm', 'Group Members': 'Thành viên Nhóm', 'Group Memberships': 'Hội viên nhóm', 'Group Name': 'Tên nhóm', 'Group Type': 'Loại hình nhóm', 'Group added': 'Nhóm đã được thêm', 'Group deleted': 'Nhóm đã được xóa', 'Group description': 'Mô tả Nhóm', 'Group type': 'Loại nhóm', 'Group updated': 'Nhóm đã được cập nhật', 'Group': 'Nhóm', 'Grouped by': 'Nhóm theo', 'Groups': 'Nhóm', 'Guide': 'Hướng dẫn', 'HFA Priorities': 'Ưu tiên HFA', 'HFA1: Ensure that disaster risk reduction is a national and a local priority with a strong institutional basis for implementation.': 'HFA1: Đảm bảo rằng giảm thiểu rủi ro thảm họa là ưu tiên quốc gia và địa phương với một nền tảng tổ chức mạnh mễ để thực hiện hoạt động', 'HFA2: Identify, assess and monitor disaster risks and enhance early warning.': 'HFA2: Xác định, đánh giá và giám sát rủi ro thảm họa và tăng cường cảnh báo sớm.', 'HFA3: Use knowledge, innovation and education to build a culture of safety and resilience at all levels.': 'HFA3: Sử dụng kiến thức, sáng kiến và tập huấn để xây dựng cộng đồng an toàn ở mọi cấp.', 'HFA4: Reduce the underlying risk factors.': 'HFA4: Giảm các yếu tố rủi ro gốc rễ', 'HFA5: Strengthen disaster preparedness for effective response at all levels.': 'HFA5: Tăng cường phòng ngừa thảm họa để đảm bảo ứng phó hiệu quả ở mọi cấp.', 'HIGH RESILIENCE': 'MỨC ĐỘ AN TOÀN CAO', 'HIGH': 'CAO', 'Hail': 'Mưa đá', 'Hair Color': 'Màu tóc', 'Hair Length': 'Độ dài tóc', 'Hair Style': 'Kiểu tóc', 'Has the %(GRN)s (%(GRN_name)s) form been completed?': 'Mẫu %(GRN)s (%(GRN_name)s) đã được hoàn thành chưa?', 'Has the Certificate for receipt of the shipment been given to the sender?': 'Chứng nhận đã nhận được lô hàng đã gửi đến người gửi chưa?', 'Hazard Details': 'Thông tin vê hiểm họa', 'Hazard Points': 'Điểm hiểm họa', 'Hazard added': 'Hiểm họa đã được thêm', 'Hazard deleted': 'Hiểm họa đã được xóa', 'Hazard updated': 'Hiểm họa đã được cập nhật', 'Hazard': 'Hiểm họa', 'Hazardous Material': 'Vật liệu nguy hiểm', 'Hazardous Road Conditions': 'Điều kiện đường xá nguy hiểm', 'Hazards': 'Hiểm họa', 'Header Background': 'Nền vùng trên', 'Health & Health Facilities': 'CSSK & Cơ sở CSSK', 'Health center': 'Trung tâm y tế', 'Health': 'Sức khỏe', 'Heat Wave': 'Nắng nóng gay gắt', 'Heat and Humidity': 'Nóng và ẩm', 'Height (cm)': 'Chiều cao (cm)', 'Height (m)': 'Chiều cao (m)', 'Height': 'Chiều cao', 'Help': 'Trợ giúp', 'Helps to monitor status of hospitals': 'Hỗ trợ giám sát trạng thái các bệnh viện', 'Helps to report and search for Missing Persons': 'Hỗ trợ báo cáo và tìm kếm những người mất tích', 'Hide Chart': 'Ẩn biểu đồ', 'Hide Pivot Table': 'Ẩn Pivot Table', 'Hide Table': 'Ẩn bảng', 'Hide': 'Ẩn', 'Hierarchy Level 1 Name (e.g. State or Province)': 'Hệ thống tên cấp 1 (ví dụ Bang hay Tỉnh)', 'Hierarchy Level 2 Name (e.g. District or County)': 'Hệ thống tên cấp 2 (ví dụ Huyện hay thị xã)', 'Hierarchy Level 3 Name (e.g. City / Town / Village)': 'Hệ thống tên cấp 3 (ví dụ Thành phố/thị trấn/xã)', 'Hierarchy Level 4 Name (e.g. Neighbourhood)': 'Hệ thống tên cấp 4 (ví dụ xóm làng)', 'Hierarchy Level 5 Name': 'Hệ thống tên cấp 5', 'Hierarchy': 'Thứ tự', 'High School': 'Trung học', 'High Water': 'Nước Cao', 'High': 'Cao', 'Hindu': 'Người theo đạo Hindu', 'History': 'Lịch sử', 'Hit the back button on your browser to try again.': 'Bấm nút trở lại trên màn hình để thử lại', 'Home Address': 'Địa chỉ nhà riêng', 'Home Country': 'Bản quốc', 'Home Crime': 'Tội ác tại nhà', 'Home phone': 'Điện thoại nhà riêng', 'Home': 'Trang chủ', 'Hospital Details': 'Chi tiết thông tin bệnh viện', 'Hospital Status Report': 'Báo cáo tình trạng bệnh viện', 'Hospital information added': 'Đã thêm thông tin Bệnh viện', 'Hospital information deleted': 'Đã xóa thông tin bệnh viện', 'Hospital information updated': 'Đã cập nhật thông tin bệnh viện', 'Hospital status assessment.': 'Đánh giá trạng thái bệnh viện', 'Hospital': 'Bệnh viện', 'Hospitals': 'Bệnh viện', 'Host National Society': 'Hội QG chủ nhà', 'Host': 'Chủ nhà', 'Hot Spot': 'Điểm Nóng', 'Hour': 'Thời gian', 'Hourly': 'Theo giờ', 'Hours Details': 'Thông tin về thời gian hoạt động', 'Hours added': 'Thời gian hoạt động đã được thêm', 'Hours by Program Report': 'Thời gian hoạt động theo chương trình', 'Hours by Role Report': 'Thời gian hoạt động theo vai trò', 'Hours deleted': 'Thời gian hoạt động đã được xóa', 'Hours updated': 'Thời gian hoạt động đã được cập nhật', 'Hours': 'Thời gian hoạt động', 'Households below %(br)s poverty line': 'Hộ gia đình dưới %(br)s mức nghèo', 'Households below poverty line': 'Hộ gia đình dưới mức nghèo', 'Households': 'Hộ gia đình', 'Housing Repair & Retrofitting': 'Sửa chữa và Thay thế nhà cửa', 'How data shall be transferred': 'Dữ liệu sẽ được chuyển giao như thế nào', 'How local records shall be updated': 'Hồ sơ địa phương sẽ được cập nhật thế nào', 'How many Boys (0-17 yrs) are Injured due to the crisis': 'Đối tượng nam trong độ tuổi 0-17 bị thương trong thiên tai', 'How many Boys (0-17 yrs) are Missing due to the crisis': 'Có bao nhiêu bé trai (0 đến 17 tuổi) bị mất tích do thiên tai', 'How many Girls (0-17 yrs) are Injured due to the crisis': 'Đối tượng nữ từ 0-17 tuổi bị thương trong thiên tai', 'How many Men (18 yrs+) are Dead due to the crisis': 'Bao nhiêu người (trên 18 tuổi) chết trong thảm họa', 'How many Men (18 yrs+) are Missing due to the crisis': 'Đối tượng nam 18 tuổi trở lên mất tích trong thiên tai', 'How many Women (18 yrs+) are Dead due to the crisis': 'Đối tượng nữ từ 18 tuổi trở lên thiệt mạng trong thiên tai', 'How many Women (18 yrs+) are Injured due to the crisis': 'Số nạn nhân là nữ trên 18 tuổi chịu ảnh hưởng của cuộc khủng hoảng', 'How much detail is seen. A high Zoom level means lot of detail, but not a wide area. A low Zoom level means seeing a wide area, but not a high level of detail.': 'Mức độ chi tiết có thể xem. Mức phóng to cao có thể xem được nhiều chi tiết, nhưng không xem được diện tích rộng. Mức Phóng thấp có thể xem được diện tích rộng, nhưng không xem được nhiều chi tiết.', 'How often you want to be notified. If there are no changes, no notification will be sent.': 'Mức độ thường xuyên bạn muốn nhận thông báo. Nếu không có thay đổi, bạn sẽ không nhận được thông báo.', 'How you want to be notified.': 'Bạn muốn được thông báo như thế nào.', 'Human Resource Assignment updated': 'Phân bổ nguồn nhân lực đã được cập nhật', 'Human Resource Assignments': 'Phân bổ nguồn nhân lực', 'Human Resource Details': 'Thông tin về nguồn nhân lực', 'Human Resource assigned': 'Nguồn nhân lực được phân bổ', 'Human Resource development': 'Phát triển nhân lực', 'Human Resource unassigned': 'Nguồn nhân lực chưa được phân bổ', 'Human Resource': 'Nguồn Nhân lực', 'Human Resources': 'Nguồn Nhân lực', 'Hurricane Force Wind': 'Gió mạnh cấp bão lốc', 'Hurricane': 'Bão lốc', 'Hygiene Promotion': 'Khuyến khích hành vi vệ sinh', 'Hygiene kits, source': 'Dụng cụ vệ sinh, nguồn', 'I accept. Create my account.': 'Tôi đồng ý. Tạo tài khoản của tôi', 'ICONS': 'BIỂU TƯỢNG', 'ID Tag Number': 'Số nhận dạng thẻ', 'ID type': 'Loại giấy tờ nhận dạng', 'ID': 'Thông tin nhận dạng', 'INDICATOR RATINGS': 'XẾP LOẠI CHỈ SỐ', 'INDICATORS': 'CHỈ SỐ', 'Ice Pressure': 'Sức ép băng tuyết', 'Iceberg': 'Tảng băng', 'Identification label of the Storage bin.': 'Nhãn xác định Bin lưu trữ', 'Identifier Name for your Twilio Account.': 'Xác định tên trong tài khoản Twilio của bạn', 'Identifier which the repository identifies itself with when sending synchronization requests.': 'Xác định danh mục lưu trữ nào cần được yêu cầu đồng bộ hóa', 'Identities': 'Các Chứng minh', 'Identity Details': 'Chi tiết Chứng minh', 'Identity added': 'Thêm Chứng minh', 'Identity deleted': 'Xóa Chứng minh', 'Identity updated': 'Cập nhất Chứng minh', 'Identity': 'Chứng minh ND', 'If a ticket was issued then please provide the Ticket ID.': 'Nếu vé đã được cấp, vui lòng cung cấp mã vé', 'If a user verifies that they own an Email Address with this domain, the Approver field is used to determine whether & by whom further approval is required.': 'Nếu người dùng xác nhận rằng họ sở hữu địa chỉ email với miền này, ô Người phê duyệt sẽ được sử dụng để xác định xem liệu có cần thiết phải có phê duyệt và phê duyệt của ai.', 'If checked, the notification will contain all modified records. If not checked, a notification will be send for each modified record.': 'Nếu chọn, thông báo sẽ bao gồm toàn bộ hồ sơ được chỉnh sửa. Nếu không chọn, thông báo sẽ được gửi mỗi khi có hồ sơ được chỉnh sửa', 'If it is a URL leading to HTML, then this will downloaded.': 'Nếu đó là đường dẫn URL dẫn đến trang HTML, thì sẽ được tải xuống', 'If neither are defined, then the Default Marker is used.': 'Nếu cả hai đều không được xác định, thì đánh dấu mặc định sẽ được sử dụng.', 'If none are selected, then all are searched.': 'Nếu không chọn gì, thì sẽ tìm kiếm tất cả.', 'If not found, you can have a new location created.': 'Nếu không tìm thấy, bạn có thể tạo địa điểm mới.', 'If the location is a geographic area, then state at what level here.': 'Nếu địa điểm là một vùng địa lý thì cần nêu rõ là cấp độ nào ở đây.', 'If the person counts as essential staff when evacuating all non-essential staff.': 'Nếu người đó là cán bộ chủ chốt khi đó sẽ sơ tán mọi cán bộ không quan trọng.', 'If the request is for %s, please enter the details on the next screen.': 'Nếu yêu cầu là %s thì xin mời nhập các chi tiết vào trang tiếp theo.', 'If the request type is "Other", please enter request details here.': "Nếu loại yêu cầu là 'Khác', xin nhập chi tiết của yêu cầu ở đây.", 'If this field is populated then a user with the Domain specified will automatically be assigned as a Staff of this Organization': 'Nếu trường này đã nhiều người khi đó người dùng có chức năng tổ chức sẽ được tự động phân bổ như là Cán bộ của tổ chức.', 'If this is set to True then mails will be deleted from the server after downloading.': 'Nếu đã được xác định là Đúng thư sau đó sẽ bị xóa khỏi máy chủ sau khi tải về', 'If this record should be restricted then select which role is required to access the record here.': 'Nếu hồ sơ này cần bị hạn chế truy cập, lựa chọn ở đây chức năng nào có thể truy cập vào hồ sơ này ', 'If this record should be restricted then select which role(s) are permitted to access the record here.': 'Nếu hồ sơ này cần bị hạn chế truy cập, lựa chọn ở đây những chức năng nào được quyền truy cập vào hồ sơ này ', 'If yes, specify what and by whom': 'Nếu có, hãy ghi rõ đã chỉnh sửa những gì và chỉnh sửa', 'If yes, which and how': 'nếu có thì cái nào và như thế nào', 'If you need to add a new document then you can click here to attach one.': 'Nếu cần thêm một tài liệu mới, nhấn vào đây để đính kèm', 'If you want several values, then separate with': 'Nếu bạn muốn nhiều giá trị, thì tách rời với', 'If you would like to help, then please %(sign_up_now)s': 'Nếu bạn muốn giúp đỡ, thì xin mời %(đăng ký bây giờ)s', 'If you would like to help, then please': 'Vui lòng giúp đỡ nếu bạn muốn', 'Ignore Errors?': 'Bỏ qua lỗi?', 'Illegal Immigrant': 'Người nhập cư bất hợp pháp', 'Image Details': 'Chi tiết hình ảnh', 'Image File(s), one image per page': 'Tệp hình ảnh, một hình ảnh trên một trang', 'Image Type': 'Loại hình ảnh', 'Image added': 'Thêm hình ảnh', 'Image deleted': 'Xóa hình ảnh', 'Image updated': 'Cập nhật hình ảnh', 'Image': 'Hình ảnh', 'Image/Attachment': 'Ảnh/ tệp đính kèm', 'Images': 'Các hình ảnh', 'Impact Assessments': 'Đánh giá tác động', 'Import Activity Data': 'Nhập khẩu dữ liệu hoạt động', 'Import Annual Budget data': 'Nhập khẩu dữ liệu ngân sách hàng năm', 'Import Assets': 'Nhập khẩu dữ liệu tài sản', 'Import Branch Organizations': 'Nhập khẩu dữ liệu về Tỉnh/thành Hội', 'Import Certificates': 'Nhập khẩu dữ liệu về chứng chỉ tập huấn', 'Import Community Data': 'Nhập khẩu dữ liệu cộng đồng', 'Import Completed Assessment Forms': 'Nhập khẩu biểu mẫu đánh giá đã hoàn chỉnh', 'Import Courses': 'Nhập khẩu dữ liệu về khóa tập huấn', 'Import Data for Theme Layer': 'Nhập khảu dữ liệu cho lớp chủ đề', 'Import Demographic Data': 'Nhập khẩu số liệu dân số', 'Import Demographic Sources': 'Nhập khẩu nguồn số liệu dân số', 'Import Demographic': 'Nhập khẩu dữ liệu nhân khẩu', 'Import Demographics': 'Tải dữ liệu dân số', 'Import Departments': 'Nhập khẩu dữ liệu phòng/ban', 'Import Facilities': 'Nhập khẩu bộ phận', 'Import Facility Types': 'Nhập khẩu loại hình bộ phận', 'Import File': 'Nhập khẩu File', 'Import Framework data': 'Nhập khẩu dữ liệu về khung chương trình', 'Import Hazards': 'Nhập khẩu hiểm họa', 'Import Hours': 'Nhập khẩu thời gian hoạt động', 'Import Incident Reports from Ushahidi': 'Nhập khẩu báo cáo sự cố từ Ushahidi', 'Import Incident Reports': 'Nhập khẩu báo cáo sự cố', 'Import Job Roles': 'Nhập khẩu vai trò công việc', 'Import Jobs': 'Chuyển đổi nghề nghiệp', 'Import Location Data': 'Nhập khẩu dữ liệu địa điểm', 'Import Locations': 'Nhập khẩu địa điểm', 'Import Logged Time data': 'Nhập khẩu dữ liệu thời gian truy cập', 'Import Members': 'Nhập khẩu thành viên', 'Import Membership Types': 'Nhập khẩu loại hình thành viên', 'Import Milestone Data': 'Nhập khẩu dự liệu các thời điểm quan trọng', 'Import Milestones': 'Tải dự liệu các thời điểm quan trọng', 'Import Offices': 'Nhập khẩu văn phòng', 'Import Organizations': 'Nhập khẩu tổ chức', 'Import Participant List': 'Nhập khẩu dữ liệu học viên được tập huấn', 'Import Participants': 'Tải người tham dự', 'Import Partner Organizations': 'Nhập khẩu dữ liệu về tổ chức đối tác', 'Import Project Communities': 'Nhập khẩu dữ liệu về cộng đồng dự án', 'Import Project Organizations': 'Nhập khẩu dữ liệu về tổ chức thực hiện dự án', 'Import Projects': 'Nhập khẩu dữ liệu dự án', 'Import Red Cross & Red Crescent National Societies': 'Nhập khẩu dữ liệu về Hội CTĐ & TLLĐ Quốc gia', 'Import Staff': 'Nhập khẩu cán bộ', 'Import Stations': 'Nhập khẩu các trạm', 'Import Statuses': 'Nhập khẩu tình trạng', 'Import Suppliers': 'Nhập khẩu các nhà cung cấp', 'Import Tasks': 'Nhập khẩu Nhiệm vụ', 'Import Template Layout': 'Nhập khẩu sơ đồ mẫu', 'Import Templates': 'Nhập khẩu biểu mẫu', 'Import Theme data': 'Nhập khẩu dữ liệu chủ đề', 'Import Themes': 'Nhập khẩu Chủ đề', 'Import Training Events': 'Nhập khẩu sự kiện tập huấn', 'Import Training Participants': 'Nhập khẩu dữ liệu học viên được tập huấn', 'Import Vehicles': 'Nhập khẩu các phương tiện đi lại', 'Import Volunteer Cluster Positions': 'Nhập khẩu vị trí nhóm tình nguyện viên', 'Import Volunteer Cluster Types': 'Nhập khẩu loại hình nhóm tình nguyện viên', 'Import Volunteer Clusters': 'Nhập khẩu nhóm tình nguyện viên', 'Import Volunteers': 'Nhập khẩu tình nguyện viên', 'Import Vulnerability Aggregated Indicator': 'Nhập khẩu chỉ số phân tách tình trạng dễ bị tổn thương', 'Import Vulnerability Data': 'Nhập khẩu dữ liệu tình trạng dễ bị tổn thương', 'Import Vulnerability Indicator Sources': 'Nhập khẩu Nguồn chỉ số tình trạng dễ bị tổn thương', 'Import Vulnerability Indicator': 'Nhập khẩu chỉ số tình trạng dễ bị tổn thương', 'Import Warehouse Stock': 'Nhập khẩu hàng lưu kho', 'Import Warehouses': 'Nhập khẩu kho', 'Import from CSV': 'Nhập khẩu từ CSV', 'Import from OpenStreetMap': 'Nhập khẩu từ bản đồ OpenstreetMap', 'Import multiple tables as CSV': 'Chuyển đổi định dạng bảng sang CSV', 'Import': 'Nhập khẩu dữ liệu', 'Import/Export': 'Nhập/ Xuất dữ liệu', 'Important': 'Quan trọng', 'Imported data': 'Dữ liệu đã nhập', 'In Catalogs': 'Trong danh mục', 'In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).': 'Trong GeoServer, đây là tên lớp. Trong WFS getCapabilities, đây là tên FeatureType, phần sau dấu hai chấm (:).', 'In Inventories': 'Trong nhóm hàng', 'In Process': 'Đang tiến hành', 'In Stock': 'Đang lưu kho', 'In error': 'mắc lỗi', 'In order to be able to edit OpenStreetMap data from within %(name_short)s, you need to register for an account on the OpenStreetMap server.': 'Để có thể chỉnh sửa dữ liệu trên OpenstreetMap từ trong %(name_short)s, ban cần đăng ký tài khoản trên máy chủ OpenStreetMap.', 'In transit': 'Đang trên đường', 'Inbound Mail Settings': 'Cài đặt thư đến', 'Inbound Message Source': 'Nguồn thư đến', 'Incident Categories': 'Danh mục sự cố', 'Incident Commander': 'Chỉ huy tình huống tai nạn', 'Incident Report Details': 'Chi tiết Báo cáo tai nạn', 'Incident Report added': 'Thêm Báo cáo tai nạn', 'Incident Report deleted': 'Xóa Báo cáo tai nạn', 'Incident Report updated': 'Cập nhật Báo cáo tai nạn', 'Incident Report': 'Báo cáo tai nạn', 'Incident Reports': 'Báo cáo sự cố', 'Incident Timeline': 'Dòng thời gian tai nạn', 'Incident Types': 'Loại sự cố', 'Incident': 'Sự cố', 'Incidents': 'Tai nạn', 'Include any special requirements such as equipment which they need to bring.': 'Bao gồm các yêu cầu đặc biệt như thiết bị cần mang theo', 'Include core files': 'Bao gồm các tệp chủ chốt', 'Incoming Shipments': 'Lô hàng đang đến', 'Incorrect parameters': 'Tham số không đúng', 'Indicator Comparison': 'So sánh chỉ số', 'Indicator': 'Chỉ số', 'Indicators': 'Chỉ số', 'Individuals': 'Cá nhân', 'Industrial Crime': 'Tội ác công nghiệp', 'Industry Fire': 'Cháy nổ công nghiệp', 'Infant (0-1)': 'Trẻ sơ sinh (0-1)', 'Infectious Disease (Hazardous Material)': 'Dịch bệnh lây nhiễm (vật liệu nguy hiểm)', 'Infectious Disease': 'Dịch bệnh lây nhiễm', 'Infestation': 'Sự phá hoại', 'Informal camp': 'Trại không chính thức', 'Information Management': 'Quản lý thông tin', 'Information Technology': 'Công nghệ thông tin', 'Infrastructure Development': 'Phát triển cơ sở hạ tầng', 'Inherited?': 'Được thừa kế?', 'Initials': 'Tên viết tắt', 'Insect Infestation': 'Nhiếm độc côn trùng', 'Instance Type': 'Loại ví dụ', 'Instant Porridge': 'Cháo ăn liền', 'Instructor': 'Giảng viên', 'Insufficient Privileges': 'Không đủ đặc quyền', 'Insufficient vars: Need module, resource, jresource, instance': 'Không đủ var: cần module, nguồn lực, j nguồn lực, tức thời', 'Integrity error: record can not be deleted while it is referenced by other records': 'Lỗi liên kết: hồ sơ không thể bị xóa khi đang được liên kết với hồ sơ khác', 'Internal Shipment': 'Vận chuyển nội bộ', 'Internal State': 'Tình trạng bên trong', 'International NGO': 'Tổ chức phi chính phủ quốc tế', 'International Organization': 'Tổ chức quốc tế', 'Interview taking place at': 'Phỏng vấn diễn ra tại', 'Invalid Location!': 'Vị trí không hợp lệ!', 'Invalid Query': 'Truy vấn không hợp lệ', 'Invalid Site!': 'Trang không hợp lệ!', 'Invalid form (re-opened in another window?)': 'Mẫu không hợp lệ (mở lại trong cửa sổ khác?)', 'Invalid phone number!': 'Số điện thoại không hợp lệ!', 'Invalid phone number': 'Số điện thoại không đúng', 'Invalid request!': 'Yêu cầu không hợp lệ!', 'Invalid request': 'Yêu cầu không hợp lệ', 'Invalid source': 'Nguồn không hợp lệ', 'Invalid ticket': 'Vé không đúng', 'Invalid': 'Không đúng', 'Inventory Adjustment Item': 'Mặt hàng điều chỉnh sau kiểm kê', 'Inventory Adjustment': 'Điều chỉnh sau kiểm kê', 'Inventory Item Details': 'Chi tiết hàng hóa trong kho', 'Inventory Item added': 'Bổ sung hàng hóa vào kho lưu trữ.', 'Inventory Items include both consumable supplies & those which will get turned into Assets at their destination.': 'Hàng hóa kiểm kê bao gồm cả hàng tiêu hao & hàng hóa sẽ được trả lại như tài sản tại đích đến', 'Inventory Items': 'Mặt hàng kiểm kê', 'Inventory Store Details': 'Chi tiết kho lưu trữ', 'Inventory of Effects': 'Kho dự phòng', 'Inventory': 'Kiểm kê', 'Is editing level L%d locations allowed?': 'Có được phép chỉnh sửa vị trí cấp độ L%d?', 'Is this a strict hierarchy?': 'Có phải là thứ tự đúng?', 'Issuing Authority': 'Cơ quan cấp', 'It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.': 'Nó không chỉ nhận các vị trí đang kích hoạt mà cũng nhận các thông tin về các dự án đang có ở từng vùng', 'Item Added to Shipment': 'Mặt hàng được thêm vào lô hàng vận chuyển', 'Item Catalog Details': 'Thông tin danh mục hàng hóa', 'Item Catalog added': 'Đã thêm danh mục hàng hóa', 'Item Catalog deleted': 'Đã xóa danh mục hàng hóa', 'Item Catalog updated': 'Đã cập nhật danh mục hàng hóa', 'Item Categories': 'Danh mục hàng hóa', 'Item Category Details': 'Thông tin danh mục hàng hóa', 'Item Category added': 'Danh mục hàng hóa đã được thêm', 'Item Category deleted': 'Danh mục hàng hóa đã được xóa', 'Item Category updated': 'Danh mục hàng hóa đã được cập nhật', 'Item Category': 'Danh mục hàng hóa', 'Item Code': 'Mã hàng hóa', 'Item Details': 'Thông tin hàng hóa', 'Item Pack Details': 'Thông tin về gói hàng', 'Item Pack added': 'Gói hàng đã được thêm', 'Item Pack deleted': 'Gói hàng đã được xóa', 'Item Pack updated': 'Gói hàng đã được cập nhật', 'Item Packs': 'Gói hàng', 'Item Status': 'Tình trạng hàng hóa', 'Item Sub-Category updated': 'Đã cập nhật tiêu chí phụ của hàng hóa', 'Item Tracking Status': 'Theo dõi tình trạng hàng hóa', 'Item added to stock': 'Mặt hàng được thêm vào kho', 'Item added': 'Mặt hàng đã được thêm', 'Item already in Bundle!': 'Hàng đã có trong Bundle!', 'Item deleted': 'Mặt hàng đã được xóa', 'Item quantity adjusted': 'Số lượng hàng đã được điều chỉnh', 'Item updated': 'Mặt hàng đã được cập nhật', 'Item': 'Mặt hàng', 'Item(s) added to Request': 'Hàng hóa đã được thêm vào yêu cầu', 'Item(s) deleted from Request': 'Hàng hóa đã được xóa khỏi yêu cầu', 'Item(s) updated on Request': 'Hàng hóa đã được cập nhật vào yêu cầu', 'Item/Description': 'Mặt hàng/ Miêu tả', 'Items in Category are Vehicles': 'Mặt hàng trong danh mục là phương tiện vận chuyển', 'Items in Category can be Assets': 'Mặt hàng trong danh mục có thể là tài sản', 'Items in Request': 'Hàng hóa trong thư yêu cầu', 'Items in Stock': 'Hàng hóa lưu kho', 'Items': 'Hàng hóa', 'Items/Description': 'Mô tả/Hàng hóa', 'JS Layer': 'Lớp JS', 'Jewish': 'Người Do Thái', 'Job Role Catalog': 'Danh mục vai trò công việc', 'Job Role Details': 'Chi tiết vai trò công việc', 'Job Role added': 'Vai trò công việc đã được thêm', 'Job Role deleted': 'Vai trò công việc đã được xóa', 'Job Role updated': 'Vai trò công việc đã được cập nhật', 'Job Role': 'Vai trò công việc', 'Job Schedule': 'Kế hoạch công việc', 'Job Title Catalog': 'Danh mục chức danh công việc', 'Job Title Details': 'Chi tiết chức danh công việc', 'Job Title added': 'Chức danh công việc đã được thêm', 'Job Title deleted': 'Chức danh công việc đã được xóa', 'Job Title updated': 'Chức danh công việc đã được cập nhật', 'Job Title': 'Chức danh công việc', 'Job Titles': 'Chức vụ', 'Job added': 'Công việc đã được thêm', 'Job deleted': 'Công việc đã được xóa', 'Job reactivated': 'Công việc đã được kích hoạt lại', 'Job updated': 'Công việc đã được cập nhật', 'Journal Entry Details': 'Chi tiết ghi chép nhật ký', 'Journal entry added': 'Ghi chép nhật ký đã được thêm', 'Journal entry deleted': 'Ghi chép nhật ký đã được xóa', 'Journal entry updated': 'Ghi chép nhật ký đã được cập nhật', 'Journal': 'Nhật ký', 'KML Layer': 'Lớp KML', 'Key Value pairs': 'Đôi giá trị Khóa', 'Key deleted': 'Đã xóa từ khóa', 'Key': 'Phím', 'Keyword': 'Từ khóa', 'Keywords': 'Từ khóa', 'Kit Created': 'Thùng hàng đã được tạo', 'Kit Details': 'Chi tiết thùng hàng', 'Kit Item': 'Mặt hàng trong thùng', 'Kit Items': 'Mặt hàng trong thùng', 'Kit canceled': 'Thùng hàng đã được hủy', 'Kit deleted': 'Đã xóa Kit', 'Kit updated': 'Thùng hàng đã được cập nhật', 'Kit': 'Thùng hàng', 'Kit?': 'Thùng hàng?', 'Kits': 'Thùng hàng', 'Kitting': 'Trang bị dụng cụ', 'Known Locations': 'Vị trí được xác định', 'LEGEND': 'CHÚ GIẢI', 'LICENSE': 'Bản quyền', 'LOW RESILIENCE': 'MỨC ĐỘ AN TOÀN THẤP', 'LOW': 'THẤP', 'Label': 'Nhãn', 'Lack of transport to school': 'Thiếu phương tiện di chuyển cho trẻ em đến trường', 'Lahar': 'Dòng dung nham', 'Land Slide': 'Sạt lở đất', 'Landslide': 'Sạt lở đất', 'Language Code': 'Mã Ngôn ngữ', 'Language code': 'Mã ngôn ngữ', 'Language': 'Ngôn ngữ', 'Last Checked': 'Lần cuối cùng được kiểm tra', 'Last Data Collected on': 'Dữ liệu mới nhất được thu thập trên', 'Last Name': 'Tên họ', 'Last Pull': 'Kéo gần nhất', 'Last Push': 'Đầy gần nhất', 'Last known location': 'Địa điểm vừa biết đến', 'Last pull on': 'Kéo về gần đây', 'Last push on': 'Đẩy vào gần đây', 'Last run': 'Lần chạy gần nhất', 'Last status': 'Trạng thái gần đây', 'Last updated ': 'Cập nhật mới nhất', 'Last': 'Trang cuối', 'Latitude & Longitude': 'Vĩ độ & Kinh độ', 'Latitude is Invalid!': 'Vị độ không hợp lệ', 'Latitude is North-South (Up-Down). Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.': 'Vĩ độ là Bắc-Nam (trên xuống). Vĩ độ bằng không trên đường xích đạo, dương phía bán cầu Bắc và âm phía bán cầu Nam', 'Latitude is North-South (Up-Down).': 'Vĩ độ Bắc-Nam (trên-xuống)', 'Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.': 'Vĩ độ bằng 0 là ở xích đạo và có giá trị dương ở bắc bán cầu và giá trị âm ở nam bán cầu', 'Latitude must be between -90 and 90.': 'Vĩ độ phải nằm giữa -90 và 90', 'Latitude of Map Center': 'Vĩ độ trung tâm bản đồ vùng', 'Latitude of far northern end of the region of interest.': 'Vĩ độ bắc điểm cuối của vùng quan tâm', 'Latitude of far southern end of the region of interest.': 'Vĩ độ nam điểm cuối của vùng quan tâm', 'Latitude should be between': 'Vĩ độ phải từ ', 'Latitude': 'Vĩ độ', 'Latrines': 'nhà vệ sinh', 'Layer Details': 'Thông tin về Lớp', 'Layer Name': 'Tên lớp', 'Layer Properties': 'Đặc tính của lớp bản đồ', 'Layer added': 'Lớp đã được thêm', 'Layer deleted': 'Lớp đã được xóa', 'Layer has been Disabled': 'Lớp đã bị khóa', 'Layer has been Enabled': 'Lớp đã được bật', 'Layer removed from Symbology': 'Lớp đã được gỡ khỏi danh mục biểu tượng', 'Layer updated': 'Lớp đã được cập nhật', 'Layer': 'Lớp', 'Layers updated': 'Đã cập nhật Layer', 'Layers': 'Lớp', 'Layout': 'Định dạng', 'Lead Implementer for this project is already set, please choose another role.': 'Người thực hiện chính của Dự án này đã được chỉ định, đề nghị chọn một vai trò khác', 'Lead Implementer': 'Trưởng nhóm thực hiện', 'Lead Organization': 'Tổ chức chỉ đạo', 'Leader': 'Người lãnh đạo', 'Leave blank to request an unskilled person': 'Bỏ trắng nếu yêu cầu người không cần kỹ năng', 'Left-side is fully transparent (0), right-side is opaque (1.0).': 'Bên trái là hoàn toàn trong suốt (0), bên phải là không trong suốt (1.0)', 'Legend URL': 'Chú giải URL', 'Legend': 'Chú giải', 'Length (m)': 'Chiều dài (m)', 'Length': 'Độ dài', 'Less Options': 'Thu hẹp chức năng', 'Level of Award (Count)': 'Trình độ học vấn (Số lượng)', 'Level of Award': 'Trình độ học vấn', 'Level of competency this person has with this skill.': 'Cấp độ năng lực của người này với kỹ năng đó', 'Level': 'Cấp độ', 'Library support not available for OpenID': 'Thư viện hỗ trợ không có sẵn cho việc tạo ID', 'License Number': 'Số giấy phép', 'Link (or refresh link) between User, Person & HR Record': 'Đường dẫn (hay đường dẫn mới) giữa người dùng, người và hồ sơ cán bộ', 'Link to this result': 'Đường dẫn tới kết quả này', 'Link': 'Liên kết', 'List / Add Baseline Types': 'Liệt kê / thêm loại hình khảo sát trước can thiệp', 'List / Add Impact Types': 'Liệt kê / thêm loại tác động', 'List Activities': 'Liêt kê hoạt động', 'List Activity Types': 'Liệt kê loại hoạt động', 'List Addresses': 'Liệt kê địa chỉ', 'List Affiliations': 'Liệt kê liên kết', 'List Aid Requests': 'Danh sách Yêu cầu cứu trợ', 'List All Catalogs & Add Items to Catalogs': 'Liệt kê danh mục & Thêm mục mặt hàng vào danh mục', 'List All Commitments': 'Liệt kê tất cả cam kết', 'List All Community Contacts': 'Liệt kê tất cả thông tin liên lạc của cộng đồng', 'List All Entries': 'Liệt kê tất cả hồ sơ', 'List All Essential Staff': 'Liệt kê tất cả cán bộ quan trọng', 'List All Item Categories': 'Liệt kê tât cả danh mục hàng hóa', 'List All Items': 'Liệt kê tất cả mặt hàng', 'List All Memberships': 'Danh sách tất cả các thành viên', 'List All Requested Items': 'Liệt kê tất cả mặt hàng được yêu cầu', 'List All Requested Skills': 'Liệt kê tất cả kỹ năng được yêu cầu', 'List All Requests': 'Liệt kê tất cả yêu cầu', 'List All Roles': 'Liệt kê tất cẩ vai trò', 'List All Security-related Staff': 'Liệt kê tất cả cán bộ liên quan đến vai trò bảo vệ', 'List All Users': 'Liệt kê tất cả người dùng', 'List All': 'Liệt kê tất cả', 'List Alternative Items': 'Liệt kê mặt hàng thay thế', 'List Annual Budgets': 'Liệt kê ngân sách năm', 'List Assessment Answers': 'Liêt kê câu trả lời trong biểu mẫu đánh giá', 'List Assessment Questions': 'Liệt kê câu hỏi trong biểu mẫu đánh giá', 'List Assessment Templates': 'Liệt kê biểu mẫu đánh giá', 'List Assessments': 'Danh sách Trị giá tính thuế', 'List Assets': 'Liệt kê tài sản', 'List Assigned Human Resources': 'Liệt kê nguồn nhân lực đã được phân công', 'List Beneficiaries': 'Liệt kê người hưởng lợi', 'List Beneficiary Types': 'Liệt kê loại người hưởng lợi', 'List Branch Organizations': 'Liệt kê tổ chức cơ sở', 'List Brands': 'Liệt kê nhãn hiệu', 'List Catalog Items': 'Liệt kê mặt hàng trong danh mục', 'List Catalogs': 'Liệt kê danh mục', 'List Certificates': 'Liệt kê chứng chỉ', 'List Certifications': 'Liệt kê bằng cấp', 'List Checklists': 'Danh sách Checklists ', 'List Clusters': 'Liệt kê nhóm', 'List Commitment Items': 'Liệt kê mặt hàng cam kết', 'List Commitments': 'Liệt kê cam kết', 'List Committed People': 'Liệt kê người cam kết', 'List Communities': 'Liệt kê cộng đồng', 'List Competency Ratings': 'Liệt kê xếp hạng năng lực', 'List Completed Assessment Forms': 'Liệt kê biểu mẫu đánh giá đã hoàn thiện', 'List Contact Information': 'Liệt kê thông tin liên lạc', 'List Contacts': 'Liệt kê liên lạc', 'List Course Certificates': 'Liệt kê Chứng chỉ khóa học', 'List Courses': 'Liệt kê khóa học', 'List Credentials': 'Liệt kê thư ủy nhiệm', 'List Current': 'Danh mục hiện hành', 'List Data in Theme Layer': 'Liệt kê dữ liệu trong lớp chủ đề ', 'List Demographic Data': 'Liệt kê số liệu dân số', 'List Demographic Sources': 'Liệt kê nguồn thông tin về dân số', 'List Demographics': 'Liệt kê dữ liệu nhân khẩu', 'List Departments': 'Liệt kê phòng/ban', 'List Disaster Assessments': 'Liệt kê báo cáo đánh giá thảm họa', 'List Distributions': 'Danh sách ủng hộ,quyên góp', 'List Documents': 'Liệt kê tài liệu', 'List Donors': 'Liệt kê nhà tài trợ', 'List Education Details': 'Liệt kê thông tin về trình độ học vấn', 'List Facilities': 'Liệt kê bộ phận', 'List Facility Types': 'Liệt kê loại hình bộ phận', 'List Feature Layers': 'Liệt kê lớp chức năng', 'List Frameworks': 'Liệt kê khung chương trình', 'List Groups': 'Liệt kê nhóm', 'List Hazards': 'Liệt kê hiểm họa', 'List Hospitals': 'Danh sách Bệnh viện', 'List Hours': 'Liệt kê thời gian hoạt động', 'List Identities': 'Liệt kê nhận dạng', 'List Images': 'Liệt kê hình ảnh', 'List Incident Reports': 'Liệt kê báo cáo sự cố', 'List Item Categories': 'Liệt kê danh mục hàng hóa', 'List Item Packs': 'Liệt kê gói hàng', 'List Items in Request': 'Liệt kê mặt hàng đang được yêu cầu', 'List Items in Stock': 'Liệt kê mặt hàng đang lưu kho', 'List Items': 'Liệt kê hàng hóa', 'List Job Roles': 'Liệt kê vai trò công việc', 'List Job Titles': 'Liệt kê chức danh công việc', 'List Jobs': 'Liệt kê công việc', 'List Kits': 'Liệt kê thùng hàng', 'List Layers in Profile': 'Liệt kê lớp trong hồ sơ tiểu sử', 'List Layers in Symbology': 'Liệt kê lớp trong biểu tượng', 'List Layers': 'Liệt kê lớp', 'List Location Hierarchies': 'Liệt kê thứ tự địa điểm', 'List Locations': 'Liệt kê địa điểm', 'List Log Entries': 'Liệt kê ghi chép nhật ký', 'List Logged Time': 'Liệt kê thời gian đang nhập', 'List Mailing Lists': 'Liệt kê danh sách gửi thư', 'List Map Configurations': 'Liệt kê cấu hình bản đồ', 'List Markers': 'Liệt kê công cụ đánh dấu', 'List Members': 'Liệt kê hội viên', 'List Membership Types': 'Liệt kê loại hình nhóm hội viên', 'List Memberships': 'Liệt kê nhóm hội viên', 'List Messages': 'Liệt kê tin nhắn', 'List Metadata': 'Danh sách dữ liệu', 'List Milestones': 'Liệt kê mốc thời gian quan trọng', 'List Missing Persons': 'Danh sách những người mất tích', 'List Office Types': 'Liệt kê loại hình văn phòng', 'List Offices': 'Liệt kê văn phòng', 'List Orders': 'Liệt kê lệnh', 'List Organization Domains': 'Liệt kê lĩnh vực hoạt động của tổ chức', 'List Organization Types': 'Liệt kê loại hình tổ chức', 'List Organizations': 'Liệt kê tổ chức', 'List Outputs': 'Liệt kê đầu ra', 'List Participants': 'Liệt kê người Tham dự', 'List Partner Organizations': 'Liệt kê tổ chức đối tác', 'List Persons': 'Liệt kê đối tượng', 'List Photos': 'Liệt kê ảnh', 'List Profiles configured for this Layer': 'Liệt kê tiểu sử được cấu hình cho lớp này', 'List Programs': 'Liệt kê chương trình', 'List Project Organizations': 'Liệt kê tổ chức dự án', 'List Projections': 'Liệt kê dự đoán', 'List Projects': 'Liệt kê dự án', 'List Question Meta-Data': 'Liệt kê siêu dữ liệu câu hỏi', 'List Received/Incoming Shipments': 'Liệt kê lô hàng nhận được/đang đến', 'List Records': 'Liệt kê hồ sơ', 'List Red Cross & Red Crescent National Societies': 'Liệt kê Hội CTĐ & TLLĐ quốc gia', 'List Repositories': 'Liệt kê kho lưu trữ', 'List Request Items': 'Danh sách Hang hóa yêu cầu', 'List Requested Skills': 'Liệt kê kỹ năng được yêu cầu', 'List Requests': 'Liệt kê yêu cầu', 'List Resources': 'Liệt kê nguồn lực', 'List Rivers': 'Danh sách sông', 'List Roles': 'Liệt kê vai trò', 'List Rooms': 'Liệt kê phòng', 'List Sectors': 'Liệt kê lĩnh vực', 'List Sent Shipments': 'Liệt kê lô hàng đã gửi đi', 'List Shelter Services': 'Danh sách dịch vụ cư trú', 'List Shipment Items': 'Liệt kê mặt hàng trong lô hàng', 'List Shipment/Way Bills': 'Danh sách Đơn hàng/Phí đường bộ', 'List Sites': 'Danh sách site', 'List Skill Equivalences': 'Liệt kê kỹ năng tương đương', 'List Skill Types': 'Liệt kê loại kỹ năng', 'List Skills': 'Liệt kê kỹ năng', 'List Staff & Volunteers': 'Liệt kê Cán bộ và Tình nguyện viên', 'List Staff Assignments': 'Liệt kê phân công cán bộ', 'List Staff Members': 'Liệt kê cán bộ', 'List Staff Types': 'Lên danh sách các bộ phận nhân viên', 'List Staff': 'Danh sách Nhân viên', 'List Statuses': 'Liệt kê tình trạng', 'List Stock Adjustments': 'Liệt kê điều chỉnh hàng lưu kho', 'List Stock in Warehouse': 'Liệt kê hàng lưu trong kho hàng', 'List Storage Location': 'Danh sách vị trí kho lưu trữ', 'List Subscriptions': 'Danh sách Đăng ký', 'List Suppliers': 'Liệt kê nhà cung cấp', 'List Support Requests': 'Liệt kê đề nghị hỗ trợ', 'List Survey Questions': 'Danh sách câu hỏi khảo sát', 'List Survey Series': 'Lên danh sách chuỗi khảo sát', 'List Symbologies for Layer': 'Liệt kê biểu tượng cho Lớp', 'List Symbologies': 'Liệt kê biểu tượng', 'List Tasks': 'Liệt kê nhiệm vụ', 'List Teams': 'Liệt kê Đội/Nhóm', 'List Template Sections': 'Liệt kê nội dung biểu mẫu', 'List Themes': 'Liệt kê chủ đề', 'List Training Events': 'Liệt kê khóa tập huấn', 'List Trainings': 'Liệt kê lớp tập huấn', 'List Units': 'Danh sách đơn vị', 'List Users': 'Liệt kê người sử dụng', 'List Vehicle Assignments': 'Liệt kê phân công phương tiện vận chuyển', 'List Volunteer Cluster Positions': 'Liệt kê vị trí nhóm tình nguyện viên', 'List Volunteer Cluster Types': 'Liệt kê loại hình nhóm tình nguyện viên', 'List Volunteer Clusters': 'Liệt kê nhóm tình nguyện viên', 'List Volunteer Roles': 'Liệt kê vai trò của tình nguyện viên', 'List Volunteers': 'Liệt kê tình nguyện viên', 'List Vulnerability Aggregated Indicators': 'Liệt kê chỉ số gộp đánh giá tình trạng dễ bị tổn thương', 'List Vulnerability Data': 'Liệt kê dữ liệu về tình trạng dễ bị tổn thương', 'List Vulnerability Indicator Sources': 'Liệt kê nguồn chỉ số đánh giá tình trạng dễ bị tổn thương', 'List Vulnerability Indicators': 'Liệt kê chỉ số đánh giá tình trạng dễ bị tổn thương', 'List Warehouses': 'Liệt kê kho hàng', 'List alerts': 'Liệt kê cảnh báo', 'List all Entries': 'Liệt kê tất cả hồ sơ', 'List all': 'Liệt kê tất cả', 'List of Missing Persons': 'Danh sách những người mất tích', 'List of Professional Experience': 'Danh sách kinh nghiệm nghề nghiệp', 'List of Requests': 'Danh sách yêu cầu', 'List of Roles': 'Danh sách vai trò', 'List of addresses': 'Danh sách các địa chỉ', 'List saved searches': 'Liệt kê tìm kiếm đã lưu', 'List templates': 'Liệt kê biểu mẫu', 'List unidentified': 'Liệt kê danh mục chư tìm thấy', 'List': 'Liệt kê', 'List/Add': 'Liệt kê/ Thêm', 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities': 'Danh sách "Ai làm gì, ở đâu"Cho phép các tổ chức cứu trợ điều phối hoạt động của mình', 'Live Help': 'Trợ giúp trực tuyến', 'Livelihood': 'Sinh kế', 'Livelihoods': 'Sinh kế', 'Load Cleaned Data into Database': 'Tải dữ liệu sạch vào cơ sở dữ liệu', 'Load Raw File into Grid': 'Tải file thô vào hệ thống mạng', 'Load': 'Tải', 'Loaded By': 'Được tải lên bởi', 'Loading report details': 'Tải thông tin báo cáo', 'Loading': 'Đang tải', 'Local Name': 'Tên địa phương', 'Local Names': 'Tên địa phương', 'Location (Site)': 'Địa điểm (vùng)', 'Location 1': 'Địa điểm 1', 'Location 2': 'Địa điểm 2', 'Location 3': 'Địa điểm 3', 'Location Added': 'Địa điểm đã được thêm', 'Location Deleted': 'Địa điểm đã được xóa', 'Location Detail': 'Thông tin địa điểm', 'Location Details': 'Thông tin địa điểm', 'Location Group': 'Nhóm địa điểm', 'Location Hierarchies': 'Thứ tự địa điểm', 'Location Hierarchy Level 1 Name': 'Tên thứ tự địa điểm cấp 1', 'Location Hierarchy Level 2 Name': 'Tên thứ tự địa điểm cấp 2', 'Location Hierarchy Level 3 Name': 'Tên thứ tự địa điểm cấp 3', 'Location Hierarchy Level 4 Name': 'Tên thứ tự địa điểm cấp 4', 'Location Hierarchy Level 5 Name': 'Tên thứ tự địa điểm cấp 5', 'Location Hierarchy added': 'Thứ tự địa điểm đã được thêm', 'Location Hierarchy deleted': 'Thứ tự địa điểm đã được xóa', 'Location Hierarchy updated': 'Thứ tự địa điểm đã được cập nhật', 'Location Hierarchy': 'Thứ tự địa điểm', 'Location Updated': 'Địa điểm đã được cập nhật', 'Location added': 'Địa điểm đã được thêm', 'Location deleted': 'Địa điểm đã được xóa', 'Location is Required!': 'Địa điểm được yêu cầu!', 'Location needs to have WKT!': 'Địa điểm cần để có WKT!', 'Location updated': 'Địa điểm đã được cập nhật', 'Location': 'Địa điểm', 'Locations of this level need to have a parent of level': 'Địa điểm ở cấp độ này cần có các cấp độ cha', 'Locations': 'Địa điểm', 'Log Entry Deleted': 'Ghi chép nhật ký đã được xóa', 'Log Entry Details': 'Thông tin về ghi chép nhật ký', 'Log Entry': 'Ghi chép nhật ký', 'Log New Time': 'Thời gian truy cập Mới', 'Log Time Spent': 'Thời gian đã Truy cập', 'Log entry added': 'Ghi chép nhật ký đã được thêm', 'Log entry deleted': 'Ghi chép nhật ký đã được xóa', 'Log entry updated': 'Ghi chép nhật ký đã được cập nhật', 'Log': 'Nhật ký', 'Logged Time Details': 'Thông tin về thời gian đã truy cập', 'Logged Time': 'Thời gian đã truy cập', 'Login with Facebook': 'Đăng nhập với Facebook', 'Login with Google': 'Đăng nhập với Google', 'Login': 'Đăng nhập', 'Logo of the organization. This should be a png or jpeg file and it should be no larger than 400x400': 'Biểu trưng của một tổ chức phải là tệp png hay jpeg and không lớn hơn 400x400', 'Logo': 'Biểu tượng', 'Logout': 'Thoát', 'Long Name': 'Tên đầy đủ', 'Long Text': 'Đoạn văn bản dài', 'Longitude is Invalid!': 'Kinh độ không hợp lệ', 'Longitude is West - East (sideways). Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Kinh độ trải dài theo hướng Đông-Tây. Kinh tuyến không nằm trên kinh tuyến gốc (Greenwich Mean Time) hướng về phía đông, vắt ngang châu Âu và châu Á.', 'Longitude is West - East (sideways).': 'Kinh độ Tây - Đông (đường ngang)', 'Longitude is West-East (sideways).': 'Kinh độ Tây - Đông (đường ngang)', 'Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Kinh độ là 0 tại đường kinh tuyến đầu tiên (Thời gian vùng Greenwich) và có giá trị dương sang phía đông, qua Châu Âu và Châu Á. Kinh tuyến có giá trị âm sang phía tây, từ Đại Tây Dương qua Châu Mỹ.', 'Longitude is zero on the prime meridian (through Greenwich, United Kingdom) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Kinh độ là 0 tại đường kinh tuyến đầu tiên (xuyên qua Greenwich, Anh) và có giá trị dương sang phía đông, qua châu Âu và Châu Á. Kinh tuyến có giá trị âm sang phía tây qua Đại Tây Dương và Châu Mỹ.', 'Longitude must be between -180 and 180.': 'Kinh độ phải nằm giữa -180 và 180', 'Longitude of Map Center': 'Kinh độ trung tâm bản đồ của vùng quan tâm', 'Longitude of far eastern end of the region of interest.': 'Kinh độ phía đông điểm cuối của vùng quan tâm', 'Longitude of far western end of the region of interest.': 'Kinh độ phía tây điểm cuối của vùng quan tâm', 'Longitude should be between': 'Kinh độ phải từ giữa', 'Longitude': 'Kinh độ', 'Looting': 'Nạn cướp bóc', 'Lost Password': 'Mất mật khẩu', 'Lost': 'Mất', 'Low': 'Thấp', 'MEDIAN': 'ĐIỂM GIỮA', 'MGRS Layer': 'Lớp MGRS', 'MODERATE': 'TRUNG BÌNH', 'MY REPORTS': 'BÁO CÁO CỦA TÔI', 'Magnetic Storm': 'Bão từ trường', 'Mailing List Details': 'Thông tin danh sách gửi thư', 'Mailing List Name': 'Tên danh sách gửi thư', 'Mailing Lists': 'Danh sách gửi thư', 'Mailing list added': 'Danh sách gửi thư đã được thêm', 'Mailing list deleted': 'Danh sách gửi thư đã được xóa', 'Mailing list updated': 'Danh sách gửi thư đã được cập nhật', 'Mailing list': 'Danh sách gửi thư', 'Main Duties': 'Nhiệm vụ chính', 'Major Damage': 'Thiệt hại lớn', 'Major outward damage': 'Vùng ngoài chính hỏng', 'Major': 'Chuyên ngành', 'Make Commitment': 'Làm một cam kết', 'Make New Commitment': 'Làm một cam kết Mới', 'Make Request': 'Đặt yêu cầu', 'Make a Request for Aid': 'Tạo yêu cầu cứu trợ', 'Make a Request': 'Tạo yêu cầu', 'Male': 'Nam', 'Manage Layers in Catalog': 'Quản lý Lớp trong danh mục', 'Manage Returns': 'Quản lý hàng trả lại', 'Manage Sub-Category': 'Quản lý Tiêu chí phụ', 'Manage Teams Data': 'Quản lý dữ liệu đội TNV', 'Manage Users & Roles': 'Quản lý Người sử dụng & Vai trò', 'Manage Volunteer Data': 'Quản lý dữ liệu TNV', 'Manage Your Facilities': 'Quản lý bộ phận của bạn', 'Manage office inventories and assets.': 'Quản lý tài sản và thiết bị văn phòng', 'Manage volunteers by capturing their skills, availability and allocation': 'Quản ly tình nguyện viên bằng việc nắm bắt những kĩ năng, khả năng và khu vực hoạt động của họ', 'Managing material and human resources together to better prepare for future hazards and vulnerabilities.': 'Quản lý nguồn lực để chuẩn bị tốt hơn cho hiểm họa trong tương lai và tình trạng dễ bị tổn thương.', 'Managing, Storing and Distributing Relief Items.': 'Quản lý, Lưu trữ và Quyên góp hàng cứu trợ', 'Mandatory. In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).': 'Bắt buộc. Trong máy chủ về Địa lý, đây là tên Lớp. Trong lớp WFS theo Khả năng là đường dẫn, đây là phần Tên loại chức năng sau dấu hai chấm (:).', 'Mandatory. The URL to access the service.': 'Trường bắt buộc. URL để đăng nhập dịch vụ', 'Manual Synchronization': 'Đồng bộ hóa thủ công', 'Manual synchronization completed.': 'Đồng bộ hóa thủ công đã hoàn tất', 'Manual synchronization scheduled - refresh page to update status.': 'Đồng bộ hóa thủ công đã được đặt lịch - làm mới trang để cập nhật tình trạng', 'Manual synchronization started in the background.': 'Đồng bộ hóa thủ công đã bắt đầu ở nền móng', 'Map': 'Bản đồ', 'Map Center Latitude': 'Vĩ độ trung tâm bản đồ', 'Map Center Longitude': 'Kinh độ trung tâm bản đồ', 'Map Configuration added': 'Cấu hình bản đồ đã được thêm', 'Map Configuration deleted': 'Cấu hình bản đồ đã được xóa', 'Map Configuration updated': 'Cấu hình bản đồ đã được cập nhật', 'Map Configuration': 'Cấu hình bản đồ', 'Map Configurations': 'Cấu hình bản đồ', 'Map Height': 'Chiều cao bản đồ', 'Map Service Catalog': 'Catalogue bản đồ dịch vụ', 'Map Settings': 'Cài đặt bản đồ', 'Map Viewing Client': 'Người đang xem bản đồ', 'Map Width': 'Độ rộng bản đồ', 'Map Zoom': 'Phóng to thu nhỏ Bản đồ', 'Map from Sahana Eden': 'Bản đồ từ Sahana Eden', 'Map not available: No Projection configured': 'Bản đồ không có: Chưa có dự đoán được cài đặt', 'Map not available: Projection %(projection)s not supported - please add definition to %(path)s': 'Bản đồ không có: Dự đoán %(projection)s không được hỗ trỡ - xin thêm khái niệm đến %(path)s', 'Map of Communties': 'Bản đồ cộng đồng', 'Map of Hospitals': 'Bản đồ bệnh viện', 'Map of Incident Reports': 'Bản đồ báo cáo sự cố', 'Map of Offices': 'Bản đồ văn phòng', 'Map of Projects': 'Bản đồ dự án', 'Map of Warehouses': 'Bản đồ kho hàng', 'Map': 'Bản đồ', 'Marine Security': 'An ninh hàng hải', 'Marital Status': 'Tình trạng hôn nhân', 'Marker Details': 'Thông tin công cụ đánh dấu', 'Marker Levels': 'Cấp độ công cụ đánh dấu', 'Marker added': 'Công cụ đánh dấu đã được thêm', 'Marker deleted': 'Công cụ đánh dấu đã được xóa', 'Marker updated': 'Công cụ đánh dấu đã được cập nhật', 'Marker': 'Công cụ đánh dấu', 'Markers': 'Công cụ đánh dấu', 'Married': 'Đã kết hôn', 'Master Message Log to process incoming reports & requests': 'Kiểm soát log tin nhắn để xử lý báo cáo và yêu cầu gửi đến', 'Master Message Log': 'Nhật ký tin nhắn chính', 'Master': 'Chủ chốt', 'Match Requests': 'Phù hợp với yêu cầu', 'Match?': 'Phù hợp?', 'Matching Catalog Items': 'Mặt hàng trong danh mục phù hợp', 'Matching Items': 'Mặt hàng phù hợp', 'Matching Records': 'Hồ sơ phù hợp', 'Maternal, Newborn and Child Health': 'CSSK Bà mẹ, Trẻ sơ sinh và Trẻ em', 'Matrix of Choices (Only one answer)': 'Ma trận lựa chọn (chỉ chọn một câu trả lời)', 'Maximum Location Latitude': 'Vĩ độ tối đa của địa điểm', 'Maximum Location Longitude': 'Kinh độ tối đa của địa điểm', 'Maximum Weight': 'Khối lượng tối đa', 'Maximum must be greater than minimum': 'Giá trị tối đa phải lớn hơn giá trị tối thiểu', 'Maximum': 'Tối đa', 'Mean': 'Trung bình', 'Measure Area: Click the points around the polygon & end with a double-click': 'Đo diện tích: Bấm chuột vào điểm của khu vực cần đo & kết thúc bằng nháy đúp chuột', 'Measure Length: Click the points along the path & end with a double-click': 'Đo Chiều dài: Bấm chuột vào điểm dọc đường đi & kết thúc bằng nháy đúp chuột', 'Media': 'Truyền thông', 'Median Absolute Deviation': 'Độ lệch tuyệt đối trung bình', 'Median': 'Điểm giữa', 'Medical Conditions': 'Tình trạng sức khỏe', 'Medical Services': 'Dịch vụ y tế', 'Medium': 'Trung bình', 'Member Base Development': 'Phát triển dựa vào hội viên', 'Member Details': 'Thông tin về hội viên', 'Member ID': 'Tên truy nhập của hội viên', 'Member added to Group': 'Thành viên nhóm đã được thêm', 'Member added to Team': 'Thành viên Đội/Nhóm đã thêm', 'Member added': 'Hội viên đã được thêm', 'Member deleted': 'Hội viên đã được xóa', 'Member removed from Group': 'Nhóm hội viên đã được xóa', 'Member updated': 'Hội viên đã được cập nhật', 'Member': 'Hội viên', 'Members': 'Hội viên', 'Membership Details': 'Thông tin về nhóm hội viên', 'Membership Fee': 'Phí hội viên', 'Membership Paid': 'Hội viên đã đóng phí', 'Membership Type Details': 'Thông tin về loại hình nhóm hội viên', 'Membership Type added': 'Loại hình nhóm hội viên đã được thêm', 'Membership Type deleted': 'Loại hình nhóm hội viên đã được xóa', 'Membership Type updated': 'Loại hình nhóm hội viên đã được cập nhật', 'Membership Types': 'Loại hình nhóm hội viên', 'Membership updated': 'Nhóm hội viên đã được cập nhật', 'Membership': 'Nhóm hội viên', 'Memberships': 'Nhóm hội viên', 'Message Details': 'Chi tiết tin nhắn', 'Message Parser settings updated': 'Cài đặt cú pháp tin nhắn đã được cập nhật', 'Message Source': 'Nguồn tin nhắn', 'Message Variable': 'Biến tin nhắn', 'Message added': 'Tin nhắn đã được thêm ', 'Message deleted': 'Tin nhắn đã được xóa', 'Message updated': 'Tin nhắn đã được cập nhật', 'Message variable': 'Biến tin nhắn', 'Message': 'Tin nhắn', 'Messages': 'Tin nhắn', 'Messaging': 'Soạn tin nhắn', 'Metadata Details': 'Chi tiết siêu dữ liệu', 'Metadata added': 'Đã thêm dữ liệu', 'Metadata': 'Lý lịch dữ liệu', 'Meteorite': 'Thiên thạch', 'Middle Name': 'Tên đệm', 'Migrants or ethnic minorities': 'Dân di cư hoặc dân tộc thiểu số', 'Milestone Added': 'Mốc thời gian quan trọng đã được thêm', 'Milestone Deleted': 'Mốc thời gian quan trọng đã được xóa', 'Milestone Details': 'Thông tin về mốc thời gian quan trọng', 'Milestone Updated': 'Mốc thời gian quan trọng đã được cập nhật', 'Milestone': 'Mốc thời gian quan trọng', 'Milestones': 'Mốc thời gian quan trọng', 'Minimum Location Latitude': 'Vĩ độ tối thiểu của địa điểm', 'Minimum Location Longitude': 'Kinh độ tối thiểu của địa điểm', 'Minimum': 'Tối thiểu', 'Minor Damage': 'Thiệt hại nhỏ', 'Minute': 'Phút', 'Minutes must be a number.': 'Giá trị của phút phải bằng chữ số', 'Minutes must be less than 60.': 'Giá trị của phút phải ít hơn 60', 'Missing Person Details': 'Chi tiết về người mất tích', 'Missing Person Reports': 'Báo cáo số người mất tích', 'Missing Person': 'Người mất tích', 'Missing Persons Report': 'Báo cáo số người mất tích', 'Missing Persons': 'Người mất tích', 'Missing Senior Citizen': 'Người già bị mất tích', 'Missing Vulnerable Person': 'Người dễ bị tổn thương mất tích', 'Missing': 'Mất tích', 'Mobile Phone Number': 'Số di động', 'Mobile Phone': 'Số di động', 'Mobile': 'Di động', 'Mode': 'Phương thức', 'Model/Type': 'Đời máy/ Loại', 'Modem settings updated': 'Cài đặt mô đem được đã được cập nhật', 'Modem': 'Mô đem', 'Moderator': 'Điều tiết viên', 'Modify Feature: Select the feature you wish to deform & then Drag one of the dots to deform the feature in your chosen manner': 'Sửa đổi tính năng: Lựa chọn tính năng bạn muốn để thay đổi và sau đó kéo vào một trong điểm để thay đổi tính năng theoh bạn chọn', 'Modify Information on groups and individuals': 'Thay đổi thông tin của nhóm và cá nhân', 'Module Administration': 'Quản trị Mô-đun', 'Monday': 'Thứ Hai', 'Monetization Details': 'Thông tin lưu hành tiền tệ', 'Monetization Report': 'Báo cáo lưu hành tiền tệ', 'Monetization': 'Lưu hành tiền tệ', 'Month': 'Tháng', 'Monthly': 'Hàng tháng', 'Months': 'Tháng', 'More Options': 'Mở rộng chức năng', 'Morgue': 'Phòng tư liệu', 'Morgues': 'Phòng tư liệu', 'Moustache': 'Râu quai nón', 'Move Feature: Drag feature to desired location': 'Di chuyển tính năng: Kéo tính năng tới vị trí mong muốn', 'Multi-Option': 'Đa lựa chọn', 'Multiple Matches': 'Nhiều kết quả phù hợp', 'Multiple': 'Nhiều', 'Muslim': 'Tín đồ Hồi giáo', 'Must a location have a parent location?': 'Một địa danh cần phải có địa danh trực thuộc đi kèm?', 'My Logged Hours': 'Thời gian truy cập của tôi', 'My Open Tasks': 'Nhiệm vụ của tôi', 'My Profile': 'Hồ sơ của tôi', 'My Tasks': 'Nhiệm vụ của tôi', 'My reports': 'Báo cáo của tôi', 'N/A': 'Không xác định', 'NO': 'KHÔNG', 'NUMBER_GROUPING': 'SỐ_THEO NHÓM', 'NZSEE Level 1': 'Mức 1 NZSEE', 'NZSEE Level 2': 'Mức 2 NZSEE', 'Name and/or ID': 'Tên và/hoặc tên truy nhập', 'Name field is required!': 'Bắt buộc phải điền Tên!', 'Name of Award': 'Tên phần thưởng', 'Name of Driver': 'Tên tài xế', 'Name of Father': 'Tên cha', 'Name of Institute': 'Trường Đại học/ Học viện', 'Name of Mother': 'Tên mẹ', 'Name of Storage Bin Type.': 'Tên loại Bin lưu trữ', 'Name of the person in local language and script (optional).': 'Tên theo ngôn ngữ và chữ viết địa phương (tùy chọn)', 'Name of the repository (for you own reference)': 'Tên của kho (để bạn tham khảo)', 'Name': 'Tên', 'National ID Card': 'Chứng minh nhân dân', 'National NGO': 'Các tổ chức phi chính phủ ', 'National Societies': 'Hội Quốc gia', 'National Society / Branch': 'Cấp Hội', 'National Society Details': 'Thông tin về Hội Quốc gia', 'National Society added': 'Hội Quốc gia đã được thêm', 'National Society deleted': 'Hội Quốc gia đã được xóa', 'National Society updated': 'Hội Quốc gia đã được cập nhật', 'National Society': 'Hội QG', 'Nationality of the person.': 'Quốc tịch', 'Nationality': 'Quốc tịch', 'Nautical Accident': 'Tai nạn trên biển', 'Nautical Hijacking': 'Cướp trên biển', 'Need to configure Twitter Authentication': 'Cần thiết lập cấu hình Xác thực Twitter', 'Need to select 2 Locations': 'Cần chọn 2 vị trí', 'Need to specify a location to search for.': 'Cần xác định cụ thể một địa điểm để tìm kiếm', 'Need to specify a role!': 'Yêu cầu xác định vai trò', 'Needs Maintenance': 'Cần bảo dưỡng', 'Never': 'Không bao giờ', 'New Annual Budget created': 'Ngân sách hàng năm mới đã được tạo', 'New Certificate': 'Chứng chỉ mới', 'New Checklist': 'Checklist mới', 'New Entry in Asset Log': 'Ghi chép mới trong nhật ký tài sản', 'New Entry': 'Hồ sơ mới', 'New Job Title': 'Chức vụ công việc mới', 'New Organization': 'Tổ chức mới', 'New Output': 'Kết quả đầu ra mới', 'New Post': 'Bài đăng mới', 'New Record': 'Hồ sơ mới', 'New Request': 'Yêu cầu mới', 'New Role': 'Vai trò mới', 'New Stock Adjustment': 'Điều chỉnh mới về kho hàng', 'New Support Request': 'Yêu cầu hỗ trợ mới', 'New Team': 'Đội/Nhóm mới', 'New Theme': 'Chủ đề mới', 'New Training Course': 'Khóa tập huấn mới', 'New Training Event': 'Khóa tập huấn mới', 'New User': 'Người sử dụng mới', 'New': 'Thêm mới', 'News': 'Tin tức', 'Next View': 'Hiển thị tiếp', 'Next run': 'Lần chạy tiếp theo', 'Next': 'Trang sau', 'No Activities Found': 'Không tìm thấy hoạt động nào', 'No Activity Types Found': 'Không tìm thấy loại hình hoạt động nào', 'No Addresses currently registered': 'Hiện tại chưa đăng ký Địa chỉ', 'No Affiliations defined': 'Không xác định được liên kết nào', 'No Aid Requests have been made yet': 'Chưa có yêu cầu cứu trợ nào được tạo', 'No Alternative Items currently registered': 'Hiện không có mặt hàng thay thế nào được đăng ký', 'No Assessment Answers': 'Không có câu trả lời cho đánh giá', 'No Assessment Questions': 'Không có câu hỏi đánh giá', 'No Assessment Templates': 'Không có mẫu đánh giá', 'No Assessments currently registered': 'Chưa đăng ký trị giá tính thuế', 'No Assets currently registered': 'Hiện không có tài sản nào được đăng ký', 'No Awards found': 'Không tìm thấy thônng tin về khen thưởng', 'No Base Layer': 'Không có lớp bản đồ cơ sở', 'No Beneficiaries Found': 'Không tìm thấy người hưởng lợi nào', 'No Beneficiary Types Found': 'Không tìm thấy nhóm người hưởng lợi nào', 'No Branch Organizations currently registered': 'Hiện không có tổ chức cơ sở nào được đăng ký', 'No Brands currently registered': 'Hiện không có nhãn hàng nào được đăng ký', 'No Catalog Items currently registered': 'Hiện không có mặt hàng nào trong danh mục được đăng ký', 'No Catalogs currently registered': 'Hiện không có danh mục nào được đăng ký', 'No Category<>Sub-Category<>Catalog Relation currently registered': 'Hiện tại chưa có Category<>Sub-Category<>Catalog Relation được đăng ký', 'No Clusters currently registered': 'Hiện không có nhóm nào được đăng ký', 'No Commitment Items currently registered': 'Hiện không có hàng hóa cam kết nào được đăng ký', 'No Commitments': 'Không có cam kết nào', 'No Communities Found': 'Không tìm thấy cộng đồng nào', 'No Completed Assessment Forms': 'Không có mẫu khảo sát đánh giá hoàn thiện nào', 'No Contacts Found': 'Không tìm thấy liên lạc nào', 'No Data currently defined for this Theme Layer': 'Hiện không xác định được dữ liệu nào cho lớp chủ đề này', 'No Data': 'Không có dữ liệu', 'No Disaster Assessments': 'Không có đánh giá thảm họa nào', 'No Distribution Items currently registered': 'Chưa đăng ký danh sách hàng hóa đóng góp', 'No Documents found': 'Không tìm thấy tài liệu nào', 'No Donors currently registered': 'Hiện không có nhà tài trợ nào được đăng ký', 'No Emails currently in InBox': 'Hiện không có thư điện tử nào trong hộp thư đến', 'No Entries Found': 'Không có hồ sơ nào được tìm thấy', 'No Facilities currently registered': 'Hiện không có trang thiết bị nào được đăng ký', 'No Facility Types currently registered': 'Không có bộ phận nào được đăng ký', 'No Feature Layers currently defined': 'Hiện không xác định được lớp đặc điểm nào', 'No File Chosen': 'Chưa chọn File', 'No Flood Reports currently registered': 'Chưa đăng ký báo cáo lũ lụt', 'No Frameworks found': 'Không tìm thấy khung chương trình nào', 'No Groups currently defined': 'Hiện tại không xác định được nhóm', 'No Groups currently registered': 'Hiện không có nhóm nào được đăng ký', 'No Hazards currently registered': 'Hiện không có hiểm họa nào được đăng ký', 'No Hospitals currently registered': 'Chưa có bệnh viện nào đăng ký', 'No Human Resources currently assigned to this incident': 'Hiện không có nhân sự nào được phân công cho công việc này', 'No Identities currently registered': 'Hiện không có nhận diện nào được đăng ký', 'No Image': 'Không có ảnh', 'No Images currently registered': 'Hiện không có hình ảnh nào được đăng ký', 'No Incident Reports currently registered': 'Hiện không có báo cáo sự việc nào được đăng ký', 'No Incidents currently registered': 'Chưa sự việc nào được đưa lên', 'No Inventories currently have suitable alternative items in stock': 'Hiện không có bảng kiểm kê nào có mặt hàng thay thế trong kho', 'No Inventories currently have this item in stock': 'Hiện không có bảng kiểm kê nào có mặt hàng này trong kho', 'No Item Categories currently registered': 'Hiện không có nhóm mặt hàng nào được đăng ký', 'No Item Packs currently registered': 'Hiện không có gói hàng nào được đăng ký', 'No Items currently registered': 'Hiện không có mặt hàng nào được đăng ký', 'No Items currently requested': 'Hiện tại không có hàng hóa nào được yêu cầu', 'No Kits': 'Không có thùng hành nào', 'No Layers currently configured in this Profile': 'Hiện không có lớp nào được tạo ra trong hồ sơ này', 'No Layers currently defined in this Symbology': 'Hiện không xác định được lớp nào trong biểu tượng này', 'No Layers currently defined': 'Hiện không xác định được lớp nào', 'No Location Hierarchies currently defined': 'Hiện không xác định được thứ tự địa điểm', 'No Locations Found': 'Không tìm thấy địa điểm nào', 'No Locations currently available': 'Hiện không có địa điểm', 'No Locations currently registered': 'Hiện tại chưa có vị trí nào được đăng ký', 'No Mailing List currently established': 'Hiện không có danh sách địa chỉ thư nào được thiết lập', 'No Map Configurations currently defined': 'Hiện không xác định được cài đặt cấu hình bản đồ nào', 'No Markers currently available': 'Hiện không có dấu mốc nào', 'No Match': 'Không phù hợp', 'No Matching Catalog Items': 'Không có mặt hàng nào trong danh mục phù hợp', 'No Matching Items': 'Không có mặt hàng phù hợp', 'No Matching Records': 'Không có hồ sơ phù hợp', 'No Members currently registered': 'Hiện không có hội viên nào được đăng ký', 'No Memberships currently defined': 'Chưa xác nhận đăng ký thành viên', 'No Messages currently in Outbox': 'Hiện không có thư nào trong hộp thư đi', 'No Metadata currently defined': 'Hiện tại không xác định được loại siêu dữ liệu', 'No Milestones Found': 'Không tìm thấy sự kiện quan trọng nào', 'No Office Types currently registered': 'Hiện không có loại hình văn phòng nào được đăng ký', 'No Offices currently registered': 'Hiện không có văn phòng nào được đăng ký', 'No Open Tasks for %(project)s': 'Không có công việc chưa được xác định nào cho %(project)s', 'No Orders registered': 'Không có đề nghị nào được đăng ký', 'No Organization Domains currently registered': 'Không có lĩnh vực hoạt động của tổ chức nào được đăng ký', 'No Organization Types currently registered': 'Hiện không có loại hình tổ chức nào được đăng ký', 'No Organizations currently registered': 'Hiện không có tổ chức nào được đăng ký', 'No Organizations for Project(s)': 'Không có tổ chức cho dự án', 'No Organizations found for this Framework': 'Không tìm thấy tổ chức trong chương trình khung này', 'No Packs for Item': 'Không có hàng đóng gói', 'No Partner Organizations currently registered': 'Hiện không có tổ chức đối tác nào được đăng ký', 'No People currently committed': 'Hiện không có người nào cam kết', 'No People currently registered in this shelter': 'Không có người đăng ký cư trú ở đơn vị này', 'No Persons currently registered': 'Hiện không có người nào đăng ký', 'No Persons currently reported missing': 'Hiện tại không thấy báo cáo về người mất tích', 'No Photos found': 'Không tìm thấy hình ảnh', 'No PoIs available.': 'Không có PoIs', 'No Presence Log Entries currently registered': 'Hiện chư có ghi chép nhật ký được đăng ký', 'No Professional Experience found': 'Không tìm thấy kinh nghiệm nghề nghiệp', 'No Profiles currently have Configurations for this Layer': 'Hiện không có hồ sơ nào có cài đặt cấu hình cho lớp này', 'No Projections currently defined': 'Hiện không xác định được trình diễn nào', 'No Projects currently registered': 'Hiện không có dự án nào được đăng ký', 'No Question Meta-Data': 'Không có siêu dữ liệu lớn câu hỏi', 'No Ratings for Skill Type': 'Không xếp loại cho loại kỹ năng', 'No Received Shipments': 'Không có chuyến hàng nào được nhận', 'No Records currently available': 'Hiện tại không có hồ sơ nào sẵn có', 'No Red Cross & Red Crescent National Societies currently registered': 'Hiện không có Hội Chữ thập đỏ và Trăng lưỡi liềm đỏ quốc gia nào được đăng ký', 'No Request Items currently registered': 'Hiện không có mặt hàng đề nghị nào được đăng ký', 'No Requests': 'Không có đề nghị', 'No Roles defined': 'Không có vai trò nào được xác định ', 'No Rooms currently registered': 'Hiện không có phòng nào được đăng ký', 'No Search saved': 'Không có tìm kiếm nào được lưu', 'No Sectors currently registered': 'Hiện không có lĩnh vực nào được đăng ký', 'No Sent Shipments': 'Không có chuyến hàng nào được gửi', 'No Settings currently defined': 'Hiện không có cài đặt nào được xác định', 'No Shelters currently registered': 'Hiện tại chưa đăng ký nơi cư trú', 'No Shipment Items': 'Không có hàng hóa vận chuyển nào', 'No Shipment Transit Logs currently registered': 'Không có số liệu lưu về vận chuyển được ghi nhận', 'No Skill Types currently set': 'Chưa cài đặt loại kỹ năng', 'No Skills currently requested': 'Hiện không có kỹ năng nào được đề nghị', 'No Staff currently registered': 'Hiện không có cán bộ nào được đăng ký', 'No Statuses currently registered': 'Hiện không có tình trạng nào được đăng ký', 'No Stock currently registered in this Warehouse': 'Hiện không có hàng hóa nào được đăng ký trong nhà kho này', 'No Stock currently registered': 'Hiện không có hàng hóa nào được đăng ký', 'No Storage Bin Type currently registered': 'Chưa đăng ký Loại Bin lưu trữ', 'No Suppliers currently registered': 'Hiện không có nhà cung cấp nào được đăng ký', 'No Support Requests currently registered': 'Hiện tại không có yêu cầu hỗ trợ nào được đăng ký', 'No Survey Questions currently registered': 'Hiện tại không có câu hỏi khảo sát nào được đăng ký', 'No Symbologies currently defined for this Layer': 'Hiện không xác định được biểu tượng nào cho lớp này', 'No Symbologies currently defined': 'Hiện không xác định được biểu tượng nào', 'No Tasks Assigned': 'Không có công việc nào được giao', 'No Teams currently registered': 'Hiện không có Đội/Nhóm nào được đăng ký', 'No Template Sections': 'Không có phần về biểu mẫu', 'No Themes currently registered': 'Hiện không có chủ đề nào được đăng ký', 'No Tickets currently registered': 'Hiện tại chưa đăng ký Ticket ', 'No Time Logged': 'Không có thời gian nào được ghi lại', 'No Twilio Settings currently defined': 'Hiện không có cài đặt Twilio nào được xác định', 'No Units currently registered': 'Chưa đăng ký tên đơn vị', 'No Users currently registered': 'Hiện không có người sử dụng nào được đăng ký', 'No Vehicles currently assigned to this incident': 'Hiện không có phương tiện vận chuyển nào được điều động cho sự việc này', 'No Volunteer Cluster Positions': 'Không có vị trí của nhóm tình nguyện viên', 'No Volunteer Cluster Types': 'Không có loại hình nhóm tình nguyện viên', 'No Volunteer Clusters': 'Không có nhóm tình nguyện viên', 'No Volunteers currently registered': 'Hiện không có tình nguyện viên nào được đăng ký', 'No Warehouses currently registered': 'Hiện không có nhà kho nào được đăng ký', 'No access at all': 'Không truy cập', 'No access to this record!': 'Không tiếp cận được bản lưu này!', 'No annual budgets found': 'Không tìm thấy bản ngân sách năm', 'No contact information available': 'Không có thông tin liên hệ', 'No contact method found': 'Không tìm thấy cách thức liên hệ', 'No contacts currently registered': 'Chưa đăng ký thông tin liên lạc', 'No data available in table': 'Không có dữ liệu trong bảng', 'No data available': 'Không có dữ liệu sẵn có', 'No data in this table - cannot create PDF!': 'Không có dữ liệu trong bảng - không thể tạo file PDF', 'No databases in this application': 'Không có cơ sở dữ liệu trong ứng dụng này', 'No demographic data currently defined': 'Hiện không xác định được dữ liệu nhân khẩu', 'No demographic sources currently defined': 'Hiện không xác định được nguồn nhân khẩu', 'No demographics currently defined': 'Hiện không xác định được số liệu thống kê dân số', 'No education details currently registered': 'Hiện không có thông tin về học vấn được đăng ký', 'No entries currently available': 'Hiện chưa có hồ sơ nào', 'No entries found': 'Không có hồ sơ nào được tìm thấy', 'No entry available': 'Chưa có hồ sơ nào', 'No file chosen': 'Chưa chọn file', 'No forms to the corresponding resource have been downloaded yet.': 'Không tải được mẫu nào cho nguồn tài nguyên tương ứng', 'No further users can be assigned.': 'Không thể phân công thêm người sử dụng', 'No items currently in stock': 'Hiện không có mặt hàng nào trong kho', 'No items have been selected for shipping.': 'Không có mặt hàng nào được lựa chọn để vận chuyển', 'No jobs configured yet': 'Chưa thiết lập công việc', 'No jobs configured': 'Không thiết lập công việc', 'No linked records': 'Không có bản thu liên quan', 'No location information defined!': 'Không xác định được thông tin về địa điểm!', 'No match': 'Không phù hợp', 'No matching element found in the data source': 'Không tìm được yếu tố phù hợp từ nguồn dữ liệu', 'No matching records found': 'Không tìm thấy hồ sơ phù hợp', 'No matching result': 'Không có kết quả phù hợp', 'No membership types currently registered': 'Hiện không có loại hình hội viên nào được đăng ký', 'No messages in the system': 'Không có thư nào trong hệ thống', 'No offices registered for organisation': 'Không có văn phòng nào đăng ký tổ chức', 'No options available': 'Không có lựa chọn sẵn có', 'No outputs found': 'Không tìm thấy đầu ra', 'No pending registrations found': 'Không tìm thấy đăng ký đang chờ', 'No pending registrations matching the query': 'Không tìm thấy đăng ký khớp với yêu cầu', 'No problem group defined yet': 'Chưa xác định được nhóm gặp nạn', 'No records in this resource': 'Không có hồ sơ nào trong tài nguyên mới', 'No records in this resource. Add one more records manually and then retry.': 'Không có hồ sơ nào trong tài nguyên này. Thêm một hoặc nhiều hồ sơ một cách thủ công và sau đó thử lại ', 'No records to delete': 'Không có bản thu để xóa', 'No records to review': 'Không có hồ sơ nào để rà soát', 'No report available.': 'Không có báo cáo', 'No reports available.': 'Không có báo cáo nào', 'No repositories configured': 'Không có chỗ chứa hàng nào được tạo ra', 'No requests found': 'Không tìm thấy yêu cầu', 'No resources configured yet': 'Chưa có nguồn lực nào được tạo ra', 'No role to delete': 'Không có chức năng nào để xóa', 'No roles currently assigned to this user.': 'Hiện tại không có chức năng nào được cấp cho người sử dụng này', 'No service profile available': 'Không có hồ sơ đăng ký dịch vụ nào', 'No staff or volunteers currently registered': 'Hiện không có cán bộ hay tình nguyện viên nào được đăng ký', 'No stock adjustments have been done': 'Không có bất kỳ điều chỉnh nào về hàng hóa', 'No synchronization': 'Chưa đồng bộ hóa', 'No tasks currently registered': 'Hiện không có công việc nào được đăng ký', 'No template found!': 'Không tìm thấy mẫu', 'No themes found': 'Không tìm thấy chủ đề nào', 'No translations exist in spreadsheet': 'Không có phần dịch trong bảng tính', 'No users with this role at the moment.': 'Hiện tại không có người sử dụng nào có chức năng này', 'No valid data in the file': 'Không có dữ liệu có giá trị trong tệp tin', 'No volunteer information registered': 'Chưa đăng ký thông tin tình nguyện viên', 'No vulnerability aggregated indicators currently defined': 'Hiện không xác định được chỉ số tổng hợp về tình trạng dễ bị tổn thương', 'No vulnerability data currently defined': 'Hiện không xác định được dữ liệu về tình trạng dễ bị tổn thương', 'No vulnerability indicator Sources currently defined': 'Hiện không xác định được nguồn chỉ số về tình trạng dễ bị tổn thương', 'No vulnerability indicators currently defined': 'Hiện không xác định được chỉ số về tình trạng dễ bị tổn thương', 'No': 'Không', 'Non-Communicable Diseases': 'Bệnh dịch không lây nhiễm', 'None (no such record)': 'Không cái nào (không có bản lưu như thế)', 'None': 'Không có', 'Nonexistent or invalid resource': 'Không tồn tại hoặc nguồn lực không hợp lệ', 'Noodles': 'Mì', 'Normal Job': 'Công việc hiện nay', 'Normal': 'Bình thường', 'Not Authorized': 'Không được phép', 'Not Set': 'Chưa thiết đặt', 'Not implemented': 'Không được thực hiện', 'Not installed or incorrectly configured.': 'Không được cài đặt hoặc cài đặt cấu hình không chính xác', 'Not yet a Member of any Group': 'Hiện không có nhóm hội viên nào được đăng ký', 'Not you?': 'Không phải bạn chứ?', 'Note that when using geowebcache, this can be set in the GWC config.': 'Lưu ý khi sử dụng geowebcache, phần này có thể được cài đặt trong cấu hình GWC.', 'Note: Make sure that all the text cells are quoted in the csv file before uploading': 'Lưu ý: Đảm bảo tất cả các ô chữ được trích dẫn trong tệp tin csv trước khi tải lên', 'Notice to Airmen': 'Lưu ý cho phi công', 'Notification frequency': 'Tần suất thông báo', 'Notification method': 'Phương pháp thông báo', 'Notify': 'Thông báo', 'Number of Completed Assessment Forms': 'Số phiếu đánh giá đã được hoàn chỉnh', 'Number of People Affected': 'Số người bị ảnh hưởng', 'Number of People Dead': 'Số người chết', 'Number of People Injured': 'Số người bị thương', 'Number of People Required': 'Số người cần', 'Number of Rows': 'Số hàng', 'Number of alternative places for studying': 'Số địa điểm có thể dùng làm trường học tạm thời', 'Number of newly admitted patients during the past 24 hours.': 'Số lượng bệnh nhân tiếp nhận trong 24h qua', 'Number of private schools': 'Số lượng trường tư', 'Number of religious schools': 'Số lượng trường công giáo', 'Number of vacant/available beds in this hospital. Automatically updated from daily reports.': 'Số các giường bệnh trống trong bệnh viện. Tự động cập nhật từ các báo cáo hàng ngày.', 'Number or Label on the identification tag this person is wearing (if any).': 'Số hoặc nhãn trên thẻ nhận diện mà người này đang đeo (nếu có)', 'Number': 'Số', 'Number/Percentage of affected population that is Female & Aged 0-5': 'Đối tượng nữ trong độ tuổi 0-5 tuổi chịu ảnh hưởng của thiên tai ', 'Number/Percentage of affected population that is Female & Aged 6-12': 'Đối tượng nữ trong độ tuổi 6-12 chịu ảnh hưởng của thiên tai', 'Number/Percentage of affected population that is Male & Aged 0-5': 'Đối tượng nam trong độ tuổi 0-5 chịu ảnh hưởng từ thiên tai', 'Number/Percentage of affected population that is Male & Aged 18-25': 'Đối tượng nam giới trong độ tuổi 18-25 chịu ảnh hưởng của thiên tai', 'Number/Percentage of affected population that is Male & Aged 26-60': 'Đối tượng là Nam giới và trong độ tuổi từ 26-60 chịu ảnh hưởng lớn từ thiên tai', 'Numbers Only': 'Chỉ dùng số', 'Numeric': 'Bằng số', 'Nutrition': 'Dinh dưỡng', 'OCR Form Review': 'Mẫu OCR tổng hợp', 'OCR module is disabled. Ask the Server Administrator to enable it.': 'Module OCR không được phép. Yêu cầu Quản trị mạng cho phép', 'OCR review data has been stored into the database successfully.': 'Dự liệu OCR tổng hợp đã được lưu thành công vào kho dữ liệu', 'OK': 'Đồng ý', 'OSM file generation failed!': 'Chiết xuất tệp tin OSM đã bị lỗi!', 'OSM file generation failed: %s': 'Chiết xuất tệp tin OSM đã bị lỗi: %s', 'OTHER DATA': 'DỮ LIỆU KHÁC', 'OTHER REPORTS': 'BÁO CÁO KHÁC', 'OVERALL RESILIENCE': 'SỰ BỀN VỮNG TỔNG THỂ', 'Object': 'Đối tượng', 'Objectives': 'Mục tiêu', 'Observer': 'Người quan sát', 'Obsolete': 'Đã thôi hoạt động', 'Obstetrics/Gynecology': 'Sản khoa/Phụ khoa', 'Office Address': 'Địa chỉ văn phòng', 'Office Details': 'Thông tin về văn phòng', 'Office Phone': 'Điện thoại văn phòng', 'Office Type Details': 'Thông tin về loại hình văn phòng', 'Office Type added': 'Loại hình văn phòng được thêm vào', 'Office Type deleted': 'Loại hình văn phòng đã xóa', 'Office Type updated': 'Loại hình văn phòng được cập nhật', 'Office Type': 'Loại hình văn phòng', 'Office Types': 'Loại văn phòng', 'Office added': 'Văn phòng được thêm vào', 'Office deleted': 'Văn phòng đã xóa', 'Office updated': 'Văn phòng được cập nhật', 'Office': 'Văn phòng', 'Office/Center': 'Văn phòng/Trung tâm', 'Office/Warehouse/Facility': 'Văn phòng/Kho hàng/Bộ phận', 'Offices': 'Văn phòng', 'Old': 'Người già', 'On Hold': 'Tạm dừng', 'On Order': 'Theo đề nghị', 'On by default?': 'Theo mặc định?', 'One item is attached to this shipment': 'Một mặt hàng được bổ sung thêm vào kiện hàng này', 'One-time costs': 'Chí phí một lần', 'Only showing accessible records!': 'Chỉ hiển thị hồ sơ có thể truy cập', 'Only use this button to accept back into stock some items that were returned from a delivery to beneficiaries who do not record the shipment details directly into the system': 'Chỉ sử dụng nút này để nhận lại vào kho một số mặt hàng được trả lại do người nhận không trực tiếp lưu thông tin về kiện hàng này trên hệ thống', 'Only use this button to confirm that the shipment has been received by a destination which will not record the shipment directly into the system': 'Chỉ sử dụng nút này để xác nhận kiện hàng đã được nhận tại một địa điểm không trực tiếp lưu thông tin về kiện hàng trên hệ thống', 'Oops! Something went wrong...': 'Xin lỗi! Có lỗi gì đó…', 'Oops! something went wrong on our side.': 'Xin lỗi! Có trục trặc gì đó từ phía chúng tôi.', 'Opacity': 'Độ mờ', 'Open Incidents': 'Mở sự kiện', 'Open Map': 'Mở bản đồ', 'Open Tasks for %(project)s': 'Các công việc chưa xác định cho %(project)s', 'Open Tasks for Project': 'Mở nhiệm vụ cho một dự án', 'Open recent': 'Mở gần đây', 'Open': 'Mở', 'OpenStreetMap Layer': 'Mở lớp bản đồ đường đi', 'OpenStreetMap OAuth Consumer Key': 'Mã khóa người sử dụng OpenStreetMap OAuth', 'OpenStreetMap OAuth Consumer Secret': 'Bí mật người sử dụng OpenStreetMap OAuth', 'OpenWeatherMap Layer': 'Lớp OpenWeatherMap (bản đồ thời tiết mở)', 'Operating Rooms': 'Phòng điều hành', 'Operation not permitted': 'Hoạt động không được phép', 'Option Other': 'Lựa chọn khác', 'Option': 'Lựa chọn', 'Optional Subject to put into Email - can be used as a Security Password by the service provider': 'Chủ đề tùy chọn để đưa vào Thư điện tử - có thể được sử dụng như một Mật khẩu bảo mật do nhà cung cấp dịch vụ cung cấp', 'Optional password for HTTP Basic Authentication.': 'Mật khẩu tùy chọn cho Sự xác thực cơ bản HTTP.', 'Optional selection of a MapServer map.': 'Tùy chọn một bản đồ trong Máy chủ bản đồ.', 'Optional selection of a background color.': 'Tùy chọn màu sắc cho nền.', 'Optional selection of an alternate style.': 'Tùy chọn một kiểu dáng thay thế.', 'Optional username for HTTP Basic Authentication.': 'Tên truy nhập tùy chọn cho Sự xác thực cơ bản HTTP.', 'Optional. If you wish to style the features based on values of an attribute, select the attribute to use here.': 'Tùy chọn. Nếu bạn muốn tự tạo ra chức năng dựa trên các giá trị của một thuộc tính, hãy lựa chọn thuộc tính để sử dụng tại đây.', 'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).': 'Tùy chọn. Trong máy chủ về địa lý, đây là Vùng tên Vùng làm việc URI (không phải là một tên gọi!). Trong lớp WFS theo khả năng là đường dẫn, đây là phần Tên loại chức năng trước dấu hai chấm (:).', 'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.': 'Tùy chọn. Tên của một bộ phận có chứa nội dung là một URL của một tệp tin hình ảnh được đưa vào các cửa sổ tự động hiển thị.', 'Optional. The name of an element whose contents should be put into Popups.': 'Tùy chọn. Tên của một bộ phận có chứa nội dung được đưa vào các cửa sổ tự động hiển thị.', 'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.': 'Tùy chọn. Tên của sơ đồ. Trong Geoserver tên này có dạng http://tên máy chủ/geoserver/wfs/Mô tả Loại Đặc điểm ?phiên bản=1.1.0&;nhập tên=vùng làm việc_tên:lớp_tên.', 'Options': 'Các lựa chọn', 'Or add a new language code': 'Hoặc chọn một ngôn ngữ khác', 'Order Created': 'Đơn hàng đã tạo', 'Order Details': 'Thông tin đơn hàng', 'Order Due %(date)s': 'Thời hạn của đơn hàng %(date)s', 'Order Item': 'Các mặt hàng trong đơn hàng', 'Order canceled': 'Đơn hàng đã bị hủy', 'Order updated': 'Đơn hàng được cập nhật', 'Order': 'Đơn hàng', 'Orders': 'Các đơn hàng', 'Organization Details': 'Thông tin về tổ chức', 'Organization Domain Details': 'Thông tin về lĩnh vực hoạt động của tổ chức', 'Organization Domain added': 'Lĩnh vực hoạt động của tổ chức đã được thêm', 'Organization Domain deleted': 'Lĩnh vực hoạt động của tổ chức đã được xóa', 'Organization Domain updated': 'Lĩnh vực hoạt động của tổ chức đã được cập nhật', 'Organization Domains': 'Loại hình hoạt động của tổ chức', 'Organization Registry': 'Đăng ký tổ chức', 'Organization Type Details': 'Thông tin về loại hình tổ chức', 'Organization Type added': 'Loại hình tổ chức được thêm vào', 'Organization Type deleted': 'Loại hình tổ chức đã xóa', 'Organization Type updated': 'Loại hình tổ chức được cập nhật', 'Organization Type': 'Loại hình tổ chức', 'Organization Types': 'Loại hình tổ chức', 'Organization Units': 'Đơn vị của tổ chức', 'Organization added to Framework': 'Tổ chức được thêm vào Chương trình khung', 'Organization added to Project': 'Tổ chức được thêm vào Dự án', 'Organization added': 'Tổ chức được thêm vào', 'Organization deleted': 'Tổ chức đã xóa', 'Organization removed from Framework': 'Tổ chức đã rút ra khỏi Chương trình khung', 'Organization removed from Project': 'Tổ chức đã rút ra khỏi Dự án', 'Organization updated': 'Tổ chức được cập nhật', 'Organization': 'Tổ chức', 'Organization/Supplier': 'Tổ chức/ Nhà cung cấp', 'Organizational Development': 'Phát triển tổ chức', 'Organizations / Teams / Facilities': 'Tổ chức/ Đội/ Cơ sở hạ tầng', 'Organizations': 'Tổ chức', 'Organized By': 'Đơn vị tổ chức', 'Origin': 'Nguồn gốc', 'Original Quantity': 'Số lượng ban đầu', 'Original Value per Pack': 'Giá trị ban đầu cho mỗi gói hàng', 'Other Address': 'Địa chỉ khác', 'Other Details': 'Thông tin khác', 'Other Evidence': 'Bằng chứng khác', 'Other Faucet/Piped Water': 'Các đường xả lũ khác', 'Other Inventories': 'Kho hàng khác', 'Other Isolation': 'Những vùng bị cô lập khác', 'Other Users': 'Người sử dụng khác', 'Other activities of boys 13-17yrs': 'Các hoạt động khác của nam thanh niên từ 13-17 tuổi', 'Other activities of boys <12yrs before disaster': 'Các hoạt động khác của bé trai dưới 12 tuổi trước khi xảy ra thiên tai', 'Other alternative places for study': 'Những nơi có thể dùng làm trường học tạm thời', 'Other assistance needed': 'Các hỗ trợ cần thiết', 'Other assistance, Rank': 'Những sự hỗ trợ khác,thứ hạng', 'Other data': 'Dữ liệu khác', 'Other factors affecting school attendance': 'Những yếu tố khác ảnh hưởng đến việc đến trường', 'Other reports': 'Báo cáo khác', 'Other settings can only be set by editing a file on the server': 'Cài đặt khác chỉ có thể được cài đặt bằng cách sửa đổi một tệp tin trên máy chủ', 'Other side dishes in stock': 'Món trộn khác trong kho', 'Other': 'Khác', 'Others': 'Khác', 'Outbound Mail settings are configured in models/000_config.py.': 'Cài đặt thư gửi ra nước ngoài được cấu hình thành các kiểu/000_config.py.', 'Outbox': 'Hộp thư đi', 'Outcomes, Impact, Challenges': 'Kết quả, Tác động, Thách thức', 'Outgoing SMS handler': 'Bộ quản lý tin nhắn SMS gửi đi', 'Output added': 'Đầu ra được thêm vào', 'Output removed': 'Đầu ra đã xóa', 'Output updated': 'Đầu ra được cập nhật', 'Output': 'Đầu ra', 'Outputs': 'Các đầu ra', 'Over 60': 'Trên 60', 'Overall Resilience': 'Sự bền vững tổng thể', 'Overland Flow Flood': 'Dòng nước lũ lụt trên đất đất liền', 'Overlays': 'Lớp dữ liệu phủ', 'Owned By (Organization/Branch)': 'Sở hữu bởi (Tổ chức/ Chi nhánh)', 'Owned Records': 'Hồ sơ được sở hữu', 'Owned Resources': 'Nguồn lực thuộc sở hữu', 'Owner Driven Housing Reconstruction': 'Xây dựng lại nhà cửa theo nhu cầu chủ nhà', 'Owning Organization': 'Tổ chức nắm quyền sở hữu', 'PASSA': 'Phương pháp truyền thông nhà ở an toàn có sự tham', 'PIL (Python Image Library) not installed': 'PIL (thư viện ảnh Python) chưa cài đặt', 'PIL (Python Image Library) not installed, images cannot be embedded in the PDF report': 'PIL (thư viện ảnh Python) chưa được cài đặt, hình ảnh không thể gắn vào báo cáo dạng PDF', 'PIN number from Twitter (leave empty to detach account)': 'Số PIN từ Twitter (để trống để tách tài khoản)', 'PMER Development': 'Xây dựng năng lực về PMER', 'POOR': 'NGHÈO', 'POPULATION DENSITY': 'MẬT ĐỘ DÂN SỐ', 'POPULATION:': 'DÂN SỐ:', 'Pack': 'Gói', 'Packs': 'Các gói', 'Page': 'Trang', 'Paid': 'Đã thanh toán', 'Pan Map: keep the left mouse button pressed and drag the map': 'Dính bản đồ: giữ chuột trái và di chuột để di chuyển bản đồ', 'Parameters': 'Tham số', 'Parent Item': 'Mặt hàng cùng gốc', 'Parent Project': 'Dự án cùng gốc', 'Parent needs to be of the correct level': 'Phần tử cấp trên cần ở mức chính xác', 'Parent needs to be set for locations of level': 'Phần tử cấp trên cần được cài đặt cho các điểm mức độ', 'Parent needs to be set': 'Phần tử cấp trên cần được cài đặt', 'Parent': 'Phần tử cấp trên', 'Parser Setting deleted': 'Cài đặt của bộ phân tích đã xóa', 'Parser Settings': 'Các cài đặt của bộ phân tích', 'Parsing Settings': 'Cài đặt cú pháp', 'Parsing Status': 'Tình trạng phân tích', 'Parsing Workflow': 'Quá trình phân tích', 'Part of the URL to call to access the Features': 'Phần URL để gọi để truy cập tới chức năng', 'Partial': 'Một phần', 'Participant Details': 'Thông tin về người tham dự', 'Participant added': 'Người tham dự được thêm vào', 'Participant deleted': 'Người tham dự đã xóa', 'Participant updated': 'Người tham dự được cập nhật', 'Participant': 'Người tham dự', 'Participants': 'Những người tham dự', 'Participating Organizations': 'Các tổ chức tham gia', 'Partner National Society': 'Hội Quốc gia thành viên', 'Partner Organization Details': 'Thông tin về tổ chức đối tác', 'Partner Organization added': 'Tổ chức đối tác được thêm vào', 'Partner Organization deleted': 'Tổ chức đối tác đã xóa', 'Partner Organization updated': 'Tổ chức đối tác đã được cập nhật', 'Partner Organizations': 'Các tổ chức đối tác', 'Partner': 'Đối tác', 'Partnerships': 'Hợp tác', 'Pass': 'Qua', 'Passport': 'Hộ chiếu', 'Password to use for authentication at the remote site.': 'Mật khẩu để sử dụng để xác định tại một địa điểm ở xa', 'Password': 'Mật khẩu', 'Pathology': 'Bệnh lý học', 'Patients': 'Bệnh nhân', 'Pediatric ICU': 'Chuyên khoa nhi', 'Pediatric Psychiatric': 'Khoa Tâm thần dành cho bệnh nhi', 'Pediatrics': 'Khoa Nhi', 'Peer Registration Request': 'yêu cầu đăng ký', 'Peer registration request added': 'Đã thêm yêu cầu đăng ký', 'Peer registration request updated': 'Cập nhật yêu cẩu đăng ký', 'Pending Requests': 'yêu cầu đang chờ', 'Pending': 'Đang xử lý', 'People Trapped': 'Người bị bắt', 'People': 'Người', 'Percentage': 'Phần trăm', 'Performance Rating': 'Đánh giá quá trình thực hiện', 'Permanent Home Address': 'Địa chỉ thường trú', 'Person (Count)': 'Họ tên (Số lượng)', 'Person Details': 'Thông tin cá nhân', 'Person Registry': 'Cơ quan đăng ký nhân sự', 'Person added to Commitment': 'Người được thêm vào Cam kết', 'Person added to Group': 'Người được thêm vào Nhóm', 'Person added to Team': 'Người được thêm vào Đội', 'Person added': 'Người được thêm vào', 'Person deleted': 'Người đã xóa', 'Person details updated': 'Thông tin cá nhân được cập nhật', 'Person must be specified!': 'Người phải được chỉ định!', 'Person or OU': 'Người hay OU', 'Person removed from Commitment': 'Người đã xóa khỏi Cam kết', 'Person removed from Group': 'Người đã xóa khỏi Nhóm', 'Person removed from Team': 'Người đã xóa khỏi Đội', 'Person reporting': 'Báo cáo về người', 'Person who has actually seen the person/group.': 'Người đã thực sự nhìn thấy người/ nhóm', 'Person who observed the presence (if different from reporter).': 'Người quan sát tình hình (nếu khác với phóng viên)', 'Person': 'Họ tên', 'Personal Effects Details': 'Chi tiết ảnh hưởng cá nhân', 'Personal Profile': 'Hồ sơ cá nhân', 'Personal': 'Cá nhân', 'Personnel': 'Nhân viên', 'Persons with disability (mental)': 'Người tàn tật (về tinh thần)', 'Persons with disability (physical)': 'Người tàn tật (về thể chất)', 'Persons': 'Họ tên', 'Philippine Pesos': 'Đồng Pê sô Phi-lip-pin', 'Phone #': 'Số điện thoại', 'Phone 1': 'Điện thoại 1', 'Phone 2': 'Điện thoại 2', 'Phone number is required': 'Yêu cầu nhập số điện thoại', 'Phone': 'Điện thoại', 'Photo Details': 'Thông tin về ảnh', 'Photo added': 'Ảnh được thêm vào', 'Photo deleted': 'Ảnh đã xóa', 'Photo updated': 'Ảnh được cập nhật', 'Photograph': 'Ảnh', 'Photos': 'Những bức ảnh', 'Place on Map': 'Vị trí trên bản đồ', 'Place': 'Nơi', 'Planned %(date)s': 'Đã lập kế hoạch %(date)s', 'Planned Procurement Item': 'Mặt hàng mua sắm theo kế hoạch', 'Planned Procurement': 'Mua sắm theo kế hoạch', 'Planned Procurements': 'Những trường hợp mua sắm đã lập kế hoạch', 'Planned': 'Đã lập kế hoạch', 'Please do not remove this sheet': 'Xin vui lòng không xóa bảng này', 'Please enter a First Name': 'Vui lòng nhập họ', 'Please enter a Warehouse/Facility/Office OR an Organization': 'Xin vui lòng nhập một Nhà kho/ Bộ phận/ Văn phòng HOẶC một Tổ chức', 'Please enter a Warehouse/Facility/Office': 'Xin vui lòng nhập một Nhà kho/ Bộ phận/ Văn phòng', 'Please enter a first name': 'Xin vui lòng nhập một tên', 'Please enter a last name': 'Xin vui lòng nhập một họ', 'Please enter a number only': 'Vui lòng chỉ nhập một số', 'Please enter a valid email address': 'Vui lòng nhập địa chỉ email hợp lệ', 'Please enter a valid email address.': 'Vui lòng nhập địa chỉ email hợp lệ', 'Please enter an Organization/Supplier': 'Xin vui lòng nhập một Tổ chức/ Nhà cung cấp', 'Please enter the first few letters of the Person/Group for the autocomplete.': 'Xin vui lòng nhập những chữ cái đầu tiên của Tên/ Nhóm để tự động dò tìm.', 'Please enter the recipient(s)': 'Xin vui lòng nhập người nhận', 'Please fill this!': 'Xin vui lòng nhập thông tin vào đây!', 'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened.': 'Vui lòng cung cấp đường dẫn trang bạn muốn tham chiếu tới, miêu tả bạn thực sự muốn gì và cái gì đã thực sự xảy ra.', 'Please record Beneficiary according to the reporting needs of your project': 'Xin vui lòng lưu thông tin Người hưởng lợi theo những nhu cầu về báo cáo của dự án của bạn', 'Please review demographic data for': 'Xin vui lòng rà soát lại số liệu dân số để', 'Please review indicator ratings for': 'Xin vui lòng rà soát lại những đánh giá về chỉ số để', 'Please select another level': 'Xin vui lòng lựa chọn một cấp độ khác', 'Please select': 'Xin vui lòng lựa chọn', 'Please use this field to record any additional information, including a history of the record if it is updated.': 'Vui lòng sử dụng ô này để điền thêm các thông tin bổ sung, bao gồm cả lịch sử của hồ sơ nếu được cập nhật.', 'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.': 'Xin vui lòng sử dụng ô này để điền thông tin bổ sung, như là tên truy nhập phiên bản Ushahidi. Bao gồm một lịch sử của hồ sơ nếu được cập nhật.', 'PoIs successfully imported.': 'PoIs đã được nhập thành công.', 'Poisoning': 'Sự nhiễm độc', 'Poisonous Gas': 'Khí độc', 'Pollution and other environmental': 'Ô nhiễm và các vấn đề môi trường khác', 'Polygon': 'Đa giác', 'Poor': 'Nghèo', 'Population Report': 'Báo cáo dân số', 'Population': 'Dân số', 'Popup Fields': 'Các trường cửa sổ tự động hiển thị', 'Popup Label': 'Nhãn cửa sổ tự động hiển thị', 'Porridge': 'Cháo yến mạch', 'Port Closure': 'Cổng đóng', 'Port': 'Cổng', 'Portable App': 'Ứng dụng di động', 'Portal at': 'Cổng thông tin', 'Position': 'Vị trí', 'Positions': 'Những vị trí', 'Post Graduate': 'Trên đại học', 'Postcode': 'Mã bưu điện', 'Posts': 'Thư tín', 'Poultry restocking, Rank': 'Thu mua gia cầm, thứ hạng', 'Power Failure': 'Lỗi nguồn điện', 'Powered by ': 'Cung cấp bởi', 'Powered by Sahana Eden': 'Cung cấp bởi Sahana Eden', 'Powered by': 'Cung cấp bởi', 'Preferred Name': 'Tên thường gọi', 'Presence Condition': 'Điều kiện xuất hiện', 'Presence Log': 'Lịch trình xuất hiện', 'Presence': 'Sự hiện diện', 'Previous View': 'Hiển thị trước', 'Previous': 'Trang trước', 'Print / Share': 'In ra / Chia sẻ', 'Print Extent': 'Kích thước in', 'Print Map': 'In bản đồ', 'Printed from Sahana Eden': 'Được in từ Sahana Eden', 'Printing disabled since server not accessible': 'Chức năng in không thực hiện được do không thể kết nối với máy chủ', 'Priority from 1 to 9. 1 is most preferred.': 'Thứ tự ưu tiên từ 1 đến 9. 1 được ưu tiên nhất.', 'Priority': 'Ưu tiên', 'Privacy': 'Riêng tư', 'Private-Public Partnerships': 'Hợp tác Tư nhân-Nhà nước', 'Problem Administration': 'Quản lý vấn đề', 'Problem connecting to twitter.com - please refresh': 'Vấn đề khi kết nối với twitter.com - vui lòng làm lại', 'Problem updated': 'Đã cập nhật vấn đề', 'Problem': 'Vấn đề', 'Problems': 'Vấn đề', 'Procedure': 'Thủ tục', 'Process Received Shipment': 'Thủ tục nhận lô hàng', 'Process Shipment to Send': 'Thủ tục gửi lô hàng', 'Processing': 'Đang xử lý', 'Procured': 'Được mua', 'Procurement Plans': 'Kế hoạch mua sắm', 'Profession': 'Nghề nghiệp', 'Professional Experience Details': 'Thông tin về kinh nghiệm nghề nghiệp', 'Professional Experience added': 'Kinh nghiệm nghề nghiệp đã được thêm vào', 'Professional Experience deleted': 'Kinh nghiệm nghề nghiệp đã xóa', 'Professional Experience updated': 'Kinh nghiệp nghề nghiệp được cập nhật', 'Professional Experience': 'Kinh nghiệm nghề nghiệp', 'Profile Configuration removed': 'Cấu hình hồ sơ đã xóa', 'Profile Configuration updated': 'Cấu hình hồ sơ được cập nhật', 'Profile Configuration': 'Cấu hình hồ sơ', 'Profile Configurations': 'Các cấu hình hồ sơ', 'Profile Configured': 'Hồ sơ đã được cài đặt cấu hình', 'Profile Details': 'Thông tin về hồ sơ', 'Profile Picture': 'Ảnh hồ sơ', 'Profile Picture?': 'Ảnh đại diện?', 'Profile': 'Hồ sơ', 'Profiles': 'Các hồ sơ', 'Program (Count)': 'Chương trình (Số lượng)', 'Program Details': 'Thông tin về chương trình', 'Program Hours (Month)': 'Thời gian tham gia chương trình (Tháng)', 'Program Hours (Year)': 'Thời gian tham gia chương trình (Năm)', 'Program Hours': 'Thời gian tham gia chương trình', 'Program added': 'Chương trình đã được thêm vào', 'Program deleted': 'Chương trình đã xóa', 'Program updated': 'Chương trình được cập nhật', 'Program': 'Chương trình tham gia', 'Programme Planning and Management': 'Lập kế hoạch và Quản lý Chương trình', 'Programs': 'Chương trình', 'Project Activities': 'Các hoạt động của dự án', 'Project Activity': 'Hoạt động của dự án', 'Project Beneficiary Type': 'Nhóm người hưởng lợi của dự án', 'Project Beneficiary': 'Người hưởng lợi của dự án', 'Project Calendar': 'Lịch dự án', 'Project Details': 'Thông tin về dự án', 'Project Name': 'Tên dự án', 'Project Organization Details': 'Thông tin về tổ chức của dự án', 'Project Organization updated': 'Tổ chức dự án được cập nhật', 'Project Organizations': 'Các tổ chức dự án', 'Project Time Report': 'Báo cáo thời gian dự án', 'Project Title': 'Tên dự án', 'Project added': 'Dự án được thêm vào', 'Project deleted': 'Dự án đã xóa', 'Project not Found': 'Không tìm thấy dự án', 'Project updated': 'Dự án được cập nhật', 'Project': 'Dự án', 'Projection Details': 'Thông tin dự đoán', 'Projection Type': 'Loại dự báo', 'Projection added': 'Dự đoán được thêm vào', 'Projection deleted': 'Dự đoán đã xóa', 'Projection updated': 'Dự đoán được cập nhật', 'Projection': 'Dự đoán', 'Projections': 'Nhiều dự đoán', 'Projects Map': 'Bản đồ dự án', 'Projects': 'Dự án', 'Proposed': 'Được đề xuất', 'Protecting Livelihoods': 'Bảo vệ nguồn sinh kế', 'Protocol': 'Giao thức', 'Provide Metadata for your media files': 'Cung cấp lý lịch dữ liệu cho các tệp tin đa phương tiện', 'Provide a password': 'Cung cấp mật khẩu', 'Province': 'Tỉnh/thành', 'Proxy Server URL': 'Máy chủ ủy nhiệm URL', 'Psychiatrics/Pediatric': 'Khoa thần kinh/Khoa nhi', 'Psychosocial Support': 'Hỗ trợ tâm lý xã hội', 'Public Event': 'Sự kiện dành cho công chúng', 'Public and private transportation': 'Phương tiện vận chuyển công cộng và cá nhân', 'Public': 'Công khai', 'Purchase Data': 'Dữ liệu mua hàng', 'Purchase Date': 'Ngày mua hàng', 'Purchase': 'Mua hàng', 'Purpose': 'Mục đích', 'Pyroclastic Flow': 'Dòng dung nham', 'Pyroclastic Surge': 'Núi lửa phun trào', 'Python Serial module not available within the running Python - this needs installing to activate the Modem': 'Modun số liệu Python không sẵn có trong Python đang chạy - cần cài đặt để kích hoạt modem', 'Python needs the ReportLab module installed for PDF export': 'Chưa cài đặt kho báo cáo', 'Python needs the xlrd module installed for XLS export': 'Chạy Python cần xlrd module được cài đặt để chiết xuất định dạng XLS', 'Python needs the xlwt module installed for XLS export': 'Chạy Python cần xlwt module được cài đặt để chiết xuất định dạng XLS', 'Quantity Committed': 'Số lượng cam kết', 'Quantity Fulfilled': 'Số lượng đã được cung cấp', 'Quantity Received': 'Số lượng đã nhận được', 'Quantity Returned': 'Số lượng được trả lại', 'Quantity Sent': 'Số lượng đã gửi', 'Quantity in Transit': 'Số lượng đang được vận chuyển', 'Quantity': 'Số lượng', 'Quarantine': 'Cách ly để kiểm dịch', 'Queries': 'Thắc mắc', 'Query Feature': 'Đặc tính thắc mắc', 'Query': 'Yêu cầu', 'Queryable?': 'Có thể yêu cầu?', 'Question Details': 'Thông tin về câu hỏi', 'Question Meta-Data Details': 'Chi tiết lý lịch dữ liệu về câu hỏi', 'Question Meta-Data added': 'Lý lịch dữ liệu về câu hỏi được thêm vào', 'Question Meta-Data deleted': 'Lý lịch dữ liệu về câu hỏi đã xóa', 'Question Meta-Data updated': 'Lý lịch dữ liệu về câu hỏi được cập nhật', 'Question Meta-Data': 'Lý lịch dữ liệu về câu hỏi', 'Question Summary': 'Tóm tắt câu hỏi', 'Question': 'Câu hỏi', 'READ': 'ĐỌC', 'REPORTS': 'BÁO CÁO', 'RESET': 'THIẾT LẬP LẠI', 'RESILIENCE': 'AN TOÀN', 'REST Filter': 'Bộ lọc REST', 'RFA Priorities': 'Những ưu tiên RFA', 'RFA1: Governance-Organisational, Institutional, Policy and Decision Making Framework': 'RFA1: Quản trị - Về tổ chức, Về thể chế, Chính sách và Khung ra quyết định', 'RFA2: Knowledge, Information, Public Awareness and Education': 'RFA2: Kiến thức, Thông tin, Nhận thức của công chúng và Đào tạo', 'RFA3: Analysis and Evaluation of Hazards, Vulnerabilities and Elements at Risk': 'RFA3: Phân tích và Đánh giá Hiểm họa, Tình trạng dễ bị tổn thương và Những yếu tố dễ gặp rủi ro', 'RFA4: Planning for Effective Preparedness, Response and Recovery': 'RFA4: Lập kế hoạch cho Chuẩn bị, Ứng phó và Phục hồi hiệu quả', 'RFA5: Effective, Integrated and People-Focused Early Warning Systems': 'RFA5: Hệ thống cảnh báo sớm hiệu quả, tích hợp và chú trọng vào con người', 'RFA6: Reduction of Underlying Risk Factors': 'RFA6: Giảm thiểu những nhân tố rủi ro cơ bản', 'Race': 'Chủng tộc', 'Radio Callsign': 'Tín hiệu điện đàm', 'Radiological Hazard': 'Hiểm họa phóng xạ', 'Railway Accident': 'Tai nạn đường sắt', 'Railway Hijacking': 'Cướp tàu hỏa', 'Rain Fall': 'Mưa lớn', 'Rapid Assessments': 'Đánh giá nhanh', 'Rapid Close Lead': 'Nhanh chóng đóng lại', 'Rapid Data Entry': 'Nhập dữ liệu nhanh', 'Raw Database access': 'Truy cập cơ sở dữ liệu gốc', 'Ready': 'Sẵn sàng', 'Reason': 'Lý do', 'Receive %(opt_in)s updates:': 'Nhận %(opt_in)s cập nhật', 'Receive New Shipment': 'Nhận lô hàng mới', 'Receive Shipment': 'Nhận lô hàng', 'Receive updates': 'Nhập cập nhật', 'Receive': 'Nhận', 'Receive/Incoming': 'Nhận/ Đến', 'Received By': 'Nhận bởi', 'Received Shipment Details': 'Thông tin về lô hàng nhận', 'Received Shipment canceled': 'Lô hàng nhận đã bị hoãn', 'Received Shipment updated': 'Lô hàng nhận đã được cập nhật', 'Received Shipments': 'Những lô hàng nhận', 'Received date': 'Ngày nhận', 'Received': 'Đã được nhận', 'Received/Incoming Shipments': 'Những lô hàng nhận/ đến', 'Receiving Inventory': 'Nhận hàng tồn kho', 'Reception': 'Nhận', 'Recipient': 'Người nhận', 'Recipient(s)': 'Người nhận', 'Recipients': 'Những người nhận', 'Record Deleted': 'Hồ sơ bị xóa', 'Record Details': 'Chi tiết hồ sơ', 'Record added': 'Hồ sơ được thêm', 'Record already exists': 'Bản lưu đã tồn tại', 'Record approved': 'Hồ sơ được chấp thuân', 'Record could not be approved.': 'Hồ sơ không được chấp thuận', 'Record could not be deleted.': 'Hồ sơ không thể xóa', 'Record deleted': 'Hồ sơ bị xóa', 'Record not found!': 'Không tìm thấy bản lưu!', 'Record not found': 'Không tìm thấy hồ sơ', 'Record updated': 'Hồ sơ được cập nhật', 'Record': 'Hồ sơ', 'Records': 'Các hồ sơ', 'Recovery Request added': 'Đã thêm yêu cầu phục hồi', 'Recovery Request deleted': 'phục hồi các yêu cầu bị xóa', 'Recovery Request updated': 'Cập nhật Yêu cầu phục hồi', 'Recovery Request': 'Phục hồi yêu cầu', 'Recovery Requests': 'Phục hồi yêu cầu', 'Recovery': 'Phục hồi', 'Recurring costs': 'Chi phí định kỳ', 'Recurring': 'Định kỳ', 'Red Cross & Red Crescent National Societies': 'Các Hội Chữ thập đỏ & Trăng lưỡi liềm đỏ Quốc gia', 'Refresh Rate (seconds)': 'Tỉ lệ làm mới (giây)', 'Region Location': 'Địa điểm vùng', 'Region': 'Vùng', 'Regional': 'Địa phương', 'Register As': 'Đăng ký là', 'Register Person into this Shelter': 'Đăng ký cá nhân vào nơi cư trú', 'Register Person': 'Đăng ký Cá nhân', 'Register for Account': 'Đăng ký tài khoản', 'Register': 'Đăng ký', 'Registered People': 'Những người đã đăng ký', 'Registered users can %(login)s to access the system': 'Người sử dụng đã đăng ký có thể %(đăng nhập)s để truy cập vào hệ thống', 'Registered users can': 'Người dùng đã đăng ký có thể', 'Registration Details': 'Chi tiết đăng ký', 'Registration added': 'Bản đăng ký đã được thêm', 'Registration not permitted': 'Việc đăng ký không được chấp thuận', 'Reject request submitted': 'Đề nghị từ chối đã được gửi đi', 'Reject': 'Từ chối', 'Relationship': 'Mối quan hệ', 'Relief Team': 'Đội cứu trợ', 'Religion': 'Tôn giáo', 'Reload': 'Tải lại', 'Remarks': 'Những nhận xét', 'Remember Me': 'Duy trì đăng nhập', 'Remote Error': 'Lỗi từ xa', 'Remove Feature: Select the feature you wish to remove & press the delete key': 'Chức năng gỡ bỏ: Lựa chọn chức năng bạn muốn gõ bỏ và ấn phím xóa', 'Remove Human Resource from this incident': 'Xóa nguồn Nhân lực khỏi sự việc này', 'Remove Layer from Profile': 'Xóa Lớp khỏi Hồ sơ', 'Remove Layer from Symbology': 'Xóa Lớp khỏi Biểu tượng', 'Remove Organization from Project': 'Xóa Tổ chức khỏi Dự án', 'Remove Person from Commitment': 'Xóa Người khỏi Cam kết', 'Remove Person from Group': 'Xóa Người khỏi Nhóm', 'Remove Person from Team': 'Xóa Người khỏi Đội', 'Remove Profile Configuration for Layer': 'Xóa Cấu hình hồ sơ cho Lớp', 'Remove Skill from Request': 'Xóa Kỹ năng khỏi Đề nghị', 'Remove Skill': 'Xóa Kỹ năng', 'Remove Stock from Warehouse': 'Xóa Hàng hóa khỏi Nhà kho', 'Remove Symbology from Layer': 'Xóa Biểu tượng khỏi Lớp', 'Remove Vehicle from this incident': 'Xóa Phương tiện khỏi sự việc này', 'Remove all log entries': 'Xóa toàn bộ ghi chép nhật ký', 'Remove all': 'Gỡ bỏ toàn bộ', 'Remove existing data before import': 'Xóa dữ liệu đang tồn tại trước khi nhập', 'Remove selection': 'Gỡ bỏ có lựa chọn', 'Remove this entry': 'Gỡ bỏ hồ sơ này', 'Remove': 'Gỡ bỏ', 'Reopened': 'Được mở lại', 'Repacked By': 'Được đóng gói lại bởi', 'Repair': 'Sửa chữa', 'Repaired': 'Được sửa chữa', 'Repeat your password': 'Nhập lại mật khẩu', 'Repeat': 'Lặp lại', 'Replace if Newer': 'Thay thế nếu mới hơn', 'Replace': 'Thay thế', 'Replacing or Provisioning Livelihoods': 'Thay thế hoặc Dự trữ nguồn sinh kế', 'Replies': 'Trả lời', 'Reply Message': 'Trả lời tin nhắn', 'Reply': 'Trả lời', 'Report': 'Báo cáo', 'Report Date': 'Ngày báo cáo', 'Report Details': 'Chi tiết báo cáo', 'Report Options': 'Lựa chọn yêu cầu báo cáo', 'Report To': 'Báo cáo cho', 'Report Type': 'Loại báo cáo', 'Report a Problem with the Software': 'báo cáo lỗi bằng phần mềm', 'Report added': 'Đã thêm báo cáo', 'Report by Age/Gender': 'Báo cáo theo tuổi/ giới tính', 'Report deleted': 'Đã xóa báo cáo', 'Report my location': 'Báo cáo vị trí ', 'Report of': 'Báo cáo theo', 'Report on Annual Budgets': 'Báo cáo về Ngân sách năm', 'Report on Themes': 'Báo cáo về Chủ đề', 'Report the contributing factors for the current EMS status.': 'Báo cáo các nhân tố đóng góp cho tình trạng EMS hiện tại.', 'Report': 'Báo cáo', 'Reported By (Not Staff)': 'Được báo cáo bởi (không phải nhân viên)', 'Reported By (Staff)': 'Được báo cáo bởi (nhân viên)', 'Reported To': 'Được báo cáo tới', 'Reported': 'Được báo cáo', 'Reportlab not installed': 'Chưa cài đặt kho báo cáo', 'Reports': 'Báo cáo', 'Repositories': 'Nơi lưu trữ', 'Repository Base URL': 'Nơi lưu trữ cơ bản URL', 'Repository Configuration': 'Cấu hình nơi lưu trữ', 'Repository Name': 'Tên nơi lưu trữ', 'Repository UUID': 'Lưu trữ UUID', 'Repository configuration deleted': 'Cấu hình nơi lưu trữ đã xóa', 'Repository configuration updated': 'Cấu hình nơi lưu trữ được cập nhật', 'Repository configured': 'Nơi lưu trữ đã được cấu hình', 'Repository': 'Nơi lưu trữ', 'Request Added': 'Đề nghị được thêm vào', 'Request Canceled': 'Đề nghị đã bị hủy', 'Request Details': 'Yêu cầu thông tin chi tiết', 'Request From': 'Đề nghị từ', 'Request Item Details': 'Chi tiết mặt hàng đề nghị', 'Request Item added': 'Đã thêm yêu cầu hàng hóa', 'Request Item deleted': 'Xóa yêu cầu hàng hóa', 'Request Item updated': 'Đã cập nhật hàng hóa yêu cầu', 'Request Item': 'Mặt hàng yêu cầu', 'Request Items': 'Mặt hàng yêu cầu', 'Request New People': 'Yêu cầu cán bộ mới', 'Request Status': 'Tình trạng lời đề nghị', 'Request Stock from Available Warehouse': 'Đề nghị Hàng từ Kho hàng đang có', 'Request Type': 'Loại hình đề nghị', 'Request Updated': 'Đề nghị được cập nhật', 'Request added': 'Yêu cầu được thêm', 'Request deleted': 'Yêu cầu được xóa', 'Request for Role Upgrade': 'yêu cầu nâng cấp vai trò', 'Request from Facility': 'Đề nghị từ bộ phận', 'Request updated': 'Yêu cầu được cập nhật', 'Request': 'Yêu cầu', 'Request, Response & Session': 'Yêu cầu, Phản hồi và Tương tác', 'Requested By': 'Đã được đề nghị bởi', 'Requested For Facility': 'Được yêu cầu cho bộ phận', 'Requested For': 'Đã được đề nghị cho', 'Requested From': 'Đã được đề nghị từ', 'Requested Items': 'Yêu cầu mặt hàng', 'Requested Skill Details': 'Chi tiết kỹ năng đã đề nghị', 'Requested Skill updated': 'Kỹ năng được đề nghị đã được cập nhật', 'Requested Skills': 'Những kỹ năng được đề nghị', 'Requested by': 'Yêu cầu bởi', 'Requested': 'Đã được đề nghị', 'Requester': 'Người đề nghị', 'Requestor': 'Người yêu cầu', 'Requests Management': 'Quản lý những đề nghị', 'Requests for Item': 'Yêu cầu hàng hóa', 'Requests': 'Những đề nghị', 'Required Skills': 'Những kỹ năng cần có ', 'Requires Login!': 'Đề nghị đăng nhập!', 'Requires Login': 'Đề nghị đăng nhập', 'Reset Password': 'Cài đặt lại mật khẩu', 'Reset all filters': 'Tái thiết lập tất cả lựa chọn lọc', 'Reset filter': 'Tái thiết lập lựa chọn lọc', 'Reset form': 'Đặt lại mẫu', 'Reset': 'Thiết lập lại', 'Resolution': 'Nghị quyết', 'Resource Configuration': 'Cấu hình nguồn lực', 'Resource Management System': 'Hệ thống quản lý nguồn lực', 'Resource Mobilization': 'Huy động nguồn lực', 'Resource Name': 'Tên nguồn lực', 'Resource configuration deleted': 'Cấu hình nguồn lực đã xóa', 'Resource configuration updated': 'Cầu hình nguồn lực được cập nhật', 'Resource configured': 'Nguồn lực đã được cấu hình', 'Resources': 'Những nguồn lực', 'Responder(s)': 'Người ứng phó', 'Response deleted': 'Xóa phản hồi', 'Response': 'Ứng phó', 'Responses': 'Các đợt ứng phó', 'Restarting Livelihoods': 'Tái khởi động nguồn sinh kế', 'Results': 'Kết quả', 'Retail Crime': 'Chiếm đoạt tài sản để bán', 'Retrieve Password': 'Khôi phục mật khẩu', 'Return to Request': 'Trở về Đề nghị', 'Return': 'Trở về', 'Returned From': 'Được trả lại từ', 'Returned': 'Đã được trả lại', 'Returning': 'Trả lại', 'Review Incoming Shipment to Receive': 'Rà soát Lô hàng đến để Nhận', 'Review next': 'Rà soát tiếp', 'Review': 'Rà soát', 'Revised Quantity': 'Số lượng đã được điều chỉnh', 'Revised Status': 'Tình trạng đã được điều chỉnh', 'Revised Value per Pack': 'Giá trị mỗi Gói đã được điều chỉnh', 'Riot': 'Bạo động', 'Risk Identification & Assessment': 'Xác định & Đánh giá rủi ro', 'Risk Transfer & Insurance': 'Chuyển đổi rủi ro & Bảo hiểm', 'River Details': 'Chi tiết Sông', 'River': 'Sông', 'Road Accident': 'Tai nạn đường bộ', 'Road Closed': 'Đường bị chặn', 'Road Delay': 'Cản trở giao thông đường bộ', 'Road Hijacking': 'Tấn công trên đường', 'Road Safety': 'An toàn đường bộ', 'Road Usage Condition': 'Tình hình sử dụng đường sá', 'Role Details': 'Chi tiết về vai trò', 'Role Name': 'Tên chức năng', 'Role Required': 'Chức năng được yêu cầu', 'Role added': 'Vai trò được thêm vào', 'Role assigned to User': 'Chức năng được cấp cho người sử dụng này', 'Role deleted': 'Vai trò đã xóa', 'Role updated': 'Vai trò được cập nhật', 'Role': 'Vai trò', 'Roles Permitted': 'Các chức năng được cho phép', 'Roles currently assigned': 'Các chức năng được cấp hiện tại', 'Roles of User': 'Các chức năng của người sử dụng', 'Roles updated': 'Các chức năng được cập nhật', 'Roles': 'Vai trò', 'Room Details': 'Chi tiết về phòng', 'Room added': 'Phòng được thêm vào', 'Room deleted': 'Phòng đã xóa', 'Room updated': 'Phòng được cập nhật', 'Room': 'Phòng', 'Rooms': 'Những phòng', 'Rotation': 'Sự luân phiên', 'Rows in table': 'Các hàng trong bảng', 'Rows selected': 'Các hàng được chọn', 'Rows': 'Các dòng', 'Run Functional Tests': 'Kiểm thử chức năng', 'Run every': 'Khởi động mọi hàng', 'S3Pivottable unresolved dependencies': 'Các phụ thuộc không được xử lý S3pivottable', 'SMS Modems (Inbound & Outbound)': 'Modem SMS (gửi ra & gửi đến)', 'SMS Outbound': 'SMS gửi ra', 'SMS Settings': 'Cài đặt tin nhắn', 'SMS settings updated': 'Cập nhật cài đặt SMS', 'SMTP to SMS settings updated': 'Cập nhật cài đặt SMTP to SMS', 'STRONG': 'MẠNH', 'SUBMIT DATA': 'GỬI DỮ LIỆU', 'Sahana Administrator': 'Quản trị viên Sahana', 'Sahana Community Chat': 'Nói chuyện trên cộng đồng Sahana', 'Sahana Eden Humanitarian Management Platform': 'Diễn đàn Quản lý nhân đạo Sahana Eden', 'Sahana Eden Website': 'Trang thông tin Sahana Eden', 'Sahana Eden portable application generator': 'Bộ sinh ứng dụng cầm tay Sahana Eden', 'Sahana Login Approval Pending': 'Chờ chấp nhận đăng nhập vào Sahana', 'Sale': 'Bán hàng', 'Satellite': 'Vệ tinh', 'Save and add Items': 'Lưu và thêm Hàng hóa', 'Save and add People': 'Lưu và thêm Người', 'Save any Changes in the one you wish to keep': 'Lưu mọi thay đổi ở bất kỳ nơi nào bạn muốn', 'Save search': 'Lưu tìm kiếm', 'Save this search': 'Lưu tìm kiếm này', 'Save': 'Lưu', 'Save: Default Lat, Lon & Zoom for the Viewport': 'Lưu: Mặc định kinh độ, vĩ độ & phóng ảnh cho cổng nhìn', 'Saved Queries': 'Các thắc mắc được lưu', 'Saved Searches': 'Những tìm kiếm đã lưu', 'Saved search added': 'Tìm kiếm đã lưu đã được thêm vào', 'Saved search deleted': 'Tìm kiếm được lưu đã xóa', 'Saved search details': 'Chi tiết về tìm kiếm đã lưu', 'Saved search updated': 'Tìm kiếm đã lưu đã được cập nhật', 'Saved searches': 'Những tìm kiếm đã lưu', 'Scale of Results': 'Phạm vi của kết quả', 'Scale': 'Kích thước', 'Scanned Copy': 'Bản chụp điện tử', 'Scanned Forms Upload': 'Tải lên mẫu đã quyét', 'Scenarios': 'Các kịch bản', 'Schedule synchronization jobs': 'Các công việc được điều chỉnh theo lịch trình', 'Schedule': 'Lịch trình', 'Scheduled Jobs': 'Công việc đã được lập kế hoạch', 'Schema': 'Giản đồ', 'School Closure': 'Đóng cửa trường học', 'School Health': 'CSSK trong trường học', 'School Lockdown': 'Đóng cửa trường học', 'School tents received': 'Đã nhận được lều gửi cho trường học ', 'School/studying': 'Trường học', 'Seaport': 'Cảng biển', 'Seaports': 'Các cảng biển', 'Search & List Catalog': 'Tìm kiếm và liệt kê các danh mục', 'Search & List Category': 'Tìm và liệt kê danh mục', 'Search & List Items': 'Tìm kiếm và hiển thị danh sách hàng hóa', 'Search & List Locations': 'Tìm và liệt kê các địa điểm', 'Search & List Sub-Category': 'Tìm kiếm và lên danh sách Tiêu chí phụ', 'Search & Subscribe': 'Tìm kiếm và Đặt mua', 'Search Activities': 'Tìm kiếm hoạt động', 'Search Addresses': 'Tìm kiếm địa chỉ', 'Search Affiliations': 'Tìm kiếm chi nhánh', 'Search Aid Requests': 'Tìm kiếm Yêu cầu cứu trợ', 'Search Alternative Items': 'Tìm kiếm mục thay thế', 'Search Annual Budgets': 'Tìm kiếm các ngân sách năm', 'Search Assessments': 'Tìm kiếm các đánh giá', 'Search Asset Log': 'Tìm kiếm nhật ký tài sản', 'Search Assets': 'Tìm kiếm tài sản', 'Search Assigned Human Resources': 'Tìm kiếm người được phân công', 'Search Beneficiaries': 'Tìm kiếm những người hưởng lợi', 'Search Beneficiary Types': 'Tìm kiếm những nhóm người hưởng lợi', 'Search Branch Organizations': 'Tìm kiếm tổ chức chi nhánh', 'Search Brands': 'Tìm kiếm nhãn hàng', 'Search Budgets': 'Tìm kiếm các ngân sách', 'Search Catalog Items': 'Tìm kiếm mặt hàng trong danh mục', 'Search Catalogs': 'Tìm kiếm danh mục', 'Search Certificates': 'Tìm kiếm chứng chỉ', 'Search Certifications': 'Tìm kiếm bằng cấp', 'Search Checklists': 'Tìm kiếm Checklist', 'Search Clusters': 'Tìm kiếm nhóm', 'Search Commitment Items': 'Tìm kiếm mục cam kết', 'Search Commitments': 'Tìm kiếm cam kết', 'Search Committed People': 'Tìm kiếm người được cam kết', 'Search Community Contacts': 'Tìm kiếm thông tin liên lạc của cộng đồng', 'Search Community': 'Tìm kiếm cộng đồng', 'Search Competency Ratings': 'Tìm kiếm đánh giá năng lực', 'Search Contact Information': 'Tìm kiếm thông tin liên hệ', 'Search Contacts': 'Tìm kiếm liên lạc', 'Search Course Certificates': 'Tìm kiếm chứng chỉ đào tạo', 'Search Courses': 'Tìm kiếm khóa đào tạo', 'Search Credentials': 'Tìm kiếm giấy chứng nhận', 'Search Demographic Data': 'Tìm kiếm dữ liệu nhân khẩu học', 'Search Demographic Sources': 'Tìm kiếm nguồn dữ liệu dân số', 'Search Demographics': 'Tìm kiếm số liệu thống kê dân số', 'Search Departments': 'Tìm kiếm phòng/ban', 'Search Distributions': 'Tìm kiếm Quyên góp', 'Search Documents': 'Tìm kiếm tài liệu', 'Search Donors': 'Tìm kiếm nhà tài trợ', 'Search Education Details': 'Tìm kiếm thông tin đào tạo', 'Search Email InBox': 'Tìm kiếm thư trong hộp thư đến', 'Search Entries': 'Tìm kiếm hồ sơ', 'Search Facilities': 'Tìm kiếm trang thiết bị', 'Search Facility Types': 'Tìm kiếm loại hình bộ phận', 'Search Feature Layers': 'Tìm kiếm lớp tính năng', 'Search Flood Reports': 'Tìm các báo cáo về lũ lụt', 'Search Frameworks': 'Tìm kiếm khung chương trình', 'Search Groups': 'Tìm kiếm nhóm', 'Search Hospitals': 'Tìm kếm các bệnh viện', 'Search Hours': 'Tìm kiếm theo thời gian hoạt động', 'Search Identity': 'Tìm kiếm nhận dạng', 'Search Images': 'Tìm kiếm hình ảnh', 'Search Incident Reports': 'Tìm kiếm báo cáo sự việc', 'Search Item Catalog(s)': 'Tìm kiếm Catalog hàng hóa', 'Search Item Categories': 'Tìm kiếm nhóm mặt hàng', 'Search Item Packs': 'Tìm kiếm gói hàng', 'Search Items in Request': 'Tìm kiếm mặt hàng đang đề nghị', 'Search Items': 'Tìm kiếm mặt hàng', 'Search Job Roles': 'Tìm kiếm vai trò của công việc', 'Search Job Titles': 'Tìm kiếm chức danh công việc', 'Search Keys': 'Tìm kiếm mã', 'Search Kits': 'Tìm kiếm bộ dụng cụ', 'Search Layers': 'Tìm kiếm lớp', 'Search Location Hierarchies': 'Tìm kiếm thứ tự địa điểm', 'Search Location': 'Tìm kiếm địa điểm', 'Search Locations': 'Tìm kiếm địa điểm', 'Search Log Entry': 'Tìm kiếm ghi chép nhật ký', 'Search Logged Time': 'Tìm kiếm thời gian đăng nhập', 'Search Mailing Lists': 'Tìm kiếm danh sách gửi thư', 'Search Map Configurations': 'Tìm kiếm cấu hình bản đồ', 'Search Markers': 'Tìm kiếm đánh dấu', 'Search Members': 'Tìm kiếm thành viên', 'Search Membership Types': 'Tìm kiếm loại hình hội viên', 'Search Membership': 'Tìm kiếm hội viên', 'Search Memberships': 'Tim kiếm thành viên', 'Search Metadata': 'Tìm kiếm dữ liệu', 'Search Milestones': 'Tìm kiếm mốc quan trọng', 'Search Office Types': 'Tìm kiếm loại hình văn phòng', 'Search Offices': 'Tìm kiếm văn phòng', 'Search Open Tasks for %(project)s': 'Tìm kiếm Công việc Chưa được xác định cho %(project)s', 'Search Orders': 'Tìm kiếm đơn hàng', 'Search Organization Domains': 'Tìm kiếm lĩnh vực hoạt động của tổ chức', 'Search Organization Types': 'Tìm kiếm loại hình tổ chức', 'Search Organizations': 'Tìm kiếm tổ chức', 'Search Participants': 'Tìm kiếm người tham dự', 'Search Partner Organizations': 'Tìm kiếm tổ chức thành viên', 'Search Persons': 'Tìm kiếm người', 'Search Photos': 'Tìm kiếm hình ảnh', 'Search Professional Experience': 'Tìm kiếm kinh nghiệm nghề nghiệp', 'Search Programs': 'Tìm kiếm chương trình', 'Search Project Organizations': 'Tìm kiếm tổ chức dự án', 'Search Projections': 'Tìm kiếm dự đoán', 'Search Projects': 'Tìm kiếm dự án', 'Search Received/Incoming Shipments': 'Tìm kiếm lô hàng đến/nhận', 'Search Records': 'Tìm kiếm hồ sơ', 'Search Red Cross & Red Crescent National Societies': 'Tìm kiếm Hội Chữ thập đỏ và Trăng lưỡi liềm đỏ Quốc gia', 'Search Registations': 'Tìm kiếm các đăng ký', 'Search Registration Request': 'Tìm kiếm Yêu cầu Đăng ký', 'Search Report': 'Tìm kiếm báo cáo', 'Search Reports': 'Tìm kiếm Báo cáo', 'Search Request Items': 'Tìm kiếm Yêu cầu hàng hóa', 'Search Request': 'Tìm kiếm yêu cầu', 'Search Requested Skills': 'Tìm kiếm kỹ năng được đề nghị', 'Search Requests': 'Tìm kiếm đề nghị', 'Search Resources': 'Tìm kiếm các nguồn lực', 'Search Results': 'Tìm kiếm kết quả', 'Search Roles': 'Tìm kiếm vai trò', 'Search Rooms': 'Tìm kiếm phòng', 'Search Sectors': 'Tìm kiếm lĩnh vực', 'Search Sent Shipments': 'Tìm kiếm lô hàng đã gửi', 'Search Shelter Services': 'Tìm kiếm dịch vụ cư trú', 'Search Shelter Types': 'Tìm kiếm Loại Cư trú', 'Search Shipment Items': 'Tìm kiếm mặt hàng của lô hàng', 'Search Shipment/Way Bills': 'Tìm kiếm đơn hàng/hóa đơn vận chuyển', 'Search Shipped Items': 'Tìm kiếm mặt hàng được vận chuyển', 'Search Skill Equivalences': 'Tìm kiếm kỹ năng tương ứng', 'Search Skill Types': 'Tìm kiếm nhóm kỹ năng', 'Search Skills': 'Tìm kiếm kỹ năng', 'Search Staff & Volunteers': 'Tìm kiếm nhân viên & tình nguyện viên', 'Search Staff Assignments': 'Tìm kiếm công việc của nhân viên', 'Search Staff': 'Tìm kiếm nhân viên', 'Search Stock Adjustments': 'Tìm kiếm điều chỉnh về kho hàng', 'Search Stock Items': 'Tìm kiếm mặt hàng trong kho', 'Search Storage Location(s)': 'Tìm kiếm kho lưu trữ', 'Search Subscriptions': 'Tìm kiếm danh sách, số tiền quyên góp', 'Search Suppliers': 'Tìm kiếm nhà cung cấp', 'Search Support Requests': 'Tìm kiếm yêu cầu được hỗ trợ', 'Search Symbologies': 'Tìm kiếm biểu tượng', 'Search Tasks': 'Tìm kiếm nhiệm vụ', 'Search Teams': 'Tìm kiếm Đội/Nhóm', 'Search Theme Data': 'Tìm kiếm dữ liệu chủ đề', 'Search Themes': 'Tìm kiếm chủ đề', 'Search Tracks': 'Tìm kiếm dấu vết', 'Search Training Events': 'Tìm kiếm khóa tập huấn', 'Search Training Participants': 'Tìm kiếm học viên được tập huấn', 'Search Twilio SMS Inbox': 'Tìm kiếm hộp thư đến SMS Twilio', 'Search Twitter Tags': 'Tìm kiếm liên kết với Twitter', 'Search Units': 'Tìm kiếm đơn vị', 'Search Users': 'Tìm kiếm người sử dụng', 'Search Vehicle Assignments': 'Tìm kiếm việc điều động phương tiện', 'Search Volunteer Cluster Positions': 'Tìm kiếm vị trí của nhóm tình nguyện viên', 'Search Volunteer Cluster Types': 'Tìm kiếm loại hình nhóm tình nguyện viên', 'Search Volunteer Clusters': 'Tìm kiếm nhóm tình nguyện viên', 'Search Volunteer Registrations': 'Tìm kiếm Đăng ký tình nguyện viên', 'Search Volunteer Roles': 'Tìm kiếm vai trò của tình nguyện viên', 'Search Volunteers': 'Tìm kiếm tình nguyện viên', 'Search Vulnerability Aggregated Indicators': 'Tìm kiếm chỉ số theo tình trạng dễ bị tổn thương', 'Search Vulnerability Data': 'Tìm kiếm dữ liệu về tình trạng dễ bị tổn thương', 'Search Vulnerability Indicator Sources': 'Tìm kiếm nguồn chỉ số về tình trạng dễ bị tổn thương', 'Search Vulnerability Indicators': 'Tìm kiếm chỉ số về tình trạng dễ bị tổn thương', 'Search Warehouse Stock': 'Tìm kiếm Hàng trữ trong kho', 'Search Warehouses': 'Tìm kiếm Nhà kho', 'Search and Edit Group': 'Tìm và sửa thông tin nhóm', 'Search and Edit Individual': 'Tìm kiếm và chỉnh sửa cá nhân', 'Search for Activity Type': 'Tìm kiếm nhóm hoạt động', 'Search for Job': 'Tìm kiếm công việc', 'Search for Repository': 'Tìm kiếm Nơi lưu trữ', 'Search for Resource': 'Tìm kiếm nguồn lực', 'Search for a Hospital': 'Tìm kiếm bệnh viện', 'Search for a Location': 'Tìm một địa điểm', 'Search for a Person': 'Tìm kiếm theo tên', 'Search for a Project Community by name.': 'Tìm kiếm cộng đồng dự án theo tên.', 'Search for a Project by name, code, location, or description.': 'Tìm kiếm dự án theo tên, mã, địa điểm, hoặc mô tả.', 'Search for a Project by name, code, or description.': 'Tìm kiếm dự án theo tên, mã, hoặc mô tả.', 'Search for a Project': 'Tìm kiếm dự án', 'Search for a Request': 'Tìm kiếm một yêu cầu', 'Search for a Task by description.': 'Tìm kiếm nhiệm vụ theo mô tả.', 'Search for a shipment by looking for text in any field.': 'Tìm kiếm lô hàng bằng cách nhập từ khóa vào các ô.', 'Search for a shipment received between these dates': 'Tìm kiếm lô hàng đã nhận trong những ngày gần đây', 'Search for an Organization by name or acronym': 'Tìm kiếm tổ chức theo tên hoặc chữ viết tắt', 'Search for an item by Year of Manufacture.': 'Tìm kiếm mặt hàng theo năm sản xuất.', 'Search for an item by brand.': 'Tìm kiếm mặt hàng theo nhãn hàng.', 'Search for an item by catalog.': 'Tìm kiếm mặt hàng theo danh mục.', 'Search for an item by category.': 'Tìm kiếm mặt hàng theo nhóm.', 'Search for an item by its code, name, model and/or comment.': 'Tìm kiếm mặt hàng theo mã, tên, kiểu và/hoặc nhận xét.', 'Search for an item by text.': 'Tìm kiếm mặt hàng theo từ khóa.', 'Search for an order by looking for text in any field.': 'Tìm kiếm đơn đặt hàng bằng cách nhập từ khóa vào các ô.', 'Search for an order expected between these dates': 'Tìm kiếm một đơn hàng dự kiến trong những ngày gần đây', 'Search for office by organization.': 'Tìm kiếm văn phòng theo tổ chức.', 'Search for office by text.': 'Tìm kiếm văn phòng theo từ khóa.', 'Search for warehouse by organization.': 'Tìm kiếm nhà kho theo tổ chức.', 'Search for warehouse by text.': 'Tìm kiếm nhà kho theo từ khóa.', 'Search location in Geonames': 'Tìm kiếm địa điểm theo địa danh', 'Search messages': 'Tìm kiếm tin nhắn', 'Search saved searches': 'Tìm kiếm tìm kiếm được lưu', 'Search': 'Tìm kiếm', 'Secondary Server (Optional)': 'Máy chủ thứ cấp', 'Seconds must be a number between 0 and 60': 'Giây phải là số từ 0 đến 60', 'Seconds must be a number.': 'Giây phải bằng số', 'Seconds must be less than 60.': 'Giây phải nhỏ hơn 60', 'Section Details': 'Chi tiết khu vực', 'Section': 'Lĩnh vực', 'Sections that are part of this template': 'Các lĩnh vực là bộ phận của mẫu này', 'Sector Details': 'Chi tiết lĩnh vực', 'Sector added': 'Thêm Lĩnh vực', 'Sector deleted': 'Xóa Lĩnh vực', 'Sector updated': 'Cập nhật Lĩnh vực', 'Sector': 'Lĩnh vực', 'Sector(s)': 'Lĩnh vực', 'Sectors to which this Theme can apply': 'Lựa chọn Lĩnh vực phù hợp với Chủ đề này', 'Sectors': 'Lĩnh vực', 'Security Policy': 'Chính sách bảo mật', 'Security Required': 'An ninh được yêu cầu', 'Security Staff Types': 'Loại cán bộ bảo vệ', 'See All Entries': 'Xem tất cả hồ sơ', 'See a detailed description of the module on the Sahana Eden wiki': 'Xem chi tiết mô tả Modun trên Sahana Eden wiki', 'See the universally unique identifier (UUID) of this repository': 'Xem Định dạng duy nhất toàn cầu (UUID) của thư mục lưu này', 'Seen': 'Đã xem', 'Select %(location)s': 'Chọn %(location)s', 'Select %(up_to_3_locations)s to compare overall resilience': 'Chọn %(up_to_3_locations)s để so sánh tổng thể Sự phục hồi nhanh', 'Select Existing Location': 'Lựa chọn vị trí đang có', 'Select Items from the Request': 'Chọn Hàng hóa từ Yêu cầu', 'Select Label Question': 'Chọn nhãn câu hỏi', 'Select Modules for translation': 'Lựa chọn các Module để dịch', 'Select Modules which are to be translated': 'Chọn Modun cần dịch', 'Select Numeric Questions (one or more):': 'Chọn câu hỏi về lượng (một hay nhiều hơn)', 'Select Stock from this Warehouse': 'Chọn hàng hóa lưu kho từ một Kho hàng', 'Select This Location': 'Lựa chọn vị trí này', 'Select a Country': 'Chọn nước', 'Select a commune to': 'Chọn xã đến', 'Select a label question and at least one numeric question to display the chart.': 'Chọn nhãn câu hỏi và ít nhất 1 câu hỏi về lượng để thể hiện biểu đồ', 'Select a location': 'Lựa chọn Quốc gia', 'Select a question from the list': 'Chọn một câu hỏi trong danh sách', 'Select all modules': 'Chọn mọi Modun', 'Select all that apply': 'Chọn tất cả các áp dụng trên', 'Select an Organization to see a list of offices': 'Chọn một Tổ chức để xem danh sách văn phòng', 'Select an existing bin': 'Lựa chọn ngăn có sẵn', 'Select an office': 'Chọn một văn phòng', 'Select any one option that apply': 'Lựa chọn bất cứ một lựa chọn được áp dụng', 'Select data type': 'Chọn loại dữ liệu', 'Select from registry': 'Chọn từ danh sách đã đăng ký', 'Select language code': 'Chọn mã ngôn ngữ', 'Select one or more option(s) that apply': 'Lựa một hoặc nhiều lựa chọn được áp dụng', 'Select the default site.': 'Lựa chọn trang mặc định', 'Select the language file': 'Chọn tệp ngôn ngữ', 'Select the overlays for Assessments and Activities relating to each Need to identify the gap.': 'Lựa chọn lớp dữ liệu phủ cho Đánh giá và Hoạt động liên quan đến mỗi nhu cầu để xác định khoảng thiếu hụt.', 'Select the person assigned to this role for this project.': 'Chọn người được bổ nhiệm cho vai trò này trong dự án', 'Select the required modules': 'Chọn Modun cần thiết', 'Select': 'Chọn', 'Selected Questions for all Completed Assessment Forms': 'Câu hỏi được chọn cho tất cả các mẫu Đánh giá đã hoàn thành', 'Selects what type of gateway to use for outbound SMS': 'Chọn loại cổng để sử dụng tin nhắn gửi ra', 'Send Alerts using Email &/or SMS': 'Gửi Cảnh báo sử dụng thư điện từ &/hay SMS', 'Send Commitment': 'Gửi Cam kết', 'Send Dispatch Update': 'Gửi cập nhật ', 'Send Message': 'Gửi tin', 'Send New Shipment': 'Gửi Lô hàng Mới', 'Send Notification': 'Gửi thông báo', 'Send Shipment': 'Gửi Lô hàng', 'Send Task Notification': 'Gửi Thông báo Nhiệm vụ', 'Send a message to this person': 'Gửi tin nhắn cho người này', 'Send a message to this team': 'Gửi tin nhắn cho đội này', 'Send batch': 'Gửi hàng loạt', 'Send from %s': 'Gửi từ %s', 'Send message': 'Gửi tin nhắn', 'Send new message': 'Gửi tin nhắn mới', 'Send': 'Gửi', 'Sender': 'Người gửi', 'Senders': 'Người gửi', 'Senior (50+)': 'Người già (50+)', 'Sensitivity': 'Mức độ nhạy cảm', 'Sent By Person': 'Được gửi bởi Ai', 'Sent By': 'Được gửi bởi', 'Sent Shipment Details': 'Chi tiết lô hàng đã gửi', 'Sent Shipment canceled and items returned to Warehouse': 'Hủy lô hàng đã gửi và trả lại hàng hóa về kho Hàng', 'Sent Shipment canceled': 'Hủy lô hàng đã gửi', 'Sent Shipment has returned, indicate how many items will be returned to Warehouse.': 'Lô hàng được gửi đã được trả lại, nêu rõ bao nhiêu mặt hàng sẽ được trả lại kho hàng', 'Sent Shipment updated': 'Cập nhật Lô hàng đã gửi', 'Sent Shipments': 'Hàng được gửi', 'Sent date': 'Thời điểm gửi', 'Sent': 'đã được gửi', 'Separated': 'Ly thân', 'Serial Number': 'Số se ri', 'Series details missing': 'Chi tiết Se ri đang mất tích', 'Series': 'Se ri', 'Server': 'Máy chủ', 'Service Record': 'Hồ sơ hoạt động', 'Service or Facility': 'Dịch vụ hay Bộ phận', 'Service profile added': 'Đã thêm thông tin dịch vụ', 'Services Available': 'Các dịch vụ đang triển khai', 'Services': 'Dịch vụ', 'Set Base Facility/Site': 'Thiết lập Bộ phận/Địa bàn cơ bản', 'Set By': 'Thiết lập bởi', 'Set True to allow editing this level of the location hierarchy by users who are not MapAdmins.': 'Thiết lập Đúng để cho phép chỉnh sửa mức này của hệ thống hành chính địa điểm bởi người sử dụng không thuộc quản trị bản đồ', 'Setting Details': 'Chi tiết cài đặt', 'Setting added': 'Thêm cài đặt', 'Setting deleted': 'Xóa cài đặt', 'Settings were reset because authenticating with Twitter failed': 'Cài đặt được làm lại vì sự xác minh với Twitter bị lỗi', 'Settings which can be configured through the web interface are available here.': 'Cài đặt có thể được cấu hình thông quan tương tác với trang web có thể làm ở đây.', 'Settings': 'Các Cài đặt', 'Sex (Count)': 'Giới tính (Số lượng)', 'Sex': 'Giới tính', 'Sexual and Reproductive Health': 'CSSK Giới tính và Sinh sản', 'Share a common Marker (unless over-ridden at the Feature level)': 'Chia sẻ Đèn hiệu chung(nếu không vượt mức tính năng)', 'Shelter Registry': 'Đăng ký tạm trú', 'Shelter Service Details': 'Chi tiết dịch vụ cư trú', 'Shelter Services': 'Dịch vụ cư trú', 'Shelter added': 'Đã thêm Thông tin cư trú', 'Shelter deleted': 'Đã xóa nơi cư trú', 'Shelter': 'Nhà', 'Shelters': 'Địa điểm cư trú', 'Shipment Created': 'Tạo Lô hàng', 'Shipment Item Details': 'Chi tiết hàng hóa trong lô hàng', 'Shipment Item deleted': 'Xóa hàng hóa trong lô hàng', 'Shipment Item updated': 'Cập nhật hàng hóa trong lô hàng', 'Shipment Items Received': 'Hàng hóa trong lô hàng đã nhận được', 'Shipment Items sent from Warehouse': 'Hàng hóa trong lô hàng được gửi từ Kho hàng', 'Shipment Items': 'Hàng hóa trong lô hàng', 'Shipment Type': 'Loại Lô hàng', 'Shipment received': 'Lô hàng đã nhận được', 'Shipment to Receive': 'Lô hàng sẽ nhận được', 'Shipment to Send': 'Lô hàng sẽ gửi', 'Shipment': 'Lô hàng', 'Shipment/Way Bills': 'Đơn hàng/Hóa đơn vận chuyển', 'Shipment<>Item Relation added': 'Đã thêm đơn hàng <>hàng hóa liên quan', 'Shipment<>Item Relation deleted': 'Đã xóa dơn hàng <>Hàng hóa liên quan', 'Shipment<>Item Relation updated': 'Đã cập nhật Đơn hàng<>hàng hóa liên qua', 'Shipment<>Item Relations Details': 'Đơn hàng<>Chi tiết hàng hóa liên quan', 'Shipments': 'Các loại lô hàng', 'Shipping Organization': 'Tổ chức hàng hải', 'Shooting': 'Bắn', 'Short Description': 'Miêu tả ngắn gọn', 'Short Text': 'Đoạn văn bản ngắn', 'Short Title / ID': 'Tên viết tắt/ Mã dự án', 'Show Details': 'Hiển thị chi tiết', 'Show _MENU_ entries': 'Hiển thị _MENU_ hồ sơ', 'Show less': 'Thể hiện ít hơn', 'Show more': 'Thể hiện nhiều hơn', 'Show on Map': 'Thể hiện trên bản đồ', 'Show on map': 'Hiển thị trên bản đồ', 'Show totals': 'Hiển thị tổng', 'Show': 'Hiển thị', 'Showing 0 to 0 of 0 entries': 'Hiển thị 0 tới 0 của 0 hồ sơ', 'Showing _START_ to _END_ of _TOTAL_ entries': 'Hiển thị _START_ tới _END_ của _TOTAL_ hồ sơ', 'Showing latest entries first': 'Hiển thị hồ sơ mới nhất trước', 'Signature / Stamp': 'Chữ ký/dấu', 'Signature': 'Chữ ký', 'Simple Search': 'Tìm kiếm cơ bản', 'Single PDF File': 'File PDF', 'Single': 'Độc thân', 'Site Address': 'Địa chỉ trang web ', 'Site Administration': 'Quản trị Site', 'Site Manager': 'Quản trị website ', 'Site Name': 'Tên địa điểm', 'Site updated': 'Đã cập nhật site', 'Site': 'Địa điểm', 'Sitemap': 'Bản đồ địa điểm', 'Sites': 'Trang web', 'Situation Awareness & Geospatial Analysis': 'Nhận biết tình huống và phân tích tọa độ địa lý', 'Situation': 'Tình hình', 'Skeleton Example': 'Ví dụ khung', 'Sketch': 'Phác thảo', 'Skill Catalog': 'Danh mục kỹ năng', 'Skill Details': 'Chi tiết kỹ năng', 'Skill Equivalence Details': 'Chi tiết Kỹ năng tương ứng', 'Skill Equivalence added': 'Thêm Kỹ năng tương ứng', 'Skill Equivalence deleted': 'Xóa Kỹ năng tương ứng', 'Skill Equivalence updated': 'Cập nhật Kỹ năng tương ứng', 'Skill Equivalence': 'Kỹ năng tương ứng', 'Skill Equivalences': 'các Kỹ năng tương ứng', 'Skill Type Catalog': 'Danh mục Loại Kỹ năng', 'Skill Type added': 'Thêm Loại Kỹ năng', 'Skill Type deleted': 'Xóa Loại Kỹ năng', 'Skill Type updated': 'Cập nhật Loại Kỹ năng', 'Skill Type': 'Loại Kỹ năng', 'Skill added to Request': 'Thêm Kỹ năng vào Yêu cầu', 'Skill added': 'Thêm Kỹ năng', 'Skill deleted': 'Xóa kỹ năng', 'Skill removed from Request': 'Bỏ kỹ năng khỏi yêu cầu', 'Skill removed': 'Bỏ kỹ năng', 'Skill updated': 'Cập nhật kỹ năng', 'Skill': 'Kỹ năng', 'Skills': 'Kỹ năng', 'Smoke': 'Khói', 'Snapshot': 'Chụp ảnh', 'Snow Fall': 'Tuyết rơi', 'Snow Squall': 'Tiếng tuyết rơi', 'Social Impact & Resilience': 'Tác động xã hội & Khả năng phục hồi nhanh', 'Social Inclusion & Diversity': 'Đa dạng hóa và hòa nhập xã hội', 'Solid Waste Management': 'Quản lý chất thải rắn', 'Solution added': 'Đã thêm giải pháp', 'Solution deleted': 'Đã xóa giải pháp', 'Solution updated': 'Đã cập nhật giải pháp', 'Sorry - the server has a problem, please try again later.': 'Xin lỗi - Máy chủ có sự cố, vui lòng thử lại sau.', 'Sorry location %(location)s appears to be outside the area of parent %(parent)s.': 'Xin lỗi địa điểm %(location)s có vẻ như ngoài vùng của lớp trên %(parent)s', 'Sorry location %(location)s appears to be outside the area supported by this deployment.': 'Xin lỗi địa điểm %(location)s có vẻ như ngoài vùng hỗ trợ bởi đợt triển khai này', 'Sorry location appears to be outside the area of parent %(parent)s.': 'Xin lỗi địa điểm có vẻ như ngoài vùng của lớp trên %(parent)s', 'Sorry location appears to be outside the area supported by this deployment.': 'Xin lỗi địa điểm có vẻ như ngoài vùng hỗ trợ bởi đợt triển khai này', 'Sorry, I could not understand your request': 'Xin lỗi, tôi không thể hiểu yêu cầu của bạn', 'Sorry, only users with the MapAdmin role are allowed to edit these locations': 'Xin lỗi, chỉ người sử dụng có chức năng quản trị bản đồ được phép chỉnh sửa các địa điểm này', 'Sorry, something went wrong.': 'Xin lỗi, có sự cố.', 'Sorry, that page is forbidden for some reason.': 'Xin lỗi, vì một số lý do trang đó bị cấm.', 'Sorry, that service is temporary unavailable.': 'Xin lỗi, dịch vụ đó tạm thời không có', 'Sorry, there are no addresses to display': 'Xin lỗi, Không có địa chỉ để hiện thị', 'Source Type': 'Loại nguồn', 'Source not specified!': 'Nguồn không xác định', 'Source': 'Nguồn', 'Space Debris': 'Rác vũ trụ', 'Spanish': 'Người Tây Ban Nha', 'Special Ice': 'Băng tuyết đặc biệt', 'Special Marine': 'Thủy quân đặc biệt', 'Special needs': 'Nhu cầu đặc biệt', 'Specialized Hospital': 'Bệnh viện chuyên khoa', 'Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen.': 'Khu vực cụ thể (ví dụ Tòa nhà/Phòng) trong khu vực mà người/Nhóm đã xem', 'Specific locations need to have a parent of level': 'Các địa điểm cụ thể cần có lớp trên', 'Specify a descriptive title for the image.': 'Chỉ định một tiêu đề mô tả cho ảnh', 'Spherical Mercator (900913) is needed to use OpenStreetMap/Google/Bing base layers.': 'Spherical Mercator (900913) cần thiết để sử dụng OpenStreetMap/Google/Bing như là lớp bản đồ cơ sở.', 'Spreadsheet': 'Bảng tính', 'Squall': 'tiếng kêu', 'Staff & Volunteers': 'Cán bộ & Tình nguyện viên', 'Staff Assigned': 'Cán bộ được bộ nhiệm', 'Staff Assignment Details': 'Chi tiết bổ nhiệm cán bộ', 'Staff Assignment removed': 'Bỏ bổ nhiệm cán bộ', 'Staff Assignment updated': 'Cập nhật bổ nhiệm cán bộ', 'Staff Assignments': 'Các bổ nhiệm cán bộ', 'Staff ID': 'Định danh cán bộ', 'Staff Management': 'Quản lý cán bộ', 'Staff Member Details updated': 'Cập nhật chi tiết cán bộ', 'Staff Member Details': 'Chi tiết cán bộ', 'Staff Member deleted': 'Xóa Cán bộ', 'Staff Record': 'Hồ sơ cán bộ', 'Staff Report': 'Báo cáo cán bộ', 'Staff Type Details': 'Chi tiết bộ phận nhân viên', 'Staff deleted': 'Xóa tên nhân viên', 'Staff member added': 'Thêm cán bộ', 'Staff with Contracts Expiring in the next Month': 'Cán bộ mà Hợp đồng hết hạn vào tháng tới', 'Staff': 'Cán bộ', 'Staff/Volunteer Record': 'Hồ sơ Cán bộ/Tình nguyện viên', 'Staff/Volunteer': 'Cán bộ/Tình nguyện viên', 'Start Date': 'Ngày bắt đầu', 'Start date': 'Ngày bắt đầu', 'Start of Period': 'Khởi đầu chu kỳ', 'Start': 'Bắt đầu', 'State / Province (Count)': 'Tỉnh / Thành phố (Số lượng)', 'State / Province': 'Tỉnh', 'Station Parameters': 'Thông số trạm', 'Statistics Parameter': 'Chỉ số thống kê', 'Statistics': 'Thống kê', 'Stats Group': 'Nhóm thống kê', 'Status Details': 'Chi tiết Tình trạng', 'Status Report': 'Báo cáo tình trạng ', 'Status Updated': 'Cập nhật Tình trạng', 'Status added': 'Thêm Tình trạng', 'Status deleted': 'Xóa Tình trạng', 'Status of adjustment': 'Điều chỉnh Tình trạng', 'Status of operations of the emergency department of this hospital.': 'Tình trạng hoạt động của phòng cấp cứu tại bệnh viện này', 'Status of security procedures/access restrictions in the hospital.': 'Trạng thái của các giới hạn thủ tục/truy nhập an ninh trong bệnh viện', 'Status of the operating rooms of this hospital.': 'Trạng thái các phòng bệnh trong bệnh viện này', 'Status updated': 'Cập nhật Tình trạng', 'Status': 'Tình trạng', 'Statuses': 'Các tình trạng', 'Stock Adjustment Details': 'Chi tiết điều chỉnh hàng lưu kho', 'Stock Adjustments': 'Điều chỉnh Hàng lưu kho', 'Stock Expires %(date)s': 'Hàng lưu kho hết hạn %(date)s', 'Stock added to Warehouse': 'Hàng hóa lưu kho được thêm vào Kho hàng', 'Stock in Warehouse': 'Hàng lưu kho trong Kho hàng', 'Stock removed from Warehouse': 'Hàng lưu kho được lấy ra khỏi Kho hàng', 'Stock': 'Hàng lưu kho', 'Stocks and relief items.': 'Kho hàng và hàng cứu trợ.', 'Stolen': 'Bị mất cắp', 'Store spreadsheets in the Eden database': 'Lưu trữ bảng tính trên cơ sở dữ liệu của Eden', 'Storm Force Wind': 'Sức mạnh Gió bão', 'Storm Surge': 'Bão biển dâng', 'Stowaway': 'Đi tàu lậu', 'Strategy': 'Chiến lược', 'Street Address': 'Địa chỉ', 'Street View': 'Xem kiểu đường phố', 'Strengthening Livelihoods': 'Cải thiện nguồn sinh kế', 'Strong Wind': 'Gió bão', 'Strong': 'Mạnh', 'Structural Safety': 'An toàn trong xây dựng', 'Style Field': 'Kiểu trường', 'Style Values': 'Kiểu giá trị', 'Style': 'Kiểu', 'Subject': 'Tiêu đề', 'Submission successful - please wait': 'Gửi thành công - vui lòng đợi', 'Submit Data': 'Gửi dữ liệu', 'Submit New (full form)': 'Gửi mới (mẫu đầy đủ)', 'Submit New (triage)': 'Gửi mới (cho nhóm 3 người)', 'Submit New': 'Gửi mới', 'Submit all': 'Gửi tất cả', 'Submit data to the region': 'Gửi dữ liệu cho vùng', 'Submit more': 'Gửi thêm', 'Submit online': 'Gửi qua mạng', 'Submit': 'Gửi', 'Submitted by': 'Được gửi bởi', 'Subscription deleted': 'Đã xóa đăng ký', 'Subscriptions': 'Quyên góp', 'Subsistence Cost': 'Mức sống tối thiểu', 'Successfully registered at the repository.': 'Đã đăng ký thành công vào hệ thống', 'Suggest not changing this field unless you know what you are doing.': 'Khuyến nghị bạn không thay đổi trường này khi chưa chắc chắn', 'Sum': 'Tổng', 'Summary Details': 'Thông tin tổng hợp', 'Summary by Question Type - (The fewer text questions the better the analysis can be)': 'Tổng hợp theo loại câu hỏi - (Phân tích dễ dàng hơn nếu có ít câu hỏi bằng chữ)', 'Summary of Completed Assessment Forms': 'Tổng hợp biểu mẫu đánh giá đã hoàn thành', 'Summary of Incoming Supplies': 'Tổng hợp mặt hàng đang đến', 'Summary of Releases': 'Tổng hợp bản tin báo chí', 'Summary': 'Tổng hợp', 'Supplier Details': 'Thông tin nhà cung cấp', 'Supplier added': 'Nhà cung cấp đã được thêm', 'Supplier deleted': 'Nhà cung cấp đã được xóa', 'Supplier updated': 'Nhà cung cấp đã được cập nhật', 'Supplier': 'Nhà cung cấp', 'Supplier/Donor': 'Nhà cung cấp/Nhà tài trợ', 'Suppliers': 'Nhà cung cấp', 'Supply Chain Management': 'Quản lý dây chuyền cung cấp', 'Support Request': 'Hỗ trợ yêu cầu', 'Support Requests': 'Yêu cầu hỗ trợ', 'Support': 'Trợ giúp', 'Surplus': 'Thặng dư', 'Survey Answer Details': 'Chi tiết trả lời câu hỏi khảo sát', 'Survey Answer added': 'Đã thêm trả lời khảo sát', 'Survey Name': 'Tên khảo sát', 'Survey Question Display Name': 'Tên trên bảng câu hỏi khảo sát', 'Survey Question updated': 'cập nhật câu hỏi khảo sát', 'Survey Section added': 'Đã thêm khu vực khảo sát', 'Survey Section updated': 'Cập nhật khu vực khảo sát', 'Survey Series added': 'Đã thêm chuỗi khảo sát', 'Survey Series deleted': 'Đã xóa chuỗi khảo sát', 'Survey Series updated': 'Đã cập nhật serie khảo sát', 'Survey Series': 'Chuỗi khảo sát', 'Survey Template added': 'Thêm mẫu Khảo sát', 'Survey Templates': 'Mẫu khảo sát', 'Swiss Francs': 'Frăng Thụy Sỹ', 'Switch to 3D': 'Chuyển sang 3D', 'Symbologies': 'Các biểu tượng', 'Symbology Details': 'Chi tiết biểu tượng', 'Symbology added': 'Thêm biểu tượng', 'Symbology deleted': 'Xóa biểu tượng', 'Symbology removed from Layer': 'Bỏ biểu tượng khỏi lớp', 'Symbology updated': 'Cập nhật biểu tượng', 'Symbology': 'Biểu tượng', 'Sync Conflicts': 'Xung đột khi đồng bộ hóa', 'Sync Now': 'Đồng bộ hóa ngay bây giờ', 'Sync Partners': 'Đối tác đồng bộ', 'Sync Schedule': 'Lịch đồng bộ', 'Sync process already started on ': 'Quá trinh đồng bộ đã bắt đầu lúc ', 'Synchronization Job': 'Chức năng Đồng bộ hóa', 'Synchronization Log': 'Danh mục Đồng bộ hóa', 'Synchronization Schedule': 'Kế hoạch Đồng bộ hóa', 'Synchronization Settings': 'Các cài đặt Đồng bộ hóa', 'Synchronization allows you to share data that you have with others and update your own database with latest data from other peers. This page provides you with information about how to use the synchronization features of Sahana Eden': 'Đồng bộ hóa cho phép bạn chia sẻ dữ liệu và cập nhật cơ sở dữ liệu với các máy khác.Trang này hường dẫn bạn cách sử dụng các tính năng đồng bộ của Sahana Eden', 'Synchronization currently active - refresh page to update status.': 'Đồng bộ hóa đang chạy - làm mới trang để cập nhật tình trạng', 'Synchronization mode': 'Chế độ đồng bộ hóa', 'Synchronization not configured.': 'Chưa thiết đặt đồng bộ hóa', 'Synchronization settings updated': 'Các cài đặt đồng bộ hóa được cập nhật', 'Synchronization': 'Đồng bộ hóa', 'Syncronization History': 'Lịch sử đồng bộ hóa', 'System keeps track of all Volunteers working in the disaster region. It captures not only the places where they are active, but also captures information on the range of services they are providing in each area.': 'Hệ thống theo sát quá trình làm việc của các tình nguyện viên trong khu vực thiên tai.Hệ thống nắm bắt không chỉ vị trí hoạt động mà còn cả thông tin về các dịch vụ đang cung cấp trong mỗi khu vực', 'Table': 'Bảng thông tin', 'THOUSAND_SEPARATOR': 'Định dạng hàng nghìn', 'TMS Layer': 'Lớp TMS', 'TO': 'TỚI', 'Table Permissions': 'Quyền truy cập bảng', 'Table name of the resource to synchronize': 'Bảng tên nguồn lực để đồng bộ hóa', 'Tablename': 'Tên bảng', 'Tags': 'Các bảng tên', 'Task Details': 'Các chi tiết nhiệm vụ', 'Task List': 'Danh sách Nhiệm vụ', 'Task added': 'Nhiệm vụ được thêm vào', 'Task deleted': 'Nhiệm vụ đã xóa', 'Task updated': 'Nhiệm vụ được cập nhật', 'Task': 'Nhiệm vụ', 'Tasks': 'Nhiệm vụ', 'Team Description': 'Mô tả về Đội/Nhóm', 'Team Details': 'Thông tin về Đội/Nhóm', 'Team ID': 'Mã Đội/Nhóm', 'Team Leader': 'Đội trưởng', 'Team Members': 'Thành viên Đội/Nhóm', 'Team Name': 'Tên Đội/Nhóm', 'Team Type': 'Loại hình Đội/Nhóm', 'Team added': 'Đội/ Nhóm đã thêm', 'Team deleted': 'Đội/ Nhóm đã xóa', 'Team updated': 'Đội/ Nhóm đã cập nhật', 'Team': 'Đội', 'Teams': 'Đội/Nhóm', 'Technical Disaster': 'Thảm họa liên quan đến kỹ thuật', 'Telephony': 'Đường điện thoại', 'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.': 'Yêu cầu GeoServer làm MetaTiling để giảm số nhãn bị lặp', 'Template Name': 'Tên Biểu mẫu', 'Template Section Details': 'Chi tiết Mục Biểu mẫu', 'Template Section added': 'Mục Biểu mẫu được thêm', 'Template Section deleted': 'Mục Biểu mẫu đã xóa', 'Template Section updated': 'Mục Biểu mẫu được cập nhật', 'Template Sections': 'Các Mục Biểu mẫu', 'Template Summary': 'Tóm tắt Biểu mẫu', 'Template': 'Biểu mẫu', 'Templates': 'Biểu mẫu', 'Term for the fifth-level within-country administrative division (e.g. a voting or postcode subdivision). This level is not often used.': 'Khái niệm về sự phân chia hành chính trong nước cấp thứ năm (ví dụ như sự phân chia bầu cử hay mã bưu điện). Mức này thường ít được dùng', 'Term for the fourth-level within-country administrative division (e.g. Village, Neighborhood or Precinct).': 'Khái niệm về sự phân chia hành chính cấp thứ tư bên trong quốc gia (ví dụ như làng, hàng xóm hay bản)', 'Term for the primary within-country administrative division (e.g. State or Province).': 'Khái niệm về sự phân chia hành chính trong nước cấp một (ví dụ như Bang hay Tỉnh)', 'Term for the secondary within-country administrative division (e.g. District or County).': 'Khái niệm về sự phân chia hành chính trong nước cấp thứ hai (ví dụ như quận huyện hay thị xã)', 'Term for the third-level within-country administrative division (e.g. City or Town).': 'Khái niệm về sự phân chia hành chính trong nước cấp thứ ba (ví dụ như thành phố hay thị trấn)', 'Terms of Service:': 'Điều khoản Dịch vụ:', 'Terrorism': 'Khủng bố', 'Tertiary Server (Optional)': 'Máy chủ Cấp ba (Tùy chọn)', 'Text Color for Text blocks': 'Màu vản bản cho khối văn bản', 'Text': 'Từ khóa', 'Thank you for your approval': 'Cảm ơn bạn vì sự phê duyệt', 'Thank you, the submission%(br)shas been declined': 'Cảm ơn bạn, lời đề nghị %(br)s đã bị từ chối', 'Thanks for your assistance': 'Cám ơn sự hỗ trợ của bạn', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1 == db.table2.field2" results in a SQL JOIN.': '"Câu hỏi" là một điều kiện có dạng "db.bảng1.trường1==\'giá trị\'". Bất kỳ cái gì có dạng "db.bảng1.trường1 == db.bảng2.trường2" đều có kết quả là một SQL THAM GIA.', 'The Area which this Site is located within.': 'Khu vực có chứa Địa điểm này', 'The Assessment Module stores assessment templates and allows responses to assessments for specific events to be collected and analyzed': 'Mô đun Khảo sát Đánh giá chứa các biểu mẫu khảo sát đánh giá và cho phép thu thập và phân tích các phản hồi đối với khảo sát đánh giá cho các sự kiện cụ thể', 'The Author of this Document (optional)': 'Tác giá của Tài liệu này (tùy chọn)', 'The Bin in which the Item is being stored (optional).': 'Ngăn/ Khu vực chứa hàng (tùy chọn)', 'The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'Địa điểm hiện tại của Người/ Nhóm, có thể là chung chung (dùng để Báo cáo) hoặc chính xác (dùng để thể hiện trên Bản đồ). Nhập các ký tự để tìm kiếm từ các địa điểm hiện có.', 'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.': 'Địa chỉ thư điện tử để gửi các yêu cầu phê duyệt (thông thường địa chỉ này là một nhóm các địa chỉ chứ không phải là các địa chỉ đơn lẻ). Nếu trường này bị bỏ trống thì các yêu cầu sẽ được tự động chấp thuận nếu miền phù hợp.', 'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.': 'Hệ thống Báo cáo Sự kiện cho phép ', 'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'Địa điểm xuất phát của Người, có thể chung chung (dùng cho Báo cáo) hay chính xác (dùng để thể hiện trên Bản đồ). Nhập một số ký tự để tìm kiếm từ các địa điểm đã có.', 'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'Địa điểm mà Người chuẩn bị đến, có thể là chung chung (dùng cho Báo cáo) hay chính xác (dùng để thể hiện trên Bản đồ). Nhập một số ký tự để tìm kiếm từ các địa điểm đã có.', 'The Media Library provides a catalog of digital media.': 'Thư viện Đa phương tiện cung cấp một danh mục các phương tiện số.', 'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.': 'Chức năng nhắn tin là trung tâm thông tin chính của hệ thống Sahana. Chức năng này được sử dụng để gửi cảnh báo và/ hoặc tin nhắn dạng SMS và email tới các nhóm và cá nhân trước, trong và sau thảm họa.', 'The Organization Registry keeps track of all the relief organizations working in the area.': 'Cơ quan đăng ký Tổ chức theo dõi tất cả các tổ chức cứu trợ đang hoạt động trong khu vực.', 'The Organization this record is associated with.': 'Tổ chức được ghi liên kết với.', 'The Role this person plays within this hospital.': 'Vai trò của người này trong bệnh viện', 'The Tracking Number %s is already used by %s.': 'Số Theo dõi %s đã được sử dụng bởi %s.', 'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.': 'URL cho trang GetCapabilities của một Dịch vụ Bản đồ Mạng (WMS) có các lớp mà bạn muốn có thông qua bảng Trình duyệt trên Bản đồ.', 'The URL of your web gateway without the post parameters': 'URL của cổng mạng của bạn mà không có các thông số điện tín', 'The URL to access the service.': 'URL để truy cập dịch vụ.', 'The answers are missing': 'Chưa có các câu trả lời', 'The area is': 'Khu vực là', 'The attribute which is used for the title of popups.': 'Thuộc tính được sử dụng cho tiêu đề của các cửa sổ tự động hiển thị.', 'The attribute within the KML which is used for the title of popups.': 'Thuộc tính trong KML được sử dụng cho tiêu đề của các cửa sổ tự động hiển thị.', 'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)': '(Các) thuộc tính trong KML được sử dụng cho phần nội dung của các cửa sổ tự động hiển thị. (Sử dụng dấu cách giữa các thuộc tính)', 'The body height (crown to heel) in cm.': 'Chiều cao của phần thân (từ đầu đến chân) tính theo đơn vị cm.', 'The contact person for this organization.': 'Người chịu trách nhiệm liên lạc cho tổ chức này', 'The facility where this position is based.': 'Bộ phận mà vị trí này trực thuộc', 'The first or only name of the person (mandatory).': 'Tên (bắt buộc phải điền).', 'The following %s have been added': '%s dưới đây đã được thêm vào', 'The following %s have been updated': '%s dưới đây đã được cập nhật', 'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.': 'Dạng URL là http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.', 'The hospital this record is associated with.': 'Bệnh viện lưu hồ sơ này', 'The language you wish the site to be displayed in.': 'Ngôn ngữ bạn muốn đê hiển thị trên trang web', 'The length is': 'Chiều dài là', 'The list of Brands are maintained by the Administrators.': 'Danh sách các Chi nhánh do Những người quản lý giữ.', 'The list of Catalogs are maintained by the Administrators.': 'Danh sách các Danh mục do Những người quản lý giữ.', 'The list of Item categories are maintained by the Administrators.': 'Danh sách category hàng hóa được quản trị viên quản lý', 'The map will be displayed initially with this latitude at the center.': 'Bản đồ sẽ được thể hiện đầu tiên với vĩ độ này tại địa điểm trung tâm.', 'The map will be displayed initially with this longitude at the center.': 'Bản đồ sẽ được thể hiện đầu tiên với kinh độ này tại địa điểm trung tâm.', 'The minimum number of features to form a cluster.': 'Các đặc điểm tối thiểu để hình thành một nhóm.', 'The name to be used when calling for or directly addressing the person (optional).': 'Tên được sử dụng khi gọi người này (tùy chọn).', 'The number geographical units that may be part of the aggregation': 'Số đơn vị địa lý có thể là một phần của tổ hợp', 'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item': 'Số Đơn vị Đo của Các mặt hàng thay thế bằng với Một Đơn vị Đo của Mặt hàng đó', 'The number of aggregated records': 'Số bản lưu đã được tổng hợp', 'The number of pixels apart that features need to be before they are clustered.': 'Số điểm ảnh ngoài mà các đặc điểm cần trước khi được nhóm', 'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.': 'Số lớp để tải về quanh bản đồ được thể hiện. Không có nghĩa là trang đầu tiên tải nhanh hơn, các con số cao hơn nghĩa là việc quét sau nhanh hơn.', 'The person reporting about the missing person.': 'Người báo cáo về người mất tích', 'The post variable containing the phone number': 'Vị trí có thể thay đổi đang chứa số điện thoại', 'The post variable on the URL used for sending messages': 'Vị trí có thể thay đổi trên URL được dùng để gửi tin nhắn', 'The post variables other than the ones containing the message and the phone number': 'Vị trí có thể thay đổi khác với các vị trí đang chứa các tin nhắn và số điện thoại', 'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows': 'Chuỗi cổng kết nối mô đem - /dev/ttyUSB0, v.v. trên linux và com1, com2, v.v. trên Windows', 'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.': 'Máy chủ không nhận được một phản hồi kịp thời từ một máy chủ khác khi đang truy cập để hoàn tất yêu cầu bằng bộ trình duyệt.', 'The server received an incorrect response from another server that it was accessing to fill the request by the browser.': 'Máy chủ đã nhận được một phản hồi sai từ một máy chủ khác khi đang truy cập để hoàn tất yêu cầu bằng bộ trình duyệt.', 'The simple policy allows anonymous users to Read & registered users to Edit. The full security policy allows the administrator to set permissions on individual tables or records - see models/zzz.py.': 'Các chính sách đơn giản cho phép người dùng ẩn danh đọc và đăng ký để chỉnh sửa. Các chính sách bảo mật đầy đủ cho phép quản trị viên thiết lập phân quyền trên các bảng cá nhân hay - xem mô hình / zzz.py.', 'The staff responsibile for Facilities can make Requests for assistance. Commitments can be made against these Requests however the requests remain open until the requestor confirms that the request is complete.': 'Cán bộ chịu trách nhiệm về Các cơ sở có thể đưa ra Yêu cầu trợ giúp. Các cam kết có thể được đưa ra đối với những Yêu cầu này tuy nhiên các yêu cầu này phải để mở cho đến khi người yêu cầu xác nhận yêu cầu đã hoàn tất.', 'The synchronization module allows the synchronization of data resources between Sahana Eden instances.': 'Mô đun đồng bộ hóa cho phép đồng bộ hóa nguồn dữ liệu giữa các phiên bản Sahana Eden.', 'The system supports 2 projections by default:': 'Hệ thống hỗ trợ 2 dự thảo bởi chế độ mặc định:', 'The token associated with this application on': 'Mã thông báo liên quan đến ứng dụng này trên', 'The unique identifier which identifies this instance to other instances.': 'Yếu tố khác biệt phân biệt lần này với các lần khác', 'The uploaded Form is unreadable, please do manual data entry.': 'Mẫu được tải không thể đọc được, vui lòng nhập dữ liệu thủ công', 'The weight in kg.': 'Trọng lượng tính theo đơn vị kg.', 'Theme Data deleted': 'Dữ liệu Chủ đề đã xóa', 'Theme Data updated': 'Dữ liệu Chủ đề đã cập nhật', 'Theme Data': 'Dữ liệu Chủ đề', 'Theme Details': 'Chi tiết Chủ đề', 'Theme Layer': 'Lớp Chủ đề', 'Theme Sectors': 'Lĩnh vực của Chủ đề', 'Theme added': 'Chủ đề được thêm vào', 'Theme deleted': 'Chủ đề đã xóa', 'Theme removed': 'Chủ đề đã loại bỏ', 'Theme updated': 'Chủ đề đã cập nhật', 'Theme': 'Chủ đề', 'Themes': 'Chủ đề', 'There are multiple records at this location': 'Có nhiều bản lưu tại địa điểm này', 'There is a problem with your file.': 'Có vấn đề với tệp tin của bạn.', 'There is insufficient data to draw a chart from the questions selected': 'Không có đủ dữ liệu để vẽ biểu đồ từ câu hỏi đã chọn', 'There is no address for this person yet. Add new address.': 'Chưa có địa chỉ về người này. Hãy thêm địa chỉ.', 'There was a problem, sorry, please try again later.': 'Đã có vấn đề, xin lỗi, vui lòng thử lại sau.', 'These are settings for Inbound Mail.': 'Đây là những cài đặt cho Hộp thư đến.', 'These are the Incident Categories visible to normal End-Users': 'Đây là những Nhóm Sự kiện hiển thị cho Người dùng Cuối cùng thông thường.', 'These are the filters being used by the search.': 'Đây là những bộ lọc sử dụng cho tìm kiếm.', 'These need to be added in Decimal Degrees.': 'Cần thêm vào trong Số các chữ số thập phân.', 'They': 'Người ta', 'This Group has no Members yet': 'Hiện không có hội viên nào được đăng ký', 'This Team has no Members yet': 'Hiện không có hội viên nào được đăng ký', 'This adjustment has already been closed.': 'Điều chỉnh này đã đóng.', 'This email-address is already registered.': 'Địa chỉ email này đã được đăng ký.', 'This form allows the administrator to remove a duplicate location.': 'Mẫu này cho phép quản trị viên xóa bỏ các địa điểm trùng', 'This is appropriate if this level is under construction. To prevent accidental modification after this level is complete, this can be set to False.': 'Lựa chọn này phù hợp nếu cấp độ này đang được xây dựng. Để không vô tình chỉnh sửa sau khi hoàn tất cấp độ này, lựa chọn này có thể được đặt ở giá trị Sai.', 'This is normally edited using the Widget in the Style Tab in the Layer Properties on the Map.': 'Điều này thông thường được chỉnh sửa sử dụng Công cụ trong Mục Kiểu dáng trong Các đặc trưng của Lớp trên Bản đồ.', 'This is the full name of the language and will be displayed to the user when selecting the template language.': 'Đây là tên đầy đủ của ngôn ngữ và sẽ được thể hiện với người dùng khi lựa chọn ngôn ngữ.', 'This is the name of the parsing function used as a workflow.': 'Đây là tên của chức năng phân tích cú pháp được sử dụng như là một chuỗi công việc.', 'This is the name of the username for the Inbound Message Source.': 'Đây là tên của người dùng cho Nguồn tin nhắn đến.', 'This is the short code of the language and will be used as the name of the file. This should be the ISO 639 code.': 'Đây là mã ngắn gọn của ngôn ngữ và sẽ được sử dụng làm tên của tệp tin. Mã này nên theo mã ISO 639.', 'This is the way to transfer data between machines as it maintains referential integrity.': 'Đây là cách truyền dữ liệu giữa các máy vì nó bảo toàn tham chiếu', 'This job has already been finished successfully.': 'Công việc đã được thực hiện thành công.', 'This level is not open for editing.': 'Cấp độ này không cho phép chỉnh sửa.', 'This might be due to a temporary overloading or maintenance of the server.': 'Điều này có lẽ là do máy chủ đang quá tải hoặc đang được bảo trì.', 'This module allows Warehouse Stock to be managed, requested & shipped between the Warehouses and Other Inventories': 'Chức năng này giúp việc quản lý, đặt yêu cầu và di chuyển hàng lưu trữ giữa các kho hàng và các vị trí lưu trữ khác trong kho', 'This resource cannot be displayed on the map!': 'Nguồn lực này không thể hiện trên bản đồ!', 'This resource is already configured for this repository': 'Nguồn lực này đã được thiết lập cấu hình cho kho hàng này', 'This role can not be assigned to users.': 'Chức năng không thể cấp cho người sử dụng', 'This screen allows you to upload a collection of photos to the server.': 'Màn hình này cho phép bạn đăng tải một bộ sưu tập hình ảnh lên máy chủ.', 'This shipment contains %s items': 'Lô hàng này chứa %s mặt hàng', 'This shipment contains one item': 'Lô hàng này chứa một mặt hàng', 'This shipment has already been received & subsequently canceled.': 'Lô hàng này đã được nhận & về sau bị hủy.', 'This shipment has already been received.': 'Lô hàng này đã được nhận.', 'This shipment has already been sent.': 'Lô hàng này đã được gửi.', 'This shipment has not been received - it has NOT been canceled because can still be edited.': 'Lô hàng này chưa được nhận - KHÔNG bị hủy vì vẫn có thể điều chỉnh.', 'This shipment has not been returned.': 'Lô hàng này chưa được trả lại.', 'This shipment has not been sent - it cannot be returned because it can still be edited.': 'Lô hàng này chưa được gửi - không thể trả lại vì vẫn có thể điều chỉnh.', 'This shipment has not been sent - it has NOT been canceled because can still be edited.': 'Lô hàng này chưa được gửi - KHÔNG bị hủy vì vẫn có thể điều chỉnh.', 'This should be an export service URL': 'Có thể đây là một dịch vụ xuất URL', 'Thunderstorm': 'Giông bão', 'Thursday': 'Thứ Năm', 'Ticket Details': 'Chi tiết Ticket', 'Ticket Viewer': 'Người kiểm tra vé', 'Ticket deleted': 'Đã xóa Ticket', 'Ticket': 'Vé', 'Tickets': 'Vé', 'Tiled': 'Lợp', 'Time Actual': 'Thời gian thực tế', 'Time Estimate': 'Ước lượng thời gian', 'Time Estimated': 'Thời gian dự đoán', 'Time Frame': 'Khung thời gian', 'Time In': 'Thời điểm vào', 'Time Log Deleted': 'Lịch trình thời gian đã xóa', 'Time Log Updated': 'Lịch trình thời gian đã cập nhật', 'Time Log': 'Lịch trình thời gian', 'Time Logged': 'Thời gian truy nhập', 'Time Out': 'Thời gian thoát', 'Time Question': 'Câu hỏi thời gian', 'Time Taken': 'Thời gian đã dùng', 'Time of Request': 'Thời gian yêu cầu', 'Time': 'Thời gian', 'Timeline': 'Nhật ký', 'Title to show for the Web Map Service panel in the Tools panel.': 'Tiêu đề thể hiện với bảng Dịch vụ Bản đồ Mạng trong bảng Công cụ.', 'Title': 'Tiêu đề', 'To Organization': 'Tới Tổ chức', 'To Person': 'Tới Người', 'To Warehouse/Facility/Office': 'Tới Nhà kho/Bộ phận/Văn phòng', 'To begin the sync process, click the button on the right => ': 'Nhấp chuột vào nút bên phải để kích hoạt quá trình đồng bộ', 'To edit OpenStreetMap, you need to edit the OpenStreetMap settings in your Map Config': 'Để chỉnh sửa OpenStreetMap, bạn cần chỉnh sửa cài đặt OpenStreetMap trong cài đặt cấu hình bản đồ của bạn.', 'To variable': 'Tới biến số', 'To': 'Tới', 'Tools': 'Công cụ', 'Tornado': 'Lốc xoáy', 'Total # of Target Beneficiaries': 'Tổng số # đối tượng hưởng lợi', 'Total Annual Budget': 'Tổng ngân sách hàng năm', 'Total Cost per Megabyte': 'Tổng chi phí cho mỗi Megabyte', 'Total Cost': 'Giá tổng', 'Total Funding Amount': 'Tổng số tiền hỗ trợ', 'Total Locations': 'Tổng các vị trí', 'Total Persons': 'Tổng số người', 'Total Recurring Costs': 'Tổng chi phí định kỳ', 'Total Value': 'Giá trị tổng', 'Total number of beds in this hospital. Automatically updated from daily reports.': 'Tổng số giường bệnh trong bệnh viện này. Tự động cập nhật từ các báo cáo hàng ngày.', 'Total number of houses in the area': 'Tổng số nóc nhà trong khu vực', 'Total number of schools in affected area': 'Số lượng trường học trong khu vực chịu ảnh hưởng thiên tai', 'Total': 'Tổng', 'Tourist Group': 'Nhóm khách du lịch', 'Tracing': 'Đang tìm kiếm', 'Track Shipment': 'Theo dõi lô hàng', 'Track with this Person?': 'Theo dõi Người này?', 'Track': 'Dấu viết', 'Trackable': 'Có thể theo dõi được', 'Tracking and analysis of Projects and Activities.': 'Giám sát và phân tích Dự án và Hoạt động', 'Traffic Report': 'Báo cáo giao thông', 'Training (Count)': 'Tập huấn (Số lượng)', 'Training Course Catalog': 'Danh mục khóa tập huấn', 'Training Courses': 'Khóa tập huấn', 'Training Details': 'Chi tiết về khóa tập huấn', 'Training Event Details': 'Chi tiết về khóa tập huấn', 'Training Event added': 'Khóa tập huấn được thêm vào', 'Training Event deleted': 'Khóa tập huấn đã xóa', 'Training Event updated': 'Khóa tập huấn đã cập nhật', 'Training Event': 'Khóa tập huấn', 'Training Events': 'Khóa tập huấn', 'Training Facility': 'Đơn vị đào tạo', 'Training Hours (Month)': 'Thời gian tập huấn (Tháng)', 'Training Hours (Year)': 'Thời gian tập huấn (Năm)', 'Training Report': 'Tập huấn', 'Training added': 'Tập huấn được thêm vào', 'Training deleted': 'Tập huấn đã xóa', 'Training updated': 'Tập huấn đã cập nhật', 'Training': 'Tập huấn', 'Trainings': 'Tập huấn', 'Transfer Ownership To (Organization/Branch)': 'Chuyển Quyền sở hữu cho (Tổ chức/ Chi nhánh)', 'Transfer Ownership': 'Chuyển Quyền sở hữu', 'Transfer': 'Chuyển giao', 'Transit Status': 'Tình trạng chuyển tiếp', 'Transit': 'Chuyển tiếp', 'Transitional Shelter Construction': 'Xây dựng nhà tạm', 'Translate': 'Dịch', 'Translated File': 'File được dịch', 'Translation Functionality': 'Chức năng Dịch', 'Translation': 'Dịch', 'Transparent?': 'Có minh bạch không?', 'Transportation Required': 'Cần vận chuyển', 'Transported By': 'Đơn vị vận chuyển', 'Tropical Storm': 'Bão nhiệt đới', 'Tropo Messaging Token': 'Mã thông báo tin nhắn Tropo', 'Tropo settings updated': 'Cài đặt Tropo được cập nhật', 'Truck': 'Xe tải', 'Try checking the URL for errors, maybe it was mistyped.': 'Kiểm tra đường dẫn URL xem có lỗi không, có thể đường dẫn bị gõ sai.', 'Try hitting refresh/reload button or trying the URL from the address bar again.': 'Thử nhấn nút làm lại/tải lại hoặc thử lại URL từ trên thanh địa chỉ.', 'Try refreshing the page or hitting the back button on your browser.': 'Thử tải lại trang hoặc nhấn nút trở lại trên trình duyệt của bạn.', 'Tsunami': 'Sóng thần', 'Twilio SMS InBox': 'Hộp thư đến SMS twilio', 'Twilio SMS Inbox empty. ': 'Hộp thư đến Twilio trống.', 'Twilio SMS Inbox': 'Hộp thư đến Twilio', 'Twilio SMS Settings': 'Cài đặt SMS twilio', 'Twilio SMS deleted': 'Tin nhắn Twilio đã xóa', 'Twilio SMS updated': 'Tin nhắn Twilio được cập nhật', 'Twilio SMS': 'Tin nhắn Twilio', 'Twilio Setting Details': 'Chi tiết cài đặt Twilio', 'Twilio Setting added': 'Cài đặt Twilio được thêm vào', 'Twilio Setting deleted': 'Cài đặt Twilio đã xóa', 'Twilio Settings': 'Cài đặt Twilio', 'Twilio settings updated': 'Cài đặt Twilio được cập nhật', 'Twitter ID or #hashtag': 'Tên đăng nhập Twitter hay từ hay chuỗi các ký tự bắt đầu bằng dấu # (#hashtag)', 'Twitter Settings': 'Cài đặt Twitter', 'Type of Transport': 'Loại phương tiện giao thông', 'Type of adjustment': 'Loại hình điều chỉnh', 'Type': 'Đối tượng', 'Types of Activities': 'Các loại hình Hoạt động', 'Types': 'Các loại', 'UPDATE': 'CẬP NHẬT', 'URL for the twilio API.': 'URL cho twilio API.', 'URL of the default proxy server to connect to remote repositories (if required). If only some of the repositories require the use of a proxy server, you can configure this in the respective repository configurations.': 'URL của máy chủ trung chuyển mặc định để kết nối với các kho hàng ở khu vực xa (nếu cần thiết). Nếu chỉ có một số kho hàng cần một máy chủ trung chuyển sử dụng thì bạn có thể tạo cấu hình cho máy này tương ứng với cấu hình của kho hàng.', 'URL of the proxy server to connect to the repository (leave empty for default proxy)': 'URL của máy chủ trung chuyển để kết nối với kho hàng (để trống với phần ủy nhiệm mặc định)', 'URL to a Google Calendar to display on the project timeline.': 'URL đến Lịch Google để thể hiện dòng thời gian của dự án.', 'UTC Offset': 'Độ xê dịch giờ quốc tế', 'Un-Repairable': 'Không-Sửa chữa được', 'Unable to find sheet %(sheet_name)s in uploaded spreadsheet': 'Không thể tìm thấy bảng %(sheet_name)s trong bảng tính đã đăng tải', 'Unable to open spreadsheet': 'Không thể mở được bảng tính', 'Unable to parse CSV file or file contains invalid data': 'Không thể cài đặt cú pháp cho file CSV hoặc file chức dữ liệu không hợp lệ', 'Unable to parse CSV file!': 'Không thể đọc file CSV', 'Unassigned': 'Chưa được điều động', 'Under 5': 'Dưới 5', 'Under which condition a local record shall be updated if it also has been modified locally since the last synchronization': 'Trong điều kiện nào thì một bản lưu nội bộ sẽ được cập nhật nếu bản lưu này cũng được điều chỉnh trong nội bộ kể từ lần đồng bộ hóa cuối cùng', 'Under which conditions local records shall be updated': 'Trong những điều kiện nào thì các bản lưu nội bộ sẽ được cập nhật', 'Unidentified': 'Không nhận dạng được', 'Unique Locations': 'Các địa điểm duy nhất', 'Unique identifier which THIS repository identifies itself with when sending synchronization requests.': 'Ký hiệu nhận dạng duy nhất để kho hàng NÀY nhận dạng chính nó khi gửi các đề nghị đồng bộ hóa.', 'Unit Cost': 'Đơn giá', 'Unit Short Code for e.g. m for meter.': 'Viết tắt các đơn vị, ví dụ m viết tắt của mét', 'Unit Value': 'Thành tiền', 'Unit added': 'Đã thêm đơn vị', 'Unit of Measure': 'Đơn vị đo', 'Unit updated': 'Đơn vị được cập nhật', 'Unit': 'Đơn vị', 'United States Dollars': 'Đô La Mỹ', 'Units': 'Các đơn vị', 'University / College': 'Đại học / Cao đẳng', 'Unknown Locations': 'Địa điểm không xác định', 'Unknown question code': 'Mã câu hỏi chưa được biết đến', 'Unknown': 'Chưa xác định', 'Unloading': 'Đang gỡ ra', 'Unselect to disable the modem': 'Thôi chọn để tạm ngừng hoạt động của mô đem', 'Unselect to disable this API service': 'Thôi chọn để tạm ngừng dịch vụ API này', 'Unselect to disable this SMTP service': 'Thôi chọn để tạm ngừng dịch vụ SMTP này', 'Unsent': 'Chưa được gửi', 'Unspecified': 'Không rõ', 'Unsupported data format': 'Định dạng dữ liệu không được hỗ trợ', 'Unsupported method': 'Phương pháp không được hỗ trợ', 'Update Map': 'Cập nhật Bản đồ', 'Update Master file': 'Cập nhật tệp tin Gốc', 'Update Method': 'Cập nhật Phương pháp', 'Update Policy': 'Cập nhật Chính sách', 'Update Report': 'Cập nhật báo cáo', 'Update Request': 'Cập nhật Yêu cầu', 'Update Service Profile': 'Cập nhật hồ sơ đăng ký dịch vụ', 'Update Status': 'Cập nhật Tình trạng', 'Update Task Status': 'Cập nhật tình trạng công việc ', 'Update this entry': 'Cập nhật hồ sơ này', 'Updated By': 'Được cập nhật bởi', 'Upload .CSV': 'Tải lên .CSV', 'Upload Completed Assessment Form': 'Tải lên Mẫu đánh giá đã hoàn thiện', 'Upload Format': 'Tải định dạng', 'Upload Photos': 'Tải lên Hình ảnh', 'Upload Scanned OCR Form': 'Tải mẫu scan OCR', 'Upload Web2py portable build as a zip file': 'Tải lên Web2py như một tệp nén', 'Upload a Question List import file': 'Tải lên một tệp tin được chiết xuất chứa Danh sách các câu hỏi', 'Upload a Spreadsheet': 'Tải một bảng tính lên', 'Upload a text file containing new-line separated strings:': 'Tải lên một tệp tin văn bản chứa các chuỗi được tách thành dòng mới:', 'Upload an Assessment Template import file': 'Tải lên một tệp tin được chiết xuất chứa Biểu mẫu Khảo sát đánh giá', 'Upload an image file (png or jpeg), max. 400x400 pixels!': 'Tải lên file hình ảnh (png hoặc jpeg) có độ phân giải tối đa là 400x400 điểm ảnh!', 'Upload demographic data': 'Tải lên dữ liệu nhân khẩu', 'Upload file': 'Tải file', 'Upload indicators': 'Tải lên các chỉ số', 'Upload successful': 'Tải lên thành công', 'Upload the (completely or partially) translated csv file': 'Tải lên (toàn bộ hoặc một phần) tệp tin csv đã được chuyển ngữ', 'Upload the Completed Assessment Form': 'Tải lên Mẫu đánh giá', 'Upload translated files': 'Tải file được dịch', 'Upload': 'Tải lên', 'Uploaded PDF file has more/less number of page(s) than required. Check if you have provided appropriate revision for your Form as well as check the Form contains appropriate number of pages.': '', 'Uploaded file is not a PDF file. Provide a Form in valid PDF Format.': 'File được tải không phải định dạng PDF. Cung cấp mẫu ở định dạng PDF', 'Uploading report details': 'Đang tải lên các chi tiết báo cáo', 'Urban Fire': 'Cháy trong thành phố', 'Urban Risk & Planning': 'Rủi ro thảm học đô thị & Lập kế hoạch', 'Urdu': 'Ngôn ngữ Urdu(một trong hai ngôn ngữ chính thức tại Pakistan', 'Urgent': 'Khẩn cấp', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Sử dụng (...)&(...) cho VÀ, (...)|(...) cho HOẶC, và ~(...) cho KHÔNG để tạo ra những câu hỏi phức tạp hơn.', 'Use Geocoder for address lookups?': 'Sử dụng Geocoder để tìm kiếm địa chỉ?', 'Use Translation Functionality': 'Sử dụng Chức năng Dịch', 'Use decimal': 'Sử dụng dấu phẩy', 'Use default': 'Sử dụng cài đặt mặc định', 'Use deg, min, sec': 'Sử dụng độ, phút, giây', 'Use these links to download data that is currently in the database.': 'Dùng liên kết này để tải dữ liệu hiện có trên cơ sở dữ liệu xuống', 'Use this space to add a description about the Bin Type.': 'Thêm thông tin mô tả loại Bin ở đây', 'Use this space to add a description about the warehouse/site.': 'Thêm mô tả nhà kho/site ở đây', 'Use this space to add additional comments and notes about the Site/Warehouse.': 'Viết bình luận và ghi chú về site/nhà kho ở đây', 'Use this to set the starting location for the Location Selector.': 'Sử dụng cái này để thiết lập địa điểm xuất phát cho Bộ chọn lọc Địa điểm.', 'Used in onHover Tooltip & Cluster Popups to differentiate between types.': 'Đã dùng trong onHover Tooltip & Cluster Popups để phân biệt các loại', 'Used to build onHover Tooltip & 1st field also used in Cluster Popups to differentiate between records.': 'Đã dùng để xây dựng onHover Tooltip & trường thứ nhất cũng đã sử dụng trong Cluster Popups phân biệt các hồ sơ.', 'Used to check that latitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Được sử dụng để kiểm tra vĩ độ của những địa điểm được nhập có chính xác không. Có thể được sử dụng để lọc danh sách các nguồn lực có địa điểm.', 'Used to check that longitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Được sử dụng để kiểm tra kinh độ của những địa điểm được nhập có chính xác không. Có thể được sử dụng để lọc danh sách các nguồn lực có địa điểm.', 'User Account has been Approved': 'Tài khoản của người sử dụng đã được duyệt', 'User Account has been Disabled': 'Tài khoản của người sử dụng đã bị ngưng hoạt động', 'User Account': 'Tài khoản của người sử dụng', 'User Details': 'Thông tin về người sử dụng', 'User Guidelines Synchronization': 'Đồng bộ hóa Hướng dẫn cho Người sử dụng', 'User Management': 'Quản lý người dùng', 'User Profile': 'Hồ sơ người sử dụng', 'User Requests': 'Yêu cầu của người dùng', 'User Roles': 'Vai trò của người sử dụng', 'User Updated': 'Đã cập nhât người dùng', 'User added to Role': 'Người sử dụng được thêm vào chức năng', 'User added': 'Người sử dụng được thêm vào', 'User deleted': 'Người sử dụng đã xóa', 'User has been (re)linked to Person and Human Resource record': 'Người sử dụng đã được liên kết thành công', 'User updated': 'Người sử dụng được cập nhật', 'User with Role': 'Người sử dụng có chức năng này', 'User': 'Người sử dụng', 'Username to use for authentication at the remote site.': 'Tên người sử dụng dùng để xác nhận tại khu vực ở xa.', 'Username': 'Tên người sử dụng', 'Users in my Organizations': 'Những người dùng trong tổ chức của tôi', 'Users removed': 'Xóa người dùng', 'Users with this Role': 'Những người sử dụng với chức năng này', 'Users': 'Danh sách người dùng', 'Uses the REST Query Format defined in': 'Sử dụng Định dạng câu hỏi REST đã được xác định trong', 'Ushahidi Import': 'Nhập Ushahidi', 'Utilization Details': 'Chi tiết về Việc sử dụng', 'Utilization Report': 'Báo cáo quá trình sử dụng', 'VCA REPORTS': 'BÁO CÁO VCA', 'VCA Report': 'Báo cáo VCA', 'VOLUNTEERS': 'TÌNH NGUYỆN VIÊN', 'Valid From': 'Có hiệu lực từ', 'Valid Until': 'Có hiệu lực đến', 'Valid': 'Hiệu lực', 'Validation error': 'Lỗi xác thực', 'Value per Pack': 'Giá trị mỗi gói', 'Value': 'Giá trị', 'Vector Control': 'Kiểm soát vectơ', 'Vehicle Assignment updated': 'Việc điệu động xe được cập nhật', 'Vehicle Assignments': 'Các việc điều động xe', 'Vehicle Crime': 'Tội phạm liên quan đến xe', 'Vehicle Details': 'Thông tin về xe', 'Vehicle Plate Number': 'Biển số xe', 'Vehicle Types': 'Loại phương tiện di chuyển', 'Vehicle assigned': 'Xe được điều động', 'Vehicle unassigned': 'Xe chưa được điều động', 'Vehicle': 'Xe', 'Vehicles': 'Phương tiện di chuyển', 'Venue': 'Địa điểm tổ chức', 'Verified': 'Đã được thẩm định', 'Verified?': 'Đã được thẩm định?', 'Verify Password': 'Kiểm tra mật khẩu', 'Verify password': 'Kiểm tra mật khẩu', 'Version': 'Phiên bản', 'Very Good': 'Rất tốt', 'Very Strong': 'Rất mạnh', 'Vietnamese': 'Tiếng Việt', 'View Alerts received using either Email or SMS': 'Xem các Cảnh báo nhận được sử dụng thư điện tử hoặc tin nhắn', 'View All': 'Xem tất cả', 'View Email InBox': 'Xem hộp thư điện tử đến', 'View Email Settings': 'Xem cài đặt thư điện tử', 'View Error Tickets': 'Xem các vé lỗi', 'View Fullscreen Map': 'Xem bản đồ toàn màn hình', 'View Items': 'Xem các mặt hàng', 'View Location Details': 'Xem chi tiết vị trí', 'View Outbox': 'Xem hộp thư điện tử đi', 'View Reports': 'Xem báo cáo', 'View Requests for Aid': 'Xem Yêu cầu viện trợ', 'View Settings': 'Xem cài đặt', 'View Test Result Reports': 'Xem báo cáo kết quả kiểm tra', 'View Translation Percentage': 'Xem tỷ lệ phần trăm chuyển đổi', 'View Twilio SMS': 'Xem tin nhắn văn bản Twilio', 'View Twilio Settings': 'Xem các Cài đặt Twilio', 'View all log entries': 'Xem toàn bộ nhật ký ghi chép', 'View as Pages': 'Xem từng trang', 'View full size': 'Xem kích thước đầy đủ', 'View log entries per repository': 'Xem ghi chép nhật ký theo kho hàng', 'View on Map': 'Xem trên bản đồ', 'View or update the status of a hospital.': 'Xem hoặc cập nhật trạng thái của một bệnh viện', 'View the hospitals on a map.': 'Hiển thị bệnh viện trên bản đồ', 'View the module-wise percentage of translated strings': 'Xem phần trăm ', 'View': 'Xem', 'View/Edit the Database directly': 'Trực tiếp Xem/Sửa Cơ sở dữ liệu', 'Village / Suburb': 'Thôn / Xóm', 'Violence Prevention': 'Phòng ngừa bạo lực', 'Volcanic Ash Cloud': 'Mây bụi núi lửa', 'Volcanic Event': 'Sự kiện phun trào núi lửa', 'Volcano': 'Núi lửa', 'Volume (m3)': 'Thể tích (m3)', 'Volunteer Cluster Position added': 'Vị trí Nhóm Tình nguyện viên được thêm vào', 'Volunteer Cluster Position deleted': 'Vị trí Nhóm Tình nguyện viên đã xóa', 'Volunteer Cluster Position updated': 'Vị trí Nhóm Tình nguyện viên được cập nhật', 'Volunteer Cluster Position': 'Vị trí Nhóm Tình nguyện viên', 'Volunteer Cluster Type added': 'Mô hình Nhóm Tình nguyện viên được thêm vào', 'Volunteer Cluster Type deleted': 'Mô hình Nhóm Tình nguyện viên đã xóa', 'Volunteer Cluster Type updated': 'Mô hình Nhóm Tình nguyện viên được cập nhật', 'Volunteer Cluster Type': 'Mô hình Nhóm Tình nguyện viên', 'Volunteer Cluster added': 'Nhóm Tình nguyện viên được thêm vào', 'Volunteer Cluster deleted': 'Nhóm Tình nguyện viên đã xóa', 'Volunteer Cluster updated': 'Nhóm Tình nguyện viên được cập nhật', 'Volunteer Cluster': 'Nhóm Tình nguyện viên', 'Volunteer Data': 'Dữ liệu tình nguyện viên', 'Volunteer Details updated': 'Thông tin về Tình nguyện viên được cập nhật', 'Volunteer Details': 'Thông tin về Tình nguyện viên', 'Volunteer Management': 'Quản lý tình nguyện viên', 'Volunteer Project': 'Dự án tình nguyện', 'Volunteer Record': 'Hồ sơ TNV', 'Volunteer Registration': 'Đăng ký tình nguyện viên', 'Volunteer Registrations': 'Đăng ksy tình nguyện viên', 'Volunteer Report': 'Tình nguyện viên', 'Volunteer Request': 'Đề nghị Tình nguyện viên', 'Volunteer Role (Count)': 'Chức năng nhiệm vụ TNV (Số lượng)', 'Volunteer Role Catalog': 'Danh mục về Vai trò của Tình nguyện viên', 'Volunteer Role Catalogue': 'Danh mục vai trò TNV', 'Volunteer Role Details': 'Chi tiết về Vai trò của Tình nguyện viên', 'Volunteer Role added': 'Vai trò của Tình nguyện viên được thêm vào', 'Volunteer Role deleted': 'Vai trò của Tình nguyện viên đã xóa', 'Volunteer Role updated': 'Vai trò của Tình nguyện viên được cập nhật', 'Volunteer Role': 'Chức năng nhiệm vụ TNV', 'Volunteer Roles': 'Chức năng nhiệm vụ TNV', 'Volunteer Service Record': 'Bản lưu Dịch vụ Tình nguyện viên', 'Volunteer added': 'Tình nguyện viên được thêm vào', 'Volunteer and Staff Management': 'Quản lý TNV và Cán bộ', 'Volunteer deleted': 'Tình nguyện viên đã xóa', 'Volunteer registration added': 'Đã thêm đăng ký tình nguyện viên', 'Volunteer registration deleted': 'Đã xóa đăng ký tình nguyện viên', 'Volunteer registration updated': 'Đã cập nhật đăng ký tình nguyện viên', 'Volunteer': 'Tình nguyện viên', 'Volunteers': 'Tình nguyện viên', 'Votes': 'Bình chọn', 'Vulnerability Aggregated Indicator Details': 'Chi tiết về chỉ số tổng hợp về Tình trạng dễ bị tổn thương', 'Vulnerability Aggregated Indicator added': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability Aggregated Indicator deleted': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability Aggregated Indicator updated': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương được cập nhật', 'Vulnerability Aggregated Indicator': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương', 'Vulnerability Aggregated Indicators': 'Các chỉ số tổng hợp về Tình trạng dễ bị tổn thương', 'Vulnerability Data Details': 'Dữ liệu chi tiết về Tình trạng dễ bị tổn thương', 'Vulnerability Data added': 'Dữ liệu về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability Data deleted': 'Dữ liệu về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability Data updated': 'Dữ liệu về Tình trạng dễ bị tổn thương được cập nhật', 'Vulnerability Data': 'Dữ liệu về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator Details': 'Chỉ số chi tiết về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator Source Details': 'Chi tiết Nguồn Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator Sources': 'Các Nguồn Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator added': 'Chỉ số về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability Indicator deleted': 'Chỉ số về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability Indicator updated': 'Chỉ số về Tình trạng dễ bị tổn thương được cập nhật', 'Vulnerability Indicator': 'Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Indicators': 'Các Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Mapping': 'Vẽ bản đồ về Tình trạng dễ bị tổn thương', 'Vulnerability indicator sources added': 'Các nguồn chỉ số về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability indicator sources deleted': 'Các nguồn chỉ số về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability indicator sources updated': 'Các nguồn chỉ số về Tình trạng dễ bị tổn thương được cập nhật', 'Vulnerability': 'Tình trạng dễ bị tổn thương', 'Vulnerable Populations': 'Cộng đồng dễ bị tổn thương', 'WARNING': 'CẢNH BÁO', 'WATSAN': 'NSVS', 'WAYBILL': 'VẬN ĐƠN', 'WFS Layer': 'Lớp WFS', 'WGS84 (EPSG 4236) is required for many WMS servers.': 'WGS84 (EPSG 4236) cần có cho nhiều máy chủ WMS.', 'WMS Layer': 'Lớp WMS', 'Warehouse Details': 'Thông tin về Nhà kho', 'Warehouse Management': 'Quản lý kho hàng', 'Warehouse Stock Details': 'Thông tin về Hàng hóa trong kho', 'Warehouse Stock Report': 'Báo cáo Hàng hóa trong Nhà kho', 'Warehouse Stock updated': 'Hàng hóa trong kho được cập nhật', 'Warehouse Stock': 'Hàng trong kho', 'Warehouse added': 'Nhà kho được thêm vào', 'Warehouse deleted': 'Nhà kho đã xóa', 'Warehouse updated': 'Nhà kho được cập nhật', 'Warehouse': 'Nhà kho', 'Warehouse/Facility/Office (Recipient)': 'Nhà kho/Bộ phận/Văn phòng (Bên nhận)', 'Warehouse/Facility/Office': 'Nhà kho/Bộ phận/Văn phòng', 'Warehouses': 'Những nhà kho', 'Water Sources': 'Các nguồn nước', 'Water Supply': 'Cung cấp nước sạch', 'Water gallon': 'Ga-lông nước', 'Water': 'Nước', 'Waterspout': 'Máng xối nước', 'Way Bill(s)': 'Hóa đơn thu phí đường bộ', 'Waybill Number': 'Số Vận đơn', 'We have tried': 'Chúng tôi đã cố gắng', 'Weak': 'Yếu', 'Web API settings updated': 'Cài đặt API Trang thông tin được cập nhật', 'Web API': 'API Trang thông tin', 'Web Form': 'Kiểu Trang thông tin', 'Web Map Service Browser Name': 'Tên Trình duyệt Dịch vụ Bản đồ Trang thông tin', 'Web Map Service Browser URL': 'URL Trình duyệt Dịch vụ Bản đồ Trang thông tin', 'Web2py executable zip file found - Upload to replace the existing file': 'Tệp tin nén có thể thực hiện chức năng gián điệp - Đăng tải để thay thế tệp tin đang tồn tại', 'Web2py executable zip file needs to be uploaded to use this function.': 'Tệp tin nén có thể thực hiện chức năng gián điệp cần được đăng tải để sử dụng chức năng này.', 'Website': 'Trang thông tin', 'Week': 'Tuần', 'Weekly': 'Hàng tuần', 'Weight (kg)': 'Trọng lượng (kg)', 'Weight': 'Trọng lượng', 'Welcome to %(system_name)s': 'Chào mừng anh/chị truy cập %(system_name)s', 'Welcome to the': 'Chào mừng bạn tới', 'Well-Known Text': 'Từ khóa thường được dùng', 'What are you submitting?': 'Bạn đang gửi cái gì?', 'What order to be contacted in.': 'Đơn hàng nào sẽ được liên hệ trao đổi.', 'What the Items will be used for': 'Các mặt hàng sẽ được sử dụng để làm gì', 'When this search was last checked for changes.': 'Tìm kiếm này được kiểm tra lần cuối là khi nào để tìm ra những thay đổi.', 'Whether the Latitude & Longitude are inherited from a higher level in the location hierarchy rather than being a separately-entered figure.': 'Vĩ độ & Kinh độ có được chiết xuất từ một địa điểm có phân cấp hành chính cao hơn hay là một con số được nhập riêng lẻ.', 'Whether the resource should be tracked using S3Track rather than just using the Base Location': 'Nguồn lực nên được theo dõi sử dụng Dấu vết S3 hay chỉ sử dụng Địa điểm cơ bản', 'Which methods to apply when importing data to the local repository': 'Áp dụng phương pháp nào khi nhập dữ liệu vào kho dữ liệu nội bộ', 'Whiskers': 'Râu', 'Who is doing What Where': 'Ai đang làm Gì Ở đâu', 'Who usually collects water for the family?': 'Ai là người thường đi lấy nước cho cả gia đình', 'Widowed': 'Góa', 'Width (m)': 'Rộng (m)', 'Width': 'Độ rộng', 'Wild Fire': 'Cháy Lớn', 'Will be filled automatically when the Item has been Repacked': 'Sẽ được điền tự động khi Hàng hóa được Đóng gói lại', 'Will be filled automatically when the Shipment has been Received': 'Sẽ được điền tự động khi Lô hàng được Nhận', 'Wind Chill': 'Rét cắt da cắt thịt', 'Winter Storm': 'Bão Mùa đông', 'Women of Child Bearing Age': 'Phụ nữ trong độ tuổi sinh sản', 'Women who are Pregnant or in Labour': 'Phụ nữ trong thời kỳ thai sản', 'Work phone': 'Điện thoại công việc', 'Work': 'Công việc', 'Workflow not specified!': 'Chuỗi công việc chưa được xác định!', 'Workflow': 'Chuỗi công việc', 'Working hours end': 'Hết giờ làm việc', 'Working hours start': 'Bắt đầu giờ làm việc', 'X-Ray': 'Tia X', 'XML parse error': 'Lỗi phân tích cú pháp trong XML', 'XSLT stylesheet not found': 'Không tìm thấy kiểu bảng tính XSLT', 'XSLT transformation error': 'Lỗi chuyển đổi định dạng XSLT', 'XYZ Layer': 'Lớp XYZ', 'YES': 'CÓ', 'Year of Manufacture': 'Năm sản xuất', 'Year that the organization was founded': 'Năm thành lập tổ chức', 'Year': 'Năm tốt nghiệp', 'Yes': 'Có', 'Yes, No': 'Có, Không', 'You are about to submit indicator ratings for': 'Bạn chuẩn bị gửi đánh giá chỉ số cho', 'You are attempting to delete your own account - are you sure you want to proceed?': 'Bạn đang cố gắng xóa tài khoản của bạn - bạn có chắc chắn muốn tiếp tục không?', 'You are currently reported missing!': 'Hiện tại bạn được báo cáo là đã mất tích!', 'You are not permitted to approve documents': 'Bạn không được phép phê duyệt tài liệu', 'You are not permitted to upload files': 'Bạn không được phép đăng tải tệp tin', 'You are viewing': 'Bạn đang xem', 'You can click on the map below to select the Lat/Lon fields': 'Bạn có thể nhấn vào bản đồ phía dưới để chọn các trường Vĩ độ/Kinh độ', 'You can only make %d kit(s) with the available stock': 'Bạn chỉ có thể điền %d bộ(s) với các số lượng hàng có sẵn', 'You can select the Draw tool': 'Bạn có thể lựa chọn công cụ Vẽ', 'You can set the modem settings for SMS here.': 'Bạn có thể cài đặt modem cho tin nhắn ở đây', 'You can use the Conversion Tool to convert from either GPS coordinates or Degrees/Minutes/Seconds.': 'Bạn có thể sử dụng Công cụ Đổi để chuyển đổi từ tọa độ GPS (Hệ thống định vị toàn cầu) hoặc Độ/ Phút/ Giây.', 'You do not have permission for any facility to add an order.': 'Bạn không có quyền đối với bất kỳ tính năng nào để thêm đơn đặt hàng.', 'You do not have permission for any facility to make a commitment.': 'Bạn không có quyền đối với bất kỳ tính năng nào để đưa ra cam kết.', 'You do not have permission for any facility to make a request.': 'Bạn không có quyền đối với bất kỳ tính năng nào để đưa ra yêu cầu.', 'You do not have permission for any facility to perform this action.': 'Bạn không có quyền đối với bất kỳ tính năng nào để thực hiện hành động này.', 'You do not have permission for any facility to receive a shipment.': 'Bạn không có quyền đối với bất kỳ tính năng nào để nhận chuyến hàng.', 'You do not have permission for any facility to send a shipment.': 'Bạn không có quyền đối với bất kỳ tính năng nào để gửi chuyến hàng.', 'You do not have permission for any organization to perform this action.': 'Bạn không có quyền truy cập bất cứ tổ chức nào để thực hiện hành động này', 'You do not have permission for any site to add an inventory item.': 'Bạn không được phép thêm mặt hàng lưu kho tại bất kỳ địa điểm nào.', 'You do not have permission to adjust the stock level in this warehouse.': 'Bạn không được phép điều chỉnh cấp độ lưu kho trong nhà kho này.', 'You do not have permission to cancel this received shipment.': 'Bạn không được phép hủy lô hàng đã nhận này.', 'You do not have permission to cancel this sent shipment.': 'Bạn không được phép hủy lô hàng đã gửi này.', 'You do not have permission to make this commitment.': 'Bạn không được phép thực hiện cam kết này.', 'You do not have permission to receive this shipment.': 'Bạn không được phép nhận lô hàng này.', 'You do not have permission to return this sent shipment.': 'Bạn không được phép trả lại lô hàng đã gửi này.', 'You do not have permission to send messages': 'Bạn không được phép gửi tin nhắn', 'You do not have permission to send this shipment.': 'Bạn không được phép gửi lô hàng này.', 'You have unsaved changes. You need to press the Save button to save them': 'Bạn chưa lưu lại những thay đổi. Bạn cần nhấn nút Lưu để lưu lại những thay đổi này', 'You must enter a minimum of %d characters': 'Bạn phải điền ít nhất %d ký tự', 'You must provide a series id to proceed.': 'Bạn phải nhập số id của serie để thao tác tiếp', 'You need to check all item quantities and allocate to bins before you can receive the shipment': 'Bạn cần kiểm tra số lượng của tất cả các mặt hàng và chia thành các thùng trước khi nhận lô hàng', 'You need to check all item quantities before you can complete the return process': 'Bạn cần kiểm tra số lượng của tất cả các mặt hàng trước khi hoàn tất quá trình trả lại hàng', 'You need to create a template before you can create a series': 'Bạn cần tạo ra một biểu mẫu trước khi tạo ra một loạt các biểu mẫu', 'You need to use the spreadsheet which you can download from this page': 'Bạn cần sử dụng bảng tính tải từ trang này', 'You should edit Twitter settings in models/000_config.py': 'Bạn nên chỉnh sửa cài đặt Twitter trong các kiểu models/000-config.py', 'Your name for this search. Notifications will use this name.': 'Tên của bạn cho tìm kiếm này. Các thông báo sẽ sử dụng tên này.', 'Your post was added successfully.': 'Bạn đã gửi thông tin thành công', 'Youth Development': 'Phát triển TTN', 'Zone Types': 'Các loại vùng châu lục', 'Zones': 'Vùng châu lục', 'Zoom In: click in the map or use the left mouse button and drag to create a rectangle': 'Phóng to: nhấn vào bản đồ hoặc sử dụng nút chuột trái và kéo để tạo ra một hình chữ nhật', 'Zoom Levels': 'Các cấp độ phóng', 'Zoom Out: click in the map or use the left mouse button and drag to create a rectangle': 'Thu nhỏ: nhấn vào bản đồ hoặc sử dụng nút chuột trái và kéo để tạo ra một hình chữ nhật', 'Zoom in closer to Edit OpenStreetMap layer': 'Phóng gần hơn tới lớp Sửa Bản đồ Đường đi Chưa xác định', 'Zoom to Current Location': 'Phóng đến Địa điểm Hiện tại', 'Zoom to maximum map extent': 'Phóng to để mở rộng tối đa bản đồ', 'Zoom': 'Phóng', 'access granted': 'truy cập được chấp thuận', 'activate to sort column ascending': 'Sắp xếp theo thứ tự tăng dần', 'activate to sort column descending': 'Sắp xếp theo thứ tự giảm dần', 'active': 'đang hoạt động', 'always update': 'luôn luôn cập nhật', 'an individual/team to do in 1-2 days': 'một cá nhân/nhóm thực hiện trong 1-2 ngày', 'and': 'và', 'anonymous user': 'Người dùng nặc danh', 'assigned': 'đã phân công', 'average': 'Trung bình', 'black': 'đen', 'blond': 'Tóc vàng', 'blue': 'Xanh da trời', 'brown': 'Nâu', 'by %(person)s': 'bởi %(person)s', 'by': 'bởi', 'can be used to extract data from spreadsheets and put them into database tables.': 'có thể dùng để trích xuất dữ liệu từ bẳng tính đưa vào cơ sở dữ liệu', 'cancelled': 'đã xóa', 'cannot be deleted.': 'không thể xóa', 'check all': 'kiểm tra tất cả', 'clear': 'xóa', 'click here': 'Ấn vào đây', 'consider': 'cân nhắc', 'contains': 'Gồm có', 'created': 'Đã tạo', 'curly': 'Xoắn', 'current': 'Đang hoạt động', 'daily': 'hàng ngày', 'dark': 'tối', 'database %s select': '%s cơ sở dự liệu lựa chọn', 'database': 'Cơ sở Dữ liệu', 'days': 'các ngày', 'deceased': 'Đã chết', 'delete all checked': 'Xóa tất cả các chọn', 'deleted': 'đã xóa', 'diseased': 'Bị dịch bệnh', 'displaced': 'Sơ tán', 'divorced': 'ly hôn', 'does not contain': 'không chứa', 'e.g. Census 2010': 'ví dụ Điều tra 2010', 'editor': 'người biên tập', 'expired': 'đã hết hạn', 'export as csv file': 'Xuất dưới dạng file csv', 'fair': 'công bằng', 'fat': 'béo', 'feedback': 'phản hồi', 'female': 'nữ', 'fill in order: day(2) month(2) year(4)': 'điền theo thứ tự: ngày(2) tháng(2) năm(4)', 'fill in order: hour(2) min(2) day(2) month(2) year(4)': 'điền theo thứ tự: giờ(2) phút(2) ngày(2) tháng(2) năm(4)', 'forehead': 'Phía trước', 'form data': 'Tạo dữ liệu', 'found': 'Tìm thấy', 'full': 'đầy đủ', 'getting': 'đang nhận được', 'green': 'xanh lá cây', 'grey': 'xám', 'here': 'ở đây', 'hourly': 'hàng giờ', 'hours': 'thời gian hoạt động', 'ignore': 'bỏ qua', 'in GPS format': 'Ở định dạng GPS', 'in Stock': 'Tồn kho', 'in this': 'trong đó', 'in': 'trong', 'injured': 'Bị thương', 'input': 'nhập liệu', 'insert new %s': 'Thêm mới %s', 'insert new': 'Thêm mới', 'insufficient number of pages provided': 'không đủ số lượng trang được cung cấp', 'invalid request': 'Yêu cầu không hợp lệ', 'is a central online repository where information on all the disaster victims and families, especially identified casualties, evacuees and displaced people can be stored. Information like name, age, contact number, identity card number, displaced location, and other details are captured. Picture and finger print details of the people can be uploaded to the system. People can also be captured by group for efficiency and convenience.': 'là trung tâm thông tin trực tuyến, nơi lưu trữ thông tin về các nạn nhân và gia đình chịu ảnh hưởng của thiên tai, đặc biệt là xác định con số thương vong và lượng người sơ tán.Thông tin như tên, tuổi, số điện thoại, số CMND, nơi sơ tán và các thông tin khác cũng được lưu lại.Ảnh và dấu vân tay cũng có thể tải lên hệ thống.Để hiệu quả và tiện lợi hơn có thể quản lý theo nhóm', 'items selected': 'mặt hàng được lựa chọn', 'key': 'phím', 'label': 'Nhãn', 'latrines': 'nhà vệ sinh', 'light': 'Ánh sáng', 'long': 'dài', 'long>12cm': 'dài>12cm', 'male': 'Nam', 'mandatory fields': 'Trường bắt buộc', 'married': 'đã kết hôn', 'max': 'tới', 'maxExtent': 'Mở rộng tối đa', 'maxResolution': 'Độ phân giải tối đa', 'medium': 'trung bình', 'medium<12cm': 'trung bình <12cm', 'min': 'từ', 'minutes': 'biên bản', 'missing': 'mất tích', 'moderate': 'trung bình', 'module allows the site administrator to configure various options.': 'mô đun cho phép người quản trị trang thông tin cài đặt cấu hình các tùy chọn khác nhau', 'module helps monitoring the status of hospitals.': 'module giúp theo dõi tình trạng bệnh viện', 'multiplier[0]': 'số nhân[0]', 'natural hazard': 'thảm họa thiên nhiên', 'negroid': 'người da đen', 'never update': 'không bao giờ cập nhật', 'never': 'không bao giờ', 'new ACL': 'ACL mới', 'new': 'thêm mới', 'next 50 rows': '50 dòng tiếp theo', 'no options available': 'không có lựa chọn sẵn có', 'no': 'không', 'none': 'không có', 'normal': 'bình thường', 'not specified': 'không xác định', 'obsolete': 'Đã thôi hoạt động', 'of total data reported': 'của dữ liệu tổng được báo cáo', 'of': 'của', 'offices by organisation': 'văn phòng theo tổ chức', 'on %(date)s': 'vào %(date)s', 'or import from csv file': 'hoặc nhập dữ liệu từ tệp tin csv', 'or': 'hoặc', 'other': 'khác', 'out of': 'ngoài ra', 'over one hour': 'hơn một tiếng', 'overdue': 'quá hạn', 'paid': 'Đã thanh toán', 'per month': 'theo tháng', 'piece': 'chiếc', 'poor': 'nghèo', 'popup_label': 'nhãn_cửa sổ tự động hiển thị', 'previous 50 rows': '50 dòng trước', 'problem connecting to twitter.com - please refresh': 'lỗi kết nối với twitter.com - vui lòng tải lại', 'provides a catalogue of digital media.': 'cung cấp danh mục các phương tiện truyền thông kỹ thuật số', 'pull and push': 'kéo và đẩy', 'pull': 'kéo', 'push': 'đẩy', 'record does not exist': 'Thư mục ghi không tồn tại', 'record id': 'lưu tên truy nhập', 'records deleted': 'hồ sơ đã được xóa', 'red': 'đỏ', 'replace': 'thay thế', 'reports successfully imported.': 'báo cáo đã được nhập khẩu thành công', 'representation of the Polygon/Line.': 'đại diện của Polygon/Line.', 'retry': 'Thử lại', 'river': 'sông', 'row.name': 'dòng.tên', 'search': 'tìm kiếm', 'seconds': 'giây', 'see comment': 'xem ghi chú', 'selected': 'Được chọn', 'separated from family': 'Chia tách khỏi gia đình', 'separated': 'ly thân', 'shaved': 'bị cạo sạch', 'short': 'Ngắn', 'short<6cm': 'Ngắn hơn <6cm', 'sides': 'các mặt', 'sign-up now': 'Đăng ký bây giờ', 'simple': 'đơn giản', 'single': 'độc thân', 'slim': 'mỏng', 'straight': 'thẳng hướng', 'strong': 'Mạnh', 'sublayer.name': 'tên.lớp dưới', 'submitted by': 'được gửi bởi', 'suffered financial losses': 'Các mất mát tài chính đã phải chịu', 'table': 'bảng', 'tall': 'cao', 'text': 'từ khóa', 'times (0 = unlimited)': 'thời gian (0 = vô hạn)', 'times and it is still not working. We give in. Sorry.': 'Nhiều lần mà vẫn không có kết quả, thất bại, xin lỗi', 'times': 'thời gian', 'to access the system': 'truy cập vào hệ thống', 'to download a OCR Form.': 'Để tải xuống một mẫu OCR', 'tonsure': 'lễ cạo đầu', 'total': 'tổng', 'tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!': 'mô đun tweepy không có trong quá trình chạy Python - cần cài đặt để hỗ trợ Twitter không có Tropo!', 'unapproved': 'chưa được chấp thuận', 'uncheck all': 'bỏ chọn toàn bộ', 'unknown': 'không biết', 'unlimited': 'vô hạn', 'up to 3 locations': 'lên tới 3 địa điểm', 'update if master': 'cập nhật nếu là bản gốc', 'update if newer': 'cập nhật nếu mới hơn', 'update': 'cập nhật', 'updated': 'đã cập nhật', 'using default': 'sử dụng mặc định', 'wavy': 'dạng sóng', 'weekly': 'hàng tuần', 'weeks': 'tuần', 'white': 'trắng', 'wider area, longer term, usually contain multiple Activities': 'khu vực rộng lớn hơn, dài hạn hơn, thường chứa nhiều Hoạt động', 'widowed': 'góa', 'within human habitat': 'trong khu dân cư', 'yes': 'có', }
code-for-india/sahana_shelter_worldbank
languages/vi.py
Python
mit
359,193
[ "VisIt" ]
e0d55d7d3c25ba3429fc1fca620656bdc220085178145ea0941364b54cf5c3a9
# # YamlFSSource.py - New-style YAML file-system data source # Copyright (C) 2009 Tony Garnock-Jones <tonyg@kcbbs.gen.nz> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # import Gyre import os import string import yaml class YamlFSSource: def __init__(self, contentdir): self.contentdir = contentdir self.template_headers_cache = {} def _load_file(self, filepath): f = open(filepath) try: loader = yaml.Loader(f) headers = loader.get_data() body = loader.prefix(1000000000).strip('\r\n\0') # yuck except: f.seek(0) subject = os.path.split(filepath)[1] subject = os.path.splitext(subject)[0] headers = {'Subject': subject} body = f.read().strip('\r\n\0') f.close() return (headers, body) def _canonical_dirname(self, dirname): if dirname.startswith(self.contentdir): dirname = dirname[len(self.contentdir):] if dirname and dirname[0] == '/': dirname = dirname[1:] return dirname def _template_headers(self, uncanonicalized_dirname): dirname = self._canonical_dirname(uncanonicalized_dirname) if dirname not in self.template_headers_cache: filepath = os.path.join(uncanonicalized_dirname, '__template__') if dirname: parent = self._template_headers(os.path.dirname(uncanonicalized_dirname)) else: parent = Gyre.config.protostory try: p = self._load_file(filepath)[0] except IOError: p = {} self.template_headers_cache[dirname] = Gyre.Entity(_parent = parent, _props = p) return self.template_headers_cache[dirname] def _visit_story(self, dirname, name): filepath = os.path.join(dirname, name + '.' + Gyre.config.file_extension) try: s = os.stat(filepath) except OSError: return story = Gyre.Entity(self._template_headers(dirname)) story.mtime = s.st_mtime (headers, body) = self._load_file(filepath) for (key, val) in headers.items(): setattr(story, key.lower(), val) story.mtime = int(story.mtime) categorystr = dirname[len(self.contentdir) + 1:] if categorystr: story.category = string.split(categorystr, '/') else: story.category = [] story.body = body if not story.id: uid = list(story.category) uid.append(name) story.id = string.join(uid, '/') story.source = self Gyre.config.store.update(story) def updateStore(self): def visit(arg, dirname, names): for name in names: if name.endswith('.' + Gyre.config.file_extension): choplen = len(Gyre.config.file_extension) + 1 self._visit_story(dirname, name[:-choplen]) os.path.walk(self.contentdir, visit, None)
tonyg/gyre
YamlFSSource.py
Python
gpl-2.0
3,698
[ "VisIt" ]
35231e87fd5427cfd1d09dc03c8154c3a139e82d79a5023909970684b3afb419
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + from __future__ import (absolute_import, division, print_function) import filecmp import numpy as np import os import systemtesting import tempfile import mantid.simpleapi as mantid import mantid.kernel as kernel from tube_calib_fit_params import TubeCalibFitParams from tube_calib import getCalibratedPixelPositions, getPoints from tube_spec import TubeSpec from ideal_tube import IdealTube import tube class WishCalibration(systemtesting.MantidSystemTest): """ Runs the WISH calibration script and checks the result produced is sane """ def __init__(self): super(WishCalibration, self).__init__() self.calibration_table = None self.correction_table = None self.calibration_ref_name = "WishCalibrate_correction_table.csv" self.correction_ref_name = "WishCalibrate_calibration_table.csv" self.calibration_out_path = tempfile.NamedTemporaryFile().name self.correction_out_path = tempfile.NamedTemporaryFile().name def skipTests(self): return True def cleanup(self): mantid.mtd.clear() try: os.remove(self.calibration_out_path) os.remove(self.correction_out_path) except OSError: print("Failed to remove an temp output file in WishCalibration") def requiredFiles(self): return [self.calibration_ref_name, self.correction_ref_name] def validate(self): calibration_ref_path = mantid.FileFinder.getFullPath(self.calibration_ref_name) correction_ref_path = mantid.FileFinder.getFullPath(self.correction_ref_name) cal_result = filecmp.cmp(calibration_ref_path, self.calibration_out_path, False) cor_result = filecmp.cmp(correction_ref_path, self.correction_out_path, False) if not cal_result: print("Calibration did not match in WishCalibrate") if not cor_result: print("Correction did not match in WishCalibrate") return cal_result and cor_result def runTest(self): # This script calibrates WISH using known peak positions from # neutron absorbing bands. The workspace with suffix "_calib" # contains calibrated data. The workspace with suxxic "_corrected" # contains calibrated data with known problematic tubes also corrected ws = mantid.LoadNexusProcessed(Filename="WISH30541_integrated.nxs") # This array defines the positions of peaks on the detector in # meters from the center (0) # For wish this is calculated as follows: # Height of all 7 bands = 0.26m => each band is separated by 0.260 / 6 = 0.4333m # The bands are on a cylinder diameter 0.923m. So we can work out the angle as # (0.4333 * n) / (0.923 / 2) where n is the number of bands above (or below) the # center band. # Putting this together with the distance to the detector tubes (2.2m) we get # the following: (0.4333n) / 0.4615 * 2200 = Expected peak positions # From this we can show there should be 5 peaks (peaks 6 + 7 are too high/low) # at: 0, 0.206, 0.413 respectively (this is symmetrical so +/-) peak_positions = np.array([-0.413, -0.206, 0, 0.206, 0.413]) funcForm = 5 * [1] # 5 gaussian peaks fitPar = TubeCalibFitParams([59, 161, 258, 353, 448]) fitPar.setAutomatic(True) instrument = ws.getInstrument() spec = TubeSpec(ws) spec.setTubeSpecByString(instrument.getFullName()) idealTube = IdealTube() idealTube.setArray(peak_positions) # First calibrate all of the detectors calibrationTable, peaks = tube.calibrate(ws, spec, peak_positions, funcForm, margin=15, outputPeak=True, fitPar=fitPar) self.calibration_table = calibrationTable def findBadPeakFits(peaksTable, threshold=10): """ Find peaks whose fit values fall outside of a given tolerance of the mean peak centers across all tubes. Tubes are defined as have a bad fit if the absolute difference between the fitted peak centers for a specific tube and the mean of the fitted peak centers for all tubes differ more than the threshold parameter. @param peakTable: the table containing fitted peak centers @param threshold: the tolerance on the difference from the mean value @return A list of expected peak positions and a list of indices of tubes to correct """ n = len(peaksTable) num_peaks = peaksTable.columnCount() - 1 column_names = ['Peak%d' % i for i in range(1, num_peaks + 1)] data = np.zeros((n, num_peaks)) for i, row in enumerate(peaksTable): data_row = [row[name] for name in column_names] data[i, :] = data_row # data now has all the peaks positions for each tube # the mean value is the expected value for the peak position for each tube expected_peak_pos = np.mean(data, axis=0) # calculate how far from the expected position each peak position is distance_from_expected = np.abs(data - expected_peak_pos) check = np.where(distance_from_expected > threshold)[0] problematic_tubes = list(set(check)) print("Problematic tubes are: " + str(problematic_tubes)) return expected_peak_pos, problematic_tubes def correctMisalignedTubes(ws, calibrationTable, peaksTable, spec, idealTube, fitPar, threshold=10): """ Correct misaligned tubes due to poor fitting results during the first round of calibration. Misaligned tubes are first identified according to a tolerance applied to the absolute difference between the fitted tube positions and the mean across all tubes. The FindPeaks algorithm is then used to find a better fit with the ideal tube positions as starting parameters for the peak centers. From the refitted peaks the positions of the detectors in the tube are recalculated. @param ws: the workspace to get the tube geometry from @param calibrationTable: the calibration table output from running calibration @param peaksTable: the table containing the fitted peak centers from calibration @param spec: the tube spec for the instrument @param idealTube: the ideal tube for the instrument @param fitPar: the fitting parameters for calibration @param threshold: tolerance defining is a peak is outside of the acceptable range @return table of corrected detector positions """ table_name = calibrationTable.name() + 'Corrected' corrections_table = mantid.CreateEmptyTableWorkspace(OutputWorkspace=table_name) corrections_table.addColumn('int', "Detector ID") corrections_table.addColumn('V3D', "Detector Position") mean_peaks, bad_tubes = findBadPeakFits(peaksTable, threshold) for index in bad_tubes: print("Refitting tube %s" % spec.getTubeName(index)) tube_dets, _ = spec.getTube(index) getPoints(ws, idealTube.getFunctionalForms(), fitPar, tube_dets) tube_ws = mantid.mtd['TubePlot'] fit_ws = mantid.FindPeaks(InputWorkspace=tube_ws, WorkspaceIndex=0, PeakPositions=fitPar.getPeaks(), PeaksList='RefittedPeaks') centers = [row['centre'] for row in fit_ws] detIDList, detPosList = getCalibratedPixelPositions(ws, centers, idealTube.getArray(), tube_dets) for id, pos in zip(detIDList, detPosList): corrections_table.addRow({'Detector ID': id, 'Detector Position': kernel.V3D(*pos)}) return corrections_table corrected_calibration_table = correctMisalignedTubes(ws, calibrationTable, peaks, spec, idealTube, fitPar) self.correction_table = corrected_calibration_table tube.saveCalibration(self.correction_table.getName(), out_path=self.calibration_out_path) tube.saveCalibration(self.calibration_table.getName(), out_path=self.correction_out_path)
mganeva/mantid
Testing/SystemTests/tests/analysis/WishCalibrate.py
Python
gpl-3.0
8,722
[ "Gaussian" ]
f4fe9adb9cdac1eab57cc20d4cda779d2c57242666a84f8259e5e9bc9bde5ac8
""" InaSAFE Disaster risk assessment tool developed by AusAid - **IS Utilitles implementation.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'tim@linfiniti.com' __revision__ = '$Format:%H$' __date__ = '29/01/2011' __copyright__ = 'Copyright 2012, Australia Indonesia Facility for ' __copyright__ += 'Disaster Reduction' import os import sys import traceback import logging import math import numpy import uuid from PyQt4 import QtCore, QtGui from PyQt4.QtCore import QCoreApplication from qgis.core import (QGis, QgsRasterLayer, QgsMapLayer, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsGraduatedSymbolRendererV2, QgsSymbolV2, QgsRendererRangeV2, QgsSymbolLayerV2Registry, QgsColorRampShader, QgsRasterTransparency, QgsVectorLayer, QgsFeature ) from safe_interface import temp_dir from safe_qgis.exceptions import (StyleError, MethodUnavailableError, MemoryLayerCreationError) from safe_qgis.safe_interface import DEFAULTS, safeTr, get_version sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'third_party'))) # pylint: disable=F0401 from raven.handlers.logging import SentryHandler from raven import Client # pylint: enable=F0401 #do not remove this even if it is marked as unused by your IDE #resources are used by htmlfooter and header the comment will mark it unused #for pylint import safe_qgis.resources # pylint: disable=W0611 LOGGER = logging.getLogger('InaSAFE') def setVectorStyle(theQgisVectorLayer, theStyle): """Set QGIS vector style based on InaSAFE style dictionary. For **opaque** a value of **0** can be used. For **fully transparent**, a value of **100** can be used. The calling function should take care to scale the transparency level to between 0 and 100. Args: * theQgisVectorLayer: QgsMapLayer * theStyle: dict - Dictionary of the form as in the example below Returns: None - Sets and saves style for theQgisVectorLayer Raises: None Example: {'target_field': 'DMGLEVEL', 'style_classes': [{'transparency': 1, 'max': 1.5, 'colour': '#fecc5c', 'min': 0.5, 'label': 'Low damage', 'size' : 1}, {'transparency': 55, 'max': 2.5, 'colour': '#fd8d3c', 'min': 1.5, 'label': 'Medium damage', 'size' : 1}, {'transparency': 80, 'max': 3.5, 'colour': '#f31a1c', 'min': 2.5, 'label': 'High damage', 'size' : 1}]} .. note:: The transparency and size keys are optional. Size applies to points only. """ myTargetField = theStyle['target_field'] myClasses = theStyle['style_classes'] myGeometryType = theQgisVectorLayer.geometryType() myRangeList = [] for myClass in myClasses: # Transparency 100: transparent # Transparency 0: opaque mySize = 2 # mm if 'size' in myClass: mySize = myClass['size'] myTransparencyPercent = 0 if 'transparency' in myClass: myTransparencyPercent = myClass['transparency'] if 'min' not in myClass: raise StyleError('Style info should provide a "min" entry') if 'max' not in myClass: raise StyleError('Style info should provide a "max" entry') try: myMin = float(myClass['min']) except TypeError: raise StyleError( 'Class break lower bound should be a number.' 'I got %s' % myClass['min']) try: myMax = float(myClass['max']) except TypeError: raise StyleError('Class break upper bound should be a number.' 'I got %s' % myClass['max']) myColour = myClass['colour'] myLabel = myClass['label'] myColour = QtGui.QColor(myColour) mySymbol = QgsSymbolV2.defaultSymbol(myGeometryType) myColourString = "%s, %s, %s" % ( myColour.red(), myColour.green(), myColour.blue()) # Work around for the fact that QgsSimpleMarkerSymbolLayerV2 # python bindings are missing from the QGIS api. # .. see:: http://hub.qgis.org/issues/4848 # We need to create a custom symbol layer as # the border colour of a symbol can not be set otherwise myRegistry = QgsSymbolLayerV2Registry.instance() if myGeometryType == QGis.Point: myMetadata = myRegistry.symbolLayerMetadata('SimpleMarker') # note that you can get a list of available layer properties # that you can set by doing e.g. # QgsSimpleMarkerSymbolLayerV2.properties() mySymbolLayer = myMetadata.createSymbolLayer({'color_border': myColourString}) mySymbolLayer.setSize(mySize) mySymbol.changeSymbolLayer(0, mySymbolLayer) elif myGeometryType == QGis.Polygon: myMetadata = myRegistry.symbolLayerMetadata('SimpleFill') mySymbolLayer = myMetadata.createSymbolLayer({'color_border': myColourString}) mySymbol.changeSymbolLayer(0, mySymbolLayer) else: # for lines we do nothing special as the property setting # below should give us what we require. pass mySymbol.setColor(myColour) # .. todo:: Check that vectors use alpha as % otherwise scale TS # Convert transparency % to opacity # alpha = 0: transparent # alpha = 1: opaque alpha = 1 - myTransparencyPercent / 100.0 mySymbol.setAlpha(alpha) myRange = QgsRendererRangeV2(myMin, myMax, mySymbol, myLabel) myRangeList.append(myRange) myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList) myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) myRenderer.setClassAttribute(myTargetField) theQgisVectorLayer.setRendererV2(myRenderer) theQgisVectorLayer.saveDefaultStyle() def setRasterStyle(theQgsRasterLayer, theStyle): """Set QGIS raster style based on InaSAFE style dictionary. This function will set both the colour map and the transparency for the passed in layer. Args: * theQgsRasterLayer: QgsRasterLayer * style: dict - Dictionary of the form as in the example below. Example: style_classes = [dict(colour='#38A800', quantity=2, transparency=0), dict(colour='#38A800', quantity=5, transparency=50), dict(colour='#79C900', quantity=10, transparency=50), dict(colour='#CEED00', quantity=20, transparency=50), dict(colour='#FFCC00', quantity=50, transparency=34), dict(colour='#FF6600', quantity=100, transparency=77), dict(colour='#FF0000', quantity=200, transparency=24), dict(colour='#7A0000', quantity=300, transparency=22)] Returns: list: RangeList list: TransparencyList """ myNewStyles = _addMinMaxToStyle(theStyle['style_classes']) # test if QGIS 1.8.0 or older # see issue #259 if qgisVersion() <= 10800: LOGGER.debug('Rendering raster using <= 1.8 styling') return _setLegacyRasterStyle(theQgsRasterLayer, myNewStyles) else: LOGGER.debug('Rendering raster using 2+ styling') return _setNewRasterStyle(theQgsRasterLayer, myNewStyles) def _addMinMaxToStyle(theStyle): """Add a min and max to each style class in a style dictionary. When InaSAFE provides style classes they are specific values, not ranges. However QGIS wants to work in ranges, so this helper will address that by updating the dictionary to include a min max value for each class. It is assumed that we will start for 0 as the min for the first class and the quantity of each class shall constitute the max. For all other classes , min shall constitute the smalles increment to a float that can meaningfully be made by python (as determined by numpy.nextafter()). Args: style: list - A list of dictionaries of the form as in the example below. Returns: dict: A new dictionary list with min max attributes added to each entry. Example input: style_classes = [dict(colour='#38A800', quantity=2, transparency=0), dict(colour='#38A800', quantity=5, transparency=50), dict(colour='#79C900', quantity=10, transparency=50), dict(colour='#CEED00', quantity=20, transparency=50), dict(colour='#FFCC00', quantity=50, transparency=34), dict(colour='#FF6600', quantity=100, transparency=77), dict(colour='#FF0000', quantity=200, transparency=24), dict(colour='#7A0000', quantity=300, transparency=22)] Example output: style_classes = [dict(colour='#38A800', quantity=2, transparency=0, min=0, max=2), dict(colour='#38A800', quantity=5, transparency=50, min=2.0000000000002, max=5), ), dict(colour='#79C900', quantity=10, transparency=50, min=5.0000000000002, max=10),), dict(colour='#CEED00', quantity=20, transparency=50, min=5.0000000000002, max=20),), dict(colour='#FFCC00', quantity=50, transparency=34, min=20.0000000000002, max=50),), dict(colour='#FF6600', quantity=100, transparency=77, min=50.0000000000002, max=100),), dict(colour='#FF0000', quantity=200, transparency=24, min=100.0000000000002, max=200),), dict(colour='#7A0000', quantity=300, transparency=22, min=200.0000000000002, max=300),)] """ myNewStyles = [] myLastMax = 0.0 for myClass in theStyle: myQuantity = float(myClass['quantity']) myClass['min'] = myLastMax myClass['max'] = myQuantity if myQuantity == myLastMax and myQuantity != 0: # skip it as it does not represent a class increment continue myLastMax = numpy.nextafter(myQuantity, sys.float_info.max) myNewStyles.append(myClass) return myNewStyles def _setLegacyRasterStyle(theQgsRasterLayer, theStyle): """Set QGIS raster style based on InaSAFE style dictionary for QGIS < 2.0. This function will set both the colour map and the transparency for the passed in layer. Args: * theQgsRasterLayer: QgsRasterLayer. * style: List - of the form as in the example below. Returns: * list: RangeList * list: TransparencyList Example: style_classes = [dict(colour='#38A800', quantity=2, transparency=0), dict(colour='#38A800', quantity=5, transparency=50), dict(colour='#79C900', quantity=10, transparency=50), dict(colour='#CEED00', quantity=20, transparency=50), dict(colour='#FFCC00', quantity=50, transparency=34), dict(colour='#FF6600', quantity=100, transparency=77), dict(colour='#FF0000', quantity=200, transparency=24), dict(colour='#7A0000', quantity=300, transparency=22)] .. note:: There is currently a limitation in QGIS in that pixel transparency values can not be specified in ranges and consequently the opacity is of limited value and seems to only work effectively with integer values. """ theQgsRasterLayer.setDrawingStyle(QgsRasterLayer.PalettedColor) LOGGER.debug(theStyle) myRangeList = [] myTransparencyList = [] # Always make 0 pixels transparent see issue #542 myPixel = QgsRasterTransparency.TransparentSingleValuePixel() myPixel.pixelValue = 0.0 myPixel.percentTransparent = 100 myTransparencyList.append(myPixel) myLastValue = 0 for myClass in theStyle: LOGGER.debug('Evaluating class:\n%s\n' % myClass) myMax = myClass['quantity'] myColour = QtGui.QColor(myClass['colour']) myLabel = QtCore.QString() if 'label' in myClass: myLabel = QtCore.QString(myClass['label']) myShader = QgsColorRampShader.ColorRampItem(myMax, myColour, myLabel) myRangeList.append(myShader) if math.isnan(myMax): LOGGER.debug('Skipping class.') continue # Create opacity entries for this range myTransparencyPercent = 0 if 'transparency' in myClass: myTransparencyPercent = int(myClass['transparency']) if myTransparencyPercent > 0: # Always assign the transparency to the class' specified quantity myPixel = QgsRasterTransparency.TransparentSingleValuePixel() myPixel.pixelValue = myMax myPixel.percentTransparent = myTransparencyPercent myTransparencyList.append(myPixel) # Check if range extrema are integers so we know if we can # use them to calculate a value range if (myLastValue == int(myLastValue)) and (myMax == int(myMax)): # Ensure that they are integers # (e.g 2.0 must become 2, see issue #126) myLastValue = int(myLastValue) myMax = int(myMax) # Set transparencies myRange = range(myLastValue, myMax) for myValue in myRange: myPixel = \ QgsRasterTransparency.TransparentSingleValuePixel() myPixel.pixelValue = myValue myPixel.percentTransparent = myTransparencyPercent myTransparencyList.append(myPixel) #myLabel = myClass['label'] # Apply the shading algorithm and design their ramp theQgsRasterLayer.setColorShadingAlgorithm( QgsRasterLayer.ColorRampShader) myFunction = theQgsRasterLayer.rasterShader().rasterShaderFunction() # Discrete will shade any cell between maxima of this break # and minima of previous break to the colour of this break myFunction.setColorRampType(QgsColorRampShader.DISCRETE) myFunction.setColorRampItemList(myRangeList) # Now set the raster transparency theQgsRasterLayer.rasterTransparency()\ .setTransparentSingleValuePixelList(myTransparencyList) theQgsRasterLayer.saveDefaultStyle() return myRangeList, myTransparencyList def _setNewRasterStyle(theQgsRasterLayer, theClasses): """Set QGIS raster style based on InaSAFE style dictionary for QGIS >= 2.0. This function will set both the colour map and the transparency for the passed in layer. Args: * theQgsRasterLayer: QgsRasterLayer * theClasses: List of the form as in the example below. Returns: * list: RangeList * list: TransparencyList Example: style_classes = [dict(colour='#38A800', quantity=2, transparency=0), dict(colour='#38A800', quantity=5, transparency=50), dict(colour='#79C900', quantity=10, transparency=50), dict(colour='#CEED00', quantity=20, transparency=50), dict(colour='#FFCC00', quantity=50, transparency=34), dict(colour='#FF6600', quantity=100, transparency=77), dict(colour='#FF0000', quantity=200, transparency=24), dict(colour='#7A0000', quantity=300, transparency=22)] """ # Note imports here to prevent importing on unsupported QGIS versions # pylint: disable=E0611 # pylint: disable=W0621 # pylint: disable=W0404 from qgis.core import (QgsRasterShader, QgsColorRampShader, QgsSingleBandPseudoColorRenderer, QgsRasterTransparency) # pylint: enable=E0611 # pylint: enable=W0621 # pylint: enable=W0404 myRampItemList = [] myTransparencyList = [] LOGGER.debug(theClasses) for myClass in theClasses: LOGGER.debug('Evaluating class:\n%s\n' % myClass) if 'quantity' not in myClass: LOGGER.exception('Class has no quantity attribute') continue myMax = myClass['max'] if math.isnan(myMax): LOGGER.debug('Skipping class - max is nan.') continue myMin = myClass['min'] if math.isnan(myMin): LOGGER.debug('Skipping class - min is nan.') continue myColour = QtGui.QColor(myClass['colour']) myLabel = QtCore.QString() if 'label' in myClass: myLabel = QtCore.QString(myClass['label']) myRampItem = QgsColorRampShader.ColorRampItem(myMax, myColour, myLabel) myRampItemList.append(myRampItem) # Create opacity entries for this range myTransparencyPercent = 0 if 'transparency' in myClass: myTransparencyPercent = int(myClass['transparency']) if myTransparencyPercent > 0: # Check if range extrema are integers so we know if we can # use them to calculate a value range myPixel = QgsRasterTransparency.TransparentSingleValuePixel() myPixel.min = myMin # We want it just a leeetle bit smaller than max # so that ranges are discrete myPixel.max = myMax myPixel.percentTransparent = myTransparencyPercent myTransparencyList.append(myPixel) myBand = 1 # gdal counts bands from base 1 LOGGER.debug('Setting colour ramp list') myRasterShader = QgsRasterShader() myColorRampShader = QgsColorRampShader() myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED) myColorRampShader.setColorRampItemList(myRampItemList) LOGGER.debug('Setting shader function') myRasterShader.setRasterShaderFunction(myColorRampShader) LOGGER.debug('Setting up renderer') myRenderer = QgsSingleBandPseudoColorRenderer( theQgsRasterLayer.dataProvider(), myBand, myRasterShader) LOGGER.debug('Assigning renderer to raster layer') theQgsRasterLayer.setRenderer(myRenderer) LOGGER.debug('Setting raster transparency list') myRenderer = theQgsRasterLayer.renderer() myTransparency = QgsRasterTransparency() myTransparency.setTransparentSingleValuePixelList(myTransparencyList) myRenderer.setRasterTransparency(myTransparency) # For interest you can also view the list like this: #pix = t.transparentSingleValuePixelList() #for px in pix: # print 'Min: %s Max %s Percent %s' % ( # px.min, px.max, px.percentTransparent) LOGGER.debug('Saving style as default') theQgsRasterLayer.saveDefaultStyle() LOGGER.debug('Setting raster style done!') return myRampItemList, myTransparencyList def tr(theText): """We define a tr() alias here since the utilities implementation below is not a class and does not inherit from QObject. .. note:: see http://tinyurl.com/pyqt-differences Args: theText - string to be translated Returns: Translated version of the given string if available, otherwise the original string. """ return QCoreApplication.translate('@default', theText) def getExceptionWithStacktrace(theException, theHtml=False, theContext=None): """Convert exception into a string containing a stack trace. .. note: OS File path separators will be replaced with <wbr> which is a 'soft wrap' (when theHtml=True)_that will ensure that long paths do not force the web frame to be very wide. Args: * theException: Exception object. * theHtml: Optional flag if output is to be wrapped as theHtml. * theContext: Optional theContext message. Returns: Exception: with stack trace info suitable for display. """ myTraceback = ''.join(traceback.format_tb(sys.exc_info()[2])) if not theHtml: if str(theException) is None or str(theException) == '': myErrorMessage = (theException.__class__.__name__ + ' : ' + tr('No details provided')) else: myErrorMessage = (theException.__class__.__name__ + ' : ' + str(theException)) return myErrorMessage + "\n" + myTraceback else: if str(theException) is None or str(theException) == '': myErrorMessage = ('<b>' + theException.__class__.__name__ + '</b> : ' + tr('No details provided')) else: myWrappedMessage = str(theException).replace(os.sep, '<wbr>' + os.sep) # If the message contained some html above has a side effect of # turning </foo> into <<wbr>/foo> and <hr /> into <hr <wbr>/> # so we need to revert that using the next two lines. myWrappedMessage = myWrappedMessage.replace('<<wbr>' + os.sep, '<' + os.sep) myWrappedMessage = myWrappedMessage.replace('<wbr>' + os.sep + '>', os.sep + '>') myErrorMessage = ('<b>' + theException.__class__.__name__ + '</b> : ' + myWrappedMessage) myTraceback = ( '<pre id="traceback" class="prettyprint"' ' style="display: none;">\n' + myTraceback + '</pre>') # Wrap string in theHtml s = '<table class="condensed">' if theContext is not None and theContext != '': s += ('<tr><th class="warning button-cell">' + tr('Error:') + '</th></tr>\n' '<tr><td>' + theContext + '</td></tr>\n') # now the string from the error itself s += ( '<tr><th class="problem button-cell">' + tr('Problem:') + '</th></tr>\n' '<tr><td>' + myErrorMessage + '</td></tr>\n') # now the traceback heading s += ('<tr><th class="info button-cell" style="cursor:pointer;"' ' onclick="$(\'#traceback\').toggle();">' + tr('Click for Diagnostic Information:') + '</th></tr>\n' '<tr><td>' + myTraceback + '</td></tr>\n') s += '</table>' return s def getWGS84resolution(theLayer): """Return resolution of raster layer in EPSG:4326 Input theLayer: Raster layer Output resolution. If input layer is already in EPSG:4326, simply return the resolution If not, work it out based on EPSG:4326 representations of its extent """ msg = tr( 'Input layer to getWGS84resolution must be a raster layer. ' 'I got: %s' % str(theLayer.type())[1:-1]) if not theLayer.type() == QgsMapLayer.RasterLayer: raise RuntimeError(msg) if theLayer.crs().authid() == 'EPSG:4326': # If it is already in EPSG:4326, simply use the native resolution myCellSize = theLayer.rasterUnitsPerPixel() else: # Otherwise, work it out based on EPSG:4326 representations of # its extent # Reproject extent to EPSG:4326 myGeoCrs = QgsCoordinateReferenceSystem() myGeoCrs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) myXForm = QgsCoordinateTransform(theLayer.crs(), myGeoCrs) myExtent = theLayer.extent() myProjectedExtent = myXForm.transformBoundingBox(myExtent) # Estimate cellsize myColumns = theLayer.width() myGeoWidth = abs(myProjectedExtent.xMaximum() - myProjectedExtent.xMinimum()) myCellSize = myGeoWidth / myColumns return myCellSize def htmlHeader(): """Get a standard html header for wrapping content in.""" myFile = QtCore.QFile(':/plugins/inasafe/header.html') if not myFile.open(QtCore.QIODevice.ReadOnly): return '----' myStream = QtCore.QTextStream(myFile) myHeader = myStream.readAll() myFile.close() return myHeader def htmlFooter(): """Get a standard html footer for wrapping content in.""" myFile = QtCore.QFile(':/plugins/inasafe/footer.html') if not myFile.open(QtCore.QIODevice.ReadOnly): return '----' myStream = QtCore.QTextStream(myFile) myFooter = myStream.readAll() myFile.close() return myFooter def qgisVersion(): """Get the version of QGIS Args: None Returns: QGIS Version where 10700 represents QGIS 1.7 etc. Raises: None """ myVersion = None try: myVersion = unicode(QGis.QGIS_VERSION_INT) except AttributeError: myVersion = unicode(QGis.qgisVersion)[0] myVersion = int(myVersion) return myVersion # TODO: move this to its own file? TS class QgsLogHandler(logging.Handler): """A logging handler that will log messages to the QGIS logging console.""" def __init__(self, level=logging.NOTSET): logging.Handler.__init__(self) def emit(self, theRecord): """Try to log the message to QGIS if available, otherwise do nothing. Args: theRecord: logging record containing whatever info needs to be logged. Returns: None Raises: None """ try: #available from qgis 1.8 from qgis.core import QgsMessageLog # Check logging.LogRecord properties for lots of other goodies # like line number etc. you can get from the log message. QgsMessageLog.logMessage(theRecord.getMessage(), 'InaSAFE', 0) except (MethodUnavailableError, ImportError): pass def addLoggingHanderOnce(theLogger, theHandler): """A helper to add a handler to a logger, ensuring there are no duplicates. Args: * theLogger: logging.logger instance * theHandler: logging.Handler instance to be added. It will not be added if an instance of that Handler subclass already exists. Returns: bool: True if the logging handler was added Raises: None """ myClassName = theHandler.__class__.__name__ for myHandler in theLogger.handlers: if myHandler.__class__.__name__ == myClassName: return False theLogger.addHandler(theHandler) return True def setupLogger(theLogFile=None, theSentryUrl=None): """Run once when the module is loaded and enable logging Args: * theLogFile: str - optional full path to a file to write logs to. * theSentryUrl: str - optional url to sentry api for remote logging. Defaults to http://c64a83978732474ea751d432ab943a6b :d9d8e08786174227b9dcd8a4c3f6e9da@sentry.linfiniti.com/5 which is the sentry project for InaSAFE desktop. Returns: None Raises: None Borrowed heavily from this: http://docs.python.org/howto/logging-cookbook.html Use this to first initialise the logger (see safe/__init__.py):: from safe_qgis import utilities utilities.setupLogger() You would typically only need to do the above once ever as the safe modle is initialised early and will set up the logger globally so it is available to all packages / subpackages as shown below. In a module that wants to do logging then use this example as a guide to get the initialised logger instance:: # The LOGGER is intialised in utilities.py by init import logging LOGGER = logging.getLogger('InaSAFE') Now to log a message do:: LOGGER.debug('Some debug message') .. note:: The file logs are written to the inasafe user tmp dir e.g.: /tmp/inasafe/23-08-2012/timlinux/logs/inasafe.log """ myLogger = logging.getLogger('InaSAFE') myLogger.setLevel(logging.DEBUG) myDefaultHanderLevel = logging.DEBUG # create formatter that will be added to the handlers myFormatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # create syslog handler which logs even debug messages # (ariel): Make this log to /var/log/safe.log instead of # /var/log/syslog # (Tim) Ole and I discussed this - we prefer to log into the # user's temporary working directory. myTempDir = temp_dir('logs') myFilename = os.path.join(myTempDir, 'inasafe.log') if theLogFile is None: myFileHandler = logging.FileHandler(myFilename) else: myFileHandler = logging.FileHandler(theLogFile) myFileHandler.setLevel(myDefaultHanderLevel) # create console handler with a higher log level myConsoleHandler = logging.StreamHandler() myConsoleHandler.setLevel(logging.INFO) myQGISHandler = QgsLogHandler() # Sentry handler - this is optional hence the localised import # It will only log if pip install raven. If raven is available # logging messages will be sent to http://sentry.linfiniti.com # We will log exceptions only there. You need to either: # * Set env var 'INSAFE_SENTRY=1' present (value can be anything) # * Enable the 'help improve InaSAFE by submitting errors to a remove # server' option in InaSAFE options dialog # before this will be enabled. mySettings = QtCore.QSettings() myFlag = mySettings.value('inasafe/useSentry', False).toBool() if 'INASAFE_SENTRY' in os.environ or myFlag: if theSentryUrl is None: myClient = Client( 'http://c64a83978732474ea751d432ab943a6b' ':d9d8e08786174227b9dcd8a4c3f6e9da@sentry.linfiniti.com/5') else: myClient = Client(theSentryUrl) mySentryHandler = SentryHandler(myClient) mySentryHandler.setFormatter(myFormatter) mySentryHandler.setLevel(logging.ERROR) if addLoggingHanderOnce(myLogger, mySentryHandler): myLogger.debug('Sentry logging enabled') else: myLogger.debug('Sentry logging disabled') #Set formatters myFileHandler.setFormatter(myFormatter) myConsoleHandler.setFormatter(myFormatter) myQGISHandler.setFormatter(myFormatter) # add the handlers to the logger addLoggingHanderOnce(myLogger, myFileHandler) addLoggingHanderOnce(myLogger, myConsoleHandler) addLoggingHanderOnce(myLogger, myQGISHandler) def getLayerAttributeNames(theLayer, theAllowedTypes, theCurrentKeyword=None): """iterates over self.layer and returns all the attribute names of attributes that have int or string as field type and the position of the theCurrentKeyword in the attribute names list Args: * theAllowedTypes: list(Qvariant) - a list of QVariants types that are acceptable for the attribute. e.g.: [QtCore.QVariant.Int, QtCore.QVariant.String] * theCurrentKeyword - the currently stored keyword for the attribute Returns: * all the attribute names of attributes that have int or string as field type * the position of the theCurrentKeyword in the attribute names list, this is None if theCurrentKeyword is not in the lis of attributes Raises: no exceptions explicitly raised """ if theLayer.type() == QgsMapLayer.VectorLayer: myProvider = theLayer.dataProvider() myProvider = myProvider.fields() myFields = [] mySelectedIndex = None i = 0 for f in myProvider: # show only int or string myFields to be chosen as aggregation # attribute other possible would be float if myProvider[f].type() in theAllowedTypes: myCurrentFieldName = myProvider[f].name() myFields.append(myCurrentFieldName) if theCurrentKeyword == myCurrentFieldName: mySelectedIndex = i i += 1 return myFields, mySelectedIndex else: return None, None def getDefaults(theDefault=None): """returns a dictionary of defaults values to be used it takes the DEFAULTS from safe and modifies them according to qgis QSettings Args: * theDefault: a key of the defaults dictionary Returns: * A dictionary of defaults values to be used * or the default value if a key is passed * or None if the requested default value is not valid Raises: no exceptions explicitly raised """ mySettings = QtCore.QSettings() myDefaults = DEFAULTS myDefaults['FEM_RATIO'] = mySettings.value( 'inasafe/defaultFemaleRatio', DEFAULTS['FEM_RATIO']).toDouble()[0] if theDefault is None: return myDefaults elif theDefault in myDefaults: return myDefaults[theDefault] else: return None def copyInMemory(vLayer, copyName=''): """Return a memory copy of a layer Input origLayer: layer copyName: the name of the copy Output memory copy of a layer """ if copyName is '': copyName = vLayer.name() + ' TMP' if vLayer.type() == QgsMapLayer.VectorLayer: vType = vLayer.geometryType() if vType == QGis.Point: typeStr = 'Point' elif vType == QGis.Line: typeStr = 'Line' elif vType == QGis.Polygon: typeStr = 'Polygon' else: raise MemoryLayerCreationError('Layer is whether Point nor ' 'Line nor Polygon') else: raise MemoryLayerCreationError('Layer is not a VectorLayer') crs = vLayer.crs().authid().toLower() myUUID = str(uuid.uuid4()) uri = '%s?crs=%s&index=yes&uuid=%s' % (typeStr, crs, myUUID) memLayer = QgsVectorLayer(uri, copyName, 'memory') memProvider = memLayer.dataProvider() vProvider = vLayer.dataProvider() vAttrs = vProvider.attributeIndexes() vFields = vProvider.fields() fields = [] for i in vFields: fields.append(vFields[i]) memProvider.addAttributes(fields) vProvider.select(vAttrs) ft = QgsFeature() while vProvider.nextFeature(ft): memProvider.addFeatures([ft]) if qgisVersion() <= 10800: # Next two lines a workaround for a QGIS bug (lte 1.8) # preventing mem layer attributes being saved to shp. memLayer.startEditing() memLayer.commitChanges() return memLayer def mmToPoints(theMM, theDpi): """Convert measurement in points to one in mm. Args: * theMM: int - distance in millimeters * theDpi: int - dots per inch in the print / display medium Returns: mm converted value Raises: Any exceptions raised by the InaSAFE library will be propagated. """ myInchAsMM = 25.4 myPoints = (theMM * theDpi) / myInchAsMM return myPoints def pointsToMM(thePoints, theDpi): """Convert measurement in points to one in mm. Args: * thePoints: int - number of points in display / print medium * theDpi: int - dots per inch in the print / display medium Returns: mm converted value Raises: Any exceptions raised by the InaSAFE library will be propagated. """ myInchAsMM = 25.4 myMM = (float(thePoints) / theDpi) * myInchAsMM return myMM def dpiToMeters(theDpi): """Convert dots per inch (dpi) to dots perMeters. Args: theDpi: int - dots per inch in the print / display medium Returns: int - dpm converted value Raises: Any exceptions raised by the InaSAFE library will be propagated. """ myInchAsMM = 25.4 myInchesPerM = 1000.0 / myInchAsMM myDotsPerM = myInchesPerM * theDpi return myDotsPerM def setupPrinter(theFilename, theResolution=300, thePageHeight=297, thePageWidth=210): """Create a QPrinter instance defaulted to print to an A4 portrait pdf Args: theFilename - filename for pdf generated using this printer Returns: None Raises: None """ # # Create a printer device (we are 'printing' to a pdf # LOGGER.debug('InaSAFE Map setupPrinter called') myPrinter = QtGui.QPrinter() myPrinter.setOutputFormat(QtGui.QPrinter.PdfFormat) myPrinter.setOutputFileName(theFilename) myPrinter.setPaperSize( QtCore.QSizeF(thePageWidth, thePageHeight), QtGui.QPrinter.Millimeter) myPrinter.setFullPage(True) myPrinter.setColorMode(QtGui.QPrinter.Color) myPrinter.setResolution(theResolution) return myPrinter def humaniseSeconds(theSeconds): """Utility function to humanise seconds value into e.g. 10 seconds ago. The function will try to make a nice phrase of the seconds count provided. .. note:: Currently theSeconds that amount to days are not supported. Args: theSeconds: int - mandatory seconds value e.g. 1100 Returns: str: A humanised version of the seconds count. Raises: None """ myDays = theSeconds / (3600 * 24) myDayModulus = theSeconds % (3600 * 24) myHours = myDayModulus / 3600 myHourModulus = myDayModulus % 3600 myMinutes = myHourModulus / 60 if theSeconds < 60: return tr('%i seconds' % theSeconds) if theSeconds < 120: return tr('a minute') if theSeconds < 3600: return tr('%s minutes' % myMinutes) if theSeconds < 7200: return tr('over an hour') if theSeconds < 86400: return tr('%i hours and %i minutes' % (myHours, myMinutes)) else: # If all else fails... return tr('%i days, %i hours and %i minutes' % ( myDays, myHours, myMinutes)) def impactLayerAttribution(theKeywords, theInaSAFEFlag=False): """Make a little table for attribution of data sources used in impact. Args: * theKeywords: dict{} - a keywords dict for an impact layer. * theInaSAFEFlag: bool - whether to show a little InaSAFE promotional text in the attribution output. Defaults to False. Returns: str: an html snippet containing attribution information for the impact layer. If no keywords are present or no appropriate keywords are present, None is returned. Raises: None """ if theKeywords is None: return None myReport = '' myJoinWords = ' - %s ' % tr('sourced from') myHazardDetails = tr('Hazard details') myHazardTitleKeyword = 'hazard_title' myHazardSourceKeyword = 'hazard_source' myExposureDetails = tr('Exposure details') myExposureTitleKeyword = 'exposure_title' myExposureSourceKeyword = 'exposure_source' if myHazardTitleKeyword in theKeywords: # We use safe translation infrastructure for this one (rather than Qt) myHazardTitle = safeTr(theKeywords[myHazardTitleKeyword]) else: myHazardTitle = tr('Hazard layer') if myHazardSourceKeyword in theKeywords: # We use safe translation infrastructure for this one (rather than Qt) myHazardSource = safeTr(theKeywords[myHazardSourceKeyword]) else: myHazardSource = tr('an unknown source') if myExposureTitleKeyword in theKeywords: myExposureTitle = theKeywords[myExposureTitleKeyword] else: myExposureTitle = tr('Exposure layer') if myExposureSourceKeyword in theKeywords: myExposureSource = theKeywords[myExposureSourceKeyword] else: myExposureSource = tr('an unknown source') myReport += ('<table class="table table-striped condensed' ' bordered-table">') myReport += '<tr><th>%s</th></tr>' % myHazardDetails myReport += '<tr><td>%s%s %s.</td></tr>' % ( myHazardTitle, myJoinWords, myHazardSource) myReport += '<tr><th>%s</th></tr>' % myExposureDetails myReport += '<tr><td>%s%s %s.</td></tr>' % ( myExposureTitle, myJoinWords, myExposureSource) if theInaSAFEFlag: myReport += '<tr><th>%s</th></tr>' % tr('Software notes') myInaSAFEPhrase = tr( 'This report was created using InaSAFE ' 'version %1. Visit http://inasafe.org to get ' 'your free copy of this software!').arg(get_version()) myInaSAFEPhrase += tr( 'InaSAFE has been jointly developed by' ' BNPB, AusAid & the World Bank') myReport += '<tr><td>%s</td></tr>' % myInaSAFEPhrase myReport += '</table>' return myReport def addComboItemInOrder(theCombo, theItemText, theItemData=None): """Although QComboBox allows you to set an InsertAlphabetically enum this only has effect when a user interactively adds combo items to an editable combo. This we have this little function to ensure that combos are always sorted alphabetically. Args: * theCombo - combo box receiving the new item * theItemText - display text for the combo * theItemData - optional UserRole data to be associated with the item Returns: None Raises: ..todo:: Move this to utilities """ mySize = theCombo.count() for myCount in range(0, mySize): myItemText = str(theCombo.itemText(myCount)) # see if theItemText alphabetically precedes myItemText if cmp(str(theItemText).lower(), myItemText.lower()) < 0: theCombo.insertItem(myCount, theItemText, theItemData) return #otherwise just add it to the end theCombo.insertItem(mySize, theItemText, theItemData) def isPolygonLayer(theLayer): """Tell if a QGIS layer is vector and its geometries are polygons. Args: the theLayer Returns: bool - true if the theLayer contains polygons Raises: None """ try: return (theLayer.type() == QgsMapLayer.VectorLayer) and ( theLayer.geometryType() == QGis.Polygon) except AttributeError: return False def isPointLayer(theLayer): """Tell if a QGIS layer is vector and its geometries are points. Args: the theLayer Returns: bool - true if the theLayer contains polygons Raises: None """ try: return (theLayer.type() == QgsMapLayer.VectorLayer) and ( theLayer.geometryType() == QGis.Point) except AttributeError: return False def which(name, flags=os.X_OK): """Search PATH for executable files with the given name. ..note:: This function was taken verbatim from the twisted framework, licence available here: http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.2.0/LICENSE On newer versions of MS-Windows, the PATHEXT environment variable will be set to the list of file extensions for files considered executable. This will normally include things like ".EXE". This fuction will also find files with the given name ending with any of these extensions. On MS-Windows the only flag that has any meaning is os.F_OK. Any other flags will be ignored. @type name: C{str} @param name: The name for which to search. @type flags: C{int} @param flags: Arguments to L{os.access}. @rtype: C{list} @param: A list of the full paths to files found, in the order in which they were found. """ result = [] #pylint: disable=W0141 exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep)) #pylint: enable=W0141 path = os.environ.get('PATH', None) # In c6c9b26 we removed this hard coding for issue #529 but I am # adding it back here in case the user's path does not include the # gdal binary dir on OSX but it is actually there. (TS) if sys.platform == 'darwin': # Mac OS X myGdalPrefix = ('/Library/Frameworks/GDAL.framework/' 'Versions/1.9/Programs/') path = '%s:%s' % (path, myGdalPrefix) LOGGER.debug('Search path: %s' % path) if path is None: return [] for p in path.split(os.pathsep): p = os.path.join(p, name) if os.access(p, flags): result.append(p) for e in exts: pext = p + e if os.access(pext, flags): result.append(pext) return result
rukku/inasafe
safe_qgis/utilities.py
Python
gpl-3.0
45,636
[ "VisIt" ]
c8f8af75d89d86a31bb0923066d830f1a7a8cdc35fda762ef8c6dabb21025e4f
"""Convert to and from Roman numerals This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version. """ __author__ = "Mark Pilgrim (mark@diveintopython.org)" __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2004/05/05 21:57:19 $" __copyright__ = "Copyright (c) 2001 Mark Pilgrim" __license__ = "Python" import re #Define exceptions class RomanError(Exception): """ General error for roman numerals # PyUML: Do not remove this line! # XMI_ID:_EH19YhEREd-LgJ4IxcJkTA """ pass class OutOfRangeError(RomanError): """ Thrown then the requested value os out of the roman numeral range # PyUML: Do not remove this line! # XMI_ID:_EH19YxEREd-LgJ4IxcJkTA """ pass class NotIntegerError(RomanError): """ Thrown when input is not an integer # PyUML: Do not remove this line! # XMI_ID:_EH19ZBEREd-LgJ4IxcJkTA """ pass class InvalidRomanNumeralError(RomanError): """ Thrown when the input is not a roman numeral # PyUML: Do not remove this line! # XMI_ID:_EH2kcBEREd-LgJ4IxcJkTA """ pass #Define digit mapping ROMAN_NUMERAL_MAP = (('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)) def to_roman(number): """convert integer to Roman numeral""" if number == 0: return "N" if not (0 < number < 3999): raise OutOfRangeError, "number out of range (must be 1..3999)" if int(number) != number: raise NotIntegerError, "non-integers can not be converted" result = "" for numeral, integer in ROMAN_NUMERAL_MAP: while number >= integer: result += numeral number -= integer return result #Define pattern to detect valid Roman numerals ROMAN_NUMERAL_PATTERN = re.compile(''' ^ # beginning of string M{0,3} # thousands - 0 to 3 M's (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's), # or 500-800 (D, followed by 0 to 3 C's) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's), # or 50-80 (L, followed by 0 to 3 X's) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's), # or 5-8 (V, followed by 0 to 3 I's) $ # end of string ''' , re.VERBOSE) def from_roman(roman_numeral): """convert Roman numeral to integer""" if not roman_numeral: raise InvalidRomanNumeralError, 'Input can not be blank' if roman_numeral == "N": return 0 if not ROMAN_NUMERAL_PATTERN.search(roman_numeral): raise InvalidRomanNumeralError, 'Invalid Roman numeral: {}'.format(roman_numeral) result = 0 index = 0 for numeral, integer in ROMAN_NUMERAL_MAP: while roman_numeral[index:index+len(numeral)] == numeral: result += integer index += len(numeral) return result
Iconik/eve-suite
src/model/generated/roman/roman.py
Python
gpl-3.0
3,339
[ "VisIt" ]
c0fe00c7aa4ffd95a505bb1c048153cad40d43b11fa5df50f0384fd856b2938b
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .. import ir from ..jvmops import * _dup = bytes([DUP]) _dup2 = bytes([DUP2]) _pop = bytes([POP]) _pop2 = bytes([POP2]) def visitLinearCode(irdata, visitor): # Visit linear sections of code, pessimistically treating all exception # handler ranges as jumps. except_level = 0 for instr in irdata.flat_instructions: if instr in irdata.except_starts: except_level += 1 visitor.visitExceptionRange() elif instr in irdata.except_ends: except_level -= 1 if except_level > 0: continue if instr in irdata.jump_targets or isinstance(instr, (ir.LazyJumpBase, ir.Switch)): visitor.visitJumpTargetOrBranch(instr) elif not instr.fallsthrough(): visitor.visitReturn() else: visitor.visit(instr) assert(except_level == 0) return visitor class NoExceptVisitorBase: def visitExceptionRange(self): self.reset() def visitJumpTargetOrBranch(self, instr): self.reset() class ConstInliner(NoExceptVisitorBase): def __init__(self): self.uses = {} self.notmultiused = set() self.current = {} def reset(self): self.current = {} def visitReturn(self): for key in self.current: self.notmultiused.add(self.current[key]) self.reset() def visit(self, instr): if isinstance(instr, ir.RegAccess): key = instr.key if instr.store: if key in self.current: self.notmultiused.add(self.current[key]) self.current[key] = instr elif key in self.current: # if currently used 0, mark it used once # if used once already, mark it as multiused if self.current[key] in self.uses: del self.current[key] else: self.uses[self.current[key]] = instr def inlineConsts(irdata): # Inline constants which are only used once or not at all. This only covers # linear sections of code and pessimistically assumes everything is used # when it reaches a jump or exception range. Essentially, this means that # the value can only be considered unused if it is either overwritten by a # store or reaches a return or throw before any jumps. # As usual, assume no iinc. instrs = irdata.flat_instructions visitor = visitLinearCode(irdata, ConstInliner()) remove = set() replace = {} for ins1, ins2 in zip(instrs, instrs[1:]): if ins2 in visitor.notmultiused and isinstance(ins1, (ir.PrimConstant, ir.OtherConstant)): replace[ins1] = [] replace[ins2] = [] if ins2 in visitor.uses: replace[visitor.uses[ins2]] = [ins1] irdata.replaceInstrs(replace) class StoreLoadPruner(NoExceptVisitorBase): def __init__(self): self.current = {} self.last = None self.removed = set() def reset(self): self.current = {} self.last = None def visitReturn(self): for pair in self.current.values(): assert(pair[0].store and not pair[1].store) self.removed.update(pair) self.reset() def visit(self, instr): if isinstance(instr, ir.RegAccess): key = instr.key if instr.store: if key in self.current: pair = self.current[key] assert(pair[0].store and not pair[1].store) self.removed.update(self.current.pop(key)) self.last = instr else: self.current.pop(key, None) if self.last and self.last.key == key: self.current[key] = self.last, instr self.last = None elif not isinstance(instr, ir.Label): self.last = None def pruneStoreLoads(irdata): # Remove a store immediately followed by a load from the same register # (potentially with a label in between) if it can be proven that this # register isn't read again. As above, this only considers linear sections of code. # Must not be run before dup2ize! data = visitLinearCode(irdata, StoreLoadPruner()) irdata.replaceInstrs({instr:[] for instr in data.removed}) # used by writeir too def genDups(needed, needed_after): # Generate a sequence of dup and dup2 instructions to duplicate the given # value. This keeps up to 4 copies of the value on the stack. Thanks to dup2 # this asymptotically takes only half a byte per access. have = 1 ele_count = needed needed += needed_after for _ in range(ele_count): cur = [] if have < needed: if have == 1 and needed >= 2: cur.append(_dup) have += 1 if have == 2 and needed >= 4: cur.append(_dup2) have += 2 have -= 1 needed -= 1 yield cur assert(have >= needed) # check if we have to pop at end yield [_pop]*(have-needed) # Range of instruction indexes at which a given register is read (in linear code) class UseRange: def __init__(self, uses): self.uses = uses def add(self, i): self.uses.append(i) @property def start(self): return self.uses[0] @property def end(self): return self.uses[-1] def subtract(self, other): s, e = other.start, other.end left = [i for i in self.uses if i < s] right = [i for i in self.uses if i > e] if len(left) >= 2: yield UseRange(left) if len(right) >= 2: yield UseRange(right) def sortkey(self): return len(self.uses), self.uses[0] def makeRange(instr): assert(isinstance(instr, ir.RegAccess) and not instr.store) return UseRange([]) def dup2ize(irdata): # This optimization replaces narrow registers which are frequently read at # stack height 0 with a single read followed by the more efficient dup and # dup2 instructions. This asymptotically uses only half a byte per access. # For simplicity, instead of explicitly keeping track of which locations # have stack height 0, we take advantage of the invariant that ranges of code # corresponding to a single Dalvik instruction always begin with empty stack. # These can be recognized by labels with a non-None id. # This isn't true for move-result instructions, but in that case the range # won't begin with a register load so it doesn't matter. # Note that pruneStoreLoads breaks this invariant, so dup2ize must be run first. # Also, for simplicity, we only keep at most one such value on the stack at # a time (duplicated up to 4 times). instrs = irdata.flat_instructions ranges = [] current = {} at_head = False for i, instr in enumerate(instrs): # if not linear section of bytecode, reset everything. Exceptions are ok # since they clear the stack, but jumps obviously aren't. if instr in irdata.jump_targets or isinstance(instr, (ir.If, ir.Switch)): ranges.extend(current.values()) current = {} if isinstance(instr, ir.RegAccess): key = instr.key if not instr.wide: if instr.store: if key in current: ranges.append(current.pop(key)) elif at_head: current.setdefault(key, makeRange(instr)).add(i) at_head = isinstance(instr, ir.Label) and instr.id is not None ranges.extend(current.values()) ranges = [ur for ur in ranges if len(ur.uses) >= 2] ranges.sort(key=UseRange.sortkey) # Greedily choose a set of disjoint ranges to dup2ize. chosen = [] while ranges: best = ranges.pop() chosen.append(best) newranges = [] for ur in ranges: newranges.extend(ur.subtract(best)) ranges = sorted(newranges, key=UseRange.sortkey) replace = {} for ur in chosen: gen = genDups(len(ur.uses), 0) for pos in ur.uses: ops = [ir.Other(bytecode) for bytecode in next(gen)] # remember to include initial load! if pos == ur.start: ops = [instrs[pos]] + ops replace[instrs[pos]] = ops irdata.replaceInstrs(replace)
jamesmarva/enjarify
enjarify/jvm/optimization/stack.py
Python
apache-2.0
9,011
[ "VisIt" ]
8bf2e9b420b7176fcb72c96b1ad3bcb55486641783deb443cf11331e43d151df
from __future__ import print_function import pyspeckit # Grab a .fits spectrum with a legitimate header sp = pyspeckit.Spectrum('G031.947+00.076_nh3_11_Tastar.fits') """ HEADER: SIMPLE = T / Written by IDL: Tue Aug 31 18:17:01 2010 BITPIX = -64 NAXIS = 1 / number of array dimensions NAXIS1 = 8192 /Number of positions along axis 1 CDELT1 = -0.077230503 CRPIX1 = 4096.0000 CRVAL1 = 68.365635 CTYPE1 = 'VRAD' CUNIT1 = 'km/s ' SPECSYS = 'LSRK' RESTFRQ = 2.3694500e+10 VELOSYS = -43755.930 CDELT1F = 6103.5156 CRPIX1F = 4096.0000 CRVAL1F = 2.3692555e+10 CTYPE1F = 'FREQ' CUNIT1F = 'Hz' SPECSYSF= 'LSRK' RESTFRQF= 2.3694500e+10 VELOSYSF= -43755.930 VDEF = 'RADI-LSR' SRCVEL = 70.000000 ZSOURCE = 0.00023349487 BUNIT = 'K ' OBJECT = 'G031.947+00.076' TELESCOP= 'GBT' TSYS = 42.1655 ELEV = 34.904846 AIRMASS = 1.7475941 LINE = 'nh3_11' FREQ = 23.692555 TARGLON = 31.947236 TARGLAT = 0.076291610 MJD-AVG = 54548.620 CONTINUU= 0.0477613 CONTERR = 0.226990 SMTHOFF = 0 COMMENT 1 blank line END """ # Start by computing the error using a reasonably signal-free region sp.error[:] = sp.stats((-100, 50))['std'] # Change the plot range to be a reasonable physical coverage (the default is to # plot the whole 8192 channel spectrum) sp.plotter(xmin=-100,xmax=300) # There are many extra channels, so let's smooth. Default is a Gaussian # smooth. Downsampling helps speed up the fitting (assuming the line is still # Nyquist sampled, which it is) sp.smooth(2) # replot after smoothing sp.plotter(xmin=-100,xmax=300) # First, fit a gaussian to the whole spectrum as a "first guess" (good at # picking up the centroid, bad at getting the width right) # negamp=False forces the fitter to search for a positive peak, not the # negatives created in this spectrum by frequency switching sp.specfit.selectregion(xmin=60,xmax=120,xtype='wcs') sp.specfit(negamp=False, guesses='moments') # Save the fit... sp.plotter.figure.savefig('nh3_gaussfit.png') # and print some information to screen print("Guesses: ", sp.specfit.guesses) print("Best fit: ", sp.specfit.modelpars) # Run the ammonia spec fitter with a reasonable guess # Since we only have a single line (1-1), the kinetic temperature is # unconstrained: we'll fix it at 7 K. Similarly, the ortho fraction # is fixed to 0.5 T=True; F=False sp.specfit(fittype='ammonia_tau', guesses=[7,4.45,4.5,0.84,96.2,0.43], fixed=[T,F,F,F,F,T], quiet=False) # plot up the residuals in a different window. The residuals strongly suggest # the presence of a second velocity component. sp.specfit.plotresiduals() sp.plotter.figure.savefig('nh3_ammonia_vtau_fit.png') print("Guesses: ", sp.specfit.guesses) print("Best fit: ", sp.specfit.modelpars) # re-plot zoomed in sp.plotter(xmin=70,xmax=125) # replot the fit sp.specfit.plot_fit() sp.plotter.figure.savefig('nh3_ammonia_fit_vtau_zoom.png') # refit with two components sp.specfit(fittype='ammonia_tau', guesses=[7,3.5,4.5,0.68,97.3,0.5]+[7,4.2,4.5,0.52,95.8,0.5], fixed=[T,F,F,F,F,T]*2, quiet=False) sp.specfit.plotresiduals() sp.plotter.figure.savefig('nh3_ammonia_multifit_vtau_zoom.png') # compare to the 'thin' version # In the thin version, Tex = Tk by force sp.specfit.Registry.add_fitter('ammonia_tau_thin', pyspeckit.spectrum.models.ammonia.ammonia_model_vtau_thin(), 5) sp.specfit(fittype='ammonia_tau_thin', guesses=[7,4.5,0.68,97.3,0.5]+[7,4.5,0.52,95.8,0.5], fixed=[F,F,F,F,T]*2, quiet=False) sp.specfit.plotresiduals() sp.plotter.figure.savefig('nh3_ammonia_multifit_vtau_thin_zoom.png')
vlas-sokolov/pyspeckit
examples/ammonia_vtau_fit_example.py
Python
mit
3,778
[ "Gaussian" ]
3c25db86de5d9d8d2beba48046a7c4e909d68827f52f0b63b92ddeba66ca89ce
"""A VTK interactor scene which provides a convenient toolbar that allows the user to set the camera view, turn on the axes indicator etc. """ # Authors: Prabhu Ramachandran <prabhu_r@users.sf.net>, # Dave Peterson <dpeterson@enthought.com> # Copyright (c) 2006, Enthought, Inc. # License: BSD Style. # System imports. from os.path import dirname import os from pyface.qt import QtGui # Enthought library imports. from pyface.api import ImageResource, FileDialog, OK from pyface.action.api import ToolBarManager, Group, Action from tvtk.api import tvtk from traits.api import Instance, false, Either, List # Local imports. from scene import Scene ########################################################################### # 'DecoratedScene' class ########################################################################### class DecoratedScene(Scene): """A VTK interactor scene which provides a convenient toolbar that allows the user to set the camera view, turn on the axes indicator etc. """ ####################################################################### # Traits ####################################################################### if hasattr(tvtk, 'OrientationMarkerWidget'): # The tvtk orientation marker widget. This only exists in VTK # 5.x. marker = Instance(tvtk.OrientationMarkerWidget, ()) # The tvtk axes that will be shown for the orientation. axes = Instance(tvtk.AxesActor, ()) else: marker = None axes = None # Determine if the orientation axis is shown or not. show_axes = false # The list of actions represented in the toolbar actions = List(Either(Action, Group)) ########################################################################## # `object` interface ########################################################################## def __init__(self, parent, **traits): super(DecoratedScene, self).__init__(parent, **traits) self._setup_axes_marker() def __get_pure_state__(self): """Allows us to pickle the scene.""" # The control attribute is not picklable since it is a VTK # object so we remove it. d = super(DecoratedScene, self).__get_pure_state__() for x in ['_content', '_panel', '_tool_bar', 'actions']: d.pop(x, None) return d ########################################################################## # Non-public interface. ########################################################################## def _create_control(self, parent): """ Create the toolkit-specific control that represents the widget. Overridden to wrap the Scene control within a panel that also contains a toolbar. """ # Create a panel as a wrapper of the scene toolkit control. This # allows us to also add additional controls. self._panel = QtGui.QMainWindow() # Add our toolbar to the panel. tbm = self._get_tool_bar_manager() self._tool_bar = tbm.create_tool_bar(self._panel) self._panel.addToolBar(self._tool_bar) # Create the actual scene content self._content = super(DecoratedScene, self)._create_control(self._panel) self._panel.setCentralWidget(self._content) return self._panel def _setup_axes_marker(self): axes = self.axes if axes is None: # For VTK versions < 5.0. return axes.set( normalized_tip_length=(0.4, 0.4, 0.4), normalized_shaft_length=(0.6, 0.6, 0.6), shaft_type='cylinder' ) p = axes.x_axis_caption_actor2d.caption_text_property axes.y_axis_caption_actor2d.caption_text_property = p axes.z_axis_caption_actor2d.caption_text_property = p p.set(color=(1,1,1), shadow=False, italic=False) self._background_changed(self.background) self.marker.set(key_press_activation=False) self.marker.orientation_marker = axes def _get_tool_bar_manager(self): """ Returns the tool_bar_manager for this scene. """ tbm = ToolBarManager( *self.actions ) return tbm def _get_image_path(self): """Returns the directory which contains the images used by the toolbar.""" # So that we can find the images. import tvtk.pyface.api return dirname(tvtk.pyface.api.__file__) def _toggle_projection(self): """ Toggle between perspective and parallel projection, this is used for the toolbar. """ if self._panel is not None: self.parallel_projection = not self.parallel_projection def _toggle_axes(self, *args): """Used by the toolbar to turn on/off the axes indicator. """ if self._panel is not None: self.show_axes = not self.show_axes def _save_snapshot(self): """Invoked by the toolbar menu to save a snapshot of the scene to an image. Note that the extension of the filename determines what image type is saved. The default is PNG. """ if self._panel is not None: wildcard = "PNG images (*.png)|*.png|Determine by extension (*.*)|*.*" dialog = FileDialog( parent = self._panel, title = 'Save scene to image', action = 'save as', default_filename = "snapshot.png", wildcard = wildcard ) if dialog.open() == OK: # The extension of the path will determine the actual # image type saved. self.save(dialog.path) def _configure_scene(self): """Invoked when the toolbar icon for configuration is clicked. """ self.edit_traits() ###################################################################### # Trait handlers. ###################################################################### def _show_axes_changed(self): marker = self.marker if (self._vtk_control is not None) and (marker is not None): if not self.show_axes: marker.interactor = None marker.enabled = False else: marker.interactor = self.interactor marker.enabled = True self.render() def _background_changed(self, value): # Depending on the background, this sets the axes text and # outline color to something that should be visible. axes = self.axes if (self._vtk_control is not None) and (axes is not None): p = self.axes.x_axis_caption_actor2d.caption_text_property m = self.marker s = value[0] + value[1] + value[2] if s <= 1.0: p.color = (1,1,1) m.set_outline_color(1,1,1) else: p.color = (0,0,0) m.set_outline_color(0,0,0) self.render() def _actions_default(self): return [ Group( Action( image = ImageResource('16x16/x-axis', search_path = [self._get_image_path()], ), tooltip = "View along the -X axis", on_perform = self.x_minus_view, ), Action( image = ImageResource('16x16/x-axis', search_path = [self._get_image_path()], ), tooltip = "View along the +X axis", on_perform = self.x_plus_view, ), Action( image = ImageResource('16x16/y-axis', search_path = [self._get_image_path()], ), tooltip = "View along the -Y axis", on_perform = self.y_minus_view, ), Action( image = ImageResource('16x16/y-axis', search_path = [self._get_image_path()], ), tooltip = "View along the +Y axis", on_perform = self.y_plus_view, ), Action( image = ImageResource('16x16/z-axis', search_path = [self._get_image_path()], ), tooltip = "View along the -Z axis", on_perform = self.z_minus_view, ), Action( image = ImageResource('16x16/z-axis', search_path = [self._get_image_path()], ), tooltip = "View along the +Z axis", on_perform = self.z_plus_view, ), Action( image = ImageResource('16x16/isometric', search_path = [self._get_image_path()], ), tooltip = "Obtain an isometric view", on_perform = self.isometric_view, ), ), Group( Action( image = ImageResource('16x16/parallel', search_path = [self._get_image_path()], ), tooltip = 'Toggle parallel projection', style="toggle", on_perform = self._toggle_projection, checked = self.parallel_projection, ), Action( image = ImageResource('16x16/origin_glyph', search_path = [self._get_image_path()], ), tooltip = 'Toggle axes indicator', style="toggle", enabled=(self.marker is not None), on_perform = self._toggle_axes, checked = self.show_axes, ), Action( image = ImageResource('16x16/fullscreen', search_path = [self._get_image_path()], ), tooltip = 'Full Screen (press "q" or "e" or Esc to exit fullscreen)', style="push", on_perform = self._full_screen_fired, ), ), Group( Action( image = ImageResource('16x16/save', search_path = [self._get_image_path()], ), tooltip = "Save a snapshot of this scene", on_perform = self._save_snapshot, ), Action( image = ImageResource('16x16/configure', search_path = [self._get_image_path()], ), tooltip = 'Configure the scene', style="push", on_perform = self._configure_scene, ), ), ]
liulion/mayavi
tvtk/pyface/ui/qt4/decorated_scene.py
Python
bsd-3-clause
11,285
[ "VTK" ]
3a85894b0ed87b3016c7e4e683d0d1cadc3b3acca34388c8f342cd077206afe8
""" Kernel Density Estimation ------------------------- """ # Author: Jake Vanderplas <jakevdp@cs.washington.edu> import numpy as np from scipy.special import gammainc from ..base import BaseEstimator from ..utils import check_array, check_random_state from ..utils.extmath import row_norms from .ball_tree import BallTree, DTYPE from .kd_tree import KDTree VALID_KERNELS = ['gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', 'cosine'] TREE_DICT = {'ball_tree': BallTree, 'kd_tree': KDTree} # TODO: implement a brute force version for testing purposes # TODO: bandwidth estimation # TODO: create a density estimation base class? class KernelDensity(BaseEstimator): """Kernel Density Estimation Read more in the :ref:`User Guide <kernel_density>`. Parameters ---------- bandwidth : float The bandwidth of the kernel. algorithm : string The tree algorithm to use. Valid options are ['kd_tree'|'ball_tree'|'auto']. Default is 'auto'. kernel : string The kernel to use. Valid kernels are ['gaussian'|'tophat'|'epanechnikov'|'exponential'|'linear'|'cosine'] Default is 'gaussian'. metric : string The distance metric to use. Note that not all metrics are valid with all algorithms. Refer to the documentation of :class:`BallTree` and :class:`KDTree` for a description of available algorithms. Note that the normalization of the density output is correct only for the Euclidean distance metric. Default is 'euclidean'. atol : float The desired absolute tolerance of the result. A larger tolerance will generally lead to faster execution. Default is 0. rtol : float The desired relative tolerance of the result. A larger tolerance will generally lead to faster execution. Default is 1E-8. breadth_first : boolean If true (default), use a breadth-first approach to the problem. Otherwise use a depth-first approach. leaf_size : int Specify the leaf size of the underlying tree. See :class:`BallTree` or :class:`KDTree` for details. Default is 40. metric_params : dict Additional parameters to be passed to the tree for use with the metric. For more information, see the documentation of :class:`BallTree` or :class:`KDTree`. """ def __init__(self, bandwidth=1.0, algorithm='auto', kernel='gaussian', metric="euclidean", atol=0, rtol=0, breadth_first=True, leaf_size=40, metric_params=None): self.algorithm = algorithm self.bandwidth = bandwidth self.kernel = kernel self.metric = metric self.atol = atol self.rtol = rtol self.breadth_first = breadth_first self.leaf_size = leaf_size self.metric_params = metric_params # run the choose algorithm code so that exceptions will happen here # we're using clone() in the GenerativeBayes classifier, # so we can't do this kind of logic in __init__ self._choose_algorithm(self.algorithm, self.metric) if bandwidth <= 0: raise ValueError("bandwidth must be positive") if kernel not in VALID_KERNELS: raise ValueError("invalid kernel: '{0}'".format(kernel)) def _choose_algorithm(self, algorithm, metric): # given the algorithm string + metric string, choose the optimal # algorithm to compute the result. if algorithm == 'auto': # use KD Tree if possible if metric in KDTree.valid_metrics: return 'kd_tree' elif metric in BallTree.valid_metrics: return 'ball_tree' else: raise ValueError("invalid metric: '{0}'".format(metric)) elif algorithm in TREE_DICT: if metric not in TREE_DICT[algorithm].valid_metrics: raise ValueError("invalid metric for {0}: " "'{1}'".format(TREE_DICT[algorithm], metric)) return algorithm else: raise ValueError("invalid algorithm: '{0}'".format(algorithm)) def fit(self, X, y=None): """Fit the Kernel Density model on the data. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. """ algorithm = self._choose_algorithm(self.algorithm, self.metric) X = check_array(X, order='C', dtype=DTYPE) kwargs = self.metric_params if kwargs is None: kwargs = {} self.tree_ = TREE_DICT[algorithm](X, metric=self.metric, leaf_size=self.leaf_size, **kwargs) return self def score_samples(self, X): """Evaluate the density model on the data. Parameters ---------- X : array_like, shape (n_samples, n_features) An array of points to query. Last dimension should match dimension of training data (n_features). Returns ------- density : ndarray, shape (n_samples,) The array of log(density) evaluations. """ # The returned density is normalized to the number of points. # For it to be a probability, we must scale it. For this reason # we'll also scale atol. X = check_array(X, order='C', dtype=DTYPE) N = self.tree_.data.shape[0] atol_N = self.atol * N log_density = self.tree_.kernel_density( X, h=self.bandwidth, kernel=self.kernel, atol=atol_N, rtol=self.rtol, breadth_first=self.breadth_first, return_log=True) log_density -= np.log(N) return log_density def score(self, X, y=None): """Compute the total log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- logprob : float Total log-likelihood of the data in X. """ return np.sum(self.score_samples(X)) def sample(self, n_samples=1, random_state=None): """Generate random samples from the model. Currently, this is implemented only for gaussian and tophat kernels. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. random_state : int, RandomState instance or None. default to None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- X : array_like, shape (n_samples, n_features) List of samples. """ # TODO: implement sampling for other valid kernel shapes if self.kernel not in ['gaussian', 'tophat']: raise NotImplementedError() data = np.asarray(self.tree_.data) rng = check_random_state(random_state) i = rng.randint(data.shape[0], size=n_samples) if self.kernel == 'gaussian': return np.atleast_2d(rng.normal(data[i], self.bandwidth)) elif self.kernel == 'tophat': # we first draw points from a d-dimensional normal distribution, # then use an incomplete gamma function to map them to a uniform # d-dimensional tophat distribution. dim = data.shape[1] X = rng.normal(size=(n_samples, dim)) s_sq = row_norms(X, squared=True) correction = (gammainc(0.5 * dim, 0.5 * s_sq) ** (1. / dim) * self.bandwidth / np.sqrt(s_sq)) return data[i] + X * correction[:, np.newaxis]
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/sklearn/neighbors/kde.py
Python
mit
8,218
[ "Gaussian" ]
0e8971ce7a990bcab68d2aaf7cb11c05ac0f887443310507960110d9b326e05b
# $Id$ # # Copyright (C) 2000-2006 greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ defines class _DbConnect_, for abstracting connections to databases """ from rdkit import RDConfig import sys,types import exceptions class DbError(RuntimeError): pass from rdkit.Dbase import DbUtils,DbInfo import DbModule class DbConnect(object): """ This class is intended to abstract away many of the details of interacting with databases. It includes some GUI functionality """ def __init__(self,dbName='',tableName='',user='sysdba',password='masterkey'): """ Constructor **Arguments** (all optional) - dbName: the name of the DB file to be used - tableName: the name of the table to be used - user: the username for DB access - password: the password to be used for DB access """ self.dbName = dbName self.tableName = tableName self.user = user self.password = password self.cn = None self.cursor = None def UpdateTableNames(self,dlg): """ Modifies a connect dialog to reflect new table names **Arguments** - dlg: the dialog to be updated """ self.user = self.userEntry.GetValue() self.password = self.passwdEntry.GetValue() self.dbName = self.dbBrowseButton.GetValue() for i in xrange(self.dbTableChoice.Number()): self.dbTableChoice.Delete(0) names = self.GetTableNames() for name in names: self.dbTableChoice.Append(name) dlg.sizer.Fit(dlg) dlg.sizer.SetSizeHints(dlg) dlg.Refresh() def GetTableNames(self,includeViews=0): """ gets a list of tables available in a database **Arguments** - includeViews: if this is non-null, the views in the db will also be returned **Returns** a list of table names **Notes** - this uses _DbInfo.GetTableNames_ """ return DbInfo.GetTableNames(self.dbName,self.user,self.password, includeViews=includeViews,cn=self.cn) def GetColumnNames(self,table='',join='',what='*',where='',**kwargs): """ gets a list of columns available in the current table **Returns** a list of column names **Notes** - this uses _DbInfo.GetColumnNames_ """ if not table: table = self.tableName return DbInfo.GetColumnNames(self.dbName,table, self.user,self.password, join=join,what=what,cn=self.cn) def GetColumnNamesAndTypes(self,table='',join='',what='*',where='',**kwargs): """ gets a list of columns available in the current table along with their types **Returns** a list of 2-tuples containing: 1) column name 2) column type **Notes** - this uses _DbInfo.GetColumnNamesAndTypes_ """ if not table: table = self.tableName return DbInfo.GetColumnNamesAndTypes(self.dbName,table, self.user,self.password, join=join,what=what,cn=self.cn) def GetColumns(self,fields,table='',join='',**kwargs): """ gets a set of data from a table **Arguments** - fields: a string with the names of the fields to be extracted, this should be a comma delimited list **Returns** a list of the data **Notes** - this uses _DbUtils.GetColumns_ """ if not table: table = self.tableName return DbUtils.GetColumns(self.dbName,table,fields, self.user,self.password, join=join) def GetData(self,table=None,fields='*',where='',removeDups=-1,join='', transform=None,randomAccess=1,**kwargs): """ a more flexible method to get a set of data from a table **Arguments** - table: (optional) the table to use - fields: a string with the names of the fields to be extracted, this should be a comma delimited list - where: the SQL where clause to be used with the DB query - removeDups: indicates which column should be used to recognize duplicates in the data. -1 for no duplicate removal. **Returns** a list of the data **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName kwargs['forceList'] = kwargs.get('forceList',0) return DbUtils.GetData(self.dbName,table,fieldString=fields,whereString=where, user=self.user,password=self.password,removeDups=removeDups, join=join,cn=self.cn, transform=transform,randomAccess=randomAccess,**kwargs) def GetDataCount(self,table=None,where='',join='',**kwargs): """ returns a count of the number of results a query will return **Arguments** - table: (optional) the table to use - where: the SQL where clause to be used with the DB query - join: the SQL join clause to be used with the DB query **Returns** an int **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName return DbUtils.GetData(self.dbName,table,fieldString='count(*)', whereString=where,cn=self.cn, user=self.user,password=self.password,join=join,forceList=0)[0][0] def GetCursor(self): """ returns a cursor for direct manipulation of the DB only one cursor is available """ if self.cursor is not None: return self.cursor self.cn = DbModule.connect(self.dbName,self.user,self.password) self.cursor = self.cn.cursor() return self.cursor def KillCursor(self): """ closes the cursor """ self.cursor = None self.cn = None def AddTable(self,tableName,colString): """ adds a table to the database **Arguments** - tableName: the name of the table to add - colString: a string containing column defintions **Notes** - if a table named _tableName_ already exists, it will be dropped - the sqlQuery for addition is: "create table %(tableName) (%(colString))" """ c = self.GetCursor() try: c.execute('drop table %s cascade'%tableName) except: try: c.execute('drop table %s'%tableName) except: pass self.Commit() addStr = 'create table %s (%s)'%(tableName,colString) try: c.execute(addStr) except: import traceback print 'command failed:',addStr traceback.print_exc() else: self.Commit() def InsertData(self,tableName,vals): """ inserts data into a table **Arguments** - tableName: the name of the table to manipulate - vals: a sequence with the values to be inserted """ c = self.GetCursor() if type(vals) != types.TupleType: vals = tuple(vals) insTxt = '('+','.join([DbModule.placeHolder]*len(vals))+')' #insTxt = '(%s'%('%s,'*len(vals)) #insTxt = insTxt[0:-1]+')' cmd = "insert into %s values %s"%(tableName,insTxt) try: c.execute(cmd,vals) except: import traceback print 'insert failed:' print cmd print 'the error was:' traceback.print_exc() raise DbError,"Insert Failed" def InsertColumnData(self,tableName,columnName,value,where): """ inserts data into a particular column of the table **Arguments** - tableName: the name of the table to manipulate - columnName: name of the column to update - value: the value to insert - where: a query yielding the row where the data should be inserted """ c = self.GetCursor() cmd = "update %s set %s=%s where %s"%(tableName,columnName, DbModule.placeHolder,where) c.execute(cmd,(value,)) def AddColumn(self,tableName,colName,colType): """ adds a column to a table **Arguments** - tableName: the name of the table to manipulate - colName: name of the column to insert - colType: the type of the column to add """ c = self.GetCursor() try: c.execute("alter table %s add %s %s"%(tableName,colName,colType)) except: print 'AddColumn failed' def Commit(self): """ commits the current transaction """ self.cn.commit()
rdkit/rdkit-orig
rdkit/Dbase/DbConnection.py
Python
bsd-3-clause
8,808
[ "RDKit" ]
cf72fe82763c35cccab5b6ae1a82bf2ee7eb2b35b7bd86a511582c5b2edd389c
import logging from logging.handlers import SysLogHandler from logging import Formatter LOG_PATH = '/var/log/syslog' LOG_APP_LABEL = 'moosefstool' LOG_MFS_LABEL = 'mfsmaster' def get_logger(): """ get_logger function provides logging object with file/syslog handlers. Path to local Moose log file could be obtained from Moose app config. By default this path is /var/log/moosetool.log. In [logging] section in app's config there is ability to specify appropriate type of logging for you (file, syslog, both types). """ logger = logging.getLogger() logger.setLevel(logging.ERROR) formatStr = '%(asctime)s {0} - - %(name)s: %(levelname)s %(message)s'.format(LOG_APP_LABEL) formatter = Formatter(formatStr) log_handler = SysLogHandler(address='/dev/log') log_handler.setFormatter(formatter) logger.addHandler(log_handler) return logger logger = get_logger()
ochirkov/MooseFSTool
app/utils/log_helper.py
Python
gpl-3.0
931
[ "MOOSE" ]
6ce34467107c4a47ac69008215e099851a081169d32c826a81b28d00411fb2b9
#!/usr/bin/python # # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # # Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_clusterclouddetails author: Gaurav Rastogi (grastogi@avinetworks.com) short_description: Module for setup of ClusterCloudDetails Avi RESTful Object description: - This module is used to configure ClusterCloudDetails object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.5" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] azure_info: description: - Azure info to configure cluster_vip on the controller. - Field introduced in 17.2.5. name: description: - Field introduced in 17.2.5. required: true tenant_ref: description: - It is a reference to an object of type tenant. - Field introduced in 17.2.5. url: description: - Avi controller URL of the object. uuid: description: - Field introduced in 17.2.5. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create ClusterCloudDetails object avi_clusterclouddetails: controller: 10.10.25.42 username: admin password: something state: present name: sample_clusterclouddetails """ RETURN = ''' obj: description: ClusterCloudDetails (api/clusterclouddetails) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), azure_info=dict(type='dict',), name=dict(type='str', required=True), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'clusterclouddetails', set([])) if __name__ == '__main__': main()
alexlo03/ansible
lib/ansible/modules/network/avi/avi_clusterclouddetails.py
Python
gpl-3.0
3,609
[ "VisIt" ]
6cfcda1788aaa90ac71b372f1793e429386f93253784482c41f26c9914f54fbc
""" A simple manager for a task queue. The manager handles creating, submitting, and managing running jobs, and can even resubmit jobs that have failed. author: Brian Schrader since: 2015-08-27 """ from .reporting import BaseReportingMixin, HtmlReportingMixin, TextReportingMixin from .job_template import JobTemplate class BaseQueue(object): """ An abstract class for managing a queue of jobs. To use this class, subclass it and fill in the callbacks you need. """ MAX_CONCURRENT_JOBS = 10 def __init__(self, name=''): self.name = name self.queue = [] self.running = [] self.failed = [] self.complete = [] def __repr__(self): return '<Queue: jobs=%s>' % str(len(self.active_jobs)) @property def is_empty(self): return len(self.active_jobs) == 0 @property def active_jobs(self): """ Returns a list of all jobs submitted to the queue, or in progress. """ return list(set(self.queue + self.running)) @property def all_jobs(self): """ Returns a list of all jobs submitted to the queue, complete, in-progess or failed. """ return list(set(self.complete + self.failed + self.queue + self.running)) @property def progress(self): """ Returns the percentage, current and total number of jobs in the queue. """ total = len(self.all_jobs) remaining = total - len(self.active_jobs) if total > 0 else 0 percent = int(100 * (float(remaining) / total)) if total > 0 else 0 return percent def ready(self, job): """ Determines if the job is ready to be sumitted to the queue. It checks if the job depends on any currently running or queued operations. """ no_deps = len(job.depends_on) == 0 all_complete = all(j.is_complete() for j in self.active_jobs if j.alias in job.depends_on) none_failed = not any(True for j in self.failed if j.alias in job.depends_on) queue_is_open = len(self.running) < self.MAX_CONCURRENT_JOBS return queue_is_open and (no_deps or (all_complete and none_failed)) def locked(self): """ Determines if the queue is locked. """ if len(self.failed) == 0: return False for fail in self.failed: for job in self.active_jobs: if fail.alias in job.depends_on: return True def push(self, job): """ Push a job onto the queue. This does not submit the job. """ self.queue.append(job) def tick(self): """ Submits all the given jobs in the queue and watches their progress as they proceed. This function yields at the end of each iteration of the queue. :raises RuntimeError: If queue is locked. """ self.on_start() while not self.is_empty: cruft = [] for job in self.queue: if not self.ready(job): continue self.on_ready(job) try: job.submit() except ValueError: if job.should_retry: self.on_error(job) job.attempts += 1 else: self.on_fail(job) cruft.append(job) self.failed.append(job) else: self.running.append(job) self.on_submit(job) cruft.append(job) self.queue = [job for job in self.queue if job not in cruft] cruft = [] for job in self.running: if job.is_running() or job.is_queued(): pass elif job.is_complete(): self.on_complete(job) cruft.append(job) self.complete.append(job) elif job.is_fail(): self.on_fail(job) cruft.append(job) self.failed.append(job) elif job.is_error(): self.on_error(job) cruft.append(job) else: pass self.running = [job for job in self.running if job not in cruft] if self.locked() and self.on_locked(): raise RuntimeError self.on_tick() yield self.on_end() # Callbacks... def on_start(self): """ Called when the queue is starting up. """ pass def on_end(self): """ Called when the queue is shutting down. """ pass def on_locked(self): """ Called when the queue is locked and no jobs can proceed. If this callback returns True, then the queue will be restarted, else it will be terminated. """ return True def on_tick(self): """ Called when a tick of the queue is complete. """ pass def on_ready(self, job): """ Called when a job is ready to be submitted. :param job: The given job that is ready. """ pass def on_submit(self, job): """ Called when a job has been submitted. :param job: The given job that has been submitted. """ pass def on_complete(self, job): """ Called when a job has completed. :param job: The given job that has completed. """ pass def on_error(self, job): """ Called when a job has errored. By default, the job is resubmitted until some max threshold is reached. :param job: The given job that has errored. """ pass def on_fail(self, job): """ Called when a job has failed after multiple resubmissions. The given job will be removed from the queue. :param job: The given job that has errored. """ pass class ReportingJobQueue(BaseReportingMixin, BaseQueue): """ An abstract subclass of the Queue which reports on progress. """ @property def real_jobs(self): """ Returns all jobs that represent work. """ return [j for j in self.all_jobs if not isinstance(j, JobTemplate)] def on_locked(self): self.render('The queue is locked. Please check the logs.', self.progress) return True def on_submit(self, job): if not isinstance(job, JobTemplate): self.render('Submitted: %s' % job.alias, self.progress) def on_complete(self, job): if not isinstance(job, JobTemplate): self.render('Complete: %s' % job.alias, self.progress) def on_error(self, job): if not isinstance(job, JobTemplate): self.render('Error: Job %s has failed, retrying (%s/%s)' % (job.alias, str(job.attempts), str(job.MAX_RETRY)), self.progress) def on_fail(self, job): if not isinstance(job, JobTemplate): self.render('Error: Job %s has failed. Retried %s times.' % (job.alias, str(job.attempts)), self.progress) def on_end(self): self.render('All jobs are complete.', self.progress) class HtmlReportingJobQueue(HtmlReportingMixin, ReportingJobQueue): """ A queue that generates HTML reports. """ pass class TextReportingJobQueue(TextReportingMixin, ReportingJobQueue): """ A queue that generates textual reports. """ pass
TorkamaniLab/metapipe
metapipe/models/queue.py
Python
mit
7,561
[ "Brian" ]
0de567c6f31939d32b01b150789d7a8433dc49cf11b38c6e6d9b5feadade2570
# -*- coding: utf-8 from yade import ymport, utils,pack,export import gts,os from yade import geom #import matplotlib from yade import plot #from pylab import * #import os.path, locale #### set False when running in batch mode #defaultTable = True defaultTable = False ####------------------------------------- ####------------------------------------- utils.readParamsFromTable( rm = 0.33, noTableOk = True ) from yade.params.table import * print 'rm=',rm O.tags['description']='triaxial_rm_'+str(rm) ################################# ##### FUNCTIONS #### ################################# def hMax(n): idHMax=0 hMax=-1000000.0 for i in O.bodies: h=i.state.pos[n] if (h>hMax): hMax=h idHMax=i.id hMax=hMax+O.bodies[idHMax].shape.radius return (hMax) def hMin(n): idHMin=0 hMin=100000.0 for i in O.bodies: h=i.state.pos[n] if (h<hMin): hMin=h idHMin=i.id hMin=hMin-O.bodies[idHMin].shape.radius return (hMin) #Function in order to calculate rmin (minimum radius) and rmax (maximum radius) def MinMax(): rmax=0 rmin=10 r=0 for i in O.bodies: if(type(i.shape)==Sphere): r=i.shape.radius if(r>rmax): rmax=r if(r<rmin): rmin=r l=[rmin,rmax] return (l) def sup(): for i in O.bodies: if (type(i.shape)==Sphere) and (i.state.pos[2]>0.098): O.bodies.erase(i.id) def scalar(u,v): ps=u[0]*v[0]+u[1]*v[1]+u[2]*v[2] return ps def cross(u,v): ps=Vector3(u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2] ,u[0]*v[1]-u[1]*v[0]) return ps def limitfinder(): for b in O.bodies: if(b.state.pos[2]>=L-2*radius): if isinstance(b.shape,GridNode): top_boundary.append(b.id) b.shape.color=(1,0,0) b.state.blockedDOFs='z' if(b.state.pos[2]<0.1*radius ): if isinstance(b.shape,GridNode): bottom_boundary.append(b.id) b.state.blockedDOFs='z' b.shape.color=(1,0,0) ############################## ##### SCRIPT #### ############################## try: os.mkdir('data') except: pass try: os.mkdir('paraview') except: pass isBatch = runningInBatch() #################### ### ENGINES ### #################### O.engines=[ ForceResetter(), InsertionSortCollider([ Bo1_Sphere_Aabb(), Bo1_Wall_Aabb(), Bo1_PFacet_Aabb(), Bo1_Facet_Aabb(), ]), InteractionLoop([ Ig2_GridNode_GridNode_GridNodeGeom6D(), Ig2_GridConnection_GridConnection_GridCoGridCoGeom(), Ig2_Sphere_PFacet_ScGridCoGeom(), Ig2_Sphere_Sphere_ScGeom(), Ig2_Facet_Sphere_ScGeom(), Ig2_Wall_Sphere_ScGeom() ], [Ip2_CohFrictMat_CohFrictMat_CohFrictPhys(setCohesionNow=True,setCohesionOnNewContacts=True), Ip2_FrictMat_FrictMat_FrictPhys()], [Law2_ScGeom6D_CohFrictPhys_CohesionMoment(), Law2_ScGeom_FrictPhys_CundallStrack(), Law2_ScGridCoGeom_FrictPhys_CundallStrack(), Law2_GridCoGridCoGeom_FrictPhys_CundallStrack() ] ), ] ###################### ### PROPERTIES ### ###################### radius=0.0025*rm sigma=-3e6 #### Parameters of a rectangular grid ### L=0.205 #length [m] l=0.101/2. #half width (radius) [m] nbL=36#number of nodes for the length [#] doit etre paire nbl=44 #number of nodes for the perimeter [#] ABSOLUMENT MULTIPLE de 4 !!! #nbL=1 #number of nodes for the length [#] doit etre paire #nbl=4 #number of nodes for the perimeter [#] ABSOLUMENT MULTIPLE de 4 !!! r=radius color=[155./255.,155./255.,100./255.] oriBody = Quaternion(Vector3(0,0,1),(pi/2)) nodesIds=[] nodesIds1=[] cylIds=[] pfIds=[] top_boundary=[] bottom_boundary=[] #################### ### MATERIAL ### #################### poisson=0.28 E=2*7.9e10*(1+poisson) ##1e11 density=7.8e10 Et=0 Emem=E/1e3 frictionAngle=0.096 frictionAngleW=0.228 O.materials.append(CohFrictMat(young=Emem,poisson=poisson,density=density,frictionAngle=0,normalCohesion=1e19,shearCohesion=1e19,momentRotationLaw=False,alphaKr=0,label='NodeMat')) O.materials.append(FrictMat(young=Emem,poisson=poisson,density=density,frictionAngle=0,label='memMat')) O.materials.append(FrictMat(young=E,poisson=poisson,density=density,frictionAngle=frictionAngleW,label='Wallmat')) O.materials.append(FrictMat(young=E,poisson=poisson,density=density,frictionAngle=frictionAngle,label='Smat')) ############################## ### SAMPLE GENERATION ### ############################## kw={'color':[0.6,0.6,0.6],'wire':False,'dynamic':True,'material':3} #pile=ymport.text('spheres.txt',**kw) #pile2=O.bodies.append(pile) #sup() #print hMin(2), hMax(2) #zmin=hMin(2) #zmax=hMax(2) ##L=hMax(2) ################################## ##### MEMBRANE GENERATION ### ################################## #mesh=2 #Create all nodes first : for i in range(0,nbL+1): for j in range(0,nbl): z=i*L/float(nbL) y=l*sin(2*pi*j/float(nbl)) x=l*cos(2*pi*j/float(nbl)) nodesIds.append( O.bodies.append(gridNode([x,y,z],r,wire=False,fixed=False,material='NodeMat',color=color)) ) ##Create connection between the nodes for i in range(0,nbL+1): for j in range(0,nbl-1): O.bodies.append( gridConnection(nodesIds[i*nbl+j],nodesIds[i*nbl+j+1],r,color=color,mask=5,material='memMat') ) for i in range(0,nbL,1): for j in range(0,nbl): O.bodies.append( gridConnection(nodesIds[i*nbl+j],nodesIds[(i+1)*nbl+j],r,color=color,mask=5,material='memMat') ) for i in range(-1,nbL): j=nbl O.bodies.append( gridConnection(nodesIds[i*nbl+j],nodesIds[(i+1)*nbl+j-1],r,color=color,mask=5,material='memMat') ) for i in range(0,nbL): for j in range(0,nbl-1): if (j%2==0): O.bodies.append( gridConnection(nodesIds[i*nbl+j],nodesIds[(i+1)*nbl+j+1],r,color=color,mask=5,material='memMat') ) else: O.bodies.append( gridConnection(nodesIds[(i+1)*nbl+j],nodesIds[i*nbl+j+1],r,color=color,mask=5,material='memMat') ) for i in range(0,nbL): j=nbl #O.bodies[nodesIds[(i-1)*nbl+j]].shape.color=Vector3(155./255.,155./255.,1.) #O.bodies[nodesIds[(i)*nbl+j-1]].shape.color=Vector3(1,0,0) O.bodies.append( gridConnection(nodesIds[(i-1)*nbl+j],nodesIds[(i+1)*nbl+j-1],r,color=color,mask=5,material='memMat') ) ###Create PFacets ##wire=True for i in range(0,nbL): for j in range(0,nbl-1): if (j%2==0): pfIds.append(O.bodies.append(pfacet(nodesIds[i*nbl+j],nodesIds[(i+1)*nbl+j],nodesIds[(i+1)*nbl+j+1],color=color,mask=5,material='memMat'))) pfIds.append(O.bodies.append(pfacet(nodesIds[i*nbl+j],nodesIds[(i+1)*nbl+j+1],nodesIds[(i)*nbl+j+1],color=color,mask=5,material='memMat'))) else: pfIds.append(O.bodies.append(pfacet(nodesIds[i*nbl+j],nodesIds[(i+1)*nbl+j],nodesIds[(i)*nbl+j+1],color=color,mask=5,material='memMat'))) pfIds.append(O.bodies.append(pfacet(nodesIds[i*nbl+j+1],nodesIds[(i+1)*nbl+j],nodesIds[(i+1)*nbl+j+1],color=color,mask=5,material='memMat'))) for i in range(0,nbL,1): j=nbl pfIds.append(O.bodies.append(pfacet( nodesIds[i*nbl+j],nodesIds[(i-1)*nbl+j],nodesIds[(i+1)*nbl+j-1],color=color,material='memMat' ))) pfIds.append(O.bodies.append(pfacet( nodesIds[(i)*nbl+j-1],nodesIds[(i+1)*nbl+j-1],nodesIds[(i-1)*nbl+j],color=color,material='memMat' ))) limitfinder() ######################### ##### WALL GENERATION ## ######################### O.materials.append(FrictMat(young=E,poisson=poisson,density=density,frictionAngle=frictionAngleW,label='Wallmat')) topPlate=utils.wall(position=hMax(2)+radius,sense=0, axis=2,color=Vector3(1,0,0),material='Wallmat') O.bodies.append(topPlate) bottomPlate=utils.wall(position=-hMin(2)-radius,sense=0, axis=2,color=Vector3(1,0,0),material='Wallmat') O.bodies.append(bottomPlate) ################### #### APPLY LOAD ## ################### normalVEL=0 loading=True S0=pi*l**2 normalSTRESS=sigma shearing=False sigmaN=0 #### APPLY CONFINING PRESSURE def Apply_load(): global sigmaN, Fn, top, load,shearing,loading,u Fn=abs(O.forces.f(topPlate.id)[2]) sigmaN=Fn/S0 if abs((normalSTRESS-sigmaN)/normalSTRESS)<0.001: topPlate.state.vel[2]=0 def Apply_confiningpressure(): #print 'Apply_confiningpressure' for i in pfIds: e0 =O.bodies[i].shape.node3.state.pos - O.bodies[i].shape.node1.state.pos e1 =O.bodies[i].shape.node2.state.pos - O.bodies[i].shape.node1.state.pos e2 =O.bodies[i].shape.node2.state.pos - O.bodies[i].shape.node3.state.pos P=(O.bodies[i].shape.node1.state.pos+O.bodies[i].shape.node2.state.pos+O.bodies[i].shape.node3.state.pos)/3 #print e0,e1,e2 #nodesIds.append( O.bodies.append(gridNode([P[0],P[1],P[2]],r,wire=False,fixed=True,material='NodeMat',color=color)) ) #print 'P=',P v0 = e0 v1 = e1 v2 = P - O.bodies[i].shape.node1.state.pos ##// Compute dot products dot00 = scalar(v0,v0) dot01 = scalar(v0,v1) dot02 = scalar(v0,v2) dot11 = scalar(v1,v1) dot12 = scalar(v1,v2) ##// Compute the barycentric coordinates of the projection P invDenom = 1 / (dot00 * dot11 - dot01 * dot01) p1 = (dot11 * dot02 - dot01 * dot12) * invDenom p2 = (dot00 * dot12 - dot01 * dot02) * invDenom p3 = 1-p1-p2 a = sqrt(scalar(e0,e0)) b = sqrt(scalar(e1,e1)) c = sqrt(scalar(e2,e2)) s=0.5*(a+b+c) area= sqrt(s*(s-a)*(s-b)*(s-c)) Fapplied=area*sigma normal = cross(e0,e1) normal=normal/normal.norm() F=Fapplied p1normal=F*p1*normal p2normal=F*p2*normal p3normal=F*p3*normal O.forces.addF(O.bodies[i].shape.node1.id,p1normal,permanent=False) O.forces.addF(O.bodies[i].shape.node2.id,p2normal,permanent=False) O.forces.addF(O.bodies[i].shape.node3.id,p3normal,permanent=False) #Apply_confiningpressure() sigma3=0 def check_confiningpressure(): global sigma3 sigma3=0 for i in pfIds: e0 =O.bodies[i].shape.node3.state.pos - O.bodies[i].shape.node1.state.pos e1 =O.bodies[i].shape.node2.state.pos - O.bodies[i].shape.node1.state.pos e2 =O.bodies[i].shape.node2.state.pos - O.bodies[i].shape.node3.state.pos a = sqrt(scalar(e0,e0)) b = sqrt(scalar(e1,e1)) c = sqrt(scalar(e2,e2)) s=0.5*(a+b+c) area= sqrt(s*(s-a)*(s-b)*(s-c)) F=(O.forces.f(O.bodies[i].shape.node1.id) + O.forces.f(O.bodies[i].shape.node2.id)+O.forces.f(O.bodies[i].shape.node3.id)).norm() sigma3=sigma3+F/area #print sigma3 return sigma3 pos=topPlate.state.pos[2] def dataCollector(): global pos,p,q,sigma1 #if(pos<0.16): #O.wait() #saveData() #O.exitNoBacktrace() S=pi*l**2 Fnt=O.forces.f(topPlate.id)[2] Fnb=O.forces.f(bottomPlate.id)[2] sigma1=Fnt/S sigma3=check_confiningpressure() pos=topPlate.state.pos[2] q=(sigma1-3e6) p=(sigma1+2*3e6)/2 plot.addData(t=O.time,pos=pos,Fnt=Fnt,Fnb=Fnb,sigma1=sigma1,sigma3=sigma3,unbF=unbalancedForce(),p=p,q=q) def saveData(): plot.saveDataTxt('data/'+O.tags['description']+'.dat',vars=('t','pos','Fnt','Fnb','sigma1','sigma3','unbF')) plot.plots={'p':('q')} #### MOVE TOP AND BOTTOM WALL #v=1.7e-03 v=1.7e-05 def moveWall(v): topPlate.state.vel=(0,0,-v) #bottomPlate.state.vel=(0,0,v) #g=-9.81 g=0 #moveWall(v) #limitfinder() ########################### ##### ENGINE DEFINITION ## ########################### O.dt=0.5*PWaveTimeStep() O.engines=O.engines+[ #PyRunner(iterPeriod=1,initRun=True,command='Apply_load()'), PyRunner(iterPeriod=1,dead=False,command='Apply_confiningpressure()'), #PyRunner(iterPeriod=1,initRun=True,command='Apply_load()'), NewtonIntegrator(damping=0.7,gravity=(0,0,g),label='Newton'), #PyRunner(initRun=True,iterPeriod=1,command='dataCollector()'), #VTKRecorder(iterPeriod=500,initRun=True,fileName='paraview/'+O.tags['description']+'_',recorders=['spheres','velocity']), ] if not isBatch: # VISUALIZATION from yade import qt qt.Controller() #qtv = qt.View() #qtr = qt.Renderer() plot.plot(noShow=False, subPlots=True) #O.run(5000) #moveWall(v) else: O.run(1,True) moveWall(v) O.wait() saveData()
anna-effeindzourou/trunk
examples/anna_scripts/triax/triaxial_uniformrm.py
Python
gpl-2.0
11,635
[ "ParaView" ]
33c4db11ba1749babcab7bc84c88e68ee35b26fc805db7c8e4541aecf7e2069a
""" The Script class provides a simple way for users to specify an executable or file to run (and is also a simple example of a workflow module). """ import os, sys, re from DIRAC.Core.Utilities.Subprocess import shellCall from DIRAC import gLogger from DIRAC.Core.Utilities.Os import which from DIRAC.Workflow.Modules.ModuleBase import ModuleBase class Script( ModuleBase ): ############################################################################# def __init__( self ): """ c'tor """ self.log = gLogger.getSubLogger( 'Script' ) super( Script, self ).__init__( self.log ) # Set defaults for all workflow parameters here self.executable = '' self.applicationName = '' self.applicationVersion = '' self.applicationLog = '' self.arguments = '' self.step_commons = {} self.environment = None self.callbackFunction = None self.bufferLimit = 52428800 ############################################################################# def _resolveInputVariables( self ): """ By convention the workflow parameters are resolved here. """ super( Script, self )._resolveInputVariables() super( Script, self )._resolveInputStep() if self.step_commons.has_key( 'arguments' ): self.arguments = self.step_commons['arguments'] ############################################################################# def _initialize( self ): """ simple checks """ if not self.executable: raise RuntimeError, 'No executable defined' def _setCommand( self ): """ set the command that will be executed """ self.command = self.executable if os.path.exists( os.path.basename( self.executable ) ): self.executable = os.path.basename( self.executable ) if not os.access( '%s/%s' % ( os.getcwd(), self.executable ), 5 ): os.chmod( '%s/%s' % ( os.getcwd(), self.executable ), 0755 ) self.command = '%s/%s' % ( os.getcwd(), self.executable ) elif re.search( '.py$', self.executable ): self.command = '%s %s' % ( sys.executable, self.executable ) elif which( self.executable ): self.command = self.executable if self.arguments: self.command = '%s %s' % ( self.command, self.arguments ) self.log.info( 'Command is: %s' % self.command ) def _executeCommand( self ): """ execute the self.command (uses shellCall) """ failed = False outputDict = shellCall( 0, self.command, env = self.environment, callbackFunction = self.callbackFunction, bufferLimit = self.bufferLimit ) if not outputDict['OK']: failed = True self.log.error( 'Shell call execution failed:' ) self.log.error( outputDict['Message'] ) status, stdout, stderr = outputDict['Value'][0:3] if status: failed = True self.log.error( "Non-zero status %s while executing %s" % ( status, self.command ) ) else: self.log.info( "%s execution completed with status %s" % ( self.executable, status ) ) self.log.verbose( stdout ) self.log.verbose( stderr ) if os.path.exists( self.applicationLog ): self.log.verbose( 'Removing existing %s' % self.applicationLog ) os.remove( self.applicationLog ) fopen = open( '%s/%s' % ( os.getcwd(), self.applicationLog ), 'w' ) fopen.write( "<<<<<<<<<< %s Standard Output >>>>>>>>>>\n\n%s " % ( self.executable, stdout ) ) if stderr: fopen.write( "<<<<<<<<<< %s Standard Error >>>>>>>>>>\n\n%s " % ( self.executable, stderr ) ) fopen.close() self.log.info( "Output written to %s, execution complete." % ( self.applicationLog ) ) if failed: raise RuntimeError, "'%s' Exited With Status %s" % ( os.path.basename( self.executable ), status ) def _finalize( self ): """ simply finalize """ status = "%s (%s %s) Successful" % ( os.path.basename( self.executable ), self.applicationName, self.applicationVersion ) super( Script, self )._finalize( status )
avedaee/DIRAC
Core/Workflow/Modules/Script.py
Python
gpl-3.0
4,169
[ "DIRAC" ]
14aa6a0b80fe850e70e687bb94fa45553652398120ab7a23774e9e23b05c5ee7
# Small Genome Tools # Copyright (C) 2015 University of the Witwatersrand, Johannesburg, South Africa # Author: Dr Trevor G. Bell, TrevorGrahamBell@gmail.com # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. #!/usr/bin/python import os import re import sys from Bio import SeqIO import Bio.Seq PROGRAM = 'CLIMBEDmini' VERSION = '0.1.20150115a' BASEREFERENCE = { 'A' : 'A', 'C' : 'C', 'G' : 'G', 'T' : 'T', '-' : '-', 'AC' : 'M', 'AG' : 'R', 'AT' : 'W', 'CG' : 'S', 'CT' : 'Y', 'GT' : 'K', 'ACG' : 'V', 'ACT' : 'H', 'AGT' : 'D', 'CGT' : 'B', 'ACGT' : 'N'} BASES = ['A', 'C', 'G', 'T'] NONBASES = ['M', 'R', 'W', 'S', 'Y', 'K', 'V', 'H', 'D', 'B', 'N', '-'] BASECOMPLEMENT = {'A' : 'T', 'T' : 'A', 'C' : 'G', 'G' : 'C', '-' : '-', 'N' : 'N', 'K' : 'M', 'M' : 'K', 'R' : 'Y', 'Y' : 'R', 'W' : 'W', 'S' : 'S', 'B' : 'V', 'V' : 'B', 'D' : 'H', 'H' : 'D', 'X' : 'X', 'a' : 't', 't' : 'a', 'c' : 'g', 'g' : 'c', 'n' : 'n', 'k' : 'm', 'm' : 'k', 'r' : 'y', 'y' : 'r', 'w' : 'w', 's' : 's', 'b' : 'v', 'v' : 'b', 'd' : 'h', 'h' : 'd', 'x' : 'x'} GAP = '-' DISAMBIGUATE = { 'M' : 'AC', 'R' : 'AG', 'W' : 'AT', 'S' : 'CG', 'Y' : 'CT', 'K' : 'GT', 'V' : 'ACG', 'H' : 'ACT', 'D' : 'AGT', 'B' : 'CGT', 'N' : 'ACGT' } QUALITYTHRESHOLD = 20 BASESTHRESHOLD = 5 GAPCOLUMNTHRESHOLD = 0.80 AMINOACIDS = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'] HIGHLIGHTAMINOACIDS = { 'Met': 'green', 'Ter': 'red', 'Xaa': 'gray', 'Xaa': 'gray', 'Ala': '#BFBFFE', 'Arg': '#FF80FE', 'Asn': '#8080FE', 'Asp': '#BFFFFE', 'Cys': '#80FFFE', 'Gln': '#9999FF', 'Glu': '#7A7ACC', 'Gly': '#FEFF80', 'His': '#B2B300', 'Ile': '#FEBFBF', 'Leu': '#CCCC00', 'Lys': '#BFFEBF', 'Phe': '#80FE80', 'Pro': '#FE8080', 'Ser': '#FF66CC', 'Thr': '#00B3B2', 'Trp': '#8FFEBF', 'Tyr': '#FEFFBF', 'Val': '#80FE80' } SEROPATTERNS = { 'KR...' : 'adr', 'KKP..' : 'adw2', 'KKT..' : 'adw3', 'KK[I|L]..' : 'adw4', 'RR...' : 'ayr', 'RKT..' : 'ayw3', 'RK[I|L]..' : 'ayw4', 'RKPA.' : 'ayw1', 'RKP[^A][^S]' : 'ayw2', 'RKP[^A]S' : 'ayw4' } SEROGROUP = { 'K' : '(ad)', 'R' : '(ay)' } GENOTYPES = {'adw2CGTCA[T|Y|C]...C[A|C]' : 'A1', 'ayw1CGTCA[T|Y|C]...C[A|C]' : 'A1', 'adw2CGGCAC...CG' : 'A2', 'ayw1CGTCA[T|Y|C]...CG' : 'A3', 'ayw1CG.......CG' : 'A4', 'adw.TT.......T.' : 'B1/B2/B3/B6', 'ayw.TT.......T.' : 'B3/B4/B5', 'adrTT.......C.' : 'C1/C2', 'ayrTT.......C.' : 'C1/C2', 'adrCG.......C.' : 'C3', 'ayrCG.......C.' : 'C3', 'ayw.TT.......T.' : 'C4', 'adw2CG.......T.' : 'C5', 'ayw[^4]CG.......T.' : 'D', 'ayw4CG.......T.' : 'E', 'adw4TT.......T.' : 'F1/F4', 'adw4TT.......C.' : 'F2/F3/H', 'adw2CG....TAAT.' : 'G' } HIGHLIGHTSEROTYPES = { '(ad)' : '#FEFF80', '(ay)' : '#7A7ACC', 'Unknown' : 'gray', 'adr' : '#FEFFBF', 'adw2' : '#80FE80', 'adw3' : '#B2B300', 'adw4' : '#BFBFFE', 'ayr' : '#FF80FE', 'ayw1' : '#80FFFE', 'ayw2' : '#FF66CC', 'ayw3' : '#9999FF', 'ayw4' : '#BFFFFE' } S_START = '[A|a][T|t|C|c|G|g][G|g][G|g][A|a][G|A|C|S|g|a|c|s][A|G|R|a|g|r][A|G|R|a|g|r][C|c][A|a][C|T|c|t]' B_START = '[A|a|C|c|T|t][T|t|C|c][G|g|A|a][C|T|c|t][A|a][A|a][C|c][T|t][T|t][T|t][T|t][T|t][C|c][A|a][C|c][C|c][T|t][C|c][T|t][G|g]' TEMPFOLDER = '/tmp/' MAX_FRAGMENTS = 12 if __name__ == '__main__': interactive = True else: interactive = False def motd(): divider = '-' * 40 + '\n' return divider + 'This is %s %s\n\nDependencies:\n\tBioPython from http://www.biopython.org\n\tABIFReader.py from http://www.interactive-biosoftware.com/open-source/ABIFReader.py\n' % (PROGRAM, VERSION) + divider # --------------- def error(message): out = 'Error [%s]: %s' % (sys._getframe(1).f_code.co_name, message) if interactive: sys.stderr.write(out + '\n') else: sys.exit(out) # generates errorlevel of 1 (check with 'echo $?' after running); no tracebacks # was 'raise Exception(out)' def warning(message): # Name of calling method: http://bytes.com/topic/python/answers/665113-how-can-i-know-name-caller out = 'Warning [%s]: %s ' % (sys._getframe(1).f_code.co_name, message) if interactive: print (out) else: sys.stderr.write(out) # --------------- def parseList(tempcc, aa=False, mappingPos=1): # default mapping is 1:1 '''Returns a start and end value for each distinct entity''' # For example: 1800-1810 returns 1800 and 1810 # 1820 returns 1820 and 1820 ll = tempcc.split(',') tempNucList = [] for i in ll: rr = i.find('-') if rr != -1: tt = i.split('-') start = tt[0] end = tt[1] else: start = end = i try: startPos = int(start) endPos = int(end) if aa: startPos = startPos * 3 - 2 # start position endPos = endPos * 3 # do not subtract 2 -- triplets tempNucList.append([startPos - mappingPos + 1, endPos - mappingPos + 1]) # a list of the positions requested except: error('%s: Bad nucleotide positions' % tempcc) return False return tempNucList # --------------- def randomStamp(): import datetime, random return "%s%02i" % (datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d%H%M%S'), random.random()*999) # ---------------- def contig(F, R): '''Generate a contig from two input sequences''' # Method requires two sequences objects which may optionally have been trimmed; objects required because quality scores are required # Processes the first sequence in each Sequence object # Ancestry: stand-alone qualTrim.py modified into stand-alone Contig.py # Tested with SHH061A BCP forward and reverse sequences; after _5_10 trimming and needle alignment, base T at 220 with QS of 54 was aligned with gap # This needs a forward and reverse file, called F and R -- must parameterize this # Pass in the entire object; only the first sequence of the object used from Bio.Emboss.Applications import NeedleCommandline from Bio import AlignIO import subprocess, sys R.seqRevComp() randomStampToken = randomStamp() # same token for forward and reverse files tempOutF = TEMPFOLDER + 'tempOutF-' + randomStampToken tempOutR = TEMPFOLDER + 'tempOutR-' + randomStampToken F.writeFASTA(tempOutF) R.writeFASTA(tempOutR) # http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc74 # Using BioPython tools to call needle with prepared files # Uses subprocess to pipe stdout, which avoids making a temporary output file cline = NeedleCommandline(asequence=tempOutF, bsequence=tempOutR, gapopen=10, gapextend=0.5, stdout=True, auto=True) child = subprocess.Popen(str(cline), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=(sys.platform!="win32")) align = AlignIO.read(child.stdout, "emboss") # Quality scores always preceed bases pos1 = -1 # track the actual base position regardless of gaps pos2 = -1 gap = '-' cons = '' # use a moving window around the current pair of bases # the quality of the bases in this window will be conisidered # SHH009A reverse sequence contains an an unpaired Y base with quality of 5, but this base is valid and should not be deleted # arbitrarily deleting unpaired bases is not advisable; possibly lower thresholds on non-ACGT bases CW = BASESTHRESHOLD # CW ~ ContigWindow QT = QUALITYTHRESHOLD # shorter to type and only one change here if module name is changed pairBaseGood = 1.0 pairBaseBase = 0.75 pairBaseNon = 0.67 pairGapBase = 0.50 pairBaseBasePoor = 0.33 PairNon = 0.25 CQ = 0.0 # Contig Quality for i in range(len(align[0].seq)): base1 = align[0].seq[i] base2 = align[1].seq[i] if base1 != gap: pos1 += 1 if base2 != gap: pos2 += 1 qual1 = F.QS[pos1 + F.trimLeft] qual2 = R.QS[pos2 + R.trimLeft] window1 = [pos1 + F.trimLeft - CW, pos1 + F.trimLeft + CW] window2 = [pos2 + R.trimLeft - CW, pos2 + R.trimLeft + CW] if window1[0] < 0: window1[0] = 0 if window1[1] > len(F.seq[0]['seq']): window1[1] = len(F.seq[0]['seq']) if window2[0] < 0: window2[0] = 0 if window2[1] > len(R.seq[0]['seq']): window2[1] = len(R.seq[0]['seq']) baseWin1 = F.seq[0]['seq'][window1[0]:window1[1]+1] baseWin2 = R.seq[0]['seq'][window2[0]:window2[1]+1] qualWin1 = sum(F.QS[window1[0]:window1[1]+1]) // (CW * 2 + 1) # integer division qualWin2 = sum(R.QS[window1[0]:window1[1]+1]) // (CW * 2 + 1) # print "pos1:%03i qual1:%i base1:%s window1:%03i-%03i basewin1:%s qualwin1:%i | pos2:%03i qual2:%i base2:%s window2:%03i-%03i basewin2:%s qualwin2:%i" % (pos1, qual1, base1, window1[0], window1[1], baseWin1, qualWin1, pos2, qual2, base2, window2[0], window2[1], baseWin2, qualWin2) # using (quality score of base (qual) OR quality score of window (window) means that # an indiviual good quality base is never lost, but also that one poor quality base # surrounded by good quality bases is not removed # base1 is a gap and base2 to is not a gap and (base2 quality score OR quality score of window2 >= quality threshold) if base1 == gap and base2 != gap and (qual2 >= QT or qualWin2 >= QT): # print i, base1, qual2, base2 cons += base2 CQ += pairGapBase # base2 is a gap and base1 to is not a gap and (base1 quality score OR quality score of window1 >= quality threshold) elif base1 != gap and base2 == gap and (qual1 >= QT or qualWin1 >= QT): # print i, qual1, base1, base2 cons += base1 CQ += pairGapBase # if one of the bases is a gap and the one which is not a gap has BOTH a quality score and a quality score of window below threshold, then nothing is added to the consensus # Bases do not match: elif base1 != base2 and base1 != gap and base2 != gap: # extra clauses just to ensure that neither are gaps # If both are ACGT then use the one with the highest quality score as long as it is above qualityThreshold # If only one is ACGT, then use that one (currently regardless of quality) # If neither are ACGT, then use the one with the best quality (above quality threshold) if base1 in BASES and base2 in BASES: if qual1 >= qual2 and qual1 >= QT: cons += base1 CQ += pairBaseBase elif qual2 >= QT: cons += base2 CQ += pairBaseBase # both are ACGT but neither are above qualityThreshold elif qual1 > qual2: # base1 quality is better cons += base1 CQ += pairBaseBasePoor elif qual2 < qual1: # base2 quality is better cons += base2 CQ += pairBaseBasePoor elif qualWin1 > qualWin2: # base1 window quality is better; will only execute if bases are = quality cons += base1 CQ += pairBaseBasePoor else: cons += base2 CQ += pairBaseBasePoor elif base1 in BASES and qual1 >= QT: # base1 is ACGT so base2 is not cons += base1 # use base1, regardless of quality CQ += pairBaseNon elif base2 in BASES and qual2 >= QT: # base2 is ACGT so base1 is not cons += base2 # use base2, regardless of quality CQ += pairBaseNon else: if qual1 >= QT: # it's not ACGT, but if quality score is above threshold, add it cons += base1 CQ += pairNon elif qual2 >= QT: # ditto; if this is not met, then nothing is added cons += base2 CQ += pairNon else: cons += base1 # bases are the same so use either -- erroneously takes (took?) "-" from "-|Y" CQ += pairBaseGood # print cons # print "Consensus Length %i" % (len(cons)) # c = 0 # for i in cons: # if i not in BASES: # c += 1 # print "%i of %i (%3.2f%%) bases are ambiguous" % (c, len(cons), float(c)/len(cons) * 100) # return contig, CW, aligned forward and reverse sequences, original forward and reverse sequences # the original, untrimmed sequence is not available, as this was trimmed when the chromatogram was loaded return [[">Contig_%s_%s" % (F.seq[0]['id'][1:], R.seq[0]['id'][1:]), cons], CQ/len(cons), [">Aligned_Forward_%s" % (F.seq[0]['id'][1:]), str(align[0].seq)], [">Aligned_Reverse_%s]" % (F.seq[0]['id'][1:]), str(align[1].seq)], [F.seq[0]['id'], F.seq[0]['seq']], [R.seq[0]['id'], R.seq[0]['seq']]] # Also highlight bases with low quality scores for reference # Cannot simply remove base:- pairing arbitrarily if it is found in a long sequence of gaps (as at the start and end of the sequence) # Can do it if there position is surrounded by a certain number of base:base pairings -- a threshold # Will work well then in the cases examined where base:- should be the base (base with high quality score) or should be removed (base with low quality score) # MUST ALSO ADD QUALTRIM PRETTY OUTPUT # Output stats: F, R, Contig: As, Gs, Ys, Gaps, Length, etc. # Final output must (be/include) a Sequence object? # --------------- def robustTranslate(ss): '''Use BioPython functionality to translate codons into amino acids''' # This method returns a tuple containing the one- and three-letter amino acid codes for the input codon # However, this method does not break if the codon cannot be translated # as is the case when gaps are present, for example # The function will return None if the input parameter is not exactly three characters in length if len (ss) != 3: return None import Bio.SeqUtils if ss.find('-') >= 0: return ('-', '---') # means that at least one position is a gap ss = ss.upper() ss = ss.replace('U', 'T') # so that translation to three-letter code works for i in range(3): if ss[i] not in BASES + NONBASES: return ('#', '###') # means that at least one position is not a base or an ambiguous base single = Bio.Seq.translate(ss) return (single, Bio.SeqUtils.seq3(single)) # --------------- class Sequence: def __init__(self): self.fileLoaded = False self.fileName = '' self.changed = False; self.seq = [] # dictonary to store description and sequence self.fileType = '' self.QS = [] self.originalCalls = '' self.trimThreshold = None self.trimLeft = None self.originalLength = None self.trimRight = None self.trimGoodBases = None self.trimGoodQuality = None self.linenumbers = 0 self.truncate = 20 # always applied; set to large value to 'disable' self.totalCount = 0 self.mergeSlide = False # --------------- # def __str__(self): # return "OK" # --------------- def seqLength(self, cc=''): '''Return sequence ID and length''' cc = cc.split() out = [] # no marker for data output -- easy copy and paste elsewhere if not self.fileLoaded: error('No file loaded') else: for i in range(len(self.seq)): out.append((self.seq[i]['id'][:self.truncate], len(self.seq[i]['seq']))) # ACTIVE command; SORT return out # --------------- def status(self): '''Return status''' if not self.fileLoaded: error('No file loaded') else: return (self.fileName, len(self.seq), self.fileType, self.trimThreshold, self.trimLeft, self.trimRight, self.changed) # --------------- def load(self, cc, ABIF=False, autoTrimThreshold=0, minGoodBases=BASESTHRESHOLD, minGoodQuality=QUALITYTHRESHOLD, filterPattern='.+', filterInclude=True): '''Load sequence data from a file''' # minGoodBases and minGoodQuality are ignored when autoTrimThreshold is specified # filterPattern to filter sequence IDs according to regular expression # filterInclude = True includes only sequences matching the filter pattern # filters are only applicable to FASTA files, as these can contain multiple sequences # filters will be ignored when an ABIF file is specified (this may change in future, but the benefit # to filting out an ABIF file is obscure -- the file would not be loaded if the filter did not match, # which may be the point in that case) ### cc = cc.split() if len(cc) < 1: error('Load what?') cc = [cc] ### if len(cc) > 1: ### error('Specify one file to load') # Check reporting of following ... if self.fileLoaded: error('Cannot load file %s: File %s already loaded' % (cc[0], self.fileName)) try: if cc[0][0] in ["'", '"'] and cc[0][len(cc[0])-1] in ["'", '"']: cc[0] = cc[0][1:len(cc[0])-1] if ABIF: import ABIFReader try: f = ABIFReader.ABIFReader(cc[0]) except: print "Bad chromatogram file: %s" % os.path.split(cc[0])[1] # clumsy but effective sys.exit(1) else: f = open(cc[0], 'r') except IOError: error('Error opening file %s' % cc[0]) else: self.fileLoaded = True self.fileName = cc[0] if not ABIF: for record in SeqIO.parse(f, "fasta"): # id repeated as first part of description, so storing description only # length no longer stored here; can be determined on the fly # filter each input sequence ID self.totalCount += 1 # total all sequences in the file to output include/exclude if relevant filterFound = (re.search(filterPattern, record.description) != None) # return True of found if filterFound == filterInclude: self.seq.append({'id': record.description, 'seq': str(record.seq)}) self.originalLength = len(str(record.seq)) self.trimLeft = 0 self.trimRight = 0 # (filterfound == True and filterInclude == True) or (filterFound == False and filterInclude == False) # are the two conditions under which the sequence should be included # condition above implements this in one condition if len(self.seq) < 1: if self.totalCount > 1: print "All sequences excluded by filter pattern: %s" % filterPattern else: print "Bad FASTA file: %s" % os.path.split(cc[0])[1] # clumsy but effective sys.exit(1) self.fileType = 'FASTA' else: tempID = f.getData('SMPL') # Sample ID used as FASTA identifier if len(tempID) == 0 or tempID == None: tempID = cc[0] # Filename instead base = f.getData('PBAS') # Base Calls qual = f.getData('PCON') # Quality Scores self.date = f.getData('RUND') # Start run date self.QS = [] for i in qual: self.QS.append(ord(i)) self.originalCalls = base # preserve the original base calls (as required by fragmentmerger) if autoTrimThreshold > 0: # This should really be an average of the first X bases? # For example: first base QS = 21, then next 10 bases are below 10 ... # Or ignore first base? # This will break if autoTrimThreshold is very high -- no bases will be good enough Qleft = 0 while self.QS[Qleft] < autoTrimThreshold: Qleft += 1 Qright = len(base) - 1 # indexed from 0 while self.QS[Qright] < autoTrimThreshold: Qright -= 1 if Qleft <= 0: # first base is above threshold Qleft = 1 if Qright >= len(base): Qright = len(base) - 2 # ? base = base[Qleft-1:Qright+1] self.trimThreshold = autoTrimThreshold self.trimLeft = Qleft self.trimRight = Qright # print self.QS[0:20] # print Qleft, Qright # print base else: # No autotrim -- using minGoodBases and minGoodQuality c = 0 # counter i = 0 # position in sequence while i < len(self.QS) and c < minGoodBases: # still in the sequence and counter < minimum consecutive bases if self.QS[i] >= minGoodQuality: c += 1 else: c = 0 i += 1 if i >= len(self.QS): # reached the right of the string f.close() return None # error('No good window found searching from the left') # this could happen if minGoodQuality is too high else: self.trimLeft = i - minGoodBases # start of 'good' sequence is X bases 'back' from i c = 0 # counter i = len(self.QS)-1 # position in sequence, indexed from 0, starting from the right while i > 0 and c < minGoodBases: # still in the sequence and counter < minimum consecutive bases if self.QS[i] >= minGoodQuality: c += 1 else: c = 0 i -= 1 if i == 0: # reached the left of the string f.close() return None # error('No good window found searching from the right') # this could happen if minGoodQuality is too high else: self.trimRight = len(self.QS) - i - minGoodBases - 1 self.originalLength = len(base) base = base[self.trimLeft:len(self.QS)-self.trimRight] self.trimGoodBases = minGoodBases self.trimGoodQuality = minGoodQuality tempID += '_(Trimmed_%i_%i)' % (minGoodBases,minGoodQuality) # no space so trimmed annotation part of ID self.seq.append( {'id': tempID, 'seq': base}) ## MARK A ## self.fileType = 'ABIF' f.close() return self.status() # --------------- def save(self, cc, overWrite=False): '''Save sequence data to a file''' # Saves as FASTA # Saving with a new name makes that name the 'active' name cc = cc.split() if len(cc) < 1: error('Save what?') if len(cc) > 1: error('Specify filename to save') if not self.fileLoaded: error ('Cannot save file %s: No file loaded' % (cc[0])) if cc[0][0] in ["'", '"'] and cc[0][len(cc[0])-1] in ["'", '"']: cc[0] = cc[0][1:len(cc[0])-1] if os.path.exists(cc[0]) and not overWrite: error('File exists; specify overWrite=True to overwrite') try: f = open(cc[0], 'w') except IOError: error('Error creating file %s' % cc[0]) else: self.changed = False self.fileName = cc[0] for i in self.seq: if i['id'] is not None: # do not write out empty entries f.write('>' + i['id'] + '\n') # id and description f.write(i['seq'] + '\n') # sequence data f.close() return self.status() # --------------- def unload(self, override=False): '''Unload file''' if self.fileLoaded: if self.changed and not override: warning('Data changed; specify override=True to unload') return None t = self.fileName self.__init__() return None else: error('Cannot unload: No file loaded') # --------------- def extract(self, cc, aain=False, aaout=False, mapping=1, inData=''): '''Return proteins from a nucleotide sequence''' # Base distributions are not returned by this method, as it would be difficult # to encapsulate totals for each base for each position requested, # and difficult to disentangle these (map them back to positions); # the same may be true of the bases themselves, but these are only single characters # and produce a 'pattern' or 'motif' which can be processed # # 04 March 2011: added inData parameter # this must be a list (to be interrated over), # so to process only one item, pass in inData=[S.seq[0]] # several items can be processed with inData=[S.seq[0], S.seq[1]] # always returns a list # cc = cc.split() out = [] if len(cc) < 1: error('Specify nucloetide position/s') if len(cc) > 1: error('Bad position syntax') if cc[0].find(' ') != -1: error('Spaces not permitted in positions') if aain: nucList = parseList(cc[0], mappingPos=mapping, aa=True) else: nucList = parseList(cc[0], mappingPos=mapping) if inData == '': inData = self.seq for i in inData: t = i['id'][:self.truncate] tempout = '' for j in nucList: tempout += i['seq'][j[0]-1:j[1]] if aaout: out.append((t, Bio.Seq.Seq(tempout).translate().data)) else: out.append((t, tempout)) return out # --------------- def nucCopy(self, cc): '''Crop sequences''' self.changed = True c = 0 for i in self.extract(cc): self.seq[c]['seq'] = i[1] # update sequence data only c += 1 # --------------- def find(self, cc, aain=False, aaout=False, readingframe=0): '''Return all occurrences of a regular expression in a nucleotide sequence''' # Returns nucleotide position and, if relevant, amino acid position # find over the gap # does not return anything if search string not found in sequence (report) # returns multiple hits -- some way to limit? # output in format which can be added as a new object? # removed "context" in output as this did not work well with aain and aaout... # supplying aain=False aaout=True with context makes no sense if not self.fileLoaded: error('No file loaded') if len(cc) < 1: error('Specify regular expression to find') out = [] outLength = len(cc) if aain != aaout: if aain and not aaout: outLength = outLength * 3 else: outLength = outLength / 3 # not aain and aaout for i in self.seq: iiid = i['id'] if aain: # Cannot translate gapped sequences; replace - with N for translation to "X" ii = i['seq'][readingframe:].replace('-', 'N') ii = Bio.Seq.Seq(ii).translate().data else: ii = i['seq'] findTemp = re.finditer(cc, ii) for foundItem in findTemp: startPos = foundItem.start() endPos = foundItem.end() if startPos < 0: startPos = 0 if endPos > len(ii): endPos = len(ii) pos = foundItem.start()+1 if aain: nucpos = pos * 3 - 2 + readingframe aapos = pos else: nucpos = pos aapos = pos / 3 if aain != aaout: if aain: startPos = pos * 3 - 3 + readingframe # -3 not -2 ... ? endPos = startPos + outLength lettersOut = i['seq'][startPos:endPos] else: lettersOut = Bio.Seq.Seq(ii[startPos:endPos]).translate().data else: lettersOut = ii[startPos:endPos] out.append((iiid[:self.truncate], lettersOut, nucpos, aapos)) return out # --------------- def seqSlide(self, SStr, SPos): '''Place SStr starting at position SPos''' self.changed = True c = 0 for i in self.seq: if (SPos < 1) or (SPos > len(i['seq'])): error('Invalid position') start = i['seq'].find(SStr) newStart = SPos - 1 - start # Python indexes strings from zero if start < 0: warning('%s not found in Sequence %03i (%s)' % (SStr, c, i['id'])) # return None # Continue processing rather ... else: i['seq'] = i['seq'][-newStart:] + i['seq'][:-newStart] c += 1 # --------------- def basePercentage(self, cc, byChar=False, percentage=True, ignoreCase=True): '''Return count or percentage of base(s) or fragment (no regular expressions)''' # cc = str(cc.split()[0]) out = [] for i in self.seq: if percentage: denom = float(len(i['seq'])) # for division later else: denom = 1 if ignoreCase: cc = cc.upper() if not byChar: if ignoreCase: ccCount = cc.upper() count = i['seq'].upper().count(ccCount) else: ccCount = cc count = i['seq'].count(ccCount) out.append((i['id'][:self.truncate], ccCount, count / denom)) else: for j in cc: if ignoreCase: count = i['seq'].upper().count(j) else: count = i['seq'].count(j) out.append((i['id'][:self.truncate], j, count / denom)) return out # --------------- def seqRemoveByIndex(self, cc): '''Remove sequence (indexed from zero)''' # Remove a range or from a list? Numbering? self.changed = True if cc < 0 or cc > len(self.seq) - 1: error('Out of range') self.seq.remove(self.seq[cc]) # --------------- # remove sequences by length, by first/last N, odds, evens ... def seqRemoveByID(self, cc, retain=False, verbose=False, escape=False): '''Remove sequence with regex match against sequence ID''' # cc is a list of the regular expressions to be included or excluded # verbose for debugging only # escape will escape the search pattern; useful for GenBank ID strings which contain | if not isinstance(cc, list): return None self.changed = True count = 0 i = 0 found = False # if item is empty, found needs a value later while i < len(self.seq): if not retain: for item in cc: if escape: tempItem = re.escape(item) else: tempItem = item found = re.search(tempItem, self.seq[i]['id']) if found == None: found = False else: found = True if found: if verbose: print item self.seqRemoveByIndex(i) count += 1 i -= 1 # one item removed; incremented outside loop break # no need to check the rest of the list else: for item in cc: if escape: tempItem = re.escape(item) else: tempItem = item found = re.search(tempItem, self.seq[i]['id']) if found == None: found = False else: found = True if found: break if not found: if verbose: print item self.seqRemoveByIndex(i) count += 1 i -= 1 # one item removed; incremented outside loop i += 1 return count # return number of entries delete (regardless of value of retain) # --------------- def seqAdd(self, cc): '''Add sequences from another object (.seq)''' # Must be added from other objects as lists if NewS is empty: NewS.seqAdd([OldS.seq[0]]) # Or just NewS.seqAdd(OldS.seq) ... ? # Can add results of a search: New.seqAdd (OldSeq.seqFind('GAGGAC', 0)) # This only adds the found sequence not the entire sequence # self.fileloaded is not true -- must run seqLength ... self.changed = True self.seq.extend(cc) # --------------- def seqCount(self): '''Return the number of sequences''' if self.fileLoaded: return len(self.seq) else: error('No file loaded') # --------------- def seqCase(self, lower=False): '''Change case of sequence data''' self.changed = True for i in self.seq: if lower: i['seq'] = i['seq'].lower() else: i['seq'] = i['seq'].upper() # --------------- def seqSR(self, search, replace): '''Replace "search" with "replace" in sequence''' self.changed = True for i in self.seq: i['seq'] = re.sub(search, replace, i['seq']) # --------------- def seqDegap(self): '''Remove gaps by calling seqSR''' self.seqSR('-', '') # --------------- def seqRevComp(self, rev=True, comp=True): '''Reverse and/or complement sequences''' # Might be useful to be able to do one or the other of these on only SOME sequences? # Might be useful to simply RETURN the reversed and/or complemented sequence? for i in self.seq: if rev: i['seq'] = i['seq'][::-1] self.trimLeft, self.trimRight = self.trimRight, self.trimLeft # swap self.QS = self.QS[::-1] # Reverse quality scores if comp: tt = '' # strings are immutable for j in i['seq']: tt += BASECOMPLEMENT[j] i['seq'] = tt # --------------- def outFASTA(self): out = '' for i in self.seq: out += '>' + i['id'] + '\n' + i['seq'] + '\n' return out # --------------- def writeFASTA(self, filename): try: outFile = open(filename, 'w') except IOError: error('Cannot create file %s' % filename) outFile.write(self.outFASTA()) outFile.close() # --------------- def countMotif(self, motifPos, motifSeq, match, motifMapping = 1): '''Count mutations -- that is, where mutSeq == sequence data''' count = 0 out = [] pp = self.extract(motifPos, mapping=motifMapping) for i in pp: if match: if i[1] == motifSeq: count += 1 out.append(i) else: if i[1] != motifSeq: count += 1 out.append(i) return (count, out) # ---------------- def baseDistribution(self, positions, set1=BASES, set2=NONBASES, distributionMapping = 1): '''Return base distribution values (not percentages) at a given position''' # Accepts a parseList-able list of positions and returns a list of dictionaries # Processes vertically over all sequences out = [] for i in parseList(positions): for j in range(i[0], i[1]+1): c = {} for k in set1: c[k] = 0 for k in set2: c[k] = 0 for k in self.seq: cc = k['seq'][j - distributionMapping] if cc in set1 + set2: c[cc] += 1 out.append(c) return out # returned as a list of dictionary; each position is one dictionary # --------------- def translateLoci(self, positions, translateMapping = 1): '''Returns amino acids from all three reading frames for each position''' # (Bio.SeqUtils.seq3 converts a Bio.Seq.translate single-letter amino acid to a three-letter amino acid) # (Was unable to find a method to to return the full-name of the amino acid) # Loop over all positions and extract first reading frame # Repeat for other reading frames; therefore three reading frames output per position # List of dictionaries is read for output with requiring transposition (as is required for baseDistribtuon) # Translation in all three reading frames for all positions is done for completeness and reference # This is strictly not necessary for positions which vary by less than three out = [] # Looping over reading frames, then sequences, then positions for i in range(3): # three reading frames per codon for j in self.seq: c = {} # prepare the dictionary for this 'row' for k in parseList(positions): # loop over all positions requested for the ith reading frame for l in range(k[0], k[1]+1): # Returned as a list of dictionaries (as baseDistribution) to allow for easier (modular) output of the table # The above turned out not to be possible because of the increased complexity required to store # the output from this method; a reading frame, the sequence ID and codons for each position are required # The method mentioned above is returing totals for each base, so the data are summarized # This method returns output for each reading frame for each sequence for all positions # Therefore, a list of list is returned: the inner listcontains the reading frame (0, 1 or 2), the sequence ID # and the dictionary of position:codon pairs # The key of the dictionary is the actual position number # All three reading frames are reaturned, even though some may be empty # Returns three reading frames, where position is the first, second and third base:: X--. -X-, --X # Reading frames moves 'backwards', but the actual base at the position in question # moves from position 1 to 2 to 3, which is more intuitive actualPos = l - translateMapping start = actualPos - i # get start position from i end = start + 2 # end position is always 2 positions downstream if start >= 0: # upper bound check not required; lower bound check against 0 # put the codon into dictionary where key is position # The translation into an amino acid can be done by the routine # which outputs the data, which must consider that not all codons can be translated # Codons containing gaps, for exampel, cannot be translated # The actual translation into a three-letter amino acid code is done with: # import Bio.SeqUtils; Bio.SeqUtils.seq3(Bio.Seq.translate('AUG')) # The outer 'seq3' method can be omitted if one-letter amino acid codes are required # Translating functionality is provided by the class method robustTranslate here c[l] = j['seq'][start:end+1] out.append([i, j['id'][:self.truncate], c]) return out # --------------- def eliminateGapColumns(self, gapThreshold=GAPCOLUMNTHRESHOLD, verbose=False): '''Eliminate columns containing >= threshold proportion of GAPs''' gapList = [] thresholdList = [] startingLength = self.seqLength()[0][1] for i in range(self.seqLength()[0][1]): # aligned sequences; all have the same length column = '' for j in self.seq: column += j['seq'][i] gapRatio = column.count(GAP) / float(len(self.seq)) if gapRatio >= gapThreshold: gapList.append(i) thresholdList.append(gapRatio) eliminatedCount = 0 for i in gapList: for j in self.seq: j['seq'] = j['seq'][:i - eliminatedCount] + j['seq'][i + 1 - eliminatedCount:] eliminatedCount += 1 if verbose: return ['Gap-columns eliminated: %i (%3.2f%%)' % (len(gapList), (len(gapList)/float(startingLength)*100)), 'Gap threshold: %3.2f' % (gapThreshold), 'Start length: %i' % (startingLength), 'End length: %i' % (self.seqLength()[0][1])] # --------------- def disambiguateColumns(self, verbose=False): '''Replace/correct/disambiguate ambiguous bases in mono-base gap-free columns''' monobaseCount = 0 monobaseColumns = 0 self.seqCase() # convert to uppercase for i in range(self.seqLength()[0][1]): bb = [] column = '' for j in self.seq: column += j['seq'][i] for j in BASES: bb.append(column.count(j) / float(len(self.seq))) # percentage of column which is each basea if column.count(GAP) != 0: # if a gap is present, exclude this column continue if (bb[1] + bb[2] + bb[3] == 0) and (bb[0] != 1): # only A present, but not at 100% BB = 'A' elif (bb[0] + bb[2] + bb[3] == 0) and (bb[1] != 1): # only C present, but not at 100% BB = 'C' elif (bb[0] + bb[1] + bb[3] == 0) and (bb[2] != 1): # only G present, but not at 100% BB = 'G' elif (bb[0] + bb[1] + bb[2] == 0) and (bb[3] != 1): # only T present. but not at 100% BB = 'T' else: BB = None # column contains more than one base-type if BB != None: monobaseColumns += 1 for j in column: if j != BB: # if j is the ambiguous base (j is not equal to the base) if BB in DISAMBIGUATE[j]: # the base at this position is one of the disambiguous ones monobaseCount += 1 # print i, column, '<br>' # print column[:column.index(j)] + BB + column[column.index(j) + 1:], '<br>' # print j, ' becomes ', BB, '<br>' self.seq[column.index(j)]['seq'] = self.seq[column.index(j)]['seq'][:i] + BB + self.seq[column.index(j)]['seq'][i + 1:] # also update the column so that subsequent ambiguous bases can be found # as these are indexed by column.index(j) so the same entry is updated # repeatedly instead of the next one being updated column = column[:column.index(j)] + BB + column[column.index(j) + 1:] if verbose: if monobaseColumns == 0: out = 0 else: out = monobaseCount / float(monobaseColumns) return ['Ambiguous bases corrected: %i' % (monobaseCount), 'Columns containing ambiguous bases: %i (%3.2f%%)' % (monobaseColumns, monobaseColumns/float(self.seqLength()[0][1])*100), 'Ambiguous bases per corrected column: %3.2f' % (out)] # ---------------- def blunt(self, left=True, right=True): '''Remove columns from multiple sequence alignment such that no sequence starts or ends with a gap''' # method to trim off tatty ends (make blunt ends) # required for phylogenetic analysis # but not required when joining fragments together, as more bases should be included in this case ## import operator ## X = sorted(self.seq, key=operator.itemgetter('seq')) # sort according to actual sequence data; slow for large sequences? memory requirements? if left: longest = 0 for i in range(len(self.seq)): # process all sequences for j in range(longest, self.seqLength()[0][1]): if self.seq[i]['seq'][j] != GAP: longest = j break leftCount = longest for i in range(len(self.seq)): self.seq[i]['seq'] = self.seq[i]['seq'][longest:] else: leftCount = None if right: longest = 0 for i in range(len(self.seq)): # process all sequences for j in range(self.seqLength()[0][1] - longest - 1, 0, -1): if self.seq[i]['seq'][j] != GAP: longest = self.seqLength()[0][1] - j - 1 break rightCount = longest longest = self.seqLength()[0][1] - longest for i in range(len(self.seq)): self.seq[i]['seq'] = self.seq[i]['seq'][:longest] else: rightCount = None return [leftCount, rightCount] # --------------- def seqSerotype(self, startMotif='ATGGAGAACAT'): '''Return serotype according to Purdy 2007''' # Requires aligned sequences # Using list.index() to extract each 'find' result can be used to get around this later if necessary import Bio.SeqUtils StartS = self.find(startMotif)[0][2] seroMotifs = self.extract('122,160,127,159,140', aain=True, aaout=True, mapping = -StartS + 2) seroNucs = self.extract('122,160,127,159,140', aain=True, aaout=False, mapping = -StartS + 2) out = [] for i in seroMotifs: serotyped = False # print i[0][:20], i[1], for j in SEROPATTERNS: found = re.search(j, i[1]) if found: # print j, SEROPATTERNS[j] serotype = SEROPATTERNS[j] serotyped = True if not serotyped: if i[1][0] in SEROGROUP: # print j[0], SEROGROUP[j[0]] # at least "ad" or "ay" -- i[1][0] is the first amino acid in the pattern serotype = SEROGROUP[i[1][0]] else: # print "Unknown" serotype = "Unknown" three = '' for j in i[1]: # each letter in the motif three += Bio.SeqUtils.seq3(j) out.append([i[0], serotype, i[1], three, seroNucs[seroMotifs.index(i)][1]]) return out # --------------- def mutationFinder(self, reference, startMotif, stopMotif, gene, aa=True, nucleotideMapping=0): '''Return mutations found in self using given object reference as reference sequence''' # patterns are regular expressions # aa=True means return amino acid positions # currently only the first sequence in the reference object is processed self.seqCase() reference.seqCase() prefixList = {'P' : 'rt', 'S': 's', 'BCP' : '', 'X': 'x', 'C' : 'c'} if gene not in prefixList: prefixList[gene] = '' # ensure lookup later works startReference = re.search(startMotif, reference.seq[0]['seq']) stopReference = re.search(stopMotif, reference.seq[0]['seq']) if startReference == None or stopReference == None: return None # if either motif is not found in the reference sequence, abort startReference = startReference.start() stopReference = stopReference.start() out = [] # will store the list out found mutations: ['ID1', ['A123C', 'C456G']] for theSeq in self.seq: startQuery = re.search(startMotif, theSeq['seq']) stopQuery = re.search(stopMotif, theSeq['seq']) if startQuery == None or stopQuery == None: out.append([theSeq['id'], []]) # return (iterable) empty list rather than (non-iterable) "None" continue # start or stop motifs are not found; abort this sequence startQuery = startQuery.start() stopQuery = stopQuery.start() mapping = startReference - startQuery outQuery = '' outReference = '' mutationList = [] # temporarily store the list of mutations for i in range(startQuery, stopQuery): outQuery += theSeq['seq'][i] outReference += reference.seq[0]['seq'][i + mapping] # should avoid building and translating the reference sequence each time ... if aa: #import Bio.Seq #transReference = Bio.Seq.translate(outReference) #transQuery = Bio.Seq.translate(outQuery) #for i in range(len(transQuery)): # if transQuery[i] != transReference[i]: # mutationList.append( '%s%s%i%s' % (prefixList[gene], transReference[i], i+1, transQuery[i]) ) # startReference + (i * 3) = nucleotide position import Bio.Seq for i in range(0, len(outQuery), 3): rr = outReference[i:i+3] qq = outQuery[i:i+3] if rr != qq: mutationList.append((i+startQuery, rr, qq, Bio.Seq.translate(rr), Bio.Seq.translate(qq), i/3+1)) # position output is the actual position in the sequence, not the amino acid position else: for i in range(len(outReference)): if outQuery[i] != outReference[i]: mutationList.append('%s%s%i%s' % (prefixList[gene], outReference[i], i+nucleotideMapping, outQuery[i]) ) # 1741 out.append([theSeq['id'], mutationList]) return out # --------------- def seqNames(self): out = [] for i in self.seq: out.append(i['id']) return out # --------------- def seqGenotype(self, s_start=S_START, b_start=B_START): '''Return serotype according to Kramvis 2008''' # adapted from stand-alone 'genotyper.py' import Bio.SeqUtils out = [] for i in self.seq: # iterate over each sequence searching each one; not using S.find which searches all ss = re.search(S_START, i['seq']) bb = re.search(B_START, i['seq']) if ss != None: ss = ss.start()+1 if bb != None: bb = bb.start()+1 if ss != None: seroMotif = self.extract('122,160,127,159,140', aain=True, aaout=True, mapping = -ss + 2, inData=[i])[0] seroNucs = self.extract('122,160,127,159,140', aain=True, aaout=False, mapping = -ss + 2, inData=[i])[0] serotyped = False for k in SEROPATTERNS: found = re.search(k, seroMotif[1]) if found: serotype = SEROPATTERNS[k] serotyped = True if not serotyped: if seroMotif[1][0] in SEROGROUP: serotype = SEROGROUP[seroMotif[1][0]] else: serotype = '??' three = '' for k in seroMotif[1]: # each letter in the motif three += Bio.SeqUtils.seq3(k) serotype = ([seroMotif[0], serotype, seroMotif[1], three, seroNucs[1]]) else: serotype = '??' if bb != None: bcpMotif = self.extract('1802,1803,1809-1812,1817-1819,1858,1888', aain=False, aaout=False, mapping = 1814-bb+1, inData=[i])[0] else: bcpMotif = '??' if bb != None and ss != None: final = serotype[1] + bcpMotif[1] found = False for j in GENOTYPES: found = re.search(j, final) if found: genotype = (i['id'][:self.truncate], GENOTYPES[j], final, serotype[1], serotype[2], serotype[3], serotype[4], len(i['seq'])) break if not found: genotype = (i['id'][:self.truncate], '??', final, serotype[1], serotype[2], serotype[3], serotype[4], len(i['seq'])) else: genotype = (i['id'][:self.truncate], '??', '??', '??' ,'??', '??', '??', len(i['seq'])) out.append(genotype) return (out) # --------------- def DEPRECATED_groupDistribution_DEPRECATED(self, grouping, threshold=0.05, aa=False): '''Return chi-squared ViPR/BRC p-value for all columns using provided grouping''' # Passing parameter for all columns is better, as then the splitting into groups is done only once, # rather than repeating this for each column. Typical usage would be to process all columns in a sequence. # Differences from the ViPR tool: this one allows for more groups and *requires* aligned sequences # how to identify a sequence is protein not nucleotide; conceivable that a *protein* column # contain only A, C, G and T amino acids...? # Web interface: file to upload -- threshold -- amino acid -- grouping list for 12 groups # Sequences *must* be aligned -- this is better, because the sequence data can be checked/curated before # Otherwise, if an alignment is done and then the data is scanned for significant columns, these results # would depend on the (unchecked) alignment # MRT is used to examine distribution at loci of interest which are known before # This tool can focus on *which* positions are of interest and then these can be given to the MRT to report on. # The two tools are used together -- this one then the MRT # Must abort if groups < 2 # Stop checking if no variation in a column (rather than ending up with degrees of freedom = 0) # Algorithm for dynamic totals for amino acids: # - Start as for nucleotides, totalling each into it's own column # - Afterwards, total the number of non-zero columns import scipy, scipy.stats, numpy emptyColumn = 0.01 # used instead of zero in empty columns groups = len(grouping) gg = [] for i in grouping: # each group is expanded into list gg gg.append(parseList(i)) # ['1-10', '11,13'] becomes [[[1,10]], [[11,11],[13,13]]] g = [] # which then becomes [(1,2,3,4,5,6,7,8,9,10), (11,13)] (1-indexed here) for i in gg: # stores the grouping as a list of tuples (0-indexed) tt = () for j in i: for k in range(j[0], j[1]+1): tt += (k-1,) # k-1: convert from 1-indexed (provided grouping) to 0-indexed (required) g.append(tt) residueCols = {} # stores the position (column number) for each residue; A in column 0, B in column 1, etc. cc = 0 if not aa: residueList = BASES residueCols[GAP] = len(BASES) # gaps are stored in the last (right-most) column else: residueList = AMINOACIDS residueCols[GAP] = len(AMINOACIDS) for i in residueList: residueCols[i] = cc cc += 1 for i in range(len(self.seq[0]['seq'])): # each column in the sequence if not aa: residueCount = len(BASES) + 1 # for nucleotides; dynamically determined for amino acids below observed = numpy.zeros((groups, len(residueCols)), dtype=float) expected = numpy.zeros((groups, len(residueCols)), dtype=float) gapsPresent = False # flag; if at least one gap, increase degrees of freedom for j in g: # each group for k in j: # each sequence in each group if self.seq[k]['seq'][i] in residueList + [GAP]: # ignore non-bases or non-gaps observed[g.index(j), residueCols[self.seq[k]['seq'][i]]] += 1 if self.seq[k]['seq'][i] == GAP: gapsPresent = True # looks up each residue in the dictionary to determine the column number # row number (group number) determined as follows: # j could hold (1,2,3) for group '1' for example, so index returns the group number if not aa: degreesFreedom = (groups - 1) * (4 - 1) # nt: dof fixed at 4 else: residueCount = 0 for j in range(len(AMINOACIDS)+1): if observed.sum(axis=0)[j] > 0: # determine which residues have a non-zero total residueCount += 1 degreesFreedom = (groups - 1) * (residueCount - 1) if not gapsPresent: if not aa: residueCount -= 1 observed = numpy.delete(observed, 4, 1) # delete column (axis 1) number 4 expected = numpy.delete(expected, 4, 1) # delete column (axis 1) number 4 # for amino acids, the gap is just another residue which is included in the preceeding code else: degreesFreedom =+ 1 # if gaps present, add one to degrees of freedom for j in range(groups): for k in range(residueCount): if observed[j, k] == 0: observed[j, k] = emptyColumn for j in range(groups): expected[j] = (observed.sum(axis=0) * observed[j].sum()) / observed.sum() chisq = ((observed - expected) ** 2) / expected if i == 27: print "observed", observed.round(decimals=3) print "expected", expected.round(decimals=3) print residueCount, "residue count" print degreesFreedom, "degrees freedom" print "CALCULATION", ((observed - expected) ** 2) / expected print "CHI SQUARED", chisq.sum() CHI = scipy.stats.chisqprob(chisq.sum(), degreesFreedom) if CHI <= threshold: print 'position %04i, p=%3.8f, chi-squared=%3.2f, DOF=%i' % (i+1, CHI, chisq.sum(), degreesFreedom) # --------------- def parseReGroups(self, grouping): import re listID = {} c = 0 for i in self.seq: listID[c] = i['id'] # ID stored as dictionary value rather than key; the key is the position c += 1 numSeqs = len(listID) c = 0 groups = [] for i in grouping: thisGroup = '' p = 0 while (len(listID) > 0) and (p <= numSeqs): # while there are items left in the dictionary and we haven't gone further than the initial number of sequences if p in listID: match = re.search(i, listID[p]) # search for the group ("D4") in each of the keys of the dictionary if match: c += 1 thisGroup = thisGroup + str(p+1) + ',' # positions are 1-indexed del listID[p] p += 1 else: p += 1 groups.append(thisGroup[:-1]) # strip the trailing comma and add to the groups list; tuple # ----- i ----- return groups # ----- parseReGroups ----- def groupDistribution(self, grouping, threshold=0.05, aa=False, reGroups=False): # Assumptions: input sequences are aligned and of identical length # Non-nucleotide and/or non-amino acid bases # Completely ignore completely conserved columns import scipy, scipy.stats, numpy emptyColumn = 0.01 # used instead of zero in empty columns if reGroups: grouping = self.parseReGroups(grouping) # convert to standard grouping format: ['1,2-10,12', '11,15-19'] groups = len(grouping) gg = [] for i in grouping: # each group is expanded into list gg gg.append(parseList(i)) # ['1-10', '11,13'] becomes [[[1,10]], [[11,11],[13,13]]] g = [] # which then becomes [(1,2,3,4,5,6,7,8,9,10), (11,13)] (1-indexed here) for i in gg: # stores the grouping as a list of tuples (0-indexed) tt = () for j in i: for k in range(j[0], j[1]+1): tt += (k-1,) # k-1: convert from 1-indexed (provided grouping) to 0-indexed (required) g.append(tt) # g is a list of tuples of each group if aa: residueList = AMINOACIDS[:] # copy list else: residueList = BASES[:] # copy list residueList += [GAP] # add the GAP so that we can check to see if any are present later for i in range(len(self.seq[0]['seq'])): # each column # for i in range(1): residues = [] # list (for column) holding dictionary (for each group) for j in g: # each group rr = {} # make fresh each time; 'copying' didn't seem to work for rrLoop in residueList: rr[rrLoop] = 0 for k in j: # each sequence (in each group) theResidue = self.seq[k]['seq'][i] if theResidue not in residueList: theResidue = GAP rr[theResidue] += 1 # increment each residue # ----- end sequence ----- residues.append(rr) # append the dictionary (rr) for the group to the list (residues) for the column # ----- end group ----- # Check here if column is completely conserved? if aa: # all amino acids, or a gap, are considered as a residue in the column; total them up into reisdueCount rr = {} # make fresh each time; 'copying' didn't seemd to work for rrLoop in residueList: rr[rrLoop] = False residueCount = 0 residuesFound = [] for j in residues: for k in j: if (j[k] > 0) and (not rr[k]): # if there is >0 residue occurences and we've not seen this residue before... rr[k] = True # ...then mark it as seen... residueCount += 1 # ...and add to the residueCount residuesFound.append(k) # ----- aa ----- else: # all four nucleotides are always automatically included; if at least one gap is present, then it is also included residueCount = 4 residuesFound = BASES[:] for j in residues: if j[GAP] > 0: residueCount = 5 residuesFound = residueList # includes GAP break for j in residues: for k in j: if j[k] == 0: j[k] = emptyColumn # all four nucleotides are included; those which are absent are scored at 'emptyColumn' # ----- not aa ----- # print 'residues', residues # print 'residuecount', residueCount # print 'residuesFound', residuesFound observed = numpy.zeros((groups, residueCount), dtype=float) expected = numpy.zeros((groups, residueCount), dtype=float) degreesFreedom = (groups - 1) * (residueCount - 1) residuesFound.sort() for j in range(groups): for k in range(residueCount): observed[j, k] = residues[j][residuesFound[k]] for j in range(groups): expected[j] = (observed.sum(axis=0) * observed[j].sum()) / observed.sum() chisq = ((observed - expected) ** 2) / expected CHI = scipy.stats.chisqprob(chisq.sum(), degreesFreedom) if CHI <= threshold: print 'position %04i, p=%3.8f, chi-squared=%3.2f, DOF=%i' % (i+1, CHI, chisq.sum(), degreesFreedom) # print "observed", observed.round(decimals=3) # print "expected", expected.round(decimals=3) # print residueCount, "residue count" # print degreesFreedom, "degrees freedom" # print "CALCULATION", ((observed - expected) ** 2) / expected # print "CHI SQUARED", chisq.sum() # ----- end column ----- # --------------- def wt2x2(self, grouping, threshold=0.1, reGroups=False): '''Return position, wild-type, Fisher's and Chi for significant positions in 2x2 contingency table''' import math, scipy.stats if reGroups: grouping = climb.parseReGroups(grouping) # convert to standard grouping format: ['1,2-10,12', '11,15-19'] groups = len(grouping) gg = [] for i in grouping: # each group is expanded into list gg gg.append(parseList(i)) # ['1-10', '11,13'] becomes [[[1,10]], [[11,11],[13,13]]] g = [] # which then becomes [(1,2,3,4,5,6,7,8,9,10), (11,13)] (1-indexed here) for i in gg: # stores the grouping as a list of tuples (0-indexed) tt = () for j in i: for k in range(j[0], j[1]+1): tt += (k-1,) # k-1: convert from 1-indexed (provided grouping) to 0-indexed (required) g.append(tt) # g is a list of tuples of each group out = [] length = len(self.seq[0]['seq']) for i in range(0, length): # each position in the sequence d = self.baseDistribution(str(i+1), set1=AMINOACIDS, set2=[GAP]) # print d high = 0 highRes = GAP for j in d[0]: if int(d[0][j]) > high: high = int(d[0][j]) highRes = j # iterate over g[0] for group 1; iterate over g[1] for group 2 mutantList1 = '' mutantList2 = '' tempC = 0 for j in g[0]: if self.seq[j]['seq'][i] == highRes: tempC += 1 else: mutantList1 += self.seq[j]['seq'][i] group1 = (tempC, len(g[0]) - tempC) tempC = 0 for j in g[1]: if self.seq[j]['seq'][i] == highRes: tempC += 1 else: mutantList2 += self.seq[j]['seq'][i] group2 = (tempC, len(g[1]) - tempC) # print group1, group2 # 2x2 contingency "shortcut" variables a = group1[0] b = group1[1] c = group2[0] d = group2[1] FET = (math.factorial(a+b) * math.factorial(c+d) * math.factorial(a+c) * math.factorial(b+d)) / float(math.factorial(a) * math.factorial(b) * math.factorial(c) * math.factorial(d) * math.factorial(a+b+c+d)) # if FET < 0.1: # print "position %03i with wild-type %s has p=%4.3f (Fisher's Exact)" % (i+1, highRes, FET) # if verbose: # print "%05s %05s %05s %05s" % ("grp", "wt", "mut", "tot") # print "%05s %5i %5i %5i" % ("1", group1[0], group1[1], group1[0] + group1[1]) # print "%05s %5i %5i %5i" % ("2", group2[0], group2[1], group2[0] + group2[1]) # print "%05s %5i %5i %5i" % ("tot", group1[0] + group2[0], group1[1] + group2[1], group1[0] + group1[1] + group2[0] + group2[1]) # print if (a > 5) and (b > 5) and (c > 5) and (d > 5): CHI = (((a*d - b*c) ** 2) * (a+b+c+d)) / float( (a+b) * (c+d) * (b+d) * (a+c)) CHIp = scipy.stats.chisqprob(CHI, 1) # 1 dof # if CHIp < 0.1: # print "position %03i with wild-type %s has p=%4.3f (Chi Square = %4.3f)" % (i+1, highRes, CHIp, CHI) else: CHIp = 99 # prevent including this in the returned output below # returns position, wild-type, FET, CHIp, group1, group2 if (FET <= threshold) or (CHIp <= threshold): out.append([i+1, highRes, FET, CHIp, group1, group2, ''.join(sorted(mutantList1)), ''.join(sorted(mutantList2))]) return out # --------------- def gvt(self, grouping, reGroups=False): '''Return variation at each locus for two groups''' # Effectively, a base distribution method for two groups if reGroups: grouping = climb.parseReGroups(grouping) # convert to standard grouping format: ['1,2-10,12', '11,15-19'] groups = len(grouping) gg = [] for i in grouping: # each group is expanded into list gg gg.append(parseList(i)) # ['1-10', '11,13'] becomes [[[1,10]], [[11,11],[13,13]]] g = [] # which then becomes [(1,2,3,4,5,6,7,8,9,10), (11,13)] (1-indexed here) for i in gg: # stores the grouping as a list of tuples (0-indexed) tt = () for j in i: for k in range(j[0], j[1]+1): tt += (k-1,) # k-1: convert from 1-indexed (provided grouping) to 0-indexed (required) g.append(tt) # g is a list of tuples of each group out = [] length = len(self.seq[0]['seq']) for i in range(0, length): # each position in the sequence mutantList1 = {} # dictionaries to store the number of occurrences of each reside in each group mutantList2 = {} # iterate over g[0] for group 1; iterate over g[1] for group 2 for j in AMINOACIDS + ['U', 'O', 'B', 'Z' ,'J', '*']: mutantList1[j] = 0 mutantList2[j] = 0 for j in BASES + [GAP] + ['N', '?', 'X']: mutantList1[j] = 0 mutantList2[j] = 0 for j in g[0]: mutantList1[self.seq[j]['seq'][i]] += 1 for j in g[1]: mutantList2[self.seq[j]['seq'][i]] += 1 out.append([mutantList1, mutantList2]) return (out, g) # return the list of distributions and the grouping # --------------- def deepThreshold(self, prErr=0.01, power=0.05): import scipy.stats df = 1 def chi2(o, e): return ((o-e)**2)/(e) # -------------- chiThreshold = scipy.stats.chi2.isf(power, df) Expected = int(round(prErr * self.seqCount())) # float(prErr * self.seqCount()) if Expected == 0: Expected = 1 Observed = Expected+1 while chi2(Observed, Expected) < chiThreshold: Observed += 1 return (Expected, Observed) # -------------- def deepColumns(self, countThreshold, numColumns=0): # count residues in column which are not majority # any above threshold mean that the position is interesting errorsPerRow = [] for i in range(self.seqCount()): errorsPerRow.append(0) c = 1 interestingColumns = [] if numColumns == 0: numColumns = len(self.seq[0]['seq']) for i in self.baseDistribution('1-%s' % (str(numColumns))): maxCount = 0 maxResidue = '' ignoreBases = [] for j in (BASES + NONBASES): if i[j] > maxCount: maxCount = i[j] maxResidue = j for j in (BASES + NONBASES): if (j <> maxResidue) and (i[j] >= countThreshold): interestingColumns.append(c) break for j in (BASES + NONBASES): if i[j] < countThreshold: ignoreBases.append(j) r = 0 for j in self.seq: if j['seq'][c-1] in ignoreBases: errorsPerRow[r] += 1 r += 1 c += 1 return (interestingColumns, errorsPerRow) # -------------- def SRID(self, searchString, replaceString): import re import copy # >gi|87295395|gb|DQ315783.1| Hepatitis B virus isolate EI03188, complete genome # re.sub(r'.+[bj]\|(?P<n>.+)\.1\|.+', r'\g<n>', x) Temp = copy.deepcopy(self) for i in Temp.seq: i['id'] = re.sub(searchString, replaceString, i['id']) return Temp # S.writeFASTA(sys.argv[2]) # -------------- def SplitID(self, splitList): import re import copy # splitList = ['Y18855','Y18856','Y18857','Y18858','DQ315778','FJ023675','FJ023659'] Temp1 = copy.deepcopy(self) Temp2 = copy.deepcopy(self) Temp1.seqRemoveByID(splitList, retain=True, verbose=False, escape=True) Temp2.seqRemoveByID(splitList, retain=False, verbose=False, escape=True) return (Temp1, Temp2) # -------------- def SplitLength(self, expression): import copy Temp1 = copy.deepcopy(self) Temp2 = copy.deepcopy(self) matchList = [] for i in self.seq: l = len(i['seq']) if eval(expression): matchList.append(i['id']) Temp1.seqRemoveByID(matchList, retain=True, verbose=False, escape=True) Temp2.seqRemoveByID(matchList, retain=False, verbose=False, escape=True) return (Temp1, Temp2) # -------------- def SRseq(self, searchString, replaceString): import copy Temp = copy.deepcopy(self) Temp.seqSR(searchString, replaceString) return Temp # -------------- def SplitMotif(self, queryLoci, queryMotif): import copy Temp1 = copy.deepcopy(self) Temp2 = copy.deepcopy(self) matchList = [] t = self.extract(queryLoci) for i in range(0, self.seqCount()): if re.match(queryMotif, t[i][1]) is not None: matchList.append(self.seq[i]['id']) Temp1.seqRemoveByID(matchList, retain=True, verbose=False, escape=True) Temp2.seqRemoveByID(matchList, retain=False, verbose=False, escape=True) return (Temp1, Temp2) # -------------- if __name__ == '__main__': print motd()
DrTrevorBell/SmallGenomeTools
cgi-bin/climbMini.py
Python
gpl-2.0
65,005
[ "Biopython" ]
0ded0b620682a1fa9e6fd5047116cf90287786e679b0c9de5e32eb5b935d6a48
## INFO ######################################################################## ## ## ## Python and Cython Syntax Highlighters ## ## ===================================== ## ## ## ## Version: 2.0.00.015 (20141006) ## ## File: src/cython.py ## ## ## ## For more information about the project, please visit ## ## <https://github.com/petervaro/python>. ## ## Copyright (C) 2013 - 2014 Peter Varo ## ## ## ## This program is free software: you can redistribute it and/or modify it ## ## under the terms of the GNU General Public License as published by the ## ## Free Software Foundation, either version 3 of the License, or ## ## (at your option) any later version. ## ## ## ## This program is distributed in the hope that it will be useful, but ## ## WITHOUT ANY WARRANTY; without even the implied warranty of ## ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ## ## See the GNU General Public License for more details. ## ## ## ## You should have received a copy of the GNU General Public License ## ## along with this program, most likely a file in the root directory, ## ## called 'LICENSE'. If not, see <http://www.gnu.org/licenses>. ## ## ## ######################################################################## INFO ## #-- CHEATSHEET ----------------------------------------------------------------# # HOWTO: http://sublimetext.info/docs/en/reference/syntaxdefs.html # REGEX: http://manual.macromates.com/en/regular_expressions # Import python modules from copy import deepcopy # Import user modules from src.common import syntax as original # Syntax Definition syntax = deepcopy(original) # Auto-recognition syntax['fileTypes'] = ['pyx', 'pxi', 'pxd'] syntax['keyEquivalent'] = '^~C' # Shebang syntax['firstLineMatch'] = r'^#!/.*\bpython[\d.-]*\b' # Folding marks for the TextEditor syntax['foldingStartMarker'] = (r'^\s*((cp?)?def|class)\s+([.\w>]+)\s*(\((.*)\))?\s*:' r'|\{\s*$|\(\s*$|\[\s*$|^\s*"""(?=.)(?!.*""")') syntax['foldingStopMarker'] = r'^\s*$|^\s*\}|^\s*\]|^\s*\)|^\s*"""\s*$' # Language ID syntax['uuid'] = 'D085155B-E40A-40B3-8FEC-6865318CDEEA' # Patterns syntax['patterns'].update({ #-- COMMENT -------------------------------------------------------------------# # ALL ARE COMMON #-- KEYWORDS ------------------------------------------------------------------# 0x0080: { 'name' : 'storage.modifier.declaration.{SCOPE}', 'match': ( r'\b(global|nonlocal|gil|nogil|extern|api|public|readonly|' r'const(\svolatile)?|inline)\b' ) }, 0x0090: { 'name' : 'keyword.control.import_and_import_from.{SCOPE}', 'match': r'\b(cimport|include|extern|import|from)\b' }, 0x00A0: { 'name' : 'keyword.control.flow_block_delimiters.{SCOPE}', 'match': ( r'\b(elif|else|except|finally|for|if|try|while|with|break|' r'continue|pass|raise|return|yield|IF|ELIF|ELSE|DEF)\b' ) }, 0x00C0: { 'name' : 'keyword.other.{SCOPE}', 'match': r'\b(as|assert|by|del)\b' }, #-- OPERATORS -----------------------------------------------------------------# 0x0101: { 'name' : 'keyword.operator.type_test.{SCOPE}', 'match': r'\?' }, #-- CLASS ---------------------------------------------------------------------# 0x0110: { 'name' : 'meta.class.{SCOPE}', 'begin': r'^\s*(cdef\s+)?(class)\s+(?=[a-zA-Z_]\w*(\s*\()?)', 'beginCaptures': { 1: {'name': 'storage.type.class.definition.{SCOPE}'}, 2: {'name': 'storage.type.class.{SCOPE}'} }, 'patterns': [ {'include': '#class_entity_name'}, {'include': '#class_inheritance'} ], 'end' : r'(\)?\s*:|\s+([\w#\s:]+))', 'endCaptures': { 3: {'name': 'invalid.illegal.missing_section_begin.{SCOPE}'} } }, #-- FUNCTION ------------------------------------------------------------------# 0x0120: { 'name' : 'meta.function.{SCOPE}', 'begin': r'^\s*((cp?)?def)\s+(?=[a-zA-Z_]\w*\s*\()', 'beginCaptures': { 1: {'name': 'storage.type.function.{SCOPE}'} }, 'patterns': [ # TODO: highlight type declarations in functions! # Function name {'include': '#function_entity_name'}, # Arguments {'include': '#function_arguments'}, # Global Interpreter Lock { 'begin': r'\)\s*(nogil)\s*', 'beginCaptures': { 1: {'name': 'storage.modifier.declaration.{SCOPE}'} }, 'end': r'\s*((->)|:|\n+)' }, # Annotation assignment (function) {'include': '#function_annotation'} ], # todo: add illegal 'end': r'(\s*:|\n+)', 'endCaptures': { 2: {'name': 'invalid.illegal.missing_section_begin.{SCOPE}'} } }, #-- LAMBDA --------------------------------------------------------------------# # ALL ARE COMMON #-- DECORATOR -----------------------------------------------------------------# # ALL ARE COMMONE #-- CONSTANTS -----------------------------------------------------------------# 0x0160: { 'name' : 'constant.language.word_like.{SCOPE}', 'match': ( r'\b(NULL|None|True|False|Ellipsis|NotImplemented|' r'UNAME_SYSNAME|UNAME_NODENAME|UNAME_RELEASE|UNAME_VERSION|' r'UNAME_MACHINE|EXIT_FAILURE|EXIT_SUCCESS|RAND_MAX)\b' ) }, #-- STORAGES ------------------------------------------------------------------# 0x0180: { 'name' : 'storage.type.function.{SCOPE}', 'match': r'\b((c(p|type)?)?def|lambda)\b' }, #-- BUILTINS ------------------------------------------------------------------# 0x01A1: { 'include': '#c_types' }, #-- MAGIC STUFFS --------------------------------------------------------------# # ALL ARE COMMON #-- ETC -----------------------------------------------------------------------# # ALL ARE COMMON #-- STRUCTURES ----------------------------------------------------------------# # ALL ARE COMMON #-- ACCESS --------------------------------------------------------------------# # ALL ARE COMMON #-- STRING --------------------------------------------------------------------# # ALL ARE COMMON }) #-- REPOSITORY ----------------------------------------------------------------# syntax['repository'].update({ #-- COMMENTS ------------------------------------------------------------------# # ALL ARE COMMON #-- CLASS ---------------------------------------------------------------------# # ALL ARE COMMON #-- FUNCTION ------------------------------------------------------------------# # ALL ARE COMMON #-- BUILTINS ------------------------------------------------------------------# # TODO: rearrange -> what is builtin function and what is builtin type? 'builtin_functions': { 'name' : 'support.function.builtin.{SCOPE}', 'match': ( r'(?<!\.)\b(' r'__import__|abort|(c|m|re)alloc|(ll?)?abs|all|any|ascii|bin|bsearch|' r'callable|chr|compile|delattr|dir|(ll?)?div|divmod|eval|exec|(_|at)?exit|' r'filter|format|free|getattr|getenv|globals|hasattr|hash|help|hex|id|' r'input|isinstance|issubclass|iter|len|locals|map|max|min|next|' r'oct|ord|pow|print|qsort|range|s?rand|repr|round|setattr|sizeof|' r'sorted|sum|system|vars|zip' r')\b' ) }, 'builtin_types': { 'name' : 'support.type.{SCOPE}', 'match': ( r'(?<!\.)\b(' r'basestring|bool|buffer|bytearray|bytes|classmethod|complex|' r'dict|enumerate|file|frozenset|list|memoryview|object|open|' r'property|reversed|set|slice|staticmethod|str|super|tuple|type' r')\b' ) }, 'c_types': { 'name' : 'support.type.c_types.{SCOPE}', 'match': ( r'(?<!\.)\b(' r'bint|(long\s)?double|enum|float|struct|union|void|const|fused|' r'((un)?signed\s)?(char|((short|long(\slong)?)\s)?int|short|long(\slong)?)' r')\b' ) }, #-- ENTITY --------------------------------------------------------------------# 'illegal_names': { 'name' : 'invalid.illegal_names.name.{SCOPE}', 'match': ( r'\b(' r'and|api|as|assert|break|by|class|continue|(c(p|type)?)?def|del|' r'elif|else|except|finally|for|from|global|if|import|in|is|lambda|' r'nonlocal|not|or|pass|public|raise|return|try|while|with|yield' r')\b' ) }, #-- KEYWORDS ------------------------------------------------------------------# # ALL ARE COMMON #-- MAGIC STUFFS --------------------------------------------------------------# # TODO: rearrange -> what is magic function and what is magic variable? 'magic_function_names': { 'name' : 'support.function.magic.{SCOPE}', 'match': ( r'\b__(' r'abs|add|and|bool|bytes|call|ceil|complex|contains|copy|' r'dealloc|deepcopy|del|delattr|delete|delitem|dir|div|divmod|enter|' r'eq|exit|float|floor|floordiv|format|ge|get|getattr|getattribute|' r'getinitargs|getitem|getnewargs|getstate|gt|hash|hex|iadd|' r'iand|idiv|ifloordiv|ilshift|imul|index|c?init|instancecheck|' r'int|invert|ior|ipow|irshift|isub|iter|itruediv|ixor|le|len|' r'lshift|lt|metaclass|missing|mod|mul|ne|neg|new|next|oct|or|' r'pos|pow|prepare|radd|rand|rdiv|rdivmod|reduce|reduce_ex|' r'repr|reversed|rfloordiv|rlshift|rmod|rmul|ror|round|rpow|' r'rrshift|rshift|rsub|rtruediv|rxor|set|setattr|setitem|' r'setstate|signatures|str|sub|subclasscheck|subclasshook|truediv|' r'trunc|unicode|weakref|xor' r')__\b' ) }, #-- STRING --------------------------------------------------------------------# # ALL ARE COMMON #-- REGEX ---------------------------------------------------------------------# # ALL ARE COMMON })
jotomicron/python
src/cython.py
Python
gpl-3.0
12,220
[ "VisIt" ]
87bf8d30ea5b58215631f9487a3fce336a17e840f9c881d574a02952b0305aa1
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class EcpIoSdk(CMakePackage): """ECP I/O Services SDK""" homepage = "https://github.com/chuckatkins/ecp-data-viz-sdk" git = "https://github.com/chuckatkins/ecp-data-viz-sdk.git" maintainers = ['chuckatkins'] version('1.0', branch='master') variant('adios2', default=True, description="Enable ADIOS2") variant('darshan', default=True, description="Enable Darshan") variant('faodel', default=False, description="Enable FAODEL") variant('hdf5', default=True, description="Enable HDF5") variant('mercury', default=True, description="Enable Mercury") variant('pnetcdf', default=True, description="Enable PNetCDF") variant('unifyfs', default=True, description="Enable UnifyFS") variant('veloc', default=True, description="Enable VeloC") # Currently no spack packages # variant('romio', default=False, description="Enable ROMIO") depends_on('adios2+mpi+fortran+zfp+hdf5', when='+adios2') depends_on('darshan-runtime', when='+darshan') depends_on('darshan-util', when='+darshan') depends_on('faodel+mpi+hdf5', when='+faodel') depends_on('hdf5+mpi+fortran', when='+hdf5') depends_on('mercury+mpi+ofi+sm', when='+mercury') depends_on('parallel-netcdf+fortran+pic', when='+pnetcdf') depends_on('unifyfs+fortran', when='+unifyfs') depends_on('veloc', when='+veloc') def cmake_args(self): return ['-DIO=ON']
rspavel/spack
var/spack/repos/builtin/packages/ecp-io-sdk/package.py
Python
lgpl-2.1
1,635
[ "NetCDF" ]
2ca16c47e4ec33e591283b5c9451112662e6b306a91ebb09a3a74dd7d4b71abd
# pyresample, Resampling of remote sensing image data in python # # Copyright (C) 2010, 2014, 2015 Esben S. Nielsen # Adam.Dybbroe # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or #(at your option) any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. """Handles reprojection of geolocated data. Several types of resampling are supported""" from __future__ import absolute_import import types import warnings import sys import numpy as np from pyresample import geometry, data_reduce, _spatial_mp if sys.version < '3': range = xrange else: long = int kd_tree_name = None try: from pykdtree.kdtree import KDTree kd_tree_name = 'pykdtree' except ImportError: try: import scipy.spatial as sp kd_tree_name = 'scipy.spatial' except ImportError: raise ImportError('Either pykdtree or scipy must be available') class EmptyResult(Exception): pass def which_kdtree(): """Returns the name of the kdtree used for resampling """ return kd_tree_name def resample_nearest(source_geo_def, data, target_geo_def, radius_of_influence, epsilon=0, fill_value=0, reduce_data=True, nprocs=1, segments=None): """Resamples data using kd-tree nearest neighbour approach Parameters ---------- source_geo_def : object Geometry definition of source data : numpy array 1d array of single channel data points or (source_size, k) array of k channels of datapoints target_geo_def : object Geometry definition of target radius_of_influence : float Cut off distance in meters epsilon : float, optional Allowed uncertainty in meters. Increasing uncertainty reduces execution time fill_value : int or None, optional Set undetermined pixels to this value. If fill_value is None a masked array is returned with undetermined pixels masked reduce_data : bool, optional Perform initial coarse reduction of source dataset in order to reduce execution time nprocs : int, optional Number of processor cores to be used segments : int or None Number of segments to use when resampling. If set to None an estimate will be calculated Returns ------- data : numpy array Source data resampled to target geometry """ return _resample(source_geo_def, data, target_geo_def, 'nn', radius_of_influence, neighbours=1, epsilon=epsilon, fill_value=fill_value, reduce_data=reduce_data, nprocs=nprocs, segments=segments) def resample_gauss(source_geo_def, data, target_geo_def, radius_of_influence, sigmas, neighbours=8, epsilon=0, fill_value=0, reduce_data=True, nprocs=1, segments=None, with_uncert=False): """Resamples data using kd-tree gaussian weighting neighbour approach Parameters ---------- source_geo_def : object Geometry definition of source data : numpy array Array of single channel data points or (source_geo_def.shape, k) array of k channels of datapoints target_geo_def : object Geometry definition of target radius_of_influence : float Cut off distance in meters sigmas : list of floats or float List of sigmas to use for the gauss weighting of each channel 1 to k, w_k = exp(-dist^2/sigma_k^2). If only one channel is resampled sigmas is a single float value. neighbours : int, optional The number of neigbours to consider for each grid point epsilon : float, optional Allowed uncertainty in meters. Increasing uncertainty reduces execution time fill_value : {int, None}, optional Set undetermined pixels to this value. If fill_value is None a masked array is returned with undetermined pixels masked reduce_data : bool, optional Perform initial coarse reduction of source dataset in order to reduce execution time nprocs : int, optional Number of processor cores to be used segments : int or None Number of segments to use when resampling. If set to None an estimate will be calculated with_uncert : bool, optional Calculate uncertainty estimates Returns ------- data : numpy array (default) Source data resampled to target geometry data, stddev, counts : numpy array, numpy array, numpy array (if with_uncert == True) Source data resampled to target geometry. Weighted standard devaition for all pixels having more than one source value Counts of number of source values used in weighting per pixel """ def gauss(sigma): # Return gauss function object return lambda r: np.exp(-r ** 2 / float(sigma) ** 2) # Build correct sigma argument is_multi_channel = False try: sigmas.__iter__() sigma_list = sigmas is_multi_channel = True except: sigma_list = [sigmas] for sigma in sigma_list: if not isinstance(sigma, (long, int, float)): raise TypeError('sigma must be number') # Get gauss function objects if is_multi_channel: weight_funcs = list(map(gauss, sigma_list)) else: weight_funcs = gauss(sigmas) return _resample(source_geo_def, data, target_geo_def, 'custom', radius_of_influence, neighbours=neighbours, epsilon=epsilon, weight_funcs=weight_funcs, fill_value=fill_value, reduce_data=reduce_data, nprocs=nprocs, segments=segments, with_uncert=with_uncert) def resample_custom(source_geo_def, data, target_geo_def, radius_of_influence, weight_funcs, neighbours=8, epsilon=0, fill_value=0, reduce_data=True, nprocs=1, segments=None, with_uncert=False): """Resamples data using kd-tree custom radial weighting neighbour approach Parameters ---------- source_geo_def : object Geometry definition of source data : numpy array Array of single channel data points or (source_geo_def.shape, k) array of k channels of datapoints target_geo_def : object Geometry definition of target radius_of_influence : float Cut off distance in meters weight_funcs : list of function objects or function object List of weight functions f(dist) to use for the weighting of each channel 1 to k. If only one channel is resampled weight_funcs is a single function object. neighbours : int, optional The number of neigbours to consider for each grid point epsilon : float, optional Allowed uncertainty in meters. Increasing uncertainty reduces execution time fill_value : {int, None}, optional Set undetermined pixels to this value. If fill_value is None a masked array is returned with undetermined pixels masked reduce_data : bool, optional Perform initial coarse reduction of source dataset in order to reduce execution time nprocs : int, optional Number of processor cores to be used segments : {int, None} Number of segments to use when resampling. If set to None an estimate will be calculated Returns ------- data : numpy array (default) Source data resampled to target geometry data, stddev, counts : numpy array, numpy array, numpy array (if with_uncert == True) Source data resampled to target geometry. Weighted standard devaition for all pixels having more than one source value Counts of number of source values used in weighting per pixel """ try: for weight_func in weight_funcs: if not isinstance(weight_func, types.FunctionType): raise TypeError('weight_func must be function object') except: if not isinstance(weight_funcs, types.FunctionType): raise TypeError('weight_func must be function object') return _resample(source_geo_def, data, target_geo_def, 'custom', radius_of_influence, neighbours=neighbours, epsilon=epsilon, weight_funcs=weight_funcs, fill_value=fill_value, reduce_data=reduce_data, nprocs=nprocs, segments=segments, with_uncert=with_uncert) def _resample(source_geo_def, data, target_geo_def, resample_type, radius_of_influence, neighbours=8, epsilon=0, weight_funcs=None, fill_value=0, reduce_data=True, nprocs=1, segments=None, with_uncert=False): """Resamples swath using kd-tree approach""" valid_input_index, valid_output_index, index_array, distance_array = \ get_neighbour_info(source_geo_def, target_geo_def, radius_of_influence, neighbours=neighbours, epsilon=epsilon, reduce_data=reduce_data, nprocs=nprocs, segments=segments) return get_sample_from_neighbour_info(resample_type, target_geo_def.shape, data, valid_input_index, valid_output_index, index_array, distance_array=distance_array, weight_funcs=weight_funcs, fill_value=fill_value, with_uncert=with_uncert) def get_neighbour_info(source_geo_def, target_geo_def, radius_of_influence, neighbours=8, epsilon=0, reduce_data=True, nprocs=1, segments=None): """Returns neighbour info Parameters ---------- source_geo_def : object Geometry definition of source target_geo_def : object Geometry definition of target radius_of_influence : float Cut off distance in meters neighbours : int, optional The number of neigbours to consider for each grid point epsilon : float, optional Allowed uncertainty in meters. Increasing uncertainty reduces execution time fill_value : int or None, optional Set undetermined pixels to this value. If fill_value is None a masked array is returned with undetermined pixels masked reduce_data : bool, optional Perform initial coarse reduction of source dataset in order to reduce execution time nprocs : int, optional Number of processor cores to be used segments : int or None Number of segments to use when resampling. If set to None an estimate will be calculated Returns ------- (valid_input_index, valid_output_index, index_array, distance_array) : tuple of numpy arrays Neighbour resampling info """ if source_geo_def.size < neighbours: warnings.warn('Searching for %s neighbours in %s data points' % (neighbours, source_geo_def.size)) if segments is None: cut_off = 3000000 if target_geo_def.size > cut_off: segments = int(target_geo_def.size / cut_off) else: segments = 1 # Find reduced input coordinate set valid_input_index, source_lons, source_lats = _get_valid_input_index(source_geo_def, target_geo_def, reduce_data, radius_of_influence, nprocs=nprocs) # Create kd-tree try: resample_kdtree = _create_resample_kdtree(source_lons, source_lats, valid_input_index, nprocs=nprocs) except EmptyResult: # Handle if all input data is reduced away valid_output_index, index_array, distance_array = \ _create_empty_info(source_geo_def, target_geo_def, neighbours) return (valid_input_index, valid_output_index, index_array, distance_array) if segments > 1: # Iterate through segments for i, target_slice in enumerate(geometry._get_slice(segments, target_geo_def.shape)): # Query on slice of target coordinates next_voi, next_ia, next_da = \ _query_resample_kdtree(resample_kdtree, source_geo_def, target_geo_def, radius_of_influence, target_slice, neighbours=neighbours, epsilon=epsilon, reduce_data=reduce_data, nprocs=nprocs) # Build result iteratively if i == 0: # First iteration valid_output_index = next_voi index_array = next_ia distance_array = next_da else: valid_output_index = np.append(valid_output_index, next_voi) if neighbours > 1: index_array = np.row_stack((index_array, next_ia)) distance_array = np.row_stack((distance_array, next_da)) else: index_array = np.append(index_array, next_ia) distance_array = np.append(distance_array, next_da) else: # Query kd-tree with full target coordinate set full_slice = slice(None) valid_output_index, index_array, distance_array = \ _query_resample_kdtree(resample_kdtree, source_geo_def, target_geo_def, radius_of_influence, full_slice, neighbours=neighbours, epsilon=epsilon, reduce_data=reduce_data, nprocs=nprocs) # Check if number of neighbours is potentially too low if neighbours > 1: if not np.all(np.isinf(distance_array[:, -1])): warnings.warn(('Possible more than %s neighbours ' 'within %s m for some data points') % (neighbours, radius_of_influence)) return valid_input_index, valid_output_index, index_array, distance_array def _get_valid_input_index(source_geo_def, target_geo_def, reduce_data, radius_of_influence, nprocs=1): """Find indices of reduced inputput data""" source_lons, source_lats = source_geo_def.get_lonlats(nprocs=nprocs) source_lons = source_lons.ravel() source_lats = source_lats.ravel() if source_lons.size == 0 or source_lats.size == 0: raise ValueError('Cannot resample empty data set') elif source_lons.size != source_lats.size or \ source_lons.shape != source_lats.shape: raise ValueError('Mismatch between lons and lats') # Remove illegal values valid_data = ((source_lons >= -180) & (source_lons <= 180) & (source_lats <= 90) & (source_lats >= -90)) valid_input_index = np.ones(source_geo_def.size, dtype=np.bool) if reduce_data: # Reduce dataset if (isinstance(source_geo_def, geometry.CoordinateDefinition) and isinstance(target_geo_def, (geometry.GridDefinition, geometry.AreaDefinition))) or \ (isinstance(source_geo_def, (geometry.GridDefinition, geometry.AreaDefinition)) and isinstance(target_geo_def, (geometry.GridDefinition, geometry.AreaDefinition))): # Resampling from swath to grid or from grid to grid lonlat_boundary = target_geo_def.get_boundary_lonlats() valid_input_index = \ data_reduce.get_valid_index_from_lonlat_boundaries( lonlat_boundary[0], lonlat_boundary[1], source_lons, source_lats, radius_of_influence) # Combine reduced and legal values valid_input_index = (valid_data & valid_input_index) if(isinstance(valid_input_index, np.ma.core.MaskedArray)): # Make sure valid_input_index is not a masked array valid_input_index = valid_input_index.filled(False) return valid_input_index, source_lons, source_lats def _get_valid_output_index(source_geo_def, target_geo_def, target_lons, target_lats, reduce_data, radius_of_influence): """Find indices of reduced output data""" valid_output_index = np.ones(target_lons.size, dtype=np.bool) if reduce_data: if isinstance(source_geo_def, (geometry.GridDefinition, geometry.AreaDefinition)) and \ isinstance(target_geo_def, geometry.CoordinateDefinition): # Resampling from grid to swath lonlat_boundary = source_geo_def.get_boundary_lonlats() valid_output_index = \ data_reduce.get_valid_index_from_lonlat_boundaries( lonlat_boundary[0], lonlat_boundary[1], target_lons, target_lats, radius_of_influence) valid_output_index = valid_output_index.astype(np.bool) # Remove illegal values valid_out = ((target_lons >= -180) & (target_lons <= 180) & (target_lats <= 90) & (target_lats >= -90)) # Combine reduced and legal values valid_output_index = (valid_output_index & valid_out) return valid_output_index def _create_resample_kdtree(source_lons, source_lats, valid_input_index, nprocs=1): """Set up kd tree on input""" """ if not isinstance(source_geo_def, geometry.BaseDefinition): raise TypeError('source_geo_def must be of geometry type') #Get reduced cartesian coordinates and flatten them source_cartesian_coords = source_geo_def.get_cartesian_coords(nprocs=nprocs) input_coords = geometry._flatten_cartesian_coords(source_cartesian_coords) input_coords = input_coords[valid_input_index] """ source_lons_valid = source_lons[valid_input_index] source_lats_valid = source_lats[valid_input_index] if nprocs > 1: cartesian = _spatial_mp.Cartesian_MP(nprocs) else: cartesian = _spatial_mp.Cartesian() input_coords = cartesian.transform_lonlats( source_lons_valid, source_lats_valid) if input_coords.size == 0: raise EmptyResult('No valid data points in input data') # Build kd-tree on input if kd_tree_name == 'pykdtree': resample_kdtree = KDTree(input_coords) elif nprocs > 1: resample_kdtree = _spatial_mp.cKDTree_MP(input_coords, nprocs=nprocs) else: resample_kdtree = sp.cKDTree(input_coords) return resample_kdtree def _query_resample_kdtree(resample_kdtree, source_geo_def, target_geo_def, radius_of_influence, data_slice, neighbours=8, epsilon=0, reduce_data=True, nprocs=1): """Query kd-tree on slice of target coordinates""" # Check validity of input if not isinstance(target_geo_def, geometry.BaseDefinition): raise TypeError('target_geo_def must be of geometry type') elif not isinstance(radius_of_influence, (long, int, float)): raise TypeError('radius_of_influence must be number') elif not isinstance(neighbours, int): raise TypeError('neighbours must be integer') elif not isinstance(epsilon, (long, int, float)): raise TypeError('epsilon must be number') # Get sliced target coordinates target_lons, target_lats = target_geo_def.get_lonlats(nprocs=nprocs, data_slice=data_slice, dtype=source_geo_def.dtype) # Find indiced of reduced target coordinates valid_output_index = _get_valid_output_index(source_geo_def, target_geo_def, target_lons.ravel(), target_lats.ravel(), reduce_data, radius_of_influence) # Get cartesian target coordinates and select reduced set if nprocs > 1: cartesian = _spatial_mp.Cartesian_MP(nprocs) else: cartesian = _spatial_mp.Cartesian() target_lons_valid = target_lons.ravel()[valid_output_index] target_lats_valid = target_lats.ravel()[valid_output_index] output_coords = cartesian.transform_lonlats( target_lons_valid, target_lats_valid) # pykdtree requires query points have same data type as kdtree. try: dt = resample_kdtree.data.dtype except AttributeError: # use a sensible default dt = np.dtype('d') output_coords = np.asarray(output_coords, dtype=dt) # Query kd-tree distance_array, index_array = resample_kdtree.query(output_coords, k=neighbours, eps=epsilon, distance_upper_bound=radius_of_influence) return valid_output_index, index_array, distance_array def _create_empty_info(source_geo_def, target_geo_def, neighbours): """Creates dummy info for empty result set""" valid_output_index = np.ones(target_geo_def.size, dtype=np.bool) if neighbours > 1: index_array = (np.ones((target_geo_def.size, neighbours), dtype=np.int32) * source_geo_def.size) distance_array = np.ones((target_geo_def.size, neighbours)) else: index_array = (np.ones(target_geo_def.size, dtype=np.int32) * source_geo_def.size) distance_array = np.ones(target_geo_def.size) return valid_output_index, index_array, distance_array def get_sample_from_neighbour_info(resample_type, output_shape, data, valid_input_index, valid_output_index, index_array, distance_array=None, weight_funcs=None, fill_value=0, with_uncert=False): """Resamples swath based on neighbour info Parameters ---------- resample_type : {'nn', 'custom'} 'nn': Use nearest neighbour resampling 'custom': Resample based on weight_funcs output_shape : (int, int) Shape of output as (rows, cols) data : numpy array Source data valid_input_index : numpy array valid_input_index from get_neighbour_info valid_output_index : numpy array valid_output_index from get_neighbour_info index_array : numpy array index_array from get_neighbour_info distance_array : numpy array, optional distance_array from get_neighbour_info Not needed for 'nn' resample type weight_funcs : list of function objects or function object, optional List of weight functions f(dist) to use for the weighting of each channel 1 to k. If only one channel is resampled weight_funcs is a single function object. Must be supplied when using 'custom' resample type fill_value : int or None, optional Set undetermined pixels to this value. If fill_value is None a masked array is returned with undetermined pixels masked Returns ------- result : numpy array Source data resampled to target geometry """ if data.ndim > 2 and data.shape[0] * data.shape[1] == valid_input_index.size: data = data.reshape(data.shape[0] * data.shape[1], data.shape[2]) elif data.shape[0] != valid_input_index.size: data = data.ravel() if valid_input_index.size != data.shape[0]: raise ValueError('Mismatch between geometry and dataset') is_multi_channel = (data.ndim > 1) valid_input_size = valid_input_index.sum() valid_output_size = valid_output_index.sum() # Handle empty result set if valid_input_size == 0 or valid_output_size == 0: if is_multi_channel: output_shape = list(output_shape) output_shape.append(data.shape[1]) if fill_value is None: # Use masked array for fill values return np.ma.array(np.zeros(output_shape, data.dtype), mask=np.ones(output_shape, dtype=np.bool)) else: # Return fill vaues for all pixels return np.ones(output_shape, dtype=data.dtype) * fill_value # Get size of output and reduced input input_size = valid_input_size if len(output_shape) > 1: output_size = output_shape[0] * output_shape[1] else: output_size = output_shape[0] # Check validity of input if not isinstance(data, np.ndarray): raise TypeError('data must be numpy array') elif valid_input_index.ndim != 1: raise TypeError('valid_index must be one dimensional array') elif data.shape[0] != valid_input_index.size: raise TypeError('Not the same number of datapoints in ' 'valid_input_index and data') valid_types = ('nn', 'custom') if not resample_type in valid_types: raise TypeError('Invalid resampling type: %s' % resample_type) if resample_type == 'custom' and weight_funcs is None: raise ValueError('weight_funcs must be supplied when using ' 'custom resampling') if not isinstance(fill_value, (long, int, float)) and fill_value is not None: raise TypeError('fill_value must be number or None') if index_array.ndim == 1: neighbours = 1 else: neighbours = index_array.shape[1] if resample_type == 'nn': raise ValueError('index_array contains more neighbours than ' 'just the nearest') # Reduce data new_data = data[valid_input_index] # Nearest neighbour resampling should conserve data type # Get data type conserve_input_data_type = False if resample_type == 'nn': conserve_input_data_type = True input_data_type = new_data.dtype # Handle masked array input is_masked_data = False if np.ma.is_masked(new_data): # Add the mask as channels to the dataset is_masked_data = True new_data = np.column_stack((new_data.data, new_data.mask)) if new_data.ndim > 1: # Multiple channels or masked input output_shape = list(output_shape) output_shape.append(new_data.shape[1]) # Prepare weight_funcs argument for handeling mask data if weight_funcs is not None and is_masked_data: if is_multi_channel: weight_funcs = weight_funcs * 2 else: weight_funcs = (weight_funcs,) * 2 # Handle request for masking intead of using fill values use_masked_fill_value = False if fill_value is None: use_masked_fill_value = True fill_value = _get_fill_mask_value(new_data.dtype) # Resample based on kd-tree query result if resample_type == 'nn' or neighbours == 1: # Get nearest neighbour using array indexing index_mask = (index_array == input_size) new_index_array = np.where(index_mask, 0, index_array) result = new_data[new_index_array] result[index_mask] = fill_value else: # Calculate result using weighting. # Note: the code below has low readability in order # to avoid looping over numpy arrays # Get neighbours and masks of valid indices ch_neighbour_list = [] index_mask_list = [] for i in range(neighbours): # Iterate over number of neighbours # Make working copy neighbour index and # set out of bounds indices to zero index_ni = index_array[:, i].copy() index_mask_ni = (index_ni == input_size) index_ni[index_mask_ni] = 0 # Get channel data for the corresponing indices ch_ni = new_data[index_ni] ch_neighbour_list.append(ch_ni) index_mask_list.append(index_mask_ni) # Calculate weights weight_list = [] for i in range(neighbours): # Iterate over number of neighbours # Make working copy of neighbour distances and # set out of bounds distance to 1 in order to avoid numerical Inf distance = distance_array[:, i].copy() distance[index_mask_list[i]] = 1 if new_data.ndim > 1: # More than one channel in data set. # Calculate weights for each channel weights = [] num_weights = valid_output_index.sum() num_channels = new_data.shape[1] for j in range(num_channels): calc_weight = weight_funcs[j](distance) # Turn a scalar weight into a numpy array # (no effect if calc_weight already is an array) expanded_calc_weight = np.ones(num_weights) * calc_weight weights.append(expanded_calc_weight) # Collect weights for all channels for neighbour number weight_list.append(np.column_stack(weights)) else: # Only one channel weights = weight_funcs(distance) weight_list.append(weights) result = 0 norm = 0 count = 0 norm_sqr = 0 stddev = 0 # Calculate result for i in range(neighbours): # Iterate over number of neighbours # Find invalid indices to be masked of from calculation if new_data.ndim > 1: # More than one channel in data set. inv_index_mask = np.expand_dims( np.invert(index_mask_list[i]), axis=1) else: # Only one channel inv_index_mask = np.invert(index_mask_list[i]) # Aggregate result and norm weights_tmp = inv_index_mask * weight_list[i] result += weights_tmp * ch_neighbour_list[i] norm += weights_tmp # Normalize result and set fillvalue result_valid_index = (norm > 0) result[result_valid_index] /= norm[result_valid_index] if with_uncert: # Calculate uncertainties # 2. pass to calculate standard deviation for i in range(neighbours): # Iterate over number of neighbours # Find invalid indices to be masked of from calculation if new_data.ndim > 1: # More than one channel in data set. inv_index_mask = np.expand_dims( np.invert(index_mask_list[i]), axis=1) else: # Only one channel inv_index_mask = np.invert(index_mask_list[i]) # Aggregate stddev information weights_tmp = inv_index_mask * weight_list[i] count += inv_index_mask norm_sqr += weights_tmp ** 2 values = inv_index_mask * ch_neighbour_list[i] stddev += weights_tmp * (values - result) ** 2 # Calculate final stddev new_valid_index = (count > 1) v1 = norm[new_valid_index] v2 = norm_sqr[new_valid_index] stddev[new_valid_index] = np.sqrt( (v1 / (v1 ** 2 - v2)) * stddev[new_valid_index]) stddev[~new_valid_index] = np.NaN # Add fill values result[np.invert(result_valid_index)] = fill_value # Create full result if new_data.ndim > 1: # More than one channel output_raw_shape = ((output_size, new_data.shape[1])) else: # One channel output_raw_shape = output_size full_result = np.ones(output_raw_shape) * fill_value full_result[valid_output_index] = result result = full_result if with_uncert: # Add fill values for uncertainty full_stddev = np.ones(output_raw_shape) * np.nan full_count = np.zeros(output_raw_shape) full_stddev[valid_output_index] = stddev full_count[valid_output_index] = count stddev = full_stddev count = full_count stddev = stddev.reshape(output_shape) count = count.reshape(output_shape) if is_masked_data: # Ignore uncert computation of masks stddev = _remask_data(stddev, is_to_be_masked=False) count = _remask_data(count, is_to_be_masked=False) # Set masks for invalid stddev stddev = np.ma.array(stddev, mask=np.isnan(stddev)) # Reshape resampled data to correct shape result = result.reshape(output_shape) # Remap mask channels to create masked output if is_masked_data: result = _remask_data(result) # Create masking of fill values if use_masked_fill_value: result = np.ma.masked_equal(result, fill_value) # Set output data type to input data type if relevant if conserve_input_data_type: result = result.astype(input_data_type) if with_uncert: if np.ma.isMA(result): stddev = np.ma.array(stddev, mask=(result.mask | stddev.mask)) count = np.ma.array(count, mask=result.mask) return result, stddev, count else: return result def _get_fill_mask_value(data_dtype): """Returns the maximum value of dtype""" if issubclass(data_dtype.type, np.floating): fill_value = np.finfo(data_dtype.type).max elif issubclass(data_dtype.type, np.integer): fill_value = np.iinfo(data_dtype.type).max else: raise TypeError('Type %s is unsupported for masked fill values' % data_dtype.type) return fill_value def _remask_data(data, is_to_be_masked=True): """Interprets half the array as mask for the other half""" channels = data.shape[-1] if is_to_be_masked: mask = data[..., (channels // 2):] # All pixels affected by masked pixels are masked out mask = (mask != 0) data = np.ma.array(data[..., :(channels // 2)], mask=mask) else: data = data[..., :(channels // 2)] if data.shape[-1] == 1: data = data.reshape(data.shape[:-1]) return data
mitkin/pyresample
pyresample/kd_tree.py
Python
lgpl-3.0
35,833
[ "Gaussian" ]
1ec1eebf938dc3575ca2adcf85db6680fafa9dc95da12f8facc7bbc8fde98c84
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import os import unittest import numpy as np from pymatgen.core.structure import Structure from pymatgen.io.cif import CifParser from pymatgen.io.feff.inputs import Atoms, Header, Paths, Potential, Tags from pymatgen.util.testing import PymatgenTest header_string = """* This FEFF.inp file generated by pymatgen TITLE comment: From cif file TITLE Source: CoO19128.cif TITLE Structure Summary: Co2 O2 TITLE Reduced formula: CoO TITLE space group: (Cmc2_1), space number: (36) TITLE abc: 3.297078 3.297078 5.254213 TITLE angles: 90.000000 90.000000 120.000000 TITLE sites: 4 * 1 Co 0.666666 0.333332 0.496324 * 2 Co 0.333333 0.666667 0.996324 * 3 O 0.666666 0.333332 0.878676 * 4 O 0.333333 0.666667 0.378675""" class HeaderTest(unittest.TestCase): def test_init(self): filepath = os.path.join(PymatgenTest.TEST_FILES_DIR, "HEADER") header = Header.header_string_from_file(filepath) h = header.splitlines() hs = header_string.splitlines() for i, line in enumerate(h): self.assertEqual(line, hs[i]) self.assertEqual( header_string.splitlines(), header.splitlines(), "Failed to read HEADER file", ) def test_from_string(self): header = Header.from_string(header_string) self.assertEqual( header.struct.composition.reduced_formula, "CoO", "Failed to generate structure from HEADER string", ) def test_get_string(self): cif_file = os.path.join(PymatgenTest.TEST_FILES_DIR, "CoO19128.cif") h = Header.from_cif_file(cif_file) head = str(h) self.assertEqual( head.splitlines()[3].split()[-1], header_string.splitlines()[3].split()[-1], "Failed to generate HEADER from structure", ) def test_as_dict_and_from_dict(self): file_name = os.path.join(PymatgenTest.TEST_FILES_DIR, "HEADER") header = Header.from_file(file_name) d = header.as_dict() header2 = Header.from_dict(d) self.assertEqual(str(header), str(header2), "Header failed to and from dict test") class FeffAtomsTest(unittest.TestCase): @classmethod def setUpClass(cls): r = CifParser(os.path.join(PymatgenTest.TEST_FILES_DIR, "CoO19128.cif")) cls.structure = r.get_structures()[0] cls.atoms = Atoms(cls.structure, "O", 10.0) def test_absorbing_atom(self): atoms_1 = Atoms(self.structure, 0, 10.0) atoms_2 = Atoms(self.structure, 2, 10.0) self.assertEqual(atoms_1.absorbing_atom, "Co") self.assertEqual(atoms_2.absorbing_atom, "O") def test_absorber_line(self): atoms_lines = self.atoms.get_lines() # x self.assertAlmostEqual(float(atoms_lines[0][0]), 0.0) # y self.assertAlmostEqual(float(atoms_lines[0][1]), 0.0) # z self.assertAlmostEqual(float(atoms_lines[0][2]), 0.0) # ipot self.assertEqual(int(atoms_lines[0][3]), 0) # atom symbol self.assertEqual(atoms_lines[0][4], "O") # distance self.assertAlmostEqual(float(atoms_lines[0][5]), 0.0) # id self.assertEqual(int(atoms_lines[0][6]), 0) def test_distances(self): atoms_1 = self.atoms.get_lines() distances_1 = [float(a[5]) for a in atoms_1] atoms_2 = Atoms.atoms_string_from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "ATOMS")) atoms_2 = atoms_2.splitlines()[3:] distances_2 = [float(a.split()[5]) for a in atoms_2] np.testing.assert_allclose(distances_1, distances_2, rtol=1e-5) def test_atoms_from_file(self): filepath = os.path.join(PymatgenTest.TEST_FILES_DIR, "ATOMS") atoms = Atoms.atoms_string_from_file(filepath) self.assertEqual(atoms.splitlines()[3].split()[4], "O", "failed to read ATOMS file") def test_get_string(self): header = Header.from_string(header_string) struc = header.struct central_atom = "O" a = Atoms(struc, central_atom, radius=10.0) atoms = str(a) self.assertEqual( atoms.splitlines()[3].split()[4], central_atom, "failed to create ATOMS string", ) def test_as_dict_and_from_dict(self): file_name = os.path.join(PymatgenTest.TEST_FILES_DIR, "HEADER") header = Header.from_file(file_name) struct = header.struct atoms = Atoms(struct, "O", radius=10.0) d = atoms.as_dict() atoms2 = Atoms.from_dict(d) self.assertEqual(str(atoms), str(atoms2), "Atoms failed to and from dict test") def test_cluster_from_file(self): self.atoms.write_file("ATOMS_test") mol_1 = Atoms.cluster_from_file("ATOMS_test") mol_2 = Atoms.cluster_from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "ATOMS")) self.assertEqual(mol_1.formula, mol_2.formula) self.assertEqual(len(mol_1), len(mol_2)) os.remove("ATOMS_test") class FeffTagsTest(unittest.TestCase): def test_init(self): filepath = os.path.join(PymatgenTest.TEST_FILES_DIR, "PARAMETERS") parameters = Tags.from_file(filepath) parameters["RPATH"] = 10 self.assertEqual(parameters["COREHOLE"], "Fsr", "Failed to read PARAMETERS file") self.assertEqual(parameters["LDOS"], [-30.0, 15.0, 0.1], "Failed to read PARAMETERS file") def test_diff(self): filepath1 = os.path.join(PymatgenTest.TEST_FILES_DIR, "PARAMETERS") parameters1 = Tags.from_file(filepath1) filepath2 = os.path.join(PymatgenTest.TEST_FILES_DIR, "PARAMETERS.2") parameters2 = Tags.from_file(filepath2) self.assertEqual( Tags(parameters1).diff(parameters2), { "Different": {}, "Same": { "CONTROL": [1, 1, 1, 1, 1, 1], "MPSE": [2], "OPCONS": "", "SCF": [6.0, 0, 30, 0.2, 1], "EXCHANGE": [0, 0.0, 0.0, 2], "S02": [0.0], "COREHOLE": "Fsr", "FMS": [8.5, 0], "XANES": [3.7, 0.04, 0.1], "EDGE": "K", "PRINT": [1, 0, 0, 0, 0, 0], "LDOS": [-30.0, 15.0, 0.1], }, }, ) def test_as_dict_and_from_dict(self): file_name = os.path.join(PymatgenTest.TEST_FILES_DIR, "PARAMETERS") tags = Tags.from_file(file_name) d = tags.as_dict() tags2 = Tags.from_dict(d) self.assertEqual(tags, tags2, "Parameters do not match to and from dict") def test_eels_tags(self): ans_1 = { "CONTROL": [1, 1, 1, 1, 1, 1], "COREHOLE": "Fsr", "EDGE": "K", "ELNES": { "ANGLES": "7.6 6.4", "BEAM_ENERGY": "200 1 0 1", "ENERGY": "4.0 .04 0.1", "MESH": "50 1", "POSITION": "0 0", }, "EXCHANGE": [0, 0.0, 0.0, 2], "FMS": [7.5], "PRINT": [1, 0, 0, 0, 0, 0], "RPATH": [-1], "S02": [0.0], "SCF": [6, 0, 30, 0.2, 5], } tags_1 = Tags.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "feff_eels_powder.inp")) self.assertEqual(dict(tags_1), ans_1) ans_1["ELNES"]["BEAM_ENERGY"] = "200 0 1 1" ans_1["ELNES"]["BEAM_DIRECTION"] = "1 0 0" tags_2 = Tags.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "feff_eels_x.inp")) self.assertEqual(dict(tags_2), ans_1) class FeffPotTest(unittest.TestCase): def test_init(self): filepath = os.path.join(PymatgenTest.TEST_FILES_DIR, "POTENTIALS") feffpot = Potential.pot_string_from_file(filepath) d, dr = Potential.pot_dict_from_string(feffpot) self.assertEqual(d["Co"], 1, "Wrong symbols read in for Potential") def test_as_dict_and_from_dict(self): file_name = os.path.join(PymatgenTest.TEST_FILES_DIR, "HEADER") header = Header.from_file(file_name) struct = header.struct pot = Potential(struct, "O") d = pot.as_dict() pot2 = Potential.from_dict(d) self.assertEqual(str(pot), str(pot2), "Potential to and from dict does not match") class PathsTest(unittest.TestCase): def setUp(self): feo = Structure.from_dict( { "lattice": { "a": 3.3960486211791285, "alpha": 91.45136142952781, "b": 3.410591877060444, "beta": 89.27127081348024, "c": 10.71766796897646, "gamma": 120.14175587658389, "matrix": [ [3.39597035, -0.00828486, 0.02151698], [-1.70515997, 2.9534242, -0.04303398], [0.06812465, -0.11799566, 10.71680189], ], "volume": 107.31813123502585, }, "sites": [ { "abc": [0.33497754, 0.66579918, 0.97174225], "label": "Fe", "properties": { "coordination_no": 4, "forces": [-0.01537896, -0.08731049, 0.04884326], }, "species": [{"element": "Fe", "occu": 1}], "xyz": [ 0.06847928463257683, 1.8489508003914767, 10.392524897825345, ], }, { "abc": [0.99661905, 0.00734083, 0.22366433], "label": "Fe", "properties": { "coordination_no": 4, "forces": [-0.01685376, -0.01008504, 0.05451912], }, "species": [{"element": "Fe", "occu": 1}], "xyz": [ 3.387208508781326, -0.0129676845693048, 2.4180946415046494, ], }, { "abc": [0.00338095, 0.01072178, 0.72366433], "label": "Fe", "properties": { "coordination_no": 4, "forces": [0.01716078, 0.00955327, 0.05451912], }, "species": [{"element": "Fe", "occu": 1}], "xyz": [ 0.04249863509042039, -0.053751296415148794, 7.754978606437029, ], }, { "abc": [0.66502246, 0.33082164, 0.47174225], "label": "Fe", "properties": { "coordination_no": 4, "forces": [0.08330257, -0.03033668, 0.04884326], }, "species": [{"element": "Fe", "occu": 1}], "xyz": [ 1.7264300141777726, 0.9158834813430974, 5.055640939524896, ], }, { "abc": [0.33062914, 0.66733572, 0.77744897], "label": "O", "properties": { "coordination_no": 4, "forces": [-0.07726687, -0.00523346, -0.05206924], }, "species": [{"element": "O", "occu": 1}], "xyz": [ 0.03785603896498114, 1.8764506445041333, 8.310162619639584, ], }, { "abc": [0.00312189, 0.99229908, 0.52714445], "label": "O", "properties": { "coordination_no": 4, "forces": [-0.06744419, 0.00047044, -0.05129314], }, "species": [{"element": "O", "occu": 1}], "xyz": [ -1.6455152924521734, 2.8684534947950637, 5.606667232944964, ], }, { "abc": [0.99687811, 0.98917618, 0.02714445], "label": "O", "properties": { "coordination_no": 4, "forces": [0.03331469, 0.05864361, -0.05129314], }, "species": [{"element": "O", "occu": 1}], "xyz": [ 1.7005140848662161, 2.9099949452040543, 0.2697833114717219, ], }, { "abc": [0.66937086, 0.33670658, 0.27744897], "label": "O", "properties": { "coordination_no": 4, "forces": [0.04316575, 0.06429835, -0.05206924], }, "species": [{"element": "O", "occu": 1}], "xyz": [ 1.7179261258365088, 0.9561539434765862, 2.9732786612521678, ], }, ], } ) atoms = Atoms(feo, 0, 10.0) self.paths = Paths(atoms, [[22, 16, 0], [250, 282, 250, 0]]) def test_paths_string(self): lines = [ "PATH", "---------------", "9999 3 1", "x y z ipot label", "-3.428830 -3.869922 -5.336884 1 Fe", "-5.133990 -0.916498 -5.379918 1 Fe", "0.000000 0.000000 0.000000 0 Fe", "9998 4 1", "x y z ipot label", "5.056157 2.964354 -2.082362 2 O", "8.473635 0.956940 2.742372 1 Fe", "5.056157 2.964354 -2.082362 2 O", "0.000000 0.000000 0.000000 0 Fe", ] ans = "\n".join(lines) self.assertEqual(ans, str(self.paths)) if __name__ == "__main__": unittest.main()
materialsproject/pymatgen
pymatgen/io/feff/tests/test_inputs.py
Python
mit
15,079
[ "FEFF", "pymatgen" ]
b3b1e1aa071eae9ffdc99542677359df849c3e4b186de74850de7a3a8e32dae2
# Copyright: (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # Copyright: (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com> # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import getpass import os import subprocess import sys from abc import ABCMeta, abstractmethod from ansible.cli.arguments import option_helpers as opt_help from ansible import constants as C from ansible import context from ansible.errors import AnsibleError from ansible.inventory.manager import InventoryManager from ansible.module_utils.six import with_metaclass, string_types from ansible.module_utils._text import to_bytes, to_text from ansible.parsing.dataloader import DataLoader from ansible.parsing.vault import PromptVaultSecret, get_file_vault_secret from ansible.plugins.loader import add_all_plugin_dirs from ansible.release import __version__ from ansible.utils.collection_loader import AnsibleCollectionConfig from ansible.utils.collection_loader._collection_finder import _get_collection_name_from_path from ansible.utils.display import Display from ansible.utils.path import unfrackpath from ansible.utils.unsafe_proxy import to_unsafe_text from ansible.vars.manager import VariableManager try: import argcomplete HAS_ARGCOMPLETE = True except ImportError: HAS_ARGCOMPLETE = False display = Display() class CLI(with_metaclass(ABCMeta, object)): ''' code behind bin/ansible* programs ''' PAGER = 'less' # -F (quit-if-one-screen) -R (allow raw ansi control chars) # -S (chop long lines) -X (disable termcap init and de-init) LESS_OPTS = 'FRSX' SKIP_INVENTORY_DEFAULTS = False def __init__(self, args, callback=None): """ Base init method for all command line programs """ if not args: raise ValueError('A non-empty list for args is required') self.args = args self.parser = None self.callback = callback if C.DEVEL_WARNING and __version__.endswith('dev0'): display.warning( 'You are running the development version of Ansible. You should only run Ansible from "devel" if ' 'you are modifying the Ansible engine, or trying out features under development. This is a rapidly ' 'changing source of code and can become unstable at any point.' ) @abstractmethod def run(self): """Run the ansible command Subclasses must implement this method. It does the actual work of running an Ansible command. """ self.parse() display.vv(to_text(opt_help.version(self.parser.prog))) if C.CONFIG_FILE: display.v(u"Using %s as config file" % to_text(C.CONFIG_FILE)) else: display.v(u"No config file found; using defaults") # warn about deprecated config options for deprecated in C.config.DEPRECATED: name = deprecated[0] why = deprecated[1]['why'] if 'alternatives' in deprecated[1]: alt = ', use %s instead' % deprecated[1]['alternatives'] else: alt = '' ver = deprecated[1].get('version') date = deprecated[1].get('date') collection_name = deprecated[1].get('collection_name') display.deprecated("%s option, %s%s" % (name, why, alt), version=ver, date=date, collection_name=collection_name) @staticmethod def split_vault_id(vault_id): # return (before_@, after_@) # if no @, return whole string as after_ if '@' not in vault_id: return (None, vault_id) parts = vault_id.split('@', 1) ret = tuple(parts) return ret @staticmethod def build_vault_ids(vault_ids, vault_password_files=None, ask_vault_pass=None, create_new_password=None, auto_prompt=True): vault_password_files = vault_password_files or [] vault_ids = vault_ids or [] # convert vault_password_files into vault_ids slugs for password_file in vault_password_files: id_slug = u'%s@%s' % (C.DEFAULT_VAULT_IDENTITY, password_file) # note this makes --vault-id higher precedence than --vault-password-file # if we want to intertwingle them in order probably need a cli callback to populate vault_ids # used by --vault-id and --vault-password-file vault_ids.append(id_slug) # if an action needs an encrypt password (create_new_password=True) and we dont # have other secrets setup, then automatically add a password prompt as well. # prompts cant/shouldnt work without a tty, so dont add prompt secrets if ask_vault_pass or (not vault_ids and auto_prompt): id_slug = u'%s@%s' % (C.DEFAULT_VAULT_IDENTITY, u'prompt_ask_vault_pass') vault_ids.append(id_slug) return vault_ids # TODO: remove the now unused args @staticmethod def setup_vault_secrets(loader, vault_ids, vault_password_files=None, ask_vault_pass=None, create_new_password=False, auto_prompt=True): # list of tuples vault_secrets = [] # Depending on the vault_id value (including how --ask-vault-pass / --vault-password-file create a vault_id) # we need to show different prompts. This is for compat with older Towers that expect a # certain vault password prompt format, so 'promp_ask_vault_pass' vault_id gets the old format. prompt_formats = {} # If there are configured default vault identities, they are considered 'first' # so we prepend them to vault_ids (from cli) here vault_password_files = vault_password_files or [] if C.DEFAULT_VAULT_PASSWORD_FILE: vault_password_files.append(C.DEFAULT_VAULT_PASSWORD_FILE) if create_new_password: prompt_formats['prompt'] = ['New vault password (%(vault_id)s): ', 'Confirm new vault password (%(vault_id)s): '] # 2.3 format prompts for --ask-vault-pass prompt_formats['prompt_ask_vault_pass'] = ['New Vault password: ', 'Confirm New Vault password: '] else: prompt_formats['prompt'] = ['Vault password (%(vault_id)s): '] # The format when we use just --ask-vault-pass needs to match 'Vault password:\s*?$' prompt_formats['prompt_ask_vault_pass'] = ['Vault password: '] vault_ids = CLI.build_vault_ids(vault_ids, vault_password_files, ask_vault_pass, create_new_password, auto_prompt=auto_prompt) for vault_id_slug in vault_ids: vault_id_name, vault_id_value = CLI.split_vault_id(vault_id_slug) if vault_id_value in ['prompt', 'prompt_ask_vault_pass']: # --vault-id some_name@prompt_ask_vault_pass --vault-id other_name@prompt_ask_vault_pass will be a little # confusing since it will use the old format without the vault id in the prompt built_vault_id = vault_id_name or C.DEFAULT_VAULT_IDENTITY # choose the prompt based on --vault-id=prompt or --ask-vault-pass. --ask-vault-pass # always gets the old format for Tower compatibility. # ie, we used --ask-vault-pass, so we need to use the old vault password prompt # format since Tower needs to match on that format. prompted_vault_secret = PromptVaultSecret(prompt_formats=prompt_formats[vault_id_value], vault_id=built_vault_id) # a empty or invalid password from the prompt will warn and continue to the next # without erroring globally try: prompted_vault_secret.load() except AnsibleError as exc: display.warning('Error in vault password prompt (%s): %s' % (vault_id_name, exc)) raise vault_secrets.append((built_vault_id, prompted_vault_secret)) # update loader with new secrets incrementally, so we can load a vault password # that is encrypted with a vault secret provided earlier loader.set_vault_secrets(vault_secrets) continue # assuming anything else is a password file display.vvvvv('Reading vault password file: %s' % vault_id_value) # read vault_pass from a file file_vault_secret = get_file_vault_secret(filename=vault_id_value, vault_id=vault_id_name, loader=loader) # an invalid password file will error globally try: file_vault_secret.load() except AnsibleError as exc: display.warning('Error in vault password file loading (%s): %s' % (vault_id_name, to_text(exc))) raise if vault_id_name: vault_secrets.append((vault_id_name, file_vault_secret)) else: vault_secrets.append((C.DEFAULT_VAULT_IDENTITY, file_vault_secret)) # update loader with as-yet-known vault secrets loader.set_vault_secrets(vault_secrets) return vault_secrets @staticmethod def ask_passwords(): ''' prompt for connection and become passwords if needed ''' op = context.CLIARGS sshpass = None becomepass = None become_prompt = '' become_prompt_method = "BECOME" if C.AGNOSTIC_BECOME_PROMPT else op['become_method'].upper() try: if op['ask_pass']: sshpass = getpass.getpass(prompt="SSH password: ") become_prompt = "%s password[defaults to SSH password]: " % become_prompt_method else: become_prompt = "%s password: " % become_prompt_method if op['become_ask_pass']: becomepass = getpass.getpass(prompt=become_prompt) if op['ask_pass'] and becomepass == '': becomepass = sshpass except EOFError: pass # we 'wrap' the passwords to prevent templating as # they can contain special chars and trigger it incorrectly if sshpass: sshpass = to_unsafe_text(sshpass) if becomepass: becomepass = to_unsafe_text(becomepass) return (sshpass, becomepass) def validate_conflicts(self, op, runas_opts=False, fork_opts=False): ''' check for conflicting options ''' if fork_opts: if op.forks < 1: self.parser.error("The number of processes (--forks) must be >= 1") return op @abstractmethod def init_parser(self, usage="", desc=None, epilog=None): """ Create an options parser for most ansible scripts Subclasses need to implement this method. They will usually call the base class's init_parser to create a basic version and then add their own options on top of that. An implementation will look something like this:: def init_parser(self): super(MyCLI, self).init_parser(usage="My Ansible CLI", inventory_opts=True) ansible.arguments.option_helpers.add_runas_options(self.parser) self.parser.add_option('--my-option', dest='my_option', action='store') """ self.parser = opt_help.create_base_parser(os.path.basename(self.args[0]), usage=usage, desc=desc, epilog=epilog, ) @abstractmethod def post_process_args(self, options): """Process the command line args Subclasses need to implement this method. This method validates and transforms the command line arguments. It can be used to check whether conflicting values were given, whether filenames exist, etc. An implementation will look something like this:: def post_process_args(self, options): options = super(MyCLI, self).post_process_args(options) if options.addition and options.subtraction: raise AnsibleOptionsError('Only one of --addition and --subtraction can be specified') if isinstance(options.listofhosts, string_types): options.listofhosts = string_types.split(',') return options """ # process tags if hasattr(options, 'tags') and not options.tags: # optparse defaults does not do what's expected # More specifically, we want `--tags` to be additive. So we cannot # simply change C.TAGS_RUN's default to ["all"] because then passing # --tags foo would cause us to have ['all', 'foo'] options.tags = ['all'] if hasattr(options, 'tags') and options.tags: tags = set() for tag_set in options.tags: for tag in tag_set.split(u','): tags.add(tag.strip()) options.tags = list(tags) # process skip_tags if hasattr(options, 'skip_tags') and options.skip_tags: skip_tags = set() for tag_set in options.skip_tags: for tag in tag_set.split(u','): skip_tags.add(tag.strip()) options.skip_tags = list(skip_tags) # process inventory options except for CLIs that require their own processing if hasattr(options, 'inventory') and not self.SKIP_INVENTORY_DEFAULTS: if options.inventory: # should always be list if isinstance(options.inventory, string_types): options.inventory = [options.inventory] # Ensure full paths when needed options.inventory = [unfrackpath(opt, follow=False) if ',' not in opt else opt for opt in options.inventory] else: options.inventory = C.DEFAULT_HOST_LIST # Dup args set on the root parser and sub parsers results in the root parser ignoring the args. e.g. doing # 'ansible-galaxy -vvv init' has no verbosity set but 'ansible-galaxy init -vvv' sets a level of 3. To preserve # back compat with pre-argparse changes we manually scan and set verbosity based on the argv values. if self.parser.prog in ['ansible-galaxy', 'ansible-vault'] and not options.verbosity: verbosity_arg = next(iter([arg for arg in self.args if arg.startswith('-v')]), None) if verbosity_arg: display.deprecated("Setting verbosity before the arg sub command is deprecated, set the verbosity " "after the sub command", "2.13", collection_name='ansible.builtin') options.verbosity = verbosity_arg.count('v') return options def parse(self): """Parse the command line args This method parses the command line arguments. It uses the parser stored in the self.parser attribute and saves the args and options in context.CLIARGS. Subclasses need to implement two helper methods, init_parser() and post_process_args() which are called from this function before and after parsing the arguments. """ self.init_parser() if HAS_ARGCOMPLETE: argcomplete.autocomplete(self.parser) try: options = self.parser.parse_args(self.args[1:]) except SystemExit as e: if(e.code != 0): self.parser.exit(status=2, message=" \n%s " % self.parser.format_help()) raise options = self.post_process_args(options) context._init_global_context(options) @staticmethod def version_info(gitinfo=False): ''' return full ansible version info ''' if gitinfo: # expensive call, user with care ansible_version_string = opt_help.version() else: ansible_version_string = __version__ ansible_version = ansible_version_string.split()[0] ansible_versions = ansible_version.split('.') for counter in range(len(ansible_versions)): if ansible_versions[counter] == "": ansible_versions[counter] = 0 try: ansible_versions[counter] = int(ansible_versions[counter]) except Exception: pass if len(ansible_versions) < 3: for counter in range(len(ansible_versions), 3): ansible_versions.append(0) return {'string': ansible_version_string.strip(), 'full': ansible_version, 'major': ansible_versions[0], 'minor': ansible_versions[1], 'revision': ansible_versions[2]} @staticmethod def pager(text): ''' find reasonable way to display text ''' # this is a much simpler form of what is in pydoc.py if not sys.stdout.isatty(): display.display(text, screen_only=True) elif 'PAGER' in os.environ: if sys.platform == 'win32': display.display(text, screen_only=True) else: CLI.pager_pipe(text, os.environ['PAGER']) else: p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() if p.returncode == 0: CLI.pager_pipe(text, 'less') else: display.display(text, screen_only=True) @staticmethod def pager_pipe(text, cmd): ''' pipe text through a pager ''' if 'LESS' not in os.environ: os.environ['LESS'] = CLI.LESS_OPTS try: cmd = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=sys.stdout) cmd.communicate(input=to_bytes(text)) except IOError: pass except KeyboardInterrupt: pass @staticmethod def _play_prereqs(): options = context.CLIARGS # all needs loader loader = DataLoader() basedir = options.get('basedir', False) if basedir: loader.set_basedir(basedir) add_all_plugin_dirs(basedir) AnsibleCollectionConfig.playbook_paths = basedir default_collection = _get_collection_name_from_path(basedir) if default_collection: display.warning(u'running with default collection {0}'.format(default_collection)) AnsibleCollectionConfig.default_collection = default_collection vault_ids = list(options['vault_ids']) default_vault_ids = C.DEFAULT_VAULT_IDENTITY_LIST vault_ids = default_vault_ids + vault_ids vault_secrets = CLI.setup_vault_secrets(loader, vault_ids=vault_ids, vault_password_files=list(options['vault_password_files']), ask_vault_pass=options['ask_vault_pass'], auto_prompt=False) loader.set_vault_secrets(vault_secrets) # create the inventory, and filter it based on the subset specified (if any) inventory = InventoryManager(loader=loader, sources=options['inventory']) # create the variable manager, which will be shared throughout # the code, ensuring a consistent view of global variables variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False)) return loader, inventory, variable_manager @staticmethod def get_host_list(inventory, subset, pattern='all'): no_hosts = False if len(inventory.list_hosts()) == 0: # Empty inventory if C.LOCALHOST_WARNING and pattern not in C.LOCALHOST: display.warning("provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'") no_hosts = True inventory.subset(subset) hosts = inventory.list_hosts(pattern) if not hosts and no_hosts is False: raise AnsibleError("Specified hosts and/or --limit does not match any hosts") return hosts
s-hertel/ansible
lib/ansible/cli/__init__.py
Python
gpl-3.0
20,965
[ "Galaxy" ]
b6e22a97287005af6388fc18595afda250f467d9341b1b3bd72e54ac2d134fdd
#!/usr/bin/env python import sys from .lammps_main import LammpsSimulation from .structure_data import ase_from_CIF, from_CIF, write_CIF, write_PDB, write_RASPA_CIF, write_RASPA_sim_files, MDMC_config from .InputHandler import Options def main(): # command line parsing options = Options() sim = LammpsSimulation(options) cell, graph = from_CIF(options.cif_file) #cell, graph = ase_from_CIF(options.cif_file) sim.set_cell(cell) sim.set_graph(graph) sim.split_graph() sim.assign_force_fields() sim.compute_simulation_size() sim.merge_graphs() if options.output_cif: print("CIF file requested. Exiting...") write_CIF(graph, cell) sys.exit() if options.output_pdb: print("PDB file requested. Exiting...") write_PDB(graph, cell) sys.exit() sim.write_lammps_files() # Additional capability to write RASPA files if requested if options.output_raspa: print("Writing RASPA files to current WD") classifier = 1 write_RASPA_CIF(graph, cell, classifier) write_RASPA_sim_files(sim, classifier) this_config = MDMC_config(sim) sim.set_MDMC_config(this_config)
peteboyd/lammps_interface
lammps_interface/cli.py
Python
mit
1,209
[ "RASPA" ]
f7caa12194f10307615ab75c1c7c7bfcd681a6f35eb3e9286592cb6a555b4787
import numpy, vigra import os.path #******************************************************************************* # s i z e _ i n _ p i x e l s * #******************************************************************************* class size_in_pixels(): def __init__(self): pass def getName(self): return "size in pixels" def generateOutput(self, obj_points): #generate output for the html table only for one object #as it's done row by row return str(len(obj_points[0])) def cleanUp(self): pass #******************************************************************************* # c o o r d s * #******************************************************************************* class coords(): def __init__(self): pass def getName(self): return "(X, Y, Z)" def generateOutput(self, obj_points): #take the central scan x = min(obj_points[0]) + (max(obj_points[0])-min(obj_points[0]))/2 y = min(obj_points[1]) + (max(obj_points[1])-min(obj_points[1]))/2 z = min(obj_points[2]) + (max(obj_points[2])-min(obj_points[2]))/2 strtowrite = "(" + str(x)+" ,"+str(y)+" ,"+str(z)+")" return strtowrite def cleanUp(self): pass #******************************************************************************* # s l i c e _ v i e w * #******************************************************************************* class slice_view(): def __init__(self, objects, raw_data, outputdir): self.objects = objects self.raw_data = raw_data self.max_spread_x = 0 self.max_spread_y = 0 self.max_spread_z = 0 for iobj in self.objects.values(): spread_x = max(iobj[0])-min(iobj[0]) if self.max_spread_x < spread_x: self.max_spread_x = spread_x spread_y = max(iobj[1])-min(iobj[1]) if self.max_spread_y < spread_y: self.max_spread_y = spread_y spread_z = max(iobj[2])-min(iobj[2]) if self.max_spread_z < spread_z: self.max_spread_z = spread_z self.max_spread_x = self.max_spread_x/2+10 self.max_spread_y = self.max_spread_y/2+10 self.max_spread_z = self.max_spread_z/2+10 self.counter = 0 self.outputdir = outputdir def getName(self): return "XY projection" + "<th>" + "XZ projection" + "</th>" + "<th>" + "YZ projection" def generateOutput(self, obj_points): #take the central scan x = min(obj_points[0]) + (max(obj_points[0])-min(obj_points[0]))/2 y = min(obj_points[1]) + (max(obj_points[1])-min(obj_points[1]))/2 z = min(obj_points[2]) + (max(obj_points[2])-min(obj_points[2]))/2 minx = max(x-self.max_spread_x, 0) maxx = min(x+self.max_spread_x, self.raw_data.shape[1]) miny = max(y-self.max_spread_y, 0) maxy = min(y+self.max_spread_y, self.raw_data.shape[2]) minz = max(z-self.max_spread_z, 0) maxz = min(z+self.max_spread_z, self.raw_data.shape[3]) image = self.raw_data[0, minx:maxx, miny:maxy, z, 0] fnamexy = str(self.counter)+ "_xy"+".png" fnamexy = os.path.join(self.outputdir, fnamexy) #print fnamexy vigra.impex.writeImage(image, fnamexy) image = self.raw_data[0, minx:maxx, y, minz:maxz, 0] fnamexz = str(self.counter)+"_xz"+".png" fnamexz = os.path.join(self.outputdir, fnamexz) #print fnamexz vigra.impex.writeImage(image, fnamexz) image = self.raw_data[0, x, miny:maxy, minz:maxz, 0] fnameyz = str(self.counter)+"_yz"+".png" fnameyz = os.path.join(self.outputdir, fnameyz) #print fnameyz vigra.impex.writeImage(image, fnameyz) self.counter = self.counter+1 strtowrite = "<img src=\"" + fnamexy + "\"/>"+"</td>" strtowrite = strtowrite + "<td align=\"center\">"+"<img src=\"" + fnamexz + "\"/>"+"</td>" strtowrite = strtowrite +"<td align=\"center\">"+"<img src=\"" + fnameyz + "\"/>" return strtowrite def cleanUp(self): pass #******************************************************************************* # p c _ p r o j e c t i o n _ 3 d * #******************************************************************************* class pc_projection_3d(): def __init__(self, objects, objectsOverlay, objectInputOverlay, outputdir): self.objects = objects self.objectsOverlay = objectsOverlay self.objectsInputOverlay = objectInputOverlay self.outputdir = outputdir self.counter = 0 self.max_spread_x = 0 self.max_spread_y = 0 self.max_spread_z = 0 for iobj in self.objects.values(): spread_x = max(iobj[0])-min(iobj[0]) if self.max_spread_x < spread_x: self.max_spread_x = spread_x spread_y = max(iobj[1])-min(iobj[1]) if self.max_spread_y < spread_y: self.max_spread_y = spread_y spread_z = max(iobj[2])-min(iobj[2]) if self.max_spread_z < spread_z: self.max_spread_z = spread_z self.max_spread_x = self.max_spread_x/2+10 self.max_spread_y = self.max_spread_y/2+10 self.max_spread_z = self.max_spread_z/2 from enthought.mayavi import mlab # Returns the current scene. self.scene = mlab.figure(size = (2*self.max_spread_x, 2*self.max_spread_y), bgcolor = (1., 1., 1.)) self.engine = mlab.get_engine() def getName(self): return "3d projection" def generateOutput(self, obj_points): from enthought.mayavi.sources.api import ArraySource x = min(obj_points[0]) + (max(obj_points[0])-min(obj_points[0]))/2 y = min(obj_points[1]) + (max(obj_points[1])-min(obj_points[1]))/2 z = min(obj_points[2]) + (max(obj_points[2])-min(obj_points[2]))/2 minx = max(x-self.max_spread_x, 0) maxx = min(x+self.max_spread_x, self.objectsInputOverlay._data.shape[1]) miny = max(y-self.max_spread_y, 0) maxy = min(y+self.max_spread_y, self.objectsInputOverlay._data.shape[2]) minz = max(z-self.max_spread_z, 0) maxz = min(z+self.max_spread_z, self.objectsInputOverlay._data.shape[3]) image_comp = self.objectsInputOverlay._data[0, minx:maxx, miny:maxy, minz:maxz, 0] value = self.objectsInputOverlay._data[0, obj_points[0][0], obj_points[1][0], obj_points[2][0], 0] image = numpy.where(image_comp==value, 1, 0) #image = self.overlay._data[0, minx:maxx, miny:maxy, minz:maxz, 0] src = ArraySource(scalar_data=image) self.engine.add_source(src) #axes are needed to get all the images at the same scale from enthought.mayavi.modules.api import Axes axes = Axes() self.engine.add_module(axes) from enthought.mayavi.modules.api import IsoSurface iso = IsoSurface() self.engine.add_module(iso) iso.contour.contours = [1, 2] iso.actor.mapper.scalar_visibility = False iso.actor.property.specular_color = (0.58, 0.58, 0.58) iso.actor.property.diffuse_color = (0.58, 0.58, 0.58) iso.actor.property.ambient_color = (0.58, 0.58, 0.58) iso.actor.property.color = (0.58, 0.58, 0.58) fname = str(self.counter)+".png" fname = os.path.join(self.outputdir, fname) from enthought.mayavi import mlab azimuth, elevation, d, f = mlab.view() el_deg = numpy.rad2deg(elevation) az_deg = numpy.rad2deg(azimuth) mean = numpy.zeros((1, 3)) if len(obj_points[0])>100: #TODO: This part is not really ready yet, but somehow works matr = numpy.array(obj_points) matr = matr.transpose() mean = numpy.mean(matr, 0) meanmatr = numpy.zeros(matr.shape) meanmatr[:, 0]=mean[0] meanmatr[:, 1]=mean[1] meanmatr[:, 2]=mean[2] matr = matr - meanmatr u, s, vh = numpy.linalg.svd(matr, full_matrices=False) normal_index = numpy.argmin(s) normal_vector = vh[normal_index, :] elevation = numpy.arccos(normal_vector[2]) azimuth = numpy.arctan(normal_vector[0]/normal_vector[1]) el_deg = numpy.rad2deg(elevation) az_deg = numpy.rad2deg(azimuth) if normal_vector[1]<0 and normal_vector[0]<0: az_deg = az_deg + 180 elif normal_vector[1]<0 and normal_vector[0]>0: az_deg = az_deg + 360 elif normal_vector[1]>0 and normal_vector[0]<0: az_deg = az_deg + 180 else: pass #print fname #print image.shape #a, e, d, f = self.scene.scene.view() #print a, e, d, f #self.scene.scene.view(azimuth, elevation, d, f) #mlab.view(numpy.rad2deg(azimuth), numpy.rad2deg(elevation), 'auto', focalpoint=[mean[0], mean[1], mean[2]]) mlab.view(az_deg, el_deg) #self.scene.scene.camera.azimuth(azimuth) #self.scene.scene.camera.elevation(elevation) self.scene.scene.save(fname) self.counter = self.counter+1 src.remove() strtowrite = "<img src=\"" + fname + "\"/>" return strtowrite def cleanUp(self): from enthought.mayavi import mlab mlab.close()
ilastik/ilastik-0.5
ilastik/modules/object_picking/core/objectOperators.py
Python
bsd-2-clause
9,958
[ "Mayavi" ]
180238d6bb374fb1605ae5a00b59ab786fd1056a132a07a6530da81487ef0455
r""" :mod:`~matplotlib.mathtext` is a module for parsing a subset of the TeX math syntax and drawing them to a matplotlib backend. For a tutorial of its usage see :ref:`mathtext-tutorial`. This document is primarily concerned with implementation details. The module uses pyparsing_ to parse the TeX expression. .. _pyparsing: http://pyparsing.wikispaces.com/ The Bakoma distribution of the TeX Computer Modern fonts, and STIX fonts are supported. There is experimental support for using arbitrary fonts, but results may vary without proper tweaking and metrics for those fonts. If you find TeX expressions that don't parse or render properly, please email mdroe@stsci.edu, but please check KNOWN ISSUES below first. """ from __future__ import division import os from cStringIO import StringIO from math import ceil try: set except NameError: from sets import Set as set import unicodedata from warnings import warn from numpy import inf, isinf import numpy as np from matplotlib.pyparsing import Combine, Group, Optional, Forward, \ Literal, OneOrMore, ZeroOrMore, ParseException, Empty, \ ParseResults, Suppress, oneOf, StringEnd, ParseFatalException, \ FollowedBy, Regex, ParserElement # Enable packrat parsing ParserElement.enablePackrat() from matplotlib.afm import AFM from matplotlib.cbook import Bunch, get_realpath_and_stat, \ is_string_like, maxdict from matplotlib.ft2font import FT2Font, FT2Image, KERNING_DEFAULT, LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING from matplotlib.font_manager import findfont, FontProperties from matplotlib._mathtext_data import latex_to_bakoma, \ latex_to_standard, tex2uni, latex_to_cmex, stix_virtual_fonts from matplotlib import get_data_path, rcParams import matplotlib.colors as mcolors import matplotlib._png as _png #################### ############################################################################## # FONTS def get_unicode_index(symbol): """get_unicode_index(symbol) -> integer Return the integer index (from the Unicode table) of symbol. *symbol* can be a single unicode character, a TeX command (i.e. r'\pi'), or a Type1 symbol name (i.e. 'phi'). """ # From UTF #25: U+2212 minus sign is the preferred # representation of the unary and binary minus sign rather than # the ASCII-derived U+002D hyphen-minus, because minus sign is # unambiguous and because it is rendered with a more desirable # length, usually longer than a hyphen. if symbol == '-': return 0x2212 try:# This will succeed if symbol is a single unicode char return ord(symbol) except TypeError: pass try:# Is symbol a TeX symbol (i.e. \alpha) return tex2uni[symbol.strip("\\")] except KeyError: message = """'%(symbol)s' is not a valid Unicode character or TeX/Type1 symbol"""%locals() raise ValueError, message def unichr_safe(index): """Return the Unicode character corresponding to the index, or the replacement character if this is a narrow build of Python and the requested character is outside the BMP.""" try: return unichr(index) except ValueError: return unichr(0xFFFD) class MathtextBackend(object): """ The base class for the mathtext backend-specific code. The purpose of :class:`MathtextBackend` subclasses is to interface between mathtext and a specific matplotlib graphics backend. Subclasses need to override the following: - :meth:`render_glyph` - :meth:`render_filled_rect` - :meth:`get_results` And optionally, if you need to use a Freetype hinting style: - :meth:`get_hinting_type` """ def __init__(self): self.fonts_object = None def set_canvas_size(self, w, h, d): 'Dimension the drawing canvas' self.width = w self.height = h self.depth = d def render_glyph(self, ox, oy, info): """ Draw a glyph described by *info* to the reference point (*ox*, *oy*). """ raise NotImplementedError() def render_filled_rect(self, x1, y1, x2, y2): """ Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*). """ raise NotImplementedError() def get_results(self, box): """ Return a backend-specific tuple to return to the backend after all processing is done. """ raise NotImplementedError() def get_hinting_type(self): """ Get the Freetype hinting type to use with this particular backend. """ return LOAD_NO_HINTING class MathtextBackendBbox(MathtextBackend): """ A backend whose only purpose is to get a precise bounding box. Only required for the Agg backend. """ def __init__(self, real_backend): MathtextBackend.__init__(self) self.bbox = [0, 0, 0, 0] self.real_backend = real_backend def _update_bbox(self, x1, y1, x2, y2): self.bbox = [min(self.bbox[0], x1), min(self.bbox[1], y1), max(self.bbox[2], x2), max(self.bbox[3], y2)] def render_glyph(self, ox, oy, info): self._update_bbox(ox + info.metrics.xmin, oy - info.metrics.ymax, ox + info.metrics.xmax, oy - info.metrics.ymin) def render_rect_filled(self, x1, y1, x2, y2): self._update_bbox(x1, y1, x2, y2) def get_results(self, box): orig_height = box.height orig_depth = box.depth ship(0, 0, box) bbox = self.bbox bbox = [bbox[0] - 1, bbox[1] - 1, bbox[2] + 1, bbox[3] + 1] self._switch_to_real_backend() self.fonts_object.set_canvas_size( bbox[2] - bbox[0], (bbox[3] - bbox[1]) - orig_depth, (bbox[3] - bbox[1]) - orig_height) ship(-bbox[0], -bbox[1], box) return self.fonts_object.get_results(box) def get_hinting_type(self): return self.real_backend.get_hinting_type() def _switch_to_real_backend(self): self.fonts_object.mathtext_backend = self.real_backend self.real_backend.fonts_object = self.fonts_object self.real_backend.ox = self.bbox[0] self.real_backend.oy = self.bbox[1] class MathtextBackendAggRender(MathtextBackend): """ Render glyphs and rectangles to an FTImage buffer, which is later transferred to the Agg image by the Agg backend. """ def __init__(self): self.ox = 0 self.oy = 0 self.image = None MathtextBackend.__init__(self) def set_canvas_size(self, w, h, d): MathtextBackend.set_canvas_size(self, w, h, d) self.image = FT2Image(ceil(w), ceil(h + d)) def render_glyph(self, ox, oy, info): info.font.draw_glyph_to_bitmap( self.image, ox, oy - info.metrics.iceberg, info.glyph) def render_rect_filled(self, x1, y1, x2, y2): height = max(int(y2 - y1) - 1, 0) if height == 0: center = (y2 + y1) / 2.0 y = int(center - (height + 1) / 2.0) else: y = int(y1) self.image.draw_rect_filled(int(x1), y, ceil(x2), y + height) def get_results(self, box): return (self.ox, self.oy, self.width, self.height + self.depth, self.depth, self.image, self.fonts_object.get_used_characters()) def get_hinting_type(self): if rcParams['text.hinting']: return LOAD_FORCE_AUTOHINT else: return LOAD_NO_HINTING def MathtextBackendAgg(): return MathtextBackendBbox(MathtextBackendAggRender()) class MathtextBackendBitmapRender(MathtextBackendAggRender): def get_results(self, box): return self.image, self.depth def MathtextBackendBitmap(): """ A backend to generate standalone mathtext images. No additional matplotlib backend is required. """ return MathtextBackendBbox(MathtextBackendBitmapRender()) class MathtextBackendPs(MathtextBackend): """ Store information to write a mathtext rendering to the PostScript backend. """ def __init__(self): self.pswriter = StringIO() self.lastfont = None def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset postscript_name = info.postscript_name fontsize = info.fontsize symbol_name = info.symbol_name if (postscript_name, fontsize) != self.lastfont: ps = """/%(postscript_name)s findfont %(fontsize)s scalefont setfont """ % locals() self.lastfont = postscript_name, fontsize self.pswriter.write(ps) ps = """%(ox)f %(oy)f moveto /%(symbol_name)s glyphshow\n """ % locals() self.pswriter.write(ps) def render_rect_filled(self, x1, y1, x2, y2): ps = "%f %f %f %f rectfill\n" % (x1, self.height - y2, x2 - x1, y2 - y1) self.pswriter.write(ps) def get_results(self, box): ship(0, -self.depth, box) #print self.depth return (self.width, self.height + self.depth, self.depth, self.pswriter, self.fonts_object.get_used_characters()) class MathtextBackendPdf(MathtextBackend): """ Store information to write a mathtext rendering to the PDF backend. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): filename = info.font.fname oy = self.height - oy + info.offset self.glyphs.append( (ox, oy, filename, info.fontsize, info.num, info.symbol_name)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append((x1, self.height - y2, x2 - x1, y2 - y1)) def get_results(self, box): ship(0, -self.depth, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects, self.fonts_object.get_used_characters()) class MathtextBackendSvg(MathtextBackend): """ Store information to write a mathtext rendering to the SVG backend. """ def __init__(self): self.svg_glyphs = [] self.svg_rects = [] def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset self.svg_glyphs.append( (info.font, info.fontsize, info.num, ox, oy, info.metrics)) def render_rect_filled(self, x1, y1, x2, y2): self.svg_rects.append( (x1, self.height - y1 + 1, x2 - x1, y2 - y1)) def get_results(self, box): ship(0, -self.depth, box) svg_elements = Bunch(svg_glyphs = self.svg_glyphs, svg_rects = self.svg_rects) return (self.width, self.height + self.depth, self.depth, svg_elements, self.fonts_object.get_used_characters()) class MathtextBackendPath(MathtextBackend): """ Store information to write a mathtext rendering to the text path machinery. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset thetext = info.num self.glyphs.append( (info.font, info.fontsize, thetext, ox, oy)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append( (x1, self.height-y2 , x2 - x1, y2 - y1)) def get_results(self, box): ship(0, -self.depth, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects) class MathtextBackendCairo(MathtextBackend): """ Store information to write a mathtext rendering to the Cairo backend. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): oy = oy - info.offset - self.height thetext = unichr_safe(info.num) self.glyphs.append( (info.font, info.fontsize, thetext, ox, oy)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append( (x1, y1 - self.height, x2 - x1, y2 - y1)) def get_results(self, box): ship(0, -self.depth, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects) class Fonts(object): """ An abstract base class for a system of fonts to use for mathtext. The class must be able to take symbol keys and font file names and return the character metrics. It also delegates to a backend class to do the actual drawing. """ def __init__(self, default_font_prop, mathtext_backend): """ *default_font_prop*: A :class:`~matplotlib.font_manager.FontProperties` object to use for the default non-math font, or the base font for Unicode (generic) font rendering. *mathtext_backend*: A subclass of :class:`MathTextBackend` used to delegate the actual rendering. """ self.default_font_prop = default_font_prop self.mathtext_backend = mathtext_backend # Make these classes doubly-linked self.mathtext_backend.fonts_object = self self.used_characters = {} def destroy(self): """ Fix any cyclical references before the object is about to be destroyed. """ self.used_characters = None def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): """ Get the kerning distance for font between *sym1* and *sym2*. *fontX*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default/regular (non-math) *fontclassX*: TODO *symX*: a symbol in raw TeX form. e.g. '1', 'x' or '\sigma' *fontsizeX*: the fontsize in points *dpi*: the current dots-per-inch """ return 0. def get_metrics(self, font, font_class, sym, fontsize, dpi): """ *font*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default/regular (non-math) *font_class*: TODO *sym*: a symbol in raw TeX form. e.g. '1', 'x' or '\sigma' *fontsize*: font size in points *dpi*: current dots-per-inch Returns an object with the following attributes: - *advance*: The advance distance (in points) of the glyph. - *height*: The height of the glyph in points. - *width*: The width of the glyph in points. - *xmin*, *xmax*, *ymin*, *ymax* - the ink rectangle of the glyph - *iceberg* - the distance from the baseline to the top of the glyph. This corresponds to TeX's definition of "height". """ info = self._get_info(font, font_class, sym, fontsize, dpi) return info.metrics def set_canvas_size(self, w, h, d): """ Set the size of the buffer used to render the math expression. Only really necessary for the bitmap backends. """ self.width, self.height, self.depth = ceil(w), ceil(h), ceil(d) self.mathtext_backend.set_canvas_size(self.width, self.height, self.depth) def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi): """ Draw a glyph at - *ox*, *oy*: position - *facename*: One of the TeX face names - *font_class*: - *sym*: TeX symbol name or single character - *fontsize*: fontsize in points - *dpi*: The dpi to draw at. """ info = self._get_info(facename, font_class, sym, fontsize, dpi) realpath, stat_key = get_realpath_and_stat(info.font.fname) used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].add(info.num) self.mathtext_backend.render_glyph(ox, oy, info) def render_rect_filled(self, x1, y1, x2, y2): """ Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*). """ self.mathtext_backend.render_rect_filled(x1, y1, x2, y2) def get_xheight(self, font, fontsize, dpi): """ Get the xheight for the given *font* and *fontsize*. """ raise NotImplementedError() def get_underline_thickness(self, font, fontsize, dpi): """ Get the line thickness that matches the given font. Used as a base unit for drawing lines such as in a fraction or radical. """ raise NotImplementedError() def get_used_characters(self): """ Get the set of characters that were used in the math expression. Used by backends that need to subset fonts so they know which glyphs to include. """ return self.used_characters def get_results(self, box): """ Get the data needed by the backend to render the math expression. The return value is backend-specific. """ return self.mathtext_backend.get_results(box) def get_sized_alternatives_for_symbol(self, fontname, sym): """ Override if your font provides multiple sizes of the same symbol. Should return a list of symbols matching *sym* in various sizes. The expression renderer will select the most appropriate size for a given situation from this list. """ return [(fontname, sym)] class TruetypeFonts(Fonts): """ A generic base class for all font setups that use Truetype fonts (through FT2Font). """ class CachedFont: def __init__(self, font): self.font = font self.charmap = font.get_charmap() self.glyphmap = dict( [(glyphind, ccode) for ccode, glyphind in self.charmap.iteritems()]) def __repr__(self): return repr(self.font) def __init__(self, default_font_prop, mathtext_backend): Fonts.__init__(self, default_font_prop, mathtext_backend) self.glyphd = {} self._fonts = {} filename = findfont(default_font_prop) default_font = self.CachedFont(FT2Font(str(filename))) self._fonts['default'] = default_font self._fonts['regular'] = default_font def destroy(self): self.glyphd = None Fonts.destroy(self) def _get_font(self, font): if font in self.fontmap: basename = self.fontmap[font] else: basename = font cached_font = self._fonts.get(basename) if cached_font is None: font = FT2Font(str(basename)) cached_font = self.CachedFont(font) self._fonts[basename] = cached_font self._fonts[font.postscript_name] = cached_font self._fonts[font.postscript_name.lower()] = cached_font return cached_font def _get_offset(self, cached_font, glyph, fontsize, dpi): if cached_font.font.postscript_name == 'Cmex10': return ((glyph.height/64.0/2.0) + (fontsize/3.0 * dpi/72.0)) return 0. def _get_info(self, fontname, font_class, sym, fontsize, dpi): key = fontname, font_class, sym, fontsize, dpi bunch = self.glyphd.get(key) if bunch is not None: return bunch cached_font, num, symbol_name, fontsize, slanted = \ self._get_glyph(fontname, font_class, sym, fontsize) font = cached_font.font font.set_size(fontsize, dpi) glyph = font.load_char( num, flags=self.mathtext_backend.get_hinting_type()) xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] offset = self._get_offset(cached_font, glyph, fontsize, dpi) metrics = Bunch( advance = glyph.linearHoriAdvance/65536.0, height = glyph.height/64.0, width = glyph.width/64.0, xmin = xmin, xmax = xmax, ymin = ymin+offset, ymax = ymax+offset, # iceberg is the equivalent of TeX's "height" iceberg = glyph.horiBearingY/64.0 + offset, slanted = slanted ) result = self.glyphd[key] = Bunch( font = font, fontsize = fontsize, postscript_name = font.postscript_name, metrics = metrics, symbol_name = symbol_name, num = num, glyph = glyph, offset = offset ) return result def get_xheight(self, font, fontsize, dpi): cached_font = self._get_font(font) cached_font.font.set_size(fontsize, dpi) pclt = cached_font.font.get_sfnt_table('pclt') if pclt is None: # Some fonts don't store the xHeight, so we do a poor man's xHeight metrics = self.get_metrics(font, rcParams['mathtext.default'], 'x', fontsize, dpi) return metrics.iceberg xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0) return xHeight def get_underline_thickness(self, font, fontsize, dpi): # This function used to grab underline thickness from the font # metrics, but that information is just too un-reliable, so it # is now hardcoded. return ((0.75 / 12.0) * fontsize * dpi) / 72.0 def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): if font1 == font2 and fontsize1 == fontsize2: info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) font = info1.font return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64.0 return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi) class BakomaFonts(TruetypeFonts): """ Use the Bakoma TrueType fonts for rendering. Symbols are strewn about a number of font files, each of which has its own proprietary 8-bit encoding. """ _fontmap = { 'cal' : 'cmsy10', 'rm' : 'cmr10', 'tt' : 'cmtt10', 'it' : 'cmmi10', 'bf' : 'cmb10', 'sf' : 'cmss10', 'ex' : 'cmex10' } def __init__(self, *args, **kwargs): self._stix_fallback = StixFonts(*args, **kwargs) TruetypeFonts.__init__(self, *args, **kwargs) self.fontmap = {} for key, val in self._fontmap.iteritems(): fullpath = findfont(val) self.fontmap[key] = fullpath self.fontmap[val] = fullpath _slanted_symbols = set(r"\int \oint".split()) def _get_glyph(self, fontname, font_class, sym, fontsize): symbol_name = None if fontname in self.fontmap and sym in latex_to_bakoma: basename, num = latex_to_bakoma[sym] slanted = (basename == "cmmi10") or sym in self._slanted_symbols try: cached_font = self._get_font(basename) except RuntimeError: pass else: symbol_name = cached_font.font.get_glyph_name(num) num = cached_font.glyphmap[num] elif len(sym) == 1: slanted = (fontname == "it") try: cached_font = self._get_font(fontname) except RuntimeError: pass else: num = ord(sym) gid = cached_font.charmap.get(num) if gid is not None: symbol_name = cached_font.font.get_glyph_name( cached_font.charmap[num]) if symbol_name is None: return self._stix_fallback._get_glyph( fontname, font_class, sym, fontsize) return cached_font, num, symbol_name, fontsize, slanted # The Bakoma fonts contain many pre-sized alternatives for the # delimiters. The AutoSizedChar class will use these alternatives # and select the best (closest sized) glyph. _size_alternatives = { '(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'), ('ex', '\xb5'), ('ex', '\xc3')], ')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'), ('ex', '\xb6'), ('ex', '\x21')], '{' : [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'), ('ex', '\xbd'), ('ex', '\x28')], '}' : [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), ('ex', '\xbe'), ('ex', '\x29')], # The fourth size of '[' is mysteriously missing from the BaKoMa # font, so I've ommitted it for both '[' and ']' '[' : [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), ('ex', '\x22')], ']' : [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), ('ex', '\x23')], r'\lfloor' : [('ex', '\xa5'), ('ex', '\x6a'), ('ex', '\xb9'), ('ex', '\x24')], r'\rfloor' : [('ex', '\xa6'), ('ex', '\x6b'), ('ex', '\xba'), ('ex', '\x25')], r'\lceil' : [('ex', '\xa7'), ('ex', '\x6c'), ('ex', '\xbb'), ('ex', '\x26')], r'\rceil' : [('ex', '\xa8'), ('ex', '\x6d'), ('ex', '\xbc'), ('ex', '\x27')], r'\langle' : [('ex', '\xad'), ('ex', '\x44'), ('ex', '\xbf'), ('ex', '\x2a')], r'\rangle' : [('ex', '\xae'), ('ex', '\x45'), ('ex', '\xc0'), ('ex', '\x2b')], r'\__sqrt__' : [('ex', '\x70'), ('ex', '\x71'), ('ex', '\x72'), ('ex', '\x73')], r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'), ('ex', '\xc2'), ('ex', '\x2d')], r'/' : [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'), ('ex', '\xcb'), ('ex', '\x2c')], r'\widehat' : [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'), ('ex', '\x64')], r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'), ('ex', '\x67')], r'<' : [('cal', 'h'), ('ex', 'D')], r'>' : [('cal', 'i'), ('ex', 'E')] } for alias, target in [('\leftparen', '('), ('\rightparent', ')'), ('\leftbrace', '{'), ('\rightbrace', '}'), ('\leftbracket', '['), ('\rightbracket', ']')]: _size_alternatives[alias] = _size_alternatives[target] def get_sized_alternatives_for_symbol(self, fontname, sym): return self._size_alternatives.get(sym, [(fontname, sym)]) class UnicodeFonts(TruetypeFonts): """ An abstract base class for handling Unicode fonts. While some reasonably complete Unicode fonts (such as DejaVu) may work in some situations, the only Unicode font I'm aware of with a complete set of math symbols is STIX. This class will "fallback" on the Bakoma fonts when a required symbol can not be found in the font. """ use_cmex = True def __init__(self, *args, **kwargs): # This must come first so the backend's owner is set correctly if rcParams['mathtext.fallback_to_cm']: self.cm_fallback = BakomaFonts(*args, **kwargs) else: self.cm_fallback = None TruetypeFonts.__init__(self, *args, **kwargs) self.fontmap = {} for texfont in "cal rm tt it bf sf".split(): prop = rcParams['mathtext.' + texfont] font = findfont(prop) self.fontmap[texfont] = font prop = FontProperties('cmex10') font = findfont(prop) self.fontmap['ex'] = font _slanted_symbols = set(r"\int \oint".split()) def _map_virtual_font(self, fontname, font_class, uniindex): return fontname, uniindex def _get_glyph(self, fontname, font_class, sym, fontsize): found_symbol = False if self.use_cmex: uniindex = latex_to_cmex.get(sym) if uniindex is not None: fontname = 'ex' found_symbol = True if not found_symbol: try: uniindex = get_unicode_index(sym) found_symbol = True except ValueError: uniindex = ord('?') warn("No TeX to unicode mapping for '%s'" % sym.encode('ascii', 'backslashreplace'), MathTextWarning) fontname, uniindex = self._map_virtual_font( fontname, font_class, uniindex) new_fontname = fontname # Only characters in the "Letter" class should be italicized in 'it' # mode. Greek capital letters should be Roman. if found_symbol: if fontname == 'it': if uniindex < 0x10000: unistring = unichr(uniindex) if (not unicodedata.category(unistring)[0] == "L" or unicodedata.name(unistring).startswith("GREEK CAPITAL")): new_fontname = 'rm' slanted = (new_fontname == 'it') or sym in self._slanted_symbols found_symbol = False try: cached_font = self._get_font(new_fontname) except RuntimeError: pass else: try: glyphindex = cached_font.charmap[uniindex] found_symbol = True except KeyError: pass if not found_symbol: if self.cm_fallback: warn("Substituting with a symbol from Computer Modern.", MathTextWarning) return self.cm_fallback._get_glyph( fontname, 'it', sym, fontsize) else: if fontname in ('it', 'regular') and isinstance(self, StixFonts): return self._get_glyph('rm', font_class, sym, fontsize) warn("Font '%s' does not have a glyph for '%s' [U%x]" % (new_fontname, sym.encode('ascii', 'backslashreplace'), uniindex), MathTextWarning) warn("Substituting with a dummy symbol.", MathTextWarning) fontname = 'rm' new_fontname = fontname cached_font = self._get_font(fontname) uniindex = 0xA4 # currency character, for lack of anything better glyphindex = cached_font.charmap[uniindex] slanted = False symbol_name = cached_font.font.get_glyph_name(glyphindex) return cached_font, uniindex, symbol_name, fontsize, slanted def get_sized_alternatives_for_symbol(self, fontname, sym): if self.cm_fallback: return self.cm_fallback.get_sized_alternatives_for_symbol( fontname, sym) return [(fontname, sym)] class StixFonts(UnicodeFonts): """ A font handling class for the STIX fonts. In addition to what UnicodeFonts provides, this class: - supports "virtual fonts" which are complete alpha numeric character sets with different font styles at special Unicode code points, such as "Blackboard". - handles sized alternative characters for the STIXSizeX fonts. """ _fontmap = { 'rm' : 'STIXGeneral', 'it' : 'STIXGeneral:italic', 'bf' : 'STIXGeneral:weight=bold', 'nonunirm' : 'STIXNonUnicode', 'nonuniit' : 'STIXNonUnicode:italic', 'nonunibf' : 'STIXNonUnicode:weight=bold', 0 : 'STIXGeneral', 1 : 'STIXSizeOneSym', 2 : 'STIXSizeTwoSym', 3 : 'STIXSizeThreeSym', 4 : 'STIXSizeFourSym', 5 : 'STIXSizeFiveSym' } use_cmex = False cm_fallback = False _sans = False def __init__(self, *args, **kwargs): TruetypeFonts.__init__(self, *args, **kwargs) self.fontmap = {} for key, name in self._fontmap.iteritems(): fullpath = findfont(name) self.fontmap[key] = fullpath self.fontmap[name] = fullpath def _map_virtual_font(self, fontname, font_class, uniindex): # Handle these "fonts" that are actually embedded in # other fonts. mapping = stix_virtual_fonts.get(fontname) if (self._sans and mapping is None and fontname not in ('regular', 'default')): mapping = stix_virtual_fonts['sf'] doing_sans_conversion = True else: doing_sans_conversion = False if mapping is not None: if isinstance(mapping, dict): mapping = mapping.get(font_class, 'rm') # Binary search for the source glyph lo = 0 hi = len(mapping) while lo < hi: mid = (lo+hi)//2 range = mapping[mid] if uniindex < range[0]: hi = mid elif uniindex <= range[1]: break else: lo = mid + 1 if uniindex >= range[0] and uniindex <= range[1]: uniindex = uniindex - range[0] + range[3] fontname = range[2] elif not doing_sans_conversion: # This will generate a dummy character uniindex = 0x1 fontname = rcParams['mathtext.default'] # Handle private use area glyphs if (fontname in ('it', 'rm', 'bf') and uniindex >= 0xe000 and uniindex <= 0xf8ff): fontname = 'nonuni' + fontname return fontname, uniindex _size_alternatives = {} def get_sized_alternatives_for_symbol(self, fontname, sym): alternatives = self._size_alternatives.get(sym) if alternatives: return alternatives alternatives = [] try: uniindex = get_unicode_index(sym) except ValueError: return [(fontname, sym)] fix_ups = { ord('<'): 0x27e8, ord('>'): 0x27e9 } uniindex = fix_ups.get(uniindex, uniindex) for i in range(6): cached_font = self._get_font(i) glyphindex = cached_font.charmap.get(uniindex) if glyphindex is not None: alternatives.append((i, unichr_safe(uniindex))) # The largest size of the radical symbol in STIX has incorrect # metrics that cause it to be disconnected from the stem. if sym == r'\__sqrt__': alternatives = alternatives[:-1] self._size_alternatives[sym] = alternatives return alternatives class StixSansFonts(StixFonts): """ A font handling class for the STIX fonts (that uses sans-serif characters by default). """ _sans = True class StandardPsFonts(Fonts): """ Use the standard postscript fonts for rendering to backend_ps Unlike the other font classes, BakomaFont and UnicodeFont, this one requires the Ps backend. """ basepath = os.path.join( get_data_path(), 'fonts', 'afm' ) fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery 'rm' : 'pncr8a', # New Century Schoolbook 'tt' : 'pcrr8a', # Courier 'it' : 'pncri8a', # New Century Schoolbook Italic 'sf' : 'phvr8a', # Helvetica 'bf' : 'pncb8a', # New Century Schoolbook Bold None : 'psyr' # Symbol } def __init__(self, default_font_prop): Fonts.__init__(self, default_font_prop, MathtextBackendPs()) self.glyphd = {} self.fonts = {} filename = findfont(default_font_prop, fontext='afm', directory=self.basepath) if filename is None: filename = findfont('Helvetica', fontext='afm', directory=self.basepath) default_font = AFM(file(filename, 'r')) default_font.fname = filename self.fonts['default'] = default_font self.fonts['regular'] = default_font self.pswriter = StringIO() def _get_font(self, font): if font in self.fontmap: basename = self.fontmap[font] else: basename = font cached_font = self.fonts.get(basename) if cached_font is None: fname = os.path.join(self.basepath, basename + ".afm") cached_font = AFM(file(fname, 'r')) cached_font.fname = fname self.fonts[basename] = cached_font self.fonts[cached_font.get_fontname()] = cached_font return cached_font def _get_info (self, fontname, font_class, sym, fontsize, dpi): 'load the cmfont, metrics and glyph with caching' key = fontname, sym, fontsize, dpi tup = self.glyphd.get(key) if tup is not None: return tup # Only characters in the "Letter" class should really be italicized. # This class includes greek letters, so we're ok if (fontname == 'it' and (len(sym) > 1 or not unicodedata.category(unicode(sym)).startswith("L"))): fontname = 'rm' found_symbol = False if sym in latex_to_standard: fontname, num = latex_to_standard[sym] glyph = chr(num) found_symbol = True elif len(sym) == 1: glyph = sym num = ord(glyph) found_symbol = True else: warn("No TeX to built-in Postscript mapping for '%s'" % sym, MathTextWarning) slanted = (fontname == 'it') font = self._get_font(fontname) if found_symbol: try: symbol_name = font.get_name_char(glyph) except KeyError: warn("No glyph in standard Postscript font '%s' for '%s'" % (font.postscript_name, sym), MathTextWarning) found_symbol = False if not found_symbol: glyph = sym = '?' num = ord(glyph) symbol_name = font.get_name_char(glyph) offset = 0 scale = 0.001 * fontsize xmin, ymin, xmax, ymax = [val * scale for val in font.get_bbox_char(glyph)] metrics = Bunch( advance = font.get_width_char(glyph) * scale, width = font.get_width_char(glyph) * scale, height = font.get_height_char(glyph) * scale, xmin = xmin, xmax = xmax, ymin = ymin+offset, ymax = ymax+offset, # iceberg is the equivalent of TeX's "height" iceberg = ymax + offset, slanted = slanted ) self.glyphd[key] = Bunch( font = font, fontsize = fontsize, postscript_name = font.get_fontname(), metrics = metrics, symbol_name = symbol_name, num = num, glyph = glyph, offset = offset ) return self.glyphd[key] def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): if font1 == font2 and fontsize1 == fontsize2: info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) font = info1.font return (font.get_kern_dist(info1.glyph, info2.glyph) * 0.001 * fontsize1) return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi) def get_xheight(self, font, fontsize, dpi): cached_font = self._get_font(font) return cached_font.get_xheight() * 0.001 * fontsize def get_underline_thickness(self, font, fontsize, dpi): cached_font = self._get_font(font) return cached_font.get_underline_thickness() * 0.001 * fontsize ############################################################################## # TeX-LIKE BOX MODEL # The following is based directly on the document 'woven' from the # TeX82 source code. This information is also available in printed # form: # # Knuth, Donald E.. 1986. Computers and Typesetting, Volume B: # TeX: The Program. Addison-Wesley Professional. # # The most relevant "chapters" are: # Data structures for boxes and their friends # Shipping pages out (Ship class) # Packaging (hpack and vpack) # Data structures for math mode # Subroutines for math mode # Typesetting math formulas # # Many of the docstrings below refer to a numbered "node" in that # book, e.g. node123 # # Note that (as TeX) y increases downward, unlike many other parts of # matplotlib. # How much text shrinks when going to the next-smallest level. GROW_FACTOR # must be the inverse of SHRINK_FACTOR. SHRINK_FACTOR = 0.7 GROW_FACTOR = 1.0 / SHRINK_FACTOR # The number of different sizes of chars to use, beyond which they will not # get any smaller NUM_SIZE_LEVELS = 6 # Percentage of x-height of additional horiz. space after sub/superscripts SCRIPT_SPACE = 0.2 # Percentage of x-height that sub/superscripts drop below the baseline SUBDROP = 0.3 # Percentage of x-height that superscripts drop below the baseline SUP1 = 0.5 # Percentage of x-height that subscripts drop below the baseline SUB1 = 0.0 # Percentage of x-height that superscripts are offset relative to the subscript DELTA = 0.18 class MathTextWarning(Warning): pass class Node(object): """ A node in the TeX box model """ def __init__(self): self.size = 0 def __repr__(self): return self.__internal_repr__() def __internal_repr__(self): return self.__class__.__name__ def get_kerning(self, next): return 0.0 def shrink(self): """ Shrinks one level smaller. There are only three levels of sizes, after which things will no longer get smaller. """ self.size += 1 def grow(self): """ Grows one level larger. There is no limit to how big something can get. """ self.size -= 1 def render(self, x, y): pass class Box(Node): """ Represents any node with a physical location. """ def __init__(self, width, height, depth): Node.__init__(self) self.width = width self.height = height self.depth = depth def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR def grow(self): Node.grow(self) self.width *= GROW_FACTOR self.height *= GROW_FACTOR self.depth *= GROW_FACTOR def render(self, x1, y1, x2, y2): pass class Vbox(Box): """ A box with only height (zero width). """ def __init__(self, height, depth): Box.__init__(self, 0., height, depth) class Hbox(Box): """ A box with only width (zero height and depth). """ def __init__(self, width): Box.__init__(self, width, 0., 0.) class Char(Node): """ Represents a single character. Unlike TeX, the font information and metrics are stored with each :class:`Char` to make it easier to lookup the font metrics when needed. Note that TeX boxes have a width, height, and depth, unlike Type1 and Truetype which use a full bounding box and an advance in the x-direction. The metrics must be converted to the TeX way, and the advance (if different from width) must be converted into a :class:`Kern` node when the :class:`Char` is added to its parent :class:`Hlist`. """ def __init__(self, c, state): Node.__init__(self) self.c = c self.font_output = state.font_output assert isinstance(state.font, (str, unicode, int)) self.font = state.font self.font_class = state.font_class self.fontsize = state.fontsize self.dpi = state.dpi # The real width, height and depth will be set during the # pack phase, after we know the real fontsize self._update_metrics() def __internal_repr__(self): return '`%s`' % self.c def _update_metrics(self): metrics = self._metrics = self.font_output.get_metrics( self.font, self.font_class, self.c, self.fontsize, self.dpi) if self.c == ' ': self.width = metrics.advance else: self.width = metrics.width self.height = metrics.iceberg self.depth = -(metrics.iceberg - metrics.height) def is_slanted(self): return self._metrics.slanted def get_kerning(self, next): """ Return the amount of kerning between this and the given character. Called when characters are strung together into :class:`Hlist` to create :class:`Kern` nodes. """ advance = self._metrics.advance - self.width kern = 0. if isinstance(next, Char): kern = self.font_output.get_kern( self.font, self.font_class, self.c, self.fontsize, next.font, next.font_class, next.c, next.fontsize, self.dpi) return advance + kern def render(self, x, y): """ Render the character to the canvas """ self.font_output.render_glyph( x, y, self.font, self.font_class, self.c, self.fontsize, self.dpi) def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.fontsize *= SHRINK_FACTOR self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR def grow(self): Node.grow(self) self.fontsize *= GROW_FACTOR self.width *= GROW_FACTOR self.height *= GROW_FACTOR self.depth *= GROW_FACTOR class Accent(Char): """ The font metrics need to be dealt with differently for accents, since they are already offset correctly from the baseline in TrueType fonts. """ def _update_metrics(self): metrics = self._metrics = self.font_output.get_metrics( self.font, self.font_class, self.c, self.fontsize, self.dpi) self.width = metrics.xmax - metrics.xmin self.height = metrics.ymax - metrics.ymin self.depth = 0 def shrink(self): Char.shrink(self) self._update_metrics() def grow(self): Char.grow(self) self._update_metrics() def render(self, x, y): """ Render the character to the canvas. """ self.font_output.render_glyph( x - self._metrics.xmin, y + self._metrics.ymin, self.font, self.font_class, self.c, self.fontsize, self.dpi) class List(Box): """ A list of nodes (either horizontal or vertical). """ def __init__(self, elements): Box.__init__(self, 0., 0., 0.) self.shift_amount = 0. # An arbitrary offset self.children = elements # The child nodes of this list # The following parameters are set in the vpack and hpack functions self.glue_set = 0. # The glue setting of this list self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching self.glue_order = 0 # The order of infinity (0 - 3) for the glue def __repr__(self): return '[%s <%.02f %.02f %.02f %.02f> %s]' % ( self.__internal_repr__(), self.width, self.height, self.depth, self.shift_amount, ' '.join([repr(x) for x in self.children])) def _determine_order(self, totals): """ A helper function to determine the highest order of glue used by the members of this list. Used by vpack and hpack. """ o = 0 for i in range(len(totals) - 1, 0, -1): if totals[i] != 0.0: o = i break return o def _set_glue(self, x, sign, totals, error_type): o = self._determine_order(totals) self.glue_order = o self.glue_sign = sign if totals[o] != 0.: self.glue_set = x / totals[o] else: self.glue_sign = 0 self.glue_ratio = 0. if o == 0: if len(self.children): warn("%s %s: %r" % (error_type, self.__class__.__name__, self), MathTextWarning) def shrink(self): for child in self.children: child.shrink() Box.shrink(self) if self.size < NUM_SIZE_LEVELS: self.shift_amount *= SHRINK_FACTOR self.glue_set *= SHRINK_FACTOR def grow(self): for child in self.children: child.grow() Box.grow(self) self.shift_amount *= GROW_FACTOR self.glue_set *= GROW_FACTOR class Hlist(List): """ A horizontal list of boxes. """ def __init__(self, elements, w=0., m='additional', do_kern=True): List.__init__(self, elements) if do_kern: self.kern() self.hpack() def kern(self): """ Insert :class:`Kern` nodes between :class:`Char` nodes to set kerning. The :class:`Char` nodes themselves determine the amount of kerning they need (in :meth:`~Char.get_kerning`), and this function just creates the linked list in the correct way. """ new_children = [] num_children = len(self.children) if num_children: for i in range(num_children): elem = self.children[i] if i < num_children - 1: next = self.children[i + 1] else: next = None new_children.append(elem) kerning_distance = elem.get_kerning(next) if kerning_distance != 0.: kern = Kern(kerning_distance) new_children.append(kern) self.children = new_children # This is a failed experiment to fake cross-font kerning. # def get_kerning(self, next): # if len(self.children) >= 2 and isinstance(self.children[-2], Char): # if isinstance(next, Char): # print "CASE A" # return self.children[-2].get_kerning(next) # elif isinstance(next, Hlist) and len(next.children) and isinstance(next.children[0], Char): # print "CASE B" # result = self.children[-2].get_kerning(next.children[0]) # print result # return result # return 0.0 def hpack(self, w=0., m='additional'): """ The main duty of :meth:`hpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. The computed sizes normally enclose all of the material inside the new box; but some items may stick out if negative glue is used, if the box is overfull, or if a ``\\vbox`` includes other boxes that have been shifted left. - *w*: specifies a width - *m*: is either 'exactly' or 'additional'. Thus, ``hpack(w, 'exactly')`` produces a box whose width is exactly *w*, while ``hpack(w, 'additional')`` yields a box whose width is the natural width plus *w*. The default values produce a box with the natural width. """ # I don't know why these get reset in TeX. Shift_amount is pretty # much useless if we do. #self.shift_amount = 0. h = 0. d = 0. x = 0. total_stretch = [0.] * 4 total_shrink = [0.] * 4 for p in self.children: if isinstance(p, Char): x += p.width h = max(h, p.height) d = max(d, p.depth) elif isinstance(p, Box): x += p.width if not isinf(p.height) and not isinf(p.depth): s = getattr(p, 'shift_amount', 0.) h = max(h, p.height - s) d = max(d, p.depth + s) elif isinstance(p, Glue): glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += p.width self.height = h self.depth = d if m == 'additional': w += x self.width = w x = w - x if x == 0.: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0. return if x > 0.: self._set_glue(x, 1, total_stretch, "Overfull") else: self._set_glue(x, -1, total_shrink, "Underfull") class Vlist(List): """ A vertical list of boxes. """ def __init__(self, elements, h=0., m='additional'): List.__init__(self, elements) self.vpack() def vpack(self, h=0., m='additional', l=float(inf)): """ The main duty of :meth:`vpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. - *h*: specifies a height - *m*: is either 'exactly' or 'additional'. - *l*: a maximum height Thus, ``vpack(h, 'exactly')`` produces a box whose height is exactly *h*, while ``vpack(h, 'additional')`` yields a box whose height is the natural height plus *h*. The default values produce a box with the natural width. """ # I don't know why these get reset in TeX. Shift_amount is pretty # much useless if we do. # self.shift_amount = 0. w = 0. d = 0. x = 0. total_stretch = [0.] * 4 total_shrink = [0.] * 4 for p in self.children: if isinstance(p, Box): x += d + p.height d = p.depth if not isinf(p.width): s = getattr(p, 'shift_amount', 0.) w = max(w, p.width + s) elif isinstance(p, Glue): x += d d = 0. glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += d + p.width d = 0. elif isinstance(p, Char): raise RuntimeError("Internal mathtext error: Char node found in Vlist.") self.width = w if d > l: x += d - l self.depth = l else: self.depth = d if m == 'additional': h += x self.height = h x = h - x if x == 0: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0. return if x > 0.: self._set_glue(x, 1, total_stretch, "Overfull") else: self._set_glue(x, -1, total_shrink, "Underfull") class Rule(Box): """ A :class:`Rule` node stands for a solid black rectangle; it has *width*, *depth*, and *height* fields just as in an :class:`Hlist`. However, if any of these dimensions is inf, the actual value will be determined by running the rule up to the boundary of the innermost enclosing box. This is called a "running dimension." The width is never running in an :class:`Hlist`; the height and depth are never running in a :class:`Vlist`. """ def __init__(self, width, height, depth, state): Box.__init__(self, width, height, depth) self.font_output = state.font_output def render(self, x, y, w, h): self.font_output.render_rect_filled(x, y, x + w, y + h) class Hrule(Rule): """ Convenience class to create a horizontal rule. """ def __init__(self, state, thickness=None): if thickness is None: thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) height = depth = thickness * 0.5 Rule.__init__(self, inf, height, depth, state) class Vrule(Rule): """ Convenience class to create a vertical rule. """ def __init__(self, state): thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) Rule.__init__(self, thickness, inf, inf, state) class Glue(Node): """ Most of the information in this object is stored in the underlying :class:`GlueSpec` class, which is shared between multiple glue objects. (This is a memory optimization which probably doesn't matter anymore, but it's easier to stick to what TeX does.) """ def __init__(self, glue_type, copy=False): Node.__init__(self) self.glue_subtype = 'normal' if is_string_like(glue_type): glue_spec = GlueSpec.factory(glue_type) elif isinstance(glue_type, GlueSpec): glue_spec = glue_type else: raise ArgumentError("glue_type must be a glue spec name or instance.") if copy: glue_spec = glue_spec.copy() self.glue_spec = glue_spec def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: if self.glue_spec.width != 0.: self.glue_spec = self.glue_spec.copy() self.glue_spec.width *= SHRINK_FACTOR def grow(self): Node.grow(self) if self.glue_spec.width != 0.: self.glue_spec = self.glue_spec.copy() self.glue_spec.width *= GROW_FACTOR class GlueSpec(object): """ See :class:`Glue`. """ def __init__(self, width=0., stretch=0., stretch_order=0, shrink=0., shrink_order=0): self.width = width self.stretch = stretch self.stretch_order = stretch_order self.shrink = shrink self.shrink_order = shrink_order def copy(self): return GlueSpec( self.width, self.stretch, self.stretch_order, self.shrink, self.shrink_order) def factory(cls, glue_type): return cls._types[glue_type] factory = classmethod(factory) GlueSpec._types = { 'fil': GlueSpec(0., 1., 1, 0., 0), 'fill': GlueSpec(0., 1., 2, 0., 0), 'filll': GlueSpec(0., 1., 3, 0., 0), 'neg_fil': GlueSpec(0., 0., 0, 1., 1), 'neg_fill': GlueSpec(0., 0., 0, 1., 2), 'neg_filll': GlueSpec(0., 0., 0, 1., 3), 'empty': GlueSpec(0., 0., 0, 0., 0), 'ss': GlueSpec(0., 1., 1, -1., 1) } # Some convenient ways to get common kinds of glue class Fil(Glue): def __init__(self): Glue.__init__(self, 'fil') class Fill(Glue): def __init__(self): Glue.__init__(self, 'fill') class Filll(Glue): def __init__(self): Glue.__init__(self, 'filll') class NegFil(Glue): def __init__(self): Glue.__init__(self, 'neg_fil') class NegFill(Glue): def __init__(self): Glue.__init__(self, 'neg_fill') class NegFilll(Glue): def __init__(self): Glue.__init__(self, 'neg_filll') class SsGlue(Glue): def __init__(self): Glue.__init__(self, 'ss') class HCentered(Hlist): """ A convenience class to create an :class:`Hlist` whose contents are centered within its enclosing box. """ def __init__(self, elements): Hlist.__init__(self, [SsGlue()] + elements + [SsGlue()], do_kern=False) class VCentered(Hlist): """ A convenience class to create a :class:`Vlist` whose contents are centered within its enclosing box. """ def __init__(self, elements): Vlist.__init__(self, [SsGlue()] + elements + [SsGlue()]) class Kern(Node): """ A :class:`Kern` node has a width field to specify a (normally negative) amount of spacing. This spacing correction appears in horizontal lists between letters like A and V when the font designer said that it looks better to move them closer together or further apart. A kern node can also appear in a vertical list, when its *width* denotes additional spacing in the vertical direction. """ height = 0 depth = 0 def __init__(self, width): Node.__init__(self) self.width = width def __repr__(self): return "k%.02f" % self.width def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR def grow(self): Node.grow(self) self.width *= GROW_FACTOR class SubSuperCluster(Hlist): """ :class:`SubSuperCluster` is a sort of hack to get around that fact that this code do a two-pass parse like TeX. This lets us store enough information in the hlist itself, namely the nucleus, sub- and super-script, such that if another script follows that needs to be attached, it can be reconfigured on the fly. """ def __init__(self): self.nucleus = None self.sub = None self.super = None Hlist.__init__(self, []) class AutoHeightChar(Hlist): """ :class:`AutoHeightChar` will create a character as close to the given height and depth as possible. When using a font with multiple height versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph. """ def __init__(self, c, height, depth, state, always=False): alternatives = state.font_output.get_sized_alternatives_for_symbol( state.font, c) state = state.copy() target_total = height + depth for fontname, sym in alternatives: state.font = fontname char = Char(sym, state) if char.height + char.depth >= target_total: break factor = target_total / (char.height + char.depth) state.fontsize *= factor char = Char(sym, state) shift = (depth - char.depth) Hlist.__init__(self, [char]) self.shift_amount = shift class AutoWidthChar(Hlist): """ :class:`AutoWidthChar` will create a character as close to the given width as possible. When using a font with multiple width versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph. """ def __init__(self, c, width, state, always=False, char_class=Char): alternatives = state.font_output.get_sized_alternatives_for_symbol( state.font, c) state = state.copy() for fontname, sym in alternatives: state.font = fontname char = char_class(sym, state) if char.width >= width: break factor = width / char.width state.fontsize *= factor char = char_class(sym, state) Hlist.__init__(self, [char]) self.width = char.width class Ship(object): """ Once the boxes have been set up, this sends them to output. Since boxes can be inside of boxes inside of boxes, the main work of :class:`Ship` is done by two mutually recursive routines, :meth:`hlist_out` and :meth:`vlist_out`, which traverse the :class:`Hlist` nodes and :class:`Vlist` nodes inside of horizontal and vertical boxes. The global variables used in TeX to store state as it processes have become member variables here. """ def __call__(self, ox, oy, box): self.max_push = 0 # Deepest nesting of push commands so far self.cur_s = 0 self.cur_v = 0. self.cur_h = 0. self.off_h = ox self.off_v = oy + box.height self.hlist_out(box) def clamp(value): if value < -1000000000.: return -1000000000. if value > 1000000000.: return 1000000000. return value clamp = staticmethod(clamp) def hlist_out(self, box): cur_g = 0 cur_glue = 0. glue_order = box.glue_order glue_sign = box.glue_sign base_line = self.cur_v left_edge = self.cur_h self.cur_s += 1 self.max_push = max(self.cur_s, self.max_push) clamp = self.clamp for p in box.children: if isinstance(p, Char): p.render(self.cur_h + self.off_h, self.cur_v + self.off_v) self.cur_h += p.width elif isinstance(p, Kern): self.cur_h += p.width elif isinstance(p, List): # node623 if len(p.children) == 0: self.cur_h += p.width else: edge = self.cur_h self.cur_v = base_line + p.shift_amount if isinstance(p, Hlist): self.hlist_out(p) else: # p.vpack(box.height + box.depth, 'exactly') self.vlist_out(p) self.cur_h = edge + p.width self.cur_v = base_line elif isinstance(p, Box): # node624 rule_height = p.height rule_depth = p.depth rule_width = p.width if isinf(rule_height): rule_height = box.height if isinf(rule_depth): rule_depth = box.depth if rule_height > 0 and rule_width > 0: self.cur_v = baseline + rule_depth p.render(self.cur_h + self.off_h, self.cur_v + self.off_v, rule_width, rule_height) self.cur_v = baseline self.cur_h += rule_width elif isinstance(p, Glue): # node625 glue_spec = p.glue_spec rule_width = glue_spec.width - cur_g if glue_sign != 0: # normal if glue_sign == 1: # stretching if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = round(clamp(float(box.glue_set) * cur_glue)) elif glue_spec.shrink_order == glue_order: cur_glue += glue_spec.shrink cur_g = round(clamp(float(box.glue_set) * cur_glue)) rule_width += cur_g self.cur_h += rule_width self.cur_s -= 1 def vlist_out(self, box): cur_g = 0 cur_glue = 0. glue_order = box.glue_order glue_sign = box.glue_sign self.cur_s += 1 self.max_push = max(self.max_push, self.cur_s) left_edge = self.cur_h self.cur_v -= box.height top_edge = self.cur_v clamp = self.clamp for p in box.children: if isinstance(p, Kern): self.cur_v += p.width elif isinstance(p, List): if len(p.children) == 0: self.cur_v += p.height + p.depth else: self.cur_v += p.height self.cur_h = left_edge + p.shift_amount save_v = self.cur_v p.width = box.width if isinstance(p, Hlist): self.hlist_out(p) else: self.vlist_out(p) self.cur_v = save_v + p.depth self.cur_h = left_edge elif isinstance(p, Box): rule_height = p.height rule_depth = p.depth rule_width = p.width if isinf(rule_width): rule_width = box.width rule_height += rule_depth if rule_height > 0 and rule_depth > 0: self.cur_v += rule_height p.render(self.cur_h + self.off_h, self.cur_v + self.off_v, rule_width, rule_height) elif isinstance(p, Glue): glue_spec = p.glue_spec rule_height = glue_spec.width - cur_g if glue_sign != 0: # normal if glue_sign == 1: # stretching if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = round(clamp(float(box.glue_set) * cur_glue)) elif glue_spec.shrink_order == glue_order: # shrinking cur_glue += glue_spec.shrink cur_g = round(clamp(float(box.glue_set) * cur_glue)) rule_height += cur_g self.cur_v += rule_height elif isinstance(p, Char): raise RuntimeError("Internal mathtext error: Char node found in vlist") self.cur_s -= 1 ship = Ship() ############################################################################## # PARSER def Error(msg): """ Helper class to raise parser errors. """ def raise_error(s, loc, toks): raise ParseFatalException(msg + "\n" + s) empty = Empty() empty.setParseAction(raise_error) return empty class Parser(object): """ This is the pyparsing-based parser for math expressions. It actually parses full strings *containing* math expressions, in that raw text may also appear outside of pairs of ``$``. The grammar is based directly on that in TeX, though it cuts a few corners. """ _binary_operators = set(r''' + * \pm \sqcap \rhd \mp \sqcup \unlhd \times \vee \unrhd \div \wedge \oplus \ast \setminus \ominus \star \wr \otimes \circ \diamond \oslash \bullet \bigtriangleup \odot \cdot \bigtriangledown \bigcirc \cap \triangleleft \dagger \cup \triangleright \ddagger \uplus \lhd \amalg'''.split()) _relation_symbols = set(r''' = < > : \leq \geq \equiv \models \prec \succ \sim \perp \preceq \succeq \simeq \mid \ll \gg \asymp \parallel \subset \supset \approx \bowtie \subseteq \supseteq \cong \Join \sqsubset \sqsupset \neq \smile \sqsubseteq \sqsupseteq \doteq \frown \in \ni \propto \vdash \dashv \dots'''.split()) _arrow_symbols = set(r''' \leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow \Longrightarrow \Downarrow \leftrightarrow \longleftrightarrow \updownarrow \Leftrightarrow \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow \hookleftarrow \hookrightarrow \searrow \leftharpoonup \rightharpoonup \swarrow \leftharpoondown \rightharpoondown \nwarrow \rightleftharpoons \leadsto'''.split()) _spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols _punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split()) _overunder_symbols = set(r''' \sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee \bigwedge \bigodot \bigotimes \bigoplus \biguplus '''.split()) _overunder_functions = set( r"lim liminf limsup sup max min".split()) _dropsub_symbols = set(r'''\int \oint'''.split()) _fontnames = set("rm cal it tt sf bf default bb frak circled scr regular".split()) _function_names = set(""" arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan coth inf max tanh""".split()) _ambiDelim = set(r""" | \| / \backslash \uparrow \downarrow \updownarrow \Uparrow \Downarrow \Updownarrow .""".split()) _leftDelim = set(r"( [ { < \lfloor \langle \lceil".split()) _rightDelim = set(r") ] } > \rfloor \rangle \rceil".split()) def __init__(self): # All forward declarations are here font = Forward().setParseAction(self.font).setName("font") latexfont = Forward() subsuper = Forward().setParseAction(self.subsuperscript).setName("subsuper") placeable = Forward().setName("placeable") simple = Forward().setName("simple") autoDelim = Forward().setParseAction(self.auto_sized_delimiter) self._expression = Forward().setParseAction(self.finish).setName("finish") float = Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)") lbrace = Literal('{').suppress() rbrace = Literal('}').suppress() start_group = (Optional(latexfont) - lbrace) start_group.setParseAction(self.start_group) end_group = rbrace.copy() end_group.setParseAction(self.end_group) bslash = Literal('\\') accent = oneOf(self._accent_map.keys() + list(self._wide_accents)) function = oneOf(list(self._function_names)) fontname = oneOf(list(self._fontnames)) latex2efont = oneOf(['math' + x for x in self._fontnames]) space =(FollowedBy(bslash) + oneOf([r'\ ', r'\/', r'\,', r'\;', r'\quad', r'\qquad', r'\!']) ).setParseAction(self.space).setName('space') customspace =(Literal(r'\hspace') - (( lbrace - float - rbrace ) | Error(r"Expected \hspace{n}")) ).setParseAction(self.customspace).setName('customspace') unicode_range = u"\U00000080-\U0001ffff" symbol =(Regex(UR"([a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|%s])|(\\[%%${}\[\]_|])" % unicode_range) | (Combine( bslash + oneOf(tex2uni.keys()) ) + FollowedBy(Regex("[^a-zA-Z]"))) ).setParseAction(self.symbol).leaveWhitespace() c_over_c =(Suppress(bslash) + oneOf(self._char_over_chars.keys()) ).setParseAction(self.char_over_chars) accent = Group( Suppress(bslash) + accent - placeable ).setParseAction(self.accent).setName("accent") function =(Suppress(bslash) + function ).setParseAction(self.function).setName("function") group = Group( start_group + ZeroOrMore( autoDelim ^ simple) - end_group ).setParseAction(self.group).setName("group") font <<(Suppress(bslash) + fontname) latexfont <<(Suppress(bslash) + latex2efont) frac = Group( Suppress(Literal(r"\frac")) + ((group + group) | Error(r"Expected \frac{num}{den}")) ).setParseAction(self.frac).setName("frac") stackrel = Group( Suppress(Literal(r"\stackrel")) + ((group + group) | Error(r"Expected \stackrel{num}{den}")) ).setParseAction(self.stackrel).setName("stackrel") binom = Group( Suppress(Literal(r"\binom")) + ((group + group) | Error(r"Expected \binom{num}{den}")) ).setParseAction(self.binom).setName("binom") ambiDelim = oneOf(list(self._ambiDelim)) leftDelim = oneOf(list(self._leftDelim)) rightDelim = oneOf(list(self._rightDelim)) rightDelimSafe = oneOf(list(self._rightDelim - set(['}']))) genfrac = Group( Suppress(Literal(r"\genfrac")) + ((Suppress(Literal('{')) + oneOf(list(self._ambiDelim | self._leftDelim | set(['']))) + Suppress(Literal('}')) + Suppress(Literal('{')) + oneOf(list(self._ambiDelim | (self._rightDelim - set(['}'])) | set(['', r'\}']))) + Suppress(Literal('}')) + Suppress(Literal('{')) + Regex("[0-9]*(\.?[0-9]*)?") + Suppress(Literal('}')) + group + group + group) | Error(r"Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}")) ).setParseAction(self.genfrac).setName("genfrac") sqrt = Group( Suppress(Literal(r"\sqrt")) + Optional( Suppress(Literal("[")) - Regex("[0-9]+") - Suppress(Literal("]")), default = None ) + (group | Error("Expected \sqrt{value}")) ).setParseAction(self.sqrt).setName("sqrt") overline = Group( Suppress(Literal(r"\overline")) + (group | Error("Expected \overline{value}")) ).setParseAction(self.overline).setName("overline") placeable <<(function ^ (c_over_c | symbol) ^ accent ^ group ^ frac ^ stackrel ^ binom ^ genfrac ^ sqrt ^ overline ) simple <<(space | customspace | font | subsuper ) subsuperop = oneOf(["_", "^"]) subsuper << Group( ( Optional(placeable) + OneOrMore( subsuperop - placeable ) ) | placeable ) autoDelim <<(Suppress(Literal(r"\left")) + ((leftDelim | ambiDelim) | Error("Expected a delimiter")) + Group( OneOrMore( autoDelim ^ simple)) + Suppress(Literal(r"\right")) + ((rightDelim | ambiDelim) | Error("Expected a delimiter")) ) math = OneOrMore( autoDelim ^ simple ).setParseAction(self.math).setName("math") math_delim = ~bslash + Literal('$') non_math = Regex(r"(?:(?:\\[$])|[^$])*" ).setParseAction(self.non_math).setName("non_math").leaveWhitespace() self._expression << ( non_math + ZeroOrMore( Suppress(math_delim) + Optional(math) + (Suppress(math_delim) | Error("Expected end of math '$'")) + non_math ) ) + StringEnd() self.clear() def clear(self): """ Clear any state before parsing. """ self._expr = None self._state_stack = None self._em_width_cache = {} def parse(self, s, fonts_object, fontsize, dpi): """ Parse expression *s* using the given *fonts_object* for output, at the given *fontsize* and *dpi*. Returns the parse tree of :class:`Node` instances. """ self._state_stack = [self.State(fonts_object, 'default', 'rm', fontsize, dpi)] try: self._expression.parseString(s) except ParseException, err: raise ValueError("\n".join([ "", err.line, " " * (err.column - 1) + "^", str(err)])) return self._expr # The state of the parser is maintained in a stack. Upon # entering and leaving a group { } or math/non-math, the stack # is pushed and popped accordingly. The current state always # exists in the top element of the stack. class State(object): """ Stores the state of the parser. States are pushed and popped from a stack as necessary, and the "current" state is always at the top of the stack. """ def __init__(self, font_output, font, font_class, fontsize, dpi): self.font_output = font_output self._font = font self.font_class = font_class self.fontsize = fontsize self.dpi = dpi def copy(self): return Parser.State( self.font_output, self.font, self.font_class, self.fontsize, self.dpi) def _get_font(self): return self._font def _set_font(self, name): if name in ('rm', 'it', 'bf'): self.font_class = name self._font = name font = property(_get_font, _set_font) def get_state(self): """ Get the current :class:`State` of the parser. """ return self._state_stack[-1] def pop_state(self): """ Pop a :class:`State` off of the stack. """ self._state_stack.pop() def push_state(self): """ Push a new :class:`State` onto the stack which is just a copy of the current state. """ self._state_stack.append(self.get_state().copy()) def finish(self, s, loc, toks): #~ print "finish", toks self._expr = Hlist(toks) return [self._expr] def math(self, s, loc, toks): #~ print "math", toks hlist = Hlist(toks) self.pop_state() return [hlist] def non_math(self, s, loc, toks): #~ print "non_math", toks s = toks[0].replace(r'\$', '$') symbols = [Char(c, self.get_state()) for c in s] hlist = Hlist(symbols) # We're going into math now, so set font to 'it' self.push_state() self.get_state().font = rcParams['mathtext.default'] return [hlist] def _make_space(self, percentage): # All spaces are relative to em width state = self.get_state() key = (state.font, state.fontsize, state.dpi) width = self._em_width_cache.get(key) if width is None: metrics = state.font_output.get_metrics( state.font, rcParams['mathtext.default'], 'm', state.fontsize, state.dpi) width = metrics.advance self._em_width_cache[key] = width return Kern(width * percentage) _space_widths = { r'\ ' : 0.3, r'\,' : 0.4, r'\;' : 0.8, r'\quad' : 1.6, r'\qquad' : 3.2, r'\!' : -0.4, r'\/' : 0.4 } def space(self, s, loc, toks): assert(len(toks)==1) num = self._space_widths[toks[0]] box = self._make_space(num) return [box] def customspace(self, s, loc, toks): return [self._make_space(float(toks[1]))] def symbol(self, s, loc, toks): # print "symbol", toks c = toks[0] if c == "'": c = '\prime' try: char = Char(c, self.get_state()) except ValueError: raise ParseFatalException("Unknown symbol: %s" % c) if c in self._spaced_symbols: return [Hlist( [self._make_space(0.2), char, self._make_space(0.2)] , do_kern = False)] elif c in self._punctuation_symbols: return [Hlist( [char, self._make_space(0.2)] , do_kern = False)] return [char] _char_over_chars = { # The first 2 entires in the tuple are (font, char, sizescale) for # the two symbols under and over. The third element is the space # (in multiples of underline height) r'AA' : ( ('rm', 'A', 1.0), (None, '\circ', 0.5), 0.0), } def char_over_chars(self, s, loc, toks): sym = toks[0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) under_desc, over_desc, space = \ self._char_over_chars.get(sym, (None, None, 0.0)) if under_desc is None: raise ParseFatalException("Error parsing symbol") over_state = state.copy() if over_desc[0] is not None: over_state.font = over_desc[0] over_state.fontsize *= over_desc[2] over = Accent(over_desc[1], over_state) under_state = state.copy() if under_desc[0] is not None: under_state.font = under_desc[0] under_state.fontsize *= under_desc[2] under = Char(under_desc[1], under_state) width = max(over.width, under.width) over_centered = HCentered([over]) over_centered.hpack(width, 'exactly') under_centered = HCentered([under]) under_centered.hpack(width, 'exactly') return Vlist([ over_centered, Vbox(0., thickness * space), under_centered ]) _accent_map = { r'hat' : r'\circumflexaccent', r'breve' : r'\combiningbreve', r'bar' : r'\combiningoverline', r'grave' : r'\combininggraveaccent', r'acute' : r'\combiningacuteaccent', r'ddot' : r'\combiningdiaeresis', r'tilde' : r'\combiningtilde', r'dot' : r'\combiningdotabove', r'vec' : r'\combiningrightarrowabove', r'"' : r'\combiningdiaeresis', r"`" : r'\combininggraveaccent', r"'" : r'\combiningacuteaccent', r'~' : r'\combiningtilde', r'.' : r'\combiningdotabove', r'^' : r'\circumflexaccent', r'overrightarrow' : r'\rightarrow', r'overleftarrow' : r'\leftarrow' } _wide_accents = set(r"widehat widetilde widebar".split()) def accent(self, s, loc, toks): assert(len(toks)==1) state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) if len(toks[0]) != 2: raise ParseFatalException("Error parsing accent") accent, sym = toks[0] if accent in self._wide_accents: accent = AutoWidthChar( '\\' + accent, sym.width, state, char_class=Accent) else: accent = Accent(self._accent_map[accent], state) centered = HCentered([accent]) centered.hpack(sym.width, 'exactly') return Vlist([ centered, Vbox(0., thickness * 2.0), Hlist([sym]) ]) def function(self, s, loc, toks): #~ print "function", toks self.push_state() state = self.get_state() state.font = 'rm' hlist = Hlist([Char(c, state) for c in toks[0]]) self.pop_state() hlist.function_name = toks[0] return hlist def start_group(self, s, loc, toks): self.push_state() # Deal with LaTeX-style font tokens if len(toks): self.get_state().font = toks[0][4:] return [] def group(self, s, loc, toks): grp = Hlist(toks[0]) return [grp] def end_group(self, s, loc, toks): self.pop_state() return [] def font(self, s, loc, toks): assert(len(toks)==1) name = toks[0] self.get_state().font = name return [] def is_overunder(self, nucleus): if isinstance(nucleus, Char): return nucleus.c in self._overunder_symbols elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'): return nucleus.function_name in self._overunder_functions return False def is_dropsub(self, nucleus): if isinstance(nucleus, Char): return nucleus.c in self._dropsub_symbols return False def is_slanted(self, nucleus): if isinstance(nucleus, Char): return nucleus.is_slanted() return False def subsuperscript(self, s, loc, toks): assert(len(toks)==1) # print 'subsuperscript', toks nucleus = None sub = None super = None if len(toks[0]) == 1: return toks[0].asList() elif len(toks[0]) == 2: op, next = toks[0] nucleus = Hbox(0.0) if op == '_': sub = next else: super = next elif len(toks[0]) == 3: nucleus, op, next = toks[0] if op == '_': sub = next else: super = next elif len(toks[0]) == 5: nucleus, op1, next1, op2, next2 = toks[0] if op1 == op2: if op1 == '_': raise ParseFatalException("Double subscript") else: raise ParseFatalException("Double superscript") if op1 == '_': sub = next1 super = next2 else: super = next1 sub = next2 else: raise ParseFatalException( "Subscript/superscript sequence is too long. " "Use braces { } to remove ambiguity.") state = self.get_state() rule_thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) xHeight = state.font_output.get_xheight( state.font, state.fontsize, state.dpi) # Handle over/under symbols, such as sum or integral if self.is_overunder(nucleus): vlist = [] shift = 0. width = nucleus.width if super is not None: super.shrink() width = max(width, super.width) if sub is not None: sub.shrink() width = max(width, sub.width) if super is not None: hlist = HCentered([super]) hlist.hpack(width, 'exactly') vlist.extend([hlist, Kern(rule_thickness * 3.0)]) hlist = HCentered([nucleus]) hlist.hpack(width, 'exactly') vlist.append(hlist) if sub is not None: hlist = HCentered([sub]) hlist.hpack(width, 'exactly') vlist.extend([Kern(rule_thickness * 3.0), hlist]) shift = hlist.height vlist = Vlist(vlist) vlist.shift_amount = shift + nucleus.depth result = Hlist([vlist]) return [result] # Handle regular sub/superscripts shift_up = nucleus.height - SUBDROP * xHeight if self.is_dropsub(nucleus): shift_down = nucleus.depth + SUBDROP * xHeight else: shift_down = SUBDROP * xHeight if super is None: # node757 sub.shrink() x = Hlist([sub]) # x.width += SCRIPT_SPACE * xHeight shift_down = max(shift_down, SUB1) clr = x.height - (abs(xHeight * 4.0) / 5.0) shift_down = max(shift_down, clr) x.shift_amount = shift_down else: super.shrink() x = Hlist([super, Kern(SCRIPT_SPACE * xHeight)]) # x.width += SCRIPT_SPACE * xHeight clr = SUP1 * xHeight shift_up = max(shift_up, clr) clr = x.depth + (abs(xHeight) / 4.0) shift_up = max(shift_up, clr) if sub is None: x.shift_amount = -shift_up else: # Both sub and superscript sub.shrink() y = Hlist([sub]) # y.width += SCRIPT_SPACE * xHeight shift_down = max(shift_down, SUB1 * xHeight) clr = (2.0 * rule_thickness - ((shift_up - x.depth) - (y.height - shift_down))) if clr > 0.: shift_up += clr shift_down += clr if self.is_slanted(nucleus): x.shift_amount = DELTA * (shift_up + shift_down) x = Vlist([x, Kern((shift_up - x.depth) - (y.height - shift_down)), y]) x.shift_amount = shift_down result = Hlist([nucleus, x]) return [result] def _genfrac(self, ldelim, rdelim, rule, style, num, den): state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) rule = float(rule) num.shrink() den.shrink() cnum = HCentered([num]) cden = HCentered([den]) width = max(num.width, den.width) cnum.hpack(width, 'exactly') cden.hpack(width, 'exactly') vlist = Vlist([cnum, # numerator Vbox(0, thickness * 2.0), # space Hrule(state, rule), # rule Vbox(0, thickness * 2.0), # space cden # denominator ]) # Shift so the fraction line sits in the middle of the # equals sign metrics = state.font_output.get_metrics( state.font, rcParams['mathtext.default'], '=', state.fontsize, state.dpi) shift = (cden.height - ((metrics.ymax + metrics.ymin) / 2 - thickness * 3.0)) vlist.shift_amount = shift result = [Hlist([vlist, Hbox(thickness * 2.)])] if ldelim or rdelim: if ldelim == '': ldelim = '.' if rdelim == '': rdelim = '.' elif rdelim == r'\}': rdelim = '}' return self._auto_sized_delimiter(ldelim, result, rdelim) return result def genfrac(self, s, loc, toks): assert(len(toks)==1) assert(len(toks[0])==6) return self._genfrac(*tuple(toks[0])) def frac(self, s, loc, toks): assert(len(toks)==1) assert(len(toks[0])==2) state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) num, den = toks[0] return self._genfrac('', '', thickness, '', num, den) def stackrel(self, s, loc, toks): assert(len(toks)==1) assert(len(toks[0])==2) num, den = toks[0] return self._genfrac('', '', 0.0, '', num, den) def binom(self, s, loc, toks): assert(len(toks)==1) assert(len(toks[0])==2) num, den = toks[0] return self._genfrac('(', ')', 0.0, '', num, den) def sqrt(self, s, loc, toks): #~ print "sqrt", toks root, body = toks[0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) # Determine the height of the body, and add a little extra to # the height so it doesn't seem cramped height = body.height - body.shift_amount + thickness * 5.0 depth = body.depth + body.shift_amount check = AutoHeightChar(r'\__sqrt__', height, depth, state, always=True) height = check.height - check.shift_amount depth = check.depth + check.shift_amount # Put a little extra space to the left and right of the body padded_body = Hlist([Hbox(thickness * 2.0), body, Hbox(thickness * 2.0)]) rightside = Vlist([Hrule(state), Fill(), padded_body]) # Stretch the glue between the hrule and the body rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), depth, 'exactly') # Add the root and shift it upward so it is above the tick. # The value of 0.6 is a hard-coded hack ;) if root is None: root = Box(check.width * 0.5, 0., 0.) else: root = Hlist([Char(x, state) for x in root]) root.shrink() root.shrink() root_vlist = Vlist([Hlist([root])]) root_vlist.shift_amount = -height * 0.6 hlist = Hlist([root_vlist, # Root # Negative kerning to put root over tick Kern(-check.width * 0.5), check, # Check rightside]) # Body return [hlist] def overline(self, s, loc, toks): assert(len(toks)==1) assert(len(toks[0])==1) body = toks[0][0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) height = body.height - body.shift_amount + thickness * 3.0 depth = body.depth + body.shift_amount # Place overline above body rightside = Vlist([Hrule(state), Fill(), Hlist([body])]) # Stretch the glue between the hrule and the body rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), depth, 'exactly') hlist = Hlist([rightside]) return [hlist] def _auto_sized_delimiter(self, front, middle, back): state = self.get_state() height = max([x.height for x in middle]) depth = max([x.depth for x in middle]) parts = [] # \left. and \right. aren't supposed to produce any symbols if front != '.': parts.append(AutoHeightChar(front, height, depth, state)) parts.extend(middle) if back != '.': parts.append(AutoHeightChar(back, height, depth, state)) hlist = Hlist(parts) return hlist def auto_sized_delimiter(self, s, loc, toks): #~ print "auto_sized_delimiter", toks front, middle, back = toks return self._auto_sized_delimiter(front, middle.asList(), back) ### ############################################################################## # MAIN class MathTextParser(object): _parser = None _backend_mapping = { 'bitmap': MathtextBackendBitmap, 'agg' : MathtextBackendAgg, 'ps' : MathtextBackendPs, 'pdf' : MathtextBackendPdf, 'svg' : MathtextBackendSvg, 'path' : MathtextBackendPath, 'cairo' : MathtextBackendCairo, 'macosx': MathtextBackendAgg, } _font_type_mapping = { 'cm' : BakomaFonts, 'stix' : StixFonts, 'stixsans' : StixSansFonts, 'custom' : UnicodeFonts } def __init__(self, output): """ Create a MathTextParser for the given backend *output*. """ self._output = output.lower() self._cache = maxdict(50) def parse(self, s, dpi = 72, prop = None): """ Parse the given math expression *s* at the given *dpi*. If *prop* is provided, it is a :class:`~matplotlib.font_manager.FontProperties` object specifying the "default" font to use in the math expression, used for all non-math text. The results are cached, so multiple calls to :meth:`parse` with the same expression should be fast. """ if prop is None: prop = FontProperties() cacheKey = (s, dpi, hash(prop)) result = self._cache.get(cacheKey) if result is not None: return result if self._output == 'ps' and rcParams['ps.useafm']: font_output = StandardPsFonts(prop) else: backend = self._backend_mapping[self._output]() fontset = rcParams['mathtext.fontset'] fontset_class = self._font_type_mapping.get(fontset.lower()) if fontset_class is not None: font_output = fontset_class(prop, backend) else: raise ValueError( "mathtext.fontset must be either 'cm', 'stix', " "'stixsans', or 'custom'") fontsize = prop.get_size_in_points() # This is a class variable so we don't rebuild the parser # with each request. if self._parser is None: self.__class__._parser = Parser() box = self._parser.parse(s, font_output, fontsize, dpi) font_output.set_canvas_size(box.width, box.height, box.depth) result = font_output.get_results(box) self._cache[cacheKey] = result # Free up the transient data structures self._parser.clear() # Fix cyclical references font_output.destroy() font_output.mathtext_backend.fonts_object = None font_output.mathtext_backend = None return result def to_mask(self, texstr, dpi=120, fontsize=14): """ *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels. """ assert(self._output=="bitmap") prop = FontProperties(size=fontsize) ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) x = ftimage.as_array() return x, depth def to_rgba(self, texstr, color='black', dpi=120, fontsize=14): """ *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *color* Any matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels. """ x, depth = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) r, g, b = mcolors.colorConverter.to_rgb(color) RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8) RGBA[:,:,0] = int(255*r) RGBA[:,:,1] = int(255*g) RGBA[:,:,2] = int(255*b) RGBA[:,:,3] = x return RGBA, depth def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14): """ Writes a tex expression to a PNG file. Returns the offset of the baseline from the bottom of the image in pixels. *filename* A writable filename or fileobject *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *color* A valid matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns the offset of the baseline from the bottom of the image in pixels. """ rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) numrows, numcols, tmp = rgba.shape _png.write_png(rgba.tostring(), numcols, numrows, filename) return depth def get_depth(self, texstr, dpi=120, fontsize=14): """ Returns the offset of the baseline from the bottom of the image in pixels. *texstr* A valid mathtext string, eg r'IQ: $\sigma_i=15$' *dpi* The dots-per-inch to render the text *fontsize* The font size in points """ assert(self._output=="bitmap") prop = FontProperties(size=fontsize) ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) return depth def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None): """ Given a math expression, renders it in a closely-clipped bounding box to an image file. *s* A math expression. The math portion should be enclosed in dollar signs. *filename_or_obj* A filepath or writable file-like object to write the image data to. *prop* If provided, a FontProperties() object describing the size and style of the text. *dpi* Override the output dpi, otherwise use the default associated with the output format. *format* The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not provided, will be deduced from the filename. """ from matplotlib import figure # backend_agg supports all of the core output formats from matplotlib.backends import backend_agg if prop is None: prop = FontProperties() parser = MathTextParser('path') width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) fig.text(0, depth/height, s, fontproperties=prop) backend_agg.FigureCanvasAgg(fig) fig.savefig(filename_or_obj, dpi=dpi, format=format) return depth
ryandougherty/mwa-capstone
MWA_Tools/build/matplotlib/lib/matplotlib/mathtext.py
Python
gpl-2.0
108,907
[ "Bowtie" ]
40e5d983019bea1f74a5af1120c3157bb5bbefd80aa55c33801355f5b4898b73
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import os from monty.serialization import loadfn from pymatgen.analysis.structure_matcher import StructureMatcher """ This module uses data from the AFLOW LIBRARY OF CRYSTALLOGRAPHIC PROTOTYPES. If using this module, please cite their publication appropriately: Mehl, M. J., Hicks, D., Toher, C., Levy, O., Hanson, R. M., Hart, G., & Curtarolo, S. (2017). The AFLOW library of crystallographic prototypes: part 1. Computational Materials Science, 136, S1-S828. http://doi.org/10.1016/j.commatsci.2017.01.017 """ module_dir = os.path.dirname(os.path.abspath(__file__)) AFLOW_PROTOTYPE_LIBRARY = loadfn(os.path.join(os.path.dirname(os.path.abspath(__file__)), "aflow_prototypes.json")) class AflowPrototypeMatcher: """ This class will match structures to their crystal prototypes, and will attempt to group species together to match structures derived from prototypes (e.g. an A_xB_1-x_C from a binary prototype), and will give these the names the "-like" suffix. This class uses data from the AFLOW LIBRARY OF CRYSTALLOGRAPHIC PROTOTYPES. If using this class, please cite their publication appropriately: Mehl, M. J., Hicks, D., Toher, C., Levy, O., Hanson, R. M., Hart, G., & Curtarolo, S. (2017). The AFLOW library of crystallographic prototypes: part 1. Computational Materials Science, 136, S1-S828. http://doi.org/10.1016/j.commatsci.2017.01.017 """ def __init__(self, initial_ltol=0.2, initial_stol=0.3, initial_angle_tol=5): """ Tolerances as defined in StructureMatcher. Tolerances will be gradually decreased until only a single match is found (if possible). Args: initial_ltol: fractional length tolerance initial_stol: site tolerance initial_angle_tol: angle tolerance """ self.initial_ltol = initial_ltol self.initial_stol = initial_stol self.initial_angle_tol = initial_angle_tol @staticmethod def _match_prototype(structure_matcher, structure): tags = [] for d in AFLOW_PROTOTYPE_LIBRARY: p = d['snl'].structure match = structure_matcher.fit_anonymous(p, structure) if match: tags.append(d) return tags def _match_single_prototype(self, structure): sm = StructureMatcher(ltol=self.initial_ltol, stol=self.initial_stol, angle_tol=self.initial_angle_tol) tags = self._match_prototype(sm, structure) while len(tags) > 1: sm.ltol *= 0.8 sm.stol *= 0.8 sm.angle_tol *= 0.8 tags = self._match_prototype(sm, structure) if sm.ltol < 0.01: break return tags def get_prototypes(self, structure): """ Get prototype(s) structures for a given input structure. If you use this method in your work, please cite the appropriate AFLOW publication: Mehl, M. J., Hicks, D., Toher, C., Levy, O., Hanson, R. M., Hart, G., & Curtarolo, S. (2017). The AFLOW library of crystallographic prototypes: part 1. Computational Materials Science, 136, S1-S828. http://doi.org/10.1016/j.commatsci.2017.01.017 Args: structure: structure to match Returns (list): A list of dicts with keys 'snl' for the matched prototype and 'tags', a dict of tags ('mineral', 'strukturbericht' and 'aflow') of that prototype. This should be a list containing just a single entry, but it is possible a material can match multiple prototypes. """ tags = self._match_single_prototype(structure) if len(tags) == 0: return None else: return tags
dongsenfo/pymatgen
pymatgen/analysis/aflow_prototypes.py
Python
mit
4,002
[ "CRYSTAL", "pymatgen" ]
b20382543720e90430484dfccd9c6bbbfd0a677d86ac765707fa40d832db65bd
#=== CONTEXT ========================================================================================= # 2D NodeBox API in OpenGL. # Authors: Tom De Smedt, Frederik De Bleser # License: BSD (see LICENSE.txt for details). # Copyright (c) 2008 City In A Bottle (cityinabottle.org) # http://cityinabottle.org/nodebox # All graphics are drawn directly to the screen. # No scenegraph is kept for obvious performance reasons (therefore, no canvas._grobs as in NodeBox). # Debugging must be switched on or of before other modules are imported. import pyglet pyglet.options['debug_gl'] = False from pyglet.gl import * from pyglet.image import Texture from math import cos, sin, radians, pi, floor from time import time from random import seed, choice, shuffle, random as rnd from new import instancemethod from glob import glob from os import path, remove from sys import getrefcount from StringIO import StringIO from hashlib import md5 from types import FunctionType from datetime import datetime import geometry #import bezier # Do this at the end, when we have defined BezierPath, which is needed in the bezier module. #import shader # Do this when we have defined texture() and image(), which are needed in the shader module. def find(match=lambda item: False, list=[]): for item in list: if match(item): return item return None # OpenGL version, e.g. "2.0 NVIDIA-1.5.48". OPENGL = pyglet.gl.gl_info.get_version() #===================================================================================================== #--- CACHING ----------------------------------------------------------------------------------------- # OpenGL Display Lists offer a simple way to precompile batches of OpenGL commands. # The drawback is that the commands, once compiled, can't be modified. def precompile(function, *args, **kwargs): """ Creates an OpenGL Display List from the OpenGL commands in the given function. A Display List will precompile the commands and (if possible) store them in graphics memory. Returns an id which can be used with precompiled() to execute the cached commands. """ id = glGenLists(1) glNewList(id, GL_COMPILE) function(*args, **kwargs) glEndList() return id def precompiled(id): """ Executes the Display List program with the given id. """ glCallList(id) def flush(id): """ Removes the Display List program with the given id from memory. """ if id is not None: glDeleteLists(id, 1) #===================================================================================================== #--- COLOR ------------------------------------------------------------------------------------------- RGB = "RGB" HSB = "HSB" XYZ = "XYZ" LAB = "LAB" _background = None # Current state background color. _fill = None # Current state fill color. _stroke = None # Current state stroke color. _strokewidth = 1 # Current state strokewidth. _strokestyle = "solid" # Current state strokestyle. _alpha = 1 # Current state alpha transparency. class Color(list): def __init__(self, *args, **kwargs): """ A color with R,G,B,A channels, with channel values ranging between 0.0-1.0. Either takes four parameters (R,G,B,A), three parameters (R,G,B), two parameters (grayscale and alpha) or one parameter (grayscale or Color object). An optional base=1.0 parameter defines the range of the given parameters. An optional colorspace=RGB defines the color space of the given parameters. """ # Values are supplied as a tuple. if len(args) == 1 and isinstance(args[0], (list, tuple)): args = args[0] # R, G, B and A. if len(args) == 4: r, g, b, a = args[0], args[1], args[2], args[3] # R, G and B. elif len(args) == 3: r, g, b, a = args[0], args[1], args[2], 1 # Two values, grayscale and alpha. elif len(args) == 2: r, g, b, a = args[0], args[0], args[0], args[1] # One value, another color object. elif len(args) == 1 and isinstance(args[0], Color): r, g, b, a = args[0].r, args[0].g, args[0].b, args[0].a # One value, grayscale. elif len(args) == 1: r, g, b, a = args[0], args[0], args[0], 1 # No values or None, transparent black. elif len(args) == 0 or (len(args) == 1 and args[0] is None): r, g, b, a = 0, 0, 0, 0 # Transform to base 1: base = float(kwargs.get("base", 1.0)) if base != 1: r, g, b, a = [ch/base for ch in r, g, b, a] # Transform to color space RGB: colorspace = kwargs.get("colorspace") if colorspace and colorspace != RGB: if colorspace == HSB: r, g, b = hsb_to_rgb(r, g, b) if colorspace == XYZ: r, g, b = xyz_to_rgb(r, g, b) if colorspace == LAB: r, g, b = lab_to_rgb(r, g, b) list.__init__(self, [r, g, b, a]) self._dirty = False def __setitem__(self, i, v): list.__setitem__(self, i, v) self._dirty = True def _get_r(self): return self[0] def _get_g(self): return self[1] def _get_b(self): return self[2] def _get_a(self): return self[3] def _set_r(self, v): self[0] = v def _set_g(self, v): self[1] = v def _set_b(self, v): self[2] = v def _set_a(self, v): self[3] = v r = red = property(_get_r, _set_r) g = green = property(_get_g, _set_g) b = blue = property(_get_b, _set_b) a = alpha = property(_get_a, _set_a) def _get_rgb(self): return self[0], self[1], self[2] def _set_rgb(self, (r,g,b)): self[0] = r self[1] = g self[2] = b rgb = property(_get_rgb, _set_rgb) def _get_rgba(self): return self[0], self[1], self[2], self[3] def _set_rgba(self, (r,g,b,a)): self[0] = r self[1] = g self[2] = b self[3] = a rgba = property(_get_rgba, _set_rgba) def copy(self): return Color(self) def _apply(self): glColor4f(self[0], self[1], self[2], self[3] * _alpha) def __repr__(self): return "Color(%.3f, %.3f, %.3f, %.3f)" % \ (self[0], self[1], self[2], self[3]) def __eq__(self, clr): if not isinstance(clr, Color): return False return self[0] == clr[0] \ and self[1] == clr[1] \ and self[2] == clr[2] \ and self[3] == clr[3] def __ne__(self, clr): return not self.__eq__(clr) def map(self, base=1.0, colorspace=RGB): """ Returns a list of R,G,B,A values mapped to the given base, e.g. from 0-255 instead of 0.0-1.0 which is useful for setting image pixels. Other values than RGBA can be obtained by setting the colorspace (RGB/HSB/XYZ/LAB). """ r, g, b, a = self if colorspace != RGB: if colorspace == HSB: r, g, b = rgb_to_hsb(r, g, b) if colorspace == XYZ: r, g, b = rgb_to_xyz(r, g, b) if colorspace == LAB: r, g, b = rgb_to_lab(r, g, b) if base != 1: r, g, b, a = [ch*base for ch in r, g, b, a] if base != 1 and isinstance(base, int): r, g, b, a = [int(ch) for ch in r, g, b, a] return r, g, b, a def blend(self, clr, t=0.5, colorspace=RGB): """ Returns a new color between the two colors. Parameter t is the amount to interpolate between the two colors (0.0 equals the first color, 0.5 is half-way in between, etc.) Blending in CIE-LAB colorspace avoids "muddy" colors in the middle of the blend. """ ch = zip(self.map(1, colorspace)[:3], clr.map(1, colorspace)[:3]) r, g, b = [geometry.lerp(a, b, t) for a, b in ch] a = geometry.lerp(self.a, len(clr)==4 and clr[3] or 1, t) return Color(r, g, b, a, colorspace=colorspace) def rotate(self, angle): """ Returns a new color with it's hue rotated on the RYB color wheel. """ h, s, b = rgb_to_hsb(*self[:3]) h, s, b = rotate_ryb(h, s, b, angle) return Color(h, s, b, self.a, colorspace=HSB) color = Color def background(*args): """ Sets the current background color. """ global _background if args: _background = Color(*args) xywh = (GLint*4)(); glGetIntegerv(GL_VIEWPORT, xywh); x,y,w,h = xywh rect(x, y, w, h, fill=_background, stroke=None) return _background def fill(*args): """ Sets the current fill color for drawing primitives and paths. """ global _fill if args: _fill = Color(*args) return _fill fill(0) # The default fill is black. def stroke(*args, **kwargs): """ Sets the current stroke color. """ global _stroke if args: _stroke = Color(*args) return _stroke def nofill(): """ No current fill color. """ global _fill _fill = None def nostroke(): """ No current stroke color. """ global _stroke _stroke = None def strokewidth(width=None): """ Sets the outline stroke width. """ # Note: strokewidth is clamped to integers (e.g. 0.2 => 1), # but finer lines can be achieved visually with a transparent stroke. # Thicker strokewidth results in ugly (i.e. no) line caps. global _strokewidth if width is not None: _strokewidth = width glLineWidth(width) return _strokewidth SOLID = "solid" DOTTED = "dotted" DASHED = "dashed" def strokestyle(style=None): """ Sets the outline stroke style (SOLID / DOTTED / DASHED). """ global _strokestyle if style is not None and style != _strokestyle: _strokestyle = style glLineDash(style) return _strokestyle def glLineDash(style): if style == SOLID: glDisable(GL_LINE_STIPPLE) elif style == DOTTED: glEnable(GL_LINE_STIPPLE); glLineStipple(0, 0x0101) elif style == DASHED: glEnable(GL_LINE_STIPPLE); glLineStipple(1, 0x000F) def outputmode(mode=None): raise NotImplementedError def colormode(mode=None, range=1.0): raise NotImplementedError #--- COLOR SPACE ------------------------------------------------------------------------------------- # Transformations between RGB, HSB, CIE XYZ and CIE LAB color spaces. # http://www.easyrgb.com/math.php def rgb_to_hsb(r, g, b): """ Converts the given R,G,B values to H,S,B (between 0.0-1.0). """ h, s, v = 0, 0, max(r, g, b) d = v - min(r, g, b) if v != 0: s = d / float(v) if s != 0: if r == v: h = 0 + (g-b) / d elif g == v: h = 2 + (b-r) / d else : h = 4 + (r-g) / d h = h / 6.0 % 1 return h, s, v def hsb_to_rgb(h, s, v): """ Converts the given H,S,B color values to R,G,B (between 0.0-1.0). """ if s == 0: return v, v, v h = h % 1 * 6.0 i = floor(h) f = h - i x = v * (1-s) y = v * (1-s * f) z = v * (1-s * (1-f)) if i > 4: return v, x, y return [(v,z,x), (y,v,x), (x,v,z), (x,y,v), (z,x,v)][int(i)] def rgb_to_xyz(r, g, b): """ Converts the given R,G,B values to CIE X,Y,Z (between 0.0-1.0). """ r, g, b = [ch > 0.04045 and ((ch+0.055) / 1.055) ** 2.4 or ch / 12.92 for ch in r, g, b] r, g, b = [ch * 100.0 for ch in r, g, b] r, g, b = ( # Observer = 2, Illuminant = D65 r * 0.4124 + g * 0.3576 + b * 0.1805, r * 0.2126 + g * 0.7152 + b * 0.0722, r * 0.0193 + g * 0.1192 + b * 0.9505) return r/95.047, g/100.0, b/108.883 def xyz_to_rgb(x, y, z): """ Converts the given CIE X,Y,Z color values to R,G,B (between 0.0-1.0). """ x, y, z = x*95.047, y*100.0, z*108.883 x, y, z = [ch / 100.0 for ch in x, y, z] r = x * 3.2406 + y * -1.5372 + z * -0.4986 g = x * -0.9689 + y * 1.8758 + z * 0.0415 b = x * -0.0557 + y * -0.2040 + z * 1.0570 r, g, b = [ch > 0.0031308 and 1.055 * ch**(1/2.4) - 0.055 or ch * 12.92 for ch in r, g, b] return r, g, b def rgb_to_lab(r, g, b): """ Converts the given R,G,B values to CIE L,A,B (between 0.0-1.0). """ x, y, z = rgb_to_xyz(r, g, b) x, y, z = [ch > 0.008856 and ch**(1/3.0) or (ch*7.787) + (16/116.0) for ch in x, y, z] l, a, b = y*116-16, 500*(x-y), 200*(y-z) l, a, b = l/100.0, (a+86)/(86+98), (b+108)/(108+94) return l, a, b def lab_to_rgb(l, a, b): """ Converts the given CIE L,A,B color values to R,G,B (between 0.0-1.0). """ l, a, b = l*100, a*(86+98)-86, b*(108+94)-108 y = (l+16)/116.0 x = y + a/500.0 z = y - b/200.0 x, y, z = [ch**3 > 0.008856 and ch**3 or (ch-16/116.0)/7.787 for ch in x, y, z] return xyz_to_rgb(x, y, z) def luminance(r, g, b): """ Returns an indication (0.0-1.0) of how bright the color appears. """ return (r*0.2125 + g*0.7154 + b+0.0721) * 0.5 def darker(clr, step=0.2): """ Returns a copy of the color with a darker brightness. """ h, s, b = rgb_to_hsb(clr.r, clr.g, clr.b) r, g, b = hsb_to_rgb(h, s, max(0, b-step)) return Color(r, g, b, len(clr)==4 and clr[3] or 1) def lighter(clr, step=0.2): """ Returns a copy of the color with a lighter brightness. """ h, s, b = rgb_to_hsb(clr.r, clr.g, clr.b) r, g, b = hsb_to_rgb(h, s, min(1, b+step)) return Color(r, g, b, len(clr)==4 and clr[3] or 1) darken, lighten = darker, lighter #--- COLOR ROTATION ---------------------------------------------------------------------------------- # Approximation of the RYB color wheel. # In HSB, colors hues range from 0 to 360, # but on the color wheel these values are not evenly distributed. # The second tuple value contains the actual value on the wheel (angle). _colorwheel = [ ( 0, 0), ( 15, 8), ( 30, 17), ( 45, 26), ( 60, 34), ( 75, 41), ( 90, 48), (105, 54), (120, 60), (135, 81), (150, 103), (165, 123), (180, 138), (195, 155), (210, 171), (225, 187), (240, 204), (255, 219), (270, 234), (285, 251), (300, 267), (315, 282), (330, 298), (345, 329), (360, 360) ] def rotate_ryb(h, s, b, angle=180): """ Rotates the given H,S,B color (0.0-1.0) on the RYB color wheel. The RYB colorwheel is not mathematically precise, but focuses on aesthetically pleasing complementary colors. """ h = h*360 % 360 # Find the location (angle) of the hue on the RYB color wheel. for i in range(len(_colorwheel)-1): (x0, y0), (x1, y1) = _colorwheel[i], _colorwheel[i+1] if y0 <= h <= y1: a = geometry.lerp(x0, x1, t=(h-y0)/(y1-y0)) break # Rotate the angle and retrieve the hue. a = (a+angle) % 360 for i in range(len(_colorwheel)-1): (x0, y0), (x1, y1) = _colorwheel[i], _colorwheel[i+1] if x0 <= a <= x1: h = geometry.lerp(y0, y1, t=(a-x0)/(x1-x0)) break return h/360.0, s, b def complement(clr): """ Returns the color opposite on the color wheel. The complementary color contrasts with the given color. """ return clr.rotate(180) def analog(clr, angle=20, d=0.1): """ Returns a random adjacent color on the color wheel. Analogous color schemes can often be found in nature. """ h, s, b = rgb_to_hsb(*clr[:3]) h, s, b = rotate_ryb(h, s, b, angle=random(-1.0,1.0)) s *= 1 - random(-d,d) b *= 1 - random(-d,d) return Color(h, s, b, len(clr)==4 and clr[3] or 1, colorspace=HSB) #--- COLOR MIXIN ------------------------------------------------------------------------------------- # Drawing commands like rect() have optional parameters fill and stroke to set the color directly. def color_mixin(**kwargs): fill = kwargs.get("fill", _fill) stroke = kwargs.get("stroke", _stroke) strokewidth = kwargs.get("strokewidth", _strokewidth) strokestyle = kwargs.get("strokestyle", _strokestyle) return (fill, stroke, strokewidth, strokestyle) #--- COLOR PLANE ------------------------------------------------------------------------------------- # Not part of the standard API but too convenient to leave out. def colorplane(x, y, width, height, *a): """ Draws a rectangle that emits a different fill color from each corner. An optional number of colors can be given: - four colors define top left, top right, bottom right and bottom left, - three colors define top left, top right and bottom, - two colors define top and bottom, - no colors assumes black top and white bottom gradient. """ if len(a) == 2: # Top and bottom colors. clr1, clr2, clr3, clr4 = a[0], a[0], a[1], a[1] elif len(a) == 4: # Top left, top right, bottom right, bottom left. clr1, clr2, clr3, clr4 = a[0], a[1], a[2], a[3] elif len(a) == 3: # Top left, top right, bottom. clr1, clr2, clr3, clr4 = a[0], a[1], a[2], a[2] elif len(a) == 0: # Black top, white bottom. clr1 = clr2 = (0,0,0,1) clr3 = clr4 = (1,1,1,1) glPushMatrix() glTranslatef(x, y, 0) glScalef(width, height, 1) glBegin(GL_QUADS) glColor4f(clr1[0], clr1[1], clr1[2], clr1[3] * _alpha); glVertex2f(-0.0, 1.0) glColor4f(clr2[0], clr2[1], clr2[2], clr2[3] * _alpha); glVertex2f( 1.0, 1.0) glColor4f(clr3[0], clr3[1], clr3[2], clr3[3] * _alpha); glVertex2f( 1.0, -0.0) glColor4f(clr4[0], clr4[1], clr4[2], clr4[3] * _alpha); glVertex2f(-0.0, -0.0) glEnd() glPopMatrix() #===================================================================================================== #--- TRANSFORMATIONS --------------------------------------------------------------------------------- # Unlike NodeBox, all transformations are CORNER-mode and originate from the bottom-left corner. # Example: using Transform to get a transformed path. # t = Transform() # t.rotate(45) # p = BezierPath() # p.rect(10,10,100,70) # p = t.transform_path(p) # p.contains(x,y) # now we can check if the mouse is in the transformed shape. Transform = geometry.AffineTransform def push(): """ Pushes the transformation state. Subsequent transformations (translate, rotate, scale) remain in effect until pop() is called. """ glPushMatrix() def pop(): """ Pops the transformation state. This reverts the transformation to before the last push(). """ glPopMatrix() def translate(x, y): """ By default, the origin of the layer or canvas is at the bottom left. This origin point will be moved by (x,y) pixels. """ glTranslatef(round(x), round(y), 0) def rotate(degrees): """ Rotates the transformation state, i.e. all subsequent drawing primitives are rotated. Rotations work incrementally: calling rotate(60) and rotate(30) sets the current rotation to 90. """ glRotatef(degrees, 0, 0, 1) def scale(x, y=None): """ Scales the transformation state. """ if y is None: y = x glScalef(x, y, 1) def reset(): """ Resets the transform state of the layer or canvas. """ glLoadIdentity() CORNER = "corner" CENTER = "center" def transform(mode=None): if mode == CENTER: raise NotImplementedError, "no center-mode transform" return CORNER def skew(x, y): raise NotImplementedError #===================================================================================================== #--- DRAWING PRIMITIVES ------------------------------------------------------------------------------ # Drawing primitives: Point, line, rect, ellipse, arrow. star. # The fill and stroke are two different shapes put on top of each other. Point = geometry.Point def line(x0, y0, x1, y1, **kwargs): """ Draws a straight line from x0, y0 to x1, y1 with the current stroke color and strokewidth. """ fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs) if stroke is not None and strokewidth > 0: glColor4f(stroke[0], stroke[1], stroke[2], stroke[3] * _alpha) glLineWidth(strokewidth) glLineDash(strokestyle) glBegin(GL_LINE_LOOP) glVertex2f(x0, y0) glVertex2f(x1, y1) glEnd() def rect(x, y, width, height, **kwargs): """ Draws a rectangle with the bottom left corner at x, y. The current stroke, strokewidth and fill color are applied. """ fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs) for i, clr in enumerate((fill, stroke)): if clr is not None and (i==0 or strokewidth > 0): if i == 1: glLineWidth(strokewidth) glLineDash(strokestyle) glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha) # Note: this performs equally well as when using precompile(). glBegin((GL_POLYGON, GL_LINE_LOOP)[i]) glVertex2f(x, y) glVertex2f(x+width, y) glVertex2f(x+width, y+height) glVertex2f(x, y+height) glEnd() def triangle(x1, y1, x2, y2, x3, y3, **kwargs): """ Draws the triangle created by connecting the three given points. The current stroke, strokewidth and fill color are applied. """ fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs) for i, clr in enumerate((fill, stroke)): if clr is not None and (i==0 or strokewidth > 0): if i == 1: glLineWidth(strokewidth) glLineDash(strokestyle) glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha) # Note: this performs equally well as when using precompile(). glBegin((GL_POLYGON, GL_LINE_LOOP)[i]) glVertex2f(x1, y1) glVertex2f(x2, y2) glVertex2f(x3, y3) #glVertex2f(x, y+height) glEnd() _ellipses = {} ELLIPSE_SEGMENTS = 50 def ellipse(x, y, width, height, segments=ELLIPSE_SEGMENTS, **kwargs): """ Draws an ellipse with the center located at x, y. The current stroke, strokewidth and fill color are applied. """ if not segments in _ellipses: # For the given amount of line segments, calculate the ellipse once. # Then reuse the cached ellipse by scaling it to the desired size. _ellipses[segments] = [] for mode in (GL_POLYGON, GL_LINE_LOOP): _ellipses[segments].append(precompile(lambda:( glBegin(mode), [glVertex2f(cos(t)/2, sin(t)/2) for t in [2*pi*i/segments for i in range(segments)]], glEnd() ))) fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs) for i, clr in enumerate((fill, stroke)): if clr is not None and (i==0 or strokewidth > 0): if i == 1: glLineWidth(strokewidth) glLineDash(strokestyle) glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha) glPushMatrix() glTranslatef(x, y, 0) glScalef(width, height, 1) glCallList(_ellipses[segments][i]) glPopMatrix() oval = ellipse # Backwards compatibility. def arrow(x, y, width, **kwargs): """ Draws an arrow with its tip located at x, y. The current stroke, strokewidth and fill color are applied. """ head = width * 0.4 tail = width * 0.2 fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs) for i, clr in enumerate((fill, stroke)): if clr is not None and (i==0 or strokewidth > 0): if i == 1: glLineWidth(strokewidth) glLineDash(strokestyle) glColor4f(clr[0], clr[1], clr[2], clr[3] * _alpha) # Note: this performs equally well as when using precompile(). glBegin((GL_POLYGON, GL_LINE_LOOP)[i]) glVertex2f(x, y) glVertex2f(x-head, y+head) glVertex2f(x-head, y+tail) glVertex2f(x-width, y+tail) glVertex2f(x-width, y-tail) glVertex2f(x-head, y-tail) glVertex2f(x-head, y-head) glVertex2f(x, y) glEnd() def star(x, y, points=20, outer=100, inner=50, **kwargs): """ Draws a star with the given points, outer radius and inner radius. The current stroke, strokewidth and fill color are applied. """ # GL_POLYGON only works with convex polygons, # so we use a BezierPath (which does tessellation for fill colors). p = BezierPath(**kwargs) p.moveto(x, y+outer) for i in range(0, int(2*points)+1): r = (outer, inner)[i%2] a = pi*i/points p.lineto(x+r*sin(a), y+r*cos(a)) p.closepath() if kwargs.get("draw", True): p.draw() return p #===================================================================================================== #--- BEZIER PATH ------------------------------------------------------------------------------------- # A BezierPath class with lineto(), curveto() and moveto() commands. # It has all the path math functionality from NodeBox and a ray casting algorithm for contains(). # A number of caching mechanisms are used for performance: # drawn vertices, segment lengths, path bounds, and a hit test area for BezierPath.contains(). # For optimal performance, the path should be created once (not every frame) and left unmodified. # When points in the path are added, removed or modified, a _dirty flag is set. # When dirty, the cache will be cleared and the new path recalculated. # If the path is being drawn with a fill color, this means doing tessellation # (i.e. additional math for finding out if parts overlap and punch a hole in the shape). MOVETO = "moveto" LINETO = "lineto" CURVETO = "curveto" CLOSE = "close" RELATIVE = "relative" # Number of straight lines to represent a curve = 20% of curve length. RELATIVE_PRECISION = 0.2 class PathError(Exception): pass class NoCurrentPointForPath(Exception): pass class NoCurrentPath(Exception): pass class PathPoint(Point): def __init__(self, x=0, y=0): """ A control handle for PathElement. """ self._x = x self._y = y self._dirty = False def _get_x(self): return self._x def _set_x(self, v): self._x = v self._dirty = True def _get_y(self): return self._y def _set_y(self, v): self._y = v self._dirty = True x = property(_get_x, _set_x) y = property(_get_y, _set_y) def copy(self, parent=None): return PathPoint(self._x, self._y) class PathElement(object): def __init__(self, cmd=None, pts=None): """ A point in the path, optionally with control handles: - MOVETO : the list of points contains a single (x,y)-tuple. - LINETO : the list of points contains a single (x,y)-tuple. - CURVETO : the list of points contains (x,y), (vx1,vy1), (vx2,vy2) tuples. - CLOSETO : no points. """ if cmd == MOVETO \ or cmd == LINETO: pt, h1, h2 = pts[0], pts[0], pts[0] elif cmd == CURVETO: pt, h1, h2 = pts[2], pts[0], pts[1] else: pt, h1, h2 = (0,0), (0,0), (0,0) self._cmd = cmd self._x = pt[0] self._y = pt[1] self._ctrl1 = PathPoint(h1[0], h1[1]) self._ctrl2 = PathPoint(h2[0], h2[1]) self.__dirty = False def _get_dirty(self): return self.__dirty \ or self.ctrl1._dirty \ or self.ctrl2._dirty def _set_dirty(self, b): self.__dirty = b self.ctrl1._dirty = b self.ctrl2._dirty = b _dirty = property(_get_dirty, _set_dirty) @property def cmd(self): return self._cmd def _get_x(self): return self._x def _set_x(self, v): self._x = v self.__dirty = True def _get_y(self): return self._y def _set_y(self, v): self._y = v self.__dirty = True x = property(_get_x, _set_x) y = property(_get_y, _set_y) def _get_xy(self): return (self.x, self.y) def _set_xy(self, (x,y)): self.x = x self.y = y xy = property(_get_xy, _set_xy) # Handle 1 describes now the curve from the previous point started. def _get_ctrl1(self): return self._ctrl1 def _set_ctrl1(self, v): self._ctrl1 = PathPoint(v.x, v.y) self.__dirty = True # Handle 2 describes how the curve from the previous point arrives in this point. def _get_ctrl2(self): return self._ctrl2 def _set_ctrl2(self, v): self._ctrl2 = PathPoint(v.x, v.y) self.__dirty = True ctrl1 = property(_get_ctrl1, _set_ctrl1) ctrl2 = property(_get_ctrl2, _set_ctrl2) def __eq__(self, pt): if not isinstance(pt, PathElement): return False return self.cmd == pt.cmd \ and self.x == pt.x \ and self.y == pt.y \ and self.ctrl1 == pt.ctrl1 \ and self.ctrl2 == pt.ctrl2 def __ne__(self, pt): return not self.__eq__(pt) def __repr__(self): return "%s(cmd='%s', x=%.1f, y=%.1f, ctrl1=(%.1f, %.1f), ctrl2=(%.1f, %.1f))" % ( self.__class__.__name__, self.cmd, self.x, self.y, self.ctrl1.x, self.ctrl1.y, self.ctrl2.x, self.ctrl2.y) def copy(self): if self.cmd == MOVETO \ or self.cmd == LINETO: pts = ((self.x, self.y),) elif self.cmd == CURVETO: pts = ((self.ctrl1.x, self.ctrl1.y), (self.ctrl2.x, self.ctrl2.y), (self.x, self.y)) else: pts = None return PathElement(self.cmd, pts) class BezierPath(list): def __init__(self, path=None, **kwargs): """ A list of PathElements describing the curves and lines that make up the path. """ if isinstance(path, (BezierPath, list, tuple)): self.extend([pt.copy() for pt in path]) self._kwargs = kwargs self._cache = None # Cached vertices for drawing. self._segments = None # Cached segment lengths. self._bounds = None # Cached bounding rectangle. self._polygon = None # Cached polygon hit test area. self._dirty = False def copy(self): return BezierPath(self, **self._kwargs) def insert(self, i, pathelement): self._dirty = True; list.insert(self, i, pathelement) def append(self, pathelement): self._dirty = True; list.append(self, pathelement) def extend(self, pathelements): self._dirty = True; list.extend(self, pathelements) def remove(self, pathelement): self._dirty = True; list.remove(self, pathelement) def pop(self, i): self._dirty = True; list.pop(self, i) def __setitem__(self, i, pathelement): self._dirty = True; list.__setitem__(self, i, pathelement) def __delitem__(self, i): self._dirty = True; list.__delitem__(self, i) def sort(self): self._dirty = True; list.sort(self) def reverse(self): self._dirty = True; list.reverse(self) def _update(self): # Called from BezierPath.draw(). # If points were added or removed, clear the cache. b = self._dirty for pt in self: b = b or pt._dirty; pt._dirty = False if b: if self._cache is not None: if self._cache[0]: flush(self._cache[0]) if self._cache[1]: flush(self._cache[1]) self._cache = self._segments = self._bounds = self._polygon = None self._dirty = False def moveto(self, x, y): """ Adds a new point to the path at x, y. """ self.append(PathElement(MOVETO, ((x, y),))) def lineto(self, x, y): """ Adds a line from the previous point to x, y. """ self.append(PathElement(LINETO, ((x, y),))) def curveto(self, x1, y1, x2, y2, x3, y3): """ Adds a Bezier-curve from the previous point to x3, y3. The curvature is determined by control handles x1, y1 and x2, y2. """ self.append(PathElement(CURVETO, ((x1, y1), (x2, y2), (x3, y3)))) def arcto(self, x, y, radius=1, clockwise=True, short=False): """ Adds a number of Bezier-curves that draw an arc with the given radius to (x,y). The short parameter selects either the "long way" around or the "shortcut". """ x0, y0 = self[-1].x, self[-1].y phi = geometry.angle(x0,y0,x,y) for p in bezier.arcto(x0, y0, radius, radius, phi, short, not clockwise, x, y): f = len(p) == 2 and self.lineto or self.curveto f(*p) def closepath(self): """ Adds a line from the previous point to the last MOVETO. """ self.append(PathElement(CLOSE)) def rect(self, x, y, width, height, roundness=0.0): """ Adds a (rounded) rectangle to the path. Corner roundness can be given as a relative float or absolute int. """ if roundness <= 0: self.moveto(x, y) self.lineto(x+width, y) self.lineto(x+width, y+height) self.lineto(x, y+height) self.lineto(x, y) else: if isinstance(roundness, int): r = min(roundness, width/2, height/2) else: r = min(width, height) r = min(roundness, 1) * r * 0.5 self.moveto(x+r, y) self.lineto(x+width-r, y) self.arcto(x+width, y+r, radius=r, clockwise=False) self.lineto(x+width, y+height-r) self.arcto(x+width-r, y+height, radius=r, clockwise=False) self.lineto(x+r, y+height) self.arcto(x, y+height-r, radius=r, clockwise=False) self.lineto(x, y+r) self.arcto(x+r, y, radius=r, clockwise=False) def ellipse(self, x, y, width, height): """ Adds an ellipse to the path. """ w, h = width*0.5, height*0.5 k = 0.5522847498 # kappa: (-1 + sqrt(2)) / 3 * 4 self.moveto(x, y-h) # http://www.whizkidtech.redprince.net/bezier/circle/ self.curveto(x+w*k, y-h, x+w, y-h*k, x+w, y, ) self.curveto(x+w, y+h*k, x+w*k, y+h, x, y+h) self.curveto(x-w*k, y+h, x-w, y+h*k, x-w, y, ) self.curveto(x-w, y-h*k, x-w*k, y-h, x, y-h) self.closepath() oval = ellipse def arc(self, x, y, width, height, start=0, stop=90): """ Adds an arc to the path. The arc follows the ellipse defined by (x, y, width, height), with start and stop specifying what angle range to draw. """ w, h = width*0.5, height*0.5 for i, p in enumerate(bezier.arc(x-w, y-h, x+w, y+h, start, stop)): if i == 0: self.moveto(*p[:2]) self.curveto(*p[2:]) def flatten(self, precision=RELATIVE): """ Returns a list of contours, in which each contour is a list of (x,y)-tuples. The precision determines the number of straight lines to use as a substition for a curve. It can be a fixed number (int) or relative to the curve length (float or RELATIVE). """ if precision == RELATIVE: precision = RELATIVE_PRECISION contours = [[]] x0, y0 = None, None closeto = None for pt in self: if (pt.cmd == LINETO or pt.cmd == CURVETO) and x0 == y0 is None: raise NoCurrentPointForPathError elif pt.cmd == LINETO: contours[-1].append((x0, y0)) contours[-1].append((pt.x, pt.y)) elif pt.cmd == CURVETO: # Curves are interpolated from a number of straight line segments. # With relative precision, we use the (rough) curve length to determine the number of lines. x1, y1, x2, y2, x3, y3 = pt.ctrl1.x, pt.ctrl1.y, pt.ctrl2.x, pt.ctrl2.y, pt.x, pt.y if isinstance(precision, float): n = int(max(0, precision) * bezier.curvelength(x0, y0, x1, y1, x2, y2, x3, y3, 3)) else: n = int(max(0, precision)) if n > 0: xi, yi = x0, y0 for i in range(n+1): xj, yj, vx1, vy1, vx2, vy2 = bezier.curvepoint(float(i)/n, x0, y0, x1, y1, x2, y2, x3, y3) contours[-1].append((xi, yi)) contours[-1].append((xj, yj)) xi, yi = xj, yj elif pt.cmd == MOVETO: contours.append([]) # Start a new contour. closeto = pt elif pt.cmd == CLOSE and closeto is not None: contours[-1].append((x0, y0)) contours[-1].append((closeto.x, closeto.y)) x0, y0 = pt.x, pt.y return contours def draw(self, precision=RELATIVE, **kwargs): """ Draws the path. The precision determines the number of straight lines to use as a substition for a curve. It can be a fixed number (int) or relative to the curve length (float or RELATIVE). """ if len(kwargs) > 0: # Optional parameters in draw() overrule those set during initialization. kw = dict(self._kwargs) kw.update(kwargs) fill, stroke, strokewidth, strokestyle = color_mixin(**kw) else: fill, stroke, strokewidth, strokestyle = color_mixin(**self._kwargs) def _draw_fill(contours): # Drawing commands for the path fill (as triangles by tessellating the contours). v = geometry.tesselate(contours) glBegin(GL_TRIANGLES), for x, y in v: glVertex3f(x, y, 0) glEnd() def _draw_stroke(contours): # Drawing commands for the path stroke. for path in contours: glBegin(GL_LINE_STRIP) for x, y in path: glVertex2f(x, y) glEnd() self._update() # Remove the cache if points were modified. if self._cache is None \ or self._cache[0] is None and fill \ or self._cache[1] is None and stroke \ or self._cache[-1] != precision: # Calculate and cache the vertices as Display Lists. # If the path requires a fill color, it will have to be tessellated. if self._cache is not None: if self._cache[0]: flush(self._cache[0]) if self._cache[1]: flush(self._cache[1]) contours = self.flatten(precision) self._cache = [None, None, precision] if fill : self._cache[0] = precompile(_draw_fill, contours) if stroke : self._cache[1] = precompile(_draw_stroke, contours) if fill is not None: glColor4f(fill[0], fill[1], fill[2], fill[3] * _alpha) glCallList(self._cache[0]) if stroke is not None and strokewidth > 0: glColor4f(stroke[0], stroke[1], stroke[2], stroke[3] * _alpha) glLineWidth(strokewidth) glLineDash(strokestyle) glCallList(self._cache[1]) def angle(self, t): """ Returns the directional angle at time t (0.0-1.0) on the path. """ # The directed() enumerator is much faster but less precise. pt0, pt1 = t==0 and (self.point(t), self.point(t+0.001)) or (self.point(t-0.001), self.point(t)) return geometry.angle(pt0.x, pt0.y, pt1.x, pt1.y) def point(self, t): """ Returns the PathElement at time t (0.0-1.0) on the path. See the linear interpolation math in bezier.py. """ if self._segments is None: self._segments = bezier.length(self, segmented=True, n=10) return bezier.point(self, t, segments=self._segments) def points(self, amount=2, start=0.0, end=1.0): """ Returns a list of PathElements along the path. To omit the last point on closed paths: end=1-1.0/amount """ if self._segments is None: self._segments = bezier.length(self, segmented=True, n=10) return bezier.points(self, amount, start, end, segments=self._segments) def addpoint(self, t): """ Inserts a new PathElement at time t (0.0-1.0) on the path. """ self._segments = None bezier.insert_point(self, t) split = addpoint @property def length(self, precision=10): """ Returns an approximation of the total length of the path. """ return bezier.length(self, segmented=False, n=precision) @property def contours(self): """ Returns a list of contours (i.e. segments separated by a MOVETO) in the path. Each contour is a BezierPath object. """ return bezier.contours(self) @property def bounds(self, precision=100): """ Returns a (x, y, width, height)-tuple of the approximate path dimensions. """ # In _update(), traverse all the points and check if they have changed. # If so, the bounds must be recalculated. self._update() if self._bounds is None: l = t = float( "inf") r = b = float("-inf") for pt in self.points(precision): if pt.x < l: l = pt.x if pt.y < t: t = pt.y if pt.x > r: r = pt.x if pt.y > b: b = pt.y self._bounds = (l, t, r-l, b-t) return self._bounds def contains(self, x, y, precision=100): """ Returns True when point (x,y) falls within the contours of the path. """ bx, by, bw, bh = self.bounds if bx <= x <= bx+bw and \ by <= y <= by+bh: if self._polygon is None \ or self._polygon[1] != precision: self._polygon = [(pt.x,pt.y) for pt in self.points(precision)], precision # Ray casting algorithm: return geometry.point_in_polygon(self._polygon[0], x, y) return False def hash(self, state=None, decimal=1): """ Returns the path id, based on the position and handles of its PathElements. Two distinct BezierPath objects that draw the same path therefore have the same id. """ f = lambda x: int(x*10**decimal) # Format floats as strings with given decimal precision. id = [state] for pt in self: id.extend(( pt.cmd, f(pt.x), f(pt.y), f(pt.ctrl1.x), f(pt.ctrl1.y), f(pt.ctrl2.x), f(pt.ctrl2.y))) id = str(id) id = md5(id).hexdigest() return id def __repr__(self): return "BezierPath(%s)" % repr(list(self)) def __del__(self): # Note: it is important that __del__() is called since it unloads the cache from GPU. # BezierPath and PathElement should contain no circular references, e.g. no PathElement.parent. if hasattr(self, "_cache") and self._cache is not None and flush: if self._cache[0]: flush(self._cache[0]) if self._cache[1]: flush(self._cache[1]) def drawpath(path, **kwargs): """ Draws the given BezierPath (or list of PathElements). The current stroke, strokewidth and fill color are applied. """ if not isinstance(path, BezierPath): path = BezierPath(path) path.draw(**kwargs) _autoclosepath = True def autoclosepath(close=False): """ Paths constructed with beginpath() and endpath() are automatically closed. """ global _autoclosepath _autoclosepath = close _path = None def beginpath(x, y): """ Starts a new path at (x,y). The commands moveto(), lineto(), curveto() and closepath() can then be used between beginpath() and endpath() calls. """ global _path _path = BezierPath() _path.moveto(x, y) def moveto(x, y): """ Moves the current point in the current path to (x,y). """ if _path is None: raise NoCurrentPath _path.moveto(x, y) def lineto(x, y): """ Draws a line from the current point in the current path to (x,y). """ if _path is None: raise NoCurrentPath _path.lineto(x, y) def curveto(x1, y1, x2, y2, x3, y3): """ Draws a curve from the current point in the current path to (x3,y3). The curvature is determined by control handles x1, y1 and x2, y2. """ if _path is None: raise NoCurrentPath _path.curveto(x1, y1, x2, y2, x3, y3) def closepath(): """ Closes the current path with a straight line to the last MOVETO. """ if _path is None: raise NoCurrentPath _path.closepath() def endpath(draw=True, **kwargs): """ Draws and returns the current path. With draw=False, only returns the path so it can be manipulated and drawn with drawpath(). """ global _path, _autoclosepath if _path is None: raise NoCurrentPath if _autoclosepath is True: _path.closepath() if draw: _path.draw(**kwargs) p, _path = _path, None return p def findpath(points, curvature=1.0): """ Returns a smooth BezierPath from the given list of (x,y)-tuples. """ return bezier.findpath(points, curvature) Path = BezierPath #--- POINT ANGLES ------------------------------------------------------------------------------------ def directed(points): """ Returns an iterator that yields (angle, point)-tuples for the given list of points. The angle represents the direction of the point on the path. This works with BezierPath, Bezierpath.points, [pt1, pt2, pt2, ...] For example: for a, pt in directed(path.points(30)): push() translate(pt.x, pt.y) rotate(a) arrow(0, 0, 10) pop() This is useful if you want to have shapes following a path. To put text on a path, rotate the angle by +-90 to get the normal (i.e. perpendicular). """ p = list(points) n = len(p) for i, pt in enumerate(p): if 0 < i < n-1 and pt.__dict__.get("_cmd") == CURVETO: # For a point on a curve, the control handle gives the best direction. # For PathElement (fixed point in BezierPath), ctrl2 tells us how the curve arrives. # For DynamicPathElement (returnd from BezierPath.point()), ctrl1 tell how the curve arrives. ctrl = isinstance(pt, bezier.DynamicPathElement) and pt.ctrl1 or pt.ctrl2 angle = geometry.angle(ctrl.x, ctrl.y, pt.x, pt.y) elif 0 < i < n-1 and pt.__dict__.get("_cmd") == LINETO and p[i-1].__dict__.get("_cmd") == CURVETO: # For a point on a line preceded by a curve, look ahead gives better results. angle = geometry.angle(pt.x, pt.y, p[i+1].x, p[i+1].y) elif i == 0 and isinstance(points, BezierPath): # For the first point in a BezierPath, we can calculate a next point very close by. pt1 = points.point(0.001) angle = geometry.angle(pt.x, pt.y, pt1.x, pt1.y) elif i == n-1 and isinstance(points, BezierPath): # For the last point in a BezierPath, we can calculate a previous point very close by. pt0 = points.point(0.999) angle = geometry.angle(pt0.x, pt0.y, pt.x, pt.y) elif i == n-1 and isinstance(pt, bezier.DynamicPathElement) and pt.ctrl1.x != pt.x or pt.ctrl1.y != pt.y: angle = geometry.angle(pt.ctrl1.x, pt.ctrl1.y, pt.x, pt.y) elif 0 < i: # For any point, look back gives a good result, if enough points are given. angle = geometry.angle(p[i-1].x, p[i-1].y, pt.x, pt.y) elif i < n-1: # For the first point, the best (only) guess is the location of the next point. angle = geometry.angle(pt.x, pt.y, p[i+1].x, p[i+1].y) else: angle = 0 yield angle, pt #--- CLIPPING PATH ----------------------------------------------------------------------------------- class ClippingMask: def draw(self, fill=(0,0,0,1), stroke=None): pass def beginclip(path): """ Enables the given BezierPath (or ClippingMask) as a clipping mask. Drawing commands between beginclip() and endclip() are constrained to the shape of the path. """ # Enable the stencil buffer to limit the area of rendering (stenciling). glClear(GL_STENCIL_BUFFER_BIT) glEnable(GL_STENCIL_TEST) glStencilFunc(GL_NOTEQUAL, 0, 0) glStencilOp(GL_INCR, GL_INCR, GL_INCR) # Shouldn't depth testing be disabled when stencilling? # In any case, if it is, transparency doesn't work. #glDisable(GL_DEPTH_TEST) path.draw(fill=(0,0,0,1), stroke=None) # Disregard color settings; always use a black mask. #glEnable(GL_DEPTH_TEST) glStencilFunc(GL_EQUAL, 1, 1) glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP) def endclip(): glDisable(GL_STENCIL_TEST) #===================================================================================================== #--- IMAGE ------------------------------------------------------------------------------------------- # Textures and quad vertices are cached for performance. # Textures remain in cache for the duration of the program. # Quad vertices are cached as Display Lists and destroyed when the Image object is deleted. # For optimal performance, images should be created once (not every frame) and its quads left unmodified. # Performance should be comparable to (moving) pyglet.Sprites drawn in a batch. pow2 = [2**n for n in range(20)] # [1, 2, 4, 8, 16, 32, 64, ...] def ceil2(x): """ Returns the nearest power of 2 that is higher than x, e.g. 700 => 1024. """ for y in pow2: if y >= x: return y class ImageError(Exception): pass _texture_cache = {} # pyglet.Texture referenced by filename. _texture_cached = {} # pyglet.Texture.id is in keys once the image has been cached. def texture(img, data=None): """ Returns a (cached) texture from the given image filename or byte data. When a Image or Pixels object is given, returns the associated texture. """ # Image texture stored in cache, referenced by file path (or a custom id defined with cache()). if isinstance(img, (basestring, int)) and img in _texture_cache: return _texture_cache[img] # Image file path, load it, cache it, return texture. if isinstance(img, basestring): try: cache(img, pyglet.image.load(img).get_texture()) except IOError: raise ImageError, "can't load image from %s" % repr(img) return _texture_cache[img] # Image texture, return original. if isinstance(img, pyglet.image.Texture): return img # Image object, return image texture. # (if you use this to create a new image, the new image will do expensive caching as well). if isinstance(img, Image): return img.texture # Pixels object, return pixel texture. if isinstance(img, Pixels): return img.texture # Image data as byte string, load it, return texture. if isinstance(data, basestring): return pyglet.image.load("", file=StringIO(data)).get_texture() # Don't know how to handle this image. raise ImageError, "unknown image type: %s" % repr(img.__class__) def cache(id, texture): """ Store the given texture in cache, referenced by id (which can then be passed to image()). This is useful for procedurally rendered images (which are not stored in cache by default). """ if isinstance(texture, (Image, Pixels)): texture = texture.texture if not isinstance(texture, pyglet.image.Texture): raise ValueError, "can only cache texture, not %s" % repr(texture.__class__.__name__) _texture_cache[id] = texture _texture_cached[_texture_cache[id].id] = id def cached(texture): """ Returns the cache id if the texture has been cached (None otherwise). """ if isinstance(texture, (Image, Pixels)): texture = texture.texture if isinstance(texture, pyglet.image.Texture): return _texture_cached.get(texture.texture.id) if isinstance(texture, (basestring, int)): return texture in _texture_cache and texture or None return None def _render(texture, quad=(0,0,0,0,0,0,0,0)): """ Renders the texture on the canvas inside a quadtriliteral (i.e. rectangle). The quadtriliteral can be distorted by giving corner offset coordinates. """ t = texture.tex_coords # power-2 dimensions w = texture.width # See Pyglet programming guide -> OpenGL imaging. h = texture.height dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4 = quad or (0,0,0,0,0,0,0,0) glEnable(texture.target) glBindTexture(texture.target, texture.id) glBegin(GL_QUADS) glTexCoord3f(t[0], t[1], t[2] ); glVertex3f(dx4, dy4, 0) glTexCoord3f(t[3], t[4], t[5] ); glVertex3f(dx3+w, dy3, 0) glTexCoord3f(t[6], t[7], t[8] ); glVertex3f(dx2+w, dy2+h, 0) glTexCoord3f(t[9], t[10], t[11]); glVertex3f(dx1, dy1+h, 0) glEnd() glDisable(texture.target) class Quad(list): def __init__(self, dx1=0, dy1=0, dx2=0, dy2=0, dx3=0, dy3=0, dx4=0, dy4=0): """ Describes the four-sided polygon on which an image texture is "mounted". This is a quadrilateral (four sides) of which the vertices do not necessarily have a straight angle (i.e. the corners can be distorted). """ list.__init__(self, (dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4)) self._dirty = True # Image objects poll Quad._dirty to check if the image cache is outdated. def copy(self): return Quad(*self) def reset(self): list.__init__(self, (0,0,0,0,0,0,0,0)) self._dirty = True def __setitem__(self, i, v): list.__setitem__(self, i, v) self._dirty = True def _get_dx1(self): return self[0] def _get_dy1(self): return self[1] def _get_dx2(self): return self[2] def _get_dy2(self): return self[3] def _get_dx3(self): return self[4] def _get_dy3(self): return self[5] def _get_dx4(self): return self[6] def _get_dy4(self): return self[7] def _set_dx1(self, v): self[0] = v def _set_dy1(self, v): self[1] = v def _set_dx2(self, v): self[2] = v def _set_dy2(self, v): self[3] = v def _set_dx3(self, v): self[4] = v def _set_dy3(self, v): self[5] = v def _set_dx4(self, v): self[6] = v def _set_dy4(self, v): self[7] = v dx1 = property(_get_dx1, _set_dx1) dy1 = property(_get_dy1, _set_dy1) dx2 = property(_get_dx2, _set_dx2) dy2 = property(_get_dy2, _set_dy2) dx3 = property(_get_dx3, _set_dx3) dy3 = property(_get_dy3, _set_dy3) dx4 = property(_get_dx4, _set_dx4) dy4 = property(_get_dy4, _set_dy4) class Image(object): def __init__(self, path, x=0, y=0, width=None, height=None, alpha=1.0, data=None): """ A texture that can be drawn at a given position. The quadrilateral in which the texture is drawn can be distorted (slow, image cache is flushed). The image can be resized, colorized and its opacity can be set. """ self._src = (path, data) self._texture = texture(path, data=data) self._cache = None self.x = x self.y = y self.width = width or self._texture.width # Scaled width, Image.texture.width yields original width. self.height = height or self._texture.height # Scaled height, Image.texture.height yields original height. self.quad = Quad() self.color = Color(1.0, 1.0, 1.0, alpha) def copy(self, texture=None, width=None, height=None): img = texture is None \ and self.__class__(self._src[0], data=self._src[1]) \ or self.__class__(texture) img.x = self.x img.y = self.y img.width = self.width img.height = self.height img.quad = self.quad.copy() img.color = self.color.copy() if width is not None: img.width = width if height is not None: img.height = height return img @property def id(self): return self._texture.id @property def texture(self): return self._texture def _get_xy(self): return (self.x, self.y) def _set_xy(self, (x,y)): self.x = x self.y = y xy = property(_get_xy, _set_xy) def _get_size(self): return (self.width, self.height) def _set_size(self, (w,h)): self.width = w self.height = h size = property(_get_size, _set_size) def _get_alpha(self): return self.color[3] def _set_alpha(self, v): self.color[3] = v alpha = property(_get_alpha, _set_alpha) def distort(self, dx1=0, dy1=0, dx2=0, dy2=0, dx3=0, dy3=0, dx4=0, dy4=0): """ Adjusts the four-sided polygon on which an image texture is "mounted", by incrementing the corner coordinates with the given values. """ for i, v in enumerate((dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4)): if v != 0: self.quad[i] += v def adjust(r=1.0, g=1.0, b=1.0, a=1.0): """ Adjusts the image color by multiplying R,G,B,A channels with the given values. """ self.color[0] *= r self.color[1] *= g self.color[2] *= b self.color[3] *= a def draw(self, x=None, y=None, width=None, height=None, alpha=None, color=None, filter=None): """ Draws the image. The given parameters (if any) override the image's attributes. """ # Calculate and cache the quad vertices as a Display List. # If the quad has changed, update the cache. if self._cache is None or self.quad._dirty: flush(self._cache) self._cache = precompile(_render, self._texture, self.quad) self.quad._dirty = False # Given parameters override Image attributes. if x is None: x = self.x if y is None: y = self.y if width is None: width = self.width if height is None: height = self.height if color and len(color) < 4: color = color[0], color[1], color[2], 1.0 if color is None: color = self.color if alpha is not None: color = color[0], color[1], color[2], alpha if filter: filter.texture = self._texture # Register the current texture with the filter. filter.push() # Round position (x,y) to nearest integer to avoid sub-pixel rendering. # This ensures there are no visual artefacts on transparent borders (e.g. the "white halo"). # Halo can also be avoided by overpainting in the source image, but this requires some work: # http://technology.blurst.com/remove-white-borders-in-transparent-textures/ x = round(x) y = round(y) w = float(width) / self._texture.width h = float(height) / self._texture.height # Transform and draw the quads. glPushMatrix() glTranslatef(x, y, 0) glScalef(w, h, 0) glColor4f(color[0], color[1], color[2], color[3] * _alpha) glCallList(self._cache) glPopMatrix() if filter: filter.pop() def save(self, path): """ Exports the image as a PNG-file. """ self._texture.save(path) def __repr__(self): return "%s(x=%.1f, y=%.1f, width=%.1f, height=%.1f, alpha=%.2f)" % ( self.__class__.__name__, self.x, self.y, self.width, self.height, self.alpha) def __del__(self): if hasattr(self, "_cache") and self._cache is not None and flush: flush(self._cache) _IMAGE_CACHE = 200 _image_cache = {} # Image object referenced by Image.texture.id. _image_queue = [] # Most recent id's are at the front of the list. def image(img, x=None, y=None, width=None, height=None, alpha=None, color=None, filter=None, data=None, draw=True): """ Draws the image at (x,y), scaling it to the given width and height. The image's transparency can be set with alpha (0.0-1.0). Applies the given color adjustment, quad distortion and filter (one filter can be specified). Note: with a filter enabled, alpha and color will not be applied. This is because the filter overrides the default drawing behavior with its own. """ if not isinstance(img, Image): # If the given image is not an Image object, create one on the fly. # This object is cached for reuse. # The cache has a limited size (200), so the oldest Image objects are deleted. t = texture(img, data=data) if t.id in _image_cache: img = _image_cache[t.id] else: img = Image(img, data=data) _image_cache[img.texture.id] = img _image_queue.insert(0, img.texture.id) for id in reversed(_image_queue[_IMAGE_CACHE:]): del _image_cache[id] del _image_queue[-1] # Draw the image. if draw: img.draw(x, y, width, height, alpha, color, filter) return img def imagesize(img): """ Returns a (width, height)-tuple with the image dimensions. """ t = texture(img) return (t.width, t.height) def crop(img, x=0, y=0, width=None, height=None): """ Returns the given (x, y, width, height)-region from the image. Use this to pass cropped image files to image(). """ t = texture(img) if width is None: width = t.width if height is None: height = t.height t = t.get_region(x, y, min(t.width-x, width), min(t.height-y, height)) if isinstance(img, Image): img = img.copy(texture=t) return img.copy(texture=t, width=t.width, height=t.height) if isinstance(img, Pixels): return Pixels(t) if isinstance(img, pyglet.image.Texture): return t return Image(t) #--- PIXELS ------------------------------------------------------------------------------------------ class Pixels(list): def __init__(self, img): """ A list of RGBA color values (0-255) for each pixel in the given image. The Pixels object can be passed to the image() command. """ self._img = texture(img).get_image_data() # A negative pitch means the pixels are stored top-to-bottom row. self._flipped = self._img.pitch >= 0 # Data yields a byte array if no conversion (e.g. BGRA => RGBA) was necessary, # or a byte string otherwise - which needs to be converted to a list of ints. data = self._img.get_data("RGBA", self._img.width*4 * (-1,1)[self._flipped]) if isinstance(data, str): data = map(ord, list(data)) # Some formats seem to store values from -1 to -256. data = [(256+v)%256 for v in data] self.array = data self._texture = None @property def width(self): return self._img.width @property def height(self): return self._img.height @property def size(self): return (self.width, self.height) def __len__(self): return len(self.array) / 4 def __iter__(self): for i in xrange(len(self)): yield self[i] def __getitem__(self, i): """ Returns a list of R,G,B,A channel values between 0-255 from pixel i. Users need to wrap the list in a Color themselves for performance. - r,g,b,a = Pixels[i] - clr = color(Pixels[i], base=255) """ return self.array[i*4:i*4+4] def __setitem__(self, i, v): """ Sets pixel i to the given R,G,B,A values. Users need to unpack a Color themselves for performance, and are resposible for keeping channes values between 0 and 255 (otherwise an error will occur when Pixels.update() is called), - Pixels[i] = r,g,b,a - Pixels[i] = clr.map(base=255) """ for j in range(4): self.array[i*4+j] = v[j] def __getslice__(self, i, j): return [self[i+n] for n in xrange(j-i)] def __setslice__(self, i, j, seq): for n in xrange(j-i): self[i+n] = seq[n] def map(self, function): """ Applies a function to each pixel. Function takes a list of R,G,B,A channel values and must return a similar list. """ for i in xrange(len(self)): self[i] = function(self[i]) def get(self, i, j): """ Returns the pixel at row i, column j as a Color object. """ if 0 <= i < self.width and 0 <= j < self.height: return color(self[i+j*self.width], base=255) def set(self, i, j, clr): """ Sets the pixel at row i, column j from a Color object. """ if 0 <= i < self.width and 0 <= j < self.height: self[i+j*self.width] = clr.map(base=255) def update(self): """ Pixels.update() must be called to refresh the image. """ data = self.array data = "".join(map(chr, data)) self._img.set_data("RGBA", self._img.width*4*(-1,1)[self._flipped], data) self._texture = self._img.get_texture() @property def texture(self): if self._texture is None: self.update() return self._texture def copy(self): return Pixels(self.texture) def __repr__(self): return "%s(width=%.1f, height=%.1f)" % ( self.__class__.__name__, self.width, self.height) pixels = Pixels #--- ANIMATION --------------------------------------------------------------------------------------- # A sequence of images displayed in a loop. # Useful for storing pre-rendered effect frames like explosions etc. class Animation(list): def __init__(self, images=[], duration=None, loop=False, **kwargs): """ Constructs an animation loop from the given image frames. The duration specifies the time for the entire animation to run. Animations are useful to cache effects like explosions, that have for example been prepared in an offscreen buffer. """ list.__init__(self, list(images)) self.duration = duration # Duration of the entire animation. self.loop = loop # Loop from last frame to first frame? self._i = -1 # Frame counter. self._t = Transition(0, interpolation=kwargs.get("interpolation", LINEAR)) def copy(self, **kwargs): return Animation(self, duration = kwargs.get("duration", self.duration), loop = kwargs.get("loop", self.loop), interpolation = self._t._interpolation) def update(self): if self.duration is not None: # With a duration, # skip to a next frame so that the entire animation takes the given time. if self._i < 0 or self.loop and self._i == len(self)-1: self._t.set(0, 0) self._t.update() self._t.set(len(self)-1, self.duration) self._t.update() self._i = int(self._t.current) else: # Without a duration, # Animation.update() simply moves to the next frame. if self._i < 0 or self.loop and self._i == len(self)-1: self._i = -1 self._i = min(self._i+1, len(self)-1) @property def frames(self): return self @property def frame(self): # Yields the current frame Image (or None). try: return self[self._i] except: return None @property def done(self): # Yields True when the animation has stopped (or hasn't started). return self.loop is False and self._i == len(self)-1 def draw(self, *args, **kwargs): if not self.done: image(self.frame, *args, **kwargs) def __repr__(self): return "%s(frames=%i, duration=%s)" % ( self.__class__.__name__, len(self), repr(self.duration)) animation = Animation #--- OFFSCREEN RENDERING ----------------------------------------------------------------------------- # Offscreen buffers can be used to render images from paths etc. # or to apply filters on images before drawing them to the screen. # There are several ways to draw offscreen: # - render(img, filter): applies the given filter to the image and returns it. # - procedural(function, width, height): execute the drawing commands in function inside an image. # - Create your own subclass of OffscreenBuffer with a draw() method: # class MyBuffer(OffscreenBuffer): # def draw(self): pass # - Define drawing commands between OffscreenBuffer.push() and pop(): # b = MyBuffer() # b.push() # # drawing commands # b.pop() # img = Image(b.render()) # # The shader.py module already defines several filters that use an offscreen buffer, for example: # blur(), adjust(), multiply(), twirl(), ... # # The less you change about an offscreen buffer, the faster it runs. # This includes switching it on and off and changing its size. from shader import * #===================================================================================================== #--- FONT -------------------------------------------------------------------------------------------- def install_font(ttf): """ Loads the given TrueType font from file, and returns True on success. """ try: pyglet.font.add_file(ttf) return True except: # This might fail with Carbon on 64-bit Mac systems. # Fonts can be installed on the system manually if this is the case. return False # Load the platform-independent fonts shipped with NodeBox. # The default font is Droid (licensed under Apache 2.0). try: for f in glob(path.join(path.dirname(__file__), "..", "font", "*")): install_font(f) DEFAULT_FONT = "Droid Sans" except: DEFAULT_FONT = "Arial" # Font weight NORMAL = "normal" BOLD = "bold" ITALIC = "italic" # Text alignment LEFT = "left" RIGHT = "right" CENTER = "center" _fonts = [] # Custom fonts loaded from file. _fontname = DEFAULT_FONT # Current state font name. _fontsize = 12 # Current state font size. _fontweight = [False, False] # Current state font weight (bold, italic). _lineheight = 1.0 # Current state text lineheight. _align = LEFT # Current state text alignment (LEFT/RIGHT/CENTER). def font(fontname=None, fontsize=None, fontweight=None, file=None): """ Sets the current font and/or fontsize. If a filename is also given, loads the fontname from the given font file. """ global _fontname, _fontsize if file is not None and file not in _fonts: _fonts.append(file); install_font(file) if fontname is not None: _fontname = fontname if fontsize is not None: _fontsize = fontsize if fontweight is not None: _fontweight_(fontweight) # _fontweight_() is just an alias for fontweight(). return _fontname def fontname(name=None): """ Sets the current font used when drawing text. """ global _fontname if name is not None: _fontname = name return _fontname def fontsize(size=None): """ Sets the current fontsize in points. """ global _fontsize if size is not None: _fontsize = size return _fontsize def fontweight(*args, **kwargs): """ Sets the current font weight. You can supply NORMAL, BOLD and/or ITALIC or set named parameters bold=True and/or italic=True. """ global _fontweight if len(args) == 1 and isinstance(args, (list, tuple)): args = args[0] if NORMAL in args: _fontweight = [False, False] if BOLD in args or kwargs.get(BOLD): _fontweight[0] = True if ITALIC in args or kwargs.get(ITALIC): _fontweight[1] = True return _fontweight _fontweight_ = fontweight def lineheight(size=None): """ Sets the vertical spacing between lines of text. The given size is a relative value: lineheight 1.2 for fontsize 10 means 12. """ global _lineheight if size is not None: _lineheight = size return _lineheight def align(mode=None): """ Sets the alignment of text paragrapgs (LEFT, RIGHT or CENTER). """ global _align if mode is not None: _align = mode return _align #--- FONT MIXIN -------------------------------------------------------------------------------------- # The text() command has optional parameters font, fontsize, fontweight, bold, italic, lineheight and align. def font_mixin(**kwargs): fontname = kwargs.get("fontname", kwargs.get("font", _fontname)) fontsize = kwargs.get("fontsize", _fontsize) bold = kwargs.get("bold", BOLD in kwargs.get("fontweight", "") or _fontweight[0]) italic = kwargs.get("italic", ITALIC in kwargs.get("fontweight", "") or _fontweight[1]) lineheight = kwargs.get("lineheight", _lineheight) align = kwargs.get("align", _align) return (fontname, fontsize, bold, italic, lineheight, align) #--- TEXT -------------------------------------------------------------------------------------------- # Text is cached for performance. # For optimal performance, texts should be created once (not every frame) and left unmodified. # Dynamic texts use a cache of recycled Text objects. # pyglet.text.Label leaks memory when deleted, because its old batch continues to reference # loaded font/fontsize/bold/italic glyphs. # Adding all labels to our own batch remedies this. _label_batch = pyglet.graphics.Batch() def label(str="", width=None, height=None, **kwargs): """ Returns a drawable pyglet.text.Label object from the given string. Optional arguments include: font, fontsize, bold, italic, align, lineheight, fill. If these are omitted the current state is used. """ fontname, fontsize, bold, italic, lineheight, align = font_mixin(**kwargs) fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs) fill = fill is None and (0,0,0,0) or fill # We use begin_update() so that the TextLayout doesn't refresh on each update. # FormattedDocument allows individual styling of characters - see Text.style(). label = pyglet.text.Label(batch=_label_batch) label.begin_update() label.document = pyglet.text.document.FormattedDocument(str) label.width = width label.height = height label.font_name = fontname label.font_size = fontsize label.bold = bold label.italic = italic label.multiline = True label.anchor_y = "bottom" label.set_style("align", align) label.set_style("line_spacing", lineheight * fontsize) label.color = [int(ch*255) for ch in fill] label.end_update() return label class Text(object): def __init__(self, str, x=0, y=0, width=None, height=None, **kwargs): """ A formatted string of text that can be drawn at a given position. Text has the following properties: text, x, y, width, height, font, fontsize, bold, italic, lineheight, align, fill. Individual character ranges can be styled with Text.style(). """ if width is None: # Supplying a string with "\n" characters will crash if no width is given. # On the outside it appears as None but inside we use a very large number. width = geometry.INFINITE a, kwargs["align"] = kwargs.get("align", _align), LEFT else: a = None self.__dict__["x"] = x self.__dict__["y"] = y self.__dict__["_label"] = label(str, width, height, **kwargs) self.__dict__["_dirty"] = False self.__dict__["_align"] = a self.__dict__["_fill"] = None def _get_xy(self): return (self.x, self.y) def _set_xy(self, (x,y)): self.x = x self.y = y xy = property(_get_xy, _set_xy) def _get_size(self): return (self.width, self.height) def _set_size(self, (w,h)): self.width = w self.height = h size = property(_get_size, _set_size) def __getattr__(self, k): if k in self.__dict__: return self.__dict__[k] elif k in ("text", "height", "bold", "italic"): return getattr(self._label, k) elif k == "width": if self._label.width != geometry.INFINITE: return self._label.width elif k in ("font", "fontname"): return self._label.font_name elif k == "fontsize": return self._label.font_size elif k == "fontweight": return ((None, BOLD)[self._label.bold], (None, ITALIC)[self._label.italic]) elif k == "lineheight": return self._label.get_style("line_spacing") / (self.fontsize or 1) elif k == "align": if not self._align: self._align = self._label.get_style(k) return self._align elif k == "fill": if not self._fill: self._fill = Color([ch/255.0 for ch in self._label.color]) return self._fill else: raise AttributeError, "'Text' object has no attribute '%s'" % k def __setattr__(self, k, v): if k in self.__dict__: self.__dict__[k] = v; return # Setting properties other than x and y requires the label's layout to be updated. self.__dict__["_dirty"] = True self._label.begin_update() if k in ("text", "height", "bold", "italic"): setattr(self._label, k, v) elif k == "width": self._label.width = v is None and geometry.INFINITE or v elif k in ("font", "fontname"): self._label.font_name = v elif k == "fontsize": self._label.font_size = v elif k == "fontweight": self._label.bold, self._label.italic = BOLD in v, ITALIC in v elif k == "lineheight": self._label.set_style("line_spacing", v * (self.fontsize or 1)) elif k == "align": self._align = v self._label.set_style(k, self._label.width == geometry.INFINITE and LEFT or v) elif k == "fill": self._fill = v self._label.color = [int(255*ch) for ch in self._fill or (0,0,0,0)] else: raise AttributeError, "'Text' object has no attribute '%s'" % k def _update(self): # Called from Text.draw(), Text.copy() and Text.metrics. # Ensures that all the color changes have been reflected in Text._label. # If necessary, recalculates the label's layout (happens in end_update()). if hasattr(self._fill, "_dirty") and self._fill._dirty: self.fill = self._fill self._fill._dirty = False if self._dirty: self._label.end_update() self._dirty = False @property def path(self): raise NotImplementedError @property def metrics(self): """ Yields a (width, height)-tuple of the actual text content. """ self._update() return self._label.content_width, self._label.content_height def draw(self, x=None, y=None): """ Draws the text. """ # Given parameters override Text attributes. if x is None: x = self.x if y is None: y = self.y # Fontsize is rounded, and fontsize 0 will output a default font. # Therefore, we don't draw text with a fontsize smaller than 0.5. if self._label.font_size >= 0.5: glPushMatrix() glTranslatef(x, y, 0) self._update() self._label.draw() glPopMatrix() def copy(self): self._update() txt = Text(self.text, self.x, self.y, self.width, self.height, fontname = self.fontname, fontsize = self.fontsize, bold = self.bold, italic = self.italic, lineheight = self.lineheight, align = self.align, fill = self.fill ) # The individual character styling is retrieved from Label.document._style_runs. # Traverse it and set the styles in the new text. txt._label.begin_update() for k in self._label.document._style_runs: for i, j, v in self._label.document._style_runs[k]: txt.style(i,j, **{k:v}) txt._label.end_update() return txt def style(self, i, j, **kwargs): """ Defines the styling for a range of characters in the text. Valid arguments can include: font, fontsize, bold, italic, lineheight, align, fill. For example: text.style(0, 10, bold=True, fill=color(1,0,0)) """ attributes = {} for k,v in kwargs.items(): if k in ("font", "fontname"): attributes["font_name"] = v elif k == "fontsize": attributes["font_size"] = v elif k in ("bold", "italic", "align"): attributes[k] = v elif k == "fontweight": attributes.setdefault("bold", BOLD in v) attributes.setdefault("italic", ITALIC in v) elif k == "lineheight": attributes["line_spacing"] = v * self._label.font_size elif k == "fill": attributes["color"] = [int(ch*255) for ch in v] else: attributes[k] = v self._dirty = True self._label.begin_update() self._label.document.set_style(i, j, attributes) def __len__(self): return len(self.text) def __del__(self): if hasattr(self, "_label") and self._label: self._label.delete() _TEXT_CACHE = 200 _text_cache = {} _text_queue = [] def text(str, x=None, y=None, width=None, height=None, draw=True, **kwargs): """ Draws the string at the given position, with the current font(). Lines of text will span the given width before breaking to the next line. The text will be displayed with the current state font(), fontsize(), fontweight(), etc. When the given text is a Text object, the state will not be applied. """ if isinstance(str, Text) and width is None and height is None and len(kwargs) == 0: txt = str else: # If the given text is not a Text object, create one on the fly. # Dynamic Text objects are cached by (font, fontsize, bold, italic), # and those that are no longer referenced by the user are recycled. # Changing Text properties is still faster than creating a new Text. # The cache has a limited size (200), so the oldest Text objects are deleted. fontname, fontsize, bold, italic, lineheight, align = font_mixin(**kwargs) fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs) id = (fontname, int(fontsize), bold, italic) recycled = False if id in _text_cache: for txt in _text_cache[id]: # Reference count 3 => Python, _text_cache[id], txt. # No other variables are referencing the text, so we can recycle it. if getrefcount(txt) == 3: txt.text = str txt.x = x or 0 txt.y = y or 0 txt.width = width txt.height = height txt.lineheight = lineheight txt.align = align txt.fill = fill recycled = True break if not recycled: txt = Text(str, x or 0, y or 0, width, height, **kwargs) _text_cache.setdefault(id, []) _text_cache[id].append(txt) _text_queue.insert(0, id) for id in reversed(_text_queue[_TEXT_CACHE:]): del _text_cache[id][0] del _text_queue[-1] if draw: txt.draw(x, y) return txt def textwidth(txt, **kwargs): """ Returns the width of the given text. """ if not isinstance(txt, Text) or len(kwargs) > 0: kwargs["draw"] = False txt = text(txt, 0, 0, **kwargs) return txt.metrics[0] def textheight(txt, width=None, **kwargs): """ Returns the height of the given text. """ if not isinstance(txt, Text) or len(kwargs) > 0 or width != txt.width: kwargs["draw"] = False txt = text(txt, 0, 0, width=width, **kwargs) return txt.metrics[1] def textmetrics(txt, width=None, **kwargs): """ Returns a (width, height)-tuple for the given text. """ if not isinstance(txt, Text) or len(kwargs) > 0 or width != txt.width: kwargs["draw"] = False txt = text(txt, 0, 0, width=width, **kwargs) return txt.metrics #--- TEXTPATH ---------------------------------------------------------------------------------------- class GlyphPathError(Exception): pass import cPickle glyphs = {} try: # Load cached font glyph path information from nodebox/font/glyph.p. # By default, it has glyph path info for Droid Sans, Droid Sans Mono, Droid Serif. glyphs = path.join(path.dirname(__file__), "..", "font", "glyph.p") glyphs = cPickle.load(open(glyphs)) except: pass def textpath(string, x=0, y=0, **kwargs): """ Returns a BezierPath from the given text string. The fontname, fontsize and fontweight can be given as optional parameters, width, height, lineheight and align are ignored. Only works with ASCII characters in the default fonts (Droid Sans, Droid Sans Mono, Droid Serif, Arial). See nodebox/font/glyph.py on how to activate other fonts. """ fontname, fontsize, bold, italic, lineheight, align = font_mixin(**kwargs) w = bold and italic and "bold italic" or bold and "bold" or italic and "italic" or "normal" p = BezierPath() f = fontsize / 1000.0 for ch in string: #try: glyph = glyphs[fontname][w][ch] glyph = glyphs[fontname][w][ch] #except: # print fontname # raise GlyphPathError, "no glyph path information for %s %s '%s'" % (w, fontname, ch) for pt in glyph: if pt[0] == MOVETO: p.moveto(x+pt[1]*f, y-pt[2]*f) elif pt[0] == LINETO: p.lineto(x+pt[1]*f, y-pt[2]*f) elif pt[0] == CURVETO: p.curveto(x+pt[3]*f, y-pt[4]*f, x+pt[5]*f, y-pt[6]*f, x+pt[1]*f, y-pt[2]*f) elif pt[0] == CLOSE: p.closepath() x += textwidth(ch, font=fontname, fontsize=fontsize, bold=bold, italic=italic) return p #===================================================================================================== #--- UTILITIES --------------------------------------------------------------------------------------- _RANDOM_MAP = [90.0, 9.00, 4.00, 2.33, 1.50, 1.00, 0.66, 0.43, 0.25, 0.11, 0.01] def _rnd_exp(bias=0.5): bias = max(0, min(bias, 1)) * 10 i = int(floor(bias)) # bias*10 => index in the _map curve. n = _RANDOM_MAP[i] # If bias is 0.3, rnd()**2.33 will average 0.3. if bias < 10: n += (_RANDOM_MAP[i+1]-n) * (bias-i) return n def random(v1=1.0, v2=None, bias=None): """ Returns a number between v1 and v2, including v1 but not v2. The bias (0.0-1.0) represents preference towards lower or higher numbers. """ if v2 is None: v1, v2 = 0, v1 if bias is None: r = rnd() else: r = rnd()**_rnd_exp(bias) x = r * (v2-v1) + v1 if isinstance(v1, int) and isinstance(v2, int): x = int(x) return x def grid(cols, rows, colwidth=1, rowheight=1, shuffled=False): """ Yields (x,y)-tuples for the given number of rows and columns. The space between each point is determined by colwidth and colheight. """ rows = range(int(rows)) cols = range(int(cols)) if shuffled: shuffle(rows) shuffle(cols) for y in rows: for x in cols: yield (x*colwidth, y*rowheight) def files(path="*"): """ Returns a list of files found at the given path. """ return glob(path) #===================================================================================================== #--- PROTOTYPE ---------------------------------------------------------------------------------------- class Prototype(object): def __init__(self): """ A base class that allows on-the-fly extension. This means that external functions can be bound to it as methods, and properties set at runtime are copied correctly. Prototype can handle: - functions (these become class methods), - immutable types (str, unicode, int, long, float, bool), - lists, tuples and dictionaries of immutable types, - objects with a copy() method. """ self._dynamic = {} def _deepcopy(self, value): if isinstance(value, FunctionType): return instancemethod(value, self) elif hasattr(value, "copy"): return value.copy() elif isinstance(value, (list, tuple)): return [self._deepcopy(x) for x in value] elif isinstance(value, dict): return dict([(k, self._deepcopy(v)) for k,v in value.items()]) elif isinstance(value, (str, unicode, int, long, float, bool)): return value else: # Biggest problem here is how to find/relink circular references. raise TypeError, "Prototype can't bind %s." % str(value.__class__) def _bind(self, key, value): """ Adds a new method or property to the prototype. For methods, the given function is expected to take the object (i.e. self) as first parameter. For properties, values can be: list, tuple, dict, str, unicode, int, long, float, bool, or an object with a copy() method. For example, we can define a Layer's custom draw() method in two ways: - By subclassing: class MyLayer(Layer): def draw(layer): pass layer = MyLayer() layer.draw() - By function binding: def my_draw(layer): pass layer = Layer() layer._bind("draw", my_draw) layer.draw() """ self._dynamic[key] = value object.__setattr__(self, key, self._deepcopy(value)) def set_method(self, function, name=None): """ Creates a dynamic method (with the given name) from the given function. """ if not name: name = function.__name__ self._bind(name, function) def set_property(self, key, value): """ Adds a property to the prototype. Using this method ensures that dynamic properties are copied correctly - see inherit(). """ self._bind(key, value) def inherit(self, prototype): """ Inherit all the dynamic properties and methods of another prototype. """ for k,v in prototype._dynamic.items(): self._bind(k,v) #===================================================================================================== #--- EVENT HANDLER ------------------------------------------------------------------------------------ class EventHandler: def __init__(self): # Use __dict__ directly so we can do multiple inheritance in combination with Prototype: self.__dict__["enabled"] = True # Receive events from the canvas? self.__dict__["focus"] = False # True when this object receives the focus. self.__dict__["pressed"] = False # True when the mouse is pressed on this object. self.__dict__["dragged"] = False # True when the mouse is dragged on this object. self.__dict__["_queue"] = [] def on_mouse_enter(self, mouse): pass def on_mouse_leave(self, mouse): pass def on_mouse_motion(self, mouse): pass def on_mouse_press(self, mouse): pass def on_mouse_release(self, mouse): pass def on_mouse_drag(self, mouse): pass def on_mouse_scroll(self, mouse): pass def on_key_press(self, key): pass def on_key_release(self, key): pass # Instead of calling an event directly it could be queued, # e.g. layer.queue_event(layer.on_mouse_press, canvas.mouse). # layer.process_events() can then be called whenever desired, # e.g. after the canvas has been drawn so that events can contain drawing commands. def queue_event(self, event, *args): self._queue.append((event, args)) def process_events(self): for event, args in self._queue: event(*args) self._queue = [] # Note: there is no event propagation. # Event propagation means that, for example, if a layer is pressed # all its child (or parent) layers receive an on_mouse_press() event as well. # If this kind of behavior is desired, it is the responsibility of custom subclasses of Layer. #===================================================================================================== #--- TRANSITION -------------------------------------------------------------------------------------- # Transition.update() will tween from the last value to transition.set() new value in the given time. # Transitions are used as attributes (e.g. position, rotation) for the Layer class. TIME = 0 # the current time in this frame changes when the canvas is updated LINEAR = "linear" SMOOTH = "smooth" class Transition(object): def __init__(self, value, interpolation=SMOOTH): self._v0 = value # Previous value => Transition.start. self._vi = value # Current value => Transition.current. self._v1 = value # Desired value => Transition.stop. self._t0 = TIME # Start time. self._t1 = TIME # End time. self._interpolation = interpolation def copy(self): t = Transition(None) t._v0 = self._v0 t._vi = self._vi t._v1 = self._v1 t._t0 = self._t0 t._t1 = self._t1 t._interpolation = self._interpolation return t def get(self): """ Returns the transition stop value. """ return self._v1 def set(self, value, duration=1.0): """ Sets the transition stop value, which will be reached in the given duration (seconds). Calling Transition.update() moves the Transition.current value toward Transition.stop. """ if duration == 0: # If no duration is given, Transition.start = Transition.current = Transition.stop. self._vi = value self._v1 = value self._v0 = self._vi self._t0 = TIME # Now. self._t1 = TIME + duration @property def start(self): return self._v0 @property def stop(self): return self._v1 @property def current(self): return self._vi @property def done(self): return TIME >= self._t1 def update(self): """ Calculates the new current value. Returns True when done. The transition approaches the desired value according to the interpolation: - LINEAR: even transition over the given duration time, - SMOOTH: transition goes slower at the beginning and end. """ if TIME >= self._t1 or self._vi is None: self._vi = self._v1 return True else: # Calculate t: the elapsed time as a number between 0.0 and 1.0. t = (TIME-self._t0) / (self._t1-self._t0) if self._interpolation == LINEAR: self._vi = self._v0 + (self._v1-self._v0) * t else: self._vi = self._v0 + (self._v1-self._v0) * geometry.smoothstep(0.0, 1.0, t) return False #--- LAYER ------------------------------------------------------------------------------------------- # The Layer class is responsible for the following: # - it has a draw() method to override; all sorts of NodeBox drawing commands can be put here, # - it has a transformation origin point and rotates/scales its drawn items as a group, # - it has child layers that transform relative to this layer, # - when its attributes (position, scale, angle, ...) change, they will tween smoothly over time. _UID = 0 def _uid(): global _UID; _UID+=1; return _UID RELATIVE = "relative" # Origin point is stored as float, e.g. (0.5, 0.5). ABSOLUTE = "absolute" # Origin point is stored as int, e.g. (100, 100). class LayerRenderError(Exception): pass # When Layer.clipped=True, children are clipped to the bounds of the layer. # The layer clipping masks lazily changes size with the layer. class LayerClippingMask(ClippingMask): def __init__(self, layer): self.layer = layer def draw(self, fill=(0,0,0,1), stroke=None): w = not self.layer.width and geometry.INFINITE or self.layer.width h = not self.layer.height and geometry.INFINITE or self.layer.height rect(0, 0, w, h, fill=fill, stroke=stroke) class Layer(list, Prototype, EventHandler): def __init__(self, x=0, y=0, width=None, height=None, origin=(0,0), scale=1.0, rotation=0, opacity=1.0, duration=0.0, name=None, parent=None, **kwargs): """ Creates a new drawing layer that can be appended to the canvas. The duration defines the time (seconds) it takes to animate transformations or opacity. When the animation has terminated, layer.done=True. """ if origin == CENTER: origin = (0.5,0.5) origin_mode = RELATIVE elif isinstance(origin[0], float) \ and isinstance(origin[1], float): origin_mode = RELATIVE else: origin_mode = ABSOLUTE Prototype.__init__(self) # Facilitates extension on the fly. EventHandler.__init__(self) self._id = _uid() self.name = name # Layer name. Layers are accessible as ParentLayer.[name] self.canvas = None # The canvas this layer is drawn to. self.parent = parent # The layer this layer is a child of. self._x = Transition(x) # Layer horizontal position in pixels, from the left. self._y = Transition(y) # Layer vertical position in pixels, from the bottom. self._width = Transition(width) # Layer width in pixels. self._height = Transition(height) # Layer height in pixels. self._dx = Transition(origin[0]) # Transformation origin point. self._dy = Transition(origin[1]) # Transformation origin point. self._origin = origin_mode # Origin point as RELATIVE or ABSOLUTE coordinates? self._scale = Transition(scale) # Layer width and height scale. self._rotation = Transition(rotation) # Layer rotation. self._opacity = Transition(opacity) # Layer opacity. self.duration = duration # The time it takes to animate transformations. self.top = True # Draw on top of or beneath parent? self.flipped = False # Flip the layer horizontally? self.clipped = False # Clip child layers to bounds? self.hidden = False # Hide the layer? self._transform_cache = None # Cache of the local transformation matrix. self._transform_stack = None # Cache of the cumulative transformation matrix. self._clipping_mask = LayerClippingMask(self) @classmethod def from_image(self, img, *args, **kwargs): """ Returns a new layer that renders the given image, and with the same size as the image. The layer's draw() method and an additional image property are set. """ if not isinstance(img, Image): img = Image(img, data=kwargs.get("data")) kwargs.setdefault("width", img.width) kwargs.setdefault("height", img.height) def draw(layer): image(layer.image) layer = self(*args, **kwargs) layer.set_method(draw) layer.set_property("image", img) return layer @classmethod def from_function(self, function, *args, **kwargs): """ Returns a new layer that renders the drawing commands in the given function. The layer's draw() method is set. """ def draw(layer): function(layer) layer = self(*args, **kwargs) layer.set_method(draw) return layer def copy(self, parent=None, canvas=None): """ Returns a copy of the layer. All Layer properties will be copied, except for the new parent and canvas, which you need to define as optional parameters. This means that copies are not automatically appended to the parent layer or canvas. """ layer = self.__class__() # Create instance of the derived class, not Layer. layer.duration = 0 # Copy all transitions instantly. layer.canvas = canvas layer.parent = parent layer.name = self.name layer._x = self._x.copy() layer._y = self._y.copy() layer._width = self._width.copy() layer._height = self._height.copy() layer._origin = self._origin layer._dx = self._dx.copy() layer._dy = self._dy.copy() layer._scale = self._scale.copy() layer._rotation = self._rotation.copy() layer._opacity = self._opacity.copy() layer.duration = self.duration layer.top = self.top layer.flipped = self.flipped layer.clipped = self.clipped layer.hidden = self.hidden layer.enabled = self.enabled # Use base Layer.extend(), we don't care about what subclass.extend() does. Layer.extend(layer, [child.copy() for child in self]) # Inherit all the dynamic properties and methods. Prototype.inherit(layer, self) return layer def __getattr__(self, key): """ Returns the given property, or the layer with the given name. """ if key in self.__dict__: return self.__dict__[key] for layer in self: if layer.name == key: return layer raise AttributeError, "%s instance has no attribute '%s'" % (self.__class__.__name__, key) def _set_container(self, key, value): # If Layer.canvas is set to None, the canvas should no longer contain the layer. # If Layer.canvas is set to Canvas, this canvas should contain the layer. # Remove the layer from the old canvas/parent. # Append the layer to the new container. if self in (self.__dict__.get(key) or ()): self.__dict__[key].remove(self) if isinstance(value, list) and self not in value: list.append(value, self) self.__dict__[key] = value def _get_canvas(self): return self.__dict__.get("canvas") def _get_parent(self): return self.__dict__.get("parent") def _set_canvas(self, canvas): self._set_container("canvas", canvas) def _set_parent(self, layer): self._set_container("parent", layer) canvas = property(_get_canvas, _set_canvas) parent = property(_get_parent, _set_parent) @property def root(self): return self.parent and self.parent.root or self @property def layers(self): return self def insert(self, index, layer): list.insert(self, index, layer) layer.__dict__["parent"] = self def append(self, layer): list.append(self, layer) layer.__dict__["parent"] = self def extend(self, layers): for layer in layers: Layer.append(self, layer) def remove(self, layer): list.remove(self, layer) layer.__dict__["parent"] = None def pop(self, index): layer = list.pop(self, index) layer.__dict__["parent"] = None return layer def _get_x(self): return self._x.get() def _get_y(self): return self._y.get() def _get_width(self): return self._width.get() def _get_height(self): return self._height.get() def _get_scale(self): return self._scale.get() def _get_rotation(self): return self._rotation.get() def _get_opacity(self): return self._opacity.get() def _set_x(self, x): self._transform_cache = None self._x.set(x, self.duration) def _set_y(self, y): self._transform_cache = None self._y.set(y, self.duration) def _set_width(self, width): self._transform_cache = None self._width.set(width, self.duration) def _set_height(self, height): self._transform_cache = None self._height.set(height, self.duration) def _set_scale(self, scale): self._transform_cache = None self._scale.set(scale, self.duration) def _set_rotation(self, rotation): self._transform_cache = None self._rotation.set(rotation, self.duration) def _set_opacity(self, opacity): self._opacity.set(opacity, self.duration) x = property(_get_x, _set_x) y = property(_get_y, _set_y) width = property(_get_width, _set_width) height = property(_get_height, _set_height) scaling = property(_get_scale, _set_scale) rotation = property(_get_rotation, _set_rotation) opacity = property(_get_opacity, _set_opacity) def _get_xy(self): return (self.x, self.y) def _set_xy(self, (x,y)): self.x = x self.y = y xy = property(_get_xy, _set_xy) def _get_origin(self, relative=False): """ Returns the point (x,y) from which all layer transformations originate. When relative=True, x and y are defined percentually (0.0-1.0) in terms of width and height. In some cases x=0 or y=0 is returned: - For an infinite layer (width=None or height=None), we can't deduct the absolute origin from coordinates stored relatively (e.g. what is infinity*0.5?). - Vice versa, for an infinite layer we can't deduct the relative origin from coordinates stored absolute (e.g. what is 200/infinity?). """ dx = self._dx.current dy = self._dy.current w = self._width.current h = self._height.current # Origin is stored as absolute coordinates and we want it relative. if self._origin == ABSOLUTE and relative: if w is None: w = 0 if h is None: h = 0 dx = w!=0 and dx/w or 0 dy = h!=0 and dy/h or 0 # Origin is stored as relative coordinates and we want it absolute. elif self._origin == RELATIVE and not relative: dx = w is not None and dx*w or 0 dy = h is not None and dy*h or 0 return dx, dy def _set_origin(self, x, y, relative=False): """ Sets the transformation origin point in either absolute or relative coordinates. For example, if a layer is 400x200 pixels, setting the origin point to (200,100) all transformations (translate, rotate, scale) originate from the center. """ self._transform_cache = None self._dx.set(x, self.duration) self._dy.set(y, self.duration) self._origin = relative and RELATIVE or ABSOLUTE def origin(self, x=None, y=None, relative=False): """ Sets or returns the point (x,y) from which all layer transformations originate. """ if x is not None: if x == CENTER: x, y, relative = 0.5, 0.5, True if y is not None: self._set_origin(x, y, relative) return self._get_origin(relative) def _get_relative_origin(self): return self.origin(relative=True) def _set_relative_origin(self, xy): self._set_origin(xy[0], xy[1], relative=True) relative_origin = property(_get_relative_origin, _set_relative_origin) def _get_absolute_origin(self): return self.origin(relative=False) def _set_absolute_origin(self, xy): self._set_origin(xy[0], xy[1], relative=False) absolute_origin = property(_get_absolute_origin, _set_absolute_origin) def _get_visible(self): return not self.hidden def _set_visible(self, b): self.hidden = not b visible = property(_get_visible, _set_visible) def translate(self, x, y): self.x += x self.y += y def rotate(self, angle): self.rotation += angle def scale(self, f): self.scaling *= f def flip(self): self.flipped = not self.flipped def _update(self): """ Called each frame from canvas._update() to update the layer transitions. """ done = self._x.update() done &= self._y.update() done &= self._width.update() done &= self._height.update() done &= self._dx.update() done &= self._dy.update() done &= self._scale.update() done &= self._rotation.update() if not done: # i.e. the layer is being transformed self._transform_cache = None self._opacity.update() self.update() for layer in self: layer._update() def update(self): """Override this method to provide custom updating code. """ pass @property def done(self): """ Returns True when all transitions have finished. """ return self._x.done \ and self._y.done \ and self._width.done \ and self._height.done \ and self._dx.done \ and self._dy.done \ and self._scale.done \ and self._rotation.done \ and self._opacity.done def _draw(self): """ Draws the transformed layer and all of its children. """ if self.hidden: return glPushMatrix() # Be careful that the transformations happen in the same order in Layer._transform(). # translate => flip => rotate => scale => origin. # Center the contents around the origin point. dx, dy = self.origin(relative=False) glTranslatef(round(self._x.current), round(self._y.current), 0) if self.flipped: glScalef(-1, 1, 1) glRotatef(self._rotation.current, 0, 0, 1) glScalef(self._scale.current, self._scale.current, 1) # Enable clipping mask if Layer.clipped=True. if self.clipped: beginclip(self._clipping_mask) # Draw child layers below. for layer in self: if layer.top is False: layer._draw() # Draw layer. global _alpha _alpha = self._opacity.current # XXX should also affect child layers? glPushMatrix() glTranslatef(-round(dx), -round(dy), 0) # Layers are drawn relative from parent origin. self.draw() glPopMatrix() _alpha = 1 # Draw child layers on top. for layer in self: if layer.top is True: layer._draw() if self.clipped: endclip() glPopMatrix() def draw(self): """Override this method to provide custom drawing code for this layer. At this point, the layer is correctly transformed. """ pass def render(self): """ Returns the layer as a flattened image. The layer and all of its children need to have width and height set. """ b = self.bounds if geometry.INFINITE in (b.x, b.y, b.width, b.height): raise LayerRenderError, "can't render layer of infinite size" return render(lambda: (translate(-b.x,-b.y), self._draw()), b.width, b.height) def layer_at(self, x, y, clipped=False, enabled=False, transformed=True, _covered=False): """ Returns the topmost layer containing the mouse position, None otherwise. With clipped=True, no parts of child layers outside the parent's bounds are checked. With enabled=True, only enabled layers are checked (useful for events). """ if self.hidden: # Don't do costly operations on layers the user can't see. return None if enabled and not self.enabled: # Skip disabled layers during event propagation. return None if _covered: # An ancestor is blocking this layer, so we can't select it. return None hit = self.contains(x, y, transformed) if clipped: # If (x,y) is not inside the clipped bounds, return None. # If children protruding beyond the layer's bounds are clipped, # we only need to look at children on top of the layer. # Each child is drawn on top of the previous child, # so we hit test them in reverse order (highest-first). if not hit: return None children = [layer for layer in reversed(self) if layer.top is True] else: # Otherwise, traverse all children in on-top-first order to avoid # selecting a child underneath the layer that is in reality # covered by a peer on top of the layer, further down the list. children = sorted(reversed(self), key=lambda layer: not layer.top) for child in children: # An ancestor (e.g. grandparent) may be covering the child. # This happens when it hit tested and is somewhere on top of the child. # We keep a recursive covered-state to verify visibility. # The covered-state starts as False, but stays True once it switches. _covered = _covered or (hit and not child.top) child = child.layer_at(x, y, clipped, enabled, transformed, _covered) if child is not None: # Note: "if child:" won't work because it can be an empty list (no children). # Should be improved by not having Layer inherit from list. return child if hit: return self else: return None def _transform(self, local=True): """ Returns the transformation matrix of the layer: a calculated state of its translation, rotation and scaling. If local=False, prepends all transformations of the parent layers, i.e. you get the absolute transformation state of a nested layer. """ if self._transform_cache is None: # Calculate the local transformation matrix. # Be careful that the transformations happen in the same order in Layer._draw(). # translate => flip => rotate => scale => origin. tf = Transform() dx, dy = self.origin(relative=False) tf.translate(round(self._x.current), round(self._y.current)) if self.flipped: tf.scale(-1, 1) tf.rotate(self._rotation.current) tf.scale(self._scale.current, self._scale.current) tf.translate(-round(dx), -round(dy)) self._transform_cache = tf # Flush the cumulative transformation cache of all children. def _flush(layer): layer._transform_stack = None self.traverse(_flush) if not local: # Return the cumulative transformation matrix. # All of the parent transformation states need to be up to date. # If not, we need to recalculate the whole chain. if self._transform_stack is None: if self.parent is None: self._transform_stack = self._transform_cache.copy() else: # Accumulate all the parent layer transformations. # In the process, we update the transformation state of any outdated parent. dx, dy = self.parent.origin(relative=False) # Layers are drawn relative from parent origin. tf = self.parent._transform(local=False).copy() tf.translate(round(dx), round(dy)) self._transform_stack = self._transform_cache.copy() self._transform_stack.prepend(tf) return self._transform_stack return self._transform_cache @property def transform(self): return self._transform(local=False) def _bounds(self, local=True): """ Returns the rectangle that encompasses the transformed layer and its children. If one of the children has width=None or height=None, bounds will be infinite. """ w = self._width.current; w = w is None and geometry.INFINITE or w h = self._height.current; h = h is None and geometry.INFINITE or h # Find the transformed bounds of the layer: p = self.transform.map([(0,0), (w,0), (w,h), (0,h)]) x = min(p[0][0], p[1][0], p[2][0], p[3][0]) y = min(p[0][1], p[1][1], p[2][1], p[3][1]) w = max(p[0][0], p[1][0], p[2][0], p[3][0]) - x h = max(p[0][1], p[1][1], p[2][1], p[3][1]) - y b = geometry.Bounds(x, y, w, h) if not local: for child in self: b = b.union(child.bounds) return b @property def bounds(self): return self._bounds(local=False) def contains(self, x, y, transformed=True): """ Returns True if (x,y) falls within the layer's rectangular area. Useful for GUI elements: with transformed=False the calculations are much faster; and it will report correctly as long as the layer (or parent layer) is not rotated or scaled, and has its origin at (0,0). """ w = self._width.current; w = w is None and geometry.INFINITE or w h = self._height.current; h = h is None and geometry.INFINITE or h if not transformed: x0, y0 = self.absolute_position() return x0 <= x <= x0+w \ and y0 <= y <= y0+h # Find the transformed bounds of the layer: p = self.transform.map([(0,0), (w,0), (w,h), (0,h)]) return geometry.point_in_polygon(p, x, y) hit_test = contains def absolute_position(self, root=None): """ Returns the absolute (x,y) position (i.e. cumulative with parent position). """ x = 0 y = 0 layer = self while layer is not None and layer != root: x += layer.x y += layer.y layer = layer.parent return x, y def traverse(self, visit=lambda layer: None): """ Recurses the layer structure and calls visit() on each child layer. """ visit(self) [layer.traverse(visit) for layer in self] def __repr__(self): return "Layer(%sx=%.2f, y=%.2f, scale=%.2f, rotation=%.2f, opacity=%.2f, duration=%.2f)" % ( self.name is not None and "name='%s', " % self.name or "", self.x, self.y, self.scaling, self.rotation, self.opacity, self.duration ) def __eq__(self, other): return isinstance(other, Layer) and self._id == other._id def __ne__(self, other): return not self.__eq__(other) layer = Layer #--- GROUP ------------------------------------------------------------------------------------------- class Group(Layer): def __init__(self, *args, **kwargs): """ A layer that serves as a container for other layers. It has no width or height and doesn't draw anything. """ Layer.__init__(self, *args, **kwargs) self._set_width(0) self._set_height(0) @classmethod def from_image(*args, **kwargs): raise NotImplementedError @classmethod def from_function(*args, **kwargs): raise NotImplementedError @property def width(self): return 0 @property def height(self): return 0 def layer_at(self, x, y, clipped=False, enabled=False, transformed=True, _covered=False): # Ignores clipped=True for Group (since it has no width or height). for child in reversed(self): layer = child.layer_at(x, y, clipped, enabled, transformed, _covered) if layer: return layer group = Group #===================================================================================================== #--- MOUSE ------------------------------------------------------------------------------------------- # Mouse cursors: DEFAULT = "default" HIDDEN = "hidden" CROSS = pyglet.window.Window.CURSOR_CROSSHAIR HAND = pyglet.window.Window.CURSOR_HAND TEXT = pyglet.window.Window.CURSOR_TEXT WAIT = pyglet.window.Window.CURSOR_WAIT # Mouse buttons: LEFT = "left" RIGHT = "right" MIDDLE = "middle" class Mouse(Point): def __init__(self, canvas, x=0, y=0): """ Keeps track of the mouse position on the canvas, buttons pressed and the cursor icon. """ Point.__init__(self, x, y) self._canvas = canvas self._cursor = DEFAULT # Mouse cursor: CROSS, HAND, HIDDEN, TEXT, WAIT. self._button = None # Mouse button pressed: LEFT, RIGHT, MIDDLE. self.modifiers = [] # Mouse button modifiers: CTRL, SHIFT, OPTION. self.pressed = False # True if the mouse button is pressed. self.dragged = False # True if the mouse is dragged. self.scroll = Point(0,0) # Scroll offset. self.dx = 0 # Relative offset from previous horizontal position. self.dy = 0 # Relative offset from previous vertical position. # Backwards compatibility due to an old typo: @property def vx(self): return self.dx @property def vy(self): return self.dy @property def relative_x(self): try: return float(self.x) / self._canvas.width except ZeroDivisionError: return 0 @property def relative_y(self): try: return float(self.y) / self._canvas.height except ZeroDivisionError: return 0 def _get_cursor(self): return self._cursor def _set_cursor(self, mode): self._cursor = mode != DEFAULT and mode or None if mode == HIDDEN: self._canvas._window.set_mouse_visible(False); return self._canvas._window.set_mouse_cursor( self._canvas._window.get_system_mouse_cursor( self._cursor)) cursor = property(_get_cursor, _set_cursor) def _get_button(self): return self._button def _set_button(self, button): self._button = \ button == pyglet.window.mouse.LEFT and LEFT or \ button == pyglet.window.mouse.RIGHT and RIGHT or \ button == pyglet.window.mouse.MIDDLE and MIDDLE or None button = property(_get_button, _set_button) def __repr__(self): return "Mouse(x=%.1f, y=%.1f, pressed=%s, dragged=%s)" % ( self.x, self.y, repr(self.pressed), repr(self.dragged)) #--- KEYBOARD ---------------------------------------------------------------------------------------- # Key codes: BACKSPACE = "backspace" DELETE = "delete" TAB = "tab" ENTER = "enter" SPACE = "space" ESCAPE = "escape" UP = "up" DOWN = "down" LEFT = "left" RIGHT = "right" # Key modifiers: OPTION = \ ALT = "option" CTRL = "ctrl" SHIFT = "shift" class Key(object): def __init__(self, canvas): """ Keeps track of the key pressed and any modifiers (e.g. shift or control key). """ self._canvas = canvas self._code = None self.char = "" self.modifiers = [] self.pressed = False def _get_code(self): return self._code def _set_code(self, v): if isinstance(v, int): s = pyglet.window.key.symbol_string(v) # 65288 => "BACKSPACE" s = s.lower() # "BACKSPACE" => "backspace" s = s.lstrip("_") # "_1" => "1" s = s.endswith((OPTION, CTRL, SHIFT)) and s.lstrip("lr") or s # "lshift" => "shift" s = s.replace("return", ENTER) # "return" => "enter" s = s.replace("num_", "") # "num_space" => "space" else: s = v self._code = s code = property(_get_code, _set_code) def __repr__(self): return "Key(char=%s, code=%s, modifiers=%s, pressed=%s)" % ( repr(self.char), repr(self.code), repr(self.modifiers), repr(self.pressed)) #===================================================================================================== #--- CANVAS ------------------------------------------------------------------------------------------ VERY_LIGHT_GREY = 0.95 FRAME = 0 # Configuration settings for the canvas. # http://www.pyglet.org/doc/programming_guide/opengl_configuration_options.html # The stencil buffer is enabled (we need it to do clipping masks). # Multisampling will be enabled (if possible) to do anti-aliasing. settings = OPTIMAL = dict( # buffer_size = 32, # Let Pyglet decide automatically. # red_size = 8, # green_size = 8, # blue_size = 8, depth_size = 24, stencil_size = 1, alpha_size = 8, double_buffer = 1, sample_buffers = 1, samples = 4 ) def _configure(settings): """ Returns a pyglet.gl.Config object from the given dictionary of settings. If the settings are not supported, returns the default settings. """ screen = pyglet.window.get_platform().get_default_display().get_default_screen() c = pyglet.gl.Config(**settings) try: c = screen.get_best_config(c) except pyglet.window.NoSuchConfigException: # Probably the hardwarde doesn't support multisampling. # We can still do some anti-aliasing by turning on GL_LINE_SMOOTH. c = pyglet.gl.Config() c = screen.get_best_config(c) return c class Canvas(list, Prototype, EventHandler): def __init__(self, width=640, height=480, name="NodeBox for OpenGL", resizable=False, settings=OPTIMAL, vsync=True): """ The main application window containing the drawing canvas. It is opened when Canvas.run() is called. It is a collection of drawable Layer objects, and it has its own draw() method. This method must be overridden with your own drawing commands, which will be executed each frame. Event handlers for keyboard and mouse interaction can also be overriden. Events will be passed to layers that have been appended to the canvas. """ window = dict( caption = name, visible = False, width = width, height = height, resizable = resizable, config = _configure(settings), vsync = vsync ) Prototype.__init__(self) EventHandler.__init__(self) self.profiler = Profiler(self) self._window = pyglet.window.Window(**window) self._fps = None # Frames per second. self._frame = 0 # The current frame. self._active = False # Application is running? self.paused = False # Pause animation? self._mouse = Mouse(self) # The mouse cursor location. self._key = Key(self) # The key pressed on the keyboard. self._focus = None # The layer being focused by the mouse. # Mouse and keyboard events: self._window.on_mouse_enter = self._on_mouse_enter self._window.on_mouse_leave = self._on_mouse_leave self._window.on_mouse_motion = self._on_mouse_motion self._window.on_mouse_press = self._on_mouse_press self._window.on_mouse_release = self._on_mouse_release self._window.on_mouse_drag = self._on_mouse_drag self._window.on_mouse_scroll = self._on_mouse_scroll self._window.on_key_pressed = False self._window.on_key_press = self._on_key_press self._window.on_key_release = self._on_key_release self._window.on_text = self._on_text self._window.on_text_motion = self._on_text_motion self._window.on_move = self._on_move self._window.on_resize = self._on_resize self._window.on_close = self.stop def _get_name(self): return self._window.caption def _set_name(self, str): self._window.set_caption(str) name = property(_get_name, _set_name) def _get_vsync(self): return self._window.vsync def _set_vsync(self, bool): self._window.set_vsync(bool) vsync = property(_get_vsync, _set_vsync) @property def layers(self): return self def insert(self, index, layer): list.insert(self, index, layer) layer.__dict__["canvas"] = self def append(self, layer): list.append(self, layer) layer.__dict__["canvas"] = self def extend(self, layers): for layer in layers: self.append(layer) def remove(self, layer): list.remove(self, layer) layer.__dict__["canvas"] = None def pop(self, index): layer = list.pop(index) layer.__dict__["canvas"] = None return layer def _get_x(self): return self._window.get_location()[0] def _set_x(self, v): self._window.set_location(v, self.y) def _get_y(self): return self._window.get_location()[1] def _set_y(self, v): self._window.set_location(self.x, v) def _get_xy(self): return (self.x, self.y) def _set_xy(self, (x,y)): self.x = x self.y = y def _get_width(self): return self._window.width def _get_height(self): return self._window.height def _get_size(self): return (self.width, self.height) def _set_width(self, v): self._window.width = v def _set_height(self, v): self._window.height = v def _set_size(self, (w,h)): self.width = w self.height = h x = property(_get_x, _set_x) y = property(_get_y, _set_y) xy = property(_get_xy, _set_xy) width = property(_get_width, _set_width) height = property(_get_height, _set_height) size = property(_get_size, _set_size) def _get_fullscreen(self): return self._window.fullscreen def _set_fullscreen(self, mode=True): self._window.set_fullscreen(mode) fullscreen = property(_get_fullscreen, _set_fullscreen) @property def screen(self): return pyglet.window.get_platform().get_default_display().get_default_screen() @property def frame(self): """ Yields the current frame number. """ return self._frame @property def mouse(self): """ Yields a Point(x, y) with the mouse position on the canvas. """ return self._mouse @property def key(self): return self._key @property def focus(self): return self._focus #--- Event dispatchers ------------------------------ # First events are dispatched, then update() and draw() are called. def layer_at(self, x, y, **kwargs): """ Find the topmost layer at the specified coordinates. This method returns None if no layer was found. """ for layer in reversed(self): layer = layer.layer_at(x, y, **kwargs) if layer is not None: return layer return None def _on_mouse_enter(self, x, y): self._mouse.x = x self._mouse.y = y self.on_mouse_enter(self._mouse) def _on_mouse_leave(self, x, y): self._mouse.x = x self._mouse.y = y self.on_mouse_leave(self._mouse) # When the mouse leaves the canvas, no layer has the focus. if self._focus is not None: self._focus.on_mouse_leave(self._mouse) self._focus.focus = False self._focus.pressed = False self._focus.dragged = False self._focus = None def _on_mouse_motion(self, x, y, dx, dy): self._mouse.x = x self._mouse.y = y self._mouse.dx = int(dx) self._mouse.dy = int(dy) self.on_mouse_motion(self._mouse) # Get the topmost layer over which the mouse is hovering. layer = self.layer_at(x, y, enabled=True) # If the layer differs from the layer which currently has the focus, # or the mouse is not over any layer, remove the current focus. if self._focus is not None and (self._focus != layer or not self._focus.contains(x,y)): self._focus.on_mouse_leave(self._mouse) self._focus.focus = False self._focus = None # Set the focus. if self.focus != layer and layer is not None: self._focus = layer self._focus.focus = True self._focus.on_mouse_enter(self._mouse) # Propagate mouse motion to layer with the focus. if self._focus is not None: self._focus.on_mouse_motion(self._mouse) def _on_mouse_press(self, x, y, button, modifiers): self._mouse.pressed = True self._mouse.button = button self._mouse.modifiers = [a for (a,b) in ( (CTRL, pyglet.window.key.MOD_CTRL), (SHIFT, pyglet.window.key.MOD_SHIFT), (OPTION, pyglet.window.key.MOD_OPTION)) if modifiers & b] self.on_mouse_press(self._mouse) # Propagate mouse clicking to the layer with the focus. if self._focus is not None: self._focus.pressed = True self._focus.on_mouse_press(self._mouse) def _on_mouse_release(self, x, y, button, modifiers): self._mouse.button = None self._mouse.modifiers = [] self._mouse.pressed = False self._mouse.dragged = False self.on_mouse_release(self._mouse) if self._focus is not None: self._focus.on_mouse_release(self._mouse) self._focus.pressed = False self._focus.dragged = False # Get the topmost layer over which the mouse is hovering. layer = self.layer_at(x, y, enabled=True) # If the mouse is no longer over the layer with the focus # (this can happen after dragging), remove the focus. if self._focus != layer or not self._focus.contains(x,y): self._focus.on_mouse_leave(self._mouse) self._focus.focus = False self._focus = None # Propagate mouse to the layer with the focus. if self._focus != layer and layer is not None: layer.focus = True layer.on_mouse_enter(self._mouse) self._focus = layer def _on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): self._mouse.dragged = True self._mouse.x = x self._mouse.y = y self._mouse.dx = int(dx) self._mouse.dy = int(dy) self._mouse.modifiers = [a for (a,b) in ( (CTRL, pyglet.window.key.MOD_CTRL), (SHIFT, pyglet.window.key.MOD_SHIFT), (OPTION, pyglet.window.key.MOD_OPTION)) if modifiers & b] # XXX also needs to log buttons. self.on_mouse_drag(self._mouse) # Propagate mouse dragging to the layer with the focus. if self._focus is not None: self._focus.dragged = True self._focus.on_mouse_drag(self._mouse) def _on_mouse_scroll(self, x, y, scroll_x, scroll_y): self._mouse.scroll.x = scroll_x self._mouse.scroll.y = scroll_y self.on_mouse_scroll(self._mouse) # Propagate mouse scrolling to the layer with the focus. if self._focus is not None: self._focus.on_mouse_scroll(self._mouse) def _on_key_press(self, keycode, modifiers): self._key.pressed = True self._key.code = keycode self._key.modifiers = [a for (a,b) in ( (CTRL, pyglet.window.key.MOD_CTRL), (SHIFT, pyglet.window.key.MOD_SHIFT), (OPTION, pyglet.window.key.MOD_OPTION)) if modifiers & b] # The event is delegated in _update(): self._window.on_key_pressed = True def _on_key_release(self, keycode, modifiers): self._key.char = "" self._key.code = None self._key.modifiers = [] self._key.pressed = False self.on_key_release(self.key) for layer in self: layer.on_key_release(self.key) def _on_text(self, text): self._key.char = text # The event is delegated in _update(): self._window.on_key_pressed = True def _on_text_motion(self, keycode): self._key.char = "" self._key.code = keycode # The event is delegated in _update(): self._window.on_key_pressed = True def _on_move(self, x, y): self.on_move() def _on_resize(self, width, height): pyglet.window.Window.on_resize(self._window, width, height) self.on_resize() # Event methods are meant to be overridden or patched with Prototype.set_method(). def on_key_press(self, key): """ The default behavior of the canvas: - ESC exits the application, - CTRL-P pauses the animation, - CTRL-S saves a screenshot. """ if key.code == ESCAPE: self.stop() if key.code == "p" and CTRL in key.modifiers: self.paused = not self.paused if key.code == "s" and CTRL in key.modifiers: self.save("nodebox-%s.png" % str(datetime.now()).split(".")[0].replace(" ","-").replace(":","-")) def on_move(self): pass def on_resize(self): pass #--- Main loop -------------------------------------- def setup(self): pass def update(self): pass def draw(self): self.clear() def draw_overlay(self): """ Override this method to draw once all the layers have been drawn. """ pass draw_over = draw_overlay def _setup(self): # Set the window color, this will be transparent in saved images. glClearColor(VERY_LIGHT_GREY, VERY_LIGHT_GREY, VERY_LIGHT_GREY, 0) # Reset the transformation state. glLoadIdentity() # Enable line anti-aliasing. glEnable(GL_LINE_SMOOTH) # Enable alpha transparency. glEnable(GL_BLEND) glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA) #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Start the application (if not already running). if not self._active: self._window.switch_to() self._window.dispatch_events() self._window.set_visible() self._active = True self.clear() self.setup() def _draw(self, lapse=0): """ Draws the canvas and its layers. This method gives the same result each time it gets drawn; only _update() advances state. """ self._frame += 1 if self.paused: return glPushMatrix() self.draw() glPopMatrix() glPushMatrix() for layer in self: layer._draw() glPopMatrix() glPushMatrix() self.draw_overlay() glPopMatrix() def _update(self, lapse=0): """ Updates the canvas and its layers. This method does not actually draw anything, it only updates the state. """ if not self.paused: # Advance the animation by updating all layers. # This is only done when the canvas is not paused. # Events will still be propagated during pause. global TIME; TIME = time() self.update() for layer in self: layer._update() if self._window.on_key_pressed is True: # Fire on_key_press() event, # which combines _on_key_press(), _on_text() and _on_text_motion(). self._window.on_key_pressed = False self.on_key_press(self._key) for layer in self: layer.on_key_press(self._key) def stop(self): # If you override this method, don't forget to call Canvas.stop() to exit the app. # Any user-defined stop method, added with canvas.set_method() or canvas.run(stop=stop), # is called first. try: self._user_defined_stop() except: pass for f in (self._update, self._draw): pyglet.clock.unschedule(f) self._window.close() self._active = False pyglet.app.exit() def clear(self): """ Clears the previous frame from the canvas. """ glClear(GL_COLOR_BUFFER_BIT) glClear(GL_DEPTH_BUFFER_BIT) glClear(GL_STENCIL_BUFFER_BIT) def run(self, draw=None, setup=None, update=None, stop=None): """ Opens the application windows and starts drawing the canvas. Canvas.setup() will be called once during initialization. Canvas.draw() and Canvas.update() will be called each frame. Canvas.clear() needs to be called explicitly to clear the previous frame drawing. Canvas.stop() closes the application window. If the given setup, draw or update parameter is a function, it overrides that canvas method. """ if isinstance(setup, FunctionType): self.set_method(setup, name="setup") if isinstance(draw, FunctionType): self.set_method(draw, name="draw") if isinstance(update, FunctionType): self.set_method(update, name="update") if isinstance(stop, FunctionType): self.set_method(stop, name="stop") self._setup() self.fps = self._fps # Schedule the _update and _draw events. pyglet.app.run() @property def active(self): return self._active def _get_fps(self): return self._fps def _set_fps(self, v): # Use pyglet.clock to schedule _update() and _draw() events. # The clock will then take care of calling them enough times. # Note: frames per second is related to vsync. # If the vertical refresh rate is about 30Hz you'll get top speed of around 33fps. # It's probably a good idea to leave vsync=True if you don't want to fry the GPU. for f in (self._update, self._draw): pyglet.clock.unschedule(f) if v is None: pyglet.clock.schedule(f) if v > 0: pyglet.clock.schedule_interval(f, 1.0/v) self._fps = v fps = property(_get_fps, _set_fps) #--- Frame export ----------------------------------- def render(self): """ Returns a screenshot of the current frame as a texture. This texture can be passed to the image() command. """ return pyglet.image.get_buffer_manager().get_color_buffer().get_texture() buffer = screenshot = render @property def texture(self): return pyglet.image.get_buffer_manager().get_color_buffer().get_texture() def save(self, path): """ Exports the current frame as a PNG-file. """ pyglet.image.get_buffer_manager().get_color_buffer().save(path) #--- Prototype -------------------------------------- def __setattr__(self, k, v): # Canvas is a Prototype, so Canvas.draw() can be overridden # but it can also be patched with Canvas.set_method(draw). # Specific methods (setup, draw, mouse and keyboard events) can also be set directly # (e.g. canvas.on_mouse_press = my_mouse_handler). # This way we don't have to explain set_method() to beginning users.. if isinstance(v, FunctionType) and (k in ("setup", "draw", "update", "stop") \ or k.startswith("on_") and k in ( "on_mouse_enter", "on_mouse_leave", "on_mouse_motion", "on_mouse_press", "on_mouse_release", "on_mouse_drag", "on_mouse_scroll", "on_key_press", "on_key_release", "on_move", "on_resize")): self.set_method(v, name=k) else: object.__setattr__(self, k, v) def set_method(self, function, name=None): if name == "stop" \ or name is None and function.__name__ == "stop": Prototype.set_method(self, function, name="_user_defined_stop") # Called from Canvas.stop(). else: Prototype.set_method(self, function, name) def __repr__(self): return "Canvas(name='%s', size='%s', layers=%s)" % (self.name, self.size, repr(list(self))) #--- PROFILER ---------------------------------------------------------------------------------------- CUMULATIVE = "cumulative" SLOWEST = "slowest" _profile_canvas = None _profile_frames = 100 def profile_run(): for i in range(_profile_frames): _profile_canvas._update() _profile_canvas._draw() class Profiler: def __init__(self, canvas): self.canvas = canvas @property def framerate(self): return pyglet.clock.get_fps() def run(self, draw=None, setup=None, update=None, frames=100, sort=CUMULATIVE, top=30): """ Runs cProfile on the canvas for the given number of frames. The performance statistics are returned as a string, sorted by SLOWEST or CUMULATIVE. For example, instead of doing canvas.run(draw): print canvas.profiler.run(draw, frames=100) """ # Register the setup, draw, update functions with the canvas (if given). if isinstance(setup, FunctionType): self.canvas.set_method(setup, name="setup") if isinstance(draw, FunctionType): self.canvas.set_method(draw, name="draw") if isinstance(update, FunctionType): self.canvas.set_method(update, name="update") # If enabled, turn Psyco off. psyco_stopped = False try: psyco.stop() psyco_stopped = True except: pass # Set the current canvas and the number of frames to profile. # The profiler will then repeatedly execute canvas._update() and canvas._draw(). # Statistics are redirected from stdout to a temporary file. global _profile_canvas, _profile_frames _profile_canvas = self.canvas _profile_frames = frames import cProfile import pstats cProfile.run("profile_run()", "_profile") p = pstats.Stats("_profile") p.stream = open("_profile", "w") p.sort_stats(sort==SLOWEST and "time" or sort).print_stats(top) p.stream.close() s = open("_profile").read() remove("_profile") # Restart Psyco if we stopped it. if psyco_stopped: psyco.profile() return s #--- LIBRARIES --------------------------------------------------------------------------------------- # Import the library and assign it a _ctx variable containing the current context. # This mimics the behavior in NodeBox. def ximport(library): from sys import modules library = __import__(library) library._ctx = modules[__name__] return library #----------------------------------------------------------------------------------------------------- # Linear interpolation math for BezierPath.point() etc. import bezier #----------------------------------------------------------------------------------------------------- # Expose the canvas and some common canvas properties on global level. # Some magic constants from NodeBox are commands here: # - WIDTH => width() # - HEIGHT => height() # - FRAME => frame() canvas = Canvas() def size(width=None, height=None): if width is not None: canvas.width = width if height is not None: canvas.height = height return canvas.size def speed(fps=None): if fps is not None: canvas.fps = fps return canvas.fps def frame(): return canvas.frame def clear(): canvas.clear() global WIDTH, HEIGHT WIDTH = canvas.width HEIGHT = canvas.height
est/nodebox-gl
graphics/context.py
Python
bsd-3-clause
151,331
[ "VisIt" ]
f2bcf51018e15de41fc36aafffabadf13d07a1386425566783b9282f16399c1d
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import ast import re from jinja2.compiler import generate from jinja2.exceptions import UndefinedError from ansible.errors import AnsibleError, AnsibleUndefinedVariable from ansible.module_utils.six import text_type from ansible.module_utils._text import to_native from ansible.playbook.attribute import FieldAttribute try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() DEFINED_REGEX = re.compile(r'(hostvars\[.+\]|[\w_]+)\s+(not\s+is|is|is\s+not)\s+(defined|undefined)') LOOKUP_REGEX = re.compile(r'lookup\s*\(') VALID_VAR_REGEX = re.compile("^[_A-Za-z][_a-zA-Z0-9]*$") class Conditional: ''' This is a mix-in class, to be used with Base to allow the object to be run conditionally when a condition is met or skipped. ''' _when = FieldAttribute(isa='list', default=[]) def __init__(self, loader=None): # when used directly, this class needs a loader, but we want to # make sure we don't trample on the existing one if this class # is used as a mix-in with a playbook base class if not hasattr(self, '_loader'): if loader is None: raise AnsibleError("a loader must be specified when using Conditional() directly") else: self._loader = loader super(Conditional, self).__init__() def _validate_when(self, attr, name, value): if not isinstance(value, list): setattr(self, name, [ value ]) def _get_attr_when(self): ''' Override for the 'tags' getattr fetcher, used from Base. ''' when = self._attributes['when'] if when is None: when = [] if hasattr(self, '_get_parent_attribute'): when = self._get_parent_attribute('when', extend=True, prepend=True) return when def extract_defined_undefined(self, conditional): results = [] cond = conditional m = DEFINED_REGEX.search(cond) while m: results.append(m.groups()) cond = cond[m.end():] m = DEFINED_REGEX.search(cond) return results def evaluate_conditional(self, templar, all_vars): ''' Loops through the conditionals set on this object, returning False if any of them evaluate as such. ''' # since this is a mix-in, it may not have an underlying datastructure # associated with it, so we pull it out now in case we need it for # error reporting below ds = None if hasattr(self, '_ds'): ds = getattr(self, '_ds') try: # this allows for direct boolean assignments to conditionals "when: False" if isinstance(self.when, bool): return self.when for conditional in self.when: if not self._check_conditional(conditional, templar, all_vars): return False except Exception as e: raise AnsibleError( "The conditional check '%s' failed. The error was: %s" % (to_native(conditional), to_native(e)), obj=ds ) return True def _check_conditional(self, conditional, templar, all_vars): ''' This method does the low-level evaluation of each conditional set on this object, using jinja2 to wrap the conditionals for evaluation. ''' original = conditional if conditional is None or conditional == '': return True # pull the "bare" var out, which allows for nested conditionals # and things like: # - assert: # that: # - item # with_items: # - 1 == 1 if conditional in all_vars and VALID_VAR_REGEX.match(conditional): conditional = all_vars[conditional] if templar.is_template(conditional): display.warning('when statements should not include jinja2 ' 'templating delimiters such as {{ }} or {%% %%}. ' 'Found: %s' % conditional) # make sure the templar is using the variables specified with this method templar.set_available_variables(variables=all_vars) try: # if the conditional is "unsafe", disable lookups disable_lookups = hasattr(conditional, '__UNSAFE__') conditional = templar.template(conditional, disable_lookups=disable_lookups) if not isinstance(conditional, text_type) or conditional == "": return conditional # update the lookups flag, as the string returned above may now be unsafe # and we don't want future templating calls to do unsafe things disable_lookups |= hasattr(conditional, '__UNSAFE__') # First, we do some low-level jinja2 parsing involving the AST format of the # statement to ensure we don't do anything unsafe (using the disable_lookup flag above) class CleansingNodeVisitor(ast.NodeVisitor): def generic_visit(self, node, inside_call=False, inside_yield=False): if isinstance(node, ast.Call): inside_call = True elif isinstance(node, ast.Yield): inside_yield = True elif isinstance(node, ast.Str): if disable_lookups: if inside_call and node.s.startswith("__"): # calling things with a dunder is generally bad at this point... raise AnsibleError( "Invalid access found in the conditional: '%s'" % conditional ) elif inside_yield: # we're inside a yield, so recursively parse and traverse the AST # of the result to catch forbidden syntax from executing parsed = ast.parse(node.s, mode='exec') cnv = CleansingNodeVisitor() cnv.visit(parsed) # iterate over all child nodes for child_node in ast.iter_child_nodes(node): self.generic_visit( child_node, inside_call=inside_call, inside_yield=inside_yield ) try: e = templar.environment.overlay() e.filters.update(templar._get_filters()) e.tests.update(templar._get_tests()) res = e._parse(conditional, None, None) res = generate(res, e, None, None) parsed = ast.parse(res, mode='exec') cnv = CleansingNodeVisitor() cnv.visit(parsed) except Exception as e: raise AnsibleError("Invalid conditional detected: %s" % to_native(e)) # and finally we generate and template the presented string and look at the resulting string presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional val = templar.template(presented, disable_lookups=disable_lookups).strip() if val == "True": return True elif val == "False": return False else: raise AnsibleError("unable to evaluate conditional: %s" % original) except (AnsibleUndefinedVariable, UndefinedError) as e: # the templating failed, meaning most likely a variable was undefined. If we happened # to be looking for an undefined variable, return True, otherwise fail try: # first we extract the variable name from the error message var_name = re.compile(r"'(hostvars\[.+\]|[\w_]+)' is undefined").search(str(e)).groups()[0] # next we extract all defined/undefined tests from the conditional string def_undef = self.extract_defined_undefined(conditional) # then we loop through these, comparing the error variable name against # each def/undef test we found above. If there is a match, we determine # whether the logic/state mean the variable should exist or not and return # the corresponding True/False for (du_var, logic, state) in def_undef: # when we compare the var names, normalize quotes because something # like hostvars['foo'] may be tested against hostvars["foo"] if var_name.replace("'", '"') == du_var.replace("'", '"'): # the should exist is a xor test between a negation in the logic portion # against the state (defined or undefined) should_exist = ('not' in logic) != (state == 'defined') if should_exist: return False else: return True # as nothing above matched the failed var name, re-raise here to # trigger the AnsibleUndefinedVariable exception again below raise except Exception as new_e: raise AnsibleUndefinedVariable( "error while evaluating conditional (%s): %s" % (original, e) )
sidartaoliveira/ansible
lib/ansible/playbook/conditional.py
Python
gpl-3.0
10,450
[ "VisIt" ]
acc6ec1055f724bb1635e429d16cd34c65a954028864e6fbf1992b8512fc04bd
""" @name: Modules/families/UPB/UPB_data.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2014-2020 by D. Brian Kimmel @license: MIT License @note: Created on Aug 6, 2014 @summary: This module is for communicating with UPB controllers. """ __updated__ = '2020-02-17' # Import system type stuff # Import PyMh files from Modules.House.Lighting.Lights.lights import LightControlInformation class UPBData(LightControlInformation): """ Locally held data about each of the UPB PIM controllers we find. This is known only within the UPB family package. """ def __init__(self): super(UPBData, self).__init__() self.UPBAddress = 0 self.UPBPassword = 0 self.UPBNetworkID = 0 # ## END DBK
DBrianKimmel/PyHouse
Project/src/Modules/House/Family/Upb/upb_data.py
Python
mit
787
[ "Brian" ]
2bc4f8f7f8211fb6adfe8bafe17537d9c473f560f1b7c53fa388374034cad6b7
from __future__ import absolute_import from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, UserManager, \ PermissionsMixin from django.dispatch import receiver from zerver.lib.cache import cache_with_key, flush_user_profile, flush_realm, \ user_profile_by_id_cache_key, user_profile_by_email_cache_key, \ generic_bulk_cached_fetch, cache_set, flush_stream, \ display_recipient_cache_key, cache_delete, \ get_stream_cache_key, active_user_dicts_in_realm_cache_key, \ active_bot_dicts_in_realm_cache_key from zerver.lib.utils import make_safe_digest, generate_random_token from django.db import transaction, IntegrityError from zerver.lib.avatar import gravatar_hash, get_avatar_url from django.utils import timezone from django.contrib.sessions.models import Session from zerver.lib.timestamp import datetime_to_timestamp from django.db.models.signals import pre_save, post_save, post_delete from guardian.shortcuts import get_users_with_perms import zlib from bitfield import BitField from collections import defaultdict from datetime import timedelta import pylibmc import re import ujson import logging bugdown = None MAX_SUBJECT_LENGTH = 60 MAX_MESSAGE_LENGTH = 10000 # Doing 1000 memcached requests to get_display_recipient is quite slow, # so add a local cache as well as the memcached cache. per_request_display_recipient_cache = {} def get_display_recipient_by_id(recipient_id, recipient_type, recipient_type_id): if recipient_id not in per_request_display_recipient_cache: result = get_display_recipient_memcached(recipient_id, recipient_type, recipient_type_id) per_request_display_recipient_cache[recipient_id] = result return per_request_display_recipient_cache[recipient_id] def get_display_recipient(recipient): return get_display_recipient_by_id( recipient.id, recipient.type, recipient.type_id ) def flush_per_request_caches(): global per_request_display_recipient_cache per_request_display_recipient_cache = {} global per_request_realm_filters_cache per_request_realm_filters_cache = {} @cache_with_key(lambda *args: display_recipient_cache_key(args[0]), timeout=3600*24*7) def get_display_recipient_memcached(recipient_id, recipient_type, recipient_type_id): """ returns: an appropriate object describing the recipient. For a stream this will be the stream name as a string. For a huddle or personal, it will be an array of dicts about each recipient. """ if recipient_type == Recipient.STREAM: stream = Stream.objects.get(id=recipient_type_id) return stream.name # We don't really care what the ordering is, just that it's deterministic. user_profile_list = (UserProfile.objects.filter(subscription__recipient_id=recipient_id) .select_related() .order_by('email')) return [{'email': user_profile.email, 'domain': user_profile.realm.domain, 'full_name': user_profile.full_name, 'short_name': user_profile.short_name, 'id': user_profile.id, 'is_mirror_dummy': user_profile.is_mirror_dummy,} for user_profile in user_profile_list] def completely_open(domain): # This domain is completely open to everyone on the internet to # join. E-mail addresses do not need to match the domain and # an invite from an existing user is not required. realm = get_realm(domain) if not realm: return False return not realm.invite_required and not realm.restricted_to_domain def get_unique_open_realm(): # We only return a realm if there is a unique realm and it is completely open. realms = Realm.objects.filter(deactivated=False) if settings.VOYAGER: # On production installations, the "zulip.com" realm is an # empty realm just used for system bots, so don't include it # in this accounting. realms = realms.exclude(domain="zulip.com") if len(realms) != 1: return None realm = realms[0] if realm.invite_required or realm.restricted_to_domain: return None return realm def get_realm_emoji_cache_key(realm): return 'realm_emoji:%s' % (realm.id,) class Realm(models.Model): # domain is a domain in the Internet sense. It must be structured like a # valid email domain. We use is to restrict access, identify bots, etc. domain = models.CharField(max_length=40, db_index=True, unique=True) # name is the user-visible identifier for the realm. It has no required # structure. name = models.CharField(max_length=40, null=True) restricted_to_domain = models.BooleanField(default=True) invite_required = models.BooleanField(default=False) invite_by_admins_only = models.BooleanField(default=False) mandatory_topics = models.BooleanField(default=False) show_digest_email = models.BooleanField(default=True) name_changes_disabled = models.BooleanField(default=False) date_created = models.DateTimeField(default=timezone.now) notifications_stream = models.ForeignKey('Stream', related_name='+', null=True, blank=True) deactivated = models.BooleanField(default=False) DEFAULT_NOTIFICATION_STREAM_NAME = 'zulip' def __repr__(self): return (u"<Realm: %s %s>" % (self.domain, self.id)).encode("utf-8") def __str__(self): return self.__repr__() @cache_with_key(get_realm_emoji_cache_key, timeout=3600*24*7) def get_emoji(self): return get_realm_emoji_uncached(self) @property def deployment(self): try: return self._deployments.all()[0] except IndexError: return None @deployment.setter def set_deployments(self, value): self._deployments = [value] def get_admin_users(self): # This method is kind of expensive, due to our complex permissions model. candidates = get_users_with_perms(self, only_with_perms=['administer']) return candidates def get_active_users(self): return UserProfile.objects.filter(realm=self, is_active=True).select_related() class Meta(object): permissions = ( ('administer', "Administer a realm"), ('api_super_user', "Can send messages as other users for mirroring"), ) post_save.connect(flush_realm, sender=Realm) class RealmAlias(models.Model): realm = models.ForeignKey(Realm, null=True) domain = models.CharField(max_length=80, db_index=True, unique=True) # These functions should only be used on email addresses that have # been validated via django.core.validators.validate_email # # Note that we need to use some care, since can you have multiple @-signs; e.g. # "tabbott@test"@zulip.com # is valid email address def email_to_username(email): return "@".join(email.split("@")[:-1]).lower() # Returns the raw domain portion of the desired email address def split_email_to_domain(email): return email.split("@")[-1].lower() # Returns the domain, potentually de-aliased, for the realm # that this user's email is in def resolve_email_to_domain(email): domain = split_email_to_domain(email) alias = alias_for_realm(domain) if alias is not None: domain = alias.realm.domain return domain def alias_for_realm(domain): try: return RealmAlias.objects.get(domain=domain) except RealmAlias.DoesNotExist: return None def remote_user_to_email(remote_user): if settings.SSO_APPEND_DOMAIN is not None: remote_user += "@" + settings.SSO_APPEND_DOMAIN return remote_user class RealmEmoji(models.Model): realm = models.ForeignKey(Realm) name = models.TextField() img_url = models.TextField() class Meta(object): unique_together = ("realm", "name") def __str__(self): return "<RealmEmoji(%s): %s %s>" % (self.realm.domain, self.name, self.img_url) def get_realm_emoji_uncached(realm): d = {} for row in RealmEmoji.objects.filter(realm=realm): d[row.name] = row.img_url return d def flush_realm_emoji(sender, **kwargs): realm = kwargs['instance'].realm cache_set(get_realm_emoji_cache_key(realm), get_realm_emoji_uncached(realm), timeout=3600*24*7) post_save.connect(flush_realm_emoji, sender=RealmEmoji) post_delete.connect(flush_realm_emoji, sender=RealmEmoji) class RealmFilter(models.Model): realm = models.ForeignKey(Realm) pattern = models.TextField() url_format_string = models.TextField() class Meta(object): unique_together = ("realm", "pattern") def __str__(self): return "<RealmFilter(%s): %s %s>" % (self.realm.domain, self.pattern, self.url_format_string) def get_realm_filters_cache_key(domain): return 'all_realm_filters:%s' % (domain,) # We have a per-process cache to avoid doing 1000 memcached queries during page load per_request_realm_filters_cache = {} def realm_filters_for_domain(domain): domain = domain.lower() if domain not in per_request_realm_filters_cache: per_request_realm_filters_cache[domain] = realm_filters_for_domain_memcached(domain) return per_request_realm_filters_cache[domain] @cache_with_key(get_realm_filters_cache_key, timeout=3600*24*7) def realm_filters_for_domain_memcached(domain): filters = [] for realm_filter in RealmFilter.objects.filter(realm=get_realm(domain)): filters.append((realm_filter.pattern, realm_filter.url_format_string)) return filters def all_realm_filters(): filters = defaultdict(list) for realm_filter in RealmFilter.objects.all(): filters[realm_filter.realm.domain].append((realm_filter.pattern, realm_filter.url_format_string)) return filters def flush_realm_filter(sender, **kwargs): realm = kwargs['instance'].realm cache_delete(get_realm_filters_cache_key(realm.domain)) try: per_request_realm_filters_cache.pop(realm.domain.lower()) except KeyError: pass post_save.connect(flush_realm_filter, sender=RealmFilter) post_delete.connect(flush_realm_filter, sender=RealmFilter) class UserProfile(AbstractBaseUser, PermissionsMixin): # Fields from models.AbstractUser minus last_name and first_name, # which we don't use; email is modified to make it indexed and unique. email = models.EmailField(blank=False, db_index=True, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_bot = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) is_mirror_dummy = models.BooleanField(default=False) bot_owner = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) USERNAME_FIELD = 'email' MAX_NAME_LENGTH = 100 # Our custom site-specific fields full_name = models.CharField(max_length=MAX_NAME_LENGTH) short_name = models.CharField(max_length=MAX_NAME_LENGTH) # pointer points to Message.id, NOT UserMessage.id. pointer = models.IntegerField() last_pointer_updater = models.CharField(max_length=64) realm = models.ForeignKey(Realm) api_key = models.CharField(max_length=32) ### Notifications settings. ### # Stream notifications. enable_stream_desktop_notifications = models.BooleanField(default=False) enable_stream_sounds = models.BooleanField(default=False) # PM + @-mention notifications. enable_desktop_notifications = models.BooleanField(default=True) enable_sounds = models.BooleanField(default=True) enable_offline_email_notifications = models.BooleanField(default=True) enable_offline_push_notifications = models.BooleanField(default=True) enable_digest_emails = models.BooleanField(default=True) # Old notification field superseded by existence of stream notification # settings. default_desktop_notifications = models.BooleanField(default=True) ### last_reminder = models.DateTimeField(default=timezone.now, null=True) rate_limits = models.CharField(default="", max_length=100) # comma-separated list of range:max pairs # Default streams default_sending_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+') default_events_register_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+') default_all_public_streams = models.BooleanField(default=False) # UI vars enter_sends = models.NullBooleanField(default=True) autoscroll_forever = models.BooleanField(default=False) left_side_userlist = models.BooleanField(default=False) # display settings twenty_four_hour_time = models.BooleanField(default=False) # Hours to wait before sending another email to a user EMAIL_REMINDER_WAITPERIOD = 24 # Minutes to wait before warning a bot owner that her bot sent a message # to a nonexistent stream BOT_OWNER_STREAM_ALERT_WAITPERIOD = 1 AVATAR_FROM_GRAVATAR = 'G' AVATAR_FROM_USER = 'U' AVATAR_FROM_SYSTEM = 'S' AVATAR_SOURCES = ( (AVATAR_FROM_GRAVATAR, 'Hosted by Gravatar'), (AVATAR_FROM_USER, 'Uploaded by user'), (AVATAR_FROM_SYSTEM, 'System generated'), ) avatar_source = models.CharField(default=AVATAR_FROM_GRAVATAR, choices=AVATAR_SOURCES, max_length=1) TUTORIAL_WAITING = 'W' TUTORIAL_STARTED = 'S' TUTORIAL_FINISHED = 'F' TUTORIAL_STATES = ((TUTORIAL_WAITING, "Waiting"), (TUTORIAL_STARTED, "Started"), (TUTORIAL_FINISHED, "Finished")) tutorial_status = models.CharField(default=TUTORIAL_WAITING, choices=TUTORIAL_STATES, max_length=1) # Contains serialized JSON of the form: # [("step 1", true), ("step 2", false)] # where the second element of each tuple is if the step has been # completed. onboarding_steps = models.TextField(default=ujson.dumps([])) invites_granted = models.IntegerField(default=0) invites_used = models.IntegerField(default=0) alert_words = models.TextField(default=ujson.dumps([])) # json-serialized list of strings # Contains serialized JSON of the form: # [["social", "mit"], ["devel", "ios"]] muted_topics = models.TextField(default=ujson.dumps([])) objects = UserManager() def can_admin_user(self, target_user): """Returns whether this user has permission to modify target_user""" if target_user.bot_owner == self: return True elif self.has_perm('administer', target_user.realm): return True else: return False def is_admin(self): return self.has_perm('administer', self.realm) def is_api_super_user(self): # TODO: Remove API_SUPER_USERS hack; fixing this will require # setting the email bot as a super user in the provision process. return self.has_perm('api_super_user', self.realm) or self.email in settings.API_SUPER_USERS def last_reminder_tzaware(self): if self.last_reminder is not None and timezone.is_naive(self.last_reminder): logging.warning("Loaded a user_profile.last_reminder for user %s that's not tz-aware: %s" % (self.email, self.last_reminder)) return self.last_reminder.replace(tzinfo=timezone.utc) return self.last_reminder def __repr__(self): return (u"<UserProfile: %s %s>" % (self.email, self.realm)).encode("utf-8") def __str__(self): return self.__repr__() @staticmethod def emails_from_ids(user_ids): rows = UserProfile.objects.filter(id__in=user_ids).values('id', 'email') return {row['id']: row['email'] for row in rows} def can_create_streams(self): # Long term this might be an actual DB attribute. Short term and long term, we want # this to be conceptually a property of the user, although it may actually be administered # in a more complicated way, like certain realms may allow only admins to create streams. return True def receives_offline_notifications(user_profile): return ((user_profile.enable_offline_email_notifications or user_profile.enable_offline_push_notifications) and not user_profile.is_bot) # Make sure we flush the UserProfile object from our memcached # whenever we save it. post_save.connect(flush_user_profile, sender=UserProfile) class PreregistrationUser(models.Model): email = models.EmailField() referred_by = models.ForeignKey(UserProfile, null=True) streams = models.ManyToManyField('Stream') invited_at = models.DateTimeField(auto_now=True) # status: whether an object has been confirmed. # if confirmed, set to confirmation.settings.STATUS_ACTIVE status = models.IntegerField(default=0) realm = models.ForeignKey(Realm, null=True) # Deprecated. Drop this table once prod uses PushDeviceToken and the data has # been copied there. class AppleDeviceToken(models.Model): # The token is a unique device-specific token that is # sent to us from each iOS device, after registering with # the APNS service token = models.CharField(max_length=255, unique=True) last_updated = models.DateTimeField(auto_now=True) # The user who's device this is user = models.ForeignKey(UserProfile, db_index=True) class PushDeviceToken(models.Model): APNS = 1 GCM = 2 KINDS = ( (APNS, 'apns'), (GCM, 'gcm'), ) kind = models.PositiveSmallIntegerField(choices=KINDS) # The token is a unique device-specific token that is # sent to us from each device: # - APNS token if kind == APNS # - GCM registration id if kind == GCM token = models.CharField(max_length=4096, unique=True) last_updated = models.DateTimeField(auto_now=True) # The user who's device this is user = models.ForeignKey(UserProfile, db_index=True) # [optional] Contains the app id of the device if it is an iOS device ios_app_id = models.TextField(null=True) class MitUser(models.Model): email = models.EmailField(unique=True) # status: whether an object has been confirmed. # if confirmed, set to confirmation.settings.STATUS_ACTIVE status = models.IntegerField(default=0) def generate_email_token_for_stream(): return generate_random_token(32) class Stream(models.Model): MAX_NAME_LENGTH = 60 name = models.CharField(max_length=MAX_NAME_LENGTH, db_index=True) realm = models.ForeignKey(Realm, db_index=True) invite_only = models.NullBooleanField(default=False) # Used by the e-mail forwarder. The e-mail RFC specifies a maximum # e-mail length of 254, and our max stream length is 30, so we # have plenty of room for the token. email_token = models.CharField( max_length=32, default=generate_email_token_for_stream) description = models.CharField(max_length=1024, default='') date_created = models.DateTimeField(default=timezone.now) deactivated = models.BooleanField(default=False) def __repr__(self): return (u"<Stream: %s>" % (self.name,)).encode("utf-8") def __str__(self): return self.__repr__() def is_public(self): # All streams are private at MIT. return self.realm.domain != "mit.edu" and not self.invite_only class Meta(object): unique_together = ("name", "realm") @classmethod def create(cls, name, realm): stream = cls(name=name, realm=realm) stream.save() recipient = Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM) return (stream, recipient) def num_subscribers(self): return Subscription.objects.filter( recipient__type=Recipient.STREAM, recipient__type_id=self.id, user_profile__is_active=True, active=True ).count() # This is stream information that is sent to clients def to_dict(self): return dict(name=self.name, stream_id=self.id, description=self.description, invite_only=self.invite_only) post_save.connect(flush_stream, sender=Stream) post_delete.connect(flush_stream, sender=Stream) def valid_stream_name(name): return name != "" class Recipient(models.Model): type_id = models.IntegerField(db_index=True) type = models.PositiveSmallIntegerField(db_index=True) # Valid types are {personal, stream, huddle} PERSONAL = 1 STREAM = 2 HUDDLE = 3 class Meta(object): unique_together = ("type", "type_id") # N.B. If we used Django's choice=... we would get this for free (kinda) _type_names = { PERSONAL: 'personal', STREAM: 'stream', HUDDLE: 'huddle' } def type_name(self): # Raises KeyError if invalid return self._type_names[self.type] def __repr__(self): display_recipient = get_display_recipient(self) return (u"<Recipient: %s (%d, %s)>" % (display_recipient, self.type_id, self.type)).encode("utf-8") class Client(models.Model): name = models.CharField(max_length=30, db_index=True, unique=True) get_client_cache = {} def get_client(name): if name not in get_client_cache: result = get_client_memcached(name) get_client_cache[name] = result return get_client_cache[name] def get_client_cache_key(name): return 'get_client:%s' % (make_safe_digest(name),) @cache_with_key(get_client_cache_key, timeout=3600*24*7) def get_client_memcached(name): (client, _) = Client.objects.get_or_create(name=name) return client # get_stream_backend takes either a realm id or a realm @cache_with_key(get_stream_cache_key, timeout=3600*24*7) def get_stream_backend(stream_name, realm): if isinstance(realm, Realm): realm_id = realm.id else: realm_id = realm return Stream.objects.select_related("realm").get( name__iexact=stream_name.strip(), realm_id=realm_id) def get_active_streams(realm): """ Return all streams (including invite-only streams) that have not been deactivated. """ return Stream.objects.filter(realm=realm, deactivated=False) # get_stream takes either a realm id or a realm def get_stream(stream_name, realm): try: return get_stream_backend(stream_name, realm) except Stream.DoesNotExist: return None def bulk_get_streams(realm, stream_names): if isinstance(realm, Realm): realm_id = realm.id else: realm_id = realm def fetch_streams_by_name(stream_names): # This should be just # # Stream.objects.select_related("realm").filter(name__iexact__in=stream_names, # realm_id=realm_id) # # But chaining __in and __iexact doesn't work with Django's # ORM, so we have the following hack to construct the relevant where clause if len(stream_names) == 0: return [] upper_list = ", ".join(["UPPER(%s)"] * len(stream_names)) where_clause = "UPPER(zerver_stream.name::text) IN (%s)" % (upper_list,) return get_active_streams(realm_id).select_related("realm").extra( where=[where_clause], params=stream_names) return generic_bulk_cached_fetch(lambda stream_name: get_stream_cache_key(stream_name, realm), fetch_streams_by_name, [stream_name.lower() for stream_name in stream_names], id_fetcher=lambda stream: stream.name.lower()) def get_recipient_cache_key(type, type_id): return "get_recipient:%s:%s" % (type, type_id,) @cache_with_key(get_recipient_cache_key, timeout=3600*24*7) def get_recipient(type, type_id): return Recipient.objects.get(type_id=type_id, type=type) def bulk_get_recipients(type, type_ids): def cache_key_function(type_id): return get_recipient_cache_key(type, type_id) def query_function(type_ids): return Recipient.objects.filter(type=type, type_id__in=type_ids) return generic_bulk_cached_fetch(cache_key_function, query_function, type_ids, id_fetcher=lambda recipient: recipient.type_id) # NB: This function is currently unused, but may come in handy. def linebreak(string): return string.replace('\n\n', '<p/>').replace('\n', '<br/>') def extract_message_dict(message_str): return ujson.loads(zlib.decompress(message_str)) def stringify_message_dict(message_dict): return zlib.compress(ujson.dumps(message_dict)) def to_dict_cache_key_id(message_id, apply_markdown): return 'message_dict:%d:%d' % (message_id, apply_markdown) def to_dict_cache_key(message, apply_markdown): return to_dict_cache_key_id(message.id, apply_markdown) class Message(models.Model): sender = models.ForeignKey(UserProfile) recipient = models.ForeignKey(Recipient) subject = models.CharField(max_length=MAX_SUBJECT_LENGTH, db_index=True) content = models.TextField() rendered_content = models.TextField(null=True) rendered_content_version = models.IntegerField(null=True) pub_date = models.DateTimeField('date published', db_index=True) sending_client = models.ForeignKey(Client) last_edit_time = models.DateTimeField(null=True) edit_history = models.TextField(null=True) has_attachment = models.BooleanField(default=False, db_index=True) has_image = models.BooleanField(default=False, db_index=True) has_link = models.BooleanField(default=False, db_index=True) def __repr__(self): display_recipient = get_display_recipient(self.recipient) return (u"<Message: %s / %s / %r>" % (display_recipient, self.subject, self.sender)).encode("utf-8") def __str__(self): return self.__repr__() def get_realm(self): return self.sender.realm def render_markdown(self, content, domain=None): """Return HTML for given markdown. Bugdown may add properties to the message object such as `mentions_user_ids` and `mentions_wildcard`. These are only on this Django object and are not saved in the database. """ global bugdown if bugdown is None: from zerver.lib import bugdown self.mentions_wildcard = False self.is_me_message = False self.mentions_user_ids = set() self.user_ids_with_alert_words = set() if not domain: domain = self.sender.realm.domain if self.sending_client.name == "zephyr_mirror" and domain == "mit.edu": # Use slightly customized Markdown processor for content # delivered via zephyr_mirror domain = "mit.edu/zephyr_mirror" rendered_content = bugdown.convert(content, domain, self) # For /me syntax, JS can detect the is_me_message flag # and do special rendering. if content.startswith('/me ') and '\n' not in content: if rendered_content.startswith('<p>') and rendered_content.endswith('</p>'): self.is_me_message = True return rendered_content def set_rendered_content(self, rendered_content, save = False): """Set the content on the message. """ global bugdown if bugdown is None: from zerver.lib import bugdown self.rendered_content = rendered_content self.rendered_content_version = bugdown.version if self.rendered_content is not None: if save: self.save_rendered_content() return True else: return False def save_rendered_content(self): self.save(update_fields=["rendered_content", "rendered_content_version"]) def maybe_render_content(self, domain, save = False): """Render the markdown if there is no existing rendered_content""" global bugdown if bugdown is None: from zerver.lib import bugdown if Message.need_to_render_content(self.rendered_content, self.rendered_content_version): return self.set_rendered_content(self.render_markdown(self.content, domain), save) else: return True @staticmethod def need_to_render_content(rendered_content, rendered_content_version): return rendered_content_version < bugdown.version or rendered_content is None def to_dict(self, apply_markdown): return extract_message_dict(self.to_dict_json(apply_markdown)) @cache_with_key(to_dict_cache_key, timeout=3600*24) def to_dict_json(self, apply_markdown): return stringify_message_dict(self.to_dict_uncached(apply_markdown)) def to_dict_uncached(self, apply_markdown): return Message.build_message_dict( apply_markdown = apply_markdown, message = self, message_id = self.id, last_edit_time = self.last_edit_time, edit_history = self.edit_history, content = self.content, subject = self.subject, pub_date = self.pub_date, rendered_content = self.rendered_content, rendered_content_version = self.rendered_content_version, sender_id = self.sender.id, sender_email = self.sender.email, sender_realm_domain = self.sender.realm.domain, sender_full_name = self.sender.full_name, sender_short_name = self.sender.short_name, sender_avatar_source = self.sender.avatar_source, sender_is_mirror_dummy = self.sender.is_mirror_dummy, sending_client_name = self.sending_client.name, recipient_id = self.recipient.id, recipient_type = self.recipient.type, recipient_type_id = self.recipient.type_id, ) @staticmethod def build_dict_from_raw_db_row(row, apply_markdown): ''' row is a row from a .values() call, and it needs to have all the relevant fields populated ''' return Message.build_message_dict( apply_markdown = apply_markdown, message = None, message_id = row['id'], last_edit_time = row['last_edit_time'], edit_history = row['edit_history'], content = row['content'], subject = row['subject'], pub_date = row['pub_date'], rendered_content = row['rendered_content'], rendered_content_version = row['rendered_content_version'], sender_id = row['sender_id'], sender_email = row['sender__email'], sender_realm_domain = row['sender__realm__domain'], sender_full_name = row['sender__full_name'], sender_short_name = row['sender__short_name'], sender_avatar_source = row['sender__avatar_source'], sender_is_mirror_dummy = row['sender__is_mirror_dummy'], sending_client_name = row['sending_client__name'], recipient_id = row['recipient_id'], recipient_type = row['recipient__type'], recipient_type_id = row['recipient__type_id'], ) @staticmethod def build_message_dict( apply_markdown, message, message_id, last_edit_time, edit_history, content, subject, pub_date, rendered_content, rendered_content_version, sender_id, sender_email, sender_realm_domain, sender_full_name, sender_short_name, sender_avatar_source, sender_is_mirror_dummy, sending_client_name, recipient_id, recipient_type, recipient_type_id, ): global bugdown if bugdown is None: from zerver.lib import bugdown avatar_url = get_avatar_url(sender_avatar_source, sender_email) display_recipient = get_display_recipient_by_id( recipient_id, recipient_type, recipient_type_id ) if recipient_type == Recipient.STREAM: display_type = "stream" elif recipient_type in (Recipient.HUDDLE, Recipient.PERSONAL): display_type = "private" if len(display_recipient) == 1: # add the sender in if this isn't a message between # someone and his self, preserving ordering recip = {'email': sender_email, 'domain': sender_realm_domain, 'full_name': sender_full_name, 'short_name': sender_short_name, 'id': sender_id, 'is_mirror_dummy': sender_is_mirror_dummy} if recip['email'] < display_recipient[0]['email']: display_recipient = [recip, display_recipient[0]] elif recip['email'] > display_recipient[0]['email']: display_recipient = [display_recipient[0], recip] obj = dict( id = message_id, sender_email = sender_email, sender_full_name = sender_full_name, sender_short_name = sender_short_name, sender_domain = sender_realm_domain, sender_id = sender_id, type = display_type, display_recipient = display_recipient, recipient_id = recipient_id, subject = subject, timestamp = datetime_to_timestamp(pub_date), gravatar_hash = gravatar_hash(sender_email), # Deprecated June 2013 avatar_url = avatar_url, client = sending_client_name) obj['subject_links'] = bugdown.subject_links(sender_realm_domain.lower(), subject) if last_edit_time != None: obj['last_edit_timestamp'] = datetime_to_timestamp(last_edit_time) obj['edit_history'] = ujson.loads(edit_history) if apply_markdown: if Message.need_to_render_content(rendered_content, rendered_content_version): if message is None: # We really shouldn't be rendering objects in this method, but there is # a scenario where we upgrade the version of bugdown and fail to run # management commands to re-render historical messages, and then we # need to have side effects. This method is optimized to not need full # blown ORM objects, but the bugdown renderer is unfortunately highly # coupled to Message, and we also need to persist the new rendered content. # If we don't have a message object passed in, we get one here. The cost # of going to the DB here should be overshadowed by the cost of rendering # and updating the row. message = Message.objects.select_related().get(id=message_id) # It's unfortunate that we need to have side effects on the message # in some cases. rendered_content = message.render_markdown(content, sender_realm_domain) message.set_rendered_content(rendered_content, True) if rendered_content is not None: obj['content'] = rendered_content else: obj['content'] = '<p>[Zulip note: Sorry, we could not understand the formatting of your message]</p>' obj['content_type'] = 'text/html' else: obj['content'] = content obj['content_type'] = 'text/x-markdown' return obj def to_log_dict(self): return dict( id = self.id, sender_email = self.sender.email, sender_domain = self.sender.realm.domain, sender_full_name = self.sender.full_name, sender_short_name = self.sender.short_name, sending_client = self.sending_client.name, type = self.recipient.type_name(), recipient = get_display_recipient(self.recipient), subject = self.subject, content = self.content, timestamp = datetime_to_timestamp(self.pub_date)) @staticmethod def get_raw_db_rows(needed_ids): # This is a special purpose function optimized for # callers like get_old_messages_backend(). fields = [ 'id', 'subject', 'pub_date', 'last_edit_time', 'edit_history', 'content', 'rendered_content', 'rendered_content_version', 'recipient_id', 'recipient__type', 'recipient__type_id', 'sender_id', 'sending_client__name', 'sender__email', 'sender__full_name', 'sender__short_name', 'sender__realm__id', 'sender__realm__domain', 'sender__avatar_source', 'sender__is_mirror_dummy', ] return Message.objects.filter(id__in=needed_ids).values(*fields) @classmethod def remove_unreachable(cls): """Remove all Messages that are not referred to by any UserMessage.""" cls.objects.exclude(id__in = UserMessage.objects.values('message_id')).delete() def sent_by_human(self): sending_client = self.sending_client.name.lower() return (sending_client in ('zulipandroid', 'zulipios', 'zulipdesktop', 'website', 'ios', 'android')) or \ ('desktop app' in sending_client) @staticmethod def content_has_attachment(content): return re.search('[/\-]user[\-_]uploads[/\.-]', content) @staticmethod def content_has_image(content): return bool(re.search('[/\-]user[\-_]uploads[/\.-]\S+\.(bmp|gif|jpg|jpeg|png|webp)', content, re.IGNORECASE)) @staticmethod def content_has_link(content): return 'http://' in content or 'https://' in content or '/user_uploads' in content def update_calculated_fields(self): # TODO: rendered_content could also be considered a calculated field content = self.content self.has_attachment = bool(Message.content_has_attachment(content)) self.has_image = bool(Message.content_has_image(content)) self.has_link = bool(Message.content_has_link(content)) @receiver(pre_save, sender=Message) def pre_save_message(sender, **kwargs): if kwargs['update_fields'] is None or "content" in kwargs['update_fields']: message = kwargs['instance'] message.update_calculated_fields() def get_context_for_message(message): return Message.objects.filter( recipient_id=message.recipient_id, subject=message.subject, id__lt=message.id, pub_date__gt=message.pub_date - timedelta(minutes=15), ).order_by('-id')[:10] class UserMessage(models.Model): user_profile = models.ForeignKey(UserProfile) message = models.ForeignKey(Message) # We're not using the archived field for now, but create it anyway # since this table will be an unpleasant one to do schema changes # on later ALL_FLAGS = ['read', 'starred', 'collapsed', 'mentioned', 'wildcard_mentioned', 'summarize_in_home', 'summarize_in_stream', 'force_expand', 'force_collapse', 'has_alert_word', "historical", 'is_me_message'] flags = BitField(flags=ALL_FLAGS, default=0) class Meta(object): unique_together = ("user_profile", "message") def __repr__(self): display_recipient = get_display_recipient(self.message.recipient) return (u"<UserMessage: %s / %s (%s)>" % (display_recipient, self.user_profile.email, self.flags_list())).encode("utf-8") def flags_list(self): return [flag for flag in self.flags.keys() if getattr(self.flags, flag).is_set] def parse_usermessage_flags(val): flags = [] mask = 1 for flag in UserMessage.ALL_FLAGS: if val & mask: flags.append(flag) mask <<= 1 return flags class Subscription(models.Model): user_profile = models.ForeignKey(UserProfile) recipient = models.ForeignKey(Recipient) active = models.BooleanField(default=True) in_home_view = models.NullBooleanField(default=True) DEFAULT_STREAM_COLOR = "#c2c2c2" color = models.CharField(max_length=10, default=DEFAULT_STREAM_COLOR) desktop_notifications = models.BooleanField(default=True) audible_notifications = models.BooleanField(default=True) # Combination desktop + audible notifications superseded by the # above. notifications = models.BooleanField(default=False) class Meta(object): unique_together = ("user_profile", "recipient") def __repr__(self): return (u"<Subscription: %r -> %s>" % (self.user_profile, self.recipient)).encode("utf-8") def __str__(self): return self.__repr__() @cache_with_key(user_profile_by_id_cache_key, timeout=3600*24*7) def get_user_profile_by_id(uid): return UserProfile.objects.select_related().get(id=uid) @cache_with_key(user_profile_by_email_cache_key, timeout=3600*24*7) def get_user_profile_by_email(email): return UserProfile.objects.select_related().get(email__iexact=email.strip()) @cache_with_key(active_user_dicts_in_realm_cache_key, timeout=3600*24*7) def get_active_user_dicts_in_realm(realm): return UserProfile.objects.filter(realm=realm, is_active=True) \ .values('id', 'full_name', 'short_name', 'email', 'is_bot') @cache_with_key(active_bot_dicts_in_realm_cache_key, timeout=3600*24*7) def get_active_bot_dicts_in_realm(realm): return UserProfile.objects.filter(realm=realm, is_active=True, is_bot=True) \ .values('id', 'full_name', 'short_name', 'email', 'default_sending_stream__name', 'default_events_register_stream__name', 'default_all_public_streams', 'api_key', 'bot_owner__email', 'avatar_source') def get_prereg_user_by_email(email): # A user can be invited many times, so only return the result of the latest # invite. return PreregistrationUser.objects.filter(email__iexact=email.strip()).latest("invited_at") class Huddle(models.Model): # TODO: We should consider whether using # CommaSeparatedIntegerField would be better. huddle_hash = models.CharField(max_length=40, db_index=True, unique=True) def get_huddle_hash(id_list): id_list = sorted(set(id_list)) hash_key = ",".join(str(x) for x in id_list) return make_safe_digest(hash_key) def huddle_hash_cache_key(huddle_hash): return "huddle_by_hash:%s" % (huddle_hash,) def get_huddle(id_list): huddle_hash = get_huddle_hash(id_list) return get_huddle_backend(huddle_hash, id_list) @cache_with_key(lambda huddle_hash, id_list: huddle_hash_cache_key(huddle_hash), timeout=3600*24*7) def get_huddle_backend(huddle_hash, id_list): (huddle, created) = Huddle.objects.get_or_create(huddle_hash=huddle_hash) if created: with transaction.atomic(): recipient = Recipient.objects.create(type_id=huddle.id, type=Recipient.HUDDLE) subs_to_create = [Subscription(recipient=recipient, user_profile=get_user_profile_by_id(user_profile_id)) for user_profile_id in id_list] Subscription.objects.bulk_create(subs_to_create) return huddle def get_realm(domain): if not domain: return None try: return Realm.objects.get(domain__iexact=domain.strip()) except Realm.DoesNotExist: return None def clear_database(): pylibmc.Client(['127.0.0.1']).flush_all() for model in [Message, Stream, UserProfile, Recipient, Realm, Subscription, Huddle, UserMessage, Client, DefaultStream]: model.objects.all().delete() Session.objects.all().delete() class UserActivity(models.Model): user_profile = models.ForeignKey(UserProfile) client = models.ForeignKey(Client) query = models.CharField(max_length=50, db_index=True) count = models.IntegerField() last_visit = models.DateTimeField('last visit') class Meta(object): unique_together = ("user_profile", "client", "query") class UserActivityInterval(models.Model): user_profile = models.ForeignKey(UserProfile) start = models.DateTimeField('start time', db_index=True) end = models.DateTimeField('end time', db_index=True) class UserPresence(models.Model): user_profile = models.ForeignKey(UserProfile) client = models.ForeignKey(Client) # Valid statuses ACTIVE = 1 IDLE = 2 timestamp = models.DateTimeField('presence changed') status = models.PositiveSmallIntegerField(default=ACTIVE) @staticmethod def status_to_string(status): if status == UserPresence.ACTIVE: return 'active' elif status == UserPresence.IDLE: return 'idle' @staticmethod def get_status_dict_by_realm(realm_id): user_statuses = defaultdict(dict) query = UserPresence.objects.filter( user_profile__realm_id=realm_id, user_profile__is_active=True, user_profile__is_bot=False ).values( 'client__name', 'status', 'timestamp', 'user_profile__email', 'user_profile__id', 'user_profile__enable_offline_push_notifications', 'user_profile__is_mirror_dummy', ) mobile_user_ids = [row['user'] for row in PushDeviceToken.objects.filter( user__realm_id=1, user__is_active=True, user__is_bot=False, ).distinct("user").values("user")] for row in query: info = UserPresence.to_presence_dict( client_name=row['client__name'], status=row['status'], timestamp=row['timestamp'], push_enabled=row['user_profile__enable_offline_push_notifications'], has_push_devices=row['user_profile__id'] in mobile_user_ids, is_mirror_dummy=row['user_profile__is_mirror_dummy'], ) user_statuses[row['user_profile__email']][row['client__name']] = info return user_statuses @staticmethod def to_presence_dict(client_name=None, status=None, timestamp=None, push_enabled=None, has_push_devices=None, is_mirror_dummy=None): presence_val = UserPresence.status_to_string(status) timestamp = datetime_to_timestamp(timestamp) return dict( client=client_name, status=presence_val, timestamp=timestamp, pushable=(push_enabled and has_push_devices), ) def to_dict(self): return UserPresence.to_presence_dict( client_name=self.client.name, status=self.status, timestamp=self.timestamp ) @staticmethod def status_from_string(status): if status == 'active': status_val = UserPresence.ACTIVE elif status == 'idle': status_val = UserPresence.IDLE else: status_val = None return status_val class Meta(object): unique_together = ("user_profile", "client") class DefaultStream(models.Model): realm = models.ForeignKey(Realm) stream = models.ForeignKey(Stream) class Meta(object): unique_together = ("realm", "stream") # FIXME: The foreign key relationship here is backwards. # # We can't easily get a list of streams and their associated colors (if any) in # a single query. See zerver.views.gather_subscriptions for an example. # # We should change things around so that is possible. Probably this should # just be a column on Subscription. class StreamColor(models.Model): DEFAULT_STREAM_COLOR = "#c2c2c2" subscription = models.ForeignKey(Subscription) color = models.CharField(max_length=10) class Referral(models.Model): user_profile = models.ForeignKey(UserProfile) email = models.EmailField(blank=False, null=False) timestamp = models.DateTimeField(auto_now_add=True, null=False) # This table only gets used on Zulip Voyager instances # For reasons of deliverability (and sending from multiple email addresses), # we will still send from mandrill when we send things from the (staging.)zulip.com install class ScheduledJob(models.Model): scheduled_timestamp = models.DateTimeField(auto_now_add=False, null=False) type = models.PositiveSmallIntegerField() # Valid types are {email} # for EMAIL, filter_string is recipient_email EMAIL = 1 # JSON representation of the job's data. Be careful, as we are not relying on Django to do validation data = models.TextField() # Kind if like a ForeignKey, but table is determined by type. filter_id = models.IntegerField(null=True) filter_string = models.CharField(max_length=100)
esander91/zulip
zerver/models.py
Python
apache-2.0
50,057
[ "VisIt" ]
fd71cbccde9c956a9ec9b2105de25e949a7e83b55f984581c806bc9bb1d6f509
#!/usr/bin/env python # -*- coding: utf-8 -*- import rdkit from rdkit.Chem import AllChem from rdkit import DataStructs __license__ = "X11" METADATA = { "id": "method_rdkit_ecfp2_1023_tanimoto", "representation": "ecfp2_1023", "similarity": "tanimoto" } def _compute_fingerprint(molecule): return AllChem.GetMorganFingerprintAsBitVect(molecule, 1, nBits=1023) def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right) def create_model(train_ligands, train_decoys): model = [] for molecule in train_ligands: model.append({ "name": molecule.GetProp("_Name"), "fingerprint": _compute_fingerprint(molecule) }) model_information = {} return model, model_information def compute_score(model, molecule): fingerprint = _compute_fingerprint(molecule) similarities = [_compute_similarity(fingerprint, item["fingerprint"]) for item in model] max_score = max(similarities) index_of_max_score = similarities.index(max_score) closest_molecule = model[index_of_max_score] return { "value": max_score, "info": { "closest": closest_molecule["name"] } } def compute_similarity(left, right): return _compute_similarity(_compute_fingerprint(left), _compute_fingerprint(right))
skodapetr/lbvs-environment
methods/ecfp/ecfp2_1023_tanimoto.py
Python
mit
1,396
[ "RDKit" ]
db43f39d323efebf46886f8f30f98fb3593dbf9611f12c25c67bf564982db505
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import unittest import os import json from pymatgen.entries.computed_entries import ComputedEntry from pymatgen.apps.battery.insertion_battery import InsertionElectrode from pymatgen import MontyEncoder, MontyDecoder test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", 'test_files') class InsertionElectrodeTest(unittest.TestCase): def setUp(self): self.entry_Li = ComputedEntry("Li", -1.90753119) self.entry_Ca = ComputedEntry("Ca", -1.99689568) with open(os.path.join(test_dir, "LiTiO2_batt.json"), "r") as f: self.entries_LTO = json.load(f, cls=MontyDecoder) with open(os.path.join(test_dir, "MgVO_batt.json"), "r") as file: self.entries_MVO = json.load(file, cls=MontyDecoder) with open(os.path.join(test_dir, "Mg_batt.json"), "r") as file: self.entry_Mg = json.load(file, cls=MontyDecoder) with open(os.path.join(test_dir, "CaMoO2_batt.json"), "r") as f: self.entries_CMO = json.load(f, cls=MontyDecoder) self.ie_LTO = InsertionElectrode(self.entries_LTO, self.entry_Li) self.ie_MVO = InsertionElectrode(self.entries_MVO, self.entry_Mg) self.ie_CMO = InsertionElectrode(self.entries_CMO, self.entry_Ca) def test_voltage(self): # test basic voltage self.assertAlmostEqual(self.ie_LTO.max_voltage, 2.78583901, 3) self.assertAlmostEqual(self.ie_LTO.min_voltage, 0.89702381, 3) self.assertAlmostEqual(self.ie_LTO.get_average_voltage(), 1.84143141, 3) # test voltage range selectors self.assertAlmostEqual(self.ie_LTO.get_average_voltage(0, 1), 0.89702381, 3) self.assertAlmostEqual(self.ie_LTO.get_average_voltage(2, 3), 2.78583901, 3) # test non-existing voltage range self.assertAlmostEqual(self.ie_LTO.get_average_voltage(0, 0.1), 0, 3) self.assertAlmostEqual(self.ie_LTO.get_average_voltage(4, 5), 0, 3) self.assertAlmostEqual(self.ie_MVO.get_average_voltage(), 2.513767, 3) def test_capacities(self): # test basic capacity self.assertAlmostEqual(self.ie_LTO.get_capacity_grav(), 308.74865045, 3) self.assertAlmostEqual(self.ie_LTO.get_capacity_vol(), 1205.99391136, 3) # test capacity selector self.assertAlmostEqual(self.ie_LTO.get_capacity_grav(1, 3), 154.374325225, 3) # test alternate normalization option self.assertAlmostEqual(self.ie_LTO.get_capacity_grav(1, 3, False), 160.803169506, 3) self.assertIsNotNone(self.ie_LTO.as_dict_summary(True)) self.assertAlmostEqual(self.ie_MVO.get_capacity_grav(), 281.845548242, 3) self.assertAlmostEqual(self.ie_MVO.get_capacity_vol(), 1145.80087994, 3) def test_get_instability(self): self.assertIsNone(self.ie_LTO.get_max_instability()) self.assertAlmostEqual(self.ie_MVO.get_max_instability(), 0.7233711650000014) self.assertAlmostEqual(self.ie_MVO.get_min_instability(), 0.4913575099999994) def test_get_muO2(self): self.assertIsNone(self.ie_LTO.get_max_muO2()) self.assertAlmostEqual(self.ie_MVO.get_max_muO2(), -4.93552791875) self.assertAlmostEqual(self.ie_MVO.get_min_muO2(), -11.06599657) def test_entries(self): # test that the proper number of sub-electrodes are returned self.assertEqual(len(self.ie_LTO.get_sub_electrodes(False, True)), 3) self.assertEqual(len(self.ie_LTO.get_sub_electrodes(True, True)), 2) def test_get_all_entries(self): self.ie_LTO.get_all_entries() def test_to_from_dict(self): d = self.ie_LTO.as_dict() ie = InsertionElectrode.from_dict(d) self.assertAlmostEqual(ie.max_voltage, 2.78583901, 3) self.assertAlmostEqual(ie.min_voltage, 0.89702381, 3) self.assertAlmostEqual(ie.get_average_voltage(), 1.84143141, 3) # Just to make sure json string works. json_str = json.dumps(self.ie_LTO, cls=MontyEncoder) ie = json.loads(json_str, cls=MontyDecoder) self.assertAlmostEqual(ie.max_voltage, 2.78583901, 3) self.assertAlmostEqual(ie.min_voltage, 0.89702381, 3) self.assertAlmostEqual(ie.get_average_voltage(), 1.84143141, 3) def test_voltage_pair(self): vpair = self.ie_LTO[0] self.assertAlmostEqual(vpair.voltage, 2.78583901) self.assertAlmostEqual(vpair.mAh, 13400.7411749, 2) self.assertAlmostEqual(vpair.mass_charge, 79.8658) self.assertAlmostEqual(vpair.mass_discharge, 83.3363) self.assertAlmostEqual(vpair.vol_charge, 37.553684467) self.assertAlmostEqual(vpair.vol_discharge, 37.917719932) self.assertAlmostEqual(vpair.frac_charge, 0.0) self.assertAlmostEqual(vpair.frac_discharge, 0.14285714285714285) def test_as_dict_summary(self): d = self.ie_CMO.as_dict_summary() self.assertAlmostEqual(d['stability_charge'], 0.2346574583333325) self.assertAlmostEqual(d['stability_discharge'], 0.33379544031249786) self.assertAlmostEqual(d['muO2_data']['mp-714969'][0]['chempot'], -4.93552791875) if __name__ == '__main__': unittest.main()
tschaume/pymatgen
pymatgen/apps/battery/tests/test_insertion_battery.py
Python
mit
5,523
[ "pymatgen" ]
91cc5f3e362cf62ac6c191ab1d10ff43744364ec5b755df34e37a685a70d4d4e
""" an XML-RPC server to allow remote control of PyMol Author: Greg Landrum (glandrum@users.sourceforge.net) Created: January 2002 $LastChangedDate$ License: This file is part of the RDKit. The contents are covered by the terms of the BSD license which is included in the file license.txt, found at the root of the RDKit source tree. Requires: - a python xmlrpclib distribution containing the SimpleXMLRPCServer module (1.0 or greater should be fine) - python with threading enabled RD Version: $Rev$ """ from __future__ import print_function import SimpleXMLRPCServer import threading, sys, time, types, os, tempfile from pymol import cmd, cgo # initial port to try for the server _xmlPort = 9123 # number of alternate ports to try if the first fails _nPortsToTry = 5 def rpcCmd(cmdText): """ executes a PyMol API command return value is either the result of the command or the empty string """ res = cmd.do(cmdText) if res is not None: return res else: return '' def rpcQuit(): """ causes PyMol to quit """ cmd.quit() return 1 def rpcZoom(what=''): """ executes cmd.zoom(what) """ cmd.zoom(what) return 1 def rpcSet(prop, val, obj): """ executes a PyMol set command return value is either the result of the command or the empty string """ res = cmd.set(prop, val, obj) if res is not None: return res else: return '' def rpcGet(prop, obj): """ executes a PyMol get command return value is either the result of the command or the empty string """ res = cmd.get(prop, obj) if res is not None: return res else: return '' def rpcPing(): """ Used to establish whether or not the server is alive. This is a good thing to call after establishing a connection just to make sure that everything is ok. Returns 1 """ return 1 def rpcLabel(pos, labelText, id='lab1', color=(1, 1, 1)): """ create a text label Arguments: pos: a 3 tuple with the position of the label text: a string with the label color: a 3 tuple with the color of the label. (1,1,1) is white id: (OPTIONAL) the name of the object to be created NOTE: at the moment this is, how you say, a hack """ x, y, z = pos text = """ Atom 1 0 0 0 0 0 0 0 0 0999 V2000 % 10.4f% 10.4f%10.4f C 0 0 0 0 0 0 0 0 0 0 0 0 M END""" % (x, y, z) cmd.read_molstr(text, id) cmd.label("%s" % (id), '"%s"' % labelText) cmd.hide("nonbonded", id) cmd.set_color("%s-color" % id, color) cmd.color("%s-color" % id, id) return 1 def rpcResetCGO(id): """ removes a CGO from the local dictionary """ global cgoDict if id == "*": cgoDict = {} res = 1 elif id in cgoDict: del (cgoDict[id]) res = 1 else: res = 0 return res def rpcSphere(pos, rad, color, id='cgo', extend=1, transparent=0, transparency=0.5): """ create a sphere Arguments: pos: a 3 tuple with the position of the sphere rad: a float with the radius color: a 3 tuple with the color of the sphere. (1,1,1) is white id: (OPTIONAL) the name of the object to be created extend: (OPTIONAL) if this is nonzero, the object will be cleared before adding the new sphere. Otherwise the sphere is appended to the ojbect transparent: (OPTIONAL) sets the object to be transparent transparency: (OPTIONAL) the percent transparency of the object """ r, g, b = color x, y, z = pos if extend: obj = cgoDict.get(id, []) else: obj = [] if not transparent: o = [] else: o = [cgo.ALPHA, 1 - transparency] o.extend([cgo.COLOR, r, g, b, cgo.SPHERE, x, y, z, rad]) obj.extend(o) cgoDict[id] = obj cmd.load_cgo(obj, id, 1) return 1 def rpcRenderCGO(cgoV, id='cgo', extend=1): """ renders a CGO vector Arguments: cgoV: a vector of floats id: (OPTIONAL) the name of the object to be created extend: (OPTIONAL) if this is nonzero, the object will be cleared before adding the new sphere. Otherwise the sphere is appended to the ojbect """ if extend: obj = cgoDict.get(id, []) else: obj = [] obj.extend(cgoV) cmd.load_cgo(obj, id, 1) return 1 def rpcSpheres(sphereD, id='cgo', extend=1): """ create a sphere Arguments: sphereD: a series of (pos,rad,color,transparent,transparency) tuples id: (OPTIONAL) the name of the object to be created extend: (OPTIONAL) if this is nonzero, the object will be cleared before adding the new sphere. Otherwise the sphere is appended to the ojbect """ if extend: obj = cgoDict.get(id, []) else: obj = [] for pos, rad, color, transparent, transparency in sphereD: r, g, b = color x, y, z = pos if not transparent: o = [] else: o = [cgo.ALPHA, 1 - transparency] o.extend([cgo.COLOR, r, g, b, cgo.SPHERE, x, y, z, rad]) obj.extend(o) cgoDict[id] = obj cmd.load_cgo(obj, id, 1) return 1 def rpcCylinder(end1, end2, rad, color1, id='cgo', color2=None, extend=1, transparent=0, transparency=0.5): """ create a cylinder Arguments: end1: a 3 tuple with the position of end1 of the sphere end2: a 3 tuple with the position of end1 of the sphere rad: a float with the radius color1: a 3 tuple with the color of end1 of the sphere. (1,1,1) is white id: (OPTIONAL) the name of the object to be created color2: (OPTIONAL) a 3 tuple with the color of end2 of the sphere. (1,1,1) is white extend: (OPTIONAL) if this is nonzero, the object will be cleared before adding the new sphere. Otherwise the sphere is appended to the ojbect transparent: (OPTIONAL) sets the object to be transparent transparency: (OPTIONAL) the percent transparency of the object NOTE: the reason that color2 follows id is that I think clients are going to be interested in setting the id more often than they are going to care about the second color. """ global cgoDict if color2 is None: color2 = color1 r1, g1, b1 = color1 r2, g2, b2 = color2 x1, y1, z1 = end1 x2, y2, z2 = end2 if extend: obj = cgoDict.get(id, []) else: obj = [] if not transparent: o = [] else: o = [cgo.ALPHA, 1 - transparency] o.extend([cgo.CYLINDER, x1, y1, z1, x2, y2, z2, rad, r1, g1, b1, r2, g2, b2, ]) obj.extend(o) cgoDict[id] = obj cmd.load_cgo(obj, id, 1) return 1 def rpcShow(objs): """ shows (enables) an object (or objects)""" if type(objs) not in (types.ListType, types.TupleType): objs = (objs, ) for objName in objs: try: cmd.enable(objName) except Exception: res = 0 break else: res = 1 return res def rpcHide(objs): """ hides (disables) an object (or objects) """ if type(objs) not in (types.ListType, types.TupleType): objs = (objs, ) for objName in objs: try: cmd.disable(objName) except Exception: res = 0 break else: res = 1 return res def rpcDeleteObject(objName): """ deletes an object """ try: cmd.delete(objName) except Exception: res = 0 else: res = 1 return res def rpcDeleteAll(): """ deletes all objects """ res = cmd.delete('all') if res is not None: return res else: return '' def colorObj(objName, colorScheme): """ sets an molecule's color scheme Arguments: - objName: the object (molecule) to change - colorScheme: name of the color scheme to use for the object (should be either 'std' or one of the color schemes defined in pymol.utils) """ if colorScheme: if colorScheme == 'std': # this is an adaptation of the cbag scheme from util.py, but # with a gray carbon. cmd.color("magenta", "(" + objName + ")", quiet=1) cmd.color("oxygen", "(elem O and " + objName + ")", quiet=1) cmd.color("nitrogen", "(elem N and " + objName + ")", quiet=1) cmd.color("sulfur", "(elem S and " + objName + ")", quiet=1) cmd.color("hydrogen", "(elem H and " + objName + ")", quiet=1) cmd.color("gray", "(elem C and " + objName + ")", quiet=1) elif hasattr(utils, colorScheme): fn = getattr(utils, colorScheme) fn(objName, quiet=1) res = 1 else: res = 0 return res def rpcLoadPDB(data, objName, colorScheme='', replace=1): """ loads a molecule from a pdb string Arguments: data: the mol block objName: name of the object to create colorScheme: (OPTIONAL) name of the color scheme to use for the molecule (should be either 'std' or one of the color schemes defined in pymol.utils) replace: (OPTIONAL) if an object with the same name already exists, delete it before adding this one """ from pymol import util if replace: cmd.delete(objName) res = cmd.read_pdbstr(data, objName) colorObj(objName, colorScheme) if res is not None: return res else: return '' def rpcLoadMolBlock(data, objName, colorScheme='', replace=1): """ loads a molecule from a mol block Arguments: data: the mol block objName: name of the object to create colorScheme: (OPTIONAL) name of the color scheme to use for the molecule (should be either 'std' or one of the color schemes defined in pymol.utils) replace: (OPTIONAL) if an object with the same name already exists, delete it before adding this one """ from pymol import util if replace: cmd.delete(objName) res = cmd.read_molstr(data, objName) colorObj(objName, colorScheme) if res is not None: return res else: return '' def rpcLoadFile(fileName, objName='', format='', colorScheme='', replace=1): """ loads an object from a file Arguments: fileName: the file to load objName: (OPTIONAL) name of the object to create format: (OPTIONAL) the format of the input file colorScheme: (OPTIONAL) name of the color scheme to use for the object (should be either 'std' or one of the color schemes defined in pymol.utils) replace: (OPTIONAL) if an object with the same name already exists, delete it before adding this one """ if not objName: objName = fileName.split('.')[0] if replace: cmd.delete(objName) res = cmd.load(fileName, objName, format=format) colorObj(objName, colorScheme) if res is not None: return res else: return '' def rpcLoadSurface(fileName, objName, format='', surfaceLevel=1.0): """ loads surface data from a file and adds an isosurface Arguments: fileName: the file to load objName: (OPTIONAL) name of the object to create format: (OPTIONAL) the format of the input file surfaceLevel: (OPTIONAL) the isosurface level """ if not objName: objName = fileName.split('.')[0] gridName = 'grid-%s' % objName res = cmd.load(fileName, gridName, format='') cmd.isosurface(objName, gridName, level=surfaceLevel) if res is not None: return res else: return '' def rpcLoadSurfaceData(data, objName='surface', format='', surfaceLevel=1.0): """ loads surface data from a string and adds an isosurface Arguments: data: the data to load objName: (OPTIONAL) name of the object to create format: (OPTIONAL) the format of the input file surfaceLevel: (OPTIONAL) the isosurface level """ gridName = 'grid-%s' % objName # it would be nice if we didn't have to go by way of the temporary file, # but at the moment pymol will only read shapes from files tempnm = tempfile.mktemp('.grd') open(tempnm, 'w+').write(data) res = rpcLoadSurface(tempnm, objName, format='', surfaceLevel=surfaceLevel) os.unlink(tempnm) if res is not None: return res else: return '' def rpcSave(filename, objName='all', state=0, format=''): """ executes a cmd.save command Arguments: - filename: output filename - objName: (OPTIONAL) object(s) to be saved - state: (OPTIONAL) - format: (OPTIONAL) output format """ res = cmd.save(filename, objName, state, format) if res is not None: return res else: return '' def rpcRotate(vect, objName='', state=-1): """ rotates objects Arguments: - vect: a sequence with x y and z rotations - objName: (OPTIONAL) object to be rotated - state: (OPTIONAL) if zero only visible states are rotated, if -1 (the default), all states are rotated """ cmd.rotate('x', vect[0], objName, state=state) cmd.rotate('y', vect[1], objName, state=state) cmd.rotate('z', vect[2], objName, state=state) return 1 def rpcTranslate(vect, objName='all', state=-1): """ translates objects Arguments: - vect: a sequence with x y and z translations - objName: (OPTIONAL) object to be translated - state: (OPTIONAL) if zero only visible states are translated, if -1 (the default), all states are translated """ cmd.translate(vect, objNAme, state=state) return 1 def rpcGetNames(what='selections', enabledOnly=1): """ returns the results of cmd.get_names(what) """ return cmd.get_names(what, enabled_only=enabledOnly) def rpcIdentify(what='all', mode=0): """ returns the results of cmd.identify(what,mode) """ return cmd.identify(what, mode=mode) def rpcIndex(what='all'): """ returns the results of cmd.index(what) """ return cmd.index(what) def rpcCountAtoms(what='all'): """ returns the results of cmd.count_atoms(what) """ return cmd.count_atoms(what) def rpcIdAtom(what='all', mode=0): """ returns the results of cmd.id_atom(what) """ return cmd.id_atom(what, mode=mode) def rpcGetAtomCoords(what='all', state=0): """ returns the results of cmd.get_atom_coords(what,state) """ return cmd.get_atom_coords(what, state=state) def rpcHelp(what=''): """ returns general help text or help on a particular command """ global serv res = 'Command Not Found' if not what: res = serv.funcs.keys() else: funcs = serv.funcs if what in funcs: fn = funcs[what] res = "Function: %s(" % what defs = fn.func_defaults if defs: code = fn.func_code nDefs = len(defs) args = [] i = -1 for i in range(code.co_argcount - nDefs): args.append(code.co_varnames[i]) for j in range(nDefs): vName = code.co_varnames[j + i + 1] args.append("%s=%s" % (vName, repr(defs[j]))) res += ','.join(args) res += ')\n' if fn.func_doc: res += fn.func_doc return res def launch_XMLRPC(hostname='', port=_xmlPort, nToTry=_nPortsToTry): """ launches the xmlrpc server into a separate thread Arguments: hostname: (OPTIONAL) name of the host for the server (defaults to be the name of the localhost) port: (OPTIONAL) the first port to try for the server nToTry: (OPTIONAL) the number of possible ports to try (in case the first can't be opened) """ if not hostname: import os hostname = os.environ.get('PYMOL_RPCHOST', '') if not hostname or hostname.upper() == 'LOCALHOST': hostname = 'localhost' else: import socket hostname = socket.gethostbyname(socket.gethostname()) global cgoDict, serv cgoDict = {} for i in range(nToTry): try: serv = SimpleXMLRPCServer.SimpleXMLRPCServer((hostname, port + i), logRequests=0) except Exception: serv = None else: break if serv: print('xml-rpc server running on host %s, port %d' % (hostname, port + i)) serv.register_function(rpcCmd, 'do') serv.register_function(rpcQuit, 'quit') serv.register_function(rpcSet, 'set') serv.register_function(rpcGet, 'get') serv.register_function(rpcPing, 'ping') serv.register_function(rpcResetCGO, 'resetCGO') serv.register_function(rpcRenderCGO, 'renderCGO') serv.register_function(rpcSphere, 'sphere') serv.register_function(rpcSpheres, 'spheres') serv.register_function(rpcCylinder, 'cylinder') serv.register_function(rpcHide, 'hide') serv.register_function(rpcShow, 'show') serv.register_function(rpcZoom, 'zoom') serv.register_function(rpcDeleteObject, 'deleteObject') serv.register_function(rpcDeleteAll, 'deleteAll') serv.register_function(rpcLoadPDB, 'loadPDB') serv.register_function(rpcLoadMolBlock, 'loadMolBlock') serv.register_function(rpcLoadSurface, 'loadSurface') serv.register_function(rpcLoadSurfaceData, 'loadSurfaceData') serv.register_function(rpcLoadFile, 'loadFile') serv.register_function(rpcSave, 'save') serv.register_function(rpcLabel, 'label') serv.register_function(rpcRotate, 'rotate') serv.register_function(rpcTranslate, 'translate') serv.register_function(rpcGetNames, 'getNames') serv.register_function(rpcIdentify, 'identify') serv.register_function(rpcIndex, 'index') serv.register_function(rpcCountAtoms, 'countAtoms') serv.register_function(rpcIdAtom, 'idAtom') serv.register_function(rpcHelp, 'help') serv.register_function(rpcGetAtomCoords, 'getAtomCoords') serv.register_introspection_functions() t = threading.Thread(target=serv.serve_forever) t.setDaemon(1) t.start() else: print('xml-rpc server could not be started')
rvianello/rdkit
External/pymol/modules/pymol/rpc.py
Python
bsd-3-clause
17,644
[ "PyMOL", "RDKit" ]
47a1e6824e861b50cc67de0270e4204024db0ae33885764b18d9ba64bad33eeb
import librosa import scipy import scipy.linalg as linalg import scipy.signal as sig import numpy as np import sklearn.cluster as sklhc import scipy.cluster.hierarchy as scihc from collections import OrderedDict from .analysis import create_selfsim from ..VMO.utility.misc import entropy """Segmentation algorithms """ def segment_by_connectivity(connectivity, median_filter_width, cluster_method, **kwargs): obs_len = connectivity.shape[0] df = librosa.segment.timelag_filter(scipy.ndimage.median_filter) connectivity = df(connectivity, size=(1, median_filter_width)) connectivity[range(1, obs_len), range(obs_len - 1)] = 1.0 connectivity[range(obs_len - 1), range(1, obs_len)] = 1.0 connectivity[np.diag_indices(obs_len)] = 0 if cluster_method == 'spectral': return _seg_by_spectral_single_frame(connectivity=connectivity, **kwargs) elif cluster_method == 'spectral_agg': return _seg_by_spectral_agg_single_frame(connectivity=connectivity, **kwargs) else: return _seg_by_spectral_single_frame(connectivity=connectivity, **kwargs) def _seg_by_structure_feature(oracle, delta=0.05, width=9, hier=False, connectivity='rsfx'): self_sim = create_selfsim(oracle, method=connectivity) lag_sim = librosa.segment.recurrence_to_lag(self_sim, pad=False) sf = scipy.ndimage.filters.gaussian_filter(lag_sim, [0.5, width], 0, mode='reflect') novelty_curve = np.sqrt(np.mean(np.diff(sf, axis=1) ** 2, axis=0)) novelty_curve -= np.min(novelty_curve) novelty_curve /= np.max(novelty_curve) novelty_curve = np.insert(novelty_curve,0,0) bound_width=9 offset = int((bound_width - 1) / 2) tmp_novelty = np.pad(novelty_curve, [offset], mode='reflect') boundaries = [0] for i in range(len(novelty_curve)): if (np.greater(tmp_novelty[i + offset], tmp_novelty[i:i + offset]).all() and np.greater(tmp_novelty[i + offset], tmp_novelty[i + offset + 1:i + bound_width]).all() and tmp_novelty[i + offset] > delta): boundaries.append(i) boundaries.append(oracle.n_states-2) seg_sim_mat = np.zeros((len(boundaries) - 1, len(boundaries) - 1)) intervals = zip(boundaries[:-1], boundaries[1:]) self_sim[self_sim > 1.0] = 1.0 for i in range(len(boundaries) - 1): for j in range(len(boundaries) - 1): seg_sim_mat[i, j] = _segment_sim(self_sim[intervals[i][0]:intervals[i][1], intervals[j][0]:intervals[j][1]]) seg_sim_mat = (seg_sim_mat + seg_sim_mat.T) / 2 seg_sim_mat[seg_sim_mat < (np.mean(seg_sim_mat) + np.std(seg_sim_mat))] = 0.0 new_seg_mat = seg_sim_mat while True: new_seg_mat = np.dot(new_seg_mat, new_seg_mat) thresh_seg_mat = new_seg_mat new_seg_mat[new_seg_mat < 1.0] = 0.0 new_seg_mat[new_seg_mat >= 1.0] = 1.0 if np.array_equal(new_seg_mat, thresh_seg_mat): break labels = np.zeros(len(boundaries) - 1) for i in range(thresh_seg_mat.shape[0]): ind = np.nonzero(thresh_seg_mat[i, :]) label_ind = 0 for idx in ind[0]: if labels[idx]: if label_ind: labels[idx] = label_ind else: label_ind = labels[idx] else: if label_ind: labels[idx] = label_ind else: labels[idx] = i + 1 label_ind = i + 1 return np.array(boundaries), labels def _segment_sim(mat): u, v = mat.shape qmat = np.zeros((u, v)) for i in range(u): for j in range(v): if i < 1 or j < 1: qmat[i, j] = mat[i, j] else: qmat[i, j] = np.max([qmat[i-1, j-1], qmat[i-2, j-1], qmat[i-1, j-2]]) + mat[i, j] return np.max(qmat) / np.min([u, v]) def _seg_by_single_frame(oracle, cluster_method='agglomerative', connectivity='temporal', data='symbol', median_filter_width=9, **kwargs): obs_len = oracle.n_states - 1 median_filter_width = median_filter_width if data == 'raw': data = np.array(oracle.f_array[1:]) else: data = np.zeros((oracle.n_states - 1, oracle.num_clusters())) data[range(oracle.n_states - 1), oracle.data[1:]] = 1 if connectivity == 'temporal': connectivity = np.zeros((obs_len, obs_len)) elif type(connectivity) == np.ndarray: connectivity = connectivity else: connectivity = create_selfsim(oracle, method=connectivity) if cluster_method == 'agglomerative': return _seg_by_hc_single_frame(obs_len=obs_len, connectivity=connectivity, data=data, **kwargs) else: return segment_by_connectivity(connectivity, median_filter_width, cluster_method, **kwargs) def _seg_by_hc_single_frame(obs_len, connectivity, data, width=9, hier=False, **kwargs): _children, _n_c, _n_leaves, parents, distances = \ sklhc.ward_tree(data, connectivity=connectivity, return_distance=True) reconstructed_z = np.zeros((obs_len - 1, 4)) reconstructed_z[:, :2] = _children reconstructed_z[:, 2] = distances if 'criterion' in kwargs.keys(): criterion = kwargs['criterion'] else: criterion = 'distance' if hier: t_list = range(2, 11) label_dict = OrderedDict() boundary_dict = OrderedDict() criterion = 'maxclust' for t in t_list: boundaries, labels = _agg_segment(reconstructed_z, t, criterion, width, data) label_dict[np.max(labels) + 1] = labels boundary_dict[np.max(labels) + 1] = boundaries return boundary_dict, label_dict else: t = 0.7 * np.max(reconstructed_z[:, 2]) return _agg_segment(reconstructed_z, t, criterion, width, data) def _agg_segment(z, t, criterion, width, data): label = scihc.fcluster(z, t=t, criterion=criterion) k = len(np.unique(label)) boundaries = find_boundaries(label, width=width) while len(boundaries) < k + 1 and width > 0: width -= 3 boundaries = find_boundaries(label, width=width - 3) labels = segment_labeling(data, boundaries, c_method='kmeans', k=k) return boundaries, labels def _seg_by_spectral_single_frame(connectivity, width=9, hier=False, k_min=4, k_max=6): graph_lap = normalized_graph_laplacian(connectivity) if hier: k_max = 10 eigen_vecs = eigen_decomposition(graph_lap, k=k_max) boundaries, labels = clustering_by_entropy(eigen_vecs, k_min=k_min, width=width, hier=hier) return boundaries, labels def _seg_by_spectral_agg_single_frame(connectivity, width=9): graph_lap = normalized_graph_laplacian(connectivity) eigen_vecs = eigen_decomposition(graph_lap) x = librosa.util.normalize(eigen_vecs, norm=2, axis=1) z = scihc.linkage(x, method='ward') t = 0.75 * np.max(z[:, 2]) return _agg_segment(z, t, criterion='distance', width=width, data=x) def clustering_by_entropy(eigen_vecs, k_min=1, width=9, hier=False): best_score = -np.inf best_boundaries = [0, eigen_vecs.shape[0] - 1] best_n_types = 1 y_best = eigen_vecs[:, :1] if hier: label_dict = OrderedDict() boundary_dict = OrderedDict() k_min = 2 for n_types in range(k_min, eigen_vecs.shape[1]): y = librosa.util.normalize(eigen_vecs[:, :n_types], norm=2, axis=1) # Try to label the data with n_types c = sklhc.KMeans(n_clusters=n_types, n_init=100) labels = c.fit_predict(y) # Find the label change-points boundaries = find_boundaries(labels, width) # boundaries now include start and end markers; n-1 is the number of segments if len(boundaries) < n_types + 1: n_types = len(boundaries) - 1 values = np.unique(labels) hits = np.zeros(len(values)) for v in values: hits[v] = np.sum(labels == v) hits = hits / hits.sum() score = entropy(hits) / np.log(n_types) if score > best_score: best_boundaries = boundaries best_n_types = n_types best_score = score y_best = y if hier: labels = segment_labeling(y, boundaries, c_method='kmeans', k=n_types) label_dict[n_types] = labels boundary_dict[n_types] = boundaries # Classify each segment centroid labels = segment_labeling(y_best, best_boundaries, c_method='kmeans', k=best_n_types) best_labels = labels if hier: return boundary_dict, label_dict else: return best_boundaries, best_labels def segmentation(oracle, method='symbol_agglomerative', **kwargs): if oracle: if method == 'symbol_agglomerative': return _seg_by_single_frame(oracle, cluster_method='agglomerative', **kwargs) elif method == 'symbol_spectral': return _seg_by_single_frame(oracle, cluster_method='spectral', **kwargs) elif method == 'symbol_spectral_agglomerative': return _seg_by_single_frame(oracle, cluster_method='spectral_agg', **kwargs) elif method == 'structure_feature': return _seg_by_structure_feature(oracle, **kwargs) else: print("Method unknown. Use spectral clustering.") return _seg_by_single_frame(oracle, cluster_method='spectral', **kwargs) else: raise TypeError('Oracle is None') """Adapted from Brian McFee`s spectral clustering algorithm for music structural segmentation https://github.com/bmcfee/laplacian_segmentation """ def segment_labeling(x, boundaries, c_method='kmeans', k=5): x_sync = librosa.util.utils.sync(x.T, boundaries[:-1]) if c_method == 'kmeans': c = sklhc.KMeans(n_clusters=k, n_init=100) seg_labels = c.fit_predict(x_sync.T) elif c_method == 'agglomerative': z = scihc.linkage(x_sync.T, method='ward') t = k * np.max(z[:, 2]) seg_labels = scihc.fcluster(z, t=t, criterion='distance') else: c = sklhc.KMeans(n_clusters=k, n_init=100) seg_labels = c.fit_predict(x_sync.T) return seg_labels def find_boundaries(frame_labels, width=9): # frame_labels = np.pad(frame_labels, (int(width / 2), int(width / 2) + 1), mode='edge') # frame_labels = np.array([stats.mode(frame_labels[i:j])[0][0] # for (i, j) in zip(range(0, len(frame_labels) - width), # range(width, len(frame_labels)))]) boundaries = 1 + np.flatnonzero(frame_labels[:-1] != frame_labels[1:]) # np.asarray(np.where(frame_labels[:-1] != frame_labels[1:])).reshape((-1,)) boundaries = np.unique(np.concatenate([[0], boundaries, [len(frame_labels)-1]])) return boundaries def normalized_graph_laplacian(mat): mat_inv = 1. / np.sum(mat, axis=1) mat_inv[~np.isfinite(mat_inv)] = 1. mat_inv = np.diag(mat_inv ** 0.5) laplacian = np.eye(len(mat)) - mat_inv.dot(mat.dot(mat_inv)) return laplacian def eigen_decomposition(mat, k=6): # Changed from 11 to 8 then to 6(7/22) vals, vecs = linalg.eig(mat) vals = vals.real vecs = vecs.real idx = np.argsort(vals) vals = vals[idx] vecs = vecs[:, idx] if len(vals) < k + 1: k = -1 vecs = scipy.ndimage.median_filter(vecs, size=(5,1)) return vecs[:, :k]
wangsix/vmo
vmo/analysis/segmentation.py
Python
gpl-3.0
11,477
[ "Brian" ]
ba0f39c3011e6b4413ec025c1c3b39cb13dff30ba178021f7f6a975fd86535dd
#!/usr/bin/env python """ This module contains a class to parse a ppi predictions output file in tsv format and perform network related operations on it. """ from collections import OrderedDict as Od import numpy as np import pandas as pd from ..base.constants import P1, P2, G1, G2, SOURCE, TARGET from ..database.models import Protein from ..database.utilities import full_training_network class InteractionNetwork(object): """ Utility class to ecapsulate all network related operations for predictions over some interaction network. Parameters ----------- interactions, pd.DataFrame or string. The dataframe containing prediction output in the PTSV format or a string directing the path containing the PTSV file. Attributes ----------- interactions_: :class:`pd.DataFrame` The dataframe from the input parameter or loaded from the input parameter. Contains columns p1, p2, g1, g2 for the accession, and a series of ptm labels for each predicted label. columns_: list[str] List of columns in `interactions_` gene_names_: dict[str, str] A mapping of protein accession to gene accession found in `interactions_` edges_ : list List of tuples of `UniProt` accession parsed from the `source` and `target` columns output_dir_ : str Output directory. training_edges : set Edges that are part of the training network according the database. These are the :class:`Interaction`s in the parsed file that have instances with `is_training` set to True. training_nodes : set All :class:`Protein`s in the supplied interactions which appear in :class:`Interaction`s with `is_training` set to True. """ def __init__(self, interactions, sep='\t', output_dir='./'): self.interactions_ = interactions self.columns_ = list(interactions.columns) self.gene_names_ = {} self.output_dir_ = output_dir self.sep = sep self.edges_ = list(zip(interactions[P1], interactions[G1])) self.training_edges = {} self.training_nodes = set() p1_g1 = zip(interactions[P1], interactions[G1]) p2_g2 = zip(interactions[P2], interactions[G2]) for (p1, g1), (p2, g2) in zip(p1_g1, p2_g2): self.gene_names_[p1] = g1 self.gene_names_[p2] = g2 self.labels = [ c[:-3] for c in interactions.columns if ('-pr' in c) and ('sum' not in c) and ('max' not in c) ] training_edges = full_training_network(taxon_id=None) for interaction in training_edges: a = Protein.query.get(interaction.source).uniprot_id b = Protein.query.get(interaction.target).uniprot_id a, b = sorted((a, b)) self.training_edges[(a, b)] = interaction.labels_as_list for (a, b) in self.training_edges: self.training_nodes.add(a) self.training_nodes.add(b) def _validate_threshold(self, value): try: return float(value) except (ValueError, TypeError): raise ValueError( "Threshold must be a float. Found {}.".format(type(value)) ) def _label_to_column(self, label): if not label.endswith('-pr'): return label + '-pr' else: return label def node_in_training_set(self, node): return node in self.training_nodes def edge_in_training_set(self, edge, label=None): p1, p2 = sorted(edge) if label is None: return (p1, p2) in self.training_edges else: return label.capitalize() in self.training_edges.get((p1, p2), []) def induce_subnetwork_from_label(self, label, threshold=0.5): """ Filter the interactions to contain those with predicted `label` at or over the `threshold`. Parameters ---------- label: str A PTM label seen in `interactions_` threshold: float, optional, default: 0.5 Minimum prediction probability. Returns ------- :class:`InteractionNetwork` Returns self """ if label not in self.labels: raise ValueError( "{} is not a valid label. Please choose from {}.".format( label, ', '.join(self.labels)) ) column = self._label_to_column(label) threshold = self._validate_threshold(threshold) label_idx = self.interactions_[ self.interactions_[column] >= threshold ].index.values pp_path = '{}/{}_pp.tsv'.format(self.output_dir_, label) noa_path = '{}/{}_node_attrs.noa'.format(self.output_dir_, label) eda_path = '{}/{}_edge_attrs.eda'.format(self.output_dir_, label) self._write_cytoscape_files( pp_path=pp_path, noa_path=noa_path, eda_path=eda_path, idx_selection=label_idx, label=label ) return self def induce_subnetwork_from_pathway(self, accession_list, threshold, genes=False): """ Filter the interactions to contain any interaction with both accessions in `accesion_list` and with predictions at or over the `threshold`. Parameters ---------- accesion_list: str A list of uniprot/gene accessions to induce a network from. Network will induce all edges incident upon these accessions. threshold: float Minimum prediction probability. genes: boolean, optional, default: False Use gene identifier accessions in `interactions_` instead. Set this to True if your `accession_list` is a list of gene names. Returns ------- :class:`InteractionNetwork` Returns self """ df = self.interactions_ accesion_list = set(accession_list) threshold = self._validate_threshold(threshold) a, b = (P1, P2) if genes: a, b = (G1, G2) edges = [tuple(sorted([p1, p2])) for (p1, p2) in zip(df[a], df[b])] edge_idx = np.asarray( [ i for i, (p1, p2) in enumerate(edges) if (p1 in accesion_list) or (p2 in accesion_list) ] ) if len(edge_idx) == 0: raise ValueError( "No subnetwork could be induced with the given" "pathway list." ) # Filter for the interactions with a max probability greater # than `threshold`. df = df.loc[edge_idx, ] sel = (df['max-pr'] >= threshold).values edge_idx = df[sel].index.values if len(edge_idx) == 0: raise ValueError( "Threshold set too high and no subnetwork could be " "induced with the given pathway list." ) label = 'pathway' pp_path = '{}/{}_pp.tsv'.format(self.output_dir_, label) noa_path = '{}/{}_node_attrs.noa'.format(self.output_dir_, label) eda_path = '{}/{}_edge_attrs.eda'.format(self.output_dir_, label) self._write_cytoscape_files( pp_path=pp_path, noa_path=noa_path, eda_path=eda_path, idx_selection=edge_idx ) return self def _write_cytoscape_files(self, noa_path, eda_path, pp_path, idx_selection, label=None): """ Compute some node and edge attributes and write these to files that can be loaded in cytoscape. """ df = self.interactions_.loc[idx_selection, ] edges = [sorted([p1, p2]) for (p1, p2) in zip(df[P1].values, df[P2].values)] # Compute some selected node-attributes, # Write the noa (noda-attribute) file. accessions = sorted(set([p for tup in edges for p in tup])) gene_names = [self.gene_names_[a] for a in accessions] node_in_training = [self.node_in_training_set(a) for a in accessions] cyto_n_attrs = pd.DataFrame(Od([ ('name', accessions), ('node in training', node_in_training), ('gene name', gene_names) ])) cyto_n_attrs.to_csv(noa_path, sep=self.sep, index=False) # Compute some selected edge-attributes a, # Write the eda (edge-attribute) file. columns = ['source', 'target', 'name', 'edge in training', 'max-pr'] cyto_e_attrs = dict() cyto_e_attrs['source'] = [p1 for p1, _ in edges] cyto_e_attrs['target'] = [p2 for _, p2 in edges] cyto_e_attrs['name'] = ['{} pp {}'.format(p1, p2) for p1, p2 in edges] cyto_e_attrs['edge in training'] = [ self.edge_in_training_set(e, label) for e in edges ] cyto_e_attrs['max-pr'] = list(df['max-pr'].values) for label in self.labels: column = self._label_to_column(label) cyto_e_attrs[column] = df[column].values columns.append(column) cyto_interactions = pd.DataFrame(cyto_e_attrs, columns=columns) cyto_interactions.to_csv(pp_path, sep=self.sep, index=False) return self
daniaki/pyPPI
pyppi/network_analysis/__init__.py
Python
mit
9,649
[ "Cytoscape" ]
12e537fd43120b9e583739027c18a8990fc7ff8adc59948186e1c102f3e5a7f6
from __future__ import print_function import IMP import IMP.test import IMP.core import IMP.atom class Tests(IMP.test.TestCase): def _test_simple(self): """Check that hierarchies don't have circular ref counts """ # make sure internal things are created m = IMP.Model() h = IMP.atom.Hierarchy.setup_particle(IMP.Particle(m)) del m del h refcnt = IMP.test.RefCountChecker(self) m = IMP.Model() h = IMP.atom.Hierarchy.setup_particle(IMP.Particle(m)) hc = IMP.atom.Hierarchy.setup_particle(IMP.Particle(m)) h.add_child(hc) del m del hc del h refcnt.assert_number(0) def _test_simple_bond(self): """Check that bonded don't have circular ref counts """ m = IMP.Model() h = IMP.atom.Bonded.setup_particle(IMP.Particle(m)) del m del h refcnt = IMP.test.RefCountChecker(self) m = IMP.Model() h = IMP.atom.Bonded.setup_particle(IMP.Particle(m)) hc = IMP.atom.Bonded.setup_particle(IMP.Particle(m)) IMP.atom.create_bond(h, hc, 0) del m del hc del h refcnt.assert_number(0) def _test_bonded(self): """Check that pdbs don't have circular ref counts """ # charm creates all sorts of things m = IMP.Model() h = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m) del m del h IMP.set_log_level(IMP.MEMORY) refcnt = IMP.test.RefCountChecker(self) m = IMP.Model() print("reading") h = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m) del m del h refcnt.assert_number(0) def test_rbbonded(self): """Check that pdbs with rigid bodies don't have circular ref counts """ m = IMP.Model() h = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m) rb = IMP.atom.create_rigid_body([h], "test rb") # print [x.get_name() for x in rb.get_members()] del rb del m del h print("initial live") while (True): # charm creates all sorts of things refcnt = IMP.test.RefCountChecker(self) m = IMP.Model() p = IMP.Particle(m) p.set_name("TEST") del p h = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m) # IMP.atom.show_molecular_hierarchy(h) rb = IMP.atom.create_rigid_body([h], "test rb") # print [x.get_name() for x in rb.get_members()] del rb #del x del m del h print(dir()) # print "live" # print [x for x in IMP.Object.get_live_object_names() if # (x.find("CHARMM")==-1)] refcnt.assert_number(0) # except: # pass # print "wait" # for i in range(0,60000000): # pass # print "end wait" return if __name__ == '__main__': IMP.test.main()
shanot/imp
modules/atom/test/test_refcount_hierarchy.py
Python
gpl-3.0
3,105
[ "CHARMM" ]
2760d4e7c823b86e11f06d7aa5e6182cf356fb5115b872aab61269ca0e7e585d
################################################################################ # Peach - Computational Intelligence for Python # Jose Alexandre Nalon # # This file: nn/nn.py # Basic topologies of neural networks ################################################################################ # Doc string, reStructuredText formatted: __doc__ = """ Basic topologies of neural networks. This sub-package implements various neural network topologies, see the complete list below. These topologies are implemented using the ``Layer`` class of the ``base`` sub-package. Please, consult the documentation of that module for more information on layers of neurons. The neural nets implemented here don't derive from the ``Layer`` class, instead, they have instance variables to take control of them. Thus, there is no base class for networks. While subclassing the classes of this module is usually safe, it is recomended that a new kind of net is developed from the ground up. """ ################################################################################ from numpy import array, sum, abs, reshape, sqrt, argmin, zeros, dot import random from base import * from af import * from lrules import * ################################################################################ class FeedForward(list): ''' Classic completely connected neural network. A feedforward neural network is implemented as a list of layers, each layer being a ``Layer`` object (please consult the documentation on the ``base`` module for more information on layers). The layers are completely connected, which means that every neuron in one layers is connected to every other neuron in the following layer. There is a number of learning methods that are already implemented, but in general, any learning class derived from ``FFLearning`` can be used. No other kind of learning can be used. Please, consult the documentation on the ``lrules`` (*learning rules*) module. ''' def __init__(self, layers, phi=Linear, lrule=BackPropagation, bias=False): ''' Initializes a feedforward neural network. A feedforward network is implemented as a list of layers, completely connected. :Parameters: layers A list of integers containing the shape of the network. The first element of the list is the number of inputs of the network (or, as somebody prefer, the number of input neurons); the number of outputs is the number of neurons in the last layer. Thus, at least two numbers should be given. phi The activation functions to be used with each layer of the network. Please consult the ``Layer`` documentation in the ``base`` module for more information. This parameter can be a single function or a list of functions. If only one function is given, then the same function is used in every layer. If a list of functions is given, then the layers use the functions in the sequence given. Note that heterogeneous networks can be created that way. Defaults to ``Linear``. lrule The learning rule used. Only ``FFLearning`` objects (instances of the class or of the subclasses) are allowed. Defaults to ``BackPropagation``. Check the ``lrules`` documentation for more information. bias If ``True``, then the neurons are biased. ''' list.__init__(self, [ ]) layers = list(layers) for n, m in zip(layers[:-1], layers[1:]): self.append(Layer((m, n), bias=bias)) self.phi = phi self.__n = len(self) self.__lrule = lrule if isinstance(lrule, FFLearning): self.__lrule = lrule else: try: issubclass(lrule, FFLearning) self.__lrule = lrule() except TypeError: raise ValueError, 'uncompatible learning rule' def __getnlayers(self): return self.__n nlayers = property(__getnlayers, None) '''Number of layers of the neural network. Not writable.''' def __getbias(self): r = [ ] for l in self: r.append(l.bias) return tuple(r) bias = property(__getbias, None) '''A tuple containing the bias of each layer. Not writable.''' def __gety(self): return self[-1].y y = property(__gety, None) '''A list of activation values for each neuron in the last layer of the network, ie., the answer of the network. This property is available only after the network is fed some input.''' def __getphi(self): r = [ ] for l in self: r.append(l.phi) return tuple(r) def __setphi(self, phis): try: phis = tuple(phis) for w, v in zip(self, phis): w.phi = v except TypeError: for w in self: w.phi = phis phi = property(__getphi, __setphi) '''Activation functions for every layer in the network. It is a list of ``Activation`` objects, but can be set with only one function. In this case, the same function is used for every layer.''' def __call__(self, x): ''' The feedforward method of the network. The ``__call__`` interface should be called if the answer of the neuron network to a given input vector ``x`` is desired. *This method has collateral effects*, so beware. After the calling of this method, the ``y`` property is set with the activation potential and the answer of the neurons, respectivelly. :Parameters: x The input vector to the network. :Returns: The vector containing the answer of every neuron in the last layer, in the respective order. ''' for w in self: x = w(x) return self[-1].y def learn(self, x, d): ''' Applies one example of the training set to the network. Using this method, one iteration of the learning procedure is made with the neurons of this network. This method presents one example (not necessarilly of a training set) and applies the learning rule over the network. The learning rule is defined in the initialization of the network, and some are implemented on the ``lrules`` method. New methods can be created, consult the ``lrules`` documentation but, for ``FeedForward`` instances, only ``FFLearning`` learning is allowed. Also, notice that *this method only applies the learning method!* The network should be fed with the same input vector before trying to learn anything first. Consult the ``feed`` and ``train`` methods below for more ways to train a network. :Parameters: x Input vector of the example. It should be a column vector of the correct dimension, that is, the number of input neurons. d The desired answer of the network for this particular input vector. Notice that the desired answer should have the same dimension of the last layer of the network. This means that a desired answer should be given for every output of the network. :Returns: The error obtained by the network. ''' self.__lrule(self, x, d) return sum(abs(d - self.y)) def feed(self, x, d): ''' Feed the network and applies one example of the training set to the network. Using this method, one iteration of the learning procedure is made with the neurons of this network. This method presents one example (not necessarilly of a training set) and applies the learning rule over the network. The learning rule is defined in the initialization of the network, and some are implemented on the ``lrules`` method. New methods can be created, consult the ``lrules`` documentation but, for ``FeedForward`` instances, only ``FFLearning`` learning is allowed. Also, notice that *this method feeds the network* before applying the learning rule. Feeding the network has collateral effects, and some properties change when this happens. Namely, the ``y`` property is set. Please consult the ``__call__`` interface. :Parameters: x Input vector of the example. It should be a column vector of the correct dimension, that is, the number of input neurons. d The desired answer of the network for this particular input vector. Notice that the desired answer should have the same dimension of the last layer of the network. This means that a desired answer should be given for every output of the network. :Returns: The error obtained by the network. ''' self(x) return self.learn(x, d) def train(self, train_set, imax=2000, emax=1e-5, randomize=False): ''' Presents a training set to the network. This method automatizes the training of the network. Given a training set, the examples are shown to the network (possibly in a randomized way). A maximum number of iterations or a maximum admitted error should be given as a stop condition. :Parameters: train_set The training set is a list of examples. It can have any size and can contain repeated examples. In fact, the definition of the training set is open. Each element of the training set, however, should be a two-tuple ``(x, d)``, where ``x`` is the input vector, and ``d`` is the desired response of the network for this particular input. See the ``learn`` and ``feed`` for more information. imax The maximum number of iterations. Examples from the training set will be presented to the network while this limit is not reached. Defaults to 2000. emax The maximum admitted error. Examples from the training set will be presented to the network until the error obtained is lower than this limit. Defaults to 1e-5. randomize If this is ``True``, then the examples are shown in a randomized order. If ``False``, then the examples are shown in the same order that they appear in the ``train_set`` list. Defaults to ``False``. ''' i = 0 error = 1 s = len(train_set) while i<imax and error>emax: if randomize: x, d = random.choice(train_set) else: x, d = train_set[i%s] error = self.feed(x, d) i = i+1 return error ################################################################################ class SOM(Layer): ''' A Self-Organizing Map (SOM). A self-organizing map is a type of neural network that is trained via unsupervised learning. In particular, the self-organizing map finds the neuron closest to an input vector -- this neuron is the winning neuron, and it is the answer of the network. Thus, the SOM is usually used for classification and pattern recognition. The SOM is a single-layer network, so this class subclasses the ``Layer`` class. But some of the properties of a ``Layer`` object are not available or make no sense in this context. ''' def __init__(self, shape, lrule=Competitive): ''' Initializes a self-organizing map. A self-organizing map is implemented as a layer of neurons. There is no connection among the neurons. The answer to a given input is the neuron closer to the given input. ``phi`` (the activation function) ``v`` (the activation potential) and ``bias`` are not used. :Parameters: shape Stablishes the size of the SOM. It must be a two-tuple of the format ``(m, n)``, where ``m`` is the number of neurons in the layer, and ``n`` is the number of inputs of each neuron. The neurons in the layer all have the same number of inputs. lrule The learning rule used. Only ``SOMLearning`` objects (instances of the class or of the subclasses) are allowed. Defaults to ``Competitive``. Check the ``lrules`` documentation for more information. ''' Layer.__init__(self, shape, phi=None, bias=False) self.__lrule = lrule self.__y = None self.__phi = None if isinstance(lrule, SOMLearning): self.__lrule = lrule else: try: issubclass(lrule, SOMLearning) self.__lrule = lrule() except TypeError: raise ValueError, 'uncompatible learning rule' def __gety(self): if self.__y is None: raise ValueError, "activation unavailable" else: return self.__y y = property(__gety, None) '''The winning neuron for a given input, the answer of the network. This property is available only after the network is fed some input.''' def __call__(self, x): ''' The response of the network to a given input. The ``__call__`` interface should be called if the answer of the neuron network to a given input vector ``x`` is desired. *This method has collateral effects*, so beware. After the calling of this method, the ``y`` property is set with the activation potential and the answer of the neurons, respectivelly. :Parameters: x The input vector to the network. :Returns: The winning neuron. ''' x = reshape(x, (1, self.inputs)) dist = sqrt(sum((x - self.weights)**2, axis=1)) self.__y = argmin(dist) return self.y def learn(self, x): ''' Applies one example of the training set to the network. Using this method, one iteration of the learning procedure is made with the neurons of this network. This method presents one example (not necessarilly of a training set) and applies the learning rule over the network. The learning rule is defined in the initialization of the network, and some are implemented on the ``lrules`` method. New methods can be created, consult the ``lrules`` documentation but, for ``SOM`` instances, only ``SOMLearning`` learning is allowed. Also, notice that *this method only applies the learning method!* The network should be fed with the same input vector before trying to learn anything first. Consult the ``feed`` and ``train`` methods below for more ways to train a network. :Parameters: x Input vector of the example. It should be a column vector of the correct dimension, that is, the number of input neurons. :Returns: The error obtained by the network. ''' self.__lrule(self, x) return sum(abs(x - self.y)) def feed(self, x): ''' Feed the network and applies one example of the training set to the network. Using this method, one iteration of the learning procedure is made with the neurons of this network. This method presents one example (not necessarilly of a training set) and applies the learning rule over the network. The learning rule is defined in the initialization of the network, and some are implemented on the ``lrules`` method. New methods can be created, consult the ``lrules`` documentation but, for ``SOM`` instances, only ``SOMLearning`` learning is allowed. Also, notice that *this method feeds the network* before applying the learning rule. Feeding the network has collateral effects, and some properties change when this happens. Namely, the ``y`` property is set. Please consult the ``__call__`` interface. :Parameters: x Input vector of the example. It should be a column vector of the correct dimension, that is, the number of input neurons. :Returns: The error obtained by the network. ''' self(x) return self.learn(x) def train(self, train_set, imax=2000, emax=1e-5, randomize=False): ''' Presents a training set to the network. This method automatizes the training of the network. Given a training set, the examples are shown to the network (possibly in a randomized way). A maximum number of iterations or a maximum admitted error should be given as a stop condition. :Parameters: train_set The training set is a list of examples. It can have any size and can contain repeated examples. In fact, the definition of the training set is open. Each element of the training set, however, should be a input vector of the correct dimensions, See the ``learn`` and ``feed`` for more information. imax The maximum number of iterations. Examples from the training set will be presented to the network while this limit is not reached. Defaults to 2000. emax The maximum admitted error. Examples from the training set will be presented to the network until the error obtained is lower than this limit. Defaults to 1e-5. randomize If this is ``True``, then the examples are shown in a randomized order. If ``False``, then the examples are shown in the same order that they appear in the ``train_set`` list. Defaults to ``False``. ''' i = 0 error = 1 s = len(train_set) while i<imax and error>emax: if randomize: x = random.choice(train_set) else: x = train_set[i%s] error = self.feed(x) i = i+1 return error ################################################################################ class GRNN(object): """ GRNN is the implementation of General Regression Neural Network, a kind of probabilistic neural network used in regression tasks. """ def __init__(self, sigma=0.1): """ Initializes the network. Is not necessary to inform the training set size, GRNN will do it by itself in ``train`` method. :Parameters: sigma A real number. This value determines the spread of probability density function (i.e is the smoothness parameter). A great value for sigma will result in a large spread gaussian and the sample points will cover a wide range of inputs, while a small value will create a limited spread gaussian and the sample points will cover a small range of inputs """ self._samples = None self._targets = None self.sigma = sigma def _kernel(self, x1, x2): """ This method gives a measure of how well a training sample can represent the position of prediction (i.e. how well x1 can represent x2, or vice versa). If the distance D between x1 and x2 is small, result becomes big. For distance 0 (i.e. x1 == x2), result becomes one and the sample point is the best representation of prediction point. In the probabilistic view, this method calculates the probability distribution. """ D = x1-x2 return exp(-dot(D, D)/(2*self.sigma**2)) def train(self, sampleInputs, targets): """ Presents a training set to the network. This method uses the sample inputs to set the size of network. :Parameters: sampleInputs Should be a list of numbers or a list of ``numpy.array`` to set the sample inputs. These inputs are used to calculate the distance between prediction points. targets The target values of sample inputs. Should be a list of numbers. """ self._samples = array(sampleInputs) self._targets = array(targets) def __call__(self, x): """ The method to predict a value from input ``x``. :Parameters: x The input vector to the network. :Returns: The predicted value. """ values = [self._kernel(x, x2) for x2 in self._samples] regular = sum(values) return dot(values, self._targets)/regular class PNN(object): """ PNN is the implementation of Probabilistic Neural Network, a network used for classification tasks """ def __init__(self, sigma=0.1): """ Initializes the network. Is not necessary to inform the training set size, PNN will do it by itself in ``train`` method. :Parameters: sigma A real number. This value determines the spread of probability density function (i.e is the smoothness parameter). A great value for sigma will result in a large spread gaussian and the sample points will cover a wide range of inputs, while a small value will create a limited spread gaussian and the sample points will cover a small range of inputs """ self.sigma = sigma self._categorys = None def _kernel(self, x1, x2): """ This method gives a measure of how well a training sample can represent the position of evaluation (i.e. how well x1 can represent x2, or vice versa). If the distance D between x1 and x2 is small, result becomes big. For distance 0 (i.e. x1 == x2), result becomes one and the sample point is the best representation of evaluation point. In the probabilistic view, this method calculates the probability distribution. """ D = x1-x2 return exp(-dot(D, D)/(2*self.sigma**2)) def train(self, trainSet): """ Presents a training set to the network. This method uses the sample inputs to set the size of network. :Parameters: train_set The training set is a list of examples. It can have any size. In fact, the definition of the training set is open. Each element of the training set, however, should be a two-tuple ``(x, d)``, where ``x`` is the input vector, and ``d`` is the desired response of the network for this particular input, i.e the category of ``x`` pattern. """ self._categorys = {} for pattern, category in trainSet: if category not in self._categorys: self._categorys[category] = [] self._categorys[category].append(array(pattern)) def __call__(self, x): """ The method to classify the input ``x`` into one of trained category. :Parameters: x The input vector to the network. :Returns: The category that best represent the input vector. """ sums = {} for category in self._categorys: patterns = self._categorys[category] sums[category] = sum([self._kernel(x, x2) for x2 in patterns]) sums[category] /= float(len(patterns)) return max(sums, key=lambda x:sums[x]) ################################################################################ # Test if __name__ == "__main__": pass
anki1909/peach
peach/nn/nnet.py
Python
lgpl-2.1
24,145
[ "Gaussian", "NEURON" ]
20eefaa470057c16dc3280a220453d208e90a54b33e0c11b01af93c8de8b86cb
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Shortbred(Package): """ShortBRED is a system for profiling protein families of interest at very high specificity in shotgun meta'omic sequencing data.""" homepage = "https://huttenhower.sph.harvard.edu/shortbred" url = "https://bitbucket.org/biobakery/shortbred/get/0.9.4.tar.gz" version('0.9.4', 'ad3dff344cbea3713e78b384afad28fd') depends_on('blast-plus@2.2.28:') depends_on('cdhit@4.6:') depends_on('muscle@3.8.31:') depends_on('python@2.7.9:') depends_on('py-biopython') depends_on('usearch@6.0.307:') def install(self, spec, prefix): mkdirp(prefix.bin) install('shortbred_identify.py', prefix.bin) install('shortbred_quantify.py', prefix.bin) install_tree('src', prefix.src) def setup_environment(self, spack_env, run_env): run_env.prepend_path('PYTHONPATH', self.prefix)
EmreAtes/spack
var/spack/repos/builtin/packages/shortbred/package.py
Python
lgpl-2.1
2,142
[ "BLAST", "Biopython" ]
e24a555133717b8fcb726813ae91de84a50204e5e060f969ac0b0d475385cd48
#!/usr/bin/env python import os import sys sys.path.insert(0, os.path.abspath('lib')) from ansible.release import __version__, __author__ try: from setuptools import setup, find_packages except ImportError: print("Ansible now needs setuptools in order to build. Install it using" " your package manager (usually python-setuptools) or via pip (pip" " install setuptools).") sys.exit(1) setup(name='true-ansible', version=__version__, description='Radically simple IT automation', author=__author__, author_email='support@ansible.com', url='http://ansible.com/', license='GPLv3', # Ansible will also make use of a system copy of python-six if installed but use a # Bundled copy if it's not. install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'], package_dir={ '': 'lib' }, packages=find_packages('lib'), package_data={ '': ['module_utils/*.ps1', 'modules/core/windows/*.ps1', 'modules/extras/windows/*.ps1', 'galaxy/data/*'], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Natural Language :: English', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Systems Administration', 'Topic :: Utilities', ], scripts=[ 'bin/ansible', 'bin/ansible-playbook', 'bin/ansible-pull', 'bin/ansible-doc', 'bin/ansible-galaxy', 'bin/ansible-console', 'bin/ansible-vault', ], data_files=[], )
Censio/ansible-dev
setup.py
Python
gpl-3.0
2,025
[ "Galaxy" ]
b4a3cdef853db9d5022f2becc49baedf03880fb57b6eb6d302eb60e4bdfeca9f
#!/usr/bin/env python """ Plot ORA-IP annual mean profile (T or S) and Hiroshis or WOA13 1995-2004 profile. """ import os import sys import re import copy import glob import string import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import netCDF4 as nc from datetime import datetime from netcdftime import utime from seawater import dens0 # Global variables Alphabets = list(string.ascii_lowercase) LevelBounds = {} LevelBounds['T'] = np.array([[ 0, 100],[ 100, 300],\ [ 300, 700],[ 700, 1500],\ [1500,3000],[3000, 6000]]) LevelBounds['S'] = np.array([[ 0, 10],[ 10, 100],\ [ 100, 300],[ 300, 700],\ [ 700,1500],[1500, 3000],\ [3000, 4000]]) ModelLineColors = {"GECCO2":"darkred",\ # "GMAO":"blue",\ #"MOVECORE":"red",\ #"ORAS3":"red",\ "ORAP5":"red",\ #"CFSR":"green",\ "TP4":"green",\ "GLORYS2V1":"orange",\ "G2V3":"orange",\ "GSOP_GLORYS2V3":"orange",\ "GSOP_GLORYS2V4":"orange",\ "MOVEG2":"cyan",\ #"PEODAS":"cyan",\ "CGLORS":"lightgreen",\ "GloSea":"blue",\ "GloSea5_GO5":"blue",\ #"K7ODA":"pink",\ #"ORAS4":"lightgreen",\ "SODA":"brown",\ "ECDA":"yellow",\ #"PECDAS":"yellow",\ "UoR":"lightblue",\ "UR025":"lightblue",\ "EN3":"pink",\ "EN3v2a":"pink",\ "EN4":"pink",\ "EN4.2.0.g10":"pink",\ } # Models without Arctic: "ECCOJPL","GODAS","MOVEC","K7" # Models without sea ice: SODA # Not a model: EN3 class WOA13profile(object): """ WOA13 decadal means in 1 deg grid. """ def __init__(self,vname,plon,plat,dset='WOA13',\ months=range(1,13),syr=1995,eyr=2004,\ path='/home/uotilap/tiede/WOA/2013/'): self.dset = dset self.vname = vname # T or S self.lon = plon self.lat = plat self.months = months self.syr = syr self.eyr = eyr self.level_bounds = LevelBounds[vname] if vname=='T': ncname = 't_an' elif vname=='S': ncname = 's_an' else: print "%s has not been implemented! Exiting..." % vname sys.exit(1) data = [] fn = os.path.join(path,"%s_merged_%s_%04d-%04d.nc" % \ (dset.lower(),vname.lower(),syr,eyr)) fp = nc.Dataset(fn) depth = np.array(fp.variables['depth'][:]) lat = np.array(fp.variables['lat'][:]) iy = np.where(np.abs(lat-plat)==np.min(np.abs(lat-plat)))[0][0] lon = np.array(fp.variables['lon'][:]) # transfer negative lons to positive lon[np.where(lon<0.)] += 360. ix = np.where(np.abs(lon-plon)==np.min(np.abs(lon-plon)))[0][0] time = np.array(fp.variables['time'][:])+1 for t in time: if t in months: data.append(fp.variables[ncname][t-1,:,iy,ix]) fp.close() tavg_data = np.ma.average(data,axis=0) # vertical layer averaging self.data = [] for lb in self.level_bounds: iz = np.where((depth>=lb[0])&(depth<lb[1])) self.data.append(tavg_data[iz].mean()) self.depth = np.hstack((self.level_bounds[:,0],4000)) class ORAIPprofile(object): """ ORAIP annual means in 1 deg grid. """ def __init__(self,vname,plon,plat,dset='oraip',\ syr=1993,eyr=2009,\ path='/home/uotilap/tiede/ORA-IP/annual_mean/'): print "Reading %s" % dset self.dset = dset if dset=='EN3' and vname=='S': self.dset = dset = 'EN3v2a' if dset=='EN4': self.dset = dset = 'EN4.2.0.g10' self.vname = vname # T or S self.path = path self.lat = plat self.lon = plon self.syr = syr self.eyr = eyr self.level_bounds = LevelBounds[vname] self.depth = np.hstack((self.level_bounds[:,0],4000)) if self.dset in ['GECCO2'] and vname=='S': #self.data = np.ma.masked_less_equal(self.readGECCO2salinity(),32) self.data = self.readGECCO2salinity() return if vname=='T': self.ncname = 'vertically_integrated_temperature' elif vname=='S': self.ncname = 'vertically_integrated_salinity' else: print "%s has not been implemented! Exiting..." % vname sys.exit(1) data = [[] for i in self.level_bounds[:,0]] for li, lb in enumerate(self.level_bounds): fns = glob.glob(os.path.join(path,"%s_int%s_annmean_????to????_%d-%dm_r360x180.nc" % \ (dset,vname,lb[0],lb[1]))) if len(fns) and os.path.exists(fns[0]): ldata = self.readOneFile(fns[0],lb) else: # level is missing, need to calculate it from two other # levels. E.g. 100-300m is 0-300m minus 0-100m fn = glob.glob(os.path.join(path,"%s_int%s_annmean_????to????_%d-%dm_r360x180.nc" % \ (dset,vname,0,lb[0])))[0] ldatau = self.readOneFile(fn,[0,lb[0]]) if dset in ['GloSea5_GO5'] and lb[1] in [6000]: if vname=='S': fns = glob.glob(os.path.join(path,"%s_int%s_annmean_????to????_%d-%s_r360x180.nc" % \ (dset,vname,0,'bottom'))) else: lb[1] = 4000. fns = glob.glob(os.path.join(path,"%s_int%s_annmean_????to????_%d-%d_r360x180.nc" % \ (dset,vname,0,lb[1]))) elif dset in ['EN4.2.0.g10'] and lb[1] in [6000]: fns = glob.glob(os.path.join(path,"%s_int%s_annmean_????to????_%s_r360x180.nc" % \ (dset,vname,'full'))) else: fns = glob.glob(os.path.join(path,"%s_int%s_annmean_????to????_%d-%dm_r360x180.nc" % \ (dset,vname,0,lb[1]))) if len(fns) and os.path.exists(fns[0]): ldatal = self.readOneFile(fns[0],[0,lb[1]]) ldata = ldatal - ldatau else: ldata = np.zeros(ldatau.shape) data[li].append(ldata/np.diff(self.level_bounds)[li]) #if vname=='T': #if self.dset in ['EN4.2.0.g10'] and vname=='T': # self.data = np.ma.masked_equal(np.ma.squeeze(data),0)-273.15 #else: self.data = np.ma.masked_equal(np.ma.squeeze(data),0) if vname=='S' and self.data[-1]<self.data[-2]: self.data[-1] = self.data[-2] if vname=='S' and self.data[-2]<self.data[-3]: self.data[-1] = self.data[-2] = self.data[-3] #else: #S #self.data = np.ma.masked_less_equal(np.ma.squeeze(data),32) # self.data = np.ma.squeeze(data) #self.data = np.ma.squeeze(data) def readGECCO2salinity(self,dsyr=1948,deyr=2011): """ GECCO2_intS_annmean_1948to2011_all_layers_r360x180.nc """ fn = "%s_int%s_annmean_%04dto%04d_all_layers_r360x180.nc" % \ (self.dset,self.vname,dsyr,deyr) fp = nc.Dataset(os.path.join(self.path,fn)) print "Reading %s." % fn lat = np.array(fp.variables['lat'][:]) iy = np.where(np.abs(lat-self.lat)==np.min(np.abs(lat-self.lat)))[0][0] lon = np.array(fp.variables['lon'][:]) # transfer negative lons to positive lon[np.where(lon<0.)] += 360. ix = np.where(np.abs(lon-self.lon)==np.min(np.abs(lon-self.lon)))[0][0] years = np.arange(dsyr,deyr+1) time = fp.variables['time'] # as 0-10m is missing, assume it is the same than 0-100m # values are level means NOT level integrals! # also assuming that S_K in the netcdf file is the mean salinity from # surface to bottom ncnames = ['S_0_100','S_0_100','S_0_300','S_0_700','S_0_1500','S_0_3000','S_0_4000'] # level thicknesses zdpths = [100,100,300,700,1500,3000,4000] data, zdata = [], [] for i,t in enumerate(time[:]): year = years[i] if year in range(self.syr,self.eyr+1): zdata.append(np.ma.array(fp.variables[ncnames[0]][i,iy,ix])) data.append(np.ma.mean(zdata)) # 0-100m data.append(np.ma.mean(zdata)) # 0-100m for li,ncname in enumerate(ncnames[2:]): zdata = [] for i,t in enumerate(time[:]): year = years[i] if year in range(self.syr,self.eyr+1): zdatal = np.ma.array(fp.variables[ncname][i,iy,ix])*zdpths[li+2] zdatau = np.ma.array(fp.variables[ncnames[li+1]][i,iy,ix])*zdpths[li+1] zdata.append((zdatal - zdatau)/(zdpths[li+2]-zdpths[li+1])) data.append(np.ma.mean(zdata)) fp.close() return np.ma.array(data) def readOneFile(self,fn,lb): #fpat = ".+/%s_int%s_annmean_(\d+)to(\d+)_%d-%dm_r360x180.nc" % \ # (self.dset,self.vname,lb[0],lb[1]) #fpat = ".+/%s_int%s_annmean_(\d+)to(\d+)_%d-.+_r360x180.nc" % \ # (self.dset,self.vname,lb[0]) fpat = ".+/%s_int%s_annmean_(\d+)to(\d+)_.+_r360x180.nc" % \ (self.dset,self.vname) m = re.match(fpat,fn) dsyr, deyr = [int(i) for i in m.groups()] fp = nc.Dataset(fn) print "Reading %s." % fn if fp.variables.has_key('latitude'): lat = np.array(fp.variables['latitude'][:]) elif fp.variables.has_key('lat'): lat = np.array(fp.variables['lat'][:]) else: lat = np.arange(-89.5,90.) iy = np.where(np.abs(lat-self.lat)==np.min(np.abs(lat-self.lat)))[0][0] if fp.variables.has_key('longitude'): lon = np.array(fp.variables['longitude'][:]) elif fp.variables.has_key('lon'): lon = np.array(fp.variables['lon'][:]) else: lon = np.arange(.5,360.) # transfer negative lons to positive lon[np.where(lon<0.)] += 360. ix = np.where(np.abs(lon-self.lon)==np.min(np.abs(lon-self.lon)))[0][0] if fp.variables.has_key('TIME'): time = fp.variables['TIME'] elif fp.variables.has_key('time_counter'): time = fp.variables['time_counter'] else: time = fp.variables['time'] m1 = re.search('months since\s+(\d+)-(\d+)-(\d+)',time.units) m2 = re.search('month since\s+(\d+)-(\d+)-(\d+)',time.units) if m1 or m2: if m1: m = m1 else: m = m2 year0, month0, day0 = [int(s) for s in m.groups()] dates = [datetime(year0+int(t/12),month0+int(t%12),day0) for t in time[:]] else: if hasattr(time,'calendar'): cdftime = utime(time.units,calendar=time.calendar) else: cdftime = utime(time.units) dates = [cdftime.num2date(t) for t in time[:]] ldata = [] if not fp.variables.has_key(self.ncname): """ EN4 has t|s_int_depth variable """ self.ncname = [k for k in fp.variables.keys() if \ re.match("%s_int_" % (self.vname.lower()),k)][0] # re.match("%s_int_\d+" % (self.vname.lower()),k)][0] for i,t in enumerate(time[:]): date = dates[i] if date.year in range(self.syr,self.eyr+1): if self.dset in ['K7ODA'] or \ (self.dset in ['MOVEG2'] and self.vname=='S'): ldata.append(np.ma.array(fp.variables[self.ncname][i,:,iy,ix]).squeeze()) else: ldata.append(np.ma.array(fp.variables[self.ncname][i,iy,ix])) fp.close() return np.ma.mean(np.ma.array(ldata)) class TOPAZprofile(object): """ TP4 annual means in 1 deg grid. Monthly files of form: TP4_r360x180_temp|salt_1999_12.nc temperature|salinity(depth, latitude, longitude) """ def __init__(self,vname,plon,plat,dset='TP4',\ syr=1993,eyr=2009,\ path='/home/uotilap/tiede/ORA-IP/annual_mean/'): print "Reading %s" % dset self.dset = dset self.vname = vname # T or S if self.vname=='T': fvarstr = 'temp' self.ncname = 'temperature' else: fvarstr = 'salt' self.ncname = 'salinity' self.path = path self.lat = plat self.lon = plon self.syr = syr self.eyr = eyr self.level_bounds = LevelBounds[vname] fn = "%s_r360x180_%s_%04d_%02d.nc" % (self.dset,fvarstr,syr,1) fp = nc.Dataset(os.path.join(self.path,fn)) depth = np.array(fp.variables['depth'][:]) lat = np.array(fp.variables['latitude'][:]) lon = np.array(fp.variables['longitude'][:]) fp.close() # transfer negative lons to positive lon[np.where(lon<0.)] += 360. iy = np.where(np.abs(lat-self.lat)==np.min(np.abs(lat-self.lat)))[0][0] ix = np.where(np.abs(lon-self.lon)==np.min(np.abs(lon-self.lon)))[0][0] self.months = range(1,13) years = range(syr,eyr+1) ldata = [] for y in years: for m in self.months: fn = "%s_r360x180_%s_%04d_%02d.nc" % (self.dset,fvarstr,y,m) fp = nc.Dataset(os.path.join(self.path,fn)) ldata.append(np.ma.array(fp.variables[self.ncname][:,iy,ix])) # depth, lat, lon fp.close() tavg_data = np.ma.mean(ldata,axis=0) self.data = [] for lb in self.level_bounds: iz = np.where((depth>=lb[0])&(depth<lb[1])) self.data.append(tavg_data[iz].mean()) self.depth = np.hstack((self.level_bounds[:,0],4000)) class ORAP5profile(object): """ ORAP5 annual means in 1 deg grid. temperature|salinity3D_orap5_1m_1993-2012_r360x180.nc votemper|vosaline(time_counter, deptht, lat, lon) """ def __init__(self,vname,plon,plat,dset='ORAP5',\ syr=1993,eyr=2009,\ path='/home/uotilap/tiede/ORA-IP/annual_mean/'): print "Reading %s" % dset self.dset = dset self.vname = vname # T or S self.path = path self.lat = plat self.lon = plon self.syr = syr self.eyr = eyr self.level_bounds = LevelBounds[vname] if self.vname=='T': fvarstr = 'temperature' self.ncname = 'votemper' else: fvarstr = 'salinity' self.ncname = 'vosaline' fn = "%s3D_%s_1m_1993-2012_r360x180.nc" % (fvarstr,self.dset.lower()) fp = nc.Dataset(os.path.join(self.path,fn)) depth = np.array(fp.variables['deptht'][:]) lat = np.array(fp.variables['lat'][:]) lon = np.array(fp.variables['lon'][:]) # transfer negative lons to positive lon[np.where(lon<0.)] += 360. iy = np.where(np.abs(lat-self.lat)==np.min(np.abs(lat-self.lat)))[0][0] ix = np.where(np.abs(lon-self.lon)==np.min(np.abs(lon-self.lon)))[0][0] time = fp.variables['time_counter'] m = re.search('months since\s+(\d+)-(\d+)-(\d+)',time.units) if m: year0, month0, day0 = [int(s) for s in m.groups()] dates = [datetime(year0+int(t/12),month0+int(t%12),day0) for t in time[:]] else: print "Cannot convert time to dates!"; sys.exit(1) ldata = [] for i,t in enumerate(time[:]): date = dates[i] if date.year in range(self.syr,self.eyr+1): ldata.append(np.ma.array(fp.variables[self.ncname][i,:,iy,ix]).squeeze()) fp.close() tavg_data = np.ma.mean(ldata,axis=0) self.data = [] for lb in self.level_bounds: iz = np.where((depth>=lb[0])&(depth<lb[1])) self.data.append(tavg_data[iz].mean()) self.depth = np.hstack((self.level_bounds[:,0],4000)) class GSOP_GLORYS2V4profile(object): """ GSOP_GLORYS2V4 annual means in 1 deg grid. GSOP_GLORYS2V3_ORCA025_H|SC.nc votemper|vosaline(time, lat, lon) """ def __init__(self,vname,plon,plat,dset='GSOP_GLORYS2V4',\ syr=1993,eyr=2009,\ path='/home/uotilap/tiede/ORA-IP/annual_mean/'): print "Reading %s" % dset self.dset = dset self.vname = vname # T or S self.path = path self.lat = plat self.lon = plon self.syr = syr self.eyr = eyr self.level_bounds = LevelBounds[vname] self.depth = np.hstack((self.level_bounds[:,0],4000)) if self.vname=='T': fn = "%s_ORCA025_HC.nc" % (self.dset) varname = 'heatc' else: fn = "%s_ORCA025_SC.nc" % (self.dset) varname = 'saltc' fp = nc.Dataset(os.path.join(self.path,fn)) lat = np.array(fp.variables['lat'][:]) lon = np.array(fp.variables['lon'][:]) # transfer negative lons to positive lon[np.where(lon<0.)] += 360. iy = np.where(np.abs(lat-self.lat)==np.min(np.abs(lat-self.lat)))[0][0] ix = np.where(np.abs(lon-self.lon)==np.min(np.abs(lon-self.lon)))[0][0] time = fp.variables['time'] cdftime = utime(time.units,calendar=time.calendar) dates = [cdftime.num2date(t) for t in time[:]] data = [[] for i in self.level_bounds[:,0]] for li, lb in enumerate(self.level_bounds): ncnameu = "z%d%s" % (lb[0],varname) if lb[1]==6000: ncnamel = "zbot%s" % (varname) else: ncnamel = "z%d%s" % (lb[1],varname) ldata = [] for i,t in enumerate(time[:]): date = dates[i] if date.year in range(self.syr,self.eyr+1): ldatal = fp.variables[ncnamel][i,iy,ix] if ncnameu in ['z0heatc','z0saltc']: ldata.append(ldatal/lb[1]) else: ldatau = fp.variables[ncnameu][i,iy,ix] ldata.append((ldatal-ldatau)/(lb[1]-lb[0])) data[li].append(np.ma.mean(ldata)) fp.close() if vname=='T': self.data = np.ma.masked_equal(np.ma.squeeze(data),0) else: #S self.data = np.ma.masked_less_equal(np.ma.squeeze(data),32) if self.data[-1]<self.data[-2]: self.data[-1] = self.data[-2] if self.data[-2]<self.data[-3]: self.data[-1] = self.data[-2] = self.data[-3] class GSOP_GLORYS2V3profile(GSOP_GLORYS2V4profile): def __init__(self,vname,plon,plat,dset='GSOP_GLORYS2V3',\ syr=1993,eyr=2009,\ path='/home/uotilap/tiede/ORA-IP/annual_mean/'): super( GSOP_GLORYS2V3profile, self).__init__(vname,plon,plat,\ dset=dset,\ syr=syr,eyr=eyr,\ path=path) class Experiments(object): """ Container for data (keep obs climatolog first) """ def __init__(self,exps): self.exps = exps self.vname = self.exps[0].vname if self.vname=='T': self.xlabel = "Temperature [$^\circ$C]" else: self.xlabel = "Salinity [psu]" self.ylabel = "depth [m]" self.title = "%4.1f$^\circ$N, %5.1f$^\circ$E" % \ (exps[0].lat,exps[0].lon) modstr = '_'.join([e.dset for e in self.exps]) self.figfile = "%s_%s_%04d-%04d_%04.1fN_%05.1fE.png" % \ (self.vname,modstr,\ self.exps[0].syr,self.exps[0].eyr,\ exps[0].lat,exps[0].lon) # MMM = multimodel mean frstmodidx = 2 exmmm = copy.copy(exps[frstmodidx]) exmmm.dset = 'MMM' exmmm.data = np.ma.average([e.data for e in exps[frstmodidx:]],axis=0) self.exps.append(exmmm) # Products per 3 panels: self.ProductPanel = [{'T':['CGLORS','GECCO2','GSOP_GLORYS2V4','GloSea5_GO5'],\ 'S':['CGLORS','GECCO2','GSOP_GLORYS2V4','GloSea5_GO5']},\ {'T':['ORAP5','TP4','UoR'],\ 'S':['ORAP5','TP4','UoR']},\ {'T':['ECDA','MOVEG2','EN4.2.0.g10'],\ 'S':['ECDA','MOVEG2','EN4.2.0.g10']}] #{'T':['ECDA','MOVEG2','EN3'],\ # 'S':['ECDA','MOVEG2','EN3v2a']}] def plotProfiles(self): fig = plt.figure(figsize=(8*2,10)) ax1 = plt.axes([0.10, 0.1, .2, .8]) ax2 = plt.axes([0.40, 0.1, .2, .8]) ax3 = plt.axes([0.70, 0.1, .2, .8]) for ia, ax in enumerate([ax1,ax2,ax3]): lnes, lgnds = [],[] # 1st observed climatology (Sumata) # 2nd observed climatology (WOA13) # multi-model mean (MMM) for oicol in [(0,'black','-'),(1,'lightgrey','--'),(-1,'darkgrey',':')]: oi, oc, ol = oicol[0], oicol[1], oicol[2] y = np.ma.hstack((self.exps[oi].data,self.exps[oi].data[-1])) lnes.append(ax.plot(y,self.exps[oi].depth,lw=3,linestyle=ol,\ drawstyle='steps-pre',color=oc)[0]) lgnds.append(self.exps[oi].dset) # then individual models for ename in self.ProductPanel[ia][self.vname]: exp = [e for e in self.exps if e.dset==ename][0] y = np.ma.hstack((exp.data,exp.data[-1])) lnes.append(ax.plot(y,exp.depth,lw=2,\ drawstyle='steps-pre',color=ModelLineColors[exp.dset])[0]) if exp.dset=='GSOP_GLORYS2V4': lgnds.append('GLORYS2V4') elif exp.dset=='GSOP_GLORYS2V3': lgnds.append('GLORYS2V3') elif exp.dset=='GloSea5_GO5': lgnds.append('GloSea5') elif exp.dset=='EN3v2a': lgnds.append('EN3') elif exp.dset=='EN4.2.0.g10': lgnds.append('EN4') else: lgnds.append(exp.dset) ax.invert_yaxis() ax.set_ylim(3000,0) if self.vname=='S': ax.set_xlim(30,35) ax.set_ylabel(self.ylabel) ax.set_title("%s) %s" % (Alphabets[ia],self.title)) ax.set_xlabel(self.xlabel) if self.vname=='T': ax.legend(lnes,tuple(lgnds),ncol=1,bbox_to_anchor=(1.2, 0.5)) else: ax.legend(lnes,tuple(lgnds),ncol=1,bbox_to_anchor=(0.6, 0.5)) #plt.show() plt.savefig(self.figfile) def plotTSdiagram(self,sxps): fig = plt.figure(figsize=(8*2.5,10)) ax1 = plt.axes([0.10, 0.1, .2, .8]) ax2 = plt.axes([0.40, 0.1, .2, .8]) ax3 = plt.axes([0.70, 0.1, .2, .8]) texps, sexps = self.exps, sxps.exps # Calculate how many gridcells we need in the x and y dimensions tdata = np.ma.hstack([np.ma.array(e.data) for e in texps]) sdata = np.ma.hstack([np.ma.array(e.data) for e in sexps]) tmin, tmax = np.ma.min(tdata), np.ma.max(tdata) smin, smax = np.ma.min(sdata), np.ma.max(sdata) xdim, ydim = round((smax-smin)/0.1+1,0), round((tmax-tmin)/0.1+1,0) # Create empty grid of zeros dens = np.zeros((ydim,xdim)) # Create temp and salt vectors of appropiate dimensions ti = np.linspace(1,ydim-1,ydim)*0.1+tmin si = np.linspace(1,xdim-1,xdim)*0.1+smin # Loop to fill in grid with densities for j in range(0,int(ydim)): for i in range(0, int(xdim)): dens[j,i]=dens0(si[i],ti[j]) # Substract 1000 to convert to sigma-t dens -= 1000 for ia, ax in enumerate([ax1,ax2,ax3]): CS = ax.contour(si,ti,dens, linestyles='dashed', colors='k') ax.clabel(CS, fontsize=12, inline=1, fmt='%2.1f') # Label every second level pnts, lgnds = [],[] lastidx = -2 # observed climatology 1 t = np.ma.hstack((texps[0].data,texps[0].data[lastidx])) s = np.ma.hstack((sexps[0].data[1:],sexps[0].data[lastidx])) pnts.append(ax.scatter(s,t,lw=3,color='black')) lgnds.append(texps[0].dset) # observed climatology 2 t = np.ma.hstack((texps[1].data,texps[1].data[lastidx])) s = np.ma.hstack((sexps[1].data[1:],sexps[1].data[lastidx])) pnts.append(ax.scatter(s,t,lw=3,color='lightgrey')) lgnds.append(texps[1].dset) # multi-model mean t = np.ma.hstack((texps[-1].data,texps[-1].data[lastidx])) s = np.ma.hstack((sexps[-1].data[1:],sexps[-1].data[lastidx])) pnts.append(ax.scatter(s,t,lw=3,color='darkgrey')) lgnds.append(texps[-1].dset) # then individual models for ename in self.ProductPanel[ia][self.vname]: texp = [e for e in texps if e.dset==ename][0] if ename=='EN3': sexp = [e for e in sexps if e.dset=='EN3v2a'][0] else: sexp = [e for e in sexps if e.dset==ename][0] t = np.ma.hstack((texp.data,texp.data[lastidx])) s = np.ma.hstack((sexp.data[1:],sexp.data[lastidx])) pnts.append(ax.scatter(s,t,lw=3,color=ModelLineColors[texp.dset])) if texp.dset=='GSOP_GLORYS2V4': lgnds.append('GLORYS2V4') elif texp.dset=='GSOP_GLORYS2V3': lgnds.append('GLORYS2V3') elif texp.dset=='GloSea5_GO5': lgnds.append('GloSea5') elif texp.dset=='EN4.2.0.g10': lgnds.append('EN4') else: lgnds.append(texp.dset) if ia==0: ax.set_ylabel("temperature ($^\circ$C)") ax.set_title("%s) %s" % (Alphabets[ia],self.title)) ax.set_xlabel('salinity (ppm)') ax.legend(pnts,tuple(lgnds),ncol=1,bbox_to_anchor=(0.65, 1.0)) #plt.show() plt.savefig("S"+self.figfile) if __name__ == "__main__": from HiroshisArcticTS import Hiroshis # lons should be E and lats should be N # General central Arctic point # lon, lat = 10., 88. # Nansen Basin that Marika says is good #lon, lat = 100., 83. # Amerasian basin lon, lat = 220., 80. vname = 'S' # 'T' or 'S' models = ['CGLORS', 'ECDA','GloSea5_GO5',\ 'MOVEG2', 'UoR','EN4','GECCO2'] for vname in ['S','T']: hrs = Hiroshis() hrs.getPoint(lon,lat,vname) woa = WOA13profile(vname,lon,lat) experiments = Experiments([hrs,woa]+ \ [ORAIPprofile(vname,lon,lat,dset=model) \ for model in models]+\ [GSOP_GLORYS2V4profile(vname,lon,lat),\ ORAP5profile(vname,lon,lat),\ TOPAZprofile(vname,lon,lat)]) experiments.plotProfiles() if vname=='S': Sxperiments = experiments else: Txperiments = experiments Txperiments.plotTSdiagram(Sxperiments) print "Finnished!"
puotila/PORA-IP
plotAnnuaMeanProfile.py
Python
gpl-3.0
28,427
[ "NetCDF" ]
f22ce30aacc6215bd3d4ecc7e838ae3a5f3d3a4f998dae04370f7fc97653dc11
""" Class that define a normal estimation method based on vtkPointSetNormalsEstimation by David Doria """ __all__ = ["vtkPointSetNormalsEstimation"] from pcloudpy.core.filters.base import FilterBase import numpy as np from vtk import vtkPolyDataAlgorithm, vtkFloatArray, vtkKdTree, vtkPlane, vtkPolyData, vtkIdList from scipy.linalg import eigh FIXED_NUMBER = 0 RADIUS = 1 class vtkPointSetNormalsEstimation(FilterBase): """ vtkPointSetNormalEstimation filter estimates normals of a point set using a local best fit plane. At every point in the point set, vtkPointSetNormalEstimation computes the best fit plane of the set of points within a specified radius of the point (or a fixed number of neighbors). The normal of this plane is used as an estimate of the normal of the surface that would go through the points. vtkPointSetNormalEstimation Class is a python implementation based on the version included in PointSetProcessing by David Doria, see https://github.com/daviddoria/PointSetProcessing """ def __init__(self, number_neighbors = 10, mode = 0, radius = 1): self.mode = mode #FIXED_NUMBER self.number_neighbors = number_neighbors self.radius = radius def set_mode_to_fixednumber(self): self.mode = FIXED_NUMBER def set_mode_to_radius(self): self.mode = RADIUS def set_input(self, input_data): """ set input data Parameters ---------- input-data : vtkPolyData Returns ------- is_valid: bool Returns True if the input_data is valid for processing """ if isinstance(input_data, vtkPolyData): super(vtkPointSetNormalsEstimation, self).set_input(input_data) return True else: return False def update(self): normalArray = vtkFloatArray() normalArray.SetNumberOfComponents( 3 ) normalArray.SetNumberOfTuples( self.input_.GetNumberOfPoints() ) normalArray.SetName( "Normals" ) kDTree = vtkKdTree() kDTree.BuildLocatorFromPoints(self.input_.GetPoints()) # Estimate the normal at each point. for pointId in range(0, self.input_.GetNumberOfPoints()): point = [0,0,0] self.input_.GetPoint(pointId, point) neighborIds = vtkIdList() if self.mode == FIXED_NUMBER: kDTree.FindClosestNPoints(self.number_neighbors, point, neighborIds) elif self.mode == RADIUS: kDTree.FindPointsWithinRadius(self.radius, point, neighborIds) #If there are not at least 3 points within the specified radius (the current # #point gets included in the neighbors set), a plane is not defined. Instead, # #force it to use 3 points. if neighborIds.GetNumberOfIds() < 3 : kDTree.FindClosestNPoints(3, point, neighborIds) bestPlane = vtkPlane() self.best_fit_plane(self.input_.GetPoints(), bestPlane, neighborIds) normal = bestPlane.GetNormal() normalArray.SetTuple( pointId, normal ) self.output_ = vtkPolyData() self.output_.ShallowCopy(self.input_) self.output_.GetPointData().SetNormals(normalArray) def best_fit_plane(self, points, bestPlane, idsToUse): #Compute the best fit (least squares) plane through a set of points. dnumPoints = idsToUse.GetNumberOfIds() #Find the center of mass of the points center = self.center_of_mass(points, idsToUse) a = np.zeros((3,3)) for pointId in range(0, dnumPoints): x = np.asarray([0,0,0]) xp = np.asarray([0,0,0]) points.GetPoint(idsToUse.GetId(pointId), x) xp = x - center a[0,:] += xp[0] * xp[:] a[1,:] += xp[1] * xp[:] a[2,:] += xp[2] * xp[:] #Divide by N-1 a /= (dnumPoints-1) eigval, eigvec = eigh(a, overwrite_a=True, overwrite_b=True) #Jacobi iteration for the solution of eigenvectors/eigenvalues of a 3x3 real symmetric matrix. #Square 3x3 matrix a; output eigenvalues in w; and output eigenvectors in v. #Resulting eigenvalues/vectors are sorted in decreasing order; eigenvectors are normalized. #Set the plane normal to the smallest eigen vector bestPlane.SetNormal(eigvec[0,0], eigvec[1,0], eigvec[2,0]) #Set the plane origin to the center of mass bestPlane.SetOrigin(center[0], center[1], center[2]) def center_of_mass(self, points, idsToUse): #Compute the center of mass of a set of points. point = np.asarray([0.0, 0.0, 0.0]) center = np.asarray([0.0,0.0,0.0]) for i in range(0, idsToUse.GetNumberOfIds() ): points.GetPoint(idsToUse.GetId(i), point) center += point numberOfPoints = float(idsToUse.GetNumberOfIds()) center /= numberOfPoints return center
mmolero/pcloudpy
pcloudpy/core/filters/vtkPointSetNormalsEstimation.py
Python
bsd-3-clause
5,076
[ "VTK" ]
65fcdc2aa0a197f405bf2d97deb5ae390af212248de0538d5a9585d38be7c372
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007 Johan Gronqvist (johan.gronqvist@gmail.com) # copyright (C) 2007 Brian G. Matherly # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # $Id$ #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.get_translation().gettext #------------------------------------------------------------------------- # # GRAMPS modules # #------------------------------------------------------------------------- from .. import Rule #------------------------------------------------------------------------- # "People with less than 2 parents" #------------------------------------------------------------------------- class MissingParent(Rule): """People with less than two parents""" name = _('People missing parents') description = _("Matches people that are children" " in a family with less than two parents" " or are not children in any family.") category = _('Family filters') def apply(self,db,person): families = person.get_parent_family_handle_list() if families == []: return True for family_handle in person.get_parent_family_handle_list(): family = db.get_family_from_handle(family_handle) if family: father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() if not father_handle: return True if not mother_handle: return True return False
Forage/Gramps
gramps/gen/filters/rules/person/_missingparent.py
Python
gpl-2.0
2,420
[ "Brian" ]
0de89f23bd8cf0217064af5e48c351d05952863b9d6a0fdc2e336249068a1e02
#!/usr/bin/env python import math __author__ = "Pablo Marchant" __credits__ = ["Pablo Marchant", "Fabian Schneider"] __license__ = "GPL" __version__ = "3.0" __maintainer__ = "Pablo Marchant" __email__ = "pamarca@gmail.com" """Define multiple constants. Much of this taken directly from MESA. This module simply defines a multitude of constants for general use. Importing this module as from const_lib import * will allow access to multiple useful constants such as PI and RSUN. TODO: Potentially better to use scipy.constants and convert units """ PI = math.pi EULERCON = math.e CGRAV = 6.67428e-8 # gravitational constant (g^-1 cm^3 s^-2) PLANCK_H = 6.62606896e-27 # Planck's constant (erg s) HBAR = PLANCK_H / (2*PI) QE = 4.80320440e-10 # electron charge (esu == (g cm^3 s^-2)^(1/2)) AVO = 6.02214179e23 # Avogadro's constant (mole^-1) CLIGHT = 2.99792458e10 # speed of light in vacuum (cm s^-1) KERG = 1.3806504e-16 # Boltzmann's constant (erg K^-1) CGAS = KERG*AVO # ideal gas constant; erg/K KEV = 8.617385e-5 # converts temp to ev (ev K^-1) AMU = 1.660538782e-24 # atomic mass unit (g) MN = 1.6749286e-24 # neutron mass (g) MP = 1.6726231e-24 # proton mass (g) ME = 9.1093826e-28 # (was 9.1093897d-28) electron mass (g) RBOHR = HBAR**2/(ME * QE**2) # Bohr radius (cm) FINE = QE**2/(HBAR*CLIGHT) # fine structure constant HION = 13.605698140e0 # hydrogen ionization energy (eV) EV2ERG = 1.602176487e-12 # electron volt (erg) MEV_TO_ERGS = 1e6*EV2ERG MEV_AMU = MEV_TO_ERGS/AMU QCONV = MEV_TO_ERGS*AVO BOLTZ_SIGMA = 5.670400e-5 # boltzmann's sigma = a*c/4 (erg cm^-2 K^-4 s^-1) CRAD = BOLTZ_SIGMA*4/CLIGHT # = radiation density constant, a (erg cm^-3 K^-4); Prad = crad * T^4 / 3 # approx = 7.5657e-15 WEINLAM = PLANCK_H*CLIGHT/(KERG * 4.965114232e0) WEINFRE = 2.821439372E0*KERG/PLANCK_H RHONUC = 2.342e14 # density of nucleus (g cm^3) # solar age, L, and R values from Bahcall et al, ApJ 618 (2005) 1049-1056. MSUN = 1.9892e33 # solar mass (g) <<< gravitational mass, not baryonic RSUN = 6.9598e10 # solar radius (cm) LSUN = 3.8418e33 # solar luminosity (erg s^-1) AGESUN = 4.57e9 # solar age (years) LY = 9.460528e17 # light year (cm) PC = 3.261633e0*LY # parsec (cm) SECYER = 3.1558149984e7 # seconds per year DAYYER = 365.25e0 # days per year TEFFSOL = 5777.0e0 LOGGSOL = 4.4378893534131256e0 # With mesa's default msol, rsol and standard_cgrav MBOLSUN = 4.746 # Bolometric magnitude of the Sun M_EARTH = 5.9764e27 # earth mass (g) # = 3.004424e-6 Msun R_EARTH = 6.37e8 # earth radius (cm) AU = 1.495978921e13 # astronomical unit (cm) M_JUPITER = 1.8986e30 # jupiter mass (g) # = 0.954454d-3 Msun R_JUPITER = 6.9911e9 # jupiter mean radius (cm) SEMIMAJOR_AXIS_JUPITER = 7.7857e13 # jupiter semimajor axis (cm)
orlox/medusa
const/const_lib.py
Python
gpl-3.0
3,318
[ "Avogadro" ]
a4957e812e8d6cb122940a3c64225b3bda4d205dd84123e491ab5df080c5c4fe
import numpy as np import glob filename2 = 'data.poly-d200' #lammps 'charge' data file outputfile = 'data.GP-composite_200nm_charge' flist2 = glob.glob(filename2) #the 1st col. is string so its loaded seperately for f in flist2: load2 = np.genfromtxt(f, dtype=float, skip_header=10, usecols=(1,3,4,5)) #dtype=("|S10", float, float, float), dataovito1=np.array(load2) for f in flist2: load2 = np.genfromtxt(f, dtype=str, skip_header=10, usecols=(1)) #dtype=("|S10", float, float, float), dataovito2=np.array(load2) size1 = len(dataovito1) #total atoms-water size2 = len(dataovito1) #total atoms grain_types = 131 grain_list = [] grain_new = [] for i in range(1,grain_types+1): grain_list.append(i) for i in range(1,grain_types+1): grain_new.append(int(np.random.uniform(1,4))) natoms = size2 #print dataovito2 xmin = 0.0 #np.min(dataovito1[:,0]) # added -1.0 to prohibit overlapping at boundaries xmax = 1000 #np.max(dataovito1[:,0]) ymin = 0.0 #np.min(dataovito1[:,1]) ymax = 1000 #np.max(dataovito1[:,1]) zmin = 0.0 #np.min(dataovito1[:,2]) zmax = 1000 #np.max(dataovito1[:,2]) #print xmax, ymax, zmax density = 0.0022 #2.2 gm/cm3 or 0.0022 atto-gram/nm3 volume = 1000 #cube of sc outFile = open(outputfile, 'w') outFile.write('PDLAMMPS data file written by Python\n') outFile.write('\n') outFile.write('%i %s \n' %(natoms, 'atoms')) outFile.write('3 atom types \n') outFile.write('\n') outFile.write('%f %f %s %s \n' %(xmin-1, xmax+1, 'xlo', 'xhi')) outFile.write('%f %f %s %s \n' %(ymin-1, ymax+1, 'ylo', 'yhi')) outFile.write('%f %f %s %s \n' %(zmin-1, zmax+1, 'zlo', 'zhi')) outFile.write('\n') outFile.write('Atoms # charge\n') outFile.write('\n') for j in range(size1): #if int(dataovito2[j]) in grain_list: #outFile.write('%i %i %i %f %f %f \n' %(j+1, np.random.uniform(1,4), 1, dataovito1[j,1], dataovito1[j,2], dataovito1[j,3])) outFile.write('%i %i %i %f %f %f \n' %(j+1, grain_new[grain_list.index(int(dataovito2[j]))], 1, dataovito1[j,1], dataovito1[j,2], dataovito1[j,3])) ''' elif dataovito2[j]=="2": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, np.random.uniform(1,5), volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="3": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, np.random.uniform(1,5), volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="4": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, np.random.uniform(1,5), volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="5": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, np.random.uniform(1,5), volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="6": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, np.random.uniform(1,5), volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="7": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, np.random.uniform(1,5), volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="8": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, np.random.uniform(1,5), volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="9": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, 3, volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) elif dataovito2[j]=="10": outFile.write('%i %i %s %s %s %s %s %i %i %i \n' %(j+1, 3, volume, density, dataovito1[j,0], dataovito1[j,1], dataovito1[j,2], 0, 0, 0)) ''' outFile.close() print "All done!"
msadat/python-scripts
write_multigrain__few-grains_charge.py
Python
gpl-3.0
3,874
[ "LAMMPS" ]
a2c6dc45e8cbe1c3ca0317baf567db148aa51fa5bd567b72b49d8d7c63430172
from slm_lab.agent import net from slm_lab.agent.algorithm import policy_util from slm_lab.agent.algorithm.reinforce import Reinforce from slm_lab.agent.net import net_util from slm_lab.lib import logger, math_util, util from slm_lab.lib.decorator import lab_api import numpy as np import pydash as ps import torch logger = logger.get_logger(__name__) class ActorCritic(Reinforce): ''' Implementation of single threaded Advantage Actor Critic Original paper: "Asynchronous Methods for Deep Reinforcement Learning" https://arxiv.org/abs/1602.01783 Algorithm specific spec param: memory.name: batch (through OnPolicyBatchReplay memory class) or episodic through (OnPolicyReplay memory class) lam: if not null, used as the lambda value of generalized advantage estimation (GAE) introduced in "High-Dimensional Continuous Control Using Generalized Advantage Estimation https://arxiv.org/abs/1506.02438. This lambda controls the bias variance tradeoff for GAE. Floating point value between 0 and 1. Lower values correspond to more bias, less variance. Higher values to more variance, less bias. Algorithm becomes A2C(GAE). num_step_returns: if lam is null and this is not null, specifies the number of steps for N-step returns from "Asynchronous Methods for Deep Reinforcement Learning". The algorithm becomes A2C(Nstep). If both lam and num_step_returns are null, use the default TD error. Then the algorithm stays as AC. net.type: whether the actor and critic should share params (e.g. through 'MLPNetShared') or have separate params (e.g. through 'MLPNetSeparate'). If param sharing is used then there is also the option to control the weight given to the policy and value components of the loss function through 'policy_loss_coef' and 'val_loss_coef' Algorithm - separate actor and critic: Repeat: 1. Collect k examples 2. Train the critic network using these examples 3. Calculate the advantage of each example using the critic 4. Multiply the advantage by the negative of log probability of the action taken, and sum all the values. This is the policy loss. 5. Calculate the gradient the parameters of the actor network with respect to the policy loss 6. Update the actor network parameters using the gradient Algorithm - shared parameters: Repeat: 1. Collect k examples 2. Calculate the target for each example for the critic 3. Compute current estimate of state-value for each example using the critic 4. Calculate the critic loss using a regression loss (e.g. square loss) between the target and estimate of the state-value for each example 5. Calculate the advantage of each example using the rewards and critic 6. Multiply the advantage by the negative of log probability of the action taken, and sum all the values. This is the policy loss. 7. Compute the total loss by summing the value and policy lossses 8. Calculate the gradient of the parameters of shared network with respect to the total loss 9. Update the shared network parameters using the gradient e.g. algorithm_spec "algorithm": { "name": "ActorCritic", "action_pdtype": "default", "action_policy": "default", "explore_var_spec": null, "gamma": 0.99, "lam": 0.95, "num_step_returns": 100, "entropy_coef_spec": { "name": "linear_decay", "start_val": 0.01, "end_val": 0.001, "start_step": 100, "end_step": 5000, }, "policy_loss_coef": 1.0, "val_loss_coef": 0.01, "training_frequency": 1, } e.g. special net_spec param "shared" to share/separate Actor/Critic "net": { "type": "MLPNet", "shared": true, ... ''' @lab_api def init_algorithm_params(self): '''Initialize other algorithm parameters''' # set default util.set_attr(self, dict( action_pdtype='default', action_policy='default', explore_var_spec=None, entropy_coef_spec=None, policy_loss_coef=1.0, val_loss_coef=1.0, )) util.set_attr(self, self.algorithm_spec, [ 'action_pdtype', 'action_policy', # theoretically, AC does not have policy update; but in this implementation we have such option 'explore_var_spec', 'gamma', # the discount factor 'lam', 'num_step_returns', 'entropy_coef_spec', 'policy_loss_coef', 'val_loss_coef', 'training_frequency', ]) self.to_train = 0 self.action_policy = getattr(policy_util, self.action_policy) self.explore_var_scheduler = policy_util.VarScheduler(self.explore_var_spec) self.body.explore_var = self.explore_var_scheduler.start_val if self.entropy_coef_spec is not None: self.entropy_coef_scheduler = policy_util.VarScheduler(self.entropy_coef_spec) self.body.entropy_coef = self.entropy_coef_scheduler.start_val # Select appropriate methods to calculate advs and v_targets for training if self.lam is not None: self.calc_advs_v_targets = self.calc_gae_advs_v_targets elif self.num_step_returns is not None: # need to override training_frequency for nstep to be the same self.training_frequency = self.num_step_returns self.calc_advs_v_targets = self.calc_nstep_advs_v_targets else: self.calc_advs_v_targets = self.calc_ret_advs_v_targets @lab_api def init_nets(self, global_nets=None): ''' Initialize the neural networks used to learn the actor and critic from the spec Below we automatically select an appropriate net based on two different conditions 1. If the action space is discrete or continuous action - Networks for continuous action spaces have two heads and return two values, the first is a tensor containing the mean of the action policy, the second is a tensor containing the std deviation of the action policy. The distribution is assumed to be a Gaussian (Normal) distribution. - Networks for discrete action spaces have a single head and return the logits for a categorical probability distribution over the discrete actions 2. If the actor and critic are separate or share weights - If the networks share weights then the single network returns a list. - Continuous action spaces: The return list contains 3 elements: The first element contains the mean output for the actor (policy), the second element the std dev of the policy, and the third element is the state-value estimated by the network. - Discrete action spaces: The return list contains 2 element. The first element is a tensor containing the logits for a categorical probability distribution over the actions. The second element contains the state-value estimated by the network. 3. If the network type is feedforward, convolutional, or recurrent - Feedforward and convolutional networks take a single state as input and require an OnPolicyReplay or OnPolicyBatchReplay memory - Recurrent networks take n states as input and require env spec "frame_op": "concat", "frame_op_len": seq_len ''' assert 'shared' in self.net_spec, 'Specify "shared" for ActorCritic network in net_spec' self.shared = self.net_spec['shared'] # create actor/critic specific specs actor_net_spec = self.net_spec.copy() critic_net_spec = self.net_spec.copy() for k in self.net_spec: if 'actor_' in k: actor_net_spec[k.replace('actor_', '')] = actor_net_spec.pop(k) critic_net_spec.pop(k) if 'critic_' in k: critic_net_spec[k.replace('critic_', '')] = critic_net_spec.pop(k) actor_net_spec.pop(k) if critic_net_spec['use_same_optim']: critic_net_spec = actor_net_spec in_dim = self.body.state_dim out_dim = net_util.get_out_dim(self.body, add_critic=self.shared) # main actor network, may contain out_dim self.shared == True NetClass = getattr(net, actor_net_spec['type']) self.net = NetClass(actor_net_spec, in_dim, out_dim) self.net_names = ['net'] if not self.shared: # add separate network for critic critic_out_dim = 1 CriticNetClass = getattr(net, critic_net_spec['type']) self.critic_net = CriticNetClass(critic_net_spec, in_dim, critic_out_dim) self.net_names.append('critic_net') # init net optimizer and its lr scheduler self.optim = net_util.get_optim(self.net, self.net.optim_spec) self.lr_scheduler = net_util.get_lr_scheduler(self.optim, self.net.lr_scheduler_spec) if not self.shared: self.critic_optim = net_util.get_optim(self.critic_net, self.critic_net.optim_spec) self.critic_lr_scheduler = net_util.get_lr_scheduler(self.critic_optim, self.critic_net.lr_scheduler_spec) net_util.set_global_nets(self, global_nets) self.end_init_nets() @lab_api def calc_pdparam(self, x, net=None): ''' The pdparam will be the logits for discrete prob. dist., or the mean and std for continuous prob. dist. ''' out = super().calc_pdparam(x, net=net) if self.shared: assert ps.is_list(out), f'Shared output should be a list [pdparam, v]' if len(out) == 2: # single policy pdparam = out[0] else: # multiple-task policies, still assumes 1 value pdparam = out[:-1] self.v_pred = out[-1].view(-1) # cache for loss calc to prevent double-pass else: # out is pdparam pdparam = out return pdparam def calc_v(self, x, net=None, use_cache=True): ''' Forward-pass to calculate the predicted state-value from critic_net. ''' if self.shared: # output: policy, value if use_cache: # uses cache from calc_pdparam to prevent double-pass v_pred = self.v_pred else: net = self.net if net is None else net v_pred = net(x)[-1].view(-1) else: net = self.critic_net if net is None else net v_pred = net(x).view(-1) return v_pred def calc_pdparam_v(self, batch): '''Efficiently forward to get pdparam and v by batch for loss computation''' states = batch['states'] if self.body.env.is_venv: states = math_util.venv_unpack(states) pdparam = self.calc_pdparam(states) v_pred = self.calc_v(states) # uses self.v_pred from calc_pdparam if self.shared return pdparam, v_pred def calc_ret_advs_v_targets(self, batch, v_preds): '''Calculate plain returns, and advs = rets - v_preds, v_targets = rets''' v_preds = v_preds.detach() # adv does not accumulate grad if self.body.env.is_venv: v_preds = math_util.venv_pack(v_preds, self.body.env.num_envs) rets = math_util.calc_returns(batch['rewards'], batch['dones'], self.gamma) advs = rets - v_preds v_targets = rets if self.body.env.is_venv: advs = math_util.venv_unpack(advs) v_targets = math_util.venv_unpack(v_targets) logger.debug(f'advs: {advs}\nv_targets: {v_targets}') return advs, v_targets def calc_nstep_advs_v_targets(self, batch, v_preds): ''' Calculate N-step returns, and advs = nstep_rets - v_preds, v_targets = nstep_rets See n-step advantage under http://rail.eecs.berkeley.edu/deeprlcourse-fa17/f17docs/lecture_5_actor_critic_pdf.pdf ''' next_states = batch['next_states'][-1] if not self.body.env.is_venv: next_states = next_states.unsqueeze(dim=0) with torch.no_grad(): next_v_pred = self.calc_v(next_states, use_cache=False) v_preds = v_preds.detach() # adv does not accumulate grad if self.body.env.is_venv: v_preds = math_util.venv_pack(v_preds, self.body.env.num_envs) nstep_rets = math_util.calc_nstep_returns(batch['rewards'], batch['dones'], next_v_pred, self.gamma, self.num_step_returns) advs = nstep_rets - v_preds v_targets = nstep_rets if self.body.env.is_venv: advs = math_util.venv_unpack(advs) v_targets = math_util.venv_unpack(v_targets) logger.debug(f'advs: {advs}\nv_targets: {v_targets}') return advs, v_targets def calc_gae_advs_v_targets(self, batch, v_preds): ''' Calculate GAE, and advs = GAE, v_targets = advs + v_preds See GAE from Schulman et al. https://arxiv.org/pdf/1506.02438.pdf ''' next_states = batch['next_states'][-1] if not self.body.env.is_venv: next_states = next_states.unsqueeze(dim=0) with torch.no_grad(): next_v_pred = self.calc_v(next_states, use_cache=False) v_preds = v_preds.detach() # adv does not accumulate grad if self.body.env.is_venv: v_preds = math_util.venv_pack(v_preds, self.body.env.num_envs) next_v_pred = next_v_pred.unsqueeze(dim=0) v_preds_all = torch.cat((v_preds, next_v_pred), dim=0) advs = math_util.calc_gaes(batch['rewards'], batch['dones'], v_preds_all, self.gamma, self.lam) v_targets = advs + v_preds advs = math_util.standardize(advs) # standardize only for advs, not v_targets if self.body.env.is_venv: advs = math_util.venv_unpack(advs) v_targets = math_util.venv_unpack(v_targets) logger.debug(f'advs: {advs}\nv_targets: {v_targets}') return advs, v_targets def calc_policy_loss(self, batch, pdparams, advs): '''Calculate the actor's policy loss''' return super().calc_policy_loss(batch, pdparams, advs) def calc_val_loss(self, v_preds, v_targets): '''Calculate the critic's value loss''' assert v_preds.shape == v_targets.shape, f'{v_preds.shape} != {v_targets.shape}' val_loss = self.val_loss_coef * self.net.loss_fn(v_preds, v_targets) logger.debug(f'Critic value loss: {val_loss:g}') return val_loss def train(self): '''Train actor critic by computing the loss in batch efficiently''' clock = self.body.env.clock if self.to_train == 1: batch = self.sample() clock.set_batch_size(len(batch)) pdparams, v_preds = self.calc_pdparam_v(batch) advs, v_targets = self.calc_advs_v_targets(batch, v_preds) policy_loss = self.calc_policy_loss(batch, pdparams, advs) # from actor val_loss = self.calc_val_loss(v_preds, v_targets) # from critic if self.shared: # shared network loss = policy_loss + val_loss self.net.train_step(loss, self.optim, self.lr_scheduler, clock=clock, global_net=self.global_net) else: self.net.train_step(policy_loss, self.optim, self.lr_scheduler, clock=clock, global_net=self.global_net) self.critic_net.train_step(val_loss, self.critic_optim, self.critic_lr_scheduler, clock=clock, global_net=self.global_critic_net) loss = policy_loss + val_loss # reset self.to_train = 0 logger.debug(f'Trained {self.name} at epi: {clock.epi}, frame: {clock.frame}, t: {clock.t}, total_reward so far: {self.body.env.total_reward}, loss: {loss:g}') return loss.item() else: return np.nan @lab_api def update(self): self.body.explore_var = self.explore_var_scheduler.update(self, self.body.env.clock) if self.entropy_coef_spec is not None: self.body.entropy_coef = self.entropy_coef_scheduler.update(self, self.body.env.clock) return self.body.explore_var
kengz/Unity-Lab
slm_lab/agent/algorithm/actor_critic.py
Python
mit
16,313
[ "Gaussian" ]
8ef06d656d8634eb1a86ae5523f3c77fb176378102ef732a839d0b64fececa26
import Bio from Bio import SeqIO, SeqFeature from Bio.SeqRecord import SeqRecord from Bio.Blast import NCBIXML from Bio.Blast import NCBIStandalone import sys import os import site import argparse import string import numpy import re import subprocess import genbank import blast import intergene loc_reg = re.compile("(\d+):(\d+)\S\((\S)\)") class GenomeHandler: def __init__(self, genome, intermediate, evalue, num_threads, verbose, keep_tmp): self.genome_file = genome self.evalue = evalue self.num_threads = num_threads self.verbose = verbose self.keep_tmp = keep_tmp # SeqIO.write(input_genes,self.target_genes,"fasta") self.noHits = True self.intermediate = intermediate def cleanup(self): #os.remove(self.genomic_query) #os.remove(self.genome_file) pass """Gets the filtered intergenic regions""" def getGenomicQuery(self): return self.genomic_query def getGenomeFile(self): return self.genome_file """Runs blast to find the gene locations in all of the bacterial genomes""" def getAlignedGenes(self,genes,gene_evalue,num_threads,formatdb): geneBlast = blast.BLAST(self.genome_file,genes,self.intermediate,gene_evalue) if formatdb: geneBlast.buildDatabase("nucleotide") print geneBlast.formatDBCommand() geneBlast.run(blast_cmd="tblastn",mode="xml",num_threads=num_threads) hits = geneBlast.parseBLAST("xml") print hits return hits def main(genome_files,bacteriocins,genes,outHandle,intermediate,gene_evalue,bac_evalue,num_threads,verbose,keep_tmp): for gbk in genome_files: ghr = GenomeHandler(gbk,intermediate,gene_evalue,num_threads,verbose,keep_tmp) hits = ghr.getAlignedGenes(genes,gene_evalue,num_threads) outHandle.write("\n".join( map( str, hits))+"\n") if __name__=="__main__": parser = argparse.ArgumentParser(description=\ 'Finds target genes in a FASTA file') parser.add_argument(\ '--genome-files', type=str, nargs="+", required=False, help='The FASTA containg the bacterial genome') parser.add_argument(\ '--genes', type=str,required=True,default="", help='A FASTA file containing all of the target genes of interest') parser.add_argument(\ '--bacteriocins', type=str, required=True, help='The bacteriocin proteins that are to be blasted') parser.add_argument(\ '--gene-evalue', type=float, required=False, default=0.00001, help='The evalue for gene hits') parser.add_argument(\ '--bac-evalue', type=float, required=False, default=0.000000001, help='The evalue for bacteriocin hits') parser.add_argument(\ '--intermediate', type=str, required=True, help='Directory for storing intermediate files') parser.add_argument(\ '--verbose', action='store_const', const=True, default=False, help='Messages for debugging') parser.add_argument(\ '--test', action='store_const', const=True, default=False, help='Run unittests') blast.addArgs(parser) args = parser.parse_args() outHandle = open(args.output_file,'w') main(args.genome_files, args.bacteriocins, args.genes, outHandle, args.intermediate, args.gene_evalue, args.bac_evalue, args.num_threads, args.verbose, args.keep_tmp)
idoerg/BOA
src/genome/genome.py
Python
gpl-3.0
3,607
[ "BLAST" ]
e9c90b8ba5978b04905b8a0d7e5fec1061d5aef7adce5c01c537d132461f97f1
#!/usr/bin/env ipython from pylab import * import numpy as np from scipy.io.netcdf import netcdf_file import os, sys import matplotlib.patches as patches import matplotlib.transforms as transforms from numpy import array from matplotlib.gridspec import GridSpec import matplotlib.pyplot as plt from os.path import isdir, isfile #--- otros sys.path += ['../'] import console_colors as ccl class gral: def __init__(self): self.name='name' #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ def makefig(ax, mc, sh, TEXT, TEXT_LOC, YLIMS, varname): LW = 0.3 # linewidth MS = 1.5 fmc,fsh = 3.0, 1.0 # escaleos temporales if(varname == 'Temp.ACE'): mc.med /= 1.0e4; sh.med /= 1.0e4 mc.avr /= 1.0e4; sh.avr /= 1.0e4 mc.std_err /= 1.0e4; sh.std_err /= 1.0e4 YLIMS[0] /= 1.0e4; YLIMS[1] /= 1.0e4 TEXT_LOC['mc'][1] /= 1.0e4 TEXT_LOC['sh'][1] /= 1.0e4 # curvas del mc time = fsh+fmc*mc.tnorm cc = time>=fsh ax.plot(time[cc], mc.avr[cc], 'o-', color='black', markersize=MS, label='mean', lw=LW) ax.plot(time[cc], mc.med[cc], 'o-', color='red', alpha=.8, markersize=MS, markeredgecolor='none', label='median', lw=LW) # sombra del mc inf = mc.avr + mc.std_err/np.sqrt(mc.nValues) sup = mc.avr - mc.std_err/np.sqrt(mc.nValues) ax.fill_between(time[cc], inf[cc], sup[cc], facecolor='gray', alpha=0.5) trans = transforms.blended_transform_factory( ax.transData, ax.transAxes) rect1 = patches.Rectangle((fsh, 0.), width=fmc, height=1, transform=trans, color='blue', alpha=0.3) ax.add_patch(rect1) # curvas del sheath time = fsh*sh.tnorm cc = time<=fsh ax.plot(time[cc], sh.avr[cc], 'o-', color='black', markersize=MS, lw=LW) ax.plot(time[cc], sh.med[cc], 'o-', color='red', alpha=.8, markersize=MS, markeredgecolor='none', lw=LW) # sombra del sheath inf = sh.avr + sh.std_err/np.sqrt(sh.nValues) sup = sh.avr - sh.std_err/np.sqrt(sh.nValues) ax.fill_between(time[cc], inf[cc], sup[cc], facecolor='gray', alpha=0.5) #trans = transforms.blended_transform_factory( # ax.transData, ax.transAxes) rect1 = patches.Rectangle((0., 0.), width=fsh, height=1, transform=trans, color='orange', alpha=0.3) ax.add_patch(rect1) #ax.legend(loc='best', fontsize=10) ax.tick_params(labelsize=10) ax.grid() ax.set_xlim(-2.0, 7.0) ax.set_ylim(YLIMS) ax.text(TEXT_LOC['mc'][0], TEXT_LOC['mc'][1], TEXT['mc'], fontsize=7) ax.text(TEXT_LOC['sh'][0], TEXT_LOC['sh'][1], TEXT['sh'], fontsize=7) if(varname in ('beta.ACE','Temp.ACE', 'rmsB.ACE', 'rmsBoB.ACE')): ax.set_yscale('log') else: ax.set_yscale('linear') return ax #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ stf = {} stf['B.ACE'] = { 'label': 'B [nT]', 'ylims': [3., 20.], 'text_loc_1': {'mc':[4.5, 15.0], 'sh':[-1.95, 12.0]}, 'text_loc_2': {'mc':[4.5, 18.0], 'sh':[-1.95, 12.0]}, 'text_loc_3': {'mc':[4.5, 12.0], 'sh':[-1.95, 12.0]}, 'nrow': 1 } stf['V.ACE'] = { 'label': 'V [km/s]', 'ylims': [300., 650.], 'text_loc_1': {'mc':[4.5, 500.0], 'sh':[-1.95, 520.0]}, 'text_loc_2': {'mc':[4.5, 600.0], 'sh':[-1.95, 600.0]}, 'text_loc_3': {'mc':[4.5, 410.0], 'sh':[-1.95, 600.0]}, 'nrow': 2 } stf['rmsBoB.ACE'] = { 'label': 'rmsBoB [1]', 'ylims': [0.01, 0.21], 'text_loc_1': {'mc':[4.5, 0.020], 'sh':[-1.95, 0.02]}, 'text_loc_2': {'mc':[4.5, 0.095], 'sh':[-1.95, 0.02]}, 'text_loc_3': {'mc':[4.5, 0.099], 'sh':[-1.95, 0.02]}, 'nrow': 6 } stf['rmsB.ACE'] = { 'label': 'rmsB [nT]', 'ylims': [0.1, 4.0], 'text_loc_1': {'mc':[4.5, 1.0], 'sh':[-1.95, 1.3]}, 'text_loc_2': {'mc':[4.5, 1.0], 'sh':[-1.95, 1.3]}, 'text_loc_3': {'mc':[4.5, 1.0], 'sh':[-1.95, 1.3]} } stf['beta.ACE'] = { 'label': '$\\beta$ [1]', 'ylims': [0.1, 10.0], 'text_loc_1': {'mc':[4.5, 0.1], 'sh':[-1.95, 0.2]}, 'text_loc_2': {'mc':[4.5, 0.1], 'sh':[-1.95, 0.2]}, 'text_loc_3': {'mc':[4.5, 0.1], 'sh':[-1.95, 0.2]}, 'nrow': 5 } stf['Pcc.ACE'] = { 'label': '$n_p$ [$cm^{-3}$]', 'ylims': [1, 23], 'text_loc_1': {'mc':[4.5, 14], 'sh':[-1.95, 16.0]}, 'text_loc_2': {'mc':[4.5, 14], 'sh':[-1.95, 16.0]}, 'text_loc_3': {'mc':[4.5, 11], 'sh':[-1.95, 18.0]}, 'nrow': 3 } stf['Temp.ACE'] = { 'label': 'Tp ($\\times 10^4$) [K]', 'ylims': [1e4, 40e4], 'text_loc_1': {'mc':[4.5, 18.0e4], 'sh':[-1.95, 20.0e4]}, 'text_loc_2': {'mc':[4.5, 2.0e4], 'sh':[-1.95, 20.0e4]}, 'text_loc_3': {'mc':[4.5, 2.0e4], 'sh':[-1.95, 20.0e4]}, 'nrow': 4 } stf['AlphaRatio.ACE'] = { 'label': 'alpha ratio [1]', 'ylims': [0.02, 0.09], 'text_loc_1': {'mc':[4.5, 0.022], 'sh':[-1.95, 0.07]}, 'text_loc_2': {'mc':[4.5, 0.022], 'sh':[-1.95, 0.07]}, 'text_loc_3': {'mc':[4.5, 0.022], 'sh':[-1.95, 0.07]} } stf['CRs.Auger'] = { 'label': 'GCR rate @Auger [%]', 'ylims': [-8.0, 1.0], 'text_loc_1': {'mc':[4.5, -4.0], 'sh':[-1.95, -4.5]}, 'text_loc_2': {'mc':[4.5, -7.0], 'sh':[-1.95, -4.5]}, 'text_loc_3': {'mc':[4.5, -7.5], 'sh':[-1.95, -4.5]} } TEXT = {} GROUP_NAME = { '1': 'SLOW', '2': 'MID', '3': 'FAST' } dir_figs = '../../plots/woShiftCorr/MCflag0.1.2.2H/_auger_' dir_inp_mc = '../../../icmes/ascii/MCflag0.1.2.2H/woShiftCorr/_auger_' dir_inp_sh = '../../../sheaths.icmes/ascii/MCflag0.1.2.2H/woShiftCorr/_auger_' fname_fig = '%s/figs_splitted_1.png' % dir_figs vlo = [100.0, 375.0, 450.0] vhi = [375.0, 450.0, 3000.0] nvars = len(stf.keys()) print " input: " print " %s " % dir_inp_mc print " %s \n" % dir_inp_sh print " vlo, vhi: ", (vlo, vhi), '\n' print " nvars: ", nvars #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ f = plt.figure(1, figsize=(9, 10)) nr = 1 # scale for row size gs = GridSpec(nrows=6*nr, ncols=2*3) gs.update(left=0.1, right=0.98, hspace=0.13, wspace=0.15) for i in range(3): fname_inp = 'MCflag0.1.2.2H_2before.4after_fgap0.2_WangNaN_vlo.%3.1f.vhi.%3.1f' % (vlo[i], vhi[i]) fname_inp_nro_mc = dir_inp_mc + '/n.events_' + fname_inp + '.txt' fname_inp_nro_sh = dir_inp_sh + '/n.events_' + fname_inp + '.txt' fnro_mc = open(fname_inp_nro_mc, 'r') fnro_sh = open(fname_inp_nro_sh, 'r') n = 1 # number of row print " ______ col %d ______" % i for lmc, lsh in zip(fnro_mc, fnro_sh): l_mc = lmc.split() l_sh = lsh.split() varname = l_mc[0] # nombre de la variable if varname in ('AlphaRatio.ACE', 'CRs.Auger', 'CRs.McMurdo', 'rmsB.ACE'): continue n = stf[varname]['nrow'] ax = plt.subplot(gs[(n-1)*nr:n*nr, (2*i):(2*(i+1))]) # title for each column if varname=='B.ACE': # first panel row ax.set_title(GROUP_NAME['%d'%(i+1)], fontsize=18) Nfinal_mc, Nfinal_sh = int(l_mc[1]), int(l_sh[1]) print " %s"%varname, ' Nfinal_mc:%d' % Nfinal_mc, 'Nfinal_sh:%d' % Nfinal_sh #print " nax: %d" % nax mc, sh = gral(), gral() fname_inp_mc = dir_inp_mc + '/' + fname_inp + '_%s.txt' % varname fname_inp_sh = dir_inp_sh + '/' + fname_inp + '_%s.txt' % varname mc.tnorm, mc.med, mc.avr, mc.std_err, mc.nValues = np.loadtxt(fname_inp_mc).T sh.tnorm, sh.med, sh.avr, sh.std_err, sh.nValues = np.loadtxt(fname_inp_sh).T # nro de datos con mas del 80% non-gap data TEXT['mc'] = 'events: %d' % Nfinal_mc TEXT['sh'] = 'events: %d' % Nfinal_sh if(vlo[i]==100.0): TEXT_LOC = stf[varname]['text_loc_1'] #1.7, 12.0 elif(vlo[i]==375.0): TEXT_LOC = stf[varname]['text_loc_2'] #1.7, 12.0 elif(vlo[i]==450.0): TEXT_LOC = stf[varname]['text_loc_3'] #1.7, 12.0 else: print " ----> ERROR con 'v_lo'!" raise SystemExit ylims = array(stf[varname]['ylims']) #[4., 17.] ylabel = stf[varname]['label'] #'B [nT]' ax = makefig(ax, mc, sh, TEXT, TEXT_LOC, ylims, varname) # ticks & labels x if n==6: #n==nvars-1: ax.set_xlabel('time normalized to\nsheath/ICME passage [1]', fontsize=11) else: ax.set_xlabel('') #ax.get_xaxis().set_ticks([]) ax.xaxis.set_ticklabels([]) # ticks & labels y if i==0: ax.set_ylabel(ylabel, fontsize=13) else: ax.set_ylabel('') #ax.get_yaxis().set_ticks([]) ax.yaxis.set_ticklabels([]) #n += 1 # next row/axis fnro_mc.close() fnro_sh.close() #fig.tight_layout() savefig(fname_fig, dpi=250, bbox_inches='tight') close() print "\n output en:\n %s\n" % fname_fig #EOF
jimsrc/seatos
mixed.icmes/src/report/tt.py
Python
mit
9,791
[ "NetCDF" ]
603331ce96ebc6307acdad4382fbd7a74a98d4cf9d96100b84f2b9db08a2e383
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import mock import grpc from grpc.experimental import aio import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.essential_contacts_v1.services.essential_contacts_service import ( EssentialContactsServiceAsyncClient, ) from google.cloud.essential_contacts_v1.services.essential_contacts_service import ( EssentialContactsServiceClient, ) from google.cloud.essential_contacts_v1.services.essential_contacts_service import ( pagers, ) from google.cloud.essential_contacts_v1.services.essential_contacts_service import ( transports, ) from google.cloud.essential_contacts_v1.types import enums from google.cloud.essential_contacts_v1.types import service from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import google.auth def client_cert_source_callback(): return b"cert bytes", b"key bytes" # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): return ( "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT ) def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" assert EssentialContactsServiceClient._get_default_mtls_endpoint(None) is None assert ( EssentialContactsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint ) assert ( EssentialContactsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint ) assert ( EssentialContactsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint ) assert ( EssentialContactsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint ) assert ( EssentialContactsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi ) @pytest.mark.parametrize( "client_class", [EssentialContactsServiceClient, EssentialContactsServiceAsyncClient,], ) def test_essential_contacts_service_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == "essentialcontacts.googleapis.com:443" @pytest.mark.parametrize( "transport_class,transport_name", [ (transports.EssentialContactsServiceGrpcTransport, "grpc"), (transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio"), ], ) def test_essential_contacts_service_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() @pytest.mark.parametrize( "client_class", [EssentialContactsServiceClient, EssentialContactsServiceAsyncClient,], ) def test_essential_contacts_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds assert isinstance(client, client_class) client = client_class.from_service_account_json("dummy/file/path.json") assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == "essentialcontacts.googleapis.com:443" def test_essential_contacts_service_client_get_transport_class(): transport = EssentialContactsServiceClient.get_transport_class() available_transports = [ transports.EssentialContactsServiceGrpcTransport, ] assert transport in available_transports transport = EssentialContactsServiceClient.get_transport_class("grpc") assert transport == transports.EssentialContactsServiceGrpcTransport @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ ( EssentialContactsServiceClient, transports.EssentialContactsServiceGrpcTransport, "grpc", ), ( EssentialContactsServiceAsyncClient, transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), ], ) @mock.patch.object( EssentialContactsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EssentialContactsServiceClient), ) @mock.patch.object( EssentialContactsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EssentialContactsServiceAsyncClient), ) def test_essential_contacts_service_client_client_options( client_class, transport_class, transport_name ): # Check that if channel is provided we won't create a new one. with mock.patch.object( EssentialContactsServiceClient, "get_transport_class" ) as gtc: transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. with mock.patch.object( EssentialContactsServiceClient, "get_transport_class" ) as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, host="squid.clam.whelk", scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,use_client_cert_env", [ ( EssentialContactsServiceClient, transports.EssentialContactsServiceGrpcTransport, "grpc", "true", ), ( EssentialContactsServiceAsyncClient, transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true", ), ( EssentialContactsServiceClient, transports.EssentialContactsServiceGrpcTransport, "grpc", "false", ), ( EssentialContactsServiceAsyncClient, transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false", ), ], ) @mock.patch.object( EssentialContactsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EssentialContactsServiceClient), ) @mock.patch.object( EssentialContactsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EssentialContactsServiceAsyncClient), ) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) def test_essential_contacts_service_client_mtls_env_auto( client_class, transport_class, transport_name, use_client_cert_env ): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None expected_host = client.DEFAULT_ENDPOINT else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=client_cert_source_callback, ): if use_client_cert_env == "false": expected_host = client.DEFAULT_ENDPOINT expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT expected_client_cert_source = client_cert_source_callback patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class", [EssentialContactsServiceClient, EssentialContactsServiceAsyncClient], ) @mock.patch.object( EssentialContactsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EssentialContactsServiceClient), ) @mock.patch.object( EssentialContactsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EssentialContactsServiceAsyncClient), ) def test_essential_contacts_service_client_get_mtls_endpoint_and_cert_source( client_class, ): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): ( api_endpoint, cert_source, ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ ( EssentialContactsServiceClient, transports.EssentialContactsServiceGrpcTransport, "grpc", ), ( EssentialContactsServiceAsyncClient, transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), ], ) def test_essential_contacts_service_client_client_options_scopes( client_class, transport_class, transport_name ): # Check the case scopes are provided. options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,grpc_helpers", [ ( EssentialContactsServiceClient, transports.EssentialContactsServiceGrpcTransport, "grpc", grpc_helpers, ), ( EssentialContactsServiceAsyncClient, transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async, ), ], ) def test_essential_contacts_service_client_client_options_credentials_file( client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) def test_essential_contacts_service_client_client_options_from_dict(): with mock.patch( "google.cloud.essential_contacts_v1.services.essential_contacts_service.transports.EssentialContactsServiceGrpcTransport.__init__" ) as grpc_transport: grpc_transport.return_value = None client = EssentialContactsServiceClient( client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, host="squid.clam.whelk", scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,grpc_helpers", [ ( EssentialContactsServiceClient, transports.EssentialContactsServiceGrpcTransport, "grpc", grpc_helpers, ), ( EssentialContactsServiceAsyncClient, transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async, ), ], ) def test_essential_contacts_service_client_create_channel_credentials_file( client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # test that the credentials from file are saved and used as the credentials. with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch.object( google.auth, "default", autospec=True ) as adc, mock.patch.object( grpc_helpers, "create_channel" ) as create_channel: creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) adc.return_value = (creds, None) client = client_class(client_options=options, transport=transport_name) create_channel.assert_called_with( "essentialcontacts.googleapis.com:443", credentials=file_creds, credentials_file=None, quota_project_id=None, default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="essentialcontacts.googleapis.com", ssl_credentials=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) @pytest.mark.parametrize("request_type", [service.CreateContactRequest, dict,]) def test_create_contact(request_type, transport: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact( name="name_value", email="email_value", notification_category_subscriptions=[enums.NotificationCategory.ALL], language_tag="language_tag_value", validation_state=enums.ValidationState.VALID, ) response = client.create_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == service.CreateContactRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Contact) assert response.name == "name_value" assert response.email == "email_value" assert response.notification_category_subscriptions == [ enums.NotificationCategory.ALL ] assert response.language_tag == "language_tag_value" assert response.validation_state == enums.ValidationState.VALID def test_create_contact_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_contact), "__call__") as call: client.create_contact() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.CreateContactRequest() @pytest.mark.asyncio async def test_create_contact_async( transport: str = "grpc_asyncio", request_type=service.CreateContactRequest ): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.Contact( name="name_value", email="email_value", notification_category_subscriptions=[enums.NotificationCategory.ALL], language_tag="language_tag_value", validation_state=enums.ValidationState.VALID, ) ) response = await client.create_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == service.CreateContactRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Contact) assert response.name == "name_value" assert response.email == "email_value" assert response.notification_category_subscriptions == [ enums.NotificationCategory.ALL ] assert response.language_tag == "language_tag_value" assert response.validation_state == enums.ValidationState.VALID @pytest.mark.asyncio async def test_create_contact_async_from_dict(): await test_create_contact_async(request_type=dict) def test_create_contact_field_headers(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.CreateContactRequest() request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_contact), "__call__") as call: call.return_value = service.Contact() client.create_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] @pytest.mark.asyncio async def test_create_contact_field_headers_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.CreateContactRequest() request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_contact), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Contact()) await client.create_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_create_contact_flattened(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_contact( parent="parent_value", contact=service.Contact(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent mock_val = "parent_value" assert arg == mock_val arg = args[0].contact mock_val = service.Contact(name="name_value") assert arg == mock_val def test_create_contact_flattened_error(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.create_contact( service.CreateContactRequest(), parent="parent_value", contact=service.Contact(name="name_value"), ) @pytest.mark.asyncio async def test_create_contact_flattened_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Contact()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_contact( parent="parent_value", contact=service.Contact(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent mock_val = "parent_value" assert arg == mock_val arg = args[0].contact mock_val = service.Contact(name="name_value") assert arg == mock_val @pytest.mark.asyncio async def test_create_contact_flattened_error_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.create_contact( service.CreateContactRequest(), parent="parent_value", contact=service.Contact(name="name_value"), ) @pytest.mark.parametrize("request_type", [service.UpdateContactRequest, dict,]) def test_update_contact(request_type, transport: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact( name="name_value", email="email_value", notification_category_subscriptions=[enums.NotificationCategory.ALL], language_tag="language_tag_value", validation_state=enums.ValidationState.VALID, ) response = client.update_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == service.UpdateContactRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Contact) assert response.name == "name_value" assert response.email == "email_value" assert response.notification_category_subscriptions == [ enums.NotificationCategory.ALL ] assert response.language_tag == "language_tag_value" assert response.validation_state == enums.ValidationState.VALID def test_update_contact_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_contact), "__call__") as call: client.update_contact() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.UpdateContactRequest() @pytest.mark.asyncio async def test_update_contact_async( transport: str = "grpc_asyncio", request_type=service.UpdateContactRequest ): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.Contact( name="name_value", email="email_value", notification_category_subscriptions=[enums.NotificationCategory.ALL], language_tag="language_tag_value", validation_state=enums.ValidationState.VALID, ) ) response = await client.update_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == service.UpdateContactRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Contact) assert response.name == "name_value" assert response.email == "email_value" assert response.notification_category_subscriptions == [ enums.NotificationCategory.ALL ] assert response.language_tag == "language_tag_value" assert response.validation_state == enums.ValidationState.VALID @pytest.mark.asyncio async def test_update_contact_async_from_dict(): await test_update_contact_async(request_type=dict) def test_update_contact_field_headers(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.UpdateContactRequest() request.contact.name = "contact.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_contact), "__call__") as call: call.return_value = service.Contact() client.update_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "contact.name=contact.name/value",) in kw[ "metadata" ] @pytest.mark.asyncio async def test_update_contact_field_headers_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.UpdateContactRequest() request.contact.name = "contact.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_contact), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Contact()) await client.update_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "contact.name=contact.name/value",) in kw[ "metadata" ] def test_update_contact_flattened(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_contact( contact=service.Contact(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].contact mock_val = service.Contact(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val def test_update_contact_flattened_error(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.update_contact( service.UpdateContactRequest(), contact=service.Contact(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_contact_flattened_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Contact()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_contact( contact=service.Contact(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].contact mock_val = service.Contact(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio async def test_update_contact_flattened_error_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.update_contact( service.UpdateContactRequest(), contact=service.Contact(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize("request_type", [service.ListContactsRequest, dict,]) def test_list_contacts(request_type, transport: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListContactsResponse( next_page_token="next_page_token_value", ) response = client.list_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == service.ListContactsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListContactsPager) assert response.next_page_token == "next_page_token_value" def test_list_contacts_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: client.list_contacts() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.ListContactsRequest() @pytest.mark.asyncio async def test_list_contacts_async( transport: str = "grpc_asyncio", request_type=service.ListContactsRequest ): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListContactsResponse(next_page_token="next_page_token_value",) ) response = await client.list_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == service.ListContactsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListContactsAsyncPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio async def test_list_contacts_async_from_dict(): await test_list_contacts_async(request_type=dict) def test_list_contacts_field_headers(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.ListContactsRequest() request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: call.return_value = service.ListContactsResponse() client.list_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] @pytest.mark.asyncio async def test_list_contacts_field_headers_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.ListContactsRequest() request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListContactsResponse() ) await client.list_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_list_contacts_flattened(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListContactsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_contacts(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent mock_val = "parent_value" assert arg == mock_val def test_list_contacts_flattened_error(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.list_contacts( service.ListContactsRequest(), parent="parent_value", ) @pytest.mark.asyncio async def test_list_contacts_flattened_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListContactsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListContactsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_contacts(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio async def test_list_contacts_flattened_error_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.list_contacts( service.ListContactsRequest(), parent="parent_value", ) def test_list_contacts_pager(transport_name: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ListContactsResponse(contacts=[], next_page_token="def",), service.ListContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ListContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) metadata = () metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_contacts(request={}) assert pager._metadata == metadata results = [i for i in pager] assert len(results) == 6 assert all(isinstance(i, service.Contact) for i in results) def test_list_contacts_pages(transport_name: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contacts), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ListContactsResponse(contacts=[], next_page_token="def",), service.ListContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ListContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) pages = list(client.list_contacts(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio async def test_list_contacts_async_pager(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.list_contacts), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( service.ListContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ListContactsResponse(contacts=[], next_page_token="def",), service.ListContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ListContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) async_pager = await client.list_contacts(request={},) assert async_pager.next_page_token == "abc" responses = [] async for response in async_pager: responses.append(response) assert len(responses) == 6 assert all(isinstance(i, service.Contact) for i in responses) @pytest.mark.asyncio async def test_list_contacts_async_pages(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.list_contacts), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( service.ListContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ListContactsResponse(contacts=[], next_page_token="def",), service.ListContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ListContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) pages = [] async for page_ in (await client.list_contacts(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.parametrize("request_type", [service.GetContactRequest, dict,]) def test_get_contact(request_type, transport: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact( name="name_value", email="email_value", notification_category_subscriptions=[enums.NotificationCategory.ALL], language_tag="language_tag_value", validation_state=enums.ValidationState.VALID, ) response = client.get_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == service.GetContactRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Contact) assert response.name == "name_value" assert response.email == "email_value" assert response.notification_category_subscriptions == [ enums.NotificationCategory.ALL ] assert response.language_tag == "language_tag_value" assert response.validation_state == enums.ValidationState.VALID def test_get_contact_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_contact), "__call__") as call: client.get_contact() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.GetContactRequest() @pytest.mark.asyncio async def test_get_contact_async( transport: str = "grpc_asyncio", request_type=service.GetContactRequest ): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.Contact( name="name_value", email="email_value", notification_category_subscriptions=[enums.NotificationCategory.ALL], language_tag="language_tag_value", validation_state=enums.ValidationState.VALID, ) ) response = await client.get_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == service.GetContactRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Contact) assert response.name == "name_value" assert response.email == "email_value" assert response.notification_category_subscriptions == [ enums.NotificationCategory.ALL ] assert response.language_tag == "language_tag_value" assert response.validation_state == enums.ValidationState.VALID @pytest.mark.asyncio async def test_get_contact_async_from_dict(): await test_get_contact_async(request_type=dict) def test_get_contact_field_headers(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.GetContactRequest() request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_contact), "__call__") as call: call.return_value = service.Contact() client.get_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] @pytest.mark.asyncio async def test_get_contact_field_headers_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.GetContactRequest() request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_contact), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Contact()) await client.get_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_get_contact_flattened(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_contact(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name mock_val = "name_value" assert arg == mock_val def test_get_contact_flattened_error(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_contact( service.GetContactRequest(), name="name_value", ) @pytest.mark.asyncio async def test_get_contact_flattened_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Contact() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Contact()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_contact(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio async def test_get_contact_flattened_error_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_contact( service.GetContactRequest(), name="name_value", ) @pytest.mark.parametrize("request_type", [service.DeleteContactRequest, dict,]) def test_delete_contact(request_type, transport: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == service.DeleteContactRequest() # Establish that the response is the type that we expect. assert response is None def test_delete_contact_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_contact), "__call__") as call: client.delete_contact() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.DeleteContactRequest() @pytest.mark.asyncio async def test_delete_contact_async( transport: str = "grpc_asyncio", request_type=service.DeleteContactRequest ): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == service.DeleteContactRequest() # Establish that the response is the type that we expect. assert response is None @pytest.mark.asyncio async def test_delete_contact_async_from_dict(): await test_delete_contact_async(request_type=dict) def test_delete_contact_field_headers(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.DeleteContactRequest() request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_contact), "__call__") as call: call.return_value = None client.delete_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] @pytest.mark.asyncio async def test_delete_contact_field_headers_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.DeleteContactRequest() request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_contact), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_contact(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_delete_contact_flattened(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_contact(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name mock_val = "name_value" assert arg == mock_val def test_delete_contact_flattened_error(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.delete_contact( service.DeleteContactRequest(), name="name_value", ) @pytest.mark.asyncio async def test_delete_contact_flattened_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_contact), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_contact(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio async def test_delete_contact_flattened_error_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.delete_contact( service.DeleteContactRequest(), name="name_value", ) @pytest.mark.parametrize("request_type", [service.ComputeContactsRequest, dict,]) def test_compute_contacts(request_type, transport: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.compute_contacts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ComputeContactsResponse( next_page_token="next_page_token_value", ) response = client.compute_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == service.ComputeContactsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ComputeContactsPager) assert response.next_page_token == "next_page_token_value" def test_compute_contacts_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.compute_contacts), "__call__") as call: client.compute_contacts() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.ComputeContactsRequest() @pytest.mark.asyncio async def test_compute_contacts_async( transport: str = "grpc_asyncio", request_type=service.ComputeContactsRequest ): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.compute_contacts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ComputeContactsResponse(next_page_token="next_page_token_value",) ) response = await client.compute_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == service.ComputeContactsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ComputeContactsAsyncPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio async def test_compute_contacts_async_from_dict(): await test_compute_contacts_async(request_type=dict) def test_compute_contacts_field_headers(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.ComputeContactsRequest() request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.compute_contacts), "__call__") as call: call.return_value = service.ComputeContactsResponse() client.compute_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] @pytest.mark.asyncio async def test_compute_contacts_field_headers_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.ComputeContactsRequest() request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.compute_contacts), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ComputeContactsResponse() ) await client.compute_contacts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_compute_contacts_pager(transport_name: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.compute_contacts), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ComputeContactsResponse(contacts=[], next_page_token="def",), service.ComputeContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) metadata = () metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.compute_contacts(request={}) assert pager._metadata == metadata results = [i for i in pager] assert len(results) == 6 assert all(isinstance(i, service.Contact) for i in results) def test_compute_contacts_pages(transport_name: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.compute_contacts), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ComputeContactsResponse(contacts=[], next_page_token="def",), service.ComputeContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) pages = list(client.compute_contacts(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio async def test_compute_contacts_async_pager(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.compute_contacts), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ComputeContactsResponse(contacts=[], next_page_token="def",), service.ComputeContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) async_pager = await client.compute_contacts(request={},) assert async_pager.next_page_token == "abc" responses = [] async for response in async_pager: responses.append(response) assert len(responses) == 6 assert all(isinstance(i, service.Contact) for i in responses) @pytest.mark.asyncio async def test_compute_contacts_async_pages(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.compute_contacts), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(), service.Contact(),], next_page_token="abc", ), service.ComputeContactsResponse(contacts=[], next_page_token="def",), service.ComputeContactsResponse( contacts=[service.Contact(),], next_page_token="ghi", ), service.ComputeContactsResponse( contacts=[service.Contact(), service.Contact(),], ), RuntimeError, ) pages = [] async for page_ in (await client.compute_contacts(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.parametrize("request_type", [service.SendTestMessageRequest, dict,]) def test_send_test_message(request_type, transport: str = "grpc"): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.send_test_message), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None response = client.send_test_message(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == service.SendTestMessageRequest() # Establish that the response is the type that we expect. assert response is None def test_send_test_message_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.send_test_message), "__call__" ) as call: client.send_test_message() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.SendTestMessageRequest() @pytest.mark.asyncio async def test_send_test_message_async( transport: str = "grpc_asyncio", request_type=service.SendTestMessageRequest ): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.send_test_message), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.send_test_message(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == service.SendTestMessageRequest() # Establish that the response is the type that we expect. assert response is None @pytest.mark.asyncio async def test_send_test_message_async_from_dict(): await test_send_test_message_async(request_type=dict) def test_send_test_message_field_headers(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.SendTestMessageRequest() request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.send_test_message), "__call__" ) as call: call.return_value = None client.send_test_message(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] @pytest.mark.asyncio async def test_send_test_message_field_headers_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = service.SendTestMessageRequest() request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.send_test_message), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.send_test_message(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EssentialContactsServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.EssentialContactsServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EssentialContactsServiceClient( client_options={"credentials_file": "credentials.json"}, transport=transport, ) # It is an error to provide an api_key and a transport instance. transport = transports.EssentialContactsServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): client = EssentialContactsServiceClient( client_options=options, transport=transport, ) # It is an error to provide an api_key and a credential. options = mock.Mock() options.api_key = "api_key" with pytest.raises(ValueError): client = EssentialContactsServiceClient( client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. transport = transports.EssentialContactsServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EssentialContactsServiceClient( client_options={"scopes": ["1", "2"]}, transport=transport, ) def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.EssentialContactsServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) client = EssentialContactsServiceClient(transport=transport) assert client.transport is transport def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EssentialContactsServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.EssentialContactsServiceGrpcAsyncIOTransport( credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @pytest.mark.parametrize( "transport_class", [ transports.EssentialContactsServiceGrpcTransport, transports.EssentialContactsServiceGrpcAsyncIOTransport, ], ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.EssentialContactsServiceGrpcTransport, ) def test_essential_contacts_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EssentialContactsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) def test_essential_contacts_service_base_transport(): # Instantiate the base transport. with mock.patch( "google.cloud.essential_contacts_v1.services.essential_contacts_service.transports.EssentialContactsServiceTransport.__init__" ) as Transport: Transport.return_value = None transport = transports.EssentialContactsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly # raise NotImplementedError. methods = ( "create_contact", "update_contact", "list_contacts", "get_contact", "delete_contact", "compute_contacts", "send_test_message", ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) with pytest.raises(NotImplementedError): transport.close() def test_essential_contacts_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.essential_contacts_v1.services.essential_contacts_service.transports.EssentialContactsServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EssentialContactsServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=None, default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_essential_contacts_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.essential_contacts_v1.services.essential_contacts_service.transports.EssentialContactsServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EssentialContactsServiceTransport() adc.assert_called_once() def test_essential_contacts_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) EssentialContactsServiceClient() adc.assert_called_once_with( scopes=None, default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @pytest.mark.parametrize( "transport_class", [ transports.EssentialContactsServiceGrpcTransport, transports.EssentialContactsServiceGrpcAsyncIOTransport, ], ) def test_essential_contacts_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.EssentialContactsServiceGrpcTransport, grpc_helpers), (transports.EssentialContactsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_essential_contacts_service_transport_create_channel( transport_class, grpc_helpers ): # If credentials and host are not provided, the transport class should use # ADC credentials. with mock.patch.object( google.auth, "default", autospec=True ) as adc, mock.patch.object( grpc_helpers, "create_channel", autospec=True ) as create_channel: creds = ga_credentials.AnonymousCredentials() adc.return_value = (creds, None) transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "essentialcontacts.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="essentialcontacts.googleapis.com", ssl_credentials=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) @pytest.mark.parametrize( "transport_class", [ transports.EssentialContactsServiceGrpcTransport, transports.EssentialContactsServiceGrpcAsyncIOTransport, ], ) def test_essential_contacts_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: mock_ssl_channel_creds = mock.Mock() transport_class( host="squid.clam.whelk", credentials=cred, ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", credentials=cred, credentials_file=None, scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls # is used. with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, client_cert_source_for_mtls=client_cert_source_callback, ) expected_cert, expected_key = client_cert_source_callback() mock_ssl_cred.assert_called_once_with( certificate_chain=expected_cert, private_key=expected_key ) def test_essential_contacts_service_host_no_port(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="essentialcontacts.googleapis.com" ), ) assert client.transport._host == "essentialcontacts.googleapis.com:443" def test_essential_contacts_service_host_with_port(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="essentialcontacts.googleapis.com:8000" ), ) assert client.transport._host == "essentialcontacts.googleapis.com:8000" def test_essential_contacts_service_grpc_transport_channel(): channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.EssentialContactsServiceGrpcTransport( host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" assert transport._ssl_channel_credentials == None def test_essential_contacts_service_grpc_asyncio_transport_channel(): channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.EssentialContactsServiceGrpcAsyncIOTransport( host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" assert transport._ssl_channel_credentials == None # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ transports.EssentialContactsServiceGrpcTransport, transports.EssentialContactsServiceGrpcAsyncIOTransport, ], ) def test_essential_contacts_service_transport_channel_mtls_with_client_cert_source( transport_class, ): with mock.patch( "grpc.ssl_channel_credentials", autospec=True ) as grpc_ssl_channel_cred: with mock.patch.object( transport_class, "create_channel" ) as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", api_mtls_endpoint="mtls.squid.clam.whelk", client_cert_source=client_cert_source_callback, ) adc.assert_called_once() grpc_ssl_channel_cred.assert_called_once_with( certificate_chain=b"cert bytes", private_key=b"key bytes" ) grpc_create_channel.assert_called_once_with( "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ transports.EssentialContactsServiceGrpcTransport, transports.EssentialContactsServiceGrpcAsyncIOTransport, ], ) def test_essential_contacts_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): with mock.patch.object( transport_class, "create_channel" ) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel mock_cred = mock.Mock() with pytest.warns(DeprecationWarning): transport = transport_class( host="squid.clam.whelk", credentials=mock_cred, api_mtls_endpoint="mtls.squid.clam.whelk", client_cert_source=None, ) grpc_create_channel.assert_called_once_with( "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) assert transport.grpc_channel == mock_grpc_channel def test_contact_path(): project = "squid" contact = "clam" expected = "projects/{project}/contacts/{contact}".format( project=project, contact=contact, ) actual = EssentialContactsServiceClient.contact_path(project, contact) assert expected == actual def test_parse_contact_path(): expected = { "project": "whelk", "contact": "octopus", } path = EssentialContactsServiceClient.contact_path(**expected) # Check that the path construction is reversible. actual = EssentialContactsServiceClient.parse_contact_path(path) assert expected == actual def test_common_billing_account_path(): billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) actual = EssentialContactsServiceClient.common_billing_account_path(billing_account) assert expected == actual def test_parse_common_billing_account_path(): expected = { "billing_account": "nudibranch", } path = EssentialContactsServiceClient.common_billing_account_path(**expected) # Check that the path construction is reversible. actual = EssentialContactsServiceClient.parse_common_billing_account_path(path) assert expected == actual def test_common_folder_path(): folder = "cuttlefish" expected = "folders/{folder}".format(folder=folder,) actual = EssentialContactsServiceClient.common_folder_path(folder) assert expected == actual def test_parse_common_folder_path(): expected = { "folder": "mussel", } path = EssentialContactsServiceClient.common_folder_path(**expected) # Check that the path construction is reversible. actual = EssentialContactsServiceClient.parse_common_folder_path(path) assert expected == actual def test_common_organization_path(): organization = "winkle" expected = "organizations/{organization}".format(organization=organization,) actual = EssentialContactsServiceClient.common_organization_path(organization) assert expected == actual def test_parse_common_organization_path(): expected = { "organization": "nautilus", } path = EssentialContactsServiceClient.common_organization_path(**expected) # Check that the path construction is reversible. actual = EssentialContactsServiceClient.parse_common_organization_path(path) assert expected == actual def test_common_project_path(): project = "scallop" expected = "projects/{project}".format(project=project,) actual = EssentialContactsServiceClient.common_project_path(project) assert expected == actual def test_parse_common_project_path(): expected = { "project": "abalone", } path = EssentialContactsServiceClient.common_project_path(**expected) # Check that the path construction is reversible. actual = EssentialContactsServiceClient.parse_common_project_path(path) assert expected == actual def test_common_location_path(): project = "squid" location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) actual = EssentialContactsServiceClient.common_location_path(project, location) assert expected == actual def test_parse_common_location_path(): expected = { "project": "whelk", "location": "octopus", } path = EssentialContactsServiceClient.common_location_path(**expected) # Check that the path construction is reversible. actual = EssentialContactsServiceClient.parse_common_location_path(path) assert expected == actual def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( transports.EssentialContactsServiceTransport, "_prep_wrapped_messages" ) as prep: client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object( transports.EssentialContactsServiceTransport, "_prep_wrapped_messages" ) as prep: transport_class = EssentialContactsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @pytest.mark.asyncio async def test_transport_close_async(): client = EssentialContactsServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) with mock.patch.object( type(getattr(client.transport, "grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() def test_transport_close(): transports = { "grpc": "_grpc_channel", } for transport, close_name in transports.items(): client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) with mock.patch.object( type(getattr(client.transport, close_name)), "close" ) as close: with client: close.assert_not_called() close.assert_called_once() def test_client_ctx(): transports = [ "grpc", ] for transport in transports: client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: close.assert_not_called() with client: pass close.assert_called() @pytest.mark.parametrize( "client_class,transport_class", [ ( EssentialContactsServiceClient, transports.EssentialContactsServiceGrpcTransport, ), ( EssentialContactsServiceAsyncClient, transports.EssentialContactsServiceGrpcAsyncIOTransport, ), ], ) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True ) as get_api_key_credentials: mock_cred = mock.Mock() get_api_key_credentials.return_value = mock_cred options = client_options.ClientOptions() options.api_key = "api_key" with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, )
googleapis/python-essential-contacts
tests/unit/gapic/essential_contacts_v1/test_essential_contacts_service.py
Python
apache-2.0
113,777
[ "Octopus" ]
0e3ec8cb31c3c9c628ed2c4e884e8d4ecfd6fda0af47bd6387b998f41097a71a
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import os import unittest import numpy as np from pymatgen.io.pwscf import PWInput, PWInputError, PWOutput from pymatgen.util.testing import PymatgenTest class PWInputTest(PymatgenTest): def test_init(self): s = self.get_structure("Li2O") self.assertRaises( PWInputError, PWInput, s, control={"calculation": "scf", "pseudo_dir": "./"}, pseudo={"Li": "Li.pbe-n-kjpaw_psl.0.1.UPF"}, ) def test_str_mixed_oxidation(self): s = self.get_structure("Li2O") s.remove_oxidation_states() s[1] = "Li1" pw = PWInput( s, control={"calculation": "scf", "pseudo_dir": "./"}, pseudo={ "Li": "Li.pbe-n-kjpaw_psl.0.1.UPF", "Li+": "Li.pbe-n-kjpaw_psl.0.1.UPF", "O": "O.pbe-n-kjpaw_psl.0.1.UPF", }, system={"ecutwfc": 50}, ) ans = """&CONTROL calculation = 'scf', pseudo_dir = './', / &SYSTEM ecutwfc = 50, ibrav = 0, nat = 3, ntyp = 3, / &ELECTRONS / &IONS / &CELL / ATOMIC_SPECIES Li 6.9410 Li.pbe-n-kjpaw_psl.0.1.UPF Li+ 6.9410 Li.pbe-n-kjpaw_psl.0.1.UPF O 15.9994 O.pbe-n-kjpaw_psl.0.1.UPF ATOMIC_POSITIONS crystal O 0.000000 0.000000 0.000000 Li+ 0.750178 0.750178 0.750178 Li 0.249822 0.249822 0.249822 K_POINTS automatic 1 1 1 0 0 0 CELL_PARAMETERS angstrom 2.917389 0.097894 1.520005 0.964634 2.755036 1.520005 0.133206 0.097894 3.286918 """ self.assertEqual(pw.__str__().strip(), ans.strip()) def test_str_without_oxidation(self): s = self.get_structure("Li2O") s.remove_oxidation_states() pw = PWInput( s, control={"calculation": "scf", "pseudo_dir": "./"}, pseudo={ "Li": "Li.pbe-n-kjpaw_psl.0.1.UPF", "O": "O.pbe-n-kjpaw_psl.0.1.UPF", }, system={"ecutwfc": 50}, ) ans = """&CONTROL calculation = 'scf', pseudo_dir = './', / &SYSTEM ecutwfc = 50, ibrav = 0, nat = 3, ntyp = 2, / &ELECTRONS / &IONS / &CELL / ATOMIC_SPECIES Li 6.9410 Li.pbe-n-kjpaw_psl.0.1.UPF O 15.9994 O.pbe-n-kjpaw_psl.0.1.UPF ATOMIC_POSITIONS crystal O 0.000000 0.000000 0.000000 Li 0.750178 0.750178 0.750178 Li 0.249822 0.249822 0.249822 K_POINTS automatic 1 1 1 0 0 0 CELL_PARAMETERS angstrom 2.917389 0.097894 1.520005 0.964634 2.755036 1.520005 0.133206 0.097894 3.286918 """ self.assertEqual(pw.__str__().strip(), ans.strip()) def test_str_with_oxidation(self): s = self.get_structure("Li2O") pw = PWInput( s, control={"calculation": "scf", "pseudo_dir": "./"}, pseudo={ "Li+": "Li.pbe-n-kjpaw_psl.0.1.UPF", "O2-": "O.pbe-n-kjpaw_psl.0.1.UPF", }, system={"ecutwfc": 50}, ) ans = """&CONTROL calculation = 'scf', pseudo_dir = './', / &SYSTEM ecutwfc = 50, ibrav = 0, nat = 3, ntyp = 2, / &ELECTRONS / &IONS / &CELL / ATOMIC_SPECIES Li+ 6.9410 Li.pbe-n-kjpaw_psl.0.1.UPF O2- 15.9994 O.pbe-n-kjpaw_psl.0.1.UPF ATOMIC_POSITIONS crystal O2- 0.000000 0.000000 0.000000 Li+ 0.750178 0.750178 0.750178 Li+ 0.249822 0.249822 0.249822 K_POINTS automatic 1 1 1 0 0 0 CELL_PARAMETERS angstrom 2.917389 0.097894 1.520005 0.964634 2.755036 1.520005 0.133206 0.097894 3.286918 """ self.assertEqual(pw.__str__().strip(), ans.strip()) def test_write_str_with_kpoints(self): s = self.get_structure("Li2O") s.remove_oxidation_states() kpoints = [[0.0, 0.0, 0.0], [0.0, 0.5, 0.5], [0.5, 0.0, 0.0], [0.0, 0.0, 0.5], [0.5, 0.5, 0.5]] pw = PWInput( s, control={"calculation": "scf", "pseudo_dir": "./"}, pseudo={ "Li": "Li.pbe-n-kjpaw_psl.0.1.UPF", "O": "O.pbe-n-kjpaw_psl.0.1.UPF", }, system={"ecutwfc": 50}, kpoints_mode="crystal_b", kpoints_grid=kpoints, ) ans = """ &CONTROL calculation = 'scf', pseudo_dir = './', / &SYSTEM ecutwfc = 50, ibrav = 0, nat = 3, ntyp = 2, / &ELECTRONS / &IONS / &CELL / ATOMIC_SPECIES Li 6.9410 Li.pbe-n-kjpaw_psl.0.1.UPF O 15.9994 O.pbe-n-kjpaw_psl.0.1.UPF ATOMIC_POSITIONS crystal O 0.000000 0.000000 0.000000 Li 0.750178 0.750178 0.750178 Li 0.249822 0.249822 0.249822 K_POINTS crystal_b 5 0.0000 0.0000 0.0000 0.0000 0.5000 0.5000 0.5000 0.0000 0.0000 0.0000 0.0000 0.5000 0.5000 0.5000 0.5000 CELL_PARAMETERS angstrom 2.917389 0.097894 1.520005 0.964634 2.755036 1.520005 0.133206 0.097894 3.286918 """ self.assertEqual(pw.__str__().strip(), ans.strip()) def test_read_str(self): string = """ &CONTROL calculation = 'scf' pseudo_dir = './' wf_collect = .TRUE. / &SYSTEM ibrav = 0, nat = 53 ntyp = 2 input_dft = 'PBE' ecutwfc = 80 nspin = 1 nbnd = 280 / &ELECTRONS / &IONS / &CELL / ATOMIC_SPECIES Mg 24.3050 Mg_ONCV_PBE-1.2.upf O 15.9994 O_ONCV_PBE-1.2.upf ATOMIC_POSITIONS crystal Mg -0.000000000 0.000000000 -0.000000000 Mg 0.000000000 1.000000000 0.333134366 Mg 0.000000000 1.000000000 0.666865634 Mg -0.000000000 0.333134366 1.000000000 Mg 0.000037606 0.333320465 0.333320465 Mg 0.000000000 0.333134366 0.666865634 Mg 0.000000000 0.666865634 1.000000000 Mg 0.000000000 0.666865634 0.333134366 Mg -0.000037606 0.666679535 0.666679535 Mg 0.333134366 0.000000000 0.000000000 Mg 0.333320465 0.000037606 0.333320465 Mg 0.333134366 1.000000000 0.666865634 Mg 0.333320465 0.333320465 0.000037606 Mg 0.333320465 0.333320465 0.333320465 Mg 0.331436170 0.331436170 0.668563830 Mg 0.333134366 0.666865634 -0.000000000 Mg 0.331436170 0.668563830 0.331436170 Mg 0.331436170 0.668563830 0.668563830 Mg 0.666865634 0.000000000 0.000000000 Mg 0.666865634 0.000000000 0.333134366 Mg 0.666679535 -0.000037606 0.666679535 Mg 0.666865634 0.333134366 -0.000000000 Mg 0.668563830 0.331436170 0.331436170 Mg 0.668563830 0.331436170 0.668563830 Mg 0.666679535 0.666679535 -0.000037606 Mg 0.668563830 0.668563830 0.331436170 Mg 0.666679535 0.666679535 0.666679535 O 0.166588534 0.166588534 0.166588534 O 0.166588534 0.166588534 0.500235399 O 0.166465543 0.166465543 0.833534457 O 0.166588534 0.500235399 0.166588534 O 0.166169242 0.500000000 0.500000000 O 0.166169242 0.500000000 0.833830758 O 0.166465543 0.833534457 0.166465543 O 0.166169242 0.833830758 0.500000000 O 0.166465543 0.833534457 0.833534457 O 0.500235399 0.166588534 0.166588534 O 0.500000000 0.166169242 0.500000000 O 0.500000000 0.166169242 0.833830758 O 0.500000000 0.500000000 0.166169242 O 0.500000000 0.500000000 0.833830758 O 0.500000000 0.833830758 0.166169242 O 0.500000000 0.833830758 0.500000000 O 0.499764601 0.833411466 0.833411466 O 0.833534457 0.166465543 0.166465543 O 0.833830758 0.166169242 0.500000000 O 0.833534457 0.166465543 0.833534457 O 0.833830758 0.500000000 0.166169242 O 0.833830758 0.500000000 0.500000000 O 0.833411466 0.499764601 0.833411466 O 0.833534457 0.833534457 0.166465543 O 0.833411466 0.833411466 0.499764601 O 0.833411466 0.833411466 0.833411466 K_POINTS gamma CELL_PARAMETERS angstrom 0.000000 6.373854 6.373854 6.373854 0.000000 6.373854 6.373854 6.373854 0.000000 """ lattice = np.array([[0.0, 6.373854, 6.373854], [6.373854, 0.0, 6.373854], [6.373854, 6.373854, 0.0]]) sites = np.array( [ [0.0, 0.0, 0.0], [8.49720381, 2.12334981, 6.373854], [10.62435819, 4.25050419, 6.373854], [8.49720381, 6.373854, 2.12334981], [4.24907196, 2.12477567, 2.12477567], [6.373854, 4.25050419, 2.12334981], [10.62435819, 6.373854, 4.25050419], [6.373854, 2.12334981, 4.25050419], [8.49863604, 4.24907833, 4.24907833], [0.0, 2.12334981, 2.12334981], [2.12477567, 4.24907196, 2.12477567], [10.62435819, 6.373854, 8.49720381], [2.12477567, 2.12477567, 4.24907196], [4.24907196, 4.24907196, 4.24907196], [6.373854, 6.373854, 4.22505152], [4.25050419, 2.12334981, 6.373854], [6.373854, 4.22505152, 6.373854], [8.52265648, 6.373854, 6.373854], [0.0, 4.25050419, 4.25050419], [2.12334981, 6.373854, 4.25050419], [4.24907833, 8.49863604, 4.24907833], [2.12334981, 4.25050419, 6.373854], [4.22505152, 6.373854, 6.373854], [6.373854, 8.52265648, 6.373854], [4.24907833, 4.24907833, 8.49863604], [6.373854, 6.373854, 8.52265648], [8.49863604, 8.49863604, 8.49863604], [2.12362199, 2.12362199, 2.12362199], [4.25023839, 4.25023839, 2.12362199], [6.373854, 6.373854, 2.12205413], [4.25023839, 2.12362199, 4.25023839], [6.373854, 4.24606549, 4.24606549], [8.50164251, 6.373854, 4.24606549], [6.373854, 2.12205413, 6.373854], [8.50164251, 4.24606549, 6.373854], [10.62565387, 6.373854, 6.373854], [2.12362199, 4.25023839, 4.25023839], [4.24606549, 6.373854, 4.24606549], [6.373854, 8.50164251, 4.24606549], [4.24606549, 4.24606549, 6.373854], [8.50164251, 8.50164251, 6.373854], [6.373854, 4.24606549, 8.50164251], [8.50164251, 6.373854, 8.50164251], [10.62408601, 8.49746961, 8.49746961], [2.12205413, 6.373854, 6.373854], [4.24606549, 8.50164251, 6.373854], [6.373854, 10.62565387, 6.373854], [4.24606549, 6.373854, 8.50164251], [6.373854, 8.50164251, 8.50164251], [8.49746961, 10.62408601, 8.49746961], [6.373854, 6.373854, 10.62565387], [8.49746961, 8.49746961, 10.62408601], [10.62408601, 10.62408601, 10.62408601], ] ) pwin = PWInput.from_string(string) # generate list of coords pw_sites = [] for site in pwin.structure.sites: pw_sites.append(list(site.coords)) pw_sites = np.array(pw_sites) np.testing.assert_allclose(sites, pw_sites) np.testing.assert_allclose(lattice, pwin.structure.lattice.matrix) class PWOuputTest(PymatgenTest): def setUp(self): self.pwout = PWOutput(os.path.join(PymatgenTest.TEST_FILES_DIR, "Si.pwscf.out")) def test_properties(self): self.assertAlmostEqual(self.pwout.final_energy, -93.45259708) def test_get_celldm(self): self.assertAlmostEqual(self.pwout.get_celldm(1), 10.323) for i in range(2, 7): self.assertAlmostEqual(self.pwout.get_celldm(i), 0) if __name__ == "__main__": unittest.main()
materialsproject/pymatgen
pymatgen/io/tests/test_pwscf.py
Python
mit
11,756
[ "CRYSTAL", "pymatgen" ]
05c20da09d3d31484e00bdc8d994146de92e9f882a7addaa5339917cbd67848a
import re import os import shutil import logging import netCDF4 from django.dispatch import receiver from django.core.files.uploadedfile import UploadedFile from hs_core.signals import pre_add_files_to_resource, \ pre_delete_file_from_resource, pre_metadata_element_create, pre_metadata_element_update, \ post_add_files_to_resource, post_create_resource from hs_core.hydroshare.resource import ResourceFile, delete_resource_file_only from hs_core.hydroshare import utils from hs_app_netCDF.forms import VariableValidationForm, OriginalCoverageForm, VariableForm from hs_app_netCDF.models import NetcdfResource import hs_file_types.nc_functions.nc_utils as nc_utils import hs_file_types.nc_functions.nc_meta as nc_meta from hs_file_types.models.netcdf import create_header_info_txt_file, add_metadata_to_list @receiver(post_create_resource, sender=NetcdfResource) def netcdf_post_create_resource(sender, **kwargs): log = logging.getLogger() resource = kwargs['resource'] validate_files_dict = kwargs['validate_files'] res_file = resource.files.all().first() if res_file: temp_file = utils.get_file_from_irods(res_file) nc_dataset = nc_utils.get_nc_dataset(temp_file) nc_file_name = res_file.file_name if isinstance(nc_dataset, netCDF4.Dataset): # Extract the metadata from netcdf file res_dublin_core_meta, res_type_specific_meta = nc_meta.get_nc_meta_dict(temp_file) # populate metadata list with extracted metadata metadata = [] add_metadata_to_list(metadata, res_dublin_core_meta, res_type_specific_meta) for element in metadata: # here k is the name of the element # v is a dict of all element attributes/field names and field values k, v = element.items()[0] if k == 'title': # update title element title_element = resource.metadata.title resource.metadata.update_element('title', title_element.id, **v) elif k == 'rights': rights_element = resource.metadata.rights resource.metadata.update_element('rights', rights_element.id, **v) elif k == 'creator': resource.metadata.creators.all().delete() resource.metadata.create_element('creator', **v) else: resource.metadata.create_element(k, **v) # create the ncdump text file dump_file = create_header_info_txt_file(temp_file, nc_file_name) dump_file_name = nc_file_name + '_header_info.txt' uploaded_file = UploadedFile(file=open(dump_file), name=dump_file_name) utils.add_file_to_resource(resource, uploaded_file) else: delete_resource_file_only(resource, res_file) validate_files_dict['are_files_valid'] = False err_msg = "Uploaded file was not added to the resource." \ " Please provide a valid NetCDF file. " validate_files_dict['message'] = err_msg log_msg = "File validation failed for netcdf resource (ID:{})." log_msg = log_msg.format(resource.short_id) log.error(log_msg) # cleanup the temp file directory if os.path.exists(temp_file): shutil.rmtree(os.path.dirname(temp_file)) # set metadata is dirty flag as false for resource creation metadata = resource.metadata metadata.is_dirty = False metadata.save() # since we are extracting metadata after resource creation # metadata xml files need to be regenerated - so need to set the # dirty bag flags if resource.files.all().count() > 0: utils.set_dirty_bag_flag(resource) # receiver used after user clicks on "delete file" for existing netcdf file @receiver(pre_delete_file_from_resource, sender=NetcdfResource) def netcdf_pre_delete_file_from_resource(sender, **kwargs): nc_res = kwargs['resource'] metadata = nc_res.metadata metadata.is_dirty = False metadata.save() del_file = kwargs['file'] del_file_ext = utils.get_resource_file_name_and_extension(del_file)[2] # update resource modification info user = nc_res.creator utils.resource_modified(nc_res, user, overwrite_bag=False) # delete the netcdf header file or .nc file file_ext = {'.nc': 'application/x-netcdf', '.txt': 'text/plain'} if del_file_ext in file_ext: del file_ext[del_file_ext] for f in ResourceFile.objects.filter(object_id=nc_res.id): ext = utils.get_resource_file_name_and_extension(f)[2] if ext in file_ext: delete_resource_file_only(nc_res, f) nc_res.metadata.formats.filter(value=file_ext[ext]).delete() break # delete all the coverage info nc_res.metadata.coverages.all().delete() # delete all the extended meta info nc_res.metadata.variables.all().delete() nc_res.metadata.ori_coverage.all().delete() # receiver used after user clicks on "add file" for existing resource netcdf file @receiver(pre_add_files_to_resource, sender=NetcdfResource) def netcdf_pre_add_files_to_resource(sender, **kwargs): nc_res = kwargs['resource'] files = kwargs['files'] validate_files_dict = kwargs['validate_files'] source_names = kwargs['source_names'] if __debug__: assert(isinstance(source_names, list)) if len(files) > 1: # file number validation validate_files_dict['are_files_valid'] = False validate_files_dict['message'] = 'Only one file can be uploaded.' file_selected = False in_file_name = '' nc_file_name = '' if files: file_selected = True in_file_name = files[0].file.name nc_file_name = os.path.splitext(files[0].name)[0] elif source_names: nc_file_name = os.path.splitext(os.path.basename(source_names[0]))[0] ref_tmpfiles = utils.get_fed_zone_files(source_names) if ref_tmpfiles: in_file_name = ref_tmpfiles[0] file_selected = True if file_selected and in_file_name: # file type validation and existing metadata update and create new ncdump text file nc_dataset = nc_utils.get_nc_dataset(in_file_name) if isinstance(nc_dataset, netCDF4.Dataset): # delete all existing resource files and metadata related for f in ResourceFile.objects.filter(object_id=nc_res.id): delete_resource_file_only(nc_res, f) # update resource modification info user = kwargs['user'] utils.resource_modified(nc_res, user, overwrite_bag=False) # extract metadata res_dublin_core_meta, res_type_specific_meta = nc_meta.get_nc_meta_dict(in_file_name) # update title info if res_dublin_core_meta.get('title'): if nc_res.metadata.title: nc_res.metadata.title.delete() nc_res.metadata.create_element('title', value=res_dublin_core_meta['title']) # update description info if res_dublin_core_meta.get('description'): if nc_res.metadata.description: nc_res.metadata.description.delete() nc_res.metadata.create_element('description', abstract=res_dublin_core_meta.get('description')) # update creator info if res_dublin_core_meta.get('creator_name'): name = res_dublin_core_meta.get('creator_name') email = res_dublin_core_meta.get('creator_email', '') url = res_dublin_core_meta.get('creator_url', '') arguments = dict(name=name, email=email, homepage=url) creator = nc_res.metadata.creators.all().filter(name=name).first() if creator: order = creator.order if order != 1: creator.delete() arguments['order'] = order nc_res.metadata.create_element('creator', **arguments) else: nc_res.metadata.create_element('creator', **arguments) # update contributor info if res_dublin_core_meta.get('contributor_name'): name_list = res_dublin_core_meta['contributor_name'].split(',') existing_contributor_names = [contributor.name for contributor in nc_res.metadata.contributors.all()] for name in name_list: if name not in existing_contributor_names: nc_res.metadata.create_element('contributor', name=name) # update subject info if res_dublin_core_meta.get('subject'): keywords = res_dublin_core_meta['subject'].split(',') existing_keywords = [subject.value for subject in nc_res.metadata.subjects.all()] for keyword in keywords: if keyword not in existing_keywords: nc_res.metadata.create_element('subject', value=keyword) # update source if res_dublin_core_meta.get('source'): for source in nc_res.metadata.sources.all(): source.delete() nc_res.metadata.create_element('source', derived_from=res_dublin_core_meta.get('source')) # update license element: if res_dublin_core_meta.get('rights'): raw_info = res_dublin_core_meta.get('rights') b = re.search("(?P<url>https?://[^\s]+)", raw_info) url = b.group('url') if b else '' statement = raw_info.replace(url, '') if url else raw_info if nc_res.metadata.rights: nc_res.metadata.rights.delete() nc_res.metadata.create_element('rights', statement=statement, url=url) # update relation if res_dublin_core_meta.get('references'): nc_res.metadata.relations.filter(type='cites').all().delete() nc_res.metadata.create_element('relation', type='cites', value=res_dublin_core_meta['references']) # update box info nc_res.metadata.coverages.all().delete() if res_dublin_core_meta.get('box'): nc_res.metadata.create_element('coverage', type='box', value=res_dublin_core_meta['box']) # update period info if res_dublin_core_meta.get('period'): nc_res.metadata.create_element('coverage', type='period', value=res_dublin_core_meta['period']) # update variable info nc_res.metadata.variables.all().delete() for var_info in res_type_specific_meta.values(): nc_res.metadata.create_element('variable', name=var_info['name'], unit=var_info['unit'], type=var_info['type'], shape=var_info['shape'], missing_value=var_info['missing_value'], descriptive_name=var_info['descriptive_name'], method=var_info['method']) # update the original spatial coverage meta nc_res.metadata.ori_coverage.all().delete() if res_dublin_core_meta.get('original-box'): if res_dublin_core_meta.get('projection-info'): nc_res.metadata.create_element( 'originalcoverage', value=res_dublin_core_meta['original-box'], projection_string_type=res_dublin_core_meta['projection-info']['type'], projection_string_text=res_dublin_core_meta['projection-info']['text'], datum=res_dublin_core_meta['projection-info']['datum']) else: nc_res.metadata.create_element('originalcoverage', value=res_dublin_core_meta['original-box']) # create the ncdump text file dump_file = create_header_info_txt_file(in_file_name, nc_file_name) dump_file_name = nc_file_name + '_header_info.txt' uploaded_file = UploadedFile(file=open(dump_file), name=dump_file_name) files.append(uploaded_file) else: validate_files_dict['are_files_valid'] = False validate_files_dict['message'] = 'Please check if the uploaded file is ' \ 'invalid NetCDF format.' if source_names and in_file_name: shutil.rmtree(os.path.dirname(in_file_name)) @receiver(post_add_files_to_resource, sender=NetcdfResource) def netcdf_post_add_files_to_resource(sender, **kwargs): resource = kwargs['resource'] metadata = resource.metadata for f in resource.files.all(): if f.extension == ".txt": if f.resource_file: nc_text = f.resource_file.read() else: nc_text = f.fed_resource_file.read() break if 'title = ' not in nc_text and metadata.title.value != 'Untitled resource': metadata.is_dirty = True elif 'summary = ' not in nc_text and metadata.description: metadata.is_dirty = True elif 'keywords' not in nc_text and metadata.subjects.all(): metadata.is_dirty = True elif 'contributor_name =' not in nc_text and metadata.contributors.all(): metadata.is_dirty = True elif 'creator_name =' not in nc_text and metadata.creators.all(): metadata.is_dirty = True elif 'license =' not in nc_text and metadata.rights: metadata.is_dirty = True elif 'references =' not in nc_text and metadata.relations.all().filter(type='cites'): metadata.is_dirty = True elif 'source =' not in nc_text and metadata.sources.all(): metadata.is_dirty = True else: metadata.is_dirty = False metadata.save() @receiver(pre_metadata_element_create, sender=NetcdfResource) def metadata_element_pre_create_handler(sender, **kwargs): request = kwargs['request'] element_name = kwargs['element_name'] if element_name == "variable": element_form = VariableForm(data=request.POST) elif element_name == 'originalcoverage': element_form = OriginalCoverageForm(data=request.POST) if element_form.is_valid(): return {'is_valid': True, 'element_data_dict': element_form.cleaned_data} else: return {'is_valid': False, 'element_data_dict': None, "errors": element_form.errors} # This handler is executed only when a metadata element is added as part of editing a resource @receiver(pre_metadata_element_update, sender=NetcdfResource) def metadata_element_pre_update_handler(sender, **kwargs): element_name = kwargs['element_name'].lower() request = kwargs['request'] if element_name == 'variable': form_data = {} for field_name in VariableValidationForm().fields: matching_key = [key for key in request.POST if '-'+field_name in key][0] form_data[field_name] = request.POST[matching_key] element_form = VariableValidationForm(form_data) elif element_name == 'originalcoverage': element_form = OriginalCoverageForm(data=request.POST) if element_form.is_valid(): return {'is_valid': True, 'element_data_dict': element_form.cleaned_data} else: return {'is_valid': False, 'element_data_dict': None, "errors": element_form.errors}
ResearchSoftwareInstitute/MyHPOM
hs_app_netCDF/receivers.py
Python
bsd-3-clause
16,184
[ "NetCDF" ]
8992ed66ccb7301b95201d14b7a265e8adb6c62a25c8cb4376a7a854e9b0fcb0
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import numpy as np import pickle from pymatgen.util.testing import PymatgenTest from pymatgen.core.periodic_table import Element, Specie from pymatgen.core.sites import Site, PeriodicSite from pymatgen.core.lattice import Lattice from pymatgen.core.composition import Composition """ Created on Jul 17, 2012 """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Jul 17, 2012" class SiteTest(PymatgenTest): def setUp(self): self.ordered_site = Site("Fe", [0.25, 0.35, 0.45]) self.disordered_site = Site({"Fe": 0.5, "Mn": 0.5}, [0.25, 0.35, 0.45]) self.propertied_site = Site("Fe2+", [0.25, 0.35, 0.45], {'magmom': 5.1, 'charge': 4.2}) self.dummy_site = Site("X", [0, 0, 0]) def test_properties(self): self.assertRaises(AttributeError, getattr, self.disordered_site, 'specie') self.assertIsInstance(self.ordered_site.specie, Element) self.assertEqual(self.propertied_site.properties["magmom"], 5.1) self.assertEqual(self.propertied_site.properties["charge"], 4.2) def test_to_from_dict(self): d = self.disordered_site.as_dict() site = Site.from_dict(d) self.assertEqual(site, self.disordered_site) self.assertNotEqual(site, self.ordered_site) d = self.propertied_site.as_dict() site = Site.from_dict(d) self.assertEqual(site.properties["magmom"], 5.1) self.assertEqual(site.properties["charge"], 4.2) d = self.dummy_site.as_dict() site = Site.from_dict(d) self.assertEqual(site.species, self.dummy_site.species) def test_hash(self): self.assertEqual(self.ordered_site.__hash__(), 26) self.assertEqual(self.disordered_site.__hash__(), 51) def test_cmp(self): self.assertTrue(self.ordered_site > self.disordered_site) def test_distance(self): osite = self.ordered_site self.assertAlmostEqual(np.linalg.norm([0.25, 0.35, 0.45]), osite.distance_from_point([0, 0, 0])) self.assertAlmostEqual(osite.distance(self.disordered_site), 0) def test_pickle(self): o = pickle.dumps(self.propertied_site) self.assertEqual(pickle.loads(o), self.propertied_site) def test_setters(self): self.disordered_site.species = "Cu" self.assertEqual(self.disordered_site.species, Composition("Cu")) self.disordered_site.x = 1.25 self.disordered_site.y = 1.35 self.assertEqual(self.disordered_site.coords[0], 1.25) self.assertEqual(self.disordered_site.coords[1], 1.35) def set_bad_species(): self.disordered_site.species = {"Cu": 0.5, "Gd": 0.6} self.assertRaises(ValueError, set_bad_species) class PeriodicSiteTest(PymatgenTest): def setUp(self): self.lattice = Lattice.cubic(10.0) self.si = Element("Si") self.site = PeriodicSite("Fe", [0.25, 0.35, 0.45], self.lattice) self.site2 = PeriodicSite({"Si": 0.5}, [0, 0, 0], self.lattice) self.assertEqual(self.site2.species, Composition({Element('Si'): 0.5}), "Inconsistent site created!") self.propertied_site = PeriodicSite(Specie("Fe", 2), [0.25, 0.35, 0.45], self.lattice, properties={'magmom': 5.1, 'charge': 4.2}) self.dummy_site = PeriodicSite("X", [0, 0, 0], self.lattice) def test_properties(self): """ Test the properties for a site """ self.assertEqual(self.site.a, 0.25) self.assertEqual(self.site.b, 0.35) self.assertEqual(self.site.c, 0.45) self.assertEqual(self.site.x, 2.5) self.assertEqual(self.site.y, 3.5) self.assertEqual(self.site.z, 4.5) self.assertTrue(self.site.is_ordered) self.assertFalse(self.site2.is_ordered) self.assertEqual(self.propertied_site.properties["magmom"], 5.1) self.assertEqual(self.propertied_site.properties["charge"], 4.2) def test_distance(self): other_site = PeriodicSite("Fe", np.array([0, 0, 0]), self.lattice) self.assertAlmostEqual(self.site.distance(other_site), 6.22494979899, 5) def test_distance_from_point(self): self.assertNotAlmostEqual(self.site.distance_from_point([0.1, 0.1, 0.1]), 6.22494979899, 5) self.assertAlmostEqual(self.site.distance_from_point([0.1, 0.1, 0.1]), 6.0564015718906887, 5) def test_distance_and_image(self): other_site = PeriodicSite("Fe", np.array([1, 1, 1]), self.lattice) (distance, image) = self.site.distance_and_image(other_site) self.assertAlmostEqual(distance, 6.22494979899, 5) self.assertTrue(([-1, -1, -1] == image).all()) (distance, image) = self.site.distance_and_image(other_site, [1, 0, 0]) self.assertAlmostEqual(distance, 19.461500456028563, 5) # Test that old and new distance algo give the same ans for # "standard lattices" lattice = Lattice(np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])) site1 = PeriodicSite("Fe", np.array([0.01, 0.02, 0.03]), lattice) site2 = PeriodicSite("Fe", np.array([0.99, 0.98, 0.97]), lattice) self.assertAlmostEqual(get_distance_and_image_old(site1, site2)[0], site1.distance_and_image(site2)[0]) lattice = Lattice.from_parameters(1, 0.01, 1, 10, 10, 10) site1 = PeriodicSite("Fe", np.array([0.01, 0.02, 0.03]), lattice) site2 = PeriodicSite("Fe", np.array([0.99, 0.98, 0.97]), lattice) self.assertTrue(get_distance_and_image_old(site1, site2)[0] > site1.distance_and_image(site2)[0]) site2 = PeriodicSite("Fe", np.random.rand(3), lattice) (dist_old, jimage_old) = get_distance_and_image_old(site1, site2) (dist_new, jimage_new) = site1.distance_and_image(site2) self.assertTrue(dist_old - dist_new > -1e-8, "New distance algo should give smaller answers!") self.assertFalse((abs(dist_old - dist_new) < 1e-8) ^ (jimage_old == jimage_new).all(), "If old dist == new dist, images must be the same!") latt = Lattice.from_parameters(3.0, 3.1, 10.0, 2.96, 2.0, 1.0) site = PeriodicSite("Fe", [0.1, 0.1, 0.1], latt) site2 = PeriodicSite("Fe", [0.99, 0.99, 0.99], latt) (dist, img) = site.distance_and_image(site2) self.assertAlmostEqual(dist, 0.15495358379511573) self.assertEqual(list(img), [-11, 6, 0]) def test_is_periodic_image(self): other = PeriodicSite("Fe", np.array([1.25, 2.35, 4.45]), self.lattice) self.assertTrue(self.site.is_periodic_image(other), "This other site should be a periodic image.") other = PeriodicSite("Fe", np.array([1.25, 2.35, 4.46]), self.lattice) self.assertFalse(self.site.is_periodic_image(other), "This other site should not be a periodic image.") other = PeriodicSite("Fe", np.array([1.25, 2.35, 4.45]), Lattice.rhombohedral(2, 60)) self.assertFalse(self.site.is_periodic_image(other), "Different lattices should not be periodic images.") def test_equality(self): other_site = PeriodicSite("Fe", np.array([1, 1, 1]), self.lattice) self.assertTrue(self.site.__eq__(self.site)) self.assertFalse(other_site.__eq__(self.site)) self.assertFalse(self.site.__ne__(self.site)) self.assertTrue(other_site.__ne__(self.site)) def test_as_from_dict(self): d = self.site2.as_dict() site = PeriodicSite.from_dict(d) self.assertEqual(site, self.site2) self.assertNotEqual(site, self.site) d = self.propertied_site.as_dict() site3 = PeriodicSite({"Si": 0.5, "Fe": 0.5}, [0, 0, 0], self.lattice) d = site3.as_dict() site = PeriodicSite.from_dict(d) self.assertEqual(site.species, site3.species) d = self.dummy_site.as_dict() site = PeriodicSite.from_dict(d) self.assertEqual(site.species, self.dummy_site.species) def test_to_unit_cell(self): site = PeriodicSite("Fe", np.array([1.25, 2.35, 4.46]), self.lattice) site.to_unit_cell(in_place=True) val = [0.25, 0.35, 0.46] self.assertArrayAlmostEqual(site.frac_coords, val) def test_setters(self): site = self.propertied_site site.species = "Cu" self.assertEqual(site.species, Composition("Cu")) site.x = 1.25 site.y = 1.35 self.assertEqual(site.coords[0], 1.25) self.assertEqual(site.coords[1], 1.35) self.assertEqual(site.a, 0.125) self.assertEqual(site.b, 0.135) site.lattice = Lattice.cubic(100) self.assertEqual(site.x, 12.5) def set_bad_species(): site.species = {"Cu": 0.5, "Gd": 0.6} self.assertRaises(ValueError, set_bad_species) site.frac_coords = [0, 0, 0.1] self.assertArrayAlmostEqual(site.coords, [0, 0, 10]) site.coords = [1.5, 3.25, 5] self.assertArrayAlmostEqual(site.frac_coords, [0.015, 0.0325, 0.05]) def test_repr(self): self.assertEqual(self.propertied_site.__repr__(), "PeriodicSite: Fe2+ (2.5000, 3.5000, 4.5000) [0.2500, 0.3500, 0.4500]") def get_distance_and_image_old(site1, site2, jimage=None): """ Gets distance between two sites assuming periodic boundary conditions. If the index jimage of two sites atom j is not specified it selects the j image nearest to the i atom and returns the distance and jimage indices in terms of lattice vector translations. If the index jimage of atom j is specified it returns the distance between the i atom and the specified jimage atom, the given jimage is also returned. Args: other: other site to get distance from. jimage: specific periodic image in terms of lattice translations, e.g., [1,0,0] implies to take periodic image that is one a-lattice vector away. If jimage is None, the image that is nearest to the site is found. Returns: (distance, jimage): distance and periodic lattice translations of the other site for which the distance applies. .. note:: Assumes the primitive cell vectors are sufficiently not skewed such that the condition \\|a\\|cos(ab_angle) < \\|b\\| for all possible cell vector pairs. ** this method does not check this condition ** """ if jimage is None: # Old algorithm jimage = -np.array(np.around(site2.frac_coords - site1.frac_coords), int) mapped_vec = site1.lattice.get_cartesian_coords(jimage + site2.frac_coords - site1.frac_coords) dist = np.linalg.norm(mapped_vec) return dist, jimage if __name__ == "__main__": import unittest unittest.main()
tschaume/pymatgen
pymatgen/core/tests/test_sites.py
Python
mit
11,857
[ "pymatgen" ]
65733ce8fa627d7edae90710d84d40f495689dcb661fd24fb290df5b7d227b3f
#!/usr/bin/env python ######################################################################## # File : dirac-admin-get-pilot-info # Author : Ricardo Graciani ######################################################################## """ Retrieve available info about the given pilot Example: $ dirac-admin-get-pilot-info https://marlb.in2p3.fr:9000/26KCLKBFtxXKHF4_ZrQjkw {'https://marlb.in2p3.fr:9000/26KCLKBFtxXKHF4_ZrQjkw': {'AccountingSent': 'False', 'BenchMark': 0.0, 'Broker': 'marwms.in2p3.fr', 'DestinationSite': 'cclcgceli01.in2p3.fr', 'GridSite': 'LCG.IN2P3.fr', 'GridType': 'gLite', 'LastUpdateTime': datetime.datetime(2011, 2, 21, 12, 49, 14), 'OutputReady': 'False', 'OwnerDN': '/O=GRID/C=FR/O=CNRS/OU=LPC/CN=Sebastien Guizard', 'OwnerGroup': '/biomed', 'ParentID': 0L, 'PilotID': 2241L, 'PilotJobReference': 'https://marlb.in2p3.fr:9000/2KHFrQjkw', 'PilotStamp': '', 'Status': 'Done', 'SubmissionTime': datetime.datetime(2011, 2, 21, 12, 27, 52), 'TaskQueueID': 399L}} """ # pylint: disable=wrong-import-position from DIRAC.Core.Utilities.DIRACScript import DIRACScript as Script extendedPrint = False def setExtendedPrint(_arg): global extendedPrint extendedPrint = True @Script() def main(): Script.registerSwitch("e", "extended", "Get extended printout", setExtendedPrint) _, args = Script.parseCommandLine(ignoreErrors=True) from DIRAC import exit as DIRACExit from DIRAC.Interfaces.API.Dirac import Dirac from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin diracAdmin = DiracAdmin() dirac = Dirac() exitCode = 0 errorList = [] for gridID in args: result = diracAdmin.getPilotInfo(gridID) if not result["OK"]: errorList.append((gridID, result["Message"])) exitCode = 2 else: res = result["Value"][gridID] if extendedPrint: tab = "" for key in [ "PilotJobReference", "Status", "OwnerDN", "OwnerGroup", "SubmissionTime", "DestinationSite", "GridSite", ]: if key in res: diracAdmin.log.notice("%s%s: %s" % (tab, key, res[key])) if not tab: tab = " " diracAdmin.log.notice("") for jobID in res["Jobs"]: tab = " " result = dirac.getJobAttributes(int(jobID)) if not result["OK"]: errorList.append((gridID, result["Message"])) exitCode = 2 else: job = result["Value"] diracAdmin.log.notice("%sJob ID: %s" % (tab, jobID)) tab += " " for key in [ "OwnerDN", "OwnerGroup", "JobName", "Status", "StartExecTime", "LastUpdateTime", "EndExecTime", ]: if key in job: diracAdmin.log.notice("%s%s:" % (tab, key), job[key]) diracAdmin.log.notice("") else: print(diracAdmin.pPrint.pformat({gridID: res})) for error in errorList: print("ERROR %s: %s" % error) DIRACExit(exitCode) if __name__ == "__main__": main()
ic-hep/DIRAC
src/DIRAC/Interfaces/scripts/dirac_admin_get_pilot_info.py
Python
gpl-3.0
4,570
[ "DIRAC" ]
96f9e5ee02fdd27849613321541d5ca4cdfeec5de22eef681d788e38b6826118
# -*- coding: utf-8 -*- # Copyright (c) 2015-2022, Exa Analytics Development Team # Distributed under the terms of the Apache License 2.0 """ Atomic Position Data ############################ This module provides a collection of dataframes supporting nuclear positions, forces, velocities, symbols, etc. (all data associated with atoms as points). """ from numbers import Integral import numpy as np import pandas as pd from exatomic.exa import DataFrame, Series from exatomic.exa.util.units import Length from exatomic.base import sym2z, sym2mass from exatomic.algorithms.distance import modv from exatomic.core.error import PeriodicUniverseError from exatomic.algorithms.geometry import make_small_molecule from exatomic import plotter class Atom(DataFrame): """ The atom dataframe. +-------------------+----------+-------------------------------------------+ | Column | Type | Description | +===================+==========+===========================================+ | x | float | position in x (req.) | +-------------------+----------+-------------------------------------------+ | y | float | position in y (req.) | +-------------------+----------+-------------------------------------------+ | z | float | position in z (req.) | +-------------------+----------+-------------------------------------------+ | frame | category | non-unique integer (req.) | +-------------------+----------+-------------------------------------------+ | symbol | category | element symbol (req.) | +-------------------+----------+-------------------------------------------+ | fx | float | force in x | +-------------------+----------+-------------------------------------------+ | fy | float | force in y | +-------------------+----------+-------------------------------------------+ | fz | float | force in z | +-------------------+----------+-------------------------------------------+ | vx | float | velocity in x | +-------------------+----------+-------------------------------------------+ | vy | float | velocity in y | +-------------------+----------+-------------------------------------------+ | vz | float | velocity in z | +-------------------+----------+-------------------------------------------+ """ _index = 'atom' _cardinal = ('frame', np.int64) _categories = {'symbol': str, 'set': np.int64, 'molecule': np.int64, 'label': np.int64} _columns = ['x', 'y', 'z', 'symbol'] #@property #def _constructor(self): # return Atom @property def nframes(self): """Return the total number of frames in the atom table.""" return np.int64(self.frame.cat.as_ordered().max() + 1) @property def last_frame(self): """Return the last frame of the atom table.""" return self[self.frame == self.nframes - 1] @property def unique_atoms(self): """Return unique atom symbols of the last frame.""" return self.last_frame.symbol.unique() @staticmethod def _determine_center(attr, coords): """Determine the center of the molecule with respect to the given attribute data. Used for the center of nuclear charge and center of mass.""" center = 1/np.sum(attr)*np.sum(np.multiply(np.transpose(coords), attr), axis=1) center = pd.Series(center, index=['x', 'y', 'z']) return center def center(self, idx=None, frame=None, to=None): """ Return a copy of a single frame of the atom table centered around a specific atom index. There is also the ability to center the molecule to the center of nuclear charge (NuclChrg) or center of mass (Mass). Args: idx (int): Atom index in the atom table frame (int): Frame to perform the operation on to (str): Tells the program which centering algorithm to use Returs: frame (:class:`exatomic.Universe.atom`): Atom frame """ if frame is None: frame = self.last_frame.copy() else: frame = self[self.frame == frame].copy() if to is None: if idx is None: raise TypeError("Must provide an atom to center to") center = frame.iloc[idx] elif to == 'NuclChrg': try: Z = frame['Z'].astype(int).values except KeyError: Z = frame['symbol'].map(sym2z).astype(int).values center = self._determine_center(attr=Z, coords=frame[['x', 'y', 'z']].values) elif to == 'Mass': mass = frame['symbol'].map(sym2mass).astype(int).values center = self._determine_center(attr=mass, coords=frame[['x', 'y', 'z']].values) else: raise NotImplementedError("Sorry the centering option {} is not available".format(to)) for r in ['x', 'y', 'z']: if center[r] > 0: frame[r] = frame[r] - center[r] else: frame[r] = frame[r] + np.abs(center[r]) return Atom(frame) def rotate(self, theta, axis=None, frame=None, degrees=True): """ Return a copy of a single frame of the atom table rotated around the specified rotation axis by the specified angle. As we have the rotation axis and the rotation angle we are able to use the Rodrigues' formula to get the rotated vectors. Args: theta (float): The angle that you wish to rotate by axis (list): The axis of rotation frame (int): The frame that you wish to rotate degrees (bool): If true convert from degrees to radians Returns: frame (:class:`exatomic.Universe.atom`): Atom frame """ if axis is None: axis = [0, 0, 1] if frame is None: frame = self.last_frame.copy() else: frame = self[self.frame == frame].copy() if all(map(lambda x: x == 0., axis)) or theta == 0.: return frame # as we have the rotation axis and the angle we will rotate over # we implement the Rodrigues' rotation formula # v_rot = v*np.cos(theta) + (np.cross(k,v))*np.sin(theta) + k*(np.dot(k,v))*(1-np.cos(theta)) # convert units if not degrees if degrees: theta = theta*np.pi/180. # normalize rotation axis vector norm = np.linalg.norm(axis) try: axis /= norm except ZeroDivisionError: raise ZeroDivisionError("Trying to normalize axis {} by a 0 value".format(axis)) # get the coordinates coords = frame[['x', 'y', 'z']].values # generate the first term in rodrigues formula a = coords * np.cos(theta) # generate second term in rodrigures formula # this creates a matrix of size coords.shape[0] b = np.cross(axis, coords) * np.sin(theta) # generate the last term in rodrigues formula # we use np.outer to make a dyadic productof the result from the dot product vector # and the axis vector c = np.outer(np.dot(coords, axis), axis) * (1-np.cos(theta)) rotated = a + b + c frame[['x', 'y', 'z']] = rotated return Atom(frame) def translate(self, dx=0, dy=0, dz=0, vector=None, frame=None, units='au'): """ Return a copy of a single frame of the atom table translated by some specified distance. Note: Vector can be used instead of dx, dy, dz as it will be decomposed into those components. If vector and any of the others are specified the values in vector will be used. Args: dx (float): Displacement distance in x dy (float): Displacement distance in y dz (float): Displacement distance in z vector (list): Displacement vector units (str): Units that are used for the displacement Returns: frame (:class:`exatomic.Universe.atom`): Atom frame """ if frame is None: frame = self.last_frame.copy() else: frame = self[self.frame == frame].copy() # check if vector is specified if vector is not None: # convert vector units to au vector = [i * Length[units, 'au'] for i in vector] dx = vector[0] dy = vector[1] dz = vector[2] # add the values to each respective coordinate frame['x'] += dx frame['y'] += dy frame['z'] += dz return Atom(frame) def align_to_axis(self, adx0, adx1, axis=None, frame=None, center_to=None): ''' This a short method to center and align the molecule along some defined axis. Args: adx0 (int): Atom to place at the origin adx1 (int): Atom to align along the axis axis (list): Axis that the vector adx0-adx1 will align to frame (int): Frame to align Returns: aligned (:class:`exatomic.Universe.atom`): Aligned atom frame ''' if frame is None: atom = self.last_frame.copy() else: atom = self[self.frame == frame].copy() cols = ['x', 'y', 'z'] # define the original vector v0 = atom.iloc[adx1][cols].values.astype(np.float64) - atom.iloc[adx0][cols].values.astype(np.float64) # get the vector to align with and normalize v1 = axis/np.linalg.norm(axis) # find the normal vector to rotate around n = np.cross(v0, v1) # find the angle to rotate the vector theta = np.arccos(np.dot(v0, v1) / (np.linalg.norm(v0)*np.linalg.norm(v1))) # use the center method to center the molecule centered = Atom(atom).center(adx0, frame=frame, to=center_to) # rotate the molecule around the normal vector aligned = centered.rotate(theta=theta, axis=n, degrees=False) return Atom(aligned) def to_xyz(self, tag='symbol', header=False, comments='', columns=None, frame=None, units='Angstrom'): """ Return atomic data in XYZ format, by default without the first 2 lines. If multiple frames are specified, return an XYZ trajectory format. If frame is not specified, by default returns the last frame in the table. Args: tag (str): column name to use in place of 'symbol' header (bool): if True, return the first 2 lines of XYZ format comment (str, list): comment(s) to put in the comment line frame (int, iter): frame or frames to return units (str): units (default angstroms) Returns: ret (str): XYZ formatted atomic data """ # TODO :: this is conceptually a duplicate of XYZ.from_universe columns = (tag, 'x', 'y', 'z') if columns is None else columns frame = self.nframes - 1 if frame is None else frame if isinstance(frame, Integral): frame = [frame] if not isinstance(comments, list): comments = [comments] if len(comments) == 1: comments = comments * len(frame) df = self[self['frame'].isin(frame)].copy() if tag not in df.columns: if tag == 'Z': stoz = sym2z() df[tag] = df['symbol'].map(stoz) df['x'] *= Length['au', units] df['y'] *= Length['au', units] df['z'] *= Length['au', units] grps = df.groupby('frame') ret = '' formatter = {tag: '{:<5}'.format} stargs = {'columns': columns, 'header': False, 'index': False, 'formatters': formatter} t = 0 for _, grp in grps: if not len(grp): continue tru = (header or comments[t] or len(frame) > 1) hdr = '\n'.join([str(len(grp)), comments[t], '']) if tru else '' ret = ''.join([ret, hdr, grp.to_string(**stargs), '\n']) t += 1 return ret def get_element_masses(self): """Compute and return element masses from symbols.""" return self['symbol'].astype('O').map(sym2mass) def get_atom_labels(self): """ Compute and return enumerated atoms. Returns: labels (:class:`~exatomic.exa.core.numerical.Series`): Enumerated atom labels (of type int) """ nats = self.cardinal_groupby().size().values labels = Series([i for nat in nats for i in range(nat)], dtype='category') labels.index = self.index return labels @classmethod def from_small_molecule_data(cls, center=None, ligand=None, distance=None, geometry=None, offset=None, plane=None, axis=None, domains=None, unit='Angstrom'): ''' A minimal molecule builder for simple one-center, homogeneous ligand molecules of various general chemistry molecular geometries. If domains is not specified and geometry is ambiguous (like 'bent'), it just guesses the simplest geometry (smallest number of domains). Args center (str): atomic symbol of central atom ligand (str): atomic symbol of ligand atoms distance (float): distance between central atom and any ligand geometry (str): molecular geometry domains (int): number of electronic domains offset (np.array): 3-array of position of central atom plane (str): cartesian plane of molecule (eg. for 'square_planar') axis (str): cartesian axis of molecule (eg. for 'linear') Returns exatomic.atom.Atom: Atom table of small molecule ''' return cls(make_small_molecule(center=center, ligand=ligand, distance=distance, geometry=geometry, offset=offset, plane=plane, axis=axis, domains=domains, unit=unit)) class UnitAtom(DataFrame): """ In unit cell coordinates (sparse) for periodic systems. These coordinates are used to update the corresponding :class:`~exatomic.atom.Atom` object """ _index = 'atom' _columns = ['x', 'y', 'z'] #@property #def _constructor(self): # return UnitAtom @classmethod def from_universe(cls, universe): if universe.periodic: if "rx" not in universe.frame.columns: universe.frame.compute_cell_magnitudes() a, b, c = universe.frame[["rx", "ry", "rz"]].max().values x = modv(universe.atom['x'].values, a) y = modv(universe.atom['y'].values, b) z = modv(universe.atom['z'].values, c) df = pd.DataFrame.from_dict({'x': x, 'y': y, 'z': z}) df.index = universe.atom.index return cls(df[universe.atom[['x', 'y', 'z']] != df]) raise PeriodicUniverseError() class ProjectedAtom(DataFrame): """ Projected atom coordinates (e.g. on 3x3x3 supercell). These coordinates are typically associated with their corresponding indices in another dataframe. Note: This table is computed when periodic two body properties are computed; it doesn't have meaning outside of that context. See Also: :func:`~exatomic.two.compute_periodic_two`. """ _index = 'two' _columns = ['x', 'y', 'z'] #@property #def _constructor(self): # return ProjectedAtom class VisualAtom(DataFrame): """ """ _index = 'atom' _columns = ['x', 'y', 'z'] @classmethod def from_universe(cls, universe): """ """ if universe.frame.is_periodic(): atom = universe.atom[['x', 'y', 'z']].copy() atom.update(universe.unit_atom) bonded = universe.atom_two.loc[universe.atom_two['bond'] == True, 'atom1'].astype(np.int64) prjd = universe.projected_atom.loc[bonded.index].to_dense() prjd['atom'] = bonded prjd.drop_duplicates('atom', inplace=True) prjd.set_index('atom', inplace=True) atom.update(prjd) return cls(atom[atom != universe.atom[['x', 'y', 'z']]]) raise PeriodicUniverseError() #@property #def _constructor(self): # return VisualAtom class Frequency(DataFrame): """ The Frequency dataframe. +-------------------+----------+-------------------------------------------+ | Column | Type | Description | +===================+==========+===========================================+ | frame | category | non-unique integer (req.) | +-------------------+----------+-------------------------------------------+ | frequency | float | frequency of oscillation (cm-1) (req.) | +-------------------+----------+-------------------------------------------+ | freqdx | int | index of frequency of oscillation (req.) | +-------------------+----------+-------------------------------------------+ | dx | float | atomic displacement in x direction (req.) | +-------------------+----------+-------------------------------------------+ | dy | float | atomic displacement in y direction (req.) | +-------------------+----------+-------------------------------------------+ | dz | float | atomic displacement in z direction (req.) | +-------------------+----------+-------------------------------------------+ | ir_int | float | ir intensity of the vibrational mode | +-------------------+----------+-------------------------------------------+ | symbol | str | atomic symbol (req.) | +-------------------+----------+-------------------------------------------+ | label | int | atomic identifier | +-------------------+----------+-------------------------------------------+ """ _index = 'frequency' _cardinal = ('frame', np.int64) _categories = {'symbol': str, 'label': np.int64} _columns = ['dx', 'dy', 'dz', 'symbol', 'frequency', 'freqdx', 'ir_int'] #@property #def _constructor(self): # return Frequency def displacement(self, freqdx): return self[self['freqdx'] == freqdx][['dx', 'dy', 'dz', 'symbol']] def ir_spectra(self, fwhm=15, lineshape='gaussian', xrange=None, res=None, invert_x=False, **kwargs): ''' Generate an IR spectra with the plotter classes. We can define a gaussian or lorentzian lineshape functions. For the most part we pass all of the kwargs directly into the plotter.Plot class. Args: fwhm (float): Full-width at half-maximum lineshape (str): Switch between the different lineshape functions available xrange (list): X-bounds for the plot res (float): Resolution for the plot line invert_x (bool): Invert x-axis ''' # define the lineshape and store the function call in the line variable try: line = getattr(plotter, lineshape) except AttributeError: raise NotImplementedError("Sorry we have not yet implemented the lineshape {}.".format(lineshape)) # define a default parameter for the plot width # we did this for a full-screen jupyter notebook on a 1920x1080 monitor if not "plot_width" in kwargs: kwargs.update(plot_width=900) # define xbounds xrange = [0, 4000] if xrange is None else xrange # deal with inverted bounds if xrange[0] > xrange[1]: xrange = sorted(xrange) invert_x = True # define the resolution res = fwhm/50 if res is None else res # define the class plot = plotter.Plot(**kwargs) # this is designed for a single frame if self['frame'].unique().shape[0] != 1: raise NotImplementedError("We have not yet expanded to include multiple frames") # grab the locations of the peaks between the bounds freqdx = self['freqdx'].drop_duplicates().index freq = self.loc[freqdx, 'frequency'] freq = freq[freq.between(*xrange)] # grab the ir intensity data # we use the frequency indexes instead of drop duplicates as we may have similar intensities inten = self.loc[freq.index, 'ir_int'].astype(np.float64).values # change to using the values instead as we no longer need the index data # we could also use jit for the lineshape functions as we only deal with numpy arrays freq = freq.values x_data = np.arange(*xrange, res) # get the y data by calling the lineshape function generator y_data = line(freq=freq, x=x_data, fwhm=fwhm, inten=inten) # plot the lineshape data plot.fig.line(x_data, y_data) # plot the points on the plot to show were the frequency values are # more useful when we have nearly degenerate vibrations plot.fig.scatter(freq, line(freq=freq, x=freq, fwhm=fwhm, inten=inten)) if invert_x: plot.set_xrange(xmin=xrange[1], xmax=xrange[0]) else: plot.set_xrange(xmin=xrange[0], xmax=xrange[1]) # display the figure with our generated method plot.show() def add_vibrational_mode(uni, freqdx): displacements = uni.frequency.displacements(freqdx) if not all(displacements['symbol'] == uni.atom['symbol']): print('Mismatch in ordering of atoms and frequencies.') return displaced = [] frames = [] # Should these only be absolute values? factor = np.abs(np.sin(np.linspace(-4*np.pi, 4*np.pi, 200))) for fac in factor: moved = uni.atom.copy() moved['x'] += displacements['dx'].values * fac moved['y'] += displacements['dy'].values * fac moved['z'] += displacements['dz'].values * fac displaced.append(moved) frames.append(uni.frame) movie = pd.concat(displaced).reset_index() movie['frame'] = np.repeat(range(len(factor)), len(uni.atom)) uni.frame = pd.concat(frames).reset_index() uni.atom = movie
exa-analytics/exatomic
exatomic/core/atom.py
Python
apache-2.0
22,762
[ "Gaussian" ]
f6bf094800fab6dfb99e3621474581b009edfc8da588a154b729d91083e5df1b
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import division, print_function, absolute_import import math import numpy from . import _ni_support from . import _nd_image from scipy.misc import doccer from scipy._lib._version import NumpyVersion __all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace', 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude', 'gaussian_gradient_magnitude', 'correlate', 'convolve', 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', 'maximum_filter1d', 'minimum_filter', 'maximum_filter', 'rank_filter', 'median_filter', 'percentile_filter', 'generic_filter1d', 'generic_filter'] _input_doc = \ """input : array_like Input array to filter.""" _axis_doc = \ """axis : int, optional The axis of `input` along which to calculate. Default is -1.""" _output_doc = \ """output : array, optional The `output` parameter passes an array in which to store the filter output.""" _size_foot_doc = \ """size : scalar or tuple, optional See footprint, below footprint : array, optional Either `size` or `footprint` must be defined. `size` gives the shape that is taken from the input array, at every element position, to define the input to the filter function. `footprint` is a boolean array that specifies (implicitly) a shape, but also which of the elements within this shape will get passed to the filter function. Thus ``size=(n,m)`` is equivalent to ``footprint=np.ones((n,m))``. We adjust `size` to the number of dimensions of the input array, so that, if the input array is shape (10,10,10), and `size` is 2, then the actual size used is (2,2,2). """ _mode_doc = \ """mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional The `mode` parameter determines how the array borders are handled, where `cval` is the value when mode is equal to 'constant'. Default is 'reflect'""" _cval_doc = \ """cval : scalar, optional Value to fill past edges of input if `mode` is 'constant'. Default is 0.0""" _origin_doc = \ """origin : scalar, optional The `origin` parameter controls the placement of the filter. Default 0.0.""" _extra_arguments_doc = \ """extra_arguments : sequence, optional Sequence of extra positional arguments to pass to passed function""" _extra_keywords_doc = \ """extra_keywords : dict, optional dict of extra keyword arguments to pass to passed function""" docdict = { 'input': _input_doc, 'axis': _axis_doc, 'output': _output_doc, 'size_foot': _size_foot_doc, 'mode': _mode_doc, 'cval': _cval_doc, 'origin': _origin_doc, 'extra_arguments': _extra_arguments_doc, 'extra_keywords': _extra_keywords_doc, } docfiller = doccer.filldoc(docdict) @docfiller def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional correlation along the given axis. The lines of the array along the given axis are correlated with the given weights. Parameters ---------- %(input)s weights : array One-dimensional sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) weights = numpy.asarray(weights, dtype=numpy.float64) if weights.ndim != 1 or weights.shape[0] < 1: raise RuntimeError('no filter weights given') if not weights.flags.contiguous: weights = weights.copy() axis = _ni_support._check_axis(axis, input.ndim) if (len(weights) // 2 + origin < 0) or (len(weights) // 2 + origin > len(weights)): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate1d(input, weights, axis, output, mode, cval, origin) return return_value @docfiller def convolve1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional convolution along the given axis. The lines of the array along the given axis are convolved with the given weights. Parameters ---------- %(input)s weights : ndarray One-dimensional sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- convolve1d : ndarray Convolved array with same shape as input """ weights = weights[::-1] origin = -origin if not len(weights) & 1: origin -= 1 return correlate1d(input, weights, axis, output, mode, cval, origin) @docfiller def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """One-dimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar standard deviation for Gaussian kernel %(axis)s order : {0, 1, 2, 3}, optional An order of 0 corresponds to convolution with a Gaussian kernel. An order of 1, 2, or 3 corresponds to convolution with the first, second or third derivatives of a Gaussian. Higher order derivatives are not implemented %(output)s %(mode)s %(cval)s truncate : float, optional Truncate the filter at this many standard deviations. Default is 4.0. Returns ------- gaussian_filter1d : ndarray """ if order not in range(4): raise ValueError('Order outside 0..3 not implemented') sd = float(sigma) # make the radius of the filter equal to truncate standard deviations lw = int(truncate * sd + 0.5) weights = [0.0] * (2 * lw + 1) weights[lw] = 1.0 sum = 1.0 sd = sd * sd # calculate the kernel: for ii in range(1, lw + 1): tmp = math.exp(-0.5 * float(ii * ii) / sd) weights[lw + ii] = tmp weights[lw - ii] = tmp sum += 2.0 * tmp for ii in range(2 * lw + 1): weights[ii] /= sum # implement first, second and third order derivatives: if order == 1: # first derivative weights[lw] = 0.0 for ii in range(1, lw + 1): x = float(ii) tmp = -x / sd * weights[lw + ii] weights[lw + ii] = -tmp weights[lw - ii] = tmp elif order == 2: # second derivative weights[lw] *= -1.0 / sd for ii in range(1, lw + 1): x = float(ii) tmp = (x * x / sd - 1.0) * weights[lw + ii] / sd weights[lw + ii] = tmp weights[lw - ii] = tmp elif order == 3: # third derivative weights[lw] = 0.0 sd2 = sd * sd for ii in range(1, lw + 1): x = float(ii) tmp = (3.0 - x * x / sd) * x * weights[lw + ii] / sd2 weights[lw + ii] = -tmp weights[lw - ii] = tmp return correlate1d(input, weights, axis, output, mode, cval, 0) @docfiller def gaussian_filter(input, sigma, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """Multidimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar or sequence of scalars Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. order : {0, 1, 2, 3} or sequence from same set, optional The order of the filter along each axis is given as a sequence of integers, or as a single number. An order of 0 corresponds to convolution with a Gaussian kernel. An order of 1, 2, or 3 corresponds to convolution with the first, second or third derivatives of a Gaussian. Higher order derivatives are not implemented %(output)s %(mode)s %(cval)s truncate : float Truncate the filter at this many standard deviations. Default is 4.0. Returns ------- gaussian_filter : ndarray Returned array of same shape as `input`. Notes ----- The multidimensional filter is implemented as a sequence of one-dimensional convolution filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) orders = _ni_support._normalize_sequence(order, input.ndim) if not set(orders).issubset(set(range(4))): raise ValueError('Order outside 0..4 not implemented') sigmas = _ni_support._normalize_sequence(sigma, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sigmas[ii], orders[ii]) for ii in range(len(axes)) if sigmas[ii] > 1e-15] if len(axes) > 0: for axis, sigma, order in axes: gaussian_filter1d(input, sigma, axis, order, output, mode, cval, truncate) input = output else: output[...] = input[...] return return_value @docfiller def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Prewitt filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode)s %(cval)s """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) output, return_value = _ni_support._get_output(output, input) correlate1d(input, [-1, 0, 1], axis, output, mode, cval, 0) axes = [ii for ii in range(input.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 1, 1], ii, output, mode, cval, 0,) return return_value @docfiller def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Sobel filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode)s %(cval)s """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) output, return_value = _ni_support._get_output(output, input) correlate1d(input, [-1, 0, 1], axis, output, mode, cval, 0) axes = [ii for ii in range(input.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 2, 1], ii, output, mode, cval, 0) return return_value @docfiller def generic_laplace(input, derivative2, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords = None): """N-dimensional Laplace filter using a provided second derivative function Parameters ---------- %(input)s derivative2 : callable Callable with the following signature:: derivative2(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = list(range(input.ndim)) if len(axes) > 0: derivative2(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) for ii in range(1, len(axes)): tmp = derivative2(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) output += tmp else: output[...] = input[...] return return_value @docfiller def laplace(input, output=None, mode="reflect", cval=0.0): """N-dimensional Laplace filter based on approximate second derivatives. Parameters ---------- %(input)s %(output)s %(mode)s %(cval)s """ def derivative2(input, axis, output, mode, cval): return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0) return generic_laplace(input, derivative2, output, mode, cval) @docfiller def gaussian_laplace(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multidimensional Laplace filter using gaussian second derivatives. Parameters ---------- %(input)s sigma : scalar or sequence of scalars The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. %(output)s %(mode)s %(cval)s Extra keyword arguments will be passed to gaussian_filter(). """ input = numpy.asarray(input) def derivative2(input, axis, output, mode, cval, sigma, **kwargs): order = [0] * input.ndim order[axis] = 2 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) return generic_laplace(input, derivative2, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs) @docfiller def generic_gradient_magnitude(input, derivative, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords = None): """Gradient magnitude using a provided gradient function. Parameters ---------- %(input)s derivative : callable Callable with the following signature:: derivative(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. `derivative` can assume that `input` and `output` are ndarrays. Note that the output from `derivative` is modified inplace; be careful to copy important inputs before returning them. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = list(range(input.ndim)) if len(axes) > 0: derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(output, output, output) for ii in range(1, len(axes)): tmp = derivative(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(tmp, tmp, tmp) output += tmp # This allows the sqrt to work with a different default casting if NumpyVersion(numpy.__version__) > '1.6.1': numpy.sqrt(output, output, casting='unsafe') else: numpy.sqrt(output, output) else: output[...] = input[...] return return_value @docfiller def gaussian_gradient_magnitude(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multidimensional gradient magnitude using Gaussian derivatives. Parameters ---------- %(input)s sigma : scalar or sequence of scalars The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.. %(output)s %(mode)s %(cval)s Extra keyword arguments will be passed to gaussian_filter(). """ input = numpy.asarray(input) def derivative(input, axis, output, mode, cval, sigma, **kwargs): order = [0] * input.ndim order[axis] = 1 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) return generic_gradient_magnitude(input, derivative, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs) def _correlate_or_convolve(input, weights, output, mode, cval, origin, convolution): input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) weights = numpy.asarray(weights, dtype=numpy.float64) wshape = [ii for ii in weights.shape if ii > 0] if len(wshape) != input.ndim: raise RuntimeError('filter weights array has incorrect shape.') if convolution: weights = weights[tuple([slice(None, None, -1)] * weights.ndim)] for ii in range(len(origins)): origins[ii] = -origins[ii] if not weights.shape[ii] & 1: origins[ii] -= 1 for origin, lenw in zip(origins, wshape): if (lenw // 2 + origin < 0) or (lenw // 2 + origin > lenw): raise ValueError('invalid origin') if not weights.flags.contiguous: weights = weights.copy() output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate(input, weights, output, mode, cval, origins) return return_value @docfiller def correlate(input, weights, output=None, mode='reflect', cval=0.0, origin=0): """ Multi-dimensional correlation. The array is correlated with the given kernel. Parameters ---------- input : array-like input array to filter weights : ndarray array of weights, same number of dimensions as input output : array, optional The ``output`` parameter passes an array in which to store the filter output. mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional The ``mode`` parameter determines how the array borders are handled, where ``cval`` is the value when mode is equal to 'constant'. Default is 'reflect' cval : scalar, optional Value to fill past edges of input if ``mode`` is 'constant'. Default is 0.0 origin : scalar, optional The ``origin`` parameter controls the placement of the filter. Default 0 See Also -------- convolve : Convolve an image with a kernel. """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, False) @docfiller def convolve(input, weights, output=None, mode='reflect', cval=0.0, origin=0): """ Multidimensional convolution. The array is convolved with the given kernel. Parameters ---------- input : array_like Input array to filter. weights : array_like Array of weights, same number of dimensions as input output : ndarray, optional The `output` parameter passes an array in which to store the filter output. mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional the `mode` parameter determines how the array borders are handled. For 'constant' mode, values beyond borders are set to be `cval`. Default is 'reflect'. cval : scalar, optional Value to fill past edges of input if `mode` is 'constant'. Default is 0.0 origin : array_like, optional The `origin` parameter controls the placement of the filter. Default is 0. Returns ------- result : ndarray The result of convolution of `input` with `weights`. See Also -------- correlate : Correlate an image with a kernel. Notes ----- Each value in result is :math:`C_i = \\sum_j{I_{i+j-k} W_j}`, where W is the `weights` kernel, j is the n-D spatial index over :math:`W`, I is the `input` and k is the coordinate of the center of W, specified by `origin` in the input parameters. Examples -------- Perhaps the simplest case to understand is ``mode='constant', cval=0.0``, because in this case borders (i.e. where the `weights` kernel, centered on any one value, extends beyond an edge of `input`. >>> a = np.array([[1, 2, 0, 0], ... [5, 3, 0, 4], ... [0, 0, 0, 7], ... [9, 3, 0, 0]]) >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]]) >>> from scipy import ndimage >>> ndimage.convolve(a, k, mode='constant', cval=0.0) array([[11, 10, 7, 4], [10, 3, 11, 11], [15, 12, 14, 7], [12, 3, 7, 0]]) Setting ``cval=1.0`` is equivalent to padding the outer edge of `input` with 1.0's (and then extracting only the original region of the result). >>> ndimage.convolve(a, k, mode='constant', cval=1.0) array([[13, 11, 8, 7], [11, 3, 11, 14], [16, 12, 14, 10], [15, 6, 10, 5]]) With ``mode='reflect'`` (the default), outer values are reflected at the edge of `input` to fill in missing values. >>> b = np.array([[2, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]]) >>> ndimage.convolve(b, k, mode='reflect') array([[5, 0, 0], [3, 0, 0], [1, 0, 0]]) This includes diagonally at the corners. >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]]) >>> ndimage.convolve(b, k) array([[4, 2, 0], [3, 2, 0], [1, 1, 0]]) With ``mode='nearest'``, the single nearest value in to an edge in `input` is repeated as many times as needed to match the overlapping `weights`. >>> c = np.array([[2, 0, 1], ... [1, 0, 0], ... [0, 0, 0]]) >>> k = np.array([[0, 1, 0], ... [0, 1, 0], ... [0, 1, 0], ... [0, 1, 0], ... [0, 1, 0]]) >>> ndimage.convolve(c, k, mode='nearest') array([[7, 0, 3], [5, 0, 2], [3, 0, 1]]) """ return _correlate_or_convolve(input, weights, output, mode, cval, origin, True) @docfiller def uniform_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional uniform filter along the given axis. The lines of the array along the given axis are filtered with a uniform filter of given size. Parameters ---------- %(input)s size : int length of uniform filter %(axis)s %(output)s %(mode)s %(cval)s %(origin)s """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, origin) return return_value @docfiller def uniform_filter(input, size=3, output=None, mode="reflect", cval=0.0, origin=0): """Multi-dimensional uniform filter. Parameters ---------- %(input)s size : int or sequence of ints, optional The sizes of the uniform filter are given for each axis as a sequence, or as a single number, in which case the size is equal for all axes. %(output)s %(mode)s %(cval)s %(origin)s Notes ----- The multi-dimensional filter is implemented as a sequence of one-dimensional uniform filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. """ input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) sizes = _ni_support._normalize_sequence(size, input.ndim) origins = _ni_support._normalize_sequence(origin, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes)) if sizes[ii] > 1] if len(axes) > 0: for axis, size, origin in axes: uniform_filter1d(input, int(size), axis, output, mode, cval, origin) input = output else: output[...] = input[...] return return_value @docfiller def minimum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional minimum filter along the given axis. The lines of the array along the given axis are filtered with a minimum filter of given size. Parameters ---------- %(input)s size : int length along which to calculate 1D minimum %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Notes ----- This function implements the MINLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 1) return return_value @docfiller def maximum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional maximum filter along the given axis. The lines of the array along the given axis are filtered with a maximum filter of given size. Parameters ---------- %(input)s size : int Length along which to calculate the 1-D maximum. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- maximum1d : ndarray, None Maximum-filtered array with same shape as input. None if `output` is not None Notes ----- This function implements the MAXLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0) return return_value def _min_or_max_filter(input, size, footprint, structure, output, mode, cval, origin, minimum): if structure is None: if footprint is None: if size is None: raise RuntimeError("no footprint provided") separable = True else: footprint = numpy.asarray(footprint) footprint = footprint.astype(bool) if numpy.alltrue(numpy.ravel(footprint), axis=0): size = footprint.shape footprint = None separable = True else: separable = False else: structure = numpy.asarray(structure, dtype=numpy.float64) separable = False if footprint is None: footprint = numpy.ones(structure.shape, bool) else: footprint = numpy.asarray(footprint) footprint = footprint.astype(bool) input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) origins = _ni_support._normalize_sequence(origin, input.ndim) if separable: sizes = _ni_support._normalize_sequence(size, input.ndim) axes = list(range(input.ndim)) axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes)) if sizes[ii] > 1] if minimum: filter_ = minimum_filter1d else: filter_ = maximum_filter1d if len(axes) > 0: for axis, size, origin in axes: filter_(input, int(size), axis, output, mode, cval, origin) input = output else: output[...] = input[...] else: fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() if structure is not None: if len(structure.shape) != input.ndim: raise RuntimeError('structure array has incorrect shape') if not structure.flags.contiguous: structure = structure.copy() mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter(input, footprint, structure, output, mode, cval, origins, minimum) return return_value @docfiller def minimum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional minimum filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 1) @docfiller def maximum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional maximum filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _min_or_max_filter(input, size, footprint, None, output, mode, cval, origin, 0) @docfiller def _rank_filter(input, rank, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, operation='rank'): input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) if footprint is None: if size is None: raise RuntimeError("no footprint or filter size provided") sizes = _ni_support._normalize_sequence(size, input.ndim) footprint = numpy.ones(sizes, dtype=bool) else: footprint = numpy.asarray(footprint, dtype=bool) fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('filter footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() filter_size = numpy.where(footprint, 1, 0).sum() if operation == 'median': rank = filter_size // 2 elif operation == 'percentile': percentile = rank if percentile < 0.0: percentile += 100.0 if percentile < 0 or percentile > 100: raise RuntimeError('invalid percentile') if percentile == 100.0: rank = filter_size - 1 else: rank = int(float(filter_size) * percentile / 100.0) if rank < 0: rank += filter_size if rank < 0 or rank >= filter_size: raise RuntimeError('rank not within filter footprint size') if rank == 0: return minimum_filter(input, None, footprint, output, mode, cval, origins) elif rank == filter_size - 1: return maximum_filter(input, None, footprint, output, mode, cval, origins) else: output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins) return return_value @docfiller def rank_filter(input, rank, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional rank filter. Parameters ---------- %(input)s rank : int The rank parameter may be less then zero, i.e., rank = -1 indicates the largest element. %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _rank_filter(input, rank, size, footprint, output, mode, cval, origin, 'rank') @docfiller def median_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """ Calculates a multidimensional median filter. Parameters ---------- %(input)s %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s Returns ------- median_filter : ndarray Return of same shape as `input`. """ return _rank_filter(input, 0, size, footprint, output, mode, cval, origin, 'median') @docfiller def percentile_filter(input, percentile, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): """Calculates a multi-dimensional percentile filter. Parameters ---------- %(input)s percentile : scalar The percentile parameter may be less then zero, i.e., percentile = -20 equals percentile = 80 %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s """ return _rank_filter(input, percentile, size, footprint, output, mode, cval, origin, 'percentile') @docfiller def generic_filter1d(input, function, filter_size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0, extra_arguments=(), extra_keywords = None): """Calculate a one-dimensional filter along the given axis. `generic_filter1d` iterates over the lines of the array, calling the given function at each line. The arguments of the line are the input line, and the output line. The input and output lines are 1D double arrays. The input line is extended appropriately according to the filter size and origin. The output line must be modified in-place with the result. Parameters ---------- %(input)s function : callable Function to apply along given axis. filter_size : scalar Length of the filter. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s %(extra_arguments)s %(extra_keywords)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) if filter_size < 1: raise RuntimeError('invalid filter size') axis = _ni_support._check_axis(axis, input.ndim) if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >= filter_size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.generic_filter1d(input, function, filter_size, axis, output, mode, cval, origin, extra_arguments, extra_keywords) return return_value @docfiller def generic_filter(input, function, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, extra_arguments=(), extra_keywords = None): """Calculates a multi-dimensional filter using the given function. At each element the provided function is called. The input values within the filter footprint at that element are passed to the function as a 1D array of double values. Parameters ---------- %(input)s function : callable Function to apply at each element. %(size_foot)s %(output)s %(mode)s %(cval)s %(origin)s %(extra_arguments)s %(extra_keywords)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) if footprint is None: if size is None: raise RuntimeError("no footprint or filter size provided") sizes = _ni_support._normalize_sequence(size, input.ndim) footprint = numpy.ones(sizes, dtype=bool) else: footprint = numpy.asarray(footprint) footprint = footprint.astype(bool) fshape = [ii for ii in footprint.shape if ii > 0] if len(fshape) != input.ndim: raise RuntimeError('filter footprint array has incorrect shape.') for origin, lenf in zip(origins, fshape): if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): raise ValueError('invalid origin') if not footprint.flags.contiguous: footprint = footprint.copy() output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.generic_filter(input, function, footprint, output, mode, cval, origins, extra_arguments, extra_keywords) return return_value
ales-erjavec/scipy
scipy/ndimage/filters.py
Python
bsd-3-clause
40,515
[ "Gaussian" ]
3dba0eecd8415443aa352b4095f7397a2e27cbb9bb4b76043dfe14e42a3ff8b9
try: paraview.simple except: from paraview.simple import * paraview.simple._DisableFirstRenderCameraReset() import os,sys,glob,struct,math,subprocess import vtk #os.chdir("/home/zeli/tmp/delme1/") cwd_folder=os.getcwd() #------------------------------------------------------------- def window(LT, title): RenderView1 = GetRenderView() RenderView1.ViewSize = [450, 800] RenderView1.CacheKey = 0.0 RenderView1.Background = [1.0, 1.0, 1.0] RenderView1.UseLight = 1 RenderView1.LightSwitch = 0 RenderView1.RemoteRenderThreshold = 3.0 RenderView1.OrientationAxesVisibility = 0 RenderView1.OrientationAxesLabelColor = [0.0, 0.0, 0.0] RenderView1.CameraFocalPoint = [15, 7.5, 0.0] # for GOST RenderView1.CameraPosition = [15, 7.5, -57] # for GOST RenderView1.CameraViewAngle = 30 # for GOST RenderView1.CenterAxesVisibility = 0 def layout(representation, array, LT, PF): DataRepresentation1 = Show() DataRepresentation1.CubeAxesXTitle = '' DataRepresentation1.CubeAxesYTitle = '' DataRepresentation1.AxesOrigin = [0.0, 0.0, 0.0] DataRepresentation1.Origin = [-0.0, 0.0, 0.0] DataRepresentation1.EdgeColor = [0.0, 0.0, 0.0] #DataRepresentation1.SelectionPointFieldDataArrayName = 'Potential' DataRepresentation1.ScalarOpacityFunction = PF DataRepresentation1.ScalarOpacityUnitDistance = 0.5802894042140944 DataRepresentation1.LookupTable = LT DataRepresentation1.CubeAxesVisibility = 1 DataRepresentation1.ScaleFactor = 1.0 DataRepresentation1.CubeAxesColor = [0.0, 0.0, 0.0] DataRepresentation1.CubeAxesXAxisVisibility = 1 DataRepresentation1.CubeAxesYAxisVisibility = 1 DataRepresentation1.CubeAxesXAxisMinorTickVisibility = 0 DataRepresentation1.CubeAxesYAxisMinorTickVisibility = 0 DataRepresentation1.CubeAxesTickLocation = 'Outside' #DataRepresentation1.CustomRangeActive = [1, 1, 1] #DataRepresentation1.CustomBoundsActive = [1, 1, 1] #DataRepresentation1.CustomRange = [xmin, xmax, ymin, ymax, 0.0, 0.0] #DataRepresentation1.CustomBounds = [xmin, xmax, ymin, ymax, 0.0, 0.0] DataRepresentation1.ColorArrayName = ('POINT_DATA', array) DataRepresentation1.Representation = representation #------------------------------------------------------------------------- #Durchsucht alles unter "pathname" und macht liste aus gefundenen Datein: file_list=[] sp = subprocess.Popen( 'find . -type f -name "final-*.pvtu" | sed \'s:^\./::\'', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) file_list = sp.communicate()[0].split() #print file_list cam1 = GetActiveCamera() cam1.Roll(90) #cam1.Azimuth(180) for file in file_list: print file current_folder = cwd_folder + '/' + os.path.dirname( file ) + '/'; os.chdir( current_folder ); filename = os.path.basename( file ) filename_noext = os.path.splitext(filename)[0] #------------------------------------------------------------- final_pvtu = XMLPartitionedUnstructuredGridReader(PointArrayStatus=['Psi_sol','error per cell'], FileName=[filename] ) pd = final_pvtu.PointData #for n in range(pd.GetNumberOfArrays()): # print "Range for array ", pd.GetArray(n).GetName(), " ", pd.GetArray(n).GetRange() my_range = pd.GetArray("Psi_sol").GetRange() psirefLUT = MakeBlueToRedLT(my_range[0],my_range[1]) psirefPWF = GetOpacityTransferFunction('Psi_sol') clip1 = Clip(Input=final_pvtu) clip1.ClipType = 'Plane' clip1.Scalars = ['POINTS', 'Psi_sol'] clip1.Value = -0.7669909596442928 clip1.InsideOut = 0 clip1.Crinkleclip = 0 # init the 'Plane' selected for 'ClipType' clip1.ClipType.Origin = [20.0, 15.0, 0.0] clip1.ClipType.Normal = [0.0, -1.0, 0.0] clip1.ClipType.Offset = 0.0 Hide(final_pvtu,GetRenderView()) clip2 = Clip(Input=clip1) clip2.ClipType = 'Plane' clip2.Scalars = ['POINTS', 'Psi_sol'] clip2.ClipType.Origin = [30.0, 7.5, 0.0] clip2.ClipType.Normal = [-1.0, 0.0, 0.0] clip2.ClipType.Offset = 0.0 Hide(clip1,GetRenderView()) # show data in view SetActiveSource(clip2) clip2Display = Show() clip2Display.Representation = 'Surface' clip2Display.ColorArrayName = ['POINTS', 'Psi_sol'] window(psirefLUT, ' Psi_sol') layout('Surface', 'Psi_sol', psirefLUT, psirefPWF) Render() WriteImage( current_folder + "sol.png") Delete(psirefLUT) del psirefLUT Delete(psirefPWF) del psirefPWF Delete(clip2) del clip2 Delete(clip1) del clip1 Delete(final_pvtu) del final_pvtu #for f in GetSources().values(): # print GetSources().values() # if f.GetProperty("Input") is not None: # Delete(f)
zeli86/playground
paraview/mass_image_creation_mit_clipping_cs.py
Python
gpl-3.0
4,794
[ "ParaView", "VTK" ]
24accf156b5d8d36ea9ec8600562d9c0fb03b02692276088d9082440a81ed9fb
import itertools import numpy as np from six.moves import zip, range from nose.plugins.attrib import attr from unittest import TestCase from numpy.testing import (assert_equal, assert_raises, assert_almost_equal, assert_array_almost_equal, raises, assert_allclose, assert_, dec) import MDAnalysis as mda from MDAnalysis.coordinates.base import Timestep from MDAnalysis import NoDataError from MDAnalysis.lib.mdamath import triclinic_vectors from MDAnalysisTests.coordinates.reference import RefAdKSmall from MDAnalysisTests.datafiles import AUX_XVG_HIGHF, AUX_XVG_LOWF from MDAnalysisTests import tempdir class _SingleFrameReader(TestCase, RefAdKSmall): # see TestPDBReader how to set up! def tearDown(self): del self.universe def test_load_file(self): U = self.universe assert_equal(len(U.atoms), self.ref_n_atoms, "load Universe from file {0!s}".format(U.trajectory.filename)) assert_equal(U.atoms.select_atoms('resid 150 and name HA2').atoms[0], U.atoms[self.ref_E151HA2_index], "Atom selections") def test_n_atoms(self): assert_equal(self.universe.trajectory.n_atoms, self.ref_n_atoms, "wrong number of atoms") def test_numres(self): assert_equal(self.universe.atoms.n_residues, 214, "wrong number of residues") def test_n_frames(self): assert_equal(self.universe.trajectory.n_frames, 1, "wrong number of frames in pdb") def test_time(self): assert_equal(self.universe.trajectory.time, 0.0, "wrong time of the frame") def test_frame(self): assert_equal( self.universe.trajectory.frame, 0, "wrong frame number (0-based, should be 0 for single frame " "readers)") def test_frame_index_0(self): self.universe.trajectory[0] assert_equal(self.universe.trajectory.ts.frame, 0, "frame number for frame index 0 should be 0") def test_frame_index_1_raises_IndexError(self): def go_to_2(traj=self.universe.trajectory): traj[1] assert_raises(IndexError, go_to_2) def test_dt(self): """testing that accessing universe.trajectory.dt gives 1.0 (the default)""" assert_equal(1.0, self.universe.trajectory.dt) def test_coordinates(self): A10CA = self.universe.atoms.CA[10] # restrict accuracy to maximum in PDB files (3 decimals) assert_almost_equal(A10CA.position, self.ref_coordinates['A10CA'], 3, err_msg="wrong coordinates for A10:CA") def test_distances(self): NTERM = self.universe.atoms.N[0] CTERM = self.universe.atoms.C[-1] d = mda.lib.mdamath.norm(NTERM.position - CTERM.position) assert_almost_equal(d, self.ref_distances['endtoend'], self.prec, err_msg="distance between M1:N and G214:C") def test_full_slice(self): trj_iter = self.universe.trajectory[:] frames = [ts.frame for ts in trj_iter] assert_equal(frames, np.arange(self.universe.trajectory.n_frames)) def test_last_slice(self): # should be same as above: only 1 frame! trj_iter = self.universe.trajectory[-1:] frames = [ts.frame for ts in trj_iter] assert_equal(frames, np.arange(self.universe.trajectory.n_frames)) class BaseReference(object): def __init__(self): self.trajectory = None self.n_atoms = 5 self.n_frames = 5 # default for the numpy test functions self.prec = 6 self.container_format = False self.changing_dimensions = False # for testing auxiliary addition self.aux_lowf = AUX_XVG_LOWF # test auxiliary with lower frequency self.aux_lowf_dt = 2 # has steps at 0ps, 2ps, 4ps # representative data for each trajectory frame, assuming 'closest' option self.aux_lowf_data = [[2 ** 0], # frame 0 = 0ps = step 0 [np.nan], # frame 1 = 1ps = no step [2 ** 1], # frame 2 = 2ps = step 1 [np.nan], # frame 3 = 3ps = no step [2 ** 2], # frame 4 = 4ps = step 2 ] self.aux_lowf_frames_with_steps = [0, 2, 4] # trajectory frames with # corresponding auxiliary steps self.aux_highf = AUX_XVG_HIGHF # test auxiliary with higher frequency self.aux_highf_dt = 0.5 # has steps at 0, 0.5, 1, ... 3.5, 4ps self.aux_highf_data = [[2 ** 0], # frame 0 = 0ps = step 0 [2 ** 2], # frame 1 = 1ps = step 2 [2 ** 4], # frame 2 = 2ps = step 4 [2 ** 6], # frame 3 = 3ps = step 6 [2 ** 8], # frame 4 = 4ps = step 8 ] self.aux_highf_n_steps = 10 self.aux_highf_all_data = [[2 ** i] for i in range(self.aux_highf_n_steps)] self.aux_offset_by = 0.25 self.first_frame = Timestep(self.n_atoms) self.first_frame.positions = np.arange( 3 * self.n_atoms).reshape(self.n_atoms, 3) self.first_frame.frame = 0 self.first_frame.aux.lowf = self.aux_lowf_data[0] self.first_frame.aux.highf = self.aux_highf_data[0] self.second_frame = self.first_frame.copy() self.second_frame.positions = 2 ** 1 * self.first_frame.positions self.second_frame.frame = 1 self.second_frame.aux.lowf = self.aux_lowf_data[1] self.second_frame.aux.highf = self.aux_highf_data[1] self.last_frame = self.first_frame.copy() self.last_frame.positions = 2 ** 4 * self.first_frame.positions self.last_frame.frame = self.n_frames - 1 self.last_frame.aux.lowf = self.aux_lowf_data[-1] self.last_frame.aux.highf = self.aux_highf_data[-1] # remember frames are 0 indexed self.jump_to_frame = self.first_frame.copy() self.jump_to_frame.positions = 2 ** 3 * self.first_frame.positions self.jump_to_frame.frame = 3 self.jump_to_frame.aux.lowf = self.aux_lowf_data[3] self.jump_to_frame.aux.highf = self.aux_highf_data[3] self.dimensions = np.array([81.1, 82.2, 83.3, 75, 80, 85], dtype=np.float32) self.dimensions_second_frame = np.array([82.1, 83.2, 84.3, 75.1, 80.1, 85.1], dtype=np.float32) self.volume = mda.lib.mdamath.box_volume(self.dimensions) self.time = 0 self.dt = 1 self.totaltime = 4 def iter_ts(self, i): ts = self.first_frame.copy() ts.positions = 2 ** i * self.first_frame.positions ts.time = i ts.frame = i ts.aux.lowf = np.array(self.aux_lowf_data[i]) ts.aux.highf = np.array(self.aux_highf_data[i]) return ts class BaseReaderTest(object): def __init__(self, reference): self.ref = reference self.reader = self.ref.reader(self.ref.trajectory) self.reader.add_auxiliary('lowf', self.ref.aux_lowf, dt=self.ref.aux_lowf_dt, initial_time=0, time_selector=None) self.reader.add_auxiliary('highf', self.ref.aux_highf, dt=self.ref.aux_highf_dt, initial_time=0, time_selector=None) def test_n_atoms(self): assert_equal(self.reader.n_atoms, self.ref.n_atoms) def test_n_frames(self): assert_equal(len(self.reader), self.ref.n_frames) def test_first_frame(self): self.reader.rewind() assert_timestep_almost_equal(self.reader.ts, self.ref.first_frame, decimal=self.ref.prec) def test_double_close(self): self.reader.close() self.reader.close() self.reader._reopen() def test_get_writer_1(self): with tempdir.in_tempdir(): self.outfile = 'test-writer' + self.ref.ext with self.reader.Writer(self.outfile) as W: assert_equal(isinstance(W, self.ref.writer), True) assert_equal(W.n_atoms, self.reader.n_atoms) def test_get_writer_2(self): with tempdir.in_tempdir(): self.outfile = 'test-writer' + self.ref.ext with self.reader.Writer(self.outfile, n_atoms=100) as W: assert_equal(isinstance(W, self.ref.writer), True) assert_equal(W.n_atoms, 100) def test_dt(self): assert_equal(self.reader.dt, self.ref.dt) def test_ts_dt_matches_reader(self): assert_equal(self.reader.ts.dt, self.reader.dt) def test_total_time(self): assert_equal(self.reader.totaltime, self.ref.totaltime) def test_first_dimensions(self): self.reader.rewind() assert_array_almost_equal(self.reader.ts.dimensions, self.ref.dimensions, decimal=self.ref.prec) def test_changing_dimensions(self): if self.ref.changing_dimensions: self.reader.rewind() assert_array_almost_equal(self.reader.ts.dimensions, self.ref.dimensions, decimal=self.ref.prec) self.reader[1] assert_array_almost_equal(self.reader.ts.dimensions, self.ref.dimensions_second_frame, decimal=self.ref.prec) def test_volume(self): self.reader.rewind() vol = self.reader.ts.volume # Here we can only be sure about the numbers upto the decimal point due # to floating point impressions. assert_almost_equal(vol, self.ref.volume, 0) def test_iter(self): for i, ts in enumerate(self.reader): assert_timestep_almost_equal(ts, self.ref.iter_ts(i), decimal=self.ref.prec) @raises(ValueError) def test_add_same_auxname_raises_ValueError(self): self.reader.add_auxiliary('lowf', self.ref.aux_lowf) def test_remove_auxiliary(self): self.reader.remove_auxiliary('lowf') assert_raises(AttributeError, getattr, self.reader._auxs, 'lowf') assert_raises(AttributeError, getattr, self.reader.ts.aux, 'lowf') @raises(ValueError) def test_remove_nonexistant_auxiliary_raises_ValueError(self): self.reader.remove_auxiliary('nonexistant') def test_iter_auxiliary(self): # should go through all steps in 'highf' for i, auxstep in enumerate(self.reader.iter_auxiliary('highf')): assert_almost_equal(auxstep.data, self.ref.aux_highf_all_data[i], err_msg="Auxiliary data does not match for " "step {}".format(i)) def test_get_aux_attribute(self): assert_equal(self.reader.get_aux_attribute('lowf', 'dt'), self.ref.aux_lowf_dt) def test_iter_as_aux_cutoff(self): # load an auxiliary with the same dt but offset from trajectory, and a # cutoff of 0 self.reader.add_auxiliary('offset', self.ref.aux_lowf, dt=self.ref.dt, time_selector=None, initial_time=self.ref.aux_offset_by, cutoff=0) # no auxiliary steps will fall within the cutoff for any frame, so # iterating using iter_as_aux should give us nothing num_frames = len([i for i in self.reader.iter_as_aux('offset')]) assert_equal(num_frames, 0, "iter_as_aux should iterate over 0 frames," " not {}".format(num_frames)) def test_reload_auxiliaries_from_description(self): # get auxiliary desscriptions form existing reader descriptions = self.reader.get_aux_descriptions() # load a new reader, without auxiliaries reader = self.ref.reader(self.ref.trajectory) # load auxiliaries into new reader, using description... for aux in descriptions: reader.add_auxiliary(**aux) # should have the same number of auxiliaries assert_equal(reader.aux_list, self.reader.aux_list, 'Number of auxiliaries does not match') # each auxiliary should be the same for auxname in reader.aux_list: assert_equal(reader._auxs[auxname], self.reader._auxs[auxname], 'AuxReaders do not match') def test_stop_iter(self): # reset to 0 self.reader.rewind() for ts in self.reader[:-1]: pass assert_equal(self.reader.frame, 0) class MultiframeReaderTest(BaseReaderTest): def test_last_frame(self): ts = self.reader[-1] assert_timestep_almost_equal(ts, self.ref.last_frame, decimal=self.ref.prec) @raises(IndexError) def test_go_over_last_frame(self): self.reader[self.ref.n_frames + 1] def test_frame_jump(self): ts = self.reader[self.ref.jump_to_frame.frame] assert_timestep_almost_equal(ts, self.ref.jump_to_frame, decimal=self.ref.prec) def test_next_gives_second_frame(self): reader = self.ref.reader(self.ref.trajectory) ts = reader.next() assert_timestep_almost_equal(ts, self.ref.second_frame, decimal=self.ref.prec) def test_reopen(self): self.reader.close() self.reader._reopen() ts = self.reader.next() assert_timestep_almost_equal(ts, self.ref.first_frame, decimal=self.ref.prec) def test_rename_aux(self): self.reader.rename_aux('lowf', 'lowf_renamed') # data should now be in aux namespace under new name assert_equal(self.reader.ts.aux.lowf_renamed, self.ref.aux_lowf_data[0]) # old name should be removed assert_raises(AttributeError, getattr, self.reader.ts.aux, 'lowf') # new name should be retained next(self.reader) assert_equal(self.reader.ts.aux.lowf_renamed, self.ref.aux_lowf_data[1]) def test_iter_as_aux_highf(self): # auxiliary has a higher frequency, so iter_as_aux should behave the # same as regular iteration over the trjectory for i, ts in enumerate(self.reader.iter_as_aux('highf')): assert_timestep_almost_equal(ts, self.ref.iter_ts(i), decimal=self.ref.prec) def test_iter_as_aux_lowf(self): # auxiliary has a lower frequency, so iter_as_aux should iterate over # only frames where there is a corresponding auxiliary value for i, ts in enumerate(self.reader.iter_as_aux('lowf')): assert_timestep_almost_equal(ts, self.ref.iter_ts(self.ref.aux_lowf_frames_with_steps[i]), decimal=self.ref.prec) class BaseWriterTest(object): def __init__(self, reference): self.ref = reference self.tmpdir = tempdir.TempDir() self.reader = self.ref.reader(self.ref.trajectory) def tmp_file(self, name): return self.tmpdir.name + name + '.' + self.ref.ext def test_write_trajectory_timestep(self): outfile = self.tmp_file('write-timestep-test') with self.ref.writer(outfile, self.reader.n_atoms) as W: for ts in self.reader: W.write(ts) self._check_copy(outfile) def test_write_different_box(self): if self.ref.changing_dimensions: outfile = self.tmp_file('write-dimensions-test') with self.ref.writer(outfile, self.reader.n_atoms) as W: for ts in self.reader: ts.dimensions[:3] += 1 W.write(ts) written = self.ref.reader(outfile) for ts_ref, ts_w in zip(self.reader, written): ts_ref.dimensions[:3] += 1 assert_array_almost_equal(ts_ref.dimensions, ts_w.dimensions, decimal=self.ref.prec) def test_write_trajectory_atomgroup(self): uni = mda.Universe(self.ref.topology, self.ref.trajectory) outfile = self.tmp_file('write-atoms-test') with self.ref.writer(outfile, uni.atoms.n_atoms) as w: for ts in uni.trajectory: w.write(uni.atoms) self._check_copy(outfile) def test_write_trajectory_universe(self): uni = mda.Universe(self.ref.topology, self.ref.trajectory) outfile = self.tmp_file('write-uni-test') with self.ref.writer(outfile, uni.atoms.n_atoms) as w: for ts in uni.trajectory: w.write(uni) self._check_copy(outfile) def test_write_selection(self): uni = mda.Universe(self.ref.topology, self.ref.trajectory) sel_str = 'resid 1' sel = uni.select_atoms(sel_str) outfile = self.tmp_file('write-selection-test') with self.ref.writer(outfile, sel.n_atoms) as W: for ts in uni.trajectory: W.write(sel.atoms) copy = self.ref.reader(outfile) for orig_ts, copy_ts in zip(uni.trajectory, copy): assert_array_almost_equal( copy_ts._pos, sel.atoms.positions, self.ref.prec, err_msg="coordinate mismatch between original and written " "trajectory at frame {} (orig) vs {} (copy)".format( orig_ts.frame, copy_ts.frame)) def _check_copy(self, fname): copy = self.ref.reader(fname) assert_equal(self.reader.n_frames, copy.n_frames) for orig_ts, copy_ts in zip(self.reader, copy): assert_timestep_almost_equal( copy_ts, orig_ts, decimal=self.ref.prec) @raises(TypeError) def test_write_none(self): outfile = self.tmp_file('write-none') with self.ref.writer(outfile, 42) as w: w.write(None) def test_no_container(self): with tempdir.in_tempdir(): if self.ref.container_format: self.ref.writer('foo') else: assert_raises(TypeError, self.ref.writer, 'foo') def test_write_not_changing_ts(self): outfile = self.tmp_file('write-not-changing-ts') ts = self.reader.ts.copy() copy_ts = ts.copy() with self.ref.writer(outfile, n_atoms=5) as W: W.write(ts) assert_timestep_almost_equal(copy_ts, ts) class BaseTimestepTest(object): """Test all the base functionality of a Timestep All Timesteps must pass these tests! These test the Timestep independent of the Reader which it comes into contact with. Failures here are the Timesteps fault. """ # define the class made in test Timestep = mda.coordinates.base.Timestep name = "base" # for error messages only size = 10 # size of arrays, 10 is enough to allow slicing etc # each coord is unique refpos = np.arange(size * 3, dtype=np.float32).reshape(size, 3) * 1.234 refvel = np.arange(size * 3, dtype=np.float32).reshape(size, 3) * 2.345 reffor = np.arange(size * 3, dtype=np.float32).reshape(size, 3) * 3.456 has_box = True set_box = True # whether you can set dimensions info. # If you can set box, what the underlying unitcell should be # if dimensions are: newbox = np.array([10., 11., 12., 90., 90., 90.]) unitcell = np.array([10., 11., 12., 90., 90., 90.]) ref_volume = 1320. # what the volume is after setting newbox uni_args = None def setUp(self): self.ts = self.Timestep(self.size) self.ts.frame += 1 self.ts.positions = self.refpos def tearDown(self): del self.ts def test_getitem(self): assert_equal(self.ts[1], self.refpos[1]) def test_getitem_neg(self): assert_equal(self.ts[-1], self.refpos[-1]) def test_getitem_neg_IE(self): assert_raises(IndexError, self.ts.__getitem__, -(self.size + 1)) def test_getitem_pos_IE(self): assert_raises(IndexError, self.ts.__getitem__, (self.size + 1)) def test_getitem_slice(self): assert_equal(len(self.ts[:2]), len(self.refpos[:2])) assert_allclose(self.ts[:2], self.refpos[:2]) def test_getitem_slice2(self): assert_equal(len(self.ts[1::2]), len(self.refpos[1::2])) assert_allclose(self.ts[1::2], self.refpos[1::2]) def test_getitem_ndarray(self): sel = np.array([0, 1, 4]) assert_equal(len(self.ts[sel]), len(self.refpos[sel])) assert_allclose(self.ts[sel], self.refpos[sel]) def test_getitem_TE(self): assert_raises(TypeError, self.ts.__getitem__, 'string') def test_len(self): assert_equal(len(self.ts), self.size) def test_iter(self): for a, b in zip(self.ts, self.refpos): assert_allclose(a, b) assert_equal(len(list(self.ts)), self.size) def test_repr(self): assert_equal(type(repr(self.ts)), str) # Dimensions has 2 possible cases # Timestep doesn't do dimensions, # should raise NotImplementedError for .dimension and .volume # Timestep does do them, should return values properly def test_dimensions(self): if self.has_box: assert_allclose(self.ts.dimensions, np.zeros(6, dtype=np.float32)) else: assert_raises(NotImplementedError, getattr, self.ts, "dimensions") def test_dimensions_set_box(self): if self.set_box: self.ts.dimensions = self.newbox assert_allclose(self.ts._unitcell, self.unitcell) assert_allclose(self.ts.dimensions, self.newbox) else: pass def test_volume(self): if self.has_box and self.set_box: self.ts.dimensions = self.newbox assert_equal(self.ts.volume, self.ref_volume) elif self.has_box and not self.set_box: pass # How to test volume of box when I don't set unitcell first? else: assert_raises(NotImplementedError, getattr, self.ts, "volume") def test_triclinic_vectors(self): assert_allclose(self.ts.triclinic_dimensions, triclinic_vectors(self.ts.dimensions)) def test_set_triclinic_vectors(self): ref_vec = triclinic_vectors(self.newbox) self.ts.triclinic_dimensions = ref_vec assert_equal(self.ts.dimensions, self.newbox) assert_allclose(self.ts._unitcell, self.unitcell) @attr('issue') def test_coordinate_getter_shortcuts(self): """testing that reading _x, _y, and _z works as expected # (Issue 224) (TestTimestep)""" assert_allclose(self.ts._x, self.ts._pos[:, 0]) assert_allclose(self.ts._y, self.ts._pos[:, 1]) assert_allclose(self.ts._z, self.ts._pos[:, 2]) def test_coordinate_setter_shortcuts(self): # Check that _x _y and _z are read only for coordinate in ('_x', '_y', '_z'): random_positions = np.arange(self.size).astype(np.float32) assert_raises(AttributeError, setattr, self.ts, coordinate, random_positions) # n_atoms should be a read only property # all Timesteps require this attribute def test_n_atoms(self): assert_equal(self.ts.n_atoms, self.ts._n_atoms) def test_n_atoms_readonly(self): assert_raises(AttributeError, self.ts.__setattr__, 'n_atoms', 20) def test_n_atoms_presence(self): assert_equal(hasattr(self.ts, '_n_atoms'), True) def test_unitcell_presence(self): assert_equal(hasattr(self.ts, '_unitcell'), True) def test_data_presence(self): assert_equal(hasattr(self.ts, 'data'), True) assert_equal(isinstance(self.ts.data, dict), True) def test_allocate_velocities(self): assert_equal(self.ts.has_velocities, False) assert_raises(NoDataError, getattr, self.ts, 'velocities') self.ts.has_velocities = True assert_equal(self.ts.has_velocities, True) assert_equal(self.ts.velocities.shape, (self.ts.n_atoms, 3)) def test_allocate_forces(self): assert_equal(self.ts.has_forces, False) assert_raises(NoDataError, getattr, self.ts, 'forces') self.ts.has_forces = True assert_equal(self.ts.has_forces, True) assert_equal(self.ts.forces.shape, (self.ts.n_atoms, 3)) def test_velocities_remove(self): ts = self.Timestep(10, velocities=True) ts.frame += 1 assert_equal(ts.has_velocities, True) ts.has_velocities = False assert_equal(ts.has_velocities, False) assert_raises(NoDataError, getattr, ts, 'velocities') def test_forces_remove(self): ts = self.Timestep(10, forces=True) ts.frame += 1 assert_equal(ts.has_forces, True) ts.has_forces = False assert_equal(ts.has_forces, False) assert_raises(NoDataError, getattr, ts, 'forces') def _empty_ts(self): assert_raises(ValueError, self.Timestep.from_coordinates, None, None, None) def _from_coords(self, p, v, f): posi = self.refpos if p else None velo = self.refvel if v else None forc = self.reffor if f else None ts = self.Timestep.from_coordinates(posi, velo, forc) return ts def _check_from_coordinates(self, p, v, f): ts = self._from_coords(p, v, f) if p: assert_array_almost_equal(ts.positions, self.refpos) else: assert_raises(NoDataError, getattr, ts, 'positions') if v: assert_array_almost_equal(ts.velocities, self.refvel) else: assert_raises(NoDataError, getattr, ts, 'velocities') if f: assert_array_almost_equal(ts.forces, self.reffor) else: assert_raises(NoDataError, getattr, ts, 'forces') def test_from_coordinates(self): # Check all combinations of creating a Timestep from data # 8 possibilites of with and without 3 data categories for p, v, f in itertools.product([True, False], repeat=3): if not any([p, v, f]): yield self._empty_ts else: yield self._check_from_coordinates, p, v, f def test_from_coordinates_mismatch(self): velo = self.refvel[:2] assert_raises(ValueError, self.Timestep.from_coordinates, self.refpos, velo) def test_from_coordinates_nodata(self): assert_raises(ValueError, self.Timestep.from_coordinates) def _check_from_timestep(self, p, v, f): ts = self._from_coords(p, v, f) ts2 = self.Timestep.from_timestep(ts) assert_timestep_almost_equal(ts, ts2) def test_from_timestep(self): for p, v, f in itertools.product([True, False], repeat=3): if not any([p, v, f]): continue yield self._check_from_timestep, p, v, f # Time related tests def test_supply_dt(self): # Check that this gets stored in data properly ts = self.Timestep(20, dt=0.04) assert_equal(ts.data['dt'], 0.04) assert_equal(ts.dt, 0.04) def test_redefine_dt(self): ts = self.Timestep(20, dt=0.04) assert_equal(ts.data['dt'], 0.04) assert_equal(ts.dt, 0.04) ts.dt = refdt = 0.46 assert_equal(ts.data['dt'], refdt) assert_equal(ts.dt, refdt) def test_delete_dt(self): ts = self.Timestep(20, dt=0.04) assert_equal(ts.data['dt'], 0.04) assert_equal(ts.dt, 0.04) del ts.dt assert_equal('dt' in ts.data, False) assert_equal(ts.dt, 1.0) # default value def test_supply_time_offset(self): ts = self.Timestep(20, time_offset=100.0) assert_equal(ts.data['time_offset'], 100.0) def test_time(self): ts = self.Timestep(20) ts.frame = 0 ts.time = reftime = 1234.0 assert_equal(ts.time, reftime) def test_delete_time(self): ts = self.Timestep(20) ts.frame = 0 ts.time = reftime = 1234.0 assert_equal(ts.time, reftime) del ts.time assert_equal(ts.time, 0.0) # default to 1.0 (dt) * 0 (frame) def test_time_with_offset(self): ref_offset = 2345.0 ts = self.Timestep(20, time_offset=ref_offset) ts.frame = 0 ts.time = reftime = 1234.0 assert_equal(ts.time, reftime + ref_offset) def test_dt(self): ref_dt = 45.0 ts = self.Timestep(20, dt=ref_dt) for i in range(10): ts.frame = i assert_equal(ts.time, i * ref_dt) def test_change_dt(self): ref_dt = 45.0 ts = self.Timestep(20, dt=ref_dt) for i in range(10): ts.frame = i assert_equal(ts.time, i * ref_dt) ts.dt = ref_dt = 77.0 for i in range(10): ts.frame = i assert_equal(ts.time, i * ref_dt) def test_dt_with_offset(self): ref_dt = 45.0 ref_offset = 2345.0 ts = self.Timestep(20, dt=ref_dt, time_offset=ref_offset) for i in range(10): ts.frame = i assert_equal(ts.time, i * ref_dt + ref_offset) def test_time_overrides_dt_with_offset(self): ref_dt = 45.0 ref_offset = 2345.0 ts = self.Timestep(20, dt=ref_dt, time_offset=ref_offset) ts.frame = 0 ts.time = reftime = 456.7 assert_equal(ts.time, reftime + ref_offset) def _check_copy(self, name, ref_ts): """Check basic copy""" ts2 = ref_ts.copy() err_msg = ("Timestep copy failed for format {form}" " on attribute {att}") # eq method checks: # - frame # - n_atoms # - positions, vels and forces assert_(ref_ts == ts2) assert_array_almost_equal(ref_ts.dimensions, ts2.dimensions, decimal=4) # Check things not covered by eq for d in ref_ts.data: assert_(d in ts2.data) if isinstance(ref_ts.data[d], np.ndarray): assert_array_almost_equal( ref_ts.data[d], ts2.data[d]) else: assert_(ref_ts.data[d] == ts2.data[d]) def _check_independent(self, name, ts): """Check that copies made are independent""" ts2 = ts.copy() if ts.has_positions: self._check_array(ts.positions, ts2.positions) if ts.has_velocities: self._check_array(ts.velocities, ts2.velocities) if ts.has_forces: self._check_array(ts.forces, ts2.forces) self._check_array(ts.dimensions, ts2.dimensions) def _check_array(self, arr1, arr2): """Check modifying one array doesn't change other""" ref = arr1.copy() arr2 += 1.0 assert_array_almost_equal(ref, arr1) def _check_copy_slice_indices(self, name, ts): sl = slice(0, len(ts), 3) ts2 = ts.copy_slice(sl) self._check_slice(ts, ts2, sl) def _check_copy_slice_slice(self, name, ts): sl = [0, 1, 3, 5, 6, 7] ts2 = ts.copy_slice(sl) self._check_slice(ts, ts2, sl) def _check_npint_slice(self, name, ts): for integers in [np.byte, np.short, np.intc, np.int_, np.longlong, np.intp, np.int8, np.int16, np.int32, np.int64, np.ubyte, np.ushort, np.uintc, np.ulonglong, np.uintp, np.uint8, np.uint16, np.uint32, np.uint64]: sl = slice(1, 2, 1) ts2 = ts.copy_slice(slice(integers(1), integers(2), integers(1))) self._check_slice(ts, ts2, sl) def _check_slice(self, ts1, ts2, sl): if ts1.has_positions: assert_array_almost_equal(ts1.positions[sl], ts2.positions) if ts1.has_velocities: assert_array_almost_equal(ts1.velocities[sl], ts2.velocities) if ts1.has_forces: assert_array_almost_equal(ts1.forces[sl], ts2.forces) def test_copy(self): if self.uni_args is None: return u = mda.Universe(*self.uni_args) ts = u.trajectory.ts yield self._check_copy, self.name, ts yield self._check_independent, self.name, ts yield self._check_copy_slice_indices, self.name, ts yield self._check_copy_slice_slice, self.name, ts yield self._check_npint_slice, self.name, ts def test_copy_slice(self): for p, v, f in itertools.product([True, False], repeat=3): if not any([p, v, f]): continue ts = self._from_coords(p, v, f) yield self._check_copy, self.name, ts yield self._check_independent, self.name, ts yield self._check_copy_slice_indices, self.name, ts yield self._check_copy_slice_slice, self.name, ts def _check_bad_slice(self, p, v, f): ts = self._from_coords(p, v, f) sl = ['this', 'is', 'silly'] assert_raises(TypeError, ts.copy_slice, sl) def test_bad_copy_slice(self): for p, v, f in itertools.product([True, False], repeat=3): if not any([p, v, f]): continue yield self._check_bad_slice, p, v, f def _get_pos(self): # Get generic reference positions return np.arange(30).reshape(10, 3) * 1.234 def _check_ts_equal(self, a, b, err_msg): assert_(a == b, err_msg) assert_(b == a, err_msg) def test_check_equal(self): for p, v, f in itertools.product([True, False], repeat=3): if not any([p, v, f]): continue ts1 = self.Timestep(self.size, positions=p, velocities=v, forces=f) ts2 = self.Timestep(self.size, positions=p, velocities=v, forces=f) if p: ts1.positions = self.refpos.copy() ts2.positions = self.refpos.copy() if v: ts1.velocities = self.refvel.copy() ts2.velocities = self.refvel.copy() if f: ts1.forces = self.reffor.copy() ts2.forces = self.reffor.copy() yield (self._check_ts_equal, ts1, ts2, 'Failed on {0}'.format(self.name)) def test_wrong_class_equality(self): ts1 = self.Timestep(self.size) ts1.positions = self._get_pos() b = tuple([0, 1, 2, 3]) assert_(ts1 != b) assert_(b != ts1) def test_wrong_frame_equality(self): ts1 = self.Timestep(self.size) ts1.positions = self._get_pos() ts2 = self.Timestep(self.size) ts2.positions = self._get_pos() ts2.frame = 987 assert_(ts1 != ts2) assert_(ts2 != ts1) def test_wrong_n_atoms_equality(self): ts1 = self.Timestep(self.size) ts1.positions = self._get_pos() ts3 = self.Timestep(self.size * 2) assert_(ts1 != ts3) assert_(ts3 != ts1) def test_wrong_pos_equality(self): ts1 = self.Timestep(self.size) ts1.positions = self._get_pos() ts2 = self.Timestep(self.size) ts2.positions = self._get_pos() + 1.0 assert_(ts1 != ts2) assert_(ts2 != ts1) def test_check_vels_equality(self): ts1 = self.Timestep(self.size, velocities=True) ts2 = self.Timestep(self.size, velocities=True) ts1.velocities = self._get_pos() ts2.velocities = self._get_pos() assert_(ts1 == ts2) assert_(ts2 == ts1) def test_check_mismatched_vels_equality(self): ts1 = self.Timestep(self.size, velocities=True) ts2 = self.Timestep(self.size, velocities=False) ts1.velocities = self._get_pos() assert_(ts1 != ts2) assert_(ts2 != ts1) def test_check_wrong_vels_equality(self): ts1 = self.Timestep(self.size, velocities=True) ts2 = self.Timestep(self.size, velocities=True) ts1.velocities = self._get_pos() ts2.velocities = self._get_pos() + 1.0 assert_(ts1 != ts2) assert_(ts2 != ts1) def test_check_forces_equality(self): ts1 = self.Timestep(self.size, forces=True) ts2 = self.Timestep(self.size, forces=True) ts1.forces = self._get_pos() ts2.forces = self._get_pos() assert_(ts1 == ts2) assert_(ts2 == ts1) def test_check_mismatched_forces_equality(self): ts1 = self.Timestep(self.size, forces=True) ts2 = self.Timestep(self.size, forces=False) ts1.forces = self._get_pos() assert_(ts1 != ts2) assert_(ts2 != ts1) def test_check_wrong_forces_equality(self): ts1 = self.Timestep(self.size, forces=True) ts2 = self.Timestep(self.size, forces=True) ts1.forces = self._get_pos() ts2.forces = self._get_pos() + 1.0 assert_(ts1 != ts2) assert_(ts2 != ts1) def assert_timestep_almost_equal(A, B, decimal=6, verbose=True): if not isinstance(A, Timestep): raise AssertionError('A is not of type Timestep') if not isinstance(B, Timestep): raise AssertionError('B is not of type Timestep') if A.frame != B.frame: raise AssertionError('A and B refer to different frames: ' 'A.frame = {}, B.frame={}'.format( A.frame, B.frame)) if A.time != B.time: raise AssertionError('A and B refer to different times: ' 'A.time = {}, B.time={}'.format( A.time, B.time)) if A.n_atoms != B.n_atoms: raise AssertionError('A and B have a differnent number of atoms: ' 'A.n_atoms = {}, B.n_atoms = {}'.format( A.n_atoms, B.n_atoms)) if A.has_positions != B.has_positions: raise AssertionError('Only one Timestep has positions:' 'A.has_positions = {}, B.has_positions = {}'.format( A.has_positions, B.has_positions)) if A.has_positions: assert_array_almost_equal(A.positions, B.positions, decimal=decimal, err_msg='Timestep positions', verbose=verbose) if A.has_velocities != B.has_velocities: raise AssertionError('Only one Timestep has velocities:' 'A.has_velocities = {}, B.has_velocities = {}'.format( A.has_velocities, B.has_velocities)) if A.has_velocities: assert_array_almost_equal(A.velocities, B.velocities, decimal=decimal, err_msg='Timestep velocities', verbose=verbose) if A.has_forces != B.has_forces: raise AssertionError('Only one Timestep has forces:' 'A.has_forces = {}, B.has_forces = {}'.format( A.has_forces, B.has_forces)) if A.has_forces: assert_array_almost_equal(A.forces, B.forces, decimal=decimal, err_msg='Timestep forces', verbose=verbose) # Check we've got auxiliaries before comparing values (auxiliaries aren't written # so we won't have aux values to compare when testing writer) if len(A.aux) > 0 and len(B.aux) > 0: assert_equal(A.aux, B.aux, err_msg='Auxiliary values do not match: ' 'A.aux = {}, B.aux = {}'.format(A.aux, B.aux))
alejob/mdanalysis
testsuite/MDAnalysisTests/coordinates/base.py
Python
gpl-2.0
40,567
[ "MDAnalysis" ]
a534e14aab044bd4fb9491b0aca4679f96373d62744f6a373dba20042860d979
from __future__ import absolute_import from typing import Any, Dict, List, Set, Tuple, TypeVar, Text, \ Union, Optional, Sequence, AbstractSet, Pattern, AnyStr from typing.re import Match from zerver.lib.str_utils import NonBinaryStr from django.db import models from django.db.models.query import QuerySet from django.db.models import Manager from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, UserManager, \ PermissionsMixin import django.contrib.auth from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.dispatch import receiver from zerver.lib.cache import cache_with_key, flush_user_profile, flush_realm, \ user_profile_by_id_cache_key, user_profile_by_email_cache_key, \ generic_bulk_cached_fetch, cache_set, flush_stream, \ display_recipient_cache_key, cache_delete, \ get_stream_cache_key, active_user_dicts_in_realm_cache_key, \ active_bot_dicts_in_realm_cache_key, active_user_dict_fields, \ active_bot_dict_fields, flush_message from zerver.lib.utils import make_safe_digest, generate_random_token from zerver.lib.str_utils import ModelReprMixin from django.db import transaction from zerver.lib.camo import get_camo_url from django.utils import timezone from django.contrib.sessions.models import Session from zerver.lib.timestamp import datetime_to_timestamp from django.db.models.signals import pre_save, post_save, post_delete from django.core.validators import MinLengthValidator, RegexValidator from django.utils.translation import ugettext_lazy as _ from zerver.lib import cache from bitfield import BitField from bitfield.types import BitHandler from collections import defaultdict from datetime import timedelta import pylibmc import re import logging import sre_constants import time import datetime MAX_SUBJECT_LENGTH = 60 MAX_MESSAGE_LENGTH = 10000 MAX_LANGUAGE_ID_LENGTH = 50 # type: int STREAM_NAMES = TypeVar('STREAM_NAMES', Sequence[Text], AbstractSet[Text]) # Doing 1000 remote cache requests to get_display_recipient is quite slow, # so add a local cache as well as the remote cache cache. per_request_display_recipient_cache = {} # type: Dict[int, List[Dict[str, Any]]] def get_display_recipient_by_id(recipient_id, recipient_type, recipient_type_id): # type: (int, int, int) -> Union[Text, List[Dict[str, Any]]] if recipient_id not in per_request_display_recipient_cache: result = get_display_recipient_remote_cache(recipient_id, recipient_type, recipient_type_id) per_request_display_recipient_cache[recipient_id] = result return per_request_display_recipient_cache[recipient_id] def get_display_recipient(recipient): # type: (Recipient) -> Union[Text, List[Dict[str, Any]]] return get_display_recipient_by_id( recipient.id, recipient.type, recipient.type_id ) def flush_per_request_caches(): # type: () -> None global per_request_display_recipient_cache per_request_display_recipient_cache = {} global per_request_realm_filters_cache per_request_realm_filters_cache = {} @cache_with_key(lambda *args: display_recipient_cache_key(args[0]), timeout=3600*24*7) def get_display_recipient_remote_cache(recipient_id, recipient_type, recipient_type_id): # type: (int, int, int) -> Union[Text, List[Dict[str, Any]]] """ returns: an appropriate object describing the recipient. For a stream this will be the stream name as a string. For a huddle or personal, it will be an array of dicts about each recipient. """ if recipient_type == Recipient.STREAM: stream = Stream.objects.get(id=recipient_type_id) return stream.name # We don't really care what the ordering is, just that it's deterministic. user_profile_list = (UserProfile.objects.filter(subscription__recipient_id=recipient_id) .select_related() .order_by('email')) return [{'email': user_profile.email, 'domain': user_profile.realm.domain, 'full_name': user_profile.full_name, 'short_name': user_profile.short_name, 'id': user_profile.id, 'is_mirror_dummy': user_profile.is_mirror_dummy} for user_profile in user_profile_list] def get_realm_emoji_cache_key(realm): # type: (Realm) -> Text return u'realm_emoji:%s' % (realm.id,) class Realm(ModelReprMixin, models.Model): # domain is a domain in the Internet sense. It must be structured like a # valid email domain. We use is to restrict access, identify bots, etc. domain = models.CharField(max_length=40, db_index=True, unique=True) # type: Text # name is the user-visible identifier for the realm. It has no required # structure. AUTHENTICATION_FLAGS = [u'Google', u'Email', u'GitHub', u'LDAP', u'Dev', u'RemoteUser'] name = models.CharField(max_length=40, null=True) # type: Optional[Text] string_id = models.CharField(max_length=40, unique=True) # type: Text restricted_to_domain = models.BooleanField(default=False) # type: bool invite_required = models.BooleanField(default=True) # type: bool invite_by_admins_only = models.BooleanField(default=False) # type: bool create_stream_by_admins_only = models.BooleanField(default=False) # type: bool add_emoji_by_admins_only = models.BooleanField(default=False) # type: bool mandatory_topics = models.BooleanField(default=False) # type: bool show_digest_email = models.BooleanField(default=True) # type: bool name_changes_disabled = models.BooleanField(default=False) # type: bool allow_message_editing = models.BooleanField(default=True) # type: bool DEFAULT_MESSAGE_CONTENT_EDIT_LIMIT_SECONDS = 600 # if changed, also change in admin.js message_content_edit_limit_seconds = models.IntegerField(default=DEFAULT_MESSAGE_CONTENT_EDIT_LIMIT_SECONDS) # type: int message_retention_days = models.IntegerField(null=True) # type: Optional[int] # Valid org_types are {CORPORATE, COMMUNITY} CORPORATE = 1 COMMUNITY = 2 org_type = models.PositiveSmallIntegerField(default=COMMUNITY) # type: int date_created = models.DateTimeField(default=timezone.now) # type: datetime.datetime notifications_stream = models.ForeignKey('Stream', related_name='+', null=True, blank=True) # type: Optional[Stream] deactivated = models.BooleanField(default=False) # type: bool default_language = models.CharField(default=u'en', max_length=MAX_LANGUAGE_ID_LENGTH) # type: Text authentication_methods = BitField(flags=AUTHENTICATION_FLAGS, default=2**31 - 1) # type: BitHandler waiting_period_threshold = models.PositiveIntegerField(default=0) # type: int DEFAULT_NOTIFICATION_STREAM_NAME = u'announce' def authentication_methods_dict(self): # type: () -> Dict[Text, bool] """Returns the a mapping from authentication flags to their status, showing only those authentication flags that are supported on the current server (i.e. if EmailAuthBackend is not configured on the server, this will not return an entry for "Email").""" # This mapping needs to be imported from here due to the cyclic # dependency. from zproject.backends import AUTH_BACKEND_NAME_MAP ret = {} # type: Dict[Text, bool] supported_backends = {backend.__class__ for backend in django.contrib.auth.get_backends()} for k, v in self.authentication_methods.iteritems(): backend = AUTH_BACKEND_NAME_MAP[k] if backend in supported_backends: ret[k] = v return ret def __unicode__(self): # type: () -> Text return u"<Realm: %s %s>" % (self.domain, self.id) @cache_with_key(get_realm_emoji_cache_key, timeout=3600*24*7) def get_emoji(self): # type: () -> Dict[Text, Dict[str, Text]] return get_realm_emoji_uncached(self) @property def deployment(self): # type: () -> Any # returns a Deployment from zilencer.models # see https://github.com/zulip/zulip/issues/1845 before you # attempt to add test coverage for this method, as we may # be revisiting the deployments model soon try: return self._deployments.all()[0] except IndexError: return None @deployment.setter # type: ignore # https://github.com/python/mypy/issues/220 def set_deployments(self, value): # type: (Any) -> None self._deployments = [value] # type: Any def get_admin_users(self): # type: () -> Sequence[UserProfile] # TODO: Change return type to QuerySet[UserProfile] return UserProfile.objects.filter(realm=self, is_realm_admin=True, is_active=True).select_related() def get_active_users(self): # type: () -> Sequence[UserProfile] # TODO: Change return type to QuerySet[UserProfile] return UserProfile.objects.filter(realm=self, is_active=True).select_related() @property def subdomain(self): # type: () -> Text if settings.REALMS_HAVE_SUBDOMAINS: return self.string_id return None @property def uri(self): # type: () -> str if settings.REALMS_HAVE_SUBDOMAINS and self.subdomain is not None: return '%s%s.%s' % (settings.EXTERNAL_URI_SCHEME, self.subdomain, settings.EXTERNAL_HOST) return settings.SERVER_URI @property def host(self): # type: () -> str if settings.REALMS_HAVE_SUBDOMAINS and self.subdomain is not None: return "%s.%s" % (self.subdomain, settings.EXTERNAL_HOST) return settings.EXTERNAL_HOST @property def is_zephyr_mirror_realm(self): # type: () -> bool return self.domain == "mit.edu" @property def webathena_enabled(self): # type: () -> bool return self.is_zephyr_mirror_realm @property def presence_disabled(self): # type: () -> bool return self.is_zephyr_mirror_realm class Meta(object): permissions = ( ('administer', "Administer a realm"), ('api_super_user', "Can send messages as other users for mirroring"), ) post_save.connect(flush_realm, sender=Realm) def get_realm(string_id): # type: (Text) -> Optional[Realm] return Realm.objects.filter(string_id=string_id).first() def completely_open(realm): # type: (Realm) -> bool # This realm is completely open to everyone on the internet to # join. E-mail addresses do not need to match a realmalias and # an invite from an existing user is not required. if not realm: return False return not realm.invite_required and not realm.restricted_to_domain def get_unique_open_realm(): # type: () -> Optional[Realm] """We only return a realm if there is a unique non-system-only realm, it is completely open, and there are no subdomains.""" if settings.REALMS_HAVE_SUBDOMAINS: return None realms = Realm.objects.filter(deactivated=False) # On production installations, the (usually "zulip.com") system # realm is an empty realm just used for system bots, so don't # include it in this accounting. realms = realms.exclude(string_id__in=settings.SYSTEM_ONLY_REALMS) if len(realms) != 1: return None realm = realms[0] if realm.invite_required or realm.restricted_to_domain: return None return realm def name_changes_disabled(realm): # type: (Optional[Realm]) -> bool if realm is None: return settings.NAME_CHANGES_DISABLED return settings.NAME_CHANGES_DISABLED or realm.name_changes_disabled class RealmAlias(models.Model): realm = models.ForeignKey(Realm, null=True) # type: Optional[Realm] # should always be stored lowercase domain = models.CharField(max_length=80, db_index=True) # type: Text def can_add_alias(domain): # type: (Text) -> bool if settings.REALMS_HAVE_SUBDOMAINS: return True if RealmAlias.objects.filter(domain=domain).exists(): return False return True # These functions should only be used on email addresses that have # been validated via django.core.validators.validate_email # # Note that we need to use some care, since can you have multiple @-signs; e.g. # "tabbott@test"@zulip.com # is valid email address def email_to_username(email): # type: (Text) -> Text return "@".join(email.split("@")[:-1]).lower() # Returns the raw domain portion of the desired email address def email_to_domain(email): # type: (Text) -> Text return email.split("@")[-1].lower() class GetRealmByDomainException(Exception): pass def get_realm_by_email_domain(email): # type: (Text) -> Optional[Realm] if settings.REALMS_HAVE_SUBDOMAINS: raise GetRealmByDomainException( "Cannot get realm from email domain when settings.REALMS_HAVE_SUBDOMAINS = True") try: alias = RealmAlias.objects.select_related('realm').get(domain = email_to_domain(email)) return alias.realm except RealmAlias.DoesNotExist: return None # Is a user with the given email address allowed to be in the given realm? # (This function does not check whether the user has been invited to the realm. # So for invite-only realms, this is the test for whether a user can be invited, # not whether the user can sign up currently.) def email_allowed_for_realm(email, realm): # type: (Text, Realm) -> bool if not realm.restricted_to_domain: return True domain = email_to_domain(email) return RealmAlias.objects.filter(realm = realm, domain = domain).exists() def list_of_domains_for_realm(realm): # type: (Realm) -> List[Text] return list(RealmAlias.objects.filter(realm=realm).values('domain')) class RealmEmoji(ModelReprMixin, models.Model): author = models.ForeignKey('UserProfile', blank=True, null=True) realm = models.ForeignKey(Realm) # type: Realm # Second part of the regex (negative lookbehind) disallows names ending with one of the punctuation characters name = models.TextField(validators=[MinLengthValidator(1), RegexValidator(regex=r'^[0-9a-zA-Z.\-_]+(?<![.\-_])$', message=_("Invalid characters in emoji name"))]) # type: Text # URLs start having browser compatibility problem below 2000 # characters, so 1000 seems like a safe limit. img_url = models.URLField(max_length=1000) # type: Text class Meta(object): unique_together = ("realm", "name") def __unicode__(self): # type: () -> Text return u"<RealmEmoji(%s): %s %s>" % (self.realm.domain, self.name, self.img_url) def get_realm_emoji_uncached(realm): # type: (Realm) -> Dict[Text, Dict[str, Text]] d = {} for row in RealmEmoji.objects.filter(realm=realm).select_related('author'): if row.author: author = { 'id': row.author.id, 'email': row.author.email, 'full_name': row.author.full_name} else: author = None d[row.name] = dict(source_url=row.img_url, display_url=get_camo_url(row.img_url), author=author) return d def flush_realm_emoji(sender, **kwargs): # type: (Any, **Any) -> None realm = kwargs['instance'].realm cache_set(get_realm_emoji_cache_key(realm), get_realm_emoji_uncached(realm), timeout=3600*24*7) post_save.connect(flush_realm_emoji, sender=RealmEmoji) post_delete.connect(flush_realm_emoji, sender=RealmEmoji) def filter_pattern_validator(value): # type: (Text) -> None regex = re.compile(r'(?:[\w\-#]*)(\(\?P<\w+>.+\))') error_msg = 'Invalid filter pattern, you must use the following format OPTIONAL_PREFIX(?P<id>.+)' if not regex.match(str(value)): raise ValidationError(error_msg) try: re.compile(value) except sre_constants.error: # Regex is invalid raise ValidationError(error_msg) def filter_format_validator(value): # type: (str) -> None regex = re.compile(r'^[\.\/:a-zA-Z0-9_-]+%\(([a-zA-Z0-9_-]+)\)s[a-zA-Z0-9_-]*$') if not regex.match(value): raise ValidationError('URL format string must be in the following format: `https://example.com/%(\w+)s`') class RealmFilter(models.Model): realm = models.ForeignKey(Realm) # type: Realm pattern = models.TextField(validators=[filter_pattern_validator]) # type: Text url_format_string = models.TextField(validators=[URLValidator, filter_format_validator]) # type: Text class Meta(object): unique_together = ("realm", "pattern") def __unicode__(self): # type: () -> Text return u"<RealmFilter(%s): %s %s>" % (self.realm.domain, self.pattern, self.url_format_string) def get_realm_filters_cache_key(realm_id): # type: (int) -> Text return u'all_realm_filters:%s' % (realm_id,) # We have a per-process cache to avoid doing 1000 remote cache queries during page load per_request_realm_filters_cache = {} # type: Dict[int, List[Tuple[Text, Text, int]]] def realm_in_local_realm_filters_cache(realm_id): # type: (int) -> bool return realm_id in per_request_realm_filters_cache def realm_filters_for_realm(realm_id): # type: (int) -> List[Tuple[Text, Text, int]] if not realm_in_local_realm_filters_cache(realm_id): per_request_realm_filters_cache[realm_id] = realm_filters_for_realm_remote_cache(realm_id) return per_request_realm_filters_cache[realm_id] @cache_with_key(get_realm_filters_cache_key, timeout=3600*24*7) def realm_filters_for_realm_remote_cache(realm_id): # type: (int) -> List[Tuple[Text, Text, int]] filters = [] for realm_filter in RealmFilter.objects.filter(realm_id=realm_id): filters.append((realm_filter.pattern, realm_filter.url_format_string, realm_filter.id)) return filters def all_realm_filters(): # type: () -> Dict[int, List[Tuple[Text, Text, int]]] filters = defaultdict(list) # type: Dict[int, List[Tuple[Text, Text, int]]] for realm_filter in RealmFilter.objects.all(): filters[realm_filter.realm_id].append((realm_filter.pattern, realm_filter.url_format_string, realm_filter.id)) return filters def flush_realm_filter(sender, **kwargs): # type: (Any, **Any) -> None realm_id = kwargs['instance'].realm_id cache_delete(get_realm_filters_cache_key(realm_id)) try: per_request_realm_filters_cache.pop(realm_id) except KeyError: pass post_save.connect(flush_realm_filter, sender=RealmFilter) post_delete.connect(flush_realm_filter, sender=RealmFilter) class UserProfile(ModelReprMixin, AbstractBaseUser, PermissionsMixin): DEFAULT_BOT = 1 """ Incoming webhook bots are limited to only sending messages via webhooks. Thus, it is less of a security risk to expose their API keys to third-party services, since they can't be used to read messages. """ INCOMING_WEBHOOK_BOT = 2 # Fields from models.AbstractUser minus last_name and first_name, # which we don't use; email is modified to make it indexed and unique. email = models.EmailField(blank=False, db_index=True, unique=True) # type: Text is_staff = models.BooleanField(default=False) # type: bool is_active = models.BooleanField(default=True, db_index=True) # type: bool is_realm_admin = models.BooleanField(default=False, db_index=True) # type: bool is_bot = models.BooleanField(default=False, db_index=True) # type: bool bot_type = models.PositiveSmallIntegerField(null=True, db_index=True) # type: Optional[int] is_api_super_user = models.BooleanField(default=False, db_index=True) # type: bool date_joined = models.DateTimeField(default=timezone.now) # type: datetime.datetime is_mirror_dummy = models.BooleanField(default=False) # type: bool bot_owner = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) # type: Optional[UserProfile] USERNAME_FIELD = 'email' MAX_NAME_LENGTH = 100 # Our custom site-specific fields full_name = models.CharField(max_length=MAX_NAME_LENGTH) # type: Text short_name = models.CharField(max_length=MAX_NAME_LENGTH) # type: Text # pointer points to Message.id, NOT UserMessage.id. pointer = models.IntegerField() # type: int last_pointer_updater = models.CharField(max_length=64) # type: Text realm = models.ForeignKey(Realm) # type: Realm api_key = models.CharField(max_length=32) # type: Text tos_version = models.CharField(null=True, max_length=10) # type: Text ### Notifications settings. ### # Stream notifications. enable_stream_desktop_notifications = models.BooleanField(default=False) # type: bool enable_stream_sounds = models.BooleanField(default=False) # type: bool # PM + @-mention notifications. enable_desktop_notifications = models.BooleanField(default=True) # type: bool pm_content_in_desktop_notifications = models.BooleanField(default=True) # type: bool enable_sounds = models.BooleanField(default=True) # type: bool enable_offline_email_notifications = models.BooleanField(default=True) # type: bool enable_offline_push_notifications = models.BooleanField(default=True) # type: bool enable_online_push_notifications = models.BooleanField(default=False) # type: bool enable_digest_emails = models.BooleanField(default=True) # type: bool # Old notification field superseded by existence of stream notification # settings. default_desktop_notifications = models.BooleanField(default=True) # type: bool ### last_reminder = models.DateTimeField(default=timezone.now, null=True) # type: Optional[datetime.datetime] rate_limits = models.CharField(default=u"", max_length=100) # type: Text # comma-separated list of range:max pairs # Default streams default_sending_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+') # type: Optional[Stream] default_events_register_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+') # type: Optional[Stream] default_all_public_streams = models.BooleanField(default=False) # type: bool # UI vars enter_sends = models.NullBooleanField(default=False) # type: Optional[bool] autoscroll_forever = models.BooleanField(default=False) # type: bool left_side_userlist = models.BooleanField(default=False) # type: bool # display settings twenty_four_hour_time = models.BooleanField(default=False) # type: bool default_language = models.CharField(default=u'en', max_length=MAX_LANGUAGE_ID_LENGTH) # type: Text # Hours to wait before sending another email to a user EMAIL_REMINDER_WAITPERIOD = 24 # Minutes to wait before warning a bot owner that her bot sent a message # to a nonexistent stream BOT_OWNER_STREAM_ALERT_WAITPERIOD = 1 AVATAR_FROM_GRAVATAR = u'G' AVATAR_FROM_USER = u'U' AVATAR_SOURCES = ( (AVATAR_FROM_GRAVATAR, 'Hosted by Gravatar'), (AVATAR_FROM_USER, 'Uploaded by user'), ) avatar_source = models.CharField(default=AVATAR_FROM_GRAVATAR, choices=AVATAR_SOURCES, max_length=1) # type: Text avatar_version = models.PositiveSmallIntegerField(default=1) # type: int TUTORIAL_WAITING = u'W' TUTORIAL_STARTED = u'S' TUTORIAL_FINISHED = u'F' TUTORIAL_STATES = ((TUTORIAL_WAITING, "Waiting"), (TUTORIAL_STARTED, "Started"), (TUTORIAL_FINISHED, "Finished")) tutorial_status = models.CharField(default=TUTORIAL_WAITING, choices=TUTORIAL_STATES, max_length=1) # type: Text # Contains serialized JSON of the form: # [("step 1", true), ("step 2", false)] # where the second element of each tuple is if the step has been # completed. onboarding_steps = models.TextField(default=u'[]') # type: Text invites_granted = models.IntegerField(default=0) # type: int invites_used = models.IntegerField(default=0) # type: int alert_words = models.TextField(default=u'[]') # type: Text # json-serialized list of strings # Contains serialized JSON of the form: # [["social", "mit"], ["devel", "ios"]] muted_topics = models.TextField(default=u'[]') # type: Text objects = UserManager() # type: UserManager def can_admin_user(self, target_user): # type: (UserProfile) -> bool """Returns whether this user has permission to modify target_user""" if target_user.bot_owner == self: return True elif self.is_realm_admin and self.realm == target_user.realm: return True else: return False def __unicode__(self): # type: () -> Text return u"<UserProfile: %s %s>" % (self.email, self.realm) @property def is_incoming_webhook(self): # type: () -> bool return self.bot_type == UserProfile.INCOMING_WEBHOOK_BOT @staticmethod def emails_from_ids(user_ids): # type: (Sequence[int]) -> Dict[int, Text] rows = UserProfile.objects.filter(id__in=user_ids).values('id', 'email') return {row['id']: row['email'] for row in rows} def can_create_streams(self): # type: () -> bool diff = (timezone.now() - self.date_joined).days if self.is_realm_admin: return True elif self.realm.create_stream_by_admins_only: return False if diff >= self.realm.waiting_period_threshold: return True return False def major_tos_version(self): # type: () -> int if self.tos_version is not None: return int(self.tos_version.split('.')[0]) else: return -1 def receives_offline_notifications(user_profile): # type: (UserProfile) -> bool return ((user_profile.enable_offline_email_notifications or user_profile.enable_offline_push_notifications) and not user_profile.is_bot) def receives_online_notifications(user_profile): # type: (UserProfile) -> bool return (user_profile.enable_online_push_notifications and not user_profile.is_bot) def remote_user_to_email(remote_user): # type: (Text) -> Text if settings.SSO_APPEND_DOMAIN is not None: remote_user += "@" + settings.SSO_APPEND_DOMAIN return remote_user # Make sure we flush the UserProfile object from our remote cache # whenever we save it. post_save.connect(flush_user_profile, sender=UserProfile) class PreregistrationUser(models.Model): email = models.EmailField() # type: Text referred_by = models.ForeignKey(UserProfile, null=True) # Optional[UserProfile] streams = models.ManyToManyField('Stream') # type: Manager invited_at = models.DateTimeField(auto_now=True) # type: datetime.datetime realm_creation = models.BooleanField(default=False) # status: whether an object has been confirmed. # if confirmed, set to confirmation.settings.STATUS_ACTIVE status = models.IntegerField(default=0) # type: int realm = models.ForeignKey(Realm, null=True) # type: Optional[Realm] class PushDeviceToken(models.Model): APNS = 1 GCM = 2 KINDS = ( (APNS, 'apns'), (GCM, 'gcm'), ) kind = models.PositiveSmallIntegerField(choices=KINDS) # type: int # The token is a unique device-specific token that is # sent to us from each device: # - APNS token if kind == APNS # - GCM registration id if kind == GCM token = models.CharField(max_length=4096, unique=True) # type: Text last_updated = models.DateTimeField(auto_now=True) # type: datetime.datetime # The user who's device this is user = models.ForeignKey(UserProfile, db_index=True) # type: UserProfile # [optional] Contains the app id of the device if it is an iOS device ios_app_id = models.TextField(null=True) # type: Optional[Text] def generate_email_token_for_stream(): # type: () -> Text return generate_random_token(32) class Stream(ModelReprMixin, models.Model): MAX_NAME_LENGTH = 60 name = models.CharField(max_length=MAX_NAME_LENGTH, db_index=True) # type: Text realm = models.ForeignKey(Realm, db_index=True) # type: Realm invite_only = models.NullBooleanField(default=False) # type: Optional[bool] # Used by the e-mail forwarder. The e-mail RFC specifies a maximum # e-mail length of 254, and our max stream length is 30, so we # have plenty of room for the token. email_token = models.CharField( max_length=32, default=generate_email_token_for_stream) # type: Text description = models.CharField(max_length=1024, default=u'') # type: Text date_created = models.DateTimeField(default=timezone.now) # type: datetime.datetime deactivated = models.BooleanField(default=False) # type: bool def __unicode__(self): # type: () -> Text return u"<Stream: %s>" % (self.name,) def is_public(self): # type: () -> bool # All streams are private in Zephyr mirroring realms. return not self.invite_only and not self.realm.is_zephyr_mirror_realm class Meta(object): unique_together = ("name", "realm") def num_subscribers(self): # type: () -> int return Subscription.objects.filter( recipient__type=Recipient.STREAM, recipient__type_id=self.id, user_profile__is_active=True, active=True ).count() # This is stream information that is sent to clients def to_dict(self): # type: () -> Dict[str, Any] return dict(name=self.name, stream_id=self.id, description=self.description, invite_only=self.invite_only) post_save.connect(flush_stream, sender=Stream) post_delete.connect(flush_stream, sender=Stream) # The Recipient table is used to map Messages to the set of users who # received the message. It is implemented as a set of triples (id, # type_id, type). We have 3 types of recipients: Huddles (for group # private messages), UserProfiles (for 1:1 private messages), and # Streams. The recipient table maps a globally unique recipient id # (used by the Message table) to the type-specific unique id (the # stream id, user_profile id, or huddle id). class Recipient(ModelReprMixin, models.Model): type_id = models.IntegerField(db_index=True) # type: int type = models.PositiveSmallIntegerField(db_index=True) # type: int # Valid types are {personal, stream, huddle} PERSONAL = 1 STREAM = 2 HUDDLE = 3 class Meta(object): unique_together = ("type", "type_id") # N.B. If we used Django's choice=... we would get this for free (kinda) _type_names = { PERSONAL: 'personal', STREAM: 'stream', HUDDLE: 'huddle'} def type_name(self): # type: () -> str # Raises KeyError if invalid return self._type_names[self.type] def __unicode__(self): # type: () -> Text display_recipient = get_display_recipient(self) return u"<Recipient: %s (%d, %s)>" % (display_recipient, self.type_id, self.type) class Client(ModelReprMixin, models.Model): name = models.CharField(max_length=30, db_index=True, unique=True) # type: Text def __unicode__(self): # type: () -> Text return u"<Client: %s>" % (self.name,) get_client_cache = {} # type: Dict[Text, Client] def get_client(name): # type: (Text) -> Client # Accessing KEY_PREFIX through the module is necessary # because we need the updated value of the variable. cache_name = cache.KEY_PREFIX + name if cache_name not in get_client_cache: result = get_client_remote_cache(name) get_client_cache[cache_name] = result return get_client_cache[cache_name] def get_client_cache_key(name): # type: (Text) -> Text return u'get_client:%s' % (make_safe_digest(name),) @cache_with_key(get_client_cache_key, timeout=3600*24*7) def get_client_remote_cache(name): # type: (Text) -> Client (client, _) = Client.objects.get_or_create(name=name) return client # get_stream_backend takes either a realm id or a realm @cache_with_key(get_stream_cache_key, timeout=3600*24*7) def get_stream_backend(stream_name, realm): # type: (Text, Realm) -> Stream return Stream.objects.select_related("realm").get( name__iexact=stream_name.strip(), realm_id=realm.id) def get_active_streams(realm): # type: (Realm) -> QuerySet """ Return all streams (including invite-only streams) that have not been deactivated. """ return Stream.objects.filter(realm=realm, deactivated=False) def get_stream(stream_name, realm): # type: (Text, Realm) -> Optional[Stream] try: return get_stream_backend(stream_name, realm) except Stream.DoesNotExist: return None def bulk_get_streams(realm, stream_names): # type: (Realm, STREAM_NAMES) -> Dict[Text, Any] def fetch_streams_by_name(stream_names): # type: (List[Text]) -> Sequence[Stream] # # This should be just # # Stream.objects.select_related("realm").filter(name__iexact__in=stream_names, # realm_id=realm_id) # # But chaining __in and __iexact doesn't work with Django's # ORM, so we have the following hack to construct the relevant where clause if len(stream_names) == 0: return [] upper_list = ", ".join(["UPPER(%s)"] * len(stream_names)) where_clause = "UPPER(zerver_stream.name::text) IN (%s)" % (upper_list,) return get_active_streams(realm.id).select_related("realm").extra( where=[where_clause], params=stream_names) return generic_bulk_cached_fetch(lambda stream_name: get_stream_cache_key(stream_name, realm), fetch_streams_by_name, [stream_name.lower() for stream_name in stream_names], id_fetcher=lambda stream: stream.name.lower()) def get_recipient_cache_key(type, type_id): # type: (int, int) -> Text return u"get_recipient:%s:%s" % (type, type_id,) @cache_with_key(get_recipient_cache_key, timeout=3600*24*7) def get_recipient(type, type_id): # type: (int, int) -> Recipient return Recipient.objects.get(type_id=type_id, type=type) def bulk_get_recipients(type, type_ids): # type: (int, List[int]) -> Dict[int, Any] def cache_key_function(type_id): # type: (int) -> Text return get_recipient_cache_key(type, type_id) def query_function(type_ids): # type: (List[int]) -> Sequence[Recipient] # TODO: Change return type to QuerySet[Recipient] return Recipient.objects.filter(type=type, type_id__in=type_ids) return generic_bulk_cached_fetch(cache_key_function, query_function, type_ids, id_fetcher=lambda recipient: recipient.type_id) def sew_messages_and_reactions(messages, reactions): # type: (List[Dict[str, Any]], List[Dict[str, Any]]) -> List[Dict[str, Any]] """Given a iterable of messages and reactions stitch reactions into messages. """ # Add all messages with empty reaction item for message in messages: message['reactions'] = [] # Convert list of messages into dictionary to make reaction stitching easy converted_messages = {message['id']: message for message in messages} for reaction in reactions: converted_messages[reaction['message_id']]['reactions'].append( reaction) return list(converted_messages.values()) class Message(ModelReprMixin, models.Model): sender = models.ForeignKey(UserProfile) # type: UserProfile recipient = models.ForeignKey(Recipient) # type: Recipient subject = models.CharField(max_length=MAX_SUBJECT_LENGTH, db_index=True) # type: Text content = models.TextField() # type: Text rendered_content = models.TextField(null=True) # type: Optional[Text] rendered_content_version = models.IntegerField(null=True) # type: Optional[int] pub_date = models.DateTimeField('date published', db_index=True) # type: datetime.datetime sending_client = models.ForeignKey(Client) # type: Client last_edit_time = models.DateTimeField(null=True) # type: Optional[datetime.datetime] edit_history = models.TextField(null=True) # type: Optional[Text] has_attachment = models.BooleanField(default=False, db_index=True) # type: bool has_image = models.BooleanField(default=False, db_index=True) # type: bool has_link = models.BooleanField(default=False, db_index=True) # type: bool def topic_name(self): # type: () -> Text """ Please start using this helper to facilitate an eventual switch over to a separate topic table. """ return self.subject def __unicode__(self): # type: () -> Text display_recipient = get_display_recipient(self.recipient) return u"<Message: %s / %s / %r>" % (display_recipient, self.subject, self.sender) def get_realm(self): # type: () -> Realm return self.sender.realm def save_rendered_content(self): # type: () -> None self.save(update_fields=["rendered_content", "rendered_content_version"]) @staticmethod def need_to_render_content(rendered_content, rendered_content_version, bugdown_version): # type: (Optional[Text], int, int) -> bool return rendered_content is None or rendered_content_version < bugdown_version def to_log_dict(self): # type: () -> Dict[str, Any] return dict( id = self.id, sender_id = self.sender.id, sender_email = self.sender.email, sender_domain = self.sender.realm.domain, sender_full_name = self.sender.full_name, sender_short_name = self.sender.short_name, sending_client = self.sending_client.name, type = self.recipient.type_name(), recipient = get_display_recipient(self.recipient), subject = self.topic_name(), content = self.content, timestamp = datetime_to_timestamp(self.pub_date)) @staticmethod def get_raw_db_rows(needed_ids): # type: (List[int]) -> List[Dict[str, Any]] # This is a special purpose function optimized for # callers like get_old_messages_backend(). fields = [ 'id', 'subject', 'pub_date', 'last_edit_time', 'edit_history', 'content', 'rendered_content', 'rendered_content_version', 'recipient_id', 'recipient__type', 'recipient__type_id', 'sender_id', 'sending_client__name', 'sender__email', 'sender__full_name', 'sender__short_name', 'sender__realm__id', 'sender__realm__domain', 'sender__avatar_source', 'sender__is_mirror_dummy', ] messages = Message.objects.filter(id__in=needed_ids).values(*fields) """Adding one-many or Many-Many relationship in values results in N X results. Link: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values """ reactions = Reaction.get_raw_db_rows(needed_ids) return sew_messages_and_reactions(messages, reactions) def sent_by_human(self): # type: () -> bool sending_client = self.sending_client.name.lower() return (sending_client in ('zulipandroid', 'zulipios', 'zulipdesktop', 'website', 'ios', 'android')) or ( 'desktop app' in sending_client) @staticmethod def content_has_attachment(content): # type: (Text) -> Match return re.search(r'[/\-]user[\-_]uploads[/\.-]', content) @staticmethod def content_has_image(content): # type: (Text) -> bool return bool(re.search(r'[/\-]user[\-_]uploads[/\.-]\S+\.(bmp|gif|jpg|jpeg|png|webp)', content, re.IGNORECASE)) @staticmethod def content_has_link(content): # type: (Text) -> bool return ('http://' in content or 'https://' in content or '/user_uploads' in content or (settings.ENABLE_FILE_LINKS and 'file:///' in content)) @staticmethod def is_status_message(content, rendered_content): # type: (Text, Text) -> bool """ Returns True if content and rendered_content are from 'me_message' """ if content.startswith('/me ') and '\n' not in content: if rendered_content.startswith('<p>') and rendered_content.endswith('</p>'): return True return False def update_calculated_fields(self): # type: () -> None # TODO: rendered_content could also be considered a calculated field content = self.content self.has_attachment = bool(Message.content_has_attachment(content)) self.has_image = bool(Message.content_has_image(content)) self.has_link = bool(Message.content_has_link(content)) @receiver(pre_save, sender=Message) def pre_save_message(sender, **kwargs): # type: (Any, **Any) -> None if kwargs['update_fields'] is None or "content" in kwargs['update_fields']: message = kwargs['instance'] message.update_calculated_fields() def get_context_for_message(message): # type: (Message) -> Sequence[Message] # TODO: Change return type to QuerySet[Message] return Message.objects.filter( recipient_id=message.recipient_id, subject=message.subject, id__lt=message.id, pub_date__gt=message.pub_date - timedelta(minutes=15), ).order_by('-id')[:10] post_save.connect(flush_message, sender=Message) class Reaction(ModelReprMixin, models.Model): user_profile = models.ForeignKey(UserProfile) # type: UserProfile message = models.ForeignKey(Message) # type: Message emoji_name = models.TextField() # type: Text class Meta(object): unique_together = ("user_profile", "message", "emoji_name") @staticmethod def get_raw_db_rows(needed_ids): # type: (List[int]) -> List[Dict[str, Any]] fields = ['message_id', 'emoji_name', 'user_profile__email', 'user_profile__id', 'user_profile__full_name'] return Reaction.objects.filter(message_id__in=needed_ids).values(*fields) # Whenever a message is sent, for each user current subscribed to the # corresponding Recipient object, we add a row to the UserMessage # table, which has has columns (id, user profile id, message id, # flags) indicating which messages each user has received. This table # allows us to quickly query any user's last 1000 messages to generate # the home view. # # Additionally, the flags field stores metadata like whether the user # has read the message, starred the message, collapsed or was # mentioned the message, etc. # # UserMessage is the largest table in a Zulip installation, even # though each row is only 4 integers. class UserMessage(ModelReprMixin, models.Model): user_profile = models.ForeignKey(UserProfile) # type: UserProfile message = models.ForeignKey(Message) # type: Message # We're not using the archived field for now, but create it anyway # since this table will be an unpleasant one to do schema changes # on later ALL_FLAGS = ['read', 'starred', 'collapsed', 'mentioned', 'wildcard_mentioned', 'summarize_in_home', 'summarize_in_stream', 'force_expand', 'force_collapse', 'has_alert_word', "historical", 'is_me_message'] flags = BitField(flags=ALL_FLAGS, default=0) # type: BitHandler class Meta(object): unique_together = ("user_profile", "message") def __unicode__(self): # type: () -> Text display_recipient = get_display_recipient(self.message.recipient) return u"<UserMessage: %s / %s (%s)>" % (display_recipient, self.user_profile.email, self.flags_list()) def flags_list(self): # type: () -> List[str] return [flag for flag in self.flags.keys() if getattr(self.flags, flag).is_set] def parse_usermessage_flags(val): # type: (int) -> List[str] flags = [] mask = 1 for flag in UserMessage.ALL_FLAGS: if val & mask: flags.append(flag) mask <<= 1 return flags class Attachment(ModelReprMixin, models.Model): file_name = models.TextField(db_index=True) # type: Text # path_id is a storage location agnostic representation of the path of the file. # If the path of a file is http://localhost:9991/user_uploads/a/b/abc/temp_file.py # then its path_id will be a/b/abc/temp_file.py. path_id = models.TextField(db_index=True) # type: Text owner = models.ForeignKey(UserProfile) # type: UserProfile realm = models.ForeignKey(Realm, blank=True, null=True) # type: Realm is_realm_public = models.BooleanField(default=False) # type: bool messages = models.ManyToManyField(Message) # type: Manager create_time = models.DateTimeField(default=timezone.now, db_index=True) # type: datetime.datetime def __unicode__(self): # type: () -> Text return u"<Attachment: %s>" % (self.file_name,) def is_claimed(self): # type: () -> bool return self.messages.count() > 0 def get_old_unclaimed_attachments(weeks_ago): # type: (int) -> Sequence[Attachment] # TODO: Change return type to QuerySet[Attachment] delta_weeks_ago = timezone.now() - datetime.timedelta(weeks=weeks_ago) old_attachments = Attachment.objects.filter(messages=None, create_time__lt=delta_weeks_ago) return old_attachments class Subscription(ModelReprMixin, models.Model): user_profile = models.ForeignKey(UserProfile) # type: UserProfile recipient = models.ForeignKey(Recipient) # type: Recipient active = models.BooleanField(default=True) # type: bool in_home_view = models.NullBooleanField(default=True) # type: Optional[bool] DEFAULT_STREAM_COLOR = u"#c2c2c2" color = models.CharField(max_length=10, default=DEFAULT_STREAM_COLOR) # type: Text pin_to_top = models.BooleanField(default=False) # type: bool desktop_notifications = models.BooleanField(default=True) # type: bool audible_notifications = models.BooleanField(default=True) # type: bool # Combination desktop + audible notifications superseded by the # above. notifications = models.BooleanField(default=False) # type: bool class Meta(object): unique_together = ("user_profile", "recipient") def __unicode__(self): # type: () -> Text return u"<Subscription: %r -> %s>" % (self.user_profile, self.recipient) @cache_with_key(user_profile_by_id_cache_key, timeout=3600*24*7) def get_user_profile_by_id(uid): # type: (int) -> UserProfile return UserProfile.objects.select_related().get(id=uid) @cache_with_key(user_profile_by_email_cache_key, timeout=3600*24*7) def get_user_profile_by_email(email): # type: (Text) -> UserProfile return UserProfile.objects.select_related().get(email__iexact=email.strip()) @cache_with_key(active_user_dicts_in_realm_cache_key, timeout=3600*24*7) def get_active_user_dicts_in_realm(realm): # type: (Realm) -> List[Dict[str, Any]] return UserProfile.objects.filter(realm=realm, is_active=True) \ .values(*active_user_dict_fields) @cache_with_key(active_bot_dicts_in_realm_cache_key, timeout=3600*24*7) def get_active_bot_dicts_in_realm(realm): # type: (Realm) -> List[Dict[str, Any]] return UserProfile.objects.filter(realm=realm, is_active=True, is_bot=True) \ .values(*active_bot_dict_fields) def get_owned_bot_dicts(user_profile, include_all_realm_bots_if_admin=True): # type: (UserProfile, bool) -> List[Dict[str, Any]] if user_profile.is_realm_admin and include_all_realm_bots_if_admin: result = get_active_bot_dicts_in_realm(user_profile.realm) else: result = UserProfile.objects.filter(realm=user_profile.realm, is_active=True, is_bot=True, bot_owner=user_profile).values(*active_bot_dict_fields) # TODO: Remove this import cycle from zerver.lib.avatar import get_avatar_url return [{'email': botdict['email'], 'user_id': botdict['id'], 'full_name': botdict['full_name'], 'api_key': botdict['api_key'], 'default_sending_stream': botdict['default_sending_stream__name'], 'default_events_register_stream': botdict['default_events_register_stream__name'], 'default_all_public_streams': botdict['default_all_public_streams'], 'owner': botdict['bot_owner__email'], 'avatar_url': get_avatar_url(botdict['avatar_source'], botdict['email']), } for botdict in result] def get_prereg_user_by_email(email): # type: (Text) -> PreregistrationUser # A user can be invited many times, so only return the result of the latest # invite. return PreregistrationUser.objects.filter(email__iexact=email.strip()).latest("invited_at") def get_cross_realm_emails(): # type: () -> Set[Text] return set(settings.CROSS_REALM_BOT_EMAILS) # The Huddle class represents a group of individuals who have had a # Group Private Message conversation together. The actual membership # of the Huddle is stored in the Subscription table just like with # Streams, and a hash of that list is stored in the huddle_hash field # below, to support efficiently mapping from a set of users to the # corresponding Huddle object. class Huddle(models.Model): # TODO: We should consider whether using # CommaSeparatedIntegerField would be better. huddle_hash = models.CharField(max_length=40, db_index=True, unique=True) # type: Text def get_huddle_hash(id_list): # type: (List[int]) -> Text id_list = sorted(set(id_list)) hash_key = ",".join(str(x) for x in id_list) return make_safe_digest(hash_key) def huddle_hash_cache_key(huddle_hash): # type: (Text) -> Text return u"huddle_by_hash:%s" % (huddle_hash,) def get_huddle(id_list): # type: (List[int]) -> Huddle huddle_hash = get_huddle_hash(id_list) return get_huddle_backend(huddle_hash, id_list) @cache_with_key(lambda huddle_hash, id_list: huddle_hash_cache_key(huddle_hash), timeout=3600*24*7) def get_huddle_backend(huddle_hash, id_list): # type: (Text, List[int]) -> Huddle with transaction.atomic(): (huddle, created) = Huddle.objects.get_or_create(huddle_hash=huddle_hash) if created: recipient = Recipient.objects.create(type_id=huddle.id, type=Recipient.HUDDLE) subs_to_create = [Subscription(recipient=recipient, user_profile=get_user_profile_by_id(user_profile_id)) for user_profile_id in id_list] Subscription.objects.bulk_create(subs_to_create) return huddle def clear_database(): # type: () -> None pylibmc.Client(['127.0.0.1']).flush_all() model = None # type: Any for model in [Message, Stream, UserProfile, Recipient, Realm, Subscription, Huddle, UserMessage, Client, DefaultStream]: model.objects.all().delete() Session.objects.all().delete() class UserActivity(models.Model): user_profile = models.ForeignKey(UserProfile) # type: UserProfile client = models.ForeignKey(Client) # type: Client query = models.CharField(max_length=50, db_index=True) # type: Text count = models.IntegerField() # type: int last_visit = models.DateTimeField('last visit') # type: datetime.datetime class Meta(object): unique_together = ("user_profile", "client", "query") class UserActivityInterval(models.Model): user_profile = models.ForeignKey(UserProfile) # type: UserProfile start = models.DateTimeField('start time', db_index=True) # type: datetime.datetime end = models.DateTimeField('end time', db_index=True) # type: datetime.datetime class UserPresence(models.Model): user_profile = models.ForeignKey(UserProfile) # type: UserProfile client = models.ForeignKey(Client) # type: Client # Valid statuses ACTIVE = 1 IDLE = 2 timestamp = models.DateTimeField('presence changed') # type: datetime.datetime status = models.PositiveSmallIntegerField(default=ACTIVE) # type: int @staticmethod def status_to_string(status): # type: (int) -> str if status == UserPresence.ACTIVE: return 'active' elif status == UserPresence.IDLE: return 'idle' @staticmethod def get_status_dict_by_realm(realm_id): # type: (int) -> defaultdict[Any, Dict[Any, Any]] user_statuses = defaultdict(dict) # type: defaultdict[Any, Dict[Any, Any]] query = UserPresence.objects.filter( user_profile__realm_id=realm_id, user_profile__is_active=True, user_profile__is_bot=False ).values( 'client__name', 'status', 'timestamp', 'user_profile__email', 'user_profile__id', 'user_profile__enable_offline_push_notifications', 'user_profile__is_mirror_dummy', ) mobile_user_ids = [row['user'] for row in PushDeviceToken.objects.filter( user__realm_id=1, user__is_active=True, user__is_bot=False, ).distinct("user").values("user")] for row in query: info = UserPresence.to_presence_dict( client_name=row['client__name'], status=row['status'], dt=row['timestamp'], push_enabled=row['user_profile__enable_offline_push_notifications'], has_push_devices=row['user_profile__id'] in mobile_user_ids, is_mirror_dummy=row['user_profile__is_mirror_dummy'], ) user_statuses[row['user_profile__email']][row['client__name']] = info return user_statuses @staticmethod def to_presence_dict(client_name=None, status=None, dt=None, push_enabled=None, has_push_devices=None, is_mirror_dummy=None): # type: (Optional[Text], Optional[int], Optional[datetime.datetime], Optional[bool], Optional[bool], Optional[bool]) -> Dict[str, Any] presence_val = UserPresence.status_to_string(status) timestamp = datetime_to_timestamp(dt) return dict( client=client_name, status=presence_val, timestamp=timestamp, pushable=(push_enabled and has_push_devices), ) def to_dict(self): # type: () -> Dict[str, Any] return UserPresence.to_presence_dict( client_name=self.client.name, status=self.status, dt=self.timestamp ) @staticmethod def status_from_string(status): # type: (NonBinaryStr) -> Optional[int] if status == 'active': status_val = UserPresence.ACTIVE elif status == 'idle': status_val = UserPresence.IDLE else: status_val = None return status_val class Meta(object): unique_together = ("user_profile", "client") class DefaultStream(models.Model): realm = models.ForeignKey(Realm) # type: Realm stream = models.ForeignKey(Stream) # type: Stream class Meta(object): unique_together = ("realm", "stream") class Referral(models.Model): user_profile = models.ForeignKey(UserProfile) # type: UserProfile email = models.EmailField(blank=False, null=False) # type: Text timestamp = models.DateTimeField(auto_now_add=True, null=False) # type: datetime.datetime # This table only gets used on Zulip Voyager instances # For reasons of deliverability (and sending from multiple email addresses), # we will still send from mandrill when we send things from the (staging.)zulip.com install class ScheduledJob(models.Model): scheduled_timestamp = models.DateTimeField(auto_now_add=False, null=False) # type: datetime.datetime type = models.PositiveSmallIntegerField() # type: int # Valid types are {email} # for EMAIL, filter_string is recipient_email EMAIL = 1 # JSON representation of the job's data. Be careful, as we are not relying on Django to do validation data = models.TextField() # type: Text # Kind if like a ForeignKey, but table is determined by type. filter_id = models.IntegerField(null=True) # type: Optional[int] filter_string = models.CharField(max_length=100) # type: Text
sharmaeklavya2/zulip
zerver/models.py
Python
apache-2.0
57,439
[ "VisIt" ]
ddc439026a251177e653c5a1b061c0c6ff521eec9c0b69443313f7397cf8d64a
#!/usr/bin/env python # Copyright (c) 2015-2018 # Jakub Krajniak (jkrajniak at gmail.com) # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import espressopp import mpi4py.MPI as MPI import os import sys import time import unittest as ut def remove_file(file_name): if os.path.exists(file_name): os.unlink(file_name) class TestDumpTopology(ut.TestCase): def setUp(self): self.h5md_file = 'output.h5' remove_file(self.h5md_file) self.system, self.integrator = espressopp.standard_system.Default((10., 10., 10.), dt=0.1) self.particles = [ (1, espressopp.Real3D(1,2,3), 1), (2, espressopp.Real3D(2,3,4), 2), (3, espressopp.Real3D(3,4,5), 3), (4, espressopp.Real3D(4,5,6), 4)] self.system.storage.addParticles(self.particles, 'id', 'pos', 'type') self.fpl = espressopp.FixedPairList(self.system.storage) self.fpl.addBonds([(1, 2), (2, 3)]) self.ftl = espressopp.FixedTripleList(self.system.storage) self.ftl.addTriples([(1, 2, 3)]) self.fql = espressopp.FixedQuadrupleList(self.system.storage) self.fql.addQuadruples([(1, 2, 3, 4)]) self.dump_h5md = espressopp.io.DumpH5MD( self.system, self.integrator, self.h5md_file, store_species=True, store_velocity=True, store_state=True) self.dump_topology = espressopp.io.DumpTopology(self.system, self.integrator, self.dump_h5md) self.dump_topology.observe_tuple(self.fpl, 'bonds_0') self.dump_topology.observe_triple(self.ftl, 'angles_0') self.dump_topology.observe_quadruple(self.fql, 'dihs_0') self.dump_topology.dump() ext_dump = espressopp.integrator.ExtAnalyze(self.dump_topology, 1) self.integrator.addExtension(ext_dump) def tearDown(self): remove_file(self.h5md_file) def test_datasets(self): self.dump_h5md.flush() self.dump_h5md.close() h5 = h5py.File(self.h5md_file, 'r') self.assertEqual(h5['/connectivity'].keys(), ['angles_0', 'bonds_0', 'dihs_0']) class TestDumpFPL(TestDumpTopology): def test_check_dynamic_list(self): """Checks if positions are written correctly.""" self.dump_h5md.dump() self.integrator.run(5) self.dump_h5md.dump() self.dump_topology.update() self.dump_h5md.flush() self.dump_h5md.close() h5 = h5py.File(self.h5md_file, 'r') for bond_list in h5['/connectivity/bonds_0/value']: self.assertListEqual(sorted(map(tuple, filter(lambda x: -1 not in x, bond_list))), [(1, 2), (2, 3)]) def test_check_dynamic_list_update(self): self.integrator.run(5) self.dump_topology.update() self.fpl.addBonds([(1, 4)]) self.integrator.run(5) self.dump_topology.update() self.dump_h5md.flush() self.dump_h5md.close() h5 = h5py.File(self.h5md_file, 'r') self.assertEqual(list(h5['/connectivity/bonds_0/step']), range(11)) for bond_list in h5['/connectivity/bonds_0/value'][:6]: self.assertListEqual( sorted(map(tuple, filter(lambda x: -1 not in x, bond_list))), [(1, 2), (2, 3)]) # Second part contains added pair (1, 4) for bond_list in h5['/connectivity/bonds_0/value'][6:]: self.assertListEqual( sorted(map(tuple, filter(lambda x: -1 not in x, bond_list))), [(1, 2), (1, 4), (2, 3)]) class TestDumpFTL(TestDumpTopology): def test_check_dynamic_list(self): """Checks if positions are written correctly.""" self.dump_h5md.dump() self.integrator.run(5) self.dump_h5md.dump() self.dump_topology.update() self.dump_h5md.flush() self.dump_h5md.close() h5 = h5py.File(self.h5md_file, 'r') for bond_list in h5['/connectivity/angles_0/value']: self.assertListEqual(sorted(map(tuple, filter(lambda x: -1 not in x, bond_list))), [(1, 2, 3)]) def test_check_dynamic_list_update(self): self.integrator.run(5) self.dump_topology.update() self.ftl.addTriples([(1, 4, 3)]) self.integrator.run(5) self.dump_topology.update() self.dump_h5md.flush() self.dump_h5md.close() h5 = h5py.File(self.h5md_file, 'r') self.assertEqual(list(h5['/connectivity/angles_0/step']), range(11)) for angle_list in h5['/connectivity/angles_0/value'][:6]: self.assertListEqual( sorted(map(tuple, filter(lambda x: -1 not in x, angle_list))), [(1, 2, 3)]) # Second part contains added pair (1, 4, 3) for angle_list in h5['/connectivity/angles_0/value'][6:]: self.assertListEqual( sorted(map(tuple, filter(lambda x: -1 not in x, angle_list))), [(1, 2, 3), (1, 4, 3)]) class TestDumpFQL(TestDumpTopology): def test_check_dynamic_list(self): """Checks if positions are written correctly.""" self.dump_h5md.dump() self.integrator.run(5) self.dump_h5md.dump() self.dump_topology.update() self.dump_h5md.flush() self.dump_h5md.close() h5 = h5py.File(self.h5md_file, 'r') for plist in h5['/connectivity/dihs_0/value']: self.assertListEqual(sorted(map(tuple, filter(lambda x: -1 not in x, plist))), [(2, 1, 3, 4)]) def test_check_dynamic_list_update(self): self.integrator.run(5) self.dump_topology.update() self.fql.addQuadruples([(1, 4, 3, 2)]) self.integrator.run(5) self.dump_topology.update() self.dump_h5md.flush() self.dump_h5md.close() h5 = h5py.File(self.h5md_file, 'r') self.assertEqual(list(h5['/connectivity/dihs_0/step']), range(11)) for plist in h5['/connectivity/dihs_0/value'][:6]: self.assertListEqual( sorted(map(tuple, filter(lambda x: -1 not in x, plist))), [(2, 1, 3, 4)]) # Second part contains added pair (1, 4, 3) for plist in h5['/connectivity/dihs_0/value'][6:]: self.assertListEqual( sorted(map(tuple, filter(lambda x: -1 not in x, plist))), [(2, 1, 3, 4), (4, 1, 3, 2)]) if __name__ == '__main__': try: import h5py ut.main() except ImportError as ex: if os.environ.get('TEST_H5MD'): # For travis-ci tests raise ex print('Skip DumpH5MD testsuit, h5py module not found')
govarguz/espressopp
testsuite/FileIOTests/h5md/dump_topology_test.py
Python
gpl-3.0
7,346
[ "ESPResSo" ]
63d62f5435365c981a4271f55be22ef065431cf2910cee4cf918d9e80c419b40
### Code written for STDP tutorial @ CAMP 2016 ### Adapted from Song et al 2000 (Competitive Hebbian Learning through spike-timing-dependent synaptic plasticity ### With independent Poisson inputs (relevant figures : Fig 2a,b,c) ### Author: Harsha Gurnani ### Date: June 15, 2016 ####################################### from brian2 import * from time import time #set_device('cpp_standalone') ################# def newrun( fe = 15, fi = 15, Weakratio=1.05, simtime = 100*second, delta = 0.1*ms): if fe<30: simtime=150*second defaultclock.dt = delta taum = 20*ms Vrest = -70*mV Erev = 0*mV #Excitatory synapse - reversal potential Irev = -70*mV #Inhibitory synapse - reversal potential taue = 5*ms taui = 5*ms gmax = 0.015 #Max excitatory conductance ginh = 0.05 #Inhibitory conductance Vt = -54*mV # Spike threshold Vr = -60*mV # Reset potential #### How does no. of synapses/ ratio influence firing rates? Ne = 1000 #No. of excitatory synapses Ni = 200 #No. of ihibitory synapses # How does final distribution of weights depend on presynaptic firing rates? Why??? FRe = fe*Hz #Firing rate for excitatory input FRi = fi*Hz #FR for inhibitory input ### Neuron model eqs = Equations(''' dV/dt = ( (Vrest - V) + ge*(Erev - V) + gi*(Irev - V) )/taum :volt dge/dt = -ge/taue :1 #Current from exc synapse dgi/dt = -gi/taui :1 #Current from inh synapse ''') NRN = NeuronGroup(1, model=eqs, threshold = 'V>Vt', reset = 'V=Vr', method='euler') ## STDP parameters for excitatory synapses taupre = 20*ms taupost = 20*ms #Weakratio = 1.05 ##Apost*taupost/(Apre/taupre) ##:Weakening:Strengthening ratio (slightly greater than 1 for stabilising network) Apre = 0.005 # %Strengthening with pre-post pair Apost = Apre*(taupre/taupost)*Weakratio ### Excitatory input and synapse model InpE = PoissonGroup(Ne, rates = FRe) syneqs = ''' gsyn :1 dx/dt = -x/taupre :1 (event-driven) dy/dt = -y/taupost :1 (event-driven) ''' preeqs = ''' ge_post += gsyn x += Apre gsyn += -y*gmax gsyn = clip(gsyn, 0, gmax) ''' posteqs = ''' y += Apost gsyn += x*gmax gsyn = clip(gsyn, 0, gmax) ''' S_exc = Synapses(InpE, NRN, model=syneqs, on_pre=preeqs, on_post=posteqs ) S_exc.connect() S_exc.gsyn[:] = gmax*rand(Ne) #Initialise uniformly between 0 and gmax #print 'Created', Ne, 'excitatory synapses with mean weight = ', float(int(mean(S_exc.gsyn[:]*10000)))/10 ### Inhibitory synapses InpI = PoissonGroup(Ni, rates = FRi) S_inh = Synapses(InpI, NRN, model = ' ', on_pre = '''gi_post += ginh''') S_inh.connect() #print 'Created', Ni, 'inhibitory synapses ...' ## Monitors SM = SpikeMonitor(NRN) VMon = StateMonitor( NRN, 'V', record = 0 ) FR = PopulationRateMonitor(NRN) ## Runtime print '\n Running for', simtime, 'at dt = ', delta, 'with excitatory inputs at', fe, 'Hz' run( simtime, report = 'text', report_period = 50*second) #device.build(directory='output', compile=True, run=True, debug=False) ## Plotting figure() suptitle('Excitatory firing rate = %d Hz' %(fe)) ### Histogram of sinal synaptic weights subplot(311) hist(S_exc.gsyn[:] /gmax, 20) ylabel('No. of synapses') xlabel('Normalised synaptic weight') ### Initial membrane potential trace subplot(323) plot(VMon.t[0:3000] /ms, VMon.V[0,0:3000] /mV) ylim([-80,-40]) ylabel('Membrane potential (mV)') legend('Initial V') ### Final membrane potential trace subplot(324) plot(VMon.t[-3000:-1] /ms, VMon.V[0,-3000:-1] /mV) ylim([-80,-40]) legend('Final V') ### Evolution of Firing rate in time subplot(313) plot(FR.t /second, FR.smooth_rate(window='gaussian', width=50*ms)/Hz) ylabel('Firing rate (Hz)') tight_layout() poprate=FR.smooth_rate(window='gaussian', width=100*ms) fin_poprate = mean( poprate[-1000:-500] ) print fin_poprate spt = SM.t[:] L = len(spt) ##Get last 500 spikes. Fixed no. of spikes instead of duration. if L > 500: spt = spt[-500:L] isi = spt[1:500] - spt[0:499] cv = sqrt(var(isi))/mean(isi) else : cv = NaN print ' \n' return fin_poprate, cv ################ fe_rates = [15,20,25,30,35,40,45] poprates = [] cv = [] for fe in fe_rates: ret1, ret2 = newrun(fe) poprates.append(ret1) cv.append(ret2) print poprates fig = figure() A = fig.add_subplot(111) A.plot(fe_rates, poprates, marker ='o', color = 'b') A.set_xlabel('Excitatory input (Hz)') A.set_ylabel('Firing rate of postsynaptic neuron (Hz)', color='b') for tl in A.get_yticklabels(): tl.set_color('b') ## Different y-scales for the two plots with same x-axis B = A.twinx() B.plot(fe_rates, cv, marker='*', color='g') B.set_ylabel('CV', color='g') for tl in B.get_yticklabels(): tl.set_color('g') show()
h-mayorquin/camp_india_2016
tutorials/LTP-I/Demo1/For_abbott_repfig2.py
Python
mit
5,265
[ "Gaussian", "NEURON" ]
04f93c660838b77ff7c60ef6f260283b7b0f36f6f308fc5ed0d825e1462c71f8
from disposable_email_domains import blacklist def is_reserved_subdomain(subdomain: str) -> bool: if subdomain in ZULIP_RESERVED_SUBDOMAINS: return True if subdomain[-1] == 's' and subdomain[:-1] in ZULIP_RESERVED_SUBDOMAINS: return True if subdomain in GENERIC_RESERVED_SUBDOMAINS: return True if subdomain[-1] == 's' and subdomain[:-1] in GENERIC_RESERVED_SUBDOMAINS: return True return False def is_disposable_domain(domain: str) -> bool: if domain.lower() in WHITELISTED_EMAIL_DOMAINS: return False return domain.lower() in DISPOSABLE_DOMAINS ZULIP_RESERVED_SUBDOMAINS = frozenset([ # zulip terms 'stream', 'channel', 'topic', 'thread', 'installation', 'organization', 'realm', 'team', 'subdomain', 'activity', 'octopus', 'acme', 'push', # machines 'zulipdev', 'localhost', 'staging', 'prod', 'production', 'testing', 'nagios', 'nginx', # website pages 'server', 'client', 'features', 'integration', 'bot', 'blog', 'history', 'story', 'stories', 'testimonial', 'compare', 'for', 'vs', # competitor pages 'slack', 'mattermost', 'rocketchat', 'irc', 'twitter', 'zephyr', 'flowdock', 'spark', 'skype', 'microsoft', 'twist', 'ryver', 'matrix', 'discord', 'email', 'usenet', # zulip names 'zulip', 'tulip', 'humbug', # platforms 'plan9', 'electron', 'linux', 'mac', 'windows', 'cli', 'ubuntu', 'android', 'ios', # floss 'contribute', 'floss', 'foss', 'free', 'opensource', 'open', 'code', 'license', # intership programs 'intern', 'outreachy', 'gsoc', 'gci', 'externship', # Things that sound like security 'auth', 'authentication', 'security', # tech blogs 'engineering', 'infrastructure', 'tooling', 'tools', 'javascript', 'python']) # Most of this list was curated from the following sources: # http://wiki.dwscoalition.org/notes/List_of_reserved_subdomains (license: CC-BY-SA 3.0) # https://stackoverflow.com/questions/11868191/which-saas-subdomains-to-block (license: CC-BY-SA 2.5) GENERIC_RESERVED_SUBDOMAINS = frozenset([ 'about', 'abuse', 'account', 'ad', 'admanager', 'admin', 'admindashboard', 'administrator', 'adsense', 'adword', 'affiliate', 'alpha', 'anonymous', 'api', 'assets', 'audio', 'badges', 'beta', 'billing', 'biz', 'blog', 'board', 'bookmark', 'bot', 'bugs', 'buy', 'cache', 'calendar', 'chat', 'clients', 'cname', 'code', 'comment', 'communities', 'community', 'contact', 'contributor', 'control', 'coppa', 'copyright', 'cpanel', 'css', 'cssproxy', 'customise', 'customize', 'dashboard', 'data', 'demo', 'deploy', 'deployment', 'desktop', 'dev', 'devel', 'developer', 'development', 'discussion', 'diversity', 'dmca', 'docs', 'donate', 'download', 'e-mail', 'email', 'embed', 'embedded', 'example', 'explore', 'faq', 'favorite', 'favourites', 'features', 'feed', 'feedback', 'files', 'forum', 'friend', 'ftp', 'general', 'gettingstarted', 'gift', 'git', 'global', 'graphs', 'guide', 'hack', 'help', 'home', 'hostmaster', 'https', 'icon', 'im', 'image', 'img', 'inbox', 'index', 'investors', 'invite', 'invoice', 'ios', 'ipad', 'iphone', 'irc', 'jabber', 'jars', 'jobs', 'join', 'js', 'kb', 'knowledgebase', 'launchpad', 'legal', 'livejournal', 'lj', 'login', 'logs', 'm', 'mail', 'main', 'manage', 'map', 'media', 'memories', 'memory', 'merchandise', 'messages', 'mobile', 'my', 'mystore', 'networks', 'new', 'newsite', 'official', 'ogg', 'online', 'order', 'paid', 'panel', 'partner', 'partnerpage', 'pay', 'payment', 'picture', 'policy', 'pop', 'popular', 'portal', 'post', 'postmaster', 'press', 'pricing', 'principles', 'privacy', 'private', 'profile', 'public', 'random', 'redirect', 'register', 'registration', 'resolver', 'root', 'rss', 's', 'sandbox', 'school', 'search', 'secure', 'servers', 'service', 'setting', 'shop', 'shortcuts', 'signin', 'signup', 'sitemap', 'sitenews', 'sites', 'sms', 'smtp', 'sorry', 'ssl', 'staff', 'stage', 'staging', 'stars', 'stat', 'static', 'statistics', 'status', 'store', 'style', 'support', 'surveys', 'svn', 'syn', 'syndicated', 'system', 'tag', 'talk', 'team', 'termsofservice', 'test', 'testers', 'ticket', 'tool', 'tos', 'trac', 'translate', 'update', 'upgrade', 'uploads', 'use', 'user', 'username', 'validation', 'videos', 'volunteer', 'web', 'webdisk', 'webmail', 'webmaster', 'whm', 'whois', 'wiki', 'www', 'www0', 'www8', 'www9', 'xml', 'xmpp', 'xoxo']) DISPOSABLE_DOMAINS = frozenset(blacklist) WHITELISTED_EMAIL_DOMAINS = frozenset([ # Controlled by https://www.abine.com; more legitimate than most # disposable domains 'opayq.com', 'abinemail.com', 'blurmail.net', 'maskmemail.com', ])
brainwane/zulip
zerver/lib/name_restrictions.py
Python
apache-2.0
4,774
[ "Octopus" ]
2dd47b0e301221ecefea359fd754612e1832f3ade019a6439d08526e1caf7d63
#!/usr/bin/env python # -*- coding: utf-8 -*- # ------------------------------------------------------------------- # Filename: local_handler.py # Purpose: handling local processing/plotting in obspyDMT # Author: Kasra Hosseini # Email: kasra.hosseinizad@earth.ox.ac.uk # License: GNU Lesser General Public License, Version 3 # ------------------------------------------------------------------- # ----------------------------------------------------------------------- # ----------------Import required Modules (Python and Obspy)------------- # ----------------------------------------------------------------------- from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import input as raw_input_built import matplotlib.pyplot as plt import multiprocessing import numpy as np try: from obspy.imaging.beachball import beach as Beach except: from obspy.imaging.beachball import beachball as Beach from obspy import UTCDateTime, read try: from obspy.geodetics import locations2degrees except: from obspy.core.util import locations2degrees try: from obspy.geodetics.base import gps2dist_azimuth as gps2DistAzimuth except: try: from obspy.geodetics import gps2DistAzimuth except: from obspy.core.util import gps2DistAzimuth import os import sys from .data_handler import update_sta_ev_file from .kml_handler import create_ev_sta_kml from .utility_codes import locate, check_par_jobs, plot_filter_station # ###################### process_data ######################################### def process_data(input_dics, event): """ prepare the target directories and pass them to process_serial_parallel :param input_dics: :param event: :return: """ target_path = locate(input_dics['datapath'], event['event_id'], num_matches=1) if len(target_path) == 0: return if len(target_path) > 1: print("[LOCAL] more than one path was found for one event:") print(target_path) print("use the first one:") target_path = target_path[0] print(target_path) else: print("[LOCAL] Path:") target_path = target_path[0] print(target_path) print("[INFO] update station_event file...") update_sta_ev_file(target_path, event) sta_ev_arr = np.loadtxt(os.path.join(target_path, 'info', 'station_event'), delimiter=',', dtype=bytes, ndmin=2).astype(np.str) sta_ev_arr = sta_ev_arr.astype(np.object) if input_dics['select_data']: sta_ev_arr = select_data(deg_step=float(input_dics['select_data']), sta_ev=sta_ev_arr) if len(sta_ev_arr) > 0: if len(np.shape(sta_ev_arr)) == 1: sta_ev_arr = np.reshape(sta_ev_arr, [1, len(sta_ev_arr)]) process_serial_parallel(sta_ev_arr, input_dics, target_path) else: print("[LOCAL] no waveform to process for %s!" % target_path) # ###################### select_data ################################# def select_data(deg_step, sta_ev): """ select stations every deg_step :param deg_step: :param sta_ev: :return: """ lat_step = deg_step lon_step = deg_step eradius = 6371 lats = np.arange(-90, 90+lat_step, lat_step) lons = np.arange(-180, 180+lon_step, lon_step) grd_points = np.empty([len(lats)*len(lons), 2]) counter = 0 for lat in lats: for lon in lons: grd_points[counter, 0] = lat grd_points[counter, 1] = lon counter += 1 from .utils.spherical_nearest import SphericalNearestNeighbour kd = SphericalNearestNeighbour(grd_points[:, 0], grd_points[:, 1], np.zeros(len(grd_points[:, 1])), eradius=eradius) dists, indxs = kd.query(sta_ev[:, 4].astype(np.float), sta_ev[:, 5].astype(np.float), np.zeros(len(sta_ev[:, 4])), 1) indxs_unique = np.unique(indxs, return_index=True) sta_ev_arr_unique = sta_ev[indxs_unique] return sta_ev_arr_unique # ###################### process_serial_parallel ############################## def process_serial_parallel(sta_ev_arr, input_dics, target_path): """ run the processing unit in parallel or in serial :param sta_ev_arr: :param input_dics: :param target_path: :return: """ if input_dics['parallel_process']: start = 0 end = int(len(sta_ev_arr)) if end < input_dics['process_np']: req_proc = end else: req_proc = input_dics['process_np'] step = (end - start) / req_proc + 1 step = int(step) jobs = [] for index in range(req_proc): starti = start + index * step endi = min(start + (index + 1) * step, end) if starti == endi: break p = multiprocessing.Process(target=process_core_iterate, args=(sta_ev_arr, input_dics, target_path, starti, endi)) jobs.append(p) for i in range(len(jobs)): jobs[i].start() check_par_jobs(jobs) else: process_core_iterate(sta_ev_arr, input_dics, target_path, 0, len(sta_ev_arr)) # ###################### process_core_iterate ################################# def process_core_iterate(sta_ev_arr, input_dics, target_path, starti, endi): """ running the process_unit for starti and endi defined by either serial or parallel mode :param sta_ev_arr: :param input_dics: :param target_path: :param starti: :param endi: :return: """ import importlib try: process_unit = importlib.import_module( 'obspyDMT.%s' % input_dics['pre_process']) except: from obspyDMT import __path__ as dmt_path sys.exit("\n\n%s.py DOES NOT EXIST at %s!" % (input_dics['pre_process'], dmt_path)) for i in range(starti, endi): staev_ar = sta_ev_arr[i] station_id = '%s.%s.%s.%s' % (staev_ar[0], staev_ar[1], staev_ar[2], staev_ar[3]) tr_add = os.path.join(target_path, 'raw', station_id) data_source = staev_ar[8] if input_dics['pre_process']: print('[%s/%s] start processing: %s' % (i+1, len(sta_ev_arr), station_id)) process_unit.process_unit(tr_add, target_path, input_dics, staev_ar) # ###################### plot_unit ############################################ def plot_unit(input_dics, events): """ this function re-direct the flow to the relevant plotting function :param input_dics: :param events: :return: """ events = event_filter(events, input_dics) if input_dics['create_event_vtk']: vtk_generator(events) if input_dics['create_kml']: create_ev_sta_kml(input_dics, events) if input_dics['plot_seismicity']: plot_seismicity(input_dics, events) if input_dics['plot_ev'] or input_dics['plot_sta'] or \ input_dics['plot_availability'] or input_dics['plot_ray']: plot_sta_ev_ray(input_dics, events) if input_dics['plot_waveform']: plot_waveform(input_dics, events) # ##################### event_filter ########################################## def event_filter(events, input_dics): """ filtering events based on the inputs :param events: :param input_dics: :return: """ del_index = [] for ev in range(len(events)): if input_dics['dir_select']: if events[ev]['event_id'] not in input_dics['dir_select']: del_index.append(ev) continue if not plot_filter_event(input_dics, events[ev]): del_index.append(ev) del_index.sort(reverse=True) for di in del_index: del events[di] return events # ##################### plot_filter_event ##################################### def plot_filter_event(input_dics, event_dic): """ check whether the event can pass the criteria :param input_dics: :param event_dic: :return: """ try: if not event_dic['datetime'] <= UTCDateTime(input_dics['max_date']): return False if not event_dic['datetime'] >= UTCDateTime(input_dics['min_date']): return False if not event_dic['magnitude'] < 0: if not event_dic['magnitude'] <= float(input_dics['max_mag']): return False if not event_dic['magnitude'] >= float(input_dics['min_mag']): return False if not event_dic['depth'] <= float(input_dics['max_depth']): return False if not event_dic['depth'] >= float(input_dics['min_depth']): return False if isinstance(input_dics['evlatmin'], float): if float(event_dic['longitude']) < 0: event_dic_360 = 360. + float(event_dic['longitude']) else: event_dic_360 = float(event_dic['longitude']) if float(input_dics['evlonmin']) < 0: evlonmin_360 = 360. + float(input_dics['evlonmin']) else: evlonmin_360 = float(input_dics['evlonmin']) if float(input_dics['evlonmax']) < 0: evlonmax_360 = 360. + float(input_dics['evlonmax']) else: evlonmax_360 = float(input_dics['evlonmax']) if not event_dic['latitude'] <= float(input_dics['evlatmax']): return False if not event_dic_360 <= evlonmax_360: return False if not event_dic['latitude'] >= float(input_dics['evlatmin']): return False if not event_dic_360 >= evlonmin_360: return False return True except Exception as error: return False # ##################### plot_waveform ######################################### def plot_waveform(input_dics, events): """ plot waveforms arranged by the epicentral distance :param input_dics: :param events: :return: """ # plt.rc('font', family='serif') for ei in range(len(events)): target_path = locate(input_dics['datapath'], events[ei]['event_id'], num_matches=1) if len(target_path) == 0: continue if len(target_path) > 1: print("[LOCAL] more than one path was found for the event:") print(target_path) print("[INFO] use the first one:") target_path = target_path[0] print(target_path) else: print("[LOCAL] Path:") target_path = target_path[0] print(target_path) update_sta_ev_file(target_path, events[ei]) sta_ev_arr = np.loadtxt( os.path.join(target_path, 'info', 'station_event'), delimiter=',', dtype=bytes, ndmin=2).astype(np.str) sta_ev_arr = sta_ev_arr.astype(np.object) del_index = [] for sti in range(len(sta_ev_arr)): if not plot_filter_station(input_dics, sta_ev_arr[sti]): del_index.append(sti) del_index.sort(reverse=True) for di in del_index: sta_ev_arr[di] = np.delete(sta_ev_arr, (di), axis=0) for si in range(len(sta_ev_arr)): sta_id = sta_ev_arr[si, 0] + '.' + sta_ev_arr[si, 1] + '.' + \ sta_ev_arr[si, 2] + '.' + sta_ev_arr[si, 3] try: tr = read(os.path.join(target_path, input_dics['plot_dir_name'], sta_id))[0] time_diff = tr.stats.starttime - events[ei]['datetime'] taxis = tr.times() + time_diff dist, azi, bazi = gps2DistAzimuth(events[ei]['latitude'], events[ei]['longitude'], float(sta_ev_arr[si, 4]), float(sta_ev_arr[si, 5])) epi_dist = dist/111.194/1000. if input_dics['min_azi'] or input_dics['max_azi'] or \ input_dics['min_epi'] or input_dics['max_epi']: if input_dics['min_epi']: if epi_dist < input_dics['min_epi']: continue if input_dics['max_epi']: if epi_dist > input_dics['max_epi']: continue if input_dics['min_azi']: if azi < input_dics['min_azi']: continue if input_dics['max_azi']: if azi > input_dics['max_azi']: continue plt.plot(taxis, tr.normalize().data + epi_dist, c='k', alpha=0.7) except: continue plt.xlabel('Time (sec)', size=24) plt.ylabel('Distance (deg)', size=24) plt.xticks(size=18) plt.yticks(size=18) plt.tight_layout() if not input_dics['plot_save']: plt.savefig(os.path.join(os.path.curdir, 'waveforms.png')) else: plt.savefig(os.path.join(input_dics['plot_save'])) if not input_dics['show_no_plot']: plt.show() # ##################### plot_sta_ev_ray ############################### def plot_sta_ev_ray(input_dics, events): """ plot stations, events and ray paths on a map using basemap. :param input_dics: :param events: :return: """ from mpl_toolkits.basemap import Basemap plt.figure(figsize=(20., 10.)) plt_stations = input_dics['plot_sta'] plt_availability = input_dics['plot_availability'] plt_events = input_dics['plot_ev'] plt_ray_path = input_dics['plot_ray'] if input_dics['evlatmin'] is None: evlatmin = -90 evlatmax = +90 evlonmin = -180 evlonmax = +180 glob_map = True else: evlatmin = input_dics['evlatmin'] evlatmax = input_dics['evlatmax'] evlonmin = input_dics['evlonmin'] evlonmax = input_dics['evlonmax'] glob_map = False if plt_ray_path: # # hammer, kav7, cyl, mbtfpq, moll m = Basemap(projection='moll', lon_0=input_dics['plot_lon0']) parallels = np.arange(-90, 90, 30.) m.drawparallels(parallels, fontsize=24) meridians = np.arange(-180., 180., 60.) m.drawmeridians(meridians, fontsize=24) width_beach = 10e5 width_station = 50 elif not glob_map: m = Basemap(projection='cyl', llcrnrlat=evlatmin, urcrnrlat=evlatmax, llcrnrlon=evlonmin, urcrnrlon=evlonmax) parallels = np.arange(-90, 90, 5.) m.drawparallels(parallels, fontsize=12) meridians = np.arange(-180., 180., 5.) m.drawmeridians(meridians, fontsize=12) width_beach = 5 width_station = 10 elif glob_map: m = Basemap(projection='moll', lon_0=input_dics['plot_lon0']) parallels = np.arange(-90, 90, 30.) m.drawparallels(parallels, fontsize=24) meridians = np.arange(-180., 180., 60.) m.drawmeridians(meridians, fontsize=24) width_beach = 5e5 width_station = 50 else: sys.exit('[ERROR] can not continue, error:\n%s' % input_dics) if input_dics['plot_style'] == 'bluemarble': m.bluemarble(scale=0.5) elif input_dics['plot_style'] == 'etopo': m.etopo(scale=0.5) elif input_dics['plot_style'] == 'shadedrelief': m.shadedrelief(scale=0.1) else: m.fillcontinents() for ei in range(len(events)): if plt_events: if input_dics['plot_focal']: if not events[ei]['focal_mechanism']: print('[ERROR] moment tensor does not exist!') continue x, y = m(events[ei]['longitude'], events[ei]['latitude']) focmecs = [float(events[ei]['focal_mechanism'][0]), float(events[ei]['focal_mechanism'][1]), float(events[ei]['focal_mechanism'][2]), float(events[ei]['focal_mechanism'][3]), float(events[ei]['focal_mechanism'][4]), float(events[ei]['focal_mechanism'][5])] try: ax = plt.gca() b = Beach(focmecs, xy=(x, y), facecolor='blue', width=width_beach, linewidth=1, alpha=0.85) b.set_zorder(10) ax.add_collection(b) except Exception as error: print("[WARNING: %s -- %s]" % (error, focmecs)) continue else: x, y = m(events[ei]['longitude'], events[ei]['latitude']) magnitude = float(events[ei]['magnitude']) m.scatter(x, y, color="blue", s=10*magnitude, edgecolors='none', marker="o", zorder=5, alpha=0.65) if plt_stations or plt_availability or plt_ray_path: target_path = locate(input_dics['datapath'], events[ei]['event_id'], num_matches=1) if len(target_path) == 0: continue if len(target_path) > 1: print("[LOCAL] more than one path was found for the event:") print(target_path) print("[INFO] use the first one:") target_path = target_path[0] print(target_path) else: print("[LOCAL] Path:") target_path = target_path[0] print(target_path) update_sta_ev_file(target_path, events[ei]) if not input_dics['plot_availability']: sta_ev_arr = np.loadtxt(os.path.join(target_path, 'info', 'station_event'), delimiter=',', dtype=bytes, ndmin=2).astype(np.str) else: sta_ev_arr = np.loadtxt(os.path.join(target_path, 'info', 'availability.txt'), delimiter=',', dtype=bytes, ndmin=2).astype(np.str) sta_ev_arr = sta_ev_arr.astype(np.object) if events[ei]['magnitude'] > 0: del_index = [] for sti in range(len(sta_ev_arr)): if not plot_filter_station(input_dics, sta_ev_arr[sti]): del_index.append(sti) dist, azi, bazi = gps2DistAzimuth( events[ei]['latitude'], events[ei]['longitude'], float(sta_ev_arr[sti, 4]), float(sta_ev_arr[sti, 5])) epi_dist = dist/111.194/1000. if input_dics['min_azi'] or input_dics['max_azi'] or \ input_dics['min_epi'] or input_dics['max_epi']: if input_dics['min_epi']: if epi_dist < input_dics['min_epi']: del_index.append(sti) if input_dics['max_epi']: if epi_dist > input_dics['max_epi']: del_index.append(sti) if input_dics['min_azi']: if azi < input_dics['min_azi']: del_index.append(sti) if input_dics['max_azi']: if azi > input_dics['max_azi']: del_index.append(sti) del_index = list(set(del_index)) del_index.sort(reverse=True) for di in del_index: sta_ev_arr = np.delete(sta_ev_arr, (di), axis=0) if plt_stations or plt_availability: if len(sta_ev_arr) > 0: x, y = m(sta_ev_arr[:, 5], sta_ev_arr[:, 4]) m.scatter(x, y, color='red', s=width_station, edgecolors='none', marker='v', zorder=4, alpha=0.9) if plt_ray_path: for si in range(len(sta_ev_arr)): gcline = m.drawgreatcircle(float(events[ei]['longitude']), float(events[ei]['latitude']), float(sta_ev_arr[si][5]), float(sta_ev_arr[si][4]), color='k', alpha=0.0) gcx, gcy = gcline[0].get_data() gcx_diff = gcx[0:-1] - gcx[1:] gcy_diff = gcy[0:-1] - gcy[1:] if np.max(abs(gcx_diff))/abs(gcx_diff[0]) > 300: gcx_max_arg = abs(gcx_diff).argmax() plt.plot(gcx[0:gcx_max_arg], gcy[0:gcx_max_arg], color='k', alpha=0.1) plt.plot(gcx[gcx_max_arg+1:], gcy[gcx_max_arg+1:], color='k', alpha=0.1) elif np.max(abs(gcy_diff))/abs(gcy_diff[0]) > 400: gcy_max_arg = abs(gcy_diff).argmax() plt.plot(gcy[0:gcy_max_arg], gcy[0:gcy_max_arg], color='k', alpha=0.1) plt.plot(gcy[gcy_max_arg+1:], gcy[gcy_max_arg+1:], color='k', alpha=0.1) else: m.drawgreatcircle(float(events[ei]['longitude']), float(events[ei]['latitude']), float(sta_ev_arr[si][5]), float(sta_ev_arr[si][4]), color='k', alpha=0.1) if not input_dics['plot_save']: plt.savefig(os.path.join(os.path.curdir, 'event_station.png')) else: plt.savefig(os.path.join(input_dics['plot_save'])) if not input_dics['show_no_plot']: plt.show() # ##################### plot_seismicity ####################################### def plot_seismicity(input_dics, events): """ create a seismicity map with some basic statistical analysis on the results :param input_dics: :param events: :return: """ print('\n==============') print('Seismicity map') print('==============\n') from mpl_toolkits.basemap import Basemap # plt.rc('font', family='serif') if not len(events) > 0: print("[WARNING] no event passed the given criteria!") print("[WARNING] can not create any seismicity map.") return if input_dics['evlatmin'] is None: input_dics['evlatmin'] = -90 input_dics['evlatmax'] = +90 input_dics['evlonmin'] = -180 input_dics['evlonmax'] = +180 map_proj = 'cyl' else: map_proj = 'cyl' # set-up the map m = Basemap(projection=map_proj, llcrnrlat=input_dics['evlatmin'], urcrnrlat=input_dics['evlatmax'], llcrnrlon=input_dics['evlonmin'], urcrnrlon=input_dics['evlonmax'], lon_0=input_dics['plot_lon0'], resolution='l') parallels = np.arange(-90, 90, 30.) m.drawparallels(parallels, fontsize=24) meridians = np.arange(-180., 180., 60.) m.drawmeridians(meridians, fontsize=24) if input_dics['plot_style'] == 'bluemarble': m.bluemarble(scale=0.5) elif input_dics['plot_style'] == 'etopo': m.etopo(scale=0.5) elif input_dics['plot_style'] == 'shadedrelief': m.shadedrelief(scale=0.1) else: m.fillcontinents() # defining labels x_ev, y_ev = m(-360, 0) m.scatter(x_ev, y_ev, 20, color='red', marker="o", edgecolor="black", zorder=10, label='0-70km') m.scatter(x_ev, y_ev, 20, color='green', marker="o", edgecolor="black", zorder=10, label='70-300km') m.scatter(x_ev, y_ev, 20, color='blue', marker="o", edgecolor="black", zorder=10, label='300< km') m.scatter(x_ev, y_ev, 10, color='white', marker="o", edgecolor="black", zorder=10, label='< 4.0') m.scatter(x_ev, y_ev, 40, color='white', marker="o", edgecolor="black", zorder=10, label='4.0-5.0') m.scatter(x_ev, y_ev, 70, color='white', marker="o", edgecolor="black", zorder=10, label='5.0-6.0') m.scatter(x_ev, y_ev, 100, color='white', marker="o", edgecolor="black", zorder=10, label='6.0<=') ev_dp_all = [] ev_mag_all = [] ev_info_ar = np.array([]) plot_focal_mechanism = False for ev in events: x_ev, y_ev = m(float(ev['longitude']), float(ev['latitude'])) ev_dp_all.append(abs(float(ev['depth']))) ev_mag_all.append(abs(float(ev['magnitude']))) if abs(float(ev['depth'])) < 70.0: color = 'red' elif 70.0 <= abs(float(ev['depth'])) < 300.0: color = 'green' elif 300.0 <= abs(float(ev['depth'])): color = 'blue' if float(ev['magnitude']) < 4.0: size = 10 elif 4.0 <= float(ev['magnitude']) < 5.0: size = 40 elif 5.0 <= float(ev['magnitude']) < 6.0: size = 70 elif 6.0 <= float(ev['magnitude']): size = 100 if ev['focal_mechanism']: plot_focal_mechanism = True f1 = ev['focal_mechanism'][0] f2 = ev['focal_mechanism'][1] f3 = ev['focal_mechanism'][2] f4 = ev['focal_mechanism'][3] f5 = ev['focal_mechanism'][4] f6 = ev['focal_mechanism'][5] else: f1 = False f2 = False f3 = False f4 = False f5 = False f6 = False if np.size(ev_info_ar) < 1: ev_info_ar = np.append(ev_info_ar, [float(ev['depth']), float(x_ev), float(y_ev), size, color, f1, f2, f3, f4, f5, f6]) else: ev_info_ar = np.vstack((ev_info_ar, [float(ev['depth']), float(x_ev), float(y_ev), size, color, f1, f2, f3, f4, f5, f6])) if np.shape(ev_info_ar)[0] == np.size(ev_info_ar): ev_info_ar = np.reshape(ev_info_ar, (1, 11)) else: ev_info_ar = sorted(ev_info_ar, key=lambda ev_info_iter: float(ev_info_iter[0])) for ev in ev_info_ar: m.scatter(float(ev[1]), float(ev[2]), float(ev[3]), color=ev[4], marker="o", edgecolor='k', zorder=10) plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) if plot_focal_mechanism: plt.figure() m = Basemap(projection=map_proj, llcrnrlat=input_dics['evlatmin'], urcrnrlat=input_dics['evlatmax'], llcrnrlon=input_dics['evlonmin'], urcrnrlon=input_dics['evlonmax'], lon_0=input_dics['plot_lon0'], resolution='l') parallels = np.arange(-90, 90, 30.) m.drawparallels(parallels, fontsize=24) meridians = np.arange(-180., 180., 60.) m.drawmeridians(meridians, fontsize=24) if input_dics['plot_style'] == 'bluemarble': m.bluemarble(scale=0.5) elif input_dics['plot_style'] == 'etopo': m.etopo(scale=0.5) elif input_dics['plot_style'] == 'shadedrelief': m.shadedrelief(scale=0.1) else: m.fillcontinents() for evfoc in ev_info_ar: focmec = False try: ax = plt.gca() focmec = (float(evfoc[5]), float(evfoc[6]), float(evfoc[7]), float(evfoc[8]), float(evfoc[9]), float(evfoc[10])) b = Beach(focmec, xy=(float(evfoc[1]), float(evfoc[2])), facecolor=evfoc[4], width=float(evfoc[3])/100., linewidth=1, alpha=0.85) b.set_zorder(10) ax.add_collection(b) except Exception as error: print('[EXCEPTION] focal mechanism:') print(focmec) print('[EXCEPTION] error: %s' % error) if len(events) > 0: plt.figure() hn, hbins, hpatches = \ plt.hist(ev_dp_all, input_dics['depth_bins_seismicity'], facecolor='g', edgecolor='k', lw=3, alpha=0.5, log=True) plt.xlabel('Depth', size=32, weight='bold') plt.ylabel('#Events (log)', size=32, weight='bold') plt.yscale('log') plt.ylim(ymin=0.2) plt.xticks(size=24, weight='bold') plt.yticks(size=24, weight='bold') plt.tight_layout() plt.grid(True) plt.figure() hn, hbins, hpatches = \ plt.hist(ev_mag_all, bins=np.linspace(int(float(input_dics['min_mag'])), int(float(input_dics['max_mag'])), (int(float(input_dics['max_mag'])) - int(float(input_dics['min_mag'])))*2+1), facecolor='g', edgecolor='k', lw=3, alpha=0.5, log=True) plt.xlabel('Magnitude', size=32, weight='bold') plt.ylabel('#Events (log)', size=32, weight='bold') plt.yscale('log') plt.ylim(ymin=0.2) plt.xticks(size=24, weight='bold') plt.yticks(size=24, weight='bold') plt.tight_layout() plt.grid(True) if not input_dics['plot_save']: plt.savefig(os.path.join(os.path.curdir, 'seismicity.png')) else: plt.savefig(os.path.join(input_dics['plot_save'])) if not input_dics['show_no_plot']: plt.show() # ##################### vtk_generator ################################### def vtk_generator(events, vtk_output='events'): """ VTK generator for events :param events: :param vtk_output: :return: """ counter = 0 xyz = [] for i in range(len(events)): elat = events[i]['latitude']*np.pi/180. elon = events[i]['longitude']*np.pi/180. edp = events[i]['depth'] x = (6371-edp) * np.cos(elat) * np.cos(elon) y = (6371-edp) * np.cos(elat) * np.sin(elon) z = (6371-edp) * np.sin(elat) print xyz.append("%s %s %s" % (x, y, z)) counter += 1 fio = open(vtk_output + '.vtk', 'wt') fio.writelines('# vtk DataFile Version 3.0\n') fio.writelines('vtk output\n') fio.writelines('ASCII\n') fio.writelines('DATASET UNSTRUCTURED_GRID\n') fio.writelines('POINTS %i float\n' % counter) for i in range(len(xyz)): fio.writelines('%s\n' % xyz[i]) fio.writelines('\n') fio.writelines('CELLS %i %i\n' % (counter, counter*2)) for i in range(len(xyz)): fio.writelines('1 %s\n' % i) fio.writelines('\n') fio.writelines('CELL_TYPES %i\n' % counter) for i in range(len(xyz)): fio.writelines('1\n') fio.close()
kasra-hosseini/obspyDMT
obspyDMT/utils/local_handler.py
Python
gpl-3.0
31,984
[ "VTK" ]
ee20bf3cd8932422ebb74acc6ebf7767c597e3b45d44c44681216ef3c9158685
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Raspa Preço documentation build configuration file, created by # sphinx-quickstart on Mon Nov 6 10:52:29 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys path = os.path.abspath('.') sys.path.insert(0, path) print(path) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Raspa Preço' copyright = '2017, Ivan Brasilico' author = 'Ivan Brasilico' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'pt-BR' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'venv', '.tox'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', 'donate.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'RaspaPrecodoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'RaspaPreco.tex', 'Raspa Preço Documentation', 'Ivan Brasilico', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'raspapreco', 'Raspa Preço Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'RaspaPreco', 'Raspa Preço Documentation', author, 'RaspaPreco', 'One line description of project.', 'Miscellaneous'), ]
IvanBrasilico/raspa-preco
conf.py
Python
gpl-3.0
5,357
[ "RASPA" ]
41c3e6b6eecfac6662178addfe0b346b9907a74aa9f5b78e68fc0ebcd819477e
""" Created on 27/04/2013 @author: thom """ import unittest import math from rdkit.rdBase import DisableLog, EnableLog from kinetic_molecule import KineticMolecule from molecule import Molecule from chemistry_model.default_chemistry import DefaultChemistry from reactor_model.spatial_reaction_vessel import SpatialReactionVessel from reactor_model.aspatial_reaction_vessel import AspatialReactionVessel from molecular_population import MolecularPopulation from chemistry_model.reaction import Reaction class TestReactionVessel(unittest.TestCase): def setUp(self): DisableLog('rdApp.error') self._chemistry = DefaultChemistry() self._population = MolecularPopulation() self._population.set_quantity("O", 2) self._population.set_quantity("N", 1) self._vessel = [SpatialReactionVessel(self._chemistry, self._population), AspatialReactionVessel(self._chemistry, self._population)] def tearDown(self): EnableLog('rdApp.error') def testGetNumberMolecules(self): for rv in self._vessel: self.assertEqual(self._population.get_population_size(), rv.get_number_molecules()) def testAddMolecules(self): for rv in self._vessel: self.assertEqual(0, rv._energy_input) mols = [KineticMolecule("C", kinetic_energy=10)] rv.add_molecules(mols) self.assertEqual(self._population.get_population_size() + len(mols), rv.get_number_molecules()) def testGetReactants(self): pass def testAdjustKE(self): pass def testGetTotalPE(self): for rv in self._vessel: mols = [Molecule(smiles) for smiles in self._population.get_population()] pe = sum([mol.get_potential_energy(self._chemistry) for mol in mols]) self.assertAlmostEqual(rv.get_total_pe(), pe) def testIntegration(self): pass def Weight(self): reaction_energy = 100 # more likely to form bond than break it at low energies self.assertTrue(self._vessel.weight(100, reaction_energy) < self._vessel.weight(-100, reaction_energy)) reaction_energy = 700 # more likely to break bond than form it at high energies self.assertTrue(self._vessel.weight(100, reaction_energy) > self._vessel.weight(-100, reaction_energy)) def RegressionOnlyPossibleReactions(self): self.assertEqual(0, self._vessel.weight(100, 100)) # not possible self.assertLessEqual(0, self._vessel.weight(-10, 100)) # possible self.assertEqual(0, self._vessel.weight(200, 100)) # not possible def test_SelectReaction(self): def weight(delta, reaction_energy): if delta < 0: return(-delta) else: return max(0, reaction_energy - delta) for rv in self._vessel: reaction_options = [Reaction('BREAK', 100), Reaction('FORM', -100)] count = 0 for i in range(1000): rxn = rv._select_reaction(reaction_options, 700) count += 'BREAK' == rxn.fire() ratio = 1000.0 * weight(100, 700) / (weight(-100, 700) + weight(100, 700)) self.assertAlmostEqual(math.floor(ratio) / 1000, count / 1000.0, 1) count = 0 for i in range(1000): rxn = rv._select_reaction(reaction_options, 100) count += 'FORM' == rxn.fire() ratio = 1000.0 * weight(-100, 100) / (weight(-100, 100) + weight(100, 100)) self.assertAlmostEqual(math.floor(ratio) / 1000, count / 1000.0, 1) if __name__ == "__main__": unittest.main()
th0mmeke/toyworld
tests/test_reaction_vessel.py
Python
gpl-3.0
3,642
[ "RDKit" ]
297ef7eb02cffbe7875fa409d0729850479a82290b9c287a8fe25904c95f5c40
import numpy as np # type: ignore import re import math import warnings from .units import angstrom_to_bohr, ev_to_hartree from .band import Band from copy import deepcopy import fortranformat as ff # type: ignore from functools import reduce class KPoint(): def __init__( self, index, frac_coords, weight ): self.index = index self.frac_coords = frac_coords self.weight = weight def cart_coords( self, reciprocal_lattice ): """Convert the reciprocal fractional coordinates for this k-point to \ reciprocal Cartesian coordinates. Args: reciprocal_lattice (np.array(float)): 3x3 numpy array containing the \ Cartesian reciprocal lattice. Returns: (np.array): The reciprocal Cartesian coordinates of this k-point. """ return np.dot( self.frac_coords, reciprocal_lattice ) def __eq__( self, other ): return ( ( self.index == other.index ) & ( self.frac_coords == other.frac_coords ).all() & ( self.weight == other.weight ) ) def __repr__( self ): return "k-point {}: {} weight = {}".format( self.index, ' '.join( [ str(c) for c in self.frac_coords ] ), self.weight ) def get_numbers_from_string( string ): p = re.compile('-?\d+[.\d]*') return [ float( s ) for s in p.findall( string ) ] def k_point_parser( string ): """Parse k-point data from a PROCAR string. Finds all lines of the form:: k-point 1 : 0.50000000 0.25000000 0.75000000 weight = 0.00806452 and extracts the k-point index, reciprocal fractional coordinates, and weight into a :obj:`procar.KPoint` object. Args: string (str): String containing a full PROCAR file. Returns: (list(:obj:`procar.KPoint`)): A list of :obj:`procar.KPoint` objects. """ regex = re.compile( 'k-point\s+(\d+)\s*:\s+([- ][01].\d{8})([- ][01].\d{8})([- ][01].\d{8})\s+weight = ([01].\d+)' ) captured = regex.findall( string ) k_points = [] for kp in captured: index = int(kp[0]) frac_coords = np.array( [ float(s) for s in kp[1:4] ] ) weight = float(kp[4]) k_points.append( KPoint( index=index, frac_coords=frac_coords, weight=weight ) ) return k_points def projections_parser( string ): regex = re.compile( '([-.\d\se]+tot.+)\n' ) data = regex.findall( string ) data = [ x.replace( 'tot', '0' ) for x in data ] data = np.array( [ x.split() for x in data ], dtype = float ) return data def area_of_a_triangle_in_cartesian_space( a, b, c ): """ Returns the area of a triangle defined by three points in Cartesian space. Args: a (np.array): Cartesian coordinates of point A. b (np.array): Cartesian coordinates of point B. c (np.array): Cartesian coordinates of point C. Returns: (float): the area of the triangle. """ return 0.5 * np.linalg.norm( np.cross( b-a, c-a ) ) def points_are_in_a_straight_line( points, tolerance=1e-7 ): """ Check whether a set of points fall on a straight line. Calculates the areas of triangles formed by triplets of the points. Returns False is any of these areas are larger than the tolerance. Args: points (list(np.array)): list of Cartesian coordinates for each point. tolerance (optional:float): the maximum triangle size for these points to be considered colinear. Default is 1e-7. Returns: (bool): True if all points fall on a straight line (within the allowed tolerance). """ a = points[0] b = points[1] for c in points[2:]: if area_of_a_triangle_in_cartesian_space( a, b, c ) > tolerance: return False return True def two_point_effective_mass( cartesian_k_points, eigenvalues ): """ Calculate the effective mass given eigenvalues at two k-points. Reimplemented from Aron Walsh's original effective mass Fortran code. Args: cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) Cartesian coordinates. eigenvalues (np.array): numpy array containing the eigenvalues at each k-point. Returns: (float): The effective mass """ assert( cartesian_k_points.shape[0] == 2 ) assert( eigenvalues.size == 2 ) dk = cartesian_k_points[ 1 ] - cartesian_k_points[ 0 ] mod_dk = np.sqrt( np.dot( dk, dk ) ) delta_e = ( eigenvalues[ 1 ] - eigenvalues[ 0 ] ) * ev_to_hartree * 2.0 effective_mass = mod_dk * mod_dk / delta_e return effective_mass def least_squares_effective_mass( cartesian_k_points, eigenvalues ): """ Calculate the effective mass using a least squares quadratic fit. Args: cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points eigenvalues (np.array): Energy eigenvalues at each k-point to be used in the fit. Returns: (float): The fitted effective mass Notes: If the k-points do not sit on a straight line a ValueError will be raised. """ if not points_are_in_a_straight_line( cartesian_k_points ): raise ValueError( 'k-points are not collinear' ) dk = cartesian_k_points - cartesian_k_points[0] mod_dk = np.linalg.norm( dk, axis = 1 ) delta_e = eigenvalues - eigenvalues[0] effective_mass = 1.0 / ( np.polyfit( mod_dk, eigenvalues, 2 )[0] * ev_to_hartree * 2.0 ) return effective_mass class Procar: """ Object for working with PROCAR data. Attributes: data (numpy.array(float)): A 5D numpy array that stores the projection data. Axes are k-points, bands, spin-channels, ions and sum over ions, lm-projections. bands (numpy.array(:obj:`Band`)): A numpy array of ``Band`` objects, that contain band index, energy, and occupancy data. k_points (numpy.array(:obj:`KPoint`)): A numpy array of ``KPoint`` objects, that contain fractional coordinates and weights for each k-point. number_of_k_points (int): The number of k-points. number_of_bands (int): The number of bands. spin_channels (int): Number of spin channels in the PROCAR data: - 1 for non-spin-polarised calculations. - 2 for spin-polarised calculations. - 4 for non-collinear calculations. number_of_ions (int): The number of ions. number_of_projections (int): The number of projections, e.g. TODO calculation (dict): Dictionary of True | False values describing the calculation type. Dictionary keys are 'non_spin_polarised', 'non_collinear', and 'spin_polarised'. """ def __init__( self, spin=1, negative_occupancies='warn' ): self._spin_channels = spin # should be determined from PROCAR self._number_of_k_points = None self._number_of_ions = None self._number_of_bands = None self._number_of_projections = None self._k_point_blocks = None self._data = None self._bands = None self._k_points = None self.calculation = { 'non_spin_polarised': False, 'non_collinear': False, 'spin_polarised': False } if negative_occupancies not in [ 'warn', 'raise', 'zero' ]: raise ValueError( "negative_occupancies can be one of [ 'warn', 'raise', 'zero' ]" ) self.negative_occupancies = negative_occupancies #self.non_spin_polarised = None @property def occupancy( self ): return np.array( [ [ band.index, band.occupancy ] for band in self._bands ] ) def __add__( self, other ): if self.spin_channels != other.spin_channels: raise ValueError( 'Can only concatenate Procars with equal spin_channels: {}, {}'.format( self.spin_channels, other.spin_channels ) ) if self.number_of_ions != other.number_of_ions: raise ValueError( 'Can only concatenate Procars with equal number_of_ions: {}, {}'.format( self.number_of_ions, other.number_of_ions ) ) if self.number_of_bands != other.number_of_bands: raise ValueError( 'Can only concatenate Procars with equal number_of_bands: {}, {}'.format( self.number_of_bands, other.number_of_bands ) ) if self.number_of_projections != other.number_of_projections: raise ValueError( 'Can only concatenate Procars with equal number_of_projections: {}, {}'.format( self.number_of_projections, other.number_of_projections ) ) if self._k_point_blocks != other._k_point_blocks: raise ValueError( 'Can only concatenate Procars with equal k_point_blocks: {}, {}'.format( self._k_point_blocks, other._k_point_blocks ) ) if self.calculation != other.calculation: raise ValueError( 'Can only concatenate Procars from equal calculations: {}, {}'.format( self.calculation, other.calculation ) ) new_procar = deepcopy( self ) new_procar._data = np.concatenate( ( self._data, other._data ), axis=0 ) new_procar._number_of_k_points = self.number_of_k_points + other.number_of_k_points new_procar._bands = [] new_procar._bands = np.ravel( np.concatenate( [ self.bands, other.bands ], axis=1 ) ) new_procar._k_points = self._k_points + other._k_points for i, kp in enumerate( new_procar._k_points, 1 ): kp.index = i new_procar.sanity_check() return new_procar def parse_projections( self ): self.projection_data = projections_parser( self.read_in ) try: assert( self._number_of_bands * self._number_of_k_points == len( self.projection_data ) ) self._spin_channels = 1 # non-magnetic, non-spin-polarised self._k_point_blocks = 1 self.calculation[ 'non_spin_polarised' ] = True except: if self._number_of_bands * self._number_of_k_points * 4 == len( self.projection_data ): self._spin_channels = 4 # non-collinear (spin-orbit coupling) self._k_point_blocks = 1 self.calculation[ 'non_collinear' ] = True pass elif self._number_of_bands * self._number_of_k_points * 2 == len( self.projection_data ): self._spin_channels = 2 # spin-polarised self._k_point_blocks = 2 self.calculation[ 'spin_polarised' ] = True pass else: raise self._number_of_projections = int( self.projection_data.shape[1] / ( self._number_of_ions + 1 ) ) - 1 def parse_k_points( self ): self._k_points = k_point_parser( self.read_in )[:self._number_of_k_points] def parse_bands( self ): band_data = re.findall( r"band\s*(\d+)\s*#\s*energy\s*([-.\d]+)\s?\s*#\s"r"*occ.\s*([-.\d]+)", self.read_in ) self._bands = np.array( [ Band( float(i), float(e), float(o), negative_occupancies=self.negative_occupancies ) for i, e, o in band_data ] ) def sanity_check( self ): assert( self._number_of_k_points == len( self._k_points ) ), "k-point number mismatch: {} in header; {} in file".format( self._number_of_k_points, len( self._k_points ) ) read_bands = len( self._bands ) / self._number_of_k_points / self._k_point_blocks assert( self._number_of_bands == read_bands ), "band mismatch: {} in header; {} in file".format( self._number_of_bands, read_bands ) @classmethod def from_files( cls, filenames, **kwargs ): """Create a :obj:`Procar` object by reading the projected wavefunction character of each band from a series of VASP ``PROCAR`` files. Useful when e.g. a band-structure calculation has been split over multiple VASP calculations, for example, when using hybrid functionals. Args: filename (str): Filename of the ``PROCAR`` file. **kwargs: See the ``from_file()`` method for a description of keyword arguments. Returns: (:obj:`vasppy.Procar`) """ pcars = [ cls.from_file( f, **kwargs ) for f in filenames ] return reduce( cls.__add__, pcars ) @classmethod def from_file( cls, filename, negative_occupancies='warn', select_zero_weighted_k_points=False ): """Create a :obj:`Procar` object by reading the projected wavefunction character of each band from a VASP ``PROCAR`` file. Args: filename (str): Filename of the ``PROCAR`` file. negative_occupancies (:obj:`Str`, optional): Select how negative occupancies are handled. Options are: - ``warn`` (default): Warn that some partial occupancies are negative. - ``raise``: Raise an AttributeError. - ``ignore``: Do nothing. - ``zero``: Negative partial occupancies will be set to zero. select_zero_weighted_k_points (:obj:`bool`, optional): Set to ``True`` to only read in zero-weighted k-points from the ``PROCAR`` file. Default is ``False``. Returns: (:obj:`vasppy.Procar`) """ pcar = cls( negative_occupancies=negative_occupancies ) pcar._read_from_file( filename=filename ) if select_zero_weighted_k_points: k_point_indices = [ i for i, kp in enumerate( pcar.k_points ) if kp.weight == 0.0 ] pcar = pcar.select_k_points( k_point_indices ) return pcar def read_from_file( self, filename ): warnings.warn( "read_from_file() is deprecated as a part of the public API.\nPlease use Procar.from_file() or Procar.from_files() instead" ) return self._read_from_file( filename=filename ) def _read_from_file( self, filename ): """Reads the projected wavefunction character of each band from a VASP PROCAR file. Args: filename (str): Filename of the PROCAR file. Returns: None """ with open( filename, 'r' ) as file_in: file_in.readline() self._number_of_k_points, self._number_of_bands, self._number_of_ions = [ int( f ) for f in get_numbers_from_string( file_in.readline() ) ] self.read_in = file_in.read() self.parse_k_points() self.parse_bands() self.parse_projections() self.sanity_check() self.read_in = None # clear memory if self.calculation[ 'spin_polarised' ]: self._data = self.projection_data.reshape( self._spin_channels, self._number_of_k_points, self._number_of_bands, self._number_of_ions+1, self._number_of_projections+1 )[:,:,:,:,1:].swapaxes( 0, 1).swapaxes( 1, 2 ) else: self._data = self.projection_data.reshape( self._number_of_k_points, self._number_of_bands, self._spin_channels, self._number_of_ions+1, self._number_of_projections+1 )[:,:,:,:,1:] @property def number_of_k_points( self ): """The number of k-points described by this :obj:`Procar` object.""" assert( self._number_of_k_points == self._data.shape[0] ), "Number of k-points in metadata ({}) not equal to number in PROCAR data ({})".format( self._number_of_k_points, self._data.shape[0] ) return self._number_of_k_points @property def number_of_bands( self ): """The number of bands described by this :obj:`Procar` object.""" assert( self._number_of_bands == self._data.shape[1] ), "Number of bands in metadata ({}) not equal to number in PROCAR data ({})".format( self._number_of_bands, self._data.shape[1] ) return self._number_of_bands @property def spin_channels( self ): """The number of spin-channels described by this :obj:`Procar` object.""" assert( self._spin_channels == self._data.shape[2] ), "Number of spin channels in metadata ({}) not equal to number in PROCAR data ({})".format( self._spin_channels, self._data.shape[2] ) return self._spin_channels @property def number_of_ions( self ): """The number of ions described by thie :obj:`Procar` object.""" assert( self._number_of_ions == self._data.shape[3]-1 ), "Number of ions in metadata ({}) not equal to number in PROCAR data ({})".format( self._number_of_ions, self._data.shape[3]-1 ) return self._number_of_ions @property def number_of_projections( self ): """The number of lm-projections described by this :obj:`Procar` object.""" assert (self._number_of_projections == self._data.shape[4]), "Number of projections in metadata ({}) not equal to number in PROCAR data ({})".format( self._number_of_projections, self._data.shape[4] ) return self._number_of_projections def print_weighted_band_structure( self, spins=None, ions=None, orbitals=None, scaling=1.0, e_fermi=0.0, reciprocal_lattice=None ): band_structure_data = self.weighted_band_structure( spins=spins, ions=ions, orbitals=orbitals, scaling=scaling, e_fermi=e_fermi, reciprocal_lattice=reciprocal_lattice ) for i, band_data in enumerate( band_structure_data, 1 ): print( '# band: {}'.format( i ) ) for k_point_data in band_data: print( ' '.join( [ str(f) for f in k_point_data ] ) ) print() def weighted_band_structure( self, spins=None, ions=None, orbitals=None, scaling=1.0, e_fermi=0.0, reciprocal_lattice=None ): if spins: spins = [ s - 1 for s in spins ] else: spins = list( range( self.spin_channels ) ) if not ions: ions = [ self.number_of_ions ] # nions+1 is the `tot` index if not orbitals: orbitals = list( range( self.number_of_projections ) ) if self.calculation[ 'spin_polarised' ]: band_energies = np.array( [ band.energy for band in self._bands ] ).reshape( self.spin_channels, self.number_of_k_points, self.number_of_bands )[ spins[0] ].T else: band_energies = np.array( [ band.energy for band in self._bands ] ).reshape( self.number_of_k_points, self.number_of_bands ).T orbital_projection = np.sum( self._data[ :, :, :, :, orbitals ], axis = 4 ) ion_projection = np.sum( orbital_projection[ :, :, :, ions ], axis = 3 ) spin_projection = np.sum( ion_projection[ :, :, spins ], axis = 2 ) x_axis = self.x_axis( reciprocal_lattice ) to_return = [] for i in range( self.number_of_bands ): for k, ( e, p ) in enumerate( zip( band_energies[i], spin_projection.T[i] ) ): to_return.append( [ x_axis[ k ], e - e_fermi, p * scaling ] ) to_return = np.array( to_return ).reshape( self.number_of_bands, -1, 3 ) return to_return def effective_mass_calc( self, k_point_indices, band_index, reciprocal_lattice, spin=1, printing=False ): assert( spin <= self.k_point_blocks ) assert( len( k_point_indices ) > 1 ) # we need at least 2 k-points band_energies = self._bands[:,1:].reshape( self.k_point_blocks, self.number_of_k_points, self.number_of_bands ) frac_k_point_coords = np.array( [ self._k_points[ k - 1 ].frac_coords for k in k_point_indices ] ) eigenvalues = np.array( [ band_energies[ spin - 1 ][ k - 1 ][ band_index - 1 ] for k in k_point_indices ] ) if printing: print( '# h k l e' ) [ print( ' '.join( [ str( f ) for f in row ] ) ) for row in np.concatenate( ( frac_k_point_coords, np.array( [ eigenvalues ] ).T ), axis = 1 ) ] reciprocal_lattice = reciprocal_lattice * 2 * math.pi * angstrom_to_bohr cart_k_point_coords = np.array( [ k.cart_coords( reciprocal_lattice ) for k in k_points ] ) # convert k-points to cartesian if len( k_point_indices ) == 2: effective_mass_function = two_point_effective_mass else: effective_mass_function = least_squares_effective_mass return effective_mass_function( cart_k_point_coords, eigenvalues ) def x_axis( self, reciprocal_lattice=None ): """Generate the x-axis values for a band-structure plot. Returns an array of cumulative distances in reciprocal space between sequential k-points. Args: reciprocal_lattice (:obj:`np.array`, optional): 3x3 Cartesian reciprocal lattice. Default is ``None``. If no reciprocal lattice is provided, the returned x-axis values will be sequential integers, giving even spacings between sequential k-points. Returns: (np.array): An array of x-axis values. """ if reciprocal_lattice is not None: cartesian_k_points = np.array( [ k.cart_coords( reciprocal_lattice ) for k in k_points ] ) x_axis = [ 0.0 ] for i in range( 1, len( cartesian_k_points ) ): dk = cartesian_k_points[ i - 1 ] - cartesian_k_points[ i ] mod_dk = np.sqrt( np.dot( dk, dk ) ) x_axis.append( mod_dk + x_axis[-1] ) x_axis = np.array( x_axis ) else: x_axis = np.arange( len( self._k_points ) ) return x_axis @property def bands( self ): return self._bands.reshape( self._k_point_blocks, self._number_of_k_points, self.number_of_bands ) @property def k_points( self ): return self._k_points def select_bands_by_kpoint( self, band_indices ): return np.ravel( self.bands[:,band_indices,:] ) def select_k_points( self, band_indices ): new_procar = deepcopy( self ) new_procar._bands = np.ravel( new_procar.bands[:,band_indices,:] ) new_procar._data = np.array( [ kp for i, kp in enumerate( new_procar._data ) if i in band_indices ] ) new_procar._number_of_k_points = len( band_indices ) new_procar._k_points = [ kp for i, kp in enumerate( new_procar._k_points ) if i in band_indices ] for i, kp in enumerate( new_procar._k_points, 1 ): kp.index = i new_procar.sanity_check() return new_procar # TODO Need complete set of example PROCAR files before we start to write # something that can write these all back out in the appropriate format # def write_file( self, filename ): # if self.calculation['non_collinear']: # raise NotImplementedError # with open( filename, 'w' ) as f: # f.write( 'PROCAR lm decomposed' ) # for s in range( self.spin_channels ): # not sure what happens for non-collinear calculations # line = ff.FortranRecordWriter("/'# of k-points:',I5,9X,'# of bands:',I5,9X,'# of ions:',I5") # f.write( line.write( [ self.number_of_k_points, self.number_of_bands, self.number_of_ions ] )+'\n' ) # for k_point in self.k_points: # line = ff.FortranRecordWriter("/' k-point ',I5,' :',3X,3F11.8,' weight = ',F10.8/") # f.write( line.write( [ k_point.index, *k_point.frac_coords, k_point.weight ] ) ) # for band in self.bands: # line = ff.FortranRecordWriter("/'band ',I5,' # energy',F14.8,' # occ.',F12.8/") # f.write( line.write( [ band.index, band.energy, band.occupancy ] ) ) # f.write( '\nion s py pz px dxy dyz dz2 dxz dx2 tot\n' )
bjmorgan/vasppy
vasppy/procar.py
Python
mit
23,579
[ "VASP" ]
7a66fc89ca96d4278146ddd79882285c426f99a1ef705ee9d4506c3b669a0e23
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RAldex2(RPackage): """Analysis Of Differential Abundance Taking Sample Variation Into Account A differential abundance analysis for the comparison of two or more conditions. Useful for analyzing data from standard RNA-seq or meta-RNA- seq assays as well as selected and unselected values from in-vitro sequence selections. Uses a Dirichlet-multinomial model to infer abundance from counts, optimized for three or more experimental replicates. The method infers biological and sampling variation to calculate the expected false discovery rate, given the variation, based on a Wilcoxon Rank Sum test and Welch's t-test (via aldex.ttest), a Kruskal-Wallis test (via aldex.kw), a generalized linear model (via aldex.glm), or a correlation test (via aldex.corr). All tests report p-values and Benjamini-Hochberg corrected p-values.""" homepage = "https://bioconductor.org/packages/ALDEx2" git = "https://git.bioconductor.org/packages/ALDEx2.git" version('1.22.0', commit='ac7f0ab3f094ec52713da7620a27058b14c7181d') version('1.16.0', commit='bd698a896a5bea91187e3060e56a147bad1d586f') version('1.14.1', commit='a8b970c594a00a37c064227bf312d5f89dccabe8') version('1.12.0', commit='9efde428d22a0be1fe7b6655d45ddce8fcded180') version('1.10.0', commit='e43f99e4009ad4d5ed200cc8a19faf7091c0c98a') version('1.8.0', commit='24104824ca2402ad4f54fbf1ed9cee7fac2aaaf1') depends_on('r-zcompositions', when='@1.22.0:', type=('build', 'run')) depends_on('r-biocparallel', type=('build', 'run')) depends_on('r-genomicranges', type=('build', 'run')) depends_on('r-iranges', type=('build', 'run')) depends_on('r-s4vectors', type=('build', 'run')) depends_on('r-summarizedexperiment', type=('build', 'run')) depends_on('r-multtest', when='@1.10.0:', type=('build', 'run'))
LLNL/spack
var/spack/repos/builtin/packages/r-aldex2/package.py
Python
lgpl-2.1
2,126
[ "Bioconductor" ]
e227725599635936f5100ee64801b4a0acbb3ed4bb89d640b75acfb3ef1c4a02
# # Author: Henrique Pereira Coutada Miranda # Date: 18/10/2015 # Parallelize a GW calculation using Yambo # In this example we take advantage of the fact that the q points of the dielectric function # are totally independent calculations so its a good idea to calculate them in separate jobs # These example runs locally, if you want to make it work behind a queing system you need to # modify it accordingly # from __future__ import print_function from yambopy import * from qepy import * yambo = 'yambo' if not os.path.isdir('database'): os.mkdir('database') #check if the nscf cycle is present if os.path.isdir('nscf/bn.save'): print('nscf calculation found!') else: print('nscf calculation not found!') exit() #check if the SAVE folder is present if not os.path.isdir('database/SAVE'): print('preparing yambo database') os.system('cd nscf/bn.save; p2y') os.system('cd nscf/bn.save; yambo') os.system('mv nscf/bn.save/SAVE database') if not os.path.isdir('gw_par'): os.mkdir('gw_par') os.system('cp -r database/SAVE gw_par') #create the yambo input file y = YamboIn('%s -d -V all'%yambo,folder='gw_par') _,nqpoints = y['QpntsRXd'][0] y['FFTGvecs'] = [15,'Ry'] y['NGsBlkXd'] = [1,'Ry'] y['BndsRnXd'] = [[1,30],''] y['ETStpsXd'] = [50,''] #Here we write a range that does not make sense (upper bownd smaller than lower bound) #So that yambo has to calculate it as it would be done when running a calculation in the gw0 runlevel #The following code has to be cahnged in src/pol_function/X_em1.F # if (self_detect_E_range) then # call X_eh_setup(-iq,X,Xen,Xk,minmax_ehe) # deallocate(X_poles) # Xw%er=minmax_ehe # endif #+ ! Start modified by Henrique Miranda #+ ! If the EnRngeXd variable range does not make sense (upper bownd smaller than lower bound) #+ ! we detect the range as in the case self_detect_E_range = .True. #+ if (Xw%er(2) .lt. Xw%er(1)) then #+ call X_eh_setup(-iq,X,Xen,Xk,minmax_ehe) #+ deallocate(X_poles) #+ Xw%er=minmax_ehe #+ endif #+ ! end modified by Henrique Miranda y['EnRngeXd'] = [[1,-1],'eV'] #prepare the q-points input files f = open('jobs.sh','w') for nq in xrange(1,int(nqpoints)+1): y['QpntsRXd'] = [[nq,nq],''] y.write('gw_par/yambo_q%d.in'%nq) if nq != 1: f.write('cd gw_par; %s -F yambo_q%d.in -J %d\n'%(yambo,nq,nq)) f.close() #calculate first q-point and dipoles os.system('cd gw_par; %s -F yambo_q1.in -J 1'%yambo) #copy dipoles to save os.system('cp gw_par/1/ndb.dip* gw_par/SAVE') print('running separate yambo files') os.system('parallel :::: jobs.sh') #gather all the files #os.system('cp merge_eps.py gw_par') os.system('mkdir gw_par/yambo') os.system('cd gw_par; cp 1/ndb.em1* yambo') os.system('cd gw_par; cp */ndb.em1?_fragment_* yambo') y = YamboIn('yambo -d -g n -V all',folder='gw_par') QPKrange,_ = y['QPkrange'] y['QPkrange'] = [QPKrange[:2]+[3,6],''] y['FFTGvecs'] = [15,'Ry'] y['NGsBlkXd'] = [1,'Ry'] y['BndsRnXd'] = [[1,30],''] y['ETStpsXd'] = [50,''] y.write('gw_par/yambo_run.in') os.system('cd gw_par; %s -F yambo_run.in -J yambo'%yambo) y.write('gw_par/yambo_run.in') print('running yambo') os.system('cd gw_par; %s -F yambo_run.in -J yambo'%yambo) #pack the files in .json files pack_files_in_folder('gw_par') #plot the results using yambm analyser ya = YamboAnalyser() print(ya) print('plot all qpoints') ya.plot_gw('qp') print('plot along a path') path = [[ 0, 0, 0], [ 0.5, 0, 0], [1./3, 1/3, 0], [ 0, 0, 0]] ya.plot_gw_path('qp',path) print('done!')
alexandremorlet/yambopy
tutorial/bn/gw_par_bn.py
Python
bsd-3-clause
3,611
[ "Yambo" ]
51ea7bfc90487aa5e442fd734ecf24085c15a2a53dab7029bb09d85aba90d0e0
# -*- coding: utf-8 -*- from __future__ import division import cv2 import numpy as np import os from os.path import isfile, join from os import listdir import math import sys import itertools import urllib import caffe from time import gmtime, strftime from math import cos, sin from subprocess import check_output, STDOUT from json import loads def subsample_inner_circle_img(a, scale, value=0): b = np.zeros(a.shape) + value cv2.circle(b, (a.shape[1] // 2, a.shape[0] // 2), int(scale * 0.9), (1, 1, 1), -1, 8, 0) aa = a * b aa = aa.astype(np.uint8) return aa def extract_filename_in_path(path): return path.split('/')[-1].split('.')[0] def make_folder_tree(name, is_file=True): folder = name if not is_file else os.path.dirname(name) if not os.path.isdir(folder): os.makedirs(folder) def image_load(filename): return (caffe.io.load_image(filename) * 255.).astype(np.uint8) def unsharp_img(a, scale): b = np.zeros(a.shape) cv2.circle(b,(a.shape[1]//2,a.shape[0]//2),int(scale*0.9),(1,1,1),-1,8,0) aa = cv2.addWeighted(a,4,cv2.GaussianBlur(a,(0,0),scale/30),-4,128)*b+128*(1-b) aa = aa.astype(np.uint8) return aa def process_one(img, crop_shape, scale): a = scaleRadius(img, scale) ua = unsharp_img(a, scale) ca = random_crops(ua, shape=crop_shape) return ca def get_curl_pred(fname, thresh_pb1=0.7): res01 = check_output( "curl localhost:5000/models/images/classification/classify_one.json -XPOST -F job_id=20151217-070518-faa7 -F image_file=@%s" % (fname), shell=True) probs01 = dict(loads(res01)['predictions']) res14 = check_output( "curl localhost:5000/models/images/classification/classify_one.json -XPOST -F job_id=20151218-081502-a392 -F image_file=@%s" % (fname), shell=True) probs14 = dict(loads(res14)['predictions']) for k in probs01.iterkeys(): probs01[k] = round(probs01[k] / 100., 3) for k in probs14.iterkeys(): probs14[k] = round(probs14[k] / 100., 3) if probs01['0'] > probs01['1'] or probs01['1'] < thresh_pb1: # Best pred level 0 res = {} best_class = 0 res["level0"] = probs01['0'] for i in range(1, 4): res["level%d" % i] = round(probs01['1'] * probs14['%d' % i], 3) else: # Best pred level 1, 2, 3 or 4 res = {} best_class = -1 max_prob = -1. res["level0"] = 0.0 for i in range(1, 4): prb = probs14['%d' % i] if prb > max_prob: max_prob = prb best_class = i res["level%d" % i] = prb return res, best_class def get_label_prob(probs01, probs14, thresh_pb1=0.7): probs = [] labels = [] num_imgs = probs01.shape[0] for i in range(num_imgs): cl01 = probs01[i, :].argmax() if cl01 == 1: pb1 = probs01[i, 1] > thresh_pb1 if pb1: cl = probs14[i, :].argmax() labels.append(cl + 1) pdict = {} for j in range(probs14.shape[1]): pdict["level_%d" % (j + 1)] = round(probs14[i, j], 4) probs.append(pdict) else: labels.append(0) probs.append({"level_0": round(probs01[i, 0], 4)}) else: labels.append(0) probs.append({"level_0": round(probs01[i, 0], 4)}) return probs, labels def parse_folder(folder, ext='jpeg'): """ Return a list of tuples (filename, label). label = -1 if mode = 'test' mode = 'val', 'test', 'train' """ names = [] for r, ds, fs in os.walk(folder): for f in fs: if ".%s" % ext not in f: continue names.append(os.path.join(r, f)) return names def process_one(img, crop_shape, scale): a = scaleRadius(img, scale) ua = unsharp_img(a, scale) ca = random_crops(ua, shape=crop_shape) return ca def unsharp_img(a, scale): b = np.zeros(a.shape) cv2.circle(b, (a.shape[1] // 2, a.shape[0] // 2), int(scale * 0.9), (1, 1, 1), -1, 8, 0) aa = cv2.addWeighted(a, 4, cv2.GaussianBlur( a, (0, 0), scale / 30), -4, 128) * b + 128 * (1 - b) aa = aa.astype(np.uint8) return aa def files_list(folder, mode): """ Return a list of tuples (filename, label). label = -1 if mode = 'test' mode = 'val', 'test', 'train' """ names = [] for r, ds, fs in os.walk(folder): for f in fs: if '.jpeg' not in f: continue if "test" in mode: names.append((os.path.join(r, f), -1)) continue label = int(r.strip('/').split('/')[-1]) names.append((os.path.join(r, f), label)) return names def get_time(): return strftime("%a, %d %b %Y %H:%M:%S", gmtime()) def test_addDir(dir, path): if not os.path.exists(path + '/' + dir): os.makedirs(path + '/' + dir) return path + '/' + dir def url_imread(url): req = urllib.urlopen(url) arr = np.asarray(bytearray(req.read()), dtype=np.uint8) img = cv2.imdecode(arr, -1) # 'load it as it is' return img def rand_draw(): r = np.random.uniform(-0.15, 0) alpha = np.random.uniform(-3 * np.pi / 180, 3 * np.pi / 180) beta = np.random.uniform(-0.1, 0.1) + alpha hflip = np.random.randint(2) == 0 vflip = np.random.randint(2) == 0 return (r, alpha, beta, hflip, vflip) def distort(center, param, no_rotation=False): r, alpha, beta, hflip, vflip = param if no_rotation: alpha = 0. beta = 0. c00 = (1 + r) * cos(alpha) c01 = (1 + r) * sin(alpha) if hflip: c00 *= -1.0 c01 *= -1.0 c02 = (1 - c00) * center[0] - c01 * center[1] c10 = -(1 - r) * sin(beta) c11 = (1 - r) * cos(beta) if vflip: c10 *= -1.0 c11 *= -1.0 c12 = -c10 * center[0] + (1 - c11) * center[1] M = np.array([[c00, c01, c02], [c10, c11, c12]], dtype=np.float32) return M def get_distorted_img(im, border_value=128, no_rotation=False): if "float" not in im.dtype.name: from skimage import img_as_ubyte im = img_as_ubyte(im) if im.ndim == 3: h, w, c = im.shape out = np.zeros_like(im) param = rand_draw() for i in range(c): out[:, :, i] = cv2.warpAffine(im[:, :, i], distort((w / 2, h / 2), param, no_rotation), im[:, :, 0].T.shape, border_value) elif im.ndim == 2: h, w = im.shape out = np.zeros_like(im) param = rand_draw() for i in range(c): out = cv2.warpAffine(im, distort((w / 2, h / 2), param, no_rotation), im[:, :, 0].shape, border_value) return out def scale_radius(img, scale): h, w, _ = img.shape assert h > 0 and w > 0, ("Error: scale_radius: Shape of input img:" " (%d, %d)" % (h, w)) x = img[h // 2, :, :].sum(1) r = 0 for i in range(10, 20, 2): r = (x > x.mean() / i).sum() / 2 if r > 0: break s = scale * 1.0 / r if r <= 0: print("%s [%s] %s: Non-positive r = %f detected -" " unable to determine scale." % (get_time(), os.getpid(), "WARN", r)) s = scale / w return cv2.resize(img, (0, 0), fx=s, fy=s) def pad_img(im, shape, value=0): out = np.ones(shape, dtype=im.dtype) * value h, w = im.shape[0], im.shape[1] ho, wo = shape[0], shape[1] rows, cols = np.ogrid[-h // 2:h // 2, -w // 2:w // 2] out[rows + (ho + 1) // 2, cols + (wo + 1) // 2] = im return out def random_crops(im, shape=(256, 256)): h, w, _ = im.shape ho, wo = shape if ho > h - 4 or wo > w - 4: im = pad_img(im, (max(h, ho + 4), max(w, wo + 4), 3), 128) h, w, _ = im.shape # Setup multivariate Gaussian sampler mean = [h / 2, w / 2] sigma = np.eye(2, dtype=np.float) sigma[0, 0] = 0.73 * (h - ho) / 2 sigma[1, 1] = 0.73 * (w - wo) / 2 y, x = np.round(np.random.multivariate_normal( mean, sigma, size=1)[0]).astype(np.uint16) y = min(y, h - (ho // 2)) x = min(x, w - (wo // 2)) y = max(y, (ho // 2)) x = max(x, (wo // 2)) rows, cols = np.ogrid[-ho // 2:ho // 2, -wo // 2:wo // 2] # Return appropriate size return im[rows + h//2, cols + w//2] def bbox(im): th = 2 if im is None: return None a = np.mean(im, axis=2, dtype=np.float).mean(axis=0) b = np.mean(im, axis=2, dtype=np.float).mean(axis=1) aidx = np.where(a > th)[0] bidx = np.where(b > th)[0] return im[max(bidx[0] - 1, 0):min(bidx[-1] + 1, im.shape[0]), max(aidx[0] - 1, 0):min(aidx[-1] + 1, im.shape[1])] def brightness_decrease(im, max_dec=30, min_dec=10): br = np.random.randint(min_dec, max_dec) im_clone = im.copy().astype(np.int16) - br im_clone[im_clone < 0] = 0 return im_clone.astype(np.uint8) def brightness_increase(im, max_inc=30, min_inc=10): br = np.random.randint(min_inc, max_inc) im_clone = im.copy().astype(np.uint16) + br im_clone[im_clone > 255] = 255 im_clone[im == 0] = 0 return im_clone.astype(np.uint8) class flushfile(file): def __init__(self, f): self.f = f def write(self, x): self.f.write(x) self.f.flush() def create_fixed_image_shape(img, frame_size=(200, 200, 3), random_fill=False, mode='crop'): image_frame = None if mode == 'fit': X1, Y1, _ = frame_size if random_fill: image_frame = np.asarray(np.random.randint( 0, high=255, size=frame_size), dtype='uint8') else: image_frame = np.zeros(frame_size, dtype='uint8') X2, Y2 = img.shape[1], img.shape[0] if X2 > Y2: X_new = X1 Y_new = int(round(float(Y2 * X_new) / float(X2))) else: Y_new = Y1 X_new = int(round(float(X2 * Y_new) / float(Y2))) img = cv2.resize(img, (X_new, Y_new)) X_space_center = ((X1 - X_new) / 2) Y_space_center = ((Y1 - Y_new) / 2) # print Y_new, X_new, Y_space_center, X_space_center image_frame[Y_space_center: Y_space_center + Y_new, X_space_center: X_space_center + X_new, :] = img elif mode == 'crop': X1, Y1, _ = frame_size image_frame = np.zeros(frame_size, dtype='uint8') X2, Y2 = img.shape[1], img.shape[0] # increase the size of smaller length (width or hegiht) if X2 > Y2: Y_new = Y1 X_new = int(round(float(X2 * Y_new) / float(Y2))) else: X_new = X1 Y_new = int(round(float(Y2 * X_new) / float(X2))) img = cv2.resize(img, (X_new, Y_new)) X_space_clip = (X_new - X1) / 2 Y_space_clip = (Y_new - Y1) / 2 # trim image both top, down, left and right if X_space_clip == 0 and Y_space_clip != 0: img = img[Y_space_clip:-Y_space_clip, :] elif Y_space_clip == 0 and X_space_clip != 0: img = img[:, X_space_clip:-X_space_clip] if img.shape[0] != X1: img = img[1:, :] if img.shape[1] != Y1: img = img[:, 1:] image_frame[:, :] = img return image_frame def reshape_image(img, frame_size=(200, 200, 3), mode='crop'): image = None if mode == 'fit': X1, Y1, _ = frame_size X2, Y2 = img.shape[1], img.shape[0] if X2 > Y2: X_new = X1 Y_new = int(round(float(Y2 * X_new) / float(X2))) else: Y_new = Y1 X_new = int(round(float(X2 * Y_new) / float(Y2))) img = cv2.resize(img, (X_new, Y_new)) X_space_center = ((X1 - X_new) / 2) Y_space_center = ((Y1 - Y_new) / 2) image = img elif mode == 'crop': X1, Y1, _ = frame_size X2, Y2 = img.shape[1], img.shape[0] # increase the size of smaller length (width or hegiht) if X2 > Y2: Y_new = Y1 X_new = int(round(float(X2 * Y_new) / float(Y2))) else: X_new = X1 Y_new = int(round(float(Y2 * X_new) / float(X2))) img = cv2.resize(img, (X_new, Y_new)) X_space_clip = (X_new - X1) / 2 Y_space_clip = (Y_new - Y1) / 2 # trim image both top, down, left and right if X_space_clip == 0 and Y_space_clip != 0: img = img[Y_space_clip:-Y_space_clip, :] elif Y_space_clip == 0 and X_space_clip != 0: img = img[:, X_space_clip:-X_space_clip] if img.shape[0] != X1: img = img[1:, :] if img.shape[1] != Y1: img = img[:, 1:] image = img return image def generate_window_locations(center, patch_shape, stride=0.5, grid_shape=5): assert(grid_shape % 2 != 0), "grid_shape should be odd number" assert(stride != 0), "stride should not be <= 0" center_y, center_x = center string = "" mapping = {} # left is represented as -, center as 0 and right is + if grid_shape % 2 != 0: pointer = xrange(-(grid_shape / 2), (grid_shape / 2) + 1) # else: # pointer = range(-(grid_shape/2)+1, (grid_shape/2)+1) for i, n, in enumerate(pointer): mapping[i] = n string += str(i) windows_list = [] sequences = np.asarray( list(itertools.product(string, repeat=2)), dtype="int32") # if grid_shape%2 != 0: # center_y = (center_y - (stride * patch_shape[0])/2.0) # center_x = (center_x - (stride * patch_shape[1])/2.0) for y, x in sequences: new_center_y, new_center_x = center_y + \ patch_shape[0] * mapping[y] * stride, center_x + \ patch_shape[1] * mapping[x] * stride res = np.asarray([(math.floor(new_center_y) - patch_shape[0] / 2, math.floor(new_center_x) - patch_shape[1] / 2), (math.ceil(new_center_y) + patch_shape[0] / 2, math.ceil(new_center_x) + patch_shape[1] / 2)], dtype="int32") windows_list.append(res) return np.asarray(windows_list).tolist() def getImmediateSubdirectories(dir): """ this function return the immediate subdirectory list eg: dir /subdirectory1 /subdirectory2 . . return ['subdirectory1',subdirectory2',...] """ return [name for name in os.listdir(dir) if os.path.isdir(os.path.join(dir, name))] def getFiles(dir_path): """getFiles : gets the file in specified directory dir_path: String type dir_path: directory path where we get all files """ onlyfiles = [f for f in listdir(dir_path) if isfile(join(dir_path, f))] return onlyfiles def get_num_batch(data_size, batch_size): if data_size % batch_size == 0: return data_size / batch_size return (data_size / batch_size) + 1 def feature_normalization(data, type='standardization', params=None): u""" data: an numpy array type: (standardization, min-max) params {default None}: dictionary if params is provided it is used as mu and sigma when type=standardization else Xmax, Xmin when type=min-max rather then calculating those paramsanter two type of normalization 1) standardization or (Z-score normalization) is that the features will be rescaled so that they'll have the properties of a standard normal distribution with μ = 0 and σ = 1 where μ is the mean (average) and σ is the standard deviation from the mean Z = (X - μ)/σ return: Z, μ, σ 2) min-max normalization the data is scaled to a fixed range - usually 0 to 1. The cost of having this bounded range - in contrast to standardization - is that we will end up with smaller standard deviations, which can suppress the effect of outliers. A Min-Max scaling is typically done via the following equation: Z = (X - Xmin)/(Xmax-Xmin) return Z, Xmax, Xmin """ if type == 'standardization': if params is None: mu = np.mean(data, axis=0) sigma = np.std(data, axis=0) else: mu = params['mu'] sigma = params['sigma'] Z = (data - mu) / sigma return Z, mu, sigma elif type == 'min-max': if params is None: Xmin = np.min(data, axis=0) Xmax = np.max(data, axis=0) else: Xmin = params['Xmin'] Xmax = params['Xmax'] Xmax = Xmax.astype('float') Xmin = Xmin.astype('float') Z = (data - Xmin) / (Xmax - Xmin) return Z, Xmax, Xmin
chintak/misc_codes
utils.py
Python
gpl-2.0
17,329
[ "Gaussian" ]
6c22ffd3a125417fb3bd16565a07156e5bd2a446cbdf8ad29bfa6c8f5dc47f88
# 10/24/2013 Sebastian Raschka # BondVis # PyMOL Plugin for visualization of molecular bonds between atom pairs. import tkSimpleDialog,tkFileDialog import tkMessageBox from pymol import cmd import sys import string import itertools def __init__(self): self.menuBar.addmenuitem('Plugin', 'command', 'BondVis', label = 'BondVis', command = lambda s=self : fetch_bonds_dialog(s)) def load_bonds(bonds_filename): bond_list = [] error_list = list() bondfile = False try: bondfile = open(bonds_filename, "r") for line in bondfile: line_mod = line.strip() if line_mod: line_mod = [i.strip(string.punctuation) for i in line_mod.split()] if len(line_mod) >= 2: try: atoms = [int(line_mod[0]), int(line_mod[1])] if len(line_mod) >= 3: bond_list.append(atoms + [line_mod[2]]) else: bond_list.append(atoms + ['bond']) except ValueError: error_list.append(line) pass if not bond_list: print "Unexpected error:", sys.exc_info()[0] tkMessageBox.showerror('Could no load bond information.', 'Error. Could not detect bonds in \n' + bonds_filename) else: print "\n Detected the following bonds: " for bond in bond_list: print " {} ---- {}".format(bond[0], bond[1]) if error_list: print "\n Warning! Ignored the following line(s):" for err in error_list: print " " + err draw_bonds(bond_list) except: if bondfile: bondfile.close() print "Unexpected error:", sys.exc_info()[0] tkMessageBox.showerror('Could not open file.', 'Error. Could not open file: \n' + bonds_filename) def fetch_bonds_dialog(app): bonds_filename = tkFileDialog.askopenfilename(parent=app.root,title='Open bond info file') load_bonds(bonds_filename) def draw_bonds(bond_list): c = itertools.cycle(("yellow", "blue", "green", "red", "white", "black")) colors = dict() for t in bond_list: if t[2] not in colors: colors[t[2]] = c.next() for bond in bond_list: print(bond_list) cmd.distance("%s" % bond[2], "id %s" % bond[0], "id %s" % bond[1]) cmd.set("dash_color", colors[bond[2]], "%s" % bond[2]) cmd.hide("labels") cmd.set("dash_gap", 0.20) #cmd.extend('load_bonds', load_bonds)
rasbt/BondPack
src/BondVis.py
Python
gpl-3.0
2,744
[ "PyMOL" ]
728cc69fe5b710facbcf48918afea97d4fb8b368e57304968a3a35b54104eeaf
import json from operator import attrgetter import click from click import echo, echo_via_pager from .api import JiffyBox from .format import PlainFormatVisitor API = None OUTPUT_FORMAT = None USE_PAGER = None def sort_data(data): return sorted(data, key=attrgetter('id')) def format_data(data): data = sort_data(data) if OUTPUT_FORMAT == 'plain': return '\n\n'.join(PlainFormatVisitor().visit(box) for box in data) # FIXME id on top in json elif OUTPUT_FORMAT == 'json': return '\n'.join([json.dumps(elem.json) for elem in data]) elif OUTPUT_FORMAT == 'json-pretty': return '\n'.join([json.dumps(elem.json, indent=2) for elem in data]) def output(data): if USE_PAGER: echo_via_pager(data) else: echo(data) def print_data(data): output(format_data(data)) @click.group() @click.version_option() @click.option('--api-key', envvar='JIFFYBOX_API_KEY', help='also read from JIFFYBOX_API_KEY', required=True) @click.option('-v', '--verbose', count=True) @click.option('--output-format', type=click.Choice(['plain', 'json', 'json-pretty'])) @click.option('--pager', is_flag=True) def jiffybox(api_key, verbose, output_format, pager): global API, OUTPUT_FORMAT, USE_PAGER API = JiffyBox(api_key=api_key) OUTPUT_FORMAT = output_format or 'plain' USE_PAGER = pager @jiffybox.group('box', help='Manages boxes') def box(): pass @box.command('list', help='Lists all boxes in account') @click.option('--quiet', '-q', is_flag=True, default=False, help='Suppress warning at the start') def list_boxes(quiet): if not quiet: echo('Please use this API call sparingly; see ' 'https://www.df.eu/fileadmin/user_upload/' 'jiffybox-api-dokumentation.pdf [pg. 10] for details.', err=True) print_data(API.boxes()) @box.command('show', help='Shows a single box') @click.argument('id') def show_box(id): box = API.box(id) print_data([box]) @box.command('create', help='Creates and start a new box') @click.argument('name') @click.argument('plan') @click.argument('distribution') @click.option('--sshkey/--no-sshkey', is_flag=True, default=True) def create_box(name, plan, distribution, sshkey): box = API.create_box(name, plan, distribution=distribution, use_sshkey=sshkey) print_data([box]) @box.command('delete', help='Deletes a box') @click.argument('id') @click.option('--no-confirm', is_flag=True, default=False) @click.option('--force', '-f', is_flag=True, help='Stop jiffybox if necessary') def delete_box(id, no_confirm, force): box = API.box(id) box_desc = '{0} ({1})'.format(box.id, box.name) if not no_confirm: click.confirm('Really delete box {}?'.format(box_desc), abort=True) echo('Waiting for box to become ready') box.wait_for_status() if box.running and force: echo('Stopping box {}'.format(box_desc)) box.stop() box.wait_for_status() if not box.delete(): raise click.exceptions.RuntimeError('could not delete box') echo('Removed box {}'.format(box_desc)) @jiffybox.command(help='Shows a list of distributions') def distributions(): print_data(API.distributions()) @jiffybox.command(help='Shows a list of pricing plans') def plans(): print_data(API.plans())
AmadeusITGroup/python-jiffybox
jiffybox/cli.py
Python
gpl-3.0
3,486
[ "VisIt" ]
137828d072e29bec272d961f825c20f1c3d97e5b43262f4ee511a9fdbb8308de
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 """A python based tool for interfacial molecules analysis """ # To use a consistent encoding import codecs import os import sys # Always prefer setuptools over distutils try: from setuptools import find_packages from Cython.Distutils import build_ext import numpy except ImportError as mod_error: mod_name = mod_error.message.split()[3] sys.stderr.write("Error : " + mod_name + " is not installed\n" "Use pip install " + mod_name + "\n") exit(100) from setuptools import setup from setuptools.command.test import test as TestCommand from distutils.extension import Extension class NoseTestCommand(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # Run nose ensuring that argv simulates running nosetests directly import nose nose.run_exit(argv=['nosetests']) pytim_dbscan = Extension( "pytim_dbscan", ["pytim/dbscan_inner.pyx"], language="c++", include_dirs=[numpy.get_include()]) circumradius = Extension( "circumradius", ["pytim/circumradius.pyx"], language="c++", include_dirs=[numpy.get_include()]) here = os.path.abspath(os.path.dirname(__file__)) # Get the long description from the README file with codecs.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() # This fixes the default architecture flags of Apple's python if sys.platform == 'darwin' and os.path.exists('/usr/bin/xcodebuild'): os.environ['ARCHFLAGS'] = '' # Get version from the file version.py version = {} with open("pytim/version.py") as fp: exec(fp.read(), version) setup( name='pytim', ext_modules=[pytim_dbscan, circumradius], cmdclass={ 'build_ext': build_ext, 'test': NoseTestCommand }, # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version=version['__version__'], description='Python Tool for Interfacial Molecules Analysis', long_description=long_description, # The project's main homepage. url='https://github.com/Marcello-Sega/pytim', # Author details author='Marcello Sega, Balazs Fabian, Gyorgy Hantal, Pal Jedlovszky', author_email='marcello.sega@univie.ac.at', # Choose your license license='GPLv3', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Topic :: Scientific/Engineering :: Chemistry', 'Topic :: Scientific/Engineering :: Physics', 'Topic :: Software Development :: Libraries :: Python Modules', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], # What does your project relate to? keywords='molecular simuations analysis ', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=[ 'MDAnalysis>=1.0.0', 'PyWavelets>=0.5.2', 'numpy>=1.16', 'scipy>=1.1', 'scikit-image>=0.14.2', 'cython>=0.24.1', 'sphinx>=1.4.3', 'matplotlib', 'pytest', 'dask>=1.1.1' ], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] tests_require=['nose>=1.3.7', 'coverage'], # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ 'pytim': ['data/*'], }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' ## data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. # entry_points={ # 'console_scripts': [ # 'sample=sample:main', # ], # }, )
Marcello-Sega/pytim
setup.py
Python
gpl-3.0
5,678
[ "MDAnalysis" ]
cbeb4543f66d60210b2bde003a28238d7ed73c756ea2945961892cfd9ae297e8
#!/usr/bin/env python # -*- coding: utf-8 -*- # # gaussian_class.py # # Copyright 2017 ssd <ssd@ssd> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # # http://scikit-learn.org/stable/auto_examples/preprocessing/plot_robust_scaling.html#sphx-glr-auto-examples-preprocessing-plot-robust-scaling-py import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.datasets import make_blobs from sklearn.datasets import make_gaussian_quantiles import numpy as np def main(args): #plt.figure(figsize=(8, 8)) #plt.title("Gaussian divided into three quantiles", fontsize='small') #X1, Y1 = make_gaussian_quantiles(n_features=2, n_classes=3) #plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) #plt.show() plt.figure(figsize=(8, 8)) plt.title("Gaussian divided i", fontsize='small') X1, Y1 = make_gaussian_quantiles(n_features=1, n_classes=3) feat = X1[:, 0] print(np.min(feat), np.mean(feat), np.max(feat) ) plt.scatter(feat, len(feat) * [1], marker='o', c=Y1) plt.show() return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
cimadure/programming-on-purpose
gaussian_class.py
Python
gpl-3.0
1,792
[ "Gaussian" ]
bb2c7d5ecc51fb70db5e93e1e4af1c17ea1bc7b64009507fb6adb5a738f4dbec
#!/usr/bin/env python # # Copyright 2008 Jose Fonseca # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # '''Visualize dot graphs via the xdot format.''' __author__ = "Jose Fonseca" import os import sys import subprocess import math import colorsys import time import re import gobject import gtk import gtk.gdk import gtk.keysyms import cairo import pango import pangocairo # See http://www.graphviz.org/pub/scm/graphviz-cairo/plugin/cairo/gvrender_cairo.c # For pygtk inspiration and guidance see: # - http://mirageiv.berlios.de/ # - http://comix.sourceforge.net/ class Pen: """Store pen attributes.""" def __init__(self): # set default attributes self.color = (0.0, 0.0, 0.0, 1.0) self.fillcolor = (0.0, 0.0, 0.0, 1.0) self.linewidth = 1.0 self.fontsize = 14.0 self.fontname = "Times-Roman" self.dash = () def copy(self): """Create a copy of this pen.""" pen = Pen() pen.__dict__ = self.__dict__.copy() return pen def highlighted(self): pen = self.copy() pen.color = (1, 0, 0, 1) pen.fillcolor = (1, .8, .8, 1) return pen class Shape: """Abstract base class for all the drawing shapes.""" def __init__(self): pass def draw(self, cr, highlight=False): """Draw this shape with the given cairo context""" raise NotImplementedError def select_pen(self, highlight): if highlight: if not hasattr(self, 'highlight_pen'): self.highlight_pen = self.pen.highlighted() return self.highlight_pen else: return self.pen class TextShape(Shape): #fontmap = pangocairo.CairoFontMap() #fontmap.set_resolution(72) #context = fontmap.create_context() LEFT, CENTER, RIGHT = -1, 0, 1 def __init__(self, pen, x, y, j, w, t): Shape.__init__(self) self.pen = pen.copy() self.x = x self.y = y self.j = j self.w = w self.t = t def draw(self, cr, highlight=False): try: layout = self.layout except AttributeError: layout = cr.create_layout() # set font options # see http://lists.freedesktop.org/archives/cairo/2007-February/009688.html context = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_DEFAULT) fo.set_hint_style(cairo.HINT_STYLE_NONE) fo.set_hint_metrics(cairo.HINT_METRICS_OFF) try: pangocairo.context_set_font_options(context, fo) except TypeError: # XXX: Some broken pangocairo bindings show the error # 'TypeError: font_options must be a cairo.FontOptions or None' pass # set font font = pango.FontDescription() font.set_family(self.pen.fontname) font.set_absolute_size(self.pen.fontsize*pango.SCALE) layout.set_font_description(font) # set text layout.set_text(self.t) # cache it self.layout = layout else: cr.update_layout(layout) descent = 2 # XXX get descender from font metrics width, height = layout.get_size() width = float(width)/pango.SCALE height = float(height)/pango.SCALE # we know the width that dot thinks this text should have # we do not necessarily have a font with the same metrics # scale it so that the text fits inside its box if width > self.w: f = self.w / width width = self.w # equivalent to width *= f height *= f descent *= f else: f = 1.0 if self.j == self.LEFT: x = self.x elif self.j == self.CENTER: x = self.x - 0.5*width elif self.j == self.RIGHT: x = self.x - width else: assert 0 y = self.y - height + descent cr.move_to(x, y) cr.save() cr.scale(f, f) cr.set_source_rgba(*self.select_pen(highlight).color) cr.show_layout(layout) cr.restore() if 0: # DEBUG # show where dot thinks the text should appear cr.set_source_rgba(1, 0, 0, .9) if self.j == self.LEFT: x = self.x elif self.j == self.CENTER: x = self.x - 0.5*self.w elif self.j == self.RIGHT: x = self.x - self.w cr.move_to(x, self.y) cr.line_to(x+self.w, self.y) cr.stroke() class ImageShape(Shape): def __init__(self, pen, x0, y0, w, h, path): Shape.__init__(self) self.pen = pen.copy() self.x0 = x0 self.y0 = y0 self.w = w self.h = h self.path = path def draw(self, cr, highlight=False): cr2 = gtk.gdk.CairoContext(cr) pixbuf = gtk.gdk.pixbuf_new_from_file(self.path) sx = float(self.w)/float(pixbuf.get_width()) sy = float(self.h)/float(pixbuf.get_height()) cr.save() cr.translate(self.x0, self.y0 - self.h) cr.scale(sx, sy) cr2.set_source_pixbuf(pixbuf, 0, 0) cr2.paint() cr.restore() class EllipseShape(Shape): def __init__(self, pen, x0, y0, w, h, filled=False): Shape.__init__(self) self.pen = pen.copy() self.x0 = x0 self.y0 = y0 self.w = w self.h = h self.filled = filled def draw(self, cr, highlight=False): cr.save() cr.translate(self.x0, self.y0) cr.scale(self.w, self.h) cr.move_to(1.0, 0.0) cr.arc(0.0, 0.0, 1.0, 0, 2.0*math.pi) cr.restore() pen = self.select_pen(highlight) if self.filled: cr.set_source_rgba(*pen.fillcolor) cr.fill() else: cr.set_dash(pen.dash) cr.set_line_width(pen.linewidth) cr.set_source_rgba(*pen.color) cr.stroke() class PolygonShape(Shape): def __init__(self, pen, points, filled=False): Shape.__init__(self) self.pen = pen.copy() self.points = points self.filled = filled def draw(self, cr, highlight=False): x0, y0 = self.points[-1] cr.move_to(x0, y0) for x, y in self.points: cr.line_to(x, y) cr.close_path() pen = self.select_pen(highlight) if self.filled: cr.set_source_rgba(*pen.fillcolor) cr.fill_preserve() cr.fill() else: cr.set_dash(pen.dash) cr.set_line_width(pen.linewidth) cr.set_source_rgba(*pen.color) cr.stroke() class LineShape(Shape): def __init__(self, pen, points): Shape.__init__(self) self.pen = pen.copy() self.points = points def draw(self, cr, highlight=False): x0, y0 = self.points[0] cr.move_to(x0, y0) for x1, y1 in self.points[1:]: cr.line_to(x1, y1) pen = self.select_pen(highlight) cr.set_dash(pen.dash) cr.set_line_width(pen.linewidth) cr.set_source_rgba(*pen.color) cr.stroke() class BezierShape(Shape): def __init__(self, pen, points, filled=False): Shape.__init__(self) self.pen = pen.copy() self.points = points self.filled = filled def draw(self, cr, highlight=False): x0, y0 = self.points[0] cr.move_to(x0, y0) for i in xrange(1, len(self.points), 3): x1, y1 = self.points[i] x2, y2 = self.points[i + 1] x3, y3 = self.points[i + 2] cr.curve_to(x1, y1, x2, y2, x3, y3) pen = self.select_pen(highlight) if self.filled: cr.set_source_rgba(*pen.fillcolor) cr.fill_preserve() cr.fill() else: cr.set_dash(pen.dash) cr.set_line_width(pen.linewidth) cr.set_source_rgba(*pen.color) cr.stroke() class CompoundShape(Shape): def __init__(self, shapes): Shape.__init__(self) self.shapes = shapes def draw(self, cr, highlight=False): for shape in self.shapes: shape.draw(cr, highlight=highlight) class Url(object): def __init__(self, item, url, highlight=None): self.item = item self.url = url if highlight is None: highlight = set([item]) self.highlight = highlight class Jump(object): def __init__(self, item, x, y, highlight=None): self.item = item self.x = x self.y = y if highlight is None: highlight = set([item]) self.highlight = highlight class Element(CompoundShape): """Base class for graph nodes and edges.""" def __init__(self, shapes): CompoundShape.__init__(self, shapes) def get_url(self, x, y): return None def get_jump(self, x, y): return None class Node(Element): def __init__(self, x, y, w, h, shapes, url): Element.__init__(self, shapes) self.x = x self.y = y self.x1 = x - 0.5*w self.y1 = y - 0.5*h self.x2 = x + 0.5*w self.y2 = y + 0.5*h self.url = url def is_inside(self, x, y): return self.x1 <= x and x <= self.x2 and self.y1 <= y and y <= self.y2 def get_url(self, x, y): if self.url is None: return None #print (x, y), (self.x1, self.y1), "-", (self.x2, self.y2) if self.is_inside(x, y): return Url(self, self.url) return None def get_jump(self, x, y): if self.is_inside(x, y): return Jump(self, self.x, self.y) return None def square_distance(x1, y1, x2, y2): deltax = x2 - x1 deltay = y2 - y1 return deltax*deltax + deltay*deltay class Edge(Element): def __init__(self, src, dst, points, shapes): Element.__init__(self, shapes) self.src = src self.dst = dst self.points = points RADIUS = 10 def get_jump(self, x, y): if square_distance(x, y, *self.points[0]) <= self.RADIUS*self.RADIUS: return Jump(self, self.dst.x, self.dst.y, highlight=set([self, self.dst])) if square_distance(x, y, *self.points[-1]) <= self.RADIUS*self.RADIUS: return Jump(self, self.src.x, self.src.y, highlight=set([self, self.src])) return None class Graph(Shape): def __init__(self, width=1, height=1, shapes=(), nodes=(), edges=()): Shape.__init__(self) self.width = width self.height = height self.shapes = shapes self.nodes = nodes self.edges = edges def get_size(self): return self.width, self.height def draw(self, cr, highlight_items=None): if highlight_items is None: highlight_items = () cr.set_source_rgba(0.0, 0.0, 0.0, 1.0) cr.set_line_cap(cairo.LINE_CAP_BUTT) cr.set_line_join(cairo.LINE_JOIN_MITER) for shape in self.shapes: shape.draw(cr) for edge in self.edges: edge.draw(cr, highlight=(edge in highlight_items)) for node in self.nodes: node.draw(cr, highlight=(node in highlight_items)) def get_url(self, x, y): for node in self.nodes: url = node.get_url(x, y) if url is not None: return url return None def get_jump(self, x, y): for edge in self.edges: jump = edge.get_jump(x, y) if jump is not None: return jump for node in self.nodes: jump = node.get_jump(x, y) if jump is not None: return jump return None class XDotAttrParser: """Parser for xdot drawing attributes. See also: - http://www.graphviz.org/doc/info/output.html#d:xdot """ def __init__(self, parser, buf): self.parser = parser self.buf = buf self.pos = 0 self.pen = Pen() self.shapes = [] def __nonzero__(self): return self.pos < len(self.buf) def read_code(self): pos = self.buf.find(" ", self.pos) res = self.buf[self.pos:pos] self.pos = pos + 1 while self.pos < len(self.buf) and self.buf[self.pos].isspace(): self.pos += 1 return res def read_number(self): return int(self.read_code()) def read_float(self): return float(self.read_code()) def read_point(self): x = self.read_number() y = self.read_number() return self.transform(x, y) def read_text(self): num = self.read_number() pos = self.buf.find("-", self.pos) + 1 self.pos = pos + num res = self.buf[pos:self.pos] while self.pos < len(self.buf) and self.buf[self.pos].isspace(): self.pos += 1 return res def read_polygon(self): n = self.read_number() p = [] for i in range(n): x, y = self.read_point() p.append((x, y)) return p def read_color(self): # See http://www.graphviz.org/doc/info/attrs.html#k:color c = self.read_text() c1 = c[:1] if c1 == '#': hex2float = lambda h: float(int(h, 16)/255.0) r = hex2float(c[1:3]) g = hex2float(c[3:5]) b = hex2float(c[5:7]) try: a = hex2float(c[7:9]) except (IndexError, ValueError): a = 1.0 return r, g, b, a elif c1.isdigit() or c1 == ".": # "H,S,V" or "H S V" or "H, S, V" or any other variation h, s, v = map(float, c.replace(",", " ").split()) r, g, b = colorsys.hsv_to_rgb(h, s, v) a = 1.0 return r, g, b, a else: return self.lookup_color(c) def lookup_color(self, c): try: color = gtk.gdk.color_parse(c) except ValueError: pass else: s = 1.0/65535.0 r = color.red*s g = color.green*s b = color.blue*s a = 1.0 return r, g, b, a try: dummy, scheme, index = c.split('/') r, g, b = brewer_colors[scheme][int(index)] except (ValueError, KeyError): pass else: s = 1.0/255.0 r = r*s g = g*s b = b*s a = 1.0 return r, g, b, a sys.stderr.write("unknown color '%s'\n" % c) return None def parse(self): s = self while s: op = s.read_code() if op == "c": color = s.read_color() if color is not None: self.handle_color(color, filled=False) elif op == "C": color = s.read_color() if color is not None: self.handle_color(color, filled=True) elif op == "S": # http://www.graphviz.org/doc/info/attrs.html#k:style style = s.read_text() if style.startswith("setlinewidth("): lw = style.split("(")[1].split(")")[0] lw = float(lw) self.handle_linewidth(lw) elif style in ("solid", "dashed", "dotted"): self.handle_linestyle(style) elif op == "F": size = s.read_float() name = s.read_text() self.handle_font(size, name) elif op == "T": x, y = s.read_point() j = s.read_number() w = s.read_number() t = s.read_text() self.handle_text(x, y, j, w, t) elif op == "E": x0, y0 = s.read_point() w = s.read_number() h = s.read_number() self.handle_ellipse(x0, y0, w, h, filled=True) elif op == "e": x0, y0 = s.read_point() w = s.read_number() h = s.read_number() self.handle_ellipse(x0, y0, w, h, filled=False) elif op == "L": points = self.read_polygon() self.handle_line(points) elif op == "B": points = self.read_polygon() self.handle_bezier(points, filled=False) elif op == "b": points = self.read_polygon() self.handle_bezier(points, filled=True) elif op == "P": points = self.read_polygon() self.handle_polygon(points, filled=True) elif op == "p": points = self.read_polygon() self.handle_polygon(points, filled=False) elif op == "I": x0, y0 = s.read_point() w = s.read_number() h = s.read_number() path = s.read_text() self.handle_image(x0, y0, w, h, path) else: sys.stderr.write("unknown xdot opcode '%s'\n" % op) break return self.shapes def transform(self, x, y): return self.parser.transform(x, y) def handle_color(self, color, filled=False): if filled: self.pen.fillcolor = color else: self.pen.color = color def handle_linewidth(self, linewidth): self.pen.linewidth = linewidth def handle_linestyle(self, style): if style == "solid": self.pen.dash = () elif style == "dashed": self.pen.dash = (6, ) # 6pt on, 6pt off elif style == "dotted": self.pen.dash = (2, 4) # 2pt on, 4pt off def handle_font(self, size, name): self.pen.fontsize = size self.pen.fontname = name def handle_text(self, x, y, j, w, t): self.shapes.append(TextShape(self.pen, x, y, j, w, t)) def handle_ellipse(self, x0, y0, w, h, filled=False): if filled: # xdot uses this to mean "draw a filled shape with an outline" self.shapes.append(EllipseShape(self.pen, x0, y0, w, h, filled=True)) self.shapes.append(EllipseShape(self.pen, x0, y0, w, h)) def handle_image(self, x0, y0, w, h, path): self.shapes.append(ImageShape(self.pen, x0, y0, w, h, path)) def handle_line(self, points): self.shapes.append(LineShape(self.pen, points)) def handle_bezier(self, points, filled=False): if filled: # xdot uses this to mean "draw a filled shape with an outline" self.shapes.append(BezierShape(self.pen, points, filled=True)) self.shapes.append(BezierShape(self.pen, points)) def handle_polygon(self, points, filled=False): if filled: # xdot uses this to mean "draw a filled shape with an outline" self.shapes.append(PolygonShape(self.pen, points, filled=True)) self.shapes.append(PolygonShape(self.pen, points)) EOF = -1 SKIP = -2 class ParseError(Exception): def __init__(self, msg=None, filename=None, line=None, col=None): self.msg = msg self.filename = filename self.line = line self.col = col def __str__(self): return ':'.join([str(part) for part in (self.filename, self.line, self.col, self.msg) if part != None]) class Scanner: """Stateless scanner.""" # should be overriden by derived classes tokens = [] symbols = {} literals = {} ignorecase = False def __init__(self): flags = re.DOTALL if self.ignorecase: flags |= re.IGNORECASE self.tokens_re = re.compile( '|'.join(['(' + regexp + ')' for type, regexp, test_lit in self.tokens]), flags ) def next(self, buf, pos): if pos >= len(buf): return EOF, '', pos mo = self.tokens_re.match(buf, pos) if mo: text = mo.group() type, regexp, test_lit = self.tokens[mo.lastindex - 1] pos = mo.end() if test_lit: type = self.literals.get(text, type) return type, text, pos else: c = buf[pos] return self.symbols.get(c, None), c, pos + 1 class Token: def __init__(self, type, text, line, col): self.type = type self.text = text self.line = line self.col = col class Lexer: # should be overriden by derived classes scanner = None tabsize = 8 newline_re = re.compile(r'\r\n?|\n') def __init__(self, buf = None, pos = 0, filename = None, fp = None): if fp is not None: try: fileno = fp.fileno() length = os.path.getsize(fp.name) import mmap except: # read whole file into memory buf = fp.read() pos = 0 else: # map the whole file into memory if length: # length must not be zero buf = mmap.mmap(fileno, length, access = mmap.ACCESS_READ) pos = os.lseek(fileno, 0, 1) else: buf = '' pos = 0 if filename is None: try: filename = fp.name except AttributeError: filename = None self.buf = buf self.pos = pos self.line = 1 self.col = 1 self.filename = filename def next(self): while True: # save state pos = self.pos line = self.line col = self.col type, text, endpos = self.scanner.next(self.buf, pos) assert pos + len(text) == endpos self.consume(text) type, text = self.filter(type, text) self.pos = endpos if type == SKIP: continue elif type is None: msg = 'unexpected char ' if text >= ' ' and text <= '~': msg += "'%s'" % text else: msg += "0x%X" % ord(text) raise ParseError(msg, self.filename, line, col) else: break return Token(type = type, text = text, line = line, col = col) def consume(self, text): # update line number pos = 0 for mo in self.newline_re.finditer(text, pos): self.line += 1 self.col = 1 pos = mo.end() # update column number while True: tabpos = text.find('\t', pos) if tabpos == -1: break self.col += tabpos - pos self.col = ((self.col - 1)//self.tabsize + 1)*self.tabsize + 1 pos = tabpos + 1 self.col += len(text) - pos class Parser: def __init__(self, lexer): self.lexer = lexer self.lookahead = self.lexer.next() def match(self, type): if self.lookahead.type != type: raise ParseError( msg = 'unexpected token %r' % self.lookahead.text, filename = self.lexer.filename, line = self.lookahead.line, col = self.lookahead.col) def skip(self, type): while self.lookahead.type != type: self.consume() def consume(self): token = self.lookahead self.lookahead = self.lexer.next() return token ID = 0 STR_ID = 1 HTML_ID = 2 EDGE_OP = 3 LSQUARE = 4 RSQUARE = 5 LCURLY = 6 RCURLY = 7 COMMA = 8 COLON = 9 SEMI = 10 EQUAL = 11 PLUS = 12 STRICT = 13 GRAPH = 14 DIGRAPH = 15 NODE = 16 EDGE = 17 SUBGRAPH = 18 class DotScanner(Scanner): # token regular expression table tokens = [ # whitespace and comments (SKIP, r'[ \t\f\r\n\v]+|' r'//[^\r\n]*|' r'/\*.*?\*/|' r'#[^\r\n]*', False), # Alphanumeric IDs (ID, r'[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*', True), # Numeric IDs (ID, r'-?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)', False), # String IDs (STR_ID, r'"[^"\\]*(?:\\.[^"\\]*)*"', False), # HTML IDs (HTML_ID, r'<[^<>]*(?:<[^<>]*>[^<>]*)*>', False), # Edge operators (EDGE_OP, r'-[>-]', False), ] # symbol table symbols = { '[': LSQUARE, ']': RSQUARE, '{': LCURLY, '}': RCURLY, ',': COMMA, ':': COLON, ';': SEMI, '=': EQUAL, '+': PLUS, } # literal table literals = { 'strict': STRICT, 'graph': GRAPH, 'digraph': DIGRAPH, 'node': NODE, 'edge': EDGE, 'subgraph': SUBGRAPH, } ignorecase = True class DotLexer(Lexer): scanner = DotScanner() def filter(self, type, text): # TODO: handle charset if type == STR_ID: text = text[1:-1] # line continuations text = text.replace('\\\r\n', '') text = text.replace('\\\r', '') text = text.replace('\\\n', '') # quotes text = text.replace('\\"', '"') # layout engines recognize other escape codes (many non-standard) # but we don't translate them here type = ID elif type == HTML_ID: text = text[1:-1] type = ID return type, text class DotParser(Parser): def __init__(self, lexer): Parser.__init__(self, lexer) self.graph_attrs = {} self.node_attrs = {} self.edge_attrs = {} def parse(self): self.parse_graph() self.match(EOF) def parse_graph(self): if self.lookahead.type == STRICT: self.consume() self.skip(LCURLY) self.consume() while self.lookahead.type != RCURLY: self.parse_stmt() self.consume() def parse_subgraph(self): id = None if self.lookahead.type == SUBGRAPH: self.consume() if self.lookahead.type == ID: id = self.lookahead.text self.consume() if self.lookahead.type == LCURLY: self.consume() while self.lookahead.type != RCURLY: self.parse_stmt() self.consume() return id def parse_stmt(self): if self.lookahead.type == GRAPH: self.consume() attrs = self.parse_attrs() self.graph_attrs.update(attrs) self.handle_graph(attrs) elif self.lookahead.type == NODE: self.consume() self.node_attrs.update(self.parse_attrs()) elif self.lookahead.type == EDGE: self.consume() self.edge_attrs.update(self.parse_attrs()) elif self.lookahead.type in (SUBGRAPH, LCURLY): self.parse_subgraph() else: id = self.parse_node_id() if self.lookahead.type == EDGE_OP: self.consume() node_ids = [id, self.parse_node_id()] while self.lookahead.type == EDGE_OP: node_ids.append(self.parse_node_id()) attrs = self.parse_attrs() for i in range(0, len(node_ids) - 1): self.handle_edge(node_ids[i], node_ids[i + 1], attrs) elif self.lookahead.type == EQUAL: self.consume() self.parse_id() else: attrs = self.parse_attrs() self.handle_node(id, attrs) if self.lookahead.type == SEMI: self.consume() def parse_attrs(self): attrs = {} while self.lookahead.type == LSQUARE: self.consume() while self.lookahead.type != RSQUARE: name, value = self.parse_attr() attrs[name] = value if self.lookahead.type == COMMA: self.consume() self.consume() return attrs def parse_attr(self): name = self.parse_id() if self.lookahead.type == EQUAL: self.consume() value = self.parse_id() else: value = 'true' return name, value def parse_node_id(self): node_id = self.parse_id() if self.lookahead.type == COLON: self.consume() port = self.parse_id() if self.lookahead.type == COLON: self.consume() compass_pt = self.parse_id() else: compass_pt = None else: port = None compass_pt = None # XXX: we don't really care about port and compass point values when parsing xdot return node_id def parse_id(self): self.match(ID) id = self.lookahead.text self.consume() return id def handle_graph(self, attrs): pass def handle_node(self, id, attrs): pass def handle_edge(self, src_id, dst_id, attrs): pass class XDotParser(DotParser): def __init__(self, xdotcode): lexer = DotLexer(buf = xdotcode) DotParser.__init__(self, lexer) self.nodes = [] self.edges = [] self.shapes = [] self.node_by_name = {} self.top_graph = True def handle_graph(self, attrs): if self.top_graph: try: bb = attrs['bb'] except KeyError: return if not bb: return xmin, ymin, xmax, ymax = map(float, bb.split(",")) self.xoffset = -xmin self.yoffset = -ymax self.xscale = 1.0 self.yscale = -1.0 # FIXME: scale from points to pixels self.width = max(xmax - xmin, 1) self.height = max(ymax - ymin, 1) self.top_graph = False for attr in ("_draw_", "_ldraw_", "_hdraw_", "_tdraw_", "_hldraw_", "_tldraw_"): if attr in attrs: parser = XDotAttrParser(self, attrs[attr]) self.shapes.extend(parser.parse()) def handle_node(self, id, attrs): try: pos = attrs['pos'] except KeyError: return x, y = self.parse_node_pos(pos) w = float(attrs.get('width', 0))*72 h = float(attrs.get('height', 0))*72 shapes = [] for attr in ("_draw_", "_ldraw_"): if attr in attrs: parser = XDotAttrParser(self, attrs[attr]) shapes.extend(parser.parse()) url = attrs.get('URL', None) node = Node(x, y, w, h, shapes, url) self.node_by_name[id] = node if shapes: self.nodes.append(node) def handle_edge(self, src_id, dst_id, attrs): try: pos = attrs['pos'] except KeyError: return points = self.parse_edge_pos(pos) shapes = [] for attr in ("_draw_", "_ldraw_", "_hdraw_", "_tdraw_", "_hldraw_", "_tldraw_"): if attr in attrs: parser = XDotAttrParser(self, attrs[attr]) shapes.extend(parser.parse()) if shapes: src = self.node_by_name[src_id] dst = self.node_by_name[dst_id] self.edges.append(Edge(src, dst, points, shapes)) def parse(self): DotParser.parse(self) return Graph(self.width, self.height, self.shapes, self.nodes, self.edges) def parse_node_pos(self, pos): x, y = pos.split(",") return self.transform(float(x), float(y)) def parse_edge_pos(self, pos): points = [] for entry in pos.split(' '): fields = entry.split(',') try: x, y = fields except ValueError: # TODO: handle start/end points continue else: points.append(self.transform(float(x), float(y))) return points def transform(self, x, y): # XXX: this is not the right place for this code x = (x + self.xoffset)*self.xscale y = (y + self.yoffset)*self.yscale return x, y class Animation(object): step = 0.03 # seconds def __init__(self, dot_widget): self.dot_widget = dot_widget self.timeout_id = None def start(self): self.timeout_id = gobject.timeout_add(int(self.step * 1000), self.tick) def stop(self): self.dot_widget.animation = NoAnimation(self.dot_widget) if self.timeout_id is not None: gobject.source_remove(self.timeout_id) self.timeout_id = None def tick(self): self.stop() class NoAnimation(Animation): def start(self): pass def stop(self): pass class LinearAnimation(Animation): duration = 0.6 def start(self): self.started = time.time() Animation.start(self) def tick(self): t = (time.time() - self.started) / self.duration self.animate(max(0, min(t, 1))) return (t < 1) def animate(self, t): pass class MoveToAnimation(LinearAnimation): def __init__(self, dot_widget, target_x, target_y): Animation.__init__(self, dot_widget) self.source_x = dot_widget.x self.source_y = dot_widget.y self.target_x = target_x self.target_y = target_y def animate(self, t): sx, sy = self.source_x, self.source_y tx, ty = self.target_x, self.target_y self.dot_widget.x = tx * t + sx * (1-t) self.dot_widget.y = ty * t + sy * (1-t) self.dot_widget.queue_draw() class ZoomToAnimation(MoveToAnimation): def __init__(self, dot_widget, target_x, target_y): MoveToAnimation.__init__(self, dot_widget, target_x, target_y) self.source_zoom = dot_widget.zoom_ratio self.target_zoom = self.source_zoom self.extra_zoom = 0 middle_zoom = 0.5 * (self.source_zoom + self.target_zoom) distance = math.hypot(self.source_x - self.target_x, self.source_y - self.target_y) rect = self.dot_widget.get_allocation() visible = min(rect.width, rect.height) / self.dot_widget.zoom_ratio visible *= 0.9 if distance > 0: desired_middle_zoom = visible / distance self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom)) def animate(self, t): a, b, c = self.source_zoom, self.extra_zoom, self.target_zoom self.dot_widget.zoom_ratio = c*t + b*t*(1-t) + a*(1-t) self.dot_widget.zoom_to_fit_on_resize = False MoveToAnimation.animate(self, t) class DragAction(object): def __init__(self, dot_widget): self.dot_widget = dot_widget def on_button_press(self, event): self.startmousex = self.prevmousex = event.x self.startmousey = self.prevmousey = event.y self.start() def on_motion_notify(self, event): if event.is_hint: x, y, state = event.window.get_pointer() else: x, y, state = event.x, event.y, event.state deltax = self.prevmousex - x deltay = self.prevmousey - y self.drag(deltax, deltay) self.prevmousex = x self.prevmousey = y def on_button_release(self, event): self.stopmousex = event.x self.stopmousey = event.y self.stop() def draw(self, cr): pass def start(self): pass def drag(self, deltax, deltay): pass def stop(self): pass def abort(self): pass class NullAction(DragAction): def on_motion_notify(self, event): if event.is_hint: x, y, state = event.window.get_pointer() else: x, y, state = event.x, event.y, event.state dot_widget = self.dot_widget item = dot_widget.get_url(x, y) if item is None: item = dot_widget.get_jump(x, y) if item is not None: dot_widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND2)) dot_widget.set_highlight(item.highlight) else: dot_widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.ARROW)) dot_widget.set_highlight(None) class PanAction(DragAction): def start(self): self.dot_widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR)) def drag(self, deltax, deltay): self.dot_widget.x += deltax / self.dot_widget.zoom_ratio self.dot_widget.y += deltay / self.dot_widget.zoom_ratio self.dot_widget.queue_draw() def stop(self): self.dot_widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.ARROW)) abort = stop class ZoomAction(DragAction): def drag(self, deltax, deltay): self.dot_widget.zoom_ratio *= 1.005 ** (deltax + deltay) self.dot_widget.zoom_to_fit_on_resize = False self.dot_widget.queue_draw() def stop(self): self.dot_widget.queue_draw() class ZoomAreaAction(DragAction): def drag(self, deltax, deltay): self.dot_widget.queue_draw() def draw(self, cr): cr.save() cr.set_source_rgba(.5, .5, 1.0, 0.25) cr.rectangle(self.startmousex, self.startmousey, self.prevmousex - self.startmousex, self.prevmousey - self.startmousey) cr.fill() cr.set_source_rgba(.5, .5, 1.0, 1.0) cr.set_line_width(1) cr.rectangle(self.startmousex - .5, self.startmousey - .5, self.prevmousex - self.startmousex + 1, self.prevmousey - self.startmousey + 1) cr.stroke() cr.restore() def stop(self): x1, y1 = self.dot_widget.window2graph(self.startmousex, self.startmousey) x2, y2 = self.dot_widget.window2graph(self.stopmousex, self.stopmousey) self.dot_widget.zoom_to_area(x1, y1, x2, y2) def abort(self): self.dot_widget.queue_draw() class DotWidget(gtk.DrawingArea): """PyGTK widget that draws dot graphs.""" __gsignals__ = { 'expose-event': 'override', 'clicked' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING, gtk.gdk.Event)) } filter = 'dot' def __init__(self): gtk.DrawingArea.__init__(self) self.graph = Graph() self.openfilename = None self.set_flags(gtk.CAN_FOCUS) self.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK) self.connect("button-press-event", self.on_area_button_press) self.connect("button-release-event", self.on_area_button_release) self.add_events(gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_RELEASE_MASK) self.connect("motion-notify-event", self.on_area_motion_notify) self.connect("scroll-event", self.on_area_scroll_event) self.connect("size-allocate", self.on_area_size_allocate) self.connect('key-press-event', self.on_key_press_event) self.last_mtime = None gobject.timeout_add(1000, self.update) self.x, self.y = 0.0, 0.0 self.zoom_ratio = 1.0 self.zoom_to_fit_on_resize = False self.animation = NoAnimation(self) self.drag_action = NullAction(self) self.presstime = None self.highlight = None def set_filter(self, filter): self.filter = filter def run_filter(self, dotcode): if not self.filter: return dotcode p = subprocess.Popen( [self.filter, '-Txdot'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, universal_newlines=True ) xdotcode, error = p.communicate(dotcode) sys.stderr.write(error) if p.returncode != 0: dialog = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, message_format=error, buttons=gtk.BUTTONS_OK) dialog.set_title('Dot Viewer') dialog.run() dialog.destroy() return None return xdotcode def set_dotcode(self, dotcode, filename=None): self.openfilename = None if isinstance(dotcode, unicode): dotcode = dotcode.encode('utf8') xdotcode = self.run_filter(dotcode) if xdotcode is None: return False try: self.set_xdotcode(xdotcode) except ParseError, ex: dialog = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, message_format=str(ex), buttons=gtk.BUTTONS_OK) dialog.set_title('Dot Viewer') dialog.run() dialog.destroy() return False else: if filename is None: self.last_mtime = None else: self.last_mtime = os.stat(filename).st_mtime self.openfilename = filename return True def set_xdotcode(self, xdotcode): #print xdotcode parser = XDotParser(xdotcode) self.graph = parser.parse() self.zoom_image(self.zoom_ratio, center=True) def reload(self): if self.openfilename is not None: try: fp = file(self.openfilename, 'rt') self.set_dotcode(fp.read(), self.openfilename) fp.close() except IOError: pass def update(self): if self.openfilename is not None: current_mtime = os.stat(self.openfilename).st_mtime if current_mtime != self.last_mtime: self.last_mtime = current_mtime self.reload() return True def do_expose_event(self, event): cr = self.window.cairo_create() # set a clip region for the expose event cr.rectangle( event.area.x, event.area.y, event.area.width, event.area.height ) cr.clip() cr.set_source_rgba(1.0, 1.0, 1.0, 1.0) cr.paint() cr.save() rect = self.get_allocation() cr.translate(0.5*rect.width, 0.5*rect.height) cr.scale(self.zoom_ratio, self.zoom_ratio) cr.translate(-self.x, -self.y) self.graph.draw(cr, highlight_items=self.highlight) cr.restore() self.drag_action.draw(cr) return False def get_current_pos(self): return self.x, self.y def set_current_pos(self, x, y): self.x = x self.y = y self.queue_draw() def set_highlight(self, items): if self.highlight != items: self.highlight = items self.queue_draw() def zoom_image(self, zoom_ratio, center=False, pos=None): # Constrain zoom ratio to a sane range to prevent numeric instability. zoom_ratio = min(zoom_ratio, 1E4) zoom_ratio = max(zoom_ratio, 1E-6) if center: self.x = self.graph.width/2 self.y = self.graph.height/2 elif pos is not None: rect = self.get_allocation() x, y = pos x -= 0.5*rect.width y -= 0.5*rect.height self.x += x / self.zoom_ratio - x / zoom_ratio self.y += y / self.zoom_ratio - y / zoom_ratio self.zoom_ratio = zoom_ratio self.zoom_to_fit_on_resize = False self.queue_draw() def zoom_to_area(self, x1, y1, x2, y2): rect = self.get_allocation() width = abs(x1 - x2) height = abs(y1 - y2) self.zoom_ratio = min( float(rect.width)/float(width), float(rect.height)/float(height) ) self.zoom_to_fit_on_resize = False self.x = (x1 + x2) / 2 self.y = (y1 + y2) / 2 self.queue_draw() def zoom_to_fit(self): rect = self.get_allocation() rect.x += self.ZOOM_TO_FIT_MARGIN rect.y += self.ZOOM_TO_FIT_MARGIN rect.width -= 2 * self.ZOOM_TO_FIT_MARGIN rect.height -= 2 * self.ZOOM_TO_FIT_MARGIN zoom_ratio = min( float(rect.width)/float(self.graph.width), float(rect.height)/float(self.graph.height) ) self.zoom_image(zoom_ratio, center=True) self.zoom_to_fit_on_resize = True ZOOM_INCREMENT = 1.25 ZOOM_TO_FIT_MARGIN = 12 def on_zoom_in(self, action): self.zoom_image(self.zoom_ratio * self.ZOOM_INCREMENT) def on_zoom_out(self, action): self.zoom_image(self.zoom_ratio / self.ZOOM_INCREMENT) def on_zoom_fit(self, action): self.zoom_to_fit() def on_zoom_100(self, action): self.zoom_image(1.0) POS_INCREMENT = 100 def on_key_press_event(self, widget, event): if event.keyval == gtk.keysyms.Left: self.x -= self.POS_INCREMENT/self.zoom_ratio self.queue_draw() return True if event.keyval == gtk.keysyms.Right: self.x += self.POS_INCREMENT/self.zoom_ratio self.queue_draw() return True if event.keyval == gtk.keysyms.Up: self.y -= self.POS_INCREMENT/self.zoom_ratio self.queue_draw() return True if event.keyval == gtk.keysyms.Down: self.y += self.POS_INCREMENT/self.zoom_ratio self.queue_draw() return True if event.keyval in (gtk.keysyms.Page_Up, gtk.keysyms.plus, gtk.keysyms.equal, gtk.keysyms.KP_Add): self.zoom_image(self.zoom_ratio * self.ZOOM_INCREMENT) self.queue_draw() return True if event.keyval in (gtk.keysyms.Page_Down, gtk.keysyms.minus, gtk.keysyms.KP_Subtract): self.zoom_image(self.zoom_ratio / self.ZOOM_INCREMENT) self.queue_draw() return True if event.keyval == gtk.keysyms.Escape: self.drag_action.abort() self.drag_action = NullAction(self) return True if event.keyval == gtk.keysyms.r: self.reload() return True if event.keyval == gtk.keysyms.q: gtk.main_quit() return True if event.keyval == gtk.keysyms.p: self.on_print() return True return False print_settings = None def on_print(self, action=None): print_op = gtk.PrintOperation() if self.print_settings != None: print_op.set_print_settings(self.print_settings) print_op.connect("begin_print", self.begin_print) print_op.connect("draw_page", self.draw_page) res = print_op.run(gtk.PRINT_OPERATION_ACTION_PRINT_DIALOG, self.parent.parent) if res == gtk.PRINT_OPERATION_RESULT_APPLY: print_settings = print_op.get_print_settings() def begin_print(self, operation, context): operation.set_n_pages(1) #operation.set_support_selection(True) #operation.set_has_selection(True) return True def draw_page(self, operation, context, page_nr): cr = context.get_cairo_context() rect = self.get_allocation() cr.translate(0.5*rect.width, 0.5*rect.height) cr.scale(self.zoom_ratio, self.zoom_ratio) cr.translate(-self.x, -self.y) self.graph.draw(cr, highlight_items=self.highlight) def get_drag_action(self, event): state = event.state if event.button in (1, 2): # left or middle button if state & gtk.gdk.CONTROL_MASK: return ZoomAction elif state & gtk.gdk.SHIFT_MASK: return ZoomAreaAction else: return PanAction return NullAction def on_area_button_press(self, area, event): self.animation.stop() self.drag_action.abort() action_type = self.get_drag_action(event) self.drag_action = action_type(self) self.drag_action.on_button_press(event) self.presstime = time.time() self.pressx = event.x self.pressy = event.y return False def is_click(self, event, click_fuzz=4, click_timeout=1.0): assert event.type == gtk.gdk.BUTTON_RELEASE if self.presstime is None: # got a button release without seeing the press? return False # XXX instead of doing this complicated logic, shouldn't we listen # for gtk's clicked event instead? deltax = self.pressx - event.x deltay = self.pressy - event.y return (time.time() < self.presstime + click_timeout and math.hypot(deltax, deltay) < click_fuzz) def on_area_button_release(self, area, event): self.drag_action.on_button_release(event) self.drag_action = NullAction(self) if event.button == 1 and self.is_click(event): x, y = int(event.x), int(event.y) url = self.get_url(x, y) if url is not None: self.emit('clicked', unicode(url.url), event) else: jump = self.get_jump(x, y) if jump is not None: self.animate_to(jump.x, jump.y) return True if event.button == 1 or event.button == 2: return True return False def on_area_scroll_event(self, area, event): if event.direction == gtk.gdk.SCROLL_UP: self.zoom_image(self.zoom_ratio * self.ZOOM_INCREMENT, pos=(event.x, event.y)) return True if event.direction == gtk.gdk.SCROLL_DOWN: self.zoom_image(self.zoom_ratio / self.ZOOM_INCREMENT, pos=(event.x, event.y)) return True return False def on_area_motion_notify(self, area, event): self.drag_action.on_motion_notify(event) return True def on_area_size_allocate(self, area, allocation): if self.zoom_to_fit_on_resize: self.zoom_to_fit() def animate_to(self, x, y): self.animation = ZoomToAnimation(self, x, y) self.animation.start() def window2graph(self, x, y): rect = self.get_allocation() x -= 0.5*rect.width y -= 0.5*rect.height x /= self.zoom_ratio y /= self.zoom_ratio x += self.x y += self.y return x, y def get_url(self, x, y): x, y = self.window2graph(x, y) return self.graph.get_url(x, y) def get_jump(self, x, y): x, y = self.window2graph(x, y) return self.graph.get_jump(x, y) class DotWindow(gtk.Window): ui = ''' <ui> <toolbar name="ToolBar"> <toolitem action="Open"/> <toolitem action="Reload"/> <toolitem action="Print"/> <separator/> <toolitem action="ZoomIn"/> <toolitem action="ZoomOut"/> <toolitem action="ZoomFit"/> <toolitem action="Zoom100"/> </toolbar> </ui> ''' base_title = 'Dot Viewer' def __init__(self): gtk.Window.__init__(self) self.graph = Graph() window = self window.set_title(self.base_title) window.set_default_size(512, 512) vbox = gtk.VBox() window.add(vbox) self.widget = DotWidget() # Create a UIManager instance uimanager = self.uimanager = gtk.UIManager() # Add the accelerator group to the toplevel window accelgroup = uimanager.get_accel_group() window.add_accel_group(accelgroup) # Create an ActionGroup actiongroup = gtk.ActionGroup('Actions') self.actiongroup = actiongroup # Create actions actiongroup.add_actions(( ('Open', gtk.STOCK_OPEN, None, None, None, self.on_open), ('Reload', gtk.STOCK_REFRESH, None, None, None, self.on_reload), ('Print', gtk.STOCK_PRINT, None, None, "Prints the currently visible part of the graph", self.widget.on_print), ('ZoomIn', gtk.STOCK_ZOOM_IN, None, None, None, self.widget.on_zoom_in), ('ZoomOut', gtk.STOCK_ZOOM_OUT, None, None, None, self.widget.on_zoom_out), ('ZoomFit', gtk.STOCK_ZOOM_FIT, None, None, None, self.widget.on_zoom_fit), ('Zoom100', gtk.STOCK_ZOOM_100, None, None, None, self.widget.on_zoom_100), )) # Add the actiongroup to the uimanager uimanager.insert_action_group(actiongroup, 0) # Add a UI descrption uimanager.add_ui_from_string(self.ui) # Create a Toolbar toolbar = uimanager.get_widget('/ToolBar') vbox.pack_start(toolbar, False) vbox.pack_start(self.widget) self.set_focus(self.widget) self.show_all() def set_filter(self, filter): self.widget.set_filter(filter) def set_dotcode(self, dotcode, filename=None): if self.widget.set_dotcode(dotcode, filename): self.update_title(filename) self.widget.zoom_to_fit() def set_xdotcode(self, xdotcode, filename=None): if self.widget.set_xdotcode(xdotcode): self.update_title(filename) self.widget.zoom_to_fit() def update_title(self, filename=None): if filename is None: self.set_title(self.base_title) else: self.set_title(os.path.basename(filename) + ' - ' + self.base_title) def open_file(self, filename): try: fp = file(filename, 'rt') self.set_dotcode(fp.read(), filename) fp.close() except IOError, ex: dlg = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, message_format=str(ex), buttons=gtk.BUTTONS_OK) dlg.set_title(self.base_title) dlg.run() dlg.destroy() def on_open(self, action): chooser = gtk.FileChooserDialog(title="Open dot File", action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) filter = gtk.FileFilter() filter.set_name("Graphviz dot files") filter.add_pattern("*.dot") chooser.add_filter(filter) filter = gtk.FileFilter() filter.set_name("All files") filter.add_pattern("*") chooser.add_filter(filter) if chooser.run() == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() self.open_file(filename) else: chooser.destroy() def on_reload(self, action): self.widget.reload() def main(): import optparse parser = optparse.OptionParser( usage='\n\t%prog [file]') parser.add_option( '-f', '--filter', type='choice', choices=('dot', 'neato', 'twopi', 'circo', 'fdp'), dest='filter', default='dot', help='graphviz filter: dot, neato, twopi, circo, or fdp [default: %default]') parser.add_option( '-n', '--no-filter', action='store_const', const=None, dest='filter', help='assume input is already filtered into xdot format (use e.g. dot -Txdot)') (options, args) = parser.parse_args(sys.argv[1:]) if len(args) > 1: parser.error('incorrect number of arguments') win = DotWindow() win.connect('destroy', gtk.main_quit) win.set_filter(options.filter) if len(args) == 0: if not sys.stdin.isatty(): win.set_dotcode(sys.stdin.read()) else: if args[0] == '-': win.set_dotcode(sys.stdin.read()) else: win.open_file(args[0]) gtk.main() # Apache-Style Software License for ColorBrewer software and ColorBrewer Color # Schemes, Version 1.1 # # Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State # University. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions as source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The end-user documentation included with the redistribution, if any, # must include the following acknowledgment: # # This product includes color specifications and designs developed by # Cynthia Brewer (http://colorbrewer.org/). # # Alternately, this acknowledgment may appear in the software itself, if and # wherever such third-party acknowledgments normally appear. # # 3. The name "ColorBrewer" must not be used to endorse or promote products # derived from this software without prior written permission. For written # permission, please contact Cynthia Brewer at cbrewer@psu.edu. # # 4. Products derived from this software may not be called "ColorBrewer", # nor may "ColorBrewer" appear in their name, without prior written # permission of Cynthia Brewer. # # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CYNTHIA # BREWER, MARK HARROWER, OR THE PENNSYLVANIA STATE UNIVERSITY BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. brewer_colors = { 'accent3': [(127, 201, 127), (190, 174, 212), (253, 192, 134)], 'accent4': [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153)], 'accent5': [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176)], 'accent6': [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176), (240, 2, 127)], 'accent7': [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176), (240, 2, 127), (191, 91, 23)], 'accent8': [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176), (240, 2, 127), (191, 91, 23), (102, 102, 102)], 'blues3': [(222, 235, 247), (158, 202, 225), (49, 130, 189)], 'blues4': [(239, 243, 255), (189, 215, 231), (107, 174, 214), (33, 113, 181)], 'blues5': [(239, 243, 255), (189, 215, 231), (107, 174, 214), (49, 130, 189), (8, 81, 156)], 'blues6': [(239, 243, 255), (198, 219, 239), (158, 202, 225), (107, 174, 214), (49, 130, 189), (8, 81, 156)], 'blues7': [(239, 243, 255), (198, 219, 239), (158, 202, 225), (107, 174, 214), (66, 146, 198), (33, 113, 181), (8, 69, 148)], 'blues8': [(247, 251, 255), (222, 235, 247), (198, 219, 239), (158, 202, 225), (107, 174, 214), (66, 146, 198), (33, 113, 181), (8, 69, 148)], 'blues9': [(247, 251, 255), (222, 235, 247), (198, 219, 239), (158, 202, 225), (107, 174, 214), (66, 146, 198), (33, 113, 181), (8, 81, 156), (8, 48, 107)], 'brbg10': [(84, 48, 5), (0, 60, 48), (140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (199, 234, 229), (128, 205, 193), (53, 151, 143), (1, 102, 94)], 'brbg11': [(84, 48, 5), (1, 102, 94), (0, 60, 48), (140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (245, 245, 245), (199, 234, 229), (128, 205, 193), (53, 151, 143)], 'brbg3': [(216, 179, 101), (245, 245, 245), (90, 180, 172)], 'brbg4': [(166, 97, 26), (223, 194, 125), (128, 205, 193), (1, 133, 113)], 'brbg5': [(166, 97, 26), (223, 194, 125), (245, 245, 245), (128, 205, 193), (1, 133, 113)], 'brbg6': [(140, 81, 10), (216, 179, 101), (246, 232, 195), (199, 234, 229), (90, 180, 172), (1, 102, 94)], 'brbg7': [(140, 81, 10), (216, 179, 101), (246, 232, 195), (245, 245, 245), (199, 234, 229), (90, 180, 172), (1, 102, 94)], 'brbg8': [(140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (199, 234, 229), (128, 205, 193), (53, 151, 143), (1, 102, 94)], 'brbg9': [(140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (245, 245, 245), (199, 234, 229), (128, 205, 193), (53, 151, 143), (1, 102, 94)], 'bugn3': [(229, 245, 249), (153, 216, 201), (44, 162, 95)], 'bugn4': [(237, 248, 251), (178, 226, 226), (102, 194, 164), (35, 139, 69)], 'bugn5': [(237, 248, 251), (178, 226, 226), (102, 194, 164), (44, 162, 95), (0, 109, 44)], 'bugn6': [(237, 248, 251), (204, 236, 230), (153, 216, 201), (102, 194, 164), (44, 162, 95), (0, 109, 44)], 'bugn7': [(237, 248, 251), (204, 236, 230), (153, 216, 201), (102, 194, 164), (65, 174, 118), (35, 139, 69), (0, 88, 36)], 'bugn8': [(247, 252, 253), (229, 245, 249), (204, 236, 230), (153, 216, 201), (102, 194, 164), (65, 174, 118), (35, 139, 69), (0, 88, 36)], 'bugn9': [(247, 252, 253), (229, 245, 249), (204, 236, 230), (153, 216, 201), (102, 194, 164), (65, 174, 118), (35, 139, 69), (0, 109, 44), (0, 68, 27)], 'bupu3': [(224, 236, 244), (158, 188, 218), (136, 86, 167)], 'bupu4': [(237, 248, 251), (179, 205, 227), (140, 150, 198), (136, 65, 157)], 'bupu5': [(237, 248, 251), (179, 205, 227), (140, 150, 198), (136, 86, 167), (129, 15, 124)], 'bupu6': [(237, 248, 251), (191, 211, 230), (158, 188, 218), (140, 150, 198), (136, 86, 167), (129, 15, 124)], 'bupu7': [(237, 248, 251), (191, 211, 230), (158, 188, 218), (140, 150, 198), (140, 107, 177), (136, 65, 157), (110, 1, 107)], 'bupu8': [(247, 252, 253), (224, 236, 244), (191, 211, 230), (158, 188, 218), (140, 150, 198), (140, 107, 177), (136, 65, 157), (110, 1, 107)], 'bupu9': [(247, 252, 253), (224, 236, 244), (191, 211, 230), (158, 188, 218), (140, 150, 198), (140, 107, 177), (136, 65, 157), (129, 15, 124), (77, 0, 75)], 'dark23': [(27, 158, 119), (217, 95, 2), (117, 112, 179)], 'dark24': [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138)], 'dark25': [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30)], 'dark26': [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30), (230, 171, 2)], 'dark27': [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30), (230, 171, 2), (166, 118, 29)], 'dark28': [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30), (230, 171, 2), (166, 118, 29), (102, 102, 102)], 'gnbu3': [(224, 243, 219), (168, 221, 181), (67, 162, 202)], 'gnbu4': [(240, 249, 232), (186, 228, 188), (123, 204, 196), (43, 140, 190)], 'gnbu5': [(240, 249, 232), (186, 228, 188), (123, 204, 196), (67, 162, 202), (8, 104, 172)], 'gnbu6': [(240, 249, 232), (204, 235, 197), (168, 221, 181), (123, 204, 196), (67, 162, 202), (8, 104, 172)], 'gnbu7': [(240, 249, 232), (204, 235, 197), (168, 221, 181), (123, 204, 196), (78, 179, 211), (43, 140, 190), (8, 88, 158)], 'gnbu8': [(247, 252, 240), (224, 243, 219), (204, 235, 197), (168, 221, 181), (123, 204, 196), (78, 179, 211), (43, 140, 190), (8, 88, 158)], 'gnbu9': [(247, 252, 240), (224, 243, 219), (204, 235, 197), (168, 221, 181), (123, 204, 196), (78, 179, 211), (43, 140, 190), (8, 104, 172), (8, 64, 129)], 'greens3': [(229, 245, 224), (161, 217, 155), (49, 163, 84)], 'greens4': [(237, 248, 233), (186, 228, 179), (116, 196, 118), (35, 139, 69)], 'greens5': [(237, 248, 233), (186, 228, 179), (116, 196, 118), (49, 163, 84), (0, 109, 44)], 'greens6': [(237, 248, 233), (199, 233, 192), (161, 217, 155), (116, 196, 118), (49, 163, 84), (0, 109, 44)], 'greens7': [(237, 248, 233), (199, 233, 192), (161, 217, 155), (116, 196, 118), (65, 171, 93), (35, 139, 69), (0, 90, 50)], 'greens8': [(247, 252, 245), (229, 245, 224), (199, 233, 192), (161, 217, 155), (116, 196, 118), (65, 171, 93), (35, 139, 69), (0, 90, 50)], 'greens9': [(247, 252, 245), (229, 245, 224), (199, 233, 192), (161, 217, 155), (116, 196, 118), (65, 171, 93), (35, 139, 69), (0, 109, 44), (0, 68, 27)], 'greys3': [(240, 240, 240), (189, 189, 189), (99, 99, 99)], 'greys4': [(247, 247, 247), (204, 204, 204), (150, 150, 150), (82, 82, 82)], 'greys5': [(247, 247, 247), (204, 204, 204), (150, 150, 150), (99, 99, 99), (37, 37, 37)], 'greys6': [(247, 247, 247), (217, 217, 217), (189, 189, 189), (150, 150, 150), (99, 99, 99), (37, 37, 37)], 'greys7': [(247, 247, 247), (217, 217, 217), (189, 189, 189), (150, 150, 150), (115, 115, 115), (82, 82, 82), (37, 37, 37)], 'greys8': [(255, 255, 255), (240, 240, 240), (217, 217, 217), (189, 189, 189), (150, 150, 150), (115, 115, 115), (82, 82, 82), (37, 37, 37)], 'greys9': [(255, 255, 255), (240, 240, 240), (217, 217, 217), (189, 189, 189), (150, 150, 150), (115, 115, 115), (82, 82, 82), (37, 37, 37), (0, 0, 0)], 'oranges3': [(254, 230, 206), (253, 174, 107), (230, 85, 13)], 'oranges4': [(254, 237, 222), (253, 190, 133), (253, 141, 60), (217, 71, 1)], 'oranges5': [(254, 237, 222), (253, 190, 133), (253, 141, 60), (230, 85, 13), (166, 54, 3)], 'oranges6': [(254, 237, 222), (253, 208, 162), (253, 174, 107), (253, 141, 60), (230, 85, 13), (166, 54, 3)], 'oranges7': [(254, 237, 222), (253, 208, 162), (253, 174, 107), (253, 141, 60), (241, 105, 19), (217, 72, 1), (140, 45, 4)], 'oranges8': [(255, 245, 235), (254, 230, 206), (253, 208, 162), (253, 174, 107), (253, 141, 60), (241, 105, 19), (217, 72, 1), (140, 45, 4)], 'oranges9': [(255, 245, 235), (254, 230, 206), (253, 208, 162), (253, 174, 107), (253, 141, 60), (241, 105, 19), (217, 72, 1), (166, 54, 3), (127, 39, 4)], 'orrd3': [(254, 232, 200), (253, 187, 132), (227, 74, 51)], 'orrd4': [(254, 240, 217), (253, 204, 138), (252, 141, 89), (215, 48, 31)], 'orrd5': [(254, 240, 217), (253, 204, 138), (252, 141, 89), (227, 74, 51), (179, 0, 0)], 'orrd6': [(254, 240, 217), (253, 212, 158), (253, 187, 132), (252, 141, 89), (227, 74, 51), (179, 0, 0)], 'orrd7': [(254, 240, 217), (253, 212, 158), (253, 187, 132), (252, 141, 89), (239, 101, 72), (215, 48, 31), (153, 0, 0)], 'orrd8': [(255, 247, 236), (254, 232, 200), (253, 212, 158), (253, 187, 132), (252, 141, 89), (239, 101, 72), (215, 48, 31), (153, 0, 0)], 'orrd9': [(255, 247, 236), (254, 232, 200), (253, 212, 158), (253, 187, 132), (252, 141, 89), (239, 101, 72), (215, 48, 31), (179, 0, 0), (127, 0, 0)], 'paired10': [(166, 206, 227), (106, 61, 154), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214)], 'paired11': [(166, 206, 227), (106, 61, 154), (255, 255, 153), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214)], 'paired12': [(166, 206, 227), (106, 61, 154), (255, 255, 153), (177, 89, 40), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214)], 'paired3': [(166, 206, 227), (31, 120, 180), (178, 223, 138)], 'paired4': [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44)], 'paired5': [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153)], 'paired6': [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28)], 'paired7': [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111)], 'paired8': [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0)], 'paired9': [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214)], 'pastel13': [(251, 180, 174), (179, 205, 227), (204, 235, 197)], 'pastel14': [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228)], 'pastel15': [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166)], 'pastel16': [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204)], 'pastel17': [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204), (229, 216, 189)], 'pastel18': [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204), (229, 216, 189), (253, 218, 236)], 'pastel19': [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204), (229, 216, 189), (253, 218, 236), (242, 242, 242)], 'pastel23': [(179, 226, 205), (253, 205, 172), (203, 213, 232)], 'pastel24': [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228)], 'pastel25': [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201)], 'pastel26': [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201), (255, 242, 174)], 'pastel27': [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201), (255, 242, 174), (241, 226, 204)], 'pastel28': [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201), (255, 242, 174), (241, 226, 204), (204, 204, 204)], 'piyg10': [(142, 1, 82), (39, 100, 25), (197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33)], 'piyg11': [(142, 1, 82), (77, 146, 33), (39, 100, 25), (197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (247, 247, 247), (230, 245, 208), (184, 225, 134), (127, 188, 65)], 'piyg3': [(233, 163, 201), (247, 247, 247), (161, 215, 106)], 'piyg4': [(208, 28, 139), (241, 182, 218), (184, 225, 134), (77, 172, 38)], 'piyg5': [(208, 28, 139), (241, 182, 218), (247, 247, 247), (184, 225, 134), (77, 172, 38)], 'piyg6': [(197, 27, 125), (233, 163, 201), (253, 224, 239), (230, 245, 208), (161, 215, 106), (77, 146, 33)], 'piyg7': [(197, 27, 125), (233, 163, 201), (253, 224, 239), (247, 247, 247), (230, 245, 208), (161, 215, 106), (77, 146, 33)], 'piyg8': [(197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33)], 'piyg9': [(197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (247, 247, 247), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33)], 'prgn10': [(64, 0, 75), (0, 68, 27), (118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (217, 240, 211), (166, 219, 160), (90, 174, 97), (27, 120, 55)], 'prgn11': [(64, 0, 75), (27, 120, 55), (0, 68, 27), (118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (247, 247, 247), (217, 240, 211), (166, 219, 160), (90, 174, 97)], 'prgn3': [(175, 141, 195), (247, 247, 247), (127, 191, 123)], 'prgn4': [(123, 50, 148), (194, 165, 207), (166, 219, 160), (0, 136, 55)], 'prgn5': [(123, 50, 148), (194, 165, 207), (247, 247, 247), (166, 219, 160), (0, 136, 55)], 'prgn6': [(118, 42, 131), (175, 141, 195), (231, 212, 232), (217, 240, 211), (127, 191, 123), (27, 120, 55)], 'prgn7': [(118, 42, 131), (175, 141, 195), (231, 212, 232), (247, 247, 247), (217, 240, 211), (127, 191, 123), (27, 120, 55)], 'prgn8': [(118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (217, 240, 211), (166, 219, 160), (90, 174, 97), (27, 120, 55)], 'prgn9': [(118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (247, 247, 247), (217, 240, 211), (166, 219, 160), (90, 174, 97), (27, 120, 55)], 'pubu3': [(236, 231, 242), (166, 189, 219), (43, 140, 190)], 'pubu4': [(241, 238, 246), (189, 201, 225), (116, 169, 207), (5, 112, 176)], 'pubu5': [(241, 238, 246), (189, 201, 225), (116, 169, 207), (43, 140, 190), (4, 90, 141)], 'pubu6': [(241, 238, 246), (208, 209, 230), (166, 189, 219), (116, 169, 207), (43, 140, 190), (4, 90, 141)], 'pubu7': [(241, 238, 246), (208, 209, 230), (166, 189, 219), (116, 169, 207), (54, 144, 192), (5, 112, 176), (3, 78, 123)], 'pubu8': [(255, 247, 251), (236, 231, 242), (208, 209, 230), (166, 189, 219), (116, 169, 207), (54, 144, 192), (5, 112, 176), (3, 78, 123)], 'pubu9': [(255, 247, 251), (236, 231, 242), (208, 209, 230), (166, 189, 219), (116, 169, 207), (54, 144, 192), (5, 112, 176), (4, 90, 141), (2, 56, 88)], 'pubugn3': [(236, 226, 240), (166, 189, 219), (28, 144, 153)], 'pubugn4': [(246, 239, 247), (189, 201, 225), (103, 169, 207), (2, 129, 138)], 'pubugn5': [(246, 239, 247), (189, 201, 225), (103, 169, 207), (28, 144, 153), (1, 108, 89)], 'pubugn6': [(246, 239, 247), (208, 209, 230), (166, 189, 219), (103, 169, 207), (28, 144, 153), (1, 108, 89)], 'pubugn7': [(246, 239, 247), (208, 209, 230), (166, 189, 219), (103, 169, 207), (54, 144, 192), (2, 129, 138), (1, 100, 80)], 'pubugn8': [(255, 247, 251), (236, 226, 240), (208, 209, 230), (166, 189, 219), (103, 169, 207), (54, 144, 192), (2, 129, 138), (1, 100, 80)], 'pubugn9': [(255, 247, 251), (236, 226, 240), (208, 209, 230), (166, 189, 219), (103, 169, 207), (54, 144, 192), (2, 129, 138), (1, 108, 89), (1, 70, 54)], 'puor10': [(127, 59, 8), (45, 0, 75), (179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (216, 218, 235), (178, 171, 210), (128, 115, 172), (84, 39, 136)], 'puor11': [(127, 59, 8), (84, 39, 136), (45, 0, 75), (179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (247, 247, 247), (216, 218, 235), (178, 171, 210), (128, 115, 172)], 'puor3': [(241, 163, 64), (247, 247, 247), (153, 142, 195)], 'puor4': [(230, 97, 1), (253, 184, 99), (178, 171, 210), (94, 60, 153)], 'puor5': [(230, 97, 1), (253, 184, 99), (247, 247, 247), (178, 171, 210), (94, 60, 153)], 'puor6': [(179, 88, 6), (241, 163, 64), (254, 224, 182), (216, 218, 235), (153, 142, 195), (84, 39, 136)], 'puor7': [(179, 88, 6), (241, 163, 64), (254, 224, 182), (247, 247, 247), (216, 218, 235), (153, 142, 195), (84, 39, 136)], 'puor8': [(179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (216, 218, 235), (178, 171, 210), (128, 115, 172), (84, 39, 136)], 'puor9': [(179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (247, 247, 247), (216, 218, 235), (178, 171, 210), (128, 115, 172), (84, 39, 136)], 'purd3': [(231, 225, 239), (201, 148, 199), (221, 28, 119)], 'purd4': [(241, 238, 246), (215, 181, 216), (223, 101, 176), (206, 18, 86)], 'purd5': [(241, 238, 246), (215, 181, 216), (223, 101, 176), (221, 28, 119), (152, 0, 67)], 'purd6': [(241, 238, 246), (212, 185, 218), (201, 148, 199), (223, 101, 176), (221, 28, 119), (152, 0, 67)], 'purd7': [(241, 238, 246), (212, 185, 218), (201, 148, 199), (223, 101, 176), (231, 41, 138), (206, 18, 86), (145, 0, 63)], 'purd8': [(247, 244, 249), (231, 225, 239), (212, 185, 218), (201, 148, 199), (223, 101, 176), (231, 41, 138), (206, 18, 86), (145, 0, 63)], 'purd9': [(247, 244, 249), (231, 225, 239), (212, 185, 218), (201, 148, 199), (223, 101, 176), (231, 41, 138), (206, 18, 86), (152, 0, 67), (103, 0, 31)], 'purples3': [(239, 237, 245), (188, 189, 220), (117, 107, 177)], 'purples4': [(242, 240, 247), (203, 201, 226), (158, 154, 200), (106, 81, 163)], 'purples5': [(242, 240, 247), (203, 201, 226), (158, 154, 200), (117, 107, 177), (84, 39, 143)], 'purples6': [(242, 240, 247), (218, 218, 235), (188, 189, 220), (158, 154, 200), (117, 107, 177), (84, 39, 143)], 'purples7': [(242, 240, 247), (218, 218, 235), (188, 189, 220), (158, 154, 200), (128, 125, 186), (106, 81, 163), (74, 20, 134)], 'purples8': [(252, 251, 253), (239, 237, 245), (218, 218, 235), (188, 189, 220), (158, 154, 200), (128, 125, 186), (106, 81, 163), (74, 20, 134)], 'purples9': [(252, 251, 253), (239, 237, 245), (218, 218, 235), (188, 189, 220), (158, 154, 200), (128, 125, 186), (106, 81, 163), (84, 39, 143), (63, 0, 125)], 'rdbu10': [(103, 0, 31), (5, 48, 97), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (209, 229, 240), (146, 197, 222), (67, 147, 195), (33, 102, 172)], 'rdbu11': [(103, 0, 31), (33, 102, 172), (5, 48, 97), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (247, 247, 247), (209, 229, 240), (146, 197, 222), (67, 147, 195)], 'rdbu3': [(239, 138, 98), (247, 247, 247), (103, 169, 207)], 'rdbu4': [(202, 0, 32), (244, 165, 130), (146, 197, 222), (5, 113, 176)], 'rdbu5': [(202, 0, 32), (244, 165, 130), (247, 247, 247), (146, 197, 222), (5, 113, 176)], 'rdbu6': [(178, 24, 43), (239, 138, 98), (253, 219, 199), (209, 229, 240), (103, 169, 207), (33, 102, 172)], 'rdbu7': [(178, 24, 43), (239, 138, 98), (253, 219, 199), (247, 247, 247), (209, 229, 240), (103, 169, 207), (33, 102, 172)], 'rdbu8': [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (209, 229, 240), (146, 197, 222), (67, 147, 195), (33, 102, 172)], 'rdbu9': [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (247, 247, 247), (209, 229, 240), (146, 197, 222), (67, 147, 195), (33, 102, 172)], 'rdgy10': [(103, 0, 31), (26, 26, 26), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (224, 224, 224), (186, 186, 186), (135, 135, 135), (77, 77, 77)], 'rdgy11': [(103, 0, 31), (77, 77, 77), (26, 26, 26), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (255, 255, 255), (224, 224, 224), (186, 186, 186), (135, 135, 135)], 'rdgy3': [(239, 138, 98), (255, 255, 255), (153, 153, 153)], 'rdgy4': [(202, 0, 32), (244, 165, 130), (186, 186, 186), (64, 64, 64)], 'rdgy5': [(202, 0, 32), (244, 165, 130), (255, 255, 255), (186, 186, 186), (64, 64, 64)], 'rdgy6': [(178, 24, 43), (239, 138, 98), (253, 219, 199), (224, 224, 224), (153, 153, 153), (77, 77, 77)], 'rdgy7': [(178, 24, 43), (239, 138, 98), (253, 219, 199), (255, 255, 255), (224, 224, 224), (153, 153, 153), (77, 77, 77)], 'rdgy8': [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (224, 224, 224), (186, 186, 186), (135, 135, 135), (77, 77, 77)], 'rdgy9': [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (255, 255, 255), (224, 224, 224), (186, 186, 186), (135, 135, 135), (77, 77, 77)], 'rdpu3': [(253, 224, 221), (250, 159, 181), (197, 27, 138)], 'rdpu4': [(254, 235, 226), (251, 180, 185), (247, 104, 161), (174, 1, 126)], 'rdpu5': [(254, 235, 226), (251, 180, 185), (247, 104, 161), (197, 27, 138), (122, 1, 119)], 'rdpu6': [(254, 235, 226), (252, 197, 192), (250, 159, 181), (247, 104, 161), (197, 27, 138), (122, 1, 119)], 'rdpu7': [(254, 235, 226), (252, 197, 192), (250, 159, 181), (247, 104, 161), (221, 52, 151), (174, 1, 126), (122, 1, 119)], 'rdpu8': [(255, 247, 243), (253, 224, 221), (252, 197, 192), (250, 159, 181), (247, 104, 161), (221, 52, 151), (174, 1, 126), (122, 1, 119)], 'rdpu9': [(255, 247, 243), (253, 224, 221), (252, 197, 192), (250, 159, 181), (247, 104, 161), (221, 52, 151), (174, 1, 126), (122, 1, 119), (73, 0, 106)], 'rdylbu10': [(165, 0, 38), (49, 54, 149), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (224, 243, 248), (171, 217, 233), (116, 173, 209), (69, 117, 180)], 'rdylbu11': [(165, 0, 38), (69, 117, 180), (49, 54, 149), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (255, 255, 191), (224, 243, 248), (171, 217, 233), (116, 173, 209)], 'rdylbu3': [(252, 141, 89), (255, 255, 191), (145, 191, 219)], 'rdylbu4': [(215, 25, 28), (253, 174, 97), (171, 217, 233), (44, 123, 182)], 'rdylbu5': [(215, 25, 28), (253, 174, 97), (255, 255, 191), (171, 217, 233), (44, 123, 182)], 'rdylbu6': [(215, 48, 39), (252, 141, 89), (254, 224, 144), (224, 243, 248), (145, 191, 219), (69, 117, 180)], 'rdylbu7': [(215, 48, 39), (252, 141, 89), (254, 224, 144), (255, 255, 191), (224, 243, 248), (145, 191, 219), (69, 117, 180)], 'rdylbu8': [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (224, 243, 248), (171, 217, 233), (116, 173, 209), (69, 117, 180)], 'rdylbu9': [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (255, 255, 191), (224, 243, 248), (171, 217, 233), (116, 173, 209), (69, 117, 180)], 'rdylgn10': [(165, 0, 38), (0, 104, 55), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (217, 239, 139), (166, 217, 106), (102, 189, 99), (26, 152, 80)], 'rdylgn11': [(165, 0, 38), (26, 152, 80), (0, 104, 55), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (217, 239, 139), (166, 217, 106), (102, 189, 99)], 'rdylgn3': [(252, 141, 89), (255, 255, 191), (145, 207, 96)], 'rdylgn4': [(215, 25, 28), (253, 174, 97), (166, 217, 106), (26, 150, 65)], 'rdylgn5': [(215, 25, 28), (253, 174, 97), (255, 255, 191), (166, 217, 106), (26, 150, 65)], 'rdylgn6': [(215, 48, 39), (252, 141, 89), (254, 224, 139), (217, 239, 139), (145, 207, 96), (26, 152, 80)], 'rdylgn7': [(215, 48, 39), (252, 141, 89), (254, 224, 139), (255, 255, 191), (217, 239, 139), (145, 207, 96), (26, 152, 80)], 'rdylgn8': [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (217, 239, 139), (166, 217, 106), (102, 189, 99), (26, 152, 80)], 'rdylgn9': [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (217, 239, 139), (166, 217, 106), (102, 189, 99), (26, 152, 80)], 'reds3': [(254, 224, 210), (252, 146, 114), (222, 45, 38)], 'reds4': [(254, 229, 217), (252, 174, 145), (251, 106, 74), (203, 24, 29)], 'reds5': [(254, 229, 217), (252, 174, 145), (251, 106, 74), (222, 45, 38), (165, 15, 21)], 'reds6': [(254, 229, 217), (252, 187, 161), (252, 146, 114), (251, 106, 74), (222, 45, 38), (165, 15, 21)], 'reds7': [(254, 229, 217), (252, 187, 161), (252, 146, 114), (251, 106, 74), (239, 59, 44), (203, 24, 29), (153, 0, 13)], 'reds8': [(255, 245, 240), (254, 224, 210), (252, 187, 161), (252, 146, 114), (251, 106, 74), (239, 59, 44), (203, 24, 29), (153, 0, 13)], 'reds9': [(255, 245, 240), (254, 224, 210), (252, 187, 161), (252, 146, 114), (251, 106, 74), (239, 59, 44), (203, 24, 29), (165, 15, 21), (103, 0, 13)], 'set13': [(228, 26, 28), (55, 126, 184), (77, 175, 74)], 'set14': [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163)], 'set15': [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0)], 'set16': [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51)], 'set17': [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51), (166, 86, 40)], 'set18': [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51), (166, 86, 40), (247, 129, 191)], 'set19': [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51), (166, 86, 40), (247, 129, 191), (153, 153, 153)], 'set23': [(102, 194, 165), (252, 141, 98), (141, 160, 203)], 'set24': [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195)], 'set25': [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84)], 'set26': [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84), (255, 217, 47)], 'set27': [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84), (255, 217, 47), (229, 196, 148)], 'set28': [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84), (255, 217, 47), (229, 196, 148), (179, 179, 179)], 'set310': [(141, 211, 199), (188, 128, 189), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217)], 'set311': [(141, 211, 199), (188, 128, 189), (204, 235, 197), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217)], 'set312': [(141, 211, 199), (188, 128, 189), (204, 235, 197), (255, 237, 111), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217)], 'set33': [(141, 211, 199), (255, 255, 179), (190, 186, 218)], 'set34': [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114)], 'set35': [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211)], 'set36': [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98)], 'set37': [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105)], 'set38': [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229)], 'set39': [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217)], 'spectral10': [(158, 1, 66), (94, 79, 162), (213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (230, 245, 152), (171, 221, 164), (102, 194, 165), (50, 136, 189)], 'spectral11': [(158, 1, 66), (50, 136, 189), (94, 79, 162), (213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (230, 245, 152), (171, 221, 164), (102, 194, 165)], 'spectral3': [(252, 141, 89), (255, 255, 191), (153, 213, 148)], 'spectral4': [(215, 25, 28), (253, 174, 97), (171, 221, 164), (43, 131, 186)], 'spectral5': [(215, 25, 28), (253, 174, 97), (255, 255, 191), (171, 221, 164), (43, 131, 186)], 'spectral6': [(213, 62, 79), (252, 141, 89), (254, 224, 139), (230, 245, 152), (153, 213, 148), (50, 136, 189)], 'spectral7': [(213, 62, 79), (252, 141, 89), (254, 224, 139), (255, 255, 191), (230, 245, 152), (153, 213, 148), (50, 136, 189)], 'spectral8': [(213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (230, 245, 152), (171, 221, 164), (102, 194, 165), (50, 136, 189)], 'spectral9': [(213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (230, 245, 152), (171, 221, 164), (102, 194, 165), (50, 136, 189)], 'ylgn3': [(247, 252, 185), (173, 221, 142), (49, 163, 84)], 'ylgn4': [(255, 255, 204), (194, 230, 153), (120, 198, 121), (35, 132, 67)], 'ylgn5': [(255, 255, 204), (194, 230, 153), (120, 198, 121), (49, 163, 84), (0, 104, 55)], 'ylgn6': [(255, 255, 204), (217, 240, 163), (173, 221, 142), (120, 198, 121), (49, 163, 84), (0, 104, 55)], 'ylgn7': [(255, 255, 204), (217, 240, 163), (173, 221, 142), (120, 198, 121), (65, 171, 93), (35, 132, 67), (0, 90, 50)], 'ylgn8': [(255, 255, 229), (247, 252, 185), (217, 240, 163), (173, 221, 142), (120, 198, 121), (65, 171, 93), (35, 132, 67), (0, 90, 50)], 'ylgn9': [(255, 255, 229), (247, 252, 185), (217, 240, 163), (173, 221, 142), (120, 198, 121), (65, 171, 93), (35, 132, 67), (0, 104, 55), (0, 69, 41)], 'ylgnbu3': [(237, 248, 177), (127, 205, 187), (44, 127, 184)], 'ylgnbu4': [(255, 255, 204), (161, 218, 180), (65, 182, 196), (34, 94, 168)], 'ylgnbu5': [(255, 255, 204), (161, 218, 180), (65, 182, 196), (44, 127, 184), (37, 52, 148)], 'ylgnbu6': [(255, 255, 204), (199, 233, 180), (127, 205, 187), (65, 182, 196), (44, 127, 184), (37, 52, 148)], 'ylgnbu7': [(255, 255, 204), (199, 233, 180), (127, 205, 187), (65, 182, 196), (29, 145, 192), (34, 94, 168), (12, 44, 132)], 'ylgnbu8': [(255, 255, 217), (237, 248, 177), (199, 233, 180), (127, 205, 187), (65, 182, 196), (29, 145, 192), (34, 94, 168), (12, 44, 132)], 'ylgnbu9': [(255, 255, 217), (237, 248, 177), (199, 233, 180), (127, 205, 187), (65, 182, 196), (29, 145, 192), (34, 94, 168), (37, 52, 148), (8, 29, 88)], 'ylorbr3': [(255, 247, 188), (254, 196, 79), (217, 95, 14)], 'ylorbr4': [(255, 255, 212), (254, 217, 142), (254, 153, 41), (204, 76, 2)], 'ylorbr5': [(255, 255, 212), (254, 217, 142), (254, 153, 41), (217, 95, 14), (153, 52, 4)], 'ylorbr6': [(255, 255, 212), (254, 227, 145), (254, 196, 79), (254, 153, 41), (217, 95, 14), (153, 52, 4)], 'ylorbr7': [(255, 255, 212), (254, 227, 145), (254, 196, 79), (254, 153, 41), (236, 112, 20), (204, 76, 2), (140, 45, 4)], 'ylorbr8': [(255, 255, 229), (255, 247, 188), (254, 227, 145), (254, 196, 79), (254, 153, 41), (236, 112, 20), (204, 76, 2), (140, 45, 4)], 'ylorbr9': [(255, 255, 229), (255, 247, 188), (254, 227, 145), (254, 196, 79), (254, 153, 41), (236, 112, 20), (204, 76, 2), (153, 52, 4), (102, 37, 6)], 'ylorrd3': [(255, 237, 160), (254, 178, 76), (240, 59, 32)], 'ylorrd4': [(255, 255, 178), (254, 204, 92), (253, 141, 60), (227, 26, 28)], 'ylorrd5': [(255, 255, 178), (254, 204, 92), (253, 141, 60), (240, 59, 32), (189, 0, 38)], 'ylorrd6': [(255, 255, 178), (254, 217, 118), (254, 178, 76), (253, 141, 60), (240, 59, 32), (189, 0, 38)], 'ylorrd7': [(255, 255, 178), (254, 217, 118), (254, 178, 76), (253, 141, 60), (252, 78, 42), (227, 26, 28), (177, 0, 38)], 'ylorrd8': [(255, 255, 204), (255, 237, 160), (254, 217, 118), (254, 178, 76), (253, 141, 60), (252, 78, 42), (227, 26, 28), (177, 0, 38)], } if __name__ == '__main__': main()
isi-nlp/bolinas
common/hgraph/xdot.py
Python
mit
91,176
[ "FLEUR" ]
d3fd31a92ac9fd92c5dc16658444acd5a68000242dac761698952cd07537817a
# numkit --- time series manipulation and analysis # Copyright (c) 2010 Oliver Beckstein <orbeckst@gmail.com> # Released under the "Modified BSD Licence" (see COPYING). """ :mod:`numkit.timeseries` --- Time series manipulation and analysis ================================================================== A time series contains of a sequence of time points (typically spaced equally) and a value for each time point. .. autoexception:: LowAccuracyWarning Correlations ------------ .. autofunction:: tcorrel .. autofunction:: autocorrelation_fft Autocorrelation time (time when ACF becomes 0 for the first time):: R = gromacs.formats.XVG("./md.xvg") acf = autocorrelation_fft(R.array[1]) numpy.where(acf <= 0)[0][0] Alternatively, fit an exponential to the ACF and extract the time constant (see :func:`tcorrel`). Coarse graining time series --------------------------- The functions in this section are all based on :func:`regularized_function`. They reduce the number of datapoints in a time series to *maxpoints* by histogramming the data into *maxpoints* bins and then applying a function to reduce the data in each bin. A number of commonly used functions are predefined but it is straightforward to either use :func:`apply_histogrammed_function` or :func:`regularized_function` directly. For instance, :func:`mean_histogrammed_function` is implemented as :: def mean_histogrammed_function(t, y, maxpoints): return apply_histogrammed_function(numpy.mean, t, y, maxpoints) More complicated functions can be defined; for instance, one could use :func:`tcorrel` to compute the correlation time of the data in short blocks:: def tc_histogrammed_function(t, y, maxpoints): dt = numpy.mean(numpy.diff(t)) def get_tcorrel(y): t = numpy.cumsum(dt*numpy.ones_like(y)) - dt results = tcorrel(t, y, nstep=1) return results['tc'] return apply_histogrammed_function(get_tcorrel, t, y, bins=maxpoints) (This particular function (implemented as :func:`tc_histogrammed_function`) is not very robust, for instance it has problems when there are only very few data points in each bin because in this case the auto correlation function is not well defined.) .. autofunction:: mean_histogrammed_function .. autofunction:: rms_histogrammed_function .. autofunction:: min_histogrammed_function .. autofunction:: max_histogrammed_function .. autofunction:: median_histogrammed_function .. autofunction:: percentile_histogrammed_function .. autofunction:: error_histogrammed_function .. autofunction:: circmean_histogrammed_function .. autofunction:: circstd_histogrammed_function .. autofunction:: tc_histogrammed_function .. autofunction:: apply_histogrammed_function .. autofunction:: regularized_function Smoothing time series --------------------- Function :func:`smooth` applies a window kernel to a time series and smoothes fluctuations. The number of points in the time series stays the same. .. autofunction:: smooth .. autofunction:: smoothing_window_length """ from itertools import izip import numpy import scipy.signal import scipy.integrate import scipy.stats import warnings import logging logger = logging.getLogger("numkit.timeseries") from numkit import LowAccuracyWarning def autocorrelation_fft(series, remove_mean=True, paddingcorrection=True, normalize=False, **kwargs): """Calculate the auto correlation function. autocorrelation_fft(series,remove_mean=False,**kwargs) --> acf The time series is correlated with itself across its whole length. Only the [0,len(series)[ interval is returned. By default, the mean of the series is subtracted and the correlation of the fluctuations around the mean are investigated. For the default setting remove_mean=True, acf[0] equals the variance of the series, acf[0] = Var(series) = <(series - <series>)**2>. Optional: * The series can be normalized to its 0-th element so that acf[0] == 1. * For calculating the acf, 0-padding is used. The ACF should be corrected for the 0-padding (the values for larger lags are increased) unless mode='valid' is set (see below). Note that the series for mode='same'|'full' is inaccurate for long times and should probably be truncated at 1/2*len(series) :Arguments: *series* (time) series, a 1D numpy array of length N *remove_mean* ``False``: use series as is; ``True``: subtract mean(series) from series [``True``] *paddingcorrection* ``False``: corrected for 0-padding; ``True``: return as is it is. (the latter is appropriate for periodic signals). The correction for element 0=<i<N amounts to a factor N/(N-i). Only applied for modes != "valid" [``True``] *normalize* ``True`` divides by acf[0] so that the first element is 1; ``False`` leaves un-normalized [``False``] *mode* "full" | "same" | "valid": see :func:`scipy.signal.fftconvolve` ["full"] *kwargs* other keyword arguments for :func:`scipy.signal.fftconvolve` """ kwargs.setdefault('mode','full') if len(series.shape) > 2: # var/mean below would need proper axis arguments to deal with high dim raise TypeError("series must be a 1D array at the moment") if remove_mean: series = numpy.squeeze(series.astype(float)).copy() # must copy because de-meaning modifies it mean = series.mean() series -= mean else: series = numpy.squeeze(series.astype(float)) # can deal with a view ac = scipy.signal.fftconvolve(series,series[::-1,...],**kwargs) origin = ac.shape[0]/2 # should work for both odd and even len(series) ac = ac[origin:] # only use second half of the symmetric acf assert len(ac) <= len(series), "Oops: len(ac)={0:d} len(series)={1:d}".format(len(ac), len(series)) if paddingcorrection and not kwargs['mode'] == 'valid': # 'valid' was not 0-padded # correct for 0 padding # XXX: reference? Where did I get this from? (But it makes sense.) ac *= len(series)/(len(series) - 1.0*numpy.arange(len(ac))) norm = ac[0] or 1.0 # to guard against ACFs of zero arrays if not normalize: # We use the convention that the ACF is divided by the total time, # which makes acf[0] == <series**2> = Var(series) + <series>**2. We do # not need to know the time (x) in order to scale the output from the # ACF-series accordingly: try: if remove_mean: norm /= numpy.var(series) else: norm /= numpy.mean(series*series) except ZeroDivisionError: norm = 1.0 return ac/norm def tcorrel(x, y, nstep=100, debug=False): """Calculate the correlation time and an estimate of the error of the mean <y>. The autocorrelation function f(t) is calculated via FFT on every *nstep* of the **fluctuations** of the data around the mean (y-<y>). The normalized ACF f(t)/f(0) is assumed to decay exponentially, f(t)/f(0) = exp(-t/tc) and the decay constant tc is estimated as the integral of the ACF from the start up to its first root. See [FrenkelSmit2002]_ `p526`_ for details. .. Note:: *nstep* should be set sufficiently large so that there are less than ~50,000 entries in the input. .. [FrenkelSmit2002] D. Frenkel and B. Smit, Understanding Molecular Simulation. Academic Press, San Diego 2002 .. _p526: http://books.google.co.uk/books?id=XmyO2oRUg0cC&pg=PA526 :Arguments: *x* 1D array of abscissa values (typically time) *y* 1D array of the ibservable y(x) *nstep* only analyze every *nstep* datapoint to speed up calculation [100] :Returns: dictionary with entries *tc* (decay constant in units of *x*), *t0* (value of the first root along x (y(t0) = 0)), *sigma* (error estimate for the mean of y, <y>, corrected for correlations in the data). """ if x.shape != y.shape: raise TypeError("x and y must be y(x), i.e. same shape") _x = x[::nstep] # do not run acf on all data: takes too long _y = y[::nstep] # and does not improve accuracy if len(_y) < 500: # 500 is a bit arbitrary wmsg = "tcorrel(): Only %d datapoints for the chosen nstep=%d; " \ "ACF will possibly not be accurate." % (len(_y), nstep) warnings.warn(wmsg, category=LowAccuracyWarning) logger.warn(wmsg) acf = autocorrelation_fft(_y, normalize=False) try: i0 = numpy.where(acf <= 0)[0][0] # first root of acf except IndexError: i0 = -1 # use last value as best estimate t0 = _x[i0] # integral of the _normalized_ acf norm = acf[0] or 1.0 # guard against a zero ACF tc = scipy.integrate.simps(acf[:i0]/norm, x=_x[:i0]) # error estimate for the mean [Frenkel & Smit, p526] sigma = numpy.sqrt(2*tc*acf[0]/(x[-1] - x[0])) result = {'tc':tc, 't0':t0, 'sigma':sigma} if debug: result['t'] = _x[:i0] result['acf'] = acf[:i0] return result def smooth(x, window_len=11, window='flat'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. :Arguments: *x* the input signal, 1D array *window_len* the dimension of the smoothing window, always converted to an integer (using :func:`int`) and must be odd *window* the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'; flat window will produce a moving average smoothing. If *window* is a :class:`numpy.ndarray` then this array is directly used as the window (but it still must contain an odd number of points) ["flat"] :Returns: the smoothed signal as a 1D array :Example: Apply a simple moving average to a noisy harmonic signal:: >>> import numpy as np >>> t = np.linspace(-2, 2, 201) >>> x = np.sin(t) + np.random.randn(len(t))*0.1 >>> y = smooth(x) .. See Also:: :func:`numpy.hanning`, :func:`numpy.hamming`, :func:`numpy.bartlett`, :func:`numpy.blackman`, :func:`numpy.convolve`, :func:`scipy.signal.lfilter` Source: based on http://www.scipy.org/Cookbook/SignalSmooth """ windows = {'flat': lambda n: numpy.ones(n, dtype=float), 'hanning': numpy.hanning, 'hamming': numpy.hamming, 'bartlett': numpy.bartlett, 'blackman': numpy.blackman, } window_len = int(window_len) if isinstance(window, numpy.ndarray): window_len = len(window) w = numpy.asarray(window, dtype=float) else: try: w = windows[window](window_len) except KeyError: raise ValueError("Window {0!r} not supported; must be one of {1!r}".format(window, windows.keys())) if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: raise ValueError("Input vector needs to be bigger than window size.") if window_len % 2 == 0: raise ValueError("window_len should be an odd integer") if window_len < 3: return x s = numpy.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]] y = numpy.convolve(w/w.sum(), s, mode='valid') return y[(window_len-1)/2:-(window_len-1)/2] # take off repeats on ends def smoothing_window_length(resolution, t): """Compute the length of a smooting window of *resolution* time units. :Arguments: *resolution* length in units of the time in which *t* us supplied *t* array of time points; if not equidistantly spaced, the mean spacing is used to compute the window length :Returns: odd integer, the size of a window of approximately *resolution* .. SeeAlso:: :func:`smooth` """ dt = numpy.mean(numpy.diff(t)) N = int(resolution/dt) if N % 2 == 0: N += 1 return N def mean_histogrammed_function(t, y, **kwargs): """Compute mean of data *y* in bins along *t*. Returns the mean-regularised function *F* and the centers of the bins. .. SeeAlso:: :func:`regularized_function` with *func* = :func:`numpy.mean` """ return apply_histogrammed_function(numpy.mean, t, y, **kwargs) def rms_histogrammed_function(t, y, **kwargs): """Compute root mean square of data *y* in bins along *t*. Returns the RMS-regularised function *F* and the centers of the bins. *demean* = ``True`` removes the mean first. :func:`regularized_function` with *func* = ``sqrt(mean(y*y))`` """ def rms(a, demean=kwargs.pop('demean', False)): if len(a) == 0: return numpy.NAN if demean: a -= numpy.mean(a) return numpy.sqrt(numpy.mean(a*a)) return apply_histogrammed_function(rms, t, y, **kwargs) def min_histogrammed_function(t, y, **kwargs): """Compute minimum of data *y* in bins along *t*. Returns the min-regularised function *F* and the centers of the bins. :func:`regularized_function` with *func* = :func:`numpy.min` """ def _min(a): if len(a) == 0: return numpy.NAN return numpy.min(a) return apply_histogrammed_function(_min, t, y, **kwargs) def max_histogrammed_function(t, y, **kwargs): """Compute maximum of data *y* in bins along *t*. Returns the max-regularised function *F* and the centers of the bins. :func:`regularized_function` with *func* = :func:`numpy.max` """ def _max(a): if len(a) == 0: return numpy.NAN return numpy.max(a) return apply_histogrammed_function(_max, t, y, **kwargs) def median_histogrammed_function(t, y, **kwargs): """Compute median of data *y* in bins along *t*. Returns the median-regularised function *F* and the centers of the bins. :func:`regularized_function` with *func* = :func:`numpy.median` """ return apply_histogrammed_function(numpy.median, t, y, **kwargs) def percentile_histogrammed_function(t, y, **kwargs): """Compute the percentile *per* of data *y* in bins along *t*. Returns the percentile-regularised function *F* and the centers of the bins. :Keywords: *per* percentile as a percentage, e.g. 75 is the value that splits the data into the lower 75% and upper 25%; 50 is the median [50.0] *demean* ``True``: remove the mean of the bin data first [``False``] :func:`regularized_function` with :func:`scipy.stats.scoreatpercentile` """ def percentile(a, per=kwargs.pop('per', 50.), limit=kwargs.pop('limit', ()), demean=kwargs.pop('demean', False), interpolation_method='fraction'): if len(a) == 0: return numpy.NAN if demean: a -= numpy.mean(a) return scipy.stats.scoreatpercentile(a, per, limit=limit) return apply_histogrammed_function(percentile, t, y, **kwargs) def tc_histogrammed_function(t, y, **kwargs): """Calculate the correlation time in each bin using :func:`tcorrel`. .. Warning:: Not well tested and fragile. """ dt = numpy.mean(numpy.diff(t)) def get_tcorrel(a): if len(a) == 0: return numpy.NAN t = numpy.cumsum(dt*numpy.ones_like(a)) - dt results = tcorrel(t, a, nstep=1) return results['tc'] return apply_histogrammed_function(get_tcorrel, t, y, **kwargs) def error_histogrammed_function(t, y, **kwargs): """Calculate the error in each bin using :func:`tcorrel`. .. Warning:: Not well tested and fragile. """ dt = numpy.mean(numpy.diff(t)) def get_tcorrel(a): if len(a) == 0: return numpy.NAN t = numpy.cumsum(dt*numpy.ones_like(a)) - dt results = tcorrel(t, a, nstep=1) return results['sigma'] return apply_histogrammed_function(get_tcorrel, t, y, **kwargs) def circmean_histogrammed_function(t, y, **kwargs): """Compute circular mean of data *y* in bins along *t*. Returns the circmean-regularised function *F* and the centers of the bins. *kwargs* are passed to :func:`scipy.stats.morestats.circmean`, in particular set the lower bound with *low* and the upper one with *high*. The default is [-pi, +pi]. :func:`regularized_function` with *func* = :func:`scipy.stats.morestats.circmean` .. Note:: Data are interpreted as angles in radians. """ low = kwargs.pop('low', -numpy.pi) high = kwargs.pop('high', numpy.pi) def _circmean(a, low=low, high=high): if len(a) == 0: return numpy.NAN return scipy.stats.morestats.circmean(a, low=low, high=high) return apply_histogrammed_function(_circmean, t, y, **kwargs) def circstd_histogrammed_function(t, y, **kwargs): """Compute circular standard deviation of data *y* in bins along *t*. Returns the circstd-regularised function *F* and the centers of the bins. *kwargs* are passed to :func:`scipy.stats.morestats.circmean`, in particular set the lower bound with *low* and the upper one with *high*. The default is [-pi, +pi]. :func:`regularized_function` with *func* = :func:`scipy.stats.morestats.circstd` .. Note:: Data are interpreted as angles in radians. """ low = kwargs.pop('low', -numpy.pi) high = kwargs.pop('high', numpy.pi) def _circstd(a, low=low, high=high): if len(a) == 0: return numpy.NAN return scipy.stats.morestats.circstd(a, low=low, high=high) return apply_histogrammed_function(_circstd, t, y, **kwargs) def apply_histogrammed_function(func, t, y, **kwargs): """Compute *func* of data *y* in bins along *t*. Returns the *func* -regularised function *F(t')* and the centers of the bins *t'*. .. function:: func(y) -> float *func* takes exactly one argument, a numpy 1D array *y* (the values in a single bin of the histogram), and reduces it to one scalar float. """ F, e = regularized_function(t, y, func, **kwargs) return F, 0.5*(e[:-1] + e[1:]) def regularized_function(x, y, func, bins=100, range=None): """Compute *func()* over data aggregated in bins. ``(x,y) --> (x', func(Y'))`` with ``Y' = {y: y(x) where x in x' bin}`` First the data is collected in bins x' along x and then *func* is applied to all data points Y' that have been collected in the bin. .. function:: func(y) -> float *func* takes exactly one argument, a numpy 1D array *y* (the values in a single bin of the histogram), and reduces it to one scalar float. .. Note:: *x* and *y* must be 1D arrays. :Arguments: x abscissa values (for binning) y ordinate values (func is applied) func a numpy ufunc that takes one argument, func(Y') bins number or array range limits (used with number of bins) :Returns: F,edges function and edges (``midpoints = 0.5*(edges[:-1]+edges[1:])``) (This function originated as :func:`recsql.sqlfunctions.regularized_function`.) """ _x = numpy.asarray(x) _y = numpy.asarray(y) if len(_x.shape) != 1 or len(_y.shape) != 1: raise TypeError("Can only deal with 1D arrays.") # setup of bins (taken from numpy.histogram) if (range is not None): mn, mx = range if (mn > mx): raise AttributeError('max must be larger than min in range parameter.') if not numpy.iterable(bins): if range is None: range = (_x.min(), _x.max()) mn, mx = [float(mi) for mi in range] if mn == mx: mn -= 0.5 mx += 0.5 bins = numpy.linspace(mn, mx, bins+1, endpoint=True) else: bins = numpy.asarray(bins) if (numpy.diff(bins) < 0).any(): raise ValueError('bins must increase monotonically.') sorting_index = numpy.argsort(_x) sx = _x[sorting_index] sy = _y[sorting_index] # boundaries in SORTED data that demarcate bins; position in bin_index is the bin number bin_index = numpy.r_[sx.searchsorted(bins[:-1], 'left'), sx.searchsorted(bins[-1], 'right')] # naive implementation: apply operator to each chunk = sy[start:stop] separately # # It's not clear to me how one could effectively block this procedure (cf # block = 65536 in numpy.histogram) because there does not seem to be a # general way to combine the chunks for different blocks, just think of # func=median F = numpy.zeros(len(bins)-1) # final function F[:] = [func(sy[start:stop]) for start,stop in izip(bin_index[:-1],bin_index[1:])] return F,bins
jandom/GromacsWrapper
numkit/timeseries.py
Python
gpl-3.0
21,347
[ "Gromacs" ]
c1c1227b08a7b035fee2b883427429334a8ece99e2396b5da6a686c81605951f
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import unittest import requests from pymatgen.ext.jhu import get_kpoints from pymatgen.io.vasp.inputs import Incar from pymatgen.io.vasp.sets import MPRelaxSet from pymatgen.util.testing import PymatgenTest __author__ = "Joseph Montoya" __copyright__ = "Copyright 2017, The Materials Project" __maintainer__ = "Joseph Montoya" __email__ = "montoyjh@lbl.gov" __date__ = "June 22, 2017" website_is_up = requests.get("http://muellergroup.jhu.edu:8080").status_code == 200 @unittest.skipIf(not website_is_up, "http://muellergroup.jhu.edu:8080 is down.") class JhuTest(PymatgenTest): _multiprocess_shared_ = True def test_get_kpoints(self): si = PymatgenTest.get_structure("Si") input_set = MPRelaxSet(si) kpoints = get_kpoints(si, incar=input_set.incar) if __name__ == "__main__": unittest.main()
richardtran415/pymatgen
pymatgen/ext/tests/test_jhu.py
Python
mit
949
[ "VASP", "pymatgen" ]
15e1e8e94a8b542332e124557771f1da8ef611c7ca3fbd38289637807a559017
"""Support for control of ElkM1 lighting (X10, UPB, etc).""" from __future__ import annotations from homeassistant.components.light import ( ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from . import ElkEntity, create_elk_entities from .const import DOMAIN async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Elk light platform.""" elk_data = hass.data[DOMAIN][config_entry.entry_id] entities: list[ElkLight] = [] elk = elk_data["elk"] create_elk_entities(elk_data, elk.lights, "plc", ElkLight, entities) async_add_entities(entities, True) class ElkLight(ElkEntity, LightEntity): """Representation of an Elk lighting device.""" def __init__(self, element, elk, elk_data): """Initialize the Elk light.""" super().__init__(element, elk, elk_data) self._brightness = self._element.status @property def brightness(self): """Get the brightness.""" return self._brightness @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS @property def is_on(self) -> bool: """Get the current brightness.""" return self._brightness != 0 def _element_changed(self, element, changeset): status = self._element.status if self._element.status != 1 else 100 self._brightness = round(status * 2.55) async def async_turn_on(self, **kwargs): """Turn on the light.""" self._element.level(round(kwargs.get(ATTR_BRIGHTNESS, 255) / 2.55)) async def async_turn_off(self, **kwargs): """Turn off the light.""" self._element.level(0)
rohitranjan1991/home-assistant
homeassistant/components/elkm1/light.py
Python
mit
1,934
[ "Elk" ]
ba7509667d728e8578bcdc92992f7ae329d2f6c04d947aaec3c693ff02e2f378
# -*- coding: utf-8 -*- """ Authors: Gonzalo E. Espinoza-Dávalos, Wim G.M. Bastiaanssen, Boaz Bett, and Xueliang Cai IHE Delft 2017 Contact: g.espinoza@un-ihe.org Repository: https://github.com/gespinoza/hants Module: hants Description: This module is an implementation of the Harmonic ANalysis of Time Series (HANTS) applied to geographic data. This module can be used to perform the HANTS analysis to a collection of time-variable raster data at each pixel. There are two equivalent options to run HANTS: - gdal: for this option use 'from hants import wa_gdal' - arcpy: for this option use 'from hants import wa_arcpy' The only difference between the two options is the underlying library to process the geographic data. The HANTS algorithm is the same. Example 1: from hants.wa_arcpy import * # Data parameters rasters_path = r'C:\example\data' name_format = 'PROBAV_S1_TOC_{0}_100M_V001.tif' start_date = '2015-08-01' end_date = '2016-07-28' latlim = [11.4505, 11.4753] lonlim = [108.8605, 108.8902] cellsize = 0.00099162627 nc_path = r'C:\example\ndvi_probav.nc' rasters_path_out = r'C:\example\output_rasters' # HANTS parameters nb = 365 nf = 3 low = -1 high = 1 HiLo = 'Lo' fet = 0.05 delta = 0.1 dod = 1 # Run run_HANTS(rasters_path, name_format, start_date, end_date, latlim, lonlim, cellsize, nc_path, nb, nf, HiLo, low, high, fet, dod, delta, 4326, -9999.0, rasters_path_out) # Check fit point = [108.87, 11.47] ylim = [-1, 1] plot_point(nc_path, point, ylim) Example 2: from hants.wa_arcpy import * # Create netcdf file rasters_path = r'C:\example\data' name_format = 'PROBAV_S1_TOC_{0}_100M_V001.tif' start_date = '2015-08-01' end_date = '2016-07-28' latlim = [11.4505, 11.4753] lonlim = [108.8605, 108.8902] cellsize = 0.00099162627 nc_path = r'C:\example\ndvi_probav.nc' create_netcdf(rasters_path, name_format, start_date, end_date, latlim, lonlim, cellsize, nc_path) # Run HANTS for a single point nb = 365 nf = 3 low = -1 high = 1 HiLo = 'Lo' fet = 0.05 delta = 0.1 dod = 1 point = [108.87, 11.47] df = HANTS_singlepoint(nc_path, point, nb, nf, HiLo, low, high, fet, dod, delta) print df # Run HANTS HANTS_netcdf(nc_path, nb, nf, HiLo, low, high, fet, dod, delta) # Check fit ylim = [-1, 1] plot_point(nc_path, point, ylim) # Export rasters rasters_path_out = r'C:\example\output_rasters' export_tiffs(rasters_path_out, nc_path, name_format) """ from .main import (run_HANTS, create_netcdf, HANTS_netcdf, HANTS, export_tiffs, HANTS_singlepoint, plot_point) __all__ = ['run_HANTS', 'create_netcdf', 'HANTS_netcdf', 'HANTS', 'export_tiffs', 'HANTS_singlepoint', 'plot_point'] __version__ = '0.1'
gespinoza/hants
wa_arcpy/__init__.py
Python
apache-2.0
2,745
[ "NetCDF" ]
229f06299acced0146b42d35ceab36132faf6c3951d43e197fbf478d9e074159
from __future__ import (absolute_import, division, print_function) import numpy as np import re import warnings from six import string_types # RegEx pattern matching a composite function parameter name, eg f2.Sigma. FN_PATTERN = re.compile('f(\\d+)\\.(.+)') # RegEx pattern matching a composite function parameter name, eg f2.Sigma. Multi-spectrum case. FN_MS_PATTERN = re.compile('f(\\d+)\\.f(\\d+)\\.(.+)') def makeWorkspace(xArray, yArray): """Create a workspace that doesn't appear in the ADS""" from mantid.api import AlgorithmManager alg = AlgorithmManager.createUnmanaged('CreateWorkspace') alg.initialize() alg.setChild(True) alg.setProperty('DataX', xArray) alg.setProperty('DataY', yArray) alg.setProperty('OutputWorkspace', 'dummy') alg.execute() return alg.getProperty('OutputWorkspace').value def islistlike(arg): return (not hasattr(arg, "strip")) and (hasattr(arg, "__getitem__") or hasattr(arg, "__iter__")) #pylint: disable=too-many-instance-attributes,too-many-public-methods class CrystalField(object): """Calculates the crystal fields for one ion""" ion_nre_map = {'Ce': 1, 'Pr': 2, 'Nd': 3, 'Pm': 4, 'Sm': 5, 'Eu': 6, 'Gd': 7, 'Tb': 8, 'Dy': 9, 'Ho': 10, 'Er': 11, 'Tm': 12, 'Yb': 13} allowed_symmetries = ['C1', 'Ci', 'C2', 'Cs', 'C2h', 'C2v', 'D2', 'D2h', 'C4', 'S4', 'C4h', 'D4', 'C4v', 'D2d', 'D4h', 'C3', 'S6', 'D3', 'C3v', 'D3d', 'C6', 'C3h', 'C6h', 'D6', 'C6v', 'D3h', 'D6h', 'T', 'Td', 'Th', 'O', 'Oh'] default_peakShape = 'Gaussian' default_background = 'FlatBackground' default_spectrum_size = 200 field_parameter_names = ['BmolX','BmolY','BmolZ','BextX','BextY','BextZ', 'B20','B21','B22','B40','B41','B42','B43','B44','B60','B61','B62','B63','B64','B65','B66', 'IB21','IB22','IB41','IB42','IB43','IB44','IB61','IB62','IB63','IB64','IB65','IB66'] def __init__(self, Ion, Symmetry, **kwargs): """ Constructor. @param Ion: A rare earth ion. Possible values: Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb @param Symmetry: Symmetry of the field. Possible values: C1, Ci, C2, Cs, C2h, C2v, D2, D2h, C4, S4, C4h, D4, C4v, D2d, D4h, C3, S6, D3, C3v, D3d, C6, C3h, C6h, D6, C6v, D3h, D6h, T, Td, Th, O, Oh @param kwargs: Other field parameters and attributes. Acceptable values include: ToleranceEnergy: energy tolerance, ToleranceIntensity: intensity tolerance, ResolutionModel: A resolution model. FWHMVariation: Absolute value of allowed variation of a peak width during a fit. FixAllPeaks: A boolean flag that fixes all parameters of the peaks. Field parameters: BmolX: The x-component of the molecular field, BmolY: The y-component of the molecular field, BmolZ: The z-component of the molecular field, BextX: The x-component of the external field, BextY: The y-component of the external field, BextZ: The z-component of the external field, B20: Real part of the B20 field parameter, B21: Real part of the B21 field parameter, B22: Real part of the B22 field parameter, B40: Real part of the B40 field parameter, B41: Real part of the B41 field parameter, B42: Real part of the B42 field parameter, B43: Real part of the B43 field parameter, B44: Real part of the B44 field parameter, B60: Real part of the B60 field parameter, B61: Real part of the B61 field parameter, B62: Real part of the B62 field parameter, B63: Real part of the B63 field parameter, B64: Real part of the B64 field parameter, B65: Real part of the B65 field parameter, B66: Real part of the B66 field parameter, IB21: Imaginary part of the B21 field parameter, IB22: Imaginary part of the B22 field parameter, IB41: Imaginary part of the B41 field parameter, IB42: Imaginary part of the B42 field parameter, IB43: Imaginary part of the B43 field parameter, IB44: Imaginary part of the B44 field parameter, IB61: Imaginary part of the B61 field parameter, IB62: Imaginary part of the B62 field parameter, IB63: Imaginary part of the B63 field parameter, IB64: Imaginary part of the B64 field parameter, IB65: Imaginary part of the B65 field parameter, IB66: Imaginary part of the B66 field parameter, Each of the following parameters can be either a single float or an array of floats. They are either all floats or all arrays of the same size. IntensityScaling: A scaling factor for the intensity of each spectrum. FWHM: A default value for the full width at half maximum of the peaks. Temperature: A temperature "of the spectrum" in Kelvin PhysicalProperty: A list of PhysicalProperties objects denoting the required data type Note that physical properties datasets should follow inelastic spectra See the Crystal Field Python Interface help page for more details. """ self._background = None if 'Temperature' in kwargs: temperature = kwargs['Temperature'] del kwargs['Temperature'] else: temperature = -1 # Create self.function attribute self._makeFunction(Ion, Symmetry, temperature) self.Temperature = temperature self.Ion = Ion self.Symmetry = Symmetry self._resolutionModel = None self._physprop = None free_parameters = {key: kwargs[key] for key in kwargs if key in CrystalField.field_parameter_names} for key in kwargs: if key == 'ToleranceEnergy': self.ToleranceEnergy = kwargs[key] elif key == 'ToleranceIntensity': self.ToleranceIntensity = kwargs[key] elif key == 'IntensityScaling': self.IntensityScaling = kwargs[key] elif key == 'FWHM': self.FWHM = kwargs[key] elif key == 'ResolutionModel': self.ResolutionModel = kwargs[key] elif key == 'NPeaks': self.NPeaks = kwargs[key] elif key == 'FWHMVariation': self.FWHMVariation = kwargs[key] elif key == 'FixAllPeaks': self.FixAllPeaks = kwargs[key] elif key == 'PhysicalProperty': self.PhysicalProperty = kwargs[key] elif key not in free_parameters: raise RuntimeError('Unknown attribute/parameters %s' % key) for param in CrystalField.field_parameter_names: if param in free_parameters: self.function.setParameter(param, free_parameters[param]) else: self.function.fixParameter(param) self._setPeaks() # Eigensystem self._dirty_eigensystem = True self._eigenvalues = None self._eigenvectors = None self._hamiltonian = None # Peak lists self._dirty_peaks = True self._peakList = None # Spectra self._dirty_spectra = True self._spectra = {} self._plot_window = {} # self._setDefaultTies() self.chi2 = None def _makeFunction(self, ion, symmetry, temperature): from mantid.simpleapi import FunctionFactory if temperature is not None and islistlike(temperature) and len(temperature) > 1: self.function = FunctionFactory.createFunction('CrystalFieldMultiSpectrum') self._isMultiSpectrum = True tempStr = 'Temperatures' else: self.function = FunctionFactory.createFunction('CrystalFieldSpectrum') self._isMultiSpectrum = False tempStr = 'Temperature' self.function.setAttributeValue('Ion', ion) self.function.setAttributeValue('Symmetry', symmetry) if temperature: temperature = [float(val) for val in temperature] if islistlike(temperature) else float(temperature) self.function.setAttributeValue(tempStr, temperature) def _remakeFunction(self, temperature): """Redefines the internal function, e.g. when `Temperature` (number of datasets) change""" fieldParams = self._getFieldParameters() self._makeFunction(self.Ion, self.Symmetry, temperature) for item in fieldParams.items(): self.function.setParameter(item[0], item[1]) for param in CrystalField.field_parameter_names: if param not in fieldParams.keys(): self.function.fixParameter(param) def _setPeaks(self): from .function import PeaksFunction if self._isMultiSpectrum: self._peaks = [] for i in range(self.NumberOfSpectra): self._peaks.append(PeaksFunction(self.crystalFieldFunction, 'f%s.' % i, 1)) else: self._peaks = PeaksFunction(self.crystalFieldFunction, '', 0) @property def crystalFieldFunction(self): if not self._isMultiSpectrum and self.background is not None: return self.function[1] else: return self.function def makePeaksFunction(self, i): """Form a definition string for the CrystalFieldPeaks function @param i: Index of a spectrum. """ temperature = self._getTemperature(i) out = 'name=CrystalFieldPeaks,Ion=%s,Symmetry=%s,Temperature=%s' % (self.Ion, self.Symmetry, temperature) out += ',ToleranceEnergy=%s,ToleranceIntensity=%s' % (self.ToleranceEnergy, self.ToleranceIntensity) out += ',%s' % ','.join(['%s=%s' % item for item in self._getFieldParameters().items()]) return out def makeSpectrumFunction(self, i=0): """Form a definition string for the CrystalFieldSpectrum function @param i: Index of a spectrum. """ if not self._isMultiSpectrum: return str(self.function) else: funs = self.function.createEquivalentFunctions() return str(funs[i]) def makePhysicalPropertiesFunction(self, i=0): """Form a definition string for one of the crystal field physical properties functions @param i: Index of the dataset (default=0), or a PhysicalProperties object. """ if hasattr(i, 'toString'): out = i.toString() else: if self._physprop is None: raise RuntimeError('Physical properties environment not defined.') ppobj = self._physprop[i] if islistlike(self._physprop) else self._physprop if hasattr(ppobj, 'toString'): out = ppobj.toString() else: return '' out += ',Ion=%s,Symmetry=%s' % (self.Ion, self.Symmetry) fieldParams = self._getFieldParameters() if len(fieldParams) > 0: out += ',%s' % ','.join(['%s=%s' % item for item in fieldParams.items()]) ties = self._getFieldTies() if len(ties) > 0: out += ',ties=(%s)' % ties constraints = self._getFieldConstraints() if len(constraints) > 0: out += ',constraints=(%s)' % constraints return out def makeMultiSpectrumFunction(self): import re return re.sub(r'FWHM[X|Y]\d+=\(\),', '', str(self.function)) @property def Ion(self): """Get value of Ion attribute. For example: cf = CrystalField(...) ... ion = cf.Ion """ return self.crystalFieldFunction.getAttributeValue('Ion') @Ion.setter def Ion(self, value): """Set new value of Ion attribute. For example: cf = CrystalField(...) ... cf.Ion = 'Pr' """ if value not in self.ion_nre_map.keys(): msg = 'Value %s is not allowed for attribute Ion.\nList of allowed values: %s' % \ (value, ', '.join(list(self.ion_nre_map.keys()))) raise RuntimeError(msg) self.crystalFieldFunction.setAttributeValue('Ion', value) self._dirty_eigensystem = True self._dirty_peaks = True self._dirty_spectra = True @property def Symmetry(self): """Get value of Symmetry attribute. For example: cf = CrystalField(...) ... symm = cf.Symmetry """ return self.crystalFieldFunction.getAttributeValue('Symmetry') @Symmetry.setter def Symmetry(self, value): """Set new value of Symmetry attribute. For example: cf = CrystalField(...) ... cf.Symmetry = 'Td' """ if value not in self.allowed_symmetries: msg = 'Value %s is not allowed for attribute Symmetry.\nList of allowed values: %s' % \ (value, ', '.join(self.allowed_symmetries)) raise RuntimeError(msg) self.crystalFieldFunction.setAttributeValue('Symmetry', value) self._dirty_eigensystem = True self._dirty_peaks = True self._dirty_spectra = True @property def ToleranceEnergy(self): """Get energy tolerance""" return self.crystalFieldFunction.getAttributeValue('ToleranceEnergy') @ToleranceEnergy.setter def ToleranceEnergy(self, value): """Set energy tolerance""" self.crystalFieldFunction.setAttributeValue('ToleranceEnergy', float(value)) self._dirty_peaks = True self._dirty_spectra = True @property def ToleranceIntensity(self): """Get intensity tolerance""" return self.crystalFieldFunction.getAttributeValue('ToleranceIntensity') @ToleranceIntensity.setter def ToleranceIntensity(self, value): """Set intensity tolerance""" self.crystalFieldFunction.setAttributeValue('ToleranceIntensity', float(value)) self._dirty_peaks = True self._dirty_spectra = True @property def IntensityScaling(self): if not self._isMultiSpectrum: return self.crystalFieldFunction.getParameterValue('IntensityScaling') iscaling = [] for i in range(self.NumberOfSpectra): paramName = 'IntensityScaling%s' % i iscaling.append(self.crystalFieldFunction.getParameterValue(paramName)) return iscaling @IntensityScaling.setter def IntensityScaling(self, value): if not self._isMultiSpectrum: if islistlike(value): if len(value) == 1: value = value[0] else: raise ValueError('IntensityScaling is expected to be a single floating point value') self.crystalFieldFunction.setParameter('IntensityScaling', value) else: n = self.NumberOfSpectra if not islistlike(value) or len(value) != n: raise ValueError('IntensityScaling is expected to be a list of %s values' % n) for i in range(n): paramName = 'IntensityScaling%s' % i self.crystalFieldFunction.setParameter(paramName, value[i]) self._dirty_peaks = True self._dirty_spectra = True @property def Temperature(self): attrName = 'Temperatures' if self._isMultiSpectrum else 'Temperature' return self.crystalFieldFunction.getAttributeValue(attrName) @Temperature.setter def Temperature(self, value): if islistlike(value) and len(value) == 1: value = value[0] if self._isMultiSpectrum: if not islistlike(value): # Try to keep current set of field parameters. self._remakeFunction(float(value)) return self.crystalFieldFunction.setAttributeValue('Temperatures', value) else: if islistlike(value): self._remakeFunction(value) return self.crystalFieldFunction.setAttributeValue('Temperature', float(value)) self._dirty_peaks = True self._dirty_spectra = True @property def FWHM(self): attrName = 'FWHMs' if self._isMultiSpectrum else 'FWHM' fwhm = self.crystalFieldFunction.getAttributeValue(attrName) if self._isMultiSpectrum: nDatasets = len(self.Temperature) if len(fwhm) != nDatasets: return list(fwhm) * nDatasets return fwhm @FWHM.setter def FWHM(self, value): if islistlike(value) and len(value) == 1: value = value[0] if self._isMultiSpectrum: if not islistlike(value): value = [value] * self.NumberOfSpectra self.crystalFieldFunction.setAttributeValue('FWHMs', value) else: if islistlike(value): raise ValueError('FWHM is expected to be a single floating point value') self.crystalFieldFunction.setAttributeValue('FWHM', float(value)) self._dirty_spectra = True @property def FWHMVariation(self): return self.crystalFieldFunction.getAttributeValue('FWHMVariation') @FWHMVariation.setter def FWHMVariation(self, value): self.crystalFieldFunction.setAttributeValue('FWHMVariation', float(value)) self._dirty_spectra = True def __getitem__(self, item): return self.crystalFieldFunction.getParameterValue(item) def __setitem__(self, key, value): self._dirty_spectra = True self.crystalFieldFunction.setParameter(key, value) @property def ResolutionModel(self): return self._resolutionModel @ResolutionModel.setter def ResolutionModel(self, value): from .function import ResolutionModel if isinstance(value, ResolutionModel): self._resolutionModel = value else: self._resolutionModel = ResolutionModel(value) if self._isMultiSpectrum: if not self._resolutionModel.multi or self._resolutionModel.NumberOfSpectra != self.NumberOfSpectra: raise RuntimeError('Resolution model is expected to have %s functions, found %s' % (self.NumberOfSpectra, self._resolutionModel.NumberOfSpectra)) for i in range(self.NumberOfSpectra): model = self._resolutionModel.model[i] self.crystalFieldFunction.setAttributeValue('FWHMX%s' % i, model[0]) self.crystalFieldFunction.setAttributeValue('FWHMY%s' % i, model[1]) else: model = self._resolutionModel.model self.crystalFieldFunction.setAttributeValue('FWHMX', model[0]) self.crystalFieldFunction.setAttributeValue('FWHMY', model[1]) @property def FixAllPeaks(self): return self.crystalFieldFunction.getAttributeValue('FixAllPeaks') @FixAllPeaks.setter def FixAllPeaks(self, value): self.crystalFieldFunction.setAttributeValue('FixAllPeaks', value) @property def PeakShape(self): return self.crystalFieldFunction.getAttributeValue('PeakShape') @PeakShape.setter def PeakShape(self, value): self.crystalFieldFunction.setAttributeValue('PeakShape', value) @property def NumberOfSpectra(self): return self.crystalFieldFunction.getNumberDomains() @property def NPeaks(self): return self.crystalFieldFunction.getAttributeValue('NPeaks') @NPeaks.setter def NPeaks(self, value): self.crystalFieldFunction.setAttributeValue('NPeaks', value) @property def peaks(self): return self._peaks @property def background(self): return self._background @background.setter def background(self, value): """ Define the background function. Args: value: an instance of function.Background class or a list of instances in a multi-spectrum case """ from .function import Background from mantid.simpleapi import FunctionFactory if self._background is not None: raise ValueError('Background has been set already') if not isinstance(value, Background): raise TypeError('Expected a Background object, found %s' % str(value)) if not self._isMultiSpectrum: fun_str = value.toString() + ';' + str(self.function) self.function = FunctionFactory.createInitialized(fun_str) self._background = self._makeBackgroundObject(value) self._setPeaks() else: self.function.setAttributeValue("Background", value.toString()) self._background = [] for ispec in range(self.NumberOfSpectra): prefix = 'f%s.' % ispec self._background.append(self._makeBackgroundObject(value, prefix)) def _makeBackgroundObject(self, value, prefix=''): from .function import Background, Function if value.peak is not None and value.background is not None: peak = Function(self.function, prefix=prefix + 'f0.f0.') background = Function(self.function, prefix=prefix + 'f0.f1.') elif value.peak is not None: peak = Function(self.function, prefix=prefix + 'f0.') background = None elif value.background is not None: peak = None background = Function(self.function, prefix=prefix + 'f0.') return Background(peak=peak, background=background) @property def PhysicalProperty(self): return self._physprop @PhysicalProperty.setter def PhysicalProperty(self, value): from .function import PhysicalProperties vlist = value if islistlike(value) else [value] if all([isinstance(pp, PhysicalProperties) for pp in vlist]): nOldPP = len(self._physprop) if islistlike(self._physprop) else (0 if self._physprop is None else 1) self._physprop = value else: errmsg = 'PhysicalProperty input must be a PhysicalProperties' errmsg += ' instance or a list of such instances' raise ValueError(errmsg) # If a spectrum (temperature) is already defined, or multiple physical properties # given, redefine the CrystalFieldMultiSpectrum function. if not self.isPhysicalPropertyOnly or islistlike(self.PhysicalProperty): tt = self.Temperature if islistlike(self.Temperature) else [self.Temperature] ww = list(self.FWHM) if islistlike(self.FWHM) else [self.FWHM] # Last n-set of temperatures correspond to PhysicalProperties if nOldPP > 0: tt = tt[:-nOldPP] # Removes 'negative' temperature, which is a flag for no INS dataset tt = [val for val in tt if val > 0] pptt = [0 if val.Temperature is None else val.Temperature for val in vlist] self._remakeFunction(list(tt)+pptt) if len(tt) > 0 and len(pptt) > 0: ww += [0] * len(pptt) self.FWHM = ww ppids = [pp.TypeID for pp in vlist] self.function.setAttributeValue('PhysicalProperties', [0]*len(tt)+ppids) for attribs in [pp.getAttributes(i+len(tt)) for i, pp in enumerate(vlist)]: for item in attribs.items(): self.function.setAttributeValue(item[0], item[1]) @property def isPhysicalPropertyOnly(self): return (not islistlike(self.Temperature) and self.Temperature < 0 and self.PhysicalProperty is not None) def ties(self, **kwargs): """Set ties on the field parameters. @param kwargs: Ties as name=value pairs: name is a parameter name, the value is a tie string or a number. For example: tie(B20 = 0.1, IB23 = '2*B23') """ for tie in kwargs: self.crystalFieldFunction.tie(tie, str(kwargs[tie])) def constraints(self, *args): """ Set constraints for the field parameters. @param args: A list of constraints. For example: constraints('B00 > 0', '0.1 < B43 < 0.9') """ self.crystalFieldFunction.addConstraints(','.join(args)) def getEigenvalues(self): self._calcEigensystem() return self._eigenvalues def getEigenvectors(self): self._calcEigensystem() return self._eigenvectors def getHamiltonian(self): self._calcEigensystem() return self._hamiltonian def getPeakList(self, i=0): """Get the peak list for spectrum i as a numpy array""" self._calcPeaksList(i) peaks = np.array([self._peakList.column(0), self._peakList.column(1)]) return peaks def getSpectrum(self, i=0, workspace=None, ws_index=0): """ Get the i-th spectrum calculated with the current field and peak parameters. Alternatively can be called getSpectrum(workspace, ws_index). Spectrum index i is assumed zero. Examples: cf.getSpectrum() # Return the first spectrum calculated on a generated set of x-values. cf.getSpectrum(1, ws, 5) # Calculate the second spectrum using the x-values from the 6th spectrum # in workspace ws. cf.getSpectrum(ws) # Calculate the first spectrum using the x-values from the 1st spectrum # in workspace ws. cf.getSpectrum(ws, 3) # Calculate the first spectrum using the x-values from the 4th spectrum # in workspace ws. @param i: Index of a spectrum to get. @param workspace: A workspace to base on. If not given the x-values of the output spectrum will be generated. @param ws_index: An index of a spectrum from workspace to use. @return: A tuple of (x, y) arrays """ if self._dirty_spectra: self._spectra = {} self._dirty_spectra = False wksp = workspace # Allow to call getSpectrum with a workspace as the first argument. if not isinstance(i, int): if wksp is not None: if not isinstance(wksp, int): raise RuntimeError('Spectrum index is expected to be int. Got %s' % i.__class__.__name__) ws_index = wksp wksp = i i = 0 if (self.Temperature[i] if islistlike(self.Temperature) else self.Temperature) < 0: raise RuntimeError('You must first define a temperature for the spectrum') # Workspace is given, always calculate if wksp is None: xArray = None elif isinstance(wksp, list) or isinstance(wksp, np.ndarray): xArray = wksp else: return self._calcSpectrum(i, wksp, ws_index) if xArray is None: if i in self._spectra: return self._spectra[i] else: x_min, x_max = self.calc_xmin_xmax(i) xArray = np.linspace(x_min, x_max, self.default_spectrum_size) yArray = np.zeros_like(xArray) wksp = makeWorkspace(xArray, yArray) self._spectra[i] = self._calcSpectrum(i, wksp, 0) return self._spectra[i] def getHeatCapacity(self, workspace=None, ws_index=0): """ Get the heat cacpacity calculated with the current crystal field parameters Examples: cf.getHeatCapacity() # Returns the heat capacity from 1 < T < 300 K in 1 K steps cf.getHeatCapacity(ws) # Returns the heat capacity with temperatures given by ws. cf.getHeatCapacity(ws, ws_index) # Use the spectrum indicated by ws_index for x-values @param workspace: Either a Mantid workspace whose x-values will be used as the temperatures to calculate the heat capacity; or a list of numpy ndarray of temperatures. Temperatures are in Kelvin. @param ws_index: The index of a spectrum in workspace to use (default=0). """ from .function import PhysicalProperties return self._getPhysProp(PhysicalProperties('Cv'), workspace, ws_index) def getSusceptibility(self, *args, **kwargs): """ Get the magnetic susceptibility calculated with the current crystal field parameters. The susceptibility is calculated using Van Vleck's formula (2nd order perturbation theory) Examples: cf.getSusceptibility() # Returns the susceptibility || [001] for 1<T<300 K in 1 K steps cf.getSusceptibility(T) # Returns the susceptibility with temperatures given by T. cf.getSusceptibility(ws, 0) # Use x-axis of spectrum 0 of workspace ws as temperature cf.getSusceptibility(T, [1, 1, 1]) # Returns the susceptibility along [111]. cf.getSusceptibility(T, 'powder') # Returns the powder averaged susceptibility cf.getSusceptibility(T, 'cgs') # Returns the susceptibility || [001] in cgs normalisation cf.getSusceptibility(..., Inverse=True) # Calculates the inverse susceptibility instead cf.getSusceptibility(Temperature=ws, ws_index=0, Hdir=[1, 1, 0], Unit='SI', Inverse=True) @param Temperature: Either a Mantid workspace whose x-values will be used as the temperatures to calculate the heat capacity; or a list or numpy ndarray of temperatures. Temperatures are in Kelvin. @param ws_index: The index of a spectrum to use (default=0) if using a workspace for x. @param Hdir: The magnetic field direction to calculate the susceptibility along. Either a Cartesian vector with z along the quantisation axis of the CF parameters, or the string 'powder' (case insensitive) to get the powder averaged susceptibility default: [0, 0, 1] @param Unit: Any one of the strings 'bohr', 'SI' or 'cgs' (case insensitive) to indicate whether to output in atomic (bohr magneton/Tesla/ion), SI (m^3/mol) or cgs (cm^3/mol) units. default: 'cgs' @param Inverse: Whether to calculate the susceptibility (Inverse=False, default) or inverse susceptibility (Inverse=True). """ from .function import PhysicalProperties # Sets defaults / parses keyword arguments workspace = kwargs['Temperature'] if 'Temperature' in kwargs.keys() else None ws_index = kwargs['ws_index'] if 'ws_index' in kwargs.keys() else 0 # Parses argument list args = list(args) if len(args) > 0: workspace = args.pop(0) if 'mantid' in str(type(workspace)) and len(args) > 0: ws_index = args.pop(0) # _calcSpectrum updates parameters and susceptibility has a 'Lambda' parameter which other # CF functions don't have. This causes problems if you want to calculate another quantity after x, y = self._getPhysProp(PhysicalProperties('chi', *args, **kwargs), workspace, ws_index) return x, y def getMagneticMoment(self, *args, **kwargs): """ Get the magnetic moment calculated with the current crystal field parameters. The moment is calculated by adding a Zeeman term to the CF Hamiltonian and then diagonlising the result. This function calculates either M(H) [default] or M(T), but can only calculate a 1D function (e.g. not M(H,T) simultaneously). Examples: cf.getMagneticMoment() # Returns M(H) for H||[001] from 0 to 30 T in 0.1 T steps cf.getMagneticMoment(H) # Returns M(H) for H||[001] at specified values of H (in Tesla) cf.getMagneticMoment(ws, 0) # Use x-axis of spectrum 0 of ws as applied field magnitude. cf.getMagneticMoment(H, [1, 1, 1]) # Returns the magnetic moment along [111]. cf.getMagneticMoment(H, 'powder') # Returns the powder averaged M(H) cf.getMagneticMoment(H, 'cgs') # Returns the moment || [001] in cgs units (emu/mol) cf.getMagneticMoment(Temperature=T) # Returns M(T) for H=1T || [001] at specified T (in K) cf.getMagneticMoment(10, [1, 1, 0], Temperature=T) # Returns M(T) for H=10T || [110]. cf.getMagneticMoment(..., Inverse=True) # Calculates 1/M instead (keyword only) cf.getMagneticMoment(Hmag=ws, ws_index=0, Hdir=[1, 1, 0], Unit='SI', Temperature=T, Inverse=True) @param Hmag: The magnitude of the applied magnetic field in Tesla, specified either as a Mantid workspace whose x-values will be used; or a list or numpy ndarray of field points. If Temperature is specified as a list / array / workspace, Hmag must be scalar. (default: 0-30T in 0.1T steps, or 1T if temperature vector specified) @param Temperature: The temperature in Kelvin at which to calculate the moment. Temperature is a keyword argument only. Can be a list, ndarray or workspace. If Hmag is a list / array / workspace, Temperature must be scalar. (default=1K) @param ws_index: The index of a spectrum to use (default=0) if using a workspace for x. @param Hdir: The magnetic field direction to calculate the susceptibility along. Either a Cartesian vector with z along the quantisation axis of the CF parameters, or the string 'powder' (case insensitive) to get the powder averaged susceptibility default: [0, 0, 1] @param Unit: Any one of the strings 'bohr', 'SI' or 'cgs' (case insensitive) to indicate whether to output in atomic (bohr magneton/ion), SI (Am^2/mol) or cgs (emu/mol) units. default: 'bohr' @param Inverse: Whether to calculate the susceptibility (Inverse=False, default) or inverse susceptibility (Inverse=True). Inverse is a keyword argument only. """ from .function import PhysicalProperties # Sets defaults / parses keyword arguments workspace = None ws_index = kwargs['ws_index'] if 'ws_index' in kwargs.keys() else 0 hmag = kwargs['Hmag'] if 'Hmag' in kwargs.keys() else 1. temperature = kwargs['Temperature'] if 'Temperature' in kwargs.keys() else 1. # Checks whether to calculate M(H) or M(T) hmag_isscalar = (not islistlike(hmag) or len(hmag) == 1) hmag_isvector = (islistlike(hmag) and len(hmag) > 1) t_isscalar = (not islistlike(temperature) or len(temperature) == 1) t_isvector = (islistlike(temperature) and len(temperature) > 1) if hmag_isscalar and (t_isvector or 'mantid' in str(type(temperature))): typeid = 4 workspace = temperature kwargs['Hmag'] = hmag[0] if islistlike(hmag) else hmag else: typeid = 3 if t_isscalar and (hmag_isvector or 'mantid' in str(type(hmag))): workspace = hmag kwargs['Temperature'] = temperature[0] if islistlike(temperature) else temperature # Parses argument list args = list(args) if len(args) > 0: if typeid == 4: kwargs['Hmag'] = args.pop(0) else: workspace = args.pop(0) if 'mantid' in str(type(workspace)) and len(args) > 0: ws_index = args.pop(0) pptype = 'M(T)' if (typeid == 4) else 'M(H)' self._typeid = self._str2id(typeid) if isinstance(typeid, string_types) else int(typeid) return self._getPhysProp(PhysicalProperties(pptype, *args, **kwargs), workspace, ws_index) def plot(self, i=0, workspace=None, ws_index=0, name=None): """Plot a spectrum. Parameters are the same as in getSpectrum(...)""" from mantidplot import plotSpectrum from mantid.api import AlgorithmManager createWS = AlgorithmManager.createUnmanaged('CreateWorkspace') createWS.initialize() xArray, yArray = self.getSpectrum(i, workspace, ws_index) ws_name = name if name is not None else 'CrystalField_%s' % self.Ion if isinstance(i, int): if workspace is None: if i > 0: ws_name += '_%s' % i createWS.setProperty('DataX', xArray) createWS.setProperty('DataY', yArray) createWS.setProperty('OutputWorkspace', ws_name) createWS.execute() plot_window = self._plot_window[i] if i in self._plot_window else None self._plot_window[i] = plotSpectrum(ws_name, 0, window=plot_window, clearWindow=True) else: ws_name += '_%s' % workspace if i > 0: ws_name += '_%s' % i createWS.setProperty('DataX', xArray) createWS.setProperty('DataY', yArray) createWS.setProperty('OutputWorkspace', ws_name) createWS.execute() plotSpectrum(ws_name, 0) else: ws_name += '_%s' % i createWS.setProperty('DataX', xArray) createWS.setProperty('DataY', yArray) createWS.setProperty('OutputWorkspace', ws_name) createWS.execute() plotSpectrum(ws_name, 0) def update(self, func): """ Update values of the fitting parameters. @param func: A IFunction object containing new parameter values. """ self.function = func if self._background is not None: if isinstance(self._background, list): for background in self._background: background.update(func) else: self._background.update(func) self._setPeaks() def calc_xmin_xmax(self, i): """Calculate the x-range containing interesting features of a spectrum (for plotting) @param i: If an integer is given then calculate the x-range for the i-th spectrum. If None given get the range covering all the spectra. @return: Tuple (xmin, xmax) """ peaks = self.getPeakList(i) x_min = np.min(peaks[0]) x_max = np.max(peaks[0]) # dx probably should depend on peak widths deltaX = np.abs(x_max - x_min) * 0.1 if x_min < 0: x_min -= deltaX x_max += deltaX return x_min, x_max def __add__(self, other): if isinstance(other, CrystalFieldMulti): return other.__radd__(self) return CrystalFieldMulti(CrystalFieldSite(self, 1.0), other) def __mul__(self, factor): ffactor = float(factor) if ffactor == 0.0: msg = 'Intensity scaling factor for %s(%s) is set to zero ' % (self.Ion, self.Symmetry) warnings.warn(msg, SyntaxWarning) return CrystalFieldSite(self, ffactor) def __rmul__(self, factor): return self.__mul__(factor) def _getTemperature(self, i): """Get temperature value for i-th spectrum.""" if not self._isMultiSpectrum: if i != 0: raise RuntimeError('Cannot evaluate spectrum %s. Only 1 temperature is given.' % i) return float(self.Temperature) else: temperatures = self.Temperature nTemp = len(temperatures) if -nTemp <= i < nTemp: return float(temperatures[i]) else: raise RuntimeError('Cannot evaluate spectrum %s. Only %s temperatures are given.' % (i, nTemp)) def _getFWHM(self, i): """Get default FWHM value for i-th spectrum.""" if not self._isMultiSpectrum: # if i != 0 assume that value for all spectra return float(self.FWHM) else: fwhm = self.FWHM nFWHM = len(fwhm) if -nFWHM <= i < nFWHM: return float(fwhm[i]) else: raise RuntimeError('Cannot get FWHM for spectrum %s. Only %s FWHM are given.' % (i, nFWHM)) def _getIntensityScaling(self, i): """Get default intensity scaling value for i-th spectrum.""" if self._intensityScaling is None: raise RuntimeError('Default intensityScaling must be set.') if islistlike(self._intensityScaling): return self._intensityScaling[i] if len(self._intensityScaling) > 1 else self._intensityScaling[0] else: return self._intensityScaling def _getPeaksFunction(self, i): if isinstance(self.peaks, list): return self.peaks[i] return self.peaks def _getFieldParameters(self): """ Get the values of non-zero field parameters. Returns: a dict with name: value pairs. """ params = {} for name in self.field_parameter_names: value = self.crystalFieldFunction.getParameterValue(name) if value != 0.0: params[name] = value return params def _getFieldTies(self): import re ties = re.match('ties=\((.*?)\)', str(self.crystalFieldFunction)) return ties.group(1) if ties else '' def _getFieldConstraints(self): import re constraints = re.match('constraints=\((.*?)\)', str(self.crystalFieldFunction)) return constraints.group(1) if constraints else '' def _getPhysProp(self, ppobj, workspace, ws_index): """ Returns a physical properties calculation @param ppobj: a PhysicalProperties object indicating the physical property type and environment @param workspace: workspace or array/list of x-values. @param ws_index: An index of a spectrum in workspace to use. """ try: typeid = ppobj.TypeID except AttributeError: raise RuntimeError('Invalid PhysicalProperties object specified') defaultX = [np.linspace(1, 300, 300), np.linspace(1, 300, 300), np.linspace(0, 30, 300), np.linspace(0, 30, 300)] funstr = self.makePhysicalPropertiesFunction(ppobj) if workspace is None: xArray = defaultX[typeid - 1] elif isinstance(workspace, list) or isinstance(workspace, np.ndarray): xArray = workspace else: return self._calcSpectrum(funstr, workspace, ws_index) yArray = np.zeros_like(xArray) wksp = makeWorkspace(xArray, yArray) return self._calcSpectrum(funstr, wksp, ws_index) def _calcEigensystem(self): """Calculate the eigensystem: energies and wavefunctions. Also store them and the hamiltonian. Protected method. Shouldn't be called directly by user code. """ if self._dirty_eigensystem: import CrystalField.energies as energies nre = self.ion_nre_map[self.Ion] self._eigenvalues, self._eigenvectors, self._hamiltonian = \ energies.energies(nre, **self._getFieldParameters()) self._dirty_eigensystem = False def _calcPeaksList(self, i): """Calculate a peak list for spectrum i""" if self._dirty_peaks: from mantid.api import AlgorithmManager alg = AlgorithmManager.createUnmanaged('EvaluateFunction') alg.initialize() alg.setChild(True) alg.setProperty('Function', self.makePeaksFunction(i)) del alg['InputWorkspace'] alg.setProperty('OutputWorkspace', 'dummy') alg.execute() self._peakList = alg.getProperty('OutputWorkspace').value def _calcSpectrum(self, i, workspace, ws_index, funstr=None): """Calculate i-th spectrum. @param i: Index of a spectrum or function string @param workspace: A workspace used to evaluate the spectrum function. @param ws_index: An index of a spectrum in workspace to use. """ from mantid.api import AlgorithmManager alg = AlgorithmManager.createUnmanaged('EvaluateFunction') alg.initialize() alg.setChild(True) alg.setProperty('Function', i if isinstance(i, string_types) else self.makeSpectrumFunction(i)) alg.setProperty("InputWorkspace", workspace) alg.setProperty('WorkspaceIndex', ws_index) alg.setProperty('OutputWorkspace', 'dummy') alg.execute() out = alg.getProperty('OutputWorkspace').value # Create copies of the x and y because `out` goes out of scope when this method returns # and x and y get deallocated return np.array(out.readX(0)), np.array(out.readY(1)) def isMultiSpectrum(self): return self._isMultiSpectrum class CrystalFieldSite(object): """ A helper class for the multi-site algebra. It is a result of the '*' operation between a CrystalField and a number. Multiplication sets the abundance for the site and which the returned object holds. """ def __init__(self, crystalField, abundance): self.crystalField = crystalField self.abundance = abundance def __add__(self, other): if isinstance(other, CrystalField): return CrystalFieldMulti(self, CrystalFieldSite(other, 1)) elif isinstance(other, CrystalFieldSite): return CrystalFieldMulti(self, other) elif isinstance(other, CrystalFieldMulti): return other.__radd__(self) raise TypeError('Unsupported operand type(s) for +: CrystalFieldSite and %s' % other.__class__.__name__) class CrystalFieldMulti(object): """CrystalFieldMulti represents crystal field of multiple ions.""" def __init__(self, *args): self.sites = [] self.abundances = [] for arg in args: if isinstance(arg, CrystalField): self.sites.append(arg) self.abundances.append(1.0) elif isinstance(arg, CrystalFieldSite): self.sites.append(arg.crystalField) self.abundances.append(arg.abundance) else: raise RuntimeError('Cannot include an object of type %s into a CrystalFieldMulti' % type(arg)) self._ties = {} def makeSpectrumFunction(self): fun = ';'.join([a.makeSpectrumFunction() for a in self.sites]) fun += self._makeIntensityScalingTies() ties = self.getTies() if len(ties) > 0: fun += ';ties=(%s)' % ties return 'composite=CompositeFunction,NumDeriv=1;' + fun def makePhysicalPropertiesFunction(self): # Handles relative intensities. Scaling factors here a fixed attributes not # variable parameters and we require the sum to be unity. factors = np.array(self.abundances) sum_factors = np.sum(factors) factstr = [',ScaleFactor=%s' % (str(factors[i] / sum_factors)) for i in range(len(self.sites))] fun = ';'.join([a.makePhysicalPropertiesFunction()+factstr[i] for a,i in enumerate(self.sites)]) ties = self.getTies() if len(ties) > 0: fun += ';ties=(%s)' % ties return fun def makeMultiSpectrumFunction(self): fun = ';'.join([a.makeMultiSpectrumFunction() for a in self.sites]) fun += self._makeIntensityScalingTiesMulti() ties = self.getTies() if len(ties) > 0: fun += ';ties=(%s)' % ties return 'composite=CompositeFunction,NumDeriv=1;' + fun def ties(self, **kwargs): """Set ties on the parameters.""" for tie in kwargs: self._ties[tie] = kwargs[tie] def getTies(self): ties = ['%s=%s' % item for item in self._ties.items()] return ','.join(ties) def getSpectrum(self, i=0, workspace=None, ws_index=0): tt = [] for site in self.sites: tt = tt + (list(site.Temperature) if islistlike(site.Temperature) else [site.Temperature]) if any([val < 0 for val in tt]): raise RuntimeError('You must first define a temperature for the spectrum') largest_abundance= max(self.abundances) if workspace is not None: xArray, yArray = self.sites[0].getSpectrum(i, workspace, ws_index) yArray *= self.abundances[0] / largest_abundance ia = 1 for arg in self.sites[1:]: _, yyArray = arg.getSpectrum(i, workspace, ws_index) yArray += yyArray * self.abundances[ia] / largest_abundance ia += 1 return xArray, yArray x_min = 0.0 x_max = 0.0 for arg in self.sites: xmin, xmax = arg.calc_xmin_xmax(i) if xmin < x_min: x_min = xmin if xmax > x_max: x_max = xmax xArray = np.linspace(x_min, x_max, CrystalField.default_spectrum_size) _, yArray = self.sites[0].getSpectrum(i, xArray, ws_index) yArray *= self.abundances[0] / largest_abundance ia = 1 for arg in self.sites[1:]: _, yyArray = arg.getSpectrum(i, xArray, ws_index) yArray += yyArray * self.abundances[ia] / largest_abundance ia += 1 return xArray, yArray def update(self, func): nFunc = func.nFunctions() assert nFunc == len(self.sites) for i in range(nFunc): self.sites[i].update(func[i]) def update_multi(self, func): nFunc = func.nFunctions() assert nFunc == len(self.sites) for i in range(nFunc): self.sites[i].update_multi(func[i]) def _makeIntensityScalingTies(self): """ Make a tie string that ties IntensityScaling's of the sites according to their abundances. """ n_sites = len(self.sites) if n_sites < 2: return '' factors = np.array(self.abundances) i_largest = np.argmax(factors) largest_factor = factors[i_largest] tie_template = 'f%s.IntensityScaling=%s*' + 'f%s.IntensityScaling' % i_largest ties = [] for i in range(n_sites): if i != i_largest: ties.append(tie_template % (i, factors[i] / largest_factor)) s = ';ties=(%s)' % ','.join(ties) return s def _makeIntensityScalingTiesMulti(self): """ Make a tie string that ties IntensityScaling's of the sites according to their abundances. """ n_sites = len(self.sites) if n_sites < 2: return '' factors = np.array(self.abundances) i_largest = np.argmax(factors) largest_factor = factors[i_largest] tie_template = 'f{1}.IntensityScaling{0}={2}*f%s.IntensityScaling{0}' % i_largest ties = [] n_spectra = self.sites[0].NumberOfSpectra for spec in range(n_spectra): for i in range(n_sites): if i != i_largest: ties.append(tie_template.format(spec, i, factors[i] / largest_factor)) s = ';ties=(%s)' % ','.join(ties) return s @property def isPhysicalPropertyOnly(self): return all([a.isPhysicalPropertyOnly for a in self.sites]) @property def PhysicalProperty(self): return [a.PhysicalProperty for a in self.sites] @PhysicalProperty.setter def PhysicalProperty(self, value): for a in self.sites: a.PhysicalProperty = value @property def NumberOfSpectra(self): """ Returns the number of expected workspaces """ num_spec = [] for site in self.sites: num_spec.append(site.NumberOfSpectra) if len(set(num_spec)) > 1: raise ValueError('Number of spectra for each site not consistent with each other') return num_spec[0] @property def Temperature(self): tt = [] for site in self.sites: tt.append([val for val in (site.Temperature if islistlike(site.Temperature) else [site.Temperature])]) if len(set([tuple(val) for val in tt])) > 1: raise ValueError('Temperatures of spectra for each site not consistent with each other') return tt[0] @Temperature.setter def Temperature(self, value): for site in self.sites: site.Temperature = value def __add__(self, other): if isinstance(other, CrystalFieldMulti): cfm = CrystalFieldMulti() cfm.sites += self.sites + other.sites cfm.abundances += self.abundances + other.abundances return cfm elif isinstance(other, CrystalField): cfm = CrystalFieldMulti() cfm.sites += self.sites + [other] cfm.abundances += self.abundances + [1] return cfm elif isinstance(other, CrystalFieldSite): cfm = CrystalFieldMulti() cfm.sites += self.sites + [other.crystalField] cfm.abundances += self.abundances + [other.abundance] return cfm else: raise TypeError('Cannot add %s to CrystalFieldMulti' % other.__class__.__name__) def __radd__(self, other): if isinstance(other, CrystalFieldMulti): cfm = CrystalFieldMulti() cfm.sites += other.sites + self.sites cfm.abundances += other.abundances + self.abundances return cfm elif isinstance(other, CrystalField): cfm = CrystalFieldMulti() cfm.sites += [other] + self.sites cfm.abundances += [1] + self.abundances return cfm elif isinstance(other, CrystalFieldSite): cfm = CrystalFieldMulti() cfm.sites += [other.crystalField] + self.sites cfm.abundances += [other.abundance] + self.abundances return cfm else: raise TypeError('Cannot add %s to CrystalFieldMulti' % other.__class__.__name__) def __len__(self): return len(self.sites) def __getitem__(self, item): return self.sites[item] #pylint: disable=too-few-public-methods class CrystalFieldFit(object): """ Object that controls fitting. """ def __init__(self, Model=None, Temperature=None, FWHM=None, InputWorkspace=None, **kwargs): self.model = Model if Temperature is not None: self.model.Temperature = Temperature if FWHM is not None: self.model.FWHM = FWHM self._input_workspace = InputWorkspace self._output_workspace_base_name = 'fit' self._fit_properties = kwargs self._function = None self._estimated_parameters = None def fit(self): """ Run Fit algorithm. Update function parameters. """ self.check_consistency() if isinstance(self._input_workspace, list): return self._fit_multi() else: return self._fit_single() def monte_carlo(self, **kwargs): fix_all_peaks = self.model.FixAllPeaks self.model.FixAllPeaks = True if isinstance(self._input_workspace, list): self._monte_carlo_multi(**kwargs) else: self._monte_carlo_single(**kwargs) self.model.FixAllPeaks = fix_all_peaks def estimate_parameters(self, EnergySplitting, Parameters, **kwargs): from CrystalField.normalisation import split2range from mantid.api import mtd self.check_consistency() ranges = split2range(Ion=self.model.Ion, EnergySplitting=EnergySplitting, Parameters=Parameters) constraints = [('%s<%s<%s' % (-bound, parName, bound)) for parName, bound in ranges.items()] self.model.constraints(*constraints) if 'Type' not in kwargs or kwargs['Type'] == 'Monte Carlo': if 'OutputWorkspace' in kwargs and kwargs['OutputWorkspace'].strip() != '': output_workspace = kwargs['OutputWorkspace'] else: output_workspace = 'estimated_parameters' kwargs['OutputWorkspace'] = output_workspace else: output_workspace = None self.monte_carlo(**kwargs) if output_workspace is not None: self._estimated_parameters = mtd[output_workspace] def get_number_estimates(self): """ Get a number of parameter sets estimated with self.estimate_parameters(). """ if self._estimated_parameters is None: return 0 else: return self._estimated_parameters.columnCount() - 1 def select_estimated_parameters(self, index): ne = self.get_number_estimates() if ne == 0: raise RuntimeError('There are no estimated parameters.') if index >= ne: raise RuntimeError('There are only %s sets of estimated parameters, requested set #%s' % (ne, index)) for row in range(self._estimated_parameters.rowCount()): name = self._estimated_parameters.cell(row, 0) value = self._estimated_parameters.cell(row, index) self.model[name] = value if self._function is not None: self._function.setParameter(name, value) def _monte_carlo_single(self, **kwargs): """ Call EstimateFitParameters algorithm in a single spectrum case. Args: **kwargs: Properties of the algorithm. """ from mantid.api import AlgorithmManager fun = self.model.makeSpectrumFunction() if 'CrystalFieldMultiSpectrum' in fun: # Hack to ensure that 'PhysicalProperties' attribute is first # otherwise it won't set up other attributes properly fun = re.sub(r'(name=.*?,)(.*?)(PhysicalProperties=\(.*?\),)',r'\1\3\2', fun) alg = AlgorithmManager.createUnmanaged('EstimateFitParameters') alg.initialize() alg.setProperty('Function', fun) alg.setProperty('InputWorkspace', self._input_workspace) for param in kwargs: alg.setProperty(param, kwargs[param]) alg.execute() function = alg.getProperty('Function').value self.model.update(function) self._function = function def _monte_carlo_multi(self, **kwargs): """ Call EstimateFitParameters algorithm in a multi-spectrum case. Args: **kwargs: Properties of the algorithm. """ from mantid.api import AlgorithmManager fun = self.model.makeMultiSpectrumFunction() if 'CrystalFieldMultiSpectrum' in fun: fun = re.sub(r'(name=.*?,)(.*?)(PhysicalProperties=\(.*?\),)',r'\1\3\2', fun) alg = AlgorithmManager.createUnmanaged('EstimateFitParameters') alg.initialize() alg.setProperty('Function', fun) alg.setProperty('InputWorkspace', self._input_workspace[0]) i = 1 for workspace in self._input_workspace[1:]: alg.setProperty('InputWorkspace_%s' % i, workspace) i += 1 for param in kwargs: alg.setProperty(param, kwargs[param]) alg.execute() function = alg.getProperty('Function').value self.model.update(function) self._function = function def _fit_single(self): """ Fit when the model has a single spectrum. """ from mantid.api import AlgorithmManager if self._function is None: if self.model.isPhysicalPropertyOnly: fun = self.model.makePhysicalPropertiesFunction() else: fun = self.model.makeSpectrumFunction() else: fun = str(self._function) if 'CrystalFieldMultiSpectrum' in fun: fun = re.sub(r'(name=.*?,)(.*?)(PhysicalProperties=\(.*?\),)',r'\1\3\2', fun) alg = AlgorithmManager.createUnmanaged('Fit') alg.initialize() alg.setProperty('Function', fun) alg.setProperty('InputWorkspace', self._input_workspace) alg.setProperty('Output', 'fit') self._set_fit_properties(alg) alg.execute() function = alg.getProperty('Function').value self.model.update(function) self.model.chi2 = alg.getProperty('OutputChi2overDoF').value def _fit_multi(self): """ Fit when the model has multiple spectra. """ from mantid.api import AlgorithmManager fun = self.model.makeMultiSpectrumFunction() if 'CrystalFieldMultiSpectrum' in fun: fun = re.sub(r'(name=.*?,)(.*?)(PhysicalProperties=\(.*?\),)',r'\1\3\2', fun) alg = AlgorithmManager.createUnmanaged('Fit') alg.initialize() alg.setProperty('Function', fun) alg.setProperty('InputWorkspace', self._input_workspace[0]) i = 1 for workspace in self._input_workspace[1:]: alg.setProperty('InputWorkspace_%s' % i, workspace) i += 1 alg.setProperty('Output', 'fit') self._set_fit_properties(alg) alg.execute() function = alg.getProperty('Function').value self.model.update(function) self.model.chi2 = alg.getProperty('OutputChi2overDoF').value def _set_fit_properties(self, alg): for prop in self._fit_properties.items(): alg.setProperty(*prop) def check_consistency(self): """ Checks that list input variables are consistent """ num_ws = self.model.NumberOfSpectra errmsg = 'Number of input workspaces not consistent with model' if islistlike(self._input_workspace): if num_ws != len(self._input_workspace): raise ValueError(errmsg) # If single element list, force use of _fit_single() if len(self._input_workspace) == 1: self._input_workspace = self._input_workspace[0] elif num_ws != 1: raise ValueError(errmsg) if not self.model.isPhysicalPropertyOnly: tt = self.model.Temperature if any([val < 0 for val in (tt if islistlike(tt) else [tt])]): raise RuntimeError('You must first define a temperature for the spectrum')
dymkowsk/mantid
scripts/Inelastic/CrystalField/fitting.py
Python
gpl-3.0
63,447
[ "CRYSTAL", "Gaussian" ]
a33f41a502e8a6d1d46b299f6c58449a3c88f2b784be9984c18fce0fd057efa6
""" This is the Job Repository which stores and manipulates DIRAC job metadata in CFG format """ from diraccfg import CFG from DIRAC import gLogger, S_OK, S_ERROR import os import time import tempfile import shutil class JobRepository: def __init__(self, repository=None): self.location = repository if not self.location: if "HOME" in os.environ: self.location = "%s/.dirac.repo.rep" % os.environ["HOME"] else: self.location = "%s/.dirac.repo.rep" % os.getcwd() self.repo = CFG() if os.path.exists(self.location): self.repo.loadFromFile(self.location) if not self.repo.existsKey("Jobs"): self.repo.createNewSection("Jobs") else: self.repo.createNewSection("Jobs") self.OK = True written = self._writeRepository(self.location) if not written: self.OK = False def isOK(self): return self.OK def readRepository(self): return S_OK(self.repo.getAsDict("Jobs")) def writeRepository(self, alternativePath=None): destination = self.location if alternativePath: destination = alternativePath written = self._writeRepository(destination) if not written: return S_ERROR("Failed to write repository") return S_OK(destination) def resetRepository(self, jobIDs=[]): if not jobIDs: jobs = self.readRepository()["Value"] jobIDs = list(jobs) paramDict = {"State": "Submitted", "Retrieved": 0, "OutputData": 0} for jobID in jobIDs: self._writeJob(jobID, paramDict, True) self._writeRepository(self.location) return S_OK() def _writeRepository(self, path): handle, tmpName = tempfile.mkstemp() written = self.repo.writeToFile(tmpName) os.close(handle) if not written: if os.path.exists(tmpName): os.remove(tmpName) return written if os.path.exists(path): gLogger.debug("Replacing %s" % path) try: shutil.move(tmpName, path) return True except Exception as x: gLogger.error("Failed to overwrite repository.", x) gLogger.info("If your repository is corrupted a backup can be found %s" % tmpName) return False def appendToRepository(self, repoLocation): if not os.path.exists(repoLocation): gLogger.error("Secondary repository does not exist", repoLocation) return S_ERROR("Secondary repository does not exist") self.repo = CFG().loadFromFile(repoLocation).mergeWith(self.repo) self._writeRepository(self.location) return S_OK() def addJob(self, jobID, state="Submitted", retrieved=0, outputData=0, update=False): paramDict = {"State": state, "Time": self._getTime(), "Retrieved": int(retrieved), "OutputData": outputData} self._writeJob(jobID, paramDict, update) self._writeRepository(self.location) return S_OK(jobID) def updateJob(self, jobID, paramDict): if self._existsJob(jobID): paramDict["Time"] = self._getTime() self._writeJob(jobID, paramDict, True) self._writeRepository(self.location) return S_OK() def updateJobs(self, jobDict): for jobID, paramDict in jobDict.items(): if self._existsJob(jobID): paramDict["Time"] = self._getTime() self._writeJob(jobID, paramDict, True) self._writeRepository(self.location) return S_OK() def _getTime(self): runtime = time.ctime() return runtime.replace(" ", "_") def _writeJob(self, jobID, paramDict, update): jobID = str(jobID) jobExists = self._existsJob(jobID) if jobExists and (not update): gLogger.warn("Job exists and not overwriting") return S_ERROR("Job exists and not overwriting") if not jobExists: self.repo.createNewSection("Jobs/%s" % jobID) for key, value in paramDict.items(): self.repo.setOption("Jobs/%s/%s" % (jobID, key), value) return S_OK() def removeJob(self, jobID): res = self.repo["Jobs"].deleteKey(str(jobID)) # pylint: disable=no-member if res: self._writeRepository(self.location) return S_OK() def existsJob(self, jobID): return S_OK(self._existsJob(jobID)) def _existsJob(self, jobID): return self.repo.isSection("Jobs/%s" % jobID) def getLocation(self): return S_OK(self.location) def getSize(self): return S_OK(len(self.repo.getAsDict("Jobs")))
DIRACGrid/DIRAC
src/DIRAC/Interfaces/API/JobRepository.py
Python
gpl-3.0
4,790
[ "DIRAC" ]
5a42b83d4f34fce095616f5f1b983222163b3b77462eee2a70ca628ac2155919
from __future__ import division, print_function import xgboost as xgb # from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor import sklearn.preprocessing as prep from sklearn import cluster # from sklearn import cross_validation as cv # from sklearn.feature_selection import RFE, RFECV # from sklearn.metrics import regression as metrics # import pandas as pd import numpy as np # import itertools from scipy.integrate import cumtrapz from matplotlib import pyplot as plt import seaborn as sns from matplotlib import rcParams sns.set_context('paper', font_scale=2, rc={"lines.linewidth": 2}) sns.set_style('ticks') rcParams['figure.figsize'] = 8, 6 def plot_the_integral(y, x, label='', color=None): sort_idx = np.argsort(x) xx = np.array(x)[sort_idx] yy = np.array(y)[sort_idx] iy = cumtrapz(yy, xx) iy -= iy[xx[1:] < 4].min() if color: pl = plt.plot(xx[1:], iy, color=color, label=label, alpha=0.6, lw=3) else: pl = plt.plot(xx[1:], iy, label=label, lw=3) return iy, pl def get_train_test_idx(X, n_interp, do_clustering=True, do_birch=True): if do_clustering: Xscaled = prep.StandardScaler().fit_transform(X) if do_birch: threshold_birch = 1. n_clusters = int(len(Xscaled) / n_interp) while True: try: clus = cluster.Birch(threshold=threshold_birch, n_clusters=n_clusters) clus.fit(Xscaled) if len(np.unique(clus.labels_)) == n_clusters: break else: threshold_birch *=0.5 except: threshold_birch *=0.5 else: n_clusters = int(len(Xscaled) / n_interp) clus = cluster.KMeans(n_clusters=n_clusters) clus.fit(Xscaled) clus_indices = [np.where(clus.labels_ == i)[0] for i in np.unique(clus.labels_)] idx_train = [] for label in np.unique(clus.labels_): cluster_center = Xscaled[clus_indices[label]].mean(axis=0) dists = ((Xscaled - cluster_center)**2).sum(axis=1)**0.5 idx_train.append(np.argmin(dists)) else: idx_train = list(np.arange(0, len(X), n_interp)) idx_test = set(np.arange(0, len(X))).difference(idx_train) idx_test = list(idx_test) return idx_train, idx_test def load_data(rtype): if rtype == 'crystal': data = np.loadtxt('db-c0.35-clusters-md-crack-300K-open-12-withf-gamma-phd.csv', delimiter=',') _, y_TS = np.loadtxt('db-cryst.csv', delimiter=',', skiprows=2).T elif rtype == 'amorph': data = np.loadtxt('db-ashift_70.0-clusters-md-crack-300K-open-12-chunk1-withf-gamma-phd.csv', delimiter=',') _, y_TS = np.loadtxt('db-amorph.csv', delimiter=',', skiprows=2).T n_data = min([len(data), len(y_TS)]) data = data[:n_data] y_TS = y_TS[:n_data] colvar = data[:, 0].copy() X = data[:, :-1].copy() y = data[:,-1].copy() X = np.hstack([X, y_TS[:,None]]) data = None return X, y, y_TS, colvar X, y, y_TS, colvar = load_data('amorph') n_data = len(y) n_interp = 50 # X = prep.StandardScaler().fit_transform(X) # X = prep.RobustScaler().fit_transform(X) # poly = prep.PolynomialFeatures(degree=2, interaction_only=False).fit_transform(X) # X = np.hstack([X, poly]) # X = prep.StandardScaler().fit_transform(X) # from sklearn import decomposition # X = decomposition.MiniBatchSparsePCA().fit_transform(X) # X = prep.RobustScaler().fit_transform(X) params = { 'eta': 0.05, 'colsample_bytree': 1, 'gamma' : 0.01, 'max_depth': 4, 'min_child_weight': 1, 'n_estimators': 500, 'subsample': 0.6, 'silent': True, 'early_stopping_rounds': 100, 'objective': 'reg:linear', 'lambda': 1., 'n_jobs': -1, 'eval_metric': "mae", 'seed': 42} idx_train, idx_test = get_train_test_idx(X, n_interp, do_clustering=True, do_birch=False) X_train = X[idx_train] X_test = X[idx_test] y_train = y[idx_train] y_test = y[idx_test] if True: dtrain = xgb.DMatrix(np.array(X_train), label=y_train) model = xgb.train(params, dtrain, params['n_estimators']) y_ML = model.predict(xgb.DMatrix(X)) else: from sklearn.gaussian_process import GaussianProcess model = GaussianProcess(nugget=0.03) model.fit(X_train, y_train) y_ML = model.predict(X) colors = sns.color_palette(palette='Set2', n_colors=3) iy, _ = plot_the_integral(y, colvar, label='DFT', color=colors[0]) y_DFT_interp = np.interp(colvar, colvar[::n_interp], y[::n_interp]) iy_DFTinterp, _ = plot_the_integral(y_DFT_interp, colvar, label='DFT interpolation', color=colors[1]) # iy_TS, _ = plot_the_integral(y_TS, colvar, label='TS', color=colors[1]) iy_ML, _ = plot_the_integral(y_ML, colvar, label='ML', color=colors[2]) plt.legend() plt.xlim(colvar.min(), colvar.max()) # plt.ylim(-1, 1.7) plt.ylim(-3, 1) plt.scatter(colvar[idx_train], [plt.ylim()[0]]*len(idx_train), marker='|', s=500, c=colors[0], alpha=1, linewidths=2) plt.xlabel("Reaction coordinate [A]") plt.ylabel("Free energy [eV]") sns.despine() plt.tight_layout() from sklearn.metrics.regression import mean_absolute_error as MAE print("MAE: %.3f" % MAE(iy, iy_ML)) import sys sys.exit(0) plt.plot(colvar[1:], iy, '-', label='1', color='black') for i, n_interp in enumerate([5,10,15,20,25]): y_DFT_interp = np.interp(colvar, colvar[::n_interp], y[::n_interp]) iy_DFTinterp, _ = plot_the_integral(y_DFT_interp, colvar, label='%d' % n_interp, color=colors[i]) def get_train_test_idx2(X, n_train): Xscaled = prep.StandardScaler().fit_transform(X) n_clusters = n_train # np.max([n_train, len(X)]) clus = cluster.KMeans(n_clusters=n_clusters) clus.fit(Xscaled) clus_indices = [np.where(clus.labels_ == i)[0] for i in np.unique(clus.labels_)] idx_train = [] for label in np.unique(clus.labels_): cluster_center = Xscaled[clus_indices[label]].mean(axis=0) dists = ((Xscaled - cluster_center)**2).sum(axis=1)**0.5 idx_train.append(np.argmin(dists)) idx_test = set(np.arange(0, len(X))).difference(idx_train) idx_test = list(idx_test) return idx_train, idx_test import pandas as pd from sklearn.metrics.regression import mean_absolute_error as MAE boo = xgb.XGBRegressor(n_estimators = 500, gamma = 0.01, max_depth = 4, learning_rate = 0.05, subsample = 0.6) results = [] res_errors = [] for n_train in np.logspace(1, np.log10(0.8 * len(X)), 20).astype('int'): errors = [] y_preds = [] for i in range(10): idx_train, idx_test = get_train_test_idx2(X, n_train) X_train = X[idx_train] X_test = X[idx_test] y_train = y[idx_train] y_test = y[idx_test] boo.fit(X_train, y_train) y_pred = boo.predict(X_test) error = MAE(y_pred, y_test) print("MAE = %.5f" % error) y_preds.append(y_pred) errors.append(error) r = [n_interp, error] results.append(r) for a, b in zip(y_pred, y_test): e = np.abs(a - b) res_errors.append([n_train, e]) df = pd.DataFrame(data=np.array(res_errors), columns=['n_train', 'error']) df['n_train'] = df['n_train'].astype('int') grp = df.groupby('n_train') r = grp.mean() # plt.scatter(r.index, r.error) res = grp['error'].agg([np.mean, np.std]) sns.set_style('ticks') rcParams['figure.figsize'] = 8, 6 plt.plot(r.index, r.error, 'o-', lw=3, label='ML', color='black') plt.plot(r.index, [MAE(y,y_TS)] * len(r.index), '--', lw=3, label='TS', color='black') plt.xscale('log') plt.ylim(0,0.40) plt.xlim(10,1000) plt.legend(loc=3) plt.xlabel("Training set size") plt.ylabel(r"MAE [$eV/\AA{}$]") sns.despine() plt.tight_layout() # r = [n_interp, np.mean(errors), np.std(errors)] # results.append(r)
marcocaccin/MLTI
step2_ML/ml_learnability.py
Python
gpl-3.0
8,004
[ "CRYSTAL" ]
1b770f9941e2c6025a82afc38a1c4ea9f8226f34c26999e0a9905868ac4b1b43
# Sample module in the public domain. Feel free to use this as a template # for your modules (and you can remove this header and take complete credit # and liability) # # Contact: Brian Carrier [carrier <at> sleuthkit [dot] org] # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # Sample report module for Autopsy. Use as a starting point for new modules. # # Search for TODO for the things that you need to change # See http://sleuthkit.org/autopsy/docs/api-docs/4.6.0/index.html for documentation import os from java.lang import System from java.util.logging import Level from org.sleuthkit.autopsy.casemodule import Case from org.sleuthkit.autopsy.coreutils import Logger from org.sleuthkit.autopsy.report import GeneralReportModuleAdapter from org.sleuthkit.autopsy.report.ReportProgressPanel import ReportStatus # TODO: Rename the class to something more specific class SampleGeneralReportModule(GeneralReportModuleAdapter): # TODO: Rename this. Will be shown to users when making a report moduleName = "Sample Report Module" _logger = None def log(self, level, msg): if _logger == None: _logger = Logger.getLogger(self.moduleName) self._logger.logp(level, self.__class__.__name__, inspect.stack()[1][3], msg) def getName(self): return self.moduleName # TODO: Give it a useful description def getDescription(self): return "A sample Jython report module" # TODO: Update this to reflect where the report file will be written to def getRelativeFilePath(self): return "sampleReport.txt" # TODO: Update this method to make a report # The 'baseReportDir' object being passed in is a string with the directory that reports are being stored in. Report should go into baseReportDir + getRelativeFilePath(). # The 'progressBar' object is of type ReportProgressPanel. # See: http://sleuthkit.org/autopsy/docs/api-docs/4.6.0/classorg_1_1sleuthkit_1_1autopsy_1_1report_1_1_report_progress_panel.html def generateReport(self, baseReportDir, progressBar): # For an example, we write a file with the number of files created in the past 2 weeks # Configure progress bar for 2 tasks progressBar.setIndeterminate(False) progressBar.start() progressBar.setMaximumProgress(2) # Find epoch time of when 2 weeks ago was currentTime = System.currentTimeMillis() / 1000 minTime = currentTime - (14 * 24 * 60 * 60) # (days * hours * minutes * seconds) # Query the database for files that meet our criteria sleuthkitCase = Case.getCurrentCase().getSleuthkitCase() files = sleuthkitCase.findAllFilesWhere("crtime > %d" % minTime) fileCount = 0 for file in files: fileCount += 1 # Could do something else here and write it to HTML, CSV, etc. # Increment since we are done with step #1 progressBar.increment() # Write the count to the report file. fileName = os.path.join(baseReportDir, self.getRelativeFilePath()) report = open(fileName, 'w') report.write("file count = %d" % fileCount) report.close() # Add the report to the Case, so it is shown in the tree Case.getCurrentCase().addReport(fileName, self.moduleName, "File Count Report") progressBar.increment() # Call this with ERROR if report was not generated progressBar.complete(ReportStatus.COMPLETE)
millmanorama/autopsy
pythonExamples/reportmodule.py
Python
apache-2.0
4,633
[ "Brian" ]
517772009698e309e95a00a27afb434c1f8bc24613109cfa66e6802508ab5271
""" Sandboxed expression parser. Copyright 2017-2018 Leon Helwerda Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Use Python 3 division from __future__ import division import ast class Expression_Parser(ast.NodeVisitor): """ Transformer that safely parses an expression, disallowing any complicated functions or control structures (inline if..else is allowed though). """ # Boolean operators # The AST nodes may have multiple ops and right comparators, but we # evaluate each op individually. _boolean_ops = { ast.And: lambda left, right: left and right, ast.Or: lambda left, right: left or right } # Binary operators _binary_ops = { ast.Add: lambda left, right: left + right, ast.Sub: lambda left, right: left - right, ast.Mult: lambda left, right: left * right, ast.Div: lambda left, right: left / right, ast.Mod: lambda left, right: left % right, ast.Pow: lambda left, right: left ** right, ast.LShift: lambda left, right: left << right, ast.RShift: lambda left, right: left >> right, ast.BitOr: lambda left, right: left | right, ast.BitXor: lambda left, right: left ^ right, ast.BitAnd: lambda left, right: left & right, ast.FloorDiv: lambda left, right: left // right } # Unary operators _unary_ops = { ast.Invert: lambda operand: ~operand, ast.Not: lambda operand: not operand, ast.UAdd: lambda operand: +operand, ast.USub: lambda operand: -operand } # Comparison operators # The AST nodes may have multiple ops and right comparators, but we # evaluate each op individually. _compare_ops = { ast.Eq: lambda left, right: left == right, ast.NotEq: lambda left, right: left != right, ast.Lt: lambda left, right: left < right, ast.LtE: lambda left, right: left <= right, ast.Gt: lambda left, right: left > right, ast.GtE: lambda left, right: left >= right, ast.Is: lambda left, right: left is right, ast.IsNot: lambda left, right: left is not right, ast.In: lambda left, right: left in right, ast.NotIn: lambda left, right: left not in right } # Predefined variable names _variable_names = { 'True': True, 'False': False, 'None': None } # Predefined functions _function_names = { 'int': int, 'float': float, 'bool': bool } def __init__(self, variables=None, functions=None, assignment=False): self._variables = None self.variables = variables if functions is None: self._functions = {} else: self._functions = functions self._assignment = False self.assignment = assignment self._used_variables = set() self._modified_variables = {} def parse(self, expression, filename='<expression>'): """ Parse a string `expression` and return its result. """ self._used_variables = set() self._modified_variables = {} try: return self.visit(ast.parse(expression)) except SyntaxError as error: error.filename = filename error.text = expression raise error except Exception as error: error_type = error.__class__.__name__ if len(error.args) > 2: line_col = error.args[1:] else: line_col = (1, 0) error = SyntaxError('{}: {}'.format(error_type, error.args[0]), (filename,) + line_col + (expression,)) raise error @property def variables(self): """ Retrieve the variables that exist in the scope of the parser. This property returns a copy of the dictionary. """ return self._variables.copy() @variables.setter def variables(self, variables): """ Set a new variable scope for the expression parser. If built-in keyword names `True`, `False` or `None` are used, then this property raises a `NameError`. """ if variables is None: variables = {} else: variables = variables.copy() variable_names = set(variables.keys()) constant_names = set(self._variable_names.keys()) forbidden_variables = variable_names.intersection(constant_names) if forbidden_variables: keyword = 'keyword' if len(forbidden_variables) == 1 else 'keywords' forbidden = ', '.join(forbidden_variables) raise NameError('Cannot override {} {}'.format(keyword, forbidden)) self._variables = variables @property def assignment(self): """ Retrieve whether assignments are accepted by the parser. """ return self._assignment @assignment.setter def assignment(self, value): """ Enable or disable parsing assignments. """ self._assignment = bool(value) @property def used_variables(self): """ Retrieve the names of the variables that were evaluated in the most recent call to `parse`. If `parse` failed with an exception, then this set may be incomplete. """ return self._used_variables @property def modified_variables(self): """ Retrieve the variables that were set or modified in the most recent call to `parse`. Since only one expression is allowed, this dictionary contains at most one element. An augmented expression such as `+=` is used, then the variable is only in this dictionary if the variable is in the scope. If `parse` failed with any other exception, then this dictionary may be incomplete. If the expression parser is set to disallow assignments, then the dictionary is always empty. This property returns a copy of the dictionary. """ return self._modified_variables.copy() def generic_visit(self, node): """ Visitor for nodes that do not have a custom visitor. This visitor denies any nodes that may not be part of the expression. """ raise SyntaxError('Node {} not allowed'.format(ast.dump(node)), ('', node.lineno, node.col_offset, '')) def visit_Module(self, node): """ Visit the root module node. """ if len(node.body) != 1: if len(node.body) > 1: lineno = node.body[1].lineno col_offset = node.body[1].col_offset else: lineno = 1 col_offset = 0 raise SyntaxError('Exactly one expression must be provided', ('', lineno, col_offset, '')) return self.visit(node.body[0]) def visit_Expr(self, node): """ Visit an expression node. """ return self.visit(node.value) def visit_BoolOp(self, node): """ Visit a boolean expression node. """ op = type(node.op) func = self._boolean_ops[op] result = func(self.visit(node.values[0]), self.visit(node.values[1])) for value in node.values[2:]: result = func(result, self.visit(value)) return result def visit_BinOp(self, node): """ Visit a binary expression node. """ op = type(node.op) func = self._binary_ops[op] return func(self.visit(node.left), self.visit(node.right)) def visit_UnaryOp(self, node): """ Visit a unary expression node. """ op = type(node.op) func = self._unary_ops[op] return func(self.visit(node.operand)) def visit_IfExp(self, node): """ Visit an inline if..else expression node. """ return self.visit(node.body) if self.visit(node.test) else self.visit(node.orelse) def visit_Compare(self, node): """ Visit a comparison expression node. """ result = self.visit(node.left) for operator, comparator in zip(node.ops, node.comparators): op = type(operator) func = self._compare_ops[op] result = func(result, self.visit(comparator)) return result def visit_Call(self, node): """ Visit a function call node. """ name = node.func.id if name in self._functions: func = self._functions[name] elif name in self._function_names: func = self._function_names[name] else: raise NameError("Function '{}' is not defined".format(name), node.lineno, node.col_offset) args = [self.visit(arg) for arg in node.args] keywords = dict([self.visit(keyword) for keyword in node.keywords]) # Python 2.7 starred arguments if hasattr(node, 'starargs') and hasattr(node, 'kwargs'): if node.starargs is not None or node.kwargs is not None: raise SyntaxError('Star arguments are not supported', ('', node.lineno, node.col_offset, '')) return func(*args, **keywords) def visit_Assign(self, node): """ Visit an assignment node. """ if not self.assignment: raise SyntaxError('Assignments are not allowed in this expression', ('', node.lineno, node.col_offset, '')) if len(node.targets) != 1: raise SyntaxError('Multiple-target assignments are not supported', ('', node.lineno, node.col_offset, '')) if not isinstance(node.targets[0], ast.Name): raise SyntaxError('Assignment target must be a variable name', ('', node.lineno, node.col_offset, '')) name = node.targets[0].id self._modified_variables[name] = self.visit(node.value) def visit_AugAssign(self, node): """ Visit an augmented assignment node. """ if not self.assignment: raise SyntaxError('Assignments are not allowed in this expression', ('', node.lineno, node.col_offset, '')) if not isinstance(node.target, ast.Name): raise SyntaxError('Assignment target must be a variable name', ('', node.lineno, node.col_offset, '')) name = node.target.id if name not in self._variables: raise NameError("Assignment name '{}' is not defined".format(name), node.lineno, node.col_offset) op = type(node.op) func = self._binary_ops[op] self._modified_variables[name] = func(self._variables[name], self.visit(node.value)) def visit_Starred(self, node): """ Visit a starred function keyword argument node. """ # pylint: disable=no-self-use raise SyntaxError('Star arguments are not supported', ('', node.lineno, node.col_offset, '')) def visit_keyword(self, node): """ Visit a function keyword argument node. """ if node.arg is None: raise SyntaxError('Star arguments are not supported', ('', node.lineno, node.col_offset, '')) return (node.arg, self.visit(node.value)) def visit_Num(self, node): """ Visit a literal number node. """ # pylint: disable=no-self-use return node.n def visit_Name(self, node): """ Visit a named variable node. """ if node.id in self._variables: self._used_variables.add(node.id) return self._variables[node.id] if node.id in self._variable_names: return self._variable_names[node.id] raise NameError("Name '{}' is not defined".format(node.id), node.lineno, node.col_offset) def visit_NameConstant(self, node): """ Visit a named constant singleton node (Python 3). """ # pylint: disable=no-self-use return node.value
lhelwerd/expression-parser
expression/parser.py
Python
apache-2.0
12,920
[ "VisIt" ]
f11b2ef197c5f47247a1a94eb605a617de4fb372af7a51875b0cd0131f343527
import environ from celery.schedules import crontab root_dir = environ.Path(__file__) - 3 project_dir = root_dir.path('shopify') env = environ.Env() env.read_env('.env') DJANGO_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', ) THIRD_PARTY_APPS = ( ) LOCAL_APPS = ( 'shopify.notification.apps.NotificationConfig', 'shopify.product.apps.ProductConfig', 'shopify.user.apps.UserConfig', 'shopify.webhook.apps.WebhookConfig', ) INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] DEBUG = env.bool('DJANGO_DEBUG', default=False) SECRET_KEY = env('DJANGO_SECRET_KEY') FIXTURE_DIRS = ( project_dir('fixtures'), ) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_SUBJECT_PREFIX = '' DEFAULT_FROM_EMAIL = 'help@corban.edu' ADMINS = ( ('Jason Bittel', 'jbittel@corban.edu'), ('Brian Elliott', 'belliott@corban.edu'), ) MANAGERS = ADMINS DATABASES = { 'default': env.db('DATABASE_URL', default='postgres://localhost/shopify'), } CACHES = { 'default': env.cache('CACHE_URL', default='locmemcache://'), } TIME_ZONE = 'America/Los_Angeles' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = False USE_L10N = False USE_TZ = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ project_dir('templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_ROOT = root_dir('staticfiles') STATIC_URL = env.str('DJANGO_STATIC_URL') STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) MEDIA_ROOT = root_dir('media') MEDIA_URL = '/media/' ROOT_URLCONF = 'config.urls' WSGI_APPLICATION = 'config.wsgi.application' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'standard': { 'format': '%(asctime)s [%(process)d] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'formatter': 'standard', 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'celery': { 'handlers': ['console'], 'level': 'INFO', }, 'django': { 'handlers': ['console'], 'level': 'INFO', }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', }, 'shopify': { 'handlers': ['console'], 'level': 'INFO', }, } } TEST_RUNNER = 'django.test.runner.DiscoverRunner' ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS') CELERY_BROKER_URL = env.str('CELERY_BROKER_URL') CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_DEFAULT_QUEUE = 'shopify' CELERY_WORKER_DISABLE_RATE_LIMITS = True CELERY_WORKER_HIJACK_ROOT_LOGGER = False CELERY_TASK_IGNORE_RESULT = True CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_BEAT_SCHEDULE = { 'email_journal_vouchers_import': { 'task': 'shopify.product.tasks.email_journal_vouchers_import', # Generate import file at 21:00 every night. This matches # the Shopify transaction cutoff at midnight EST. 'schedule': crontab(minute=0, hour=21), } } SHOPIFY_SHARED_SECRET = env('SHOPIFY_SHARED_SECRET') SHOPIFY_API_KEY = env('SHOPIFY_API_KEY') SHOPIFY_PASSWORD = env('SHOPIFY_PASSWORD') SHOPIFY_SHARED_SECRET = env('SHOPIFY_SHARED_SECRET') SHOPIFY_HOSTNAME = env('SHOPIFY_HOSTNAME') SHOPIFY_CASH_ACCOUNT_NUMBER = env('SHOPIFY_CASH_ACCOUNT_NUMBER')
CorbanU/corban-shopify
config/settings/base.py
Python
bsd-3-clause
4,845
[ "Brian" ]
1eecb0dfc03fe512b3c0eda7bcf9de598ca01bd2cf41b4133e62dc38d36347d8
#!/bin/env python """ create and put 'ReplicateAndRegister' request """ __RCSID__ = "$Id: $" import os from DIRAC.Core.Base import Script Script.setUsageMessage( '\n'.join( [ __doc__, 'Usage:', ' %s [option|cfgfile] requestName LFNs targetSE [targetSE ...]' % Script.scriptName, 'Arguments:', ' requestName: a request name', ' LFNs: single LFN or file with LFNs', ' targetSE: target SE' ] ) ) def getLFNList( LFNs ): """ get list of LFNs """ lfnList = [] if os.path.exists( LFNs ): for line in open( LFNs ).readlines(): lfnList.append( line.strip() ) else: lfnList = [ LFNs ] return list( set ( lfnList ) ) # # execution if __name__ == "__main__": from DIRAC.Core.Base.Script import parseCommandLine parseCommandLine() import DIRAC from DIRAC import gLogger args = Script.getPositionalArgs() requestName = None LFNs = None targetSEs = None if not len( args ) < 3: Script.showHelp() DIRAC.exit( 0 ) else: requestName = args[0] LFNs = args[1] targetSEs = list( set( [ targetSE.strip() for targetSE in args[2:] ] ) ) lfnList = getLFNList( LFNs ) gLogger.info( "will create request '%s' with 'ReplicateAndRegister' "\ "operation using %s lfns and %s target SEs" % ( requestName, len( lfnList ), len( targetSEs ) ) ) from DIRAC.RequestManagementSystem.Client.Request import Request from DIRAC.RequestManagementSystem.Client.Operation import Operation from DIRAC.RequestManagementSystem.Client.File import File from DIRAC.RequestManagementSystem.Client.ReqClient import ReqClient from DIRAC.Resources.Catalog.FileCatalog import FileCatalog metaDatas = FileCatalog().getFileMetadata( lfnList ) if not metaDatas["OK"]: gLogger.error( "unable to read metadata for lfns: %s" % metaDatas["Message"] ) DIRAC.exit( -1 ) metaDatas = metaDatas["Value"] for failedLFN, reason in metaDatas["Failed"].items(): gLogger.error( "skipping %s: %s" % ( failedLFN, reason ) ) lfnList = [ lfn for lfn in lfnList if lfn not in metaDatas["Failed"] ] if not lfnList: gLogger.error( "LFN list is empty!!!" ) DIRAC.exit( -1 ) if len( lfnList ) > Operation.MAX_FILES: gLogger.error( "too many LFNs, max number of files per operation is %s" % Operation.MAX_FILES ) DIRAC.exit( -1 ) request = Request() request.RequestName = requestName replicateAndRegister = Operation() replicateAndRegister.Type = "ReplicateAndRegister" replicateAndRegister.TargetSE = ",".join( targetSEs ) for lfn in lfnList: metaDict = metaDatas["Successful"][lfn] opFile = File() opFile.LFN = lfn opFile.Size = metaDict["Size"] if "Checksum" in metaDict: # # should check checksum type, now assuming Adler32 (metaDict["ChecksumType"] = 'AD' opFile.Checksum = metaDict["Checksum"] opFile.ChecksumType = "ADLER32" replicateAndRegister.addFile( opFile ) reqClient = ReqClient() putRequest = reqClient.putRequest( request ) if not putRequest["OK"]: gLogger.error( "unable to put request '%s': %s" % ( requestName, putRequest["Message"] ) ) DIRAC.exit( -1 ) gLogger.always( "Request '%s' has been put to ReqDB for execution." ) gLogger.always( "You can monitor its status using command: 'dirac-rms-show-request %s'" % requestName ) DIRAC.exit( 0 )
avedaee/DIRAC
DataManagementSystem/scripts/dirac-dms-replicate-and-register-request.py
Python
gpl-3.0
3,550
[ "DIRAC" ]
c685ca827c69b78dfd37962f9738da3c1786ae2e641c1fbf54b60e157f182129
import copy import os from visitor import * from stringstream import * class Rewriter(NodeVisitor): """ Class for rewriting of the original AST. Includes: 1. the initial small rewritings, 2. transformation into our representation, 3. transforming from our representation to C-executable code, 4. creating our representation of the device kernel code, 5. creating a C-executable kernel code, 6. Creating the host code (boilerplate code) """ def __init__(self): # List of loop indices self.index = list() # dict of the upper limit of the loop indices self.UpperLimit = dict() # dict of the lower limit of the loop indices self.LowerLimit = dict() # The local work group size self.Local = dict() self.Local['name'] = 'LSIZE' self.Local['size'] = ['64'] # The number of dimensions of each array self.NumDims = dict() # The Ids of arrays, or pointers self.ArrayIds = set() # The indices that appear in the subscript of each array self.IndexInSubscript = dict() # All Ids that are not arrays, or pointers self.NonArrayIds = set() # Ids that we remove due to parallelization of loops self.RemovedIds = set() # The mapping from the indices that we parallelize # to their function returning their thread id in the kernel self.IndexToThreadId = dict() self.IndexToLocalId = dict() self.IndexToLocalVar = dict() # The indices that we parallelize self.GridIndices = list() # The OpenCl kernel before anything self.Kernel = None # The "inside" of the OpenCl kernel after parallelization self.InsideKernel = None # The name of the kernel, i.e. the FuncName + Kernel self.KernelName = None # The mapping from the array ids to a list of # the names of their dimensions self.ArrayIdToDimName = dict() # ArrayRef inside a loop in the kernel # Mapping from Id to AST ArrayRef node self.LoopArray = dict() # The argument list in our IR self.DevArgList = list() # The name and type of the kernel function. self.DevFuncTypeId = None # The name of the kernel function. self.DevFuncId = None # The device names of the pointers in the boilerplate code self.DevId = dict() # The host names of the pointers in the boilerplate code self.HstId = dict() # The types of the arguments for the kernel self.Type = dict() # The name of the variable denoting the memory size self.Mem = dict() # Dimension of the parallelization self.ParDim = None # VarName of the global/local worksize array. self.Worksize = dict() # The dimension that the index indexes self.IdxToDim = dict() # Whether an array is read, write or both self.ReadWrite = dict() # List of arrays that are write only self.WriteOnly = list() # List of arrays that are read only self.ReadOnly = list() # dict of indices to loops in the kernel self.Loops = dict() # Contains the loop indices for each subscript self.SubIdx = dict() # Contains a list for each arrayref of what loop indices # appear in the subscript. self.Subscript = dict() # The same as above but names are saved as strings instead # of Id(strings) self.SubscriptNoId = dict() # Decides whether we read back data from GPU self.NoReadBack = False # A list of calls to the transpose function which we perform # after data was read back from the GPU. self.WriteTranspose = list() # A mapping from array references to the loops they appear in. self.RefToLoop = dict() # List of arguments for the kernel ## self.KernelArgs = list() ######################################################## # Datastructures used when performing transformations # ######################################################## # Holds the sub-AST in AllocateBuffers # that we add transposition to. self.Transposition = None # Holds the sub-AST in AllocateBuffers # that we add constant memory pointer initializations to. self.ConstantMemory = None # Holds the sub-AST in AllocateBuffers # where we set the defines for the kernel. self.Define = None # Dict containing the name and type for each kernel argument # set in SetArguments self.KernelArgs = dict() # Holds information about which names have been swapped # in a transposition self.NameSwap = dict() # Holds information about which subscripts have been swapped # in a transposition self.SubSwap = dict() # Holds information about which indices have been swapped # in a transposition self.IdxSwap = dict() # Holds information about which dimensions have been swapped # in a transposition self.DimSwap = dict() # Holds additional global variables such as pointers that we add # when we to perform transformations self.GlobalVars = dict() # Holds additional cl_mem variables that we add # when we to perform Constant Memory transformation self.ConstantMem = dict() # Name swap in relation to [local memory] self.LocalSwap = dict() # Extra things that we add to ids [local memory] self.Add = dict() # Holds includes for the kernel self.Includes = list() # Holds the ast for a function that returns the kernelstring self.KernelStringStream = list() # Holds a list of which loops we will unroll self.UnrollLoops = list() # True is SetDefine were called. self.DefinesAreMade = False # List of what kernel arguments changes self.Change = list() self.IfThenElse = None def initOriginal(self, ast): loops = ForLoops() loops.visit(ast) forLoopAst = loops.ast loopIndices = LoopIndices() loopIndices.visit(forLoopAst) self.index = loopIndices.index self.UpperLimit = loopIndices.end self.LowerLimit = loopIndices.start norm = Norm(self.index) norm.visit(forLoopAst) arrays = Arrays(self.index) arrays.visit(ast) for n in arrays.numIndices: if arrays.numIndices[n] == 2: arrays.numSubscripts[n] = 2 elif arrays.numIndices[n] > 2: arrays.numSubscripts[n] = 1 self.NumDims = arrays.numSubscripts self.IndexInSubscript = arrays.indexIds typeIds = TypeIds() typeIds.visit(loops.ast) typeIds2 = TypeIds() typeIds2.visit(ast) outsideTypeIds = typeIds2.ids - typeIds.ids for n in typeIds.ids: typeIds2.dictIds.pop(n) self.Type = typeIds2.dictIds ids = Ids() ids.visit(ast) print ids.ids print arrays.ids print typeIds.ids # print "typeIds.ids ", typeIds.ids # print "arrays.ids ", arrays.ids # print "ids.ids ", ids.ids otherIds = ids.ids - arrays.ids - typeIds.ids self.ArrayIds = arrays.ids - typeIds.ids self.NonArrayIds = otherIds def initNewRepr(self, ast, dev = 'GPU'): ## findIncludes = FindIncludes() ## findIncludes.visit(ast) ## self.Includes = findIncludes.includes perfectForLoop = PerfectForLoop() perfectForLoop.visit(ast) if self.ParDim is None: self.ParDim = perfectForLoop.depth if self.ParDim == 1: self.Local['size'] = ['256'] if dev == 'CPU': self.Local['size'] = ['16'] else: self.Local['size'] = ['16','16'] if dev == 'CPU': self.Local['size'] = ['4','4'] innerbody = perfectForLoop.inner if perfectForLoop.depth == 2 and self.ParDim == 1: innerbody = perfectForLoop.outer firstLoop = ForLoops() firstLoop.visit(innerbody.compound) loopIndices = LoopIndices() if firstLoop.ast is not None: loopIndices.visit(innerbody.compound) self.Loops = loopIndices.Loops self.InsideKernel = firstLoop.ast arrays = Arrays(self.index) arrays.visit(innerbody.compound) self.NumDims = arrays.numSubscripts self.LoopArrays = arrays.LoopArrays initIds = InitIds() initIds.visit(perfectForLoop.ast.init) gridIds = list() idMap = dict() localMap = dict() localVarMap = dict() firstIdx = initIds.index[0] idMap[firstIdx] = 'get_global_id(0)' localMap[firstIdx] = 'get_local_id(0)' localVarMap[firstIdx] = 'l' + firstIdx self.ReverseIdx = dict() self.ReverseIdx[0] = 1 gridIds.extend(initIds.index) kernel = perfectForLoop.ast.compound self.ReverseIdx[1] = 0 if self.ParDim == 2: initIds = InitIds() initIds.visit(kernel.statements[0].init) kernel = kernel.statements[0].compound secondIdx = initIds.index[0] idMap[secondIdx] = 'get_global_id(1)' localMap[secondIdx] = 'get_local_id(1)' localVarMap[secondIdx] = 'l' + secondIdx gridIds.extend(initIds.index) (idMap[gridIds[0]], idMap[gridIds[1]]) = (idMap[gridIds[1]], idMap[gridIds[0]]) (localMap[gridIds[0]], localMap[gridIds[1]]) = (localMap[gridIds[1]], localMap[gridIds[0]]) ## (localVarMap[gridIds[0]], localVarMap[gridIds[1]]) = (localVarMap[gridIds[1]], localVarMap[gridIds[0]]) self.IndexToLocalId = localMap self.IndexToLocalVar = localVarMap self.IndexToThreadId = idMap self.GridIndices = gridIds self.Kernel = kernel for i, n in enumerate(reversed(self.GridIndices)): self.IdxToDim[i] = n findDim = FindDim(self.NumDims) findDim.visit(ast) self.ArrayIdToDimName = findDim.dimNames self.RemovedIds = set(self.UpperLimit[i] for i in self.GridIndices) idsStillInKernel = Ids() idsStillInKernel.visit(self.Kernel) self.RemovedIds = self.RemovedIds - idsStillInKernel.ids otherIds = self.ArrayIds.union(self.NonArrayIds) findDeviceArgs = FindDeviceArgs(otherIds) findDeviceArgs.visit(ast) self.DevArgList = findDeviceArgs.arglist findFunction = FindFunction() findFunction.visit(ast) self.DevFuncTypeId = findFunction.typeid self.DevFuncId = self.DevFuncTypeId.name.name for n in self.ArrayIds: self.DevId[n] = 'dev_ptr' + n self.HstId[n] = 'hst_ptr' + n self.Mem[n] = 'hst_ptr' + n + '_mem_size' ## for n in self.DevArgList: ## name = n.name.name ## type = n.type[-2:] ## self.Type[name] = type for n in self.ArrayIdToDimName: for m in self.ArrayIdToDimName[n]: self.Type[m] = ['size_t'] kernelName = self.DevFuncTypeId.name.name self.KernelName = kernelName + 'Kernel' self.Worksize['local'] = kernelName + '_local_worksize' self.Worksize['global'] = kernelName + '_global_worksize' self.Worksize['offset'] = kernelName + '_global_offset' findReadWrite = FindReadWrite(self.ArrayIds) findReadWrite.visit(ast) self.ReadWrite = findReadWrite.ReadWrite for n in self.ReadWrite: pset = self.ReadWrite[n] if len(pset) == 1: if 'write' in pset: self.WriteOnly.append(n) else: self.ReadOnly.append(n) argIds = self.NonArrayIds.union(self.ArrayIds) - self.RemovedIds print self.NonArrayIds # print self.KernelArgs, "KA Rewr be" # print self.ArrayIdToDimName, "rewriter" print argIds for n in argIds: tmplist = [n] try: if self.NumDims[n] == 2: tmplist.append(self.ArrayIdToDimName[n][0]) except KeyError: pass # print tmplist, " tmp ", n for m in tmplist: self.KernelArgs[m] = self.Type[m] # print self.KernelArgs, "KA Rewrie" self.Transposition = GroupCompound([Comment('// Transposition')]) self.ConstantMemory = GroupCompound([Comment('// Constant Memory')]) self.Define = GroupCompound([Comment('// Defines for the kernel')]) arrays = Arrays(self.index) arrays.visit(ast) self.Subscript = arrays.Subscript self.SubIdx = arrays.SubIdx self.SubscriptNoId = copy.deepcopy(self.Subscript) for n in self.SubscriptNoId.values(): for m in n: for i,k in enumerate(m): try: m[i] = k.name except AttributeError: try: m[i] = k.value except AttributeError: m[i] = 'unknown' refToLoop = RefToLoop(self.GridIndices) refToLoop.visit(ast) self.RefToLoop = refToLoop.RefToLoop def DataStructures(self): print "self.index " , self.index print "self.UpperLimit " , self.UpperLimit print "self.LowerLimit " , self.LowerLimit print "self.NumDims " , self.NumDims print "self.ArrayIds " , self.ArrayIds print "self.IndexInSubscript " , self.IndexInSubscript print "self.NonArrayIds " , self.NonArrayIds print "self.RemovedIds " , self.RemovedIds print "self.IndexToThreadId " , self.IndexToThreadId print "self.IndexToLocalId " , self.IndexToLocalId print "self.IndexToLocalVar " , self.IndexToLocalVar print "self.ReverseIdx ", self.ReverseIdx print "self.GridIndices " , self.GridIndices ## print "self.Kernel " , self.Kernel print "self.ArrayIdToDimName " , self.ArrayIdToDimName print "self.DevArgList " , self.DevArgList print "self.DevFuncTypeId " , self.DevFuncTypeId print "self.DevId " , self.DevId print "self.HstId " , self.HstId print "self.Type " , self.Type print "self.Mem " , self.Mem print "self.ParDim " , self.ParDim print "self.Worksize " , self.Worksize print "self.IdxToDim " , self.IdxToDim print "self.WriteOnly " , self.WriteOnly print "self.ReadOnly " , self.ReadOnly print "self.Subscript " , self.Subscript print "self.SubscriptNoId " , self.SubscriptNoId print "TRANSFORMATIONS" print "self.Transposition " , self.Transposition print "self.ConstantMemory " , self.ConstantMemory print "self.KernelArgs " , self.KernelArgs print "self.NameSwap " , self.NameSwap print "self.LocalSwap " , self.LocalSwap print "self.LoopArrays " , self.LoopArrays print "self.Add ", self.Add print "self.GlobalVars ", self.GlobalVars print "self.ConstantMem " , self.ConstantMem print "self.Loops " , self.Loops print "self.RefToLoop ", self.RefToLoop def rewrite(self, ast, functionname = 'FunctionName', changeAST = True): """ Rewrites a few things in the AST to increase the abstraction level. """ typeid = TypeId(['void'], Id(functionname),ast.coord) arraysArg = list() for arrayid in self.ArrayIds: arraysArg.append(TypeId(self.Type[arrayid], Id(arrayid,ast.coord),ast.coord)) for iarg in xrange(self.NumDims[arrayid]): arraysArg.append(TypeId(['size_t'], Id('hst_ptr'+arrayid+'_dim'+str(iarg+1),ast.coord),ast.coord)) for arrayid in self.NonArrayIds: arraysArg.append(TypeId(self.Type[arrayid], Id(arrayid,ast.coord),ast.coord)) arglist = ArgList([] + arraysArg) while isinstance(ast.ext[0], Include): include = ast.ext.pop(0) self.Includes.append(include) while not isinstance(ast.ext[0], ForLoop): ast.ext.pop(0) compound = Compound(ast.ext) if changeAST: ast.ext = list() ast.ext.append(FuncDecl(typeid,arglist,compound)) def rewriteToSequentialC(self, ast): loops = ForLoops() loops.visit(ast) forLoopAst = loops.ast loopIndices = LoopIndices() loopIndices.visit(forLoopAst) self.index = loopIndices.index arrays2 = Arrays(self.index) arrays2.visit(ast) findDim = FindDim(arrays2.numIndices) findDim.visit(ast) rewriteArrayRef = RewriteArrayRef(self.NumDims, self.ArrayIdToDimName, self) rewriteArrayRef.visit(ast) def rewriteToDeviceCTemp(self, ast, changeAST = True): findDeviceArgs = FindDeviceArgs(self.NonArrayIds) findDeviceArgs.visit(ast) findFunction = FindFunction() findFunction.visit(ast) # add OpenCL keywords to indicate the kernel function. findFunction.typeid.type.insert(0, '__kernel') exchangeIndices = ExchangeIndices(self.IndexToThreadId) exchangeIndices.visit(self.Kernel) newast = FuncDecl(findFunction.typeid, ArgList(findDeviceArgs.arglist,ast.coord), self.Kernel, ast.coord) if changeAST: ast.ext = list() ast.ext.append(newast) def InSourceKernel(self, ast, cond, filename, kernelstringname): self.rewriteToDeviceCRelease(ast) ssprint = SSGenerator() newast = FileAST([]) ssprint.createKernelStringStream(ast, newast, self.UnrollLoops, kernelstringname, filename = filename) self.KernelStringStream.append({'name' : kernelstringname, \ 'ast' : newast, 'cond' : cond}) def rewriteToDeviceCRelease(self, ast): arglist = list() argIds = self.NonArrayIds.union(self.ArrayIds) - self.RemovedIds # The list of arguments for the kernel dictTypeHostPtrs = copy.deepcopy(self.Type) for n in self.ArrayIds: dictTypeHostPtrs[self.ArrayIdToDimName[n][0]] = ['size_t'] for n in self.KernelArgs: type = copy.deepcopy(self.KernelArgs[n]) if type[0] == 'size_t': type[0] = 'unsigned' if len(type) == 2: type.insert(0, '__global') arglist.append(TypeId(type, Id(n))) exchangeArrayId = ExchangeArrayId(self.LocalSwap) for n in self.LoopArrays.values(): for m in n: exchangeArrayId.visit(m) ## for n in self.Add: ## addToIds = AddToId(n, self.Add[n]) ## addToIds.visit(self.InsideKernel.compound) MyKernel = copy.deepcopy(self.Kernel) rewriteArrayRef = RewriteArrayRef(self.NumDims, self.ArrayIdToDimName, self) rewriteArrayRef.visit(MyKernel) arrays = self.ArrayIds exchangeIndices = ExchangeId(self.IndexToThreadId) exchangeIndices.visit(MyKernel) exchangeTypes = ExchangeTypes() exchangeTypes.visit(MyKernel) typeid = copy.deepcopy(self.DevFuncTypeId) typeid.type.insert(0, '__kernel') ext = copy.deepcopy(self.Includes) newast = FileAST(ext) for n in arglist: if len(n.type) == 3: if n.type[1] == 'double': ext.insert(0, Compound([Id("#pragma OPENCL EXTENSION cl_khr_fp64: enable")])) break else: if n.type[0] == 'double': ext.insert(0,Compound([Id("#pragma OPENCL EXTENSION cl_khr_fp64: enable")])) break ext.append(FuncDecl(typeid, ArgList(arglist), MyKernel)) ast.ext = list() ## ast.ext.append(Id('#define LSIZE ' + str(self.Local['size']))) ast.ext.append(newast) def constantMemory2(self, arrDict): arrNames = arrDict.keys() # find out if we need to split into global and constant memory space split = dict() for name in arrNames: if len(arrDict[name]) != len(self.Subscript[name]): # Every aref to name is not put in constant memory # so we split. split[name] = True else: split[name] = False # Add new constant pointer ptrname = 'Constant' + ''.join(arrNames) hst_ptrname = 'hst_ptr' + ptrname dev_ptrname = 'dev_ptr' + ptrname typeset = set() for name in arrNames: typeset.add(self.Type[name][0]) if len(typeset) > 1: print "Conflicting types in constant memory transformation... Aborting" return ptrtype = [typeset.pop(), '*'] # Add the ptr to central data structures self.Type[ptrname] = ptrtype self.DevId[ptrname] = dev_ptrname self.HstId[ptrname] = hst_ptrname self.Mem[ptrname] = self.HstId[ptrname]+'_mem_size' # Add the ptr to be a kernel argument self.KernelArgs[ptrname] = ['__constant'] + ptrtype self.GlobalVars[ptrname] = '' self.ConstantMem[ptrname] = arrNames # Delete original arguments if we split for n in split: if not split[n]: self.KernelArgs.pop(n) self.DevId.pop(n) # Add pointer allocation to AllocateBuffers lval = Id(self.HstId[ptrname]) rval = Id('new ' + self.Type[ptrname][0] + '['\ + self.Mem[ptrname] + ']') self.ConstantMemory.statements.append(Assignment(lval, rval)) # find the loop the we need to add to the allocation section # Do it by looking at the loop indices in the subscripts ids = [] for s in arrDict: # Just look at only the first subscript at the moment array = arrDict[s] subs = self.LoopArrays[s] try: sub = subs[array[0]] except IndexError: print array[0] print subs print "ConstantMemory: Wrong index... Are you using zero indexing for the beginning of the loop?" return arrays = Arrays(self.Loops.keys()) arrays.visit(sub) ids = set(arrays.SubIdx[s][0]) - set([None]) - set(self.GridIndices) break if len(ids) > 1: print "Constant memory only supported for one loop at the moment" return # Add the loop to the allocation code forloop = copy.deepcopy(self.Loops[iter(ids).next()]) newcomp = [] forcomp = [] groupComp = GroupCompound(newcomp) forloop.compound = Compound(forcomp) loopcount = forloop.init.lval.name.name # Add the for loop from the kernel newcomp.append(forloop) # find dimension of the constant ptr constantdim = sum([ (len(arrDict[m])) for m in arrDict]) # add constant writes writes = [] for i in xrange(constantdim): writes.append(( [BinOp(BinOp(Id(str(constantdim)), '*', \ Id(loopcount)), '+', Id(str(i)))])) # for rewriting the ARefs that we copy rewriteArrayRef = RewriteArrayRef(self.NumDims, self.ArrayIdToDimName, self) # add global loadings count = 0 for n in arrDict: for i in arrDict[n]: aref = copy.deepcopy(self.LoopArrays[n][i]) name = aref.name.name rewriteArrayRef.visit(aref) aref.name.name = self.HstId[name] lval = ArrayRef(Id(self.HstId[ptrname]), writes[count]) assign = Assignment(lval, aref) forcomp.append(assign) count += 1 # Must now replace global arefs with constant arefs count = 0 for n in arrDict: for i in (arrDict[n]): aref_new = writes[count] aref_old = self.LoopArrays[n][i] # Copying the internal data of the two arefs aref_old.name.name = ptrname aref_old.subscript = aref_new count += 1 self.ConstantMemory.statements.append(groupComp) def generateBoilerplateCode(self, ast): dictNToNumScripts = self.NumDims dictNToDimNames = self.ArrayIdToDimName idMap = self.IndexToThreadId gridIds = self.GridIndices NonArrayIds = copy.deepcopy(self.NonArrayIds) otherIds = self.ArrayIds.union(self.NonArrayIds) - self.RemovedIds fileAST = FileAST([]) fileAST.ext.append(Id('#include \"../../../utils/StartUtil.cpp\"')) fileAST.ext.append(Id('using namespace std;')) ## fileAST.ext.append(Id('#define LSIZE ' + str(self.Local['size'][0]))) kernelId = Id(self.KernelName) kernelTypeid = TypeId(['cl_kernel'], kernelId, 0) fileAST.ext.append(kernelTypeid) ## fileAST.show() listDevBuffers = [] for n in self.ArrayIds: try: name = self.DevId[n] listDevBuffers.append(TypeId(['cl_mem'], Id(name))) except KeyError: pass for n in self.ConstantMem: name = self.DevId[n] listDevBuffers.append(TypeId(['cl_mem'], Id(name))) dictNToDevPtr = self.DevId listDevBuffers = GroupCompound(listDevBuffers) fileAST.ext.append(listDevBuffers) listHostPtrs = [] dictTypeHostPtrs = dict() dictNToHstPtr = dict() for n in self.DevArgList: name = n.name.name type = self.Type[name] try: name = self.HstId[name] except KeyError: pass listHostPtrs.append(TypeId(type, Id(name), 0)) for n in self.GlobalVars: type = self.Type[n] name = self.HstId[n] listHostPtrs.append(TypeId(type, Id(name), 0)) dictNToHstPtr = self.HstId dictTypeHostPtrs = copy.deepcopy(self.Type) listHostPtrs = GroupCompound(listHostPtrs) fileAST.ext.append(listHostPtrs) listMemSize = [] listDimSize = [] listMemSizeCalcTemp = [] dictMemSizeCalc = dict() dictNToSize = self.Mem for n in self.Mem: sizeName = self.Mem[n] listMemSize.append(TypeId(['size_t'], Id(sizeName))) for n in self.ArrayIds: for dimName in self.ArrayIdToDimName[n]: listDimSize.append(\ TypeId(['size_t'], Id(dimName))) fileAST.ext.append(GroupCompound(listMemSize)) fileAST.ext.append(GroupCompound(listDimSize)) misc = [] lval = TypeId(['size_t'], Id('isFirstTime')) rval = Constant(1) misc.append(Assignment(lval,rval)) lval = TypeId(['std::string'], Id('KernelDefines')) rval = Constant('""') misc.append(Assignment(lval,rval)) lval = TypeId(['Stopwatch'], Id('timer')) misc.append(lval) fileAST.ext.append(GroupCompound(misc)) # Generate the GetKernelCode function for optim in self.KernelStringStream: fileAST.ext.append(optim['ast']) getKernelCode = EmptyFuncDecl('GetKernelCode', type = ['std::string']) getKernelStats = [] getKernelCode.compound.statements = getKernelStats getKernelStats.append(self.IfThenElse) ## getKernelStats.append(Id('return str.str();')) fileAST.ext.append(getKernelCode) allocateBuffer = EmptyFuncDecl('AllocateBuffers') fileAST.ext.append(allocateBuffer) listSetMemSize = [] for entry in self.ArrayIds: n = self.ArrayIdToDimName[entry] lval = Id(self.Mem[entry]) rval = BinOp(Id(n[0]),'*', Id('sizeof('+\ self.Type[entry][0]+')')) if len(n) == 2: rval = BinOp(Id(n[1]),'*', rval) listSetMemSize.append(Assignment(lval,rval)) for n in self.ConstantMem: terms = self.ConstantMem[n] rval = Id(self.Mem[terms[0]]) for s in terms[1:]: rval = BinOp(rval, '+', Id(self.Mem[s])) lval = Id(self.Mem[n]) listSetMemSize.append(Assignment(lval,rval)) allocateBuffer.compound.statements.append(\ GroupCompound(listSetMemSize)) allocateBuffer.compound.statements.append(\ self.Transposition) allocateBuffer.compound.statements.append(\ self.ConstantMemory) allocateBuffer.compound.statements.append(\ self.Define) ErrName = 'oclErrNum' lval = TypeId(['cl_int'], Id(ErrName)) rval = Id('CL_SUCCESS') clSuc = Assignment(lval,rval) allocateBuffer.compound.statements.extend(\ [GroupCompound([clSuc])]) for n in dictNToDevPtr: lval = Id(dictNToDevPtr[n]) op = '=' arrayn = dictNToHstPtr[n] try: arrayn = self.NameSwap[arrayn] except KeyError: pass if n in self.WriteOnly: flag = Id('CL_MEM_WRITE_ONLY') arraynId = Id('NULL') elif n in self.ReadOnly: flag = Id('CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY') arraynId = Id(arrayn) else: flag = Id('CL_MEM_USE_HOST_PTR') arraynId = Id(arrayn) arglist = ArgList([Id('context'),\ flag,\ Id(dictNToSize[n]),\ arraynId,\ Id('&'+ErrName)]) rval = FuncDecl(Id('clCreateBuffer'), arglist, Compound([])) allocateBuffer.compound.statements.append(\ Assignment(lval,rval)) arglist = ArgList([Id(ErrName), Constant("clCreateBuffer " + lval.name)]) ErrCheck = FuncDecl(Id('oclCheckErr'),arglist, Compound([])) allocateBuffer.compound.statements.append(ErrCheck) setArgumentsKernel = EmptyFuncDecl('SetArguments'+self.DevFuncId) fileAST.ext.append(setArgumentsKernel) ArgBody = setArgumentsKernel.compound.statements ArgBody.append(clSuc) cntName = Id('counter') lval = TypeId(['int'], cntName) rval = Constant(0) ArgBody.append(Assignment(lval,rval)) for n in dictNToDimNames: ## add dim arguments to set of ids NonArrayIds.add(dictNToDimNames[n][0]) # Add types of dimensions for size arguments dictTypeHostPtrs[dictNToDimNames[n][0]] = ['size_t'] for n in self.RemovedIds: dictTypeHostPtrs.pop(n,None) ## clSetKernelArg for Arrays for n in self.KernelArgs: lval = Id(ErrName) op = '|=' type = self.Type[n] if len(type) == 2: arglist = ArgList([kernelId,\ Increment(cntName,'++'),\ Id('sizeof(cl_mem)'),\ Id('(void *) &' + dictNToDevPtr[n])]) rval = FuncDecl(Id('clSetKernelArg'),arglist, Compound([])) else: try: n = self.NameSwap[n] except KeyError: pass cl_type = type[0] if cl_type == 'size_t': cl_type = 'unsigned' arglist = ArgList([kernelId,\ Increment(cntName,'++'),\ Id('sizeof('+cl_type+')'),\ Id('(void *) &' + n)]) rval = FuncDecl(Id('clSetKernelArg'),arglist, Compound([])) ArgBody.append(Assignment(lval,rval,op)) arglist = ArgList([Id(ErrName), Constant('clSetKernelArg')]) ErrId = Id('oclCheckErr') ErrCheck = FuncDecl(ErrId, arglist, Compound([])) ArgBody.append(ErrCheck) execKernel = EmptyFuncDecl('Exec' + self.DevFuncTypeId.name.name) fileAST.ext.append(execKernel) execBody = execKernel.compound.statements execBody.append(clSuc) eventName = Id('GPUExecution') event = TypeId(['cl_event'], eventName) execBody.append(event) for n in self.Worksize: lval = TypeId(['size_t'], Id(self.Worksize[n] + '[]')) if n == 'local': local_worksize = [Id(i) for i in self.Local['size']] rval = ArrayInit(local_worksize) elif n == 'global': initlist = [] for m in reversed(self.GridIndices): initlist.append(Id(self.UpperLimit[m]\ +' - '+ self.LowerLimit[m])) rval = ArrayInit(initlist) else: initlist = [] for m in reversed(self.GridIndices): initlist.append(Id(self.LowerLimit[m])) rval = ArrayInit(initlist) execBody.append(Assignment(lval,rval)) lval = Id(ErrName) arglist = ArgList([Id('command_queue'),\ Id(self.KernelName),\ Constant(self.ParDim),\ Id(self.Worksize['offset']),\ Id(self.Worksize['global']),\ Id(self.Worksize['local']),\ Constant(0), Id('NULL'), \ Id('&' + eventName.name)]) rval = FuncDecl(Id('clEnqueueNDRangeKernel'),arglist, Compound([])) execBody.append(Assignment(lval,rval)) arglist = ArgList([Id(ErrName), Constant('clEnqueueNDRangeKernel')]) ErrCheck = FuncDecl(ErrId, arglist, Compound([])) execBody.append(ErrCheck) arglist = ArgList([Id('command_queue')]) finish = FuncDecl(Id('clFinish'), arglist, Compound([])) execBody.append(Assignment(Id(ErrName), finish)) arglist = ArgList([Id(ErrName), Constant('clFinish')]) ErrCheck = FuncDecl(ErrId, arglist, Compound([])) execBody.append(ErrCheck) if not self.NoReadBack: for n in self.WriteOnly: lval = Id(ErrName) Hstn = self.HstId[n] try: Hstn = self.NameSwap[Hstn] except KeyError: pass arglist = ArgList([Id('command_queue'),\ Id(self.DevId[n]),\ Id('CL_TRUE'),\ Constant(0),\ Id(self.Mem[n]),\ Id(Hstn),\ Constant(1), Id('&' + eventName.name),Id('NULL')]) rval = FuncDecl(Id('clEnqueueReadBuffer'),arglist, Compound([])) execBody.append(Assignment(lval,rval)) arglist = ArgList([Id(ErrName), Constant('clEnqueueReadBuffer')]) ErrCheck = FuncDecl(ErrId, arglist, Compound([])) execBody.append(ErrCheck) # add clFinish statement arglist = ArgList([Id('command_queue')]) finish = FuncDecl(Id('clFinish'), arglist, Compound([])) execBody.append(Assignment(Id(ErrName), finish)) arglist = ArgList([Id(ErrName), Constant('clFinish')]) ErrCheck = FuncDecl(ErrId, arglist, Compound([])) execBody.append(ErrCheck) for n in self.WriteTranspose: execBody.append(n) runOCL = EmptyFuncDecl('RunOCL' + self.KernelName) fileAST.ext.append(runOCL) runOCLBody = runOCL.compound.statements argIds = self.NonArrayIds.union(self.ArrayIds) # typeIdList = [] ifThenList = [] for n in argIds: type = self.Type[n] argn = Id('arg_'+n) typeIdList.append(TypeId(type,argn)) try: newn = self.HstId[n] except KeyError: newn = n lval = Id(newn) rval = argn ifThenList.append(Assignment(lval,rval)) try: for m in self.ArrayIdToDimName[n]: type = ['size_t'] argm = Id('arg_'+m) lval = Id(m) rval = argm ifThenList.append(Assignment(lval,rval)) typeIdList.append(TypeId(type, argm)) except KeyError: pass arglist = ArgList(typeIdList) runOCL.arglist = arglist arglist = ArgList([]) ifThenList.append(FuncDecl(Id('StartUpGPU'), arglist, Compound([]))) ifThenList.append(FuncDecl(Id('AllocateBuffers'), arglist, Compound([]))) useFile = 'true' if self.KernelStringStream: useFile = 'false' ifThenList.append(Id('cout << "$Defines " << KernelDefines << endl;')) arglist = ArgList([Constant(self.DevFuncId), Constant(self.DevFuncId+'.cl'), Id('GetKernelCode()'), Id(useFile), Id('&' + self.KernelName), Id('KernelDefines')]) ifThenList.append(FuncDecl(Id('compileKernel'), arglist, Compound([]))) ifThenList.append(FuncDecl(Id('SetArguments'+self.DevFuncId), ArgList([]), Compound([]))) runOCLBody.append(IfThen(Id('isFirstTime'), Compound(ifThenList))) arglist = ArgList([]) # Insert timing runOCLBody.append(Id('timer.start();')) runOCLBody.append(FuncDecl(Id('Exec' + self.DevFuncId), arglist, Compound([]))) runOCLBody.append(Id('cout << "$Time " << timer.stop() << endl;')) return fileAST
dikujepsen/OpenTran
v2.0/framework/old/rewriter.py
Python
mit
39,575
[ "VisIt" ]
affc58229817c41ef4aebe57f6b617e1d532c69f04ede867744ec3e9ee1b5620
#!/usr/bin/env python import psycopg2 import sys time =sys.argv[1] #time = str(1086725208) #conn = psycopg2.connect("dbname=mwa host=mwa-metadata01.pawsey.org.au user=MWA-guest password=guest port=5432") conn = psycopg2.connect("dbname=mwa host=mwa-metadata01.pawsey.org.au user=mwa password=BowTie port=5432") cur = conn.cursor() cur.execute("SELECT rf_stream.frequencies, rf_stream.ra, rf_stream.dec, rf_stream.azimuth, rf_stream.elevation FROM public.mwa_setting, public.rf_stream WHERE" " mwa_setting.starttime = rf_stream.starttime and mwa_setting.starttime = %s" % (time)) params = cur.fetchone() freqs = params[0] if freqs == range(freqs[0], freqs[0]+len(freqs)): centre = freqs[len(freqs)/2] print "Center Frequency ", str((centre * 1.28) - 0.64) else: centre = None print "Non contiguous frequency channels in observation" #freqs = [str(freq) for freq in freqs] #print ','.join(freqs)
steve-ord/galaxy-scripts
scripts/fits_db.py
Python
gpl-2.0
934
[ "Bowtie" ]
08b0953848a5b7a6a099f2c5cb9ea3e78d8a93ee59faa5189a95be067b38269e
import json import os import unittest import warnings from sympy import Number, Symbol from pymatgen.analysis.surface_analysis import ( NanoscaleStability, SlabEntry, SurfaceEnergyPlotter, WorkFunctionAnalyzer, ) from pymatgen.entries.computed_entries import ComputedStructureEntry from pymatgen.util.testing import PymatgenTest __author__ = "Richard Tran" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Richard Tran" __email__ = "rit001@eng.ucsd.edu" __date__ = "Aug 24, 2017" def get_path(path_str): path = os.path.join(PymatgenTest.TEST_FILES_DIR, "surface_tests", path_str) return path class SlabEntryTest(PymatgenTest): def setUp(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") with open(os.path.join(get_path(""), "ucell_entries.txt")) as ucell_entries: ucell_entries = json.loads(ucell_entries.read()) self.ucell_entries = ucell_entries # Load objects for O adsorption tests self.metals_O_entry_dict = load_O_adsorption() # Load objects for Cu test self.Cu_entry_dict = get_entry_dict(os.path.join(get_path(""), "Cu_entries.txt")) self.assertEqual(len(self.Cu_entry_dict.keys()), 13) self.Cu_ucell_entry = ComputedStructureEntry.from_dict(self.ucell_entries["Cu"]) # Load dummy MgO slab entries self.MgO_ucell_entry = ComputedStructureEntry.from_dict(self.ucell_entries["MgO"]) self.Mg_ucell_entry = ComputedStructureEntry.from_dict(self.ucell_entries["Mg"]) self.MgO_slab_entry_dict = get_entry_dict(os.path.join(get_path(""), "MgO_slab_entries.txt")) def test_properties(self): # Test cases for getting adsorption related quantities for a 1/4 # monolalyer adsorption of O on the low MMI surfaces of Pt, Ni and Rh for el in self.metals_O_entry_dict.keys(): el_ucell = ComputedStructureEntry.from_dict(self.ucell_entries[el]) for hkl in self.metals_O_entry_dict[el].keys(): for clean in self.metals_O_entry_dict[el][hkl].keys(): for ads in self.metals_O_entry_dict[el][hkl][clean]: ml = ads.get_unit_primitive_area self.assertAlmostEqual(ml, 4, 2) self.assertAlmostEqual(ads.get_monolayer, 1 / 4, 2) Nads = ads.Nads_in_slab self.assertEqual(Nads, 1) self.assertEqual(ads.Nsurfs_ads_in_slab, 1) # Determine the correct binding energy with open(os.path.join(get_path(""), "isolated_O_entry.txt")) as isolated_O_entry: isolated_O_entry = json.loads(isolated_O_entry.read()) O = ComputedStructureEntry.from_dict(isolated_O_entry) gbind = (ads.energy - ml * clean.energy) / Nads - O.energy_per_atom self.assertEqual(gbind, ads.gibbs_binding_energy()) # Determine the correction Gibbs adsorption energy eads = Nads * gbind self.assertEqual(eads, ads.gibbs_binding_energy(eads=True)) se = ads.surface_energy(el_ucell) self.assertAlmostEqual( se.as_coefficients_dict()[Symbol("delu_O")], (-1 / 2) * ads.surface_area ** (-1), ) def test_create_slab_label(self): for el in self.metals_O_entry_dict.keys(): for hkl in self.metals_O_entry_dict[el].keys(): # Test WulffShape for adsorbed surfaces for clean in self.metals_O_entry_dict[el][hkl]: label = clean.create_slab_label comp = str(clean.composition.reduced_composition) self.assertEqual(str(hkl) + f" {comp}", label) for ads in self.metals_O_entry_dict[el][hkl][clean]: label = ads.create_slab_label self.assertEqual(label, str(hkl) + f" {comp}+O, 0.250 ML") def test_surface_energy(self): # For a nonstoichiometric case, the cheimcal potentials do not # cancel out, they serve as a reservoir for any missing atoms for slab_entry in self.MgO_slab_entry_dict[(1, 1, 1)].keys(): se = slab_entry.surface_energy(self.MgO_ucell_entry, ref_entries=[self.Mg_ucell_entry]) self.assertEqual(tuple(se.as_coefficients_dict().keys()), (Number(1), Symbol("delu_Mg"))) # For the case of a clean, stoichiometric slab, the surface energy # should be constant (i.e. surface energy is a constant). all_se = [] ECu = self.Cu_ucell_entry.energy_per_atom for hkl in self.Cu_entry_dict.keys(): slab_entry = list(self.Cu_entry_dict[hkl].keys())[0] se = slab_entry.surface_energy(self.Cu_ucell_entry) all_se.append(se) # Manually calculate surface energy manual_se = (slab_entry.energy - ECu * len(slab_entry.structure)) / (2 * slab_entry.surface_area) self.assertArrayAlmostEqual(float(se), manual_se, 10) # The (111) facet should be the most stable clean111_entry = list(self.Cu_entry_dict[(1, 1, 1)].keys())[0] se_Cu111 = clean111_entry.surface_energy(self.Cu_ucell_entry) self.assertEqual(min(all_se), se_Cu111) def test_cleaned_up_slab(self): # The cleaned up slab should have the same reduced formula as a clean slab for el in self.metals_O_entry_dict.keys(): for hkl in self.metals_O_entry_dict[el].keys(): for clean in self.metals_O_entry_dict[el][hkl].keys(): for ads in self.metals_O_entry_dict[el][hkl][clean]: s = ads.cleaned_up_slab self.assertEqual( s.composition.reduced_composition, clean.composition.reduced_composition, ) class SurfaceEnergyPlotterTest(PymatgenTest): def setUp(self): entry_dict = get_entry_dict(os.path.join(get_path(""), "Cu_entries.txt")) self.Cu_entry_dict = entry_dict with open(os.path.join(get_path(""), "ucell_entries.txt")) as ucell_entries: ucell_entries = json.loads(ucell_entries.read()) self.Cu_ucell_entry = ComputedStructureEntry.from_dict(ucell_entries["Cu"]) self.Cu_analyzer = SurfaceEnergyPlotter(entry_dict, self.Cu_ucell_entry) self.metals_O_entry_dict = load_O_adsorption() ucell_entry = ComputedStructureEntry.from_dict(ucell_entries["Pt"]) self.Pt_analyzer = SurfaceEnergyPlotter(self.metals_O_entry_dict["Pt"], ucell_entry) ucell_entry = ComputedStructureEntry.from_dict(ucell_entries["Ni"]) self.Ni_analyzer = SurfaceEnergyPlotter(self.metals_O_entry_dict["Ni"], ucell_entry) ucell_entry = ComputedStructureEntry.from_dict(ucell_entries["Rh"]) self.Rh_analyzer = SurfaceEnergyPlotter(self.metals_O_entry_dict["Rh"], ucell_entry) self.Oads_analyzer_dict = { "Pt": self.Pt_analyzer, "Ni": self.Ni_analyzer, "Rh": self.Rh_analyzer, } def test_get_stable_entry_at_u(self): for el in self.Oads_analyzer_dict.keys(): plotter = self.Oads_analyzer_dict[el] for hkl in plotter.all_slab_entries.keys(): # Test that the surface energy is clean for specific range of chempot entry1, gamma1 = plotter.get_stable_entry_at_u(hkl, delu_dict={Symbol("delu_O"): -7}) entry2, gamma2 = plotter.get_stable_entry_at_u(hkl, delu_dict={Symbol("delu_O"): -6}) self.assertEqual(gamma1, gamma2) self.assertEqual(entry1.label, entry2.label) # Now test that for a high chempot, adsorption # occurs and gamma is not equal to clean gamma entry3, gamma3 = plotter.get_stable_entry_at_u(hkl, delu_dict={Symbol("delu_O"): -1}) self.assertNotEqual(entry3.label, entry2.label) self.assertNotEqual(gamma3, gamma2) # For any chempot greater than -6, surface energy should vary # but the configuration should remain the same entry4, gamma4 = plotter.get_stable_entry_at_u(hkl, delu_dict={Symbol("delu_O"): 0}) self.assertEqual(entry3.label, entry4.label) self.assertNotEqual(gamma3, gamma4) def test_wulff_from_chempot(self): # Test if it generates a Wulff shape, test if # all the facets for Cu wulff shape are inside. Cu_wulff = self.Cu_analyzer.wulff_from_chempot() area_frac_dict = Cu_wulff.area_fraction_dict facets_hkl = [ (1, 1, 1), (3, 3, 1), (3, 1, 0), (1, 0, 0), (3, 1, 1), (2, 1, 0), (2, 2, 1), ] for hkl in area_frac_dict.keys(): if hkl in facets_hkl: self.assertNotEqual(area_frac_dict[hkl], 0) else: self.assertEqual(area_frac_dict[hkl], 0) for el in self.Oads_analyzer_dict.keys(): # Test WulffShape for adsorbed surfaces analyzer = self.Oads_analyzer_dict[el] # chempot = analyzer.max_adsorption_chempot_range(0) wulff = analyzer.wulff_from_chempot(delu_default=-6) wulff.weighted_surface_energy # Test if a different Wulff shape is generated # for Ni when adsorption comes into play wulff_neg7 = self.Oads_analyzer_dict["Ni"].wulff_from_chempot(delu_default=-7) wulff_neg6 = self.Oads_analyzer_dict["Ni"].wulff_from_chempot(delu_default=-6) self.assertEqual(wulff_neg7.weighted_surface_energy, wulff_neg6.weighted_surface_energy) wulff_neg55 = self.Oads_analyzer_dict["Ni"].wulff_from_chempot(delu_default=-5.5) self.assertNotEqual(wulff_neg55.weighted_surface_energy, wulff_neg6.weighted_surface_energy) wulff_neg525 = self.Oads_analyzer_dict["Ni"].wulff_from_chempot(delu_default=-5.25) self.assertNotEqual(wulff_neg55.weighted_surface_energy, wulff_neg525.weighted_surface_energy) def test_color_palette_dict(self): for el in self.metals_O_entry_dict.keys(): analyzer = self.Oads_analyzer_dict[el] color_dict = analyzer.color_palette_dict() for hkl in self.metals_O_entry_dict[el].keys(): for clean in self.metals_O_entry_dict[el][hkl].keys(): _ = color_dict[clean] for ads in self.metals_O_entry_dict[el][hkl][clean]: _ = color_dict[ads] def test_get_surface_equilibrium(self): # For clean stoichiometric system, the two equations should # be parallel because the surface energy is a constant. Then # get_surface_equilibrium should return None clean111_entry = list(self.Cu_entry_dict[(1, 1, 1)].keys())[0] clean100_entry = list(self.Cu_entry_dict[(1, 0, 0)].keys())[0] soln = self.Cu_analyzer.get_surface_equilibrium([clean111_entry, clean100_entry]) self.assertFalse(soln) # For adsorbed system, we should find one intercept Pt_entries = self.metals_O_entry_dict["Pt"] clean = list(Pt_entries[(1, 1, 1)].keys())[0] ads = Pt_entries[(1, 1, 1)][clean][0] Pt_analyzer = self.Oads_analyzer_dict["Pt"] soln = Pt_analyzer.get_surface_equilibrium([clean, ads]) self.assertNotEqual(list(soln.values())[0], list(soln.values())[1]) # Check if the number of parameters for adsorption are correct self.assertEqual((Symbol("delu_O"), Symbol("gamma")), tuple(soln.keys())) # Adsorbed systems have a b2=(-1*Nads) / (Nsurfs * Aads) se = ads.surface_energy(Pt_analyzer.ucell_entry, Pt_analyzer.ref_entries) self.assertAlmostEqual(se.as_coefficients_dict()[Symbol("delu_O")], -1 / (2 * ads.surface_area)) def test_stable_u_range_dict(self): for el in self.Oads_analyzer_dict.keys(): analyzer = self.Oads_analyzer_dict[el] stable_u_range = analyzer.stable_u_range_dict([-1, 0], Symbol("delu_O"), no_doped=False) all_u = [] for entry in stable_u_range.keys(): all_u.extend(stable_u_range[entry]) self.assertGreater(len(all_u), 1) def test_entry_dict_from_list(self): # Plug in a list of entries to see if it works all_Pt_slab_entries = [] Pt_entries = self.Pt_analyzer.all_slab_entries for hkl in Pt_entries.keys(): for clean in Pt_entries[hkl].keys(): all_Pt_slab_entries.append(clean) all_Pt_slab_entries.extend(Pt_entries[hkl][clean]) a = SurfaceEnergyPlotter(all_Pt_slab_entries, self.Pt_analyzer.ucell_entry) self.assertEqual(type(a).__name__, "SurfaceEnergyPlotter") # def test_monolayer_vs_BE(self): # for el in self.Oads_analyzer_dict.keys(): # # Test WulffShape for adsorbed surfaces # analyzer = self.Oads_analyzer_dict[el] # plt = analyzer.monolayer_vs_BE() # # def test_area_frac_vs_chempot_plot(self): # # for el in self.Oads_analyzer_dict.keys(): # # Test WulffShape for adsorbed surfaces # analyzer = self.Oads_analyzer_dict[el] # plt = analyzer.area_frac_vs_chempot_plot(x_is_u_ads=True) # # def test_chempot_vs_gamma_clean(self): # # plt = self.Cu_analyzer.chempot_vs_gamma_clean() # for el in self.Oads_analyzer_dict.keys(): # # Test WulffShape for adsorbed surfaces # analyzer = self.Oads_analyzer_dict[el] # plt = analyzer.chempot_vs_gamma_clean(x_is_u_ads=True) # # def test_chempot_vs_gamma_facet(self): # # for el in self.metals_O_entry_dict.keys(): # for hkl in self.metals_O_entry_dict[el].keys(): # # Test WulffShape for adsorbed surfaces # analyzer = self.Oads_analyzer_dict[el] # plt = analyzer.chempot_vs_gamma_facet(hkl) # def test_surface_chempot_range_map(self): # # for el in self.metals_O_entry_dict.keys(): # for hkl in self.metals_O_entry_dict[el].keys(): # # Test WulffShape for adsorbed surfaces # analyzer = self.Oads_analyzer_dict[el] # plt = analyzer.chempot_vs_gamma_facet(hkl) class WorkfunctionAnalyzerTest(PymatgenTest): def setUp(self): self.kwargs = { "poscar_filename": get_path("CONTCAR.relax1.gz"), "locpot_filename": get_path("LOCPOT.gz"), "outcar_filename": get_path("OUTCAR.relax1.gz"), } self.wf_analyzer = WorkFunctionAnalyzer.from_files(**self.kwargs) def test_shift(self): wf_analyzer_shift = WorkFunctionAnalyzer.from_files(shift=-0.25, blength=3.7, **self.kwargs) self.assertAlmostEqual(self.wf_analyzer.ave_bulk_p, wf_analyzer_shift.ave_bulk_p, places=0) def test_is_converged(self): self.assertTrue(self.wf_analyzer.is_converged()) class NanoscaleStabilityTest(PymatgenTest): def setUp(self): # Load all entries La_hcp_entry_dict = get_entry_dict(os.path.join(get_path(""), "La_hcp_entries.txt")) La_fcc_entry_dict = get_entry_dict(os.path.join(get_path(""), "La_fcc_entries.txt")) with open(os.path.join(get_path(""), "ucell_entries.txt")) as ucell_entries: ucell_entries = json.loads(ucell_entries.read()) La_hcp_ucell_entry = ComputedStructureEntry.from_dict(ucell_entries["La_hcp"]) La_fcc_ucell_entry = ComputedStructureEntry.from_dict(ucell_entries["La_fcc"]) # Set up the NanoscaleStabilityClass self.La_hcp_analyzer = SurfaceEnergyPlotter(La_hcp_entry_dict, La_hcp_ucell_entry) self.La_fcc_analyzer = SurfaceEnergyPlotter(La_fcc_entry_dict, La_fcc_ucell_entry) self.nanoscale_stability = NanoscaleStability([self.La_fcc_analyzer, self.La_hcp_analyzer]) def test_stability_at_r(self): # Check that we have a different polymorph that is # stable below or above the equilibrium particle size r = self.nanoscale_stability.solve_equilibrium_point(self.La_hcp_analyzer, self.La_fcc_analyzer) * 10 # hcp phase of La particle should be the stable # polymorph above the equilibrium radius hcp_wulff = self.La_hcp_analyzer.wulff_from_chempot() bulk = self.La_hcp_analyzer.ucell_entry ghcp, rhcp = self.nanoscale_stability.wulff_gform_and_r(hcp_wulff, bulk, r + 10, from_sphere_area=True) fcc_wulff = self.La_fcc_analyzer.wulff_from_chempot() bulk = self.La_fcc_analyzer.ucell_entry gfcc, rfcc = self.nanoscale_stability.wulff_gform_and_r(fcc_wulff, bulk, r + 10, from_sphere_area=True) self.assertGreater(gfcc, ghcp) # fcc phase of La particle should be the stable # polymorph below the equilibrium radius hcp_wulff = self.La_hcp_analyzer.wulff_from_chempot() bulk = self.La_hcp_analyzer.ucell_entry ghcp, rhcp = self.nanoscale_stability.wulff_gform_and_r(hcp_wulff, bulk, r - 10, from_sphere_area=True) fcc_wulff = self.La_fcc_analyzer.wulff_from_chempot() bulk = self.La_fcc_analyzer.ucell_entry gfcc, rfcc = self.nanoscale_stability.wulff_gform_and_r(fcc_wulff, bulk, r - 10, from_sphere_area=True) self.assertLess(gfcc, ghcp) def test_scaled_wulff(self): # Ensure for a given radius, the effective radius # of the Wulff shape is the same (correctly scaled) hcp_wulff = self.La_hcp_analyzer.wulff_from_chempot() fcc_wulff = self.La_fcc_analyzer.wulff_from_chempot() w1 = self.nanoscale_stability.scaled_wulff(hcp_wulff, 10) w2 = self.nanoscale_stability.scaled_wulff(fcc_wulff, 10) self.assertAlmostEqual(w1.effective_radius, w2.effective_radius) self.assertAlmostEqual(w1.effective_radius, 10) self.assertAlmostEqual(10, w2.effective_radius) def get_entry_dict(filename): # helper to generate an entry_dict entry_dict = {} with open(filename) as entries: entries = json.loads(entries.read()) for k in entries.keys(): n = k[25:] miller_index = [] for i, s in enumerate(n): if s == "_": break if s == "-": continue t = int(s) if n[i - 1] == "-": t *= -1 miller_index.append(t) hkl = tuple(miller_index) if hkl not in entry_dict.keys(): entry_dict[hkl] = {} entry = ComputedStructureEntry.from_dict(entries[k]) entry_dict[hkl][SlabEntry(entry.structure, entry.energy, hkl, label=k)] = [] return entry_dict def load_O_adsorption(): # Loads the dictionary for clean and O adsorbed Rh, Pt, and Ni entries # Load the adsorbate as an entry with open(os.path.join(get_path(""), "isolated_O_entry.txt")) as isolated_O_entry: isolated_O_entry = json.loads(isolated_O_entry.read()) O = ComputedStructureEntry.from_dict(isolated_O_entry) # entry_dict for the adsorption case, O adsorption on Ni, Rh and Pt metals_O_entry_dict = { "Ni": {(1, 1, 1): {}, (1, 0, 0): {}}, "Pt": {(1, 1, 1): {}}, "Rh": {(1, 0, 0): {}}, } with open(os.path.join(get_path(""), "csentries_slabs.json")) as entries: entries = json.loads(entries.read()) for k in entries.keys(): entry = ComputedStructureEntry.from_dict(entries[k]) for el in metals_O_entry_dict.keys(): if el in k: if "111" in k: clean = SlabEntry(entry.structure, entry.energy, (1, 1, 1), label=k + "_clean") metals_O_entry_dict[el][(1, 1, 1)][clean] = [] if "110" in k: clean = SlabEntry(entry.structure, entry.energy, (1, 1, 0), label=k + "_clean") metals_O_entry_dict[el][(1, 1, 0)][clean] = [] if "100" in k: clean = SlabEntry(entry.structure, entry.energy, (1, 0, 0), label=k + "_clean") metals_O_entry_dict[el][(1, 0, 0)][clean] = [] with open(os.path.join(get_path(""), "csentries_o_ads.json")) as entries: entries = json.loads(entries.read()) for k in entries.keys(): entry = ComputedStructureEntry.from_dict(entries[k]) for el in metals_O_entry_dict.keys(): if el in k: if "111" in k: clean = list(metals_O_entry_dict[el][(1, 1, 1)].keys())[0] ads = SlabEntry( entry.structure, entry.energy, (1, 1, 1), label=k + "_O", adsorbates=[O], clean_entry=clean, ) metals_O_entry_dict[el][(1, 1, 1)][clean] = [ads] if "110" in k: clean = list(metals_O_entry_dict[el][(1, 1, 0)].keys())[0] ads = SlabEntry( entry.structure, entry.energy, (1, 1, 0), label=k + "_O", adsorbates=[O], clean_entry=clean, ) metals_O_entry_dict[el][(1, 1, 0)][clean] = [ads] if "100" in k: clean = list(metals_O_entry_dict[el][(1, 0, 0)].keys())[0] ads = SlabEntry( entry.structure, entry.energy, (1, 0, 0), label=k + "_O", adsorbates=[O], clean_entry=clean, ) metals_O_entry_dict[el][(1, 0, 0)][clean] = [ads] return metals_O_entry_dict if __name__ == "__main__": unittest.main()
materialsproject/pymatgen
pymatgen/analysis/tests/test_surface_analysis.py
Python
mit
22,393
[ "pymatgen" ]
48adb9f905fec70aa2bd7d189492b1b180bfe8e45c803cedd703b083f1168b5d
""" /****************************************************************************** This source file is part of the Avogadro project. Copyright 2013 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ """ import argparse import json import sys def getMetaData(): metaData = {} metaData['inputFormat'] = 'xyz' metaData['outputFormat'] = 'xyz' metaData['operations'] = ['read', 'write'] metaData['identifier'] = 'ZYX Example Format' metaData['name'] = 'ZYX' metaData['description'] = "Mostly useless file format that reads xyz-style " +\ "files with reversed coordinates. Demonstrates " +\ "the implementation of a user-scripted file format." metaData['fileExtensions'] = ['zyx'] metaData['mimeTypes'] = ['chemical/x-zyx'] return metaData def write(): result = "" # Just copy the first two lines: numAtoms and comment/title result += sys.stdin.readline() result += sys.stdin.readline() for line in sys.stdin: words = line.split() result += '%-3s %9.5f %9.5f %9.5f' %\ (words[0], float(words[3]), float(words[2]), float(words[1])) if len(words) > 4: result += words[4:].join(' ') result += '\n' return result def read(): result = "" # Just copy the first two lines: numAtoms and comment/title result += sys.stdin.readline() result += sys.stdin.readline() for line in sys.stdin: words = line.split() result += '%-3s %9.5f %9.5f %9.5f' %\ (words[0], float(words[3]), float(words[2]), float(words[1])) if len(words) > 4: result += words[4:].join(' ') result += '\n' return result if __name__ == "__main__": parser = argparse.ArgumentParser('Example file format script.') parser.add_argument('--metadata', action='store_true') parser.add_argument('--read', action='store_true') parser.add_argument('--write', action='store_true') parser.add_argument('--display-name', action='store_true') parser.add_argument('--lang', nargs='?', default='en') args = vars(parser.parse_args()) if args['metadata']: print(json.dumps(getMetaData())) elif args['display_name']: print(getMetaData()['name']) elif args['read']: print(read()) elif args['write']: print(write())
OpenChemistry/avogadrolibs
avogadro/qtplugins/scriptfileformats/formatScripts/zyx.py
Python
bsd-3-clause
2,841
[ "Avogadro" ]
c33746ca72e79b7fd8a51852521f86bded89b9ac2d5ce46a4dc39cc4359bb0b3
######################################################################## # # (C) 2013, James Cammarata <jcammarata@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ######################################################################## from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os.path import re import shutil import sys import time import yaml from jinja2 import Environment, FileSystemLoader import ansible.constants as C from ansible.cli import CLI from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.galaxy import Galaxy from ansible.galaxy.api import GalaxyAPI from ansible.galaxy.login import GalaxyLogin from ansible.galaxy.role import GalaxyRole from ansible.galaxy.token import GalaxyToken from ansible.module_utils._text import to_text from ansible.playbook.role.requirement import RoleRequirement try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class GalaxyCLI(CLI): '''command to manage Ansible roles in shared repostories, the default of which is Ansible Galaxy *https://galaxy.ansible.com*.''' SKIP_INFO_KEYS = ("name", "description", "readme_html", "related", "summary_fields", "average_aw_composite", "average_aw_score", "url") VALID_ACTIONS = ("delete", "import", "info", "init", "install", "list", "login", "remove", "search", "setup") def __init__(self, args): self.api = None self.galaxy = None super(GalaxyCLI, self).__init__(args) def set_action(self): super(GalaxyCLI, self).set_action() # specific to actions if self.action == "delete": self.parser.set_usage("usage: %prog delete [options] github_user github_repo") elif self.action == "import": self.parser.set_usage("usage: %prog import [options] github_user github_repo") self.parser.add_option('--no-wait', dest='wait', action='store_false', default=True, help='Don\'t wait for import results.') self.parser.add_option('--branch', dest='reference', help='The name of a branch to import. Defaults to the repository\'s default branch (usually master)') self.parser.add_option('--role-name', dest='role_name', help='The name the role should have, if different than the repo name') self.parser.add_option('--status', dest='check_status', action='store_true', default=False, help='Check the status of the most recent import request for given github_user/github_repo.') elif self.action == "info": self.parser.set_usage("usage: %prog info [options] role_name[,version]") elif self.action == "init": self.parser.set_usage("usage: %prog init [options] role_name") self.parser.add_option('--init-path', dest='init_path', default="./", help='The path in which the skeleton role will be created. The default is the current working directory.') self.parser.add_option('--container-enabled', dest='container_enabled', action='store_true', default=False, help='Initialize the skeleton role with default contents for a Container Enabled role.') self.parser.add_option('--role-skeleton', dest='role_skeleton', default=C.GALAXY_ROLE_SKELETON, help='The path to a role skeleton that the new role should be based upon.') elif self.action == "install": self.parser.set_usage("usage: %prog install [options] [-r FILE | role_name(s)[,version] | scm+role_repo_url[,version] | tar_file(s)]") self.parser.add_option('-i', '--ignore-errors', dest='ignore_errors', action='store_true', default=False, help='Ignore errors and continue with the next specified role.') self.parser.add_option('-n', '--no-deps', dest='no_deps', action='store_true', default=False, help='Don\'t download roles listed as dependencies') self.parser.add_option('-r', '--role-file', dest='role_file', help='A file containing a list of roles to be imported') elif self.action == "remove": self.parser.set_usage("usage: %prog remove role1 role2 ...") elif self.action == "list": self.parser.set_usage("usage: %prog list [role_name]") elif self.action == "login": self.parser.set_usage("usage: %prog login [options]") self.parser.add_option('--github-token', dest='token', default=None, help='Identify with github token rather than username and password.') elif self.action == "search": self.parser.set_usage("usage: %prog search [searchterm1 searchterm2] [--galaxy-tags galaxy_tag1,galaxy_tag2] [--platforms platform1,platform2] " "[--author username]") self.parser.add_option('--platforms', dest='platforms', help='list of OS platforms to filter by') self.parser.add_option('--galaxy-tags', dest='galaxy_tags', help='list of galaxy tags to filter by') self.parser.add_option('--author', dest='author', help='GitHub username') elif self.action == "setup": self.parser.set_usage("usage: %prog setup [options] source github_user github_repo secret") self.parser.add_option('--remove', dest='remove_id', default=None, help='Remove the integration matching the provided ID value. Use --list to see ID values.') self.parser.add_option('--list', dest="setup_list", action='store_true', default=False, help='List all of your integrations.') # options that apply to more than one action if self.action in ['init', 'info']: self.parser.add_option('--offline', dest='offline', default=False, action='store_true', help="Don't query the galaxy API when creating roles") if self.action not in ("delete", "import", "init", "login", "setup"): # NOTE: while the option type=str, the default is a list, and the # callback will set the value to a list. self.parser.add_option('-p', '--roles-path', dest='roles_path', action="callback", callback=CLI.unfrack_paths, default=C.DEFAULT_ROLES_PATH, help='The path to the directory containing your roles. The default is the roles_path configured in your ansible.cfg' 'file (/etc/ansible/roles if not configured)', type='str') if self.action in ("init", "install"): self.parser.add_option('-f', '--force', dest='force', action='store_true', default=False, help='Force overwriting an existing role') def parse(self): ''' create an options parser for bin/ansible ''' self.parser = CLI.base_parser( usage="usage: %%prog [%s] [--help] [options] ..." % "|".join(self.VALID_ACTIONS), epilog="\nSee '%s <command> --help' for more information on a specific command.\n\n" % os.path.basename(sys.argv[0]) ) # common self.parser.add_option('-s', '--server', dest='api_server', default=C.GALAXY_SERVER, help='The API server destination') self.parser.add_option('-c', '--ignore-certs', action='store_true', dest='ignore_certs', default=C.GALAXY_IGNORE_CERTS, help='Ignore SSL certificate validation errors.') self.set_action() super(GalaxyCLI, self).parse() display.verbosity = self.options.verbosity self.galaxy = Galaxy(self.options) def run(self): super(GalaxyCLI, self).run() self.api = GalaxyAPI(self.galaxy) self.execute() def exit_without_ignore(self, rc=1): """ Exits with the specified return code unless the option --ignore-errors was specified """ if not self.options.ignore_errors: raise AnsibleError('- you can use --ignore-errors to skip failed roles and finish processing the list.') def _display_role_info(self, role_info): text = [u"", u"Role: %s" % to_text(role_info['name'])] text.append(u"\tdescription: %s" % role_info.get('description', '')) for k in sorted(role_info.keys()): if k in self.SKIP_INFO_KEYS: continue if isinstance(role_info[k], dict): text.append(u"\t%s:" % (k)) for key in sorted(role_info[k].keys()): if key in self.SKIP_INFO_KEYS: continue text.append(u"\t\t%s: %s" % (key, role_info[k][key])) else: text.append(u"\t%s: %s" % (k, role_info[k])) return u'\n'.join(text) ############################ # execute actions ############################ def execute_init(self): """ creates the skeleton framework of a role that complies with the galaxy metadata format. """ init_path = self.options.init_path force = self.options.force role_skeleton = self.options.role_skeleton role_name = self.args.pop(0).strip() if self.args else None if not role_name: raise AnsibleOptionsError("- no role name specified for init") role_path = os.path.join(init_path, role_name) if os.path.exists(role_path): if os.path.isfile(role_path): raise AnsibleError("- the path %s already exists, but is a file - aborting" % role_path) elif not force: raise AnsibleError("- the directory %s already exists." "you can use --force to re-initialize this directory,\n" "however it will reset any main.yml files that may have\n" "been modified there already." % role_path) inject_data = dict( role_name=role_name, author='your name', description='your description', company='your company (optional)', license='license (GPLv2, CC-BY, etc)', issue_tracker_url='http://example.com/issue/tracker', min_ansible_version='1.2', container_enabled=self.options.container_enabled ) # create role directory if not os.path.exists(role_path): os.makedirs(role_path) if role_skeleton is not None: skeleton_ignore_expressions = C.GALAXY_ROLE_SKELETON_IGNORE else: role_skeleton = self.galaxy.default_role_skeleton_path skeleton_ignore_expressions = ['^.*/.git_keep$'] role_skeleton = os.path.expanduser(role_skeleton) skeleton_ignore_re = [re.compile(x) for x in skeleton_ignore_expressions] template_env = Environment(loader=FileSystemLoader(role_skeleton)) for root, dirs, files in os.walk(role_skeleton, topdown=True): rel_root = os.path.relpath(root, role_skeleton) in_templates_dir = rel_root.split(os.sep, 1)[0] == 'templates' dirs[:] = [d for d in dirs if not any(r.match(os.path.join(rel_root, d)) for r in skeleton_ignore_re)] for f in files: filename, ext = os.path.splitext(f) if any(r.match(os.path.join(rel_root, f)) for r in skeleton_ignore_re): continue elif ext == ".j2" and not in_templates_dir: src_template = os.path.join(rel_root, f) dest_file = os.path.join(role_path, rel_root, filename) template_env.get_template(src_template).stream(inject_data).dump(dest_file) else: f_rel_path = os.path.relpath(os.path.join(root, f), role_skeleton) shutil.copyfile(os.path.join(root, f), os.path.join(role_path, f_rel_path)) for d in dirs: dir_path = os.path.join(role_path, rel_root, d) if not os.path.exists(dir_path): os.makedirs(dir_path) display.display("- %s was created successfully" % role_name) def execute_info(self): """ prints out detailed information about an installed role as well as info available from the galaxy API. """ if len(self.args) == 0: # the user needs to specify a role raise AnsibleOptionsError("- you must specify a user/role name") roles_path = self.options.roles_path data = '' for role in self.args: role_info = {'path': roles_path} gr = GalaxyRole(self.galaxy, role) install_info = gr.install_info if install_info: if 'version' in install_info: install_info['intalled_version'] = install_info['version'] del install_info['version'] role_info.update(install_info) remote_data = False if not self.options.offline: remote_data = self.api.lookup_role_by_name(role, False) if remote_data: role_info.update(remote_data) if gr.metadata: role_info.update(gr.metadata) req = RoleRequirement() role_spec = req.role_yaml_parse({'role': role}) if role_spec: role_info.update(role_spec) data = self._display_role_info(role_info) # FIXME: This is broken in both 1.9 and 2.0 as # _display_role_info() always returns something if not data: data = u"\n- the role %s was not found" % role self.pager(data) def execute_install(self): """ uses the args list of roles to be installed, unless -f was specified. The list of roles can be a name (which will be downloaded via the galaxy API and github), or it can be a local .tar.gz file. """ role_file = self.options.role_file if len(self.args) == 0 and role_file is None: # the user needs to specify one of either --role-file or specify a single user/role name raise AnsibleOptionsError("- you must specify a user/role name or a roles file") no_deps = self.options.no_deps force = self.options.force roles_left = [] if role_file: try: f = open(role_file, 'r') if role_file.endswith('.yaml') or role_file.endswith('.yml'): try: required_roles = yaml.safe_load(f.read()) except Exception as e: raise AnsibleError("Unable to load data from the requirements file: %s" % role_file) if required_roles is None: raise AnsibleError("No roles found in file: %s" % role_file) for role in required_roles: if "include" not in role: role = RoleRequirement.role_yaml_parse(role) display.vvv("found role %s in yaml file" % str(role)) if "name" not in role and "scm" not in role: raise AnsibleError("Must specify name or src for role") roles_left.append(GalaxyRole(self.galaxy, **role)) else: with open(role["include"]) as f_include: try: roles_left += [ GalaxyRole(self.galaxy, **r) for r in (RoleRequirement.role_yaml_parse(i) for i in yaml.safe_load(f_include)) ] except Exception as e: msg = "Unable to load data from the include requirements file: %s %s" raise AnsibleError(msg % (role_file, e)) else: display.deprecated("going forward only the yaml format will be supported", version="2.6") # roles listed in a file, one per line for rline in f.readlines(): if rline.startswith("#") or rline.strip() == '': continue display.debug('found role %s in text file' % str(rline)) role = RoleRequirement.role_yaml_parse(rline.strip()) roles_left.append(GalaxyRole(self.galaxy, **role)) f.close() except (IOError, OSError) as e: raise AnsibleError('Unable to open %s: %s' % (role_file, str(e))) else: # roles were specified directly, so we'll just go out grab them # (and their dependencies, unless the user doesn't want us to). for rname in self.args: role = RoleRequirement.role_yaml_parse(rname.strip()) roles_left.append(GalaxyRole(self.galaxy, **role)) for role in roles_left: # only process roles in roles files when names matches if given if role_file and self.args and role.name not in self.args: display.vvv('Skipping role %s' % role.name) continue display.vvv('Processing role %s ' % role.name) # query the galaxy API for the role data if role.install_info is not None: if role.install_info['version'] != role.version or force: if force: display.display('- changing role %s from %s to %s' % (role.name, role.install_info['version'], role.version or "unspecified")) role.remove() else: display.warning('- %s (%s) is already installed - use --force to change version to %s' % (role.name, role.install_info['version'], role.version or "unspecified")) continue else: if not force: display.display('- %s is already installed, skipping.' % str(role)) continue try: installed = role.install() except AnsibleError as e: display.warning("- %s was NOT installed successfully: %s " % (role.name, str(e))) self.exit_without_ignore() continue # install dependencies, if we want them if not no_deps and installed: role_dependencies = role.metadata.get('dependencies') or [] for dep in role_dependencies: display.debug('Installing dep %s' % dep) dep_req = RoleRequirement() dep_info = dep_req.role_yaml_parse(dep) dep_role = GalaxyRole(self.galaxy, **dep_info) if '.' not in dep_role.name and '.' not in dep_role.src and dep_role.scm is None: # we know we can skip this, as it's not going to # be found on galaxy.ansible.com continue if dep_role.install_info is None: if dep_role not in roles_left: display.display('- adding dependency: %s' % str(dep_role)) roles_left.append(dep_role) else: display.display('- dependency %s already pending installation.' % dep_role.name) else: if dep_role.install_info['version'] != dep_role.version: display.warning('- dependency %s from role %s differs from already installed version (%s), skipping' % (str(dep_role), role.name, dep_role.install_info['version'])) else: display.display('- dependency %s is already installed, skipping.' % dep_role.name) if not installed: display.warning("- %s was NOT installed successfully." % role.name) self.exit_without_ignore() return 0 def execute_remove(self): """ removes the list of roles passed as arguments from the local system. """ if len(self.args) == 0: raise AnsibleOptionsError('- you must specify at least one role to remove.') for role_name in self.args: role = GalaxyRole(self.galaxy, role_name) try: if role.remove(): display.display('- successfully removed %s' % role_name) else: display.display('- %s is not installed, skipping.' % role_name) except Exception as e: raise AnsibleError("Failed to remove role %s: %s" % (role_name, str(e))) return 0 def execute_list(self): """ lists the roles installed on the local system or matches a single role passed as an argument. """ if len(self.args) > 1: raise AnsibleOptionsError("- please specify only one role to list, or specify no roles to see a full list") if len(self.args) == 1: # show only the request role, if it exists name = self.args.pop() gr = GalaxyRole(self.galaxy, name) if gr.metadata: install_info = gr.install_info version = None if install_info: version = install_info.get("version", None) if not version: version = "(unknown version)" # show some more info about single roles here display.display("- %s, %s" % (name, version)) else: display.display("- the role %s was not found" % name) else: # show all valid roles in the roles_path directory roles_path = self.options.roles_path for path in roles_path: role_path = os.path.expanduser(path) if not os.path.exists(role_path): raise AnsibleOptionsError("- the path %s does not exist. Please specify a valid path with --roles-path" % role_path) elif not os.path.isdir(role_path): raise AnsibleOptionsError("- %s exists, but it is not a directory. Please specify a valid path with --roles-path" % role_path) path_files = os.listdir(role_path) for path_file in path_files: gr = GalaxyRole(self.galaxy, path_file) if gr.metadata: install_info = gr.install_info version = None if install_info: version = install_info.get("version", None) if not version: version = "(unknown version)" display.display("- %s, %s" % (path_file, version)) return 0 def execute_search(self): ''' searches for roles on the Ansible Galaxy server''' page_size = 1000 search = None if len(self.args): terms = [] for i in range(len(self.args)): terms.append(self.args.pop()) search = '+'.join(terms[::-1]) if not search and not self.options.platforms and not self.options.galaxy_tags and not self.options.author: raise AnsibleError("Invalid query. At least one search term, platform, galaxy tag or author must be provided.") response = self.api.search_roles(search, platforms=self.options.platforms, tags=self.options.galaxy_tags, author=self.options.author, page_size=page_size) if response['count'] == 0: display.display("No roles match your search.", color=C.COLOR_ERROR) return True data = [u''] if response['count'] > page_size: data.append(u"Found %d roles matching your search. Showing first %s." % (response['count'], page_size)) else: data.append(u"Found %d roles matching your search:" % response['count']) max_len = [] for role in response['results']: max_len.append(len(role['username'] + '.' + role['name'])) name_len = max(max_len) format_str = u" %%-%ds %%s" % name_len data.append(u'') data.append(format_str % (u"Name", u"Description")) data.append(format_str % (u"----", u"-----------")) for role in response['results']: data.append(format_str % (u'%s.%s' % (role['username'], role['name']), role['description'])) data = u'\n'.join(data) self.pager(data) return True def execute_login(self): """ verify user's identify via Github and retrieve an auth token from Ansible Galaxy. """ # Authenticate with github and retrieve a token if self.options.token is None: login = GalaxyLogin(self.galaxy) github_token = login.create_github_token() else: github_token = self.options.token galaxy_response = self.api.authenticate(github_token) if self.options.token is None: # Remove the token we created login.remove_github_token() # Store the Galaxy token token = GalaxyToken() token.set(galaxy_response['token']) display.display("Successfully logged into Galaxy as %s" % galaxy_response['username']) return 0 def execute_import(self): """ used to import a role into Ansible Galaxy """ colors = { 'INFO': 'normal', 'WARNING': C.COLOR_WARN, 'ERROR': C.COLOR_ERROR, 'SUCCESS': C.COLOR_OK, 'FAILED': C.COLOR_ERROR, } if len(self.args) < 2: raise AnsibleError("Expected a github_username and github_repository. Use --help.") github_repo = to_text(self.args.pop(), errors='surrogate_or_strict') github_user = to_text(self.args.pop(), errors='surrogate_or_strict') if self.options.check_status: task = self.api.get_import_task(github_user=github_user, github_repo=github_repo) else: # Submit an import request task = self.api.create_import_task(github_user, github_repo, reference=self.options.reference, role_name=self.options.role_name) if len(task) > 1: # found multiple roles associated with github_user/github_repo display.display("WARNING: More than one Galaxy role associated with Github repo %s/%s." % (github_user, github_repo), color='yellow') display.display("The following Galaxy roles are being updated:" + u'\n', color=C.COLOR_CHANGED) for t in task: display.display('%s.%s' % (t['summary_fields']['role']['namespace'], t['summary_fields']['role']['name']), color=C.COLOR_CHANGED) display.display(u'\nTo properly namespace this role, remove each of the above and re-import %s/%s from scratch' % (github_user, github_repo), color=C.COLOR_CHANGED) return 0 # found a single role as expected display.display("Successfully submitted import request %d" % task[0]['id']) if not self.options.wait: display.display("Role name: %s" % task[0]['summary_fields']['role']['name']) display.display("Repo: %s/%s" % (task[0]['github_user'], task[0]['github_repo'])) if self.options.check_status or self.options.wait: # Get the status of the import msg_list = [] finished = False while not finished: task = self.api.get_import_task(task_id=task[0]['id']) for msg in task[0]['summary_fields']['task_messages']: if msg['id'] not in msg_list: display.display(msg['message_text'], color=colors[msg['message_type']]) msg_list.append(msg['id']) if task[0]['state'] in ['SUCCESS', 'FAILED']: finished = True else: time.sleep(10) return 0 def execute_setup(self): """ Setup an integration from Github or Travis for Ansible Galaxy roles""" if self.options.setup_list: # List existing integration secrets secrets = self.api.list_secrets() if len(secrets) == 0: # None found display.display("No integrations found.") return 0 display.display(u'\n' + "ID Source Repo", color=C.COLOR_OK) display.display("---------- ---------- ----------", color=C.COLOR_OK) for secret in secrets: display.display("%-10s %-10s %s/%s" % (secret['id'], secret['source'], secret['github_user'], secret['github_repo']), color=C.COLOR_OK) return 0 if self.options.remove_id: # Remove a secret self.api.remove_secret(self.options.remove_id) display.display("Secret removed. Integrations using this secret will not longer work.", color=C.COLOR_OK) return 0 if len(self.args) < 4: raise AnsibleError("Missing one or more arguments. Expecting: source github_user github_repo secret") return 0 secret = self.args.pop() github_repo = self.args.pop() github_user = self.args.pop() source = self.args.pop() resp = self.api.add_secret(source, github_user, github_repo, secret) display.display("Added integration for %s %s/%s" % (resp['source'], resp['github_user'], resp['github_repo'])) return 0 def execute_delete(self): """ Delete a role from Ansible Galaxy. """ if len(self.args) < 2: raise AnsibleError("Missing one or more arguments. Expected: github_user github_repo") github_repo = self.args.pop() github_user = self.args.pop() resp = self.api.delete_role(github_user, github_repo) if len(resp['deleted_roles']) > 1: display.display("Deleted the following roles:") display.display("ID User Name") display.display("------ --------------- ----------") for role in resp['deleted_roles']: display.display("%-8s %-15s %s" % (role.id, role.namespace, role.name)) display.display(resp['status']) return True
nrwahl2/ansible
lib/ansible/cli/galaxy.py
Python
gpl-3.0
31,733
[ "Galaxy" ]
c93a0ab7bd8719b11996071d2aad3933ccca7c88e8cec1de93d6ff5937c8d9ef
#!/usr/bin/python import json import os import random import unittest import numpy as np from pymatgen.analysis.structure_matcher import StructureMatcher from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.core.surface import ( ReconstructionGenerator, Slab, SlabGenerator, generate_all_slabs, get_d, get_slab_regions, get_symmetrically_distinct_miller_indices, get_symmetrically_equivalent_miller_indices, miller_index_from_sites, ) from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.symmetry.groups import SpaceGroup from pymatgen.util.testing import PymatgenTest def get_path(path_str): cwd = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(cwd, "..", "..", "..", "test_files", "surface_tests", path_str) return path class SlabTest(PymatgenTest): def setUp(self): zno1 = Structure.from_file(get_path("ZnO-wz.cif"), primitive=False) zno55 = SlabGenerator(zno1, [1, 0, 0], 5, 5, lll_reduce=False, center_slab=False).get_slab() Ti = Structure( Lattice.hexagonal(4.6, 2.82), ["Ti", "Ti", "Ti"], [ [0.000000, 0.000000, 0.000000], [0.333333, 0.666667, 0.500000], [0.666667, 0.333333, 0.500000], ], ) Ag_fcc = Structure( Lattice.cubic(4.06), ["Ag", "Ag", "Ag", "Ag"], [ [0.000000, 0.000000, 0.000000], [0.000000, 0.500000, 0.500000], [0.500000, 0.000000, 0.500000], [0.500000, 0.500000, 0.000000], ], ) m = [[3.913449, 0, 0], [0, 3.913449, 0], [0, 0, 5.842644]] latt = Lattice(m) fcoords = [[0.5, 0, 0.222518], [0, 0.5, 0.777482], [0, 0, 0], [0, 0, 0.5], [0.5, 0.5, 0]] non_laue = Structure(latt, ["Nb", "Nb", "N", "N", "N"], fcoords) self.ti = Ti self.agfcc = Ag_fcc self.zno1 = zno1 self.zno55 = zno55 self.nonlaue = non_laue self.h = Structure(Lattice.cubic(3), ["H"], [[0, 0, 0]]) self.libcc = Structure(Lattice.cubic(3.51004), ["Li", "Li"], [[0, 0, 0], [0.5, 0.5, 0.5]]) def test_init(self): zno_slab = Slab( self.zno55.lattice, self.zno55.species, self.zno55.frac_coords, self.zno55.miller_index, self.zno55.oriented_unit_cell, 0, self.zno55.scale_factor, ) m = self.zno55.lattice.matrix area = np.linalg.norm(np.cross(m[0], m[1])) self.assertAlmostEqual(zno_slab.surface_area, area) self.assertEqual(zno_slab.lattice.parameters, self.zno55.lattice.parameters) self.assertEqual(zno_slab.oriented_unit_cell.composition, self.zno1.composition) self.assertEqual(len(zno_slab), 8) # check reorient_lattice. get a slab not oriented and check that orientation # works even with cartesian coordinates. zno_not_or = SlabGenerator( self.zno1, [1, 0, 0], 5, 5, lll_reduce=False, center_slab=False, reorient_lattice=False, ).get_slab() zno_slab_cart = Slab( zno_not_or.lattice, zno_not_or.species, zno_not_or.cart_coords, zno_not_or.miller_index, zno_not_or.oriented_unit_cell, 0, zno_not_or.scale_factor, coords_are_cartesian=True, reorient_lattice=True, ) self.assertArrayAlmostEqual(zno_slab.frac_coords, zno_slab_cart.frac_coords) c = zno_slab_cart.lattice.matrix[2] self.assertArrayAlmostEqual([0, 0, np.linalg.norm(c)], c) def test_add_adsorbate_atom(self): zno_slab = Slab( self.zno55.lattice, self.zno55.species, self.zno55.frac_coords, self.zno55.miller_index, self.zno55.oriented_unit_cell, 0, self.zno55.scale_factor, ) zno_slab.add_adsorbate_atom([1], "H", 1) self.assertEqual(len(zno_slab), 9) self.assertEqual(str(zno_slab[8].specie), "H") self.assertAlmostEqual(zno_slab.get_distance(1, 8), 1.0) self.assertTrue(zno_slab[8].c > zno_slab[0].c) m = self.zno55.lattice.matrix area = np.linalg.norm(np.cross(m[0], m[1])) self.assertAlmostEqual(zno_slab.surface_area, area) self.assertEqual(zno_slab.lattice.parameters, self.zno55.lattice.parameters) def test_get_sorted_structure(self): species = [str(site.specie) for site in self.zno55.get_sorted_structure()] self.assertEqual(species, ["Zn2+"] * 4 + ["O2-"] * 4) def test_methods(self): # Test various structure methods self.zno55.get_primitive_structure() def test_as_from_dict(self): d = self.zno55.as_dict() obj = Slab.from_dict(d) self.assertEqual(obj.miller_index, (1, 0, 0)) def test_dipole_and_is_polar(self): self.assertArrayAlmostEqual(self.zno55.dipole, [0, 0, 0]) self.assertFalse(self.zno55.is_polar()) cscl = self.get_structure("CsCl") cscl.add_oxidation_state_by_element({"Cs": 1, "Cl": -1}) slab = SlabGenerator( cscl, [1, 0, 0], 5, 5, reorient_lattice=False, lll_reduce=False, center_slab=False, ).get_slab() self.assertArrayAlmostEqual(slab.dipole, [-4.209, 0, 0]) self.assertTrue(slab.is_polar()) def test_surface_sites_and_symmetry(self): # test if surfaces are equivalent by using # Laue symmetry and surface site equivalence for bool in [True, False]: # We will also set the slab to be centered and # off centered in order to test the center of mass slabgen = SlabGenerator(self.agfcc, (3, 1, 0), 10, 10, center_slab=bool) slab = slabgen.get_slabs()[0] surf_sites_dict = slab.get_surface_sites() self.assertEqual(len(surf_sites_dict["top"]), len(surf_sites_dict["bottom"])) total_surf_sites = sum([len(surf_sites_dict[key]) for key in surf_sites_dict.keys()]) self.assertTrue(slab.is_symmetric()) self.assertEqual(total_surf_sites / 2, 4) # Test if the ratio of surface sites per area is # constant, ie are the surface energies the same r1 = total_surf_sites / (2 * slab.surface_area) slabgen = SlabGenerator(self.agfcc, (3, 1, 0), 10, 10, primitive=False) slab = slabgen.get_slabs()[0] surf_sites_dict = slab.get_surface_sites() total_surf_sites = sum([len(surf_sites_dict[key]) for key in surf_sites_dict.keys()]) r2 = total_surf_sites / (2 * slab.surface_area) self.assertArrayAlmostEqual(r1, r2) def test_symmetrization(self): # Restricted to primitive_elemental materials due to the risk of # broken stoichiometry. For compound materials, use is_polar() # Get all slabs for P6/mmm Ti and Fm-3m Ag up to index of 2 all_Ti_slabs = generate_all_slabs( self.ti, 2, 10, 10, bonds=None, tol=1e-3, max_broken_bonds=0, lll_reduce=False, center_slab=False, primitive=True, max_normal_search=2, symmetrize=True, ) all_Ag_fcc_slabs = generate_all_slabs( self.agfcc, 2, 10, 10, bonds=None, tol=1e-3, max_broken_bonds=0, lll_reduce=False, center_slab=False, primitive=True, max_normal_search=2, symmetrize=True, ) all_slabs = [all_Ti_slabs, all_Ag_fcc_slabs] for i, slabs in enumerate(all_slabs): assymetric_count = 0 symmetric_count = 0 for i, slab in enumerate(slabs): sg = SpacegroupAnalyzer(slab) # Check if a slab is symmetric if not sg.is_laue(): assymetric_count += 1 else: symmetric_count += 1 # Check if slabs are all symmetric self.assertEqual(assymetric_count, 0) self.assertEqual(symmetric_count, len(slabs)) # Check if we can generate symmetric slabs from bulk with no inversion all_non_laue_slabs = generate_all_slabs(self.nonlaue, 1, 15, 15, symmetrize=True) self.assertTrue(len(all_non_laue_slabs) > 0) def test_get_symmetric_sites(self): # Check to see if we get an equivalent site on one # surface if we add a new site to the other surface all_Ti_slabs = generate_all_slabs( self.ti, 2, 10, 10, bonds=None, tol=1e-3, max_broken_bonds=0, lll_reduce=False, center_slab=False, primitive=True, max_normal_search=2, symmetrize=True, ) for slab in all_Ti_slabs: sorted_sites = sorted(slab, key=lambda site: site.frac_coords[2]) site = sorted_sites[-1] point = np.array(site.frac_coords) point[2] = point[2] + 0.1 point2 = slab.get_symmetric_site(point) slab.append("O", point) slab.append("O", point2) # Check if slab is all symmetric sg = SpacegroupAnalyzer(slab) self.assertTrue(sg.is_laue()) def test_oriented_unit_cell(self): # Check to see if we get the fully reduced oriented unit # cell. This will also ensure that the constrain_latt # parameter for get_primitive_structure is working properly def surface_area(s): m = s.lattice.matrix return np.linalg.norm(np.cross(m[0], m[1])) all_slabs = generate_all_slabs(self.agfcc, 2, 10, 10, max_normal_search=3) for slab in all_slabs: ouc = slab.oriented_unit_cell self.assertAlmostEqual(surface_area(slab), surface_area(ouc)) self.assertGreaterEqual(len(slab), len(ouc)) def test_get_slab_regions(self): # If a slab layer in the slab cell is not completely inside # the cell (noncontiguous), check that get_slab_regions will # be able to identify where the slab layers are located s = self.get_structure("LiFePO4") slabgen = SlabGenerator(s, (0, 0, 1), 15, 15) slab = slabgen.get_slabs()[0] slab.translate_sites([i for i, site in enumerate(slab)], [0, 0, -0.25]) bottom_c, top_c = [], [] for site in slab: if site.frac_coords[2] < 0.5: bottom_c.append(site.frac_coords[2]) else: top_c.append(site.frac_coords[2]) ranges = get_slab_regions(slab) self.assertEqual(tuple(ranges[0]), (0, max(bottom_c))) self.assertEqual(tuple(ranges[1]), (min(top_c), 1)) def test_as_dict(self): slabs = generate_all_slabs( self.ti, 1, 10, 10, bonds=None, tol=1e-3, max_broken_bonds=0, lll_reduce=False, center_slab=False, primitive=True, ) slab = slabs[0] s = json.dumps(slab.as_dict()) d = json.loads(s) self.assertEqual(slab, Slab.from_dict(d)) # test initialising with a list scale_factor slab = Slab( self.zno55.lattice, self.zno55.species, self.zno55.frac_coords, self.zno55.miller_index, self.zno55.oriented_unit_cell, 0, self.zno55.scale_factor.tolist(), ) s = json.dumps(slab.as_dict()) d = json.loads(s) self.assertEqual(slab, Slab.from_dict(d)) class SlabGeneratorTest(PymatgenTest): def setUp(self): lattice = Lattice.cubic(3.010) frac_coords = [ [0.00000, 0.00000, 0.00000], [0.00000, 0.50000, 0.50000], [0.50000, 0.00000, 0.50000], [0.50000, 0.50000, 0.00000], [0.50000, 0.00000, 0.00000], [0.50000, 0.50000, 0.50000], [0.00000, 0.00000, 0.50000], [0.00000, 0.50000, 0.00000], ] species = ["Mg", "Mg", "Mg", "Mg", "O", "O", "O", "O"] self.MgO = Structure(lattice, species, frac_coords) self.MgO.add_oxidation_state_by_element({"Mg": 2, "O": -6}) lattice_Dy = Lattice.hexagonal(3.58, 25.61) frac_coords_Dy = [ [0.00000, 0.00000, 0.00000], [0.66667, 0.33333, 0.11133], [0.00000, 0.00000, 0.222], [0.66667, 0.33333, 0.33333], [0.33333, 0.66666, 0.44467], [0.66667, 0.33333, 0.55533], [0.33333, 0.66667, 0.66667], [0.00000, 0.00000, 0.778], [0.33333, 0.66667, 0.88867], ] species_Dy = ["Dy", "Dy", "Dy", "Dy", "Dy", "Dy", "Dy", "Dy", "Dy"] self.Dy = Structure(lattice_Dy, species_Dy, frac_coords_Dy) def test_get_slab(self): s = self.get_structure("LiFePO4") gen = SlabGenerator(s, [0, 0, 1], 10, 10) s = gen.get_slab(0.25) self.assertAlmostEqual(s.lattice.abc[2], 20.820740000000001) fcc = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]]) gen = SlabGenerator(fcc, [1, 1, 1], 10, 10, max_normal_search=1) slab = gen.get_slab() self.assertEqual(len(slab), 6) gen = SlabGenerator(fcc, [1, 1, 1], 10, 10, primitive=False, max_normal_search=1) slab_non_prim = gen.get_slab() self.assertEqual(len(slab_non_prim), len(slab) * 4) # Some randomized testing of cell vectors for i in range(1, 231): i = random.randint(1, 230) sg = SpaceGroup.from_int_number(i) if sg.crystal_system == "hexagonal" or ( sg.crystal_system == "trigonal" and ( sg.symbol.endswith("H") or sg.int_number in [ 143, 144, 145, 147, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, 162, 163, 164, 165, ] ) ): latt = Lattice.hexagonal(5, 10) else: # Cubic lattice is compatible with all other space groups. latt = Lattice.cubic(5) s = Structure.from_spacegroup(i, latt, ["H"], [[0, 0, 0]]) miller = (0, 0, 0) while miller == (0, 0, 0): miller = ( random.randint(0, 6), random.randint(0, 6), random.randint(0, 6), ) gen = SlabGenerator(s, miller, 10, 10) a, b, c = gen.oriented_unit_cell.lattice.matrix self.assertAlmostEqual(np.dot(a, gen._normal), 0) self.assertAlmostEqual(np.dot(b, gen._normal), 0) def test_normal_search(self): fcc = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]]) for miller in [(1, 0, 0), (1, 1, 0), (1, 1, 1), (2, 1, 1)]: gen = SlabGenerator(fcc, miller, 10, 10) gen_normal = SlabGenerator(fcc, miller, 10, 10, max_normal_search=max(miller)) slab = gen_normal.get_slab() self.assertAlmostEqual(slab.lattice.alpha, 90) self.assertAlmostEqual(slab.lattice.beta, 90) self.assertGreaterEqual(len(gen_normal.oriented_unit_cell), len(gen.oriented_unit_cell)) graphite = self.get_structure("Graphite") for miller in [(1, 0, 0), (1, 1, 0), (0, 0, 1), (2, 1, 1)]: gen = SlabGenerator(graphite, miller, 10, 10) gen_normal = SlabGenerator(graphite, miller, 10, 10, max_normal_search=max(miller)) self.assertGreaterEqual(len(gen_normal.oriented_unit_cell), len(gen.oriented_unit_cell)) sc = Structure( Lattice.hexagonal(3.32, 5.15), ["Sc", "Sc"], [[1 / 3, 2 / 3, 0.25], [2 / 3, 1 / 3, 0.75]], ) gen = SlabGenerator(sc, (1, 1, 1), 10, 10, max_normal_search=1) self.assertAlmostEqual(gen.oriented_unit_cell.lattice.angles[1], 90) def test_get_slabs(self): gen = SlabGenerator(self.get_structure("CsCl"), [0, 0, 1], 10, 10) # Test orthogonality of some internal variables. a, b, c = gen.oriented_unit_cell.lattice.matrix self.assertAlmostEqual(np.dot(a, gen._normal), 0) self.assertAlmostEqual(np.dot(b, gen._normal), 0) self.assertEqual(len(gen.get_slabs()), 1) s = self.get_structure("LiFePO4") gen = SlabGenerator(s, [0, 0, 1], 10, 10) self.assertEqual(len(gen.get_slabs()), 5) self.assertEqual(len(gen.get_slabs(bonds={("P", "O"): 3})), 2) # There are no slabs in LFP that does not break either P-O or Fe-O # bonds for a miller index of [0, 0, 1]. self.assertEqual(len(gen.get_slabs(bonds={("P", "O"): 3, ("Fe", "O"): 3})), 0) # If we allow some broken bonds, there are a few slabs. self.assertEqual( len(gen.get_slabs(bonds={("P", "O"): 3, ("Fe", "O"): 3}, max_broken_bonds=2)), 2, ) # At this threshold, only the origin and center Li results in # clustering. All other sites are non-clustered. So the of # slabs is of sites in LiFePO4 unit cell - 2 + 1. self.assertEqual(len(gen.get_slabs(tol=1e-4, ftol=1e-4)), 15) LiCoO2 = Structure.from_file(get_path("icsd_LiCoO2.cif"), primitive=False) gen = SlabGenerator(LiCoO2, [0, 0, 1], 10, 10) lco = gen.get_slabs(bonds={("Co", "O"): 3}) self.assertEqual(len(lco), 1) a, b, c = gen.oriented_unit_cell.lattice.matrix self.assertAlmostEqual(np.dot(a, gen._normal), 0) self.assertAlmostEqual(np.dot(b, gen._normal), 0) scc = Structure.from_spacegroup("Pm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]]) gen = SlabGenerator(scc, [0, 0, 1], 10, 10) slabs = gen.get_slabs() self.assertEqual(len(slabs), 1) gen = SlabGenerator(scc, [1, 1, 1], 10, 10, max_normal_search=1) slabs = gen.get_slabs() self.assertEqual(len(slabs), 1) # Test whether using units of hkl planes instead of Angstroms for # min_slab_size and min_vac_size will give us the same number of atoms natoms = [] for a in [1, 1.4, 2.5, 3.6]: s = Structure.from_spacegroup("Im-3m", Lattice.cubic(a), ["Fe"], [[0, 0, 0]]) slabgen = SlabGenerator(s, (1, 1, 1), 10, 10, in_unit_planes=True, max_normal_search=2) natoms.append(len(slabgen.get_slab())) n = natoms[0] for i in natoms: self.assertEqual(n, i) def test_triclinic_TeI(self): # Test case for a triclinic structure of TeI. Only these three # Miller indices are used because it is easier to identify which # atoms should be in a surface together. The closeness of the sites # in other Miller indices can cause some ambiguity when choosing a # higher tolerance. numb_slabs = {(0, 0, 1): 5, (0, 1, 0): 3, (1, 0, 0): 7} TeI = Structure.from_file(get_path("icsd_TeI.cif"), primitive=False) for k, v in numb_slabs.items(): trclnc_TeI = SlabGenerator(TeI, k, 10, 10) TeI_slabs = trclnc_TeI.get_slabs() self.assertEqual(v, len(TeI_slabs)) def test_get_orthogonal_c_slab(self): TeI = Structure.from_file(get_path("icsd_TeI.cif"), primitive=False) trclnc_TeI = SlabGenerator(TeI, (0, 0, 1), 10, 10) TeI_slabs = trclnc_TeI.get_slabs() slab = TeI_slabs[0] norm_slab = slab.get_orthogonal_c_slab() self.assertAlmostEqual(norm_slab.lattice.angles[0], 90) self.assertAlmostEqual(norm_slab.lattice.angles[1], 90) def test_get_orthogonal_c_slab_site_props(self): TeI = Structure.from_file(get_path("icsd_TeI.cif"), primitive=False) trclnc_TeI = SlabGenerator(TeI, (0, 0, 1), 10, 10) TeI_slabs = trclnc_TeI.get_slabs() slab = TeI_slabs[0] # Add site property to slab sd_list = [[True, True, True] for site in slab.sites] new_sp = slab.site_properties new_sp["selective_dynamics"] = sd_list slab_with_site_props = slab.copy(site_properties=new_sp) # Get orthogonal slab norm_slab = slab_with_site_props.get_orthogonal_c_slab() # Check if site properties is consistent (or kept) self.assertEqual(slab_with_site_props.site_properties, norm_slab.site_properties) def test_get_tasker2_slabs(self): # The uneven distribution of ions on the (111) facets of Halite # type slabs are typical examples of Tasker 3 structures. We # will test this algo to generate a Tasker 2 structure instead slabgen = SlabGenerator(self.MgO, (1, 1, 1), 10, 10, max_normal_search=1) # We generate the Tasker 3 structure first slab = slabgen.get_slabs()[0] self.assertFalse(slab.is_symmetric()) self.assertTrue(slab.is_polar()) # Now to generate the Tasker 2 structure, we must # ensure there are enough ions on top to move around slab.make_supercell([2, 1, 1]) slabs = slab.get_tasker2_slabs() # Check if our Tasker 2 slab is nonpolar and symmetric for slab in slabs: self.assertTrue(slab.is_symmetric()) self.assertFalse(slab.is_polar()) def test_nonstoichiometric_symmetrized_slab(self): # For the (111) halite slab, sometimes a nonstoichiometric # system is preferred over the stoichiometric Tasker 2. slabgen = SlabGenerator(self.MgO, (1, 1, 1), 10, 10, max_normal_search=1) slabs = slabgen.get_slabs(symmetrize=True) # We should end up with two terminations, one with # an Mg rich surface and another O rich surface self.assertEqual(len(slabs), 2) for slab in slabs: self.assertTrue(slab.is_symmetric()) # For a low symmetry primitive_elemental system such as # R-3m, there should be some nonsymmetric slabs # without using nonstoichiometric_symmetrized_slab slabs = generate_all_slabs(self.Dy, 1, 30, 30, center_slab=True, symmetrize=True) for s in slabs: self.assertTrue(s.is_symmetric()) self.assertGreater(len(s), len(self.Dy)) def test_move_to_other_side(self): # Tests to see if sites are added to opposite side s = self.get_structure("LiFePO4") slabgen = SlabGenerator(s, (0, 0, 1), 10, 10, center_slab=True) slab = slabgen.get_slab() surface_sites = slab.get_surface_sites() # check if top sites are moved to the bottom top_index = [ss[1] for ss in surface_sites["top"]] slab = slabgen.move_to_other_side(slab, top_index) all_bottom = [slab[i].frac_coords[2] < slab.center_of_mass[2] for i in top_index] self.assertTrue(all(all_bottom)) # check if bottom sites are moved to the top bottom_index = [ss[1] for ss in surface_sites["bottom"]] slab = slabgen.move_to_other_side(slab, bottom_index) all_top = [slab[i].frac_coords[2] > slab.center_of_mass[2] for i in bottom_index] self.assertTrue(all(all_top)) def test_bonds_broken(self): # Querying the Materials Project database for Si s = self.get_structure("Si") # Conventional unit cell is supplied to ensure miller indices # correspond to usual crystallographic definitions conv_bulk = SpacegroupAnalyzer(s).get_conventional_standard_structure() slabgen = SlabGenerator(conv_bulk, [1, 1, 1], 10, 10, center_slab=True) # Setting a generous estimate for max_broken_bonds # so that all terminations are generated. These slabs # are ordered by ascending number of bonds broken # which is assigned to Slab.energy slabs = slabgen.get_slabs(bonds={("Si", "Si"): 2.40}, max_broken_bonds=30) # Looking at the two slabs generated in VESTA, we # expect 2 and 6 bonds broken so we check for this. # Number of broken bonds are floats due to primitive # flag check and subsequent transformation of slabs. self.assertTrue(slabs[0].energy, 2.0) self.assertTrue(slabs[1].energy, 6.0) class ReconstructionGeneratorTests(PymatgenTest): def setUp(self): l = Lattice.cubic(3.51) species = ["Ni"] coords = [[0, 0, 0]] self.Ni = Structure.from_spacegroup("Fm-3m", l, species, coords) l = Lattice.cubic(2.819000) species = ["Fe"] coords = [[0, 0, 0]] self.Fe = Structure.from_spacegroup("Im-3m", l, species, coords) self.Si = Structure.from_spacegroup("Fd-3m", Lattice.cubic(5.430500), ["Si"], [(0, 0, 0.5)]) with open( os.path.join( os.path.abspath(os.path.dirname(__file__)), "..", "reconstructions_archive.json", ) ) as data_file: self.rec_archive = json.load(data_file) def test_build_slab(self): # First lets test a reconstruction where we only remove atoms recon = ReconstructionGenerator(self.Ni, 10, 10, "fcc_110_missing_row_1x2") slab = recon.get_unreconstructed_slabs()[0] recon_slab = recon.build_slabs()[0] self.assertTrue(recon_slab.reconstruction) self.assertEqual(len(slab), len(recon_slab) + 2) self.assertTrue(recon_slab.is_symmetric()) # Test if the ouc corresponds to the reconstructed slab recon_ouc = recon_slab.oriented_unit_cell ouc = slab.oriented_unit_cell self.assertEqual(ouc.lattice.b * 2, recon_ouc.lattice.b) self.assertEqual(len(ouc) * 2, len(recon_ouc)) # Test a reconstruction where we simply add atoms recon = ReconstructionGenerator(self.Ni, 10, 10, "fcc_111_adatom_t_1x1") slab = recon.get_unreconstructed_slabs()[0] recon_slab = recon.build_slabs()[0] self.assertEqual(len(slab), len(recon_slab) - 2) self.assertTrue(recon_slab.is_symmetric()) # If a slab references another slab, # make sure it is properly generated recon = ReconstructionGenerator(self.Ni, 10, 10, "fcc_111_adatom_ft_1x1") slab = recon.build_slabs()[0] self.assertTrue(slab.is_symmetric) # Test a reconstruction where it works on a specific # termination (Fd-3m (111)) recon = ReconstructionGenerator(self.Si, 10, 10, "diamond_111_1x2") slab = recon.get_unreconstructed_slabs()[0] recon_slab = recon.build_slabs()[0] self.assertEqual(len(slab), len(recon_slab) - 8) self.assertTrue(recon_slab.is_symmetric()) # Test a reconstruction where terminations give # different reconstructions with a non-primitive_elemental system def test_get_d(self): # Ensure that regardles of the size of the vacuum or slab # layer, the spacing between atomic layers should be the same recon = ReconstructionGenerator(self.Si, 10, 10, "diamond_100_2x1") recon2 = ReconstructionGenerator(self.Si, 20, 10, "diamond_100_2x1") s1 = recon.get_unreconstructed_slabs()[0] s2 = recon2.get_unreconstructed_slabs()[0] self.assertAlmostEqual(get_d(s1), get_d(s2)) @unittest.skip("This test relies on neighbor orders and is hard coded. Disable temporarily") def test_previous_reconstructions(self): # Test to see if we generated all reconstruction # types correctly and nothing changes m = StructureMatcher() for n in self.rec_archive.keys(): if "base_reconstruction" in self.rec_archive[n].keys(): arch = self.rec_archive[self.rec_archive[n]["base_reconstruction"]] sg = arch["spacegroup"]["symbol"] else: sg = self.rec_archive[n]["spacegroup"]["symbol"] if sg == "Fm-3m": rec = ReconstructionGenerator(self.Ni, 20, 20, n) el = self.Ni[0].species_string elif sg == "Im-3m": rec = ReconstructionGenerator(self.Fe, 20, 20, n) el = self.Fe[0].species_string elif sg == "Fd-3m": rec = ReconstructionGenerator(self.Si, 20, 20, n) el = self.Si[0].species_string slabs = rec.build_slabs() s = Structure.from_file(get_path(os.path.join("reconstructions", el + "_" + n + ".cif"))) self.assertTrue(any([len(m.group_structures([s, slab])) == 1 for slab in slabs])) class MillerIndexFinderTests(PymatgenTest): def setUp(self): self.cscl = Structure.from_spacegroup("Pm-3m", Lattice.cubic(4.2), ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]) self.Fe = Structure.from_spacegroup("Im-3m", Lattice.cubic(2.82), ["Fe"], [[0, 0, 0]]) mglatt = Lattice.from_parameters(3.2, 3.2, 5.13, 90, 90, 120) self.Mg = Structure(mglatt, ["Mg", "Mg"], [[1 / 3, 2 / 3, 1 / 4], [2 / 3, 1 / 3, 3 / 4]]) self.lifepo4 = self.get_structure("LiFePO4") self.tei = Structure.from_file(get_path("icsd_TeI.cif"), primitive=False) self.LiCoO2 = Structure.from_file(get_path("icsd_LiCoO2.cif"), primitive=False) self.p1 = Structure( Lattice.from_parameters(3, 4, 5, 31, 43, 50), ["H", "He"], [[0, 0, 0], [0.1, 0.2, 0.3]], ) self.graphite = self.get_structure("Graphite") self.trigBi = Structure( Lattice.from_parameters(3, 3, 10, 90, 90, 120), ["Bi", "Bi", "Bi", "Bi", "Bi", "Bi"], [ [0.3333, 0.6666, 0.39945113], [0.0000, 0.0000, 0.26721554], [0.0000, 0.0000, 0.73278446], [0.6666, 0.3333, 0.60054887], [0.6666, 0.3333, 0.06611779], [0.3333, 0.6666, 0.93388221], ], ) def test_get_symmetrically_distinct_miller_indices(self): # Tests to see if the function obtains the known number of unique slabs indices = get_symmetrically_distinct_miller_indices(self.cscl, 1) self.assertEqual(len(indices), 3) indices = get_symmetrically_distinct_miller_indices(self.cscl, 2) self.assertEqual(len(indices), 6) self.assertEqual(len(get_symmetrically_distinct_miller_indices(self.lifepo4, 1)), 7) # The TeI P-1 structure should have 13 unique millers (only inversion # symmetry eliminates pairs) indices = get_symmetrically_distinct_miller_indices(self.tei, 1) self.assertEqual(len(indices), 13) # P1 and P-1 should have the same # of miller indices since surfaces # always have inversion symmetry. indices = get_symmetrically_distinct_miller_indices(self.p1, 1) self.assertEqual(len(indices), 13) indices = get_symmetrically_distinct_miller_indices(self.graphite, 2) self.assertEqual(len(indices), 12) # Now try a trigonal system. indices = get_symmetrically_distinct_miller_indices(self.trigBi, 2, return_hkil=True) self.assertEqual(len(indices), 17) self.assertTrue(all([len(hkl) == 4 for hkl in indices])) def test_get_symmetrically_equivalent_miller_indices(self): # Tests to see if the function obtains all equivalent hkl for cubic (100) indices001 = [ (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, -1), (0, -1, 0), (-1, 0, 0), ] indices = get_symmetrically_equivalent_miller_indices(self.cscl, (1, 0, 0)) self.assertTrue(all([hkl in indices for hkl in indices001])) # Tests to see if it captures expanded Miller indices in the family e.g. (001) == (002) hcp_indices_100 = get_symmetrically_equivalent_miller_indices(self.Mg, (1, 0, 0)) hcp_indices_200 = get_symmetrically_equivalent_miller_indices(self.Mg, (2, 0, 0)) self.assertEqual(len(hcp_indices_100) * 2, len(hcp_indices_200)) self.assertEqual(len(hcp_indices_100), 6) self.assertTrue(all([len(hkl) == 4 for hkl in hcp_indices_100])) def test_generate_all_slabs(self): slabs = generate_all_slabs(self.cscl, 1, 10, 10) # Only three possible slabs, one each in (100), (110) and (111). self.assertEqual(len(slabs), 3) # make sure it generates reconstructions slabs = generate_all_slabs(self.Fe, 1, 10, 10, include_reconstructions=True) # Four possible slabs, (100), (110), (111) and the zigzag (100). self.assertEqual(len(slabs), 4) slabs = generate_all_slabs(self.cscl, 1, 10, 10, bonds={("Cs", "Cl"): 4}) # No slabs if we don't allow broken Cs-Cl self.assertEqual(len(slabs), 0) slabs = generate_all_slabs(self.cscl, 1, 10, 10, bonds={("Cs", "Cl"): 4}, max_broken_bonds=100) self.assertEqual(len(slabs), 3) slabs2 = generate_all_slabs(self.lifepo4, 1, 10, 10, bonds={("P", "O"): 3, ("Fe", "O"): 3}) self.assertEqual(len(slabs2), 0) # There should be only one possible stable surfaces, all of which are # in the (001) oriented unit cell slabs3 = generate_all_slabs(self.LiCoO2, 1, 10, 10, bonds={("Co", "O"): 3}) self.assertEqual(len(slabs3), 1) mill = (0, 0, 1) for s in slabs3: self.assertEqual(s.miller_index, mill) slabs1 = generate_all_slabs(self.lifepo4, 1, 10, 10, tol=0.1, bonds={("P", "O"): 3}) self.assertEqual(len(slabs1), 4) # Now we test this out for repair_broken_bonds() slabs1_repair = generate_all_slabs(self.lifepo4, 1, 10, 10, tol=0.1, bonds={("P", "O"): 3}, repair=True) self.assertGreater(len(slabs1_repair), len(slabs1)) # Lets see if there are no broken PO4 polyhedrons miller_list = get_symmetrically_distinct_miller_indices(self.lifepo4, 1) all_miller_list = [] for slab in slabs1_repair: hkl = tuple(slab.miller_index) if hkl not in all_miller_list: all_miller_list.append(hkl) broken = [] for site in slab: if site.species_string == "P": neighbors = slab.get_neighbors(site, 3) cn = 0 for nn in neighbors: cn += 1 if nn[0].species_string == "O" else 0 broken.append(cn != 4) self.assertFalse(any(broken)) # check if we were able to produce at least one # termination for each distinct Miller _index self.assertEqual(len(miller_list), len(all_miller_list)) def test_miller_index_from_sites(self): """Test surface miller index convenience function""" # test on a cubic system m = Lattice.cubic(1) s1 = np.array([0.5, -1.5, 3]) s2 = np.array([0.5, 3.0, -1.5]) s3 = np.array([2.5, 1.5, -4.0]) self.assertEqual(miller_index_from_sites(m, [s1, s2, s3]), (2, 1, 1)) # test casting from matrix to Lattice m = [[2.319, -4.01662582, 0.0], [2.319, 4.01662582, 0.0], [0.0, 0.0, 7.252]] s1 = np.array([2.319, 1.33887527, 6.3455]) s2 = np.array([1.1595, 0.66943764, 4.5325]) s3 = np.array([1.1595, 0.66943764, 0.9065]) hkl = miller_index_from_sites(m, [s1, s2, s3]) self.assertEqual(hkl, (2, -1, 0)) if __name__ == "__main__": unittest.main()
gmatteo/pymatgen
pymatgen/core/tests/test_surface.py
Python
mit
36,585
[ "pymatgen" ]
320e626957fbb79632b32926cfd119cef1d599e73def32baf237f2142dc1c29b
# Copyright (C) 2018 Henrique Pereira Coutada Miranda, Alejandro Molina Sanchez # All rights reserved. # # This file is part of yambopy # # import os import re import shutil from math import sqrt from qepy import qepyenv from .pseudo import get_pseudo_path from .tools import fortran_bool from .lattice import red_car, car_red class PwIn(object): """ Class to generate an manipulate Quantum Espresso input files Can be initialized either reading from a file or starting from a new file. This class is not meant to be comprehensive but a lightweight version capable of basic input/ouput of PW files. For a comprehensive class use the tools provoded by the AiiDa package: http://www.aiida.net/ Examples of use: To read a local file with name "mos2.in" .. code-block :: python qe = PwIn.from_file('mos2.scf') print qe To start a file from scratch .. code-block :: python qe = PwIn() qe.atoms = [['N',[ 0.0, 0.0,0.0]], ['B',[1./3,2./3,0.0]]] qe.atypes = {'B': [10.811, "B.pbe-mt_fhi.UPF"], 'N': [14.0067,"N.pbe-mt_fhi.UPF"]} qe.control['prefix'] = "'%s'"%prefix qe.control['verbosity'] = "'high'" qe.control['wf_collect'] = '.true.' qe.control['pseudo_dir'] = "'../pseudos/'" qe.system['celldm(1)'] = 4.7 qe.system['celldm(3)'] = layer_separation/qe.system['celldm(1)'] qe.system['ecutwfc'] = 60 qe.system['occupations'] = "'fixed'" qe.system['nat'] = 2 qe.system['ntyp'] = 2 qe.system['ibrav'] = 4 qe.kpoints = [6, 6, 1] qe.electrons['conv_thr'] = 1e-8 print qe Special care should be taken with string variables e.g. "'high'" """ _pw = 'pw.x' def __init__(self): """ TODO: specify the required parameters """ #kpoints self.ktype = "automatic" self.kpoints = [1,1,1] self.shiftk = [0,0,0] self.klist = [] #dictionaries self.control = dict(prefix="'pw'",wf_collect='.true.',verbosity="'high'") self.system = dict() self.electrons = dict(conv_thr=qepyenv.CONV_THR) self.ions = dict() self.cell = dict() self.atypes = dict() self.cell_units = 'bohr' self.atomic_pos_type = 'crystal' @classmethod def from_file(cls,filename): """ Initialize the QE structure from a file """ new = cls() with open(filename,"r") as f: new.file_lines = f.readlines() #set file lines new.store(new.control,"control") #read &control new.store(new.system,"system") #read &system new.store(new.electrons,"electrons") #read &electrons new.store(new.ions,"ions") #read &ions new.store(new.cell,"cell") #read &ions #read ATOMIC_SPECIES new.read_atomicspecies() #read ATOMIC_POSITIONS new.read_atoms() #read K_POINTS new.read_kpoints() #read CELL_PARAMETERS new.read_cell_parameters() return new @classmethod def from_structure_dict(cls,structure,kpoints=None,ecut=None,pseudo_dir='.',conv_thr=None): pwi = cls() pwi.set_structure(structure) if kpoints: pwi.set_kpoints(kpoints) if ecut: pwi.set_ecut(ecut) if pseudo_dir: pwi.pseudo_dir = pseudo_dir if conv_thr: pwi.electrons['conv_thr'] = conv_thr return pwi @property def natoms(self): return len(self.atoms) @property def ntyp(self): return int(self.system['ntyp']) @property def pseudo_dir(self): if 'pseudo_dir' not in self.control: return None return self.control['pseudo_dir'].replace("'",'') @pseudo_dir.setter def pseudo_dir(self,value): self.control['pseudo_dir'] = "'%s'"%value.replace("'",'') @property def prefix(self): return self.control['prefix'].replace("'",'') @prefix.setter def prefix(self,value): self.control['prefix'] = "'%s'"%value.replace("'",'') def set_ecut(self,ecut): self.system['ecutwfc'] = ecut def set_structure(self,structure): """ Set the structure from a structure dictionary Example: .. code-block :: python structure = dict(ibrav=4,celldm1=4.7,celldm3=12) atypes = dict(Si=[28.086,"Si.pbe-mt_fhi.UPF"]) atoms = [['N',[ 0.0, 0.0,0.5]], ['B',[1./3,2./3,0.5]]] BN = dict(structure=structure,atypes=atypes,atoms=atoms) pwi = PwIn() pwi.set_structure(BN) """ if 'lattice' in structure: self.set_lattice(**structure['lattice']) if 'atypes' in structure: self.set_atypes(structure['atypes']) if 'atoms' in structure: self.set_atoms(structure['atoms']) if 'occupations' in structure: self.set_occupations(structure['occupations']) def get_structure(self): """ Return an instance of a structure dictionary """ lattice = self.get_lattice() return dict(lattice=lattice,atypes=self.atypes,atoms=self.atoms) def change_cell_parameters(self): """ Convert the atomic postions to cartesian, change the lattice and convert the atomic positions to reduced """ raise NotImplementedError('TODO') def set_lattice(self,ibrav=None,celldm1=None,celldm2=None,celldm3=None, celldm4=None,celldm5=None,celldm6=None,cell_parameters=None): """Set the structure using the typical QE input variables""" if ibrav == 0 and cell_parameters is None: raise ValueError('ibrav = 0 implies that the cell_parameters variable is set') if cell_parameters: self.cell_parameters = cell_parameters if ibrav is not None: self.set_ibrav(ibrav) if celldm1 is not None: self.system['celldm(1)'] = celldm1 if celldm2 is not None: self.system['celldm(2)'] = celldm2 if celldm3 is not None: self.system['celldm(3)'] = celldm3 if celldm4 is not None: self.system['celldm(4)'] = celldm4 if celldm5 is not None: self.system['celldm(5)'] = celldm5 if celldm6 is not None: self.system['celldm(6)'] = celldm6 def get_lattice(self): lattice_dict = {} if 'ibrav' in self.system: lattice_dict['ibrav'] = self.ibrav if 'celldm(1)' in self.system: lattice_dict['celldm1'] = self.system['celldm(1)'] if 'celldm(2)' in self.system: lattice_dict['celldm2'] = self.system['celldm(2)'] if 'celldm(3)' in self.system: lattice_dict['celldm3'] = self.system['celldm(3)'] if 'celldm(4)' in self.system: lattice_dict['celldm4'] = self.system['celldm(4)'] if 'celldm(5)' in self.system: lattice_dict['celldm5'] = self.system['celldm(5)'] if 'celldm(6)' in self.system: lattice_dict['celldm6'] = self.system['celldm(6)'] if self.ibrav == 0: lattice_dict['cell_parameters'] = self.cell_parameters return lattice_dict def set_atoms(self,atoms,coordtype="reduced"): """ Set the atoms. Internally the atoms are always stored in reduced coordinates. The positions are written/read in the format from atomic_pos_type Arguments: coordtype: ("reduced"/"crystal") or cartesian Example: .. code-block :: python pwi = PwIn() pwi.set_atoms( [['Si',[0.125,0.125,0.125]], ['Si',[-.125,-.125,-.125]]]) """ self.system['nat'] = len(atoms) #TODO: add consistency check #convert the positions if needed if coordtype in ["reduced","crystal"]: self._atoms = atoms else: red_atoms = [] for atype,apos in atoms: red_atoms.append( [atype,car_red([apos],self.cell_parameters)[0]] ) self._atoms = red_atoms def set_atypes(self,atypes): """" Set the atom types. Example: .. code-block :: python pwi = PwIn() pwi.set_atypes({'Si': [28.086,"Si.pbe-mt_fhi.UPF"]}) """ self.system['ntyp'] = len(atypes) #TODO: add consistency check self.atypes = atypes def set_occupations(self,occupations): self.system['occupations'] = "'%s'" % occupations['occupations'] if 'smearing' in occupations: self.system['smearing'] = "'%s'" % occupations['smearing'] if 'degauss' in occupations: self.system['degauss'] = occupations['degauss'] if 'nbnd' in occupations: self.system['nbnd'] = occupations['nbnd'] def update_structure_from_xml(self,pwxml): """ Update input from an PW xml file. Useful for relaxation. """ structure_dict = pwxml.get_structure_dict() self.set_structure(structure_dict) def set_nscf(self,nbnd,nscf_kpoints=None,conv_thr=1e-8, diago_full_acc=True,force_symmorphic=True): """ set the calculation to be nscf """ self.control['calculation'] = "'nscf'" self.electrons['conv_thr'] = conv_thr self.system['nbnd'] = nbnd self.electrons['diago_full_acc'] = fortran_bool(diago_full_acc) self.system['force_symmorphic'] = fortran_bool(force_symmorphic) if nscf_kpoints: self.set_kpoints(nscf_kpoints) return self def set_bands(self,nbnd,path_kpoints=None,conv_thr=1e-8, diago_full_acc=True,force_symmorphic=True): """ set the calculation to be nscf """ self.control['calculation'] = "'bands'" self.electrons['conv_thr'] = conv_thr self.system['nbnd'] = nbnd self.electrons['diago_full_acc'] = fortran_bool(diago_full_acc) self.system['force_symmorphic'] = fortran_bool(force_symmorphic) self.ktype = 'crystal' if path_kpoints: self.set_path(path_kpoints) return self def set_relax(self,cell_dofree=None): """ set the calculation to be relax """ self.control['calculation'] = "'relax'" self.ions['ion_dynamics'] = "'bfgs'" if cell_dofree: self.control['calculation'] = "'vc-relax'" self.cell['cell_dynamics'] = "'bfgs'" self.cell['cell_dofree'] = "'%s'"%cell_dofree return self def set_spinorbit(self): self.system['lspinorb'] = '.true.' self.system['noncolin'] = '.true.' def set_spinpolarized(self): self.system['lspinorb'] = '.false.' self.system['noncolin'] = '.false.' self.system['nspin'] = 2 def set_magnetization(self,starting_magnetization): """ Set the starting_magnetization for a spin calculation. Args: starting_magnetization: a list with the starting magnetizations for each atomic type """ if starting_magnetization is None: return if len(starting_magnetization) != self.ntyp: raise ValueError('Invalid size for starting_magnetization') for atom_type,magnetization in enumerate(starting_magnetization): self.system['starting_magnetization(%d)' % (atom_type+1)] = magnetization def get_pseudos(self,destpath='.',pseudo_paths=[],verbose=0): """ Check if the pseudopotential files can be found in the specified path and copy them to destpath """ import qepy.data.pseudos as qe_pseudos pseudo_paths.append(os.path.dirname(qe_pseudos.__file__)) #use pseudo_dir from control if self.pseudo_dir: if os.path.isdir(self.pseudo_dir): pseudo_paths.append(self.pseudo_dir) ppstring = '\n'.join(pseudo_paths) if verbose: print('List of pseudo_paths:\n'+ppstring) #find all the pseudopotentials for atype,(mass,pseudo_filename) in self.atypes.items(): pseudo_filename = get_pseudo_path( pseudo_filename, pseudo_paths ) if pseudo_filename is None: err_msg = 'Pseudopotential %s not found in any of these paths:\n'%pseudo_filename raise ValueError(err_msg+ppstring) if verbose: print('cp %s %s'%(pseudo_filename,destpath)) shutil.copy(pseudo_filename,destpath) def set_kpoints(self,kpoints,shiftk=[0,0,0]): """Add some logic to set the kpoints mesh""" #sanity check if len(kpoints) != 3: raise ValueError('Wrong kpoints dimensions') self.kpoints = kpoints self.shiftk = shiftk def copy(self): """Return a copy of this instance""" import copy return copy.deepcopy(self) def read_atomicspecies(self): lines = iter(self.file_lines) #find ATOMIC_SPECIES keyword in file and read next line for line in lines: if "ATOMIC_SPECIES" in line: for i in range(self.ntyp): atype, mass, psp = next(lines).split() self.atypes[atype] = [mass,psp] def get_symmetry_spglib(self): """ get the symmetry group of this system using spglib """ import spglib lat, positions, atypes = self.get_cell() lat = np.array(lat) at = np.unique(atypes) an = dict(list(zip(at,list(range(len(at)))))) atypes = [an[a] for a in atypes] cell = (lat,positions,atypes) spacegroup = spglib.get_spacegroup(cell,symprec=1e-5) return spacegroup def get_masses(self): """ Get an array with the masses of all the atoms """ masses = [] for atom in self.atoms: atype = self.atypes[atom[0]] mass = float(atype[0]) masses.append(mass) return masses def set_path(self,path): self.klist = path.get_klist() def get_cell(self): """ Get the lattice parameters, postions of the atoms and chemical symbols """ cell = self.cell_parameters sym = [atom[0] for atom in self.atoms] pos = [atom[1] for atom in self.atoms] if self.atomic_pos_type == 'bohr': pos = car_red(pos,cell) return cell, pos, sym def set_atoms_string(self,string): """ set the atomic postions using string of the form Si 0.0 0.0 0.0 Si 0.5 0.5 0.5 """ atoms_str = [line.strip().split() for line in string.strip().split('\n')] atoms = [] for atype,x,y,z in atoms_str: atoms.append([atype,list(map(float,[x,y,z]))]) self.atoms = atoms def set_atoms_ase(self,atoms): """ set the atomic postions using a Atoms datastructure from ase """ # we will write down the cell parameters explicitly self.ibrav = 0 self.cell_parameters = atoms.get_cell() self.atoms = list(zip(atoms.get_chemical_symbols(),atoms.get_scaled_positions())) def displace(self,cart_mode,displacement,masses=None): """ Displace the atoms acoording to a phonon mode """ import copy #normalize with masses if masses is None: masses = self.get_masses() if len(masses) != self.natoms: raise ValueError('Wrong dimensions of the masses list') #apply displacement atomic_car_pos_0 = self.atomic_car_pos atoms_car_pos_disp = [] for i,(atype,apos) in enumerate(self.atoms): delta = cart_mode[i].real*displacement/sqrt(masses[i]) atom = [atype, atomic_car_pos_0[i]+delta] atoms_car_pos_disp.append( atom ) #store displaced structures self.set_atoms( atoms_car_pos_disp, coordtype="cartesian" ) @property def atomic_red_pos(self): pos = [] for i in range(self.natoms): pos.append(self.atoms[i][1]) return pos @property def atomic_car_pos(self): pos = [] for i in range(self.natoms): red_pos = self.atoms[i][1] pos.append(red_car([red_pos],self.cell_parameters)[0]) return pos @property def atoms(self): return self._atoms def get_displaced(self,cart_mode,displacement,masses=None): """ Create a copy and displace along the phonon mode """ copy = self.copy() copy.displace(cart_mode,displacement,masses=masses) return copy def read_atoms(self): lines = iter(self.file_lines) #find READ_ATOMS keyword in file and read next lines for line in lines: if "ATOMIC_POSITIONS" in line: atomic_pos_type = line self.atomic_pos_type = re.findall('([A-Za-z]+)',line)[-1] atoms = [] for i in range(int(self.system["nat"])): atype, x,y,z = next(lines).split() atoms.append([atype,[float(i) for i in (x,y,z)]]) self._atoms = atoms self.atomic_pos_type = atomic_pos_type.replace('{','').replace('}','').strip().split()[1] @property def alat(self): if self.ibrav == 0: return np.linalg.norm(self.cell_parameters[0]) else: return self.system['celldm(1)'] @property def cell_parameters(self): if self.ibrav == 0: return self._cell_parameters elif self.ibrav == 1: a = float(self.system['celldm(1)']) cell_parameters = [[ a, 0, 0], [ 0, a, 0], [ 0, 0, a]] elif self.ibrav == 2: a = float(self.system['celldm(1)']) cell_parameters = [[ -a/2, 0, a/2], [ 0, a/2, a/2], [ -a/2, a/2, 0]] elif self.ibrav == 3: a = float(self.system['celldm(1)']) cell_parameters = [[ a/2, a/2, a/2], [-a/2, a/2, a/2], [-a/2, -a/2, a/2]] elif self.ibrav == 4: a = float(self.system['celldm(1)']) c = float(self.system['celldm(3)']) cell_parameters = [[ a, 0, 0], [-a/2,sqrt(3)/2*a, 0], [ 0, 0,c*a]] elif self.ibrav == 6: a = float(self.system['celldm(1)']) c = float(self.system['celldm(3)']) cell_parameters = [[ a, 0, 0], [ 0, a, 0], [ 0, 0, c*a]] else: raise NotImplementedError('ibrav = %d not implemented'%self.ibrav) return cell_parameters @cell_parameters.setter def cell_parameters(self,value): self._cell_parameters = value @property def ibrav(self): return int(self.system['ibrav']) @ibrav.setter def ibrav(self,value): self.set_ibrav(value) def set_ibrav(self,value): if not hasattr(self,'_cell_parameters') and value == 0: raise ValueError('Must set cell_parameters before setting ibrav to 0') if value == 0: for i in range(1,7): self.remove_key(self.system,'celldm(%d)'%i) self.system['ibrav'] = value def read_cell_parameters(self): """read the cell parameters from the input file """ def rmchar(string,symbols): return ''.join([c for c in string if c not in symbols]) if self.ibrav == 0: if 'celldm(1)' in list(self.system.keys()): a = float(self.system['celldm(1)']) else: a = 1 lines = iter(self.file_lines) for line in lines: if "CELL_PARAMETERS" in line: units = rmchar(line.strip(),'{}()').split() cell_parameters = [[],[],[]] if len(units) > 1: self.cell_units = units[1] else: self.cell_units = 'bohr' for i in range(3): cell_parameters[i] = [ float(x)*a for x in next(lines).split() ] if self.cell_units == 'angstrom' or self.cell_units == 'bohr': if 'celldm(1)' in self.system: del self.system['celldm(1)'] if 'celldm(1)' not in list(self.system.keys()): a = np.linalg.norm(cell_parameters[0]) self._cell_parameters = cell_parameters def read_kpoints(self): lines = iter(self.file_lines) #find K_POINTS keyword in file and read next line for line in lines: if "K_POINTS" in line: #chack if the type is automatic if "automatic" in line: self.ktype = "automatic" vals = list(map(float, next(lines).split())) self.kpoints, self.shiftk = vals[0:3], vals[3:6] #otherwise read a list else: #read number of kpoints nkpoints = int(next(lines).split()[0]) self.klist = [] self.ktype = "" try: lines_list = list(lines) for n in range(nkpoints): vals = lines_list[n].split()[:4] self.klist.append( list(map(float,vals)) ) except IndexError: print("wrong k-points list format") exit() def slicefile(self, keyword): file_slice_regexp = '&%s(?:.?)+\n((?:.+\n)+?)(?:\s+)?[\/&]'%keyword lines = re.findall(file_slice_regexp,"".join(self.file_lines),re.MULTILINE) return lines def store(self,group,name): """ Save the variables specified in each of the groups on the structure """ group_regexp = '([a-zA-Z_0-9_\(\)]+)(?:\s+)?=(?:\s+)?([a-zA-Z/\'"0-9_.-]+)' for file_slice in self.slicefile(name): for keyword, value in re.findall(group_regexp,file_slice): group[keyword.strip()]=value.strip() def stringify_group(self, keyword, group): if group != {}: string='&%s\n' % keyword for keyword in sorted(group): # Py2/3 discrepancy in keyword order string += "%20s = %s\n" % (keyword, group[keyword]) string += "/&end" return string else: return '' def remove_key(self,group,key): """ if a certain key exists in the group, remove it """ if key in list(group.keys()): del group[key] def write(self,filename): """write the file to disk """ with open(filename,'w') as f: f.write(str(self)) def get_string(self): """ Output the file in the form of a string """ lines = []; app = lines.append app( self.stringify_group("control",self.control) ) #print control app( self.stringify_group("system",self.system) ) #print system app( self.stringify_group("electrons",self.electrons) ) #print electrons app( self.stringify_group("ions",self.ions) ) #print ions app( self.stringify_group("cell",self.cell) ) #print ions #print atomic species app( "ATOMIC_SPECIES" ) for atype in self.atypes: app( " %3s %8s %20s" % (atype, self.atypes[atype][0], self.atypes[atype][1]) ) #print atomic positions app( "ATOMIC_POSITIONS { %s }"%self.atomic_pos_type ) for atom in self.atoms: app( "%3s %14.10lf %14.10lf %14.10lf" % (atom[0], atom[1][0], atom[1][1], atom[1][2]) ) #print kpoints if self.ktype == "automatic": app( "K_POINTS { %s }" % self.ktype ) app( ("%3d"*6)%(tuple(self.kpoints) + tuple(self.shiftk)) ) else: app( "K_POINTS { %s }" % self.ktype ) app( "%d" % len(self.klist) ) for kpt in self.klist: app( ("%12.8lf "*4)%tuple(kpt) ) #print cell parameters if self.ibrav == 0: app( "CELL_PARAMETERS %s"%self.cell_units ) app( ("%14.10lf "*3)%tuple(self.cell_parameters[0]) ) app( ("%14.10lf "*3)%tuple(self.cell_parameters[1]) ) app( ("%14.10lf "*3)%tuple(self.cell_parameters[2]) ) return "\n".join(lines) def __str__(self): return self.get_string()
henriquemiranda/yambo-py
qepy/pw.py
Python
bsd-3-clause
24,853
[ "ASE", "CRYSTAL", "Quantum ESPRESSO" ]
f19cbd5313b4110a4e6fbbd3f44680db39e18325eabc54594d9612b8161f9ab0
# $HeadURL$ __RCSID__ = "$Id$" from DIRAC import gLogger, S_OK from DIRAC.Core.Base.AgentModule import AgentModule from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.DataManagementSystem.Client.DataIntegrityClient import DataIntegrityClient from DIRAC.DataManagementSystem.Client.DataManager import DataManager AGENT_NAME = 'StorageManagement/RequestPreparationAgent' class RequestPreparationAgent( AgentModule ): def initialize( self ): self.fileCatalog = FileCatalog() self.dm = DataManager() self.stagerClient = StorageManagerClient() self.dataIntegrityClient = DataIntegrityClient() # This sets the Default Proxy to used as that defined under # /Operations/Shifter/DataManager # the shifterProxy option in the Configuration can be used to change this default. self.am_setOption( 'shifterProxy', 'DataManager' ) return S_OK() def execute( self ): res = self.prepareNewReplicas() return res def prepareNewReplicas( self ): """ This is the first logical task to be executed and manages the New->Waiting transition of the Replicas """ res = self.__getNewReplicas() if not res['OK']: gLogger.fatal( "RequestPreparation.prepareNewReplicas: Failed to get replicas from StagerDB.", res['Message'] ) return res if not res['Value']: gLogger.info( "There were no New replicas found" ) return res replicas = res['Value']['Replicas'] replicaIDs = res['Value']['ReplicaIDs'] gLogger.info( "RequestPreparation.prepareNewReplicas: Obtained %s New replicas for preparation." % len( replicaIDs ) ) # Check that the files exist in the FileCatalog res = self.__getExistingFiles( replicas.keys() ) if not res['OK']: return res exist = res['Value']['Exist'] terminal = res['Value']['Missing'] failed = res['Value']['Failed'] if not exist: gLogger.error( 'RequestPreparation.prepareNewReplicas: Failed determine existance of any files' ) return S_OK() terminalReplicaIDs = {} for lfn, reason in terminal.items(): for _se, replicaID in replicas[lfn].items(): terminalReplicaIDs[replicaID] = reason replicas.pop( lfn ) gLogger.info( "RequestPreparation.prepareNewReplicas: %s files exist in the FileCatalog." % len( exist ) ) if terminal: gLogger.info( "RequestPreparation.prepareNewReplicas: %s files do not exist in the FileCatalog." % len( terminal ) ) # Obtain the file sizes from the FileCatalog res = self.__getFileSize( exist ) if not res['OK']: return res failed.update( res['Value']['Failed'] ) terminal = res['Value']['ZeroSize'] fileSizes = res['Value']['FileSizes'] if not fileSizes: gLogger.error( 'RequestPreparation.prepareNewReplicas: Failed determine sizes of any files' ) return S_OK() for lfn, reason in terminal.items(): for _se, replicaID in replicas[lfn].items(): terminalReplicaIDs[replicaID] = reason replicas.pop( lfn ) gLogger.info( "RequestPreparation.prepareNewReplicas: Obtained %s file sizes from the FileCatalog." % len( fileSizes ) ) if terminal: gLogger.info( "RequestPreparation.prepareNewReplicas: %s files registered with zero size in the FileCatalog." % len( terminal ) ) # Obtain the replicas from the FileCatalog res = self.__getFileReplicas( fileSizes.keys() ) if not res['OK']: return res failed.update( res['Value']['Failed'] ) terminal = res['Value']['ZeroReplicas'] fileReplicas = res['Value']['Replicas'] if not fileReplicas: gLogger.error( 'RequestPreparation.prepareNewReplicas: Failed determine replicas for any files' ) return S_OK() for lfn, reason in terminal.items(): for _se, replicaID in replicas[lfn].items(): terminalReplicaIDs[replicaID] = reason replicas.pop( lfn ) gLogger.info( "RequestPreparation.prepareNewReplicas: Obtained replica information for %s file from the FileCatalog." % len( fileReplicas ) ) if terminal: gLogger.info( "RequestPreparation.prepareNewReplicas: %s files registered with zero replicas in the FileCatalog." % len( terminal ) ) # Check the replicas exist at the requested site replicaMetadata = [] for lfn, requestedSEs in replicas.items(): lfnReplicas = fileReplicas[lfn] for requestedSE, replicaID in requestedSEs.items(): if not requestedSE in lfnReplicas.keys(): terminalReplicaIDs[replicaID] = "LFN not registered at requested SE" replicas[lfn].pop( requestedSE ) else: replicaMetadata.append( ( replicaID, lfnReplicas[requestedSE], fileSizes[lfn] ) ) # Update the states of the files in the database if terminalReplicaIDs: gLogger.info( "RequestPreparation.prepareNewReplicas: %s replicas are terminally failed." % len( terminalReplicaIDs ) ) # res = self.stagerClient.updateReplicaFailure( terminalReplicaIDs ) res = self.stagerClient.updateReplicaFailure( terminalReplicaIDs ) if not res['OK']: gLogger.error( "RequestPreparation.prepareNewReplicas: Failed to update replica failures.", res['Message'] ) if replicaMetadata: gLogger.info( "RequestPreparation.prepareNewReplicas: %s replica metadata to be updated." % len( replicaMetadata ) ) # Sets the Status='Waiting' of CacheReplicas records that are OK with catalogue checks res = self.stagerClient.updateReplicaInformation( replicaMetadata ) if not res['OK']: gLogger.error( "RequestPreparation.prepareNewReplicas: Failed to update replica metadata.", res['Message'] ) return S_OK() def __getNewReplicas( self ): """ This obtains the New replicas from the Replicas table and for each LFN the requested storage element """ # First obtain the New replicas from the CacheReplicas table res = self.stagerClient.getCacheReplicas( {'Status':'New'} ) if not res['OK']: gLogger.error( "RequestPreparation.__getNewReplicas: Failed to get replicas with New status.", res['Message'] ) return res if not res['Value']: gLogger.debug( "RequestPreparation.__getNewReplicas: No New replicas found to process." ) return S_OK() else: gLogger.debug( "RequestPreparation.__getNewReplicas: Obtained %s New replicas(s) to process." % len( res['Value'] ) ) replicas = {} replicaIDs = {} for replicaID, info in res['Value'].items(): lfn = info['LFN'] storageElement = info['SE'] if not replicas.has_key( lfn ): replicas[lfn] = {} replicas[lfn][storageElement] = replicaID replicaIDs[replicaID] = ( lfn, storageElement ) return S_OK( {'Replicas':replicas, 'ReplicaIDs':replicaIDs} ) def __getExistingFiles( self, lfns ): """ This checks that the files exist in the FileCatalog. """ filesExist = [] missing = {} res = self.fileCatalog.exists( lfns ) if not res['OK']: gLogger.error( "RequestPreparation.__getExistingFiles: Failed to determine whether files exist.", res['Message'] ) return res failed = res['Value']['Failed'] for lfn, exists in res['Value']['Successful'].items(): if exists: filesExist.append( lfn ) else: missing[lfn] = 'LFN not registered in the FileCatalog' if missing: for lfn, reason in missing.items(): gLogger.warn( "RequestPreparation.__getExistingFiles: %s" % reason, lfn ) self.__reportProblematicFiles( missing.keys(), 'LFN-LFC-DoesntExist' ) return S_OK( {'Exist':filesExist, 'Missing':missing, 'Failed':failed} ) def __getFileSize( self, lfns ): """ This obtains the file size from the FileCatalog. """ fileSizes = {} zeroSize = {} res = self.fileCatalog.getFileSize( lfns ) if not res['OK']: gLogger.error( "RequestPreparation.__getFileSize: Failed to get sizes for files.", res['Message'] ) return res failed = res['Value']['Failed'] for lfn, size in res['Value']['Successful'].items(): if size == 0: zeroSize[lfn] = "LFN registered with zero size in the FileCatalog" else: fileSizes[lfn] = size if zeroSize: for lfn, reason in zeroSize.items(): gLogger.warn( "RequestPreparation.__getFileSize: %s" % reason, lfn ) self.__reportProblematicFiles( zeroSize.keys(), 'LFN-LFC-ZeroSize' ) return S_OK( {'FileSizes':fileSizes, 'ZeroSize':zeroSize, 'Failed':failed} ) def __getFileReplicas( self, lfns ): """ This obtains the replicas from the FileCatalog. """ replicas = {} noReplicas = {} res = self.dm.getActiveReplicas( lfns ) if not res['OK']: gLogger.error( "RequestPreparation.__getFileReplicas: Failed to obtain file replicas.", res['Message'] ) return res failed = res['Value']['Failed'] for lfn, lfnReplicas in res['Value']['Successful'].items(): if len( lfnReplicas.keys() ) == 0: noReplicas[lfn] = "LFN registered with zero replicas in the FileCatalog" else: replicas[lfn] = lfnReplicas if noReplicas: for lfn, reason in noReplicas.items(): gLogger.warn( "RequestPreparation.__getFileReplicas: %s" % reason, lfn ) self.__reportProblematicFiles( noReplicas.keys(), 'LFN-LFC-NoReplicas' ) return S_OK( {'Replicas':replicas, 'ZeroReplicas':noReplicas, 'Failed':failed} ) def __reportProblematicFiles( self, lfns, reason ): return S_OK() #res = self.dataIntegrityClient.setFileProblematic( lfns, reason, sourceComponent = 'RequestPreparationAgent' ) #if not res['OK']: # gLogger.error( "RequestPreparation.__reportProblematicFiles: Failed to report missing files.", res['Message'] ) # return res #if res['Value']['Successful']: # gLogger.info( "RequestPreparation.__reportProblematicFiles: Successfully reported %s missing files." % len( res['Value']['Successful'] ) ) #if res['Value']['Failed']: # gLogger.info( "RequestPreparation.__reportProblematicFiles: Failed to report %s problematic files." % len( res['Value']['Failed'] ) ) #return res
avedaee/DIRAC
StorageManagementSystem/Agent/RequestPreparationAgent.py
Python
gpl-3.0
10,152
[ "DIRAC" ]
d2bf3bbc44b6beb3d5552e3b0120415d21b67db1c623f87df7666ed88e427cc2
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import sys import platform from setuptools import setup, find_packages, Extension from setuptools.command.build_ext import build_ext as _build_ext class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) # Prevent numpy from thinking it is still in its setup process: if sys.version_info[0] >= 3: import builtins if hasattr(builtins, '__NUMPY_SETUP__'): del builtins.__NUMPY_SETUP__ import importlib import numpy importlib.reload(numpy) else: import __builtin__ if hasattr(__builtin__, '__NUMPY_SETUP__'): del __builtin__.__NUMPY_SETUP__ import imp import numpy imp.reload(numpy) self.include_dirs.append(numpy.get_include()) extra_link_args = [] if sys.platform.startswith('win') and platform.machine().endswith('64'): extra_link_args.append('-Wl,--allow-multiple-definition') long_desc = """ .. image:: https://circleci.com/gh/materialsproject/pymatgen.svg?style=shield&circle-token=:circle-token .. image:: https://ci.appveyor.com/api/projects/status/akdyke5jxg6gps45?svg=true .. image:: https://anaconda.org/matsci/pymatgen/badges/downloads.svg .. image:: https://coveralls.io/repos/github/materialsproject/pymatgen/badge.svg?branch=master Official docs: `http://pymatgen.org <http://pymatgen.org/>`_ Pymatgen (Python Materials Genomics) is a robust, open-source Python library for materials analysis. These are some of the main features: 1. Highly flexible classes for the representation of Element, Site, Molecule, Structure objects. 2. Extensive input/output support, including support for VASP (http://cms.mpi.univie.ac.at/vasp/), ABINIT (http://www.abinit.org/), CIF, Gaussian, XYZ, and many other file formats. 3. Powerful analysis tools, including generation of phase diagrams, Pourbaix diagrams, diffusion analyses, reactions, etc. 4. Electronic structure analyses, such as density of states and band structure. 5. Integration with the Materials Project REST API. Pymatgen is free to use. However, we also welcome your help to improve this library by making your own contributions. These contributions can be in the form of additional tools or modules you develop, or feature requests and bug reports. Please report any bugs and issues at pymatgen's `Github page <https://github.com/materialsproject/pymatgen>`_. If you wish to be notified of pymatgen releases, you may become a member of `pymatgen's Google Groups page <https://groups.google.com/forum/?fromgroups#!forum/pymatgen/>`_. Why use pymatgen? ================= There are many materials analysis codes out there, both commerical and free, but pymatgen offer several advantages: 1. **It is (fairly) robust.** Pymatgen is used by thousands of researchers, and is the analysis code powering the `Materials Project`_. The analysis it produces survives rigorous scrutiny every single day. Bugs tend to be found and corrected quickly. Pymatgen also uses `CircleCI <https://circleci.com>`_ and `Appveyor <https://www.appveyor.com/>`_ for continuous integration on the Linux and Windows platforms, respectively, which ensures that every commit passes a comprehensive suite of unittests. The coverage of the unittests can be seen at `here <coverage/index.html>`_. 2. **It is well documented.** A fairly comprehensive documentation has been written to help you get to grips with it quickly. 3. **It is open.** You are free to use and contribute to pymatgen. It also means that pymatgen is continuously being improved. We will attribute any code you contribute to any publication you specify. Contributing to pymatgen means your research becomes more visible, which translates to greater impact. 4. **It is fast.** Many of the core numerical methods in pymatgen have been optimized by vectorizing in numpy/scipy. This means that coordinate manipulations are extremely fast and are in fact comparable to codes written in other languages. Pymatgen also comes with a complete system for handling periodic boundary conditions. 5. **It will be around.** Pymatgen is not a pet research project. It is used in the well-established Materials Project. It is also actively being developed and maintained by the `Materials Virtual Lab`_, the ABINIT group and many other research groups. With effect from version 3.0, pymatgen now supports both Python 2.7 as well as Python 3.x. """ setup( name="pymatgen", packages=find_packages(), version="2017.11.6", cmdclass={'build_ext': build_ext}, setup_requires=['numpy', 'setuptools>=18.0'], install_requires=["numpy>=1.9", "six", "requests", "ruamel.yaml>=0.15.6", "monty>=0.9.6", "scipy>=0.14", "pydispatcher>=2.0.5", "tabulate", "spglib>=1.9.9.44", "matplotlib>=1.5", "palettable>=2.1.1", "sympy"], extras_require={ ':python_version == "2.7"': [ 'enum34', ], "provenance": ["pybtex"], "pourbaix": ["pyhull>=1.5.3"], "bandstructure": ["pyhull>=1.5.3"], "ase": ["ase>=3.3"], "vis": ["vtk>=6.0.0"], "abinit": ["apscheduler==2.1.0"]}, package_data={"pymatgen.core": ["*.json"], "pymatgen.analysis": ["*.yaml", "*.json"], "pymatgen.analysis.chemenv.coordination_environments.coordination_geometries_files": ["*.txt", "*.json"], "pymatgen.analysis.chemenv.coordination_environments.strategy_files": ["*.json"], "pymatgen.io.vasp": ["*.yaml"], "pymatgen.io.feff": ["*.yaml"], "pymatgen.symmetry": ["*.yaml", "*.json"], "pymatgen.entries": ["*.yaml"], "pymatgen.structure_prediction": ["data/*.json"], "pymatgen.vis": ["ElementColorSchemes.yaml"], "pymatgen.command_line": ["OxideTersoffPotentials"], "pymatgen.analysis.defects": ["*.json"], "pymatgen.analysis.diffraction": ["*.json"], "pymatgen.util": ["structures/*.json"]}, author="Pymatgen Development Team", author_email="pymatgen@googlegroups.com", maintainer="Shyue Ping Ong", maintainer_email="ongsp@eng.ucsd.edu", url="http://www.pymatgen.org", license="MIT", description="Python Materials Genomics is a robust materials " "analysis code that defines core object representations for " "structures and molecules with support for many electronic " "structure codes. It is currently the core analysis code " "powering the Materials Project " "(https://www.materialsproject.org).", long_description=long_desc, keywords=["VASP", "gaussian", "ABINIT", "nwchem", "materials", "project", "electronic", "structure", "analysis", "phase", "diagrams"], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Information Analysis", "Topic :: Scientific/Engineering :: Physics", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Software Development :: Libraries :: Python Modules" ], ext_modules=[Extension("pymatgen.optimization.linear_assignment", ["pymatgen/optimization/linear_assignment.c"], extra_link_args=extra_link_args), Extension("pymatgen.util.coord_cython", ["pymatgen/util/coord_cython.c"], extra_link_args=extra_link_args)], entry_points={ 'console_scripts': [ 'pmg = pymatgen.cli.pmg:main', 'feff_input_generation = pymatgen.cli.feff_input_generation:main', 'feff_plot_cross_section = pymatgen.cli.feff_plot_cross_section:main', 'feff_plot_dos = pymatgen.cli.feff_plot_dos:main', 'gaussian_analyzer = pymatgen.cli.gaussian_analyzer:main', 'get_environment = pymatgen.cli.get_environment:main', 'pydii = pymatgen.cli.pydii:main', ] } )
Bismarrck/pymatgen
setup.py
Python
mit
8,781
[ "ABINIT", "ASE", "FEFF", "Gaussian", "NWChem", "VASP", "VTK", "pymatgen" ]
6fa9e983d9c03287f8aa2f5157fe333a1653e00df3caaf1c23517da87263b4e6