idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
243,900 | def list_attributes ( self , namespace = None , network = None , verbose = False ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "namespace" , "network" ] , [ namespace , network ] ) response = api ( url = self . __url + "/list attributes" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Returns a list of column names assocated with a network . | 98 | 12 |
243,901 | def rename ( self , name = None , sourceNetwork = None , verbose = False ) : sourceNetwork = check_network ( self , sourceNetwork , verbose = verbose ) PARAMS = set_param ( [ "name" , "sourceNetwork" ] , [ name , sourceNetwork ] ) response = api ( url = self . __url + "/rename" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Rename an existing network . The SUID of the network is returned | 99 | 14 |
243,902 | def new ( self , verbose = False ) : response = api ( url = self . __url + "/new" , verbose = verbose ) return response | Destroys the current session and creates a new empty one . | 34 | 13 |
243,903 | def open ( self , session_file = None , session_url = None , verbose = False ) : PARAMS = set_param ( [ "file" , "url" ] , [ session_file , session_url ] ) response = api ( url = self . __url + "/open" , PARAMS = PARAMS , verbose = verbose ) return response | Opens a session from a local file or URL . | 79 | 11 |
243,904 | def save ( self , session_file , verbose = False ) : PARAMS = { "file" : session_file } response = api ( url = self . __url + "/save" , PARAMS = PARAMS , verbose = verbose ) return response | Saves the current session to an existing file which will be replaced . If this is a new session that has not been saved yet use save as instead . | 56 | 31 |
243,905 | def apply ( self , styles = None , verbose = False ) : PARAMS = set_param ( [ "styles" ] , [ styles ] ) response = api ( url = self . __url + "/apply" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Applies the specified style to the selected views and returns the SUIDs of the affected views . | 67 | 19 |
243,906 | def create_style ( self , title = None , defaults = None , mappings = None , verbose = VERBOSE ) : u = self . __url host = u . split ( "//" ) [ 1 ] . split ( ":" ) [ 0 ] port = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 0 ] version = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 1 ] if defaults : defaults_ = [ ] for d in defaults : if d : defaults_ . append ( d ) defaults = defaults_ if mappings : mappings_ = [ ] for m in mappings : if m : mappings_ . append ( m ) mappings = mappings_ try : update_style ( title = title , defaults = defaults , mappings = mappings , host = host , port = port ) print ( "Existing style was updated." ) sys . stdout . flush ( ) except : print ( "Creating new style." ) sys . stdout . flush ( ) URL = "http://" + str ( host ) + ":" + str ( port ) + "/v1/styles" PARAMS = { "title" : title , "defaults" : defaults , "mappings" : mappings } r = requests . post ( url = URL , json = PARAMS ) checkresponse ( r ) | Creates a new visual style | 293 | 6 |
243,907 | def update_style ( self , title = None , defaults = None , mappings = None , verbose = False ) : u = self . __url host = u . split ( "//" ) [ 1 ] . split ( ":" ) [ 0 ] port = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 0 ] version = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 1 ] if defaults : defaults_ = [ ] for d in defaults : if d : defaults_ . append ( d ) defaults = defaults_ if mappings : mappings_ = [ ] for m in mappings : if m : mappings_ . append ( m ) mappings = mappings_ URL = "http://" + str ( host ) + ":" + str ( port ) + "/v1/styles/" + str ( title ) if verbose : print ( URL ) sys . stdout . flush ( ) response = requests . get ( URL ) . json ( ) olddefaults = response [ "defaults" ] oldmappings = response [ "mappings" ] if mappings : mappings_visual_properties = [ m [ "visualProperty" ] for m in mappings ] newmappings = [ m for m in oldmappings if m [ "visualProperty" ] not in mappings_visual_properties ] for m in mappings : newmappings . append ( m ) else : newmappings = oldmappings if defaults : defaults_visual_properties = [ m [ "visualProperty" ] for m in defaults ] newdefaults = [ m for m in olddefaults if m [ "visualProperty" ] not in defaults_visual_properties ] for m in defaults : newdefaults . append ( m ) else : newdefaults = olddefaults r = requests . delete ( URL ) checkresponse ( r ) URL = "http://" + str ( host ) + ":" + str ( port ) + "/v1/styles" PARAMS = { "title" : title , "defaults" : newdefaults , "mappings" : newmappings } r = requests . post ( url = URL , json = PARAMS ) checkresponse ( r ) | Updates a visual style | 473 | 5 |
243,908 | def simple_defaults ( self , defaults_dic ) : defaults = [ ] for d in defaults_dic . keys ( ) : dic = { } dic [ "visualProperty" ] = d dic [ "value" ] = defaults_dic [ d ] defaults . append ( dic ) return defaults | Simplifies defaults . | 69 | 5 |
243,909 | 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" , "singlePartition" , "spacing" ] , [ EdgeAttribute , network , NodeAttribute , nodeList , singlePartition , spacing ] ) response = api ( url = self . __url + "/attribute-circle" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Attribute Circle Layout on a network . | 153 | 11 |
243,910 | 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" , "network" , "NodeAttribute" , "nodeList" , "singlePartition" , "spacing" ] , [ EdgeAttribute , maxwidth , minrad , network , NodeAttribute , nodeList , radmult , spacingx , spacingy ] ) response = api ( url = self . __url + "/attributes-layout" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Group Attributes Layout on a network | 178 | 9 |
243,911 | 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 = verbose ) PARAMS = set_param ( [ 'EdgeAttribute' , 'leftEdge' , 'network' , 'NodeAttribute' , 'nodeHorizontalSpacing' , 'nodeList' , 'nodeVerticalSpacing' , 'rightMargin' , 'singlePartition' , 'topEdge' ] , [ EdgeAttribute , leftEdge , network , NodeAttribute , nodeHorizontalSpacing , nodeList , nodeVerticalSpacing , rightMargin , singlePartition , topEdge ] ) response = api ( url = self . __url + "/circular" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Circular Layout on a network | 225 | 9 |
243,912 | 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' ] , [ gridUnmapped , selectUnmapped , sourceColumn , sourceNetwork , targetColumn , targetNetwork ] ) response = api ( url = self . __url + "/copycat" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | 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 . | 149 | 49 |
243,913 | 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' ] , [ EdgeAttribute , network , NodeAttribute , nodeList , singlePartition ] ) response = api ( url = self . __url + "/degree-circle" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Degree Sorted Circle Layout on a network . | 142 | 12 |
243,914 | 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 , singlePartition = None , Type = None , verbose = None ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'defaultEdgeWeight' , 'defaultNodeMass' , 'defaultSpringCoefficient' , 'defaultSpringLength' , 'EdgeAttribute' , 'isDeterministic' , 'maxWeightCutoff' , 'minWeightCutoff' , 'network' , 'NodeAttribute' , 'nodeList' , 'numIterations' , 'singlePartition' , 'Type' ] , [ defaultEdgeWeight , defaultNodeMass , defaultSpringCoefficient , defaultSpringLength , EdgeAttribute , isDeterministic , maxWeightCutoff , minWeightCutoff , network , NodeAttribute , nodeList , numIterations , singlePartition , Type ] ) response = api ( url = self . __url + "/force-directed" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Prefuse Force Directed Layout on a network | 295 | 12 |
243,915 | 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 , minWeightCutoff = None , network = None , NodeAttribute = None , nodeList = None , numIterations = None , singlePartition = None , Type = None , verbose = None ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'curveSteepness' , 'defaultEdgeWeight' , 'defaultSpringCoefficient' , 'defaultSpringLength' , 'EdgeAttribute' , 'ignoreHiddenElements' , 'isDeterministic' , 'maxNodeMass' , 'maxWeightCutoff' , 'midpointEdges' , 'minNodeMass' , 'minWeightCutoff' , 'network' , 'NodeAttribute' , 'nodeList' , 'numIterations' , 'singlePartition' , 'Type' ] , [ curveSteepness , defaultEdgeWeight , defaultSpringCoefficient , defaultSpringLength , EdgeAttribute , ignoreHiddenElements , isDeterministic , maxNodeMass , maxWeightCutoff , midpointEdges , minNodeMass , minWeightCutoff , network , NodeAttribute , nodeList , numIterations , singlePartition , Type ] ) response = api ( url = self . __url + "/genemania-force-directed" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the GeneMANIA Force Directed Layout on a network . | 377 | 14 |
243,916 | 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 . | 87 | 19 |
243,917 | 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' , 'nodeHorizontalSpacing' , 'nodeList' , 'nodeVerticalSpacing' ] , [ EdgeAttribute , network , NodeAttribute , nodeHorizontalSpacing , nodeList , nodeVerticalSpacing ] ) response = api ( url = self . __url + "/grid" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Grid Layout on a network . | 166 | 9 |
243,918 | 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 , network , verbose = verbose ) PARAMS = set_param ( [ 'bandGap' , 'componentSpacing' , 'EdgeAttribute' , 'leftEdge' , 'network' , 'NodeAttribute' , 'nodeHorizontalSpacing' , 'nodeList' , 'nodeVerticalSpacing' , 'rightMargin' , 'topEdge' ] , [ bandGap , componentSpacing , EdgeAttribute , leftEdge , network , NodeAttribute , nodeHorizontalSpacing , nodeList , nodeVerticalSpacing , rightMargin , topEdge ] ) response = api ( url = self . __url + "/hierarchical" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Hierarchical Layout on a network . | 243 | 11 |
243,919 | 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 ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'coolingFactor' , 'EdgeAttribute' , 'initialAdaptation' , 'maxEpoch' , 'minAdaptation' , 'minRadius' , 'network' , 'NodeAttribute' , 'nodeList' , 'radius' , 'radiusConstantTime' , 'singlePartition' , 'sizeFactor' ] , [ coolingFactor , EdgeAttribute , initialAdaptation , maxEpoch , minAdaptation , minRadius , network , NodeAttribute , nodeList , radius , radiusConstantTime , singlePartition , sizeFactor ] ) response = api ( url = self . __url + "/isom" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Inverted Self - Organizing Map Layout on a network . | 260 | 15 |
243,920 | 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_nodeDistanceStrengthConstant = None , maxWeightCutoff = None , minWeightCutoff = None , network = None , NodeAttribute = None , nodeList = None , randomize = None , singlePartition = None , Type = None , unweighted = None , verbose = None ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'defaultEdgeWeight' , 'EdgeAttribute' , 'm_anticollisionSpringStrength' , 'm_averageIterationsPerNode' , 'm_disconnectedNodeDistanceSpringRestLength' , 'm_disconnectedNodeDistanceSpringStrength' , 'm_layoutPass' , 'm_nodeDistanceRestLengthConstant' , 'm_nodeDistanceStrengthConstant' , 'maxWeightCutoff' , 'minWeightCutoff' , 'network' , 'NodeAttribute' , 'nodeList' , 'randomize' , 'singlePartition' , 'Type' , 'unweighted' ] , [ defaultEdgeWeight , EdgeAttribute , m_anticollisionSpringStrength , m_averageIterationsPerNode , m_disconnectedNodeDistanceSpringRestLength , m_disconnectedNodeDistanceSpringStrength , m_layoutPass , m_nodeDistanceRestLengthConstant , m_nodeDistanceStrengthConstant , maxWeightCutoff , minWeightCutoff , network , NodeAttribute , nodeList , randomize , singlePartition , Type , unweighted ] ) response = api ( url = self . __url + "/kamada-kawai" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Edge - weighted Spring Embedded Layout on a network . | 442 | 14 |
243,921 | 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 . | 75 | 19 |
243,922 | 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' , 'nodeList' , 'x_position' , 'y_start_position' ] , [ EdgeAttribute , network , NodeAttribute , nodeList , x_position , y_start_position ] ) response = api ( url = self . __url + "/stacked-node-layout" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Execute the Stacked Node Layout on a network . | 169 | 11 |
243,923 | 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" , verbose = verbose ) return response | Appends an additional column of attribute values to the current table . | 108 | 13 |
243,924 | 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 ) return response | Adds a new table to the network . | 99 | 8 |
243,925 | 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 . | 80 | 19 |
243,926 | 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 . | 83 | 20 |
243,927 | 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 . | 93 | 15 |
243,928 | def import_url ( self , caseSensitiveNetworkCollectionKeys = None , caseSensitiveNetworkKeys = None , dataTypeList = None , DataTypeTargetForNetworkCollection = None , DataTypeTargetForNetworkList = None , delimiters = None , delimitersForDataList = None , firstRowAsColumnNames = None , KeyColumnForMapping = None , KeyColumnForMappingNetworkList = None , keyColumnIndex = None , newTableName = None , startLoadRow = None , TargetNetworkCollection = None , TargetNetworkList = None , url = None , WhereImportTable = None , verbose = None ) : PARAMS = set_param ( [ 'caseSensitiveNetworkCollectionKeys' , 'caseSensitiveNetworkKeys' , 'dataTypeList' , 'DataTypeTargetForNetworkCollection' , 'DataTypeTargetForNetworkList' , 'delimiters' , 'delimitersForDataList' , 'firstRowAsColumnNames' , 'KeyColumnForMapping' , 'KeyColumnForMappingNetworkList' , 'keyColumnIndex' , 'newTableName' , 'startLoadRow' , 'TargetNetworkCollection' , 'TargetNetworkList' , 'url' , 'WhereImportTable' ] , [ caseSensitiveNetworkCollectionKeys , caseSensitiveNetworkKeys , dataTypeList , DataTypeTargetForNetworkCollection , DataTypeTargetForNetworkList , delimiters , delimitersForDataList , firstRowAsColumnNames , KeyColumnForMapping , KeyColumnForMappingNetworkList , keyColumnIndex , newTableName , startLoadRow , TargetNetworkCollection , TargetNetworkList , url , WhereImportTable ] ) response = api ( url = self . __url + "/import url" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | 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 . | 394 | 30 |
243,929 | 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 response | Returns a list of the table SUIDs associated with the passed network parameter . | 96 | 15 |
243,930 | 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 . | 71 | 9 |
243,931 | 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 . | 83 | 16 |
243,932 | def merge ( self , DataTypeTargetForNetworkCollection = None , dataTypeTargetForNetworkList = None , mergeType = None , SourceMergeColumns = None , SourceMergeKey = None , SourceTable = None , TargetKeyNetworkCollection = None , TargetMergeKey = None , TargetNetworkCollection = None , TargetNetworkList = None , UnassignedTable = None , WhereMergeTable = None , verbose = None ) : PARAMS = set_param ( [ 'DataTypeTargetForNetworkCollection' , 'dataTypeTargetForNetworkList' , 'mergeType' , 'SourceMergeColumns' , 'SourceMergeKey' , 'SourceTable' , 'TargetKeyNetworkCollection' , 'TargetMergeKey' , 'TargetNetworkCollection' , 'TargetNetworkList' , 'UnassignedTable' , 'WhereMergeTable' ] , [ DataTypeTargetForNetworkCollection , dataTypeTargetForNetworkList , mergeType , SourceMergeColumns , SourceMergeKey , SourceTable , TargetKeyNetworkCollection , TargetMergeKey , TargetNetworkCollection , TargetNetworkList , UnassignedTable , WhereMergeTable ] ) response = api ( url = self . __url + "/merge" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Merge tables together joining around a designated key column . Depending on the arguments might merge into multiple local tables . | 284 | 22 |
243,933 | 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 = verbose ) return response | Changes the name of a specified column in the table . | 100 | 11 |
243,934 | 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 . | 80 | 9 |
243,935 | 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" , verbose = verbose ) return response | Set all the values in the specified list of rows with a single value . | 106 | 15 |
243,936 | 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 ) != int : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "columnList" , "namespace" , "network" ] , [ "SUID" , namespace , network ] ) network = api ( namespace = "network" , command = "get attribute" , PARAMS = PARAMS , host = host , port = str ( port ) , version = version ) network = network [ 0 ] [ "SUID" ] df = pd . DataFrame ( ) def target ( column ) : URL = "http://" + str ( host ) + ":" + str ( port ) + "/v1/networks/" + str ( network ) + "/tables/" + namespace + table + "/columns/" + column if verbose : print ( "'" + URL + "'" ) sys . stdout . flush ( ) response = urllib2 . urlopen ( URL ) response = response . read ( ) colA = json . loads ( response ) col = pd . DataFrame ( ) colHeader = colA [ "name" ] colValues = colA [ "values" ] col [ colHeader ] = colValues return col ncols = [ "name" ] for c in columns : ncols . append ( c . replace ( " " , "%20" ) ) for c in ncols : try : col = target ( c ) df = pd . concat ( [ df , col ] , axis = 1 ) except : print ( "Could not find " + c ) sys . stdout . flush ( ) df . index = df [ "name" ] . tolist ( ) df = df . drop ( [ "name" ] , axis = 1 ) return df | Gets tables from cytoscape . | 482 | 8 |
243,937 | 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 ] . split ( "/" ) [ 1 ] if type ( network ) != int : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "columnList" , "namespace" , "network" ] , [ "SUID" , namespace , network ] ) networkID = api ( namespace = "network" , command = "get attribute" , PARAMS = PARAMS , host = host , port = str ( port ) , version = version ) PARAMS = set_param ( [ "columnList" , "namespace" , "network" ] , [ "name" , namespace , network ] ) networkname = api ( namespace = "network" , command = "get attribute" , PARAMS = PARAMS , host = host , port = str ( port ) , version = version ) network = networkID [ 0 ] [ "SUID" ] networkname = networkname [ 0 ] [ "name" ] tmp = df . copy ( ) if df_key != "index" : tmp . index = tmp [ df_key ] . tolist ( ) tmp = tmp . drop ( [ df_key ] , axis = 1 ) tablen = networkname + " default node" data = [ ] for c in tmp . columns . tolist ( ) : tmpcol = tmp [ [ c ] ] . dropna ( ) for r in tmpcol . index . tolist ( ) : cell = { } cell [ str ( table_key_column ) ] = str ( r ) # {"name":"p53"} val = tmpcol . loc [ r , c ] if type ( val ) != str : val = float ( val ) cell [ str ( c ) ] = val data . append ( cell ) upload = { "key" : table_key_column , "dataKey" : table_key_column , "data" : data } URL = "http://" + str ( host ) + ":" + str ( port ) + "/v1/networks/" + str ( network ) + "/tables/" + namespace + table if verbose : print ( "'" + URL + "'" , upload ) sys . stdout . flush ( ) r = requests . put ( url = URL , json = upload ) if verbose : print ( r ) checkresponse ( r ) res = r . content return res | Loads tables into cytoscape . | 612 | 8 |
243,938 | 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 . | 48 | 7 |
243,939 | 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 | 84 | 6 |
243,940 | 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 = HEADERS ) | Set multiple Visual properties at once . | 98 | 7 |
243,941 | def get_value ( self , visual_property ) : res = requests . get ( self . url + '/' + visual_property ) return res . json ( ) [ 'value' ] | Get a value for the Visual Property | 40 | 7 |
243,942 | 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 | 50 | 8 |
243,943 | 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 . | 79 | 10 |
243,944 | 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 , outputFile , Resolution , Units , Width , Zoom , view ] ) response = api ( url = self . __url + "/export" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | 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 corrupted texts in the exported PDF please set false to exportTextAsFont when exporting networks including those non - English characters . | 145 | 86 |
243,945 | 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 . | 54 | 16 |
243,946 | 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 . | 63 | 11 |
243,947 | 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 . | 88 | 11 |
243,948 | 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 . | 74 | 11 |
243,949 | 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 | 64 | 7 |
243,950 | 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 . __url + "/map column" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response | Uses the BridgeDB service to look up analogous identifiers from a wide selection of other databases | 124 | 18 |
243,951 | 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 . | 55 | 26 |
243,952 | 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 . | 38 | 28 |
243,953 | 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 | 61 | 22 |
243,954 | 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 . | 34 | 22 |
243,955 | 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 . | 73 | 41 |
243,956 | 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 . | 55 | 28 |
243,957 | 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 = body . decode ( 'utf-8' ) parts += [ ( '-d' , body ) ] if compressed : parts += [ ( '--compressed' , None ) ] if not verify : parts += [ ( '--insecure' , None ) ] parts += [ ( None , request . url ) ] flat_parts = [ ] for k , v in parts : if k : flat_parts . append ( k ) if v : flat_parts . append ( "'{0}'" . format ( v ) ) return ' ' . join ( flat_parts ) | Returns string with curl command by provided request object | 224 | 9 |
243,958 | def shared_options ( rq ) : 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 . | 82 | 10 |
243,959 | def empty ( rq , ctx , all , queues ) : return ctx . invoke ( rq_cli . empty , all = all , queues = queues or rq . queues , * * shared_options ( rq ) ) | Empty given queues . | 50 | 4 |
243,960 | def requeue ( rq , ctx , all , job_ids ) : return ctx . invoke ( rq_cli . requeue , all = all , job_ids = job_ids , * * shared_options ( rq ) ) | Requeue failed jobs . | 55 | 5 |
243,961 | def info ( rq , ctx , path , interval , raw , only_queues , only_workers , by_queue , queues ) : 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 , * * shared_options ( rq ) ) | RQ command - line monitor . | 101 | 7 |
243,962 | def worker ( rq , ctx , burst , logging_level , name , path , results_ttl , worker_ttl , verbose , quiet , sentry_dsn , exception_handler , pid , queues ) : ctx . invoke ( rq_cli . worker , burst = burst , logging_level = logging_level , name = name , path = path , results_ttl = results_ttl , worker_ttl = worker_ttl , verbose = verbose , quiet = quiet , sentry_dsn = sentry_dsn , exception_handler = exception_handler or rq . _exception_handlers , pid = pid , queues = queues or rq . queues , * * shared_options ( rq ) ) | Starts an RQ worker . | 164 | 7 |
243,963 | def suspend ( rq , ctx , duration ) : ctx . invoke ( rq_cli . suspend , duration = duration , * * shared_options ( rq ) ) | Suspends all workers . | 38 | 6 |
243,964 | def scheduler ( rq , ctx , verbose , burst , queue , interval , pid ) : 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' else : level = 'INFO' setup_loghandlers ( level ) scheduler . run ( burst = burst ) | Periodically checks for scheduled jobs . | 115 | 8 |
243,965 | def init_cli ( self , app ) : # in case click isn't installed after all if click is None : raise RuntimeError ( 'Cannot import click. Is it installed?' ) # only add commands if we have a click context available from . cli import add_commands add_commands ( app . cli , self ) | Initialize the Flask CLI support in case it was enabled for the app . | 71 | 15 |
243,966 | 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 . set_trace ( frame = sys . _getframe ( ) . f_back ) | Opens a remote PDB on first available port . | 136 | 11 |
243,967 | 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 ] ) # update boundary and ghosts idx = mesh . is_boundary_node & ~ ghosted_mesh . is_ghost_point x [ idx ] = mesh . node_coords [ idx ] x [ ghosted_mesh . is_ghost_point ] = ghosted_mesh . reflect_ghost ( x [ ghosted_mesh . mirrors ] ) return x ghosted_mesh = GhostedMesh ( points , cells ) runner ( get_new_points , ghosted_mesh , * args , * * kwargs , update_topology = lambda mesh : ghosted_mesh . update_topology ( ) , # get_stats_mesh=lambda mesh: ghosted_mesh.get_unghosted_mesh(), ) mesh = ghosted_mesh . get_unghosted_mesh ( ) return mesh . node_coords , mesh . cells [ "nodes" ] | Relaxed Lloyd s algorithm . omega = 1 leads to Lloyd s algorithm overrelaxation omega = 2 gives good results . Check out | 280 | 28 |
243,968 | def _energy_uniform_per_node ( X , cells ) : dim = 2 mesh = MeshTri ( X , cells ) star_integrals = numpy . zeros ( mesh . node_coords . shape [ 0 ] ) # Python loop over the cells... slow! 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 = quadpy . triangle . integrate ( lambda x : numpy . einsum ( "ij,ij->i" , x . T - xi , x . T - xi ) , tri , # Take any scheme with order 2 quadpy . triangle . Dunavant ( 2 ) , ) star_integrals [ idx ] += val return star_integrals / ( dim + 1 ) | The CPT mesh energy is defined as | 202 | 8 |
243,969 | 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 ) . T , ) return 2 / ( dim + 1 ) * jac | The approximated Jacobian is | 132 | 6 |
243,970 | def solve_hessian_approx_uniform ( X , cells , rhs ) : dim = 2 mesh = MeshTri ( X , cells ) # Create matrix in IJV format row_idx = [ ] col_idx = [ ] val = [ ] cells = mesh . cells [ "nodes" ] . T n = X . shape [ 0 ] # Main diagonal, 2/(d+1) |omega_i| x_i a = mesh . cell_volumes * ( 2 / ( dim + 1 ) ) for i in [ 0 , 1 , 2 ] : row_idx += [ cells [ i ] ] col_idx += [ cells [ i ] ] val += [ a ] # terms corresponding to -2/(d+1) * b_j |tau_j| a = mesh . cell_volumes * ( 2 / ( dim + 1 ) ** 2 ) for i in [ [ 0 , 1 , 2 ] , [ 1 , 2 , 0 ] , [ 2 , 0 , 1 ] ] : edges = cells [ i ] # Leads to funny osciilatory movements # row_idx += [edges[0], edges[0], edges[0]] # col_idx += [edges[0], edges[1], edges[2]] # val += [-a, -a, -a] # Best so far row_idx += [ edges [ 0 ] , edges [ 0 ] ] col_idx += [ edges [ 1 ] , edges [ 2 ] ] val += [ - a , - a ] row_idx = numpy . concatenate ( row_idx ) col_idx = numpy . concatenate ( col_idx ) val = numpy . concatenate ( val ) # Set Dirichlet conditions on the boundary matrix = scipy . sparse . coo_matrix ( ( val , ( row_idx , col_idx ) ) , shape = ( n , n ) ) # Transform to CSR format for efficiency matrix = matrix . tocsr ( ) # Apply Dirichlet conditions. # Set all Dirichlet rows to 0. for i in numpy . where ( mesh . is_boundary_node ) [ 0 ] : matrix . data [ matrix . indptr [ i ] : matrix . indptr [ i + 1 ] ] = 0.0 # Set the diagonal and RHS. d = matrix . diagonal ( ) d [ mesh . is_boundary_node ] = 1.0 matrix . setdiag ( d ) rhs [ mesh . is_boundary_node ] = 0.0 out = scipy . sparse . linalg . spsolve ( matrix , rhs ) # PyAMG fails on circleci. # ml = pyamg.ruge_stuben_solver(matrix) # # Keep an eye on multiple rhs-solves in pyamg, # # <https://github.com/pyamg/pyamg/issues/215>. # tol = 1.0e-10 # out = numpy.column_stack( # [ml.solve(rhs[:, 0], tol=tol), ml.solve(rhs[:, 1], tol=tol)] # ) return out | As discussed above the approximated Jacobian is | 710 | 9 |
243,971 | def quasi_newton_uniform ( points , cells , * args , * * kwargs ) : def get_new_points ( mesh ) : # do one Newton step # TODO need copy? 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 , mesh , * args , * * kwargs ) return mesh . node_coords , mesh . cells [ "nodes" ] | Like linear_solve above but assuming rho == 1 . Note that the energy gradient | 151 | 18 |
243,972 | def fixed_point ( points , cells , * args , * * kwargs ) : def get_new_points ( mesh ) : # move interior points into average of their neighbors 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 . node_coords . shape ) fastfunc . add . at ( new_points , idx [ : , 0 ] , mesh . node_coords [ idx [ : , 1 ] ] ) fastfunc . add . at ( new_points , idx [ : , 1 ] , mesh . node_coords [ idx [ : , 0 ] ] ) new_points /= num_neighbors [ : , None ] idx = mesh . is_boundary_node new_points [ idx ] = mesh . node_coords [ idx ] return new_points mesh = MeshTri ( points , cells ) runner ( get_new_points , mesh , * args , * * kwargs ) return mesh . node_coords , mesh . cells [ "nodes" ] | Perform k steps of Laplacian smoothing to the mesh i . e . moving each interior vertex to the arithmetic average of its neighboring points . | 291 | 31 |
243,973 | def energy ( mesh , uniform_density = False ) : # E = 1/(d+1) sum_i ||x_i||^2 |omega_i| - int_Omega_i ||x||^2 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 : # rho = 1, # int_{star} phi_i * rho = 1/(d+1) sum_{triangles in star} |triangle| fastfunc . add . at ( star_volume , idx , mesh . cell_volumes ) else : # rho = 1 / tau_j, # int_{star} phi_i * rho = 1/(d+1) |num triangles in star| fastfunc . add . at ( star_volume , idx , numpy . ones ( idx . shape , dtype = float ) ) x2 = numpy . einsum ( "ij,ij->i" , mesh . node_coords , mesh . node_coords ) out = 1 / ( dim + 1 ) * numpy . dot ( star_volume , x2 ) # could be cached assert dim == 2 x = mesh . node_coords [ : , : 2 ] triangles = numpy . moveaxis ( x [ mesh . cells [ "nodes" ] ] , 0 , 1 ) val = quadpy . triangle . integrate ( lambda x : x [ 0 ] ** 2 + x [ 1 ] ** 2 , triangles , # Take any scheme with order 2 quadpy . triangle . Dunavant ( 2 ) , ) if uniform_density : val = numpy . sum ( val ) else : rho = 1.0 / mesh . cell_volumes val = numpy . dot ( val , rho ) assert out >= val return out - val | The mesh energy is defined as | 442 | 6 |
243,974 | def quasi_newton_uniform_blocks ( points , cells , * args , * * kwargs ) : def get_new_points ( mesh ) : # TODO need copy? x = mesh . node_coords . copy ( ) x += update ( mesh ) # update ghosts x [ ghosted_mesh . is_ghost_point ] = ghosted_mesh . reflect_ghost ( x [ ghosted_mesh . mirrors ] ) return x ghosted_mesh = GhostedMesh ( points , cells ) runner ( get_new_points , ghosted_mesh , * args , * * kwargs , update_topology = lambda mesh : ghosted_mesh . update_topology ( ) , # get_stats_mesh=lambda mesh: ghosted_mesh.get_unghosted_mesh(), ) mesh = ghosted_mesh . get_unghosted_mesh ( ) return mesh . node_coords , mesh . cells [ "nodes" ] | Lloyd s algorithm can be though of a diagonal - only Hessian ; this method incorporates the diagonal blocks too . | 220 | 24 |
243,975 | 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 = { } # Create the file (empty). # Yes, this might cause an exception, which we prefer to send to the caller f = h5py . File ( name = filename , mode = 'w' ) f . create_group ( '/layers' ) f . create_group ( '/row_attrs' ) f . create_group ( '/col_attrs' ) f . create_group ( '/row_graphs' ) f . create_group ( '/col_graphs' ) f . flush ( ) f . close ( ) ds = connect ( filename , validate = False ) for vals in file_attrs : ds . attrs [ vals ] = file_attrs [ vals ] # store creation date currentTime = time . localtime ( time . time ( ) ) ds . attrs [ 'CreationDate' ] = timestamp ( ) ds . attrs [ "LOOM_SPEC_VERSION" ] = loompy . loom_spec_version return ds | Create an empty Loom file and return it as a context manager . | 286 | 14 |
243,976 | 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 ) -> None : if isinstance ( row_attrs , loompy . AttributeManager ) : row_attrs = { k : v [ : ] for k , v in row_attrs . items ( ) } if isinstance ( col_attrs , loompy . AttributeManager ) : col_attrs = { k : v [ : ] for k , v in col_attrs . items ( ) } if isinstance ( layers , np . ndarray ) or scipy . sparse . issparse ( layers ) : layers = { "" : layers } elif isinstance ( layers , loompy . LayerManager ) : layers = { k : v [ : , : ] for k , v in layers . items ( ) } if "" not in layers : raise ValueError ( "Data for default layer must be provided" ) # Sanity checks shape = layers [ "" ] . shape # type: ignore if shape [ 0 ] == 0 or shape [ 1 ] == 0 : raise ValueError ( "Main matrix cannot be empty" ) for name , layer in layers . items ( ) : if layer . shape != shape : # type: ignore raise ValueError ( f"Layer '{name}' is not the same shape as the main matrix" ) for name , ra in row_attrs . items ( ) : if ra . shape [ 0 ] != shape [ 0 ] : raise ValueError ( f"Row attribute '{name}' is not the same length ({ra.shape[0]}) as number of rows in main matrix ({shape[0]})" ) for name , ca in col_attrs . items ( ) : if ca . shape [ 0 ] != shape [ 1 ] : raise ValueError ( f"Column attribute '{name}' is not the same length ({ca.shape[0]}) as number of columns in main matrix ({shape[1]})" ) try : with new ( filename , file_attrs = file_attrs ) as ds : for key , vals in layers . items ( ) : ds . layer [ key ] = vals for key , vals in row_attrs . items ( ) : ds . ra [ key ] = vals for key , vals in col_attrs . items ( ) : ds . ca [ key ] = vals except ValueError as ve : #ds.close(suppress_warning=True) # ds does not exist here if os . path . exists ( filename ) : os . remove ( filename ) raise ve | Create a new Loom file from the given data . | 648 | 11 |
243,977 | 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 . | 64 | 11 |
243,978 | def last_modified ( self ) -> str : if "last_modified" in self . attrs : return self . attrs [ "last_modified" ] elif self . mode == "r+" : # Make sure the file has modification timestamps self . attrs [ "last_modified" ] = timestamp ( ) return self . attrs [ "last_modified" ] return timestamp ( ) | Return an ISO8601 timestamp indicating when the file was last modified | 86 | 13 |
243,979 | 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 : rg . append ( name ) if self . col_graphs . last_modified ( ) > timestamp : for name in self . col_graphs . keys ( ) : if self . col_graphs . last_modified ( name ) > timestamp : cg . append ( name ) if self . ra . last_modified ( ) > timestamp : for name in self . ra . keys ( ) : if self . ra . last_modified ( name ) > timestamp : ra . append ( name ) if self . ca . last_modified ( ) > timestamp : for name in self . ca . keys ( ) : if self . ca . last_modified ( name ) > timestamp : ca . append ( name ) if self . layers . last_modified ( ) > timestamp : for name in self . layers . keys ( ) : if self . layers . last_modified ( name ) > timestamp : layers . append ( name ) return { "row_graphs" : rg , "col_graphs" : cg , "row_attrs" : ra , "col_attrs" : ca , "layers" : layers } | Get a summary of the parts of the file that changed since the given time | 339 | 15 |
243,980 | 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 | 92 | 26 |
243,981 | def close ( self , suppress_warning : bool = False ) -> None : if self . _file is None : if not suppress_warning : # Warn user that they're being paranoid # and should clean up their code logging . warn ( "Connection to %s is already closed" , self . filename ) else : self . _file . close ( ) self . _file = None self . layers = None # type: ignore self . ra = None # type: ignore self . row_attrs = None # type: ignore self . ca = None # type: ignore self . col_attrs = None # type: ignore self . row_graphs = None # type: ignore self . col_graphs = None # type: ignore self . shape = ( 0 , 0 ) self . _closed = True | Close the connection . After this the connection object becomes invalid . Warns user if called after closing . | 169 | 20 |
243,982 | def permute ( self , ordering : np . ndarray , axis : int ) -> None : if self . _file . __contains__ ( "tiles" ) : del self . _file [ 'tiles' ] ordering = list ( np . array ( ordering ) . flatten ( ) ) # Flatten the ordering, in case we got a column vector self . layers . _permute ( ordering , axis = axis ) if axis == 0 : self . row_attrs . _permute ( ordering ) self . row_graphs . _permute ( ordering ) if axis == 1 : self . col_attrs . _permute ( ordering ) self . col_graphs . _permute ( ordering ) | Permute the dataset along the indicated axis . | 154 | 10 |
243,983 | 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 = { } # type: Dict[str, np.ndarray] if select is not None : raise ValueError ( "The 'select' argument is deprecated" ) if isinstance ( group_by , np . ndarray ) : labels = group_by else : labels = ( self . ca [ group_by ] ) . astype ( 'int' ) _ , zero_strt_sort_noholes_lbls = np . unique ( labels , return_inverse = True ) n_groups = len ( set ( labels ) ) if aggr_ca_by is not None : for key in self . ca . keys ( ) : if key not in aggr_ca_by : continue func = aggr_ca_by [ key ] if func == "tally" : for val in set ( self . ca [ key ] ) : if np . issubdtype ( type ( val ) , np . str_ ) : valnew = val . replace ( "/" , "-" ) # Slashes are not allowed in attribute names valnew = valnew . replace ( "." , "_" ) # Nor are periods ca [ key + "_" + str ( valnew ) ] = npg . aggregate ( zero_strt_sort_noholes_lbls , ( self . ca [ key ] == val ) . astype ( 'int' ) , func = "sum" , fill_value = 0 ) elif func == "mode" : def mode ( x ) : # type: ignore return scipy . stats . mode ( x ) [ 0 ] [ 0 ] ca [ key ] = npg . aggregate ( zero_strt_sort_noholes_lbls , self . ca [ key ] , func = mode , fill_value = 0 ) . astype ( 'str' ) elif func == "mean" : ca [ key ] = npg . aggregate ( zero_strt_sort_noholes_lbls , self . ca [ key ] , func = func , fill_value = 0 ) elif func == "first" : ca [ key ] = npg . aggregate ( zero_strt_sort_noholes_lbls , self . ca [ key ] , func = func , fill_value = self . ca [ key ] [ 0 ] ) m = np . empty ( ( self . shape [ 0 ] , n_groups ) ) for ( _ , selection , view ) in self . scan ( axis = 0 , layers = [ "" ] ) : vals_aggr = npg . aggregate ( zero_strt_sort_noholes_lbls , view [ : , : ] , func = aggr_by , axis = 1 , fill_value = 0 ) m [ selection , : ] = vals_aggr if out_file is not None : loompy . create ( out_file , m , self . ra , ca ) return m | Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes | 714 | 21 |
243,984 | 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 . | 36 | 32 |
243,985 | 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 loop : c = RandomColor ( seed = seed ) . generate ( count = N , hue = hue , luminosity = luminosity , format_ = "hex" ) else : n = N while n > 0 : c += _color_alphabet [ : n ] n -= 25 if bgvalue is not None : c [ bgvalue ] = "#aaaaaa" return colors . LinearSegmentedColormap . from_list ( "" , c , N ) | Return a colormap suitable for N categorical values optimized to be both aesthetically pleasing and perceptually distinct . | 202 | 23 |
243,986 | 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 | 92 | 13 |
243,987 | 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" : with loompy . connect ( path , mode = "r" ) as ds : valid2 = self . validate_conventions ( ds ) if not valid2 : self . errors . append ( "For help, see http://linnarssonlab.org/loompy/conventions/" ) return valid1 and valid2 | Validate a file for conformance to the Loom specification | 172 | 12 |
243,988 | def _permute ( self , ordering : np . ndarray ) -> None : for key in self . keys ( ) : self [ key ] = self [ key ] [ ordering ] | Permute all the attributes in the collection | 39 | 9 |
243,989 | 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 . axis ] : raise ValueError ( f"Default must be an np.ndarray with exactly {self.ds.shape[self.axis]} values but {len(default)} were given" ) return default | Return the value for a named attribute if it exists else default . Default has to be a numpy array of correct size . | 140 | 25 |
243,990 | 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." ) elif type ( a ) is list or type ( a ) is tuple : return np . array ( a ) elif sparse . issparse ( a ) : return normalize_attr_array ( a . todense ( ) ) else : raise ValueError ( "Argument must be a list, tuple, numpy matrix, numpy ndarray or sparse matrix." ) | Take all kinds of array - like inputs and normalize to a one - dimensional np . ndarray | 184 | 21 |
243,991 | 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 else ''}<br/>(showing up to 10x10)<br/>" html += ds . filename + "<br/>" for ( name , val ) in ds . attrs . items ( ) : html += f"name: <em>{val}</em><br/>" html += "<table>" # Emit column attributes for ca in ds . col_attrs . keys ( ) : html += "<tr>" for ra in ds . row_attrs . keys ( ) : html += "<td> </td>" # Space for row attrs html += "<td><strong>" + ca + "</strong></td>" # Col attr name for v in ds . col_attrs [ ca ] [ : cm ] : html += "<td>" + str ( v ) + "</td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" # Emit row attribute names html += "<tr>" for ra in ds . row_attrs . keys ( ) : html += "<td><strong>" + ra + "</strong></td>" # Row attr name html += "<td> </td>" # Space for col attrs for v in range ( cm ) : html += "<td> </td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" # Emit row attr values and matrix values for row in range ( rm ) : html += "<tr>" for ra in ds . row_attrs . keys ( ) : html += "<td>" + str ( ds . row_attrs [ ra ] [ row ] ) + "</td>" html += "<td> </td>" # Space for col attrs for v in ds [ row , : cm ] : html += "<td>" + str ( v ) + "</td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" # Emit ellipses if ds . shape [ 0 ] > rm : html += "<tr>" for v in range ( rm + 1 + len ( ds . row_attrs . keys ( ) ) ) : html += "<td>...</td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" html += "</table>" return html | Return an HTML representation of the loom file or view showing the upper - left 10x10 corner . | 675 | 21 |
243,992 | 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_graphs . values ( ) : g . _permute ( ordering ) for a in self . row_attrs . values ( ) : a . _permute ( ordering ) elif axis == 1 : if self . col_graphs is not None : for g in self . col_graphs . values ( ) : g . _permute ( ordering ) for a in self . col_attrs . values ( ) : a . _permute ( ordering ) | Permute the view by permuting its layers attributes and graphs | 197 | 13 |
243,993 | 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 | 73 | 8 |
243,994 | 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 . | 80 | 9 |
243,995 | 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 . | 64 | 12 |
243,996 | 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 ( UserProfile . EXPERIMENT_BUCKET_MAP_KEY ) if not type ( experiment_bucket_map ) is dict : return False for decision in experiment_bucket_map . values ( ) : if type ( decision ) is not dict or UserProfile . VARIATION_ID_KEY not in decision : return False return True | Determine if provided user profile is valid or not . | 163 | 12 |
243,997 | 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 False | Determine if given attribute is valid . | 83 | 9 |
243,998 | def is_finite_number ( value ) : if not isinstance ( value , ( numbers . Integral , float ) ) : # numbers.Integral instead of int to accomodate long integer in python 2 return False if isinstance ( value , bool ) : # bool is a subclass of int 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 . | 110 | 25 |
243,999 | def are_values_same_type ( first_val , second_val ) : first_val_type = type ( first_val ) second_val_type = type ( second_val ) # use isinstance to accomodate Python 2 unicode and str types. if isinstance ( first_val , string_types ) and isinstance ( second_val , string_types ) : return True # Compare types if one of the values is bool because bool is a subclass on Integer. if isinstance ( first_val , bool ) or isinstance ( second_val , bool ) : return first_val_type == second_val_type # Treat ints and floats as same type. if isinstance ( first_val , ( numbers . Integral , float ) ) and isinstance ( second_val , ( numbers . Integral , float ) ) : return True return False | Method to verify that both values belong to same type . Float and integer are considered as same type . | 186 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.