idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
14,900
def POINTER ( self , _cursor_type ) : comment = None _type = _cursor_type . get_pointee ( ) . get_canonical ( ) _p_type_name = self . get_unique_name ( _type ) size = _cursor_type . get_size ( ) align = _cursor_type . get_align ( ) log . debug ( "POINTER: size:%d align:%d typ:%s" , size , align , _type . kind ) if self . is_fundamental_type ( _type ) : p_type = self . parse_cursor_type ( _type ) elif self . is_pointer_type ( _type ) or self . is_array_type ( _type ) : p_type = self . parse_cursor_type ( _type ) elif _type . kind == TypeKind . FUNCTIONPROTO : p_type = self . parse_cursor_type ( _type ) elif _type . kind == TypeKind . FUNCTIONNOPROTO : p_type = self . parse_cursor_type ( _type ) else : decl = _type . get_declaration ( ) decl_name = self . get_unique_name ( decl ) if self . is_registered ( decl_name ) : p_type = self . get_registered ( decl_name ) else : log . debug ( 'POINTER: %s type was not previously declared' , decl_name ) try : p_type = self . parse_cursor ( decl ) except InvalidDefinitionError as e : p_type = typedesc . FundamentalType ( 'None' , 1 , 1 ) comment = "InvalidDefinitionError" log . debug ( "POINTER: pointee type_name:'%s'" , _p_type_name ) obj = typedesc . PointerType ( p_type , size , align ) obj . location = p_type . location if comment is not None : obj . comment = comment return obj
Handles POINTER types .
14,901
def _array_handler ( self , _cursor_type ) : _type = _cursor_type . get_canonical ( ) size = _type . get_array_size ( ) if size == - 1 and _type . kind == TypeKind . INCOMPLETEARRAY : size = 0 _array_type = _type . get_array_element_type ( ) if self . is_fundamental_type ( _array_type ) : _subtype = self . parse_cursor_type ( _array_type ) elif self . is_pointer_type ( _array_type ) : _subtype = self . parse_cursor_type ( _array_type ) elif self . is_array_type ( _array_type ) : _subtype = self . parse_cursor_type ( _array_type ) else : _subtype_decl = _array_type . get_declaration ( ) _subtype = self . parse_cursor ( _subtype_decl ) obj = typedesc . ArrayType ( _subtype , size ) obj . location = _subtype . location return obj
Handles all array types . Resolves it s element type and makes a Array typedesc .
14,902
def FUNCTIONPROTO ( self , _cursor_type ) : returns = _cursor_type . get_result ( ) returns = self . parse_cursor_type ( returns ) attributes = [ ] obj = typedesc . FunctionType ( returns , attributes ) for i , _attr_type in enumerate ( _cursor_type . argument_types ( ) ) : arg = typedesc . Argument ( "a%d" % ( i ) , self . parse_cursor_type ( _attr_type ) ) obj . add_argument ( arg ) self . set_location ( obj , None ) return obj
Handles function prototype .
14,903
def FUNCTIONNOPROTO ( self , _cursor_type ) : returns = _cursor_type . get_result ( ) returns = self . parse_cursor_type ( returns ) attributes = [ ] obj = typedesc . FunctionType ( returns , attributes ) self . set_location ( obj , None ) return obj
Handles function with no prototype .
14,904
def UNEXPOSED ( self , _cursor_type ) : _decl = _cursor_type . get_declaration ( ) name = self . get_unique_name ( _decl ) if self . is_registered ( name ) : obj = self . get_registered ( name ) else : obj = self . parse_cursor ( _decl ) return obj
Handles unexposed types . Returns the canonical type instead .
14,905
def INIT_LIST_EXPR ( self , cursor ) : values = [ self . parse_cursor ( child ) for child in list ( cursor . get_children ( ) ) ] return values
Returns a list of literal values .
14,906
def ENUM_CONSTANT_DECL ( self , cursor ) : name = cursor . displayname value = cursor . enum_value pname = self . get_unique_name ( cursor . semantic_parent ) parent = self . get_registered ( pname ) obj = typedesc . EnumValue ( name , value , parent ) parent . add_value ( obj ) return obj
Gets the enumeration values
14,907
def ENUM_DECL ( self , cursor ) : name = self . get_unique_name ( cursor ) if self . is_registered ( name ) : return self . get_registered ( name ) align = cursor . type . get_align ( ) size = cursor . type . get_size ( ) obj = self . register ( name , typedesc . Enumeration ( name , size , align ) ) self . set_location ( obj , cursor ) self . set_comment ( obj , cursor ) for child in cursor . get_children ( ) : self . parse_cursor ( child ) return obj
Gets the enumeration declaration .
14,908
def FUNCTION_DECL ( self , cursor ) : name = self . get_unique_name ( cursor ) if self . is_registered ( name ) : return self . get_registered ( name ) returns = self . parse_cursor_type ( cursor . type . get_result ( ) ) attributes = [ ] extern = False obj = typedesc . Function ( name , returns , attributes , extern ) for arg in cursor . get_arguments ( ) : arg_obj = self . parse_cursor ( arg ) obj . add_argument ( arg_obj ) self . register ( name , obj ) self . set_location ( obj , cursor ) self . set_comment ( obj , cursor ) return obj
Handles function declaration
14,909
def PARM_DECL ( self , cursor ) : _type = cursor . type _name = cursor . spelling if ( self . is_array_type ( _type ) or self . is_fundamental_type ( _type ) or self . is_pointer_type ( _type ) or self . is_unexposed_type ( _type ) ) : _argtype = self . parse_cursor_type ( _type ) else : _argtype_decl = _type . get_declaration ( ) _argtype_name = self . get_unique_name ( _argtype_decl ) if not self . is_registered ( _argtype_name ) : log . info ( 'This param type is not declared: %s' , _argtype_name ) _argtype = self . parse_cursor_type ( _type ) else : _argtype = self . get_registered ( _argtype_name ) obj = typedesc . Argument ( _name , _argtype ) self . set_location ( obj , cursor ) self . set_comment ( obj , cursor ) return obj
Handles parameter declarations .
14,910
def VAR_DECL ( self , cursor ) : name = self . get_unique_name ( cursor ) log . debug ( 'VAR_DECL: name: %s' , name ) if self . is_registered ( name ) : return self . get_registered ( name ) _type = self . _VAR_DECL_type ( cursor ) init_value = self . _VAR_DECL_value ( cursor , _type ) log . debug ( 'VAR_DECL: _type:%s' , _type . name ) log . debug ( 'VAR_DECL: _init:%s' , init_value ) log . debug ( 'VAR_DECL: location:%s' , getattr ( cursor , 'location' ) ) obj = self . register ( name , typedesc . Variable ( name , _type , init_value ) ) self . set_location ( obj , cursor ) self . set_comment ( obj , cursor ) return True
Handles Variable declaration .
14,911
def _VAR_DECL_type ( self , cursor ) : _ctype = cursor . type . get_canonical ( ) log . debug ( 'VAR_DECL: _ctype: %s ' , _ctype . kind ) if self . is_fundamental_type ( _ctype ) : ctypesname = self . get_ctypes_name ( _ctype . kind ) _type = typedesc . FundamentalType ( ctypesname , 0 , 0 ) elif self . is_unexposed_type ( _ctype ) : st = 'PATCH NEEDED: %s type is not exposed by clang' % ( self . get_unique_name ( cursor ) ) log . error ( st ) raise RuntimeError ( st ) elif self . is_array_type ( _ctype ) or _ctype . kind == TypeKind . RECORD : _type = self . parse_cursor_type ( _ctype ) elif self . is_pointer_type ( _ctype ) : if self . is_unexposed_type ( _ctype . get_pointee ( ) ) : _type = self . parse_cursor_type ( _ctype . get_canonical ( ) . get_pointee ( ) ) elif _ctype . get_pointee ( ) . kind == TypeKind . FUNCTIONPROTO : _type = self . parse_cursor_type ( _ctype . get_pointee ( ) ) else : _type = self . parse_cursor_type ( _ctype ) else : raise NotImplementedError ( 'What other type of variable? %s' % ( _ctype . kind ) ) log . debug ( 'VAR_DECL: _type: %s ' , _type ) return _type
Generates a typedesc object from a Variable declaration .
14,912
def _VAR_DECL_value ( self , cursor , _type ) : init_value = self . _get_var_decl_init_value ( cursor . type , list ( cursor . get_children ( ) ) ) _ctype = cursor . type . get_canonical ( ) if self . is_unexposed_type ( _ctype ) : init_value = '%s # UNEXPOSED TYPE. PATCH NEEDED.' % ( init_value ) elif ( self . is_pointer_type ( _ctype ) and _ctype . get_pointee ( ) . kind == TypeKind . FUNCTIONPROTO ) : init_value = _type elif self . is_array_type ( _ctype ) : def countof ( k , l ) : return [ item [ 0 ] for item in l ] . count ( k ) if ( countof ( CursorKind . INIT_LIST_EXPR , init_value ) == 1 ) : init_value = dict ( init_value ) [ CursorKind . INIT_LIST_EXPR ] elif ( countof ( CursorKind . STRING_LITERAL , init_value ) == 1 ) : init_value = dict ( init_value ) [ CursorKind . STRING_LITERAL ] else : init_value = [ ] if _type . size < len ( init_value ) : _type . size = len ( init_value ) elif init_value == [ ] : init_value = None else : log . debug ( 'VAR_DECL: default init_value: %s' , init_value ) if len ( init_value ) > 0 : init_value = init_value [ 0 ] [ 1 ] return init_value
Handles Variable value initialization .
14,913
def _get_var_decl_init_value ( self , _ctype , children ) : init_value = [ ] children = list ( children ) log . debug ( '_get_var_decl_init_value: children #: %d' , len ( children ) ) for child in children : _tmp = None try : _tmp = self . _get_var_decl_init_value_single ( _ctype , child ) except CursorKindException : log . debug ( '_get_var_decl_init_value: children init value skip on %s' , child . kind ) continue if _tmp is not None : init_value . append ( _tmp ) return init_value
Gathers initialisation values by parsing children nodes of a VAR_DECL .
14,914
def _get_var_decl_init_value_single ( self , _ctype , child ) : init_value = None log . debug ( '_get_var_decl_init_value_single: _ctype: %s Child.kind: %s' , _ctype . kind , child . kind ) if not child . kind . is_expression ( ) and not child . kind . is_declaration ( ) : raise CursorKindException ( child . kind ) if child . kind == CursorKind . CALL_EXPR : raise CursorKindException ( child . kind ) if child . kind . is_unexposed ( ) : init_value = self . _get_var_decl_init_value ( _ctype , child . get_children ( ) ) if len ( init_value ) == 0 : init_value = None elif len ( init_value ) == 1 : init_value = init_value [ 0 ] else : log . error ( '_get_var_decl_init_value_single: Unhandled case' ) assert len ( init_value ) <= 1 else : _v = self . parse_cursor ( child ) if isinstance ( _v , list ) and child . kind not in [ CursorKind . INIT_LIST_EXPR , CursorKind . STRING_LITERAL ] : log . warning ( '_get_var_decl_init_value_single: TOKENIZATION BUG CHECK: %s' , _v ) _v = _v [ 0 ] init_value = ( child . kind , _v ) log . debug ( '_get_var_decl_init_value_single: returns %s' , str ( init_value ) ) return init_value
Handling of a single child for initialization value . Accepted types are expressions and declarations
14,915
def _literal_handling ( self , cursor ) : tokens = list ( cursor . get_tokens ( ) ) log . debug ( 'literal has %d tokens.[ %s ]' , len ( tokens ) , str ( [ str ( t . spelling ) for t in tokens ] ) ) final_value = [ ] log . debug ( 'cursor.type:%s' , cursor . type . kind . name ) for i , token in enumerate ( tokens ) : value = token . spelling log . debug ( 'token:%s tk.kd:%11s tk.cursor.kd:%15s cursor.kd:%15s' , token . spelling , token . kind . name , token . cursor . kind . name , cursor . kind . name ) if ( token . kind == TokenKind . PUNCTUATION and ( token . cursor . kind == CursorKind . INVALID_FILE or token . cursor . kind == CursorKind . INIT_LIST_EXPR ) ) : log . debug ( 'IGNORE token %s' , value ) continue elif token . kind == TokenKind . COMMENT : log . debug ( 'Ignore comment %s' , value ) continue elif token . location not in cursor . extent : log . debug ( 'FIXME BUG: token.location not in cursor.extent %s' , value ) continue if token . cursor . kind == CursorKind . INTEGER_LITERAL : value = value . replace ( 'L' , '' ) . replace ( 'U' , '' ) value = value . replace ( 'l' , '' ) . replace ( 'u' , '' ) if value [ : 2 ] == '0x' or value [ : 2 ] == '0X' : value = '0x%s' % value [ 2 : ] else : value = int ( value ) elif token . cursor . kind == CursorKind . FLOATING_LITERAL : value = value . replace ( 'f' , '' ) . replace ( 'F' , '' ) value = float ( value ) elif ( token . cursor . kind == CursorKind . CHARACTER_LITERAL or token . cursor . kind == CursorKind . STRING_LITERAL ) : value = self . _clean_string_literal ( token . cursor , value ) elif token . cursor . kind == CursorKind . MACRO_INSTANTIATION : value = self . get_registered ( value ) . body elif token . cursor . kind == CursorKind . MACRO_DEFINITION : if i == 0 : pass elif token . kind == TokenKind . LITERAL : value = self . _clean_string_literal ( token . cursor , value ) elif token . kind == TokenKind . IDENTIFIER : value = self . get_registered ( value ) . body final_value . append ( value ) if len ( final_value ) == 1 : return final_value [ 0 ] if isinstance ( final_value , list ) and cursor . kind == CursorKind . STRING_LITERAL : final_value = '' . join ( final_value ) return final_value
Parse all literal associated with this cursor .
14,916
def _operator_handling ( self , cursor ) : values = self . _literal_handling ( cursor ) retval = '' . join ( [ str ( val ) for val in values ] ) return retval
Returns a string with the literal that are part of the operation .
14,917
def STRUCT_DECL ( self , cursor , num = None ) : return self . _record_decl ( cursor , typedesc . Structure , num )
Handles Structure declaration . Its a wrapper to _record_decl .
14,918
def UNION_DECL ( self , cursor , num = None ) : return self . _record_decl ( cursor , typedesc . Union , num )
Handles Union declaration . Its a wrapper to _record_decl .
14,919
def _fixup_record_bitfields_type ( self , s ) : bitfields = [ ] bitfield_members = [ ] current_bits = 0 for m in s . members : if m . is_bitfield : bitfield_members . append ( m ) if m . is_padding : size = current_bits bitfields . append ( ( size , bitfield_members ) ) bitfield_members = [ ] current_bits = 0 else : current_bits += m . bits elif len ( bitfield_members ) == 0 : continue else : size = current_bits bitfields . append ( ( size , bitfield_members ) ) bitfield_members = [ ] current_bits = 0 if current_bits != 0 : size = current_bits bitfields . append ( ( size , bitfield_members ) ) for bf_size , members in bitfields : name = members [ 0 ] . type . name pad_bits = 0 if bf_size <= 8 : pad_bits = 8 - bf_size elif bf_size <= 16 : pad_bits = 16 - bf_size elif bf_size <= 32 : pad_bits = 32 - bf_size elif bf_size <= 64 : name = 'c_uint64' pad_bits = 64 - bf_size else : name = 'c_uint64' pad_bits = bf_size % 64 - bf_size log . debug ( '_fixup_record_bitfield_size: fix type to %s' , name ) for m in members : m . type . name = name if m . is_padding : m . bits = pad_bits if members [ - 1 ] . is_padding and members [ - 1 ] . bits == 0 : s . members . remove ( members [ - 1 ] ) for bf_size , members in bitfields : if True or bf_size == 24 : m = members [ - 1 ] i = s . members . index ( m ) if len ( s . members ) > i + 1 : next_member = s . members [ i + 1 ] if next_member . bits == 8 : next_member . is_bitfield = True next_member . comment = "Promoted to bitfield member and type (was char)" next_member . type = m . type log . info ( "%s.%s promoted to bitfield member and type" , s . name , next_member . name ) continue return
Fix the bitfield packing issue for python ctypes by changing the bitfield type and respecting compiler alignement rules .
14,920
def _fixup_record ( self , s ) : log . debug ( 'FIXUP_STRUCT: %s %d bits' , s . name , s . size * 8 ) if s . members is None : log . debug ( 'FIXUP_STRUCT: no members' ) s . members = [ ] return if s . size == 0 : log . debug ( 'FIXUP_STRUCT: struct has size %d' , s . size ) return self . _fixup_record_bitfields_type ( s ) members = [ ] member = None offset = 0 padding_nb = 0 member = None prev_member = None for m in s . members : member = m log . debug ( 'Fixup_struct: Member:%s offsetbits:%d->%d expecting offset:%d' , member . name , member . offset , member . offset + member . bits , offset ) if member . offset < 0 : return if member . offset > offset : length = member . offset - offset log . debug ( 'Fixup_struct: create padding for %d bits %d bytes' , length , length // 8 ) padding_nb = self . _make_padding ( members , padding_nb , offset , length , prev_member ) if member . type is None : log . error ( 'FIXUP_STRUCT: %s.type is None' , member . name ) members . append ( member ) offset = member . offset + member . bits prev_member = member if s . size * 8 != offset : length = s . size * 8 - offset log . debug ( 'Fixup_struct: s:%d create tail padding for %d bits %d bytes' , s . size , length , length // 8 ) padding_nb = self . _make_padding ( members , padding_nb , offset , length , prev_member ) if len ( members ) > 0 : offset = members [ - 1 ] . offset + members [ - 1 ] . bits s . members = members log . debug ( "FIXUP_STRUCT: size:%d offset:%d" , s . size * 8 , offset ) assert offset == s . size * 8 return
Fixup padding on a record
14,921
def _make_padding ( self , members , padding_nb , offset , length , prev_member = None ) : name = 'PADDING_%d' % padding_nb padding_nb += 1 log . debug ( "_make_padding: for %d bits" , length ) if ( length % 8 ) != 0 or ( prev_member is not None and prev_member . is_bitfield ) : typename = prev_member . type . name padding = typedesc . Field ( name , typedesc . FundamentalType ( typename , 1 , 1 ) , offset , length , is_bitfield = True , is_padding = True ) members . append ( padding ) return padding_nb elif length > 8 : pad_bytes = length // 8 padding = typedesc . Field ( name , typedesc . ArrayType ( typedesc . FundamentalType ( self . get_ctypes_name ( TypeKind . CHAR_U ) , length , 1 ) , pad_bytes ) , offset , length , is_padding = True ) members . append ( padding ) return padding_nb padding = typedesc . Field ( name , typedesc . FundamentalType ( self . get_ctypes_name ( TypeKind . CHAR_U ) , 1 , 1 ) , offset , length , is_padding = True ) members . append ( padding ) return padding_nb
Make padding Fields for a specifed size .
14,922
def MACRO_DEFINITION ( self , cursor ) : if ( not hasattr ( cursor , 'location' ) or cursor . location is None or cursor . location . file is None ) : return False name = self . get_unique_name ( cursor ) comment = None tokens = self . _literal_handling ( cursor ) value = True if isinstance ( tokens , list ) : if len ( tokens ) == 2 : value = tokens [ 1 ] else : value = '' . join ( tokens [ 1 : ] ) for t in cursor . get_tokens ( ) : if t . kind == TokenKind . COMMENT : comment = t . spelling if name == 'NULL' or value == '__null' : value = None log . debug ( 'MACRO: #define %s %s' , tokens [ 0 ] , value ) obj = typedesc . Macro ( name , None , value ) try : self . register ( name , obj ) except DuplicateDefinitionException : log . info ( 'Redefinition of %s %s->%s' , name , self . parser . all [ name ] . args , value ) self . parser . all [ name ] = obj self . set_location ( obj , cursor ) obj . comment = comment return True
Parse MACRO_DEFINITION only present if the TranslationUnit is used with TranslationUnit . PARSE_DETAILED_PROCESSING_RECORD .
14,923
def set_location ( self , obj , cursor ) : if ( hasattr ( cursor , 'location' ) and cursor . location is not None and cursor . location . file is not None ) : obj . location = ( cursor . location . file . name , cursor . location . line ) return
Location is also used for codegeneration ordering .
14,924
def set_comment ( self , obj , cursor ) : if isinstance ( obj , typedesc . T ) : obj . comment = cursor . brief_comment return
If a comment is available add it to the typedesc .
14,925
def make_python_name ( self , name ) : for k , v in [ ( '<' , '_' ) , ( '>' , '_' ) , ( '::' , '__' ) , ( ',' , '' ) , ( ' ' , '' ) , ( "$" , "DOLLAR" ) , ( "." , "DOT" ) , ( "@" , "_" ) , ( ":" , "_" ) , ( '-' , '_' ) ] : if k in name : name = name . replace ( k , v ) if name . startswith ( "__" ) : return "_X" + name if len ( name ) == 0 : pass elif name [ 0 ] in "01234567879" : return "_" + name return name
Transforms an USR into a valid python name .
14,926
def _make_unknown_name ( self , cursor ) : parent = cursor . lexical_parent pname = self . get_unique_name ( parent ) log . debug ( '_make_unknown_name: Got parent get_unique_name %s' , pname ) _cursor_decl = cursor . type . get_declaration ( ) _i = 0 found = False for m in parent . get_children ( ) : log . debug ( '_make_unknown_name child %d %s %s %s' , _i , m . kind , m . type . kind , m . location ) if m . kind not in [ CursorKind . STRUCT_DECL , CursorKind . UNION_DECL , CursorKind . CLASS_DECL ] : continue if m == _cursor_decl : found = True break _i += 1 if not found : raise NotImplementedError ( "_make_unknown_name BUG %s" % cursor . location ) _premainer = '_' . join ( pname . split ( '_' ) [ 1 : ] ) name = '%s_%d' % ( _premainer , _i ) return name
Creates a name for unname type
14,927
def get_unique_name ( self , cursor ) : name = '' if cursor . kind in [ CursorKind . UNEXPOSED_DECL ] : return '' name = cursor . spelling if cursor . spelling == '' : if ( cursor . semantic_parent and cursor . semantic_parent . kind == CursorKind . TRANSLATION_UNIT ) : name = self . make_python_name ( cursor . get_usr ( ) ) log . debug ( 'get_unique_name: root unnamed type kind %s' , cursor . kind ) elif cursor . kind in [ CursorKind . STRUCT_DECL , CursorKind . UNION_DECL , CursorKind . CLASS_DECL , CursorKind . FIELD_DECL ] : name = self . _make_unknown_name ( cursor ) log . debug ( 'Unnamed cursor type, got name %s' , name ) else : log . debug ( 'Unnamed cursor, No idea what to do' ) return '' if cursor . kind in [ CursorKind . STRUCT_DECL , CursorKind . UNION_DECL , CursorKind . CLASS_DECL ] : names = { CursorKind . STRUCT_DECL : 'struct' , CursorKind . UNION_DECL : 'union' , CursorKind . CLASS_DECL : 'class' , CursorKind . TYPE_REF : '' } name = '%s_%s' % ( names [ cursor . kind ] , name ) log . debug ( 'get_unique_name: name "%s"' , name ) return name
get the spelling or create a unique name for a cursor
14,928
def get_literal_kind_affinity ( self , literal_kind ) : if literal_kind == CursorKind . INTEGER_LITERAL : return [ TypeKind . USHORT , TypeKind . UINT , TypeKind . ULONG , TypeKind . ULONGLONG , TypeKind . UINT128 , TypeKind . SHORT , TypeKind . INT , TypeKind . LONG , TypeKind . LONGLONG , TypeKind . INT128 , ] elif literal_kind == CursorKind . STRING_LITERAL : return [ TypeKind . CHAR16 , TypeKind . CHAR32 , TypeKind . CHAR_S , TypeKind . SCHAR , TypeKind . WCHAR ] elif literal_kind == CursorKind . CHARACTER_LITERAL : return [ TypeKind . CHAR_U , TypeKind . UCHAR ] elif literal_kind == CursorKind . FLOATING_LITERAL : return [ TypeKind . FLOAT , TypeKind . DOUBLE , TypeKind . LONGDOUBLE ] elif literal_kind == CursorKind . IMAGINARY_LITERAL : return [ ] return [ ]
return the list of fundamental types that are adequate for which this literal_kind is adequate
14,929
def is_newer ( source , target ) : if not os . path . exists ( source ) : raise ValueError ( "file '%s' does not exist" % source ) if not os . path . exists ( target ) : return 1 from stat import ST_MTIME mtime1 = os . stat ( source ) [ ST_MTIME ] mtime2 = os . stat ( target ) [ ST_MTIME ] return mtime1 > mtime2
Return true if source exists and is more recently modified than target or if source exists and target doesn t . Return false if both exist and target is the same age or younger than source . Raise ValueError if source does not exist .
14,930
def startElement ( self , node ) : if node is None : return if self . __filter_location is not None : if node . location . file is None : return elif node . location . file . name not in self . __filter_location : return log . debug ( '%s:%d: Found a %s|%s|%s' , node . location . file , node . location . line , node . kind . name , node . displayname , node . spelling ) try : stop_recurse = self . parse_cursor ( node ) if stop_recurse is not False : return for child in node . get_children ( ) : self . startElement ( child ) except InvalidDefinitionError : pass return None
Recurses in children of this node
14,931
def register ( self , name , obj ) : if name in self . all : log . debug ( 'register: %s already existed: %s' , name , obj . name ) raise DuplicateDefinitionException ( 'register: %s already existed: %s' % ( name , obj . name ) ) log . debug ( 'register: %s ' , name ) self . all [ name ] = obj return obj
Registers an unique type description
14,932
def get_tu ( source , lang = 'c' , all_warnings = False , flags = None ) : args = list ( flags or [ ] ) name = 't.c' if lang == 'cpp' : name = 't.cpp' args . append ( '-std=c++11' ) elif lang == 'objc' : name = 't.m' elif lang != 'c' : raise Exception ( 'Unknown language: %s' % lang ) if all_warnings : args += [ '-Wall' , '-Wextra' ] return TranslationUnit . from_source ( name , args , unsaved_files = [ ( name , source ) ] )
Obtain a translation unit from source and language .
14,933
def get_cursor ( source , spelling ) : children = [ ] if isinstance ( source , Cursor ) : children = source . get_children ( ) else : children = source . cursor . get_children ( ) for cursor in children : if cursor . spelling == spelling : return cursor result = get_cursor ( cursor , spelling ) if result is not None : return result return None
Obtain a cursor from a source object .
14,934
def get_cursors ( source , spelling ) : cursors = [ ] children = [ ] if isinstance ( source , Cursor ) : children = source . get_children ( ) else : children = source . cursor . get_children ( ) for cursor in children : if cursor . spelling == spelling : cursors . append ( cursor ) cursors . extend ( get_cursors ( cursor , spelling ) ) return cursors
Obtain all cursors from a source object with a specific spelling .
14,935
def enable_fundamental_type_wrappers ( self ) : self . enable_fundamental_type_wrappers = lambda : True import pkgutil headers = pkgutil . get_data ( 'ctypeslib' , 'data/fundamental_type_name.tpl' ) . decode ( ) from clang . cindex import TypeKind size = str ( self . parser . get_ctypes_size ( TypeKind . LONGDOUBLE ) // 8 ) headers = headers . replace ( '__LONG_DOUBLE_SIZE__' , size ) print ( headers , file = self . imports ) return
If a type is a int128 a long_double_t or a void some placeholders need to be in the generated code to be valid .
14,936
def enable_pointer_type ( self ) : self . enable_pointer_type = lambda : True import pkgutil headers = pkgutil . get_data ( 'ctypeslib' , 'data/pointer_type.tpl' ) . decode ( ) import ctypes from clang . cindex import TypeKind word_size = self . parser . get_ctypes_size ( TypeKind . POINTER ) // 8 word_type = self . parser . get_ctypes_name ( TypeKind . ULONG ) word_char = getattr ( ctypes , word_type ) . _type_ headers = headers . replace ( '__POINTER_SIZE__' , str ( word_size ) ) headers = headers . replace ( '__REPLACEMENT_TYPE__' , word_type ) headers = headers . replace ( '__REPLACEMENT_TYPE_CHAR__' , word_char ) print ( headers , file = self . imports ) return
If a type is a pointer a platform - independent POINTER_T type needs to be in the generated code .
14,937
def Alias ( self , alias ) : if self . generate_comments : self . print_comment ( alias ) print ( "%s = %s # alias" % ( alias . name , alias . alias ) , file = self . stream ) self . _aliases += 1 return
Handles Aliases . No test cases yet
14,938
def get_undeclared_type ( self , item ) : if item in self . done : return None if isinstance ( item , typedesc . FundamentalType ) : return None if isinstance ( item , typedesc . PointerType ) : return self . get_undeclared_type ( item . typ ) if isinstance ( item , typedesc . ArrayType ) : return self . get_undeclared_type ( item . typ ) return item
Checks if a typed has already been declared in the python output or is a builtin python type .
14,939
def FundamentalType ( self , _type ) : log . debug ( 'HERE in FundamentalType for %s %s' , _type , _type . name ) if _type . name in [ "None" , "c_long_double_t" , "c_uint128" , "c_int128" ] : self . enable_fundamental_type_wrappers ( ) return _type . name return "ctypes.%s" % ( _type . name )
Returns the proper ctypes class name for a fundamental type
14,940
def _generate ( self , item , * args ) : if item in self . done : return if self . generate_locations and item . location : print ( "# %s:%d" % item . location , file = self . stream ) if self . generate_comments : self . print_comment ( item ) log . debug ( "generate %s, %s" , item . __class__ . __name__ , item . name ) self . done . add ( item ) mth = getattr ( self , type ( item ) . __name__ ) mth ( item , * args ) return
wraps execution of specific methods .
14,941
def example ( ) : ldata = 200 degrees = np . arange ( ldata + 1 , dtype = float ) degrees [ 0 ] = np . inf power = degrees ** ( - 1 ) clm1 = pyshtools . SHCoeffs . from_random ( power , exact_power = False ) clm2 = pyshtools . SHCoeffs . from_random ( power , exact_power = True ) fig , ax = plt . subplots ( ) ax . plot ( clm1 . spectrum ( unit = 'per_l' ) , label = 'Normal distributed power' ) ax . plot ( clm2 . spectrum ( unit = 'per_l' ) , label = 'Exact power' ) ax . set ( xscale = 'log' , yscale = 'log' , xlabel = 'degree l' , ylabel = 'power per degree l' ) ax . grid ( which = 'both' ) ax . legend ( ) plt . show ( )
Plot random phase and Gaussian random variable spectra .
14,942
def plot_rad ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = '$g_r$, m s$^{-2}$' , ax = None , show = True , fname = None , ** kwargs ) : if ax is None : fig , axes = self . rad . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . rad . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the radial component of the gravity field .
14,943
def plot_theta ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = '$g_\\theta$, m s$^{-2}$' , ax = None , show = True , fname = None , ** kwargs ) : if ax is None : fig , axes = self . theta . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . theta . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the theta component of the gravity field .
14,944
def plot_phi ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = '$g_\phi$, m s$^{-2}$' , ax = None , show = True , fname = None , ** kwargs ) : if ax is None : fig , axes = self . phi . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . phi . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the phi component of the gravity field .
14,945
def plot_total ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if self . normal_gravity is True : if cb_label is None : cb_label = 'Gravity disturbance, mGal' else : if cb_label is None : cb_label = 'Gravity disturbance, m s$^{-2}$' if ax is None : if self . normal_gravity is True : fig , axes = ( self . total * 1.e5 ) . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) else : fig , axes = self . total . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : if self . normal_gravity is True : ( self . total * 1.e5 ) . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs ) else : self . total . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the total gravity disturbance .
14,946
def plot_pot ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = 'Potential, m$^2$ s$^{-2}$' , ax = None , show = True , fname = None , ** kwargs ) : if ax is None : fig , axes = self . pot . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . pot . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the gravitational potential .
14,947
def plot ( self , colorbar = True , cb_orientation = 'horizontal' , tick_interval = [ 60 , 60 ] , minor_tick_interval = [ 20 , 20 ] , xlabel = 'Longitude' , ylabel = 'Latitude' , axes_labelsize = 9 , tick_labelsize = 8 , show = True , fname = None , ** kwargs ) : if colorbar is True : if cb_orientation == 'horizontal' : scale = 0.8 else : scale = 0.5 else : scale = 0.6 figsize = ( _mpl . rcParams [ 'figure.figsize' ] [ 0 ] , _mpl . rcParams [ 'figure.figsize' ] [ 0 ] * scale ) fig , ax = _plt . subplots ( 2 , 2 , figsize = figsize ) self . plot_rad ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 0 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_theta ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 1 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_phi ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 2 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , minor_tick_interval = minor_tick_interval , tick_labelsize = tick_labelsize , ** kwargs ) self . plot_total ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 3 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) fig . tight_layout ( pad = 0.5 ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , ax
Plot the three vector components of the gravity field and the gravity disturbance .
14,948
def expand ( self , nmax = None , grid = 'DH2' , zeros = None ) : if type ( grid ) != str : raise ValueError ( 'grid must be a string. ' + 'Input type was {:s}' . format ( str ( type ( grid ) ) ) ) if nmax is None : nmax = self . nmax if self . galpha . kind == 'cap' : shcoeffs = _shtools . SlepianCoeffsToSH ( self . falpha , self . galpha . coeffs , nmax ) else : shcoeffs = _shtools . SlepianCoeffsToSH ( self . falpha , self . galpha . tapers , nmax ) if grid . upper ( ) in ( 'DH' , 'DH1' ) : gridout = _shtools . MakeGridDH ( shcoeffs , sampling = 1 , norm = 1 , csphase = 1 ) return SHGrid . from_array ( gridout , grid = 'DH' , copy = False ) elif grid . upper ( ) == 'DH2' : gridout = _shtools . MakeGridDH ( shcoeffs , sampling = 2 , norm = 1 , csphase = 1 ) return SHGrid . from_array ( gridout , grid = 'DH' , copy = False ) elif grid . upper ( ) == 'GLQ' : if zeros is None : zeros , weights = _shtools . SHGLQ ( self . galpha . lmax ) gridout = _shtools . MakeGridGLQ ( shcoeffs , zeros , norm = 1 , csphase = 1 ) return SHGrid . from_array ( gridout , grid = 'GLQ' , copy = False ) else : raise ValueError ( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}" . format ( repr ( grid ) ) )
Expand the function on a grid using the first n Slepian coefficients .
14,949
def to_shcoeffs ( self , nmax = None , normalization = '4pi' , csphase = 1 ) : if type ( normalization ) != str : raise ValueError ( 'normalization must be a string. ' + 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) ) if normalization . lower ( ) not in set ( [ '4pi' , 'ortho' , 'schmidt' ] ) : raise ValueError ( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" . format ( repr ( normalization ) ) ) if csphase != 1 and csphase != - 1 : raise ValueError ( "csphase must be 1 or -1. Input value was {:s}" . format ( repr ( csphase ) ) ) if nmax is None : nmax = self . nmax if self . galpha . kind == 'cap' : shcoeffs = _shtools . SlepianCoeffsToSH ( self . falpha , self . galpha . coeffs , nmax ) else : shcoeffs = _shtools . SlepianCoeffsToSH ( self . falpha , self . galpha . tapers , nmax ) temp = SHCoeffs . from_array ( shcoeffs , normalization = '4pi' , csphase = 1 ) if normalization != '4pi' or csphase != 1 : return temp . convert ( normalization = normalization , csphase = csphase ) else : return temp
Return the spherical harmonic coefficients using the first n Slepian coefficients .
14,950
def _shtools_status_message ( status ) : if ( status == 1 ) : errmsg = 'Improper dimensions of input array.' elif ( status == 2 ) : errmsg = 'Improper bounds for input variable.' elif ( status == 3 ) : errmsg = 'Error allocating memory.' elif ( status == 4 ) : errmsg = 'File IO error.' else : errmsg = 'Unhandled Fortran 95 error.' return errmsg
Determine error message to print when a SHTOOLS Fortran 95 routine exits improperly .
14,951
def from_cap ( cls , theta , lmax , clat = None , clon = None , nmax = None , theta_degrees = True , coord_degrees = True , dj_matrix = None ) : if theta_degrees : tapers , eigenvalues , taper_order = _shtools . SHReturnTapers ( _np . radians ( theta ) , lmax ) else : tapers , eigenvalues , taper_order = _shtools . SHReturnTapers ( theta , lmax ) return SlepianCap ( theta , tapers , eigenvalues , taper_order , clat , clon , nmax , theta_degrees , coord_degrees , dj_matrix , copy = False )
Construct spherical cap Slepian functions .
14,952
def from_mask ( cls , dh_mask , lmax , nmax = None ) : if nmax is None : nmax = ( lmax + 1 ) ** 2 else : if nmax > ( lmax + 1 ) ** 2 : raise ValueError ( 'nmax must be less than or equal to ' + '(lmax + 1)**2. lmax = {:d} and nmax = {:d}' . format ( lmax , nmax ) ) if dh_mask . shape [ 0 ] % 2 != 0 : raise ValueError ( 'The number of latitude bands in dh_mask ' + 'must be even. nlat = {:d}' . format ( dh_mask . shape [ 0 ] ) ) if dh_mask . shape [ 1 ] == dh_mask . shape [ 0 ] : _sampling = 1 elif dh_mask . shape [ 1 ] == 2 * dh_mask . shape [ 0 ] : _sampling = 2 else : raise ValueError ( 'dh_mask must be dimensioned as (n, n) or ' + '(n, 2 * n). Input shape is ({:d}, {:d})' . format ( dh_mask . shape [ 0 ] , dh_mask . shape [ 1 ] ) ) mask_lm = _shtools . SHExpandDH ( dh_mask , sampling = _sampling , lmax_calc = 0 ) area = mask_lm [ 0 , 0 , 0 ] * 4 * _np . pi tapers , eigenvalues = _shtools . SHReturnTapersMap ( dh_mask , lmax , ntapers = nmax ) return SlepianMask ( tapers , eigenvalues , area , copy = False )
Construct Slepian functions that are optimally concentrated within the region specified by a mask .
14,953
def expand ( self , flm , nmax = None ) : if nmax is None : nmax = ( self . lmax + 1 ) ** 2 elif nmax is not None and nmax > ( self . lmax + 1 ) ** 2 : raise ValueError ( "nmax must be less than or equal to (lmax+1)**2 " + "where lmax is {:s}. Input value is {:s}" . format ( repr ( self . lmax ) , repr ( nmax ) ) ) coeffsin = flm . to_array ( normalization = '4pi' , csphase = 1 , lmax = self . lmax ) return self . _expand ( coeffsin , nmax )
Return the Slepian expansion coefficients of the input function .
14,954
def spectra ( self , alpha = None , nmax = None , convention = 'power' , unit = 'per_l' , base = 10. ) : if alpha is None : if nmax is None : nmax = self . nmax spectra = _np . zeros ( ( self . lmax + 1 , nmax ) ) for iwin in range ( nmax ) : coeffs = self . to_array ( iwin ) spectra [ : , iwin ] = _spectrum ( coeffs , normalization = '4pi' , convention = convention , unit = unit , base = base ) else : coeffs = self . to_array ( alpha ) spectra = _spectrum ( coeffs , normalization = '4pi' , convention = convention , unit = unit , base = base ) return spectra
Return the spectra of one or more Slepian functions .
14,955
def _taper2coeffs ( self , alpha ) : taperm = self . orders [ alpha ] coeffs = _np . zeros ( ( 2 , self . lmax + 1 , self . lmax + 1 ) ) if taperm < 0 : coeffs [ 1 , : , abs ( taperm ) ] = self . tapers [ : , alpha ] else : coeffs [ 0 , : , abs ( taperm ) ] = self . tapers [ : , alpha ] return coeffs
Return the spherical harmonic coefficients of the unrotated Slepian function i as an array where i = 0 is the best concentrated function .
14,956
def plot_total ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = '$|B|$, nT' , ax = None , show = True , fname = None , ** kwargs ) : if ax is None : fig , axes = self . total . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . total . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the total magnetic intensity .
14,957
def spharm_lm ( l , m , theta , phi , normalization = '4pi' , kind = 'real' , csphase = 1 , degrees = True ) : if l < 0 : raise ValueError ( "The degree l must be greater or equal than 0. Input value was {:s}." . format ( repr ( l ) ) ) if m > l : raise ValueError ( "The order m must be less than or equal to the degree l. " + "Input values were l={:s} and m={:s}." . format ( repr ( l ) , repr ( m ) ) ) if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' , 'unnorm' ) : raise ValueError ( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." . format ( repr ( normalization ) ) ) if kind . lower ( ) not in ( 'real' , 'complex' ) : raise ValueError ( "kind must be 'real' or 'complex'. " + "Input value was {:s}." . format ( repr ( kind ) ) ) if csphase != 1 and csphase != - 1 : raise ValueError ( "csphase must be either 1 or -1. Input value was {:s}." . format ( repr ( csphase ) ) ) if normalization . lower ( ) == 'unnorm' and lmax > 85 : _warnings . warn ( "Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}." . format ( lmax ) , category = RuntimeWarning ) lmax = 85 ind = ( l * ( l + 1 ) ) // 2 + abs ( m ) if degrees is True : theta = _np . deg2rad ( theta ) phi = _np . deg2rad ( phi ) if kind . lower ( ) == 'real' : p = _legendre ( l , _np . cos ( theta ) , normalization = normalization , csphase = csphase , cnorm = 0 , packed = True ) if m >= 0 : ylm = p [ ind ] * _np . cos ( m * phi ) else : ylm = p [ ind ] * _np . sin ( abs ( m ) * phi ) else : p = _legendre ( l , _np . cos ( theta ) , normalization = normalization , csphase = csphase , cnorm = 1 , packed = True ) ylm = p [ ind ] * ( _np . cos ( m * phi ) + 1j * _np . sin ( abs ( m ) * phi ) ) if m < 0 : ylm = ylm . conj ( ) if _np . mod ( m , 2 ) == 1 : ylm = - ylm return ylm
Compute the spherical harmonic function for a specific degree and order .
14,958
def set_coeffs ( self , values , ls , ms ) : values = _np . array ( values ) ls = _np . array ( ls ) ms = _np . array ( ms ) mneg_mask = ( ms < 0 ) . astype ( _np . int ) self . coeffs [ mneg_mask , ls , _np . abs ( ms ) ] = values
Set spherical harmonic coefficients in - place to specified values .
14,959
def convert ( self , normalization = None , csphase = None , lmax = None ) : if normalization is None : normalization = self . normalization if csphase is None : csphase = self . csphase if lmax is None : lmax = self . lmax if type ( normalization ) != str : raise ValueError ( 'normalization must be a string. ' 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) ) if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' , 'unnorm' ) : raise ValueError ( "normalization must be '4pi', 'ortho', 'schmidt', or " "'unnorm'. Provided value was {:s}" . format ( repr ( normalization ) ) ) if csphase != 1 and csphase != - 1 : raise ValueError ( "csphase must be 1 or -1. Input value was {:s}" . format ( repr ( csphase ) ) ) if self . errors is not None : coeffs , errors = self . to_array ( normalization = normalization . lower ( ) , csphase = csphase , lmax = lmax ) return SHMagCoeffs . from_array ( coeffs , r0 = self . r0 , errors = errors , normalization = normalization . lower ( ) , csphase = csphase , copy = False ) else : coeffs = self . to_array ( normalization = normalization . lower ( ) , csphase = csphase , lmax = lmax ) return SHMagCoeffs . from_array ( coeffs , r0 = self . r0 , normalization = normalization . lower ( ) , csphase = csphase , copy = False )
Return an SHMagCoeffs class instance with a different normalization convention .
14,960
def pad ( self , lmax ) : clm = self . copy ( ) if lmax <= self . lmax : clm . coeffs = clm . coeffs [ : , : lmax + 1 , : lmax + 1 ] clm . mask = clm . mask [ : , : lmax + 1 , : lmax + 1 ] if self . errors is not None : clm . errors = clm . errors [ : , : lmax + 1 , : lmax + 1 ] else : clm . coeffs = _np . pad ( clm . coeffs , ( ( 0 , 0 ) , ( 0 , lmax - self . lmax ) , ( 0 , lmax - self . lmax ) ) , 'constant' ) if self . errors is not None : clm . errors = _np . pad ( clm . errors , ( ( 0 , 0 ) , ( 0 , lmax - self . lmax ) , ( 0 , lmax - self . lmax ) ) , 'constant' ) mask = _np . zeros ( ( 2 , lmax + 1 , lmax + 1 ) , dtype = _np . bool ) for l in _np . arange ( lmax + 1 ) : mask [ : , l , : l + 1 ] = True mask [ 1 , : , 0 ] = False clm . mask = mask clm . lmax = lmax return clm
Return an SHMagCoeffs class where the coefficients are zero padded or truncated to a different lmax .
14,961
def change_ref ( self , r0 = None , lmax = None ) : if lmax is None : lmax = self . lmax clm = self . pad ( lmax ) if r0 is not None and r0 != self . r0 : for l in _np . arange ( lmax + 1 ) : clm . coeffs [ : , l , : l + 1 ] *= ( self . r0 / r0 ) ** ( l + 2 ) if self . errors is not None : clm . errors [ : , l , : l + 1 ] *= ( self . r0 / r0 ) ** ( l + 2 ) clm . r0 = r0 return clm
Return a new SHMagCoeffs class instance with a different reference r0 .
14,962
def expand ( self , a = None , f = None , lmax = None , lmax_calc = None , sampling = 2 ) : if a is None : a = self . r0 if f is None : f = 0. if lmax is None : lmax = self . lmax if lmax_calc is None : lmax_calc = lmax if self . errors is not None : coeffs , errors = self . to_array ( normalization = 'schmidt' , csphase = 1 ) else : coeffs = self . to_array ( normalization = 'schmidt' , csphase = 1 ) rad , theta , phi , total , pot = _MakeMagGridDH ( coeffs , self . r0 , a = a , f = f , lmax = lmax , lmax_calc = lmax_calc , sampling = sampling ) return _SHMagGrid ( rad , theta , phi , total , pot , a , f , lmax , lmax_calc )
Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the magnetic field the total magnetic intensity and the magnetic potential and return as a SHMagGrid class instance .
14,963
def tensor ( self , a = None , f = None , lmax = None , lmax_calc = None , sampling = 2 ) : if a is None : a = self . r0 if f is None : f = 0. if lmax is None : lmax = self . lmax if lmax_calc is None : lmax_calc = lmax if self . errors is not None : coeffs , errors = self . to_array ( normalization = 'schmidt' , csphase = 1 ) else : coeffs = self . to_array ( normalization = 'schmidt' , csphase = 1 ) vxx , vyy , vzz , vxy , vxz , vyz = _MakeMagGradGridDH ( coeffs , self . r0 , a = a , f = f , lmax = lmax , lmax_calc = lmax_calc , sampling = sampling ) return _SHMagTensor ( vxx , vyy , vzz , vxy , vxz , vyz , a , f , lmax , lmax_calc )
Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the magnetic field tensor in a local north - oriented reference frame and return an SHMagTensor class instance .
14,964
def legendre ( lmax , z , normalization = '4pi' , csphase = 1 , cnorm = 0 , packed = False ) : if lmax < 0 : raise ValueError ( "lmax must be greater or equal to 0. Input value was {:s}." . format ( repr ( lmax ) ) ) if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' , 'unnorm' ) : raise ValueError ( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." . format ( repr ( normalization ) ) ) if csphase != 1 and csphase != - 1 : raise ValueError ( "csphase must be either 1 or -1. Input value was {:s}." . format ( repr ( csphase ) ) ) if cnorm != 0 and cnorm != 1 : raise ValueError ( "cnorm must be either 0 or 1. Input value was {:s}." . format ( repr ( cnorm ) ) ) if normalization . lower ( ) == 'unnorm' and lmax > 85 : _warnings . warn ( "Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}." . format ( lmax ) , category = RuntimeWarning ) lmax = 85 if normalization == '4pi' : p = _PlmBar ( lmax , z , csphase = csphase , cnorm = cnorm ) elif normalization == 'ortho' : p = _PlmON ( lmax , z , csphase = csphase , cnorm = cnorm ) elif normalization == 'schmidt' : p = _PlmSchmidt ( lmax , z , csphase = csphase , cnorm = cnorm ) elif normalization == 'unnorm' : p = _PLegendreA ( lmax , z , csphase = csphase , cnorm = cnorm ) if packed is True : return p else : plm = _np . zeros ( ( lmax + 1 , lmax + 1 ) ) for l in range ( lmax + 1 ) : for m in range ( l + 1 ) : plm [ l , m ] = p [ ( l * ( l + 1 ) ) // 2 + m ] return plm
Compute all the associated Legendre functions up to a maximum degree and order .
14,965
def legendre_lm ( l , m , z , normalization = '4pi' , csphase = 1 , cnorm = 0 ) : if l < 0 : raise ValueError ( "The degree l must be greater or equal to 0. Input value was {:s}." . format ( repr ( l ) ) ) if m < 0 : raise ValueError ( "The order m must be greater or equal to 0. Input value was {:s}." . format ( repr ( m ) ) ) if m > l : raise ValueError ( "The order m must be less than or equal to the degree l. " + "Input values were l={:s} and m={:s}." . format ( repr ( l ) , repr ( m ) ) ) if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' , 'unnorm' ) : raise ValueError ( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." . format ( repr ( normalization ) ) ) if csphase != 1 and csphase != - 1 : raise ValueError ( "csphase must be either 1 or -1. Input value was {:s}." . format ( repr ( csphase ) ) ) if cnorm != 0 and cnorm != 1 : raise ValueError ( "cnorm must be either 0 or 1. Input value was {:s}." . format ( repr ( cnorm ) ) ) if normalization . lower ( ) == 'unnorm' and lmax > 85 : _warnings . warn ( "Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}." . format ( lmax ) , category = RuntimeWarning ) lmax = 85 if normalization == '4pi' : p = _PlmBar ( l , z , csphase = csphase , cnorm = cnorm ) elif normalization == 'ortho' : p = _PlmON ( l , z , csphase = csphase , cnorm = cnorm ) elif normalization == 'schmidt' : p = _PlmSchmidt ( l , z , csphase = csphase , cnorm = cnorm ) elif normalization == 'unnorm' : p = _PLegendreA ( l , z , csphase = csphase , cnorm = cnorm ) return p [ ( l * ( l + 1 ) ) // 2 + m ]
Compute the associated Legendre function for a specific degree and order .
14,966
def _iscomment ( line ) : if line . isspace ( ) : return True elif len ( line . split ( ) ) >= 3 : try : if line . split ( ) [ 0 ] . isdecimal ( ) and line . split ( ) [ 1 ] . isdecimal ( ) : return False except : if ( line . decode ( ) . split ( ) [ 0 ] . isdecimal ( ) and line . split ( ) [ 1 ] . decode ( ) . isdecimal ( ) ) : return False return True else : return True
Determine if a line is a comment line . A valid line contains at least three words with the first two being integers . Note that Python 2 and 3 deal with strings differently .
14,967
def process_f2pydoc ( f2pydoc ) : docparts = re . split ( '\n--' , f2pydoc ) if len ( docparts ) == 4 : doc_has_optionals = True elif len ( docparts ) == 3 : doc_has_optionals = False else : print ( '-- uninterpretable f2py documentation --' ) return f2pydoc docparts [ 0 ] = re . sub ( '[\[(,]\w+_d\d' , '' , docparts [ 0 ] ) if doc_has_optionals : returnarray_dims = re . findall ( '[\[(,](\w+_d\d)' , docparts [ 3 ] ) for arg in returnarray_dims : searchpattern = arg + ' : input.*\n.*Default: (.*)\n' match = re . search ( searchpattern , docparts [ 2 ] ) if match : default = match . group ( 1 ) docparts [ 3 ] = re . sub ( arg , default , docparts [ 3 ] ) docparts [ 2 ] = re . sub ( searchpattern , '' , docparts [ 2 ] ) if doc_has_optionals : searchpattern = '\w+_d\d : input.*\n.*Default: (.*)\n' docparts [ 2 ] = re . sub ( searchpattern , '' , docparts [ 2 ] ) processed_signature = '\n--' . join ( docparts ) return processed_signature
this function replace all optional _d0 arguments with their default values in the function signature . These arguments are not intended to be used and signify merely the array dimensions of the associated argument .
14,968
def from_cap ( cls , theta , lwin , clat = None , clon = None , nwin = None , theta_degrees = True , coord_degrees = True , dj_matrix = None , weights = None ) : if theta_degrees : tapers , eigenvalues , taper_order = _shtools . SHReturnTapers ( _np . radians ( theta ) , lwin ) else : tapers , eigenvalues , taper_order = _shtools . SHReturnTapers ( theta , lwin ) return SHWindowCap ( theta , tapers , eigenvalues , taper_order , clat , clon , nwin , theta_degrees , coord_degrees , dj_matrix , weights , copy = False )
Construct spherical cap localization windows .
14,969
def from_mask ( cls , dh_mask , lwin , nwin = None , weights = None ) : if nwin is None : nwin = ( lwin + 1 ) ** 2 else : if nwin > ( lwin + 1 ) ** 2 : raise ValueError ( 'nwin must be less than or equal to ' + '(lwin + 1)**2. lwin = {:d} and nwin = {:d}' . format ( lwin , nwin ) ) if dh_mask . shape [ 0 ] % 2 != 0 : raise ValueError ( 'The number of latitude bands in dh_mask ' + 'must be even. nlat = {:d}' . format ( dh_mask . shape [ 0 ] ) ) if dh_mask . shape [ 1 ] == dh_mask . shape [ 0 ] : _sampling = 1 elif dh_mask . shape [ 1 ] == 2 * dh_mask . shape [ 0 ] : _sampling = 2 else : raise ValueError ( 'dh_mask must be dimensioned as (n, n) or ' + '(n, 2 * n). Input shape is ({:d}, {:d})' . format ( dh_mask . shape [ 0 ] , dh_mask . shape [ 1 ] ) ) mask_lm = _shtools . SHExpandDH ( dh_mask , sampling = _sampling , lmax_calc = 0 ) area = mask_lm [ 0 , 0 , 0 ] * 4 * _np . pi tapers , eigenvalues = _shtools . SHReturnTapersMap ( dh_mask , lwin , ntapers = nwin ) return SHWindowMask ( tapers , eigenvalues , weights , area , copy = False )
Construct localization windows that are optimally concentrated within the region specified by a mask .
14,970
def to_array ( self , itaper , normalization = '4pi' , csphase = 1 ) : if type ( normalization ) != str : raise ValueError ( 'normalization must be a string. ' + 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) ) if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' ) : raise ValueError ( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" . format ( repr ( normalization ) ) ) if csphase != 1 and csphase != - 1 : raise ValueError ( "csphase must be 1 or -1. Input value was {:s}" . format ( repr ( csphase ) ) ) return self . _to_array ( itaper , normalization = normalization . lower ( ) , csphase = csphase )
Return the spherical harmonic coefficients of taper i as a numpy array .
14,971
def to_shcoeffs ( self , itaper , normalization = '4pi' , csphase = 1 ) : if type ( normalization ) != str : raise ValueError ( 'normalization must be a string. ' + 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) ) if normalization . lower ( ) not in set ( [ '4pi' , 'ortho' , 'schmidt' ] ) : raise ValueError ( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" . format ( repr ( normalization ) ) ) if csphase != 1 and csphase != - 1 : raise ValueError ( "csphase must be 1 or -1. Input value was {:s}" . format ( repr ( csphase ) ) ) coeffs = self . to_array ( itaper , normalization = normalization . lower ( ) , csphase = csphase ) return SHCoeffs . from_array ( coeffs , normalization = normalization . lower ( ) , csphase = csphase , copy = False )
Return the spherical harmonic coefficients of taper i as a SHCoeffs class instance .
14,972
def to_shgrid ( self , itaper , grid = 'DH2' , zeros = None ) : if type ( grid ) != str : raise ValueError ( 'grid must be a string. ' + 'Input type was {:s}' . format ( str ( type ( grid ) ) ) ) if grid . upper ( ) in ( 'DH' , 'DH1' ) : gridout = _shtools . MakeGridDH ( self . to_array ( itaper ) , sampling = 1 , norm = 1 , csphase = 1 ) return SHGrid . from_array ( gridout , grid = 'DH' , copy = False ) elif grid . upper ( ) == 'DH2' : gridout = _shtools . MakeGridDH ( self . to_array ( itaper ) , sampling = 2 , norm = 1 , csphase = 1 ) return SHGrid . from_array ( gridout , grid = 'DH' , copy = False ) elif grid . upper ( ) == 'GLQ' : if zeros is None : zeros , weights = _shtools . SHGLQ ( self . lwin ) gridout = _shtools . MakeGridGLQ ( self . to_array ( itaper ) , zeros , norm = 1 , csphase = 1 ) return SHGrid . from_array ( gridout , grid = 'GLQ' , copy = False ) else : raise ValueError ( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}" . format ( repr ( grid ) ) )
Evaluate the coefficients of taper i on a spherical grid and return a SHGrid class instance .
14,973
def multitaper_spectrum ( self , clm , k , convention = 'power' , unit = 'per_l' , ** kwargs ) : return self . _multitaper_spectrum ( clm , k , convention = convention , unit = unit , ** kwargs )
Return the multitaper spectrum estimate and standard error .
14,974
def multitaper_cross_spectrum ( self , clm , slm , k , convention = 'power' , unit = 'per_l' , ** kwargs ) : return self . _multitaper_cross_spectrum ( clm , slm , k , convention = convention , unit = unit , ** kwargs )
Return the multitaper cross - spectrum estimate and standard error .
14,975
def spectra ( self , itaper = None , nwin = None , convention = 'power' , unit = 'per_l' , base = 10. ) : if itaper is None : if nwin is None : nwin = self . nwin spectra = _np . zeros ( ( self . lwin + 1 , nwin ) ) for iwin in range ( nwin ) : coeffs = self . to_array ( iwin ) spectra [ : , iwin ] = _spectrum ( coeffs , normalization = '4pi' , convention = convention , unit = unit , base = base ) else : coeffs = self . to_array ( itaper ) spectra = _spectrum ( coeffs , normalization = '4pi' , convention = convention , unit = unit , base = base ) return spectra
Return the spectra of one or more localization windows .
14,976
def coupling_matrix ( self , lmax , nwin = None , weights = None , mode = 'full' ) : if weights is not None : if nwin is not None : if len ( weights ) != nwin : raise ValueError ( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}' . format ( len ( weights ) , nwin ) ) else : if len ( weights ) != self . nwin : raise ValueError ( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}' . format ( len ( weights ) , self . nwin ) ) if mode == 'full' : return self . _coupling_matrix ( lmax , nwin = nwin , weights = weights ) elif mode == 'same' : cmatrix = self . _coupling_matrix ( lmax , nwin = nwin , weights = weights ) return cmatrix [ : lmax + 1 , : ] elif mode == 'valid' : cmatrix = self . _coupling_matrix ( lmax , nwin = nwin , weights = weights ) return cmatrix [ : lmax - self . lwin + 1 , : ] else : raise ValueError ( "mode has to be 'full', 'same' or 'valid', not " "{}" . format ( mode ) )
Return the coupling matrix of the first nwin tapers . This matrix relates the global power spectrum to the expectation of the localized multitaper spectrum .
14,977
def plot_coupling_matrix ( self , lmax , nwin = None , weights = None , mode = 'full' , axes_labelsize = None , tick_labelsize = None , show = True , ax = None , fname = None ) : figsize = ( _mpl . rcParams [ 'figure.figsize' ] [ 0 ] , _mpl . rcParams [ 'figure.figsize' ] [ 0 ] ) if axes_labelsize is None : axes_labelsize = _mpl . rcParams [ 'axes.labelsize' ] if tick_labelsize is None : tick_labelsize = _mpl . rcParams [ 'xtick.labelsize' ] if ax is None : fig = _plt . figure ( figsize = figsize ) axes = fig . add_subplot ( 111 ) else : axes = ax axes . imshow ( self . coupling_matrix ( lmax , nwin = nwin , weights = weights , mode = mode ) , aspect = 'auto' ) axes . set_xlabel ( 'Input power' , fontsize = axes_labelsize ) axes . set_ylabel ( 'Output power' , fontsize = axes_labelsize ) axes . tick_params ( labelsize = tick_labelsize ) axes . minorticks_on ( ) if ax is None : fig . tight_layout ( pad = 0.5 ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes
Plot the multitaper coupling matrix .
14,978
def _taper2coeffs ( self , itaper ) : taperm = self . orders [ itaper ] coeffs = _np . zeros ( ( 2 , self . lwin + 1 , self . lwin + 1 ) ) if taperm < 0 : coeffs [ 1 , : , abs ( taperm ) ] = self . tapers [ : , itaper ] else : coeffs [ 0 , : , abs ( taperm ) ] = self . tapers [ : , itaper ] return coeffs
Return the spherical harmonic coefficients of the unrotated taper i as an array where i = 0 is the best concentrated .
14,979
def rotate ( self , clat , clon , coord_degrees = True , dj_matrix = None , nwinrot = None ) : self . coeffs = _np . zeros ( ( ( self . lwin + 1 ) ** 2 , self . nwin ) ) self . clat = clat self . clon = clon self . coord_degrees = coord_degrees if nwinrot is not None : self . nwinrot = nwinrot else : self . nwinrot = self . nwin if self . coord_degrees : angles = _np . radians ( _np . array ( [ 0. , - ( 90. - clat ) , - clon ] ) ) else : angles = _np . array ( [ 0. , - ( _np . pi / 2. - clat ) , - clon ] ) if dj_matrix is None : if self . dj_matrix is None : self . dj_matrix = _shtools . djpi2 ( self . lwin + 1 ) dj_matrix = self . dj_matrix else : dj_matrix = self . dj_matrix if ( ( coord_degrees is True and clat == 90. and clon == 0. ) or ( coord_degrees is False and clat == _np . pi / 2. and clon == 0. ) ) : for i in range ( self . nwinrot ) : coeffs = self . _taper2coeffs ( i ) self . coeffs [ : , i ] = _shtools . SHCilmToVector ( coeffs ) else : coeffs = _shtools . SHRotateTapers ( self . tapers , self . orders , self . nwinrot , angles , dj_matrix ) self . coeffs = coeffs
Rotate the spherical - cap windows centered on the North pole to clat and clon and save the spherical harmonic coefficients in the attribute coeffs .
14,980
def plot_vxx ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vxx_label if ax is None : fig , axes = self . vxx . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vxx . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vxx component of the tensor .
14,981
def plot_vyy ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vyy_label if ax is None : fig , axes = self . vyy . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vyy . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vyy component of the tensor .
14,982
def plot_vzz ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vzz_label if ax is None : fig , axes = self . vzz . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vzz . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vzz component of the tensor .
14,983
def plot_vxy ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vxy_label if ax is None : fig , axes = self . vxy . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vxy . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vxy component of the tensor .
14,984
def plot_vyx ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vyx_label if ax is None : fig , axes = self . vyx . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vyx . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vyx component of the tensor .
14,985
def plot_vxz ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vxz_label if ax is None : fig , axes = self . vxz . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vxz . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vxz component of the tensor .
14,986
def plot_vzx ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vzx_label if ax is None : fig , axes = self . vzx . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vzx . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vzx component of the tensor .
14,987
def plot_vyz ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vyz_label if ax is None : fig , axes = self . vyz . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vyz . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vyz component of the tensor .
14,988
def plot_vzy ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _vzy_label if ax is None : fig , axes = self . vzy . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . vzy . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the Vzy component of the tensor .
14,989
def plot_invar ( self , colorbar = True , cb_orientation = 'horizontal' , tick_interval = [ 60 , 60 ] , minor_tick_interval = [ 20 , 20 ] , xlabel = 'Longitude' , ylabel = 'Latitude' , axes_labelsize = 9 , tick_labelsize = 8 , show = True , fname = None , ** kwargs ) : if colorbar is True : if cb_orientation == 'horizontal' : scale = 0.8 else : scale = 0.5 else : scale = 0.6 figsize = ( _mpl . rcParams [ 'figure.figsize' ] [ 0 ] , _mpl . rcParams [ 'figure.figsize' ] [ 0 ] * scale ) fig , ax = _plt . subplots ( 2 , 2 , figsize = figsize ) self . plot_i0 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 0 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_i1 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 1 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_i2 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 2 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_i ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 3 ] , tick_interval = tick_interval , xlabel = xlabel , ylabel = ylabel , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) fig . tight_layout ( pad = 0.5 ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , ax
Plot the three invariants of the tensor and the derived quantity I .
14,990
def plot_eig1 ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _eig1_label if self . eig1 is None : self . compute_eig ( ) if ax is None : fig , axes = self . eig1 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . eig1 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the first eigenvalue of the tensor .
14,991
def plot_eig2 ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _eig2_label if self . eig2 is None : self . compute_eig ( ) if ax is None : fig , axes = self . eig2 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . eig2 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the second eigenvalue of the tensor .
14,992
def plot_eig3 ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _eig3_label if self . eig3 is None : self . compute_eig ( ) if ax is None : fig , axes = self . eig3 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . eig3 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the third eigenvalue of the tensor .
14,993
def plot_eigs ( self , colorbar = True , cb_orientation = 'vertical' , tick_interval = [ 60 , 60 ] , minor_tick_interval = [ 20 , 20 ] , xlabel = 'Longitude' , ylabel = 'Latitude' , axes_labelsize = 9 , tick_labelsize = 8 , show = True , fname = None , ** kwargs ) : if colorbar is True : if cb_orientation == 'horizontal' : scale = 2.3 else : scale = 1.4 else : scale = 1.65 figsize = ( _mpl . rcParams [ 'figure.figsize' ] [ 0 ] , _mpl . rcParams [ 'figure.figsize' ] [ 0 ] * scale ) fig , ax = _plt . subplots ( 3 , 1 , figsize = figsize ) self . plot_eig1 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 0 ] , xlabel = xlabel , ylabel = ylabel , tick_interval = tick_interval , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_eig2 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 1 ] , xlabel = xlabel , ylabel = ylabel , tick_interval = tick_interval , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_eig3 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 2 ] , xlabel = xlabel , ylabel = ylabel , tick_interval = tick_interval , axes_labelsize = axes_labelsize , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) fig . tight_layout ( pad = 0.5 ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , ax
Plot the three eigenvalues of the tensor .
14,994
def plot_eigh1 ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _eigh1_label if self . eigh1 is None : self . compute_eigh ( ) if ax is None : fig , axes = self . eigh1 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . eigh1 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the first eigenvalue of the horizontal tensor .
14,995
def plot_eigh2 ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _eigh2_label if self . eigh2 is None : self . compute_eigh ( ) if ax is None : fig , axes = self . eigh2 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . eigh2 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the second eigenvalue of the horizontal tensor .
14,996
def plot_eighh ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) : if cb_label is None : cb_label = self . _eighh_label if self . eighh is None : self . compute_eigh ( ) if ax is None : fig , axes = self . eighh . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , axes else : self . eighh . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , ax = ax , ** kwargs )
Plot the maximum absolute value eigenvalue of the horizontal tensor .
14,997
def plot_eigh ( self , colorbar = True , cb_orientation = 'vertical' , tick_interval = [ 60 , 60 ] , minor_tick_interval = [ 20 , 20 ] , xlabel = 'Longitude' , ylabel = 'Latitude' , axes_labelsize = 9 , tick_labelsize = 8 , show = True , fname = None , ** kwargs ) : if colorbar is True : if cb_orientation == 'horizontal' : scale = 2.3 else : scale = 1.4 else : scale = 1.65 figsize = ( _mpl . rcParams [ 'figure.figsize' ] [ 0 ] , _mpl . rcParams [ 'figure.figsize' ] [ 0 ] * scale ) fig , ax = _plt . subplots ( 3 , 1 , figsize = figsize ) self . plot_eigh1 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 0 ] , xlabel = xlabel , ylabel = ylabel , tick_interval = tick_interval , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_eigh2 ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 1 ] , xlabel = xlabel , ylabel = ylabel , tick_interval = tick_interval , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) self . plot_eighh ( colorbar = colorbar , cb_orientation = cb_orientation , ax = ax . flat [ 2 ] , xlabel = xlabel , ylabel = ylabel , tick_interval = tick_interval , tick_labelsize = tick_labelsize , minor_tick_interval = minor_tick_interval , ** kwargs ) fig . tight_layout ( pad = 0.5 ) if show : fig . show ( ) if fname is not None : fig . savefig ( fname ) return fig , ax
Plot the two eigenvalues and maximum absolute value eigenvalue of the horizontal tensor .
14,998
def get_version ( ) : d = os . path . dirname ( __file__ ) with open ( os . path . join ( d , 'VERSION' ) ) as f : vre = re . compile ( '.Version: (.+)$' , re . M ) version = vre . search ( f . read ( ) ) . group ( 1 ) if os . path . isdir ( os . path . join ( d , '.git' ) ) : cmd = 'git describe --tags' try : git_version = check_output ( cmd . split ( ) ) . decode ( ) . strip ( ) [ 1 : ] except CalledProcessError : print ( 'Unable to get version number from git tags\n' 'Setting to x.x' ) git_version = 'x.x' if '-' in git_version : git_revision = check_output ( [ 'git' , 'rev-parse' , 'HEAD' ] ) git_revision = git_revision . strip ( ) . decode ( 'ascii' ) if ISRELEASED : version += '.post0+' + git_revision [ : 7 ] else : version += '.dev0+' + git_revision [ : 7 ] return version
Get version from git and VERSION file .
14,999
def get_compiler_flags ( ) : compiler = get_default_fcompiler ( ) if compiler == 'absoft' : flags = [ '-m64' , '-O3' , '-YEXT_NAMES=LCS' , '-YEXT_SFX=_' , '-fpic' , '-speed_math=10' ] elif compiler == 'gnu95' : flags = [ '-m64' , '-fPIC' , '-O3' , '-ffast-math' ] elif compiler == 'intel' : flags = [ '-m64' , '-fpp' , '-free' , '-O3' , '-Tf' ] elif compiler == 'g95' : flags = [ '-O3' , '-fno-second-underscore' ] elif compiler == 'pg' : flags = [ '-fast' ] else : flags = [ '-m64' , '-O3' ] return flags
Set fortran flags depending on the compiler .