idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
2,800
def render ( self ) : self . set_current ( ) size = self . physical_size fbo = FrameBuffer ( color = RenderBuffer ( size [ : : - 1 ] ) , depth = RenderBuffer ( size [ : : - 1 ] ) ) try : fbo . activate ( ) self . events . draw ( ) return fbo . read ( ) finally : fbo . deactivate ( )
Render the canvas to an offscreen buffer and return the image array .
2,801
def drag_events ( self ) : if not self . is_dragging : return None event = self events = [ ] while True : if event is None or event . type == 'mouse_press' : break events . append ( event ) event = event . last_event return events [ : : - 1 ]
Return a list of all mouse events in the current drag operation .
2,802
def width_max ( self , width_max ) : if width_max is None : self . _width_limits [ 1 ] = None return width_max = float ( width_max ) assert ( self . width_min <= width_max ) self . _width_limits [ 1 ] = width_max self . _update_layout ( )
Set the maximum width of the widget .
2,803
def height_max ( self , height_max ) : if height_max is None : self . _height_limits [ 1 ] = None return height_max = float ( height_max ) assert ( 0 <= self . height_min <= height_max ) self . _height_limits [ 1 ] = height_max self . _update_layout ( )
Set the maximum height of the widget .
2,804
def inner_rect ( self ) : m = self . margin + self . _border_width + self . padding if not self . border_color . is_blank : m += 1 return Rect ( ( m , m ) , ( self . size [ 0 ] - 2 * m , self . size [ 1 ] - 2 * m ) )
The rectangular area inside the margin border and padding .
2,805
def _update_clipper ( self ) : if self . clip_children and self . _clipper is None : self . _clipper = Clipper ( ) elif not self . clip_children : self . _clipper = None if self . _clipper is None : return self . _clipper . rect = self . inner_rect self . _clipper . transform = self . get_transform ( 'framebuffer' , 'visual' )
Called whenever the clipper for this widget may need to be updated .
2,806
def _update_line ( self ) : w = self . _border_width m = self . margin l = b = m r = self . size [ 0 ] - m t = self . size [ 1 ] - m pos = np . array ( [ [ l , b ] , [ l + w , b + w ] , [ r , b ] , [ r - w , b + w ] , [ r , t ] , [ r - w , t - w ] , [ l , t ] , [ l + w , t - w ] , ] , dtype = np . float32 ) faces = np . array ( [ [ 0 , 2 , 1 ] , [ 1 , 2 , 3 ] , [ 2 , 4 , 3 ] , [ 3 , 5 , 4 ] , [ 4 , 5 , 6 ] , [ 5 , 7 , 6 ] , [ 6 , 0 , 7 ] , [ 7 , 0 , 1 ] , [ 5 , 3 , 1 ] , [ 1 , 5 , 7 ] , ] , dtype = np . int32 ) start = 8 if self . _border_color . is_blank else 0 stop = 8 if self . _bgcolor . is_blank else 10 face_colors = None if self . _face_colors is not None : face_colors = self . _face_colors [ start : stop ] self . _mesh . set_data ( vertices = pos , faces = faces [ start : stop ] , face_colors = face_colors ) self . _picking_mesh . set_data ( vertices = pos [ : : 2 ] )
Update border line to match new shape
2,807
def add_widget ( self , widget ) : self . _widgets . append ( widget ) widget . parent = self self . _update_child_widgets ( ) return widget
Add a Widget as a managed child of this Widget .
2,808
def remove_widget ( self , widget ) : self . _widgets . remove ( widget ) widget . parent = None self . _update_child_widgets ( )
Remove a Widget as a managed child of this Widget .
2,809
def pack_ieee ( value ) : return np . fromstring ( value . tostring ( ) , np . ubyte ) . reshape ( ( value . shape + ( 4 , ) ) )
Packs float ieee binary representation into 4 unsigned int8
2,810
def load_spatial_filters ( packed = True ) : names = ( "Bilinear" , "Hanning" , "Hamming" , "Hermite" , "Kaiser" , "Quadric" , "Bicubic" , "CatRom" , "Mitchell" , "Spline16" , "Spline36" , "Gaussian" , "Bessel" , "Sinc" , "Lanczos" , "Blackman" , "Nearest" ) kernel = np . load ( op . join ( DATA_DIR , 'spatial-filters.npy' ) ) if packed : kernel = pack_unit ( kernel ) return kernel , names
Load spatial - filters kernel
2,811
def timeout ( limit , handler ) : def wrapper ( f ) : def wrapped_f ( * args , ** kwargs ) : old_handler = signal . getsignal ( signal . SIGALRM ) signal . signal ( signal . SIGALRM , timeout_handler ) signal . alarm ( limit ) try : res = f ( * args , ** kwargs ) except Timeout : handler ( limit , f , args , kwargs ) else : return res finally : signal . signal ( signal . SIGALRM , old_handler ) signal . alarm ( 0 ) return wrapped_f return wrapper
A decorator ensuring that the decorated function tun time does not exceeds the argument limit .
2,812
def _process_backend_kwargs ( self , kwargs ) : app = self . _vispy_canvas . app capability = app . backend_module . capability if kwargs [ 'context' ] . shared . name : if not capability [ 'context' ] : raise RuntimeError ( 'Cannot share context with this backend' ) for key in [ key for ( key , val ) in capability . items ( ) if not val ] : if key in [ 'context' , 'multi_window' , 'scroll' ] : continue invert = key in [ 'resizable' , 'decorate' ] if bool ( kwargs [ key ] ) - invert : raise RuntimeError ( 'Config %s is not supported by backend %s' % ( key , app . backend_name ) ) out = SimpleBunch ( ) keys = [ 'title' , 'size' , 'position' , 'show' , 'vsync' , 'resizable' , 'decorate' , 'fullscreen' , 'parent' , 'context' , 'always_on_top' , ] for key in keys : out [ key ] = kwargs [ key ] return out
Simple utility to retrieve kwargs in predetermined order . Also checks whether the values of the backend arguments do not violate the backend capabilities .
2,813
def viewbox_key_event ( self , event ) : PerspectiveCamera . viewbox_key_event ( self , event ) if event . handled or not self . interactive : return if not self . _timer . running : self . _timer . start ( ) if event . key in self . _keymap : val_dims = self . _keymap [ event . key ] val = val_dims [ 0 ] if val == 0 : vec = self . _brake val = 1 else : vec = self . _acc if event . type == 'key_release' : val = 0 for dim in val_dims [ 1 : ] : factor = 1.0 vec [ dim - 1 ] = val * factor
ViewBox key event handler
2,814
def set_inputhook ( self , callback ) : ignore_CTRL_C ( ) self . _callback = callback self . _callback_pyfunctype = self . PYFUNC ( callback ) pyos_inputhook_ptr = self . get_pyos_inputhook ( ) original = self . get_pyos_inputhook_as_func ( ) pyos_inputhook_ptr . value = ctypes . cast ( self . _callback_pyfunctype , ctypes . c_void_p ) . value self . _installed = True return original
Set PyOS_InputHook to callback and return the previous one .
2,815
def clear_inputhook ( self , app = None ) : pyos_inputhook_ptr = self . get_pyos_inputhook ( ) original = self . get_pyos_inputhook_as_func ( ) pyos_inputhook_ptr . value = ctypes . c_void_p ( None ) . value allow_CTRL_C ( ) self . _reset ( ) return original
Set PyOS_InputHook to NULL and return the previous one .
2,816
def set_current_canvas ( canvas ) : canvas . context . _do_CURRENT_command = True if canvasses and canvasses [ - 1 ] ( ) is canvas : return cc = [ c ( ) for c in canvasses if c ( ) is not None ] while canvas in cc : cc . remove ( canvas ) cc . append ( canvas ) canvasses [ : ] = [ weakref . ref ( c ) for c in cc ]
Make a canvas active . Used primarily by the canvas itself .
2,817
def forget_canvas ( canvas ) : cc = [ c ( ) for c in canvasses if c ( ) is not None ] while canvas in cc : cc . remove ( canvas ) canvasses [ : ] = [ weakref . ref ( c ) for c in cc ]
Forget about the given canvas . Used by the canvas when closed .
2,818
def create_shared ( self , name , ref ) : if self . _shared is not None : raise RuntimeError ( 'Can only set_shared once.' ) self . _shared = GLShared ( name , ref )
For the app backends to create the GLShared object .
2,819
def add_ref ( self , name , ref ) : if self . _name is None : self . _name = name elif name != self . _name : raise RuntimeError ( 'Contexts can only share between backends of ' 'the same type' ) self . _refs . append ( weakref . ref ( ref ) )
Add a reference for the backend object that gives access to the low level context . Used in vispy . app . canvas . backends . The given name must match with that of previously added references .
2,820
def obj ( x ) : j = np . arange ( 1 , 6 ) tmp1 = np . dot ( j , np . cos ( ( j + 1 ) * x [ 0 ] + j ) ) tmp2 = np . dot ( j , np . cos ( ( j + 1 ) * x [ 1 ] + j ) ) return tmp1 * tmp2
Two Dimensional Shubert Function
2,821
def copy ( self ) : return Quaternion ( self . w , self . x , self . y , self . z , False )
Create an exact copy of this quaternion .
2,822
def _normalize ( self ) : L = self . norm ( ) if not L : raise ValueError ( 'Quaternion cannot have 0-length.' ) self . w /= L self . x /= L self . y /= L self . z /= L
Make the quaternion unit length .
2,823
def rotate_point ( self , p ) : p = Quaternion ( 0 , p [ 0 ] , p [ 1 ] , p [ 2 ] , False ) q1 = self . normalize ( ) q2 = self . inverse ( ) r = ( q1 * p ) * q2 return r . x , r . y , r . z
Rotate a Point instance using this quaternion .
2,824
def get_matrix ( self ) : a = np . zeros ( ( 4 , 4 ) , dtype = np . float32 ) w , x , y , z = self . w , self . x , self . y , self . z a [ 0 , 0 ] = - 2.0 * ( y * y + z * z ) + 1.0 a [ 1 , 0 ] = + 2.0 * ( x * y + z * w ) a [ 2 , 0 ] = + 2.0 * ( x * z - y * w ) a [ 3 , 0 ] = 0.0 a [ 0 , 1 ] = + 2.0 * ( x * y - z * w ) a [ 1 , 1 ] = - 2.0 * ( x * x + z * z ) + 1.0 a [ 2 , 1 ] = + 2.0 * ( z * y + x * w ) a [ 3 , 1 ] = 0.0 a [ 0 , 2 ] = + 2.0 * ( x * z + y * w ) a [ 1 , 2 ] = + 2.0 * ( y * z - x * w ) a [ 2 , 2 ] = - 2.0 * ( x * x + y * y ) + 1.0 a [ 3 , 2 ] = 0.0 a [ 0 , 3 ] = 0.0 a [ 1 , 3 ] = 0.0 a [ 2 , 3 ] = 0.0 a [ 3 , 3 ] = 1.0 return a
Create a 4x4 homography matrix that represents the rotation of the quaternion .
2,825
def create_from_euler_angles ( cls , rx , ry , rz , degrees = False ) : if degrees : rx , ry , rz = np . radians ( [ rx , ry , rz ] ) qx = Quaternion ( np . cos ( rx / 2 ) , 0 , 0 , np . sin ( rx / 2 ) ) qy = Quaternion ( np . cos ( ry / 2 ) , 0 , np . sin ( ry / 2 ) , 0 ) qz = Quaternion ( np . cos ( rz / 2 ) , np . sin ( rz / 2 ) , 0 , 0 ) return qx * qy * qz
Classmethod to create a quaternion given the euler angles .
2,826
def as_enum ( enum ) : if isinstance ( enum , string_types ) : try : enum = getattr ( gl , 'GL_' + enum . upper ( ) ) except AttributeError : try : enum = _internalformats [ 'GL_' + enum . upper ( ) ] except KeyError : raise ValueError ( 'Could not find int value for enum %r' % enum ) return enum
Turn a possibly string enum into an integer enum .
2,827
def convert_shaders ( convert , shaders ) : out = [ ] if convert == 'es2' : for isfragment , shader in enumerate ( shaders ) : has_version = False has_prec_float = False has_prec_int = False lines = [ ] for line in shader . lstrip ( ) . splitlines ( ) : if line . startswith ( '#version' ) : has_version = True continue if line . startswith ( 'precision ' ) : has_prec_float = has_prec_float or 'float' in line has_prec_int = has_prec_int or 'int' in line lines . append ( line . rstrip ( ) ) if not has_prec_float : lines . insert ( has_version , 'precision highp float;' ) if not has_prec_int : lines . insert ( has_version , 'precision highp int;' ) out . append ( '\n' . join ( lines ) ) elif convert == 'desktop' : for isfragment , shader in enumerate ( shaders ) : has_version = False lines = [ ] for line in shader . lstrip ( ) . splitlines ( ) : has_version = has_version or line . startswith ( '#version' ) if line . startswith ( 'precision ' ) : line = '' for prec in ( ' highp ' , ' mediump ' , ' lowp ' ) : line = line . replace ( prec , ' ' ) lines . append ( line . rstrip ( ) ) if not has_version : lines . insert ( 0 , '#version 120\n' ) out . append ( '\n' . join ( lines ) ) else : raise ValueError ( 'Cannot convert shaders to %r.' % convert ) return tuple ( out )
Modify shading code so that we can write code once and make it run everywhere .
2,828
def as_es2_command ( command ) : if command [ 0 ] == 'FUNC' : return ( command [ 0 ] , re . sub ( r'^gl([A-Z])' , lambda m : m . group ( 1 ) . lower ( ) , command [ 1 ] ) ) + command [ 2 : ] if command [ 0 ] == 'SHADERS' : return command [ : 2 ] + convert_shaders ( 'es2' , command [ 2 : ] ) if command [ 0 ] == 'UNIFORM' : return command [ : - 1 ] + ( command [ - 1 ] . tolist ( ) , ) return command
Modify a desktop command so it works on es2 .
2,829
def show ( self , filter = None ) : for command in self . _commands : if command [ 0 ] is None : continue if filter and command [ 0 ] != filter : continue t = [ ] for e in command : if isinstance ( e , np . ndarray ) : t . append ( 'array %s' % str ( e . shape ) ) elif isinstance ( e , str ) : s = e . strip ( ) if len ( s ) > 20 : s = s [ : 18 ] + '... %i lines' % ( e . count ( '\n' ) + 1 ) t . append ( s ) else : t . append ( e ) print ( tuple ( t ) )
Print the list of commands currently in the queue . If filter is given print only commands that match the filter .
2,830
def flush ( self , parser ) : if self . _verbose : show = self . _verbose if isinstance ( self . _verbose , str ) else None self . show ( show ) parser . parse ( self . _filter ( self . clear ( ) , parser ) )
Flush all current commands to the GLIR interpreter .
2,831
def associate ( self , queue ) : assert isinstance ( queue , GlirQueue ) if queue . _shared is self . _shared : return self . _shared . _commands . extend ( queue . clear ( ) ) self . _shared . _verbose |= queue . _shared . _verbose self . _shared . _associations [ queue ] = None for ch in queue . _shared . _associations : ch . _shared = self . _shared self . _shared . _associations [ ch ] = None queue . _shared = self . _shared
Merge this queue with another .
2,832
def _parse ( self , command ) : cmd , id_ , args = command [ 0 ] , command [ 1 ] , command [ 2 : ] if cmd == 'CURRENT' : self . env . clear ( ) self . _gl_initialize ( ) self . env [ 'fbo' ] = args [ 0 ] gl . glBindFramebuffer ( gl . GL_FRAMEBUFFER , args [ 0 ] ) elif cmd == 'FUNC' : args = [ as_enum ( a ) for a in args ] try : getattr ( gl , id_ ) ( * args ) except AttributeError : logger . warning ( 'Invalid gl command: %r' % id_ ) elif cmd == 'CREATE' : if args [ 0 ] is not None : klass = self . _classmap [ args [ 0 ] ] self . _objects [ id_ ] = klass ( self , id_ ) else : self . _invalid_objects . add ( id_ ) elif cmd == 'DELETE' : ob = self . _objects . get ( id_ , None ) if ob is not None : self . _objects [ id_ ] = JUST_DELETED ob . delete ( ) else : ob = self . _objects . get ( id_ , None ) if ob == JUST_DELETED : return if ob is None : if id_ not in self . _invalid_objects : raise RuntimeError ( 'Cannot %s object %i because it ' 'does not exist' % ( cmd , id_ ) ) return if cmd == 'DRAW' : ob . draw ( * args ) elif cmd == 'TEXTURE' : ob . set_texture ( * args ) elif cmd == 'UNIFORM' : ob . set_uniform ( * args ) elif cmd == 'ATTRIBUTE' : ob . set_attribute ( * args ) elif cmd == 'DATA' : ob . set_data ( * args ) elif cmd == 'SIZE' : ob . set_size ( * args ) elif cmd == 'ATTACH' : ob . attach ( * args ) elif cmd == 'FRAMEBUFFER' : ob . set_framebuffer ( * args ) elif cmd == 'SHADERS' : ob . set_shaders ( * args ) elif cmd == 'WRAPPING' : ob . set_wrapping ( * args ) elif cmd == 'INTERPOLATION' : ob . set_interpolation ( * args ) else : logger . warning ( 'Invalid GLIR command %r' % cmd )
Parse a single command .
2,833
def parse ( self , commands ) : to_delete = [ ] for id_ , val in self . _objects . items ( ) : if val == JUST_DELETED : to_delete . append ( id_ ) for id_ in to_delete : self . _objects . pop ( id_ ) for command in commands : self . _parse ( command )
Parse a list of commands .
2,834
def _gl_initialize ( self ) : if '.es' in gl . current_backend . __name__ : pass else : GL_VERTEX_PROGRAM_POINT_SIZE = 34370 GL_POINT_SPRITE = 34913 gl . glEnable ( GL_VERTEX_PROGRAM_POINT_SIZE ) gl . glEnable ( GL_POINT_SPRITE ) if self . capabilities [ 'max_texture_size' ] is None : self . capabilities [ 'gl_version' ] = gl . glGetParameter ( gl . GL_VERSION ) self . capabilities [ 'max_texture_size' ] = gl . glGetParameter ( gl . GL_MAX_TEXTURE_SIZE ) this_version = self . capabilities [ 'gl_version' ] . split ( ' ' ) [ 0 ] this_version = LooseVersion ( this_version )
Deal with compatibility ; desktop does not have sprites enabled by default . ES has .
2,835
def set_shaders ( self , vert , frag ) : self . _linked = False vert_handle = gl . glCreateShader ( gl . GL_VERTEX_SHADER ) frag_handle = gl . glCreateShader ( gl . GL_FRAGMENT_SHADER ) for code , handle , type_ in [ ( vert , vert_handle , 'vertex' ) , ( frag , frag_handle , 'fragment' ) ] : gl . glShaderSource ( handle , code ) gl . glCompileShader ( handle ) status = gl . glGetShaderParameter ( handle , gl . GL_COMPILE_STATUS ) if not status : errors = gl . glGetShaderInfoLog ( handle ) errormsg = self . _get_error ( code , errors , 4 ) raise RuntimeError ( "Shader compilation error in %s:\n%s" % ( type_ + ' shader' , errormsg ) ) gl . glAttachShader ( self . _handle , vert_handle ) gl . glAttachShader ( self . _handle , frag_handle ) gl . glLinkProgram ( self . _handle ) if not gl . glGetProgramParameter ( self . _handle , gl . GL_LINK_STATUS ) : raise RuntimeError ( 'Program linking error:\n%s' % gl . glGetProgramInfoLog ( self . _handle ) ) gl . glDetachShader ( self . _handle , vert_handle ) gl . glDetachShader ( self . _handle , frag_handle ) gl . glDeleteShader ( vert_handle ) gl . glDeleteShader ( frag_handle ) self . _unset_variables = self . _get_active_attributes_and_uniforms ( ) self . _handles = { } self . _known_invalid = set ( ) self . _linked = True
This function takes care of setting the shading code and compiling + linking it into a working program object that is ready to use .
2,836
def _parse_error ( self , error ) : error = str ( error ) m = re . match ( r'(\d+)\((\d+)\)\s*:\s(.*)' , error ) if m : return int ( m . group ( 2 ) ) , m . group ( 3 ) m = re . match ( r'ERROR:\s(\d+):(\d+):\s(.*)' , error ) if m : return int ( m . group ( 2 ) ) , m . group ( 3 ) m = re . match ( r'(\d+):(\d+)\((\d+)\):\s(.*)' , error ) if m : return int ( m . group ( 2 ) ) , m . group ( 4 ) return None , error
Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this .
2,837
def _get_error ( self , code , errors , indentation = 0 ) : results = [ ] lines = None if code is not None : lines = [ line . strip ( ) for line in code . split ( '\n' ) ] for error in errors . split ( '\n' ) : error = error . strip ( ) if not error : continue linenr , error = self . _parse_error ( error ) if None in ( linenr , lines ) : results . append ( '%s' % error ) else : results . append ( 'on line %i: %s' % ( linenr , error ) ) if linenr > 0 and linenr < len ( lines ) : results . append ( ' %s' % lines [ linenr - 1 ] ) results = [ ' ' * indentation + r for r in results ] return '\n' . join ( results )
Get error and show the faulty line + some context Other GLIR implementations may omit this .
2,838
def set_texture ( self , name , value ) : if not self . _linked : raise RuntimeError ( 'Cannot set uniform when program has no code' ) handle = self . _handles . get ( name , - 1 ) if handle < 0 : if name in self . _known_invalid : return handle = gl . glGetUniformLocation ( self . _handle , name ) self . _unset_variables . discard ( name ) self . _handles [ name ] = handle if handle < 0 : self . _known_invalid . add ( name ) logger . info ( 'Variable %s is not an active uniform' % name ) return self . activate ( ) if True : tex = self . _parser . get_object ( value ) if tex == JUST_DELETED : return if tex is None : raise RuntimeError ( 'Could not find texture with id %i' % value ) unit = len ( self . _samplers ) if name in self . _samplers : unit = self . _samplers [ name ] [ - 1 ] self . _samplers [ name ] = tex . _target , tex . handle , unit gl . glUniform1i ( handle , unit )
Set a texture sampler . Value is the id of the texture to link .
2,839
def set_uniform ( self , name , type_ , value ) : if not self . _linked : raise RuntimeError ( 'Cannot set uniform when program has no code' ) handle = self . _handles . get ( name , - 1 ) count = 1 if handle < 0 : if name in self . _known_invalid : return handle = gl . glGetUniformLocation ( self . _handle , name ) self . _unset_variables . discard ( name ) if not type_ . startswith ( 'mat' ) : count = value . nbytes // ( 4 * self . ATYPEINFO [ type_ ] [ 0 ] ) if count > 1 : for ii in range ( count ) : if '%s[%s]' % ( name , ii ) in self . _unset_variables : self . _unset_variables . discard ( '%s[%s]' % ( name , ii ) ) self . _handles [ name ] = handle if handle < 0 : self . _known_invalid . add ( name ) logger . info ( 'Variable %s is not an active uniform' % name ) return funcname = self . UTYPEMAP [ type_ ] func = getattr ( gl , funcname ) self . activate ( ) if type_ . startswith ( 'mat' ) : transpose = False func ( handle , 1 , transpose , value ) else : func ( handle , count , value )
Set a uniform value . Value is assumed to have been checked .
2,840
def set_attribute ( self , name , type_ , value ) : if not self . _linked : raise RuntimeError ( 'Cannot set attribute when program has no code' ) handle = self . _handles . get ( name , - 1 ) if handle < 0 : if name in self . _known_invalid : return handle = gl . glGetAttribLocation ( self . _handle , name ) self . _unset_variables . discard ( name ) self . _handles [ name ] = handle if handle < 0 : self . _known_invalid . add ( name ) if value [ 0 ] != 0 and value [ 2 ] > 0 : return logger . info ( 'Variable %s is not an active attribute' % name ) return self . activate ( ) if value [ 0 ] == 0 : funcname = self . ATYPEMAP [ type_ ] func = getattr ( gl , funcname ) self . _attributes [ name ] = 0 , handle , func , value [ 1 : ] else : vbo_id , stride , offset = value size , gtype , dtype = self . ATYPEINFO [ type_ ] vbo = self . _parser . get_object ( vbo_id ) if vbo == JUST_DELETED : return if vbo is None : raise RuntimeError ( 'Could not find VBO with id %i' % vbo_id ) func = gl . glVertexAttribPointer args = size , gtype , gl . GL_FALSE , stride , offset self . _attributes [ name ] = vbo . handle , handle , func , args
Set an attribute value . Value is assumed to have been checked .
2,841
def as_matrix_transform ( transform ) : if isinstance ( transform , ChainTransform ) : matrix = np . identity ( 4 ) for tr in transform . transforms : matrix = np . matmul ( as_matrix_transform ( tr ) . matrix , matrix ) return MatrixTransform ( matrix ) elif isinstance ( transform , InverseTransform ) : matrix = as_matrix_transform ( transform . _inverse ) return MatrixTransform ( matrix . inv_matrix ) elif isinstance ( transform , NullTransform ) : return MatrixTransform ( ) elif isinstance ( transform , STTransform ) : return transform . as_matrix ( ) elif isinstance ( transform , MatrixTransform ) : return transform else : raise TypeError ( "Could not simplify transform of type {0}" . format ( type ( transform ) ) )
Simplify a transform to a single matrix transform which makes it a lot faster to compute transformations .
2,842
def circular ( adjacency_mat , directed = False ) : if issparse ( adjacency_mat ) : adjacency_mat = adjacency_mat . tocoo ( ) num_nodes = adjacency_mat . shape [ 0 ] t = np . linspace ( 0 , 2 * np . pi , num_nodes , endpoint = False , dtype = np . float32 ) node_coords = ( 0.5 * np . array ( [ np . cos ( t ) , np . sin ( t ) ] ) + 0.5 ) . T line_vertices , arrows = _straight_line_vertices ( adjacency_mat , node_coords , directed ) yield node_coords , line_vertices , arrows
Places all nodes on a single circle .
2,843
def set_data ( self , pos = None , symbol = 'o' , size = 10. , edge_width = 1. , edge_width_rel = None , edge_color = 'black' , face_color = 'white' , scaling = False ) : assert ( isinstance ( pos , np . ndarray ) and pos . ndim == 2 and pos . shape [ 1 ] in ( 2 , 3 ) ) if ( edge_width is not None ) + ( edge_width_rel is not None ) != 1 : raise ValueError ( 'exactly one of edge_width and edge_width_rel ' 'must be non-None' ) if edge_width is not None : if edge_width < 0 : raise ValueError ( 'edge_width cannot be negative' ) else : if edge_width_rel < 0 : raise ValueError ( 'edge_width_rel cannot be negative' ) self . symbol = symbol self . scaling = scaling edge_color = ColorArray ( edge_color ) . rgba if len ( edge_color ) == 1 : edge_color = edge_color [ 0 ] face_color = ColorArray ( face_color ) . rgba if len ( face_color ) == 1 : face_color = face_color [ 0 ] n = len ( pos ) data = np . zeros ( n , dtype = [ ( 'a_position' , np . float32 , 3 ) , ( 'a_fg_color' , np . float32 , 4 ) , ( 'a_bg_color' , np . float32 , 4 ) , ( 'a_size' , np . float32 , 1 ) , ( 'a_edgewidth' , np . float32 , 1 ) ] ) data [ 'a_fg_color' ] = edge_color data [ 'a_bg_color' ] = face_color if edge_width is not None : data [ 'a_edgewidth' ] = edge_width else : data [ 'a_edgewidth' ] = size * edge_width_rel data [ 'a_position' ] [ : , : pos . shape [ 1 ] ] = pos data [ 'a_size' ] = size self . shared_program [ 'u_antialias' ] = self . antialias self . _data = data self . _vbo . set_data ( data ) self . shared_program . bind ( self . _vbo ) self . update ( )
Set the data used to display this visual .
2,844
def hook_changed ( self , hook_name , widget , new_data ) : if hook_name == 'song' : self . song_changed ( widget , new_data ) elif hook_name == 'state' : self . state_changed ( widget , new_data ) elif hook_name == 'elapsed_and_total' : elapsed , total = new_data self . time_changed ( widget , elapsed , total )
Handle a hook upate .
2,845
def update ( self , func , ** kw ) : "Update the signature of func with the data in self" func . __name__ = self . name func . __doc__ = getattr ( self , 'doc' , None ) func . __dict__ = getattr ( self , 'dict' , { } ) func . __defaults__ = getattr ( self , 'defaults' , ( ) ) func . __kwdefaults__ = getattr ( self , 'kwonlydefaults' , None ) func . __annotations__ = getattr ( self , 'annotations' , None ) callermodule = sys . _getframe ( 3 ) . f_globals . get ( '__name__' , '?' ) func . __module__ = getattr ( self , 'module' , callermodule ) func . __dict__ . update ( kw )
Update the signature of func with the data in self
2,846
def make ( self , src_templ , evaldict = None , addsource = False , ** attrs ) : "Make a new function from a given template and update the signature" src = src_templ % vars ( self ) evaldict = evaldict or { } mo = DEF . match ( src ) if mo is None : raise SyntaxError ( 'not a valid function template\n%s' % src ) name = mo . group ( 1 ) names = set ( [ name ] + [ arg . strip ( ' *' ) for arg in self . shortsignature . split ( ',' ) ] ) for n in names : if n in ( '_func_' , '_call_' ) : raise NameError ( '%s is overridden in\n%s' % ( n , src ) ) if not src . endswith ( '\n' ) : src += '\n' try : code = compile ( src , '<string>' , 'single' ) exec ( code , evaldict ) except : print ( 'Error in generated code:' , file = sys . stderr ) print ( src , file = sys . stderr ) raise func = evaldict [ name ] if addsource : attrs [ '__source__' ] = src self . update ( func , ** attrs ) return func
Make a new function from a given template and update the signature
2,847
def get_scene_bounds ( self , dim = None ) : bounds = [ ( np . inf , - np . inf ) , ( np . inf , - np . inf ) , ( np . inf , - np . inf ) ] for ob in self . scene . children : if hasattr ( ob , 'bounds' ) : for axis in ( 0 , 1 , 2 ) : if ( dim is not None ) and dim != axis : continue b = ob . bounds ( axis ) if b is not None : b = min ( b ) , max ( b ) bounds [ axis ] = ( min ( bounds [ axis ] [ 0 ] , b [ 0 ] ) , max ( bounds [ axis ] [ 1 ] , b [ 1 ] ) ) for axis in ( 0 , 1 , 2 ) : if any ( np . isinf ( bounds [ axis ] ) ) : bounds [ axis ] = - 1 , 1 if dim is not None : return bounds [ dim ] else : return bounds
Get the total bounds based on the visuals present in the scene
2,848
def _array_clip_val ( val ) : val = np . array ( val ) if val . max ( ) > 1 or val . min ( ) < 0 : logger . warning ( 'value will be clipped between 0 and 1' ) val [ ... ] = np . clip ( val , 0 , 1 ) return val
Helper to turn val into array and clip between 0 and 1
2,849
def extend ( self , colors ) : colors = ColorArray ( colors ) self . _rgba = np . vstack ( ( self . _rgba , colors . _rgba ) ) return self
Extend a ColorArray with new colors
2,850
def rgba ( self , val ) : rgba = _user_to_rgba ( val , expand = False ) if self . _rgba is None : self . _rgba = rgba else : self . _rgba [ : , : rgba . shape [ 1 ] ] = rgba
Set the color using an Nx4 array of RGBA floats
2,851
def RGBA ( self , val ) : val = np . atleast_1d ( val ) . astype ( np . float32 ) / 255 self . rgba = val
Set the color using an Nx4 array of RGBA uint8 values
2,852
def RGB ( self , val ) : val = np . atleast_1d ( val ) . astype ( np . float32 ) / 255. self . rgba = val
Set the color using an Nx3 array of RGB uint8 values
2,853
def viewbox_mouse_event ( self , event ) : BaseCamera . viewbox_mouse_event ( self , event ) if event . type == 'mouse_wheel' : s = 1.1 ** - event . delta [ 1 ] self . _scale_factor *= s if self . _distance is not None : self . _distance *= s self . view_changed ( )
The ViewBox received a mouse event ; update transform accordingly . Default implementation adjusts scale factor when scolling .
2,854
def _set_range ( self , init ) : if init and ( self . _scale_factor is not None ) : return w , h = self . _viewbox . size w , h = float ( w ) , float ( h ) x1 , y1 , z1 = self . _xlim [ 0 ] , self . _ylim [ 0 ] , self . _zlim [ 0 ] x2 , y2 , z2 = self . _xlim [ 1 ] , self . _ylim [ 1 ] , self . _zlim [ 1 ] rx , ry , rz = ( x2 - x1 ) , ( y2 - y1 ) , ( z2 - z1 ) if w / h > 1 : rx /= w / h ry /= w / h else : rz /= h / w rxs = ( rx ** 2 + ry ** 2 ) ** 0.5 rys = ( rx ** 2 + ry ** 2 + rz ** 2 ) ** 0.5 self . scale_factor = max ( rxs , rys ) * 1.04
Reset the camera view using the known limits .
2,855
def viewbox_mouse_event ( self , event ) : if event . handled or not self . interactive : return PerspectiveCamera . viewbox_mouse_event ( self , event ) if event . type == 'mouse_release' : self . _event_value = None elif event . type == 'mouse_press' : event . handled = True elif event . type == 'mouse_move' : if event . press_event is None : return modifiers = event . mouse_event . modifiers p1 = event . mouse_event . press_event . pos p2 = event . mouse_event . pos d = p2 - p1 if 1 in event . buttons and not modifiers : self . _update_rotation ( event ) elif 2 in event . buttons and not modifiers : if self . _event_value is None : self . _event_value = ( self . _scale_factor , self . _distance ) zoomy = ( 1 + self . zoom_factor ) ** d [ 1 ] self . scale_factor = self . _event_value [ 0 ] * zoomy if self . _distance is not None : self . _distance = self . _event_value [ 1 ] * zoomy self . view_changed ( ) elif 1 in event . buttons and keys . SHIFT in modifiers : norm = np . mean ( self . _viewbox . size ) if self . _event_value is None or len ( self . _event_value ) == 2 : self . _event_value = self . center dist = ( p1 - p2 ) / norm * self . _scale_factor dist [ 1 ] *= - 1 dx , dy , dz = self . _dist_to_trans ( dist ) ff = self . _flip_factors up , forward , right = self . _get_dim_vectors ( ) dx , dy , dz = right * dx + forward * dy + up * dz dx , dy , dz = ff [ 0 ] * dx , ff [ 1 ] * dy , dz * ff [ 2 ] c = self . _event_value self . center = c [ 0 ] + dx , c [ 1 ] + dy , c [ 2 ] + dz elif 2 in event . buttons and keys . SHIFT in modifiers : if self . _event_value is None : self . _event_value = self . _fov fov = self . _event_value - d [ 1 ] / 5.0 self . fov = min ( 180.0 , max ( 0.0 , fov ) )
The viewbox received a mouse event ; update transform accordingly .
2,856
def _update_camera_pos ( self ) : ch_em = self . events . transform_change with ch_em . blocker ( self . _update_transform ) : tr = self . transform tr . reset ( ) up , forward , right = self . _get_dim_vectors ( ) pp1 = np . array ( [ ( 0 , 0 , 0 ) , ( 0 , 0 , - 1 ) , ( 1 , 0 , 0 ) , ( 0 , 1 , 0 ) ] ) pp2 = np . array ( [ ( 0 , 0 , 0 ) , forward , right , up ] ) tr . set_mapping ( pp1 , pp2 ) tr . translate ( - self . _actual_distance * forward ) self . _rotate_tr ( ) tr . scale ( [ 1.0 / a for a in self . _flip_factors ] ) tr . translate ( np . array ( self . center ) )
Set the camera position and orientation
2,857
def is_interactive ( self ) : if sys . flags . interactive : return True if '__IPYTHON__' not in dir ( six . moves . builtins ) : return False try : from IPython . config . application import Application as App return App . initialized ( ) and App . instance ( ) . interact except ( ImportError , AttributeError ) : return False
Determine if the user requested interactive mode .
2,858
def run ( self , allow_interactive = True ) : if allow_interactive and self . is_interactive ( ) : inputhook . set_interactive ( enabled = True , app = self ) else : return self . _backend . _vispy_run ( )
Enter the native GUI event loop .
2,859
def _use ( self , backend_name = None ) : test_name = os . getenv ( '_VISPY_TESTING_APP' , None ) if backend_name is not None : if backend_name . lower ( ) == 'default' : backend_name = None elif backend_name . lower ( ) not in BACKENDMAP : raise ValueError ( 'backend_name must be one of %s or None, not ' '%r' % ( BACKEND_NAMES , backend_name ) ) elif test_name is not None : backend_name = test_name . lower ( ) assert backend_name in BACKENDMAP try_others = backend_name is None imported_toolkits = [ ] backends_to_try = [ ] if not try_others : assert backend_name . lower ( ) in BACKENDMAP . keys ( ) backends_to_try . append ( backend_name . lower ( ) ) else : for name , module_name , native_module_name in CORE_BACKENDS : if native_module_name and native_module_name in sys . modules : imported_toolkits . append ( name . lower ( ) ) backends_to_try . append ( name . lower ( ) ) default_backend = config [ 'default_backend' ] . lower ( ) if default_backend . lower ( ) in BACKENDMAP . keys ( ) : if default_backend not in backends_to_try : backends_to_try . append ( default_backend ) for name , module_name , native_module_name in CORE_BACKENDS : name = name . lower ( ) if name not in backends_to_try : backends_to_try . append ( name ) for key in backends_to_try : name , module_name , native_module_name = BACKENDMAP [ key ] TRIED_BACKENDS . append ( name ) mod_name = 'backends.' + module_name __import__ ( mod_name , globals ( ) , level = 1 ) mod = getattr ( backends , module_name ) if not mod . available : msg = ( 'Could not import backend "%s":\n%s' % ( name , str ( mod . why_not ) ) ) if not try_others : raise RuntimeError ( msg ) elif key in imported_toolkits : msg = ( 'Although %s is already imported, the %s backend ' 'could not\nbe used ("%s"). \nNote that running ' 'multiple GUI toolkits simultaneously can cause ' 'side effects.' % ( native_module_name , name , str ( mod . why_not ) ) ) logger . warning ( msg ) else : logger . info ( msg ) else : self . _backend_module = mod logger . debug ( 'Selected backend %s' % module_name ) break else : raise RuntimeError ( 'Could not import any of the backends. ' 'You need to install any of %s. We recommend ' 'PyQt' % [ b [ 0 ] for b in CORE_BACKENDS ] ) self . _backend = self . backend_module . ApplicationBackend ( )
Select a backend by name . See class docstring for details .
2,860
def _get_mods ( evt ) : mods = [ ] mods += [ keys . CONTROL ] if evt . ControlDown ( ) else [ ] mods += [ keys . ALT ] if evt . AltDown ( ) else [ ] mods += [ keys . SHIFT ] if evt . ShiftDown ( ) else [ ] mods += [ keys . META ] if evt . MetaDown ( ) else [ ] return mods
Helper to extract list of mods from event
2,861
def _process_key ( evt ) : key = evt . GetKeyCode ( ) if key in KEYMAP : return KEYMAP [ key ] , '' if 97 <= key <= 122 : key -= 32 if key >= 32 and key <= 127 : return keys . Key ( chr ( key ) ) , chr ( key ) else : return None , None
Helper to convert from wx keycode to vispy keycode
2,862
def is_child ( self , node ) : if node in self . children : return True for c in self . children : if c . is_child ( node ) : return True return False
Check if a node is a child of the current node
2,863
def scene_node ( self ) : if self . _scene_node is None : from . subscene import SubScene p = self . parent while True : if isinstance ( p , SubScene ) or p is None : self . _scene_node = p break p = p . parent if self . _scene_node is None : self . _scene_node = self return self . _scene_node
The first ancestor of this node that is a SubScene instance or self if no such node exists .
2,864
def update ( self ) : self . events . update ( ) c = getattr ( self , 'canvas' , None ) if c is not None : c . update ( node = self )
Emit an event to inform listeners that properties of this Node have changed . Also request a canvas update .
2,865
def parent_chain ( self ) : chain = [ self ] while True : try : parent = chain [ - 1 ] . parent except Exception : break if parent is None : break chain . append ( parent ) return chain
Return the list of parents starting from this node . The chain ends at the first node with no parents .
2,866
def _describe_tree ( self , prefix , with_transform ) : extra = ': "%s"' % self . name if self . name is not None else '' if with_transform : extra += ( ' [%s]' % self . transform . __class__ . __name__ ) output = '' if len ( prefix ) > 0 : output += prefix [ : - 3 ] output += ' +--' output += '%s%s\n' % ( self . __class__ . __name__ , extra ) n_children = len ( self . children ) for ii , child in enumerate ( self . children ) : sub_prefix = prefix + ( ' ' if ii + 1 == n_children else ' |' ) output += child . _describe_tree ( sub_prefix , with_transform ) return output
Helper function to actuall construct the tree
2,867
def common_parent ( self , node ) : p1 = self . parent_chain ( ) p2 = node . parent_chain ( ) for p in p1 : if p in p2 : return p return None
Return the common parent of two entities
2,868
def node_path_to_child ( self , node ) : if node is self : return [ ] path1 = [ node ] child = node while child . parent is not None : child = child . parent path1 . append ( child ) if child is self : return list ( reversed ( path1 ) ) if path1 [ - 1 ] . parent is None : raise RuntimeError ( '%r is not a child of %r' % ( node , self ) ) def _is_child ( path , parent , child ) : path . append ( parent ) if child in parent . children : return path else : for c in parent . children : possible_path = _is_child ( path [ : ] , c , child ) if possible_path : return possible_path return None path2 = _is_child ( [ ] , self , path1 [ - 1 ] ) if not path2 : raise RuntimeError ( '%r is not a child of %r' % ( node , self ) ) return path2 + list ( reversed ( path1 ) )
Return a list describing the path from this node to a child node
2,869
def node_path ( self , node ) : p1 = self . parent_chain ( ) p2 = node . parent_chain ( ) cp = None for p in p1 : if p in p2 : cp = p break if cp is None : raise RuntimeError ( "No single-path common parent between nodes %s " "and %s." % ( self , node ) ) p1 = p1 [ : p1 . index ( cp ) + 1 ] p2 = p2 [ : p2 . index ( cp ) ] [ : : - 1 ] return p1 , p2
Return two lists describing the path from this node to another
2,870
def node_path_transforms ( self , node ) : a , b = self . node_path ( node ) return ( [ n . transform for n in a [ : - 1 ] ] + [ n . transform . inverse for n in b ] ) [ : : - 1 ]
Return the list of transforms along the path to another node . The transforms are listed in reverse order such that the last transform should be applied first when mapping from this node to the other .
2,871
def readLine ( self ) : line = self . _f . readline ( ) . decode ( 'ascii' , 'ignore' ) if not line : raise EOFError ( ) line = line . strip ( ) if line . startswith ( 'v ' ) : self . _v . append ( self . readTuple ( line ) ) elif line . startswith ( 'vt ' ) : self . _vt . append ( self . readTuple ( line , 3 ) ) elif line . startswith ( 'vn ' ) : self . _vn . append ( self . readTuple ( line ) ) elif line . startswith ( 'f ' ) : self . _faces . append ( self . readFace ( line ) ) elif line . startswith ( '#' ) : pass elif line . startswith ( 'mtllib ' ) : logger . warning ( 'Notice reading .OBJ: material properties are ' 'ignored.' ) elif any ( line . startswith ( x ) for x in ( 'g ' , 's ' , 'o ' , 'usemtl ' ) ) : pass elif not line . strip ( ) : pass else : logger . warning ( 'Notice reading .OBJ: ignoring %s command.' % line . strip ( ) )
The method that reads a line and processes it .
2,872
def finish ( self ) : self . _vertices = np . array ( self . _vertices , 'float32' ) if self . _faces : self . _faces = np . array ( self . _faces , 'uint32' ) else : self . _vertices = np . array ( self . _v , 'float32' ) self . _faces = None if self . _normals : self . _normals = np . array ( self . _normals , 'float32' ) else : self . _normals = self . _calculate_normals ( ) if self . _texcords : self . _texcords = np . array ( self . _texcords , 'float32' ) else : self . _texcords = None return self . _vertices , self . _faces , self . _normals , self . _texcords
Converts gathere lists to numpy arrays and creates BaseMesh instance .
2,873
def write ( cls , fname , vertices , faces , normals , texcoords , name = '' , reshape_faces = True ) : fmt = op . splitext ( fname ) [ 1 ] . lower ( ) if fmt not in ( '.obj' , '.gz' ) : raise ValueError ( 'Filename must end with .obj or .gz, not "%s"' % ( fmt , ) ) opener = open if fmt == '.obj' else gzip_open f = opener ( fname , 'wb' ) try : writer = WavefrontWriter ( f ) writer . writeMesh ( vertices , faces , normals , texcoords , name , reshape_faces = reshape_faces ) except EOFError : pass finally : f . close ( )
This classmethod is the entry point for writing mesh data to OBJ .
2,874
def writeFace ( self , val , what = 'f' ) : val = [ v + 1 for v in val ] if self . _hasValues and self . _hasNormals : val = ' ' . join ( [ '%i/%i/%i' % ( v , v , v ) for v in val ] ) elif self . _hasNormals : val = ' ' . join ( [ '%i//%i' % ( v , v ) for v in val ] ) elif self . _hasValues : val = ' ' . join ( [ '%i/%i' % ( v , v ) for v in val ] ) else : val = ' ' . join ( [ '%i' % v for v in val ] ) self . writeLine ( '%s %s' % ( what , val ) )
Write the face info to the net line .
2,875
def writeMesh ( self , vertices , faces , normals , values , name = '' , reshape_faces = True ) : self . _hasNormals = normals is not None self . _hasValues = values is not None self . _hasFaces = faces is not None if faces is None : faces = np . arange ( len ( vertices ) ) reshape_faces = True if reshape_faces : Nfaces = faces . size // 3 faces = faces . reshape ( ( Nfaces , 3 ) ) else : is_triangular = np . array ( [ len ( f ) == 3 for f in faces ] ) if not ( np . all ( is_triangular ) ) : logger . warning ( ) N = vertices . shape [ 0 ] stats = [ ] stats . append ( '%i vertices' % N ) if self . _hasValues : stats . append ( '%i texcords' % N ) else : stats . append ( 'no texcords' ) if self . _hasNormals : stats . append ( '%i normals' % N ) else : stats . append ( 'no normals' ) stats . append ( '%i faces' % faces . shape [ 0 ] ) self . writeLine ( '# Wavefront OBJ file' ) self . writeLine ( '# Created by vispy.' ) self . writeLine ( '#' ) if name : self . writeLine ( '# object %s' % name ) else : self . writeLine ( '# unnamed object' ) self . writeLine ( '# %s' % ', ' . join ( stats ) ) self . writeLine ( '' ) if True : for i in range ( N ) : self . writeTuple ( vertices [ i ] , 'v' ) if self . _hasNormals : for i in range ( N ) : self . writeTuple ( normals [ i ] , 'vn' ) if self . _hasValues : for i in range ( N ) : self . writeTuple ( values [ i ] , 'vt' ) if True : for i in range ( faces . shape [ 0 ] ) : self . writeFace ( faces [ i ] )
Write the given mesh instance .
2,876
def _fast_cross_3d ( x , y ) : assert x . ndim == 2 assert y . ndim == 2 assert x . shape [ 1 ] == 3 assert y . shape [ 1 ] == 3 assert ( x . shape [ 0 ] == 1 or y . shape [ 0 ] == 1 ) or x . shape [ 0 ] == y . shape [ 0 ] if max ( [ x . shape [ 0 ] , y . shape [ 0 ] ] ) >= 500 : return np . c_ [ x [ : , 1 ] * y [ : , 2 ] - x [ : , 2 ] * y [ : , 1 ] , x [ : , 2 ] * y [ : , 0 ] - x [ : , 0 ] * y [ : , 2 ] , x [ : , 0 ] * y [ : , 1 ] - x [ : , 1 ] * y [ : , 0 ] ] else : return np . cross ( x , y )
Compute cross product between list of 3D vectors
2,877
def _calculate_normals ( rr , tris ) : rr = rr . astype ( np . float64 ) r1 = rr [ tris [ : , 0 ] , : ] r2 = rr [ tris [ : , 1 ] , : ] r3 = rr [ tris [ : , 2 ] , : ] tri_nn = _fast_cross_3d ( ( r2 - r1 ) , ( r3 - r1 ) ) size = np . sqrt ( np . sum ( tri_nn * tri_nn , axis = 1 ) ) size [ size == 0 ] = 1.0 tri_nn /= size [ : , np . newaxis ] npts = len ( rr ) nn = np . zeros ( ( npts , 3 ) ) for verts in tris . T : for idx in range ( 3 ) : nn [ : , idx ] += np . bincount ( verts . astype ( np . int32 ) , tri_nn [ : , idx ] , minlength = npts ) size = np . sqrt ( np . sum ( nn * nn , axis = 1 ) ) size [ size == 0 ] = 1.0 nn /= size [ : , np . newaxis ] return nn
Efficiently compute vertex normals for triangulated surface
2,878
def parse ( self ) : for line in self . lines : field_defs = self . parse_line ( line ) fields = [ ] for ( kind , options ) in field_defs : logger . debug ( "Creating field %s(%r)" , kind , options ) fields . append ( self . field_registry . create ( kind , ** options ) ) self . line_fields . append ( fields ) for field in fields : self . widgets [ field ] = None
Parse the lines and fill self . line_fields accordingly .
2,879
def compute_positions ( cls , screen_width , line ) : left = 1 right = screen_width + 1 flexible = None for field in line : if field . is_flexible ( ) : if flexible : raise FormatError ( 'There can be only one flexible field per line.' ) flexible = field elif not flexible : left += field . width else : right -= field . width available = right - left if available <= 0 : raise FormatError ( "Too much data for screen width" ) if flexible : if available < 1 : raise FormatError ( "Not enough space to display flexible field %s" % flexible . name ) flexible . width = available positions = [ ] left = 1 for field in line : positions . append ( ( left , field ) ) left += field . width logger . debug ( 'Positions are %r' , positions ) return positions
Compute the relative position of the fields on a given line .
2,880
def add_to_screen ( self , screen_width , screen ) : for lineno , fields in enumerate ( self . line_fields ) : for left , field in self . compute_positions ( screen_width , fields ) : logger . debug ( "Adding field %s to screen %s at x=%d->%d, y=%d" , field , screen . ref , left , left + field . width - 1 , 1 + lineno , ) self . widgets [ field ] = field . add_to_screen ( screen , left , 1 + lineno ) self . register_hooks ( field )
Add the pattern to a screen .
2,881
def register_hooks ( self , field ) : for hook , subhooks in field . register_hooks ( ) : self . hooks [ hook ] . append ( field ) self . subhooks [ hook ] |= set ( subhooks )
Register a field on its target hooks .
2,882
def hook_changed ( self , hook , new_data ) : for field in self . hooks [ hook ] : widget = self . widgets [ field ] field . hook_changed ( hook , widget , new_data )
Called whenever the data for a hook changed .
2,883
def add ( self , pattern_txt ) : self . patterns [ len ( pattern_txt ) ] = pattern_txt low = 0 high = len ( pattern_txt ) - 1 while not pattern_txt [ low ] : low += 1 while not pattern_txt [ high ] : high -= 1 min_pattern = pattern_txt [ low : high + 1 ] self . min_patterns [ len ( min_pattern ) ] = min_pattern
Add a pattern to the list .
2,884
def _arcball ( xy , wh ) : x , y = xy w , h = wh r = ( w + h ) / 2. x , y = - ( 2. * x - w ) / r , ( 2. * y - h ) / r h = np . sqrt ( x * x + y * y ) return ( 0. , x / h , y / h , 0. ) if h > 1. else ( 0. , x , y , np . sqrt ( 1. - h * h ) )
Convert x y coordinates to w x y z Quaternion parameters
2,885
def arg_to_array ( func ) : def fn ( self , arg , * args , ** kwargs ) : return func ( self , np . array ( arg ) , * args , ** kwargs ) return fn
Decorator to convert argument to array .
2,886
def arg_to_vec4 ( func , self_ , arg , * args , ** kwargs ) : if isinstance ( arg , ( tuple , list , np . ndarray ) ) : arg = np . array ( arg ) flatten = arg . ndim == 1 arg = as_vec4 ( arg ) ret = func ( self_ , arg , * args , ** kwargs ) if flatten and ret is not None : return ret . flatten ( ) return ret elif hasattr ( arg , '_transform_in' ) : arr = arg . _transform_in ( ) ret = func ( self_ , arr , * args , ** kwargs ) return arg . _transform_out ( ret ) else : raise TypeError ( "Cannot convert argument to 4D vector: %s" % arg )
Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication .
2,887
def roll ( self ) : rem = [ ] for key , item in self . _cache . items ( ) : if item [ 0 ] > self . max_age : rem . append ( key ) item [ 0 ] += 1 for key in rem : logger . debug ( "TransformCache remove: %s" , key ) del self . _cache [ key ]
Increase the age of all items in the cache by 1 . Items whose age is greater than self . max_age will be removed from the cache .
2,888
def histogram ( self , data , bins = 10 , color = 'w' , orientation = 'h' ) : self . _configure_2d ( ) hist = scene . Histogram ( data , bins , color , orientation ) self . view . add ( hist ) self . view . camera . set_range ( ) return hist
Calculate and show a histogram of data
2,889
def image ( self , data , cmap = 'cubehelix' , clim = 'auto' , fg_color = None ) : self . _configure_2d ( fg_color ) image = scene . Image ( data , cmap = cmap , clim = clim ) self . view . add ( image ) self . view . camera . aspect = 1 self . view . camera . set_range ( ) return image
Show an image
2,890
def mesh ( self , vertices = None , faces = None , vertex_colors = None , face_colors = None , color = ( 0.5 , 0.5 , 1. ) , fname = None , meshdata = None ) : self . _configure_3d ( ) if fname is not None : if not all ( x is None for x in ( vertices , faces , meshdata ) ) : raise ValueError ( 'vertices, faces, and meshdata must be None ' 'if fname is not None' ) vertices , faces = read_mesh ( fname ) [ : 2 ] if meshdata is not None : if not all ( x is None for x in ( vertices , faces , fname ) ) : raise ValueError ( 'vertices, faces, and fname must be None if ' 'fname is not None' ) else : meshdata = MeshData ( vertices , faces ) mesh = scene . Mesh ( meshdata = meshdata , vertex_colors = vertex_colors , face_colors = face_colors , color = color , shading = 'smooth' ) self . view . add ( mesh ) self . view . camera . set_range ( ) return mesh
Show a 3D mesh
2,891
def plot ( self , data , color = 'k' , symbol = None , line_kind = '-' , width = 1. , marker_size = 10. , edge_color = 'k' , face_color = 'b' , edge_width = 1. , title = None , xlabel = None , ylabel = None ) : self . _configure_2d ( ) line = scene . LinePlot ( data , connect = 'strip' , color = color , symbol = symbol , line_kind = line_kind , width = width , marker_size = marker_size , edge_color = edge_color , face_color = face_color , edge_width = edge_width ) self . view . add ( line ) self . view . camera . set_range ( ) self . visuals . append ( line ) if title is not None : self . title . text = title if xlabel is not None : self . xlabel . text = xlabel if ylabel is not None : self . ylabel . text = ylabel return line
Plot a series of data using lines and markers
2,892
def spectrogram ( self , x , n_fft = 256 , step = None , fs = 1. , window = 'hann' , color_scale = 'log' , cmap = 'cubehelix' , clim = 'auto' ) : self . _configure_2d ( ) spec = scene . Spectrogram ( x , n_fft , step , fs , window , color_scale , cmap , clim ) self . view . add ( spec ) self . view . camera . set_range ( ) return spec
Calculate and show a spectrogram
2,893
def volume ( self , vol , clim = None , method = 'mip' , threshold = None , cmap = 'grays' ) : self . _configure_3d ( ) volume = scene . Volume ( vol , clim , method , threshold , cmap = cmap ) self . view . add ( volume ) self . view . camera . set_range ( ) return volume
Show a 3D volume
2,894
def surface ( self , zdata , ** kwargs ) : self . _configure_3d ( ) surf = scene . SurfacePlot ( z = zdata , ** kwargs ) self . view . add ( surf ) self . view . camera . set_range ( ) return surf
Show a 3D surface plot .
2,895
def colorbar ( self , cmap , position = "right" , label = "" , clim = ( "" , "" ) , border_width = 0.0 , border_color = "black" , ** kwargs ) : self . _configure_2d ( ) cbar = scene . ColorBarWidget ( orientation = position , label_str = label , cmap = cmap , clim = clim , border_width = border_width , border_color = border_color , ** kwargs ) CBAR_LONG_DIM = 50 if cbar . orientation == "bottom" : self . grid . remove_widget ( self . cbar_bottom ) self . cbar_bottom = self . grid . add_widget ( cbar , row = 5 , col = 4 ) self . cbar_bottom . height_max = self . cbar_bottom . height_max = CBAR_LONG_DIM elif cbar . orientation == "top" : self . grid . remove_widget ( self . cbar_top ) self . cbar_top = self . grid . add_widget ( cbar , row = 1 , col = 4 ) self . cbar_top . height_max = self . cbar_top . height_max = CBAR_LONG_DIM elif cbar . orientation == "left" : self . grid . remove_widget ( self . cbar_left ) self . cbar_left = self . grid . add_widget ( cbar , row = 2 , col = 1 ) self . cbar_left . width_max = self . cbar_left . width_min = CBAR_LONG_DIM else : self . grid . remove_widget ( self . cbar_right ) self . cbar_right = self . grid . add_widget ( cbar , row = 2 , col = 5 ) self . cbar_right . width_max = self . cbar_right . width_min = CBAR_LONG_DIM return cbar
Show a ColorBar
2,896
def redraw ( self ) : if self . _multiscat is not None : self . _multiscat . _update ( ) self . vispy_widget . canvas . update ( )
Redraw the Vispy canvas
2,897
def remove ( self ) : if self . _multiscat is None : return self . _multiscat . deallocate ( self . id ) self . _multiscat = None self . _viewer_state . remove_global_callback ( self . _update_scatter ) self . state . remove_global_callback ( self . _update_scatter )
Remove the layer artist from the visualization
2,898
def _check_valid ( key , val , valid ) : if val not in valid : raise ValueError ( '%s must be one of %s, not "%s"' % ( key , valid , val ) )
Helper to check valid options
2,899
def _to_args ( x ) : if not isinstance ( x , ( list , tuple , np . ndarray ) ) : x = [ x ] return x
Convert to args representation