id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
144,448
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.KineticScheme
class KineticScheme(LEMSBase): """ Kinetic scheme specifications. """ def __init__( self, name, nodes, state_variable, edges, edge_source, edge_target, forward_rate, reverse_rate, ): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the kinetic scheme. :type: str """ self.nodes = nodes """ Nodes to be used for the kinetic scheme. :type: str """ self.state_variable = state_variable """ State variable updated by the kinetic scheme. :type: str """ self.edges = edges """ Edges to be used for the kinetic scheme. :type: str """ self.edge_source = edge_source """ Attribute that defines the source of the transition. :type: str """ self.edge_target = edge_target """ Attribute that defines the target of the transition. :type: str """ self.forward_rate = forward_rate """ Name of the forward rate exposure. :type: str """ self.reverse_rate = reverse_rate """ Name of the reverse rate exposure. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( "<KineticScheme " 'name="{0}" ' 'nodes="{1}" ' 'edges="{2}" ' 'stateVariable="{3}" ' 'edgeSource="{4}" ' 'edgeTarget="{5}" ' 'forwardRate="{6}" ' 'reverseRate="{7}"/>' ).format( self.name, self.nodes, self.edges, self.state_variable, self.edge_source, self.edge_target, self.forward_rate, self.reverse_rate, )
class KineticScheme(LEMSBase): ''' Kinetic scheme specifications. ''' def __init__( self, name, nodes, state_variable, edges, edge_source, edge_target, forward_rate, reverse_rate, ): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
41
9
20
12
1
0.63
1
0
0
0
2
8
2
4
87
20
41
21
28
26
12
11
9
1
2
0
2
144,449
LEMS/pylems
lems/model/fundamental.py
lems.model.fundamental.Dimension
class Dimension(LEMSBase): """ Stores a dimension in terms of the seven fundamental SI units. """ def __init__(self, name, description="", **params): """ Constructor. :param name: Name of the dimension. :type name: str :param params: Key arguments specifying powers for each of the seven fundamental SI dimensions. :type params: dict() """ self.name = name """ Name of the dimension. :type: str """ self.m = params["m"] if "m" in params else 0 """ Power for the mass dimension. :type: int """ self.l = params["l"] if "l" in params else 0 """ Power for the length dimension. :type: int """ self.t = params["t"] if "t" in params else 0 """ Power for the time dimension. :type: int """ self.i = params["i"] if "i" in params else 0 """ Power for the electic current dimension. :type: int """ self.k = params["k"] if "k" in params else 0 """ Power for the temperature dimension. :type: int """ self.n = params["n"] if "n" in params else 0 """ Power for the quantity dimension. :type: int """ self.j = params["j"] if "j" in params else 0 """ Power for the luminous intensity dimension. :type: int """ self.description = description """ Description of this dimension. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Dimension name="{0}"'.format(self.name) + (' m = "{0}"'.format(self.m) if self.m != 0 else "") + (' l = "{0}"'.format(self.l) if self.l != 0 else "") + (' t = "{0}"'.format(self.t) if self.t != 0 else "") + (' i = "{0}"'.format(self.i) if self.i != 0 else "") + (' k = "{0}"'.format(self.k) if self.k != 0 else "") + (' n = "{0}"'.format(self.n) if self.n != 0 else "") + (' j = "{0}"'.format(self.j) if self.j != 0 else "") + "/>" )
class Dimension(LEMSBase): ''' Stores a dimension in terms of the seven fundamental SI units. ''' def __init__(self, name, description="", **params): ''' Constructor. :param name: Name of the dimension. :type name: str :param params: Key arguments specifying powers for each of the seven fundamental SI dimensions. :type params: dict() ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
36
11
11
15
8
1.39
1
0
0
0
2
9
2
4
78
23
23
12
20
32
13
12
10
8
2
0
16
144,450
LEMS/pylems
lems/parser/expr.py
lems.parser.expr.ExprParser
class ExprParser(LEMSBase): """ Parser class for parsing an expression and generating a parse tree. """ debug = False op_priority = { "$": -5, "func": 8, "+": 5, "-": 5, "*": 6, "/": 6, "^": 7, "~": 8, "exp": 8, ".and.": 1, ".or.": 1, ".gt.": 2, ".ge.": 2, ".geq.": 2, ".lt.": 2, ".le.": 2, ".eq.": 2, ".neq.": 2, ".ne.": 2, } # .neq. is preferred! depth = 0 """ Dictionary mapping operators to their priorities. :type: dict(string, Integer) """ def __init__(self, parse_string): """ Constructor. :param parse_string: Expression to be parsed. :type parse_string: string """ self.parse_string = parse_string """ Expression to be parsed. :type: string """ self.token_list = None """ List of tokens from the expression to be parsed. :type: list(string) """ def is_op(self, str): """ Checks if a token string contains an operator. :param str: Token string to be checked. :type str: string :return: True if the token string contains an operator. :rtype: Boolean """ return str in self.op_priority def is_func(self, str): """ Checks if a token string contains a function. :param str: Token string to be checked. :type str: string :return: True if the token string contains a function. :rtype: Boolean """ return str in known_functions def is_sym(self, str): """ Checks if a token string contains a symbol. :param str: Token string to be checked. :type str: string :return: True if the token string contains a symbol. :rtype: Boolean """ return str in ["+", "-", "~", "*", "/", "^", "(", ")"] def priority(self, op): if self.is_op(op): return self.op_priority[op] elif self.is_func(op): return self.op_priority["func"] else: return self.op_priority["$"] def tokenize(self): """ Tokenizes the string stored in the parser object into a list of tokens. """ self.token_list = [] ps = self.parse_string.strip() i = 0 last_token = None while i < len(ps) and ps[i].isspace(): i += 1 while i < len(ps): token = "" if ps[i].isalpha(): while i < len(ps) and (ps[i].isalnum() or ps[i] == "_"): token += ps[i] i += 1 elif ps[i].isdigit(): while i < len(ps) and ( ps[i].isdigit() or ps[i] == "." or ps[i] == "e" or ps[i] == "E" or (ps[i] == "+" and (ps[i - 1] == "e" or ps[i - 1] == "E")) or (ps[i] == "-" and (ps[i - 1] == "e" or ps[i - 1] == "E")) ): token += ps[i] i += 1 elif ps[i] == ".": if ps[i + 1].isdigit(): while i < len(ps) and (ps[i].isdigit() or ps[i] == "."): token += ps[i] i += 1 else: while i < len(ps) and (ps[i].isalpha() or ps[i] == "."): token += ps[i] i += 1 else: token += ps[i] i += 1 if token == "-" and ( last_token == None or last_token == "(" or self.is_op(last_token) ): token = "~" self.token_list += [token] last_token = token while i < len(ps) and ps[i].isspace(): i += 1 def make_op_node(self, op, right): if self.is_func(op): return Func1Node(op, right) elif op == "~": return OpNode("-", ValueNode("0"), right) else: left = self.val_stack.pop() if left == "$": left = self.node_stack.pop() else: left = ValueNode(left) return OpNode(op, left, right) def cleanup_stacks(self): right = self.val_stack.pop() if right == "$": right = self.node_stack.pop() else: right = ValueNode(right) if self.debug: print("- Cleanup > right: %s" % right) while self.op_stack.top() != "$": if self.debug: print( "5> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) op = self.op_stack.pop() right = self.make_op_node(op, right) if self.debug: print( "6> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) if self.debug: print("7> %s" % right) # if self.debug: print('' return right def parse_token_list_rec(self, min_precedence): """ Parses a tokenized arithmetic expression into a parse tree. It calls itself recursively to handle bracketed subexpressions. :return: Returns a token string. :rtype: lems.parser.expr.ExprNode @attention: Does not handle unary minuses at the moment. Needs to be fixed. """ exit_loop = False ExprParser.depth = ExprParser.depth + 1 if self.debug: print(">>>>> Depth: %i" % ExprParser.depth) precedence = min_precedence while self.token_list: token = self.token_list[0] la = self.token_list[1] if len(self.token_list) > 1 else None if self.debug: print("0> %s" % self.token_list) if self.debug: print( "1> Token: %s, next: %s, op stack: %s, val stack: %s, node stack: %s" % (token, la, self.op_stack, self.val_stack, self.node_stack) ) self.token_list = self.token_list[1:] close_bracket = False if token == "(": np = ExprParser("") np.token_list = self.token_list nexp = np.parse2() self.node_stack.push(nexp) self.val_stack.push("$") self.token_list = np.token_list if self.debug: print(">>> Tokens left: %s" % self.token_list) close_bracket = True elif token == ")": break elif self.is_func(token): self.op_stack.push(token) elif self.is_op(token): stack_top = self.op_stack.top() if self.debug: print( "OP Token: %s (prior: %i), top: %s (prior: %i)" % ( token, self.priority(token), stack_top, self.priority(stack_top), ) ) if self.priority(token) < self.priority(stack_top): if self.debug: print(" Priority of %s is less than %s" % (token, stack_top)) self.node_stack.push(self.cleanup_stacks()) self.val_stack.push("$") else: if self.debug: print( " Priority of %s is greater than %s" % (token, stack_top) ) self.op_stack.push(token) else: if self.debug: print("Not a bracket func or op...") if la == "(": raise Exception( "Error parsing expression: %s\nToken: %s is placed like a function but is not recognised!\nKnown functions: %s" % (self.parse_string, token, known_functions) ) stack_top = self.op_stack.top() if stack_top == "$": if self.debug: print("option a") self.node_stack.push(ValueNode(token)) self.val_stack.push("$") else: if self.is_op(la) and self.priority(stack_top) < self.priority(la): if self.debug: print("option b") self.node_stack.push(ValueNode(token)) self.val_stack.push("$") else: if self.debug: print("option c, nodes: %s" % self.node_stack) op = self.op_stack.pop() right = ValueNode(token) op_node = self.make_op_node(op, right) self.node_stack.push(op_node) self.val_stack.push("$") if close_bracket: stack_top = self.op_stack.top() if self.debug: print( "+ Closing bracket, op stack: %s, node stack: %s la: %s" % (self.op_stack, self.node_stack, la) ) if self.debug: print(">>> Tokens left: %s" % self.token_list) if stack_top == "$": if self.debug: print("+ option a") """ self.node_stack.push(ValueNode(token)) self.val_stack.push('$')""" else: la = self.token_list[0] if len(self.token_list) > 1 else None if self.is_op(la) and self.priority(stack_top) < self.priority(la): if self.debug: print("+ option b") # self.node_stack.push(ValueNode(token)) # self.val_stack.push('$') else: if self.debug: print("+ option c, nodes: %s" % self.node_stack) if self.debug: print( "35> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) right = self.node_stack.pop() op = self.op_stack.pop() op_node = self.make_op_node(stack_top, right) if self.debug: print("Made op node: %s, right: %s" % (op_node, right)) self.node_stack.push(op_node) self.val_stack.push("$") if self.debug: print( "36> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) if self.debug: print( "2> Token: %s, next: %s, op stack: %s, val stack: %s, node stack: %s" % (token, la, self.op_stack, self.val_stack, self.node_stack) ) if self.debug: print("") if self.debug: print( "3> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) ret = self.cleanup_stacks() if self.debug: print( "4> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) if self.debug: print("<<<<< Depth: %s, returning: %s" % (ExprParser.depth, ret)) ExprParser.depth = ExprParser.depth - 1 if self.debug: print("") return ret def parse(self): """ Tokenizes and parses an arithmetic expression into a parse tree. :return: Returns a token string. :rtype: lems.parser.expr.ExprNode """ # print("Parsing: %s"%self.parse_string) self.tokenize() if self.debug: print("Tokens found: %s" % self.token_list) try: parse_tree = self.parse2() except Exception as e: raise e return parse_tree def parse2(self): self.op_stack = Stack() self.val_stack = Stack() self.node_stack = Stack() self.op_stack.push("$") self.val_stack.push("$") try: ret = self.parse_token_list_rec(self.op_priority["$"]) except Exception as e: raise e return ret def __str__(self): return str(self.token_list)
class ExprParser(LEMSBase): ''' Parser class for parsing an expression and generating a parse tree. ''' def __init__(self, parse_string): ''' Constructor. :param parse_string: Expression to be parsed. :type parse_string: string ''' pass def is_op(self, str): ''' Checks if a token string contains an operator. :param str: Token string to be checked. :type str: string :return: True if the token string contains an operator. :rtype: Boolean ''' pass def is_func(self, str): ''' Checks if a token string contains a function. :param str: Token string to be checked. :type str: string :return: True if the token string contains a function. :rtype: Boolean ''' pass def is_sym(self, str): ''' Checks if a token string contains a symbol. :param str: Token string to be checked. :type str: string :return: True if the token string contains a symbol. :rtype: Boolean ''' pass def priority(self, op): pass def tokenize(self): ''' Tokenizes the string stored in the parser object into a list of tokens. ''' pass def make_op_node(self, op, right): pass def cleanup_stacks(self): pass def parse_token_list_rec(self, min_precedence): ''' Parses a tokenized arithmetic expression into a parse tree. It calls itself recursively to handle bracketed subexpressions. :return: Returns a token string. :rtype: lems.parser.expr.ExprNode @attention: Does not handle unary minuses at the moment. Needs to be fixed. ''' pass def parse_token_list_rec(self, min_precedence): ''' Tokenizes and parses an arithmetic expression into a parse tree. :return: Returns a token string. :rtype: lems.parser.expr.ExprNode ''' pass def parse2(self): pass def __str__(self): pass
13
8
31
5
22
5
6
0.21
1
6
4
0
12
5
12
14
417
72
286
44
273
60
198
42
185
40
2
5
77
144,451
LEMS/pylems
lems/parser/expr.py
lems.parser.expr.Func1Node
class Func1Node(ExprNode): """ Unary function node in an expression parse tree. This will always be a non-leaf node. """ def __init__(self, func, param): """ Constructor. :param func: Function to be stored in this node. :type func: string :param param: Parameter. :type param: lems.parser.expr.ExprNode """ ExprNode.__init__(self, ExprNode.FUNC1) self.func = func """ Funcion stored in this node. :type: string """ self.param = param """ Parameter. :type: lems.parser.expr.ExprNode """ def __str__(self): """ Generates a string representation of this node. """ return "({0} {1})".format(self.func, str(self.param)) def __repr__(self): return self.__str__() def to_python_expr(self): return "({0}({1}))".format(self.func, self.param.to_python_expr())
class Func1Node(ExprNode): ''' Unary function node in an expression parse tree. This will always be a non-leaf node. ''' def __init__(self, func, param): ''' Constructor. :param func: Function to be stored in this node. :type func: string :param param: Parameter. :type param: lems.parser.expr.ExprNode ''' pass def __str__(self): ''' Generates a string representation of this node. ''' pass def __repr__(self): pass def to_python_expr(self): pass
5
3
8
2
3
4
1
1.64
1
1
0
0
4
2
4
7
41
12
11
7
6
18
11
7
6
1
3
0
4
144,452
LEMS/pylems
lems/parser/expr.py
lems.parser.expr.OpNode
class OpNode(ExprNode): """ Operation node in an expression parse tree. This will always be a non-leaf node. """ def __init__(self, op, left, right): """ Constructor. :param op: Operation to be stored in this node. :type op: string :param left: Left operand. :type left: lems.parser.expr.ExprNode :param right: Right operand. :type right: lems.parser.expr.ExprNode """ ExprNode.__init__(self, ExprNode.OP) self.op = op """ Operation stored in this node. :type: string """ self.left = left """ Left operand. :type: lems.parser.expr.ExprNode """ self.right = right """ Right operand. :type: lems.parser.expr.ExprNode """ def __str__(self): """ Generates a string representation of this node. """ return "({0} {1} {2})".format(self.op, str(self.left), str(self.right)) def __repr__(self): return self.__str__() def to_python_expr(self): return "({0} {1} {2})".format( self.left.to_python_expr(), self.op, self.right.to_python_expr() )
class OpNode(ExprNode): ''' Operation node in an expression parse tree. This will always be a non-leaf node. ''' def __init__(self, op, left, right): ''' Constructor. :param op: Operation to be stored in this node. :type op: string :param left: Left operand. :type left: lems.parser.expr.ExprNode :param right: Right operand. :type right: lems.parser.expr.ExprNode ''' pass def __str__(self): ''' Generates a string representation of this node. ''' pass def __repr__(self): pass def to_python_expr(self): pass
5
3
11
3
3
5
1
1.57
1
1
0
0
4
3
4
7
51
15
14
8
9
22
12
8
7
1
3
0
4
144,453
LEMS/pylems
lems/parser/expr.py
lems.parser.expr.ValueNode
class ValueNode(ExprNode): """ Value node in an expression parse tree. This will always be a leaf node. """ def __init__(self, value): """ Constructor. :param value: Value to be stored in this node. :type value: string """ ExprNode.__init__(self, ExprNode.VALUE) self.value = value """ Value to be stored in this node. :type: string """ def clean_up(self): """ To make sure an integer is returned as a float. No division by integers!! """ try: return str(float(self.value)) except ValueError: return self.value def __str__(self): """ Generates a string representation of this node. """ return "{" + self.clean_up() + "}" def __repr__(self): return self.__str__() def to_python_expr(self): return self.clean_up()
class ValueNode(ExprNode): ''' Value node in an expression parse tree. This will always be a leaf node. ''' def __init__(self, value): ''' Constructor. :param value: Value to be stored in this node. :type value: string ''' pass def clean_up(self): ''' To make sure an integer is returned as a float. No division by integers!! ''' pass def __str__(self): ''' Generates a string representation of this node. ''' pass def __repr__(self): pass def to_python_expr(self): pass
6
4
6
1
3
3
1
1.07
1
3
0
0
5
1
5
8
39
8
15
7
9
16
15
7
9
2
3
1
6
144,454
LEMS/pylems
lems/run.py
lems.run.Display
class Display: def __init__(self, fig): self.fig = fig self.plots = list() self.legend = list()
class Display: def __init__(self, fig): pass
2
0
4
0
4
0
1
0
0
1
0
0
1
3
1
1
5
0
5
5
3
0
5
5
3
1
0
0
1
144,455
LEMS/pylems
lems/sim/recording.py
lems.sim.recording.Recording
class Recording(LEMSBase): """ Stores details of a variable recording across a single simulation run. """ def __init__(self, variable, full_path, data_output, recorder): self.variable = variable self.full_path = full_path self.data_output = data_output self.recorder = recorder self.values = [] def __str__(self): return "Recording: {0} ({1}), {2}, size: {3}".format( self.variable, self.full_path, self.recorder, len(self.values) ) def __repr__(self): return self.__str__() def add_value(self, time, value): self.values.append((time, value))
class Recording(LEMSBase): ''' Stores details of a variable recording across a single simulation run. ''' def __init__(self, variable, full_path, data_output, recorder): pass def __str__(self): pass def __repr__(self): pass def add_value(self, time, value): pass
5
1
5
1
4
0
1
0.2
1
0
0
0
4
5
4
6
26
8
15
10
10
3
13
10
8
1
2
0
4
144,456
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.Transition
class Transition(Action): """ Regime transition specification. """ def __init__(self, regime): """ Constructor. See instance variable documentation for more details on parameters. """ Action.__init__(self) self.regime = regime """ Regime to transition to. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<Transition regime="{0}"/>'.format(self.regime)
class Transition(Action): ''' Regime transition specification. ''' def __init__(self, regime): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
10
3
3
5
1
2
1
0
0
0
2
1
2
4
25
7
6
4
3
12
6
4
3
1
3
0
2
144,457
LEMS/pylems
lems/parser/expr.py
lems.parser.expr.ExprNode
class ExprNode(LEMSBase): """ Base class for a node in the expression parse tree. """ OP = 1 VALUE = 2 FUNC1 = 3 def __init__(self, type): """ Constructor. :param type: Node type :type type: enum(ExprNode.OP, ExprNode.VALUE) """ self.type = type """ Node type. :type: enum(ExprNode.OP, ExprNode.VALUE) """
class ExprNode(LEMSBase): ''' Base class for a node in the expression parse tree. ''' def __init__(self, type): ''' Constructor. :param type: Node type :type type: enum(ExprNode.OP, ExprNode.VALUE) ''' pass
2
2
12
3
2
7
1
1.67
1
0
0
3
1
1
1
3
21
5
6
6
4
10
6
6
4
1
2
0
1
144,458
LEMS/pylems
lems/sim/runnable.py
lems.sim.runnable.Regime
class Regime: def __init__(self, name): self.name = name self.update_state_variables = None self.update_derived_variables = None self.run_startup_event_handlers = None self.run_preprocessing_event_handlers = None self.run_postprocessing_event_handlers = None self.update_kinetic_scheme = None
class Regime: def __init__(self, name): pass
2
0
8
0
8
0
1
0
0
0
0
0
1
7
1
1
9
0
9
9
7
0
9
9
7
1
0
0
1
144,459
LEMS/pylems
lems/sim/sim.py
lems.sim.sim.Event
class Event: """ Stores data associated with an event. """ def __init__(self, from_id, to_id): self.from_id = from_id """ ID of the source runnable for this event. :type: Integer """ self.to_id = to_id """ ID of the destination runnable for this event. :type: Integer """
class Event: ''' Stores data associated with an event. ''' def __init__(self, from_id, to_id): pass
2
1
10
3
3
4
1
1.75
0
0
0
0
1
2
1
1
15
4
4
4
2
7
4
4
2
1
0
0
1
144,460
LEMS/pylems
lems/sim/sim.py
lems.sim.sim.Simulation
class Simulation(LEMSBase): """ Simulation class. """ debug = False def __init__(self): """ Constructor. """ self.runnables = {} """ Dictionary of runnable components in this simulation. :type: dict(string, lems.sim.runnable.Runnable) """ self.run_queue = [] """ Priority of pairs of (time-to-next run, runnable). :type: list((Integer, lems.sim.runnable.Runnable)) """ self.event_queue = [] """ List of posted events. :type: list(lems.sim.sim.Event) """ def add_runnable(self, runnable): """ Adds a runnable component to the list of runnable components in this simulation. :param runnable: A runnable component :type runnable: lems.sim.runnable.Runnable """ if runnable.id in self.runnables: raise SimError("Duplicate runnable component {0}".format(runnable.id)) self.runnables[runnable.id] = runnable def init_run(self): self.current_time = 0 for id in self.runnables: self.runnables[id].do_startup() heapq.heappush(self.run_queue, (0, self.runnables[id])) def step(self): current_time = self.current_time if self.run_queue == []: return False (current_time, runnable) = heapq.heappop(self.run_queue) time = current_time while time == current_time: next_time = current_time + runnable.single_step(runnable.time_step) if next_time > current_time: heapq.heappush(self.run_queue, (next_time, runnable)) if self.run_queue == []: break (time, runnable) = heapq.heappop(self.run_queue) if time > current_time: heapq.heappush(self.run_queue, (time, runnable)) self.current_time = current_time if self.run_queue == []: return False else: return True def run(self): """ Runs the simulation. """ self.init_run() if self.debug: self.dump("AfterInit: ") # print("++++++++++++++++ Time: %f"%self.current_time) while self.step(): # self.dump("Time: %f"%self.current_time) # print("++++++++++++++++ Time: %f"%self.current_time) pass def push_state(self): for id in self.runnables: self.runnables[id].push_state() def pop_state(self): for id in self.runnables: self.runnables[id].pop_state() def enable_plasticity(self): for id in self.runnables: self.runnables[id].plastic = True def disable_plasticity(self): for id in self.runnables: self.runnables[id].plastic = False def dump_runnable(self, runnable, prefix="."): r = runnable print("{0}............... {1} ({2})".format(prefix, r.id, r.component.type)) print(prefix + str(r)) ignores = ["Display", "Line", "OutputColumn", "OutputFile", "Simulation"] verbose = r.component.type not in ignores if verbose: if r.instance_variables: print("{0} Instance variables".format(prefix)) for vn in r.instance_variables: print("{0} {1} = {2}".format(prefix, vn, r.__dict__[vn])) if r.derived_variables: print("{0} Derived variables".format(prefix)) for vn in r.derived_variables: print("{0} {1} = {2}".format(prefix, vn, r.__dict__[vn])) if verbose: keys = list(r.__dict__.keys()) keys.sort() print("{0} Keys for {1}".format(prefix, r.id)) for k in keys: key_str = str(r.__dict__[k]) if len(key_str) > 0 and not key_str == "[]" and not key_str == "{}": print("{0} {1} -> {2}".format(prefix, k, key_str)) if r.array: for c in r.array: self.dump_runnable(c, prefix + " .") if r.uchildren: for cn in r.uchildren: self.dump_runnable(r.uchildren[cn], prefix + " .") def dump(self, prefix=""): print("Runnables:") for id in self.runnables: self.dump_runnable(self.runnables[id], prefix)
class Simulation(LEMSBase): ''' Simulation class. ''' def __init__(self): ''' Constructor. ''' pass def add_runnable(self, runnable): ''' Adds a runnable component to the list of runnable components in this simulation. :param runnable: A runnable component :type runnable: lems.sim.runnable.Runnable ''' pass def init_run(self): pass def step(self): pass def run(self): ''' Runs the simulation. ''' pass def push_state(self): pass def pop_state(self): pass def enable_plasticity(self): pass def disable_plasticity(self): pass def dump_runnable(self, runnable, prefix="."): pass def dump_runnable(self, runnable, prefix="."): pass
12
4
11
2
8
2
3
0.28
1
3
1
0
11
4
11
13
141
31
86
36
74
24
85
36
73
13
2
3
38
144,461
LEMS/pylems
lems/test/reg_test_20.py
reg_test_20.TestIssue20Regression
class TestIssue20Regression(unittest.TestCase): """Regression test for issue #20 PyLEMS does not initialise initMembPotential correctly. """ def test_initMembPotential_init(self): """Test for https://github.com/LEMS/pylems/issues/20""" initmembpot = -20.000000000000000000000 reg_20_nml = textwrap.dedent( """<neuroml xmlns="http://www.neuroml.org/schema/neuroml2" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.neuroml.org/schema/neuroml2 https://raw.github.com/NeuroML/NeuroML2/development/Schemas/NeuroML2/NeuroML_v2beta3.xsd" id="TestDoc"> <!-- regression test data for https://github.com/LEMS/pylems/issues/20 --> <ionChannel id="chnl_lk" type="ionChannelPassive" conductance="1nS" /> <cell id="cell1"> <morphology id="morpho"> <segment id ="0" name="Soma"> <proximal x="0" y="0" z="0" diameter="10"/> <distal x="10" y="0" z="0" diameter="10"/> </segment> <!-- Segment group probably not needed? --> <segmentGroup id="segs_soma"> <member segment="0" /> </segmentGroup> </morphology> <biophysicalProperties id="bio_cell"> <membraneProperties> <channelPopulation id="chn_pop_lk" ionChannel="chnl_lk" number="1" erev="-50mV" /> <spikeThresh value="20mV" /> <specificCapacitance value="1.0 uF_per_cm2" segmentGroup="segs_soma" /> <initMembPotential value="{}mV" /> </membraneProperties> <intracellularProperties /> </biophysicalProperties> </cell> </neuroml> """.format( initmembpot ) ) nml_file = tempfile.NamedTemporaryFile(mode="w+b") nml_file.write(str.encode(reg_20_nml)) nml_file.flush() reg_20_xml = textwrap.dedent( """<Lems> <!-- regression test data for https://github.com/LEMS/pylems/issues/20 --> <Target component="sim1"/> <Include file="Simulation.xml"/> <Include file="Cells.xml"/> <Include file="{}"/> <Simulation id="sim1" length="100ms" step="0.1ms" target="cell1"> <!-- (x|y)(min|max) don't appear to do anything with PyLEMS, but error if not included... --> <OutputFile path="." fileName="reg_20.dat"> <OutputColumn quantity="v" /> </OutputFile> </Simulation> </Lems> """.format( nml_file.name ) ) xml_file = tempfile.NamedTemporaryFile(mode="w+b") xml_file.write(str.encode(reg_20_xml)) xml_file.flush() # TODO: replace this with pynml's extract LEMS files function when that has # been merged and released. We won't need to carry a copy of the coretypes # then. coretype_files_dir = ( os.path.dirname(os.path.abspath(__file__)) + "/NeuroML2CoreTypes" ) lems_run(xml_file.name, include_dirs=[coretype_files_dir]) # Deletes the files also nml_file.close() xml_file.close() with open("reg_20.dat", "r") as res: for line in res: ln = line.split() time = float(ln[0]) value = float(ln[1]) assert time == 0 self.assertAlmostEqual(value, initmembpot / 1000.0, delta=0.01) # We only want to check the first line break os.remove("reg_20.dat")
class TestIssue20Regression(unittest.TestCase): '''Regression test for issue #20 PyLEMS does not initialise initMembPotential correctly. ''' def test_initMembPotential_init(self): '''Test for https://github.com/LEMS/pylems/issues/20''' pass
2
2
88
11
71
6
2
0.13
1
2
0
0
1
0
1
73
95
14
72
13
70
9
24
12
22
2
2
2
2
144,462
LEMS/pylems
lems/test/test_load_write.py
test_load_write.TestLoadWrite
class TestLoadWrite(unittest.TestCase): def test_load_write_xml(self): model = Model() file_name = "lems/test/hhcell_resaved2.xml" model.import_from_file(file_name) file_name2 = "lems/test/hhcell_resaved3.xml" model.export_to_file(file_name2) print("----------------------------------------------") print(open(file_name2, "r").read()) print("----------------------------------------------") print("Written generated LEMS to %s" % file_name2) from lems.base.util import validate_lems validate_lems(file_name2) def test_load_get_dom(self): model = Model() file_name = "lems/test/hhcell_resaved2.xml" model.import_from_file(file_name) dom0 = model.export_to_dom()
class TestLoadWrite(unittest.TestCase): def test_load_write_xml(self): pass def test_load_get_dom(self): pass
3
0
11
2
9
0
1
0
1
1
1
0
2
0
2
74
23
5
18
10
14
0
18
10
14
1
2
0
2
144,463
LEMS/pylems
lems/test/test_misc.py
test_misc.TestExposure
class TestExposure(unittest.TestCase): """Test getting exposures from LEMS models""" def test_exposure_getters(self): model = Model(include_includes=True, fail_on_missing_includes=True) file_name = ( os.path.dirname(os.path.abspath(__file__)) + "/test_exposure_listing.xml" ) model.import_from_file(file_name) exp_list = model.list_exposures() for c, es in exp_list.items(): # iaf1 defines v as an exposure if c.id == "example_iaf1_cell": self.assertTrue("v" in es) # iaf2 extends iaf1 and so should inherit v if c.id == "example_iaf2_cell": self.assertTrue("v" in es) paths = model.list_recording_paths_for_exposures(substring="", target="net1") self.assertTrue("net1/p1[0]/v" in paths) self.assertTrue("net1/p1[1]/v" in paths) self.assertTrue("net1/p1[2]/v" in paths) self.assertTrue("net1/p1[3]/v" in paths) self.assertTrue("net1/p1[4]/v" in paths) self.assertTrue("net1/p2[0]/v" in paths)
class TestExposure(unittest.TestCase): '''Test getting exposures from LEMS models''' def test_exposure_getters(self): pass
2
1
22
1
19
2
4
0.15
1
1
1
0
1
0
1
73
26
3
20
7
18
3
18
7
16
4
2
2
4
144,464
LEMS/pylems
lems/test/test_parser.py
test_parser.TestParser
class TestParser(unittest.TestCase): def test_parser(self): x = 0.5 exprs = {} exprs["x"] = "{x}" exprs["exp(x)"] = "(exp {x})" all = False all = True if all: exprs[ "(R * temperature / (zCa * F)) * log(caConcExt / caConc)" ] = "(* (/ (* {R} {temperature}) (* {zCa} {F})) (log (/ {caConcExt} {caConc})))" exprs[ "( (V - ((V^3) / 3)) - W + I) / SEC" ] = "(/ (+ (- (- {V} (/ (^ {V} {3.0}) {3.0})) {W}) {I}) {SEC})" exprs[ "(V - (V^3) / 3 - W + I) / SEC" ] = "(/ (- {V} (+ (- (/ (^ {V} {3.0}) {3.0}) {W}) {I})) {SEC})" exprs["120+300"] = "(+ {120.0} {300.0})" exprs["12e-22"] = "{1.2e-21}" exprs["1e+22"] = "{1e+22}" exprs["1-1E+2+2"] = "(+ (- {1.0} {100.0}) {2.0})" exprs["5.0E-11"] = "{5e-11}" exprs["a + (b + c) * d"] = "(+ {a} (* (+ {b} {c}) {d}))" exprs["1 + (exp(x))"] = "(+ {1.0} (exp {x}))" exprs["exp(x)"] = "(exp {x})" exprs["x / y * z"] = "(* (/ {x} {y}) {z})" exprs["x / (y) * z"] = "(* (/ {x} {y}) {z})" exprs["(y - z) + t"] = "(+ (- {y} {z}) {t})" exprs["x + (y) - z"] = "(- (+ {x} {y}) {z})" exprs["exp(v*2)"] = "(exp (* {v} {2.0}))" exprs["exp(-x)"] = "(exp (- {0.0} {x}))" exprs["sin(y)"] = "(sin {y})" exprs["H(y)"] = "(H {y})" exprs["a / b"] = "(/ {a} {b})" exprs["a / (b)"] = "(/ {a} {b})" exprs[ "(120 + 300/( (exp ((V + 55)/9)) + (exp ((V + 65)/(-16)))))" ] = "(+ {120.0} (/ {300.0} (+ (exp (/ (+ {V} {55.0}) {9.0})) (exp (/ (+ {V} {65.0}) (- {0.0} {16.0}))))))" exprs[ "(43.4 - 42.6/(1.0 + (exp ((V + 68.1)/(-20.5)))))" ] = "(- {43.4} (/ {42.6} (+ {1.0} (exp (/ (+ {V} {68.1}) (- {0.0} {20.5}))))))" exprs[ "(2.64 - 2.52/(1.0 + (exp ((V+120)/(-25)))))" ] = "(- {2.64} (/ {2.52} (+ {1.0} (exp (/ (+ {V} {120.0}) (- {0.0} {25.0}))))))" exprs[ "(1.34 / (1.0 + (exp ((V + 62.9)/(-10)))) * (1.5 + 1.0/(1.0 + (exp ((V+34.9)/3.6)))))" ] = "(* (/ {1.34} (+ {1.0} (exp (/ (+ {V} {62.9}) (- {0.0} {10.0}))))) (+ {1.5} (/ {1.0} (+ {1.0} (exp (/ (+ {V} {34.9}) {3.6}))))))" for expr in exprs.keys(): self.parse_expr(expr, exprs[expr]) bad_exprs = {} bad_exprs["exxp(x)"] = "(exxp {x})" bad_exprs["ln(x)"] = "(ln {x})" # Use log instead!! for expr in bad_exprs.keys(): self.parse_expr(expr, bad_exprs[expr], True) def parse_expr(self, expr, val, should_fail=False): print("\n--- Parsing %s, checking against %s" % (expr, val)) ep = ExprParser(expr) try: pt = ep.parse() print("Expr: %s " % expr) print("Parsed as: %s " % (str(pt))) print("Expected : %s " % (val)) print("Math : %s " % (pt.to_python_expr())) assert str(pt) == val print("Success") except Exception as e: if not should_fail: print("Exception thrown %s" % e) assert 1 == 2 else: print("Successfully failed")
class TestParser(unittest.TestCase): def test_parser(self): pass def parse_expr(self, expr, val, should_fail=False): pass
3
0
41
6
36
1
4
0.01
1
3
1
0
2
0
2
74
84
12
72
10
69
1
57
9
54
4
2
2
7
144,465
LEMS/pylems
lems/test/test_units.py
test_units.TestUnitParsing
class TestUnitParsing(unittest.TestCase): def get_model(self): model = Model() model.add(Dimension("voltage", m=1, l=3, t=-3, i=-1)) model.add(Dimension("time", t=1)) model.add(Dimension("capacitance", m=-1, l=-2, t=4, i=2)) model.add(Dimension("conductanceDensity", m="-1", l="-4", t="3", i="2")) model.add(Dimension("temperature", k=1)) model.add(Unit("volt", "V", "voltage", 0)) model.add(Unit("milliVolt", "mV", "voltage", -3)) model.add(Unit("milliSecond", "ms", "time", -3)) model.add(Unit("microFarad", "uF", "capacitance", -12)) model.add(Unit("mS_per_cm2", "mS_per_cm2", "conductanceDensity", 1)) model.add(Unit("Kelvin", "K", "temperature", 0)) model.add(Unit("celsius", "degC", "temperature", 0, offset=273.15)) model.add(Unit("hour", "hour", "time", scale=3600)) model.add(Unit("min", "min", "time", scale=60)) return model def check_num_val(self, unit_str, val, dimension=None): val2 = self.get_model().get_numeric_value(unit_str, dimension) print( "Ensuring %s returns %f in SI units of %s; it returns %f" % (unit_str, val, dimension, val2) ) self.assertAlmostEqual(val, val2) def test_parse_units(self): self.check_num_val("-60mV", -0.06, "voltage") self.check_num_val("1V", 1, "voltage") self.check_num_val("10 K", 10) self.check_num_val("0 K", 0) self.check_num_val("0 degC", 273.15) self.check_num_val("-40 degC", 233.15) self.check_num_val("1.1e-2 ms", 0.000011, "time") self.check_num_val("5E-24", 5e-24) self.check_num_val("1.1ms", 0.0011) self.check_num_val("-60mV", -0.060) self.check_num_val("-60", -60) self.check_num_val("1.1e-2 ms", 0.000011) self.check_num_val("10.5 mS_per_cm2", 105, "conductanceDensity") self.check_num_val("10.5 mS_per_cm2", 105) self.check_num_val("1 hour", 3600) self.check_num_val("30 min", 30 * 60)
class TestUnitParsing(unittest.TestCase): def get_model(self): pass def check_num_val(self, unit_str, val, dimension=None): pass def test_parse_units(self): pass
4
0
16
3
14
0
1
0
1
3
3
0
3
0
3
75
52
10
42
6
38
0
39
6
35
1
2
0
3
144,466
LEMS/pylems
lems/sim/runnable.py
lems.sim.runnable.Runnable
class Runnable(Reflective): uid_count = 0 def __init__(self, id_, component, parent=None): Reflective.__init__(self) self.uid = Runnable.uid_count Runnable.uid_count += 1 self.id = id_ self.component = component self.parent = parent self.time_step = 0 self.time_completed = 0 self.time_total = 0 self.plastic = True self.state_stack = Stack() self.children = {} self.uchildren = {} self.groups = [] self.recorded_variables = [] self.event_out_ports = [] self.event_in_ports = [] self.event_out_callbacks = {} self.event_in_counters = {} self.attachments = {} self.new_regime = "" self.current_regime = "" self.last_regime = "" self.regimes = {} def __str__(self): return "Runnable, id: {0} ({1}, {2}), component: ({3})".format( self.id, self.uid, id(self), self.component ) def __repr__(self): return self.__str__() def add_child(self, id_, runnable): self.uchildren[runnable.uid] = runnable self.children[id_] = runnable self.children[runnable.id] = runnable self.__dict__[id_] = runnable self.__dict__[runnable.id] = runnable runnable.configure_time(self.time_step, self.time_total) runnable.parent = self def add_child_typeref(self, typename, runnable): self.__dict__[typename] = runnable def add_child_to_group(self, group_name, child): # print("add_child_to_group in %s; grp: %s; child: %s "%(self.id, group_name, child)) if group_name not in self.__dict__: # print sorted(self.__dict__.keys()) self.__dict__[group_name] = [] self.groups.append(group_name) # print sorted(self.__dict__.keys()) # print ".........." # print self.__dict__[group_name] # Force group_name attribute to be a list before we append to it. if type(self.__dict__[group_name]) is not list: self.__dict__[group_name] = [self.__dict__[group_name]] self.__dict__[group_name].append(child) child.parent = self def make_attachment(self, type_, name): self.attachments[type_] = name self.__dict__[name] = [] def add_attachment(self, runnable, container=None): for ctype in runnable.component.types: if ctype in self.attachments: name = self.attachments[ctype] if container is not None and container != name: continue if name not in self.__dict__: raise SimBuildError( "Cannot attach {0} to {1} in {2}".format( runnable.id, name, self.id ) ) runnable.id = runnable.id + str(len(self.__dict__[name])) self.__dict__[name].append(runnable) runnable.parent = self return raise SimBuildError( "Unable to find appropriate attachment for {0} in {1}", runnable.id, self.id ) def add_event_in_port(self, port): self.event_in_ports.append(port) if port not in self.event_in_counters: self.event_in_counters[port] = 0 def inc_event_in(self, port): self.event_in_counters[port] += 1 if self.debug: print( "\n--- Event in to %s (%s, %s) on port: %s" % (self.id, id(self), self.__class__, port) ) print("EIC (%s): %s" % (id(self), self.event_in_counters)) def add_event_out_port(self, port): self.event_out_ports.append(port) if port not in self.event_out_callbacks: self.event_out_callbacks[port] = [] def register_event_out_link(self, port, runnable, remote_port): self.event_out_callbacks[port].append((runnable, remote_port)) def register_event_out_callback(self, port, callback): if self.debug: print( "register_event_out_callback on %s, port: %s, callback: %s" % (self.id, port, callback) ) if port in self.event_out_callbacks: self.event_out_callbacks[port].append(callback) else: raise SimBuildError( "No event out port '{0}' in " "component '{1}'".format(port, self.id) ) if self.debug: print("EOC: " + str(self.event_out_callbacks)) def add_regime(self, regime): self.regimes[regime.name] = regime def resolve_path(self, path): if self.debug: print("Resolving path: %s in %s" % (path, self)) if path == "": return self if path == "this": return self if path[0] == "/": return self.parent.resolve_path(path) elif path.find("../") == 0: return self.parent.resolve_path(path[3:]) elif path.find("..") == 0: return self.parent elif path == "parent": return self.parent else: if path.find("/") >= 1: (child, new_path) = path.split("/", 1) else: child = path new_path = "" idxbegin = child.find("[") idxend = child.find("]") if idxbegin != 0 and idxend > idxbegin: idx = int(child[idxbegin + 1 : idxend]) child = child[:idxbegin] else: idx = -1 if child in self.children: childobj = self.children[child] if idx != -1: childobj = childobj.array[idx] elif child in self.component.parameters: ctx = self.component p = ctx.parameters[child] return self.resolve_path("../" + p.value) elif child in self.__dict__.keys(): child_resolved = self.__dict__[child] # print("Think it's a link from %s to %s"%(child, child_resolved)) return self.resolve_path("../" + child_resolved) else: if self.debug: keys = list(self.__dict__.keys()) keys.sort() prefix = "--- " print("{0} Keys for {1}".format(prefix, self.id)) for k in keys: key_str = str(self.__dict__[k]) if ( len(key_str) > 0 and not key_str == "[]" and not key_str == "{}" ): print("{0} {1} -> {2}".format(prefix, k, key_str)) raise SimBuildError( "Unable to find child '{0}' in " "'{1}'".format(child, self.id) ) if new_path == "": return childobj else: return childobj.resolve_path(new_path) def add_variable_recorder(self, data_output, recorder): self.add_variable_recorder2( data_output, recorder, recorder.quantity, recorder.quantity ) def add_variable_recorder2(self, data_output, recorder, path, full_path): if path[0] == "/": self.parent.add_variable_recorder2(data_output, recorder, path, full_path) elif path.find("../") == 0: self.parent.add_variable_recorder2( data_output, recorder, path[3:], full_path ) elif path.find("/") >= 1: (child, new_path) = path.split("/", 1) if ":" in child: syn_parts = child.split(":") if syn_parts[0] == "synapses" and syn_parts[2] == "0": child = syn_parts[1] else: raise SimBuildError( "Cannot determine what to do with (synapse?) path: %s (full path: %s)" % (child, full_path) ) idxbegin = child.find("[") idxend = child.find("]") if idxbegin != 0 and idxend > idxbegin: idx = int(child[idxbegin + 1 : idxend]) child = child[:idxbegin] else: idx = -1 if child in self.children: childobj = self.children[child] if idx == -1: childobj.add_variable_recorder2( data_output, recorder, new_path, full_path ) else: childobj.array[idx].add_variable_recorder2( data_output, recorder, new_path, full_path ) elif child in self.component.children: cdef = self.component.children[child] childobj = None for cid in self.children: c = self.children[cid] if cdef.type in c.component.types: childobj = c if childobj: childobj.add_variable_recorder2(data_output, recorder, new_path) else: raise SimBuildError( "Unable to find the child '{0}' in " "'{1}'".format(child, self.id) ) else: raise SimBuildError( "Unable to find a child '{0}' in " "'{1}'".format(child, self.id) ) else: self.recorded_variables.append( Recording(path, full_path, data_output, recorder) ) def configure_time(self, time_step, time_total): self.time_step = time_step self.time_total = time_total for cn in self.uchildren: self.uchildren[cn].configure_time(self.time_step, self.time_total) for c in self.array: c.configure_time(self.time_step, self.time_total) ## for type_ in self.attachments: ## components = self.__dict__[self.attachments[type_]] ## for component in components: ## component.configure_time(self.time_step, self.time_total) def reset_time(self): self.time_completed = 0 for cid in self.uchildren: self.uchildren[cid].reset_time() for c in self.array: c.reset_time() ## for type_ in self.attachments: ## components = self.__dict__[self.attachments[type_]] ## for component in components: ## component.reset_time() def single_step(self, dt): # return self.single_step2(dt) # For debugging try: return self.single_step2(dt) # except Ex1 as e: # print self.rate # print self.midpoint # print self.scale # print self.parent.parent.parent.parent.v # # rate * exp((v - midpoint)/scale) # sys.exit(0) except KeyError as e: r = self name = r.id while r.parent: r = r.parent name = "{0}.{1}".format(r.id, name) print("Error in '{0} ({1})': {2}".format(name, self.component.type, e)) print(e) prefix = "- " if self.instance_variables: print("Instance variables".format(prefix)) for vn in self.instance_variables: print("{0} {1} = {2}".format(prefix, vn, self.__dict__[vn])) if self.derived_variables: print("{0} Derived variables".format(prefix)) for vn in self.derived_variables: print("{0} {1} = {2}".format(prefix, vn, self.__dict__[vn])) keys = list(self.__dict__.keys()) keys.sort() for k in keys: print("{0} -> {1}".format(k, str(self.__dict__[k]))) print("") print("") if isinstance(e, ArithmeticError): print( ( "This is an arithmetic error. Consider reducing the " "integration time step." ) ) sys.exit(0) def single_step2(self, dt): for cid in self.uchildren: self.uchildren[cid].single_step(dt) for child in self.array: child.single_step(dt) """ Regime transition now happens below... if self.new_regime != '': self.current_regime = self.new_regime self.new_regime = """ "" if getattr(self, "update_kinetic_scheme", None): self.update_kinetic_scheme(self, dt) # if self.time_completed == 0: # self.run_startup_event_handlers(self) if getattr(self, "run_preprocessing_event_handlers", None): self.run_preprocessing_event_handlers(self) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if getattr(self, "update_derived_variables", None): self.update_derived_variables(self) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if getattr(self, "update_state_variables", None): self.update_state_variables(self, dt) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() # if self.time_completed == 0: # self.update_derived_parameters(self) if getattr(self, "run_postprocessing_event_handlers", None): self.run_postprocessing_event_handlers(self) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if False: # self.id == 'hhpop__hhcell__0': print("1", self.uid, self.v) if False: # self.id == 'reverseRate': print( "2", self.parent.parent.parent.parent.uid, self.parent.parent.parent.parent.v, ) if self.current_regime != "": if self.debug: print("In reg: " + self.current_regime) regime = self.regimes[self.current_regime] # if getattr(self, "xxx", None): if getattr(regime, "update_kinetic_scheme", None): regime.update_kinetic_scheme(self, dt) if getattr(regime, "run_preprocessing_event_handlers", None): regime.run_preprocessing_event_handlers(self) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if getattr(regime, "update_derived_variables", None): regime.update_derived_variables(self) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if getattr(regime, "update_state_variables", None): regime.update_state_variables(self, dt) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if getattr(regime, "run_postprocessing_event_handlers", None): regime.run_postprocessing_event_handlers(self) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if self.new_regime != "": self.current_regime = self.new_regime self.new_regime = "" regime = self.regimes[self.current_regime] if getattr(regime, "run_preprocessing_event_handlers", None): regime.run_preprocessing_event_handlers(self) if getattr(self, "update_shadow_variables", None): self.update_shadow_variables() if self.debug: print("In reg: " + self.current_regime) self.record_variables() self.time_completed += dt if self.time_completed >= self.time_total: return 0 else: return dt def do_startup(self): if self.debug and False: print(" Doing startup: " + self.id) for iv in self.instance_variables: print("%s = %s" % (iv, self.__dict__[iv])) for dv in self.derived_variables: print("%s = %s" % (dv, self.__dict__[dv])) for cid in self.uchildren: self.uchildren[cid].do_startup() for child in self.array: child.do_startup() # if getattr(self, "xxx", None): if getattr(self, "update_derived_parameters", None): self.update_derived_parameters(self) try: if getattr(self, "update_derived_variables", None): self.update_derived_variables(self) except Exception as e: print( "Problem setting initial value of DerivedVariable in %s: %s" % (self.id, e) ) print("Continuing...") # Run start up handlers after all the variables have been set up if getattr(self, "run_startup_event_handlers", None): self.run_startup_event_handlers(self) for cid in self.uchildren: self.uchildren[cid].do_startup() for child in self.array: child.do_startup() def record_variables(self): for recording in self.recorded_variables: recording.add_value(self.time_completed, self.__dict__[recording.variable]) def push_state(self): vars = [] for varname in self.instance_variables: vars += [self.__dict__[varname], self.__dict__[varname + "_shadow"]] self.state_stack.push(vars) for cid in self.uchildren: self.uchildren[cid].push_state() for c in self.array: c.push_state() def pop_state(self): vars = self.state_stack.pop() for varname in self.instance_variables: self.__dict_[varname] = vars[0] self.__dict_[varname + "_shadow"] = vars[1] vars = vars[2:] for cid in self.uchildren: self.uchildren[cid].pop_state() for c in self.array: c.pop_state() def update_shadow_variables(self): if self.plastic: for var in self.instance_variables: self.__dict__[var + "_shadow"] = self.__dict__[var] for var in self.derived_variables: self.__dict__[var + "_shadow"] = self.__dict__[var] def __lt__(self, other): return self.id < other.id def copy(self): """ Make a copy of this runnable. :return: Copy of this runnable. :rtype: lems.sim.runnable.Runnable """ if self.debug: print("Coping....." + self.id) r = Runnable(self.id, self.component, self.parent) copies = dict() # Copy simulation time parameters r.time_step = self.time_step r.time_completed = self.time_completed r.time_total = self.time_total # Plasticity and state stack (?) r.plastic = self.plastic r.state_stack = Stack() # Copy variables (GG - Faster using the add_* methods?) for v in self.instance_variables: r.instance_variables.append(v) r.__dict__[v] = self.__dict__[v] r.__dict__[v + "_shadow"] = self.__dict__[v + "_shadow"] for v in self.derived_variables: r.derived_variables.append(v) r.__dict__[v] = self.__dict__[v] r.__dict__[v + "_shadow"] = self.__dict__[v + "_shadow"] # Copy array elements for child in self.array: child_copy = child.copy() child_copy.parent = r r.array.append(child_copy) copies[child.uid] = child_copy # Copy attachment def for att in self.attachments: atn = self.attachments[att] r.attachments[att] = atn r.__dict__[atn] = [] # Copy children for uid in self.uchildren: child = self.uchildren[uid] child_copy = child.copy() child_copy.parent = r copies[child.uid] = child_copy r.add_child(child_copy.id, child_copy) # For typerefs try: idx = [k for k in self.__dict__ if self.__dict__[k] == child][0] r.__dict__[idx] = child_copy except: pass # For groups and attachments: try: idx = [k for k in self.__dict__ if child in self.__dict__[k]][0] if idx not in r.__dict__: r.__dict__[idx] = [] r.__dict__[idx].append(child_copy) except: pass # Copy event ports for port in self.event_in_ports: r.event_in_ports.append(port) r.event_in_counters[port] = 0 for port in self.event_out_ports: r.event_out_ports.append(port) r.event_out_callbacks[port] = self.event_out_callbacks[port] for ec in r.component.structure.event_connections: if self.debug: print("--- Fixing event_connection: %s in %s" % (ec.toxml(), id(r))) source = r.parent.resolve_path(ec.from_) target = r.parent.resolve_path(ec.to) if ec.receiver: # Will throw error... receiver_template = self.build_runnable(ec.receiver, target) # receiver = copy.deepcopy(receiver_template) receiver = receiver_template.copy() receiver.id = "{0}__{1}__".format(component.id, receiver_template.id) if ec.receiver_container: target.add_attachment(receiver, ec.receiver_container) target.add_child(receiver_template.id, receiver) target = receiver else: source = r.resolve_path(ec.from_) target = r.resolve_path(ec.to) source_port = ec.source_port target_port = ec.target_port if not source_port: if len(source.event_out_ports) == 1: source_port = source.event_out_ports[0] else: raise SimBuildError( ( "No source event port " "uniquely identifiable" " in '{0}'" ).format(source.id) ) if not target_port: if len(target.event_in_ports) == 1: target_port = target.event_in_ports[0] else: raise SimBuildError( ( "No destination event port " "uniquely identifiable " "in '{0}'" ).format(target) ) if self.debug: print( "register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)" % (source, id(source), source_port, target, id(target), target_port) ) source.register_event_out_callback( source_port, lambda: target.inc_event_in(target_port) ) # Copy methods if getattr(self, "update_kinetic_scheme", None): r.update_kinetic_scheme = self.update_kinetic_scheme if getattr(self, "run_startup_event_handlers", None): r.run_startup_event_handlers = self.run_startup_event_handlers if getattr(self, "run_preprocessing_event_handlers", None): r.run_preprocessing_event_handlers = self.run_preprocessing_event_handlers if getattr(self, "run_postprocessing_event_handlers", None): r.run_postprocessing_event_handlers = self.run_postprocessing_event_handlers if getattr(self, "update_state_variables", None): r.update_state_variables = self.update_state_variables if getattr(self, "update_derived_variables", None): r.update_derived_variables = self.update_derived_variables # r.update_shadow_variables = self.update_shadow_variables if getattr(self, "update_derived_parameters", None): r.update_derived_parameters = self.update_derived_parameters for rn in self.regimes: r.add_regime(self.regimes[rn]) r.current_regime = self.current_regime # Copy groups for gn in self.groups: g = self.__dict__[gn] for c in g: if c.uid in copies: r.add_child_to_group(gn, copies[c.uid]) else: c2 = c.copy() c2.parent = r copies[c.uid] = c2 r.add_child_to_group(gn, c2) # Copy remaining runnable references. for k in self.__dict__: if k == "parent": continue c = self.__dict__[k] if isinstance(c, Runnable): if c.uid in copies: r.__dict__[k] = copies[c.uid] else: c2 = c.copy() c2.parent = r copies[c.uid] = c2 r.__dict__[k] = c2 # Copy text fields for k in self.__dict__: if not k in r.__dict__: c = self.__dict__[k] if self.debug: print("Adding remaining field: %s = %s" % (k, c)) r.__dict__[k] = c if self.debug: print("########################################") keys = list(self.__dict__.keys()) keys.sort() print(len(keys)) for k in keys: print(k, self.__dict__[k]) print("----------------------------------------") keys = list(r.__dict__.keys()) keys.sort() print(len(keys)) for k in keys: print(k, r.__dict__[k]) print("########################################") print("") print("") print("") print("") if self.debug: print("Finished coping..." + self.id) return r
class Runnable(Reflective): def __init__(self, id_, component, parent=None): pass def __str__(self): pass def __repr__(self): pass def add_child(self, id_, runnable): pass def add_child_typeref(self, typename, runnable): pass def add_child_to_group(self, group_name, child): pass def make_attachment(self, type_, name): pass def add_attachment(self, runnable, container=None): pass def add_event_in_port(self, port): pass def inc_event_in(self, port): pass def add_event_out_port(self, port): pass def register_event_out_link(self, port, runnable, remote_port): pass def register_event_out_callback(self, port, callback): pass def add_regime(self, regime): pass def resolve_path(self, path): pass def add_variable_recorder(self, data_output, recorder): pass def add_variable_recorder2(self, data_output, recorder, path, full_path): pass def configure_time(self, time_step, time_total): pass def reset_time(self): pass def single_step(self, dt): pass def single_step2(self, dt): pass def do_startup(self): pass def record_variables(self): pass def push_state(self): pass def pop_state(self): pass def update_shadow_variables(self): pass def __lt__(self, other): pass def copy(self): ''' Make a copy of this runnable. :return: Copy of this runnable. :rtype: lems.sim.runnable.Runnable ''' pass
29
1
25
4
20
2
6
0.1
1
11
3
0
28
22
28
37
750
128
570
123
541
56
473
123
444
43
3
5
173
144,467
LEMS/pylems
lems/parser/LEMS.py
lems.parser.LEMS.LEMSXMLNode
class LEMSXMLNode: def __init__(self, pyxmlnode): self.tag = get_nons_tag_from_node(pyxmlnode) self.ltag = self.tag.lower() self.attrib = dict() self.lattrib = dict() for k in pyxmlnode.attrib: self.attrib[k] = pyxmlnode.attrib[k] self.lattrib[k.lower()] = pyxmlnode.attrib[k] self.children = list() for pyxmlchild in pyxmlnode: self.children.append(LEMSXMLNode(pyxmlchild)) def __str__(self): return "LEMSXMLNode <{0} {1}>".format(self.tag, self.attrib)
class LEMSXMLNode: def __init__(self, pyxmlnode): pass def __str__(self): pass
3
0
8
2
7
0
2
0
0
2
0
0
2
5
2
2
18
4
14
10
11
0
14
10
11
3
0
1
4
144,468
LEMS/pylems
lems/sim/runnable.py
lems.sim.runnable.Reflective
class Reflective(LEMSBase): debug = False def __init__(self): self.instance_variables = [] self.derived_variables = [] self.array = [] self.methods = {} # self.total_code_string = '' # @classmethod def add_method(self, method_name, parameter_list, statements): if statements == []: return code_string = "def __generated_function__" if parameter_list == []: code_string += "():\n" else: code_string += "(" + parameter_list[0] for parameter in parameter_list[1:]: code_string += ", " + parameter code_string += "):\n" for statement in statements: if "random.uniform" in statement: code_string += " import random\n" if self.debug: code_string += ( ' if "xxx" in "%s": print("Calling method: %s(), dv: %s, iv: %s")\n' % ( method_name, method_name, str(self.derived_variables), str(self.instance_variables), ) ) if statements == []: code_string += " pass" else: for statement in statements: code_string += " " + statement + "\n" g = globals() l = locals() # print(code_string.replace('__generated_function__', # '{0}.{1}'.format(self.component.type, method_name))) if self.debug and statements != []: print( "------------- %s, %s, %s ----------------" % (method_name, self.id, str(self.derived_variables)) ) print(code_string) exec(compile(ast.parse(code_string), "<unknown>", "exec"), g, l) # setattr(cls, method_name, __generated_function__) self.__dict__[method_name] = l["__generated_function__"] del l["__generated_function__"] def add_instance_variable(self, variable, initial_value): self.instance_variables.append(variable) code_string = "self.{0} = {1}\nself.{0}_shadow = {1}".format( variable, initial_value ) exec(compile(ast.parse(code_string), "<unknown>", "exec")) def add_derived_variable(self, variable): self.derived_variables.append(variable) code_string = "self.{0} = {1}\nself.{0}_shadow = {1}".format(variable, 0) exec(compile(ast.parse(code_string), "<unknown>", "exec")) def add_text_variable(self, variable, value): self.__dict__[variable] = value def __getitem__(self, key): return self.array[key] def __setitem__(self, key, val): self.array[key] = val
class Reflective(LEMSBase): def __init__(self): pass def add_method(self, method_name, parameter_list, statements): pass def add_instance_variable(self, variable, initial_value): pass def add_derived_variable(self, variable): pass def add_text_variable(self, variable, value): pass def __getitem__(self, key): pass def __setitem__(self, key, val): pass
8
0
10
1
9
0
2
0.08
1
1
0
1
7
4
7
9
84
16
63
20
55
5
48
20
40
10
2
2
16
144,469
LEMS/pylems
lems/model/structure.py
lems.model.structure.With
class With(LEMSBase): """ Stores a with-as statement. """ def __init__(self, instance, as_, list=None, index=None): """ Constructor referencing single identified instance, or list/index. """ self.instance = instance """ Instance to be referenced. :type: str """ self.as_ = as_ """ Alternative name. :type: str """ self.list = list """ list of components, e.g. population :type: str """ self.index = index """ index in list to be referenced. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( "<With " + (' instance="{0}"'.format(self.instance) if self.instance else "") + (' list="{0}"'.format(self.list) if self.list else "") + (' index="{0}"'.format(self.index) if self.index else "") + ' as="{1}"/>'.format(self.instance, self.as_) )
class With(LEMSBase): ''' Stores a with-as statement. ''' def __init__(self, instance, as_, list=None, index=None): ''' Constructor referencing single identified instance, or list/index. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
19
5
7
7
3
1.21
1
0
0
0
2
4
2
4
43
12
14
7
11
17
8
7
5
4
2
0
5
144,470
LEMS/pylems
lems/parser/LEMS.py
lems.parser.LEMS.LEMSFileParser
class LEMSFileParser(LEMSBase): """ LEMS XML file format parser class. """ def __init__(self, model, include_dirs=[], include_includes=True): """ Constructor. See instance variable documentation for more details on parameters. """ self.model = model """ Model instance to be populated from the parsed file. :type: lems.model.model.Model """ self.include_dirs = include_dirs """ List of directories to search for included files. :type: list(str) """ self.tag_parse_table = None """ Dictionary of xml tags to parse methods :type: dict(string, function) """ self.valid_children = None """ Dictionary mapping each tag to it's list of valid child tags. :type: dict(string, string) """ self.id_counter = None """ Counter generator for generating unique ids. :type: generator(int) """ self.include_includes = include_includes """ Whether to include LEMS definitions in <Include> elements :type: boolean """ self.init_parser() def init_parser(self): """ Initializes the parser """ # self.token_list = None # self.prev_token_lists = None self.valid_children = dict() self.valid_children["lems"] = [ "component", "componenttype", "target", "include", "dimension", "unit", "assertion", ] # TODO: make this generic for any domain specific language based on LEMS self.valid_children["neuroml"] = ["include", "componenttype"] self.valid_children["componenttype"] = [ "dynamics", "child", "children", "componentreference", "exposure", "eventport", "fixed", "link", "parameter", "property", "indexparameter", "path", "requirement", "componentrequirement", "instancerequirement", "simulation", "structure", "text", "attachments", "constant", "derivedparameter", ] self.valid_children["dynamics"] = [ "derivedvariable", "conditionalderivedvariable", "oncondition", "onevent", "onstart", "statevariable", "timederivative", "kineticscheme", "regime", ] self.valid_children["component"] = ["component"] self.valid_children["conditionalderivedvariable"] = ["case"] self.valid_children["regime"] = ["oncondition", "onentry", "timederivative"] self.valid_children["oncondition"] = [ "eventout", "stateassignment", "transition", ] self.valid_children["onentry"] = ["eventout", "stateassignment", "transition"] self.valid_children["onevent"] = ["eventout", "stateassignment", "transition"] self.valid_children["onstart"] = ["eventout", "stateassignment", "transition"] self.valid_children["structure"] = [ "childinstance", "eventconnection", "foreach", "multiinstantiate", "with", "tunnel", ] self.valid_children["foreach"] = ["foreach", "eventconnection"] self.valid_children["simulation"] = [ "record", "eventrecord", "run", "datadisplay", "datawriter", "eventwriter", ] self.tag_parse_table = dict() # self.tag_parse_table['assertion'] = self.parse_assertion self.tag_parse_table["attachments"] = self.parse_attachments self.tag_parse_table["child"] = self.parse_child self.tag_parse_table["childinstance"] = self.parse_child_instance self.tag_parse_table["children"] = self.parse_children self.tag_parse_table["component"] = self.parse_component self.tag_parse_table["componentreference"] = self.parse_component_reference self.tag_parse_table["componentrequirement"] = self.parse_component_requirement self.tag_parse_table["componenttype"] = self.parse_component_type self.tag_parse_table["constant"] = self.parse_constant self.tag_parse_table["datadisplay"] = self.parse_data_display self.tag_parse_table["datawriter"] = self.parse_data_writer self.tag_parse_table["eventwriter"] = self.parse_event_writer self.tag_parse_table["derivedparameter"] = self.parse_derived_parameter self.tag_parse_table["derivedvariable"] = self.parse_derived_variable self.tag_parse_table[ "conditionalderivedvariable" ] = self.parse_conditional_derived_variable self.tag_parse_table["case"] = self.parse_case self.tag_parse_table["dimension"] = self.parse_dimension self.tag_parse_table["dynamics"] = self.parse_dynamics self.tag_parse_table["eventconnection"] = self.parse_event_connection self.tag_parse_table["eventout"] = self.parse_event_out self.tag_parse_table["eventport"] = self.parse_event_port self.tag_parse_table["exposure"] = self.parse_exposure self.tag_parse_table["fixed"] = self.parse_fixed self.tag_parse_table["foreach"] = self.parse_for_each self.tag_parse_table["include"] = self.parse_include self.tag_parse_table["indexparameter"] = self.parse_index_parameter self.tag_parse_table["kineticscheme"] = self.parse_kinetic_scheme self.tag_parse_table["link"] = self.parse_link self.tag_parse_table["multiinstantiate"] = self.parse_multi_instantiate self.tag_parse_table["oncondition"] = self.parse_on_condition self.tag_parse_table["onentry"] = self.parse_on_entry self.tag_parse_table["onevent"] = self.parse_on_event self.tag_parse_table["onstart"] = self.parse_on_start self.tag_parse_table["parameter"] = self.parse_parameter self.tag_parse_table["property"] = self.parse_property self.tag_parse_table["path"] = self.parse_path self.tag_parse_table["record"] = self.parse_record self.tag_parse_table["eventrecord"] = self.parse_event_record self.tag_parse_table["regime"] = self.parse_regime self.tag_parse_table["requirement"] = self.parse_requirement self.tag_parse_table["instancerequirement"] = self.parse_instance_requirement self.tag_parse_table["run"] = self.parse_run # self.tag_parse_table['show'] = self.parse_show self.tag_parse_table["simulation"] = self.parse_simulation self.tag_parse_table["stateassignment"] = self.parse_state_assignment self.tag_parse_table["statevariable"] = self.parse_state_variable self.tag_parse_table["structure"] = self.parse_structure self.tag_parse_table["target"] = self.parse_target self.tag_parse_table["text"] = self.parse_text self.tag_parse_table["timederivative"] = self.parse_time_derivative self.tag_parse_table["transition"] = self.parse_transition self.tag_parse_table["tunnel"] = self.parse_tunnel self.tag_parse_table["unit"] = self.parse_unit self.tag_parse_table["with"] = self.parse_with self.xml_node_stack = [] self.current_component_type = None self.current_dynamics = None self.current_regime = None self.current_event_handler = None self.current_structure = None self.current_simulation = None self.current_component = None def counter(): count = 1 while True: yield count count = count + 1 self.id_counter = counter() def process_nested_tags(self, node, tag=""): """ Process child tags. :param node: Current node being parsed. :type node: xml.etree.Element :raises ParseError: Raised when an unexpected nested tag is found. """ ##print("---------Processing: %s, %s"%(node.tag,tag)) if tag == "": t = node.ltag else: t = tag.lower() for child in node.children: self.xml_node_stack = [child] + self.xml_node_stack ctagl = child.ltag if ctagl in self.tag_parse_table and ctagl in self.valid_children[t]: # print("Processing known type: %s"%ctagl) self.tag_parse_table[ctagl](child) else: # print("Processing unknown type: %s"%ctagl) self.parse_component_by_typename(child, child.tag) self.xml_node_stack = self.xml_node_stack[1:] def parse(self, xmltext): """ Parse a string containing LEMS XML text. :param xmltext: String containing LEMS XML formatted text. :type xmltext: str """ xml = LEMSXMLNode(xe.XML(xmltext)) if xml.ltag != "lems" and xml.ltag != "neuroml": raise ParseError( "<Lems> expected as root element (or even <neuroml>), found: {0}".format( xml.ltag ) ) if xml.ltag == "lems": if "description" in xml.lattrib: self.model.description = xml.lattrib["description"] self.process_nested_tags(xml) def raise_error(self, message, *params, **key_params): """ Raise a parse error. """ s = "Parser error in " self.xml_node_stack.reverse() if len(self.xml_node_stack) > 1: node = self.xml_node_stack[0] s += "<{0}".format(node.tag) if "name" in node.lattrib: s += ' name="{0}"'.format(node.lattrib["name"]) if "id" in node.lattrib: s += ' id="{0}"'.format(node.lattrib["id"]) s += ">" for node in self.xml_node_stack[1:]: s += ".<{0}".format(node.tag) if "name" in node.lattrib: s += ' name="{0}"'.format(node.lattrib["name"]) if "id" in node.lattrib: s += ' id="{0}"'.format(node.lattrib["id"]) s += ">" s += ":\n " + message raise ParseError(s, *params, **key_params) self.xml_node_stack.reverse() ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### ##################################################################################### def parse_assertion(self, node): """ Parses <Assertion> :param node: Node containing the <Assertion> element :type node: xml.etree.Element """ print("TODO - <Assertion>") def parse_attachments(self, node): """ Parses <Attachments> :param node: Node containing the <Attachments> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<Attachments> must specify a name.") if "type" in node.lattrib: type_ = node.lattrib["type"] else: self.raise_error("Attachment '{0}' must specify a type.", name) description = node.lattrib.get("description", "") self.current_component_type.add_attachments( Attachments(name, type_, description) ) def parse_child(self, node): """ Parses <Child> :param node: Node containing the <Child> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<Child> must specify a name.") if "type" in node.lattrib: type_ = node.lattrib["type"] else: self.raise_error("Child '{0}' must specify a type.", name) description = node.lattrib.get("description", "") self.current_component_type.add_children( Children(name, type_, description, multiple=False) ) def parse_child_instance(self, node): """ Parses <ChildInstance> :param node: Node containing the <ChildInstance> element :type node: xml.etree.Element """ if "component" in node.lattrib: component = node.lattrib["component"] else: self.raise_error("<ChildInstance> must specify a component reference") self.current_structure.add_child_instance(ChildInstance(component)) def parse_children(self, node): """ Parses <Children> :param node: Node containing the <Children> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<Children> must specify a name.") if "type" in node.lattrib: type_ = node.lattrib["type"] else: self.raise_error("Children '{0}' must specify a type.", name) description = node.lattrib.get("description", "") self.current_component_type.add_children( Children(name, type_, description, multiple=True) ) def parse_component_by_typename(self, node, type_): """ Parses components defined directly by component name. :param node: Node containing the <Component> element :type node: xml.etree.Element :param type_: Type of this component. :type type_: string :raises ParseError: Raised when the component does not have an id. """ # print('Parsing component {0} by typename {1}'.format(node, type_)) if "id" in node.lattrib: id_ = node.lattrib["id"] else: # self.raise_error('Component must have an id') id_ = node.tag # make_id() if "type" in node.lattrib: type_ = node.lattrib["type"] else: type_ = node.tag component = Component(id_, type_) if self.current_component: component.set_parent_id(self.current_component.id) self.current_component.add_child(component) else: self.model.add_component(component) for key in node.attrib: if key.lower() not in ["id", "type"]: component.set_parameter(key, node.attrib[key]) old_component = self.current_component self.current_component = component self.process_nested_tags(node, "component") self.current_component = old_component def parse_component(self, node): """ Parses <Component> :param node: Node containing the <Component> element :type node: xml.etree.Element """ if "id" in node.lattrib: id_ = node.lattrib["id"] else: # self.raise_error('Component must have an id') id_ = make_id() if "type" in node.lattrib: type_ = node.lattrib["type"] else: self.raise_error("Component {0} must have a type.", id_) component = Component(id_, type_) if self.current_component: component.set_parent_id(self.current_component.id) self.current_component.add_child(component) else: self.model.add_component(component) for key in node.attrib: if key.lower() not in ["id", "type"]: component.set_parameter(key, node.attrib[key]) old_component = self.current_component self.current_component = component self.process_nested_tags(node) self.current_component = old_component def parse_component_reference(self, node): """ Parses <ComponentReference> :param node: Node containing the <ComponentTypeRef> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error( "<ComponentReference> must specify a name for the " + "reference." ) if "type" in node.lattrib: type_ = node.lattrib["type"] else: self.raise_error( "<ComponentReference> must specify a type for the " + "reference." ) if "local" in node.lattrib: local = node.lattrib["local"] else: local = None self.current_component_type.add_component_reference( ComponentReference(name, type_, local) ) def parse_component_type(self, node): """ Parses <ComponentType> :param node: Node containing the <ComponentType> element :type node: xml.etree.Element :raises ParseError: Raised when the component type does not have a name. """ try: name = node.lattrib["name"] except: self.raise_error("<ComponentType> must specify a name") if "extends" in node.lattrib: extends = node.lattrib["extends"] else: extends = None if "description" in node.lattrib: description = node.lattrib["description"] else: description = "" component_type = ComponentType(name, description, extends) self.model.add_component_type(component_type) self.current_component_type = component_type self.process_nested_tags(node) self.current_component_type = None def parse_constant(self, node): """ Parses <Constant> :param node: Node containing the <Constant> element :type node: xml.etree.Element """ try: name = node.lattrib["name"] except: self.raise_error("<Constant> must specify a name.") dimension = node.lattrib.get("dimension", None) try: value = node.lattrib["value"] except: self.raise_error("Constant '{0}' must have a value.", name) if "description" in node.lattrib: description = node.lattrib["description"] else: description = None if "symbol" in node.lattrib: symbol = node.lattrib["symbol"] else: symbol = None constant = Constant( name, value, dimension=dimension, description=description, symbol=symbol ) if self.current_component_type: self.current_component_type.add_constant(constant) else: self.model.add_constant(constant) def parse_data_display(self, node): """ Parses <DataDisplay> :param node: Node containing the <DataDisplay> element :type node: xml.etree.Element """ if "title" in node.lattrib: title = node.lattrib["title"] else: self.raise_error("<DataDisplay> must have a title.") if "dataregion" in node.lattrib: data_region = node.lattrib["dataregion"] else: data_region = None self.current_simulation.add_data_display(DataDisplay(title, data_region)) def parse_data_writer(self, node): """ Parses <DataWriter> :param node: Node containing the <DataWriter> element :type node: xml.etree.Element """ if "path" in node.lattrib: path = node.lattrib["path"] else: self.raise_error("<DataWriter> must specify a path.") if "filename" in node.lattrib: file_path = node.lattrib["filename"] else: self.raise_error("Data writer for '{0}' must specify a filename.", path) self.current_simulation.add_data_writer(DataWriter(path, file_path)) def parse_event_writer(self, node): """ Parses <EventWriter> :param node: Node containing the <EventWriter> element :type node: xml.etree.Element """ if "path" in node.lattrib: path = node.lattrib["path"] else: self.raise_error("<EventWriter> must specify a path.") if "filename" in node.lattrib: file_path = node.lattrib["filename"] else: self.raise_error("Event writer for '{0}' must specify a filename.", path) if "format" in node.lattrib: format = node.lattrib["format"] else: self.raise_error("Event writer for '{0}' must specify a format.", path) self.current_simulation.add_event_writer(EventWriter(path, file_path, format)) def parse_derived_parameter(self, node): """ Parses <DerivedParameter> :param node: Node containing the <DerivedParameter> element :type node: xml.etree.Element """ # if self.current_context.context_type != Context.COMPONENT_TYPE: # self.raise_error('Dynamics must be defined inside a ' + # 'component type') if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("A derived parameter must have a name") if "dimension" in node.lattrib: dimension = node.lattrib["dimension"] else: dimension = None if "value" in node.lattrib: value = node.lattrib["value"] else: value = None # TODO: this is not used in the DerivedParameter constructor if "select" in node.lattrib: select = node.lattrib["select"] else: select = None if "description" in node.lattrib: description = node.lattrib["description"] else: description = None self.current_component_type.add_derived_parameter( DerivedParameter(name, value, dimension, description) ) def parse_derived_variable(self, node): """ Parses <DerivedVariable> :param node: Node containing the <DerivedVariable> element :type node: xml.etree.Element :raises ParseError: Raised when no name of specified for the derived variable. """ if "name" in node.lattrib: name = node.lattrib["name"] elif "exposure" in node.lattrib: name = node.lattrib["exposure"] else: self.raise_error("<DerivedVariable> must specify a name") params = dict() for attr_name in [ "dimension", "exposure", "select", "value", "reduce", "required", ]: if attr_name in node.lattrib: params[attr_name] = node.lattrib[attr_name] self.current_regime.add_derived_variable(DerivedVariable(name, **params)) def parse_conditional_derived_variable(self, node): """ Parses <ConditionalDerivedVariable> :param node: Node containing the <ConditionalDerivedVariable> element :type node: xml.etree.Element :raises ParseError: Raised when no name or value is specified for the conditional derived variable. """ if "name" in node.lattrib: name = node.lattrib["name"] elif "exposure" in node.lattrib: name = node.lattrib["exposure"] else: self.raise_error("<ConditionalDerivedVariable> must specify a name") if "exposure" in node.lattrib: exposure = node.lattrib["exposure"] else: exposure = None if "dimension" in node.lattrib: dimension = node.lattrib["dimension"] else: dimension = None conditional_derived_variable = ConditionalDerivedVariable( name, dimension, exposure ) self.current_regime.add_conditional_derived_variable( conditional_derived_variable ) self.current_conditional_derived_variable = conditional_derived_variable self.process_nested_tags(node) def parse_case(self, node): """ Parses <Case> :param node: Node containing the <Case> element :type node: xml.etree.Element :raises ParseError: When no condition or value is specified """ try: condition = node.lattrib["condition"] except: condition = None try: value = node.lattrib["value"] except: self.raise_error("<Case> must specify a value") self.current_conditional_derived_variable.add_case(Case(condition, value)) def parse_dimension(self, node): """ Parses <Dimension> :param node: Node containing the <Dimension> element :type node: xml.etree.Element :raises ParseError: When the name is not a string or if the dimension is not a signed integer. """ try: name = node.lattrib["name"] except: self.raise_error("<Dimension> must specify a name") description = node.lattrib.get("description", "") dim = dict() for d in ["l", "m", "t", "i", "k", "c", "n"]: dim[d] = int(node.lattrib.get(d, 0)) self.model.add_dimension(Dimension(name, description, **dim)) def parse_dynamics(self, node): """ Parses <Dynamics> :param node: Node containing the <Behaviour> element :type node: xml.etree.Element """ self.current_dynamics = self.current_component_type.dynamics self.current_regime = self.current_dynamics self.process_nested_tags(node) self.current_regime = None self.current_dynamics = None def parse_event_connection(self, node): """ Parses <EventConnection> :param node: Node containing the <EventConnection> element :type node: xml.etree.Element """ if "from" in node.lattrib: from_ = node.lattrib["from"] else: self.raise_error( "<EventConnection> must provide a source (from) component reference." ) if "to" in node.lattrib: to = node.lattrib["to"] else: self.raise_error( "<EventConnection> must provide a target (to) component reference." ) source_port = node.lattrib.get("sourceport", "") target_port = node.lattrib.get("targetport", "") receiver = node.lattrib.get("receiver", "") receiver_container = node.lattrib.get("receivercontainer", "") ec = EventConnection( from_, to, source_port, target_port, receiver, receiver_container ) self.current_structure.add_event_connection(ec) def parse_event_out(self, node): """ Parses <EventOut> :param node: Node containing the <EventOut> element :type node: xml.etree.Element """ try: port = node.lattrib["port"] except: self.raise_error("<EventOut> must be specify a port.") action = EventOut(port) self.current_event_handler.add_action(action) def parse_event_port(self, node): """ Parses <EventPort> :param node: Node containing the <EventPort> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error(("<EventPort> must specify a name.")) if "direction" in node.lattrib: direction = node.lattrib["direction"] else: self.raise_error("Event port '{0}' must specify a direction.") direction = direction.lower() if direction != "in" and direction != "out": self.raise_error(("Event port direction must be 'in' " "or 'out'")) description = node.lattrib.get("description", "") self.current_component_type.add_event_port( EventPort(name, direction, description) ) def parse_exposure(self, node): """ Parses <Exposure> :param node: Node containing the <Exposure> element :type node: xml.etree.Element :raises ParseError: Raised when the exposure name is not being defined in the context of a component type. """ if self.current_component_type == None: self.raise_error("Exposures must be defined in a component type") try: name = node.lattrib["name"] except: self.raise_error("<Exposure> must specify a name") try: dimension = node.lattrib["dimension"] except: self.raise_error("Exposure '{0}' must specify a dimension", name) description = node.lattrib.get("description", "") self.current_component_type.add_exposure(Exposure(name, dimension, description)) def parse_fixed(self, node): """ Parses <Fixed> :param node: Node containing the <Fixed> element :type node: xml.etree.Element """ try: parameter = node.lattrib["parameter"] except: self.raise_error("<Fixed> must specify a parameter to be fixed.") try: value = node.lattrib["value"] except: self.raise_error("Fixed parameter '{0}'must specify a value.", parameter) description = node.lattrib.get("description", "") self.current_component_type.add_parameter(Fixed(parameter, value, description)) def parse_for_each(self, node): """ Parses <ForEach> :param node: Node containing the <ForEach> element :type node: xml.etree.Element """ if self.current_structure == None: self.raise_error( "<ForEach> can only be made within " + "a structure definition" ) if "instances" in node.lattrib: instances = node.lattrib["instances"] else: self.raise_error("<ForEach> must specify a reference to target" "instances") if "as" in node.lattrib: as_ = node.lattrib["as"] else: self.raise_error( "<ForEach> must specify a name for the " "enumerated target instances" ) old_structure = self.current_structure fe = ForEach(instances, as_) self.current_structure.add_for_each(fe) self.current_structure = fe self.process_nested_tags(node) self.current_structure = old_structure def parse_include(self, node): """ Parses <Include> :param node: Node containing the <Include> element :type node: xml.etree.Element :raises ParseError: Raised when the file to be included is not specified. """ if not self.include_includes: if self.model.debug: print("Ignoring included LEMS file: %s" % node.lattrib["file"]) else: # TODO: remove this hard coding for reading NeuroML includes... if "file" not in node.lattrib: if "href" in node.lattrib: self.model.include_file(node.lattrib["href"], self.include_dirs) return else: self.raise_error("<Include> must specify the file to be included.") self.model.include_file(node.lattrib["file"], self.include_dirs) def parse_kinetic_scheme(self, node): """ Parses <KineticScheme> :param node: Node containing the <KineticScheme> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<KineticScheme> must specify a name.") if "nodes" in node.lattrib: nodes = node.lattrib["nodes"] else: self.raise_error("Kinetic scheme '{0}' must specify nodes.", name) if "statevariable" in node.lattrib: state_variable = node.lattrib["statevariable"] else: self.raise_error( "Kinetic scheme '{0}' must specify a state variable.", name ) if "edges" in node.lattrib: edges = node.lattrib["edges"] else: self.raise_error("Kinetic scheme '{0}' must specify edges.", name) if "edgesource" in node.lattrib: edge_source = node.lattrib["edgesource"] else: self.raise_error( "Kinetic scheme '{0}' must specify the edge source attribute.", name ) if "edgetarget" in node.lattrib: edge_target = node.lattrib["edgetarget"] else: self.raise_error( "Kinetic scheme '{0}' must specify the edge target attribute.", name ) if "forwardrate" in node.lattrib: forward_rate = node.lattrib["forwardrate"] else: self.raise_error( "Kinetic scheme '{0}' must specify the forward rate attribute.", name ) if "reverserate" in node.lattrib: reverse_rate = node.lattrib["reverserate"] else: self.raise_error( "Kinetic scheme '{0}' must specify the reverse rate attribute", name ) self.current_regime.add_kinetic_scheme( KineticScheme( name, nodes, state_variable, edges, edge_source, edge_target, forward_rate, reverse_rate, ) ) def parse_link(self, node): """ Parses <Link> :param node: Node containing the <Link> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<Link> must specify a name") if "type" in node.lattrib: type_ = node.lattrib["type"] else: self.raise_error("Link '{0}' must specify a type", name) description = node.lattrib.get("description", "") self.current_component_type.add_link(Link(name, type_, description)) def parse_multi_instantiate(self, node): """ Parses <MultiInstantiate> :param node: Node containing the <MultiInstantiate> element :type node: xml.etree.Element """ if "component" in node.lattrib: component = node.lattrib["component"] else: self.raise_error("<MultiInstantiate> must specify a component reference.") if "number" in node.lattrib: number = node.lattrib["number"] else: self.raise_error( "Multi instantiation of '{0}' must specify a parameter specifying the number.", component, ) self.current_structure.add_multi_instantiate( MultiInstantiate(component, number) ) def parse_on_condition(self, node): """ Parses <OnCondition> :param node: Node containing the <OnCondition> element :type node: xml.etree.Element """ try: test = node.lattrib["test"] except: self.raise_error("<OnCondition> must specify a test.") event_handler = OnCondition(test) self.current_regime.add_event_handler(event_handler) self.current_event_handler = event_handler self.process_nested_tags(node) self.current_event_handler = None def parse_on_entry(self, node): """ Parses <OnEntry> :param node: Node containing the <OnEntry> element :type node: xml.etree.Element """ event_handler = OnEntry() self.current_event_handler = event_handler self.current_regime.add_event_handler(event_handler) self.process_nested_tags(node) self.current_event_handler = None def parse_on_event(self, node): """ Parses <OnEvent> :param node: Node containing the <OnEvent> element :type node: xml.etree.Element """ try: port = node.lattrib["port"] except: self.raise_error("<OnEvent> must specify a port.") event_handler = OnEvent(port) self.current_regime.add_event_handler(event_handler) self.current_event_handler = event_handler self.process_nested_tags(node) self.current_event_handler = None def parse_on_start(self, node): """ Parses <OnStart> :param node: Node containing the <OnStart> element :type node: xml.etree.Element """ event_handler = OnStart() self.current_regime.add_event_handler(event_handler) self.current_event_handler = event_handler self.process_nested_tags(node) self.current_event_handler = None def parse_parameter(self, node): """ Parses <Parameter> :param node: Node containing the <Parameter> element :type node: xml.etree.Element :raises ParseError: Raised when the parameter does not have a name. :raises ParseError: Raised when the parameter does not have a dimension. """ if self.current_component_type == None: self.raise_error("Parameters can only be defined in " + "a component type") try: name = node.lattrib["name"] except: self.raise_error("<Parameter> must specify a name") try: dimension = node.lattrib["dimension"] except: self.raise_error("Parameter '{0}' has no dimension", name) description = node.lattrib.get("description", "") parameter = Parameter(name, dimension, description) self.current_component_type.add_parameter(parameter) def parse_property(self, node): """ Parses <Property> :param node: Node containing the <Property> element :type node: xml.etree.Element :raises ParseError: Raised when the property does not have a name. :raises ParseError: Raised when the property does not have a dimension. """ if self.current_component_type == None: self.raise_error("Property can only be defined in " + "a component type") try: name = node.lattrib["name"] except: self.raise_error("<Property> must specify a name") try: dimension = node.lattrib["dimension"] except: self.raise_error("Property '{0}' has no dimension", name) default_value = node.lattrib.get("defaultvalue", None) property = Property(name, dimension, default_value=default_value) self.current_component_type.add_property(property) def parse_index_parameter(self, node): """ Parses <IndexParameter> :param node: Node containing the <IndexParameter> element :type node: xml.etree.Element :raises ParseError: Raised when the IndexParameter does not have a name. """ if self.current_component_type == None: self.raise_error( "IndexParameters can only be defined in " + "a component type" ) try: name = node.lattrib["name"] except: self.raise_error("<IndexParameter> must specify a name") index_parameter = IndexParameter(name) self.current_component_type.add_index_parameter(index_parameter) def parse_tunnel(self, node): """ Parses <Tunnel> :param node: Node containing the <Tunnel> element :type node: xml.etree.Element :raises ParseError: Raised when the Tunnel does not have a name. """ try: name = node.lattrib["name"] except: self.raise_error("<Tunnel> must specify a name") try: end_a = node.lattrib["enda"] except: self.raise_error("<Tunnel> must specify: endA") try: end_b = node.lattrib["enda"] except: self.raise_error("<Tunnel> must specify: endB") try: component_a = node.lattrib["componenta"] except: self.raise_error("<Tunnel> must specify: componentA") try: component_b = node.lattrib["componentb"] except: self.raise_error("<Tunnel> must specify: componentB") tunnel = Tunnel(name, end_a, end_b, component_a, component_b) self.current_structure.add_tunnel(tunnel) def parse_path(self, node): """ Parses <Path> :param node: Node containing the <Path> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<Path> must specify a name.") description = node.lattrib.get("description", "") self.current_component_type.add_path(Path(name, description)) def parse_record(self, node): """ Parses <Record> :param node: Node containing the <Record> element :type node: xml.etree.Element """ if self.current_simulation == None: self.raise_error( "<Record> must be only be used inside a " + "simulation specification" ) if "quantity" in node.lattrib: quantity = node.lattrib["quantity"] else: self.raise_error("<Record> must specify a quantity.") scale = node.lattrib.get("scale", None) color = node.lattrib.get("color", None) id = node.lattrib.get("id", None) self.current_simulation.add_record(Record(quantity, scale, color, id)) def parse_event_record(self, node): """ Parses <EventRecord> :param node: Node containing the <EventRecord> element :type node: xml.etree.Element """ if self.current_simulation == None: self.raise_error( "<EventRecord> must be only be used inside a " + "simulation specification" ) if "quantity" in node.lattrib: quantity = node.lattrib["quantity"] else: self.raise_error("<EventRecord> must specify a quantity.") if "eventport" in node.lattrib: eventPort = node.lattrib["eventport"] else: self.raise_error("<EventRecord> must specify an eventPort.") self.current_simulation.add_event_record(EventRecord(quantity, eventPort)) def parse_regime(self, node): """ Parses <Regime> :param node: Node containing the <Behaviour> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: name = "" if "initial" in node.lattrib: initial = node.lattrib["initial"].strip().lower() == "true" else: initial = False regime = Regime(name, self.current_dynamics, initial) old_regime = self.current_regime self.current_dynamics.add_regime(regime) self.current_regime = regime self.process_nested_tags(node) self.current_regime = old_regime def parse_requirement(self, node): """ Parses <Requirement> :param node: Node containing the <Requirement> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<Requirement> must specify a name") if "dimension" in node.lattrib: dimension = node.lattrib["dimension"] else: self.raise_error("Requirement %s must specify a dimension." % name) description = node.lattrib.get("description", "") self.current_component_type.add_requirement( Requirement(name, dimension, description) ) def parse_component_requirement(self, node): """ Parses <ComponentRequirement> :param node: Node containing the <ComponentRequirement> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<ComponentRequirement> must specify a name") self.current_component_type.add_component_requirement( ComponentRequirement(name) ) def parse_instance_requirement(self, node): """ Parses <InstanceRequirement> :param node: Node containing the <InstanceRequirement> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<InstanceRequirement> must specify a name") if "type" in node.lattrib: type = node.lattrib["type"] else: self.raise_error("InstanceRequirement %s must specify a type." % name) self.current_component_type.add_instance_requirement( InstanceRequirement(name, type) ) def parse_run(self, node): """ Parses <Run> :param node: Node containing the <Run> element :type node: xml.etree.Element """ if "component" in node.lattrib: component = node.lattrib["component"] else: self.raise_error("<Run> must specify a target component") if "variable" in node.lattrib: variable = node.lattrib["variable"] else: self.raise_error("<Run> must specify a state variable") if "increment" in node.lattrib: increment = node.lattrib["increment"] else: self.raise_error( "<Run> must specify an increment for the " + "state variable" ) if "total" in node.lattrib: total = node.lattrib["total"] else: self.raise_error( "<Run> must specify a final value for the " + "state variable" ) self.current_simulation.add_run(Run(component, variable, increment, total)) def parse_show(self, node): """ Parses <Show> :param node: Node containing the <Show> element :type node: xml.etree.Element """ pass def parse_simulation(self, node): """ Parses <Simulation> :param node: Node containing the <Simulation> element :type node: xml.etree.Element """ self.current_simulation = self.current_component_type.simulation self.process_nested_tags(node) self.current_simulation = None def parse_state_assignment(self, node): """ Parses <StateAssignment> :param node: Node containing the <StateAssignment> element :type node: xml.etree.Element """ if "variable" in node.lattrib: variable = node.lattrib["variable"] else: self.raise_error("<StateAssignment> must specify a variable name") if "value" in node.lattrib: value = node.lattrib["value"] else: self.raise_error( "State assignment for '{0}' must specify a value.", variable ) action = StateAssignment(variable, value) self.current_event_handler.add_action(action) def parse_state_variable(self, node): """ Parses <StateVariable> :param node: Node containing the <StateVariable> element :type node: xml.etree.Element :raises ParseError: Raised when the state variable is not being defined in the context of a component type. """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<StateVariable> must specify a name") if "dimension" in node.lattrib: dimension = node.lattrib["dimension"] else: self.raise_error("State variable '{0}' must specify a dimension", name) if "exposure" in node.lattrib: exposure = node.lattrib["exposure"] else: exposure = None self.current_regime.add_state_variable(StateVariable(name, dimension, exposure)) def parse_structure(self, node): """ Parses <Structure> :param node: Node containing the <Structure> element :type node: xml.etree.Element """ self.current_structure = self.current_component_type.structure self.process_nested_tags(node) self.current_structure = None def parse_target(self, node): """ Parses <Target> :param node: Node containing the <Target> element :type node: xml.etree.Element """ self.model.add_target(node.lattrib["component"]) def parse_text(self, node): """ Parses <Text> :param node: Node containing the <Text> element :type node: xml.etree.Element """ if "name" in node.lattrib: name = node.lattrib["name"] else: self.raise_error("<Text> must specify a name.") description = node.lattrib.get("description", "") self.current_component_type.add_text(Text(name, description)) def parse_time_derivative(self, node): """ Parses <TimeDerivative> :param node: Node containing the <TimeDerivative> element :type node: xml.etree.Element :raises ParseError: Raised when the time derivative does not hava a variable name of a value. """ if "variable" in node.lattrib: variable = node.lattrib["variable"] else: self.raise_error("<TimeDerivative> must specify a variable.") if "value" in node.lattrib: value = node.lattrib["value"] else: self.raise_error( "Time derivative for '{0}' must specify an expression.", variable ) self.current_regime.add_time_derivative(TimeDerivative(variable, value)) def parse_transition(self, node): """ Parses <Transition> :param node: Node containing the <Transition> element :type node: xml.etree.Element """ if "regime" in node.lattrib: regime = node.lattrib["regime"] else: self.raise_error("<Transition> mut specify a regime.") action = Transition(regime) self.current_event_handler.add_action(action) def parse_unit(self, node): """ Parses <Unit> :param node: Node containing the <Unit> element :type node: xml.etree.Element :raises ParseError: When the name is not a string or the unit specfications are incorrect. :raises ModelError: When the unit refers to an undefined dimension. """ try: symbol = node.lattrib["symbol"] dimension = node.lattrib["dimension"] except: self.raise_error("Unit must have a symbol and dimension.") if "power" in node.lattrib: power = int(node.lattrib["power"]) else: power = 0 if "name" in node.lattrib: name = node.lattrib["name"] else: name = "" if "scale" in node.lattrib: scale = float(node.lattrib["scale"]) else: scale = 1.0 if "offset" in node.lattrib: offset = float(node.lattrib["offset"]) else: offset = 0.0 self.model.add_unit(Unit(name, symbol, dimension, power, scale, offset)) def parse_with(self, node): """ Parses <With> :param node: Node containing the <With> element :type node: xml.etree.Element """ if "instance" in node.lattrib: instance = node.lattrib["instance"] list = None index = None elif "list" in node.lattrib and "index" in node.lattrib: instance = None list = node.lattrib["list"] index = node.lattrib["index"] else: self.raise_error("<With> must specify EITHER instance OR list & index") if "as" in node.lattrib: as_ = node.lattrib["as"] else: self.raise_error("<With> must specify a name for the " "target instance") self.current_structure.add_with(With(instance, as_, list, index))
class LEMSFileParser(LEMSBase): ''' LEMS XML file format parser class. ''' def __init__(self, model, include_dirs=[], include_includes=True): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def init_parser(self): ''' Initializes the parser ''' pass def counter(): pass def process_nested_tags(self, node, tag=""): ''' Process child tags. :param node: Current node being parsed. :type node: xml.etree.Element :raises ParseError: Raised when an unexpected nested tag is found. ''' pass def parse(self, xmltext): ''' Parse a string containing LEMS XML text. :param xmltext: String containing LEMS XML formatted text. :type xmltext: str ''' pass def raise_error(self, message, *params, **key_params): ''' Raise a parse error. ''' pass def parse_assertion(self, node): ''' Parses <Assertion> :param node: Node containing the <Assertion> element :type node: xml.etree.Element ''' pass def parse_attachments(self, node): ''' Parses <Attachments> :param node: Node containing the <Attachments> element :type node: xml.etree.Element ''' pass def parse_child(self, node): ''' Parses <Child> :param node: Node containing the <Child> element :type node: xml.etree.Element ''' pass def parse_child_instance(self, node): ''' Parses <ChildInstance> :param node: Node containing the <ChildInstance> element :type node: xml.etree.Element ''' pass def parse_children(self, node): ''' Parses <Children> :param node: Node containing the <Children> element :type node: xml.etree.Element ''' pass def parse_component_by_typename(self, node, type_): ''' Parses components defined directly by component name. :param node: Node containing the <Component> element :type node: xml.etree.Element :param type_: Type of this component. :type type_: string :raises ParseError: Raised when the component does not have an id. ''' pass def parse_component_by_typename(self, node, type_): ''' Parses <Component> :param node: Node containing the <Component> element :type node: xml.etree.Element ''' pass def parse_component_reference(self, node): ''' Parses <ComponentReference> :param node: Node containing the <ComponentTypeRef> element :type node: xml.etree.Element ''' pass def parse_component_type(self, node): ''' Parses <ComponentType> :param node: Node containing the <ComponentType> element :type node: xml.etree.Element :raises ParseError: Raised when the component type does not have a name. ''' pass def parse_constant(self, node): ''' Parses <Constant> :param node: Node containing the <Constant> element :type node: xml.etree.Element ''' pass def parse_data_display(self, node): ''' Parses <DataDisplay> :param node: Node containing the <DataDisplay> element :type node: xml.etree.Element ''' pass def parse_data_writer(self, node): ''' Parses <DataWriter> :param node: Node containing the <DataWriter> element :type node: xml.etree.Element ''' pass def parse_event_writer(self, node): ''' Parses <EventWriter> :param node: Node containing the <EventWriter> element :type node: xml.etree.Element ''' pass def parse_derived_parameter(self, node): ''' Parses <DerivedParameter> :param node: Node containing the <DerivedParameter> element :type node: xml.etree.Element ''' pass def parse_derived_variable(self, node): ''' Parses <DerivedVariable> :param node: Node containing the <DerivedVariable> element :type node: xml.etree.Element :raises ParseError: Raised when no name of specified for the derived variable. ''' pass def parse_conditional_derived_variable(self, node): ''' Parses <ConditionalDerivedVariable> :param node: Node containing the <ConditionalDerivedVariable> element :type node: xml.etree.Element :raises ParseError: Raised when no name or value is specified for the conditional derived variable. ''' pass def parse_case(self, node): ''' Parses <Case> :param node: Node containing the <Case> element :type node: xml.etree.Element :raises ParseError: When no condition or value is specified ''' pass def parse_dimension(self, node): ''' Parses <Dimension> :param node: Node containing the <Dimension> element :type node: xml.etree.Element :raises ParseError: When the name is not a string or if the dimension is not a signed integer. ''' pass def parse_dynamics(self, node): ''' Parses <Dynamics> :param node: Node containing the <Behaviour> element :type node: xml.etree.Element ''' pass def parse_event_connection(self, node): ''' Parses <EventConnection> :param node: Node containing the <EventConnection> element :type node: xml.etree.Element ''' pass def parse_event_out(self, node): ''' Parses <EventOut> :param node: Node containing the <EventOut> element :type node: xml.etree.Element ''' pass def parse_event_port(self, node): ''' Parses <EventPort> :param node: Node containing the <EventPort> element :type node: xml.etree.Element ''' pass def parse_exposure(self, node): ''' Parses <Exposure> :param node: Node containing the <Exposure> element :type node: xml.etree.Element :raises ParseError: Raised when the exposure name is not being defined in the context of a component type. ''' pass def parse_fixed(self, node): ''' Parses <Fixed> :param node: Node containing the <Fixed> element :type node: xml.etree.Element ''' pass def parse_for_each(self, node): ''' Parses <ForEach> :param node: Node containing the <ForEach> element :type node: xml.etree.Element ''' pass def parse_include(self, node): ''' Parses <Include> :param node: Node containing the <Include> element :type node: xml.etree.Element :raises ParseError: Raised when the file to be included is not specified. ''' pass def parse_kinetic_scheme(self, node): ''' Parses <KineticScheme> :param node: Node containing the <KineticScheme> element :type node: xml.etree.Element ''' pass def parse_link(self, node): ''' Parses <Link> :param node: Node containing the <Link> element :type node: xml.etree.Element ''' pass def parse_multi_instantiate(self, node): ''' Parses <MultiInstantiate> :param node: Node containing the <MultiInstantiate> element :type node: xml.etree.Element ''' pass def parse_on_condition(self, node): ''' Parses <OnCondition> :param node: Node containing the <OnCondition> element :type node: xml.etree.Element ''' pass def parse_on_entry(self, node): ''' Parses <OnEntry> :param node: Node containing the <OnEntry> element :type node: xml.etree.Element ''' pass def parse_on_event(self, node): ''' Parses <OnEvent> :param node: Node containing the <OnEvent> element :type node: xml.etree.Element ''' pass def parse_on_start(self, node): ''' Parses <OnStart> :param node: Node containing the <OnStart> element :type node: xml.etree.Element ''' pass def parse_parameter(self, node): ''' Parses <Parameter> :param node: Node containing the <Parameter> element :type node: xml.etree.Element :raises ParseError: Raised when the parameter does not have a name. :raises ParseError: Raised when the parameter does not have a dimension. ''' pass def parse_property(self, node): ''' Parses <Property> :param node: Node containing the <Property> element :type node: xml.etree.Element :raises ParseError: Raised when the property does not have a name. :raises ParseError: Raised when the property does not have a dimension. ''' pass def parse_index_parameter(self, node): ''' Parses <IndexParameter> :param node: Node containing the <IndexParameter> element :type node: xml.etree.Element :raises ParseError: Raised when the IndexParameter does not have a name. ''' pass def parse_tunnel(self, node): ''' Parses <Tunnel> :param node: Node containing the <Tunnel> element :type node: xml.etree.Element :raises ParseError: Raised when the Tunnel does not have a name. ''' pass def parse_path(self, node): ''' Parses <Path> :param node: Node containing the <Path> element :type node: xml.etree.Element ''' pass def parse_record(self, node): ''' Parses <Record> :param node: Node containing the <Record> element :type node: xml.etree.Element ''' pass def parse_event_record(self, node): ''' Parses <EventRecord> :param node: Node containing the <EventRecord> element :type node: xml.etree.Element ''' pass def parse_regime(self, node): ''' Parses <Regime> :param node: Node containing the <Behaviour> element :type node: xml.etree.Element ''' pass def parse_requirement(self, node): ''' Parses <Requirement> :param node: Node containing the <Requirement> element :type node: xml.etree.Element ''' pass def parse_component_requirement(self, node): ''' Parses <ComponentRequirement> :param node: Node containing the <ComponentRequirement> element :type node: xml.etree.Element ''' pass def parse_instance_requirement(self, node): ''' Parses <InstanceRequirement> :param node: Node containing the <InstanceRequirement> element :type node: xml.etree.Element ''' pass def parse_run(self, node): ''' Parses <Run> :param node: Node containing the <Run> element :type node: xml.etree.Element ''' pass def parse_show(self, node): ''' Parses <Show> :param node: Node containing the <Show> element :type node: xml.etree.Element ''' pass def parse_simulation(self, node): ''' Parses <Simulation> :param node: Node containing the <Simulation> element :type node: xml.etree.Element ''' pass def parse_state_assignment(self, node): ''' Parses <StateAssignment> :param node: Node containing the <StateAssignment> element :type node: xml.etree.Element ''' pass def parse_state_variable(self, node): ''' Parses <StateVariable> :param node: Node containing the <StateVariable> element :type node: xml.etree.Element :raises ParseError: Raised when the state variable is not being defined in the context of a component type. ''' pass def parse_structure(self, node): ''' Parses <Structure> :param node: Node containing the <Structure> element :type node: xml.etree.Element ''' pass def parse_target(self, node): ''' Parses <Target> :param node: Node containing the <Target> element :type node: xml.etree.Element ''' pass def parse_text(self, node): ''' Parses <Text> :param node: Node containing the <Text> element :type node: xml.etree.Element ''' pass def parse_time_derivative(self, node): ''' Parses <TimeDerivative> :param node: Node containing the <TimeDerivative> element :type node: xml.etree.Element :raises ParseError: Raised when the time derivative does not hava a variable name of a value. ''' pass def parse_transition(self, node): ''' Parses <Transition> :param node: Node containing the <Transition> element :type node: xml.etree.Element ''' pass def parse_unit(self, node): ''' Parses <Unit> :param node: Node containing the <Unit> element :type node: xml.etree.Element :raises ParseError: When the name is not a string or the unit specfications are incorrect. :raises ModelError: When the unit refers to an undefined dimension. ''' pass def parse_with(self, node): ''' Parses <With> :param node: Node containing the <With> element :type node: xml.etree.Element ''' pass
63
62
27
5
16
6
3
0.41
1
52
49
0
61
15
61
63
1,748
394
964
240
901
391
722
240
659
9
2
3
206
144,471
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.EventRecord
class EventRecord(LEMSBase): """ Stores the parameters of an <EventRecord> statement. """ def __init__(self, quantity, eventPort): """ Constructor. See instance variable documentation for information on parameters. """ self.id = "" """ Id of the quantity :type: str """ self.quantity = quantity """ Path to the quantity to be recorded. :type: str """ self.eventPort = eventPort """ eventPort to be used for the event record :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<EventRecord quantity="{0}" eventPort="{1}"/>'.format( self.quantity, self.eventPort )
class EventRecord(LEMSBase): ''' Stores the parameters of an <EventRecord> statement. ''' def __init__(self, quantity, eventPort): ''' Constructor. See instance variable documentation for information on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
15
4
4
7
1
1.78
1
0
0
0
2
3
2
4
35
10
9
6
6
16
7
6
4
1
2
0
2
144,472
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.DataDisplay
class DataDisplay(DataOutput): """ Stores specification for a data display. """ def __init__(self, title, data_region): """ Constuctor. See instance variable documentation for information on parameters. """ DataOutput.__init__(self) self.title = title """ Title for the display. :type: string """ self.data_region = data_region """ Display position :type: string """ self.time_scale = 1 """ Time scale :type: Number """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<DataDisplay title="{0}" dataRegion="{1}"/>'.format( self.title, self.data_region )
class DataDisplay(DataOutput): ''' Stores specification for a data display. ''' def __init__(self, title, data_region): ''' Constuctor. See instance variable documentation for information on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
16
5
5
7
1
1.6
1
0
0
0
2
3
2
5
37
11
10
6
7
16
8
6
5
1
3
0
2
144,473
LEMS/pylems
lems/model/model.py
lems.model.model.Model
class Model(LEMSBase): """ Stores a model. """ logging.basicConfig(level=logging.INFO) target_lems_version = __schema_version__ schema_location = __schema_location__ # schema_location = '/home/padraig/LEMS/Schemas/LEMS/LEMS_v%s.xsd'%target_lems_version debug = False def __init__(self, include_includes=True, fail_on_missing_includes=True): """ Constructor. """ self.targets = list() """ List of targets to be run on startup. :type: list(str) """ self.includes = Map() """ Dictionary of includes defined in the model. :type: dict(str, lems.model.fundamental.Include """ self.dimensions = Map() """ Dictionary of dimensions defined in the model. :type: dict(str, lems.model.fundamental.Dimension """ self.units = Map() """ Map of units defined in the model. :type: dict(str, lems.model.fundamental.Unit """ self.component_types = Map() """ Map of component types defined in the model. :type: dict(str, lems.model.component.ComponentType) """ self.components = Map() """ Map of root components defined in the model. :type: dict(str, lems.model.component.Component) """ self.fat_components = Map() """ Map of root fattened components defined in the model. :type: dict(str, lems.model.component.FatComponent) """ self.constants = Map() """ Map of constants in this component type. :type: dict(str, lems.model.component.Constant) """ self.include_directories = [] """ List of include directories to search for included LEMS files. :type: list(str) """ self.included_files = [] """ List of files already included. :type: list(str) """ self.description = None """ Short description of contents of LEMS file :type: str """ self.include_includes = include_includes """ Whether to include LEMS definitions in <Include> elements :type: boolean """ self.fail_on_missing_includes = fail_on_missing_includes """ Whether to raise an Exception when a file in an <Include> element is not found :type: boolean """ self.resolved_model = None """ A resolved version of the model, generated by self.resolve() :type: None or Model""" self.comp_ref_map = None """ A map of the component references in the model, generated by self.get_comp_reference_map :type: None or Map """ def add_target(self, target): """ Adds a simulation target to the model. :param target: Name of the component to be added as a simulation target. :type target: str """ self.targets.append(target) def add_include(self, include): """ Adds an include to the model. :param include: Include to be added. :type include: lems.model.fundamental.Include """ self.includes[include.file] = include def add_dimension(self, dimension): """ Adds a dimension to the model. :param dimension: Dimension to be added. :type dimension: lems.model.fundamental.Dimension """ self.dimensions[dimension.name] = dimension def add_unit(self, unit): """ Adds a unit to the model. :param unit: Unit to be added. :type unit: lems.model.fundamental.Unit """ self.units[unit.symbol] = unit def add_component_type(self, component_type): """ Adds a component type to the model. :param component_type: Component type to be added. :type component_type: lems.model.fundamental.ComponentType """ name = component_type.name # To handle colons in names in LEMS if ":" in name: name = name.replace(":", "_") component_type.name = name self.component_types[name] = component_type def add_component(self, component): """ Adds a component to the model. :param component: Component to be added. :type component: lems.model.fundamental.Component """ self.components[component.id] = component def add_fat_component(self, fat_component): """ Adds a fattened component to the model. :param fat_component: Fattened component to be added. :type fat_component: lems.model.fundamental.Fat_component """ self.fat_components[fat_component.id] = fat_component def add_constant(self, constant): """ Adds a paramter to the model. :param constant: Constant to be added. :type constant: lems.model.component.Constant """ self.constants[constant.name] = constant def add(self, child): """ Adds a typed child object to the model. :param child: Child object to be added. """ if isinstance(child, Include): self.add_include(child) elif isinstance(child, Dimension): self.add_dimension(child) elif isinstance(child, Unit): self.add_unit(child) elif isinstance(child, ComponentType): self.add_component_type(child) elif isinstance(child, Component): self.add_component(child) elif isinstance(child, FatComponent): self.add_fat_component(child) elif isinstance(child, Constant): self.add_constant(child) else: raise ModelError("Unsupported child element") def add_include_directory(self, path): """ Adds a directory to the include file search path. :param path: Directory to be added. :type path: str """ self.include_directories.append(path) def include_file(self, path, include_dirs=[]): """ Includes a file into the current model. :param path: Path to the file to be included. :type path: str :param include_dirs: Optional alternate include search path. :type include_dirs: list(str) """ if self.include_includes: if self.debug: print( "------------------ Including a file: %s" % path ) inc_dirs = include_dirs if include_dirs else self.include_dirs parser = LEMSFileParser(self, inc_dirs, self.include_includes) if os.access(path, os.F_OK): if not path in self.included_files: with open(path) as f: parser.parse(f.read()) self.included_files.append(path) return else: if self.debug: print("Already included: %s" % path) return else: for inc_dir in inc_dirs: new_path = inc_dir + "/" + path if os.access(new_path, os.F_OK): if not new_path in self.included_files: with open(new_path) as f: parser.parse(f.read()) self.included_files.append(new_path) return else: if self.debug: print("Already included: %s" % path) return msg = "Unable to open " + path if self.fail_on_missing_includes: raise Exception(msg) elif self.debug: print(msg) def import_from_file(self, filepath): """ Import a model from a file. :param filepath: File to be imported. :type filepath: str """ inc_dirs = self.include_directories[:] inc_dirs.append(dirname(filepath)) parser = LEMSFileParser(self, inc_dirs, self.include_includes) with open(filepath) as f: parser.parse(f.read()) def export_to_dom(self): """ Exports this model to a DOM. """ namespaces = ( 'xmlns="http://www.neuroml.org/lems/%s" ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'xsi:schemaLocation="http://www.neuroml.org/lems/%s %s"' ) namespaces = namespaces % ( self.target_lems_version, self.target_lems_version, self.schema_location, ) xmlstr = "<Lems %s>" % namespaces for include in self.includes: xmlstr += include.toxml() for target in self.targets: xmlstr += '<Target component="{0}"/>'.format(target) for dimension in self.dimensions: xmlstr += dimension.toxml() for unit in self.units: xmlstr += unit.toxml() for constant in self.constants: xmlstr += constant.toxml() for component_type in self.component_types: xmlstr += component_type.toxml() for component in self.components: xmlstr += component.toxml() xmlstr += "</Lems>" try: xmldom = minidom.parseString(xmlstr) except ExpatError as er: print("Parsing error:", errors.messages[er.code]) print("at: " + xmlstr[er.offset : er.offset + 20]) raise return xmldom def export_to_file(self, filepath, level_prefix=" "): """ Exports this model to a file. :param filepath: File to be exported to. :type filepath: str """ xmldom = self.export_to_dom() xmlstr = xmldom.toprettyxml( level_prefix, "\n", ) with open(filepath, "w") as f: f.write(xmlstr) f.flush() os.fsync(f.fileno()) def resolve(self) -> lems.model.Model: """ Resolves references in this model and returns resolved model. :returns: resolved Model """ if self.resolved_model: return self.resolved_model model = self.copy() for ct in model.component_types: model.resolve_component_type(ct) for c in model.components: if c.id not in model.fat_components: model.add(model.fatten_component(c)) for c in ct.constants: c2 = c.copy() c2.numeric_value = model.get_numeric_value(c2.value, c2.dimension) model.add(c2) self.resolved_model = model return self.resolved_model def resolve_component_type(self, component_type): """ Resolves references in the specified component type. :param component_type: Component type to be resolved. :type component_type: lems.model.component.ComponentType """ # Resolve component type from base types if present. if component_type.extends: try: base_ct = self.component_types[component_type.extends] except: raise ModelError( "Component type '{0}' trying to extend unknown component type '{1}'", component_type.name, component_type.extends, ) self.resolve_component_type(base_ct) self.merge_component_types(component_type, base_ct) component_type.types = set.union(component_type.types, base_ct.types) component_type.extends = None def merge_component_types(self, ct, base_ct): """ Merge various maps in the given component type from a base component type. :param ct: Component type to be resolved. :type ct: lems.model.component.ComponentType :param base_ct: Component type to be resolved. :type base_ct: lems.model.component.ComponentType """ # merge_maps(ct.parameters, base_ct.parameters) for parameter in base_ct.parameters: if parameter.name in ct.parameters: p = ct.parameters[parameter.name] basep = base_ct.parameters[parameter.name] if p.fixed: p.value = p.fixed_value p.dimension = basep.dimension else: ct.parameters[parameter.name] = base_ct.parameters[parameter.name] merge_maps(ct.properties, base_ct.properties) merge_maps(ct.derived_parameters, base_ct.derived_parameters) merge_maps(ct.index_parameters, base_ct.index_parameters) merge_maps(ct.constants, base_ct.constants) merge_maps(ct.exposures, base_ct.exposures) merge_maps(ct.requirements, base_ct.requirements) merge_maps(ct.component_requirements, base_ct.component_requirements) merge_maps(ct.instance_requirements, base_ct.instance_requirements) merge_maps(ct.children, base_ct.children) merge_maps(ct.texts, base_ct.texts) merge_maps(ct.links, base_ct.links) merge_maps(ct.paths, base_ct.paths) merge_maps(ct.event_ports, base_ct.event_ports) merge_maps(ct.component_references, base_ct.component_references) merge_maps(ct.attachments, base_ct.attachments) merge_maps(ct.dynamics.state_variables, base_ct.dynamics.state_variables) merge_maps(ct.dynamics.derived_variables, base_ct.dynamics.derived_variables) merge_maps( ct.dynamics.conditional_derived_variables, base_ct.dynamics.conditional_derived_variables, ) merge_maps(ct.dynamics.time_derivatives, base_ct.dynamics.time_derivatives) # merge_lists(ct.dynamics.event_handlers, base_ct.dynamics.event_handlers) merge_maps(ct.dynamics.kinetic_schemes, base_ct.dynamics.kinetic_schemes) merge_lists(ct.structure.event_connections, base_ct.structure.event_connections) merge_lists(ct.structure.child_instances, base_ct.structure.child_instances) merge_lists( ct.structure.multi_instantiates, base_ct.structure.multi_instantiates ) merge_maps(ct.simulation.runs, base_ct.simulation.runs) merge_maps(ct.simulation.records, base_ct.simulation.records) merge_maps(ct.simulation.event_records, base_ct.simulation.event_records) merge_maps(ct.simulation.data_displays, base_ct.simulation.data_displays) merge_maps(ct.simulation.data_writers, base_ct.simulation.data_writers) merge_maps(ct.simulation.event_writers, base_ct.simulation.event_writers) def fatten_component(self, c): """ Fatten a component but resolving all references into the corresponding component type. :param c: Lean component to be fattened. :type c: lems.model.component.Component :return: Fattened component. :rtype: lems.model.component.FatComponent """ if self.debug: print("Fattening %s" % c.id) try: ct = self.component_types[c.type] except: raise ModelError( "Unable to resolve type '{0}' for component '{1}'; existing: {2}", c.type, c.id, self.component_types.keys(), ) fc = FatComponent(c.id, c.type) if c.parent_id: fc.set_parent_id(c.parent_id) ### Resolve parameters for parameter in ct.parameters: if self.debug: print("Checking: %s" % parameter) if parameter.name in c.parameters: p = parameter.copy() p.value = c.parameters[parameter.name] p.numeric_value = self.get_numeric_value(p.value, p.dimension) fc.add_parameter(p) elif parameter.fixed: p = parameter.copy() p.numeric_value = self.get_numeric_value(p.value, p.dimension) fc.add_parameter(p) else: raise ModelError( "Parameter '{0}' not initialized for component '{1}'", parameter.name, c.id, ) ### Resolve properties for property in ct.properties: property2 = property.copy() fc.add(property2) ### Resolve derived_parameters for derived_parameter in ct.derived_parameters: derived_parameter2 = derived_parameter.copy() fc.add(derived_parameter2) ### Resolve derived_parameters for index_parameter in ct.index_parameters: raise ModelError("IndexParameter not yet implemented in PyLEMS!") index_parameter2 = index_parameter.copy() fc.add(index_parameter2) ### Resolve constants for constant in ct.constants: constant2 = constant.copy() constant2.numeric_value = self.get_numeric_value( constant2.value, constant2.dimension ) fc.add(constant2) ### Resolve texts for text in ct.texts: t = text.copy() t.value = c.parameters[text.name] if text.name in c.parameters else "" fc.add(t) ### Resolve texts for link in ct.links: if link.name in c.parameters: l = link.copy() l.value = c.parameters[link.name] fc.add(l) else: raise ModelError( "Link parameter '{0}' not initialized for component '{1}'", link.name, c.id, ) ### Resolve paths for path in ct.paths: if path.name in c.parameters: p = path.copy() p.value = c.parameters[path.name] fc.add(p) else: raise ModelError( "Path parameter '{0}' not initialized for component '{1}'", path.name, c.id, ) if len(ct.component_requirements) > 0: raise ModelError("ComponentRequirement not yet implemented in PyLEMS!") if len(ct.instance_requirements) > 0: raise ModelError("InstanceRequirement not yet implemented in PyLEMS!") ### Resolve component references. for cref in ct.component_references: if cref.local: raise ModelError( "Attribute local on ComponentReference not yet implemented in PyLEMS!" ) if cref.name in c.parameters: cref2 = cref.copy() cid = c.parameters[cref.name] if cid not in self.fat_components: self.add(self.fatten_component(self.components[cid])) cref2.referenced_component = self.fat_components[cid] fc.add(cref2) else: raise ModelError( "Component reference '{0}' not initialized for component '{1}'", cref.name, c.id, ) merge_maps(fc.exposures, ct.exposures) merge_maps(fc.requirements, ct.requirements) merge_maps(fc.component_requirements, ct.component_requirements) merge_maps(fc.instance_requirements, ct.instance_requirements) merge_maps(fc.children, ct.children) merge_maps(fc.texts, ct.texts) merge_maps(fc.links, ct.links) merge_maps(fc.paths, ct.paths) merge_maps(fc.event_ports, ct.event_ports) merge_maps(fc.attachments, ct.attachments) fc.dynamics = ct.dynamics.copy() if len(fc.dynamics.regimes) != 0: fc.dynamics.clear() self.resolve_structure(fc, ct) self.resolve_simulation(fc, ct) fc.types = ct.types ### Resolve children for child in c.children: fc.add(self.fatten_component(child)) return fc def get_parent_component(self, fc): """ TODO: Replace with more efficient way to do this... """ if self.debug: print("Looking for parent of %s (%s)" % (fc.id, fc.parent_id)) parent_comp = None for comp in self.components.values(): if self.debug: print(" - Checking " + comp.id) for child in comp.children: if parent_comp == None: if child.id == fc.id and comp.id == fc.parent_id: if self.debug: print("1) It is " + comp.id) parent_comp = comp else: for child2 in child.children: if self.debug: print( " - Checking child: %s, %s" % (child.id, child2.id) ) if ( parent_comp == None and child2.id == fc.id and child.id == fc.parent_id ): if self.debug: print("2) It is " + child.id) parent_comp = child break else: if self.debug: print("No...") return parent_comp def resolve_structure(self, fc, ct): """ Resolve structure specifications. """ if self.debug: print("++++++++ Resolving structure of (%s) with %s" % (fc, ct)) for w in ct.structure.withs: try: if w.instance == "parent" or w.instance == "this": w2 = With(w.instance, w.as_) else: w2 = With(fc.paths[w.instance].value, w.as_) except: raise ModelError( "Unable to resolve With parameters for " "'{0}' in component '{1}'", w.as_, fc.id, ) fc.structure.add(w2) if len(ct.structure.tunnels) > 0: raise ModelError("Tunnel is not yet supported in PyLEMS!") for fe in ct.structure.for_eachs: fc.structure.add_for_each(fe) for ev in ct.structure.event_connections: try: from_inst = fc.structure.withs[ev.from_].instance to_inst = fc.structure.withs[ev.to].instance if self.debug: print( "EC..: " + from_inst + " to " + to_inst + " in " + str(fc.paths) ) if len(fc.texts) > 0 or len(fc.paths) > 0: source_port = ( fc.texts[ev.source_port].value if ev.source_port and len(ev.source_port) > 0 and ev.source_port in fc.texts else None ) target_port = ( fc.texts[ev.target_port].value if ev.target_port and len(ev.target_port) > 0 and ev.target_port in fc.texts else None ) if self.debug: print("sp: %s" % source_port) if self.debug: print("tp: %s" % target_port) receiver = None # TODO: Get more efficient way to find parent comp if "../" in ev.receiver: receiver_id = None parent_attr = ev.receiver[3:] if self.debug: print( "Finding %s in the parent of: %s (%i)" % (parent_attr, fc, id(fc)) ) for comp in self.components.values(): if self.debug: print(" - Checking %s (%i)" % (comp.id, id(comp))) for child in comp.children: if self.debug: print( " - Checking %s (%i)" % (child.id, id(child)) ) for child2 in child.children: if ( child2.id == fc.id and child2.type == fc.type and child.id == fc.parent_id ): if self.debug: print( " - Got it?: %s (%i), child: %s" % (child.id, id(child), child2) ) receiver_id = child.parameters[parent_attr] if self.debug: print("Got it: " + receiver_id) break if receiver_id is not None: for comp in self.fat_components: if comp.id == receiver_id: receiver = comp if self.debug: print("receiver is: %s" % receiver) if self.debug: print("rec1: %s" % receiver) if not receiver: receiver = ( fc.component_references[ev.receiver].referenced_component if ev.receiver else None ) receiver_container = ( fc.texts[ev.receiver_container].value if (fc.texts and ev.receiver_container) else "" ) if self.debug: print("rec2: %s" % receiver) if len(receiver_container) == 0: # TODO: remove this hard coded check! receiver_container = "synapses" else: # if from_inst == 'parent': # par = fc.component_references[ev.receiver] if self.debug: print("+++++++++++++++++++") print(ev.toxml()) print(ev.source_port) print(fc) source_port = ev.source_port target_port = ev.target_port receiver = None receiver_container = None ev2 = EventConnection( from_inst, to_inst, source_port, target_port, receiver, receiver_container, ) if self.debug: print("Created EC: " + ev2.toxml()) print(receiver) print(receiver_container) except: logging.exception("Something awful happened!") raise ModelError( "Unable to resolve event connection parameters in component '{0}'", fc, ) fc.structure.add(ev2) for ch in ct.structure.child_instances: try: if self.debug: print(ch.toxml()) if "../" in ch.component: parent = self.get_parent_component(fc) if self.debug: print("Parent: %s" % parent) comp_ref = ch.component[3:] if self.debug: print("comp_ref: %s" % comp_ref) comp_id = parent.parameters[comp_ref] comp = self.fat_components[comp_id] ch2 = ChildInstance(ch.component, comp) else: ref_comp = fc.component_references[ ch.component ].referenced_component ch2 = ChildInstance(ch.component, ref_comp) except Exception as e: if self.debug: print(e) raise ModelError( "Unable to resolve child instance parameters for " "'{0}' in component '{1}'", ch.component, fc.id, ) fc.structure.add(ch2) for mi in ct.structure.multi_instantiates: try: if mi.component: mi2 = MultiInstantiate( component=fc.component_references[ mi.component ].referenced_component, number=int(fc.parameters[mi.number].numeric_value), ) else: mi2 = MultiInstantiate( component_type=fc.component_references[ mi.component_type ].referenced_component, number=int(fc.parameters[mi.number].numeric_value), ) except: raise ModelError( "Unable to resolve multi-instantiate parameters for " "'{0}' in component '{1}'", mi.component, fc, ) fc.structure.add(mi2) def resolve_simulation(self, fc, ct): """ Resolve simulation specifications. """ for run in ct.simulation.runs: try: run2 = Run( fc.component_references[run.component].referenced_component, run.variable, fc.parameters[run.increment].numeric_value, fc.parameters[run.total].numeric_value, ) except: raise ModelError( "Unable to resolve simulation run parameters in component '{0}'", fc.id, ) fc.simulation.add(run2) for record in ct.simulation.records: try: record2 = Record( fc.paths[record.quantity].value, fc.parameters[record.scale].numeric_value if record.scale else 1, fc.texts[record.color].value if record.color else "#000000", ) except: raise ModelError( "Unable to resolve simulation record parameters in component '{0}'", fc.id, ) fc.simulation.add(record2) for event_record in ct.simulation.event_records: try: event_record2 = EventRecord( fc.paths[event_record.quantity].value, fc.texts[event_record.eventPort].value, ) except: raise ModelError( "Unable to resolve simulation event_record parameters in component '{0}'", fc.id, ) fc.simulation.add(event_record2) for dd in ct.simulation.data_displays: try: dd2 = DataDisplay(fc.texts[dd.title].value, "") if "timeScale" in fc.parameters: dd2.timeScale = fc.parameters["timeScale"].numeric_value except: raise ModelError( "Unable to resolve simulation display parameters in component '{0}'", fc.id, ) fc.simulation.add(dd2) for dw in ct.simulation.data_writers: try: path = "." if fc.texts[dw.path] and fc.texts[dw.path].value: path = fc.texts[dw.path].value dw2 = DataWriter(path, fc.texts[dw.file_name].value) except: raise ModelError( "Unable to resolve simulation writer parameters in component '{0}'", fc.id, ) fc.simulation.add(dw2) for ew in ct.simulation.event_writers: try: path = "." if fc.texts[ew.path] and fc.texts[ew.path].value: path = fc.texts[ew.path].value ew2 = EventWriter( path, fc.texts[ew.file_name].value, fc.texts[ew.format].value ) except: raise ModelError( "Unable to resolve simulation writer parameters in component '{0}'", fc.id, ) fc.simulation.add(ew2) def get_numeric_value(self, value_str, dimension=None): """ Get the numeric value for a parameter value specification. :param value_str: Value string :type value_str: str :param dimension: Dimension of the value :type dimension: str """ n = None i = len(value_str) while n is None: try: part = value_str[0:i] nn = float(part) n = nn s = value_str[i:] except ValueError: i = i - 1 number = n sym = s numeric_value = None if sym == "": numeric_value = number else: if sym in self.units: unit = self.units[sym] if dimension: if dimension != unit.dimension and dimension != "*": raise SimBuildError( "Unit symbol '{0}' cannot " "be used for dimension '{1}'", sym, dimension, ) else: dimension = unit.dimension numeric_value = (number * (10**unit.power) * unit.scale) + unit.offset else: raise SimBuildError( "Unknown unit symbol '{0}'. Known: {1}", sym, self.units ) # print("Have converted %s to value: %s, dimension %s"%(value_str, numeric_value, dimension)) return numeric_value def get_component_list(self, substring: str = "") -> dict[str, Component]: """Get all components whose id matches the given substring. Note that in PyLEMS, if a component does not have an id attribute, PyLEMS uses the name of the component as its ID. See the parser methods in LEMSFileParser. This function is required because the component and fat_component attribute of the model class only holds lists of the top level components and not its child/children elements. So we need to manually fetch them. :param substring: substring to match components against :type substring: str :returns: Dict of components matching the substring of the form {'id' : Component } """ comp_list = {} ret_list = {} # For each top level component, recursively get to all children # There is no advantage of resolving the model and using fat_components # here. They do store a component's "children" but as `Children` # objects and one cannot easily recursively descend the tree using # them. So it is easier to use (non-fat) components here, which hold # children as `Component` objects. for comp in self.components: comp_list.update(self.get_nested_components(comp)) for c in comp_list.values(): if substring in c.id: ret_list.update({c.id: c}) return ret_list def get_fattened_component_list(self, substring: str = "") -> Map: """Get a list of fattened components whose ids include the substring. A "fattened component" is one where all elements of the components have been resolved. See lems.model.component.FatComponent. :param substring: substring to match components against :type substring: str :returns: Map of fattened components matching the substring """ resolved_model = self.resolve() fattened_comp_list = Map() comp_list = resolved_model.get_component_list(substring).values() for comp in comp_list: fattened_comp_list[comp.id] = resolved_model.fatten_component(comp) return fattened_comp_list def get_nested_components(self, comp: Component) -> dict[str, Component]: """Get all nested (child/children) components in the comp component :param comp: component to get all nested (child/children) components for :type comp: Component :returns: list of components """ comp_list = {} comp_list.update({comp.id: comp}) for c in comp.children: comp_list.update(self.get_nested_components(c)) return comp_list def list_exposures(self, substring: str = "") -> dict[FatComponent, Map]: """Get exposures from model belonging to components which contain the given substring. :param substring: substring to match for in component names :type substring: str :returns: dictionary of components and their exposures The returned dictionary is of the form: .. code-block:: python { "component": ["exp1", "exp2"] } """ exposures = {} comp_list = self.get_fattened_component_list(substring) for comp in comp_list.values(): cur_type = self.component_types[comp.type] allexps = Map() # Add exposures of the component type itself try: allexps.update(self.component_types[comp.type].exposures) except KeyError: if self.debug: print("No exposures found for {}".format(comp.type)) # Also get exposures inherited from parents while cur_type.extends: parent = cur_type.extends try: allexps.update(self.component_types[parent].exposures) except KeyError: if self.debug: print("No exposures found for {}".format(parent.type)) cur_type = self.component_types[parent] exposures[comp] = allexps return exposures def get_full_comp_paths_with_comp_refs( self, comp: FatComponent, comptext: typing.Optional[str] = None ): """Get list of component paths with all component references also resolved for the given component `comp`. This does not return a value, but fills in self.temp_vec with all the possible paths as individual lists. These can then be passed to the construct_path method to construct string paths. Additionally, note that this generates paths from the model declaration, not from a built simulation instance of the model. Therefore, it does not find paths that are constructed during build time. XXX: should this be converted to a private method? :param comp: Component to get all paths for :type comp: Component :param comptext: text to use for component (used for generation of path strings) :type comptext: str """ debug = False # ref_map = self.get_comp_ref_map() fat_components = self.get_fattened_component_list() if debug: print("Processing {}".format(comp.id)) self.temp_vec.append(comp.id) if comptext: if debug: print("for {}, text given: {}".format(comp.id, comptext)) self.path_vec.append(comptext) else: self.path_vec.append(comp.id) # proceed further in the tree nextchildren = [] # check if any children components are used in the model for this comp for ch in comp.children: if ch.name in fat_components: nextchildren.append(fat_components[ch.name]) if debug: print( "children {} for {} added".format( fat_components[ch.name], comp.id ) ) # check if any child components are used in the model for this comp nextchild = [] for cc in comp.child_components: if cc.id in fat_components: nextchild.append(cc) if debug: print("child {} for {} added".format(cc, comp.id)) nextattachment = [] # attachments # TODO: not sure what function these serve before build time for at in comp.attachments: if at.name in fat_components: nextattachment.append(fat_components[at.name]) if debug: print("attachment {} for {} added".format(cc, comp.id)) # structure # multi instantiates nextmi = [] for mi in comp.structure.multi_instantiates: # replace comp with comp[*] for each multi instantiated comp self.path_vec[-1] = "SKIP" for mi_n in range(mi.number): nextmi.append(mi.component) if debug: print("MI {} for {} added".format(mi.component.id, comp.id)) # child instances nextci = [] for ci in comp.structure.child_instances: nextci.append(ci.referenced_component) if debug: print("CI {} for {} added".format(ci.referenced_component.id, comp.id)) # nothing to be done for Withs # event connections: note: when the simulation is built, the event # connections are processes and the sources attached to the necessary # target instances. Since we are not building the simulation here, we # cannot list the exposures from event connection inputs at the target # instances. nextec = [] for ec in comp.structure.event_connections: nextec.append(fat_components[ec.receiver.id]) if debug: print("EC {} appended for {}".format(ec.receiver.id, comp.id)) # a leaf node if ( not len(nextchildren) and not len(nextchild) and not len(nextattachment) and not len(nextmi) and not len(nextci) and not len(nextec) ): if debug: print("{} is leaf".format(comp.id)) print("Append {} to recording_paths".format(self.temp_vec)) print("Append {} to recording_paths_text".format(self.path_vec)) # append a copy since the path_vec is emptied out each time self.recording_paths.append(copy.deepcopy(self.temp_vec)) self.recording_paths_text.append(copy.deepcopy(self.path_vec)) self.temp_vec.pop() self.path_vec.pop() return # process all next level nodes for nextnode in nextchildren + nextchild: self.get_full_comp_paths_with_comp_refs(nextnode) for nextnode in nextattachment: self.get_full_comp_paths_with_comp_refs(nextnode, "SKIP") i = 0 for nextnode in nextmi: self.get_full_comp_paths_with_comp_refs( nextnode, "{}[{}]".format(comp.id, i) ) i += 1 for nextnode in nextci: self.get_full_comp_paths_with_comp_refs(nextnode, "SKIP") for nextnode in nextec: self.get_full_comp_paths_with_comp_refs(nextnode) self.temp_vec.pop() self.path_vec.pop() def construct_path( self, pathlist: list[str], skip: typing.Optional[str] = None ) -> str: """Construct path from a list. :param vec: list of text strings to generate path from :type vec: list(str) :param skip: text strings to skip :type skip: str :returns: generated path string """ # remove "", which are components we don't want to include in the path if skip: while skip in pathlist: pathlist.remove(skip) return "/".join(pathlist) def list_recording_paths_for_exposures( self, substring: str = "", target: str = "" ) -> list[str]: """List recording paths for exposures in the model for components matching the given substring, and for the given simulation target. This is a helper method that will generate *all* recording paths for exposures in the provided LEMS model. Since a detailed model may include many paths, it is suggested to use the `substring` parameter to limit the list to necessary components only. Please note that this uses only the declared model, and not a built instance of the model. Therefore, it returns a subset of all possible paths. :param substring: substring to match component IDs against :type substring: str :param target: simulation target whose components are to be analysed :type target: str :return: list of generated path strings """ if not len(target): print("Please provide a target element.") return [] exposures = self.list_exposures(substring) resolved_comps = self.get_fattened_component_list() target_comp = self.get_fattened_component_list(target) if len(target_comp) != 1: print("Multiple targets found. Please use a unique target name") return [] if self.debug: print(resolved_comps) # temporary for the depth first search self.temp_vec = [] self.path_vec = [] # store our recording paths # this stores the comp.ids self.recording_paths = [] self.recording_paths_text = [] target_comp = resolved_comps[target] self.get_full_comp_paths_with_comp_refs(target_comp) exp_paths = [] for r in range(len(self.recording_paths)): p = self.recording_paths[r] t = self.recording_paths_text[r] # go over each element, appending exposures where needed for i in range(len(p)): compid = p[i] comppath = t[0 : i + 1] for acomp, exps in exposures.items(): if acomp.id == compid: for exp in exps: if self.debug: print( "full comppath is {}".format(comppath + [exp.name]) ) newpath = self.construct_path(comppath + [exp.name], "SKIP") if newpath not in exp_paths: exp_paths.append(newpath) else: if self.debug: print("No exposures for {}".format(p[i])) pass exp_paths.sort() if self.debug: print("\n".join(exp_paths)) return exp_paths def get_comp_ref_map(self) -> Map: """Get a Map of ComponentReferences in the model. :returns: Map with target -> [source] entries """ if self.comp_ref_map: return self.comp_ref_map fat_components = self.get_fattened_component_list() self.comp_ref_map = Map() for fc in fat_components.values(): for cr in fc.component_references.values(): try: self.comp_ref_map[cr.referenced_component.id].append(fc) except KeyError: self.comp_ref_map[cr.referenced_component.id] = [fc] return self.comp_ref_map
class Model(LEMSBase): ''' Stores a model. ''' def __init__(self, include_includes=True, fail_on_missing_includes=True): ''' Constructor. ''' pass def add_target(self, target): ''' Adds a simulation target to the model. :param target: Name of the component to be added as a simulation target. :type target: str ''' pass def add_include(self, include): ''' Adds an include to the model. :param include: Include to be added. :type include: lems.model.fundamental.Include ''' pass def add_dimension(self, dimension): ''' Adds a dimension to the model. :param dimension: Dimension to be added. :type dimension: lems.model.fundamental.Dimension ''' pass def add_unit(self, unit): ''' Adds a unit to the model. :param unit: Unit to be added. :type unit: lems.model.fundamental.Unit ''' pass def add_component_type(self, component_type): ''' Adds a component type to the model. :param component_type: Component type to be added. :type component_type: lems.model.fundamental.ComponentType ''' pass def add_component_type(self, component_type): ''' Adds a component to the model. :param component: Component to be added. :type component: lems.model.fundamental.Component ''' pass def add_fat_component(self, fat_component): ''' Adds a fattened component to the model. :param fat_component: Fattened component to be added. :type fat_component: lems.model.fundamental.Fat_component ''' pass def add_constant(self, constant): ''' Adds a paramter to the model. :param constant: Constant to be added. :type constant: lems.model.component.Constant ''' pass def add_target(self, target): ''' Adds a typed child object to the model. :param child: Child object to be added. ''' pass def add_include_directory(self, path): ''' Adds a directory to the include file search path. :param path: Directory to be added. :type path: str ''' pass def include_file(self, path, include_dirs=[]): ''' Includes a file into the current model. :param path: Path to the file to be included. :type path: str :param include_dirs: Optional alternate include search path. :type include_dirs: list(str) ''' pass def import_from_file(self, filepath): ''' Import a model from a file. :param filepath: File to be imported. :type filepath: str ''' pass def export_to_dom(self): ''' Exports this model to a DOM. ''' pass def export_to_file(self, filepath, level_prefix=" "): ''' Exports this model to a file. :param filepath: File to be exported to. :type filepath: str ''' pass def resolve(self) -> lems.model.Model: ''' Resolves references in this model and returns resolved model. :returns: resolved Model ''' pass def resolve_component_type(self, component_type): ''' Resolves references in the specified component type. :param component_type: Component type to be resolved. :type component_type: lems.model.component.ComponentType ''' pass def merge_component_types(self, ct, base_ct): ''' Merge various maps in the given component type from a base component type. :param ct: Component type to be resolved. :type ct: lems.model.component.ComponentType :param base_ct: Component type to be resolved. :type base_ct: lems.model.component.ComponentType ''' pass def fatten_component(self, c): ''' Fatten a component but resolving all references into the corresponding component type. :param c: Lean component to be fattened. :type c: lems.model.component.Component :return: Fattened component. :rtype: lems.model.component.FatComponent ''' pass def get_parent_component(self, fc): ''' TODO: Replace with more efficient way to do this... ''' pass def resolve_structure(self, fc, ct): ''' Resolve structure specifications. ''' pass def resolve_simulation(self, fc, ct): ''' Resolve simulation specifications. ''' pass def get_numeric_value(self, value_str, dimension=None): ''' Get the numeric value for a parameter value specification. :param value_str: Value string :type value_str: str :param dimension: Dimension of the value :type dimension: str ''' pass def get_component_list(self, substring: str = "") -> dict[str, Component]: '''Get all components whose id matches the given substring. Note that in PyLEMS, if a component does not have an id attribute, PyLEMS uses the name of the component as its ID. See the parser methods in LEMSFileParser. This function is required because the component and fat_component attribute of the model class only holds lists of the top level components and not its child/children elements. So we need to manually fetch them. :param substring: substring to match components against :type substring: str :returns: Dict of components matching the substring of the form {'id' : Component } ''' pass def get_fattened_component_list(self, substring: str = "") -> Map: '''Get a list of fattened components whose ids include the substring. A "fattened component" is one where all elements of the components have been resolved. See lems.model.component.FatComponent. :param substring: substring to match components against :type substring: str :returns: Map of fattened components matching the substring ''' pass def get_nested_components(self, comp: Component) -> dict[str, Component]: '''Get all nested (child/children) components in the comp component :param comp: component to get all nested (child/children) components for :type comp: Component :returns: list of components ''' pass def list_exposures(self, substring: str = "") -> dict[FatComponent, Map]: '''Get exposures from model belonging to components which contain the given substring. :param substring: substring to match for in component names :type substring: str :returns: dictionary of components and their exposures The returned dictionary is of the form: .. code-block:: python { "component": ["exp1", "exp2"] } ''' pass def get_full_comp_paths_with_comp_refs( self, comp: FatComponent, comptext: typing.Optional[str] = None ): '''Get list of component paths with all component references also resolved for the given component `comp`. This does not return a value, but fills in self.temp_vec with all the possible paths as individual lists. These can then be passed to the construct_path method to construct string paths. Additionally, note that this generates paths from the model declaration, not from a built simulation instance of the model. Therefore, it does not find paths that are constructed during build time. XXX: should this be converted to a private method? :param comp: Component to get all paths for :type comp: Component :param comptext: text to use for component (used for generation of path strings) :type comptext: str ''' pass def construct_path( self, pathlist: list[str], skip: typing.Optional[str] = None ) -> str: '''Construct path from a list. :param vec: list of text strings to generate path from :type vec: list(str) :param skip: text strings to skip :type skip: str :returns: generated path string ''' pass def list_recording_paths_for_exposures( self, substring: str = "", target: str = "" ) -> list[str]: '''List recording paths for exposures in the model for components matching the given substring, and for the given simulation target. This is a helper method that will generate *all* recording paths for exposures in the provided LEMS model. Since a detailed model may include many paths, it is suggested to use the `substring` parameter to limit the list to necessary components only. Please note that this uses only the declared model, and not a built instance of the model. Therefore, it returns a subset of all possible paths. :param substring: substring to match component IDs against :type substring: str :param target: simulation target whose components are to be analysed :type target: str :return: list of generated path strings ''' pass def get_comp_ref_map(self) -> Map: '''Get a Map of ComponentReferences in the model. :returns: Map with target -> [source] entries ''' pass
32
32
42
6
27
9
7
0.32
1
32
21
0
31
19
31
33
1,355
225
856
213
818
275
646
202
614
47
2
9
230
144,474
LEMS/pylems
lems/model/fundamental.py
lems.model.fundamental.Unit
class Unit(LEMSBase): """ Stores a unit definition. """ def __init__( self, name, symbol, dimension, power=0, scale=1.0, offset=0.0, description="" ): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the unit. :type: str """ self.symbol = symbol """ Symbol for the unit. :type: str """ self.dimension = dimension """ Dimension for the unit. :type: str """ self.power = power """ Scaling by power of 10. :type: int """ self.scale = scale """ Scaling. :type: float """ self.offset = offset """ Offset for non-zero units. :type: float """ self.description = description """ Description of this unit. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ # Probably name should be removed altogether until its usage is decided, see # https://github.com/LEMS/LEMS/issues/4 # '''(' name = "{0}"'.format(self.name) if self.name else '') +\''' return ( "<Unit" + (' symbol = "{0}"'.format(self.symbol) if self.symbol else "") + (' dimension = "{0}"'.format(self.dimension) if self.dimension else "") + (' power = "{0}"'.format(self.power) if self.power else "") + (' scale = "{0}"'.format(self.scale) if self.scale else "") + (' offset = "{0}"'.format(self.offset) if self.offset else "") + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class Unit(LEMSBase): ''' Stores a unit definition. ''' def __init__( self, name, symbol, dimension, power=0, scale=1.0, offset=0.0, description="" ): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
33
9
13
12
4
1.04
1
0
0
0
2
7
2
4
72
19
26
12
21
27
11
10
8
7
2
0
8
144,475
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.DataWriter
class DataWriter(DataOutput): """ Stores specification for a data writer. """ def __init__(self, path, file_name): """ Constuctor. See instance variable documentation for information on parameters. """ DataOutput.__init__(self) self.path = path """ Path to the quantity to be saved to file. :type: string """ self.file_name = file_name """ Text parameter to be used for the file name :type: string """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<DataWriter path="{0}" fileName="{1}"/>'.format( self.path, self.file_name ) def __str__(self): return "DataWriter, path: {0}, fileName: {1}".format(self.path, self.file_name)
class DataWriter(DataOutput): ''' Stores specification for a data writer. ''' def __init__(self, path, file_name): ''' Constuctor. See instance variable documentation for information on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass def __str__(self): pass
4
3
9
2
3
4
1
1.27
1
0
0
0
3
2
3
6
35
10
11
6
7
14
9
6
5
1
3
0
3
144,476
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.EventWriter
class EventWriter(DataOutput): """ Stores specification for an event writer. """ def __init__(self, path, file_name, format): """ Constuctor. See instance variable documentation for information on parameters. """ DataOutput.__init__(self) self.path = path """ Path to the quantity to be saved to file. :type: string """ self.file_name = file_name """ Text parameter to be used for the file name :type: string """ self.format = format """ Text parameter to be used for the format :type: string """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<EventWriter path="{0}" fileName="{1}" format="{2}"/>'.format( self.path, self.file_name, self.format ) def __str__(self): return "EventWriter, path: {0}, fileName: {1}, format: {2}".format( self.path, self.file_name, self.format )
class EventWriter(DataOutput): ''' Stores specification for an event writer. ''' def __init__(self, path, file_name, format): ''' Constuctor. See instance variable documentation for information on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass def __str__(self): pass
4
3
12
3
4
4
1
1.14
1
0
0
0
3
3
3
6
42
12
14
7
10
16
10
7
6
1
3
0
3
144,477
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.Record
class Record(LEMSBase): """ Stores the parameters of a <Record> statement. """ def __init__(self, quantity, scale=None, color=None, id=None): """ Constructor. See instance variable documentation for information on parameters. """ self.id = "" """ Id of the quantity :type: str """ self.quantity = quantity """ Path to the quantity to be recorded. :type: str """ self.scale = scale """ Text parameter to be used for scaling the quantity before display. :type: str """ self.color = color """ Text parameter to be used to specify the color for display. :type: str """ self.id = id """ Text parameter to be used to specify an id for the record :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<Record quantity="{0}" scale="{1}" color="{2}" id="{3}"/>'.format( self.quantity, self.scale, self.color, self.id )
class Record(LEMSBase): ''' Stores the parameters of a <Record> statement. ''' def __init__(self, quantity, scale=None, color=None, id=None): ''' Constructor. See instance variable documentation for information on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
20
6
5
9
1
1.82
1
0
0
0
2
4
2
4
45
14
11
7
8
20
9
7
6
1
2
0
2
144,478
LEMS/pylems
lems/model/fundamental.py
lems.model.fundamental.Include
class Include(LEMSBase): """ Include another LEMS file. """ def __init__(self, filename): """ Constructor. :param filename: Name of the file. :type name: str """ self.file = filename """ Name of the file. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<Include file="%s"/>' % self.file
class Include(LEMSBase): ''' Include another LEMS file. ''' def __init__(self, filename): ''' Constructor. :param filename: Name of the file. :type name: str ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
10
3
2
5
1
2.6
1
0
0
0
2
1
2
4
25
7
5
4
2
13
5
4
2
1
2
0
2
144,479
LEMS/pylems
lems/model/structure.py
lems.model.structure.Assign
class Assign(LEMSBase): """ Stores a child assign specification. """ def __init__(self, property, value): """ Constructor. See instance variable documentation for more details on parameters. """ self.property_ = property """ Name of the property reference to be used for instantiation. :type: str """ self.value = value """ Value of the property. :type: str""" def __eq__(self, o): return self.property_ == o.property_ and self.value == o.value def toxml(self): """ Exports this object into a LEMS XML object """ return '<Assign property="{0}" value="{1}"/>'.format(self.property_, self.value)
class Assign(LEMSBase): ''' Stores a child assign specification. ''' def __init__(self, property, value): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __eq__(self, o): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
8
2
2
4
1
1.75
1
0
0
0
3
2
3
5
30
8
8
6
4
14
8
6
4
1
2
0
3
144,480
LEMS/pylems
lems/model/structure.py
lems.model.structure.ChildInstance
class ChildInstance(LEMSBase): """ Stores a child instantiation specification. """ def __init__(self, component, referenced_component=None): """ Constructor. See instance variable documentation for more details on parameters. """ self.component = component """ Name of the component reference to be used for instantiation. :type: str """ self.referenced_component = referenced_component """ Target component being referenced after resolution. :type: lems.model.component.FatComponent """ def __eq__(self, o): return self.component == o.component def toxml(self): """ Exports this object into a LEMS XML object """ return '<ChildInstance component="{0}"/>'.format(self.component)
class ChildInstance(LEMSBase): ''' Stores a child instantiation specification. ''' def __init__(self, component, referenced_component=None): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __eq__(self, o): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
8
2
2
4
1
1.75
1
0
0
0
3
2
3
5
31
9
8
6
4
14
8
6
4
1
2
0
3
144,481
LEMS/pylems
lems/model/structure.py
lems.model.structure.EventConnection
class EventConnection(LEMSBase): """ Stores an event connection specification. """ def __init__( self, from_, to, source_port, target_port, receiver, receiver_container ): """ Constructor. See instance variable documentation for more details on parameters. """ self.from_ = from_ """ Name of the source component for event. :type: str """ self.to = to """ Name of the target component for the event. :type: str """ self.source_port = source_port """ Source port name. :type: str """ self.target_port = target_port """ Target port name. :type: str """ self.receiver = receiver """ Proxy receiver component attached to the target component that actually receiving the event. :type: Component """ self.receiver_container = receiver_container """ Name of the child component grouping to add the receiver to. :type: str """ def __eq__(self, o): return ( self.from_ == o.from_ and self.to == o.to and self.source_port == o.source_port and self.target_port == o.target_port ) def toxml(self): """ Exports this object into a LEMS XML object """ return ( "<EventConnection" + (' from="{0}"'.format(self.from_) if self.from_ else "") + (' to="{0}"'.format(self.to) if self.to else "") + (' sourcePort="{0}"'.format(self.source_port) if self.source_port else "") + (' targetPort="{0}"'.format(self.target_port) if self.target_port else "") + (' receiver="{0}"'.format(self.receiver) if self.receiver else "") + ( ' receiverContainer="{0}"'.format(self.receiver_container) if self.receiver_container else "" ) + "/>" )
class EventConnection(LEMSBase): ''' Stores an event connection specification. ''' def __init__( self, from_, to, source_port, target_port, receiver, receiver_container ): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __eq__(self, o): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
21
5
10
6
3
0.69
1
0
0
0
3
6
3
5
71
17
32
12
26
22
12
10
8
7
2
0
9
144,482
LEMS/pylems
lems/model/structure.py
lems.model.structure.ForEach
class ForEach(LEMSBase): """ ForEach specification. """ def __init__(self, instances, as_): self.instances = instances self.as_ = as_ self.event_connections = list() """ List of event connections. :type: list(lems.model.structure.EventConnection) """ self.for_eachs = list() """ List of for each specs. :type: list(lems.model.structure.ForEach) """ def add_for_each(self, fe): """ Adds a for-each specification. :param fe: For-each specification. :type fe: lems.model.structure.ForEach """ self.for_eachs.append(fe) def add_event_connection(self, ec): """ Adds an event conenction to the structure. :param ec: Event connection. :type ec: lems.model.structure.EventConnection """ self.event_connections.append(ec) def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = "" for event_connection in self.event_connections: chxmlstr += event_connection.toxml() for for_each in self.for_eachs: chxmlstr += for_each.toxml() return '<ForEach instances="{0}" as="{1}">{2}</ForEach>'.format( self.instances, self.as_, chxmlstr )
class ForEach(LEMSBase): ''' ForEach specification. ''' def __init__(self, instances, as_): pass def add_for_each(self, fe): ''' Adds a for-each specification. :param fe: For-each specification. :type fe: lems.model.structure.ForEach ''' pass def add_event_connection(self, ec): ''' Adds an event conenction to the structure. :param ec: Event connection. :type ec: lems.model.structure.EventConnection ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
5
4
12
3
5
4
2
1.05
1
1
0
0
4
4
4
6
55
16
19
12
14
20
17
12
12
3
2
1
6
144,483
LEMS/pylems
lems/model/structure.py
lems.model.structure.MultiInstantiate
class MultiInstantiate(LEMSBase): """ Stores a child multi-instantiation specification. """ def __init__(self, component=None, number=None, component_type=None): """ Constructor. See instance variable documentation for more details on parameters. """ if component and component_type: raise AttributeError( "MultiInstantiate should contain either" " an attribute component or an attribute" " component_type, not both." ) self.component = component """ Name of the component reference to be used for instantiation. :type: str """ self.component_type = component_type """ Name of the component type reference to be used for instantiation. :type: str """ self.number = number """ Name of the paramter specifying the number of times the component reference is to be instantiated. :type: str""" self.assignments = [] """ List of assignments included in MultiInstantiate. :type: list(Assign) """ def __eq__(self, o): if self.component: flag = self.component == o.component and self.number == o.number else: flag = self.component_type == o.component_type and self.number == o.number return flag def add_assign(self, assign): """ Adds an Assign to the structure. :param assign: Assign structure. :type assign: lems.model.structure.Assign """ self.assignments.append(assign) def add(self, child): """ Adds a typed child object to the structure object. :param child: Child object to be added. """ if isinstance(child, Assign): self.add_assign(child) else: raise ModelError("Unsupported child element") def toxml(self): """ Exports this object into a LEMS XML object """ argstr = "" if self.component: argstr += 'component="{0}" '.format(self.component) if self.component_type: argstr += 'componentType="{0}" '.format(self.component_type) if self.number: argstr += 'number="{0}" '.format(self.number) if self.assignments: chxmlstr = "" for assign in self.assignments: chxmlstr += assign.toxml() return "<MultiInstantiate {0}>{1}</MultiInstantiate>".format( argstr, chxmlstr ) else: return "<MultiInstantiate {0}/>".format(argstr)
class MultiInstantiate(LEMSBase): ''' Stores a child multi-instantiation specification. ''' def __init__(self, component=None, number=None, component_type=None): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __eq__(self, o): pass def add_assign(self, assign): ''' Adds an Assign to the structure. :param assign: Assign structure. :type assign: lems.model.structure.Assign ''' pass def add_assign(self, assign): ''' Adds a typed child object to the structure object. :param child: Child object to be added. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
6
5
16
2
8
5
3
0.67
1
3
2
0
5
4
5
7
87
17
42
14
36
28
33
14
27
6
2
2
13
144,484
LEMS/pylems
lems/model/structure.py
lems.model.structure.Structure
class Structure(LEMSBase): """ Stores structural properties of a component type. """ def __init__(self): """ Constructor. """ self.withs = Map() """ Map of With statements. :type: Map(str, lems.model.structure.With) """ self.tunnels = Map() """ Map of tunnel statements. :type: Map(str, lems.model.structure.Tunnel) """ self.event_connections = list() """ List of event connections. :type: list(lems.model.structure.EventConnection) """ self.child_instances = list() """ List of child instantations. :type: list(lems.model.structure.ChildInstance) """ self.multi_instantiates = list() """ List of child multi-instantiations. :type: list(lems.model.structure.MultiInstantiate) """ self.for_eachs = list() """ List of for each specs. :type: list(lems.model.structure.ForEach) """ def has_content(self): if ( len(self.withs) == 0 and len(self.event_connections) == 0 and len(self.child_instances) == 0 and len(self.multi_instantiates) == 0 and len(self.for_eachs) == 0 ): return False else: return True def add_with(self, with_): """ Adds a with-as specification to the structure. :param with_: With-as specification. :type with_: lems.model.structure.With """ self.withs[with_.as_] = with_ def add_tunnel(self, tunnel): """ Adds a tunnel specification to the structure. :param tunnel: tunnel specification. :type tunnel: lems.model.structure.Tunnel """ self.tunnels[tunnel.name] = tunnel def add_event_connection(self, ec): """ Adds an event conenction to the structure. :param ec: Event connection. :type ec: lems.model.structure.EventConnection """ self.event_connections.append(ec) def add_child_instance(self, ci): """ Adds a child instantiation specification. :param ci: Child instantiation specification. :type ci: lems.model.structure.ChildInstance """ self.child_instances.append(ci) def add_multi_instantiate(self, mi): """ Adds a child multi-instantiation specification. :param mi: Child multi-instantiation specification. :type mi: lems.model.structure.MultiInstantiate """ self.multi_instantiates.append(mi) def add_for_each(self, fe): """ Adds a for-each specification. :param fe: For-each specification. :type fe: lems.model.structure.ForEach """ self.for_eachs.append(fe) def add(self, child): """ Adds a typed child object to the structure object. :param child: Child object to be added. """ if isinstance(child, With): self.add_with(child) elif isinstance(child, EventConnection): self.add_event_connection(child) elif isinstance(child, ChildInstance): self.add_child_instance(child) elif isinstance(child, MultiInstantiate): self.add_multi_instantiate(child) elif isinstance(child, ForEach): self.add_for_each(child) else: raise ModelError("Unsupported child element") def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = "" for with_ in self.withs: chxmlstr += with_.toxml() for event_connection in self.event_connections: chxmlstr += event_connection.toxml() for child_instance in self.child_instances: chxmlstr += child_instance.toxml() for multi_instantiate in self.multi_instantiates: chxmlstr += multi_instantiate.toxml() for for_each in self.for_eachs: chxmlstr += for_each.toxml() if chxmlstr: xmlstr = "<Structure>" + chxmlstr + "</Structure>" else: xmlstr = "" return xmlstr
class Structure(LEMSBase): ''' Stores structural properties of a component type. ''' def __init__(self): ''' Constructor. ''' pass def has_content(self): pass def add_with(self, with_): ''' Adds a with-as specification to the structure. :param with_: With-as specification. :type with_: lems.model.structure.With ''' pass def add_tunnel(self, tunnel): ''' Adds a tunnel specification to the structure. :param tunnel: tunnel specification. :type tunnel: lems.model.structure.Tunnel ''' pass def add_event_connection(self, ec): ''' Adds an event conenction to the structure. :param ec: Event connection. :type ec: lems.model.structure.EventConnection ''' pass def add_child_instance(self, ci): ''' Adds a child instantiation specification. :param ci: Child instantiation specification. :type ci: lems.model.structure.ChildInstance ''' pass def add_multi_instantiate(self, mi): ''' Adds a child multi-instantiation specification. :param mi: Child multi-instantiation specification. :type mi: lems.model.structure.MultiInstantiate ''' pass def add_for_each(self, fe): ''' Adds a for-each specification. :param fe: For-each specification. :type fe: lems.model.structure.ForEach ''' pass def add_with(self, with_): ''' Adds a typed child object to the structure object. :param child: Child object to be added. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
11
10
15
3
6
5
2
0.9
1
8
7
0
10
6
10
12
159
43
61
24
50
55
48
24
37
7
2
1
22
144,485
LEMS/pylems
lems/model/structure.py
lems.model.structure.Tunnel
class Tunnel(LEMSBase): """ Stores a Tunnel. """ def __init__(self, name, end_a, end_b, component_a, component_b): """ Constructor. """ self.name = name """ name of Tunnel. :type: str """ self.end_a = end_a """ 'A' end of Tunnel. :type: str """ self.end_b = end_b """ 'B' end of Tunnel. :type: str """ self.component_a = component_a """ Component to create at A. :type: str """ self.component_b = component_b """ Component to create at B. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Tunnel name="{0}"'.format(self.name) + ' endA="{0}"'.format(self.end_a) + ' endB="{0}"'.format(self.end_b) + ' componentA="{0}"'.format(self.component_a) + ' componentB="{0}"'.format(self.component_b) + "/>" )
class Tunnel(LEMSBase): ''' Stores a Tunnel. ''' def __init__(self, name, end_a, end_b, component_a, component_b): ''' Constructor. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
22
6
8
8
1
1.19
1
0
0
0
2
5
2
4
49
14
16
8
13
19
9
8
6
1
2
0
2
144,486
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.Simulation
class Simulation(LEMSBase): """ Stores the simulation-related attributes of a component-type. """ def __init__(self): """ Constructor. """ self.runs = Map() """ Map of runs in this dynamics regime. :type: Map(string, lems.model.simulation.Run) """ self.records = Map() """ Map of recorded variables in this dynamics regime. :type: Map(string, lems.model.simulation.Record """ self.event_records = Map() """ Map of recorded events in this dynamics regime. :type: Map(string, lems.model.simulation.EventRecord """ self.data_displays = Map() """ Map of data displays mapping titles to regions. :type: Map(string, string) """ self.data_writers = Map() """ Map of recorded variables to data writers. :type: Map(string, lems.model.simulation.DataWriter """ self.event_writers = Map() """ Map of recorded variables to event writers. :type: Map(string, lems.model.simulation.EventWriter """ def add_run(self, run): """ Adds a runnable target component definition to the list of runnable components stored in this context. :param run: Run specification :type run: lems.model.simulation.Run """ self.runs[run.component] = run def add_record(self, record): """ Adds a record object to the list of record objects in this dynamics regime. :param record: Record object to be added. :type record: lems.model.simulation.Record """ self.records[record.quantity] = record def add_event_record(self, event_record): """ Adds an eventrecord object to the list of event_record objects in this dynamics regime. :param event_record: EventRecord object to be added. :type event_record: lems.model.simulation.EventRecord """ self.event_records[event_record.quantity] = event_record def add_data_display(self, data_display): """ Adds a data display to this simulation section. :param data_display: Data display to be added. :type data_display: lems.model.simulation.DataDisplay """ self.data_displays[data_display.title] = data_display def add_data_writer(self, data_writer): """ Adds a data writer to this simulation section. :param data_writer: Data writer to be added. :type data_writer: lems.model.simulation.DataWriter """ self.data_writers[data_writer.path] = data_writer def add_event_writer(self, event_writer): """ Adds an event writer to this simulation section. :param event_writer: event writer to be added. :type event_writer: lems.model.simulation.EventWriter """ self.event_writers[event_writer.path] = event_writer def add(self, child): """ Adds a typed child object to the simulation spec. :param child: Child object to be added. """ if isinstance(child, Run): self.add_run(child) elif isinstance(child, Record): self.add_record(child) elif isinstance(child, EventRecord): self.add_event_record(child) elif isinstance(child, DataDisplay): self.add_data_display(child) elif isinstance(child, DataWriter): self.add_data_writer(child) elif isinstance(child, EventWriter): self.add_event_writer(child) else: raise ModelError("Unsupported child element") def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = "" for run in self.runs: chxmlstr += run.toxml() for record in self.records: chxmlstr += record.toxml() for event_record in self.event_records: chxmlstr += event_record.toxml() for data_display in self.data_displays: chxmlstr += data_display.toxml() for data_writer in self.data_writers: chxmlstr += data_writer.toxml() for event_writer in self.event_writers: chxmlstr += event_writer.toxml() if chxmlstr: xmlstr = "<Simulation>" + chxmlstr + "</Simulation>" else: xmlstr = "" return xmlstr
class Simulation(LEMSBase): ''' Stores the simulation-related attributes of a component-type. ''' def __init__(self): ''' Constructor. ''' pass def add_run(self, run): ''' Adds a runnable target component definition to the list of runnable components stored in this context. :param run: Run specification :type run: lems.model.simulation.Run ''' pass def add_record(self, record): ''' Adds a record object to the list of record objects in this dynamics regime. :param record: Record object to be added. :type record: lems.model.simulation.Record ''' pass def add_event_record(self, event_record): ''' Adds an eventrecord object to the list of event_record objects in this dynamics regime. :param event_record: EventRecord object to be added. :type event_record: lems.model.simulation.EventRecord ''' pass def add_data_display(self, data_display): ''' Adds a data display to this simulation section. :param data_display: Data display to be added. :type data_display: lems.model.simulation.DataDisplay ''' pass def add_data_writer(self, data_writer): ''' Adds a data writer to this simulation section. :param data_writer: Data writer to be added. :type data_writer: lems.model.simulation.DataWriter ''' pass def add_event_writer(self, event_writer): ''' Adds an event writer to this simulation section. :param event_writer: event writer to be added. :type event_writer: lems.model.simulation.EventWriter ''' pass def add_run(self, run): ''' Adds a typed child object to the simulation spec. :param child: Child object to be added. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
10
10
16
4
6
6
2
1.07
1
8
8
0
9
6
9
11
156
44
54
24
44
58
47
24
37
8
2
1
22
144,487
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.DataOutput
class DataOutput(LEMSBase): """ Generic data output specification class. """ def __init__(self): """ Constuctor. """ pass
class DataOutput(LEMSBase): ''' Generic data output specification class. ''' def __init__(self): ''' Constuctor. ''' pass
2
2
6
1
2
3
1
2
1
0
0
3
1
0
1
3
11
2
3
2
1
6
3
2
1
1
2
0
1
144,488
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/examples/polkit/service.py
examples.polkit.service.TestObject
class TestObject(object): dbus = ''' <node> <interface name='net.lew21.pydbus.PolkitExample'> <method name='TestAuth'> <arg type='b' name='interactive' direction='in'/> <arg type='s' name='response' direction='out'/> </method> </interface> </node> ''' def TestAuth(self, interactive, dbus_context): if dbus_context.is_authorized('org.freedesktop.policykit.exec', {'polkit.icon': 'abcd', 'aaaa': 'zzzz'}, interactive=interactive): return "OK" else: return "Forbidden"
class TestObject(object): def TestAuth(self, interactive, dbus_context): pass
2
0
5
0
5
0
2
0
1
0
0
0
1
0
1
1
16
0
16
3
14
0
6
3
4
2
1
1
2
144,489
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy_signal.py
pydbus.proxy_signal.ProxySignal
class ProxySignal(object): def __init__(self, iface_name, signal): self._iface_name = iface_name self.__name__ = signal.attrib["name"] self.__qualname__ = self._iface_name + "." + self.__name__ self._args = [arg.attrib["type"] for arg in signal if arg.tag == "arg"] self.__doc__ = "Signal. Callback: (" + ", ".join(self._args) + ")" def connect(self, object, callback): """Subscribe to the signal.""" def signal_fired(sender, object, iface, signal, params): callback(*params) return object._bus.subscribe(sender=object._bus_name, object=object._path, iface=self._iface_name, signal=self.__name__, signal_fired=signal_fired) def __get__(self, instance, owner): if instance is None: return self return bound_signal(self, instance) def __set__(self, instance, value): raise AttributeError("can't set attribute") def __repr__(self): return "<signal " + self.__qualname__ + " at 0x" + format(id(self), "x") + ">"
class ProxySignal(object): def __init__(self, iface_name, signal): pass def connect(self, object, callback): '''Subscribe to the signal.''' pass def signal_fired(sender, object, iface, signal, params): pass def __get__(self, instance, owner): pass def __set__(self, instance, value): pass def __repr__(self): pass
7
1
4
0
3
0
1
0.05
1
2
1
0
5
5
5
5
26
6
19
12
12
1
19
12
12
2
1
1
7
144,490
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/publication.py
pydbus.publication.Publication
class Publication(ExitableWithAliases("unpublish")): __slots__ = () # allow_replacement=True, replace=False def __init__(self, bus, bus_name, *objects, **kwargs): # Python 2 sux for kwarg in kwargs: if kwarg not in ("allow_replacement", "replace",): raise TypeError( self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg)) allow_replacement = kwargs.get("allow_replacement", True) replace = kwargs.get("replace", False) bus_name = auto_bus_name(bus_name) for object_info in objects: path, object, node_info = (None, None, None) if type(object_info) == tuple: if len(object_info) == 3: path, object, node_info = object_info if len(object_info) == 2: path, object = object_info if len(object_info) == 1: object = object_info[0] else: object = object_info path = auto_object_path(bus_name, path) self._at_exit(bus.register_object( path, object, node_info).__exit__) # Request name only after registering all the objects. self._at_exit(bus.request_name( bus_name, allow_replacement=allow_replacement, replace=replace).__exit__)
class Publication(ExitableWithAliases("unpublish")): def __init__(self, bus, bus_name, *objects, **kwargs): pass
2
0
28
5
21
3
8
0.13
1
3
0
0
1
0
1
2
31
6
23
8
21
3
22
8
20
8
1
3
8
144,491
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/publication.py
pydbus.publication.PublicationMixin
class PublicationMixin(object): __slots__ = () def publish(self, bus_name, *objects): """Expose objects on the bus.""" return Publication(self, bus_name, *objects)
class PublicationMixin(object): def publish(self, bus_name, *objects): '''Expose objects on the bus.''' pass
2
1
3
0
2
1
1
0.25
1
1
1
1
1
0
1
1
6
1
4
3
2
1
4
3
2
1
1
0
1
144,492
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/registration.py
pydbus.registration.ObjectRegistration
class ObjectRegistration(ExitableWithAliases("unregister")): __slots__ = () def __init__(self, bus, path, interfaces, wrapper, own_wrapper=False): if own_wrapper: self._at_exit(wrapper.__exit__) def func(interface_name, signal_name, parameters): bus.con.emit_signal(None, path, interface_name, signal_name, parameters) self._at_exit(wrapper.SignalEmitted.connect(func).__exit__) try: ids = [bus.con.register_object( path, interface, wrapper.call_method, None, None) for interface in interfaces] except TypeError as e: if str(e).startswith("argument vtable: Expected Gio.DBusInterfaceVTable"): raise Exception( "GLib 2.46 is required to publish objects; it is impossible in older versions.") else: raise self._at_exit(lambda: [bus.con.unregister_object(id) for id in ids])
class ObjectRegistration(ExitableWithAliases("unregister")): def __init__(self, bus, path, interfaces, wrapper, own_wrapper=False): pass def func(interface_name, signal_name, parameters): pass
3
0
10
2
8
0
3
0
1
3
0
0
1
0
1
2
21
5
16
7
13
0
15
5
12
4
1
2
5
144,493
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/registration.py
pydbus.registration.ObjectWrapper
class ObjectWrapper(ExitableWithAliases("unwrap")): __slots__ = ["object", "outargs", "readable_properties", "writable_properties"] def __init__(self, object, interfaces): self.object = object self.outargs = {} for iface in interfaces: for method in iface.methods: self.outargs[iface.name + "." + method.name] = [arg.signature for arg in method.out_args] self.readable_properties = {} self.writable_properties = {} for iface in interfaces: for prop in iface.properties: if prop.flags & Gio.DBusPropertyInfoFlags.READABLE: self.readable_properties[iface.name + "." + prop.name] = prop.signature if prop.flags & Gio.DBusPropertyInfoFlags.WRITABLE: self.writable_properties[iface.name + "." + prop.name] = prop.signature for iface in interfaces: for signal in iface.signals: s_name = signal.name def EmitSignal(iface, signal): return lambda *args: self.SignalEmitted(iface.name, signal.name, GLib.Variant("(" + "".join(s.signature for s in signal.args) + ")", args)) self._at_exit(getattr(object, signal.name).connect( EmitSignal(iface, signal)).__exit__) if "org.freedesktop.DBus.Properties" not in (iface.name for iface in interfaces): try: def onPropertiesChanged(iface, changed, invalidated): changed = {key: GLib.Variant( self.readable_properties[iface + "." + key], val) for key, val in changed.items()} args = GLib.Variant( "(sa{sv}as)", (iface, changed, invalidated)) self.SignalEmitted( "org.freedesktop.DBus.Properties", "PropertiesChanged", args) self._at_exit(object.PropertiesChanged.connect( onPropertiesChanged).__exit__) except AttributeError: pass SignalEmitted = generic.signal() def call_method(self, connection, sender, object_path, interface_name, method_name, parameters, invocation): try: try: outargs = self.outargs[interface_name + "." + method_name] method = getattr(self.object, method_name) except KeyError: if interface_name == "org.freedesktop.DBus.Properties": if method_name == "Get": method = self.Get outargs = ["v"] elif method_name == "GetAll": method = self.GetAll outargs = ["a{sv}"] elif method_name == "Set": method = self.Set outargs = [] else: raise else: raise sig = signature(method) kwargs = {} if "dbus_context" in sig.parameters and sig.parameters["dbus_context"].kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY): kwargs["dbus_context"] = MethodCallContext(invocation) result = method(*parameters, **kwargs) if len(outargs) == 0: invocation.return_value(None) elif len(outargs) == 1: invocation.return_value(GLib.Variant( "(" + "".join(outargs) + ")", (result,))) else: invocation.return_value(GLib.Variant( "(" + "".join(outargs) + ")", result)) except Exception as e: logger = logging.getLogger(__name__) logger.exception("Exception while handling %s.%s()", interface_name, method_name) # TODO Think of a better way to translate Python exception types to DBus error types. e_type = type(e).__name__ if not "." in e_type: e_type = "unknown." + e_type invocation.return_dbus_error(e_type, str(e)) def Get(self, interface_name, property_name): type = self.readable_properties[interface_name + "." + property_name] result = getattr(self.object, property_name) return GLib.Variant(type, result) def GetAll(self, interface_name): ret = {} for name, type in self.readable_properties.items(): ns, local = name.rsplit(".", 1) if ns == interface_name: ret[local] = GLib.Variant(type, getattr(self.object, local)) return ret def Set(self, interface_name, property_name, value): self.writable_properties[interface_name + "." + property_name] setattr(self.object, property_name, value)
class ObjectWrapper(ExitableWithAliases("unwrap")): def __init__(self, object, interfaces): pass def EmitSignal(iface, signal): pass def onPropertiesChanged(iface, changed, invalidated): pass def call_method(self, connection, sender, object_path, interface_name, method_name, parameters, invocation): pass def Get(self, interface_name, property_name): pass def GetAll(self, interface_name): pass def Set(self, interface_name, property_name, value): pass
8
0
14
1
12
0
4
0.01
1
7
1
0
5
4
5
6
101
16
84
33
76
1
78
32
70
11
1
4
29
144,494
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/registration.py
pydbus.registration.RegistrationMixin
class RegistrationMixin: __slots__ = () def register_object(self, path, object, node_info): if node_info is None: try: node_info = type(object).dbus except AttributeError: node_info = type(object).__doc__ if type(node_info) != list and type(node_info) != tuple: node_info = [node_info] node_info = [Gio.DBusNodeInfo.new_for_xml(ni) for ni in node_info] interfaces = sum((ni.interfaces for ni in node_info), []) wrapper = ObjectWrapper(object, interfaces) return ObjectRegistration(self, path, interfaces, wrapper, own_wrapper=True)
class RegistrationMixin: def register_object(self, path, object, node_info): pass
2
0
15
3
12
0
4
0
0
6
2
1
1
0
1
1
18
4
14
5
12
0
14
5
12
4
0
2
4
144,495
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/_inspect3.py
pydbus._inspect3.Signature
class Signature: empty = _empty def __init__(self, parameters=None, return_annotation=_empty): self.parameters = OrderedDict( ((param.name, param) for param in parameters)) self.return_annotation = return_annotation
class Signature: def __init__(self, parameters=None, return_annotation=_empty): pass
2
0
3
0
3
0
1
0
0
2
1
0
1
2
1
1
6
1
5
5
3
0
5
5
3
1
0
0
1
144,496
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/request_name.py
pydbus.request_name.RequestNameMixin
class RequestNameMixin(object): __slots__ = () def request_name(self, name, allow_replacement=True, replace=False): """Aquires a bus name. Returns ------- NameOwner An object you can use as a context manager to unown the name later. """ return NameOwner(self, name, allow_replacement, replace)
class RequestNameMixin(object): def request_name(self, name, allow_replacement=True, replace=False): '''Aquires a bus name. Returns ------- NameOwner An object you can use as a context manager to unown the name later. ''' pass
2
1
9
1
2
6
1
1.5
1
1
1
1
1
0
1
1
12
2
4
3
2
6
4
3
2
1
1
0
1
144,497
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/subscription.py
pydbus.subscription.Subscription
class Subscription(ExitableWithAliases("unsubscribe", "disconnect")): Flags = Gio.DBusSignalFlags __slots__ = () def __init__(self, con, sender, iface, member, object, arg0, flags, callback): id = con.signal_subscribe( sender, iface, member, object, arg0, flags, callback) self._at_exit(lambda: con.signal_unsubscribe(id))
class Subscription(ExitableWithAliases("unsubscribe", "disconnect")): def __init__(self, con, sender, iface, member, object, arg0, flags, callback): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
0
1
2
7
1
6
4
4
0
6
4
4
1
1
0
1
144,498
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/subscription.py
pydbus.subscription.SubscriptionMixin
class SubscriptionMixin(object): __slots__ = () SubscriptionFlags = Subscription.Flags def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None): """Subscribes to matching signals. Subscribes to signals on connection and invokes signal_fired callback whenever the signal is received. To receive signal_fired callback, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters ---------- sender : string, optional Sender name to match on (unique or well-known name) or None to listen from all senders. iface : string, optional Interface name to match on or None to match on all interfaces. signal : string, optional Signal name to match on or None to match on all signals. object : string, optional Object path to match on or None to match on all object paths. arg0 : string, optional Contents of first string argument to match on or None to match on all kinds of arguments. flags : SubscriptionFlags, optional signal_fired : callable, optional Invoked when there is a signal matching the requested data. Parameters: sender, object, iface, signal, params Returns ------- Subscription An object you can use as a context manager to unsubscribe from the signal later. See Also -------- See https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe for more information. """ callback = (lambda con, sender, object, iface, signal, params: signal_fired( sender, object, iface, signal, params.unpack())) if signal_fired is not None else lambda *args: None return Subscription(self.con, sender, iface, signal, object, arg0, flags, callback)
class SubscriptionMixin(object): def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None): '''Subscribes to matching signals. Subscribes to signals on connection and invokes signal_fired callback whenever the signal is received. To receive signal_fired callback, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters ---------- sender : string, optional Sender name to match on (unique or well-known name) or None to listen from all senders. iface : string, optional Interface name to match on or None to match on all interfaces. signal : string, optional Signal name to match on or None to match on all signals. object : string, optional Object path to match on or None to match on all object paths. arg0 : string, optional Contents of first string argument to match on or None to match on all kinds of arguments. flags : SubscriptionFlags, optional signal_fired : callable, optional Invoked when there is a signal matching the requested data. Parameters: sender, object, iface, signal, params Returns ------- Subscription An object you can use as a context manager to unsubscribe from the signal later. See Also -------- See https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe for more information. ''' pass
2
1
38
5
3
30
2
5
1
1
1
1
1
0
1
1
42
6
6
5
4
30
6
5
4
2
1
0
2
144,499
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/_inspect3.py
pydbus._inspect3.Parameter
class Parameter: empty = _empty POSITIONAL_ONLY = 0 POSITIONAL_OR_KEYWORD = 1 KEYWORD_ONLY = 999 def __init__(self, name, kind, default=_empty, annotation=_empty): self.name = name self.kind = kind self.annotation = annotation
class Parameter: def __init__(self, name, kind, default=_empty, annotation=_empty): pass
2
0
4
0
4
0
1
0
0
1
1
0
1
3
1
1
11
2
9
9
7
0
9
9
7
1
0
0
1
144,500
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/tests/publish.py
tests.publish.TestObject
class TestObject(object): ''' <node> <interface name='net.lvht.Foo1'> <method name='HelloWorld'> <arg type='s' name='a' direction='in'/> <arg type='i' name='b' direction='in'/> <arg type='s' name='response' direction='out'/> </method> </interface> </node> ''' def __init__(self, id): self.id = id def HelloWorld(self, a, b): res = self.id + ": " + a + str(b) global done done += 1 if done == 2: loop.quit() print(res) return res
class TestObject(object): ''' <node> <interface name='net.lvht.Foo1'> <method name='HelloWorld'> <arg type='s' name='a' direction='in'/> <arg type='i' name='b' direction='in'/> <arg type='s' name='response' direction='out'/> </method> </interface> </node> ''' def __init__(self, id): pass def HelloWorld(self, a, b): pass
3
1
5
0
5
0
2
1
1
1
0
0
2
1
2
2
23
1
11
6
7
11
11
6
7
2
1
1
3
144,501
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/tests/publish_multiface.py
tests.publish_multiface.TestObject
class TestObject(object): ''' <node> <interface name='net.lew21.pydbus.tests.Iface1'> <method name='Method1'> <arg type='s' name='response' direction='out'/> </method> </interface> <interface name='net.lew21.pydbus.tests.Iface2'> <method name='Method2'> <arg type='s' name='response' direction='out'/> </method> </interface> </node> ''' def Method1(self): global done done += 1 if done == 2: loop.quit() return "M1" def Method2(self): global done done += 1 if done == 2: loop.quit() return "M2"
class TestObject(object): ''' <node> <interface name='net.lew21.pydbus.tests.Iface1'> <method name='Method1'> <arg type='s' name='response' direction='out'/> </method> </interface> <interface name='net.lew21.pydbus.tests.Iface2'> <method name='Method2'> <arg type='s' name='response' direction='out'/> </method> </interface> </node> ''' def Method1(self): pass def Method2(self): pass
3
1
6
0
6
0
2
1.08
1
0
0
0
2
0
2
2
28
1
13
5
8
14
13
5
8
2
1
1
4
144,502
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/tests/publish_properties.py
tests.publish_properties.TestObject
class TestObject(object): ''' <node> <interface name='net.lew21.pydbus.tests.publish_properties'> <property name="Foobar" type="s" access="readwrite"/> <property name="Foo" type="s" access="read"/> <property name="Bar" type="s" access="write"/> <method name='Quit'/> </interface> </node> ''' def __init__(self): self.Foo = "foo" self.Foobar = "foobar" def Quit(self): loop.quit()
class TestObject(object): ''' <node> <interface name='net.lew21.pydbus.tests.publish_properties'> <property name="Foobar" type="s" access="readwrite"/> <property name="Foo" type="s" access="read"/> <property name="Bar" type="s" access="write"/> <method name='Quit'/> </interface> </node> ''' def __init__(self): pass def Quit(self): pass
3
1
3
0
3
0
1
1.67
1
0
0
0
2
2
2
2
17
1
6
5
3
10
6
5
3
1
1
0
2
144,503
LEW21/pydbus
LEW21_pydbus/pydbus/_inspect3.py
pydbus._inspect3._empty
class _empty: pass
class _empty: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
144,504
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/examples/clientserver/server.py
examples.clientserver.server.MyDBUSService
class MyDBUSService(object): """ <node> <interface name='net.lew21.pydbus.ClientServerExample'> <method name='Hello'> <arg type='s' name='response' direction='out'/> </method> <method name='EchoString'> <arg type='s' name='a' direction='in'/> <arg type='s' name='response' direction='out'/> </method> <method name='Quit'/> </interface> </node> """ def Hello(self): """returns the string 'Hello, World!'""" return "Hello, World!" def EchoString(self, s): """returns whatever is passed to it""" return s def Quit(self): """removes this object from the DBUS connection and exits""" loop.quit()
class MyDBUSService(object): ''' <node> <interface name='net.lew21.pydbus.ClientServerExample'> <method name='Hello'> <arg type='s' name='response' direction='out'/> </method> <method name='EchoString'> <arg type='s' name='a' direction='in'/> <arg type='s' name='response' direction='out'/> </method> <method name='Quit'/> </interface> </node> ''' def Hello(self): '''returns the string 'Hello, World!'''' pass def EchoString(self, s): '''returns whatever is passed to it''' pass def Quit(self): '''removes this object from the DBUS connection and exits''' pass
4
4
3
0
2
1
1
2.43
1
0
0
0
3
0
3
3
27
3
7
4
3
17
7
4
3
1
1
0
3
144,505
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/examples/notifications_server.py
examples.notifications_server.Notifications
class Notifications(object): """ <node> <interface name="org.freedesktop.Notifications"> <signal name="NotificationClosed"> <arg direction="out" type="u" name="id"/> <arg direction="out" type="u" name="reason"/> </signal> <signal name="ActionInvoked"> <arg direction="out" type="u" name="id"/> <arg direction="out" type="s" name="action_key"/> </signal> <method name="Notify"> <arg direction="out" type="u"/> <arg direction="in" type="s" name="app_name"/> <arg direction="in" type="u" name="replaces_id"/> <arg direction="in" type="s" name="app_icon"/> <arg direction="in" type="s" name="summary"/> <arg direction="in" type="s" name="body"/> <arg direction="in" type="as" name="actions"/> <arg direction="in" type="a{sv}" name="hints"/> <arg direction="in" type="i" name="timeout"/> </method> <method name="CloseNotification"> <arg direction="in" type="u" name="id"/> </method> <method name="GetCapabilities"> <arg direction="out" type="as" name="caps"/> </method> <method name="GetServerInformation"> <arg direction="out" type="s" name="name"/> <arg direction="out" type="s" name="vendor"/> <arg direction="out" type="s" name="version"/> <arg direction="out" type="s" name="spec_version"/> </method> </interface> </node> """ NotificationClosed = signal() ActionInvoked = signal() def Notify(self, app_name, replaces_id, app_icon, summary, body, actions, hints, timeout): print("Notification: {} {} {} {} {} {} {} {}".format( app_name, replaces_id, app_icon, summary, body, actions, hints, timeout)) return 4 # chosen by fair dice roll. guaranteed to be random. def CloseNotification(self, id): pass def GetCapabilities(self): return [] def GetServerInformation(self): return ("pydbus.examples.notifications_server", "pydbus", "?", "1.1")
class Notifications(object): ''' <node> <interface name="org.freedesktop.Notifications"> <signal name="NotificationClosed"> <arg direction="out" type="u" name="id"/> <arg direction="out" type="u" name="reason"/> </signal> <signal name="ActionInvoked"> <arg direction="out" type="u" name="id"/> <arg direction="out" type="s" name="action_key"/> </signal> <method name="Notify"> <arg direction="out" type="u"/> <arg direction="in" type="s" name="app_name"/> <arg direction="in" type="u" name="replaces_id"/> <arg direction="in" type="s" name="app_icon"/> <arg direction="in" type="s" name="summary"/> <arg direction="in" type="s" name="body"/> <arg direction="in" type="as" name="actions"/> <arg direction="in" type="a{sv}" name="hints"/> <arg direction="in" type="i" name="timeout"/> </method> <method name="CloseNotification"> <arg direction="in" type="u" name="id"/> </method> <method name="GetCapabilities"> <arg direction="out" type="as" name="caps"/> </method> <method name="GetServerInformation"> <arg direction="out" type="s" name="name"/> <arg direction="out" type="s" name="vendor"/> <arg direction="out" type="s" name="version"/> <arg direction="out" type="s" name="spec_version"/> </method> </interface> </node> ''' def Notify(self, app_name, replaces_id, app_icon, summary, body, actions, hints, timeout): pass def CloseNotification(self, id): pass def GetCapabilities(self): pass def GetServerInformation(self): pass
5
1
2
0
2
0
1
3.17
1
0
0
0
4
0
4
4
54
5
12
7
7
38
12
7
7
1
1
0
4
144,506
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/request_name.py
pydbus.request_name.NameOwner
class NameOwner(ExitableWithAliases("unown")): __slots__ = () def __init__(self, bus, name, allow_replacement, replace): flags = 4 | (1 if allow_replacement else 0) | (2 if replace else 0) res = bus.dbus.RequestName(name, flags) if res == 1: self._at_exit(lambda: bus.dbus.ReleaseName(name)) return # OK if res == 3: raise RuntimeError("name already exists on the bus") if res == 4: raise RuntimeError("you're already the owner of this name") raise RuntimeError("cannot take ownership of the name")
class NameOwner(ExitableWithAliases("unown")): def __init__(self, bus, name, allow_replacement, replace): pass
2
0
11
0
11
1
6
0.08
1
1
0
0
1
0
1
2
14
1
13
5
11
1
13
5
11
6
1
1
6
144,507
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy_signal.py
pydbus.proxy_signal.OnSignal
class OnSignal(object): def __init__(self, signal): self.signal = signal self.__name__ = "on" + signal.__name__ self.__qualname__ = signal._iface_name + "." + self.__name__ self.__doc__ = "Assign a callback to subscribe to the signal. Assign None to unsubscribe. Callback: (" + ", ".join( signal._args) + ")" def __get__(self, instance, owner): if instance is None: return self try: return getattr(instance, "_on" + self.signal.__name__) except AttributeError: return None def __set__(self, instance, value): if instance is None: raise AttributeError("can't set attribute") try: old = getattr(instance, "_sub" + self.signal.__name__) old.unsubscribe() except AttributeError: pass if value is None: delattr(instance, "_on" + self.signal.__name__) delattr(instance, "_sub" + self.signal.__name__) return sub = self.signal.connect(instance, value) setattr(instance, "_on" + self.signal.__name__, value) setattr(instance, "_sub" + self.signal.__name__, sub) def __repr__(self): return "<descriptor " + self.__qualname__ + " at 0x" + format(id(self), "x") + ">"
class OnSignal(object): def __init__(self, signal): pass def __get__(self, instance, owner): pass def __set__(self, instance, value): pass def __repr__(self): pass
5
0
8
1
7
0
2
0
1
1
0
0
4
4
4
4
37
7
30
11
25
0
30
11
25
4
1
1
9
144,508
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/bus.py
pydbus.bus.Bus
class Bus(ProxyMixin, RequestNameMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin): Type = Gio.BusType def __init__(self, gio_con): self.con = gio_con self.autoclose = False def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if self.autoclose: self.con.close_sync(None) @property def dbus(self): try: return self._dbus except AttributeError: self._dbus = self.get(".DBus")[""] return self._dbus @property def polkit_authority(self): try: return self._polkit_authority except AttributeError: self._polkit_authority = self.get(".PolicyKit1", "Authority")[""] return self._polkit_authority
class Bus(ProxyMixin, RequestNameMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin): def __init__(self, gio_con): pass def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): pass @property def dbus(self): pass @property def polkit_authority(self): pass
8
0
4
0
4
0
2
0
7
1
0
0
5
4
5
12
29
5
24
13
16
0
22
11
16
2
2
1
8
144,509
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/exitable.py
pydbus.exitable.ExitableWithAliases.CustomExitable
class CustomExitable(Exitable): pass
class CustomExitable(Exitable): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
4
2
0
2
1
1
0
2
1
1
0
2
0
0
144,510
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/generic.py
pydbus.generic.bound_signal
class bound_signal(object): # bound method uses ("__func__", "__self__") __slots__ = ("__signal__", "__self__") def __init__(self, signal, instance): self.__signal__ = signal self.__self__ = instance @property def callbacks(self): return self.__signal__.map[self.__self__] def connect(self, callback): """Subscribe to the signal.""" return self.__signal__.connect(self.__self__, callback) def emit(self, *args): """Emit the signal.""" self.__signal__.emit(self.__self__, *args) def __call__(self, *args): """Emit the signal.""" self.emit(*args) def __repr__(self): return "<bound signal " + self.__signal__.__qualname__ + " of " + repr(self.__self__) + ">"
class bound_signal(object): def __init__(self, signal, instance): pass @property def callbacks(self): pass def connect(self, callback): '''Subscribe to the signal.''' pass def emit(self, *args): '''Emit the signal.''' pass def __call__(self, *args): '''Emit the signal.''' pass def __repr__(self): pass
8
3
3
0
2
1
1
0.25
1
0
0
0
6
2
6
6
25
6
16
11
8
4
15
10
8
1
1
0
6
144,511
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/generic.py
pydbus.generic.signal
class signal(object): """Static signal object You're expected to set it as a class property:: class A: SomethingHappened = signal() Declared this way, it can be used on class instances to connect signal observers:: a = A() a.SomethingHappened.connect(func) and emit the signal:: a.SomethingHappened() You may pass any parameters to the emiting function - they will be forwarded to all subscribed callbacks. """ def __init__(self): self.map = {} self.__qualname__ = "<anonymous signal>" # function uses <lambda> ;) self.__doc__ = "Signal." def connect(self, object, callback): """Subscribe to the signal.""" return subscription(self.map.setdefault(object, []), callback) def emit(self, object, *args): """Emit the signal.""" for cb in self.map.get(object, []): cb(*args) def __get__(self, instance, owner): if instance is None: return self return bound_signal(self, instance) def __set__(self, instance, value): raise AttributeError("can't set attribute") def __repr__(self): return "<signal " + self.__qualname__ + " at 0x" + format(id(self), "x") + ">"
class signal(object): '''Static signal object You're expected to set it as a class property:: class A: SomethingHappened = signal() Declared this way, it can be used on class instances to connect signal observers:: a = A() a.SomethingHappened.connect(func) and emit the signal:: a.SomethingHappened() You may pass any parameters to the emiting function - they will be forwarded to all subscribed callbacks. ''' def __init__(self): pass def connect(self, object, callback): '''Subscribe to the signal.''' pass def emit(self, object, *args): '''Emit the signal.''' pass def __get__(self, instance, owner): pass def __set__(self, instance, value): pass def __repr__(self): pass
7
3
3
0
3
1
1
0.89
1
3
2
0
6
3
6
6
47
14
18
11
11
16
18
11
11
2
1
1
8
144,512
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/generic.py
pydbus.generic.subscription
class subscription(object): __slots__ = ("callback_list", "callback") def __init__(self, callback_list, callback): self.callback_list = callback_list self.callback = callback self.callback_list.append(callback) def unsubscribe(self): self.callback_list.remove(self.callback) self.callback_list = None self.callback = None def disconnect(self): """An alias for unsubscribe()""" self.unsubscribe() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if not self.callback is None: self.unsubscribe()
class subscription(object): def __init__(self, callback_list, callback): pass def unsubscribe(self): pass def disconnect(self): '''An alias for unsubscribe()''' pass def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): pass
6
1
3
0
3
0
1
0.06
1
0
0
0
5
2
5
5
23
5
17
9
11
1
17
9
11
2
1
1
6
144,513
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/method_call_context.py
pydbus.method_call_context.MethodCallContext
class MethodCallContext(object): def __init__(self, gdbus_method_invocation): self._mi = gdbus_method_invocation @property def bus(self): return self._mi.get_connection().pydbus @property def sender(self): return self._mi.get_sender() @property def object_path(self): return self._mi.get_object_path() @property def interface_name(self): return self._mi.get_interface_name() @property def method_name(self): return self._mi.get_method_name() def check_authorization(self, action_id, details, interactive=False): return AuthorizationResult(*self.bus.polkit_authority.CheckAuthorization(('system-bus-name', {'name': GLib.Variant("s", self.sender)}), action_id, details, 1 if interactive else 0, '')) def is_authorized(self, action_id, details, interactive=False): return self.check_authorization(action_id, details, interactive).is_authorized
class MethodCallContext(object): def __init__(self, gdbus_method_invocation): pass @property def bus(self): pass @property def sender(self): pass @property def object_path(self): pass @property def interface_name(self): pass @property def method_name(self): pass def check_authorization(self, action_id, details, interactive=False): pass def is_authorized(self, action_id, details, interactive=False): pass
14
0
2
0
2
0
1
0
1
0
0
0
8
1
8
8
29
7
22
15
8
0
17
10
8
2
1
0
9
144,514
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/bus_names.py
pydbus.bus_names.WatchMixin
class WatchMixin(object): __slots__ = () NameWatcherFlags = NameWatcher.Flags def watch_name(self, name, flags=0, name_appeared=None, name_vanished=None): """Asynchronously watches a bus name. Starts watching name on the bus specified by bus_type and calls name_appeared and name_vanished when the name is known to have a owner respectively known to lose its owner. To receive name_appeared and name_vanished callbacks, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters ---------- name : string Bus name to watch flags : NameWatcherFlags, optional name_appeared : callable, optional Invoked when name is known to exist Called as name_appeared(name_owner). name_vanished : callable, optional Invoked when name is known to not exist Returns ------- NameWatcher An object you can use as a context manager to unwatch the name later. See Also -------- See https://developer.gnome.org/gio/2.44/gio-Watching-Bus-Names.html#g-bus-watch-name for more information. """ name_appeared_handler = (lambda con, name, name_owner: name_appeared( name_owner)) if name_appeared is not None else None name_vanished_handler = (lambda con, name: name_vanished( )) if name_vanished is not None else None return NameWatcher(self.con, name, flags, name_appeared_handler, name_vanished_handler)
class WatchMixin(object): def watch_name(self, name, flags=0, name_appeared=None, name_vanished=None): '''Asynchronously watches a bus name. Starts watching name on the bus specified by bus_type and calls name_appeared and name_vanished when the name is known to have a owner respectively known to lose its owner. To receive name_appeared and name_vanished callbacks, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters ---------- name : string Bus name to watch flags : NameWatcherFlags, optional name_appeared : callable, optional Invoked when name is known to exist Called as name_appeared(name_owner). name_vanished : callable, optional Invoked when name is known to not exist Returns ------- NameWatcher An object you can use as a context manager to unwatch the name later. See Also -------- See https://developer.gnome.org/gio/2.44/gio-Watching-Bus-Names.html#g-bus-watch-name for more information. ''' pass
2
1
34
5
4
25
3
3.57
1
1
1
1
1
0
1
1
38
6
7
6
5
25
7
6
5
3
1
0
3
144,515
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/bus_names.py
pydbus.bus_names.OwnMixin
class OwnMixin(object): __slots__ = () NameOwnerFlags = NameOwner.Flags def own_name(self, name, flags=0, name_aquired=None, name_lost=None): """[DEPRECATED] Asynchronously aquires a bus name. Starts acquiring name on the bus specified by bus_type and calls name_acquired and name_lost when the name is acquired respectively lost. To receive name_aquired and name_lost callbacks, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters ---------- name : string Bus name to aquire flags : NameOwnerFlags, optional name_aquired : callable, optional Invoked when name is acquired name_lost : callable, optional Invoked when name is lost Returns ------- NameOwner An object you can use as a context manager to unown the name later. See Also -------- See https://developer.gnome.org/gio/2.44/gio-Owning-Bus-Names.html#g-bus-own-name for more information. """ warnings.warn( "own_name() is deprecated, use request_name() instead.", DeprecationWarning) name_aquired_handler = ( lambda con, name: name_aquired()) if name_aquired is not None else None name_lost_handler = (lambda con, name: name_lost() ) if name_lost is not None else None return NameOwner(self.con, name, flags, name_aquired_handler, name_lost_handler)
class OwnMixin(object): def own_name(self, name, flags=0, name_aquired=None, name_lost=None): '''[DEPRECATED] Asynchronously aquires a bus name. Starts acquiring name on the bus specified by bus_type and calls name_acquired and name_lost when the name is acquired respectively lost. To receive name_aquired and name_lost callbacks, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters ---------- name : string Bus name to aquire flags : NameOwnerFlags, optional name_aquired : callable, optional Invoked when name is acquired name_lost : callable, optional Invoked when name is lost Returns ------- NameOwner An object you can use as a context manager to unown the name later. See Also -------- See https://developer.gnome.org/gio/2.44/gio-Owning-Bus-Names.html#g-bus-own-name for more information. ''' pass
2
1
34
6
5
23
3
2.88
1
2
1
1
1
0
1
1
38
7
8
6
6
23
8
6
6
3
1
0
3
144,516
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy_property.py
pydbus.proxy_property.ProxyProperty
class ProxyProperty(object): def __init__(self, iface_name, property): self._iface_name = iface_name self.__name__ = property.attrib["name"] self.__qualname__ = self._iface_name + "." + self.__name__ self._type = property.attrib["type"] access = property.attrib["access"] self._readable = access.startswith("read") self._writeable = access.endswith("write") self.__doc__ = "(" + self._type + ") " + access def __get__(self, instance, owner): if instance is None: return self if not self._readable: raise AttributeError("unreadable attribute") return instance._object["org.freedesktop.DBus.Properties"].Get(self._iface_name, self.__name__) def __set__(self, instance, value): if instance is None or not self._writeable: raise AttributeError("can't set attribute") instance._object["org.freedesktop.DBus.Properties"].Set( self._iface_name, self.__name__, GLib.Variant(self._type, value)) def __repr__(self): return "<property " + self.__qualname__ + " at 0x" + format(id(self), "x") + ">"
class ProxyProperty(object): def __init__(self, iface_name, property): pass def __get__(self, instance, owner): pass def __set__(self, instance, value): pass def __repr__(self): pass
5
0
6
1
5
0
2
0
1
1
0
0
4
7
4
4
29
7
22
13
17
0
22
13
17
3
1
1
7
144,517
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy.py
pydbus.proxy.CompositeInterface.CompositeObject
class CompositeObject(ProxyObject): def __getitem__(self, iface): if iface == "" or iface[0] == ".": iface = self._path.replace("/", ".")[1:] + iface matching_bases = [base for base in type( self).__bases__ if base.__name__ == iface] if len(matching_bases) == 0: raise KeyError(iface) assert (len(matching_bases) == 1) iface_class = matching_bases[0] return iface_class(self._bus, self._bus_name, self._path, self) @classmethod def _Introspect(cls): for iface in cls.__bases__: try: iface._Introspect() except: pass
class CompositeObject(ProxyObject): def __getitem__(self, iface): pass @classmethod def _Introspect(cls): pass
4
0
9
1
8
0
3
0
1
2
0
0
1
0
2
3
20
3
17
7
13
0
16
6
13
3
2
2
6
144,518
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy.py
pydbus.proxy.Interface.interface
class interface(ProxyObject): @staticmethod def _Introspect(): print(iface.attrib["name"] + ":") for member in iface: print("\t" + member.tag + " " + member.attrib["name"]) print()
class interface(ProxyObject): @staticmethod def _Introspect(): pass
3
0
5
0
5
0
2
0
1
0
0
0
0
0
1
2
7
0
7
4
4
0
6
3
4
2
2
1
2
144,519
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/bus_names.py
pydbus.bus_names.NameWatcher
class NameWatcher(ExitableWithAliases("unwatch")): Flags = Gio.BusNameWatcherFlags __slots__ = () def __init__(self, con, name, flags, name_appeared_handler, name_vanished_handler): id = Gio.bus_watch_name_on_connection( con, name, flags, name_appeared_handler, name_vanished_handler) self._at_exit(lambda: Gio.bus_unwatch_name(id))
class NameWatcher(ExitableWithAliases("unwatch")): def __init__(self, con, name, flags, name_appeared_handler, name_vanished_handler): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
0
1
2
7
1
6
4
4
0
6
4
4
1
1
0
1
144,520
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy.py
pydbus.proxy.ProxyMixin
class ProxyMixin(object): __slots__ = () def get(self, bus_name, object_path=None, **kwargs): """Get a remote object. Parameters ---------- bus_name : string Name of the service that exposes this object. You may start with "." - then org.freedesktop will be automatically prepended. object_path : string, optional Path of the object. If not provided, bus_name translated to path format is used. Returns ------- ProxyObject implementing all the Interfaces exposed by the remote object. Note that it inherits from multiple Interfaces, so the method you want to use may be shadowed by another one, eg. from a newer version of the interface. Therefore, to interact with only a single interface, use: >>> bus.get("org.freedesktop.systemd1")["org.freedesktop.systemd1.Manager"] or simply >>> bus.get(".systemd1")[".Manager"] which will give you access to the one specific interface. """ # Python 2 sux for kwarg in kwargs: if kwarg not in ("timeout",): raise TypeError( self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg)) timeout = kwargs.get("timeout", None) bus_name = auto_bus_name(bus_name) object_path = auto_object_path(bus_name, object_path) ret = self.con.call_sync( bus_name, object_path, 'org.freedesktop.DBus.Introspectable', "Introspect", None, GLib.VariantType.new( "(s)"), 0, timeout_to_glib(timeout), None) if not ret: raise KeyError( "no such object; you might need to pass object path as the 2nd argument for get()") xml, = ret.unpack() try: introspection = ET.fromstring(xml) except: raise KeyError("object provides invalid introspection XML") return CompositeInterface(introspection)(self, bus_name, object_path)
class ProxyMixin(object): def get(self, bus_name, object_path=None, **kwargs): '''Get a remote object. Parameters ---------- bus_name : string Name of the service that exposes this object. You may start with "." - then org.freedesktop will be automatically prepended. object_path : string, optional Path of the object. If not provided, bus_name translated to path format is used. Returns ------- ProxyObject implementing all the Interfaces exposed by the remote object. Note that it inherits from multiple Interfaces, so the method you want to use may be shadowed by another one, eg. from a newer version of the interface. Therefore, to interact with only a single interface, use: >>> bus.get("org.freedesktop.systemd1")["org.freedesktop.systemd1.Manager"] or simply >>> bus.get(".systemd1")[".Manager"] which will give you access to the one specific interface. ''' pass
2
1
47
8
19
20
5
0.95
1
2
0
1
1
0
1
1
50
9
21
8
19
20
18
8
16
5
1
2
5
144,521
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy.py
pydbus.proxy.ProxyObject
class ProxyObject(object): def __init__(self, bus, bus_name, path, object=None): self._bus = bus self._bus_name = bus_name self._path = path self._object = object if object else self
class ProxyObject(object): def __init__(self, bus, bus_name, path, object=None): pass
2
0
5
0
5
0
2
0
1
0
0
2
1
4
1
1
6
0
6
6
4
0
6
6
4
2
1
0
2
144,522
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy_method.py
pydbus.proxy_method.DBUSSignature
class DBUSSignature(Signature): def __str__(self): result = [] for param in self.parameters.values(): p = param.name if not param.name.startswith("arg") else "" if type(param.annotation) == str: p += ":" + param.annotation result.append(p) rendered = '({})'.format(', '.join(result)) if self.return_annotation is not Signature.empty: rendered += ' -> {}'.format(self.return_annotation) return rendered
class DBUSSignature(Signature): def __str__(self): pass
2
0
14
3
11
0
5
0
1
2
0
0
1
0
1
16
16
4
12
6
10
0
12
6
10
5
1
2
5
144,523
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/proxy_method.py
pydbus.proxy_method.ProxyMethod
class ProxyMethod(object): def __init__(self, iface_name, method): self._iface_name = iface_name self.__name__ = method.attrib["name"] self.__qualname__ = self._iface_name + "." + self.__name__ self._inargs = [(arg.attrib.get("name", ""), arg.attrib["type"]) for arg in method if arg.tag == "arg" and arg.attrib.get("direction", "in") == "in"] self._outargs = [arg.attrib["type"] for arg in method if arg.tag == "arg" and arg.attrib.get("direction", "in") == "out"] self._sinargs = "(" + "".join(x[1] for x in self._inargs) + ")" self._soutargs = "(" + "".join(self._outargs) + ")" self_param = Parameter("self", Parameter.POSITIONAL_ONLY) pos_params = [] for i, a in enumerate(self._inargs): name = filter_identifier(a[0]) if not name: name = "arg" + str(i) param = Parameter(name, Parameter.POSITIONAL_ONLY, annotation=a[1]) pos_params.append(param) ret_type = Signature.empty if len(self._outargs) == 0 else self._outargs[0] if len( self._outargs) == 1 else "(" + ", ".join(self._outargs) + ")" self.__signature__ = DBUSSignature( [self_param] + pos_params, return_annotation=ret_type) if put_signature_in_doc: self.__doc__ = self.__name__ + str(self.__signature__) def __call__(self, instance, *args, **kwargs): argdiff = len(args) - len(self._inargs) if argdiff < 0: raise TypeError( self.__qualname__ + " missing {} required positional argument(s)".format(-argdiff)) elif argdiff > 0: raise TypeError( self.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(self._inargs), len(args))) # Python 2 sux for kwarg in kwargs: if kwarg not in ("timeout",): raise TypeError( self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg)) timeout = kwargs.get("timeout", None) ret = instance._bus.con.call_sync( instance._bus_name, instance._path, self._iface_name, self.__name__, GLib.Variant( self._sinargs, args), GLib.VariantType.new(self._soutargs), 0, timeout_to_glib(timeout), None).unpack() if len(self._outargs) == 0: return None elif len(self._outargs) == 1: return ret[0] else: return ret def __get__(self, instance, owner): if instance is None: return self return bound_method(self, instance) def __repr__(self): return "<function " + self.__qualname__ + " at 0x" + format(id(self), "x") + ">"
class ProxyMethod(object): def __init__(self, iface_name, method): pass def __call__(self, instance, *args, **kwargs): pass def __get__(self, instance, owner): pass def __repr__(self): pass
5
0
15
3
12
0
4
0.02
1
6
1
0
4
9
4
4
62
14
47
24
42
1
41
24
36
7
1
2
16
144,524
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/bus_names.py
pydbus.bus_names.NameOwner
class NameOwner(ExitableWithAliases("unown")): Flags = Gio.BusNameOwnerFlags __slots__ = () def __init__(self, con, name, flags, name_aquired_handler, name_lost_handler): id = Gio.bus_own_name_on_connection( con, name, flags, name_aquired_handler, name_lost_handler) self._at_exit(lambda: Gio.bus_unown_name(id))
class NameOwner(ExitableWithAliases("unown")): def __init__(self, con, name, flags, name_aquired_handler, name_lost_handler): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
0
1
2
7
1
6
4
4
0
6
4
4
1
1
0
1
144,525
LEW21/pydbus
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LEW21_pydbus/pydbus/exitable.py
pydbus.exitable.Exitable
class Exitable(object): __slots__ = ("_at_exit_cbs") def _at_exit(self, cb): try: self._at_exit_cbs except AttributeError: self._at_exit_cbs = [] self._at_exit_cbs.append(cb) def __enter__(self): return self def __exit__(self, exc_type=None, exc_value=None, traceback=None): if self._exited: return for cb in reversed(self._at_exit_cbs): call_with_exc = True try: inspect.getcallargs(cb, exc_type, exc_value, traceback) except TypeError: call_with_exc = False if call_with_exc: cb(exc_type, exc_value, traceback) else: cb() self._at_exit_cbs = None @property def _exited(self): try: return self._at_exit_cbs is None except AttributeError: return True
class Exitable(object): def _at_exit(self, cb): pass def __enter__(self): pass def __exit__(self, exc_type=None, exc_value=None, traceback=None): pass @property def _exited(self): pass
6
0
8
1
7
0
3
0
1
3
0
1
4
1
4
4
38
8
30
10
24
0
28
9
23
5
1
2
10
144,526
LFenske/python-scsi-pt
LFenske_python-scsi-pt/CDB.py
CDB.CDB
class CDB(object): """ Manage the data structure that holds a passthrough request. """ def __init__(self, cdb, rs_size=24): # Construct CDB object for a passthrough request. super(CDB, self).__init__() self.objp = ScsiPT.sg.construct_scsi_pt_obj() if self.objp == None: raise Exception() # Add CDB to the object. self.cdb = ctypes.create_string_buffer(str(bytearray(cdb)), len(cdb)) ScsiPT.sg.set_scsi_pt_cdb(self.objp, self.cdb, len(self.cdb)) # Add Request Sense buffer to object. self.sense = ctypes.create_string_buffer(rs_size) ScsiPT.sg.set_scsi_pt_sense(self.objp, self.sense, len(self.sense)) def __del__(self): # Destruct the object, if it exists. if self.objp != None: ScsiPT.sg.destruct_scsi_pt_obj(self.objp) self.objp = None #super(CDB, self).__del__() def set_data_out(self, buf): self.buf = ctypes.create_string_buffer(str(bytearray(buf)), len(buf)) retval = ScsiPT.sg.set_scsi_pt_data_out( self.objp, self.buf, len(self.buf)) if retval < 0: raise Exception(retval) def set_data_in(self, buflen): self.buf = ctypes.create_string_buffer(buflen) retval = ScsiPT.sg.set_scsi_pt_data_in( self.objp, self.buf, len(self.buf)) if retval < 0: raise Exception(retval)
class CDB(object): ''' Manage the data structure that holds a passthrough request. ''' def __init__(self, cdb, rs_size=24): pass def __del__(self): pass def set_data_out(self, buf): pass def set_data_in(self, buflen): pass
5
1
8
0
7
1
2
0.27
1
5
1
0
4
4
4
4
42
4
30
11
25
8
24
11
19
2
1
1
8
144,527
LFenske/python-scsi-pt
LFenske_python-scsi-pt/ScsiPT.py
ScsiPT.ScsiPT
class ScsiPT(object): """ static linkages to sgutils functions """ sg = ctypes.CDLL("libsgutils2.so.2") sg.scsi_pt_version .restype = ctypes.c_char_p sg.scsi_pt_version .argtypes = [] sg.scsi_pt_open_device .restype = ctypes.c_int sg.scsi_pt_open_device .argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int] sg.scsi_pt_open_flags .restype = ctypes.c_int sg.scsi_pt_open_flags .argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int] sg.scsi_pt_close_device .restype = ctypes.c_int sg.scsi_pt_close_device .argtypes = [ctypes.c_int] sg.construct_scsi_pt_obj .restype = ctypes.c_void_p sg.construct_scsi_pt_obj .argtypes = [] sg.clear_scsi_pt_obj .restype = ctypes.c_int # void sg.clear_scsi_pt_obj .argtypes = [ctypes.c_void_p] sg.set_scsi_pt_cdb .restype = ctypes.c_int # void sg.set_scsi_pt_cdb .argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] sg.set_scsi_pt_sense .restype = ctypes.c_int # void sg.set_scsi_pt_sense .argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] sg.set_scsi_pt_data_in .restype = ctypes.c_int # void sg.set_scsi_pt_data_in .argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] sg.set_scsi_pt_data_out .restype = ctypes.c_int # void sg.set_scsi_pt_data_out .argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] sg.set_scsi_pt_packet_id .restype = ctypes.c_int # void sg.set_scsi_pt_packet_id .argtypes = [ctypes.c_void_p, ctypes.c_int] sg.set_scsi_pt_tag .restype = ctypes.c_int # void sg.set_scsi_pt_tag .argtypes = [ctypes.c_void_p, ctypes.c_ulong] sg.set_scsi_pt_task_management .restype = ctypes.c_int # void sg.set_scsi_pt_task_management .argtypes = [ctypes.c_void_p, ctypes.c_int] sg.set_scsi_pt_task_attr .restype = ctypes.c_int # void sg.set_scsi_pt_task_attr .argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] sg.set_scsi_pt_flags .restype = ctypes.c_int # void sg.set_scsi_pt_flags .argtypes = [ctypes.c_void_p, ctypes.c_int] sg.do_scsi_pt .restype = ctypes.c_int sg.do_scsi_pt .argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int] sg.get_scsi_pt_result_category .restype = ctypes.c_int sg.get_scsi_pt_result_category .argtypes = [ctypes.c_void_p] sg.get_scsi_pt_resid .restype = ctypes.c_int sg.get_scsi_pt_resid .argtypes = [ctypes.c_void_p] sg.get_scsi_pt_status_response .restype = ctypes.c_int sg.get_scsi_pt_status_response .argtypes = [ctypes.c_void_p] sg.get_scsi_pt_sense_len .restype = ctypes.c_int sg.get_scsi_pt_sense_len .argtypes = [ctypes.c_void_p] sg.get_scsi_pt_os_err .restype = ctypes.c_int sg.get_scsi_pt_os_err .argtypes = [ctypes.c_void_p] sg.get_scsi_pt_os_err_str .restype = ctypes.c_char_p sg.get_scsi_pt_os_err_str .argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] sg.get_scsi_pt_transport_err .restype = ctypes.c_int sg.get_scsi_pt_transport_err .argtypes = [ctypes.c_void_p] sg.get_scsi_pt_transport_err_str.restype = ctypes.c_char_p sg.get_scsi_pt_transport_err_str.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] sg.get_scsi_pt_duration_ms .restype = ctypes.c_int sg.get_scsi_pt_duration_ms .argtypes = [ctypes.c_void_p] sg.destruct_scsi_pt_obj .restype = ctypes.c_int # void sg.destruct_scsi_pt_obj .argtypes = [ctypes.c_void_p] def __init__(self, filename): super(ScsiPT, self).__init__() self.file = self.sg.scsi_pt_open_device(filename, 0, 0) if self.file < 0: raise Exception(self.file) def __del__(self): try: self.sg.scsi_pt_close_device(self.file) finally: pass #super(ScsiPT, self).__del__() # doesn't exist in superclass, object def sendcdb(self, cdb): return self.sg.do_scsi_pt(cdb.objp, self.file, 20, 1)
class ScsiPT(object): ''' static linkages to sgutils functions ''' def __init__(self, filename): pass def __del__(self): pass def sendcdb(self, cdb): pass
4
1
4
0
4
0
1
0.16
1
2
0
0
3
1
3
3
126
31
91
6
87
15
65
6
61
2
1
1
4
144,528
LFenske/python-scsi-pt
LFenske_python-scsi-pt/Cmd.py
Cmd.Cmd
class Cmd(object): """ Manage creating objects of type CDB and filling in parameters. """ abbrevs = \ { # commands "tur" : "test_unit_ready", "inq" : "inquiry", "wb" : "write_buffer", "sd" : "send_diagnostic", "rdr" : "receive_diagnostic_results", "rl" : "report_luns", # fields "alloc": "allocation_length", } # indices into cdbdefs values xCDBNUM = 0 xLEN = 1 xDIR = 2 xFLDS = 3 # directions (xDIR) NONE = "NONE" OUT = "OUT" IN = "IN" # definitions of CDBs cdbdefs = \ { "test_unit_ready": (0x00, 6, NONE, {}), "inquiry" : (0x12, 6, IN, { "evpd" :((1,0),1,0), "page_code" :( 2, 8,0), "allocation_length":( 3, 16,5), }), "write_buffer" : (0x3b,10, OUT, { "mode_specific" :((1,7),3,0), "mode" :((1,4),5,0), "buffer_id" :( 2, 8,0), "buffer_offset" :( 3, 24,0), "parameter_list_length":( 6, 24,0), }), "send_diagnostic": (0x1d, 6, OUT, { "self-test_code" :((1,7),3,0), "pf" :((1,4),1,0), "selftest" :((1,2),1,0), "devoffl" :((1,1),1,0), "unitoffl" :((1,0),1,0), "parameter_list_length":( 3, 16,0), }), "receive_diagnostic_results": (0x1c, 6, IN, { "pcv" :((1,0),1,0), "page_code" :( 2, 8,0), "allocation_length":( 3, 16,5), }), "report_luns" : (0xa0,12, IN, { "select_report" :( 2 , 1*8, 2), "allocation_length":( 6 , 4*8, 8), }) } data_inquiry = \ ( (( 0,7), 3, "int", "qual", "peripheral qualifier" ), (( 0,4), 5, "int", "type", "peripheral device type" ), (( 1,0), 1, "int", None , "rmb" ), ( 2, 8, "int", None , "version" ), (( 3,5), 1, "int", None , "normaca" ), (( 3,4), 1, "int", None , "hisup" ), (( 3,3), 4, "int", None , "response data format" ), ( 4, 8, "int", None , "additional length" ), (( 5,7), 1, "int", None , "sccs" ), (( 5,6), 1, "int", None , "acc" ), (( 5,5), 2, "int", None , "tpgs" ), (( 5,3), 1, "int", None , "3pc" ), (( 5,0), 1, "int", None , "protect" ), (( 6,6), 1, "int", None , "encserv" ), (( 6,5), 1, "int", None , "vs" ), (( 6,4), 1, "int", None , "multip" ), (( 6,3), 1, "int", None , "mchngr" ), (( 6,0), 1, "int", None , "addr16" ), (( 7,5), 1, "int", None , "wbus16" ), (( 7,4), 1, "int", None , "sync" ), (( 7,1), 1, "int", None , "cmdque" ), (( 7,0), 1, "int", None , "vs" ), ( 8, 64, "str", "vid" , "t10 vendor identification"), ( 16, 128, "str", "pid" , "product identification" ), ( 32, 32, "str", "rev" , "product revision level" ), ( 36, 64, "str", "sn" , "drive serial number" ), ( 44, 96, "str", None , "vendor unique" ), ((56,3), 2, "int", None , "clocking" ), ((56,1), 1, "int", None , "qas" ), ((56,0), 1, "int", None , "ius" ), ( 58, 16, "int", None , "version descriptor 1" ), ( 60, 16, "int", None , "version descriptor 2" ), ( 62, 16, "int", None , "version descriptor 3" ), ( 64, 16, "int", None , "version descriptor 4" ), ( 66, 16, "int", None , "version descriptor 5" ), ( 68, 16, "int", None , "version descriptor 6" ), ( 70, 16, "int", None , "version descriptor 7" ), ( 72, 16, "int", None , "version descriptor 8" ), ) data_request_sense_fixed = \ ( (( 0,7), 1, "int", "valid", "valid"), (( 0,6), 6, "int", "code", "response code"), (( 2,7), 1, "int", "filemark", "filemark"), (( 2,6), 1, "int", "eom", "eom"), (( 2,5), 1, "int", "ili", "ili"), (( 2,4), 1, "int", "sdat_ovfl", "sdat_ovfl"), (( 2,3), 4, "int", "key", "sense key"), ( 3, 4*8, "int", "information", "information"), ( 7, 1*8, "int", "length", "additional sense length"), ( 8, 4*8, "int", "specific", "command-specific information"), ( 12, 1*8, "int", "asc", "additional sense code"), ( 13, 1*8, "int", "ascq", "additional sense code qualifier"), ( 14, 1*8, "int", "fru", "field replaceable unit code"), ((15,7), 1, "int", "sksv", "sksv"), ((15,6),23, "int", "sks", "sense key specific information"), ( 18, 0, "str", "more", "additional sense bytes"), ) peripheral_device_type = \ { 0x00: "Direct access block device", 0x01: "Sequential-access device", 0x02: "Printer device", 0x03: "Processor device", 0x04: "Write-once device", 0x05: "CD/DVD device", 0x06: "Scanner device", 0x07: "Optical memory device", 0x08: "Medium changer device", 0x09: "Communications device", 0x0c: "Storage array controller device", 0x0d: "Enclosure services device", 0x0e: "Simplified direct-access device", 0x0f: "Optical card reader/writer device", 0x10: "Bridge Controller Commands", 0x11: "Object-based Storage Device", 0x12: "Automation/Drive Interface", 0x1e: "Well known logical unit", 0x1f: "Unknown or no device type", } send_diagnostic_self_test_code = \ { 0: "", 1: "Background short self-test", 2: "Background extended self-test", 3: "Reserved", 4: "Abort background self-test", 5: "Foreground short self-test", 6: "Foreground extended self-test", 7: "Reserved", } def __init__(self, cdbname, params={}): super(Cmd, self).__init__() # Replace a possible abbreviation. if cdbname in self.abbrevs: cdbname = self.abbrevs[cdbname] # Ensure we know this command. if cdbname not in self.cdbdefs: raise Exception("bad CDB name") d = self.cdbdefs[cdbname] # shorthand # Create initial CDB as all 0's. self.cdb = [0] * d[self.xLEN] # Fill in all the fields. opdef = {"opcode":(0,8,0)} opdef.update(d[self.xFLDS]) opprm = {"opcode":d[self.xCDBNUM]} opprm.update( {(self.abbrevs[k] if k in self.abbrevs else k):v for (k,v) in params.items()}) Cmd.fill(self.cdb, opdef, opprm) @staticmethod def fill(cdb, defs, pparms): """ Take field values in parms and insert them into cdb based on the field definitions in defs. """ #print "defs =", defs parms = {n:v[2] for (n,v) in defs.items()} # Create parms for default field values. parms.update(pparms) # Insert real parameters. for (name, value) in parms.items(): if name not in defs: raise Exception("unknown field: "+name) width = defs[name][1] start = defs[name][0] if type(start) == type(0): # must be either number or list of 2 start = (start,7) # TODO Check type of start. if type(value) == type("str"): if len(value) > width/8: raise Exception("value too large for field: "+name) if start[1] != 7: raise Exception("string must start in bit 7: "+name) value += " " * (width/8 - len(value)) # Fill with blanks. cdb[start[0]:start[0]+len(value)] = value else: if value >= 1<<width: raise Exception("value too large for field: "+name) startbitnum = start[0]*8 + (7-start[1]) # Number bits l-to-r. bitnum = startbitnum + defs[name][1] - 1 # TODO Is value inserted backwards? while width > 0: if bitnum % 8 == 7 and width >= 8: bitlen= 8 cdb[bitnum//8] = value & 0xff; else: startofbyte = bitnum // 8 * 8 # Find first bit num in byte. firstbit = max(startofbyte, bitnum-width+1) bitlen= bitnum-firstbit+1 shift = (7 - bitnum%8) vmask = (1 << bitlen) - 1 bmask = ~(vmask << shift) cdb[bitnum//8] &= bmask cdb[bitnum//8] |= (value & vmask) << shift bitnum -= bitlen value >>= bitlen width -= bitlen class Field: def __init__(self, val, byteoffset, name, desc): self.val = val self.byteoffset = byteoffset self.name = name self.desc = desc def __str__(self): return '(' + str(self.val) + ', ' + str(self.byteoffset) + ', "' + self.name + '", "' + self.desc + '")' @staticmethod def extract(data, defs, byteoffset=0): """ Extract fields from data into a structure based on field definitions in defs. byteoffset is added to each local byte offset to get the byte offset returned for each field. defs is a list of lists comprising start, width in bits, format, nickname, description. field start is either a byte number or a tuple with byte number and bit number. Return a ListDict of Fields. """ retval = ListDict() for fielddef in defs: start, width, form, name, desc = fielddef if form == "int": if type(start) == type(0): # It's a number. Convert it into a (bytenum,bitnum) tuple. start = (start,7) ix, bitnum = start val = 0 while (width > 0): if bitnum == 7 and width >= 8: val = (val << 8) | ord(data[ix]) ix += 1 width -= 8 else: lastbit = bitnum+1 - width if lastbit < 0: lastbit = 0 thiswidth = bitnum+1 - lastbit val = (val << thiswidth) | ((ord(data[ix]) >> lastbit) & ((1<<thiswidth)-1)) bitnum = 7 ix += 1 width -= thiswidth retval.append(Cmd.Field(val, byteoffset+start[0], name, desc), name) elif form == "str": assert(type(start) == type(0)) assert(width % 8 == 0) retval.append(Cmd.Field(data[start:start+width/8], byteoffset+start, name, desc), name) else: # error in form pass return retval # @staticmethod # def extractdict(data, defs, byteoffset=0): # return Cmd.extracttodict(Cmd.extract(data, defs, byteoffset)) # # @staticmethod # def extracttodict(extractresults): # return {field.name: field for field in extractresults if field.name} # factory to create a Cmd to set time on a Rockbox device @classmethod def settime(Cls, year, day, hour, minute, second): data_settime = \ { "year" :(0,16,0), "day" :(2,16,0), "hour" :(5, 8,0), "minute":(6, 8,0), "second":(7, 8,0), } cmd = Cls("write_buffer", { "mode":1, "buffer_id":0, "buffer_offset":0xc0000, "parameter_list_length":12, # Why is this 12 when there are 8 bytes of data? }) cmd.dat = [0] * 8 Cls.fill(cmd.dat, data_settime, {"year":year, "day":day, "hour":hour, "minute":minute, "second":second}) return cmd # factory to create a Cmd to send a CLI command to a SkyTree device @classmethod def clicommandout(Cls, expanderid, command): data_clicommandout = \ { "pagecode" :(0, 8,0), "pagelength":(2,16,0), "expanderid":(4, 8,0), "command" :[5, 0,0], } cmd = Cls("send_diagnostic", { "self-test_code":0, "pf":1, "parameter_list_length": 5+len(command), }) cmd.dat = [0] * (5+len(command)) data_clicommandout["command"][1] = 8*(len(command)) Cls.fill(cmd.dat, Cmd.data_clicommandout, { "pagecode":0xe8, "pagelength":1+len(command), "expanderid":expanderid, "command":command, }) return cmd @staticmethod def inq(pt, page=None, alloc=74): """ Create an Inquiry command, send it, and parse the results. Input: pt : ScsiPT object page : vital product page number or None alloc: size to allocate for result TODO: implement page """ cmd = Cmd("inq", {"evpd":0, "alloc":alloc}) cdb = CDB(cmd.cdb) cdb.set_data_in(alloc) pt.sendcdb(cdb) inq = Cmd.extract(cdb.buf, Cmd.data_inquiry) return inq
class Cmd(object): ''' Manage creating objects of type CDB and filling in parameters. ''' def __init__(self, cdbname, params={}): pass @staticmethod def fill(cdb, defs, pparms): ''' Take field values in parms and insert them into cdb based on the field definitions in defs. ''' pass class Field: def __init__(self, cdbname, params={}): pass def __str__(self): pass @staticmethod def extract(data, defs, byteoffset=0): ''' Extract fields from data into a structure based on field definitions in defs. byteoffset is added to each local byte offset to get the byte offset returned for each field. defs is a list of lists comprising start, width in bits, format, nickname, description. field start is either a byte number or a tuple with byte number and bit number. Return a ListDict of Fields. ''' pass @classmethod def settime(Cls, year, day, hour, minute, second): pass @classmethod def clicommandout(Cls, expanderid, command): pass @staticmethod def inq(pt, page=None, alloc=74): ''' Create an Inquiry command, send it, and parse the results. Input: pt : ScsiPT object page : vital product page number or None alloc: size to allocate for result TODO: implement page ''' pass
15
4
22
1
18
5
3
0.18
1
5
2
0
1
1
6
6
362
18
299
62
284
53
119
57
109
10
1
5
27
144,529
LFenske/python-scsi-pt
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LFenske_python-scsi-pt/Cmd.py
Cmd.Cmd.Field
class Field: def __init__(self, val, byteoffset, name, desc): self.val = val self.byteoffset = byteoffset self.name = name self.desc = desc def __str__(self): return '(' + str(self.val) + ', ' + str(self.byteoffset) + ', "' + self.name + '", "' + self.desc + '")'
class Field: def __init__(self, val, byteoffset, name, desc): pass def __str__(self): pass
3
0
4
0
4
0
1
0
0
1
0
0
2
4
2
2
9
1
8
7
5
0
8
7
5
1
0
0
2
144,530
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/scripts/example_scripts.py
pylabcontrol.scripts.example_scripts.ExampleScript
class ExampleScript(Script): """ Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data. """ _DEFAULT_SETTINGS = [ Parameter('count', 3, int), Parameter('name', 'this is a counter'), Parameter('wait_time', 0.1, float), Parameter('point2', [Parameter('x', 0.1, float, 'x-coordinate'), Parameter('y', 0.1, float, 'y-coordinate') ]), Parameter('plot_style', 'main', ['main', 'aux', '2D', 'two']) ] _INSTRUMENTS = {} _SCRIPTS = {} def __init__(self, name=None, settings=None, log_function = None, data_path = None): """ Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings """ Script.__init__(self, name, settings, log_function= log_function, data_path = data_path) def _function(self): """ This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ """ # some generic function import time import random self.data['random data'] = None self.data['image data'] = None count = self.settings['count'] name = self.settings['name'] wait_time = self.settings['wait_time'] data = [] self.log('I ({:s}) am a test function counting to {:d} and creating random values'.format(self.name, count)) for i in range(count): time.sleep(wait_time) self.log('{:s} count {:02d}'.format(self.name, i)) data.append(random.random()) self.data = {'random data': data} self.progress = 100. * (i + 1) / count self.updateProgress.emit(self.progress) self.data = {'random data':data} # create image data Nx = int(np.sqrt(len(self.data['random data']))) img = np.array(self.data['random data'][0:Nx ** 2]) img = img.reshape((Nx, Nx)) self.data.update({'image data': img}) def _plot(self, axes_list, data = None): """ plots the data only the axes objects that are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript data: data to be plotted if empty take self.data Returns: None """ plot_type = self.settings['plot_style'] if data is None: data = self.data if data is not None and data is not {}: if plot_type in ('main', 'two'): if not data['random data'] is None: axes_list[0].plot(data['random data']) axes_list[0].hold(False) if plot_type in ('aux', 'two', '2D'): if not data['random data'] is None: axes_list[1].plot(data['random data']) axes_list[1].hold(False) if plot_type == '2D': if 'image data' in data and not data['image data'] is None: fig = axes_list[0].get_figure() implot = axes_list[0].imshow(data['image data'], cmap='pink', interpolation="nearest", extent=[-1,1,1,-1]) fig.colorbar(implot, label='kcounts/sec') def _update(self, axes_list): """ updates the data in already existing plots. the axes objects are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript Returns: None """ plot_type = self.settings['plot_style'] if plot_type == '2D': # we expect exactely one image in the axes object (see ScriptDummy.plot) implot = axes_list[1].get_images()[0] # now update the data implot.set_data(self.data['random data']) colorbar = implot.colorbar if not colorbar is None: colorbar.update_bruteforce(implot) else: # fall back to default behaviour Script._update(self, axes_list)
class ExampleScript(Script): ''' Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data. ''' def __init__(self, name=None, settings=None, log_function = None, data_path = None): ''' Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings ''' pass def _function(self): ''' This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ ''' pass def _plot(self, axes_list, data = None): ''' plots the data only the axes objects that are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript data: data to be plotted if empty take self.data Returns: None ''' pass def _update(self, axes_list): ''' updates the data in already existing plots. the axes objects are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript Returns: None ''' pass
5
5
24
4
13
7
4
0.48
1
2
0
0
4
2
4
53
119
23
65
25
58
31
55
25
48
9
2
3
15
144,531
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/manual_fitting_ensemble.py
pylabcontrol.gui.windows_and_widgets.manual_fitting_ensemble.FittingWindow
class FittingWindow(QMainWindow, Ui_MainWindow): def __init__(self): QMainWindow.__init__(self) self.setupUi(self) def create_figures(): self.matplotlibwidget = MatplotlibWidget(self.plot) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.matplotlibwidget.sizePolicy().hasHeightForWidth()) self.matplotlibwidget.setSizePolicy(sizePolicy) self.matplotlibwidget.setMinimumSize(QtCore.QSize(200, 200)) # self.matplotlibwidget.setObjectName(QtCore.QString.fromUtf8("matplotlibwidget")) self.horizontalLayout_3.addWidget(self.matplotlibwidget) self.mpl_toolbar = NavigationToolbar(self.matplotlibwidget.canvas, self.toolbar_space) self.horizontalLayout_2.addWidget(self.mpl_toolbar) self.peak_vals = None def setup_connections(): self.btn_fit.clicked.connect(self.btn_clicked) self.btn_clear.clicked.connect(self.btn_clicked) self.btn_next.clicked.connect(self.btn_clicked) self.matplotlibwidget.mpl_connect('button_press_event', self.plot_clicked) self.btn_open.clicked.connect(self.open_file_dialog) self.btn_run.clicked.connect(self.btn_clicked) self.btn_goto.clicked.connect(self.btn_clicked) self.btn_prev.clicked.connect(self.btn_clicked) self.btn_skip.clicked.connect(self.btn_clicked) create_figures() setup_connections() def btn_clicked(self): sender = self.sender() if sender is self.btn_run: self.start_fitting() elif sender is self.btn_next: self.queue.put('next') elif sender is self.btn_fit: self.queue.put('fit') elif sender is self.btn_clear: while not self.peak_vals == []: self.peak_vals.pop(-1) self.queue.put('clear') elif sender is self.btn_goto: self.queue.put(int(self.input_next.text())) elif sender is self.btn_prev: self.queue.put('prev') elif sender is self.btn_skip: self.queue.put('skip') def plot_clicked(self, mouse_event): if type(self.peak_vals) is list: self.peak_vals.append([mouse_event.xdata, mouse_event.ydata]) axes = self.matplotlibwidget.axes # can't use patches, as they use data coordinates for radius but this is a high aspect ratio plot so the # circle was extremely stretched axes.plot(mouse_event.xdata, mouse_event.ydata, 'ro', markersize = 5) self.matplotlibwidget.draw() class do_fit(QObject): finished = pyqtSignal() # signals the end of the script status = pyqtSignal(str) # sends messages to update the statusbar NUM_ESR_LINES = 8 def __init__(self, filepath, plotwidget, queue, peak_vals, interps): QObject.__init__(self) self.filepath = filepath self.plotwidget = plotwidget self.queue = queue self.peak_vals = peak_vals self.interps = interps def save(self): def freqs(index): return self.frequencies[0] + (self.frequencies[-1]-self.frequencies[0])/(len(self.frequencies)-1)*index save_path = os.path.join(self.filepath, 'line_data.csv') data = list() for i in range(0, self.NUM_ESR_LINES): data.append(list()) for i in range(0, self.NUM_ESR_LINES): indices = self.interps[i](self.x_range) data[i] = [freqs(indices[j]) for j in range(0,len(self.x_range))] df = pd.DataFrame(data) df = df.transpose() df.to_csv(save_path) self.plotwidget.figure.savefig(self.filepath + './lines.jpg') def run(self): data_esr = [] for f in sorted(glob.glob(os.path.join(self.filepath, './data_subscripts/*'))): data = Script.load_data(f) data_esr.append(data['data']) self.frequencies = data['frequency'] data_esr_norm = [] for d in data_esr: data_esr_norm.append(d / np.mean(d)) self.x_range = list(range(0, len(data_esr_norm))) self.status.emit('executing manual fitting') index = 0 # for data in data_array: while index < self.NUM_ESR_LINES: #this must be after the draw command, otherwise plot doesn't display for some reason self.status.emit('executing manual fitting NV #' + str(index)) self.plotwidget.axes.clear() self.plotwidget.axes.imshow(data_esr_norm, aspect = 'auto', origin = 'lower') if self.interps: for f in self.interps: self.plotwidget.axes.plot(f(self.x_range), self.x_range) self.plotwidget.draw() while(True): if self.queue.empty(): time.sleep(.5) else: value = self.queue.get() if value == 'next': while not self.peak_vals == []: self.peak_vals.pop(-1) # if len(self.single_fit) == 1: # self.fits[index] = self.single_fit # else: # self.fits[index] = [y for x in self.single_fit for y in x] index += 1 self.interps.append(f) break elif value == 'clear': self.plotwidget.axes.clear() self.plotwidget.axes.imshow(data_esr_norm, aspect='auto', origin = 'lower') if self.interps: for f in self.interps: self.plotwidget.axes.plot(f(self.x_range), self.x_range) self.plotwidget.draw() elif value == 'fit': peak_vals = sorted(self.peak_vals, key = lambda tup: tup[1]) y,x = list(zip(*peak_vals)) f = UnivariateSpline(np.array(x),np.array(y)) x_range = list(range(0,len(data_esr_norm))) self.plotwidget.axes.plot(f(x_range), x_range) self.plotwidget.draw() elif value == 'prev': index -= 1 break elif value == 'skip': index += 1 break elif type(value) is int: index = int(value) break self.finished.emit() self.status.emit('saving') self.plotwidget.axes.clear() self.plotwidget.axes.imshow(data_esr_norm, aspect='auto', origin = 'lower') if self.interps: for f in self.interps: self.plotwidget.axes.plot(f(self.x_range), self.x_range) self.save() self.status.emit('saving finished') def update_status(self, str): self.statusbar.showMessage(str) def start_fitting(self): self.queue = queue.Queue() self.peak_vals = [] self.interps = [] self.fit_thread = QThread() #must be assigned as an instance variable, not local, as otherwise thread is garbage #collected immediately at the end of the function before it runs self.fitobj = self.do_fit(str(self.data_filepath.text()), self.matplotlibwidget, self.queue, self.peak_vals, self.interps) self.fitobj.moveToThread(self.fit_thread) self.fit_thread.started.connect(self.fitobj.run) self.fitobj.finished.connect(self.fit_thread.quit) # clean up. quit thread after script is finished self.fitobj.status.connect(self.update_status) self.fit_thread.start() def open_file_dialog(self): """ opens a file dialog to get the path to a file and """ dialog = QtWidgets.QFileDialog filename = dialog.getExistingDirectory(self, 'Select a file:', self.data_filepath.text()) if str(filename)!='': self.data_filepath.setText(filename)
class FittingWindow(QMainWindow, Ui_MainWindow): def __init__(self): pass def create_figures(): pass def setup_connections(): pass def btn_clicked(self): pass def plot_clicked(self, mouse_event): pass class do_fit(QObject): def __init__(self): pass def save(self): pass def freqs(index): pass def run(self): pass def update_status(self, str): pass def start_fitting(self): pass def open_file_dialog(self): ''' opens a file dialog to get the path to a file and ''' pass
14
1
17
1
15
1
4
0.11
2
6
2
0
6
5
6
6
191
20
158
49
144
18
146
49
132
19
1
6
42
144,532
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/scripts/example_scripts.py
pylabcontrol.scripts.example_scripts.ExampleMinimalScript
class ExampleMinimalScript(Script): """ Minimal Example Script that has only a single parameter (execution time) """ _DEFAULT_SETTINGS = [ Parameter('execution_time', 0.1, float, 'execution time of script (s)') ] _INSTRUMENTS = {} _SCRIPTS = {} def __init__(self, name=None, settings=None, log_function = None, data_path = None): """ Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings """ Script.__init__(self, name, settings, log_function= log_function, data_path = data_path) def _function(self): """ This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ """ import time self.data = {'empty_data':[]} time.sleep(self.settings['execution_time'])
class ExampleMinimalScript(Script): ''' Minimal Example Script that has only a single parameter (execution time) ''' def __init__(self, name=None, settings=None, log_function = None, data_path = None): ''' Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings ''' pass def _function(self): ''' This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ ''' pass
3
3
9
1
4
5
1
1
1
0
0
0
2
1
2
51
32
6
13
9
8
13
10
8
6
1
2
0
2
144,533
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/instruments/example_instrument.py
pylabcontrol.instruments.example_instrument.Plant
class Plant(Instrument, QThread): _DEFAULT_SETTINGS = Parameter([ Parameter('update frequency', 20, float, 'update frequency of signal in Hz'), Parameter('noise_strength',1.0, float, 'strength of noise'), Parameter('noise_bandwidth', 1.0, float, 'bandwidth of noise (Hz)'), Parameter('control', 0.0, float, 'set the output varariable to a given value (in the absence of noise)') ]) _PROBES = {'output': 'this is some random output signal (float)' } def __init__(self, name = None, settings = None): QThread.__init__(self) Instrument.__init__(self, name, settings) self._is_connected = True self._output = 0 self.start() def start(self, *args, **kwargs): """ start the instrument thread """ self._stop = False super(Plant, self).start(*args, **kwargs) def quit(self, *args, **kwargs): # real signature unknown """ quit the instrument thread """ self.stop() self._stop = True self.msleep(2* int(1e3 / self.settings['update frequency'])) super(Plant, self).quit(*args, **kwargs) def run(self): """ this is the actual execution of the instrument thread: continuously read values from the probes """ eta = self.settings['noise_strength'] gamma = 2 * np.pi * self.settings['noise_bandwidth'] dt = 1. / self.settings['update frequency'] control = self.settings['control'] self._state = self._output while self._stop is False: A = -gamma * dt noise = np.sqrt(2*gamma*eta)*np.random.randn() self._state *= (1. + A) self._state += noise + control self._output = self._state self.msleep(int(1e3 / self.settings['update frequency'])) def read_probes(self, key): """ requestes value from the instrument and returns it Args: key: name of requested value Returns: reads values from instrument """ assert key in list(self._PROBES.keys()) if key == 'output': value = self._output return value @property def is_connected(self): ''' check if instrument is active and connected and return True in that case :return: bool ''' return self._is_connected
class Plant(Instrument, QThread): def __init__(self, name = None, settings = None): pass def start(self, *args, **kwargs): ''' start the instrument thread ''' pass def quit(self, *args, **kwargs): ''' quit the instrument thread ''' pass def run(self): ''' this is the actual execution of the instrument thread: continuously read values from the probes ''' pass def read_probes(self, key): ''' requestes value from the instrument and returns it Args: key: name of requested value Returns: reads values from instrument ''' pass @property def is_connected(self): ''' check if instrument is active and connected and return True in that case :return: bool ''' pass
8
5
11
2
6
3
1
0.45
2
3
0
0
6
4
6
21
85
22
44
21
36
20
37
20
30
2
2
1
8
144,534
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/instruments/example_instrument.py
pylabcontrol.instruments.example_instrument.PIControler
class PIControler(Instrument): """ Discrete PI control """ _DEFAULT_SETTINGS = Parameter([ Parameter('set_point', 0.0, float, 'setpoint to which to stabilize'), Parameter('gains',[ Parameter('proportional', 0.0, float, 'proportional gain'), Parameter('integral', 0.0, float, 'integral gain') ]), Parameter('time_step', 1.0, float, 'time_step of loop'), Parameter('output_range', [ Parameter('min', -10000, float, 'min allowed value for PI-loop output'), Parameter('max', 10000, float, 'max allowed value for PI-loop output') ]) ]) _PROBES = {} def __init__(self, name = None, settings = None): super(PIControler, self).__init__(name, settings) self.reset() def update(self, settings): super(PIControler, self).update(settings) def read_probes(self, key = None): if key is None: super(PIControler, self).read_probes() else: assert key in list(self._PROBES.keys()), "key assertion failed %s" % str(key) return None def reset(self): #COMMENT_ME self.u_P = 0 self.u_I = 0 self.error = 0 def controler_output(self, current_value): """ Calculate PI output value for given reference input and feedback """ set_point = self.settings['set_point'] Kp = self.settings['gains']['proportional'] Ki = self.settings['gains']['integral'] output_range = self.settings['output_range'] time_step = self.settings['time_step'] error_new = set_point - current_value print(('PD- error:\t', error_new, Ki, Kp, time_step)) #proportional action self.u_P = Kp * error_new * time_step print(('PD- self.u_P:\t', self.u_P, self.u_I)) #integral action self.u_I += Kp * Ki * (error_new + self.error) / 2.0 * time_step self.error = error_new print(('PD- self.u_P:\t', self.u_P, self.u_I)) # anti-windup if self.u_P + self.u_I > output_range['max']: self.u_I = output_range['max']-self.u_P if self.u_P + self.u_I < output_range['min']: self.u_I = output_range['min']-self.u_P output = self.u_P + self.u_I print(('PD- output:\t', output)) return output
class PIControler(Instrument): ''' Discrete PI control ''' def __init__(self, name = None, settings = None): pass def update(self, settings): pass def read_probes(self, key = None): pass def reset(self): pass def controler_output(self, current_value): ''' Calculate PI output value for given reference input and feedback ''' pass
6
2
10
2
7
1
2
0.2
1
3
0
0
5
3
5
20
72
13
49
18
43
10
37
18
31
3
2
1
8
144,535
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/instruments/example_instrument.py
pylabcontrol.instruments.example_instrument.ExampleInstrument
class ExampleInstrument(Instrument): ''' Dummy instrument a implementation of a dummy instrument ''' _DEFAULT_SETTINGS = Parameter([ Parameter('test1', 0, int, 'some int parameter'), Parameter('output probe2', 0, int, 'return value of probe 2 (int)'), Parameter('test2', [Parameter('test2_1', 'string', str, 'test parameter (str)'), Parameter('test2_2', 0.0, float, 'test parameter (float)') ]) ]) _PROBES = {'value1': 'this is some value from the instrument', 'value2': 'this is another', 'internal': 'gives the internal state variable', 'deep_internal': 'gives another internal state variable' } def __init__(self, name = None, settings = None): self._test_variable = 1 super(ExampleInstrument, self).__init__(name, settings) self._internal_state = None self._internal_state_deep = None def update(self, settings): ''' updates the internal dictionary and sends changed values to instrument Args: settings: parameters to be set # mabe in the future: # Returns: boolean that is true if update successful ''' Instrument.update(self, settings) for key, value in settings.items(): if key == 'test1': self._internal_state = value def read_probes(self, key): """ requestes value from the instrument and returns it Args: key: name of requested value Returns: reads values from instrument """ assert key in list(self._PROBES.keys()) import random if key == 'value1': value = random.random() elif key == 'value2': value = self.settings['output probe2'] elif key == 'internal': value = self._internal_state elif key == 'deep_internal': value = self._internal_state_deep return value @property def is_connected(self): ''' check if instrument is active and connected and return True in that case :return: bool ''' return self._is_connected
class ExampleInstrument(Instrument): ''' Dummy instrument a implementation of a dummy instrument ''' def __init__(self, name = None, settings = None): pass def update(self, settings): ''' updates the internal dictionary and sends changed values to instrument Args: settings: parameters to be set # mabe in the future: # Returns: boolean that is true if update successful ''' pass def read_probes(self, key): ''' requestes value from the instrument and returns it Args: key: name of requested value Returns: reads values from instrument ''' pass @property def is_connected(self): ''' check if instrument is active and connected and return True in that case :return: bool ''' pass
6
4
12
2
6
4
3
0.54
1
2
0
0
4
3
4
19
75
15
39
14
32
21
24
13
18
5
2
2
10
144,536
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/widgets.py
pylabcontrol.gui.windows_and_widgets.widgets.MatplotlibWidget
class MatplotlibWidget(Canvas): """ MatplotlibWidget inherits PyQt5.QtWidgets.QWidget and matplotlib.backend_bases.FigureCanvasBase Options: option_name (default_value) ------- parent (None): parent widget title (''): figure title xlabel (''): X-axis label ylabel (''): Y-axis label xlim (None): X-axis limits ([min, max]) ylim (None): Y-axis limits ([min, max]) xscale ('linear'): X-axis scale yscale ('linear'): Y-axis scale width (4): width in inches height (3): height in inches dpi (100): resolution in dpi hold (False): if False, figure will be cleared each time plot is called Widget attributes: ----------------- figure: instance of matplotlib.figure.Figure axes: figure axes Example: ------- self.widget = MatplotlibWidget(self, yscale='log', hold=True) from numpy import linspace x = linspace(-10, 10) self.widget.axes.plot(x, x**2) self.wdiget.axes.plot(x, x**3) """ def __init__(self, parent=None): self.figure = Figure(dpi=100) Canvas.__init__(self, self.figure) self.axes = self.figure.add_subplot(111) self.canvas = self.figure.canvas self.setParent(parent) Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) Canvas.updateGeometry(self) def sizeHint(self): """ gives qt a starting point for widget size during window resizing """ w, h = self.get_width_height() return QtCore.QSize(w, h) def minimumSizeHint(self): """ minimum widget size during window resizing Returns: QSize object that specifies the size of widget """ return QtCore.QSize(10, 10)
class MatplotlibWidget(Canvas): ''' MatplotlibWidget inherits PyQt5.QtWidgets.QWidget and matplotlib.backend_bases.FigureCanvasBase Options: option_name (default_value) ------- parent (None): parent widget title (''): figure title xlabel (''): X-axis label ylabel (''): Y-axis label xlim (None): X-axis limits ([min, max]) ylim (None): Y-axis limits ([min, max]) xscale ('linear'): X-axis scale yscale ('linear'): Y-axis scale width (4): width in inches height (3): height in inches dpi (100): resolution in dpi hold (False): if False, figure will be cleared each time plot is called Widget attributes: ----------------- figure: instance of matplotlib.figure.Figure axes: figure axes Example: ------- self.widget = MatplotlibWidget(self, yscale='log', hold=True) from numpy import linspace x = linspace(-10, 10) self.widget.axes.plot(x, x**2) self.wdiget.axes.plot(x, x**3) ''' def __init__(self, parent=None): pass def sizeHint(self): ''' gives qt a starting point for widget size during window resizing ''' pass def minimumSizeHint(self): ''' minimum widget size during window resizing Returns: QSize object that specifies the size of widget ''' pass
4
3
7
1
4
2
1
2.57
1
0
0
0
3
3
3
3
57
7
14
8
10
36
14
8
10
1
1
0
3
144,537
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/widgets.py
pylabcontrol.gui.windows_and_widgets.widgets.B26QTreeItem
class B26QTreeItem(QtWidgets.QTreeWidgetItem): """ Custom QTreeWidgetItem with Widgets """ def __init__(self, parent, name, value, valid_values, info, visible=None): """ Args: name: value: valid_values: info: visible (optional): Returns: """ super(B26QTreeItem, self ).__init__(parent) self.ui_type = None self.name = name self.valid_values = valid_values self._value = value self.info = info self._visible = visible self.setData(0, 0, self.name) if isinstance(self.valid_values, list): self.ui_type = 'combo_box' self.combo_box = QtWidgets.QComboBox() for item in self.valid_values: self.combo_box.addItem(str(item)) self.combo_box.setCurrentIndex(self.combo_box.findText(str(self.value))) self.treeWidget().setItemWidget(self, 1, self.combo_box) self.combo_box.currentIndexChanged.connect(lambda: self.setData(1, 2, self.combo_box)) self.combo_box.setFocusPolicy(QtCore.Qt.StrongFocus) self._visible = False elif self.valid_values is bool: self.ui_type = 'checkbox' self.checkbox = QtWidgets.QCheckBox() self.checkbox.setChecked(self.value) self.treeWidget().setItemWidget( self, 1, self.checkbox ) self.checkbox.stateChanged.connect(lambda: self.setData(1, 2, self.checkbox)) self._visible = False elif isinstance(self.value, Parameter): for key, value in self.value.items(): B26QTreeItem(self, key, value, self.value.valid_values[key], self.value.info[key]) elif isinstance(self.value, dict): for key, value in self.value.items(): if self.valid_values == dict: B26QTreeItem(self, key, value, type(value), '') else: B26QTreeItem(self, key, value, self.valid_values[key], self.info[key]) elif isinstance(self.value, Instrument): index_top_level_item = self.treeWidget().indexOfTopLevelItem(self) top_level_item = self.treeWidget().topLevelItem(index_top_level_item) if top_level_item == self: # instrument is on top level, thus we are in the instrument tab for key, value in self.value.settings.items(): B26QTreeItem(self, key, value, self.value.settings.valid_values[key], self.value.settings.info[key]) else: self.valid_values = [self.value.name] self.value = self.value.name self.combo_box = QtWidgets.QComboBox() for item in self.valid_values: self.combo_box.addItem(item) self.combo_box.setCurrentIndex(self.combo_box.findText(str(self.value))) self.treeWidget().setItemWidget(self, 1, self.combo_box) self.combo_box.currentIndexChanged.connect(lambda: self.setData(1, 2, self.combo_box)) self.combo_box.setFocusPolicy(QtCore.Qt.StrongFocus) elif isinstance(self.value, Script): for key, value in self.value.settings.items(): B26QTreeItem(self, key, value, self.value.settings.valid_values[key], self.value.settings.info[key]) for key, value in self.value.instruments.items(): B26QTreeItem(self, key, self.value.instruments[key], type(self.value.instruments[key]), '') for key, value in self.value.scripts.items(): B26QTreeItem(self, key, self.value.scripts[key], type(self.value.scripts[key]), '') self.info = self.value.__doc__ else: self.setData(1, 0, self.value) self._visible = False self.setToolTip(1, str(self.info if isinstance(self.info, str) else '')) if self._visible is not None: self.check_show = QtWidgets.QCheckBox() self.check_show.setChecked(self.visible) self.treeWidget().setItemWidget(self, 2, self.check_show) self.setFlags(self.flags() | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable) @property def value(self): """ item value """ return self._value @value.setter def value(self, value): if Parameter.is_valid(value, self.valid_values): self._value = value # check if there is a special case for setting such as a checkbox or combobox if self.ui_type == 'checkbox': self.checkbox.setChecked(value) elif self.ui_type == 'combo_box': self.combo_box.setCurrentIndex(self.combo_box.findText(str(self.value))) else: # for standard values self.setData(1, 0, value) else: if value is not None: raise TypeError("wrong type {:s}, expected {:s}".format(str(type(value)), str(self.valid_values))) @property def visible(self): """ Returns: boolean (True: item is visible) (False: item is hidden) """ if self._visible is not None: return self.check_show.isChecked() elif isinstance(self._value, (Parameter, dict)): # check if any of the children is visible for i in range(self.childCount()): if self.child(i).visible: return True # if none of the children is visible hide this parameter return False else: return True @visible.setter def visible(self, value): if self._visible is not None: self._visible = value self.check_show.setChecked(self._visible) def setData(self, column, role, value): """ if value is valid sets the data to value Args: column: column of item role: role of item (see Qt doc) value: value to be set """ assert isinstance(column, int) assert isinstance(role, int) # make sure that the right row is selected, this is not always the case for checkboxes and # combo boxes because they are items on top of the tree structure if isinstance(value, (QtWidgets.QComboBox, QtWidgets.QCheckBox)): self.treeWidget().setCurrentItem(self) # if row 2 (editrole, value has been entered) if role == 2 and column == 1: if isinstance(value, str): value = self.cast_type(value) # cast into same type as valid values if isinstance(value, QtCore.QVariant): value = self.cast_type(value.toString()) # cast into same type as valid values if isinstance(value, QtWidgets.QComboBox): value = self.cast_type(value.currentText()) if isinstance(value, QtWidgets.QCheckBox): value = bool(int(value.checkState())) # checkState() gives 2 (True) and 0 (False) # save value in internal variable self.value = value elif column == 0: # labels should not be changed so we set it back value = self.name if value is None: value = self.value # 180327(asafira) --- why do we need to do the following lines? Why not just always call super or always # emitDataChanged()? if not isinstance(value, bool): super(B26QTreeItem, self).setData(column, role, value) else: self.emitDataChanged() def cast_type(self, var, cast_type=None): """ cast the value into the type typ if type is not provided it is set to self.valid_values Args: var: variable to be cast type: target type Returns: the variable var csat into type typ """ if cast_type is None: cast_type = self.valid_values try: if cast_type == int: return int(var) elif cast_type == float: return float(var) elif cast_type == str: return str(var) elif isinstance(cast_type, list): # cast var to be of the same type as those in the list return type(cast_type[0])(var) else: return None except ValueError: return None return var def get_instrument(self): """ Returns: the instrument and the path to the instrument to which this item belongs """ if isinstance(self.value, Instrument): instrument = self.value path_to_instrument = [] else: instrument = None parent = self.parent() path_to_instrument = [self.name] while parent is not None: if isinstance(parent.value, Instrument): instrument = parent.value parent = None else: path_to_instrument.append(parent.name) parent = parent.parent() return instrument, path_to_instrument def get_script(self): """ Returns: the script and the path to the script to which this item belongs """ if isinstance(self.value, Script): script = self.value path_to_script = [] script_item = self else: script = None parent = self.parent() path_to_script = [self.name] while parent is not None: if isinstance(parent.value, Script): script = parent.value script_item = parent parent = None else: path_to_script.append(parent.name) parent = parent.parent() return script, path_to_script, script_item def get_subscript(self, sub_script_name): """ finds the item that contains the sub_script with name sub_script_name Args: sub_script_name: name of subscript Returns: B26QTreeItem in QTreeWidget which is a script """ # get tree of item tree = self.treeWidget() items = tree.findItems(sub_script_name, QtCore.Qt.MatchExactly | QtCore.Qt.MatchRecursive) if len(items) >= 1: # identify correct script by checking that it is a sub_element of the current script subscript_item = [sub_item for sub_item in items if isinstance(sub_item.value, Script) and sub_item.parent() is self] subscript_item = subscript_item[0] else: raise ValueError('several elements with name ' + sub_script_name) return subscript_item def is_point(self): """ figures out if item is a point, that is if it has two subelements of type float Args: self: Returns: if item is a point (True) or not (False) """ if self.childCount() == 2: if self.child(0).valid_values == float and self.child(1).valid_values == float: return True else: return False def to_dict(self): """ Returns: the tree item as a dictionary """ if self.childCount() > 0: value = {} for index in range(self.childCount()): value.update(self.child(index).to_dict()) else: value = self.value return {self.name: value}
class B26QTreeItem(QtWidgets.QTreeWidgetItem): ''' Custom QTreeWidgetItem with Widgets ''' def __init__(self, parent, name, value, valid_values, info, visible=None): ''' Args: name: value: valid_values: info: visible (optional): Returns: ''' pass @property def value(self): ''' item value ''' pass @value.setter def value(self): pass @property def visible(self): ''' Returns: boolean (True: item is visible) (False: item is hidden) ''' pass @visible.setter def visible(self): pass def setData(self, column, role, value): ''' if value is valid sets the data to value Args: column: column of item role: role of item (see Qt doc) value: value to be set ''' pass def cast_type(self, var, cast_type=None): ''' cast the value into the type typ if type is not provided it is set to self.valid_values Args: var: variable to be cast type: target type Returns: the variable var csat into type typ ''' pass def get_instrument(self): ''' Returns: the instrument and the path to the instrument to which this item belongs ''' pass def get_script(self): ''' Returns: the script and the path to the script to which this item belongs ''' pass def get_subscript(self, sub_script_name): ''' finds the item that contains the sub_script with name sub_script_name Args: sub_script_name: name of subscript Returns: B26QTreeItem in QTreeWidget which is a script ''' pass def is_point(self): ''' figures out if item is a point, that is if it has two subelements of type float Args: self: Returns: if item is a point (True) or not (False) ''' pass def to_dict(self): ''' Returns: the tree item as a dictionary ''' pass
17
11
26
5
16
6
5
0.36
1
13
2
0
12
9
12
12
337
70
199
43
182
72
168
39
155
19
1
3
65
144,538
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/scripts/example_scripts.py
pylabcontrol.scripts.example_scripts.ExampleScriptWrapper
class ExampleScriptWrapper(Script): """ Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data. """ _DEFAULT_SETTINGS = [] _INSTRUMENTS = {} _SCRIPTS = {'ScriptDummy': ExampleScript} def __init__(self, instruments = None, scripts = None, name=None, settings=None, log_function = None, data_path = None): """ Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings """ super(ExampleScriptWrapper, self).__init__(self, name, settings, log_function= log_function, data_path=data_path) def _function(self): """ This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ """ self.scripts['ScriptDummy'].run() def _plot(self, axes_list, data = None): """ plots the data only the axes objects that are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript data: data to be plotted if empty take self.data Returns: None """ self.scripts['ScriptDummy']._plot(axes_list) def _update(self, axes_list): """ updates the data in already existing plots. the axes objects are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript Returns: None """ self.scripts['ScriptDummy']._update(axes_list)
class ExampleScriptWrapper(Script): ''' Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data. ''' def __init__(self, instruments = None, scripts = None, name=None, settings=None, log_function = None, data_path = None): ''' Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings ''' pass def _function(self): ''' This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ ''' pass def _plot(self, axes_list, data = None): ''' plots the data only the axes objects that are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript data: data to be plotted if empty take self.data Returns: None ''' pass def _update(self, axes_list): ''' updates the data in already existing plots. the axes objects are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript Returns: None ''' pass
5
5
9
1
2
6
1
2.17
1
1
0
0
4
0
4
53
50
12
12
8
7
26
12
8
7
1
2
0
4
144,539
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/manual_fitting.py
pylabcontrol.gui.windows_and_widgets.manual_fitting.FittingWindow
class FittingWindow(QMainWindow, Ui_MainWindow): """ Class defining main gui window for doing manual fitting QMainWindow: Qt object returned from loadUiType UI_MainWindow: Ui reference returned from loadUiType """ def __init__(self): QMainWindow.__init__(self) self.setupUi(self) def create_figures(): """ Sets up figures in GUI """ self.matplotlibwidget = MatplotlibWidget(self.plot) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.matplotlibwidget.sizePolicy().hasHeightForWidth()) self.matplotlibwidget.setSizePolicy(sizePolicy) self.matplotlibwidget.setMinimumSize(QtCore.QSize(200, 200)) self.matplotlibwidget.setObjectName(QtCore.QString.fromUtf8("matplotlibwidget")) self.horizontalLayout_3.addWidget(self.matplotlibwidget) self.mpl_toolbar = NavigationToolbar(self.matplotlibwidget.canvas, self.toolbar_space) self.horizontalLayout_2.addWidget(self.mpl_toolbar) self.peak_vals = None def setup_connections(): """ Sets up all connections between buttons and plots in the gui, and their corresponding backend functions """ self.btn_fit.clicked.connect(self.btn_clicked) self.btn_clear.clicked.connect(self.btn_clicked) self.btn_next.clicked.connect(self.btn_clicked) self.matplotlibwidget.mpl_connect('button_press_event', self.plot_clicked) self.btn_open.clicked.connect(self.open_file_dialog) self.btn_run.clicked.connect(self.btn_clicked) self.btn_goto.clicked.connect(self.btn_clicked) self.btn_prev.clicked.connect(self.btn_clicked) self.btn_skip.clicked.connect(self.btn_clicked) create_figures() setup_connections() def btn_clicked(self): """ Adds the appropriate value to the queue used for communication with the fitting routine thread when a given button is clicked. """ sender = self.sender() if sender is self.btn_run: self.start_fitting() elif sender is self.btn_next: self.queue.put('next') elif sender is self.btn_fit: self.queue.put('fit') elif sender is self.btn_clear: while not self.peak_vals == []: self.peak_vals.pop(-1) self.queue.put('clear') elif sender is self.btn_goto: self.queue.put(int(self.input_next.text())) elif sender is self.btn_prev: self.queue.put('prev') elif sender is self.btn_skip: self.queue.put('skip') def plot_clicked(self, mouse_event): """ When a click is registered on the plot, appends the click location to self.peak_vals and plots a red dot in the click location :param mouse_event: a mouse event object for the click """ if type(self.peak_vals) is list: self.peak_vals.append([mouse_event.xdata, mouse_event.ydata]) axes = self.matplotlibwidget.axes # can't use patches, as they use data coordinates for radius but this is a high aspect ratio plot so the # circle was extremely stretched axes.plot(mouse_event.xdata, mouse_event.ydata, 'ro', markersize = 5) # axes.text(mouse_event.xdata, mouse_event.ydata, '{:d}'.format(len(self.peak_vals[-1])), # horizontalalignment='center', # verticalalignment='center', # color='black' # ) self.matplotlibwidget.draw() class do_fit(QObject): """ This class does all of the work of the manual fitting, including loading and saving data, processing input, and displaying output to the plots. It is implemented as a separate class so that it can be easily moved to a second thread. If it is on the same thread as the gui, you can't both run this code and still interact with the gui. Thus, the second thread allows both to occur simultaneously. """ finished = pyqtSignal() # signals the end of the script status = pyqtSignal(str) # sends messages to update the statusbar def __init__(self, filepath, plotwidget, queue, peak_vals, peak_locs): """ Initializes the fit class :param filepath: path to file containing the ESR data to fit :param plotwidget: reference to plotwidget passed from gui :param queue: thread-safe queue used for gui-class communication across threads :param peak_vals: peak locations manually selected in gui :param peak_locs: pointer to textbox that will contain locations of fit peaks """ QObject.__init__(self) self.filepath = filepath self.plotwidget = plotwidget self.queue = queue self.peak_vals = peak_vals self.peak_locs = peak_locs def n_lorentzian(self, x, offset, *peak_params): """ Defines a lorentzian with n peaks :param x: independent variable :param offset: offset of lorentzians :param peak_params: this is a flattened array of length 3n with the format [widths amplitudes centers], that is the first n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: the output of the lorentzian for each input value x """ value = 0 width_array = peak_params[:len(peak_params)/3] amplitude_array = peak_params[len(peak_params)/3:2*len(peak_params)/3] center_array = peak_params[2*len(peak_params)/3:] for width, amplitude, center in zip(width_array, amplitude_array, center_array): value += amplitude * np.square(0.5 * width) / (np.square(x - center) + np.square(0.5 * width)) value += offset return value def fit_n_lorentzian(self, x, y, fit_start_params=None): """ uses scipy.optimize.curve_fit to fit an n-peak lorentzian to the data, where the number of peaks is determined by the number of peaks given as starting parameters for the fit :param x: :param y: :param fit_start_params: this is a flattened array of length 3n + 1 with the format [offset widths amplitudes centers], that is the first value is hte offset, the next n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: optimized fit values, in the same format as fit_start_params """ popt, _ = scipy.optimize.curve_fit(self.n_lorentzian, x, y, fit_start_params) return popt def save(self): """ Saves the fit data to the data filepath + 'data-manual.csv'. The saving format has one line corresponding to each peak, with the corresponding nv number, fit center, width, and amplitude, and manual center and amplitude included """ save_path = os.path.join(self.filepath, 'data-manual.csv') self.fits.to_csv(save_path, index = False) def load_fitdata(self): """ Tries to load and return the previous results of save, or if this file has not been previously analyzed, returns a DataFrame with the correct headers and no data :return: the loaded (or new) pandas DataFrame """ load_path = os.path.join(self.filepath, 'data-manual.csv') if os.path.exists(load_path): fits = pd.read_csv(load_path) else: fits = pd.DataFrame({'nv_id': [], 'peak_id': [], 'offset': [], 'fit_center': [], 'fit_amplitude': [], 'fit_width': [], 'manual_center': [], 'manual_height': []}) return fits def run(self): """ Code to run fitting routine. Should be run in a separate thread from the gui. """ esr_folders = glob.glob(os.path.join(self.filepath, './data_subscripts/*esr*')) data_array = [] self.status.emit('loading data') for esr_folder in esr_folders[:-1]: data = Script.load_data(esr_folder) data_array.append(data) self.fits = self.load_fitdata() self.status.emit('executing manual fitting') index = 0 self.last_good = [] self.initial_fit = False # for data in data_array: while index < len(data_array): data = data_array[index] #this must be after the draw command, otherwise plot doesn't display for some reason self.status.emit('executing manual fitting NV #' + str(index)) self.plotwidget.axes.clear() self.plotwidget.axes.plot(data['frequency'], data['data']) if index in self.fits['nv_id'].values: fitdf = self.fits.loc[(self.fits['nv_id'] == index)] offset = fitdf['offset'].as_matrix()[0] centers = fitdf['fit_center'].as_matrix() amplitudes = fitdf['fit_amplitude'].as_matrix() widths = fitdf['fit_width'].as_matrix() fit_params = np.concatenate((np.concatenate((widths, amplitudes)), centers)) self.plotwidget.axes.plot(data['frequency'], self.n_lorentzian(data['frequency'], *np.concatenate(([offset], fit_params)))) self.plotwidget.draw() if not self.last_good == []: self.initial_fit = True self.queue.put('fit') while(True): if self.queue.empty(): time.sleep(.5) else: value = self.queue.get() if value == 'next': while not self.peak_vals == []: self.last_good.append(self.peak_vals.pop(-1)) if self.single_fit: to_delete = np.where(self.fits['nv_id'].values == index) # print(self.fits[to_delete]) self.fits = self.fits.drop(self.fits.index[to_delete]) # for val in to_delete[0][::-1]: # for key in self.fits.keys(): # del self.fits[key][val] for peak in self.single_fit: self.fits = self.fits.append(pd.DataFrame(peak)) index += 1 self.status.emit('saving') self.save() break elif value == 'clear': self.last_good = [] self.plotwidget.axes.clear() self.plotwidget.axes.plot(data['frequency'], data['data']) self.plotwidget.draw() elif value == 'fit': if self.initial_fit: input = self.last_good else: input = self.peak_vals if len(input) > 1: centers, heights = list(zip(*input)) widths = 1e7 * np.ones(len(heights)) elif len(input) == 1: centers, heights = input[0] widths = 1e7 elif len(input) == 0: self.single_fit = None self.peak_locs.setText('No Peak') self.plotwidget.axes.plot(data['frequency'],np.repeat(np.mean(data['data']), len(data['frequency']))) self.plotwidget.draw() continue offset = np.mean(data['data']) amplitudes = offset-np.array(heights) if len(input) > 1: fit_start_params = [[offset], np.concatenate((widths, amplitudes, centers))] fit_start_params = [y for x in fit_start_params for y in x] elif len(input) == 1: fit_start_params = [offset, widths, amplitudes, centers] try: popt = self.fit_n_lorentzian(data['frequency'], data['data'], fit_start_params = fit_start_params) except RuntimeError: print('fit failed, optimal parameters not found') break self.plotwidget.axes.clear() self.plotwidget.axes.plot(data['frequency'], data['data']) self.plotwidget.axes.plot(data['frequency'], self.n_lorentzian(data['frequency'], *popt)) self.plotwidget.draw() params = popt[1:] widths_array = params[:len(params)/3] amplitude_array = params[len(params)/3: 2 * len(params) / 3] center_array = params[2 * len(params) / 3:] positions = list(zip(center_array, amplitude_array, widths_array)) self.single_fit = [] peak_index = 0 for position in positions: self.single_fit.append({'nv_id': [index], 'peak_id': [peak_index], 'offset': [popt[0]], 'fit_center': [position[0]], 'fit_amplitude': [position[1]], 'fit_width': [position[2]], 'manual_center': [input[peak_index][0]], 'manual_height': [input[peak_index][1]]}) peak_index += 1 self.peak_locs.setText('Peak Positions: ' + str(center_array)) self.initial_fit = False elif value == 'prev': index -= 1 break elif value == 'skip': index += 1 break elif type(value) is int: index = int(value) break self.finished.emit() self.status.emit('dataset finished') def update_status(self, str): """ Updates the gui statusbar with the given string :param str: string to set the statusbar """ self.statusbar.showMessage(str) def start_fitting(self): """ Launches the fitting routine on another thread """ self.queue = queue.Queue() self.peak_vals = [] self.fit_thread = QThread() #must be assigned as an instance variable, not local, as otherwise thread is garbage #collected immediately at the end of the function before it runs self.fitobj = self.do_fit(str(self.data_filepath.text()), self.matplotlibwidget, self.queue, self.peak_vals, self.peak_locs) self.fitobj.moveToThread(self.fit_thread) self.fit_thread.started.connect(self.fitobj.run) self.fitobj.finished.connect(self.fit_thread.quit) # clean up. quit thread after script is finished self.fitobj.status.connect(self.update_status) self.fit_thread.start() def open_file_dialog(self): """ opens a file dialog to get the path to a file and sets the data_filepath entry area to that fliepath """ dialog = QtGui.QFileDialog filename = dialog.getExistingDirectory(self, 'Select a file:', self.data_filepath.text()) if str(filename)!='': self.data_filepath.setText(filename)
class FittingWindow(QMainWindow, Ui_MainWindow): ''' Class defining main gui window for doing manual fitting QMainWindow: Qt object returned from loadUiType UI_MainWindow: Ui reference returned from loadUiType ''' def __init__(self): pass def create_figures(): ''' Sets up figures in GUI ''' pass def setup_connections(): ''' Sets up all connections between buttons and plots in the gui, and their corresponding backend functions ''' pass def btn_clicked(self): ''' Adds the appropriate value to the queue used for communication with the fitting routine thread when a given button is clicked. ''' pass def plot_clicked(self, mouse_event): ''' When a click is registered on the plot, appends the click location to self.peak_vals and plots a red dot in the click location :param mouse_event: a mouse event object for the click ''' pass class do_fit(QObject): ''' This class does all of the work of the manual fitting, including loading and saving data, processing input, and displaying output to the plots. It is implemented as a separate class so that it can be easily moved to a second thread. If it is on the same thread as the gui, you can't both run this code and still interact with the gui. Thus, the second thread allows both to occur simultaneously. ''' def __init__(self): ''' Initializes the fit class :param filepath: path to file containing the ESR data to fit :param plotwidget: reference to plotwidget passed from gui :param queue: thread-safe queue used for gui-class communication across threads :param peak_vals: peak locations manually selected in gui :param peak_locs: pointer to textbox that will contain locations of fit peaks ''' pass def n_lorentzian(self, x, offset, *peak_params): ''' Defines a lorentzian with n peaks :param x: independent variable :param offset: offset of lorentzians :param peak_params: this is a flattened array of length 3n with the format [widths amplitudes centers], that is the first n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: the output of the lorentzian for each input value x ''' pass def fit_n_lorentzian(self, x, y, fit_start_params=None): ''' uses scipy.optimize.curve_fit to fit an n-peak lorentzian to the data, where the number of peaks is determined by the number of peaks given as starting parameters for the fit :param x: :param y: :param fit_start_params: this is a flattened array of length 3n + 1 with the format [offset widths amplitudes centers], that is the first value is hte offset, the next n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: optimized fit values, in the same format as fit_start_params ''' pass def save(self): ''' Saves the fit data to the data filepath + 'data-manual.csv'. The saving format has one line corresponding to each peak, with the corresponding nv number, fit center, width, and amplitude, and manual center and amplitude included ''' pass def load_fitdata(self): ''' Tries to load and return the previous results of save, or if this file has not been previously analyzed, returns a DataFrame with the correct headers and no data :return: the loaded (or new) pandas DataFrame ''' pass def run(self): ''' Code to run fitting routine. Should be run in a separate thread from the gui. ''' pass def update_status(self, str): ''' Updates the gui statusbar with the given string :param str: string to set the statusbar ''' pass def start_fitting(self): ''' Launches the fitting routine on another thread ''' pass def open_file_dialog(self): ''' opens a file dialog to get the path to a file and sets the data_filepath entry area to that fliepath ''' pass
16
15
23
1
16
6
4
0.46
2
6
2
0
6
4
6
6
325
24
210
70
194
96
192
69
176
24
1
6
49
144,540
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/core/parameter.py
pylabcontrol.core.parameter.Parameter
class Parameter(dict): def __init__(self, name, value=None, valid_values=None, info=None, visible=False): """ Parameter(name, value, valid_values, info) Parameter(name, value, valid_values) Parameter(name, value) Parameter({name: value}) Future updates: Parameter({name1: value1, name2: value2}) Parameter([p1, p2]), where p1 and p2 are parameter objects Args: name: name of parameter value: value of parameter can be any basic type or a list valid_values: defines which values are accepted for value can be a type or a list if not provided => type(value) info: description of parameter, if not provided => empty string visible: boolean if true always show parameter if false hide it """ if isinstance(name, str): if valid_values is None: valid_values = type(value) assert isinstance(valid_values, (type,list)) if info is None: info = '' assert isinstance(info, str) assert self.is_valid(value, valid_values) if isinstance(value, list) and isinstance(value[0], Parameter): self._valid_values = {name: {k: v for d in value for k, v in d.valid_values.items()}} self.update({name: {k: v for d in value for k, v in d.items()}}) self._info = {name: {k: v for d in value for k, v in d.info.items()}} self._visible = {name: {k: v for d in value for k, v in d.visible.items()}} else: self._valid_values = {name: valid_values} self.update({name: value}) self._info = {name: info} self._visible = {name: visible} elif isinstance(name, (list, dict)) and value is None: self._valid_values = {} self._info = {} self._visible = {} if isinstance(name, dict): for k, v in name.items(): # convert to Parameter if value is a dict if isinstance(v, dict): v = Parameter(v) self._valid_values.update({k: type(v)}) self.update({k: v}) self._info.update({k: ''}) self._visible.update({k: visible}) elif isinstance(name, list) and isinstance(name[0], Parameter): for p in name: for k, v in p.items(): self._valid_values.update({k: p.valid_values[k]}) self.update({k: v}) self._info.update({k: p.info[k]}) self._visible.update({k: p.visible[k]}) else: raise TypeError('unknown input: ', name) def __setitem__(self, key, value): """ overwrites the standard dictionary and checks if value is valid Args: key: dictionary key value: dictionary value """ # print('AHHAHAH', self.valid_values) message = "{0} (of type {1}) is not in {2}".format(str(value), type(value), str(self.valid_values[key])) assert self.is_valid(value, self.valid_values[key]), message if isinstance(value, dict) and len(self)>0 and len(self) == len(self.valid_values): for k, v in value.items(): self[key].update({k:v}) else: super(Parameter, self).__setitem__(key, value) def update(self, *args): """ updates the values of the parameter, just as a regular dictionary """ for d in args: for (key, value) in d.items(): self.__setitem__(key, value) @property def visible(self): """ Returns: if parameter should be shown (False) or hidden (True) in the GUI """ return self._visible @property def valid_values(self): """ Returns: valid value of the paramerer (a type like int, float or a list) """ return self._valid_values @property def info(self): """ Returns: a text describing the paramter """ return self._info @staticmethod def is_valid(value, valid_values): """ check is the value is valid Args: value: value to be tested valid_values: allowed valid values (type or list of values) Returns: """ valid = False if isinstance(valid_values, type) and type(value) is valid_values: valid = True elif isinstance(valid_values, type) and valid_values == float and type(value) == int: #special case to allow ints as float inputs valid = True elif isinstance(value, dict) and isinstance(valid_values, dict): # check that all values actually exist in valid_values # assert value.keys() & valid_values.keys() == value.keys() # python 3 syntax assert set(value.keys()) & set(valid_values.keys()) == set(value.keys()) # python 2 # valid = True for k ,v in value.items(): valid = Parameter.is_valid(v, valid_values[k]) if valid ==False: break elif isinstance(value, dict) and valid_values == Parameter: valid = True elif isinstance(valid_values, list) and value in valid_values: valid = True return valid
class Parameter(dict): def __init__(self, name, value=None, valid_values=None, info=None, visible=False): ''' Parameter(name, value, valid_values, info) Parameter(name, value, valid_values) Parameter(name, value) Parameter({name: value}) Future updates: Parameter({name1: value1, name2: value2}) Parameter([p1, p2]), where p1 and p2 are parameter objects Args: name: name of parameter value: value of parameter can be any basic type or a list valid_values: defines which values are accepted for value can be a type or a list if not provided => type(value) info: description of parameter, if not provided => empty string visible: boolean if true always show parameter if false hide it ''' pass def __setitem__(self, key, value): ''' overwrites the standard dictionary and checks if value is valid Args: key: dictionary key value: dictionary value ''' pass def update(self, *args): ''' updates the values of the parameter, just as a regular dictionary ''' pass @property def visible(self): ''' Returns: if parameter should be shown (False) or hidden (True) in the GUI ''' pass @property def valid_values(self): ''' Returns: valid value of the paramerer (a type like int, float or a list) ''' pass @property def info(self): ''' Returns: a text describing the paramter ''' pass @staticmethod def is_valid(value, valid_values): ''' check is the value is valid Args: value: value to be tested valid_values: allowed valid values (type or list of values) Returns: ''' pass
12
7
21
4
11
7
4
0.59
1
8
0
0
6
3
7
34
160
34
80
22
68
47
67
18
59
12
2
4
29
144,541
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/main_window.py
pylabcontrol.gui.windows_and_widgets.main_window.CustomEditorFactory
class CustomEditorFactory(QtWidgets.QItemEditorFactory): def createEditor(self, type, QWidget): if type == QtCore.QVariant.Double or type == QtCore.QVariant.Int: spin_box = QtWidgets.QLineEdit(QWidget) return spin_box if type == QtCore.QVariant.List or type == QtCore.QVariant.StringList: combo_box = QtWidgets.QComboBox(QWidget) combo_box.setFocusPolicy(QtCore.Qt.StrongFocus) return combo_box else: return super(CustomEditorFactory, self).createEditor(type, QWidget)
class CustomEditorFactory(QtWidgets.QItemEditorFactory): def createEditor(self, type, QWidget): pass
2
0
12
2
10
0
3
0
1
1
0
0
1
0
1
1
13
2
11
4
9
0
10
4
8
3
1
1
3
144,542
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/scripts/script_dummy.py
scripts.script_dummy.DummyPlantWithControler
class DummyPlantWithControler(Script): """ script to bring the detector response to zero two channels are set to a fixed voltage while the signal of the third channel is varied until the detector response is zero """ _DEFAULT_SETTINGS = [ Parameter('sample rate', 0.5, float, 'sample rate in Hz'), Parameter('on/off', True, bool, 'control is on/off'), Parameter('buffer_length', 500, int, 'length of data buffer') ] _INSTRUMENTS = { 'plant': Plant, 'controler': PIControler } _SCRIPTS = { } def __init__(self, instruments, scripts = None, name=None, settings=None, log_function=None, data_path = None): """ Example of a script that emits a QT signal for the gui Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings """ Script.__init__(self, name, settings=settings, scripts=scripts, instruments=instruments, log_function=log_function, data_path = data_path) self.data = {'plant_output': deque(maxlen=self.settings['buffer_length']), 'control_output': deque(maxlen=self.settings['buffer_length'])} def _function(self): """ This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ """ plant = self.instruments['plant']['instance'] controler = self.instruments['controler']['instance'] plant.update(self.instruments['plant']['settings']) controler.update(self.instruments['controler']['settings']) time_step = 1./self.settings['sample rate'] controler.update({'time_step': time_step}) self.last_plot = datetime.datetime.now() controler.reset() # if length changed we have to redefine the queue and carry over the data if self.data['plant_output'].maxlen != self.settings['buffer_length']: plant_output = deepcopy(self.data['plant_output']) control_output = deepcopy(self.data['control_output']) self.data = {'plant_output': deque(maxlen=self.settings['buffer_length']), 'control_output': deque(maxlen=self.settings['buffer_length'])} x = list(range(min(len(plant_output), self.settings['buffer_length']))) x.reverse() for i in x: self.data['plant_output'].append(plant_output[-i-1]) self.data['control_output'].append(control_output[-i - 1]) while not self._abort: measurement = plant.output self.data['plant_output'].append(measurement) control_value = controler.controler_output(measurement) self.data['control_output'].append(control_value) if self.settings['on/off']: print(('set plant control', control_value)) plant.control = float(control_value) self.progress = 50 self.updateProgress.emit(self.progress) time.sleep(time_step) def _plot(self, axes_list): if len(self.data['plant_output']) >0: time_step = 1. / self.settings['sample rate'] axes1, axes2 = axes_list # plot time domain signals axes1.hold(False) signal = self.data['plant_output'] control_value = self.data['control_output'] t = np.linspace(0, len(signal)*time_step, len(signal)) axes1.plot(t, signal, '-o') axes1.hold(True) axes1.plot(t, control_value, '-o') axes1.set_title('time signal') axes1.set_xlabel('time (s)') # only plot spectra if there is a sufficiently long signal and only refresh after 5 seconds if (len(signal)>2 and (datetime.datetime.now()-self.last_plot).total_seconds() > 5) or self.is_running is False: # plot freq domain signals axes2.hold(False) f, psd = power_spectral_density(signal, time_step) axes2.loglog(f, psd, '-o') axes2.hold(True) f, psd = power_spectral_density(control_value, time_step) axes2.loglog(f, psd, '-o') axes2.set_title('spectra') axes1.set_xlabel('frequency (Hz)') self.last_plot = datetime.datetime.now()
class DummyPlantWithControler(Script): ''' script to bring the detector response to zero two channels are set to a fixed voltage while the signal of the third channel is varied until the detector response is zero ''' def __init__(self, instruments, scripts = None, name=None, settings=None, log_function=None, data_path = None): ''' Example of a script that emits a QT signal for the gui Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings ''' pass def _function(self): ''' This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ ''' pass def _plot(self, axes_list): pass
4
3
30
7
19
5
3
0.26
1
4
0
0
3
3
3
52
118
31
69
25
65
18
59
25
55
5
2
2
9
144,543
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/main_window.py
pylabcontrol.gui.windows_and_widgets.main_window.CustomEventFilter
class CustomEventFilter(QtCore.QObject): def eventFilter(self, QObject, QEvent): if (QEvent.type() == QtCore.QEvent.Wheel): QEvent.ignore() return True return QtWidgets.QWidget.eventFilter(QObject, QEvent)
class CustomEventFilter(QtCore.QObject): def eventFilter(self, QObject, QEvent): pass
2
0
6
1
5
0
2
0
1
0
0
0
1
0
1
1
7
1
6
2
4
0
6
2
4
2
1
1
2
144,544
LISE-B26/pylabcontrol
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LISE-B26_pylabcontrol/tests/test_parameter.py
tests.test_parameter.TestParameter
class TestParameter(TestCase): def test_parameter_single(self): # init p0 = Parameter('param', 0, int, 'integer') # print(p0.info) self.assertEqual(p0.info['param'], 'integer') p0 = Parameter('param', 0.0, float, 'float') p0 = Parameter('param', '0', str, 'string') p0 = Parameter('param', 0, [0, 1, 2, 3], 'list') p0 = Parameter('param', 0) self.assertEqual(p0.valid_values['param'], int) p0 = Parameter('param', 0.0) self.assertEqual(p0.valid_values['param'], float) p0 = Parameter('param', '0') self.assertEqual(p0.valid_values['param'], str) p0 = Parameter('param', [0, 1, 2, 3]) self.assertEqual(p0.valid_values['param'], list) p0 = Parameter('param', 0, int, 'integer') self.assertEqual(p0, {'param': 0}) self.assertEqual(p0['param'], 0) p0 = Parameter({'param': 1}) self.assertEqual(p0, {'param': 1}) # update p0.update({'param': 2}) self.assertEqual(p0, {'param': 2}) with self.assertRaises(KeyError): p0.update({'paramX': 2}) with self.assertRaises(AssertionError): Parameter('param1', 0, [1, 2, 3]) with self.assertRaises(AssertionError): Parameter('pa', 2.2, int, 'type is int but value is float!') p0 = Parameter('param', [0, 1, 2, 3]) p0.update({'param': [0, 5]}) with self.assertRaises(AssertionError): p0.update({'param': 0}) def test_parameter_multi(self): # init p1 = Parameter('param1', 1) p2 = Parameter('param2', 2) p0 = Parameter('param0', [p1, p2]) self.assertEqual(p0, {'param0': {'param1': 1, 'param2': 2}}) # update p0['param0'] = {'param1': 3} self.assertEqual(p0, {'param0': {'param1': 3, 'param2': 2}}) self.assertEqual(p0['param0'], {'param1': 3, 'param2': 2}) self.assertEqual(p0['param0']['param1'], 3) with self.assertRaises(KeyError): p0.update({'param1': 4}) p0['param0'].update(Parameter('param2', 7)) self.assertEqual(p0['param0'], {'param1': 3, 'param2': 7}) p0['param0'].update({'param2': 8}) self.assertEqual(p0['param0'], {'param1': 3, 'param2': 8}) p0['param0'] = {'param1': 5, 'param2': 6} self.assertEqual(p0['param0'], {'param1': 5, 'param2': 6}) self.assertEqual(p0['param0']['param1'], 5) self.assertEqual(p0['param0']['param2'], 6) # p0['param0'].update(Parameter('param2', 's')) # # p0['param0'].update(Parameter('param3', 's')) # # p0['param0'].update({'param2', 's'}) with self.assertRaises(KeyError): print((p0['param3'])) p1 = Parameter('param1', 1) p2 = Parameter('param2', 2) p0 = Parameter('param0', [p1, p2]) with self.assertRaises(AssertionError): p0['param0'] = [0, 1] # asign list of different type p1 = Parameter('param1', 1) p2 = Parameter('param2', 2) p3 = Parameter('param2', 3) p0 = Parameter('param0', [p1, p2]) p0['param0'] = [p1, p3] with self.assertRaises(AssertionError): p1 = Parameter('param1', 1) p2 = Parameter('param2', 2) p3 = Parameter('param3', 3) p0 = Parameter('param0', [p1, p2]) p0['param0'] = [p1, p3] with self.assertRaises(AssertionError): p1 = Parameter('param1', 1) p2 = Parameter('param2', 2) p3 = Parameter('param2', 's') p0 = Parameter('param0', [p1, p2]) p0['param0'] = [p1, p3] def test_parameter_multi_v2(self): ''' test for next generation parameter object Args: self: Returns: ''' p0 = Parameter({'p1': 1, 'p2': 2}) self.assertEqual(p0, {'p2': 2, 'p1': 1}) with self.assertRaises(KeyError): p0['p3'] with self.assertRaises(KeyError): p0.update({'p3': 2}) with self.assertRaises(AssertionError): p0.update({'p1': 2.0}) p0 = Parameter('p0', 0) p1 = Parameter('p1', 1) p2 = Parameter([p0, p1]) self.assertEqual(p2, {'p0': 0, 'p1': 1}) p2['p0'] = 44 self.assertEqual(p2, {'p0': 44, 'p1': 1}) p2.update({'p0': 45}) self.assertEqual(p2, {'p0': 45, 'p1': 1}) p0['p0'] = 555 p2.update(p0) self.assertEqual(p2, {'p0': 555, 'p1': 1}) # check for nested parameters p0 = Parameter('p0', 0, int, 'test parameter (int)') p1 = Parameter('p1', 'string', str, 'test parameter (str)') p2 = Parameter('p2', 0.0, float, 'test parameter (float)') p12 = Parameter('p12', [p1, p2]) pall = Parameter([p0, p12]) self.assertEqual(pall, {'p0': 0, 'p12': {'p2': 0.0, 'p1': 'string'}}) parameters = Parameter([ Parameter('test1', 0, int, 'test parameter (int)'), Parameter('test2', [Parameter('test2_1', 'string', str, 'test parameter (str)'), Parameter('test2_2', 0.0, float, 'test parameter (float)') ]) ]) self.assertIsInstance(parameters['test2'], Parameter) with self.assertRaises(AssertionError): parameters['test1'] = 0.2 with self.assertRaises(AssertionError): parameters['test2'] = 0.2 with self.assertRaises(AssertionError): parameters['test2']['test2_1'] = 0.2 with self.assertRaises(AssertionError): parameters['test2']['test2_2'] = 's' def test_info(self): p0 = Parameter('test', 0, int, 'some info') self.assertEqual(p0.info['test'], 'some info') parameters = Parameter([ Parameter('test1', 0, int, 'test parameter (int)'), Parameter('test2', [Parameter('test2_1', 'string', str, 'test parameter (str)'), Parameter('test2_2', 0.0, float, 'test parameter (float)') ]) ]) print((parameters.info)) print((parameters['test1'].info)) self.assertEqual(parameters.info['test2'], { 'test2_1': 'test parameter (str)', 'test2_2': 'test parameter (float)'}) self.assertEqual(parameters.info['test1'], 'test parameter (int)') self.assertEqual(parameters.info['test2'] ['test2_1'], 'test parameter (str)')
class TestParameter(TestCase): def test_parameter_single(self): pass def test_parameter_multi(self): pass def test_parameter_multi_v2(self): ''' test for next generation parameter object Args: self: Returns: ''' pass def test_info(self): pass
5
1
57
20
33
5
1
0.14
1
6
0
0
4
0
4
76
239
90
132
18
127
18
120
18
115
1
2
1
4
144,545
LISE-B26/pylabcontrol
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/manual_fitting_ensemble.py
pylabcontrol.gui.windows_and_widgets.manual_fitting_ensemble.FittingWindow.do_fit
class do_fit(QObject): finished = pyqtSignal() # signals the end of the script status = pyqtSignal(str) # sends messages to update the statusbar NUM_ESR_LINES = 8 def __init__(self, filepath, plotwidget, queue, peak_vals, interps): QObject.__init__(self) self.filepath = filepath self.plotwidget = plotwidget self.queue = queue self.peak_vals = peak_vals self.interps = interps def save(self): def freqs(index): return self.frequencies[0] + (self.frequencies[-1]-self.frequencies[0])/(len(self.frequencies)-1)*index save_path = os.path.join(self.filepath, 'line_data.csv') data = list() for i in range(0, self.NUM_ESR_LINES): data.append(list()) for i in range(0, self.NUM_ESR_LINES): indices = self.interps[i](self.x_range) data[i] = [freqs(indices[j]) for j in range(0, len(self.x_range))] df = pd.DataFrame(data) df = df.transpose() df.to_csv(save_path) self.plotwidget.figure.savefig(self.filepath + './lines.jpg') def run(self): data_esr = [] for f in sorted(glob.glob(os.path.join(self.filepath, './data_subscripts/*'))): data = Script.load_data(f) data_esr.append(data['data']) self.frequencies = data['frequency'] data_esr_norm = [] for d in data_esr: data_esr_norm.append(d / np.mean(d)) self.x_range = list(range(0, len(data_esr_norm))) self.status.emit('executing manual fitting') index = 0 # for data in data_array: while index < self.NUM_ESR_LINES: # this must be after the draw command, otherwise plot doesn't display for some reason self.status.emit('executing manual fitting NV #' + str(index)) self.plotwidget.axes.clear() self.plotwidget.axes.imshow( data_esr_norm, aspect='auto', origin='lower') if self.interps: for f in self.interps: self.plotwidget.axes.plot( f(self.x_range), self.x_range) self.plotwidget.draw() while (True): if self.queue.empty(): time.sleep(.5) else: value = self.queue.get() if value == 'next': while not self.peak_vals == []: self.peak_vals.pop(-1) # if len(self.single_fit) == 1: # self.fits[index] = self.single_fit # else: # self.fits[index] = [y for x in self.single_fit for y in x] index += 1 self.interps.append(f) break elif value == 'clear': self.plotwidget.axes.clear() self.plotwidget.axes.imshow( data_esr_norm, aspect='auto', origin='lower') if self.interps: for f in self.interps: self.plotwidget.axes.plot( f(self.x_range), self.x_range) self.plotwidget.draw() elif value == 'fit': peak_vals = sorted( self.peak_vals, key=lambda tup: tup[1]) y, x = list(zip(*peak_vals)) f = UnivariateSpline(np.array(x), np.array(y)) x_range = list(range(0, len(data_esr_norm))) self.plotwidget.axes.plot(f(x_range), x_range) self.plotwidget.draw() elif value == 'prev': index -= 1 break elif value == 'skip': index += 1 break elif type(value) is int: index = int(value) break self.finished.emit() self.status.emit('saving') self.plotwidget.axes.clear() self.plotwidget.axes.imshow( data_esr_norm, aspect='auto', origin='lower') if self.interps: for f in self.interps: self.plotwidget.axes.plot(f(self.x_range), self.x_range) self.save() self.status.emit('saving finished')
class do_fit(QObject): def __init__(self, filepath, plotwidget, queue, peak_vals, interps): pass def save(self): pass def freqs(index): pass def run(self): pass
5
0
25
2
22
2
6
0.1
1
7
1
0
3
7
3
3
105
11
88
30
83
9
82
30
77
19
1
6
24
144,546
LISE-B26/pylabcontrol
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/manual_fitting.py
pylabcontrol.gui.windows_and_widgets.manual_fitting.FittingWindow.do_fit
class do_fit(QObject): """ This class does all of the work of the manual fitting, including loading and saving data, processing input, and displaying output to the plots. It is implemented as a separate class so that it can be easily moved to a second thread. If it is on the same thread as the gui, you can't both run this code and still interact with the gui. Thus, the second thread allows both to occur simultaneously. """ finished = pyqtSignal() # signals the end of the script status = pyqtSignal(str) # sends messages to update the statusbar def __init__(self, filepath, plotwidget, queue, peak_vals, peak_locs): """ Initializes the fit class :param filepath: path to file containing the ESR data to fit :param plotwidget: reference to plotwidget passed from gui :param queue: thread-safe queue used for gui-class communication across threads :param peak_vals: peak locations manually selected in gui :param peak_locs: pointer to textbox that will contain locations of fit peaks """ QObject.__init__(self) self.filepath = filepath self.plotwidget = plotwidget self.queue = queue self.peak_vals = peak_vals self.peak_locs = peak_locs def n_lorentzian(self, x, offset, *peak_params): """ Defines a lorentzian with n peaks :param x: independent variable :param offset: offset of lorentzians :param peak_params: this is a flattened array of length 3n with the format [widths amplitudes centers], that is the first n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: the output of the lorentzian for each input value x """ value = 0 width_array = peak_params[:len(peak_params)/3] amplitude_array = peak_params[len( peak_params)/3:2*len(peak_params)/3] center_array = peak_params[2*len(peak_params)/3:] for width, amplitude, center in zip(width_array, amplitude_array, center_array): value += amplitude * \ np.square(0.5 * width) / \ (np.square(x - center) + np.square(0.5 * width)) value += offset return value def fit_n_lorentzian(self, x, y, fit_start_params=None): """ uses scipy.optimize.curve_fit to fit an n-peak lorentzian to the data, where the number of peaks is determined by the number of peaks given as starting parameters for the fit :param x: :param y: :param fit_start_params: this is a flattened array of length 3n + 1 with the format [offset widths amplitudes centers], that is the first value is hte offset, the next n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: optimized fit values, in the same format as fit_start_params """ popt, _ = scipy.optimize.curve_fit( self.n_lorentzian, x, y, fit_start_params) return popt def save(self): """ Saves the fit data to the data filepath + 'data-manual.csv'. The saving format has one line corresponding to each peak, with the corresponding nv number, fit center, width, and amplitude, and manual center and amplitude included """ save_path = os.path.join(self.filepath, 'data-manual.csv') self.fits.to_csv(save_path, index=False) def load_fitdata(self): """ Tries to load and return the previous results of save, or if this file has not been previously analyzed, returns a DataFrame with the correct headers and no data :return: the loaded (or new) pandas DataFrame """ load_path = os.path.join(self.filepath, 'data-manual.csv') if os.path.exists(load_path): fits = pd.read_csv(load_path) else: fits = pd.DataFrame({'nv_id': [], 'peak_id': [], 'offset': [], 'fit_center': [], 'fit_amplitude': [], 'fit_width': [], 'manual_center': [], 'manual_height': []}) return fits def run(self): """ Code to run fitting routine. Should be run in a separate thread from the gui. """ esr_folders = glob.glob(os.path.join( self.filepath, './data_subscripts/*esr*')) data_array = [] self.status.emit('loading data') for esr_folder in esr_folders[:-1]: data = Script.load_data(esr_folder) data_array.append(data) self.fits = self.load_fitdata() self.status.emit('executing manual fitting') index = 0 self.last_good = [] self.initial_fit = False # for data in data_array: while index < len(data_array): data = data_array[index] # this must be after the draw command, otherwise plot doesn't display for some reason self.status.emit('executing manual fitting NV #' + str(index)) self.plotwidget.axes.clear() self.plotwidget.axes.plot(data['frequency'], data['data']) if index in self.fits['nv_id'].values: fitdf = self.fits.loc[(self.fits['nv_id'] == index)] offset = fitdf['offset'].as_matrix()[0] centers = fitdf['fit_center'].as_matrix() amplitudes = fitdf['fit_amplitude'].as_matrix() widths = fitdf['fit_width'].as_matrix() fit_params = np.concatenate( (np.concatenate((widths, amplitudes)), centers)) self.plotwidget.axes.plot(data['frequency'], self.n_lorentzian( data['frequency'], *np.concatenate(([offset], fit_params)))) self.plotwidget.draw() if not self.last_good == []: self.initial_fit = True self.queue.put('fit') while (True): if self.queue.empty(): time.sleep(.5) else: value = self.queue.get() if value == 'next': while not self.peak_vals == []: self.last_good.append(self.peak_vals.pop(-1)) if self.single_fit: to_delete = np.where( self.fits['nv_id'].values == index) # print(self.fits[to_delete]) self.fits = self.fits.drop( self.fits.index[to_delete]) # for val in to_delete[0][::-1]: # for key in self.fits.keys(): # del self.fits[key][val] for peak in self.single_fit: self.fits = self.fits.append( pd.DataFrame(peak)) index += 1 self.status.emit('saving') self.save() break elif value == 'clear': self.last_good = [] self.plotwidget.axes.clear() self.plotwidget.axes.plot( data['frequency'], data['data']) self.plotwidget.draw() elif value == 'fit': if self.initial_fit: input = self.last_good else: input = self.peak_vals if len(input) > 1: centers, heights = list(zip(*input)) widths = 1e7 * np.ones(len(heights)) elif len(input) == 1: centers, heights = input[0] widths = 1e7 elif len(input) == 0: self.single_fit = None self.peak_locs.setText('No Peak') self.plotwidget.axes.plot(data['frequency'], np.repeat( np.mean(data['data']), len(data['frequency']))) self.plotwidget.draw() continue offset = np.mean(data['data']) amplitudes = offset-np.array(heights) if len(input) > 1: fit_start_params = [[offset], np.concatenate( (widths, amplitudes, centers))] fit_start_params = [ y for x in fit_start_params for y in x] elif len(input) == 1: fit_start_params = [ offset, widths, amplitudes, centers] try: popt = self.fit_n_lorentzian( data['frequency'], data['data'], fit_start_params=fit_start_params) except RuntimeError: print('fit failed, optimal parameters not found') break self.plotwidget.axes.clear() self.plotwidget.axes.plot( data['frequency'], data['data']) self.plotwidget.axes.plot( data['frequency'], self.n_lorentzian(data['frequency'], *popt)) self.plotwidget.draw() params = popt[1:] widths_array = params[:len(params)/3] amplitude_array = params[len( params)/3: 2 * len(params) / 3] center_array = params[2 * len(params) / 3:] positions = list( zip(center_array, amplitude_array, widths_array)) self.single_fit = [] peak_index = 0 for position in positions: self.single_fit.append({'nv_id': [index], 'peak_id': [peak_index], 'offset': [popt[0]], 'fit_center': [position[0]], 'fit_amplitude': [ position[1]], 'fit_width': [position[2]], 'manual_center': [input[peak_index][0]], 'manual_height': [input[peak_index][1]]}) peak_index += 1 self.peak_locs.setText( 'Peak Positions: ' + str(center_array)) self.initial_fit = False elif value == 'prev': index -= 1 break elif value == 'skip': index += 1 break elif type(value) is int: index = int(value) break self.finished.emit() self.status.emit('dataset finished')
class do_fit(QObject): ''' This class does all of the work of the manual fitting, including loading and saving data, processing input, and displaying output to the plots. It is implemented as a separate class so that it can be easily moved to a second thread. If it is on the same thread as the gui, you can't both run this code and still interact with the gui. Thus, the second thread allows both to occur simultaneously. ''' def __init__(self, filepath, plotwidget, queue, peak_vals, peak_locs): ''' Initializes the fit class :param filepath: path to file containing the ESR data to fit :param plotwidget: reference to plotwidget passed from gui :param queue: thread-safe queue used for gui-class communication across threads :param peak_vals: peak locations manually selected in gui :param peak_locs: pointer to textbox that will contain locations of fit peaks ''' pass def n_lorentzian(self, x, offset, *peak_params): ''' Defines a lorentzian with n peaks :param x: independent variable :param offset: offset of lorentzians :param peak_params: this is a flattened array of length 3n with the format [widths amplitudes centers], that is the first n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: the output of the lorentzian for each input value x ''' pass def fit_n_lorentzian(self, x, y, fit_start_params=None): ''' uses scipy.optimize.curve_fit to fit an n-peak lorentzian to the data, where the number of peaks is determined by the number of peaks given as starting parameters for the fit :param x: :param y: :param fit_start_params: this is a flattened array of length 3n + 1 with the format [offset widths amplitudes centers], that is the first value is hte offset, the next n values are the n peak widths, the next n are the n amplitudes, and the last n are the n centers :return: optimized fit values, in the same format as fit_start_params ''' pass def save(self): ''' Saves the fit data to the data filepath + 'data-manual.csv'. The saving format has one line corresponding to each peak, with the corresponding nv number, fit center, width, and amplitude, and manual center and amplitude included ''' pass def load_fitdata(self): ''' Tries to load and return the previous results of save, or if this file has not been previously analyzed, returns a DataFrame with the correct headers and no data :return: the loaded (or new) pandas DataFrame ''' pass def run(self): ''' Code to run fitting routine. Should be run in a separate thread from the gui. ''' pass
7
7
32
1
23
8
5
0.4
1
7
1
0
6
9
6
6
206
13
140
52
133
56
128
51
121
24
1
6
31
144,547
LISE-B26/pylabcontrol
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/gui/load_dialog.py
gui.load_dialog.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(857, 523) self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) self.buttonBox.setGeometry(QtCore.QRect(509, 476, 341, 32)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.horizontalLayoutWidget = QtWidgets.QWidget(Dialog) self.horizontalLayoutWidget.setGeometry(QtCore.QRect(9, 436, 841, 31)) self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget") self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize) self.horizontalLayout.setContentsMargins(1, 4, 0, 4) self.horizontalLayout.setSpacing(7) self.horizontalLayout.setObjectName("horizontalLayout") self.tree_infile = QtWidgets.QTreeView(Dialog) self.tree_infile.setGeometry(QtCore.QRect(270, 30, 256, 261)) self.tree_infile.setAcceptDrops(True) self.tree_infile.setDragEnabled(True) self.tree_infile.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.tree_infile.setDefaultDropAction(QtCore.Qt.MoveAction) self.tree_infile.setUniformRowHeights(True) self.tree_infile.setWordWrap(True) self.tree_infile.setObjectName("tree_infile") self.tree_loaded = QtWidgets.QTreeView(Dialog) self.tree_loaded.setGeometry(QtCore.QRect(10, 30, 256, 261)) self.tree_loaded.setAcceptDrops(True) self.tree_loaded.setFrameShape(QtWidgets.QFrame.StyledPanel) self.tree_loaded.setFrameShadow(QtWidgets.QFrame.Sunken) self.tree_loaded.setDragEnabled(True) self.tree_loaded.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.tree_loaded.setDefaultDropAction(QtCore.Qt.MoveAction) self.tree_loaded.setWordWrap(True) self.tree_loaded.setObjectName("tree_loaded") self.lbl_info = QtWidgets.QLabel(Dialog) self.lbl_info.setGeometry(QtCore.QRect(540, 30, 311, 261)) self.lbl_info.setFrameShape(QtWidgets.QFrame.Box) self.lbl_info.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.lbl_info.setWordWrap(True) self.lbl_info.setObjectName("lbl_info") self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(20, 10, 241, 16)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(280, 10, 241, 16)) self.label_2.setObjectName("label_2") self.btn_open = QtWidgets.QPushButton(Dialog) self.btn_open.setGeometry(QtCore.QRect(774, 440, 75, 23)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btn_open.sizePolicy().hasHeightForWidth()) self.btn_open.setSizePolicy(sizePolicy) self.btn_open.setObjectName("btn_open") self.lbl_probe_log_path = QtWidgets.QLabel(Dialog) self.lbl_probe_log_path.setGeometry(QtCore.QRect(10, 440, 22, 23)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lbl_probe_log_path.sizePolicy().hasHeightForWidth()) self.lbl_probe_log_path.setSizePolicy(sizePolicy) self.lbl_probe_log_path.setObjectName("lbl_probe_log_path") self.txt_probe_log_path = QtWidgets.QLineEdit(Dialog) self.txt_probe_log_path.setGeometry(QtCore.QRect(39, 440, 728, 23)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.txt_probe_log_path.sizePolicy().hasHeightForWidth()) self.txt_probe_log_path.setSizePolicy(sizePolicy) self.txt_probe_log_path.setObjectName("txt_probe_log_path") self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setGeometry(QtCore.QRect(20, 290, 241, 16)) self.label_3.setObjectName("label_3") self.tree_script_sequence = QtWidgets.QTreeView(Dialog) self.tree_script_sequence.setGeometry(QtCore.QRect(10, 310, 261, 121)) self.tree_script_sequence.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) self.tree_script_sequence.setAcceptDrops(True) self.tree_script_sequence.setDragEnabled(True) self.tree_script_sequence.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.tree_script_sequence.setDefaultDropAction(QtCore.Qt.MoveAction) self.tree_script_sequence.setObjectName("tree_script_sequence") self.btn_script_sequence = QtWidgets.QPushButton(Dialog) self.btn_script_sequence.setGeometry(QtCore.QRect(280, 380, 111, 41)) self.btn_script_sequence.setObjectName("btn_script_sequence") self.cmb_looping_variable = QtWidgets.QComboBox(Dialog) self.cmb_looping_variable.setGeometry(QtCore.QRect(280, 350, 111, 22)) self.cmb_looping_variable.setObjectName("cmb_looping_variable") self.txt_info = QtWidgets.QTextEdit(Dialog) self.txt_info.setGeometry(QtCore.QRect(540, 300, 301, 131)) self.txt_info.setObjectName("txt_info") self.txt_script_sequence_name = QtWidgets.QLineEdit(Dialog) self.txt_script_sequence_name.setGeometry(QtCore.QRect(280, 320, 113, 20)) self.txt_script_sequence_name.setObjectName("txt_script_sequence_name") self.retranslateUi(Dialog) self.buttonBox.accepted.connect(Dialog.accept) self.buttonBox.rejected.connect(Dialog.reject) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Loading...")) self.lbl_info.setText(_translate("Dialog", "info")) self.label.setText(_translate("Dialog", "Selected")) self.label_2.setText(_translate("Dialog", "Not Selected")) self.btn_open.setText(_translate("Dialog", "open")) self.lbl_probe_log_path.setText(_translate("Dialog", "Path")) self.txt_probe_log_path.setText(_translate("Dialog", "Z:\\Lab\\Cantilever\\Measurements")) self.label_3.setText(_translate("Dialog", "Script Sequence")) self.btn_script_sequence.setText(_translate("Dialog", "Add Script Sequence")) self.txt_info.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Enter docstring here</span></p></body></html>")) self.txt_script_sequence_name.setText(_translate("Dialog", "DefaultName"))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
58
1
58
0
1
0
1
0
0
0
2
17
2
2
118
2
116
22
113
0
112
22
109
1
1
0
2