repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.attribute_circle | def attribute_circle(self, EdgeAttribute=None, network=None, \
NodeAttribute=None, nodeList=None, singlePartition=None,\
spacing=None, verbose=False):
"""
Execute the Attribute Circle Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The
keywords all, selected, or unselected can be used to specify nodes
by their selection state. The pattern COLUMN:VALUE sets this parameter
to any rows that contain the specified column value; if the COLUMN
prefix is not used, the NAME column is matched by default. A list of
COLUMN:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,...
can be used to match multiple values.
:param singlePartition (string, optional): Don't partition graph before
layout, only boolean values allowed: true or false
:param spacing (string, optional): Circle size, in numeric value
:param verbose: print more
"""
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 | python | def attribute_circle(self, EdgeAttribute=None, network=None, \
NodeAttribute=None, nodeList=None, singlePartition=None,\
spacing=None, verbose=False):
"""
Execute the Attribute Circle Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The
keywords all, selected, or unselected can be used to specify nodes
by their selection state. The pattern COLUMN:VALUE sets this parameter
to any rows that contain the specified column value; if the COLUMN
prefix is not used, the NAME column is matched by default. A list of
COLUMN:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,...
can be used to match multiple values.
:param singlePartition (string, optional): Don't partition graph before
layout, only boolean values allowed: true or false
:param spacing (string, optional): Circle size, in numeric value
:param verbose: print more
"""
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 | [
"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.
:param EdgeAttribute (string, optional): The name of the edge column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The
keywords all, selected, or unselected can be used to specify nodes
by their selection state. The pattern COLUMN:VALUE sets this parameter
to any rows that contain the specified column value; if the COLUMN
prefix is not used, the NAME column is matched by default. A list of
COLUMN:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,...
can be used to match multiple values.
:param singlePartition (string, optional): Don't partition graph before
layout, only boolean values allowed: true or false
:param spacing (string, optional): Circle size, in numeric value
:param verbose: print more | [
"Execute",
"the",
"Attribute",
"Circle",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L29-L61 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.attributes_layout | def attributes_layout(self, EdgeAttribute=None, maxwidth=None, minrad=None, \
network=None, NodeAttribute=None,nodeList=None, radmult=None, \
spacingx=None, spacingy=None, verbose=False):
"""
Execute the Group Attributes Layout on a network
:param EdgeAttribute (string, optional): The name of the edge column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param maxwidth (string, optional): Maximum width of a row, in numeric value
:param minrad (string, optional): Minimum width of a partition, in
numeric value
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The
keywords all, selected, or unselected can be used to specify nodes
by their selection state. The pattern COLUMN:VALUE sets this parameter
to any rows that contain the specified column value; if the COLUMN
prefix is not used, the NAME column is matched by default. A list
of COLUMN:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,...
can be used to match multiple values.
:param radmult (string, optional): Minimum width of a partition, in
numeric value
:param spacingx (string, optional): Horizontal spacing between two
partitions in a row, in numeric value
:param spacingy (string, optional): Vertical spacing between the largest
partitions of two rows, in numeric value
:param verbose: print more
"""
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 | python | def attributes_layout(self, EdgeAttribute=None, maxwidth=None, minrad=None, \
network=None, NodeAttribute=None,nodeList=None, radmult=None, \
spacingx=None, spacingy=None, verbose=False):
"""
Execute the Group Attributes Layout on a network
:param EdgeAttribute (string, optional): The name of the edge column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param maxwidth (string, optional): Maximum width of a row, in numeric value
:param minrad (string, optional): Minimum width of a partition, in
numeric value
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The
keywords all, selected, or unselected can be used to specify nodes
by their selection state. The pattern COLUMN:VALUE sets this parameter
to any rows that contain the specified column value; if the COLUMN
prefix is not used, the NAME column is matched by default. A list
of COLUMN:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,...
can be used to match multiple values.
:param radmult (string, optional): Minimum width of a partition, in
numeric value
:param spacingx (string, optional): Horizontal spacing between two
partitions in a row, in numeric value
:param spacingy (string, optional): Vertical spacing between the largest
partitions of two rows, in numeric value
:param verbose: print more
"""
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 | [
"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
:param EdgeAttribute (string, optional): The name of the edge column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param maxwidth (string, optional): Maximum width of a row, in numeric value
:param minrad (string, optional): Minimum width of a partition, in
numeric value
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column
containing numeric values that will be used as weights in the layout
algorithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The
keywords all, selected, or unselected can be used to specify nodes
by their selection state. The pattern COLUMN:VALUE sets this parameter
to any rows that contain the specified column value; if the COLUMN
prefix is not used, the NAME column is matched by default. A list
of COLUMN:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,...
can be used to match multiple values.
:param radmult (string, optional): Minimum width of a partition, in
numeric value
:param spacingx (string, optional): Horizontal spacing between two
partitions in a row, in numeric value
:param spacingy (string, optional): Vertical spacing between the largest
partitions of two rows, in numeric value
:param verbose: print more | [
"Execute",
"the",
"Group",
"Attributes",
"Layout",
"on",
"a",
"network"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L64-L104 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.circular | 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):
"""
Execute the Circular Layout on a network
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param leftEdge (string, optional): Left edge margin, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
:param rightMargin (string, optional): Right edge margin, in numeric value
:param singlePartition (string, optional): Don't partition graph before lay
out; only boolean values are allowed: true or false
:param topEdge (string, optional): Top edge margin, in numeric value
"""
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 | python | 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):
"""
Execute the Circular Layout on a network
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param leftEdge (string, optional): Left edge margin, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
:param rightMargin (string, optional): Right edge margin, in numeric value
:param singlePartition (string, optional): Don't partition graph before lay
out; only boolean values are allowed: true or false
:param topEdge (string, optional): Top edge margin, in numeric value
"""
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 | [
"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
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param leftEdge (string, optional): Left edge margin, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
:param rightMargin (string, optional): Right edge margin, in numeric value
:param singlePartition (string, optional): Don't partition graph before lay
out; only boolean values are allowed: true or false
:param topEdge (string, optional): Top edge margin, in numeric value | [
"Execute",
"the",
"Circular",
"Layout",
"on",
"a",
"network"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L106-L146 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.copycat | def copycat(self,gridUnmapped=None,selectUnmapped=None,sourceColumn=None,\
sourceNetwork=None,targetColumn=None,targetNetwork=None,verbose=None):
"""
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.
:param gridUnmapped (string, optional): If this is set to true, any nodes i
n the target network that could not be matched to a node in the sour
ce network will be laid out in a grid
:param selectUnmapped (string, optional): If this is set to true, any nodes
in the target network that could not be matched to a node in the so
urce network will be selected in the target network
:param sourceColumn (string): The name of column in the node table used to
match nodes
:param sourceNetwork (string): The name of network to get node coordinates
from
:param targetColumn (string): The name of column in the node table used to
match nodes
:param targetNetwork (string): The name of the network to apply coordinates
to.
"""
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 | python | def copycat(self,gridUnmapped=None,selectUnmapped=None,sourceColumn=None,\
sourceNetwork=None,targetColumn=None,targetNetwork=None,verbose=None):
"""
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.
:param gridUnmapped (string, optional): If this is set to true, any nodes i
n the target network that could not be matched to a node in the sour
ce network will be laid out in a grid
:param selectUnmapped (string, optional): If this is set to true, any nodes
in the target network that could not be matched to a node in the so
urce network will be selected in the target network
:param sourceColumn (string): The name of column in the node table used to
match nodes
:param sourceNetwork (string): The name of network to get node coordinates
from
:param targetColumn (string): The name of column in the node table used to
match nodes
:param targetNetwork (string): The name of the network to apply coordinates
to.
"""
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 | [
"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.
:param gridUnmapped (string, optional): If this is set to true, any nodes i
n the target network that could not be matched to a node in the sour
ce network will be laid out in a grid
:param selectUnmapped (string, optional): If this is set to true, any nodes
in the target network that could not be matched to a node in the so
urce network will be selected in the target network
:param sourceColumn (string): The name of column in the node table used to
match nodes
:param sourceNetwork (string): The name of network to get node coordinates
from
:param targetColumn (string): The name of column in the node table used to
match nodes
:param targetNetwork (string): The name of the network to apply coordinates
to. | [
"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",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L148-L175 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.degree_circle | def degree_circle(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeList=None,singlePartition=None,verbose=None):
"""
Execute the Degree Sorted Circle Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
"""
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 | python | def degree_circle(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeList=None,singlePartition=None,verbose=None):
"""
Execute the Degree Sorted Circle Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
"""
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 | [
"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.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false | [
"Execute",
"the",
"Degree",
"Sorted",
"Circle",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L233-L262 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.force_directed | 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):
"""
Execute the Prefuse Force Directed Layout on a network
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param defaultNodeMass (string, optional): Default Node Mass, in numeric va
lue
:param defaultSpringCoefficient (string, optional): Default Spring Coeffici
ent, in numeric value
:param defaultSpringLength (string, optional): Default Spring Length, in nu
meric value
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param isDeterministic (string, optional): Force deterministic layouts (slo
wer); boolean values only, true or false; defaults to false
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param numIterations (string, optional): Number of Iterations, in numeric v
alue
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value']
"""
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 | python | 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):
"""
Execute the Prefuse Force Directed Layout on a network
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param defaultNodeMass (string, optional): Default Node Mass, in numeric va
lue
:param defaultSpringCoefficient (string, optional): Default Spring Coeffici
ent, in numeric value
:param defaultSpringLength (string, optional): Default Spring Length, in nu
meric value
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param isDeterministic (string, optional): Force deterministic layouts (slo
wer); boolean values only, true or false; defaults to false
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param numIterations (string, optional): Number of Iterations, in numeric v
alue
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value']
"""
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 | [
"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
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param defaultNodeMass (string, optional): Default Node Mass, in numeric va
lue
:param defaultSpringCoefficient (string, optional): Default Spring Coeffici
ent, in numeric value
:param defaultSpringLength (string, optional): Default Spring Length, in nu
meric value
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param isDeterministic (string, optional): Force deterministic layouts (slo
wer); boolean values only, true or false; defaults to false
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param numIterations (string, optional): Number of Iterations, in numeric v
alue
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value'] | [
"Execute",
"the",
"Prefuse",
"Force",
"Directed",
"Layout",
"on",
"a",
"network"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L265-L321 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.genemania_force_directed | 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):
"""
Execute the GeneMANIA Force Directed Layout on a network.
:param curveSteepness (string, optional):
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param defaultSpringCoefficient (string, optional):
:param defaultSpringLength (string, optional):
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param ignoreHiddenElements (string, optional):
:param isDeterministic (string, optional):
:param maxNodeMass (string, optional):
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param midpointEdges (string, optional):
:param minNodeMass (string, optional):
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param numIterations (string, optional):
:param singlePartition (string, optional):
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value']
"""
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 | python | 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):
"""
Execute the GeneMANIA Force Directed Layout on a network.
:param curveSteepness (string, optional):
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param defaultSpringCoefficient (string, optional):
:param defaultSpringLength (string, optional):
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param ignoreHiddenElements (string, optional):
:param isDeterministic (string, optional):
:param maxNodeMass (string, optional):
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param midpointEdges (string, optional):
:param minNodeMass (string, optional):
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param numIterations (string, optional):
:param singlePartition (string, optional):
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value']
"""
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 | [
"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.
:param curveSteepness (string, optional):
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param defaultSpringCoefficient (string, optional):
:param defaultSpringLength (string, optional):
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param ignoreHiddenElements (string, optional):
:param isDeterministic (string, optional):
:param maxNodeMass (string, optional):
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param midpointEdges (string, optional):
:param minNodeMass (string, optional):
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param numIterations (string, optional):
:param singlePartition (string, optional):
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value'] | [
"Execute",
"the",
"GeneMANIA",
"Force",
"Directed",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L455-L512 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.get_preferred | def get_preferred(self,network=None,verbose=None):
"""
Returns the name of the current preferred layout or empty string if not
set. Default is grid.
:param network (string, optional): Gets the name of the current preferred l
ayout
"""
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 | python | def get_preferred(self,network=None,verbose=None):
"""
Returns the name of the current preferred layout or empty string if not
set. Default is grid.
:param network (string, optional): Gets the name of the current preferred l
ayout
"""
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 | [
"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.
:param network (string, optional): Gets the name of the current preferred l
ayout | [
"Returns",
"the",
"name",
"of",
"the",
"current",
"preferred",
"layout",
"or",
"empty",
"string",
"if",
"not",
"set",
".",
"Default",
"is",
"grid",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L515-L526 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.grid | def grid(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeHorizontalSpacing=None,nodeList=None,nodeVerticalSpacing=None,verbose=None):
"""
Execute the Grid Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
"""
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 | python | def grid(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeHorizontalSpacing=None,nodeList=None,nodeVerticalSpacing=None,verbose=None):
"""
Execute the Grid Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
"""
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 | [
"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.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value | [
"Execute",
"the",
"Grid",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L528-L560 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.hierarchical | 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):
"""
Execute the Hierarchical Layout on a network.
:param bandGap (string, optional): Band gap, in numeric value
:param componentSpacing (string, optional): Component spacing, in numeric v
alue
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param leftEdge (string, optional): Left edge margin, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
:param rightMargin (string, optional): Right edge margin, in numeric value
:param topEdge (string, optional): Top edge margin, in numeric value
"""
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 | python | 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):
"""
Execute the Hierarchical Layout on a network.
:param bandGap (string, optional): Band gap, in numeric value
:param componentSpacing (string, optional): Component spacing, in numeric v
alue
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param leftEdge (string, optional): Left edge margin, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
:param rightMargin (string, optional): Right edge margin, in numeric value
:param topEdge (string, optional): Top edge margin, in numeric value
"""
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 | [
"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.
:param bandGap (string, optional): Band gap, in numeric value
:param componentSpacing (string, optional): Component spacing, in numeric v
alue
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param leftEdge (string, optional): Left edge margin, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeHorizontalSpacing (string, optional): Horizontal spacing between
nodes, in numeric value
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param nodeVerticalSpacing (string, optional): Vertical spacing between nod
es, in numeric value
:param rightMargin (string, optional): Right edge margin, in numeric value
:param topEdge (string, optional): Top edge margin, in numeric value | [
"Execute",
"the",
"Hierarchical",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L563-L604 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.isom | 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):
"""
Execute the Inverted Self-Organizing Map Layout on a network.
:param coolingFactor (string, optional): Cooling factor, in numeric value
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param initialAdaptation (string, optional): Initial adaptation, in numeric
value
:param maxEpoch (string, optional): Number of iterations, in numeric value
:param minAdaptation (string, optional): Minimum adaptation value, in numer
ic value
:param minRadius (string, optional): Minimum radius, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param radius (string, optional): Radius, in numeric value
:param radiusConstantTime (string, optional): Radius constant, in numeric v
alue
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param sizeFactor (string, optional): Size factor, in numeric value
"""
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 | python | 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):
"""
Execute the Inverted Self-Organizing Map Layout on a network.
:param coolingFactor (string, optional): Cooling factor, in numeric value
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param initialAdaptation (string, optional): Initial adaptation, in numeric
value
:param maxEpoch (string, optional): Number of iterations, in numeric value
:param minAdaptation (string, optional): Minimum adaptation value, in numer
ic value
:param minRadius (string, optional): Minimum radius, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param radius (string, optional): Radius, in numeric value
:param radiusConstantTime (string, optional): Radius constant, in numeric v
alue
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param sizeFactor (string, optional): Size factor, in numeric value
"""
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 | [
"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.
:param coolingFactor (string, optional): Cooling factor, in numeric value
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param initialAdaptation (string, optional): Initial adaptation, in numeric
value
:param maxEpoch (string, optional): Number of iterations, in numeric value
:param minAdaptation (string, optional): Minimum adaptation value, in numer
ic value
:param minRadius (string, optional): Minimum radius, in numeric value
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param radius (string, optional): Radius, in numeric value
:param radiusConstantTime (string, optional): Radius constant, in numeric v
alue
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param sizeFactor (string, optional): Size factor, in numeric value | [
"Execute",
"the",
"Inverted",
"Self",
"-",
"Organizing",
"Map",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L607-L651 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.kamada_kawai | 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):
"""
Execute the Edge-weighted Spring Embedded Layout on a network.
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param m_anticollisionSpringStrength (string, optional): Strength to apply
to avoid collisions, in numeric value
:param m_averageIterationsPerNode (string, optional): Average number of ite
ratations for each node, in numeric value
:param m_disconnectedNodeDistanceSpringRestLength (string, optional): Rest
length of a 'disconnected' spring, in numeric value
:param m_disconnectedNodeDistanceSpringStrength (string, optional): Strengt
h of a 'disconnected' spring, in numeric value
:param m_layoutPass (string, optional): Number of layout passes, in numeric
value
:param m_nodeDistanceRestLengthConstant (string, optional): Spring rest len
gth, in numeric value
:param m_nodeDistanceStrengthConstant (string, optional): Spring strength,
in numeric value
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param randomize (string, optional): Randomize graph before layout; boolean
values only, true or false; defaults to true
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value']
:param unweighted (string, optional): Use unweighted edges; boolean values
only, true or false; defaults to false
"""
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 | python | 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):
"""
Execute the Edge-weighted Spring Embedded Layout on a network.
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param m_anticollisionSpringStrength (string, optional): Strength to apply
to avoid collisions, in numeric value
:param m_averageIterationsPerNode (string, optional): Average number of ite
ratations for each node, in numeric value
:param m_disconnectedNodeDistanceSpringRestLength (string, optional): Rest
length of a 'disconnected' spring, in numeric value
:param m_disconnectedNodeDistanceSpringStrength (string, optional): Strengt
h of a 'disconnected' spring, in numeric value
:param m_layoutPass (string, optional): Number of layout passes, in numeric
value
:param m_nodeDistanceRestLengthConstant (string, optional): Spring rest len
gth, in numeric value
:param m_nodeDistanceStrengthConstant (string, optional): Spring strength,
in numeric value
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param randomize (string, optional): Randomize graph before layout; boolean
values only, true or false; defaults to true
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value']
:param unweighted (string, optional): Use unweighted edges; boolean values
only, true or false; defaults to false
"""
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 | [
"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.
:param defaultEdgeWeight (string, optional): The default edge weight to con
sider, default is 0.5
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param m_anticollisionSpringStrength (string, optional): Strength to apply
to avoid collisions, in numeric value
:param m_averageIterationsPerNode (string, optional): Average number of ite
ratations for each node, in numeric value
:param m_disconnectedNodeDistanceSpringRestLength (string, optional): Rest
length of a 'disconnected' spring, in numeric value
:param m_disconnectedNodeDistanceSpringStrength (string, optional): Strengt
h of a 'disconnected' spring, in numeric value
:param m_layoutPass (string, optional): Number of layout passes, in numeric
value
:param m_nodeDistanceRestLengthConstant (string, optional): Spring rest len
gth, in numeric value
:param m_nodeDistanceStrengthConstant (string, optional): Spring strength,
in numeric value
:param maxWeightCutoff (string, optional): The maximum edge weight to consi
der, default to the Double.MAX value
:param minWeightCutoff (string, optional): The minimum edge weight to consi
der, numeric values, default is 0
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param randomize (string, optional): Randomize graph before layout; boolean
values only, true or false; defaults to true
:param singlePartition (string, optional): Don't partition graph before lay
out; boolean values only, true or false; defaults to false
:param Type (string, optional): How to interpret weight values; must be one
of Heuristic, -Log(value), 1 - normalized value and normalized valu
e. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali
zed value', 'normalized value']
:param unweighted (string, optional): Use unweighted edges; boolean values
only, true or false; defaults to false | [
"Execute",
"the",
"Edge",
"-",
"weighted",
"Spring",
"Embedded",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L653-L726 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.set_preferred | def set_preferred(self,preferredLayout=None,verbose=None):
"""
Sets the preferred layout. Takes a specific name as defined in the API
Default is grid.
:param preferredLayout (string, optional): Layout to use as preferred, for
allowed names see Layout API
"""
PARAMS=set_param(['preferredLayout'],[preferredLayout])
response=api(url=self.__url+"/set preferred", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def set_preferred(self,preferredLayout=None,verbose=None):
"""
Sets the preferred layout. Takes a specific name as defined in the API
Default is grid.
:param preferredLayout (string, optional): Layout to use as preferred, for
allowed names see Layout API
"""
PARAMS=set_param(['preferredLayout'],[preferredLayout])
response=api(url=self.__url+"/set preferred", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param preferredLayout (string, optional): Layout to use as preferred, for
allowed names see Layout API | [
"Sets",
"the",
"preferred",
"layout",
".",
"Takes",
"a",
"specific",
"name",
"as",
"defined",
"in",
"the",
"API",
"Default",
"is",
"grid",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L729-L739 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/layout.py | layout.stacked_node_layout | def stacked_node_layout(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeList=None,x_position=None,y_start_position=None,verbose=None):
"""
Execute the Stacked Node Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param x_position (string, optional): X start position, in numeric value
:param y_start_position (string, optional): Y start position, in numeric va
lue
"""
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 | python | def stacked_node_layout(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeList=None,x_position=None,y_start_position=None,verbose=None):
"""
Execute the Stacked Node Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param x_position (string, optional): X start position, in numeric value
:param y_start_position (string, optional): Y start position, in numeric va
lue
"""
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 | [
"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.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network by name, or by SUID
if the prefix SUID: is used. The keyword CURRENT, or a blank value c
an also be used to specify the current network.
:param NodeAttribute (string, optional): The name of the node column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param nodeList (string, optional): Specifies a list of nodes. The keywords
all, selected, or unselected can be used to specify nodes by their
selection state. The pattern COLUMN:VALUE sets this parameter to any
rows that contain the specified column value; if the COLUMN prefix
is not used, the NAME column is matched by default. A list of COLUMN
:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be
used to match multiple values.
:param x_position (string, optional): X start position, in numeric value
:param y_start_position (string, optional): Y start position, in numeric va
lue | [
"Execute",
"the",
"Stacked",
"Node",
"Layout",
"on",
"a",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L742-L772 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.create_column | def create_column(self,columnName=None,listType=None,table=None,ntype=None,verbose=None):
"""
Appends an additional column of attribute values to the current table.
:param columnName (string, optional): The new column name
:param listType (string, optional): Can be one of integer, long, double, or
string.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param ntype (string, optional): Can be one of integer, long, double, string
, or list.
"""
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 | python | def create_column(self,columnName=None,listType=None,table=None,ntype=None,verbose=None):
"""
Appends an additional column of attribute values to the current table.
:param columnName (string, optional): The new column name
:param listType (string, optional): Can be one of integer, long, double, or
string.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param ntype (string, optional): Can be one of integer, long, double, string
, or list.
"""
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 | [
"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.
:param columnName (string, optional): The new column name
:param listType (string, optional): Can be one of integer, long, double, or
string.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param ntype (string, optional): Can be one of integer, long, double, string
, or list. | [
"Appends",
"an",
"additional",
"column",
"of",
"attribute",
"values",
"to",
"the",
"current",
"table",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L30-L46 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.create_table | def create_table(self,keyColumn=None,keyColumnType=None,title=None,verbose=None):
"""
Adds a new table to the network.
:param keyColumn (string, optional): Specifies the name of a column in the
table
:param keyColumnType (string, optional): The syntactical type of the value
used in the key
:param title (string, optional): The name of the table used in the current
network
:returns: table SUID
"""
PARAMS=set_param(['keyColumn','keyColumnType','title'],[keyColumn,\
keyColumnType,title])
response=api(url=self.__url+"/create table", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def create_table(self,keyColumn=None,keyColumnType=None,title=None,verbose=None):
"""
Adds a new table to the network.
:param keyColumn (string, optional): Specifies the name of a column in the
table
:param keyColumnType (string, optional): The syntactical type of the value
used in the key
:param title (string, optional): The name of the table used in the current
network
:returns: table SUID
"""
PARAMS=set_param(['keyColumn','keyColumnType','title'],[keyColumn,\
keyColumnType,title])
response=api(url=self.__url+"/create table", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param keyColumn (string, optional): Specifies the name of a column in the
table
:param keyColumnType (string, optional): The syntactical type of the value
used in the key
:param title (string, optional): The name of the table used in the current
network
:returns: table SUID | [
"Adds",
"a",
"new",
"table",
"to",
"the",
"network",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L49-L65 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.delete_column | def delete_column(self,column=None,table=None,verbose=None):
"""
Remove a column from a table, specified by its name. Returns the name of
the column removed.
:param column (string, optional): Specifies the name of a column in the tab
le
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['column','table'],[column,table])
response=api(url=self.__url+"/delete column", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def delete_column(self,column=None,table=None,verbose=None):
"""
Remove a column from a table, specified by its name. Returns the name of
the column removed.
:param column (string, optional): Specifies the name of a column in the tab
le
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['column','table'],[column,table])
response=api(url=self.__url+"/delete column", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param column (string, optional): Specifies the name of a column in the tab
le
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d. | [
"Remove",
"a",
"column",
"from",
"a",
"table",
"specified",
"by",
"its",
"name",
".",
"Returns",
"the",
"name",
"of",
"the",
"column",
"removed",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L67-L80 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.delete_row | def delete_row(self,keyValue=None,table=None,verbose=None):
"""
Deletes a row from a table.Requires the table name or SUID and the row key.
:param keyValue (string): Specifies the primary key of a value in the row o
f a table
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['keyValue','table'],[keyValue,table])
response=api(url=self.__url+"/delete row", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def delete_row(self,keyValue=None,table=None,verbose=None):
"""
Deletes a row from a table.Requires the table name or SUID and the row key.
:param keyValue (string): Specifies the primary key of a value in the row o
f a table
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['keyValue','table'],[keyValue,table])
response=api(url=self.__url+"/delete row", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param keyValue (string): Specifies the primary key of a value in the row o
f a table
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d. | [
"Deletes",
"a",
"row",
"from",
"a",
"table",
".",
"Requires",
"the",
"table",
"name",
"or",
"SUID",
"and",
"the",
"row",
"key",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L83-L95 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.get_value | def get_value(self,column=None,keyValue=None,table=None,verbose=None):
"""
Returns the value from a cell as specified by row and column ids.
:param column (string, optional): Specifies the name of a column in the tab
le
:param keyValue (string, optional): Specifies a row of a table using the pr
imary key as the indentifier
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:returns: value from a cell as specified by row and column ids
"""
PARAMS=set_param(['column','keyValue','table'],[column,keyValue,table])
response=api(url=self.__url+"/get value", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def get_value(self,column=None,keyValue=None,table=None,verbose=None):
"""
Returns the value from a cell as specified by row and column ids.
:param column (string, optional): Specifies the name of a column in the tab
le
:param keyValue (string, optional): Specifies a row of a table using the pr
imary key as the indentifier
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:returns: value from a cell as specified by row and column ids
"""
PARAMS=set_param(['column','keyValue','table'],[column,keyValue,table])
response=api(url=self.__url+"/get value", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param column (string, optional): Specifies the name of a column in the tab
le
:param keyValue (string, optional): Specifies a row of a table using the pr
imary key as the indentifier
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:returns: value from a cell as specified by row and column ids | [
"Returns",
"the",
"value",
"from",
"a",
"cell",
"as",
"specified",
"by",
"row",
"and",
"column",
"ids",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L160-L176 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.import_url | 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):
"""
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.
:param caseSensitiveNetworkCollectionKeys (string, optional): Determines wh
ether capitalization is considered in matching and sorting
:param caseSensitiveNetworkKeys (string, optional): Determines whether capi
talization is considered in matching and sorting
:param dataTypeList (string, optional): List of column data types ordered b
y column index (e.g. "string,int,long,double,boolean,intlist" or jus
t "s,i,l,d,b,il")
:param DataTypeTargetForNetworkCollection (string, optional): Select whethe
r to import the data as Node Table Columns, Edge Table Columns, or N
etwork Table Columns
:param DataTypeTargetForNetworkList (string, optional): The data type of th
e targets
:param delimiters (string, optional): The list of delimiters that separate
columns in the table.
:param delimitersForDataList (string, optional): The delimiters between ele
ments of list columns in the table.
:param firstRowAsColumnNames (string, optional): If the first imported row
contains column names, set this to true.
:param KeyColumnForMapping (string, optional): The column in the network to
use as the merge key
:param KeyColumnForMappingNetworkList (string, optional): The column in the
network to use as the merge key
:param keyColumnIndex (string, optional): The column that contains the key
values for this import. These values will be used to match with the
key values in the network.
:param newTableName (string, optional): The title of the new table
:param startLoadRow (string, optional): The first row of the input table to
load. This allows the skipping of headers that are not part of the
import.
:param TargetNetworkCollection (string, optional): The network collection t
o use for the table import
:param TargetNetworkList (string, optional): The list of networks into whic
h the table is imported
:param url (string): The URL of the file or resource that provides the tabl
e or network to be imported.
:param WhereImportTable (string, optional): Determines what network(s) the
imported table will be associated with (if any). A table can be impo
rted into a Network Collection, Selected networks or to an unassigne
d table.
"""
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 | python | 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):
"""
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.
:param caseSensitiveNetworkCollectionKeys (string, optional): Determines wh
ether capitalization is considered in matching and sorting
:param caseSensitiveNetworkKeys (string, optional): Determines whether capi
talization is considered in matching and sorting
:param dataTypeList (string, optional): List of column data types ordered b
y column index (e.g. "string,int,long,double,boolean,intlist" or jus
t "s,i,l,d,b,il")
:param DataTypeTargetForNetworkCollection (string, optional): Select whethe
r to import the data as Node Table Columns, Edge Table Columns, or N
etwork Table Columns
:param DataTypeTargetForNetworkList (string, optional): The data type of th
e targets
:param delimiters (string, optional): The list of delimiters that separate
columns in the table.
:param delimitersForDataList (string, optional): The delimiters between ele
ments of list columns in the table.
:param firstRowAsColumnNames (string, optional): If the first imported row
contains column names, set this to true.
:param KeyColumnForMapping (string, optional): The column in the network to
use as the merge key
:param KeyColumnForMappingNetworkList (string, optional): The column in the
network to use as the merge key
:param keyColumnIndex (string, optional): The column that contains the key
values for this import. These values will be used to match with the
key values in the network.
:param newTableName (string, optional): The title of the new table
:param startLoadRow (string, optional): The first row of the input table to
load. This allows the skipping of headers that are not part of the
import.
:param TargetNetworkCollection (string, optional): The network collection t
o use for the table import
:param TargetNetworkList (string, optional): The list of networks into whic
h the table is imported
:param url (string): The URL of the file or resource that provides the tabl
e or network to be imported.
:param WhereImportTable (string, optional): Determines what network(s) the
imported table will be associated with (if any). A table can be impo
rted into a Network Collection, Selected networks or to an unassigne
d table.
"""
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 | [
"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.
:param caseSensitiveNetworkCollectionKeys (string, optional): Determines wh
ether capitalization is considered in matching and sorting
:param caseSensitiveNetworkKeys (string, optional): Determines whether capi
talization is considered in matching and sorting
:param dataTypeList (string, optional): List of column data types ordered b
y column index (e.g. "string,int,long,double,boolean,intlist" or jus
t "s,i,l,d,b,il")
:param DataTypeTargetForNetworkCollection (string, optional): Select whethe
r to import the data as Node Table Columns, Edge Table Columns, or N
etwork Table Columns
:param DataTypeTargetForNetworkList (string, optional): The data type of th
e targets
:param delimiters (string, optional): The list of delimiters that separate
columns in the table.
:param delimitersForDataList (string, optional): The delimiters between ele
ments of list columns in the table.
:param firstRowAsColumnNames (string, optional): If the first imported row
contains column names, set this to true.
:param KeyColumnForMapping (string, optional): The column in the network to
use as the merge key
:param KeyColumnForMappingNetworkList (string, optional): The column in the
network to use as the merge key
:param keyColumnIndex (string, optional): The column that contains the key
values for this import. These values will be used to match with the
key values in the network.
:param newTableName (string, optional): The title of the new table
:param startLoadRow (string, optional): The first row of the input table to
load. This allows the skipping of headers that are not part of the
import.
:param TargetNetworkCollection (string, optional): The network collection t
o use for the table import
:param TargetNetworkList (string, optional): The list of networks into whic
h the table is imported
:param url (string): The URL of the file or resource that provides the tabl
e or network to be imported.
:param WhereImportTable (string, optional): Determines what network(s) the
imported table will be associated with (if any). A table can be impo
rted into a Network Collection, Selected networks or to an unassigne
d table. | [
"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",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L246-L311 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.list_tables | def list_tables(self,includePrivate=None,namespace=None,atype=None,verbose=None):
"""
Returns a list of the table SUIDs associated with the passed network parameter.
:param includePrivate (string, optional): A boolean value determining wheth
er to return private as well as public tables
:param namespace (string, optional): An optional argument to contrain outpu
t to a single namespace, or ALL
:param atype (string, optional): One of ''network'', ''node'', ''edge'', ''u
nattached'', ''all'', to constrain the type of table listed
:returns: list of the table SUIDs associated with the passed network parameter.
"""
PARAMS=set_param(['includePrivate','namespace','type'],\
[includePrivate,namespace,atype])
response=api(url=self.__url+"/list", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def list_tables(self,includePrivate=None,namespace=None,atype=None,verbose=None):
"""
Returns a list of the table SUIDs associated with the passed network parameter.
:param includePrivate (string, optional): A boolean value determining wheth
er to return private as well as public tables
:param namespace (string, optional): An optional argument to contrain outpu
t to a single namespace, or ALL
:param atype (string, optional): One of ''network'', ''node'', ''edge'', ''u
nattached'', ''all'', to constrain the type of table listed
:returns: list of the table SUIDs associated with the passed network parameter.
"""
PARAMS=set_param(['includePrivate','namespace','type'],\
[includePrivate,namespace,atype])
response=api(url=self.__url+"/list", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param includePrivate (string, optional): A boolean value determining wheth
er to return private as well as public tables
:param namespace (string, optional): An optional argument to contrain outpu
t to a single namespace, or ALL
:param atype (string, optional): One of ''network'', ''node'', ''edge'', ''u
nattached'', ''all'', to constrain the type of table listed
:returns: list of the table SUIDs associated with the passed network parameter. | [
"Returns",
"a",
"list",
"of",
"the",
"table",
"SUIDs",
"associated",
"with",
"the",
"passed",
"network",
"parameter",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L314-L329 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.list_columns | def list_columns(self,table=None,verbose=None):
"""
Returns the list of columns in the table.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:returns: list of columns in the table.
"""
PARAMS=set_param(['table'],[table])
response=api(url=self.__url+"/list columns", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def list_columns(self,table=None,verbose=None):
"""
Returns the list of columns in the table.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:returns: list of columns in the table.
"""
PARAMS=set_param(['table'],[table])
response=api(url=self.__url+"/list columns", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:returns: list of columns in the table. | [
"Returns",
"the",
"list",
"of",
"columns",
"in",
"the",
"table",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L332-L343 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.list_rows | def list_rows(self,rowList=None,table=None,verbose=None):
"""
Returns the list of primary keys for each of the rows in the specified table.
:param rowList (string, optional): Specifies a list of rows. The pattern CO
LUMN:VALUE sets this parameter to any rows that contain the specifie
d column value; if the COLUMN prefix is not used, the NAME column is
matched by default. A list of COLUMN:VALUE pairs of the format COLU
MN1:VALUE1,COLUMN2:VALUE2,... can be used to match multiple values.
This parameter can also be set to all to include all rows.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['rowList','table'],[rowList,table])
response=api(url=self.__url+"/list rows", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def list_rows(self,rowList=None,table=None,verbose=None):
"""
Returns the list of primary keys for each of the rows in the specified table.
:param rowList (string, optional): Specifies a list of rows. The pattern CO
LUMN:VALUE sets this parameter to any rows that contain the specifie
d column value; if the COLUMN prefix is not used, the NAME column is
matched by default. A list of COLUMN:VALUE pairs of the format COLU
MN1:VALUE1,COLUMN2:VALUE2,... can be used to match multiple values.
This parameter can also be set to all to include all rows.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['rowList','table'],[rowList,table])
response=api(url=self.__url+"/list rows", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param rowList (string, optional): Specifies a list of rows. The pattern CO
LUMN:VALUE sets this parameter to any rows that contain the specifie
d column value; if the COLUMN prefix is not used, the NAME column is
matched by default. A list of COLUMN:VALUE pairs of the format COLU
MN1:VALUE1,COLUMN2:VALUE2,... can be used to match multiple values.
This parameter can also be set to all to include all rows.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d. | [
"Returns",
"the",
"list",
"of",
"primary",
"keys",
"for",
"each",
"of",
"the",
"rows",
"in",
"the",
"specified",
"table",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L346-L362 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.merge | 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):
"""
Merge tables together joining around a designated key column. Depending
on the arguments, might merge into multiple local tables.
:param DataTypeTargetForNetworkCollection (string, optional): The collectio
n of networks where the merged table will reside
:param dataTypeTargetForNetworkList (string, optional):
:param mergeType (string, optional): A choice between ''Copy Columns'' and
''Link To Columns'' that determines if replicates are created
:param SourceMergeColumns (string, optional): A list of columns that will b
e brought into the merged table
:param SourceMergeKey (string, optional): The name of the columns that exis
ts in both tables and is used to correlate rows
:param SourceTable (string, optional): The name of the table used as the ba
se data in the merge
:param TargetKeyNetworkCollection (string, optional): The name of the prima
ry column about which the merge is made
:param TargetMergeKey (string, optional):
:param TargetNetworkCollection (string, optional): The group of networks th
at will be merged into the source table
:param TargetNetworkList (string, optional): The list of networks where the
merged table will be added
:param UnassignedTable (string, optional):
:param WhereMergeTable (string, optional): The destination path of the resu
ltant merged table. The choices are ''Network Collection'', ''Select
ed Networks'', or ''All Unassigned Tables''.
"""
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 | python | 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):
"""
Merge tables together joining around a designated key column. Depending
on the arguments, might merge into multiple local tables.
:param DataTypeTargetForNetworkCollection (string, optional): The collectio
n of networks where the merged table will reside
:param dataTypeTargetForNetworkList (string, optional):
:param mergeType (string, optional): A choice between ''Copy Columns'' and
''Link To Columns'' that determines if replicates are created
:param SourceMergeColumns (string, optional): A list of columns that will b
e brought into the merged table
:param SourceMergeKey (string, optional): The name of the columns that exis
ts in both tables and is used to correlate rows
:param SourceTable (string, optional): The name of the table used as the ba
se data in the merge
:param TargetKeyNetworkCollection (string, optional): The name of the prima
ry column about which the merge is made
:param TargetMergeKey (string, optional):
:param TargetNetworkCollection (string, optional): The group of networks th
at will be merged into the source table
:param TargetNetworkList (string, optional): The list of networks where the
merged table will be added
:param UnassignedTable (string, optional):
:param WhereMergeTable (string, optional): The destination path of the resu
ltant merged table. The choices are ''Network Collection'', ''Select
ed Networks'', or ''All Unassigned Tables''.
"""
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 | [
"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.
:param DataTypeTargetForNetworkCollection (string, optional): The collectio
n of networks where the merged table will reside
:param dataTypeTargetForNetworkList (string, optional):
:param mergeType (string, optional): A choice between ''Copy Columns'' and
''Link To Columns'' that determines if replicates are created
:param SourceMergeColumns (string, optional): A list of columns that will b
e brought into the merged table
:param SourceMergeKey (string, optional): The name of the columns that exis
ts in both tables and is used to correlate rows
:param SourceTable (string, optional): The name of the table used as the ba
se data in the merge
:param TargetKeyNetworkCollection (string, optional): The name of the prima
ry column about which the merge is made
:param TargetMergeKey (string, optional):
:param TargetNetworkCollection (string, optional): The group of networks th
at will be merged into the source table
:param TargetNetworkList (string, optional): The list of networks where the
merged table will be added
:param UnassignedTable (string, optional):
:param WhereMergeTable (string, optional): The destination path of the resu
ltant merged table. The choices are ''Network Collection'', ''Select
ed Networks'', or ''All Unassigned Tables''. | [
"Merge",
"tables",
"together",
"joining",
"around",
"a",
"designated",
"key",
"column",
".",
"Depending",
"on",
"the",
"arguments",
"might",
"merge",
"into",
"multiple",
"local",
"tables",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L365-L400 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.rename_column | def rename_column(self,columnName=None,newColumnName=None,table=None,verbose=None):
"""
Changes the name of a specified column in the table.
:param columnName (string): The name of the column that will be renamed.
:param newColumnName (string): The new name of the column.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['columnName','newColumnName','table'],[columnName,newColumnName,table])
response=api(url=self.__url+"/rename column", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def rename_column(self,columnName=None,newColumnName=None,table=None,verbose=None):
"""
Changes the name of a specified column in the table.
:param columnName (string): The name of the column that will be renamed.
:param newColumnName (string): The new name of the column.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
"""
PARAMS=set_param(['columnName','newColumnName','table'],[columnName,newColumnName,table])
response=api(url=self.__url+"/rename column", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param columnName (string): The name of the column that will be renamed.
:param newColumnName (string): The new name of the column.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d. | [
"Changes",
"the",
"name",
"of",
"a",
"specified",
"column",
"in",
"the",
"table",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L404-L416 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.set_title | def set_title(self,table=None,title=None,verbose=None):
"""
Changes the visible identifier of a single table.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param title (string, optional): The name of the table used in the current
network
"""
PARAMS=set_param(['table','title'],[table,title])
response=api(url=self.__url+"/set title", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def set_title(self,table=None,title=None,verbose=None):
"""
Changes the visible identifier of a single table.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param title (string, optional): The name of the table used in the current
network
"""
PARAMS=set_param(['table','title'],[table,title])
response=api(url=self.__url+"/set title", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param title (string, optional): The name of the table used in the current
network | [
"Changes",
"the",
"visible",
"identifier",
"of",
"a",
"single",
"table",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L420-L432 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.set_values | def set_values(self,columnName=None,rowList=None,table=None,value=None,verbose=None):
"""
Set all the values in the specified list of rows with a single value.
:param columnName (string, optional): Specifies the name of a column in the
table
:param rowList (string, optional): Specifies a list of rows. The pattern CO
LUMN:VALUE sets this parameter to any rows that contain the specifie
d column value; if the COLUMN prefix is not used, the NAME column is
matched by default. A list of COLUMN:VALUE pairs of the format COLU
MN1:VALUE1,COLUMN2:VALUE2,... can be used to match multiple values.
This parameter can also be set to all to include all rows.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param value (string, optional): The value to set the columns in the select
ed rows to. This should be a string value, which will be converted t
o the appropriate column type.
"""
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 | python | def set_values(self,columnName=None,rowList=None,table=None,value=None,verbose=None):
"""
Set all the values in the specified list of rows with a single value.
:param columnName (string, optional): Specifies the name of a column in the
table
:param rowList (string, optional): Specifies a list of rows. The pattern CO
LUMN:VALUE sets this parameter to any rows that contain the specifie
d column value; if the COLUMN prefix is not used, the NAME column is
matched by default. A list of COLUMN:VALUE pairs of the format COLU
MN1:VALUE1,COLUMN2:VALUE2,... can be used to match multiple values.
This parameter can also be set to all to include all rows.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param value (string, optional): The value to set the columns in the select
ed rows to. This should be a string value, which will be converted t
o the appropriate column type.
"""
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 | [
"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.
:param columnName (string, optional): Specifies the name of a column in the
table
:param rowList (string, optional): Specifies a list of rows. The pattern CO
LUMN:VALUE sets this parameter to any rows that contain the specifie
d column value; if the COLUMN prefix is not used, the NAME column is
matched by default. A list of COLUMN:VALUE pairs of the format COLU
MN1:VALUE1,COLUMN2:VALUE2,... can be used to match multiple values.
This parameter can also be set to all to include all rows.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:param value (string, optional): The value to set the columns in the select
ed rows to. This should be a string value, which will be converted t
o the appropriate column type. | [
"Set",
"all",
"the",
"values",
"in",
"the",
"specified",
"list",
"of",
"rows",
"with",
"a",
"single",
"value",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L436-L457 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.getTable | def getTable(self, columns=None, table=None, network = "current", namespace='default', verbose=VERBOSE):
"""
Gets tables from cytoscape.
:param table: table to retrieve eg. node
:param columns: columns to retrieve in list format
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param namespace (string, optional): Node, Edge, and Network objects support
the default, local, and hidden namespaces. Root networks also support the
shared namespace. Custom namespaces may be specified by Apps.
:returns: a pandas dataframe
"""
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 | python | def getTable(self, columns=None, table=None, network = "current", namespace='default', verbose=VERBOSE):
"""
Gets tables from cytoscape.
:param table: table to retrieve eg. node
:param columns: columns to retrieve in list format
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param namespace (string, optional): Node, Edge, and Network objects support
the default, local, and hidden namespaces. Root networks also support the
shared namespace. Custom namespaces may be specified by Apps.
:returns: a pandas dataframe
"""
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 | [
"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.
:param table: table to retrieve eg. node
:param columns: columns to retrieve in list format
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param namespace (string, optional): Node, Edge, and Network objects support
the default, local, and hidden namespaces. Root networks also support the
shared namespace. Custom namespaces may be specified by Apps.
:returns: a pandas dataframe | [
"Gets",
"tables",
"from",
"cytoscape",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L459-L515 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.loadTableData | def loadTableData(self, df, df_key='index',table="node", table_key_column = "name", \
network="current",namespace="default",verbose=False):
"""
Loads tables into cytoscape.
:param df: a pandas dataframe to load
:param df_key: key column in df, default="index"
:param table: target table, default="node"
:param table_key_column: table key column, default="name"
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param namespace (string, optional): Node, Edge, and Network objects support
the default, local, and hidden namespaces. Root networks also support the
shared namespace. Custom namespaces may be specified by Apps.
:param verbose: print more information
:returns: output of put request
"""
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 | python | def loadTableData(self, df, df_key='index',table="node", table_key_column = "name", \
network="current",namespace="default",verbose=False):
"""
Loads tables into cytoscape.
:param df: a pandas dataframe to load
:param df_key: key column in df, default="index"
:param table: target table, default="node"
:param table_key_column: table key column, default="name"
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param namespace (string, optional): Node, Edge, and Network objects support
the default, local, and hidden namespaces. Root networks also support the
shared namespace. Custom namespaces may be specified by Apps.
:param verbose: print more information
:returns: output of put request
"""
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 | [
"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.
:param df: a pandas dataframe to load
:param df_key: key column in df, default="index"
:param table: target table, default="node"
:param table_key_column: table key column, default="name"
:param network (string, optional): Specifies a network by name, or by
SUID if the prefix SUID: is used. The keyword CURRENT, or a blank
value can also be used to specify the current network.
:param namespace (string, optional): Node, Edge, and Network objects support
the default, local, and hidden namespaces. Root networks also support the
shared namespace. Custom namespaces may be specified by Apps.
:param verbose: print more information
:returns: output of put request | [
"Loads",
"tables",
"into",
"cytoscape",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L517-L588 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | table.getTableCount | def getTableCount(verbose=None):
"""
Returns the number of global tables.
:param verbose: print more
:returns: 200: successful operation
"""
response=api(url=self.url+'tables/count', method="GET", verbose=verbose, parse_params=False)
return response | python | def getTableCount(verbose=None):
"""
Returns the number of global tables.
:param verbose: print more
:returns: 200: successful operation
"""
response=api(url=self.url+'tables/count', method="GET", verbose=verbose, parse_params=False)
return response | [
"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.
:param verbose: print more
:returns: 200: successful operation | [
"Returns",
"the",
"number",
"of",
"global",
"tables",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L590-L600 | train |
cytoscape/py2cytoscape | py2cytoscape/data/base_view.py | BaseView.set_value | def set_value(self, visual_property, value):
"""Set a single Visual Property Value
:param visual_property: Visual Property ID
:param value: New value for the VP
:return: None
"""
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) | python | def set_value(self, visual_property, value):
"""Set a single Visual Property Value
:param visual_property: Visual Property ID
:param value: New value for the VP
:return: None
"""
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) | [
"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
:param visual_property: Visual Property ID
:param value: New value for the VP
:return: None | [
"Set",
"a",
"single",
"Visual",
"Property",
"Value"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/data/base_view.py#L41-L57 | train |
cytoscape/py2cytoscape | py2cytoscape/data/base_view.py | BaseView.set_values | def set_values(self, values):
"""
Set multiple Visual properties at once.
:param values:
:return:
"""
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) | python | def set_values(self, values):
"""
Set multiple Visual properties at once.
:param values:
:return:
"""
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) | [
"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.
:param values:
:return: | [
"Set",
"multiple",
"Visual",
"properties",
"at",
"once",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/data/base_view.py#L59-L77 | train |
cytoscape/py2cytoscape | py2cytoscape/data/base_view.py | BaseView.get_value | def get_value(self, visual_property):
"""Get a value for the Visual Property
:param visual_property:
:return:
"""
res = requests.get(self.url + '/' + visual_property)
return res.json()['value'] | python | def get_value(self, visual_property):
"""Get a value for the Visual Property
:param visual_property:
:return:
"""
res = requests.get(self.url + '/' + visual_property)
return res.json()['value'] | [
"def",
"get_value",
"(",
"self",
",",
"visual_property",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
"+",
"'/'",
"+",
"visual_property",
")",
"return",
"res",
".",
"json",
"(",
")",
"[",
"'value'",
"]"
] | Get a value for the Visual Property
:param visual_property:
:return: | [
"Get",
"a",
"value",
"for",
"the",
"Visual",
"Property"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/data/base_view.py#L79-L86 | train |
cytoscape/py2cytoscape | py2cytoscape/data/base_view.py | BaseView.get_values | def get_values(self):
"""Get all visual property values for the object
:return: dictionary of values (VP ID - value)
"""
results = requests.get(self.url).json()
values = {}
for entry in results:
values[entry['visualProperty']] = entry['value']
return values | python | def get_values(self):
"""Get all visual property values for the object
:return: dictionary of values (VP ID - value)
"""
results = requests.get(self.url).json()
values = {}
for entry in results:
values[entry['visualProperty']] = entry['value']
return values | [
"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
:return: dictionary of values (VP ID - value) | [
"Get",
"all",
"visual",
"property",
"values",
"for",
"the",
"object"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/data/base_view.py#L88-L98 | train |
cytoscape/py2cytoscape | py2cytoscape/data/network_view.py | CyNetworkView.update_network_view | def update_network_view(self, visual_property=None, value=None):
"""
Updates single value for Network-related VP.
:param visual_property:
:param value:
:return:
"""
new_value = [
{
"visualProperty": visual_property,
"value": value
}
]
res = requests.put(self.__url + '/network',
data=json.dumps(new_value),
headers=HEADERS)
check_response(res) | python | def update_network_view(self, visual_property=None, value=None):
"""
Updates single value for Network-related VP.
:param visual_property:
:param value:
:return:
"""
new_value = [
{
"visualProperty": visual_property,
"value": value
}
]
res = requests.put(self.__url + '/network',
data=json.dumps(new_value),
headers=HEADERS)
check_response(res) | [
"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.
:param visual_property:
:param value:
:return: | [
"Updates",
"single",
"value",
"for",
"Network",
"-",
"related",
"VP",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/data/network_view.py#L153-L171 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/view.py | view.export | def export(self, Height=None, options=None, outputFile=None, Resolution=None,\
Units=None, Width=None, Zoom=None, view="current", verbose=False):
"""
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.
:param Height (string, optional): The height of the exported image. Valid
only for bitmap formats, such as PNG and JPEG.
:param options (string, optional): The format of the output file. =
['JPEG (*.jpeg, *.jpg)', 'PDF (*.pdf)', 'PNG (*.png)', 'PostScript (*.ps)',
'SVG (*.svg)']
:param OutputFile (string, optional): The path name of the file where
the view must be saved to. By default, the view's title is used as
the file name.
:param Resolution (string, optional): The resolution of the exported
image, in DPI. Valid only for bitmap formats, when the selected width
and height 'units' is inches. The possible values are: 72 (default),
100, 150, 300, 600. = ['72', '100', '150', '300', '600']
:param Units (string, optional): The units for the 'width' and 'height'
values. Valid only for bitmap formats, such as PNG and JPEG. The
possible values are: pixels (default), inches. = ['pixels', 'inches']
:param Width (string, optional): The width of the exported image. Valid
only for bitmap formats, such as PNG and JPEG.
:param Zoom (string, optional): The zoom value to proportionally scale
the image. The default value is 100.0. Valid only for bitmap formats,
such as PNG and JPEG
:param verbose: print more
:returns: path to the saved file
"""
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 | python | def export(self, Height=None, options=None, outputFile=None, Resolution=None,\
Units=None, Width=None, Zoom=None, view="current", verbose=False):
"""
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.
:param Height (string, optional): The height of the exported image. Valid
only for bitmap formats, such as PNG and JPEG.
:param options (string, optional): The format of the output file. =
['JPEG (*.jpeg, *.jpg)', 'PDF (*.pdf)', 'PNG (*.png)', 'PostScript (*.ps)',
'SVG (*.svg)']
:param OutputFile (string, optional): The path name of the file where
the view must be saved to. By default, the view's title is used as
the file name.
:param Resolution (string, optional): The resolution of the exported
image, in DPI. Valid only for bitmap formats, when the selected width
and height 'units' is inches. The possible values are: 72 (default),
100, 150, 300, 600. = ['72', '100', '150', '300', '600']
:param Units (string, optional): The units for the 'width' and 'height'
values. Valid only for bitmap formats, such as PNG and JPEG. The
possible values are: pixels (default), inches. = ['pixels', 'inches']
:param Width (string, optional): The width of the exported image. Valid
only for bitmap formats, such as PNG and JPEG.
:param Zoom (string, optional): The zoom value to proportionally scale
the image. The default value is 100.0. Valid only for bitmap formats,
such as PNG and JPEG
:param verbose: print more
:returns: path to the saved file
"""
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 | [
"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.
:param Height (string, optional): The height of the exported image. Valid
only for bitmap formats, such as PNG and JPEG.
:param options (string, optional): The format of the output file. =
['JPEG (*.jpeg, *.jpg)', 'PDF (*.pdf)', 'PNG (*.png)', 'PostScript (*.ps)',
'SVG (*.svg)']
:param OutputFile (string, optional): The path name of the file where
the view must be saved to. By default, the view's title is used as
the file name.
:param Resolution (string, optional): The resolution of the exported
image, in DPI. Valid only for bitmap formats, when the selected width
and height 'units' is inches. The possible values are: 72 (default),
100, 150, 300, 600. = ['72', '100', '150', '300', '600']
:param Units (string, optional): The units for the 'width' and 'height'
values. Valid only for bitmap formats, such as PNG and JPEG. The
possible values are: pixels (default), inches. = ['pixels', 'inches']
:param Width (string, optional): The width of the exported image. Valid
only for bitmap formats, such as PNG and JPEG.
:param Zoom (string, optional): The zoom value to proportionally scale
the image. The default value is 100.0. Valid only for bitmap formats,
such as PNG and JPEG
:param verbose: print more
:returns: path to the saved file | [
"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",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/view.py#L46-L85 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/view.py | view.fit_content | def fit_content(self, verbose=False):
"""
Zooms out the current view in order to display all of its elements.
:param verbose: print more
"""
PARAMS={}
response=api(url=self.__url+"/fit content", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def fit_content(self, verbose=False):
"""
Zooms out the current view in order to display all of its elements.
:param verbose: print more
"""
PARAMS={}
response=api(url=self.__url+"/fit content", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param verbose: print more | [
"Zooms",
"out",
"the",
"current",
"view",
"in",
"order",
"to",
"display",
"all",
"of",
"its",
"elements",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/view.py#L87-L96 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/view.py | view.get_current | def get_current(self, layout=None, network=None, verbose=False):
"""
Returns the current view or null if there is none.
:param verbose: print more
:returns: current view or null if there is none
"""
PARAMS={}
response=api(url=self.__url+"/get_current", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | python | def get_current(self, layout=None, network=None, verbose=False):
"""
Returns the current view or null if there is none.
:param verbose: print more
:returns: current view or null if there is none
"""
PARAMS={}
response=api(url=self.__url+"/get_current", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"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.
:param verbose: print more
:returns: current view or null if there is none | [
"Returns",
"the",
"current",
"view",
"or",
"null",
"if",
"there",
"is",
"none",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/view.py#L110-L120 | train |
cytoscape/py2cytoscape | py2cytoscape/data/style.py | Style.update_defaults | def update_defaults(self, prop_value_dict):
"""
Updates the value of one or more visual properties.
:param prop_value_dict: Dictionary containing, for each visual property,
the new value to use.
"""
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) | python | def update_defaults(self, prop_value_dict):
"""
Updates the value of one or more visual properties.
:param prop_value_dict: Dictionary containing, for each visual property,
the new value to use.
"""
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) | [
"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.
:param prop_value_dict: Dictionary containing, for each visual property,
the new value to use. | [
"Updates",
"the",
"value",
"of",
"one",
"or",
"more",
"visual",
"properties",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/data/style.py#L112-L129 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/cyrest.py | cyclient.status | def status(self, verbose=False):
"""
Checks the status of your CyREST server.
"""
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!') | python | def status(self, verbose=False):
"""
Checks the status of your CyREST server.
"""
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!') | [
"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. | [
"Checks",
"the",
"status",
"of",
"your",
"CyREST",
"server",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/cyrest.py#L67-L76 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/cyrest.py | cyclient.version | def version(self, verbose=False):
"""
Checks Cytoscape version
"""
response=api(url=self.__url+"version",method="H", verbose=verbose)
response=json.loads(response)
for k in response.keys():
print(k, response[k]) | python | def version(self, verbose=False):
"""
Checks Cytoscape version
"""
response=api(url=self.__url+"version",method="H", verbose=verbose)
response=json.loads(response)
for k in response.keys():
print(k, response[k]) | [
"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 | [
"Checks",
"Cytoscape",
"version"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/cyrest.py#L84-L91 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/idmapper.py | idmapper.map_column | def map_column(self, only_use_one=None, source_column=None, species=None, target_selection= None, verbose=False):
"""
Uses the BridgeDB service to look up analogous identifiers from a wide
selection of other databases
:param only_use_one (string, optional): When multiple identifiers can be
mapped from a single term, this forces a singular result
:param source_column (string): Specifies the column nmae where the
source identifiers are located = ['']
:param source_selection (string): Specifies the database describing
the existing identifiers = ['']
:param species (string, optional): The combined common or latin name of
the species to which the identifiers apply = ['Human (Homo sapiens)',
'Mouse (Mus musculus)', 'Rat (Rattus norvegicus)', 'Frog (Xenopus tropicalis)',
'Zebra fish (Danio rerio)', 'Fruit fly (Drosophila melanogaster)',
'Mosquito (Anopheles gambiae)', 'Arabidopsis thaliana (Arabidopsis thaliana)',
'Yeast (Saccharomyces cerevisiae)', 'E. coli (Escherichia coli)',
'Tuberculosis (Mycobacterium tuberculosis)', 'Worm (Caenorhabditis elegans)']
:param target_selection (string): Specifies the database identifiers to be looked up = ['']
:param verbose: print more
:returns: eg. { "new column": "SGD " }
"""
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 | python | def map_column(self, only_use_one=None, source_column=None, species=None, target_selection= None, verbose=False):
"""
Uses the BridgeDB service to look up analogous identifiers from a wide
selection of other databases
:param only_use_one (string, optional): When multiple identifiers can be
mapped from a single term, this forces a singular result
:param source_column (string): Specifies the column nmae where the
source identifiers are located = ['']
:param source_selection (string): Specifies the database describing
the existing identifiers = ['']
:param species (string, optional): The combined common or latin name of
the species to which the identifiers apply = ['Human (Homo sapiens)',
'Mouse (Mus musculus)', 'Rat (Rattus norvegicus)', 'Frog (Xenopus tropicalis)',
'Zebra fish (Danio rerio)', 'Fruit fly (Drosophila melanogaster)',
'Mosquito (Anopheles gambiae)', 'Arabidopsis thaliana (Arabidopsis thaliana)',
'Yeast (Saccharomyces cerevisiae)', 'E. coli (Escherichia coli)',
'Tuberculosis (Mycobacterium tuberculosis)', 'Worm (Caenorhabditis elegans)']
:param target_selection (string): Specifies the database identifiers to be looked up = ['']
:param verbose: print more
:returns: eg. { "new column": "SGD " }
"""
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 | [
"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
:param only_use_one (string, optional): When multiple identifiers can be
mapped from a single term, this forces a singular result
:param source_column (string): Specifies the column nmae where the
source identifiers are located = ['']
:param source_selection (string): Specifies the database describing
the existing identifiers = ['']
:param species (string, optional): The combined common or latin name of
the species to which the identifiers apply = ['Human (Homo sapiens)',
'Mouse (Mus musculus)', 'Rat (Rattus norvegicus)', 'Frog (Xenopus tropicalis)',
'Zebra fish (Danio rerio)', 'Fruit fly (Drosophila melanogaster)',
'Mosquito (Anopheles gambiae)', 'Arabidopsis thaliana (Arabidopsis thaliana)',
'Yeast (Saccharomyces cerevisiae)', 'E. coli (Escherichia coli)',
'Tuberculosis (Mycobacterium tuberculosis)', 'Worm (Caenorhabditis elegans)']
:param target_selection (string): Specifies the database identifiers to be looked up = ['']
:param verbose: print more
:returns: eg. { "new column": "SGD " } | [
"Uses",
"the",
"BridgeDB",
"service",
"to",
"look",
"up",
"analogous",
"identifiers",
"from",
"a",
"wide",
"selection",
"of",
"other",
"databases"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/idmapper.py#L13-L38 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/command.py | command.echo | def echo(self, variableName, verbose=False):
"""
The echo command will display the value of the variable specified by the
variableName argument, or all variables if variableName is not provided.
:param variableName: The name of the variable or '*' to display the value of all variables.
:param verbose: print more
"""
PARAMS={"variableName":variableName}
response=api(url=self.__url+"/echo", PARAMS=PARAMS, verbose=verbose)
return response | python | def echo(self, variableName, verbose=False):
"""
The echo command will display the value of the variable specified by the
variableName argument, or all variables if variableName is not provided.
:param variableName: The name of the variable or '*' to display the value of all variables.
:param verbose: print more
"""
PARAMS={"variableName":variableName}
response=api(url=self.__url+"/echo", PARAMS=PARAMS, verbose=verbose)
return response | [
"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.
:param variableName: The name of the variable or '*' to display the value of all variables.
:param verbose: print more | [
"The",
"echo",
"command",
"will",
"display",
"the",
"value",
"of",
"the",
"variable",
"specified",
"by",
"the",
"variableName",
"argument",
"or",
"all",
"variables",
"if",
"variableName",
"is",
"not",
"provided",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/command.py#L13-L23 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/command.py | command.open_dialog | def open_dialog(self, verbose=False):
"""
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.
:param verbose: print more
"""
response=api(url=self.__url+"/open dialog", verbose=verbose)
return response | python | def open_dialog(self, verbose=False):
"""
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.
:param verbose: print more
"""
response=api(url=self.__url+"/open dialog", verbose=verbose)
return response | [
"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.
:param verbose: print more | [
"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",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/command.py#L25-L34 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/command.py | command.pause | def pause(self, message=None, verbose=False):
"""
The pause command displays a dialog with the text provided in the
message argument and waits for the user to click OK
:param message: a message to display. default=None
:param verbose: print more
"""
PARAMS=set_param(["message"],[message])
response=api(url=self.__url+"/pause", PARAMS=PARAMS, verbose=verbose)
return response | python | def pause(self, message=None, verbose=False):
"""
The pause command displays a dialog with the text provided in the
message argument and waits for the user to click OK
:param message: a message to display. default=None
:param verbose: print more
"""
PARAMS=set_param(["message"],[message])
response=api(url=self.__url+"/pause", PARAMS=PARAMS, verbose=verbose)
return response | [
"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
:param message: a message to display. default=None
:param verbose: print more | [
"The",
"pause",
"command",
"displays",
"a",
"dialog",
"with",
"the",
"text",
"provided",
"in",
"the",
"message",
"argument",
"and",
"waits",
"for",
"the",
"user",
"to",
"click",
"OK"
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/command.py#L37-L48 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/command.py | command.quit | def quit(self,verbose=False):
"""
This command causes Cytoscape to exit. It is typically used at the end
of a script file.
:param verbose: print more
"""
response=api(url=self.__url+"/quit", verbose=verbose)
return response | python | def quit(self,verbose=False):
"""
This command causes Cytoscape to exit. It is typically used at the end
of a script file.
:param verbose: print more
"""
response=api(url=self.__url+"/quit", verbose=verbose)
return response | [
"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.
:param verbose: print more | [
"This",
"command",
"causes",
"Cytoscape",
"to",
"exit",
".",
"It",
"is",
"typically",
"used",
"at",
"the",
"end",
"of",
"a",
"script",
"file",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/command.py#L51-L59 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/command.py | command.run | def run(self,script_file,args=None,verbose=False):
"""
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.
:param script_file: file to run
:param args: enter the script arguments as key:value pairs separated by
commas. eg. "arg1:value1,arg2:value2"
:param verbose: print more
"""
PARAMS=set_param(["file","args"],[script_file,args])
response=api(url=self.__url+"/run", PARAMS=PARAMS, verbose=verbose)
return response | python | def run(self,script_file,args=None,verbose=False):
"""
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.
:param script_file: file to run
:param args: enter the script arguments as key:value pairs separated by
commas. eg. "arg1:value1,arg2:value2"
:param verbose: print more
"""
PARAMS=set_param(["file","args"],[script_file,args])
response=api(url=self.__url+"/run", PARAMS=PARAMS, verbose=verbose)
return response | [
"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.
:param script_file: file to run
:param args: enter the script arguments as key:value pairs separated by
commas. eg. "arg1:value1,arg2:value2"
:param verbose: print more | [
"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",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/command.py#L61-L75 | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/command.py | command.sleep | def sleep(self,duration,verbose=False):
"""
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.
:param duration: enter the time in seconds to sleep
:param verbose: print more
"""
PARAMS={"duration":str(duration)}
response=api(url=self.__url+"/sleep", PARAMS=PARAMS, verbose=verbose)
return response | python | def sleep(self,duration,verbose=False):
"""
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.
:param duration: enter the time in seconds to sleep
:param verbose: print more
"""
PARAMS={"duration":str(duration)}
response=api(url=self.__url+"/sleep", PARAMS=PARAMS, verbose=verbose)
return response | [
"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.
:param duration: enter the time in seconds to sleep
:param verbose: print more | [
"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",
"."
] | dd34de8d028f512314d0057168df7fef7c5d5195 | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/command.py#L77-L87 | train |
ofw/curlify | curlify.py | to_curl | def to_curl(request, compressed=False, verify=True):
"""
Returns string with curl command by provided request object
Parameters
----------
compressed : bool
If `True` then `--compressed` argument will be added to result
"""
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) | python | def to_curl(request, compressed=False, verify=True):
"""
Returns string with curl command by provided request object
Parameters
----------
compressed : bool
If `True` then `--compressed` argument will be added to result
"""
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) | [
"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
Parameters
----------
compressed : bool
If `True` then `--compressed` argument will be added to result | [
"Returns",
"string",
"with",
"curl",
"command",
"by",
"provided",
"request",
"object"
] | 5a464218431f979ac78d089682d36860b57420ce | https://github.com/ofw/curlify/blob/5a464218431f979ac78d089682d36860b57420ce/curlify.py#L4-L42 | train |
rq/Flask-RQ2 | src/flask_rq2/cli.py | shared_options | 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,
} | python | 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,
} | [
"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. | [
"Default",
"class",
"options",
"to",
"pass",
"to",
"the",
"CLI",
"commands",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L35-L44 | train |
rq/Flask-RQ2 | src/flask_rq2/cli.py | empty | 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)
) | python | 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)
) | [
"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. | [
"Empty",
"given",
"queues",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L66-L73 | train |
rq/Flask-RQ2 | src/flask_rq2/cli.py | requeue | 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)
) | python | 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)
) | [
"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. | [
"Requeue",
"failed",
"jobs",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L79-L86 | train |
rq/Flask-RQ2 | src/flask_rq2/cli.py | info | 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,
**shared_options(rq)
) | python | 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,
**shared_options(rq)
) | [
"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. | [
"RQ",
"command",
"-",
"line",
"monitor",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L100-L113 | train |
rq/Flask-RQ2 | src/flask_rq2/cli.py | worker | 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,
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)
) | python | 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,
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)
) | [
"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. | [
"Starts",
"an",
"RQ",
"worker",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L136-L155 | train |
rq/Flask-RQ2 | src/flask_rq2/cli.py | suspend | def suspend(rq, ctx, duration):
"Suspends all workers."
ctx.invoke(
rq_cli.suspend,
duration=duration,
**shared_options(rq)
) | python | def suspend(rq, ctx, duration):
"Suspends all workers."
ctx.invoke(
rq_cli.suspend,
duration=duration,
**shared_options(rq)
) | [
"def",
"suspend",
"(",
"rq",
",",
"ctx",
",",
"duration",
")",
":",
"ctx",
".",
"invoke",
"(",
"rq_cli",
".",
"suspend",
",",
"duration",
"=",
"duration",
",",
"*",
"*",
"shared_options",
"(",
"rq",
")",
")"
] | Suspends all workers. | [
"Suspends",
"all",
"workers",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L162-L168 | train |
rq/Flask-RQ2 | src/flask_rq2/cli.py | scheduler | 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'
else:
level = 'INFO'
setup_loghandlers(level)
scheduler.run(burst=burst) | python | 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'
else:
level = 'INFO'
setup_loghandlers(level)
scheduler.run(burst=burst) | [
"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. | [
"Periodically",
"checks",
"for",
"scheduled",
"jobs",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L193-L204 | train |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.init_cli | def init_cli(self, app):
"""
Initialize the Flask CLI support in case it was enabled for the
app.
Works with both Flask>=1.0's CLI support as well as the backport
in the Flask-CLI package for Flask<1.0.
"""
# 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) | python | def init_cli(self, app):
"""
Initialize the Flask CLI support in case it was enabled for the
app.
Works with both Flask>=1.0's CLI support as well as the backport
in the Flask-CLI package for Flask<1.0.
"""
# 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) | [
"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.
Works with both Flask>=1.0's CLI support as well as the backport
in the Flask-CLI package for Flask<1.0. | [
"Initialize",
"the",
"Flask",
"CLI",
"support",
"in",
"case",
"it",
"was",
"enabled",
"for",
"the",
"app",
"."
] | 58eedf6f0cd7bcde4ccd787074762ea08f531337 | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L195-L208 | train |
ionelmc/python-remote-pdb | src/remote_pdb.py | set_trace | def set_trace(host=None, port=None, patch_stdstreams=False):
"""
Opens a remote PDB on first available port.
"""
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) | python | def set_trace(host=None, port=None, patch_stdstreams=False):
"""
Opens a remote PDB on first available port.
"""
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) | [
"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. | [
"Opens",
"a",
"remote",
"PDB",
"on",
"first",
"available",
"port",
"."
] | 152b4af3b8da282bbba1fc6b62f85d5cdf70be6e | https://github.com/ionelmc/python-remote-pdb/blob/152b4af3b8da282bbba1fc6b62f85d5cdf70be6e/src/remote_pdb.py#L121-L130 | train |
nschloe/optimesh | optimesh/cvt/lloyd.py | quasi_newton_uniform_lloyd | def quasi_newton_uniform_lloyd(points, cells, *args, omega=1.0, **kwargs):
"""Relaxed Lloyd's algorithm. omega=1 leads to Lloyd's algorithm, overrelaxation
omega=2 gives good results. Check out
Xiao Xiao,
Over-Relaxation Lloyd Method For Computing Centroidal Voronoi Tessellations,
Master's thesis,
<https://scholarcommons.sc.edu/etd/295/>.
Everything above omega=2 can lead to flickering, i.e., rapidly alternating updates
and bad meshes.
"""
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"] | python | def quasi_newton_uniform_lloyd(points, cells, *args, omega=1.0, **kwargs):
"""Relaxed Lloyd's algorithm. omega=1 leads to Lloyd's algorithm, overrelaxation
omega=2 gives good results. Check out
Xiao Xiao,
Over-Relaxation Lloyd Method For Computing Centroidal Voronoi Tessellations,
Master's thesis,
<https://scholarcommons.sc.edu/etd/295/>.
Everything above omega=2 can lead to flickering, i.e., rapidly alternating updates
and bad meshes.
"""
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"] | [
"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
Xiao Xiao,
Over-Relaxation Lloyd Method For Computing Centroidal Voronoi Tessellations,
Master's thesis,
<https://scholarcommons.sc.edu/etd/295/>.
Everything above omega=2 can lead to flickering, i.e., rapidly alternating updates
and bad meshes. | [
"Relaxed",
"Lloyd",
"s",
"algorithm",
".",
"omega",
"=",
"1",
"leads",
"to",
"Lloyd",
"s",
"algorithm",
"overrelaxation",
"omega",
"=",
"2",
"gives",
"good",
"results",
".",
"Check",
"out"
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/cvt/lloyd.py#L8-L46 | train |
nschloe/optimesh | optimesh/cpt.py | _energy_uniform_per_node | def _energy_uniform_per_node(X, cells):
"""The CPT mesh energy is defined as
sum_i E_i,
E_i = 1/(d+1) * sum int_{omega_i} ||x - x_i||^2 rho(x) dx,
see Chen-Holst. This method gives the E_i and assumes uniform density, rho(x) = 1.
"""
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) | python | def _energy_uniform_per_node(X, cells):
"""The CPT mesh energy is defined as
sum_i E_i,
E_i = 1/(d+1) * sum int_{omega_i} ||x - x_i||^2 rho(x) dx,
see Chen-Holst. This method gives the E_i and assumes uniform density, rho(x) = 1.
"""
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) | [
"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
sum_i E_i,
E_i = 1/(d+1) * sum int_{omega_i} ||x - x_i||^2 rho(x) dx,
see Chen-Holst. This method gives the E_i and assumes uniform density, rho(x) = 1. | [
"The",
"CPT",
"mesh",
"energy",
"is",
"defined",
"as"
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/cpt.py#L91-L116 | train |
nschloe/optimesh | optimesh/cpt.py | jac_uniform | def jac_uniform(X, cells):
"""The approximated Jacobian is
partial_i E = 2/(d+1) (x_i int_{omega_i} rho(x) dx - int_{omega_i} x rho(x) dx)
= 2/(d+1) sum_{tau_j in omega_i} (x_i - b_{j, rho}) int_{tau_j} rho,
see Chen-Holst. This method here assumes uniform density, rho(x) = 1, such that
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|
with b_j being the ordinary barycenter.
"""
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 | python | def jac_uniform(X, cells):
"""The approximated Jacobian is
partial_i E = 2/(d+1) (x_i int_{omega_i} rho(x) dx - int_{omega_i} x rho(x) dx)
= 2/(d+1) sum_{tau_j in omega_i} (x_i - b_{j, rho}) int_{tau_j} rho,
see Chen-Holst. This method here assumes uniform density, rho(x) = 1, such that
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|
with b_j being the ordinary barycenter.
"""
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 | [
"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
partial_i E = 2/(d+1) (x_i int_{omega_i} rho(x) dx - int_{omega_i} x rho(x) dx)
= 2/(d+1) sum_{tau_j in omega_i} (x_i - b_{j, rho}) int_{tau_j} rho,
see Chen-Holst. This method here assumes uniform density, rho(x) = 1, such that
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|
with b_j being the ordinary barycenter. | [
"The",
"approximated",
"Jacobian",
"is"
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/cpt.py#L123-L147 | train |
nschloe/optimesh | optimesh/cpt.py | solve_hessian_approx_uniform | def solve_hessian_approx_uniform(X, cells, rhs):
"""As discussed above, the approximated Jacobian is
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
To get the Hessian, we have to form its derivative. As a simplifications,
let us assume again that |tau_j| is independent of the node positions. Then we get
partial_ii E = 2/(d+1) |omega_i| - 2/(d+1)**2 |omega_i|,
partial_ij E = -2/(d+1)**2 |tau_j|.
The terms with (d+1)**2 are from the barycenter in `partial_i E`. It turns out from
numerical experiments that the negative term in `partial_ii E` is detrimental to the
convergence. Hence, this approximated Hessian solver only considers the off-diagonal
contributions from the barycentric terms.
"""
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 | python | def solve_hessian_approx_uniform(X, cells, rhs):
"""As discussed above, the approximated Jacobian is
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
To get the Hessian, we have to form its derivative. As a simplifications,
let us assume again that |tau_j| is independent of the node positions. Then we get
partial_ii E = 2/(d+1) |omega_i| - 2/(d+1)**2 |omega_i|,
partial_ij E = -2/(d+1)**2 |tau_j|.
The terms with (d+1)**2 are from the barycenter in `partial_i E`. It turns out from
numerical experiments that the negative term in `partial_ii E` is detrimental to the
convergence. Hence, this approximated Hessian solver only considers the off-diagonal
contributions from the barycentric terms.
"""
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 | [
"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
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
To get the Hessian, we have to form its derivative. As a simplifications,
let us assume again that |tau_j| is independent of the node positions. Then we get
partial_ii E = 2/(d+1) |omega_i| - 2/(d+1)**2 |omega_i|,
partial_ij E = -2/(d+1)**2 |tau_j|.
The terms with (d+1)**2 are from the barycenter in `partial_i E`. It turns out from
numerical experiments that the negative term in `partial_ii E` is detrimental to the
convergence. Hence, this approximated Hessian solver only considers the off-diagonal
contributions from the barycentric terms. | [
"As",
"discussed",
"above",
"the",
"approximated",
"Jacobian",
"is"
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/cpt.py#L150-L227 | train |
nschloe/optimesh | optimesh/cpt.py | quasi_newton_uniform | def quasi_newton_uniform(points, cells, *args, **kwargs):
"""Like linear_solve above, but assuming rho==1. Note that the energy gradient
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) \\int_{tau_j} rho
becomes
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
Because of the dependence of |tau_j| on the point coordinates, this is a nonlinear
problem.
This method makes the simplifying assumption that |tau_j| does in fact _not_ depend
on the point coordinates. With this, one still only needs to solve a linear system.
"""
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"] | python | def quasi_newton_uniform(points, cells, *args, **kwargs):
"""Like linear_solve above, but assuming rho==1. Note that the energy gradient
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) \\int_{tau_j} rho
becomes
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
Because of the dependence of |tau_j| on the point coordinates, this is a nonlinear
problem.
This method makes the simplifying assumption that |tau_j| does in fact _not_ depend
on the point coordinates. With this, one still only needs to solve a linear system.
"""
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"] | [
"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
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) \\int_{tau_j} rho
becomes
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
Because of the dependence of |tau_j| on the point coordinates, this is a nonlinear
problem.
This method makes the simplifying assumption that |tau_j| does in fact _not_ depend
on the point coordinates. With this, one still only needs to solve a linear system. | [
"Like",
"linear_solve",
"above",
"but",
"assuming",
"rho",
"==",
"1",
".",
"Note",
"that",
"the",
"energy",
"gradient"
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/cpt.py#L230-L257 | train |
nschloe/optimesh | optimesh/laplace.py | fixed_point | def fixed_point(points, cells, *args, **kwargs):
"""Perform k steps of Laplacian smoothing to the mesh, i.e., moving each
interior vertex to the arithmetic average of its neighboring points.
"""
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"] | python | def fixed_point(points, cells, *args, **kwargs):
"""Perform k steps of Laplacian smoothing to the mesh, i.e., moving each
interior vertex to the arithmetic average of its neighboring points.
"""
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"] | [
"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. | [
"Perform",
"k",
"steps",
"of",
"Laplacian",
"smoothing",
"to",
"the",
"mesh",
"i",
".",
"e",
".",
"moving",
"each",
"interior",
"vertex",
"to",
"the",
"arithmetic",
"average",
"of",
"its",
"neighboring",
"points",
"."
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/laplace.py#L12-L34 | train |
nschloe/optimesh | optimesh/odt.py | energy | def energy(mesh, uniform_density=False):
"""The mesh energy is defined as
E = int_Omega |u_l(x) - u(x)| rho(x) dx
where u(x) = ||x||^2 and u_l is its piecewise linearization on the mesh.
"""
# 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 | python | def energy(mesh, uniform_density=False):
"""The mesh energy is defined as
E = int_Omega |u_l(x) - u(x)| rho(x) dx
where u(x) = ||x||^2 and u_l is its piecewise linearization on the mesh.
"""
# 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 | [
"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
E = int_Omega |u_l(x) - u(x)| rho(x) dx
where u(x) = ||x||^2 and u_l is its piecewise linearization on the mesh. | [
"The",
"mesh",
"energy",
"is",
"defined",
"as"
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/odt.py#L28-L70 | train |
nschloe/optimesh | optimesh/cvt/block_diagonal.py | quasi_newton_uniform_blocks | def quasi_newton_uniform_blocks(points, cells, *args, **kwargs):
"""Lloyd's algorithm can be though of a diagonal-only Hessian; this method
incorporates the diagonal blocks, too.
"""
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"] | python | def quasi_newton_uniform_blocks(points, cells, *args, **kwargs):
"""Lloyd's algorithm can be though of a diagonal-only Hessian; this method
incorporates the diagonal blocks, too.
"""
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"] | [
"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. | [
"Lloyd",
"s",
"algorithm",
"can",
"be",
"though",
"of",
"a",
"diagonal",
"-",
"only",
"Hessian",
";",
"this",
"method",
"incorporates",
"the",
"diagonal",
"blocks",
"too",
"."
] | b85f48d1559a51a01cc3df6214c61ca8ad5ed786 | https://github.com/nschloe/optimesh/blob/b85f48d1559a51a01cc3df6214c61ca8ad5ed786/optimesh/cvt/block_diagonal.py#L12-L39 | train |
linnarsson-lab/loompy | loompy/loompy.py | new | def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection:
"""
Create an empty Loom file, and return it as a context manager.
"""
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 | python | def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection:
"""
Create an empty Loom file, and return it as a context manager.
"""
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 | [
"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. | [
"Create",
"an",
"empty",
"Loom",
"file",
"and",
"return",
"it",
"as",
"a",
"context",
"manager",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L993-L1020 | train |
linnarsson-lab/loompy | loompy/loompy.py | create | 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:
"""
Create a new Loom file from the given data.
Args:
filename (str): The filename (typically using a ``.loom`` file extension)
layers: One of the following:
* Two-dimensional (N-by-M) numpy ndarray of float values
* Sparse matrix (e.g. :class:`scipy.sparse.csr_matrix`)
* Dictionary of named layers, each an N-by-M ndarray or sparse matrix
* A :class:`.LayerManager`, with each layer an N-by-M ndarray
row_attrs (dict): Row attributes, where keys are attribute names and values
are numpy arrays (float or string) of length N
col_attrs (dict): Column attributes, where keys are attribute names and
values are numpy arrays (float or string) of length M
file_attrs (dict): Global attributes, where keys are attribute names and
values are strings
Returns:
Nothing
Remarks:
If the file exists, it will be overwritten.
"""
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 | python | 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:
"""
Create a new Loom file from the given data.
Args:
filename (str): The filename (typically using a ``.loom`` file extension)
layers: One of the following:
* Two-dimensional (N-by-M) numpy ndarray of float values
* Sparse matrix (e.g. :class:`scipy.sparse.csr_matrix`)
* Dictionary of named layers, each an N-by-M ndarray or sparse matrix
* A :class:`.LayerManager`, with each layer an N-by-M ndarray
row_attrs (dict): Row attributes, where keys are attribute names and values
are numpy arrays (float or string) of length N
col_attrs (dict): Column attributes, where keys are attribute names and
values are numpy arrays (float or string) of length M
file_attrs (dict): Global attributes, where keys are attribute names and
values are strings
Returns:
Nothing
Remarks:
If the file exists, it will be overwritten.
"""
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 | [
"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.
Args:
filename (str): The filename (typically using a ``.loom`` file extension)
layers: One of the following:
* Two-dimensional (N-by-M) numpy ndarray of float values
* Sparse matrix (e.g. :class:`scipy.sparse.csr_matrix`)
* Dictionary of named layers, each an N-by-M ndarray or sparse matrix
* A :class:`.LayerManager`, with each layer an N-by-M ndarray
row_attrs (dict): Row attributes, where keys are attribute names and values
are numpy arrays (float or string) of length N
col_attrs (dict): Column attributes, where keys are attribute names and
values are numpy arrays (float or string) of length M
file_attrs (dict): Global attributes, where keys are attribute names and
values are strings
Returns:
Nothing
Remarks:
If the file exists, it will be overwritten. | [
"Create",
"a",
"new",
"Loom",
"file",
"from",
"the",
"given",
"data",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L1023-L1089 | train |
linnarsson-lab/loompy | loompy/loompy.py | connect | def connect(filename: str, mode: str = 'r+', *, validate: bool = True, spec_version: str = "2.0.1") -> LoomConnection:
"""
Establish a connection to a .loom file.
Args:
filename: Path to the Loom file to open
mode: Read/write mode, 'r+' (read/write) or 'r' (read-only), defaults to 'r+'
validate: Validate the file structure against the Loom file format specification
spec_version: The loom file spec version to validate against (e.g. "2.0.1" or "old")
Returns:
A LoomConnection instance.
Remarks:
This function should typically be used as a context manager (i.e. inside a ``with``-block):
.. highlight:: python
.. code-block:: python
import loompy
with loompy.connect("mydata.loom") as ds:
print(ds.ca.keys())
This ensures that the file will be closed automatically when the context block ends
Note: if validation is requested, an exception is raised if validation fails.
"""
return LoomConnection(filename, mode, validate=validate, spec_version=spec_version) | python | def connect(filename: str, mode: str = 'r+', *, validate: bool = True, spec_version: str = "2.0.1") -> LoomConnection:
"""
Establish a connection to a .loom file.
Args:
filename: Path to the Loom file to open
mode: Read/write mode, 'r+' (read/write) or 'r' (read-only), defaults to 'r+'
validate: Validate the file structure against the Loom file format specification
spec_version: The loom file spec version to validate against (e.g. "2.0.1" or "old")
Returns:
A LoomConnection instance.
Remarks:
This function should typically be used as a context manager (i.e. inside a ``with``-block):
.. highlight:: python
.. code-block:: python
import loompy
with loompy.connect("mydata.loom") as ds:
print(ds.ca.keys())
This ensures that the file will be closed automatically when the context block ends
Note: if validation is requested, an exception is raised if validation fails.
"""
return LoomConnection(filename, mode, validate=validate, spec_version=spec_version) | [
"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.
Args:
filename: Path to the Loom file to open
mode: Read/write mode, 'r+' (read/write) or 'r' (read-only), defaults to 'r+'
validate: Validate the file structure against the Loom file format specification
spec_version: The loom file spec version to validate against (e.g. "2.0.1" or "old")
Returns:
A LoomConnection instance.
Remarks:
This function should typically be used as a context manager (i.e. inside a ``with``-block):
.. highlight:: python
.. code-block:: python
import loompy
with loompy.connect("mydata.loom") as ds:
print(ds.ca.keys())
This ensures that the file will be closed automatically when the context block ends
Note: if validation is requested, an exception is raised if validation fails. | [
"Establish",
"a",
"connection",
"to",
"a",
".",
"loom",
"file",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L1290-L1316 | train |
linnarsson-lab/loompy | loompy/loompy.py | LoomConnection.last_modified | def last_modified(self) -> str:
"""
Return an ISO8601 timestamp indicating when the file was last modified
Returns:
An ISO8601 timestamp indicating when the file was last modified
Remarks:
If the file has no timestamp, and mode is 'r+', a new timestamp is created and returned.
Otherwise, the current time in UTC is returned
"""
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() | python | def last_modified(self) -> str:
"""
Return an ISO8601 timestamp indicating when the file was last modified
Returns:
An ISO8601 timestamp indicating when the file was last modified
Remarks:
If the file has no timestamp, and mode is 'r+', a new timestamp is created and returned.
Otherwise, the current time in UTC is returned
"""
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() | [
"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
Returns:
An ISO8601 timestamp indicating when the file was last modified
Remarks:
If the file has no timestamp, and mode is 'r+', a new timestamp is created and returned.
Otherwise, the current time in UTC is returned | [
"Return",
"an",
"ISO8601",
"timestamp",
"indicating",
"when",
"the",
"file",
"was",
"last",
"modified"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L115-L132 | train |
linnarsson-lab/loompy | loompy/loompy.py | LoomConnection.get_changes_since | def get_changes_since(self, timestamp: str) -> Dict[str, List]:
"""
Get a summary of the parts of the file that changed since the given time
Args:
timestamp: ISO8601 timestamp
Return:
dict: Dictionary like ``{"row_graphs": rg, "col_graphs": cg, "row_attrs": ra, "col_attrs": ca, "layers": layers}`` listing the names of objects that were modified since the given time
"""
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} | python | def get_changes_since(self, timestamp: str) -> Dict[str, List]:
"""
Get a summary of the parts of the file that changed since the given time
Args:
timestamp: ISO8601 timestamp
Return:
dict: Dictionary like ``{"row_graphs": rg, "col_graphs": cg, "row_attrs": ra, "col_attrs": ca, "layers": layers}`` listing the names of objects that were modified since the given time
"""
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} | [
"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
Args:
timestamp: ISO8601 timestamp
Return:
dict: Dictionary like ``{"row_graphs": rg, "col_graphs": cg, "row_attrs": ra, "col_attrs": ca, "layers": layers}`` listing the names of objects that were modified since the given time | [
"Get",
"a",
"summary",
"of",
"the",
"parts",
"of",
"the",
"file",
"that",
"changed",
"since",
"the",
"given",
"time"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L134-L171 | train |
linnarsson-lab/loompy | loompy/loompy.py | LoomConnection.sparse | def sparse(self, rows: np.ndarray = None, cols: np.ndarray = None, layer: str = None) -> scipy.sparse.coo_matrix:
"""
Return the main matrix or specified layer as a scipy.sparse.coo_matrix, without loading dense matrix in RAM
Args:
rows: Rows to include, or None to include all
cols: Columns to include, or None to include all
layer: Layer to return, or None to return the default layer
Returns:
Sparse matrix (:class:`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) | python | def sparse(self, rows: np.ndarray = None, cols: np.ndarray = None, layer: str = None) -> scipy.sparse.coo_matrix:
"""
Return the main matrix or specified layer as a scipy.sparse.coo_matrix, without loading dense matrix in RAM
Args:
rows: Rows to include, or None to include all
cols: Columns to include, or None to include all
layer: Layer to return, or None to return the default layer
Returns:
Sparse matrix (:class:`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) | [
"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
Args:
rows: Rows to include, or None to include all
cols: Columns to include, or None to include all
layer: Layer to return, or None to return the default layer
Returns:
Sparse matrix (:class:`scipy.sparse.coo_matrix`) | [
"Return",
"the",
"main",
"matrix",
"or",
"specified",
"layer",
"as",
"a",
"scipy",
".",
"sparse",
".",
"coo_matrix",
"without",
"loading",
"dense",
"matrix",
"in",
"RAM"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L229-L244 | train |
linnarsson-lab/loompy | loompy/loompy.py | LoomConnection.close | def close(self, suppress_warning: bool = False) -> None:
"""
Close the connection. After this, the connection object becomes invalid. Warns user if called after closing.
Args:
suppress_warning: Suppresses warning message if True (defaults to false)
"""
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 | python | def close(self, suppress_warning: bool = False) -> None:
"""
Close the connection. After this, the connection object becomes invalid. Warns user if called after closing.
Args:
suppress_warning: Suppresses warning message if True (defaults to false)
"""
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 | [
"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.
Args:
suppress_warning: Suppresses warning message if True (defaults to false) | [
"Close",
"the",
"connection",
".",
"After",
"this",
"the",
"connection",
"object",
"becomes",
"invalid",
".",
"Warns",
"user",
"if",
"called",
"after",
"closing",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L246-L269 | train |
linnarsson-lab/loompy | loompy/loompy.py | LoomConnection.permute | def permute(self, ordering: np.ndarray, axis: int) -> None:
"""
Permute the dataset along the indicated axis.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing.
"""
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) | python | def permute(self, ordering: np.ndarray, axis: int) -> None:
"""
Permute the dataset along the indicated axis.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing.
"""
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) | [
"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.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing. | [
"Permute",
"the",
"dataset",
"along",
"the",
"indicated",
"axis",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L784-L806 | train |
linnarsson-lab/loompy | loompy/loompy.py | LoomConnection.aggregate | 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:
"""
Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
Args:
out_file The name of the output Loom file (will be appended to if it exists)
select Bool array giving the columns to include (or None, to include all)
group_by The column attribute to group by, or an np.ndarray of integer group labels
aggr_by The aggregation function for the main matrix
aggr_ca_by A dictionary of aggregation functions for the column attributes (or None to skip)
Returns:
m Aggregated main matrix
Remarks:
aggr_by gives the aggregation function for the main matrix
aggr_ca_by is a dictionary with column attributes as keys and aggregation functionas as values
Aggregation functions can be any valid aggregation function from here: https://github.com/ml31415/numpy-groupies
In addition, you can specify:
"tally" to count the number of occurences of each value of a categorical attribute
"""
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 | python | 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:
"""
Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
Args:
out_file The name of the output Loom file (will be appended to if it exists)
select Bool array giving the columns to include (or None, to include all)
group_by The column attribute to group by, or an np.ndarray of integer group labels
aggr_by The aggregation function for the main matrix
aggr_ca_by A dictionary of aggregation functions for the column attributes (or None to skip)
Returns:
m Aggregated main matrix
Remarks:
aggr_by gives the aggregation function for the main matrix
aggr_ca_by is a dictionary with column attributes as keys and aggregation functionas as values
Aggregation functions can be any valid aggregation function from here: https://github.com/ml31415/numpy-groupies
In addition, you can specify:
"tally" to count the number of occurences of each value of a categorical attribute
"""
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 | [
"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
Args:
out_file The name of the output Loom file (will be appended to if it exists)
select Bool array giving the columns to include (or None, to include all)
group_by The column attribute to group by, or an np.ndarray of integer group labels
aggr_by The aggregation function for the main matrix
aggr_ca_by A dictionary of aggregation functions for the column attributes (or None to skip)
Returns:
m Aggregated main matrix
Remarks:
aggr_by gives the aggregation function for the main matrix
aggr_ca_by is a dictionary with column attributes as keys and aggregation functionas as values
Aggregation functions can be any valid aggregation function from here: https://github.com/ml31415/numpy-groupies
In addition, you can specify:
"tally" to count the number of occurences of each value of a categorical attribute | [
"Aggregate",
"the",
"Loom",
"file",
"by",
"applying",
"aggregation",
"functions",
"to",
"the",
"main",
"matrix",
"as",
"well",
"as",
"to",
"the",
"column",
"attributes"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L873-L934 | train |
linnarsson-lab/loompy | loompy/file_attribute_manager.py | FileAttributeManager.get | def get(self, name: str, default: Any = None) -> np.ndarray:
"""
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.
"""
if name in self:
return self[name]
else:
return default | python | def get(self, name: str, default: Any = None) -> np.ndarray:
"""
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.
"""
if name in self:
return self[name]
else:
return default | [
"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. | [
"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",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/file_attribute_manager.py#L78-L86 | train |
linnarsson-lab/loompy | loompy/color.py | cat_colors | 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]:
"""
Return a colormap suitable for N categorical values, optimized to be both aesthetically pleasing and perceptually distinct.
Args:
N The number of colors requested.
hue Controls the hue of the generated color. You can pass a string representing a color name: "red", "orange", "yellow", "green", "blue", "purple", "pink" and "monochrome" are currently supported. If you pass a hexidecimal color string such as "#00FFFF", its hue value will be used to generate colors.
luminosity Controls the luminosity of the generated color: "bright", "light" or "dark".
bgvalue If not None, then the corresponding index color will be set to light gray
loop If True, loop the color alphabet instead of generating random colors
seed If not None, use as the random seed (default: "cat")
Returns:
A set of colors in the requested format, either a list of values or a matplotlib LinearSegmentedColormap (when format="cmap")
If N <= 25 and hue and luminosity are both None, a subset of the optimally perceptually distinct "color alphabet" is returned.
Else, a pleasing set of random colors is returned.
Colors are designed to be displayed on a white background.
"""
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) | python | 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]:
"""
Return a colormap suitable for N categorical values, optimized to be both aesthetically pleasing and perceptually distinct.
Args:
N The number of colors requested.
hue Controls the hue of the generated color. You can pass a string representing a color name: "red", "orange", "yellow", "green", "blue", "purple", "pink" and "monochrome" are currently supported. If you pass a hexidecimal color string such as "#00FFFF", its hue value will be used to generate colors.
luminosity Controls the luminosity of the generated color: "bright", "light" or "dark".
bgvalue If not None, then the corresponding index color will be set to light gray
loop If True, loop the color alphabet instead of generating random colors
seed If not None, use as the random seed (default: "cat")
Returns:
A set of colors in the requested format, either a list of values or a matplotlib LinearSegmentedColormap (when format="cmap")
If N <= 25 and hue and luminosity are both None, a subset of the optimally perceptually distinct "color alphabet" is returned.
Else, a pleasing set of random colors is returned.
Colors are designed to be displayed on a white background.
"""
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) | [
"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.
Args:
N The number of colors requested.
hue Controls the hue of the generated color. You can pass a string representing a color name: "red", "orange", "yellow", "green", "blue", "purple", "pink" and "monochrome" are currently supported. If you pass a hexidecimal color string such as "#00FFFF", its hue value will be used to generate colors.
luminosity Controls the luminosity of the generated color: "bright", "light" or "dark".
bgvalue If not None, then the corresponding index color will be set to light gray
loop If True, loop the color alphabet instead of generating random colors
seed If not None, use as the random seed (default: "cat")
Returns:
A set of colors in the requested format, either a list of values or a matplotlib LinearSegmentedColormap (when format="cmap")
If N <= 25 and hue and luminosity are both None, a subset of the optimally perceptually distinct "color alphabet" is returned.
Else, a pleasing set of random colors is returned.
Colors are designed to be displayed on a white background. | [
"Return",
"a",
"colormap",
"suitable",
"for",
"N",
"categorical",
"values",
"optimized",
"to",
"be",
"both",
"aesthetically",
"pleasing",
"and",
"perceptually",
"distinct",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/color.py#L336-L367 | train |
linnarsson-lab/loompy | loompy/graph_manager.py | _renumber | def _renumber(a: np.ndarray, keys: np.ndarray, values: np.ndarray) -> np.ndarray:
"""
Renumber 'a' by replacing any occurrence of 'keys' by the corresponding 'values'
"""
ordering = np.argsort(keys)
keys = keys[ordering]
values = keys[ordering]
index = np.digitize(a.ravel(), keys, right=True)
return(values[index].reshape(a.shape)) | python | def _renumber(a: np.ndarray, keys: np.ndarray, values: np.ndarray) -> np.ndarray:
"""
Renumber 'a' by replacing any occurrence of 'keys' by the corresponding 'values'
"""
ordering = np.argsort(keys)
keys = keys[ordering]
values = keys[ordering]
index = np.digitize(a.ravel(), keys, right=True)
return(values[index].reshape(a.shape)) | [
"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' | [
"Renumber",
"a",
"by",
"replacing",
"any",
"occurrence",
"of",
"keys",
"by",
"the",
"corresponding",
"values"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/graph_manager.py#L7-L15 | train |
linnarsson-lab/loompy | loompy/loom_validator.py | LoomValidator.validate | def validate(self, path: str, strictness: str = "speconly") -> bool:
"""
Validate a file for conformance to the Loom specification
Args:
path: Full path to the file to be validated
strictness: "speconly" or "conventions"
Remarks:
In "speconly" mode, conformance is assessed relative to the file format specification
at http://linnarssonlab.org/loompy/format/. In "conventions" mode, conformance is additionally
assessed relative to attribute name and data type conventions given at http://linnarssonlab.org/loompy/conventions/.
"""
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 | python | def validate(self, path: str, strictness: str = "speconly") -> bool:
"""
Validate a file for conformance to the Loom specification
Args:
path: Full path to the file to be validated
strictness: "speconly" or "conventions"
Remarks:
In "speconly" mode, conformance is assessed relative to the file format specification
at http://linnarssonlab.org/loompy/format/. In "conventions" mode, conformance is additionally
assessed relative to attribute name and data type conventions given at http://linnarssonlab.org/loompy/conventions/.
"""
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 | [
"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
Args:
path: Full path to the file to be validated
strictness: "speconly" or "conventions"
Remarks:
In "speconly" mode, conformance is assessed relative to the file format specification
at http://linnarssonlab.org/loompy/format/. In "conventions" mode, conformance is additionally
assessed relative to attribute name and data type conventions given at http://linnarssonlab.org/loompy/conventions/. | [
"Validate",
"a",
"file",
"for",
"conformance",
"to",
"the",
"Loom",
"specification"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loom_validator.py#L34-L60 | train |
linnarsson-lab/loompy | loompy/attribute_manager.py | AttributeManager._permute | def _permute(self, ordering: np.ndarray) -> None:
"""
Permute all the attributes in the collection
Remarks:
This permutes the order of the values for each attribute in the file
"""
for key in self.keys():
self[key] = self[key][ordering] | python | def _permute(self, ordering: np.ndarray) -> None:
"""
Permute all the attributes in the collection
Remarks:
This permutes the order of the values for each attribute in the file
"""
for key in self.keys():
self[key] = self[key][ordering] | [
"def",
"_permute",
"(",
"self",
",",
"ordering",
":",
"np",
".",
"ndarray",
")",
"->",
"None",
":",
"for",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"self",
"[",
"key",
"]",
"=",
"self",
"[",
"key",
"]",
"[",
"ordering",
"]"
] | Permute all the attributes in the collection
Remarks:
This permutes the order of the values for each attribute in the file | [
"Permute",
"all",
"the",
"attributes",
"in",
"the",
"collection"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/attribute_manager.py#L180-L188 | train |
linnarsson-lab/loompy | loompy/attribute_manager.py | AttributeManager.get | def get(self, name: str, default: np.ndarray) -> np.ndarray:
"""
Return the value for a named attribute if it exists, else default.
Default has to be a numpy array of correct size.
"""
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 | python | def get(self, name: str, default: np.ndarray) -> np.ndarray:
"""
Return the value for a named attribute if it exists, else default.
Default has to be a numpy array of correct size.
"""
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 | [
"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. | [
"Return",
"the",
"value",
"for",
"a",
"named",
"attribute",
"if",
"it",
"exists",
"else",
"default",
".",
"Default",
"has",
"to",
"be",
"a",
"numpy",
"array",
"of",
"correct",
"size",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/attribute_manager.py#L190-L205 | train |
linnarsson-lab/loompy | loompy/normalize.py | normalize_attr_array | def normalize_attr_array(a: Any) -> np.ndarray:
"""
Take all kinds of array-like inputs and normalize to a one-dimensional 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.") | python | def normalize_attr_array(a: Any) -> np.ndarray:
"""
Take all kinds of array-like inputs and normalize to a one-dimensional 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.") | [
"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 | [
"Take",
"all",
"kinds",
"of",
"array",
"-",
"like",
"inputs",
"and",
"normalize",
"to",
"a",
"one",
"-",
"dimensional",
"np",
".",
"ndarray"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/normalize.py#L29-L47 | train |
linnarsson-lab/loompy | loompy/to_html.py | to_html | def to_html(ds: Any) -> str:
"""
Return an HTML representation of the loom file or view, showing the upper-left 10x10 corner.
"""
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 | python | def to_html(ds: Any) -> str:
"""
Return an HTML representation of the loom file or view, showing the upper-left 10x10 corner.
"""
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 | [
"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. | [
"Return",
"an",
"HTML",
"representation",
"of",
"the",
"loom",
"file",
"or",
"view",
"showing",
"the",
"upper",
"-",
"left",
"10x10",
"corner",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/to_html.py#L4-L62 | train |
linnarsson-lab/loompy | loompy/loom_view.py | LoomView.permute | def permute(self, ordering: np.ndarray, *, axis: int) -> None:
"""
Permute the view, by permuting its layers, attributes and graphs
Args:
ordering (np.ndarray): The desired ordering along the axis
axis (int): 0, permute rows; 1, permute columns
"""
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) | python | def permute(self, ordering: np.ndarray, *, axis: int) -> None:
"""
Permute the view, by permuting its layers, attributes and graphs
Args:
ordering (np.ndarray): The desired ordering along the axis
axis (int): 0, permute rows; 1, permute columns
"""
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) | [
"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
Args:
ordering (np.ndarray): The desired ordering along the axis
axis (int): 0, permute rows; 1, permute columns | [
"Permute",
"the",
"view",
"by",
"permuting",
"its",
"layers",
"attributes",
"and",
"graphs"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loom_view.py#L45-L68 | train |
linnarsson-lab/loompy | loompy/loom_layer.py | MemoryLoomLayer.permute | def permute(self, ordering: np.ndarray, *, axis: int) -> None:
"""
Permute the layer along an axis
Args:
axis: The axis to permute (0, permute the rows; 1, permute the columns)
ordering: The permutation vector
"""
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") | python | def permute(self, ordering: np.ndarray, *, axis: int) -> None:
"""
Permute the layer along an axis
Args:
axis: The axis to permute (0, permute the rows; 1, permute the columns)
ordering: The permutation vector
"""
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") | [
"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
Args:
axis: The axis to permute (0, permute the rows; 1, permute the columns)
ordering: The permutation vector | [
"Permute",
"the",
"layer",
"along",
"an",
"axis"
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loom_layer.py#L30-L43 | train |
linnarsson-lab/loompy | loompy/loom_layer.py | LoomLayer._resize | def _resize(self, size: Tuple[int, int], axis: int = None) -> None:
"""Resize the dataset, or the specified axis.
The dataset must be stored in chunked format; it can be resized up to the "maximum shape" (keyword maxshape) specified at creation time.
The rank of the dataset cannot be changed.
"Size" should be a shape tuple, or if an axis is specified, an integer.
BEWARE: This functions differently than the NumPy resize() method!
The data is not "reshuffled" to fit in the new shape; each axis is grown or shrunk independently.
The coordinates of existing data are fixed.
"""
if self.name == "":
self.ds._file['/matrix'].resize(size, axis)
else:
self.ds._file['/layers/' + self.name].resize(size, axis) | python | def _resize(self, size: Tuple[int, int], axis: int = None) -> None:
"""Resize the dataset, or the specified axis.
The dataset must be stored in chunked format; it can be resized up to the "maximum shape" (keyword maxshape) specified at creation time.
The rank of the dataset cannot be changed.
"Size" should be a shape tuple, or if an axis is specified, an integer.
BEWARE: This functions differently than the NumPy resize() method!
The data is not "reshuffled" to fit in the new shape; each axis is grown or shrunk independently.
The coordinates of existing data are fixed.
"""
if self.name == "":
self.ds._file['/matrix'].resize(size, axis)
else:
self.ds._file['/layers/' + self.name].resize(size, axis) | [
"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.
The dataset must be stored in chunked format; it can be resized up to the "maximum shape" (keyword maxshape) specified at creation time.
The rank of the dataset cannot be changed.
"Size" should be a shape tuple, or if an axis is specified, an integer.
BEWARE: This functions differently than the NumPy resize() method!
The data is not "reshuffled" to fit in the new shape; each axis is grown or shrunk independently.
The coordinates of existing data are fixed. | [
"Resize",
"the",
"dataset",
"or",
"the",
"specified",
"axis",
"."
] | 62c8373a92b058753baa3a95331fb541f560f599 | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loom_layer.py#L130-L144 | train |
optimizely/python-sdk | optimizely/helpers/validator.py | is_datafile_valid | def is_datafile_valid(datafile):
""" Given a datafile determine if it is valid or not.
Args:
datafile: JSON string representing the project.
Returns:
Boolean depending upon whether datafile is valid or not.
"""
try:
datafile_json = json.loads(datafile)
except:
return False
try:
jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
except:
return False
return True | python | def is_datafile_valid(datafile):
""" Given a datafile determine if it is valid or not.
Args:
datafile: JSON string representing the project.
Returns:
Boolean depending upon whether datafile is valid or not.
"""
try:
datafile_json = json.loads(datafile)
except:
return False
try:
jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
except:
return False
return True | [
"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.
Args:
datafile: JSON string representing the project.
Returns:
Boolean depending upon whether datafile is valid or not. | [
"Given",
"a",
"datafile",
"determine",
"if",
"it",
"is",
"valid",
"or",
"not",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/validator.py#L24-L44 | train |
optimizely/python-sdk | optimizely/helpers/validator.py | is_user_profile_valid | def is_user_profile_valid(user_profile):
""" Determine if provided user profile is valid or not.
Args:
user_profile: User's profile which needs to be validated.
Returns:
Boolean depending upon whether profile is valid or not.
"""
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 | python | def is_user_profile_valid(user_profile):
""" Determine if provided user profile is valid or not.
Args:
user_profile: User's profile which needs to be validated.
Returns:
Boolean depending upon whether profile is valid or not.
"""
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 | [
"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.
Args:
user_profile: User's profile which needs to be validated.
Returns:
Boolean depending upon whether profile is valid or not. | [
"Determine",
"if",
"provided",
"user",
"profile",
"is",
"valid",
"or",
"not",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/validator.py#L126-L156 | train |
optimizely/python-sdk | optimizely/helpers/validator.py | is_attribute_valid | def is_attribute_valid(attribute_key, attribute_value):
""" Determine if given attribute is valid.
Args:
attribute_key: Variable which needs to be validated
attribute_value: Variable which needs to be validated
Returns:
False if attribute_key is not a string
False if attribute_value is not one of the supported attribute types
True otherwise
"""
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 | python | def is_attribute_valid(attribute_key, attribute_value):
""" Determine if given attribute is valid.
Args:
attribute_key: Variable which needs to be validated
attribute_value: Variable which needs to be validated
Returns:
False if attribute_key is not a string
False if attribute_value is not one of the supported attribute types
True otherwise
"""
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 | [
"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.
Args:
attribute_key: Variable which needs to be validated
attribute_value: Variable which needs to be validated
Returns:
False if attribute_key is not a string
False if attribute_value is not one of the supported attribute types
True otherwise | [
"Determine",
"if",
"given",
"attribute",
"is",
"valid",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/validator.py#L174-L196 | train |
optimizely/python-sdk | optimizely/helpers/validator.py | is_finite_number | def is_finite_number(value):
""" Validates if the given value is a number, enforces
absolute limit of 2^53 and restricts NAN, INF, -INF.
Args:
value: Value to be validated.
Returns:
Boolean: True if value is a number and not NAN, INF, -INF or
greater than absolute limit of 2^53 else False.
"""
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 | python | def is_finite_number(value):
""" Validates if the given value is a number, enforces
absolute limit of 2^53 and restricts NAN, INF, -INF.
Args:
value: Value to be validated.
Returns:
Boolean: True if value is a number and not NAN, INF, -INF or
greater than absolute limit of 2^53 else False.
"""
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 | [
"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.
Args:
value: Value to be validated.
Returns:
Boolean: True if value is a number and not NAN, INF, -INF or
greater than absolute limit of 2^53 else False. | [
"Validates",
"if",
"the",
"given",
"value",
"is",
"a",
"number",
"enforces",
"absolute",
"limit",
"of",
"2^53",
"and",
"restricts",
"NAN",
"INF",
"-",
"INF",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/validator.py#L199-L225 | train |
optimizely/python-sdk | optimizely/helpers/validator.py | are_values_same_type | def are_values_same_type(first_val, second_val):
""" Method to verify that both values belong to same type. Float and integer are
considered as same type.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belong to same type. Otherwise False.
"""
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 | python | def are_values_same_type(first_val, second_val):
""" Method to verify that both values belong to same type. Float and integer are
considered as same type.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belong to same type. Otherwise False.
"""
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 | [
"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.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belong to same type. Otherwise False. | [
"Method",
"to",
"verify",
"that",
"both",
"values",
"belong",
"to",
"same",
"type",
".",
"Float",
"and",
"integer",
"are",
"considered",
"as",
"same",
"type",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/validator.py#L228-L255 | train |
optimizely/python-sdk | optimizely/logger.py | reset_logger | def reset_logger(name, level=None, handler=None):
"""
Make a standard python logger object with default formatter, handler, etc.
Defaults are:
- level == logging.INFO
- handler == logging.StreamHandler()
Args:
name: a logger name.
level: an optional initial log level for this logger.
handler: an optional initial handler for this logger.
Returns: a standard python logger with a single handler.
"""
# Make the logger and set its level.
if level is None:
level = logging.INFO
logger = logging.getLogger(name)
logger.setLevel(level)
# Make the handler and attach it.
handler = handler or logging.StreamHandler()
handler.setFormatter(logging.Formatter(_DEFAULT_LOG_FORMAT))
# We don't use ``.addHandler``, since this logger may have already been
# instantiated elsewhere with a different handler. It should only ever
# have one, not many.
logger.handlers = [handler]
return logger | python | def reset_logger(name, level=None, handler=None):
"""
Make a standard python logger object with default formatter, handler, etc.
Defaults are:
- level == logging.INFO
- handler == logging.StreamHandler()
Args:
name: a logger name.
level: an optional initial log level for this logger.
handler: an optional initial handler for this logger.
Returns: a standard python logger with a single handler.
"""
# Make the logger and set its level.
if level is None:
level = logging.INFO
logger = logging.getLogger(name)
logger.setLevel(level)
# Make the handler and attach it.
handler = handler or logging.StreamHandler()
handler.setFormatter(logging.Formatter(_DEFAULT_LOG_FORMAT))
# We don't use ``.addHandler``, since this logger may have already been
# instantiated elsewhere with a different handler. It should only ever
# have one, not many.
logger.handlers = [handler]
return logger | [
"def",
"reset_logger",
"(",
"name",
",",
"level",
"=",
"None",
",",
"handler",
"=",
"None",
")",
":",
"# Make the logger and set its level.",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"logging",
".",
"INFO",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"# Make the handler and attach it.",
"handler",
"=",
"handler",
"or",
"logging",
".",
"StreamHandler",
"(",
")",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"_DEFAULT_LOG_FORMAT",
")",
")",
"# We don't use ``.addHandler``, since this logger may have already been",
"# instantiated elsewhere with a different handler. It should only ever",
"# have one, not many.",
"logger",
".",
"handlers",
"=",
"[",
"handler",
"]",
"return",
"logger"
] | Make a standard python logger object with default formatter, handler, etc.
Defaults are:
- level == logging.INFO
- handler == logging.StreamHandler()
Args:
name: a logger name.
level: an optional initial log level for this logger.
handler: an optional initial handler for this logger.
Returns: a standard python logger with a single handler. | [
"Make",
"a",
"standard",
"python",
"logger",
"object",
"with",
"default",
"formatter",
"handler",
"etc",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/logger.py#L22-L52 | train |
optimizely/python-sdk | optimizely/logger.py | adapt_logger | def adapt_logger(logger):
"""
Adapt our custom logger.BaseLogger object into a standard logging.Logger object.
Adaptations are:
- NoOpLogger turns into a logger with a single NullHandler.
- SimpleLogger turns into a logger with a StreamHandler and level.
Args:
logger: Possibly a logger.BaseLogger, or a standard python logging.Logger.
Returns: a standard python logging.Logger.
"""
if isinstance(logger, logging.Logger):
return logger
# Use the standard python logger created by these classes.
if isinstance(logger, (SimpleLogger, NoOpLogger)):
return logger.logger
# Otherwise, return whatever we were given because we can't adapt.
return logger | python | def adapt_logger(logger):
"""
Adapt our custom logger.BaseLogger object into a standard logging.Logger object.
Adaptations are:
- NoOpLogger turns into a logger with a single NullHandler.
- SimpleLogger turns into a logger with a StreamHandler and level.
Args:
logger: Possibly a logger.BaseLogger, or a standard python logging.Logger.
Returns: a standard python logging.Logger.
"""
if isinstance(logger, logging.Logger):
return logger
# Use the standard python logger created by these classes.
if isinstance(logger, (SimpleLogger, NoOpLogger)):
return logger.logger
# Otherwise, return whatever we were given because we can't adapt.
return logger | [
"def",
"adapt_logger",
"(",
"logger",
")",
":",
"if",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"return",
"logger",
"# Use the standard python logger created by these classes.",
"if",
"isinstance",
"(",
"logger",
",",
"(",
"SimpleLogger",
",",
"NoOpLogger",
")",
")",
":",
"return",
"logger",
".",
"logger",
"# Otherwise, return whatever we were given because we can't adapt.",
"return",
"logger"
] | Adapt our custom logger.BaseLogger object into a standard logging.Logger object.
Adaptations are:
- NoOpLogger turns into a logger with a single NullHandler.
- SimpleLogger turns into a logger with a StreamHandler and level.
Args:
logger: Possibly a logger.BaseLogger, or a standard python logging.Logger.
Returns: a standard python logging.Logger. | [
"Adapt",
"our",
"custom",
"logger",
".",
"BaseLogger",
"object",
"into",
"a",
"standard",
"logging",
".",
"Logger",
"object",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/logger.py#L95-L117 | train |
optimizely/python-sdk | optimizely/user_profile.py | UserProfile.get_variation_for_experiment | def get_variation_for_experiment(self, experiment_id):
""" Helper method to retrieve variation ID for given experiment.
Args:
experiment_id: ID for experiment for which variation needs to be looked up for.
Returns:
Variation ID corresponding to the experiment. None if no decision available.
"""
return self.experiment_bucket_map.get(experiment_id, {self.VARIATION_ID_KEY: None}).get(self.VARIATION_ID_KEY) | python | def get_variation_for_experiment(self, experiment_id):
""" Helper method to retrieve variation ID for given experiment.
Args:
experiment_id: ID for experiment for which variation needs to be looked up for.
Returns:
Variation ID corresponding to the experiment. None if no decision available.
"""
return self.experiment_bucket_map.get(experiment_id, {self.VARIATION_ID_KEY: None}).get(self.VARIATION_ID_KEY) | [
"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.
Args:
experiment_id: ID for experiment for which variation needs to be looked up for.
Returns:
Variation ID corresponding to the experiment. None if no decision available. | [
"Helper",
"method",
"to",
"retrieve",
"variation",
"ID",
"for",
"given",
"experiment",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/user_profile.py#L34-L44 | train |
optimizely/python-sdk | optimizely/helpers/event_tag_utils.py | get_numeric_value | def get_numeric_value(event_tags, logger=None):
"""
A smart getter of the numeric value from the event tags.
Args:
event_tags: A dictionary of event tags.
logger: Optional logger.
Returns:
A float numeric metric value is returned when the provided numeric
metric value is in the following format:
- A string (properly formatted, e.g., no commas)
- An integer
- A float or double
None is returned when the provided numeric metric values is in
the following format:
- None
- A boolean
- inf, -inf, nan
- A string not properly formatted (e.g., '1,234')
- Any values that cannot be cast to a float (e.g., an array or dictionary)
"""
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 event_tags:
logger_message_debug = 'The numeric metric key is not in event tags.'
else:
numeric_metric_value = event_tags[NUMERIC_METRIC_TYPE]
try:
if isinstance(numeric_metric_value, (numbers.Integral, float, str)):
# Attempt to convert the numeric metric value to a float
# (if it isn't already a float).
cast_numeric_metric_value = float(numeric_metric_value)
# If not a float after casting, then make everything else a None.
# Other potential values are nan, inf, and -inf.
if not isinstance(cast_numeric_metric_value, float) \
or math.isnan(cast_numeric_metric_value) \
or math.isinf(cast_numeric_metric_value):
logger_message_debug = 'Provided numeric value {} is in an invalid format.'\
.format(numeric_metric_value)
numeric_metric_value = None
else:
# Handle booleans as a special case.
# They are treated like an integer in the cast, but we do not want to cast this.
if isinstance(numeric_metric_value, bool):
logger_message_debug = 'Provided numeric value is a boolean, which is an invalid format.'
numeric_metric_value = None
else:
numeric_metric_value = cast_numeric_metric_value
else:
logger_message_debug = 'Numeric metric value is not in integer, float, or string form.'
numeric_metric_value = None
except ValueError:
logger_message_debug = 'Value error while casting numeric metric value to a float.'
numeric_metric_value = None
# Log all potential debug messages while converting the numeric value to a float.
if logger and logger_message_debug:
logger.log(enums.LogLevels.DEBUG, logger_message_debug)
# Log the final numeric metric value
if numeric_metric_value is not None:
if logger:
logger.log(enums.LogLevels.INFO,
'The numeric metric value {} will be sent to results.'
.format(numeric_metric_value))
else:
if logger:
logger.log(enums.LogLevels.WARNING,
'The provided numeric metric value {} is in an invalid format and will not be sent to results.'
.format(numeric_metric_value))
return numeric_metric_value | python | def get_numeric_value(event_tags, logger=None):
"""
A smart getter of the numeric value from the event tags.
Args:
event_tags: A dictionary of event tags.
logger: Optional logger.
Returns:
A float numeric metric value is returned when the provided numeric
metric value is in the following format:
- A string (properly formatted, e.g., no commas)
- An integer
- A float or double
None is returned when the provided numeric metric values is in
the following format:
- None
- A boolean
- inf, -inf, nan
- A string not properly formatted (e.g., '1,234')
- Any values that cannot be cast to a float (e.g., an array or dictionary)
"""
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 event_tags:
logger_message_debug = 'The numeric metric key is not in event tags.'
else:
numeric_metric_value = event_tags[NUMERIC_METRIC_TYPE]
try:
if isinstance(numeric_metric_value, (numbers.Integral, float, str)):
# Attempt to convert the numeric metric value to a float
# (if it isn't already a float).
cast_numeric_metric_value = float(numeric_metric_value)
# If not a float after casting, then make everything else a None.
# Other potential values are nan, inf, and -inf.
if not isinstance(cast_numeric_metric_value, float) \
or math.isnan(cast_numeric_metric_value) \
or math.isinf(cast_numeric_metric_value):
logger_message_debug = 'Provided numeric value {} is in an invalid format.'\
.format(numeric_metric_value)
numeric_metric_value = None
else:
# Handle booleans as a special case.
# They are treated like an integer in the cast, but we do not want to cast this.
if isinstance(numeric_metric_value, bool):
logger_message_debug = 'Provided numeric value is a boolean, which is an invalid format.'
numeric_metric_value = None
else:
numeric_metric_value = cast_numeric_metric_value
else:
logger_message_debug = 'Numeric metric value is not in integer, float, or string form.'
numeric_metric_value = None
except ValueError:
logger_message_debug = 'Value error while casting numeric metric value to a float.'
numeric_metric_value = None
# Log all potential debug messages while converting the numeric value to a float.
if logger and logger_message_debug:
logger.log(enums.LogLevels.DEBUG, logger_message_debug)
# Log the final numeric metric value
if numeric_metric_value is not None:
if logger:
logger.log(enums.LogLevels.INFO,
'The numeric metric value {} will be sent to results.'
.format(numeric_metric_value))
else:
if logger:
logger.log(enums.LogLevels.WARNING,
'The provided numeric metric value {} is in an invalid format and will not be sent to results.'
.format(numeric_metric_value))
return numeric_metric_value | [
"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",
"event_tags",
":",
"logger_message_debug",
"=",
"'The numeric metric key is not in event tags.'",
"else",
":",
"numeric_metric_value",
"=",
"event_tags",
"[",
"NUMERIC_METRIC_TYPE",
"]",
"try",
":",
"if",
"isinstance",
"(",
"numeric_metric_value",
",",
"(",
"numbers",
".",
"Integral",
",",
"float",
",",
"str",
")",
")",
":",
"# Attempt to convert the numeric metric value to a float",
"# (if it isn't already a float).",
"cast_numeric_metric_value",
"=",
"float",
"(",
"numeric_metric_value",
")",
"# If not a float after casting, then make everything else a None.",
"# Other potential values are nan, inf, and -inf.",
"if",
"not",
"isinstance",
"(",
"cast_numeric_metric_value",
",",
"float",
")",
"or",
"math",
".",
"isnan",
"(",
"cast_numeric_metric_value",
")",
"or",
"math",
".",
"isinf",
"(",
"cast_numeric_metric_value",
")",
":",
"logger_message_debug",
"=",
"'Provided numeric value {} is in an invalid format.'",
".",
"format",
"(",
"numeric_metric_value",
")",
"numeric_metric_value",
"=",
"None",
"else",
":",
"# Handle booleans as a special case.",
"# They are treated like an integer in the cast, but we do not want to cast this.",
"if",
"isinstance",
"(",
"numeric_metric_value",
",",
"bool",
")",
":",
"logger_message_debug",
"=",
"'Provided numeric value is a boolean, which is an invalid format.'",
"numeric_metric_value",
"=",
"None",
"else",
":",
"numeric_metric_value",
"=",
"cast_numeric_metric_value",
"else",
":",
"logger_message_debug",
"=",
"'Numeric metric value is not in integer, float, or string form.'",
"numeric_metric_value",
"=",
"None",
"except",
"ValueError",
":",
"logger_message_debug",
"=",
"'Value error while casting numeric metric value to a float.'",
"numeric_metric_value",
"=",
"None",
"# Log all potential debug messages while converting the numeric value to a float.",
"if",
"logger",
"and",
"logger_message_debug",
":",
"logger",
".",
"log",
"(",
"enums",
".",
"LogLevels",
".",
"DEBUG",
",",
"logger_message_debug",
")",
"# Log the final numeric metric value",
"if",
"numeric_metric_value",
"is",
"not",
"None",
":",
"if",
"logger",
":",
"logger",
".",
"log",
"(",
"enums",
".",
"LogLevels",
".",
"INFO",
",",
"'The numeric metric value {} will be sent to results.'",
".",
"format",
"(",
"numeric_metric_value",
")",
")",
"else",
":",
"if",
"logger",
":",
"logger",
".",
"log",
"(",
"enums",
".",
"LogLevels",
".",
"WARNING",
",",
"'The provided numeric metric value {} is in an invalid format and will not be sent to results.'",
".",
"format",
"(",
"numeric_metric_value",
")",
")",
"return",
"numeric_metric_value"
] | A smart getter of the numeric value from the event tags.
Args:
event_tags: A dictionary of event tags.
logger: Optional logger.
Returns:
A float numeric metric value is returned when the provided numeric
metric value is in the following format:
- A string (properly formatted, e.g., no commas)
- An integer
- A float or double
None is returned when the provided numeric metric values is in
the following format:
- None
- A boolean
- inf, -inf, nan
- A string not properly formatted (e.g., '1,234')
- Any values that cannot be cast to a float (e.g., an array or dictionary) | [
"A",
"smart",
"getter",
"of",
"the",
"numeric",
"value",
"from",
"the",
"event",
"tags",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/event_tag_utils.py#L43-L123 | train |
optimizely/python-sdk | optimizely/lib/pymmh3.py | hash | def hash( key, seed = 0x0 ):
''' Implements 32bit murmur3 hash. '''
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
# body
for block_start in xrange( 0, nblocks * 4, 4 ):
# ??? big endian?
k1 = key[ block_start + 3 ] << 24 | \
key[ block_start + 2 ] << 16 | \
key[ block_start + 1 ] << 8 | \
key[ block_start + 0 ]
k1 = ( c1 * k1 ) & 0xFFFFFFFF
k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF # inlined ROTL32
k1 = ( c2 * k1 ) & 0xFFFFFFFF
h1 ^= k1
h1 = ( h1 << 13 | h1 >> 19 ) & 0xFFFFFFFF # inlined ROTL32
h1 = ( h1 * 5 + 0xe6546b64 ) & 0xFFFFFFFF
# tail
tail_index = nblocks * 4
k1 = 0
tail_size = length & 3
if tail_size >= 3:
k1 ^= key[ tail_index + 2 ] << 16
if tail_size >= 2:
k1 ^= key[ tail_index + 1 ] << 8
if tail_size >= 1:
k1 ^= key[ tail_index + 0 ]
if tail_size > 0:
k1 = ( k1 * c1 ) & 0xFFFFFFFF
k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF # inlined ROTL32
k1 = ( k1 * c2 ) & 0xFFFFFFFF
h1 ^= k1
#finalization
unsigned_val = fmix( h1 ^ length )
if unsigned_val & 0x80000000 == 0:
return unsigned_val
else:
return -( (unsigned_val ^ 0xFFFFFFFF) + 1 ) | python | def hash( key, seed = 0x0 ):
''' Implements 32bit murmur3 hash. '''
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
# body
for block_start in xrange( 0, nblocks * 4, 4 ):
# ??? big endian?
k1 = key[ block_start + 3 ] << 24 | \
key[ block_start + 2 ] << 16 | \
key[ block_start + 1 ] << 8 | \
key[ block_start + 0 ]
k1 = ( c1 * k1 ) & 0xFFFFFFFF
k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF # inlined ROTL32
k1 = ( c2 * k1 ) & 0xFFFFFFFF
h1 ^= k1
h1 = ( h1 << 13 | h1 >> 19 ) & 0xFFFFFFFF # inlined ROTL32
h1 = ( h1 * 5 + 0xe6546b64 ) & 0xFFFFFFFF
# tail
tail_index = nblocks * 4
k1 = 0
tail_size = length & 3
if tail_size >= 3:
k1 ^= key[ tail_index + 2 ] << 16
if tail_size >= 2:
k1 ^= key[ tail_index + 1 ] << 8
if tail_size >= 1:
k1 ^= key[ tail_index + 0 ]
if tail_size > 0:
k1 = ( k1 * c1 ) & 0xFFFFFFFF
k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF # inlined ROTL32
k1 = ( k1 * c2 ) & 0xFFFFFFFF
h1 ^= k1
#finalization
unsigned_val = fmix( h1 ^ length )
if unsigned_val & 0x80000000 == 0:
return unsigned_val
else:
return -( (unsigned_val ^ 0xFFFFFFFF) + 1 ) | [
"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",
"# body",
"for",
"block_start",
"in",
"xrange",
"(",
"0",
",",
"nblocks",
"*",
"4",
",",
"4",
")",
":",
"# ??? big endian?",
"k1",
"=",
"key",
"[",
"block_start",
"+",
"3",
"]",
"<<",
"24",
"|",
"key",
"[",
"block_start",
"+",
"2",
"]",
"<<",
"16",
"|",
"key",
"[",
"block_start",
"+",
"1",
"]",
"<<",
"8",
"|",
"key",
"[",
"block_start",
"+",
"0",
"]",
"k1",
"=",
"(",
"c1",
"*",
"k1",
")",
"&",
"0xFFFFFFFF",
"k1",
"=",
"(",
"k1",
"<<",
"15",
"|",
"k1",
">>",
"17",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k1",
"=",
"(",
"c2",
"*",
"k1",
")",
"&",
"0xFFFFFFFF",
"h1",
"^=",
"k1",
"h1",
"=",
"(",
"h1",
"<<",
"13",
"|",
"h1",
">>",
"19",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"h1",
"=",
"(",
"h1",
"*",
"5",
"+",
"0xe6546b64",
")",
"&",
"0xFFFFFFFF",
"# tail",
"tail_index",
"=",
"nblocks",
"*",
"4",
"k1",
"=",
"0",
"tail_size",
"=",
"length",
"&",
"3",
"if",
"tail_size",
">=",
"3",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"2",
"]",
"<<",
"16",
"if",
"tail_size",
">=",
"2",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"1",
"]",
"<<",
"8",
"if",
"tail_size",
">=",
"1",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"0",
"]",
"if",
"tail_size",
">",
"0",
":",
"k1",
"=",
"(",
"k1",
"*",
"c1",
")",
"&",
"0xFFFFFFFF",
"k1",
"=",
"(",
"k1",
"<<",
"15",
"|",
"k1",
">>",
"17",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k1",
"=",
"(",
"k1",
"*",
"c2",
")",
"&",
"0xFFFFFFFF",
"h1",
"^=",
"k1",
"#finalization",
"unsigned_val",
"=",
"fmix",
"(",
"h1",
"^",
"length",
")",
"if",
"unsigned_val",
"&",
"0x80000000",
"==",
"0",
":",
"return",
"unsigned_val",
"else",
":",
"return",
"-",
"(",
"(",
"unsigned_val",
"^",
"0xFFFFFFFF",
")",
"+",
"1",
")"
] | Implements 32bit murmur3 hash. | [
"Implements",
"32bit",
"murmur3",
"hash",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/lib/pymmh3.py#L34-L94 | train |
optimizely/python-sdk | optimizely/lib/pymmh3.py | hash64 | def hash64( key, seed = 0x0, x64arch = True ):
''' Implements 64bit murmur3 hash. Returns a tuple. '''
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 ) & 0xFFFFFFFFFFFFFFFF
if unsigned_val2 & 0x8000000000000000 == 0:
signed_val2 = unsigned_val2
else:
signed_val2 = -( (unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1 )
return ( int( signed_val1 ), int( signed_val2 ) ) | python | def hash64( key, seed = 0x0, x64arch = True ):
''' Implements 64bit murmur3 hash. Returns a tuple. '''
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 ) & 0xFFFFFFFFFFFFFFFF
if unsigned_val2 & 0x8000000000000000 == 0:
signed_val2 = unsigned_val2
else:
signed_val2 = -( (unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1 )
return ( int( signed_val1 ), int( signed_val2 ) ) | [
"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",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"if",
"unsigned_val2",
"&",
"0x8000000000000000",
"==",
"0",
":",
"signed_val2",
"=",
"unsigned_val2",
"else",
":",
"signed_val2",
"=",
"-",
"(",
"(",
"unsigned_val2",
"^",
"0xFFFFFFFFFFFFFFFF",
")",
"+",
"1",
")",
"return",
"(",
"int",
"(",
"signed_val1",
")",
",",
"int",
"(",
"signed_val2",
")",
")"
] | Implements 64bit murmur3 hash. Returns a tuple. | [
"Implements",
"64bit",
"murmur3",
"hash",
".",
"Returns",
"a",
"tuple",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/lib/pymmh3.py#L406-L423 | train |
optimizely/python-sdk | optimizely/lib/pymmh3.py | hash_bytes | def hash_bytes( key, seed = 0x0, x64arch = True ):
''' Implements 128bit murmur3 hash. Returns a byte string. '''
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 | python | def hash_bytes( key, seed = 0x0, x64arch = True ):
''' Implements 128bit murmur3 hash. Returns a byte string. '''
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 | [
"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. | [
"Implements",
"128bit",
"murmur3",
"hash",
".",
"Returns",
"a",
"byte",
"string",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/lib/pymmh3.py#L426-L438 | train |
optimizely/python-sdk | optimizely/bucketer.py | Bucketer._generate_bucket_value | def _generate_bucket_value(self, bucketing_id):
""" Helper function to generate bucket value in half-closed interval [0, MAX_TRAFFIC_VALUE).
Args:
bucketing_id: ID for bucketing.
Returns:
Bucket value corresponding to the provided bucketing ID.
"""
ratio = float(self._generate_unsigned_hash_code_32_bit(bucketing_id)) / MAX_HASH_VALUE
return math.floor(ratio * MAX_TRAFFIC_VALUE) | python | def _generate_bucket_value(self, bucketing_id):
""" Helper function to generate bucket value in half-closed interval [0, MAX_TRAFFIC_VALUE).
Args:
bucketing_id: ID for bucketing.
Returns:
Bucket value corresponding to the provided bucketing ID.
"""
ratio = float(self._generate_unsigned_hash_code_32_bit(bucketing_id)) / MAX_HASH_VALUE
return math.floor(ratio * MAX_TRAFFIC_VALUE) | [
"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).
Args:
bucketing_id: ID for bucketing.
Returns:
Bucket value corresponding to the provided bucketing ID. | [
"Helper",
"function",
"to",
"generate",
"bucket",
"value",
"in",
"half",
"-",
"closed",
"interval",
"[",
"0",
"MAX_TRAFFIC_VALUE",
")",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/bucketer.py#L55-L66 | train |
optimizely/python-sdk | optimizely/bucketer.py | Bucketer.find_bucket | def find_bucket(self, bucketing_id, parent_id, traffic_allocations):
""" Determine entity based on bucket value and traffic allocations.
Args:
bucketing_id: ID to be used for bucketing the user.
parent_id: ID representing group or experiment.
traffic_allocations: Traffic allocations representing traffic allotted to experiments or variations.
Returns:
Entity ID which may represent experiment or variation.
"""
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 bucketing ID "%s".' % (
bucketing_number,
bucketing_id
))
for traffic_allocation in traffic_allocations:
current_end_of_range = traffic_allocation.get('endOfRange')
if bucketing_number < current_end_of_range:
return traffic_allocation.get('entityId')
return None | python | def find_bucket(self, bucketing_id, parent_id, traffic_allocations):
""" Determine entity based on bucket value and traffic allocations.
Args:
bucketing_id: ID to be used for bucketing the user.
parent_id: ID representing group or experiment.
traffic_allocations: Traffic allocations representing traffic allotted to experiments or variations.
Returns:
Entity ID which may represent experiment or variation.
"""
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 bucketing ID "%s".' % (
bucketing_number,
bucketing_id
))
for traffic_allocation in traffic_allocations:
current_end_of_range = traffic_allocation.get('endOfRange')
if bucketing_number < current_end_of_range:
return traffic_allocation.get('entityId')
return None | [
"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 bucketing ID \"%s\".'",
"%",
"(",
"bucketing_number",
",",
"bucketing_id",
")",
")",
"for",
"traffic_allocation",
"in",
"traffic_allocations",
":",
"current_end_of_range",
"=",
"traffic_allocation",
".",
"get",
"(",
"'endOfRange'",
")",
"if",
"bucketing_number",
"<",
"current_end_of_range",
":",
"return",
"traffic_allocation",
".",
"get",
"(",
"'entityId'",
")",
"return",
"None"
] | Determine entity based on bucket value and traffic allocations.
Args:
bucketing_id: ID to be used for bucketing the user.
parent_id: ID representing group or experiment.
traffic_allocations: Traffic allocations representing traffic allotted to experiments or variations.
Returns:
Entity ID which may represent experiment or variation. | [
"Determine",
"entity",
"based",
"on",
"bucket",
"value",
"and",
"traffic",
"allocations",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/bucketer.py#L68-L92 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.