idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
248,100
def decrypt ( self , encrypted ) : fernet = Fernet ( self . decryption_cipher_key ) return fernet . decrypt ( encrypted )
decrypts the encrypted message using Fernet
34
9
248,101
def create_subject ( self , authc_token = None , account_id = None , existing_subject = None , subject_context = None ) : if subject_context is None : # this that means a successful login just happened # passing existing_subject is new to yosai: context = self . create_subject_context ( existing_subject ) context . authenticated = True context . authentication_token = authc_token context . account_id = account_id if ( existing_subject ) : context . subject = existing_subject else : context = copy . copy ( subject_context ) # if this necessary? TBD. context = self . ensure_security_manager ( context ) context = self . resolve_session ( context ) context = self . resolve_identifiers ( context ) subject = self . do_create_subject ( context ) # DelegatingSubject # save this subject for future reference if necessary: # (this is needed here in case remember_me identifiers were resolved # and they need to be stored in the session, so we don't constantly # re-hydrate the remember_me identifier_collection on every operation). self . save ( subject ) return subject
Creates a Subject instance for the user represented by the given method arguments .
246
15
248,102
def login ( self , subject , authc_token ) : try : # account_id is a SimpleIdentifierCollection account_id = self . authenticator . authenticate_account ( subject . identifiers , authc_token ) # implies multi-factor authc not complete: except AdditionalAuthenticationRequired as exc : # identity needs to be accessible for subsequent authentication: self . update_subject_identity ( exc . account_id , subject ) # no need to propagate account further: raise AdditionalAuthenticationRequired except AuthenticationException as authc_ex : try : self . on_failed_login ( authc_token , authc_ex , subject ) except Exception : msg = ( "on_failed_login method raised an exception. Logging " "and propagating original AuthenticationException." ) logger . info ( msg , exc_info = True ) raise logged_in = self . create_subject ( authc_token = authc_token , account_id = account_id , existing_subject = subject ) self . on_successful_login ( authc_token , account_id , logged_in ) return logged_in
Login authenticates a user using an AuthenticationToken . If authentication is successful AND the Authenticator has determined that authentication is complete for the account login constructs a Subject instance representing the authenticated account s identity . Once a subject instance is constructed it is bound to the application for subsequent access before being returned to the caller .
238
61
248,103
def ensure_security_manager ( self , subject_context ) : if ( subject_context . resolve_security_manager ( ) is not None ) : msg = ( "Subject Context resolved a security_manager " "instance, so not re-assigning. Returning." ) logger . debug ( msg ) return subject_context msg = ( "No security_manager found in context. Adding self " "reference." ) logger . debug ( msg ) subject_context . security_manager = self return subject_context
Determines whether there is a SecurityManager instance in the context and if not adds self to the context . This ensures that do_create_subject will have access to a SecurityManager during Subject construction .
105
41
248,104
def resolve_session ( self , subject_context ) : if ( subject_context . resolve_session ( ) is not None ) : msg = ( "Context already contains a session. Returning." ) logger . debug ( msg ) return subject_context try : # Context couldn't resolve it directly, let's see if we can # since we have direct access to the session manager: session = self . resolve_context_session ( subject_context ) # if session is None, given that subject_context.session # is None there is no harm done by setting it to None again subject_context . session = session except InvalidSessionException : msg = ( "Resolved subject_subject_context context session is " "invalid. Ignoring and creating an anonymous " "(session-less) Subject instance." ) logger . debug ( msg , exc_info = True ) return subject_context
This method attempts to resolve any associated session based on the context and returns a context that represents this resolved Session to ensure it may be referenced if needed by the invoked do_create_subject that performs actual Subject construction .
182
43
248,105
def resolve_identifiers ( self , subject_context ) : session = subject_context . session identifiers = subject_context . resolve_identifiers ( session ) if ( not identifiers ) : msg = ( "No identity (identifier_collection) found in the " "subject_context. Looking for a remembered identity." ) logger . debug ( msg ) identifiers = self . get_remembered_identity ( subject_context ) if identifiers : msg = ( "Found remembered IdentifierCollection. Adding to the " "context to be used for subject construction." ) logger . debug ( msg ) subject_context . identifiers = identifiers subject_context . remembered = True else : msg = ( "No remembered identity found. Returning original " "context." ) logger . debug ( msg ) return subject_context
ensures that a subject_context has identifiers and if it doesn t will attempt to locate them using heuristics
165
23
248,106
def logout ( self , subject ) : if ( subject is None ) : msg = "Subject argument cannot be None." raise ValueError ( msg ) self . before_logout ( subject ) identifiers = copy . copy ( subject . identifiers ) # copy is new to yosai if ( identifiers ) : msg = ( "Logging out subject with primary identifier {0}" . format ( identifiers . primary_identifier ) ) logger . debug ( msg ) try : # this removes two internal attributes from the session: self . delete ( subject ) except Exception : msg = "Unable to cleanly unbind Subject. Ignoring (logging out)." logger . debug ( msg , exc_info = True ) finally : try : self . stop_session ( subject ) except Exception : msg2 = ( "Unable to cleanly stop Session for Subject. " "Ignoring (logging out)." ) logger . debug ( msg2 , exc_info = True )
Logs out the specified Subject from the system .
199
10
248,107
def is_permitted ( self , identifiers , permission_s ) : identifier = identifiers . primary_identifier for required in permission_s : domain = Permission . get_domain ( required ) # assigned is a list of json blobs: assigned = self . get_authzd_permissions ( identifier , domain ) is_permitted = False for perms_blob in assigned : is_permitted = self . permission_verifier . is_permitted_from_json ( required , perms_blob ) yield ( required , is_permitted )
If the authorization info cannot be obtained from the accountstore permission check tuple yields False .
121
17
248,108
def has_role ( self , identifiers , required_role_s ) : identifier = identifiers . primary_identifier # assigned_role_s is a set assigned_role_s = self . get_authzd_roles ( identifier ) if not assigned_role_s : msg = 'has_role: no roles obtained from account_store for [{0}]' . format ( identifier ) logger . warning ( msg ) for role in required_role_s : yield ( role , False ) else : for role in required_role_s : hasrole = ( { role } <= assigned_role_s ) yield ( role , hasrole )
Confirms whether a subject is a member of one or more roles .
138
14
248,109
def on_start ( self , session , session_context ) : session_id = session . session_id web_registry = session_context [ 'web_registry' ] if self . is_session_id_cookie_enabled : web_registry . session_id = session_id logger . debug ( "Set SessionID cookie using id: " + str ( session_id ) ) else : msg = ( "Session ID cookie is disabled. No cookie has been set for " "new session with id: " + str ( session_id ) ) logger . debug ( msg )
Stores the Session s ID usually as a Cookie to associate with future requests .
125
16
248,110
def is_session_storage_enabled ( self , subject = None ) : if subject . get_session ( False ) : # then use what already exists return True if not self . session_storage_enabled : # honor global setting: return False # non-web subject instances can't be saved to web-only session managers: if ( not hasattr ( subject , 'web_registry' ) and self . session_manager and not isinstance ( self . session_manager , session_abcs . NativeSessionManager ) ) : return False return subject . web_registry . session_creation_enabled
Returns True if session storage is generally available ( as determined by the super class s global configuration property is_session_storage_enabled and no request - specific override has turned off session storage False otherwise .
126
40
248,111
def default_marshaller ( obj ) : if hasattr ( obj , '__getstate__' ) : return obj . __getstate__ ( ) try : return obj . __dict__ except AttributeError : raise TypeError ( '{!r} has no __dict__ attribute and does not implement __getstate__()' . format ( obj . __class__ . __name__ ) )
Retrieve the state of the given object .
86
9
248,112
def default_unmarshaller ( instance , state ) : if hasattr ( instance , '__setstate__' ) : instance . __setstate__ ( state ) else : try : instance . __dict__ . update ( state ) except AttributeError : raise TypeError ( '{!r} has no __dict__ attribute and does not implement __setstate__()' . format ( instance . __class__ . __name__ ) )
Restore the state of an object .
95
8
248,113
def do_authenticate_account ( self , authc_token ) : try : realms = self . token_realm_resolver [ authc_token . __class__ ] except KeyError : raise KeyError ( 'Unsupported Token Type Provided: ' , authc_token . __class__ . __name__ ) if ( len ( self . realms ) == 1 ) : account = self . authenticate_single_realm_account ( realms [ 0 ] , authc_token ) else : account = self . authenticate_multi_realm_account ( self . realms , authc_token ) cred_type = authc_token . token_info [ 'cred_type' ] attempts = account [ 'authc_info' ] [ cred_type ] . get ( 'failed_attempts' , [ ] ) self . validate_locked ( authc_token , attempts ) # TODO: refactor this to something less rigid as it is unreliable: if len ( account [ 'authc_info' ] ) > authc_token . token_info [ 'tier' ] : if self . mfa_dispatcher : realm = self . token_realm_resolver [ TOTPToken ] [ 0 ] # s/b only one totp_token = realm . generate_totp_token ( account ) mfa_info = account [ 'authc_info' ] [ 'totp_key' ] [ '2fa_info' ] self . mfa_dispatcher . dispatch ( authc_token . identifier , mfa_info , totp_token ) raise AdditionalAuthenticationRequired ( account [ 'account_id' ] ) return account
Returns an account object only when the current token authenticates AND the authentication process is complete raising otherwise
366
19
248,114
def extra_from_record ( self , record ) : return { attr_name : record . __dict__ [ attr_name ] for attr_name in record . __dict__ if attr_name not in BUILTIN_ATTRS }
Returns extra dict you passed to logger .
57
8
248,115
def save ( self , subject ) : if ( self . is_session_storage_enabled ( subject ) ) : self . merge_identity ( subject ) else : msg = ( "Session storage of subject state for Subject [{0}] has " "been disabled: identity and authentication state are " "expected to be initialized on every request or " "invocation." . format ( subject ) ) logger . debug ( msg ) return subject
Saves the subject s state to the subject s Session only if session storage is enabled for the subject . If session storage is not enabled for the specific Subject this method does nothing .
91
36
248,116
def create_manager ( self , yosai , settings , session_attributes ) : mgr_settings = SecurityManagerSettings ( settings ) attributes = mgr_settings . attributes realms = self . _init_realms ( settings , attributes [ 'realms' ] ) session_attributes = self . _init_session_attributes ( session_attributes , attributes ) serialization_manager = SerializationManager ( session_attributes , serializer_scheme = attributes [ 'serializer' ] ) # the cache_handler doesn't initialize a cache_realm until it gets # a serialization manager, which is assigned within the SecurityManager cache_handler = self . _init_cache_handler ( settings , attributes [ 'cache_handler' ] , serialization_manager ) manager = mgr_settings . security_manager ( yosai , settings , realms = realms , cache_handler = cache_handler , serialization_manager = serialization_manager ) return manager
Order of execution matters . The sac must be set before the cache_handler is instantiated so that the cache_handler s serialization manager instance registers the sac .
207
33
248,117
def check_permission ( self , identifiers , permission_s , logical_operator ) : self . assert_realms_configured ( ) permitted = self . is_permitted_collective ( identifiers , permission_s , logical_operator ) if not permitted : msg = "Subject lacks permission(s) to satisfy logical operation" raise UnauthorizedException ( msg )
like Yosai s authentication process the authorization process will raise an Exception to halt further authz checking once Yosai determines that a Subject is unauthorized to receive the requested permission
77
35
248,118
def by_type ( self , identifier_class ) : myidentifiers = set ( ) for identifier in self . source_identifiers . values ( ) : if ( isinstance ( identifier , identifier_class ) ) : myidentifiers . update ( [ identifier ] ) return set ( myidentifiers )
returns all unique instances of a type of identifier
63
10
248,119
def create ( self , session ) : sessionid = super ( ) . create ( session ) # calls _do_create and verify self . _cache ( session , sessionid ) return sessionid
caches the session and caches an entry to associate the cached session with the subject
40
16
248,120
def start ( self , session_context ) : # is a SimpleSesson: session = self . _create_session ( session_context ) self . session_handler . on_start ( session , session_context ) mysession = session_tuple ( None , session . session_id ) self . notify_event ( mysession , 'SESSION.START' ) # Don't expose the EIS-tier Session object to the client-tier, but # rather a DelegatingSession: return self . create_exposed_session ( session = session , context = session_context )
unlike shiro yosai does not apply session timeouts from within the start method of the SessionManager but rather defers timeout settings responsibilities to the SimpleSession which uses session_settings
125
38
248,121
def _setup ( self , name = None ) : envvar = self . __dict__ [ 'env_var' ] if envvar : settings_file = os . environ . get ( envvar ) else : settings_file = self . __dict__ [ 'file_path' ] if not settings_file : msg = ( "Requested settings, but none can be obtained for the envvar." "Since no config filepath can be obtained, a default config " "will be used." ) logger . error ( msg ) raise OSError ( msg ) self . _wrapped = Settings ( settings_file )
Load the settings module referenced by env_var . This environment - defined configuration process is called during the settings configuration process .
132
24
248,122
def remember_encrypted_identity ( self , subject , encrypted ) : try : # base 64 encode it and store as a cookie: encoded = base64 . b64encode ( encrypted ) . decode ( 'utf-8' ) subject . web_registry . remember_me = encoded except AttributeError : msg = ( "Subject argument is not an HTTP-aware instance. This " "is required to obtain a web registry in order to" "set the RememberMe cookie. Returning immediately " "and ignoring RememberMe operation." ) logger . debug ( msg )
Base64 - encodes the specified serialized byte array and sets that base64 - encoded String as the cookie value .
118
24
248,123
def get_remembered_encrypted_identity ( self , subject_context ) : if ( self . is_identity_removed ( subject_context ) ) : if not isinstance ( subject_context , web_subject_abcs . WebSubjectContext ) : msg = ( "SubjectContext argument is not an HTTP-aware instance. " "This is required to obtain a web registry " "in order to retrieve the RememberMe cookie. Returning " "immediately and ignoring rememberMe operation." ) logger . debug ( msg ) return None remember_me = subject_context . web_registry . remember_me # TBD: # Browsers do not always remove cookies immediately # ignore cookies that are scheduled for removal # if (web_wsgi_abcs.Cookie.DELETED_COOKIE_VALUE.equals(base64)): # return None if remember_me : logger . debug ( "Acquired encoded identity [" + str ( remember_me ) + "]" ) encrypted = base64 . b64decode ( remember_me ) return encrypted else : # no cookie set - new site visitor? return None
Returns a previously serialized identity byte array or None if the byte array could not be acquired .
241
19
248,124
def _get_settings_class ( ) : if not hasattr ( django_settings , "AUTH_ADFS" ) : msg = "The configuration directive 'AUTH_ADFS' was not found in your Django settings" raise ImproperlyConfigured ( msg ) cls = django_settings . AUTH_ADFS . get ( 'SETTINGS_CLASS' , DEFAULT_SETTINGS_CLASS ) return import_string ( cls )
Get the AUTH_ADFS setting from the Django settings .
99
12
248,125
def build_authorization_endpoint ( self , request , disable_sso = None ) : self . load_config ( ) redirect_to = request . GET . get ( REDIRECT_FIELD_NAME , None ) if not redirect_to : redirect_to = django_settings . LOGIN_REDIRECT_URL redirect_to = base64 . urlsafe_b64encode ( redirect_to . encode ( ) ) . decode ( ) query = QueryDict ( mutable = True ) query . update ( { "response_type" : "code" , "client_id" : settings . CLIENT_ID , "resource" : settings . RELYING_PARTY_ID , "redirect_uri" : self . redirect_uri ( request ) , "state" : redirect_to , } ) if self . _mode == "openid_connect" : query [ "scope" ] = "openid" if ( disable_sso is None and settings . DISABLE_SSO ) or disable_sso is True : query [ "prompt" ] = "login" return "{0}?{1}" . format ( self . authorization_endpoint , query . urlencode ( ) )
This function returns the ADFS authorization URL .
263
9
248,126
def create_user ( self , claims ) : # Create the user username_claim = settings . USERNAME_CLAIM usermodel = get_user_model ( ) user , created = usermodel . objects . get_or_create ( * * { usermodel . USERNAME_FIELD : claims [ username_claim ] } ) if created or not user . password : user . set_unusable_password ( ) logger . debug ( "User '{}' has been created." . format ( claims [ username_claim ] ) ) return user
Create the user if it doesn t exist yet
115
9
248,127
def update_user_attributes ( self , user , claims ) : required_fields = [ field . name for field in user . _meta . fields if field . blank is False ] for field , claim in settings . CLAIM_MAPPING . items ( ) : if hasattr ( user , field ) : if claim in claims : setattr ( user , field , claims [ claim ] ) logger . debug ( "Attribute '{}' for user '{}' was set to '{}'." . format ( field , user , claims [ claim ] ) ) else : if field in required_fields : msg = "Claim not found in access token: '{}'. Check ADFS claims mapping." raise ImproperlyConfigured ( msg . format ( claim ) ) else : msg = "Claim '{}' for user field '{}' was not found in the access token for user '{}'. " "Field is not required and will be left empty" . format ( claim , field , user ) logger . warning ( msg ) else : msg = "User model has no field named '{}'. Check ADFS claims mapping." raise ImproperlyConfigured ( msg . format ( field ) )
Updates user attributes based on the CLAIM_MAPPING setting .
254
15
248,128
def update_user_groups ( self , user , claims ) : if settings . GROUPS_CLAIM is not None : # Update the user's group memberships django_groups = [ group . name for group in user . groups . all ( ) ] if settings . GROUPS_CLAIM in claims : claim_groups = claims [ settings . GROUPS_CLAIM ] if not isinstance ( claim_groups , list ) : claim_groups = [ claim_groups , ] else : logger . debug ( "The configured groups claim '{}' was not found in the access token" . format ( settings . GROUPS_CLAIM ) ) claim_groups = [ ] # Make a diff of the user's groups. # Removing a user from all groups and then re-add them would cause # the autoincrement value for the database table storing the # user-to-group mappings to increment for no reason. groups_to_remove = set ( django_groups ) - set ( claim_groups ) groups_to_add = set ( claim_groups ) - set ( django_groups ) # Loop through the groups in the group claim and # add the user to these groups as needed. for group_name in groups_to_remove : group = Group . objects . get ( name = group_name ) user . groups . remove ( group ) logger . debug ( "User removed from group '{}'" . format ( group_name ) ) for group_name in groups_to_add : try : if settings . MIRROR_GROUPS : group , _ = Group . objects . get_or_create ( name = group_name ) logger . debug ( "Created group '{}'" . format ( group_name ) ) else : group = Group . objects . get ( name = group_name ) user . groups . add ( group ) logger . debug ( "User added to group '{}'" . format ( group_name ) ) except ObjectDoesNotExist : # Silently fail for non-existing groups. pass
Updates user group memberships based on the GROUPS_CLAIM setting .
434
16
248,129
def update_user_flags ( self , user , claims ) : if settings . GROUPS_CLAIM is not None : if settings . GROUPS_CLAIM in claims : access_token_groups = claims [ settings . GROUPS_CLAIM ] if not isinstance ( access_token_groups , list ) : access_token_groups = [ access_token_groups , ] else : logger . debug ( "The configured group claim was not found in the access token" ) access_token_groups = [ ] for flag , group in settings . GROUP_TO_FLAG_MAPPING . items ( ) : if hasattr ( user , flag ) : if group in access_token_groups : value = True else : value = False setattr ( user , flag , value ) logger . debug ( "Attribute '{}' for user '{}' was set to '{}'." . format ( user , flag , value ) ) else : msg = "User model has no field named '{}'. Check ADFS boolean claims mapping." raise ImproperlyConfigured ( msg . format ( flag ) ) for field , claim in settings . BOOLEAN_CLAIM_MAPPING . items ( ) : if hasattr ( user , field ) : bool_val = False if claim in claims and str ( claims [ claim ] ) . lower ( ) in [ 'y' , 'yes' , 't' , 'true' , 'on' , '1' ] : bool_val = True setattr ( user , field , bool_val ) logger . debug ( 'Attribute "{}" for user "{}" was set to "{}".' . format ( user , field , bool_val ) ) else : msg = "User model has no field named '{}'. Check ADFS boolean claims mapping." raise ImproperlyConfigured ( msg . format ( field ) )
Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting .
396
20
248,130
def get ( self , request ) : code = request . GET . get ( "code" ) if not code : # Return an error message return render ( request , 'django_auth_adfs/login_failed.html' , { 'error_message' : "No authorization code was provided." , } , status = 400 ) redirect_to = request . GET . get ( "state" ) user = authenticate ( request = request , authorization_code = code ) if user is not None : if user . is_active : login ( request , user ) # Redirect to the "after login" page. # Because we got redirected from ADFS, we can't know where the # user came from. if redirect_to : redirect_to = base64 . urlsafe_b64decode ( redirect_to . encode ( ) ) . decode ( ) else : redirect_to = django_settings . LOGIN_REDIRECT_URL url_is_safe = is_safe_url ( url = redirect_to , allowed_hosts = [ request . get_host ( ) ] , require_https = request . is_secure ( ) , ) redirect_to = redirect_to if url_is_safe else '/' return redirect ( redirect_to ) else : # Return a 'disabled account' error message return render ( request , 'django_auth_adfs/login_failed.html' , { 'error_message' : "Your account is disabled." , } , status = 403 ) else : # Return an 'invalid login' error message return render ( request , 'django_auth_adfs/login_failed.html' , { 'error_message' : "Login failed." , } , status = 401 )
Handles the redirect from ADFS to our site . We try to process the passed authorization code and login the user .
374
24
248,131
def authenticate ( self , request ) : auth = get_authorization_header ( request ) . split ( ) if not auth or auth [ 0 ] . lower ( ) != b'bearer' : return None if len ( auth ) == 1 : msg = 'Invalid authorization header. No credentials provided.' raise exceptions . AuthenticationFailed ( msg ) elif len ( auth ) > 2 : msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions . AuthenticationFailed ( msg ) # Authenticate the user # The AdfsAuthCodeBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate ( access_token = auth [ 1 ] ) if user is None : raise exceptions . AuthenticationFailed ( 'Invalid access token.' ) if not user . is_active : raise exceptions . AuthenticationFailed ( 'User inactive or deleted.' ) return user , auth [ 1 ]
Returns a User if a correct access token has been supplied in the Authorization header . Otherwise returns None .
203
20
248,132
def molecular_orbital ( coords , mocoeffs , gbasis ) : # Making a closure def f ( x , y , z , coords = coords , mocoeffs = mocoeffs , gbasis = gbasis ) : # The other functions take nanometers return sum ( c * bf ( x * 10 , y * 10 , z * 10 ) for c , bf in zip ( mocoeffs , getbfs ( coords * 10 , gbasis ) ) ) return f
Return a molecular orbital given the nuclei coordinates as well as molecular orbital coefficients and basis set specification as given by the cclib library .
118
28
248,133
def getbfs ( coords , gbasis ) : sym2powerlist = { 'S' : [ ( 0 , 0 , 0 ) ] , 'P' : [ ( 1 , 0 , 0 ) , ( 0 , 1 , 0 ) , ( 0 , 0 , 1 ) ] , 'D' : [ ( 2 , 0 , 0 ) , ( 0 , 2 , 0 ) , ( 0 , 0 , 2 ) , ( 1 , 1 , 0 ) , ( 0 , 1 , 1 ) , ( 1 , 0 , 1 ) ] , 'F' : [ ( 3 , 0 , 0 ) , ( 2 , 1 , 0 ) , ( 2 , 0 , 1 ) , ( 1 , 2 , 0 ) , ( 1 , 1 , 1 ) , ( 1 , 0 , 2 ) , ( 0 , 3 , 0 ) , ( 0 , 2 , 1 ) , ( 0 , 1 , 2 ) , ( 0 , 0 , 3 ) ] } bfs = [ ] for i , at_coords in enumerate ( coords ) : bs = gbasis [ i ] for sym , prims in bs : for power in sym2powerlist [ sym ] : bf = cgbf ( at_coords , power ) for expnt , coef in prims : bf . add_pgbf ( expnt , coef ) bf . normalize ( ) bfs . append ( bf ) return bfs
Convenience function for both wavefunction and density based on PyQuante Ints . py .
308
20
248,134
def A_term ( i , r , u , l1 , l2 , PAx , PBx , CPx , gamma ) : return pow ( - 1 , i ) * binomial_prefactor ( i , l1 , l2 , PAx , PBx ) * pow ( - 1 , u ) * factorial ( i ) * pow ( CPx , i - 2 * r - 2 * u ) * pow ( 0.25 / gamma , r + u ) / factorial ( r ) / factorial ( u ) / factorial ( i - 2 * r - 2 * u )
THO eq . 2 . 18
127
7
248,135
def A_array ( l1 , l2 , PA , PB , CP , g ) : Imax = l1 + l2 + 1 A = [ 0 ] * Imax for i in range ( Imax ) : for r in range ( int ( floor ( i / 2 ) + 1 ) ) : for u in range ( int ( floor ( ( i - 2 * r ) / 2 ) + 1 ) ) : I = i - 2 * r - u A [ I ] = A [ I ] + A_term ( i , r , u , l1 , l2 , PA , PB , CP , g ) return A
THO eq . 2 . 18 and 3 . 1
134
11
248,136
def _normalize ( self ) : l , m , n = self . powers self . norm = np . sqrt ( pow ( 2 , 2 * ( l + m + n ) + 1.5 ) * pow ( self . exponent , l + m + n + 1.5 ) / fact2 ( 2 * l - 1 ) / fact2 ( 2 * m - 1 ) / fact2 ( 2 * n - 1 ) / pow ( np . pi , 1.5 ) ) return
Normalize basis function . From THO eq . 2 . 2
104
13
248,137
def hide ( self , selections ) : if 'atoms' in selections : self . hidden_state [ 'atoms' ] = selections [ 'atoms' ] self . on_atom_hidden_changed ( ) if 'bonds' in selections : self . hidden_state [ 'bonds' ] = selections [ 'bonds' ] self . on_bond_hidden_changed ( ) if 'box' in selections : self . hidden_state [ 'box' ] = box_s = selections [ 'box' ] if box_s . mask [ 0 ] : if self . viewer . has_renderer ( self . box_renderer ) : self . viewer . remove_renderer ( self . box_renderer ) else : if not self . viewer . has_renderer ( self . box_renderer ) : self . viewer . add_renderer ( self . box_renderer ) return self . hidden_state
Hide objects in this representation . BallAndStickRepresentation support selections of atoms and bonds .
200
19
248,138
def change_radius ( self , selections , value ) : if 'atoms' in selections : atms = selections [ 'atoms' ] . mask if value is None : self . radii_state . array [ atms ] = [ vdw_radii . get ( t ) * 0.3 for t in self . system . type_array [ atms ] ] else : self . radii_state . array [ atms ] = value self . update_scale_factors ( self . scale_factors )
Change the radius of each atom by a certain value
113
10
248,139
def paintGL ( self ) : if self . post_processing : # Render to the first framebuffer glBindFramebuffer ( GL_FRAMEBUFFER , self . fb0 ) glViewport ( 0 , 0 , self . width ( ) , self . height ( ) ) status = glCheckFramebufferStatus ( GL_FRAMEBUFFER ) if ( status != GL_FRAMEBUFFER_COMPLETE ) : reason = dict ( GL_FRAMEBUFFER_UNDEFINED = 'UNDEFINED' , GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 'INCOMPLETE_ATTACHMENT' , GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 'INCOMPLETE_MISSING_ATTACHMENT' , GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = 'INCOMPLETE_DRAW_BUFFER' , GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER = 'INCOMPLETE_READ_BUFFER' , GL_FRAMEBUFFER_UNSUPPORTED = 'UNSUPPORTED' , ) [ status ] raise Exception ( 'Framebuffer is not complete: {}' . format ( reason ) ) else : glBindFramebuffer ( GL_FRAMEBUFFER , DEFAULT_FRAMEBUFFER ) # Clear color take floats bg_r , bg_g , bg_b , bg_a = self . background_color glClearColor ( bg_r / 255 , bg_g / 255 , bg_b / 255 , bg_a / 255 ) glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) proj = self . camera . projection cam = self . camera . matrix self . mvproj = np . dot ( proj , cam ) self . ldir = cam [ : 3 , : 3 ] . T . dot ( self . light_dir ) # Draw World self . on_draw_world ( ) # Iterate over all of the post processing effects if self . post_processing : if len ( self . post_processing ) > 1 : newarg = self . textures . copy ( ) # Ping-pong framebuffer rendering for i , pp in enumerate ( self . post_processing [ : - 1 ] ) : if i % 2 : outfb = self . fb1 outtex = self . _extra_textures [ 'fb1' ] else : outfb = self . fb2 outtex = self . _extra_textures [ 'fb2' ] pp . render ( outfb , newarg ) newarg [ 'color' ] = outtex self . post_processing [ - 1 ] . render ( DEFAULT_FRAMEBUFFER , newarg ) else : self . post_processing [ 0 ] . render ( DEFAULT_FRAMEBUFFER , self . textures ) # Draw the UI at the very last step self . on_draw_ui ( )
GL function called each time a frame is drawn
648
9
248,140
def toimage ( self , width = None , height = None ) : from . postprocessing import NoEffect effect = NoEffect ( self ) self . post_processing . append ( effect ) oldwidth , oldheight = self . width ( ) , self . height ( ) #self.initializeGL() if None not in ( width , height ) : self . resize ( width , height ) self . resizeGL ( width , height ) else : width = self . width ( ) height = self . height ( ) self . paintGL ( ) self . post_processing . remove ( effect ) coltex = effect . texture coltex . bind ( ) glActiveTexture ( GL_TEXTURE0 ) data = glGetTexImage ( GL_TEXTURE_2D , 0 , GL_RGBA , GL_UNSIGNED_BYTE ) image = pil_Image . frombuffer ( 'RGBA' , ( width , height ) , data , 'raw' , 'RGBA' , 0 , - 1 ) #self.resize(oldwidth, oldheight) #self.resizeGL(oldwidth, oldheight) return image
Return the current scene as a PIL Image .
236
10
248,141
def _real ( coords1 , charges1 , coords2 , charges2 , rcut , alpha , box ) : n = coords1 . shape [ 0 ] m = coords2 . shape [ 0 ] # Unit vectors a = box [ 0 ] b = box [ 1 ] c = box [ 2 ] # This is helpful to add the correct number of boxes l_max = int ( np . ceil ( 2.0 * rcut / np . min ( np . trace ( box ) ) ) ) result = np . zeros ( n ) for i in range ( n ) : q_i = charges1 [ i ] r_i = coords1 [ i ] for j in range ( m ) : q_j = charges2 [ j ] r_j = coords2 [ j ] for l_i in range ( - l_max , l_max + 1 ) : for l_j in range ( - l_max , l_max + 1 ) : for l_k in range ( - l_max , l_max + 1 ) : nv = l_i * a + l_j * b + l_k * c r_j_n = r_j + nv r_ij = _dist ( r_i , r_j_n ) if r_ij < 1e-10 or r_ij > rcut : continue value = q_i * q_j * math . erfc ( alpha * r_ij ) / r_ij result [ i ] += value return result
Calculate ewald real part . Box has to be a cuboidal box you should transform any other box shape to a cuboidal box before using this .
329
32
248,142
def _reciprocal ( coords1 , charges1 , coords2 , charges2 , kmax , kappa , box ) : n = coords1 . shape [ 0 ] m = coords2 . shape [ 0 ] result = np . zeros ( n , dtype = np . float64 ) need_self = np . zeros ( n , dtype = np . uint8 ) # Reciprocal unit vectors g1 , g2 , g3 = reciprocal_vectors ( box ) V = box_volume ( box ) prefac = 1.0 / ( np . pi * V ) for i in range ( n ) : q_i = charges1 [ i ] r_i = coords1 [ i ] for j in range ( m ) : q_j = charges2 [ j ] r_j = coords2 [ j ] r_ij = _dist ( r_i , r_j ) if r_ij < 1e-10 : need_self [ i ] = 1 for k_i in range ( - kmax , kmax + 1 ) : for k_j in range ( - kmax , kmax + 1 ) : for k_k in range ( - kmax , kmax + 1 ) : if k_i == 0 and k_j == 0 and k_k == 0 : continue # Reciprocal vector k = k_i * g1 + k_j * g2 + k_k * g3 k_sq = sqsum ( k ) result [ i ] += ( prefac * q_i * q_j * 4.0 * np . pi ** 2 / k_sq * math . exp ( - k_sq / ( 4.0 * kappa ** 2 ) ) * math . cos ( np . dot ( k , r_i - r_j ) ) ) # Self-energy correction # I had to do some FUCKED UP stuff because NUMBA SUCKS BALLS and # breaks compatibility with simple expressions such as that one # apparently doing result -= something is too hard in numba self_energy = 2 * ( need_self * kappa * charges1 ** 2 ) / ( np . pi ** 0.5 ) return result - self_energy
Calculate ewald reciprocal part . Box has to be a cuboidal box you should transform any other box shape to a cuboidal box before using this .
476
32
248,143
def update_bounds ( self , bounds ) : starts = bounds [ : , 0 , : ] ends = bounds [ : , 1 , : ] self . bounds = bounds self . lengths = np . sqrt ( ( ( ends - starts ) ** 2 ) . sum ( axis = 1 ) ) vertices , normals , colors = self . _process_reference ( ) self . tr . update_vertices ( vertices ) self . tr . update_normals ( normals )
Update cylinders start and end positions
102
6
248,144
def make_trajectory ( first , filename , restart = False ) : mode = 'w' if restart : mode = 'a' return Trajectory ( first , filename , mode )
Factory function to easily create a trajectory object
40
8
248,145
def has_key ( self , key ) : k = self . _lowerOrReturn ( key ) return k in self . data
Case insensitive test whether key exists .
27
7
248,146
def update_positions ( self , positions ) : sphs_verts = self . sphs_verts_radii . copy ( ) sphs_verts += positions . reshape ( self . n_spheres , 1 , 3 ) self . tr . update_vertices ( sphs_verts ) self . poslist = positions
Update the sphere positions .
70
5
248,147
def isnamedtuple ( obj ) : return isinstance ( obj , tuple ) and hasattr ( obj , "_fields" ) and hasattr ( obj , "_asdict" ) and callable ( obj . _asdict )
Heuristic check if an object is a namedtuple .
48
12
248,148
def running_coordination_number ( coordinates_a , coordinates_b , periodic , binsize = 0.002 , cutoff = 1.5 ) : x , y = rdf ( coordinates_a , coordinates_b , periodic = periodic , normalize = False , binsize = binsize , cutoff = cutoff ) y = y . astype ( 'float32' ) / len ( coordinates_a ) y = np . cumsum ( y ) return x , y
This is the cumulative radial distribution function also called running coordination number
99
12
248,149
def update_colors ( self , colors ) : colors = np . array ( colors , dtype = np . uint8 ) self . _vbo_c . set_data ( colors ) self . _vbo_c . unbind ( )
Update the colors
53
3
248,150
def frames ( skip = 1 ) : from PyQt4 import QtGui for i in range ( 0 , viewer . traj_controls . max_index , skip ) : viewer . traj_controls . goto_frame ( i ) yield i QtGui . qApp . processEvents ( )
Useful command to iterate on the trajectory frames . It can be used in a for loop .
66
20
248,151
def display_system ( system , autozoom = True ) : viewer . clear ( ) viewer . add_representation ( BallAndStickRepresentation , system ) if autozoom : autozoom_ ( ) viewer . update ( ) msg ( str ( system ) )
Display a ~chemlab . core . System instance at screen
58
13
248,152
def display_molecule ( mol , autozoom = True ) : s = System ( [ mol ] ) display_system ( s , autozoom = True )
Display a ~chemlab . core . Molecule instance in the viewer .
36
16
248,153
def load_molecule ( name , format = None ) : mol = datafile ( name , format = format ) . read ( 'molecule' ) display_system ( System ( [ mol ] ) )
Read a ~chemlab . core . Molecule from a file .
45
15
248,154
def write_system ( filename , format = None ) : datafile ( filename , format = format , mode = 'w' ) . write ( 'system' , current_system ( ) )
Write the system currently displayed to a file .
40
9
248,155
def write_molecule ( filename , format = None ) : datafile ( filename , format = format , mode = 'w' ) . write ( 'molecule' , current_system ( ) )
Write the system displayed in a file as a molecule .
44
11
248,156
def load_trajectory ( name , skip = 1 , format = None ) : df = datafile ( name , format = format ) dt , coords = df . read ( 'trajectory' , skip = skip ) boxes = df . read ( 'boxes' ) viewer . current_traj = coords viewer . frame_times = dt viewer . traj_controls . set_ticks ( len ( dt ) ) def update ( index ) : f = coords [ index ] for fp in _frame_processors : f = fp ( coords , index ) # update the current representation viewer . representation . update_positions ( f ) viewer . representation . update_box ( boxes [ index ] ) current_system ( ) . r_array = f current_system ( ) . box_vectors = boxes [ index ] viewer . traj_controls . set_time ( dt [ index ] ) viewer . update ( ) viewer . traj_controls . show ( ) viewer . traj_controls . frame_changed . connect ( update )
Load a trajectory file into chemlab . You should call this command after you load a ~chemlab . core . System through load_system or load_remote_system .
233
37
248,157
def from_arrays ( cls , * * kwargs ) : if 'mol_indices' in kwargs : raise DeprecationWarning ( 'The mol_indices argument is deprecated, use maps instead. (See from_arrays docstring)' ) return super ( System , cls ) . from_arrays ( * * kwargs )
Initialize a System from its constituent arrays . It is the fastest way to initialize a System well suited for reading one or more big System from data files .
78
31
248,158
def minimum_image ( self ) : if self . box_vectors is None : raise ValueError ( 'No periodic vectors defined' ) else : self . r_array = minimum_image ( self . r_array , self . box_vectors . diagonal ( ) ) return self
Align the system according to the minimum image convention
60
10
248,159
def where ( self , within_of = None , inplace = False , * * kwargs ) : masks = super ( System , self ) . where ( inplace = inplace , * * kwargs ) def index_to_mask ( index , n ) : val = np . zeros ( n , dtype = 'bool' ) val [ index ] = True return val def masks_and ( dict1 , dict2 ) : return { k : dict1 [ k ] & index_to_mask ( dict2 [ k ] , len ( dict1 [ k ] ) ) for k in dict1 } if within_of is not None : if self . box_vectors is None : raise Exception ( 'Only periodic distance supported' ) thr , ref = within_of if isinstance ( ref , int ) : a = self . r_array [ ref ] [ np . newaxis , np . newaxis , : ] # (1, 1, 3,) elif len ( ref ) == 1 : a = self . r_array [ ref ] [ np . newaxis , : ] # (1, 1, 3) else : a = self . r_array [ ref ] [ : , np . newaxis , : ] # (2, 1, 3) b = self . r_array [ np . newaxis , : , : ] dist = periodic_distance ( a , b , periodic = self . box_vectors . diagonal ( ) ) atoms = ( dist <= thr ) . sum ( axis = 0 , dtype = 'bool' ) m = self . _propagate_dim ( atoms , 'atom' ) masks = masks_and ( masks , m ) return masks
Return indices that met the conditions
360
6
248,160
def _gser ( a , x ) : ITMAX = 100 EPS = 3.e-7 gln = lgamma ( a ) assert ( x >= 0 ) , 'x < 0 in gser' if x == 0 : return 0 , gln ap = a delt = sum = 1. / a for i in range ( ITMAX ) : ap = ap + 1. delt = delt * x / ap sum = sum + delt if abs ( delt ) < abs ( sum ) * EPS : break else : print ( 'a too large, ITMAX too small in gser' ) gamser = sum * np . exp ( - x + a * np . log ( x ) - gln ) return gamser , gln
Series representation of Gamma . NumRec sect 6 . 1 .
160
12
248,161
def _gcf ( a , x ) : ITMAX = 100 EPS = 3.e-7 FPMIN = 1.e-30 gln = lgamma ( a ) b = x + 1. - a c = 1. / FPMIN d = 1. / b h = d for i in range ( 1 , ITMAX + 1 ) : an = - i * ( i - a ) b = b + 2. d = an * d + b if abs ( d ) < FPMIN : d = FPMIN c = b + an / c if abs ( c ) < FPMIN : c = FPMIN d = 1. / d delt = d * c h = h * delt if abs ( delt - 1. ) < EPS : break else : print ( 'a too large, ITMAX too small in gcf' ) gammcf = np . exp ( - x + a * np . log ( x ) - gln ) * h return gammcf , gln
Continued fraction representation of Gamma . NumRec sect 6 . 1
218
13
248,162
def dmat ( c , nocc ) : return np . dot ( c [ : , : nocc ] , c [ : , : nocc ] . T )
Form the density matrix from the first nocc orbitals of c
35
13
248,163
def geigh ( H , S ) : A = cholorth ( S ) E , U = np . linalg . eigh ( simx ( H , A ) ) return E , np . dot ( A , U )
Solve the generalized eigensystem Hc = ESc
49
13
248,164
def _check_periodic ( periodic ) : periodic = np . array ( periodic ) # If it is a matrix if len ( periodic . shape ) == 2 : assert periodic . shape [ 0 ] == periodic . shape [ 1 ] , 'periodic shoud be a square matrix or a flat array' return np . diag ( periodic ) elif len ( periodic . shape ) == 1 : return periodic else : raise ValueError ( "periodic argument can be either a 3x3 matrix or a shape 3 array." )
Validate periodic input
109
4
248,165
def count_neighbors ( coordinates_a , coordinates_b , periodic , r ) : indices = nearest_neighbors ( coordinates_a , coordinates_b , periodic , r = r ) [ 0 ] if len ( indices ) == 0 : return 0 if isinstance ( indices [ 0 ] , collections . Iterable ) : return [ len ( ix ) for ix in indices ] else : return len ( indices )
Count the neighbours number of neighbors .
90
7
248,166
def change_default_radii ( def_map ) : s = current_system ( ) rep = current_representation ( ) rep . radii_state . default = [ def_map [ t ] for t in s . type_array ] rep . radii_state . reset ( )
Change the default radii
63
5
248,167
def add_post_processing ( effect , * * options ) : from chemlab . graphics . postprocessing import SSAOEffect , OutlineEffect , FXAAEffect , GammaCorrectionEffect pp_map = { 'ssao' : SSAOEffect , 'outline' : OutlineEffect , 'fxaa' : FXAAEffect , 'gamma' : GammaCorrectionEffect } pp = viewer . add_post_processing ( pp_map [ effect ] , * * options ) viewer . update ( ) global _counter _counter += 1 str_id = effect + str ( _counter ) _effect_map [ str_id ] = pp # saving it for removal for later... return str_id
Apply a post processing effect .
149
6
248,168
def unit_vector ( x ) : y = np . array ( x , dtype = 'float' ) return y / norm ( y )
Return a unit vector in the same direction as x .
30
11
248,169
def angle ( x , y ) : return arccos ( dot ( x , y ) / ( norm ( x ) * norm ( y ) ) ) * 180. / pi
Return the angle between vectors a and b in degrees .
37
11
248,170
def metric_from_cell ( cell ) : cell = np . asarray ( cell , dtype = float ) return np . dot ( cell , cell . T )
Calculates the metric matrix from cell which is given in the Cartesian system .
35
17
248,171
def add_default_handler ( ioclass , format , extension = None ) : if format in _handler_map : print ( "Warning: format {} already present." . format ( format ) ) _handler_map [ format ] = ioclass if extension in _extensions_map : print ( "Warning: extension {} already handled by {} handler." . format ( extension , _extensions_map [ extension ] ) ) if extension is not None : _extensions_map [ extension ] = format
Register a new data handler for a given format in the default handler list .
106
15
248,172
def minimum_image ( coords , pbc ) : # This will do the broadcasting coords = np . array ( coords ) pbc = np . array ( pbc ) # For each coordinate this number represents which box we are in image_number = np . floor ( coords / pbc ) wrap = coords - pbc * image_number return wrap
Wraps a vector collection of atom positions into the central periodic image or primary simulation cell .
77
18
248,173
def subtract_vectors ( a , b , periodic ) : r = a - b delta = np . abs ( r ) sign = np . sign ( r ) return np . where ( delta > 0.5 * periodic , sign * ( periodic - delta ) , r )
Returns the difference of the points vec_a - vec_b subject to the periodic boundary conditions .
57
20
248,174
def add_vectors ( vec_a , vec_b , periodic ) : moved = noperiodic ( np . array ( [ vec_a , vec_b ] ) , periodic ) return vec_a + vec_b
Returns the sum of the points vec_a - vec_b subject to the periodic boundary conditions .
49
20
248,175
def distance_matrix ( a , b , periodic ) : a = a b = b [ : , np . newaxis ] return periodic_distance ( a , b , periodic )
Calculate a distrance matrix between coordinates sets a and b
38
13
248,176
def geometric_center ( coords , periodic ) : max_vals = periodic theta = 2 * np . pi * ( coords / max_vals ) eps = np . cos ( theta ) * max_vals / ( 2 * np . pi ) zeta = np . sin ( theta ) * max_vals / ( 2 * np . pi ) eps_avg = eps . sum ( axis = 0 ) zeta_avg = zeta . sum ( axis = 0 ) theta_avg = np . arctan2 ( - zeta_avg , - eps_avg ) + np . pi return theta_avg * max_vals / ( 2 * np . pi )
Geometric center taking into account periodic boundaries
156
8
248,177
def radius_of_gyration ( coords , periodic ) : gc = geometric_center ( coords , periodic ) return ( periodic_distance ( coords , gc , periodic ) ** 2 ) . sum ( ) / len ( coords )
Calculate the square root of the mean distance squared from the center of gravity .
53
17
248,178
def find ( query ) : assert type ( query ) == str or type ( query ) == str , 'query not a string object' searchurl = 'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s' % ( urlquote ( query ) , TOKEN ) response = urlopen ( searchurl ) tree = ET . parse ( response ) elem = tree . getroot ( ) csid_tags = elem . getiterator ( '{http://www.chemspider.com/}int' ) compoundlist = [ ] for tag in csid_tags : compoundlist . append ( Compound ( tag . text ) ) return compoundlist if compoundlist else None
Search by Name SMILES InChI InChIKey etc . Returns first 100 Compounds
159
20
248,179
def imageurl ( self ) : if self . _imageurl is None : self . _imageurl = 'http://www.chemspider.com/ImagesHandler.ashx?id=%s' % self . csid return self . _imageurl
Return the URL of a png image of the 2D structure
56
13
248,180
def loadextendedcompoundinfo ( self ) : apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s' % ( self . csid , TOKEN ) response = urlopen ( apiurl ) tree = ET . parse ( response ) mf = tree . find ( '{http://www.chemspider.com/}MF' ) self . _mf = mf . text if mf is not None else None smiles = tree . find ( '{http://www.chemspider.com/}SMILES' ) self . _smiles = smiles . text if smiles is not None else None inchi = tree . find ( '{http://www.chemspider.com/}InChI' ) self . _inchi = inchi . text if inchi is not None else None inchikey = tree . find ( '{http://www.chemspider.com/}InChIKey' ) self . _inchikey = inchikey . text if inchikey is not None else None averagemass = tree . find ( '{http://www.chemspider.com/}AverageMass' ) self . _averagemass = float ( averagemass . text ) if averagemass is not None else None molecularweight = tree . find ( '{http://www.chemspider.com/}MolecularWeight' ) self . _molecularweight = float ( molecularweight . text ) if molecularweight is not None else None monoisotopicmass = tree . find ( '{http://www.chemspider.com/}MonoisotopicMass' ) self . _monoisotopicmass = float ( monoisotopicmass . text ) if monoisotopicmass is not None else None nominalmass = tree . find ( '{http://www.chemspider.com/}NominalMass' ) self . _nominalmass = float ( nominalmass . text ) if nominalmass is not None else None alogp = tree . find ( '{http://www.chemspider.com/}ALogP' ) self . _alogp = float ( alogp . text ) if alogp is not None else None xlogp = tree . find ( '{http://www.chemspider.com/}XLogP' ) self . _xlogp = float ( xlogp . text ) if xlogp is not None else None commonname = tree . find ( '{http://www.chemspider.com/}CommonName' ) self . _commonname = commonname . text if commonname is not None else None
Load extended compound info from the Mass Spec API
612
9
248,181
def image ( self ) : if self . _image is None : apiurl = 'http://www.chemspider.com/Search.asmx/GetCompoundThumbnail?id=%s&token=%s' % ( self . csid , TOKEN ) response = urlopen ( apiurl ) tree = ET . parse ( response ) self . _image = tree . getroot ( ) . text return self . _image
Return string containing PNG binary image data of 2D structure image
93
12
248,182
def mol ( self ) : if self . _mol is None : apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % ( self . csid , TOKEN ) response = urlopen ( apiurl ) tree = ET . parse ( response ) self . _mol = tree . getroot ( ) . text return self . _mol
Return record in MOL format
103
6
248,183
def mol3d ( self ) : if self . _mol3d is None : apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s' % ( self . csid , TOKEN ) response = urlopen ( apiurl ) tree = ET . parse ( response ) self . _mol3d = tree . getroot ( ) . text return self . _mol3d
Return record in MOL format with 3D coordinates calculated
111
11
248,184
def update_positions ( self , r_array ) : self . ar . update_positions ( r_array ) if self . has_bonds : self . br . update_positions ( r_array )
Update the coordinate array r_array
47
7
248,185
def concatenate_attributes ( attributes ) : # We get a template/ tpl = attributes [ 0 ] attr = InstanceAttribute ( tpl . name , tpl . shape , tpl . dtype , tpl . dim , alias = None ) # Special case, not a single array has size bigger than 0 if all ( a . size == 0 for a in attributes ) : return attr else : attr . value = np . concatenate ( [ a . value for a in attributes if a . size > 0 ] , axis = 0 ) return attr
Concatenate InstanceAttribute to return a bigger one .
122
13
248,186
def concatenate_fields ( fields , dim ) : if len ( fields ) == 0 : raise ValueError ( 'fields cannot be an empty list' ) if len ( set ( ( f . name , f . shape , f . dtype ) for f in fields ) ) != 1 : raise ValueError ( 'fields should have homogeneous name, shape and dtype' ) tpl = fields [ 0 ] attr = InstanceAttribute ( tpl . name , shape = tpl . shape , dtype = tpl . dtype , dim = dim , alias = None ) attr . value = np . array ( [ f . value for f in fields ] , dtype = tpl . dtype ) return attr
Create an INstanceAttribute from a list of InstnaceFields
153
15
248,187
def normalize_index ( index ) : index = np . asarray ( index ) if len ( index ) == 0 : return index . astype ( 'int' ) if index . dtype == 'bool' : index = index . nonzero ( ) [ 0 ] elif index . dtype == 'int' : pass else : raise ValueError ( 'Index should be either integer or bool' ) return index
normalize numpy index
87
5
248,188
def to_dict ( self ) : ret = merge_dicts ( self . __attributes__ , self . __relations__ , self . __fields__ ) ret = { k : v . value for k , v in ret . items ( ) } ret [ 'maps' ] = { k : v . value for k , v in self . maps . items ( ) } return ret
Return a dict representing the ChemicalEntity that can be read back using from_dict .
81
17
248,189
def from_json ( cls , string ) : exp_dict = json_to_data ( string ) version = exp_dict . get ( 'version' , 0 ) if version == 0 : return cls . from_dict ( exp_dict ) elif version == 1 : return cls . from_dict ( exp_dict ) else : raise ValueError ( "Version %d not supported" % version )
Create a ChemicalEntity from a json string
88
8
248,190
def copy ( self ) : inst = super ( type ( self ) , type ( self ) ) . empty ( * * self . dimensions ) # Need to copy all attributes, fields, relations inst . __attributes__ = { k : v . copy ( ) for k , v in self . __attributes__ . items ( ) } inst . __fields__ = { k : v . copy ( ) for k , v in self . __fields__ . items ( ) } inst . __relations__ = { k : v . copy ( ) for k , v in self . __relations__ . items ( ) } inst . maps = { k : m . copy ( ) for k , m in self . maps . items ( ) } inst . dimensions = self . dimensions . copy ( ) return inst
Create a copy of this ChemicalEntity
166
7
248,191
def copy_from ( self , other ) : # Need to copy all attributes, fields, relations self . __attributes__ = { k : v . copy ( ) for k , v in other . __attributes__ . items ( ) } self . __fields__ = { k : v . copy ( ) for k , v in other . __fields__ . items ( ) } self . __relations__ = { k : v . copy ( ) for k , v in other . __relations__ . items ( ) } self . maps = { k : m . copy ( ) for k , m in other . maps . items ( ) } self . dimensions = other . dimensions . copy ( )
Copy properties from another ChemicalEntity
145
6
248,192
def update ( self , dictionary ) : allowed_attrs = list ( self . __attributes__ . keys ( ) ) allowed_attrs += [ a . alias for a in self . __attributes__ . values ( ) ] for k in dictionary : # We only update existing attributes if k in allowed_attrs : setattr ( self , k , dictionary [ k ] ) return self
Update the current chemical entity from a dictionary of attributes
82
10
248,193
def subentity ( self , Entity , index ) : dim = Entity . __dimension__ entity = Entity . empty ( ) if index >= self . dimensions [ dim ] : raise ValueError ( 'index {} out of bounds for dimension {} (size {})' . format ( index , dim , self . dimensions [ dim ] ) ) for name , attr in self . __attributes__ . items ( ) : if attr . dim == dim : # If the dimension of the attributes is the same of the # dimension of the entity, we generate a field entity . __fields__ [ name ] = attr . field ( index ) elif attr . dim in entity . dimensions : # Special case, we don't need to do anything if self . dimensions [ attr . dim ] == 0 : continue # Else, we generate a subattribute mapped_index = self . maps [ attr . dim , dim ] . value == index entity . __attributes__ [ name ] = attr . sub ( mapped_index ) entity . dimensions [ attr . dim ] = np . count_nonzero ( mapped_index ) for name , rel in self . __relations__ . items ( ) : if rel . map == dim : # The relation is between entities we need to return # which means the entity doesn't know about that pass if rel . map in entity . dimensions : # Special case, we don't need to do anything if self . dimensions [ rel . dim ] == 0 : continue mapped_index = self . maps [ rel . dim , dim ] . value == index entity . __relations__ [ name ] = rel . sub ( mapped_index ) entity . dimensions [ rel . dim ] = np . count_nonzero ( mapped_index ) # We need to remap values convert_index = self . maps [ rel . map , dim ] . value == index entity . __relations__ [ name ] . remap ( convert_index . nonzero ( ) [ 0 ] , range ( entity . dimensions [ rel . map ] ) ) return entity
Return child entity
427
3
248,194
def sub_dimension ( self , index , dimension , propagate = True , inplace = False ) : filter_ = self . _propagate_dim ( index , dimension , propagate ) return self . subindex ( filter_ , inplace )
Return a ChemicalEntity sliced through a dimension . If other dimensions depend on this one those are updated accordingly .
50
21
248,195
def expand_dimension ( self , newdim , dimension , maps = { } , relations = { } ) : for name , attr in self . __attributes__ . items ( ) : if attr . dim == dimension : newattr = attr . copy ( ) newattr . empty ( newdim - attr . size ) self . __attributes__ [ name ] = concatenate_attributes ( [ attr , newattr ] ) for name , rel in self . __relations__ . items ( ) : if dimension == rel . dim : # We need the new relation from the user if not rel . name in relations : raise ValueError ( 'You need to provide the relation {} for this resize' . format ( rel . name ) ) else : if len ( relations [ name ] ) != newdim : raise ValueError ( 'New relation {} should be of size {}' . format ( rel . name , newdim ) ) else : self . __relations__ [ name ] . value = relations [ name ] elif dimension == rel . map : # Extend the index rel . index = range ( newdim ) for ( a , b ) , rel in self . maps . items ( ) : if dimension == rel . dim : # We need the new relation from the user if not ( a , b ) in maps : raise ValueError ( 'You need to provide the map {}->{} for this resize' . format ( a , b ) ) else : if len ( maps [ a , b ] ) != newdim : raise ValueError ( 'New map {} should be of size {}' . format ( rel . name , newdim ) ) else : rel . value = maps [ a , b ] elif dimension == rel . map : # Extend the index rel . index = range ( newdim ) # Update dimensions self . dimensions [ dimension ] = newdim return self
When we expand we need to provide new maps and relations as those can t be inferred
393
17
248,196
def concat ( self , other , inplace = False ) : # Create new entity if inplace : obj = self else : obj = self . copy ( ) # Stitch every attribute for name , attr in obj . __attributes__ . items ( ) : attr . append ( other . __attributes__ [ name ] ) # Stitch every relation for name , rel in obj . __relations__ . items ( ) : rel . append ( other . __relations__ [ name ] ) # Update maps # Update dimensions if obj . is_empty ( ) : obj . maps = { k : m . copy ( ) for k , m in other . maps . items ( ) } obj . dimensions = other . dimensions . copy ( ) else : for ( a , b ) , rel in obj . maps . items ( ) : rel . append ( other . maps [ a , b ] ) for d in obj . dimensions : obj . dimensions [ d ] += other . dimensions [ d ] return obj
Concatenate two ChemicalEntity of the same kind
209
11
248,197
def sub ( self , inplace = False , * * kwargs ) : filter_ = self . where ( * * kwargs ) return self . subindex ( filter_ , inplace )
Return a entity where the conditions are met
42
8
248,198
def sub ( self , index ) : index = np . asarray ( index ) if index . dtype == 'bool' : index = index . nonzero ( ) [ 0 ] if self . size < len ( index ) : raise ValueError ( 'Can\'t subset "{}": index ({}) is bigger than the number of elements ({})' . format ( self . name , len ( index ) , self . size ) ) inst = self . copy ( ) size = len ( index ) inst . empty ( size ) if len ( index ) > 0 : inst . value = self . value . take ( index , axis = 0 ) return inst
Return a sub - attribute
135
5
248,199
def resolve ( input , representation , resolvers = None , * * kwargs ) : resultdict = query ( input , representation , resolvers , * * kwargs ) result = resultdict [ 0 ] [ 'value' ] if resultdict else None if result and len ( result ) == 1 : result = result [ 0 ] return result
Resolve input to the specified output representation
74
8