idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
244,900
def attribute_circle ( self , EdgeAttribute = None , network = None , NodeAttribute = None , nodeList = None , singlePartition = None , spacing = None , verbose = False ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "EdgeAttribute" , "network" , "NodeAttribute" , "nodeList" , ...
Execute the Attribute Circle Layout on a network .
244,901
def attributes_layout ( self , EdgeAttribute = None , maxwidth = None , minrad = None , network = None , NodeAttribute = None , nodeList = None , radmult = None , spacingx = None , spacingy = None , verbose = False ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "EdgeAttribute"...
Execute the Group Attributes Layout on a network
244,902
def circular ( self , EdgeAttribute = None , leftEdge = None , network = None , NodeAttribute = None , nodeHorizontalSpacing = None , nodeList = None , nodeVerticalSpacing = None , rightMargin = None , singlePartition = None , topEdge = None , verbose = None ) : network = check_network ( self , network , verbose = verb...
Execute the Circular Layout on a network
244,903
def copycat ( self , gridUnmapped = None , selectUnmapped = None , sourceColumn = None , sourceNetwork = None , targetColumn = None , targetNetwork = None , verbose = None ) : PARAMS = set_param ( [ 'gridUnmapped' , 'selectUnmapped' , 'sourceColumn' , 'sourceNetwork' , 'targetColumn' , 'targetNetwork' ] , [ gridUnmappe...
Sets the coordinates for each node in the target network to the coordinates of a matching node in the source network . Optional parameters such as gridUnmapped and selectUnmapped determine the behavior of target network nodes that could not be matched .
244,904
def degree_circle ( self , EdgeAttribute = None , network = None , NodeAttribute = None , nodeList = None , singlePartition = None , verbose = None ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'EdgeAttribute' , 'network' , 'NodeAttribute' , 'nodeList' , 'singlePartition' ] ,...
Execute the Degree Sorted Circle Layout on a network .
244,905
def force_directed ( self , defaultEdgeWeight = None , defaultNodeMass = None , defaultSpringCoefficient = None , defaultSpringLength = None , EdgeAttribute = None , isDeterministic = None , maxWeightCutoff = None , minWeightCutoff = None , network = None , NodeAttribute = None , nodeList = None , numIterations = None ...
Execute the Prefuse Force Directed Layout on a network
244,906
def genemania_force_directed ( self , curveSteepness = None , defaultEdgeWeight = None , defaultSpringCoefficient = None , defaultSpringLength = None , EdgeAttribute = None , ignoreHiddenElements = None , isDeterministic = None , maxNodeMass = None , maxWeightCutoff = None , midpointEdges = None , minNodeMass = None , ...
Execute the GeneMANIA Force Directed Layout on a network .
244,907
def get_preferred ( self , network = None , verbose = None ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'network' ] , [ network ] ) response = api ( url = self . __url + "/get preferred" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Returns the name of the current preferred layout or empty string if not set . Default is grid .
244,908
def grid ( self , EdgeAttribute = None , network = None , NodeAttribute = None , nodeHorizontalSpacing = None , nodeList = None , nodeVerticalSpacing = None , verbose = None ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'EdgeAttribute' , 'network' , 'NodeAttribute' , 'nodeHor...
Execute the Grid Layout on a network .
244,909
def hierarchical ( self , bandGap = None , componentSpacing = None , EdgeAttribute = None , leftEdge = None , network = None , NodeAttribute = None , nodeHorizontalSpacing = None , nodeList = None , nodeVerticalSpacing = None , rightMargin = None , topEdge = None , verbose = None ) : network = check_network ( self , ne...
Execute the Hierarchical Layout on a network .
244,910
def isom ( self , coolingFactor = None , EdgeAttribute = None , initialAdaptation = None , maxEpoch = None , minAdaptation = None , minRadius = None , network = None , NodeAttribute = None , nodeList = None , radius = None , radiusConstantTime = None , singlePartition = None , sizeFactor = None , verbose = None ) : net...
Execute the Inverted Self - Organizing Map Layout on a network .
244,911
def kamada_kawai ( self , defaultEdgeWeight = None , EdgeAttribute = None , m_anticollisionSpringStrength = None , m_averageIterationsPerNode = None , m_disconnectedNodeDistanceSpringRestLength = None , m_disconnectedNodeDistanceSpringStrength = None , m_layoutPass = None , m_nodeDistanceRestLengthConstant = None , m_n...
Execute the Edge - weighted Spring Embedded Layout on a network .
244,912
def set_preferred ( self , preferredLayout = None , verbose = None ) : PARAMS = set_param ( [ 'preferredLayout' ] , [ preferredLayout ] ) response = api ( url = self . __url + "/set preferred" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Sets the preferred layout . Takes a specific name as defined in the API Default is grid .
244,913
def stacked_node_layout ( self , EdgeAttribute = None , network = None , NodeAttribute = None , nodeList = None , x_position = None , y_start_position = None , verbose = None ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'EdgeAttribute' , 'network' , 'NodeAttribute' , 'nodeLi...
Execute the Stacked Node Layout on a network .
244,914
def create_column ( self , columnName = None , listType = None , table = None , ntype = None , verbose = None ) : PARAMS = set_param ( [ 'columnName' , 'listType' , 'table' , 'type' ] , [ columnName , listType , table , ntype ] ) response = api ( url = self . __url + "/create column" , PARAMS = PARAMS , method = "POST"...
Appends an additional column of attribute values to the current table .
244,915
def create_table ( self , keyColumn = None , keyColumnType = None , title = None , verbose = None ) : PARAMS = set_param ( [ 'keyColumn' , 'keyColumnType' , 'title' ] , [ keyColumn , keyColumnType , title ] ) response = api ( url = self . __url + "/create table" , PARAMS = PARAMS , method = "POST" , verbose = verbose )...
Adds a new table to the network .
244,916
def delete_column ( self , column = None , table = None , verbose = None ) : PARAMS = set_param ( [ 'column' , 'table' ] , [ column , table ] ) response = api ( url = self . __url + "/delete column" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Remove a column from a table specified by its name . Returns the name of the column removed .
244,917
def delete_row ( self , keyValue = None , table = None , verbose = None ) : PARAMS = set_param ( [ 'keyValue' , 'table' ] , [ keyValue , table ] ) response = api ( url = self . __url + "/delete row" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Deletes a row from a table . Requires the table name or SUID and the row key .
244,918
def get_value ( self , column = None , keyValue = None , table = None , verbose = None ) : PARAMS = set_param ( [ 'column' , 'keyValue' , 'table' ] , [ column , keyValue , table ] ) response = api ( url = self . __url + "/get value" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Returns the value from a cell as specified by row and column ids .
244,919
def import_url ( self , caseSensitiveNetworkCollectionKeys = None , caseSensitiveNetworkKeys = None , dataTypeList = None , DataTypeTargetForNetworkCollection = None , DataTypeTargetForNetworkList = None , delimiters = None , delimitersForDataList = None , firstRowAsColumnNames = None , KeyColumnForMapping = None , Key...
Similar to Import Table this uses a long list of input parameters to specify the attributes of the table the mapping keys and the destination table for the input .
244,920
def list_tables ( self , includePrivate = None , namespace = None , atype = None , verbose = None ) : PARAMS = set_param ( [ 'includePrivate' , 'namespace' , 'type' ] , [ includePrivate , namespace , atype ] ) response = api ( url = self . __url + "/list" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return...
Returns a list of the table SUIDs associated with the passed network parameter .
244,921
def list_columns ( self , table = None , verbose = None ) : PARAMS = set_param ( [ 'table' ] , [ table ] ) response = api ( url = self . __url + "/list columns" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Returns the list of columns in the table .
244,922
def list_rows ( self , rowList = None , table = None , verbose = None ) : PARAMS = set_param ( [ 'rowList' , 'table' ] , [ rowList , table ] ) response = api ( url = self . __url + "/list rows" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Returns the list of primary keys for each of the rows in the specified table .
244,923
def merge ( self , DataTypeTargetForNetworkCollection = None , dataTypeTargetForNetworkList = None , mergeType = None , SourceMergeColumns = None , SourceMergeKey = None , SourceTable = None , TargetKeyNetworkCollection = None , TargetMergeKey = None , TargetNetworkCollection = None , TargetNetworkList = None , Unassig...
Merge tables together joining around a designated key column . Depending on the arguments might merge into multiple local tables .
244,924
def rename_column ( self , columnName = None , newColumnName = None , table = None , verbose = None ) : PARAMS = set_param ( [ 'columnName' , 'newColumnName' , 'table' ] , [ columnName , newColumnName , table ] ) response = api ( url = self . __url + "/rename column" , PARAMS = PARAMS , method = "POST" , verbose = verb...
Changes the name of a specified column in the table .
244,925
def set_title ( self , table = None , title = None , verbose = None ) : PARAMS = set_param ( [ 'table' , 'title' ] , [ table , title ] ) response = api ( url = self . __url + "/set title" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Changes the visible identifier of a single table .
244,926
def set_values ( self , columnName = None , rowList = None , table = None , value = None , verbose = None ) : PARAMS = set_param ( [ 'columnName' , 'rowList' , 'table' , 'value' ] , [ columnName , rowList , table , value ] ) response = api ( url = self . __url + "/set values" , PARAMS = PARAMS , method = "POST" , verbo...
Set all the values in the specified list of rows with a single value .
244,927
def getTable ( self , columns = None , table = None , network = "current" , namespace = 'default' , verbose = VERBOSE ) : u = self . __url host = u . split ( "//" ) [ 1 ] . split ( ":" ) [ 0 ] port = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 0 ] version = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 1 ] if type ( network ...
Gets tables from cytoscape .
244,928
def loadTableData ( self , df , df_key = 'index' , table = "node" , table_key_column = "name" , network = "current" , namespace = "default" , verbose = False ) : u = self . __url host = u . split ( "//" ) [ 1 ] . split ( ":" ) [ 0 ] port = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 0 ] version = u . split ( ":" ) [ 2 ] ...
Loads tables into cytoscape .
244,929
def getTableCount ( verbose = None ) : response = api ( url = self . url + 'tables/count' , method = "GET" , verbose = verbose , parse_params = False ) return response
Returns the number of global tables .
244,930
def set_value ( self , visual_property , value ) : if visual_property is None or value is None : raise ValueError ( 'Both VP and value are required.' ) new_value = [ { 'visualProperty' : visual_property , "value" : value } ] requests . put ( self . url , data = json . dumps ( new_value ) , headers = HEADERS )
Set a single Visual Property Value
244,931
def set_values ( self , values ) : if values is None : raise ValueError ( 'Values are required.' ) new_values = [ ] for vp in values . keys ( ) : new_val = { 'visualProperty' : vp , 'value' : values [ vp ] } new_values . append ( new_val ) requests . put ( self . url , data = json . dumps ( new_values ) , headers = HEA...
Set multiple Visual properties at once .
244,932
def get_value ( self , visual_property ) : res = requests . get ( self . url + '/' + visual_property ) return res . json ( ) [ 'value' ]
Get a value for the Visual Property
244,933
def get_values ( self ) : results = requests . get ( self . url ) . json ( ) values = { } for entry in results : values [ entry [ 'visualProperty' ] ] = entry [ 'value' ] return values
Get all visual property values for the object
244,934
def update_network_view ( self , visual_property = None , value = None ) : new_value = [ { "visualProperty" : visual_property , "value" : value } ] res = requests . put ( self . __url + '/network' , data = json . dumps ( new_value ) , headers = HEADERS ) check_response ( res )
Updates single value for Network - related VP .
244,935
def export ( self , Height = None , options = None , outputFile = None , Resolution = None , Units = None , Width = None , Zoom = None , view = "current" , verbose = False ) : PARAMS = set_param ( [ "Height" , "options" , "outputFile" , "Resolution" , "Units" , "Width" , "Zoom" , "view" ] , [ Height , options , outputF...
Exports the current view to a graphics file and returns the path to the saved file . PNG and JPEG formats have options for scaling while other formats only have the option exportTextAsFont . For the PDF format exporting text as font does not work for two - byte characters such as Chinese or Japanese . To avoid corrupte...
244,936
def fit_content ( self , verbose = False ) : PARAMS = { } response = api ( url = self . __url + "/fit content" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Zooms out the current view in order to display all of its elements .
244,937
def get_current ( self , layout = None , network = None , verbose = False ) : PARAMS = { } response = api ( url = self . __url + "/get_current" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Returns the current view or null if there is none .
244,938
def update_defaults ( self , prop_value_dict ) : body = [ ] for key in prop_value_dict : entry = { 'visualProperty' : key , 'value' : prop_value_dict [ key ] } body . append ( entry ) url = self . __url + 'defaults' requests . put ( url , data = json . dumps ( body ) , headers = HEADERS )
Updates the value of one or more visual properties .
244,939
def status ( self , verbose = False ) : try : response = api ( url = self . __url , method = "GET" , verbose = verbose ) except Exception as e : print ( 'Could not get status from CyREST:\n\n' + str ( e ) ) else : print ( 'CyREST online!' )
Checks the status of your CyREST server .
244,940
def version ( self , verbose = False ) : response = api ( url = self . __url + "version" , method = "H" , verbose = verbose ) response = json . loads ( response ) for k in response . keys ( ) : print ( k , response [ k ] )
Checks Cytoscape version
244,941
def map_column ( self , only_use_one = None , source_column = None , species = None , target_selection = None , verbose = False ) : PARAMS = set_param ( [ "only_use_one" , "source_column" , "species" , "target_selection" ] , [ only_use_one , source_column , species , target_selection ] ) response = api ( url = self . _...
Uses the BridgeDB service to look up analogous identifiers from a wide selection of other databases
244,942
def echo ( self , variableName , verbose = False ) : PARAMS = { "variableName" : variableName } response = api ( url = self . __url + "/echo" , PARAMS = PARAMS , verbose = verbose ) return response
The echo command will display the value of the variable specified by the variableName argument or all variables if variableName is not provided .
244,943
def open_dialog ( self , verbose = False ) : response = api ( url = self . __url + "/open dialog" , verbose = verbose ) return response
The command line dialog provides a field to enter commands and view results . It also provides the help command to display namespaces commands and arguments .
244,944
def pause ( self , message = None , verbose = False ) : PARAMS = set_param ( [ "message" ] , [ message ] ) response = api ( url = self . __url + "/pause" , PARAMS = PARAMS , verbose = verbose ) return response
The pause command displays a dialog with the text provided in the message argument and waits for the user to click OK
244,945
def quit ( self , verbose = False ) : response = api ( url = self . __url + "/quit" , verbose = verbose ) return response
This command causes Cytoscape to exit . It is typically used at the end of a script file .
244,946
def run ( self , script_file , args = None , verbose = False ) : PARAMS = set_param ( [ "file" , "args" ] , [ script_file , args ] ) response = api ( url = self . __url + "/run" , PARAMS = PARAMS , verbose = verbose ) return response
The run command will execute a command script from the file pointed to by the file argument which should contain Cytoscape commands one per line . Arguments to the script are provided by the args argument .
244,947
def sleep ( self , duration , verbose = False ) : PARAMS = { "duration" : str ( duration ) } response = api ( url = self . __url + "/sleep" , PARAMS = PARAMS , verbose = verbose ) return response
The sleep command will pause processing for a period of time as specified by duration seconds . It is typically used as part of a command script .
244,948
def to_curl ( request , compressed = False , verify = True ) : parts = [ ( 'curl' , None ) , ( '-X' , request . method ) , ] for k , v in sorted ( request . headers . items ( ) ) : parts += [ ( '-H' , '{0}: {1}' . format ( k , v ) ) ] if request . body : body = request . body if isinstance ( body , bytes ) : body = bod...
Returns string with curl command by provided request object
244,949
def shared_options ( rq ) : "Default class options to pass to the CLI commands." return { 'url' : rq . redis_url , 'config' : None , 'worker_class' : rq . worker_class , 'job_class' : rq . job_class , 'queue_class' : rq . queue_class , 'connection_class' : rq . connection_class , }
Default class options to pass to the CLI commands .
244,950
def empty ( rq , ctx , all , queues ) : "Empty given queues." return ctx . invoke ( rq_cli . empty , all = all , queues = queues or rq . queues , ** shared_options ( rq ) )
Empty given queues .
244,951
def requeue ( rq , ctx , all , job_ids ) : "Requeue failed jobs." return ctx . invoke ( rq_cli . requeue , all = all , job_ids = job_ids , ** shared_options ( rq ) )
Requeue failed jobs .
244,952
def info ( rq , ctx , path , interval , raw , only_queues , only_workers , by_queue , queues ) : "RQ command-line monitor." return ctx . invoke ( rq_cli . info , path = path , interval = interval , raw = raw , only_queues = only_queues , only_workers = only_workers , by_queue = by_queue , queues = queues or rq . queues...
RQ command - line monitor .
244,953
def worker ( rq , ctx , burst , logging_level , name , path , results_ttl , worker_ttl , verbose , quiet , sentry_dsn , exception_handler , pid , queues ) : "Starts an RQ worker." ctx . invoke ( rq_cli . worker , burst = burst , logging_level = logging_level , name = name , path = path , results_ttl = results_ttl , wor...
Starts an RQ worker .
244,954
def suspend ( rq , ctx , duration ) : "Suspends all workers." ctx . invoke ( rq_cli . suspend , duration = duration , ** shared_options ( rq ) )
Suspends all workers .
244,955
def scheduler ( rq , ctx , verbose , burst , queue , interval , pid ) : "Periodically checks for scheduled jobs." scheduler = rq . get_scheduler ( interval = interval , queue = queue ) if pid : with open ( os . path . expanduser ( pid ) , 'w' ) as fp : fp . write ( str ( os . getpid ( ) ) ) if verbose : level = 'DEBUG'...
Periodically checks for scheduled jobs .
244,956
def init_cli ( self , app ) : if click is None : raise RuntimeError ( 'Cannot import click. Is it installed?' ) from . cli import add_commands add_commands ( app . cli , self )
Initialize the Flask CLI support in case it was enabled for the app .
244,957
def set_trace ( host = None , port = None , patch_stdstreams = False ) : if host is None : host = os . environ . get ( 'REMOTE_PDB_HOST' , '127.0.0.1' ) if port is None : port = int ( os . environ . get ( 'REMOTE_PDB_PORT' , '0' ) ) rdb = RemotePdb ( host = host , port = port , patch_stdstreams = patch_stdstreams ) rdb...
Opens a remote PDB on first available port .
244,958
def quasi_newton_uniform_lloyd ( points , cells , * args , omega = 1.0 , ** kwargs ) : def get_new_points ( mesh ) : x = ( mesh . node_coords - omega / 2 * jac_uniform ( mesh ) / mesh . control_volumes [ : , None ] ) idx = mesh . is_boundary_node & ~ ghosted_mesh . is_ghost_point x [ idx ] = mesh . node_coords [ idx ] ...
Relaxed Lloyd s algorithm . omega = 1 leads to Lloyd s algorithm overrelaxation omega = 2 gives good results . Check out
244,959
def _energy_uniform_per_node ( X , cells ) : dim = 2 mesh = MeshTri ( X , cells ) star_integrals = numpy . zeros ( mesh . node_coords . shape [ 0 ] ) for cell , cell_volume in zip ( mesh . cells [ "nodes" ] , mesh . cell_volumes ) : for idx in cell : xi = mesh . node_coords [ idx ] tri = mesh . node_coords [ cell ] val...
The CPT mesh energy is defined as
244,960
def jac_uniform ( X , cells ) : dim = 2 mesh = MeshTri ( X , cells ) jac = numpy . zeros ( X . shape ) for k in range ( mesh . cells [ "nodes" ] . shape [ 1 ] ) : i = mesh . cells [ "nodes" ] [ : , k ] fastfunc . add . at ( jac , i , ( ( mesh . node_coords [ i ] - mesh . cell_barycenters ) . T * mesh . cell_volumes ) ....
The approximated Jacobian is
244,961
def solve_hessian_approx_uniform ( X , cells , rhs ) : dim = 2 mesh = MeshTri ( X , cells ) row_idx = [ ] col_idx = [ ] val = [ ] cells = mesh . cells [ "nodes" ] . T n = X . shape [ 0 ] a = mesh . cell_volumes * ( 2 / ( dim + 1 ) ) for i in [ 0 , 1 , 2 ] : row_idx += [ cells [ i ] ] col_idx += [ cells [ i ] ] val += [...
As discussed above the approximated Jacobian is
244,962
def quasi_newton_uniform ( points , cells , * args , ** kwargs ) : def get_new_points ( mesh ) : x = mesh . node_coords . copy ( ) cells = mesh . cells [ "nodes" ] jac_x = jac_uniform ( x , cells ) x -= solve_hessian_approx_uniform ( x , cells , jac_x ) return x mesh = MeshTri ( points , cells ) runner ( get_new_points...
Like linear_solve above but assuming rho == 1 . Note that the energy gradient
244,963
def fixed_point ( points , cells , * args , ** kwargs ) : def get_new_points ( mesh ) : num_neighbors = numpy . zeros ( len ( mesh . node_coords ) , dtype = int ) idx = mesh . edges [ "nodes" ] fastfunc . add . at ( num_neighbors , idx , numpy . ones ( idx . shape , dtype = int ) ) new_points = numpy . zeros ( mesh . n...
Perform k steps of Laplacian smoothing to the mesh i . e . moving each interior vertex to the arithmetic average of its neighboring points .
244,964
def energy ( mesh , uniform_density = False ) : dim = mesh . cells [ "nodes" ] . shape [ 1 ] - 1 star_volume = numpy . zeros ( mesh . node_coords . shape [ 0 ] ) for i in range ( 3 ) : idx = mesh . cells [ "nodes" ] [ : , i ] if uniform_density : fastfunc . add . at ( star_volume , idx , mesh . cell_volumes ) else : fa...
The mesh energy is defined as
244,965
def quasi_newton_uniform_blocks ( points , cells , * args , ** kwargs ) : def get_new_points ( mesh ) : x = mesh . node_coords . copy ( ) x += update ( mesh ) x [ ghosted_mesh . is_ghost_point ] = ghosted_mesh . reflect_ghost ( x [ ghosted_mesh . mirrors ] ) return x ghosted_mesh = GhostedMesh ( points , cells ) runner...
Lloyd s algorithm can be though of a diagonal - only Hessian ; this method incorporates the diagonal blocks too .
244,966
def new ( filename : str , * , file_attrs : Optional [ Dict [ str , str ] ] = None ) -> LoomConnection : if filename . startswith ( "~/" ) : filename = os . path . expanduser ( filename ) if file_attrs is None : file_attrs = { } f = h5py . File ( name = filename , mode = 'w' ) f . create_group ( '/layers' ) f . create_...
Create an empty Loom file and return it as a context manager .
244,967
def create ( filename : str , layers : Union [ np . ndarray , Dict [ str , np . ndarray ] , loompy . LayerManager ] , row_attrs : Union [ loompy . AttributeManager , Dict [ str , np . ndarray ] ] , col_attrs : Union [ loompy . AttributeManager , Dict [ str , np . ndarray ] ] , * , file_attrs : Dict [ str , str ] = None...
Create a new Loom file from the given data .
244,968
def connect ( filename : str , mode : str = 'r+' , * , validate : bool = True , spec_version : str = "2.0.1" ) -> LoomConnection : return LoomConnection ( filename , mode , validate = validate , spec_version = spec_version )
Establish a connection to a . loom file .
244,969
def last_modified ( self ) -> str : if "last_modified" in self . attrs : return self . attrs [ "last_modified" ] elif self . mode == "r+" : self . attrs [ "last_modified" ] = timestamp ( ) return self . attrs [ "last_modified" ] return timestamp ( )
Return an ISO8601 timestamp indicating when the file was last modified
244,970
def get_changes_since ( self , timestamp : str ) -> Dict [ str , List ] : rg = [ ] cg = [ ] ra = [ ] ca = [ ] layers = [ ] if self . last_modified ( ) > timestamp : if self . row_graphs . last_modified ( ) > timestamp : for name in self . row_graphs . keys ( ) : if self . row_graphs . last_modified ( name ) > timestamp...
Get a summary of the parts of the file that changed since the given time
244,971
def sparse ( self , rows : np . ndarray = None , cols : np . ndarray = None , layer : str = None ) -> scipy . sparse . coo_matrix : if layer is None : return self . layers [ "" ] . sparse ( rows = rows , cols = cols ) else : return self . layers [ layer ] . sparse ( rows = rows , cols = cols )
Return the main matrix or specified layer as a scipy . sparse . coo_matrix without loading dense matrix in RAM
244,972
def close ( self , suppress_warning : bool = False ) -> None : if self . _file is None : if not suppress_warning : logging . warn ( "Connection to %s is already closed" , self . filename ) else : self . _file . close ( ) self . _file = None self . layers = None self . ra = None self . row_attrs = None self . ca = None ...
Close the connection . After this the connection object becomes invalid . Warns user if called after closing .
244,973
def permute ( self , ordering : np . ndarray , axis : int ) -> None : if self . _file . __contains__ ( "tiles" ) : del self . _file [ 'tiles' ] ordering = list ( np . array ( ordering ) . flatten ( ) ) self . layers . _permute ( ordering , axis = axis ) if axis == 0 : self . row_attrs . _permute ( ordering ) self . row...
Permute the dataset along the indicated axis .
244,974
def aggregate ( self , out_file : str = None , select : np . ndarray = None , group_by : Union [ str , np . ndarray ] = "Clusters" , aggr_by : str = "mean" , aggr_ca_by : Dict [ str , str ] = None ) -> np . ndarray : ca = { } if select is not None : raise ValueError ( "The 'select' argument is deprecated" ) if isinstan...
Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
244,975
def get ( self , name : str , default : Any = None ) -> np . ndarray : if name in self : return self [ name ] else : return default
Return the value for a named attribute if it exists else default . If default is not given it defaults to None so that this method never raises a KeyError .
244,976
def cat_colors ( N : int = 1 , * , hue : str = None , luminosity : str = None , bgvalue : int = None , loop : bool = False , seed : str = "cat" ) -> Union [ List [ Any ] , colors . LinearSegmentedColormap ] : c : List [ str ] = [ ] if N <= 25 and hue is None and luminosity is None : c = _color_alphabet [ : N ] elif not...
Return a colormap suitable for N categorical values optimized to be both aesthetically pleasing and perceptually distinct .
244,977
def _renumber ( a : np . ndarray , keys : np . ndarray , values : np . ndarray ) -> np . ndarray : ordering = np . argsort ( keys ) keys = keys [ ordering ] values = keys [ ordering ] index = np . digitize ( a . ravel ( ) , keys , right = True ) return ( values [ index ] . reshape ( a . shape ) )
Renumber a by replacing any occurrence of keys by the corresponding values
244,978
def validate ( self , path : str , strictness : str = "speconly" ) -> bool : valid1 = True with h5py . File ( path , mode = "r" ) as f : valid1 = self . validate_spec ( f ) if not valid1 : self . errors . append ( "For help, see http://linnarssonlab.org/loompy/format/" ) valid2 = True if strictness == "conventions" : w...
Validate a file for conformance to the Loom specification
244,979
def _permute ( self , ordering : np . ndarray ) -> None : for key in self . keys ( ) : self [ key ] = self [ key ] [ ordering ]
Permute all the attributes in the collection
244,980
def get ( self , name : str , default : np . ndarray ) -> np . ndarray : if name in self : return self [ name ] else : if not isinstance ( default , np . ndarray ) : raise ValueError ( f"Default must be an np.ndarray with exactly {self.ds.shape[self.axis]} values" ) if default . shape [ 0 ] != self . ds . shape [ self ...
Return the value for a named attribute if it exists else default . Default has to be a numpy array of correct size .
244,981
def normalize_attr_array ( a : Any ) -> np . ndarray : if type ( a ) is np . ndarray : return a elif type ( a ) is np . matrix : if a . shape [ 0 ] == 1 : return np . array ( a ) [ 0 , : ] elif a . shape [ 1 ] == 1 : return np . array ( a ) [ : , 0 ] else : raise ValueError ( "Attribute values must be 1-dimensional." )...
Take all kinds of array - like inputs and normalize to a one - dimensional np . ndarray
244,982
def to_html ( ds : Any ) -> str : rm = min ( 10 , ds . shape [ 0 ] ) cm = min ( 10 , ds . shape [ 1 ] ) html = "<p>" if ds . attrs . __contains__ ( "title" ) : html += "<strong>" + ds . attrs [ "title" ] + "</strong> " html += f"{ds.shape[0]} rows, {ds.shape[1]} columns, {len(ds.layers)} layer{'s' if len(ds.layers) > 1...
Return an HTML representation of the loom file or view showing the upper - left 10x10 corner .
244,983
def permute ( self , ordering : np . ndarray , * , axis : int ) -> None : if axis not in ( 0 , 1 ) : raise ValueError ( "Axis must be 0 (rows) or 1 (columns)" ) for layer in self . layers . values ( ) : layer . _permute ( ordering , axis = axis ) if axis == 0 : if self . row_graphs is not None : for g in self . row_gra...
Permute the view by permuting its layers attributes and graphs
244,984
def permute ( self , ordering : np . ndarray , * , axis : int ) -> None : if axis == 0 : self . values = self . values [ ordering , : ] elif axis == 1 : self . values = self . values [ : , ordering ] else : raise ValueError ( "axis must be 0 or 1" )
Permute the layer along an axis
244,985
def _resize ( self , size : Tuple [ int , int ] , axis : int = None ) -> None : if self . name == "" : self . ds . _file [ '/matrix' ] . resize ( size , axis ) else : self . ds . _file [ '/layers/' + self . name ] . resize ( size , axis )
Resize the dataset or the specified axis .
244,986
def is_datafile_valid ( datafile ) : try : datafile_json = json . loads ( datafile ) except : return False try : jsonschema . Draft4Validator ( constants . JSON_SCHEMA ) . validate ( datafile_json ) except : return False return True
Given a datafile determine if it is valid or not .
244,987
def is_user_profile_valid ( user_profile ) : if not user_profile : return False if not type ( user_profile ) is dict : return False if UserProfile . USER_ID_KEY not in user_profile : return False if UserProfile . EXPERIMENT_BUCKET_MAP_KEY not in user_profile : return False experiment_bucket_map = user_profile . get ( U...
Determine if provided user profile is valid or not .
244,988
def is_attribute_valid ( attribute_key , attribute_value ) : if not isinstance ( attribute_key , string_types ) : return False if isinstance ( attribute_value , ( string_types , bool ) ) : return True if isinstance ( attribute_value , ( numbers . Integral , float ) ) : return is_finite_number ( attribute_value ) return...
Determine if given attribute is valid .
244,989
def is_finite_number ( value ) : if not isinstance ( value , ( numbers . Integral , float ) ) : return False if isinstance ( value , bool ) : return False if isinstance ( value , float ) : if math . isnan ( value ) or math . isinf ( value ) : return False if abs ( value ) > ( 2 ** 53 ) : return False return True
Validates if the given value is a number enforces absolute limit of 2^53 and restricts NAN INF - INF .
244,990
def are_values_same_type ( first_val , second_val ) : first_val_type = type ( first_val ) second_val_type = type ( second_val ) if isinstance ( first_val , string_types ) and isinstance ( second_val , string_types ) : return True if isinstance ( first_val , bool ) or isinstance ( second_val , bool ) : return first_val_...
Method to verify that both values belong to same type . Float and integer are considered as same type .
244,991
def reset_logger ( name , level = None , handler = None ) : if level is None : level = logging . INFO logger = logging . getLogger ( name ) logger . setLevel ( level ) handler = handler or logging . StreamHandler ( ) handler . setFormatter ( logging . Formatter ( _DEFAULT_LOG_FORMAT ) ) logger . handlers = [ handler ] ...
Make a standard python logger object with default formatter handler etc .
244,992
def adapt_logger ( logger ) : if isinstance ( logger , logging . Logger ) : return logger if isinstance ( logger , ( SimpleLogger , NoOpLogger ) ) : return logger . logger return logger
Adapt our custom logger . BaseLogger object into a standard logging . Logger object .
244,993
def get_variation_for_experiment ( self , experiment_id ) : return self . experiment_bucket_map . get ( experiment_id , { self . VARIATION_ID_KEY : None } ) . get ( self . VARIATION_ID_KEY )
Helper method to retrieve variation ID for given experiment .
244,994
def get_numeric_value ( event_tags , logger = None ) : logger_message_debug = None numeric_metric_value = None if event_tags is None : logger_message_debug = 'Event tags is undefined.' elif not isinstance ( event_tags , dict ) : logger_message_debug = 'Event tags is not a dictionary.' elif NUMERIC_METRIC_TYPE not in ev...
A smart getter of the numeric value from the event tags .
244,995
def hash ( key , seed = 0x0 ) : key = bytearray ( xencode ( key ) ) def fmix ( h ) : h ^= h >> 16 h = ( h * 0x85ebca6b ) & 0xFFFFFFFF h ^= h >> 13 h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF h ^= h >> 16 return h length = len ( key ) nblocks = int ( length / 4 ) h1 = seed c1 = 0xcc9e2d51 c2 = 0x1b873593 for block_start in xran...
Implements 32bit murmur3 hash .
244,996
def hash64 ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF if unsigned_val1 & 0x8000000000000000 == 0 : signed_val1 = unsigned_val1 else : signed_val1 = - ( ( unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF ) + 1 ) unsigned_val2 = ( hash_128 >> 64 ) &...
Implements 64bit murmur3 hash . Returns a tuple .
244,997
def hash_bytes ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) bytestring = '' for i in xrange ( 0 , 16 , 1 ) : lsbyte = hash_128 & 0xFF bytestring = bytestring + str ( chr ( lsbyte ) ) hash_128 = hash_128 >> 8 return bytestring
Implements 128bit murmur3 hash . Returns a byte string .
244,998
def _generate_bucket_value ( self , bucketing_id ) : ratio = float ( self . _generate_unsigned_hash_code_32_bit ( bucketing_id ) ) / MAX_HASH_VALUE return math . floor ( ratio * MAX_TRAFFIC_VALUE )
Helper function to generate bucket value in half - closed interval [ 0 MAX_TRAFFIC_VALUE ) .
244,999
def find_bucket ( self , bucketing_id , parent_id , traffic_allocations ) : bucketing_key = BUCKETING_ID_TEMPLATE . format ( bucketing_id = bucketing_id , parent_id = parent_id ) bucketing_number = self . _generate_bucket_value ( bucketing_key ) self . config . logger . debug ( 'Assigned bucket %s to user with bucketin...
Determine entity based on bucket value and traffic allocations .