id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
229,200
onnx/onnxmltools
onnxutils/onnxconverter_common/shape_calculator.py
calculate_linear_classifier_output_shapes
def calculate_linear_classifier_output_shapes(operator): ''' This operator maps an input feature vector into a scalar label if the number of outputs is one. If two outputs appear in this operator's output list, we should further generate a map storing all classes' probabilities. Allowed input/output patterns are 1. [N, C] ---> [N, 1], A sequence of map Note that the second case is not allowed as long as ZipMap only produces dictionary. ''' check_input_and_output_numbers(operator, input_count_range=1, output_count_range=[1, 2]) check_input_and_output_types(operator, good_input_types=[FloatTensorType, Int64TensorType]) if len(operator.inputs[0].type.shape) != 2: raise RuntimeError('Input must be a [N, C]-tensor') N = operator.inputs[0].type.shape[0] class_labels = operator.raw_operator.classes_ if all(isinstance(i, np.ndarray) for i in class_labels): class_labels = np.concatenate(class_labels) if all(isinstance(i, (six.string_types, six.text_type)) for i in class_labels): operator.outputs[0].type = StringTensorType(shape=[N]) if len(class_labels) > 2 or operator.type != 'SklearnLinearSVC': # For multi-class classifier, we produce a map for encoding the probabilities of all classes if operator.target_opset < 7: operator.outputs[1].type = DictionaryType(StringTensorType([1]), FloatTensorType([1])) else: operator.outputs[1].type = SequenceType(DictionaryType(StringTensorType([]), FloatTensorType([])), N) else: # For binary LinearSVC, we produce probability of the positive class operator.outputs[1].type = FloatTensorType(shape=[N, 1]) elif all(isinstance(i, (numbers.Real, bool, np.bool_)) for i in class_labels): operator.outputs[0].type = Int64TensorType(shape=[N]) if len(class_labels) > 2 or operator.type != 'SklearnLinearSVC': # For multi-class classifier, we produce a map for encoding the probabilities of all classes if operator.target_opset < 7: operator.outputs[1].type = DictionaryType(Int64TensorType([1]), FloatTensorType([1])) else: operator.outputs[1].type = SequenceType(DictionaryType(Int64TensorType([]), FloatTensorType([])), N) else: # For binary LinearSVC, we produce probability of the positive class operator.outputs[1].type = FloatTensorType(shape=[N, 1]) else: raise ValueError('Unsupported or mixed label types')
python
def calculate_linear_classifier_output_shapes(operator): ''' This operator maps an input feature vector into a scalar label if the number of outputs is one. If two outputs appear in this operator's output list, we should further generate a map storing all classes' probabilities. Allowed input/output patterns are 1. [N, C] ---> [N, 1], A sequence of map Note that the second case is not allowed as long as ZipMap only produces dictionary. ''' check_input_and_output_numbers(operator, input_count_range=1, output_count_range=[1, 2]) check_input_and_output_types(operator, good_input_types=[FloatTensorType, Int64TensorType]) if len(operator.inputs[0].type.shape) != 2: raise RuntimeError('Input must be a [N, C]-tensor') N = operator.inputs[0].type.shape[0] class_labels = operator.raw_operator.classes_ if all(isinstance(i, np.ndarray) for i in class_labels): class_labels = np.concatenate(class_labels) if all(isinstance(i, (six.string_types, six.text_type)) for i in class_labels): operator.outputs[0].type = StringTensorType(shape=[N]) if len(class_labels) > 2 or operator.type != 'SklearnLinearSVC': # For multi-class classifier, we produce a map for encoding the probabilities of all classes if operator.target_opset < 7: operator.outputs[1].type = DictionaryType(StringTensorType([1]), FloatTensorType([1])) else: operator.outputs[1].type = SequenceType(DictionaryType(StringTensorType([]), FloatTensorType([])), N) else: # For binary LinearSVC, we produce probability of the positive class operator.outputs[1].type = FloatTensorType(shape=[N, 1]) elif all(isinstance(i, (numbers.Real, bool, np.bool_)) for i in class_labels): operator.outputs[0].type = Int64TensorType(shape=[N]) if len(class_labels) > 2 or operator.type != 'SklearnLinearSVC': # For multi-class classifier, we produce a map for encoding the probabilities of all classes if operator.target_opset < 7: operator.outputs[1].type = DictionaryType(Int64TensorType([1]), FloatTensorType([1])) else: operator.outputs[1].type = SequenceType(DictionaryType(Int64TensorType([]), FloatTensorType([])), N) else: # For binary LinearSVC, we produce probability of the positive class operator.outputs[1].type = FloatTensorType(shape=[N, 1]) else: raise ValueError('Unsupported or mixed label types')
[ "def", "calculate_linear_classifier_output_shapes", "(", "operator", ")", ":", "check_input_and_output_numbers", "(", "operator", ",", "input_count_range", "=", "1", ",", "output_count_range", "=", "[", "1", ",", "2", "]", ")", "check_input_and_output_types", "(", "op...
This operator maps an input feature vector into a scalar label if the number of outputs is one. If two outputs appear in this operator's output list, we should further generate a map storing all classes' probabilities. Allowed input/output patterns are 1. [N, C] ---> [N, 1], A sequence of map Note that the second case is not allowed as long as ZipMap only produces dictionary.
[ "This", "operator", "maps", "an", "input", "feature", "vector", "into", "a", "scalar", "label", "if", "the", "number", "of", "outputs", "is", "one", ".", "If", "two", "outputs", "appear", "in", "this", "operator", "s", "output", "list", "we", "should", "...
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/shape_calculator.py#L17-L60
229,201
onnx/onnxmltools
onnxmltools/utils/utils_backend.py
is_backend_enabled
def is_backend_enabled(backend): """ Tells if a backend is enabled. """ if backend == "onnxruntime": try: import onnxruntime return True except ImportError: return False else: raise NotImplementedError("Not implemented for backend '{0}'".format(backend))
python
def is_backend_enabled(backend): if backend == "onnxruntime": try: import onnxruntime return True except ImportError: return False else: raise NotImplementedError("Not implemented for backend '{0}'".format(backend))
[ "def", "is_backend_enabled", "(", "backend", ")", ":", "if", "backend", "==", "\"onnxruntime\"", ":", "try", ":", "import", "onnxruntime", "return", "True", "except", "ImportError", ":", "return", "False", "else", ":", "raise", "NotImplementedError", "(", "\"Not...
Tells if a backend is enabled.
[ "Tells", "if", "a", "backend", "is", "enabled", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/utils/utils_backend.py#L40-L51
229,202
onnx/onnxmltools
onnxmltools/convert/sparkml/operator_converters/string_indexer.py
calculate_sparkml_string_indexer_output_shapes
def calculate_sparkml_string_indexer_output_shapes(operator): ''' This function just copy the input shape to the output because label encoder only alters input features' values, not their shape. ''' check_input_and_output_numbers(operator, output_count_range=1) check_input_and_output_types(operator, good_input_types=[Int64TensorType, StringTensorType]) input_shape = copy.deepcopy(operator.inputs[0].type.shape) operator.outputs[0].type = Int64TensorType(input_shape)
python
def calculate_sparkml_string_indexer_output_shapes(operator): ''' This function just copy the input shape to the output because label encoder only alters input features' values, not their shape. ''' check_input_and_output_numbers(operator, output_count_range=1) check_input_and_output_types(operator, good_input_types=[Int64TensorType, StringTensorType]) input_shape = copy.deepcopy(operator.inputs[0].type.shape) operator.outputs[0].type = Int64TensorType(input_shape)
[ "def", "calculate_sparkml_string_indexer_output_shapes", "(", "operator", ")", ":", "check_input_and_output_numbers", "(", "operator", ",", "output_count_range", "=", "1", ")", "check_input_and_output_types", "(", "operator", ",", "good_input_types", "=", "[", "Int64TensorT...
This function just copy the input shape to the output because label encoder only alters input features' values, not their shape.
[ "This", "function", "just", "copy", "the", "input", "shape", "to", "the", "output", "because", "label", "encoder", "only", "alters", "input", "features", "values", "not", "their", "shape", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/sparkml/operator_converters/string_indexer.py#L33-L42
229,203
onnx/onnxmltools
onnxmltools/utils/utils_backend_onnxruntime.py
_post_process_output
def _post_process_output(res): """ Applies post processings before running the comparison such as changing type from list to arrays. """ if isinstance(res, list): if len(res) == 0: return res elif len(res) == 1: return _post_process_output(res[0]) elif isinstance(res[0], numpy.ndarray): return numpy.array(res) elif isinstance(res[0], dict): import pandas return pandas.DataFrame(res).values else: ls = [len(r) for r in res] mi = min(ls) if mi != max(ls): raise NotImplementedError("Unable to postprocess various number of outputs in [{0}, {1}]".format(min(ls), max(ls))) if mi > 1: output = [] for i in range(mi): output.append(_post_process_output([r[i] for r in res])) return output elif isinstance(res[0], list): # list of lists if isinstance(res[0][0], list): return numpy.array(res) elif len(res[0]) == 1 and isinstance(res[0][0], dict): return _post_process_output([r[0] for r in res]) elif len(res) == 1: return res else: if len(res[0]) != 1: raise NotImplementedError("Not conversion implemented for {0}".format(res)) st = [r[0] for r in res] return numpy.vstack(st) else: return res else: return res
python
def _post_process_output(res): if isinstance(res, list): if len(res) == 0: return res elif len(res) == 1: return _post_process_output(res[0]) elif isinstance(res[0], numpy.ndarray): return numpy.array(res) elif isinstance(res[0], dict): import pandas return pandas.DataFrame(res).values else: ls = [len(r) for r in res] mi = min(ls) if mi != max(ls): raise NotImplementedError("Unable to postprocess various number of outputs in [{0}, {1}]".format(min(ls), max(ls))) if mi > 1: output = [] for i in range(mi): output.append(_post_process_output([r[i] for r in res])) return output elif isinstance(res[0], list): # list of lists if isinstance(res[0][0], list): return numpy.array(res) elif len(res[0]) == 1 and isinstance(res[0][0], dict): return _post_process_output([r[0] for r in res]) elif len(res) == 1: return res else: if len(res[0]) != 1: raise NotImplementedError("Not conversion implemented for {0}".format(res)) st = [r[0] for r in res] return numpy.vstack(st) else: return res else: return res
[ "def", "_post_process_output", "(", "res", ")", ":", "if", "isinstance", "(", "res", ",", "list", ")", ":", "if", "len", "(", "res", ")", "==", "0", ":", "return", "res", "elif", "len", "(", "res", ")", "==", "1", ":", "return", "_post_process_output...
Applies post processings before running the comparison such as changing type from list to arrays.
[ "Applies", "post", "processings", "before", "running", "the", "comparison", "such", "as", "changing", "type", "from", "list", "to", "arrays", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/utils/utils_backend_onnxruntime.py#L165-L206
229,204
onnx/onnxmltools
onnxmltools/utils/utils_backend_onnxruntime.py
_create_column
def _create_column(values, dtype): "Creates a column from values with dtype" if str(dtype) == "tensor(int64)": return numpy.array(values, dtype=numpy.int64) elif str(dtype) == "tensor(float)": return numpy.array(values, dtype=numpy.float32) else: raise OnnxRuntimeAssertionError("Unable to create one column from dtype '{0}'".format(dtype))
python
def _create_column(values, dtype): "Creates a column from values with dtype" if str(dtype) == "tensor(int64)": return numpy.array(values, dtype=numpy.int64) elif str(dtype) == "tensor(float)": return numpy.array(values, dtype=numpy.float32) else: raise OnnxRuntimeAssertionError("Unable to create one column from dtype '{0}'".format(dtype))
[ "def", "_create_column", "(", "values", ",", "dtype", ")", ":", "if", "str", "(", "dtype", ")", "==", "\"tensor(int64)\"", ":", "return", "numpy", ".", "array", "(", "values", ",", "dtype", "=", "numpy", ".", "int64", ")", "elif", "str", "(", "dtype", ...
Creates a column from values with dtype
[ "Creates", "a", "column", "from", "values", "with", "dtype" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/utils/utils_backend_onnxruntime.py#L208-L215
229,205
onnx/onnxmltools
onnxmltools/convert/coreml/shape_calculators/neural_network/GRU.py
calculate_gru_output_shapes
def calculate_gru_output_shapes(operator): ''' See GRU's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 2], output_count_range=[1, 2]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operator.inputs[0].type.shape if len(input_shape) not in [2, 4]: raise RuntimeError('Input must be a [N, C]- or [N, C, 1, 1]-tensor') if operator.type == 'gru': params = operator.raw_operator.gru elif operator.type == 'simpleRecurrent': params = operator.raw_operator.simpleRecurrent else: raise RuntimeError('Only GRU and SimpleRNN are supported') # The following line is more accurate but it may break some tests # output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [2, params.outputVectorSize] output_shape = [input_shape[0] if params.sequenceOutput else 'None', params.outputVectorSize] # 'None' should be 1 state_shape = [1, params.outputVectorSize] # TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function if len(operator.inputs) > 1: Y_h_in = operator.inputs[1] # The initial hidden state of a single sequence Y_h_in.type.shape = state_shape operator.outputs[0].type.shape = output_shape if len(operator.outputs) > 1: operator.outputs[1].type.shape = state_shape
python
def calculate_gru_output_shapes(operator): ''' See GRU's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 2], output_count_range=[1, 2]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operator.inputs[0].type.shape if len(input_shape) not in [2, 4]: raise RuntimeError('Input must be a [N, C]- or [N, C, 1, 1]-tensor') if operator.type == 'gru': params = operator.raw_operator.gru elif operator.type == 'simpleRecurrent': params = operator.raw_operator.simpleRecurrent else: raise RuntimeError('Only GRU and SimpleRNN are supported') # The following line is more accurate but it may break some tests # output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [2, params.outputVectorSize] output_shape = [input_shape[0] if params.sequenceOutput else 'None', params.outputVectorSize] # 'None' should be 1 state_shape = [1, params.outputVectorSize] # TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function if len(operator.inputs) > 1: Y_h_in = operator.inputs[1] # The initial hidden state of a single sequence Y_h_in.type.shape = state_shape operator.outputs[0].type.shape = output_shape if len(operator.outputs) > 1: operator.outputs[1].type.shape = state_shape
[ "def", "calculate_gru_output_shapes", "(", "operator", ")", ":", "check_input_and_output_numbers", "(", "operator", ",", "input_count_range", "=", "[", "1", ",", "2", "]", ",", "output_count_range", "=", "[", "1", ",", "2", "]", ")", "check_input_and_output_types"...
See GRU's conversion function for its output shapes.
[ "See", "GRU", "s", "conversion", "function", "for", "its", "output", "shapes", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/shape_calculators/neural_network/GRU.py#L12-L43
229,206
onnx/onnxmltools
onnxutils/onnxconverter_common/optimizer.py
Solution.delete_node_nto1
def delete_node_nto1(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] """ delete the node which has n-input and 1-output """ if begin is None: assert node is not None begin = node.precedence elif not isinstance(begin, list): begin = [begin] if end.in_or_out: # if the end is output node, the output name will be kept to avoid the model output name updating. for nb_ in begin: nb_.out_redirect(node.single_input, node.single_output) else: for nb_ in begin: target_var_name = node.single_input assert target_var_name in nb_.output.values() # since the output info never be updated, except the final. end.in_redirect(node.single_output, target_var_name) for nb_ in begin: nb_.successor = [end if v_ == node else v_ for v_ in nb_.successor] end.precedence = [v_ for v_ in end.precedence if v_ != node] + node.precedence node_list.remove(node) return node_list
python
def delete_node_nto1(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] if begin is None: assert node is not None begin = node.precedence elif not isinstance(begin, list): begin = [begin] if end.in_or_out: # if the end is output node, the output name will be kept to avoid the model output name updating. for nb_ in begin: nb_.out_redirect(node.single_input, node.single_output) else: for nb_ in begin: target_var_name = node.single_input assert target_var_name in nb_.output.values() # since the output info never be updated, except the final. end.in_redirect(node.single_output, target_var_name) for nb_ in begin: nb_.successor = [end if v_ == node else v_ for v_ in nb_.successor] end.precedence = [v_ for v_ in end.precedence if v_ != node] + node.precedence node_list.remove(node) return node_list
[ "def", "delete_node_nto1", "(", "node_list", ",", "begin", ",", "node", ",", "end", ")", ":", "# type: ([],LinkedNode, LinkedNode, LinkedNode)->[]", "if", "begin", "is", "None", ":", "assert", "node", "is", "not", "None", "begin", "=", "node", ".", "precedence",...
delete the node which has n-input and 1-output
[ "delete", "the", "node", "which", "has", "n", "-", "input", "and", "1", "-", "output" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/optimizer.py#L262-L287
229,207
onnx/onnxmltools
onnxutils/onnxconverter_common/optimizer.py
Solution.delete_node_1ton
def delete_node_1ton(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] """ delete the node which has 1-input and n-output """ if end is None: assert end is not None end = node.successor elif not isinstance(end, list): end = [end] if any(e_.in_or_out for e_ in end): # if the end is output node, the output name will be kept to avoid the model output name updating. begin.out_redirect(node.single_input, node.single_output) else: for ne_ in end: target_var_name = node.single_input # since the output info never be updated, except the final. assert target_var_name in begin.output.values() ne_.in_redirect(node.single_output, target_var_name) begin.successor = [v_ for v_ in begin.successor if v_ != node] + node.successor for ne_ in end: ne_.precedence = [begin if v_ == node else v_ for v_ in ne_.precedence] node_list.remove(node) return node_list
python
def delete_node_1ton(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] if end is None: assert end is not None end = node.successor elif not isinstance(end, list): end = [end] if any(e_.in_or_out for e_ in end): # if the end is output node, the output name will be kept to avoid the model output name updating. begin.out_redirect(node.single_input, node.single_output) else: for ne_ in end: target_var_name = node.single_input # since the output info never be updated, except the final. assert target_var_name in begin.output.values() ne_.in_redirect(node.single_output, target_var_name) begin.successor = [v_ for v_ in begin.successor if v_ != node] + node.successor for ne_ in end: ne_.precedence = [begin if v_ == node else v_ for v_ in ne_.precedence] node_list.remove(node) return node_list
[ "def", "delete_node_1ton", "(", "node_list", ",", "begin", ",", "node", ",", "end", ")", ":", "# type: ([],LinkedNode, LinkedNode, LinkedNode)->[]", "if", "end", "is", "None", ":", "assert", "end", "is", "not", "None", "end", "=", "node", ".", "successor", "el...
delete the node which has 1-input and n-output
[ "delete", "the", "node", "which", "has", "1", "-", "input", "and", "n", "-", "output" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/optimizer.py#L290-L315
229,208
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Scope.get_onnx_variable_name
def get_onnx_variable_name(self, seed): ''' Retrieve the variable ID of the given seed or create one if it is the first time of seeing this seed ''' if seed in self.variable_name_mapping: return self.variable_name_mapping[seed][-1] else: return self.get_unique_variable_name(seed)
python
def get_onnx_variable_name(self, seed): ''' Retrieve the variable ID of the given seed or create one if it is the first time of seeing this seed ''' if seed in self.variable_name_mapping: return self.variable_name_mapping[seed][-1] else: return self.get_unique_variable_name(seed)
[ "def", "get_onnx_variable_name", "(", "self", ",", "seed", ")", ":", "if", "seed", "in", "self", ".", "variable_name_mapping", ":", "return", "self", ".", "variable_name_mapping", "[", "seed", "]", "[", "-", "1", "]", "else", ":", "return", "self", ".", ...
Retrieve the variable ID of the given seed or create one if it is the first time of seeing this seed
[ "Retrieve", "the", "variable", "ID", "of", "the", "given", "seed", "or", "create", "one", "if", "it", "is", "the", "first", "time", "of", "seeing", "this", "seed" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L141-L148
229,209
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Scope.find_sink_variables
def find_sink_variables(self): ''' Find sink variables in this scope ''' # First we assume all variables are sinks is_sink = {name: True for name in self.variables.keys()} # Then, we remove those variables which are inputs of some operators for operator in self.operators.values(): for variable in operator.inputs: is_sink[variable.onnx_name] = False return [variable for name, variable in self.variables.items() if is_sink[name]]
python
def find_sink_variables(self): ''' Find sink variables in this scope ''' # First we assume all variables are sinks is_sink = {name: True for name in self.variables.keys()} # Then, we remove those variables which are inputs of some operators for operator in self.operators.values(): for variable in operator.inputs: is_sink[variable.onnx_name] = False return [variable for name, variable in self.variables.items() if is_sink[name]]
[ "def", "find_sink_variables", "(", "self", ")", ":", "# First we assume all variables are sinks", "is_sink", "=", "{", "name", ":", "True", "for", "name", "in", "self", ".", "variables", ".", "keys", "(", ")", "}", "# Then, we remove those variables which are inputs o...
Find sink variables in this scope
[ "Find", "sink", "variables", "in", "this", "scope" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L162-L172
229,210
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Scope.declare_local_variable
def declare_local_variable(self, raw_name, type=None, prepend=False): ''' This function may create a new variable in this scope. If raw_name has been used to create other variables, the new variable will hide all other variables created using raw_name. ''' # Get unique ID for the new variable onnx_name = self.get_unique_variable_name(raw_name) # Create the variable variable = Variable(raw_name, onnx_name, self.name, type) self.variables[onnx_name] = variable if raw_name in self.variable_name_mapping: # Hide existing variables with the same raw_name if not prepend: self.variable_name_mapping[raw_name].append(onnx_name) else: self.variable_name_mapping[raw_name].insert(0, onnx_name) else: self.variable_name_mapping[raw_name] = [onnx_name] return variable
python
def declare_local_variable(self, raw_name, type=None, prepend=False): ''' This function may create a new variable in this scope. If raw_name has been used to create other variables, the new variable will hide all other variables created using raw_name. ''' # Get unique ID for the new variable onnx_name = self.get_unique_variable_name(raw_name) # Create the variable variable = Variable(raw_name, onnx_name, self.name, type) self.variables[onnx_name] = variable if raw_name in self.variable_name_mapping: # Hide existing variables with the same raw_name if not prepend: self.variable_name_mapping[raw_name].append(onnx_name) else: self.variable_name_mapping[raw_name].insert(0, onnx_name) else: self.variable_name_mapping[raw_name] = [onnx_name] return variable
[ "def", "declare_local_variable", "(", "self", ",", "raw_name", ",", "type", "=", "None", ",", "prepend", "=", "False", ")", ":", "# Get unique ID for the new variable", "onnx_name", "=", "self", ".", "get_unique_variable_name", "(", "raw_name", ")", "# Create the va...
This function may create a new variable in this scope. If raw_name has been used to create other variables, the new variable will hide all other variables created using raw_name.
[ "This", "function", "may", "create", "a", "new", "variable", "in", "this", "scope", ".", "If", "raw_name", "has", "been", "used", "to", "create", "other", "variables", "the", "new", "variable", "will", "hide", "all", "other", "variables", "created", "using",...
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L174-L194
229,211
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Scope.declare_local_operator
def declare_local_operator(self, type, raw_model=None): ''' This function is used to declare new local operator. ''' onnx_name = self.get_unique_operator_name(str(type)) operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset) self.operators[onnx_name] = operator return operator
python
def declare_local_operator(self, type, raw_model=None): ''' This function is used to declare new local operator. ''' onnx_name = self.get_unique_operator_name(str(type)) operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset) self.operators[onnx_name] = operator return operator
[ "def", "declare_local_operator", "(", "self", ",", "type", ",", "raw_model", "=", "None", ")", ":", "onnx_name", "=", "self", ".", "get_unique_operator_name", "(", "str", "(", "type", ")", ")", "operator", "=", "Operator", "(", "onnx_name", ",", "self", "....
This function is used to declare new local operator.
[ "This", "function", "is", "used", "to", "declare", "new", "local", "operator", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L214-L221
229,212
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Scope.delete_local_operator
def delete_local_operator(self, onnx_name): ''' Remove the operator whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_operator_names or onnx_name not in self.operators: raise RuntimeError('The operator to be removed not found') self.onnx_operator_names.discard(onnx_name) del self.operators[onnx_name]
python
def delete_local_operator(self, onnx_name): ''' Remove the operator whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_operator_names or onnx_name not in self.operators: raise RuntimeError('The operator to be removed not found') self.onnx_operator_names.discard(onnx_name) del self.operators[onnx_name]
[ "def", "delete_local_operator", "(", "self", ",", "onnx_name", ")", ":", "if", "onnx_name", "not", "in", "self", ".", "onnx_operator_names", "or", "onnx_name", "not", "in", "self", ".", "operators", ":", "raise", "RuntimeError", "(", "'The operator to be removed n...
Remove the operator whose onnx_name is the input onnx_name
[ "Remove", "the", "operator", "whose", "onnx_name", "is", "the", "input", "onnx_name" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L223-L230
229,213
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Scope.delete_local_variable
def delete_local_variable(self, onnx_name): ''' Remove the variable whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_variable_names or onnx_name not in self.variables: raise RuntimeError('The variable to be removed not found') self.onnx_variable_names.discard(onnx_name) raw_name = self.variables[onnx_name].raw_name self.variable_name_mapping[raw_name].remove(onnx_name) del self.variables[onnx_name]
python
def delete_local_variable(self, onnx_name): ''' Remove the variable whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_variable_names or onnx_name not in self.variables: raise RuntimeError('The variable to be removed not found') self.onnx_variable_names.discard(onnx_name) raw_name = self.variables[onnx_name].raw_name self.variable_name_mapping[raw_name].remove(onnx_name) del self.variables[onnx_name]
[ "def", "delete_local_variable", "(", "self", ",", "onnx_name", ")", ":", "if", "onnx_name", "not", "in", "self", ".", "onnx_variable_names", "or", "onnx_name", "not", "in", "self", ".", "variables", ":", "raise", "RuntimeError", "(", "'The variable to be removed n...
Remove the variable whose onnx_name is the input onnx_name
[ "Remove", "the", "variable", "whose", "onnx_name", "is", "the", "input", "onnx_name" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L232-L241
229,214
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Topology.find_root_and_sink_variables
def find_root_and_sink_variables(self): ''' Find root variables of the whole graph ''' # First we assume all variables are roots is_root = {name: True for scope in self.scopes for name in scope.variables.keys()} # Then, we remove those variables which are outputs of some operators for operator in self.unordered_operator_iterator(): for variable in operator.outputs: is_root[variable.onnx_name] = False is_sink = {name: True for scope in self.scopes for name in scope.variables.keys()} for operator in self.unordered_operator_iterator(): for variable in operator.inputs: is_sink[variable.onnx_name] = False return [variable for scope in self.scopes for name, variable in scope.variables.items() if is_root[name] or is_sink[name]]
python
def find_root_and_sink_variables(self): ''' Find root variables of the whole graph ''' # First we assume all variables are roots is_root = {name: True for scope in self.scopes for name in scope.variables.keys()} # Then, we remove those variables which are outputs of some operators for operator in self.unordered_operator_iterator(): for variable in operator.outputs: is_root[variable.onnx_name] = False is_sink = {name: True for scope in self.scopes for name in scope.variables.keys()} for operator in self.unordered_operator_iterator(): for variable in operator.inputs: is_sink[variable.onnx_name] = False return [variable for scope in self.scopes for name, variable in scope.variables.items() if is_root[name] or is_sink[name]]
[ "def", "find_root_and_sink_variables", "(", "self", ")", ":", "# First we assume all variables are roots", "is_root", "=", "{", "name", ":", "True", "for", "scope", "in", "self", ".", "scopes", "for", "name", "in", "scope", ".", "variables", ".", "keys", "(", ...
Find root variables of the whole graph
[ "Find", "root", "variables", "of", "the", "whole", "graph" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L327-L342
229,215
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Topology.topological_operator_iterator
def topological_operator_iterator(self): ''' This is an iterator of all operators in Topology object. Operators may be produced in a topological order. If you want to simply go though all operators without considering their topological structure, please use another function, unordered_operator_iterator. ''' self._initialize_graph_status_for_traversing() priorities = {'tensorToProbabilityMap': 2, 'tensorToLabel': 1} while not all(operator.is_evaluated for scope in self.scopes for operator in scope.operators.values()): is_evaluation_happened = False for operator in sorted(self.unordered_operator_iterator(), key=lambda op: priorities[op.type] if op.type in priorities else 0): if all(variable.is_fed for variable in operator.inputs) and not operator.is_evaluated: # Check if over-writing problem occurs (i.e., multiple operators produce results on one variable). for variable in operator.outputs: # Throw an error if this variable has been treated as an output somewhere if variable.is_fed: raise RuntimeError('One variable can only be assigned once') # Mark this variable as filled variable.is_fed = True # Make this operator as handled operator.is_evaluated = True is_evaluation_happened = True # Send out an operator yield operator # After scanning through the whole computational graph, at least one operator should be evaluated. If not, # we need to terminate this procedure to avoid dead lock. if not is_evaluation_happened: break
python
def topological_operator_iterator(self): ''' This is an iterator of all operators in Topology object. Operators may be produced in a topological order. If you want to simply go though all operators without considering their topological structure, please use another function, unordered_operator_iterator. ''' self._initialize_graph_status_for_traversing() priorities = {'tensorToProbabilityMap': 2, 'tensorToLabel': 1} while not all(operator.is_evaluated for scope in self.scopes for operator in scope.operators.values()): is_evaluation_happened = False for operator in sorted(self.unordered_operator_iterator(), key=lambda op: priorities[op.type] if op.type in priorities else 0): if all(variable.is_fed for variable in operator.inputs) and not operator.is_evaluated: # Check if over-writing problem occurs (i.e., multiple operators produce results on one variable). for variable in operator.outputs: # Throw an error if this variable has been treated as an output somewhere if variable.is_fed: raise RuntimeError('One variable can only be assigned once') # Mark this variable as filled variable.is_fed = True # Make this operator as handled operator.is_evaluated = True is_evaluation_happened = True # Send out an operator yield operator # After scanning through the whole computational graph, at least one operator should be evaluated. If not, # we need to terminate this procedure to avoid dead lock. if not is_evaluation_happened: break
[ "def", "topological_operator_iterator", "(", "self", ")", ":", "self", ".", "_initialize_graph_status_for_traversing", "(", ")", "priorities", "=", "{", "'tensorToProbabilityMap'", ":", "2", ",", "'tensorToLabel'", ":", "1", "}", "while", "not", "all", "(", "opera...
This is an iterator of all operators in Topology object. Operators may be produced in a topological order. If you want to simply go though all operators without considering their topological structure, please use another function, unordered_operator_iterator.
[ "This", "is", "an", "iterator", "of", "all", "operators", "in", "Topology", "object", ".", "Operators", "may", "be", "produced", "in", "a", "topological", "order", ".", "If", "you", "want", "to", "simply", "go", "though", "all", "operators", "without", "co...
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L344-L372
229,216
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Topology._check_structure
def _check_structure(self): ''' This function applies some rules to check if the parsed model is proper. Currently, it only checks if isolated variable and isolated operator exists. ''' # Collect all variable names and operator names unused_variables = set() unused_operators = set() for variable in self.unordered_variable_iterator(): unused_variables.add(variable.full_name) for operator in self.unordered_operator_iterator(): unused_operators.add(operator.full_name) for operator in self.unordered_operator_iterator(): for variable in operator.inputs: # A variable is used by an operator, so we remove the variable from the unused-variable list. unused_variables.discard(variable.full_name) # A operator has an input, so we remove the operator from the unused-operator list. unused_operators.discard(operator.full_name) for variable in operator.outputs: # A variable is used by an operator, so we remove the variable from the unused-variable list. unused_variables.discard(variable.full_name) # A operator has an output, so we remove the operator from the unused-operator list. unused_operators.discard(operator.full_name) if len(unused_variables) > 0: raise RuntimeError('Isolated variables exist: %s' % unused_variables) if len(unused_operators) > 0: raise RuntimeError('Isolated operators exist: %s' % unused_operators)
python
def _check_structure(self): ''' This function applies some rules to check if the parsed model is proper. Currently, it only checks if isolated variable and isolated operator exists. ''' # Collect all variable names and operator names unused_variables = set() unused_operators = set() for variable in self.unordered_variable_iterator(): unused_variables.add(variable.full_name) for operator in self.unordered_operator_iterator(): unused_operators.add(operator.full_name) for operator in self.unordered_operator_iterator(): for variable in operator.inputs: # A variable is used by an operator, so we remove the variable from the unused-variable list. unused_variables.discard(variable.full_name) # A operator has an input, so we remove the operator from the unused-operator list. unused_operators.discard(operator.full_name) for variable in operator.outputs: # A variable is used by an operator, so we remove the variable from the unused-variable list. unused_variables.discard(variable.full_name) # A operator has an output, so we remove the operator from the unused-operator list. unused_operators.discard(operator.full_name) if len(unused_variables) > 0: raise RuntimeError('Isolated variables exist: %s' % unused_variables) if len(unused_operators) > 0: raise RuntimeError('Isolated operators exist: %s' % unused_operators)
[ "def", "_check_structure", "(", "self", ")", ":", "# Collect all variable names and operator names", "unused_variables", "=", "set", "(", ")", "unused_operators", "=", "set", "(", ")", "for", "variable", "in", "self", ".", "unordered_variable_iterator", "(", ")", ":...
This function applies some rules to check if the parsed model is proper. Currently, it only checks if isolated variable and isolated operator exists.
[ "This", "function", "applies", "some", "rules", "to", "check", "if", "the", "parsed", "model", "is", "proper", ".", "Currently", "it", "only", "checks", "if", "isolated", "variable", "and", "isolated", "operator", "exists", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L418-L447
229,217
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Topology._initialize_graph_status_for_traversing
def _initialize_graph_status_for_traversing(self): ''' Initialize the status of all variables and operators for traversing the underline graph ''' # In the beginning, we set is_root and is_leaf true. For is_fed, we have two different behaviors depending on # whether root_names is empty. for variable in self.unordered_variable_iterator(): # If root_names is set, we only set those variable to be fed. Otherwise, all roots would be fed. if self.root_names: if variable.onnx_name in self.root_names: variable.is_fed = True else: variable.is_fed = False else: variable.is_fed = True variable.is_root = True variable.is_leaf = True # Then, we flip some flags by applying some simple rules so that only # 1. all roots get is_root=True and is_fed=True # 2. all leaves get is_leaf=True for operator in self.unordered_operator_iterator(): operator.is_evaluated = False # All operators are not processed in the beginning for variable in operator.outputs: # Output cannot be fed before graph traversing variable.is_fed = False # If the variable is an output of one operator, it must not be a root variable.is_root = False for variable in operator.inputs: # If the variable is an input of one operator, it must not be a leaf variable.is_leaf = False
python
def _initialize_graph_status_for_traversing(self): ''' Initialize the status of all variables and operators for traversing the underline graph ''' # In the beginning, we set is_root and is_leaf true. For is_fed, we have two different behaviors depending on # whether root_names is empty. for variable in self.unordered_variable_iterator(): # If root_names is set, we only set those variable to be fed. Otherwise, all roots would be fed. if self.root_names: if variable.onnx_name in self.root_names: variable.is_fed = True else: variable.is_fed = False else: variable.is_fed = True variable.is_root = True variable.is_leaf = True # Then, we flip some flags by applying some simple rules so that only # 1. all roots get is_root=True and is_fed=True # 2. all leaves get is_leaf=True for operator in self.unordered_operator_iterator(): operator.is_evaluated = False # All operators are not processed in the beginning for variable in operator.outputs: # Output cannot be fed before graph traversing variable.is_fed = False # If the variable is an output of one operator, it must not be a root variable.is_root = False for variable in operator.inputs: # If the variable is an input of one operator, it must not be a leaf variable.is_leaf = False
[ "def", "_initialize_graph_status_for_traversing", "(", "self", ")", ":", "# In the beginning, we set is_root and is_leaf true. For is_fed, we have two different behaviors depending on", "# whether root_names is empty.", "for", "variable", "in", "self", ".", "unordered_variable_iterator", ...
Initialize the status of all variables and operators for traversing the underline graph
[ "Initialize", "the", "status", "of", "all", "variables", "and", "operators", "for", "traversing", "the", "underline", "graph" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L449-L479
229,218
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Topology._infer_all_types
def _infer_all_types(self): ''' Infer all variables' shapes in the computational graph. ''' self._initialize_graph_status_for_traversing() # Deliver user-specified types to root variables for raw_name, initial_type in self.initial_types: # Check all variables declared using raw_name in the whole graph for scope in self.scopes: # Skip scopes without having the considered variable name if raw_name not in scope.variable_name_mapping: continue # Assign initial_type to all variables declared using raw_name for onnx_name in scope.variable_name_mapping[raw_name]: variable = scope.variables[onnx_name] if variable.is_root: # Assign type to the root; existing type produced by parser may be overwritten variable.type = initial_type # Traverse the graph from roots to leaves for operator in self.topological_operator_iterator(): if operator.type in self.custom_shape_calculators: self.custom_shape_calculators[operator.type](operator) elif operator.type in self.custom_conversion_functions: pass # in Keras converter, the shape calculator can be optional. else: operator.infer_types()
python
def _infer_all_types(self): ''' Infer all variables' shapes in the computational graph. ''' self._initialize_graph_status_for_traversing() # Deliver user-specified types to root variables for raw_name, initial_type in self.initial_types: # Check all variables declared using raw_name in the whole graph for scope in self.scopes: # Skip scopes without having the considered variable name if raw_name not in scope.variable_name_mapping: continue # Assign initial_type to all variables declared using raw_name for onnx_name in scope.variable_name_mapping[raw_name]: variable = scope.variables[onnx_name] if variable.is_root: # Assign type to the root; existing type produced by parser may be overwritten variable.type = initial_type # Traverse the graph from roots to leaves for operator in self.topological_operator_iterator(): if operator.type in self.custom_shape_calculators: self.custom_shape_calculators[operator.type](operator) elif operator.type in self.custom_conversion_functions: pass # in Keras converter, the shape calculator can be optional. else: operator.infer_types()
[ "def", "_infer_all_types", "(", "self", ")", ":", "self", ".", "_initialize_graph_status_for_traversing", "(", ")", "# Deliver user-specified types to root variables", "for", "raw_name", ",", "initial_type", "in", "self", ".", "initial_types", ":", "# Check all variables de...
Infer all variables' shapes in the computational graph.
[ "Infer", "all", "variables", "shapes", "in", "the", "computational", "graph", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L481-L508
229,219
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Topology._resolve_duplicates
def _resolve_duplicates(self): ''' Merge variables connected by identity operator to reduce the number of redundant variables ''' self._initialize_graph_status_for_traversing() # Traverse the graph from roots to leaves for operator in self.topological_operator_iterator(): if operator.type != 'identity': continue if any(variable.is_root for variable in operator.inputs) and \ any(variable.is_leaf for variable in operator.outputs): continue # Replace the output variable with the input variable everywhere original = operator.inputs[0] duplicate = operator.outputs[0] for another_scope in self.scopes: for another_operator in another_scope.operators.values(): for i in range(len(another_operator.inputs)): if another_operator.inputs[i].onnx_name != duplicate.onnx_name: continue another_operator.inputs[i] = original # When original variable's documentation string or denotation is empty but duplicate's is not, we # copy that field to the original variable to avoid information loss. if not original.type.doc_string and duplicate.type.doc_string: original.type.doc_string = duplicate.type.doc_string if isinstance(original.type, TensorType) and isinstance(duplicate.type, TensorType): if not original.type.denotation and duplicate.type.denotation: original.type.denotation = duplicate.type.denotation if not original.type.channel_denotations: original.type.channel_denotations = duplicate.type.channel_denotations elif duplicate.type.channel_denotations: # Merge the channel denotations if available in both the original and the duplicate for i in range(len(original.type.channel_denotations)): if original.type.channel_denotations[i]: continue original.type.channel_denotations[i] = duplicate.type.channel_denotations[i] # Sometime, shapes of duplicates are different. We try to replace the original variable's unknown dimensions # as many as possible because we will get rid of the duplicate. if len(original.type.shape) == len(duplicate.type.shape): for i in range(len(original.type.shape)): if original.type.shape[i] != 'None': continue original.type.shape[i] = duplicate.type.shape[i] # Because we're iterating through the topology, we cannot delete any operator or variable. Otherwise, # the traversing function may be broken. We will delete those abandoned ones later. duplicate.is_abandoned = True operator.is_abandoned = True for scope in self.scopes: # Find out who is going to be abandoned abandoned_operator_names = set(onnx_name for onnx_name, operator in scope.operators.items() if operator.is_abandoned) abandoned_variable_names = set(onnx_name for onnx_name, variable in scope.variables.items() if variable.is_abandoned) # Remove abandoned operators for name in abandoned_operator_names: scope.delete_local_operator(name) # Remove abandoned variables for name in abandoned_variable_names: scope.delete_local_variable(name)
python
def _resolve_duplicates(self): ''' Merge variables connected by identity operator to reduce the number of redundant variables ''' self._initialize_graph_status_for_traversing() # Traverse the graph from roots to leaves for operator in self.topological_operator_iterator(): if operator.type != 'identity': continue if any(variable.is_root for variable in operator.inputs) and \ any(variable.is_leaf for variable in operator.outputs): continue # Replace the output variable with the input variable everywhere original = operator.inputs[0] duplicate = operator.outputs[0] for another_scope in self.scopes: for another_operator in another_scope.operators.values(): for i in range(len(another_operator.inputs)): if another_operator.inputs[i].onnx_name != duplicate.onnx_name: continue another_operator.inputs[i] = original # When original variable's documentation string or denotation is empty but duplicate's is not, we # copy that field to the original variable to avoid information loss. if not original.type.doc_string and duplicate.type.doc_string: original.type.doc_string = duplicate.type.doc_string if isinstance(original.type, TensorType) and isinstance(duplicate.type, TensorType): if not original.type.denotation and duplicate.type.denotation: original.type.denotation = duplicate.type.denotation if not original.type.channel_denotations: original.type.channel_denotations = duplicate.type.channel_denotations elif duplicate.type.channel_denotations: # Merge the channel denotations if available in both the original and the duplicate for i in range(len(original.type.channel_denotations)): if original.type.channel_denotations[i]: continue original.type.channel_denotations[i] = duplicate.type.channel_denotations[i] # Sometime, shapes of duplicates are different. We try to replace the original variable's unknown dimensions # as many as possible because we will get rid of the duplicate. if len(original.type.shape) == len(duplicate.type.shape): for i in range(len(original.type.shape)): if original.type.shape[i] != 'None': continue original.type.shape[i] = duplicate.type.shape[i] # Because we're iterating through the topology, we cannot delete any operator or variable. Otherwise, # the traversing function may be broken. We will delete those abandoned ones later. duplicate.is_abandoned = True operator.is_abandoned = True for scope in self.scopes: # Find out who is going to be abandoned abandoned_operator_names = set(onnx_name for onnx_name, operator in scope.operators.items() if operator.is_abandoned) abandoned_variable_names = set(onnx_name for onnx_name, variable in scope.variables.items() if variable.is_abandoned) # Remove abandoned operators for name in abandoned_operator_names: scope.delete_local_operator(name) # Remove abandoned variables for name in abandoned_variable_names: scope.delete_local_variable(name)
[ "def", "_resolve_duplicates", "(", "self", ")", ":", "self", ".", "_initialize_graph_status_for_traversing", "(", ")", "# Traverse the graph from roots to leaves", "for", "operator", "in", "self", ".", "topological_operator_iterator", "(", ")", ":", "if", "operator", "....
Merge variables connected by identity operator to reduce the number of redundant variables
[ "Merge", "variables", "connected", "by", "identity", "operator", "to", "reduce", "the", "number", "of", "redundant", "variables" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L510-L577
229,220
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
Topology.compile
def compile(self): ''' This function aims at giving every operator enough information so that all operator conversions can happen independently. We also want to check, fix, and simplify the network structure here. ''' self._prune() self._resolve_duplicates() self._fix_shapes() self._infer_all_types() self._check_structure()
python
def compile(self): ''' This function aims at giving every operator enough information so that all operator conversions can happen independently. We also want to check, fix, and simplify the network structure here. ''' self._prune() self._resolve_duplicates() self._fix_shapes() self._infer_all_types() self._check_structure()
[ "def", "compile", "(", "self", ")", ":", "self", ".", "_prune", "(", ")", "self", ".", "_resolve_duplicates", "(", ")", "self", ".", "_fix_shapes", "(", ")", "self", ".", "_infer_all_types", "(", ")", "self", ".", "_check_structure", "(", ")" ]
This function aims at giving every operator enough information so that all operator conversions can happen independently. We also want to check, fix, and simplify the network structure here.
[ "This", "function", "aims", "at", "giving", "every", "operator", "enough", "information", "so", "that", "all", "operator", "conversions", "can", "happen", "independently", ".", "We", "also", "want", "to", "check", "fix", "and", "simplify", "the", "network", "s...
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L624-L633
229,221
onnx/onnxmltools
onnxmltools/convert/coreml/operator_converters/TensorToProbabilityMap.py
convert_tensor_to_probability_map
def convert_tensor_to_probability_map(scope, operator, container): ''' This converter tries to convert a special operator 'TensorToProbabilityMap' into a sequence of some ONNX operators. Those operators are used to create a dictionary in which keys are class labels and values are the associated probabilities. We assume that the elements in the given probability tensor are aligned with the class labels specified in the CoreML model. Notice that ONNX<1.2 doesn't support a CoreML classifier with a batch size larger than one because old ONNX ZipMap is not able to produce a sequence of dictionaries. This issue has been fixed in ONNX-1.2. ''' attrs = {'name': scope.get_unique_operator_name('ZipMap')} model_type = operator.raw_operator.WhichOneof('Type') if model_type == 'neuralNetworkClassifier': model = operator.raw_operator.neuralNetworkClassifier if model.WhichOneof('ClassLabels') == 'stringClassLabels': attrs['classlabels_strings'] = list(s.encode('utf-8') for s in model.stringClassLabels.vector) elif model.WhichOneof('ClassLabels') == 'int64ClassLabels': attrs['classlabels_int64s'] = list(int(i) for i in model.int64ClassLabels.vector) else: raise ValueError('Unknown label type found') elif model_type == 'pipelineClassifier': model = operator.raw_operator.pipelineClassifier if model.WhichOneof('ClassLabels') == 'stringClassLabels': attrs['classlabels_strings'] = list(s.encode('utf-8') for s in model.stringClassLabels.vector) elif model.WhichOneof('ClassLabels') == 'int64ClassLabels': attrs['classlabels_int64s'] = list(int(i) for i in model.int64ClassLabels.vector) else: raise ValueError('Unknown label type found') else: raise TypeError('Only neural network classifiers and pipeline classifiers are supported') input_shape = operator.inputs[0].type.shape if len(operator.inputs[0].type.shape) != 2: # Calculate the shape attribute of ONNX Reshape if input_shape[0] != 'None': N = input_shape[0] else: N = -1 # -1 means that this dimension is automatically determined in runtime and unknown in conversion time if all(isinstance(i, numbers.Integral) for i in input_shape[1:]): C = 1 for i in input_shape[1:]: C *= int(i) else: C = -1 # -1 means that this dimension is automatically determined in runtime and unknown in conversion time # ZipMap in ONNX only accepts [C] and [N, C] inputs. In cases of [N, C, 1, 1], we reshape the probability tensor # into [N, C] before feeding it into ZipMap. buffer_name = scope.get_unique_variable_name('buffer') apply_reshape(scope, operator.inputs[0].full_name, buffer_name, container, desired_shape=[N, C]) else: buffer_name = operator.inputs[0].full_name container.add_node('ZipMap', buffer_name, operator.outputs[0].full_name, op_domain='ai.onnx.ml', **attrs)
python
def convert_tensor_to_probability_map(scope, operator, container): ''' This converter tries to convert a special operator 'TensorToProbabilityMap' into a sequence of some ONNX operators. Those operators are used to create a dictionary in which keys are class labels and values are the associated probabilities. We assume that the elements in the given probability tensor are aligned with the class labels specified in the CoreML model. Notice that ONNX<1.2 doesn't support a CoreML classifier with a batch size larger than one because old ONNX ZipMap is not able to produce a sequence of dictionaries. This issue has been fixed in ONNX-1.2. ''' attrs = {'name': scope.get_unique_operator_name('ZipMap')} model_type = operator.raw_operator.WhichOneof('Type') if model_type == 'neuralNetworkClassifier': model = operator.raw_operator.neuralNetworkClassifier if model.WhichOneof('ClassLabels') == 'stringClassLabels': attrs['classlabels_strings'] = list(s.encode('utf-8') for s in model.stringClassLabels.vector) elif model.WhichOneof('ClassLabels') == 'int64ClassLabels': attrs['classlabels_int64s'] = list(int(i) for i in model.int64ClassLabels.vector) else: raise ValueError('Unknown label type found') elif model_type == 'pipelineClassifier': model = operator.raw_operator.pipelineClassifier if model.WhichOneof('ClassLabels') == 'stringClassLabels': attrs['classlabels_strings'] = list(s.encode('utf-8') for s in model.stringClassLabels.vector) elif model.WhichOneof('ClassLabels') == 'int64ClassLabels': attrs['classlabels_int64s'] = list(int(i) for i in model.int64ClassLabels.vector) else: raise ValueError('Unknown label type found') else: raise TypeError('Only neural network classifiers and pipeline classifiers are supported') input_shape = operator.inputs[0].type.shape if len(operator.inputs[0].type.shape) != 2: # Calculate the shape attribute of ONNX Reshape if input_shape[0] != 'None': N = input_shape[0] else: N = -1 # -1 means that this dimension is automatically determined in runtime and unknown in conversion time if all(isinstance(i, numbers.Integral) for i in input_shape[1:]): C = 1 for i in input_shape[1:]: C *= int(i) else: C = -1 # -1 means that this dimension is automatically determined in runtime and unknown in conversion time # ZipMap in ONNX only accepts [C] and [N, C] inputs. In cases of [N, C, 1, 1], we reshape the probability tensor # into [N, C] before feeding it into ZipMap. buffer_name = scope.get_unique_variable_name('buffer') apply_reshape(scope, operator.inputs[0].full_name, buffer_name, container, desired_shape=[N, C]) else: buffer_name = operator.inputs[0].full_name container.add_node('ZipMap', buffer_name, operator.outputs[0].full_name, op_domain='ai.onnx.ml', **attrs)
[ "def", "convert_tensor_to_probability_map", "(", "scope", ",", "operator", ",", "container", ")", ":", "attrs", "=", "{", "'name'", ":", "scope", ".", "get_unique_operator_name", "(", "'ZipMap'", ")", "}", "model_type", "=", "operator", ".", "raw_operator", ".",...
This converter tries to convert a special operator 'TensorToProbabilityMap' into a sequence of some ONNX operators. Those operators are used to create a dictionary in which keys are class labels and values are the associated probabilities. We assume that the elements in the given probability tensor are aligned with the class labels specified in the CoreML model. Notice that ONNX<1.2 doesn't support a CoreML classifier with a batch size larger than one because old ONNX ZipMap is not able to produce a sequence of dictionaries. This issue has been fixed in ONNX-1.2.
[ "This", "converter", "tries", "to", "convert", "a", "special", "operator", "TensorToProbabilityMap", "into", "a", "sequence", "of", "some", "ONNX", "operators", ".", "Those", "operators", "are", "used", "to", "create", "a", "dictionary", "in", "which", "keys", ...
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/operator_converters/TensorToProbabilityMap.py#L12-L67
229,222
onnx/onnxmltools
onnxmltools/convert/coreml/shape_calculators/neural_network/BidirectionalLSTM.py
calculate_bidirectional_lstm_output_shapes
def calculate_bidirectional_lstm_output_shapes(operator): ''' See bidirectional LSTM's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operator.inputs[0].type.shape # LSTM accepts [N, C] and [N, C, 1, 1] inputs if len(input_shape) not in [2, 4]: raise RuntimeError('Input must be a 2-D or 4-D tensor') params = operator.raw_operator.biDirectionalLSTM # The following line is more accurate but it may break some tests # output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [1, 2 *params.outputVectorSize] output_shape = ['None', 2 * params.outputVectorSize] state_shape = [1, params.outputVectorSize] # TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function if len(operator.inputs) > 1: Y_h_in = operator.inputs[1] # The forward initial hidden state of a single sequence Y_h_in.type.shape = state_shape Y_h_rev_in = operator.inputs[3] # The backward initial hidden state of a single sequence Y_h_rev_in.type.shape = state_shape if len(operator.inputs) > 2: Y_c_in = operator.inputs[2] # The forward initial cell state of a single sequence Y_c_in.type.shape = state_shape Y_c_rev_in = operator.inputs[4] # The backward initial cell state of a single sequence Y_c_rev_in.type.shape = state_shape operator.outputs[0].type.shape = output_shape if len(operator.outputs) > 1: operator.outputs[1].type.shape = state_shape operator.outputs[3].type.shape = state_shape if len(operator.outputs) > 2: operator.outputs[2].type.shape = state_shape operator.outputs[4].type.shape = state_shape
python
def calculate_bidirectional_lstm_output_shapes(operator): ''' See bidirectional LSTM's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operator.inputs[0].type.shape # LSTM accepts [N, C] and [N, C, 1, 1] inputs if len(input_shape) not in [2, 4]: raise RuntimeError('Input must be a 2-D or 4-D tensor') params = operator.raw_operator.biDirectionalLSTM # The following line is more accurate but it may break some tests # output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [1, 2 *params.outputVectorSize] output_shape = ['None', 2 * params.outputVectorSize] state_shape = [1, params.outputVectorSize] # TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function if len(operator.inputs) > 1: Y_h_in = operator.inputs[1] # The forward initial hidden state of a single sequence Y_h_in.type.shape = state_shape Y_h_rev_in = operator.inputs[3] # The backward initial hidden state of a single sequence Y_h_rev_in.type.shape = state_shape if len(operator.inputs) > 2: Y_c_in = operator.inputs[2] # The forward initial cell state of a single sequence Y_c_in.type.shape = state_shape Y_c_rev_in = operator.inputs[4] # The backward initial cell state of a single sequence Y_c_rev_in.type.shape = state_shape operator.outputs[0].type.shape = output_shape if len(operator.outputs) > 1: operator.outputs[1].type.shape = state_shape operator.outputs[3].type.shape = state_shape if len(operator.outputs) > 2: operator.outputs[2].type.shape = state_shape operator.outputs[4].type.shape = state_shape
[ "def", "calculate_bidirectional_lstm_output_shapes", "(", "operator", ")", ":", "check_input_and_output_numbers", "(", "operator", ",", "input_count_range", "=", "[", "1", ",", "5", "]", ",", "output_count_range", "=", "[", "1", ",", "5", "]", ")", "check_input_an...
See bidirectional LSTM's conversion function for its output shapes.
[ "See", "bidirectional", "LSTM", "s", "conversion", "function", "for", "its", "output", "shapes", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/shape_calculators/neural_network/BidirectionalLSTM.py#L12-L49
229,223
onnx/onnxmltools
onnxmltools/utils/main.py
load_model
def load_model(file_path): """ Loads an ONNX model to a ProtoBuf object. :param file_path: ONNX file (full file name) :return: ONNX model. Example: :: from onnxmltools.utils import load_model onnx_model = load_model("SqueezeNet.onnx") """ if not path.exists(file_path): raise FileNotFoundError("{0} was not found.".format(file_path)) model = onnx_proto.ModelProto() with open(file_path, 'rb') as f: model.ParseFromString(f.read()) return model
python
def load_model(file_path): if not path.exists(file_path): raise FileNotFoundError("{0} was not found.".format(file_path)) model = onnx_proto.ModelProto() with open(file_path, 'rb') as f: model.ParseFromString(f.read()) return model
[ "def", "load_model", "(", "file_path", ")", ":", "if", "not", "path", ".", "exists", "(", "file_path", ")", ":", "raise", "FileNotFoundError", "(", "\"{0} was not found.\"", ".", "format", "(", "file_path", ")", ")", "model", "=", "onnx_proto", ".", "ModelPr...
Loads an ONNX model to a ProtoBuf object. :param file_path: ONNX file (full file name) :return: ONNX model. Example: :: from onnxmltools.utils import load_model onnx_model = load_model("SqueezeNet.onnx")
[ "Loads", "an", "ONNX", "model", "to", "a", "ProtoBuf", "object", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/utils/main.py#L13-L32
229,224
onnx/onnxmltools
onnxmltools/utils/main.py
set_model_domain
def set_model_domain(model, domain): """ Sets the domain on the ONNX model. :param model: instance of an ONNX model :param domain: string containing the domain name of the model Example: :: from onnxmltools.utils import set_model_domain onnx_model = load_model("SqueezeNet.onnx") set_model_domain(onnx_model, "com.acme") """ if model is None or not isinstance(model, onnx_proto.ModelProto): raise ValueError("Model is not a valid ONNX model.") if not convert_utils.is_string_type(domain): raise ValueError("Domain must be a string type.") model.domain = domain
python
def set_model_domain(model, domain): if model is None or not isinstance(model, onnx_proto.ModelProto): raise ValueError("Model is not a valid ONNX model.") if not convert_utils.is_string_type(domain): raise ValueError("Domain must be a string type.") model.domain = domain
[ "def", "set_model_domain", "(", "model", ",", "domain", ")", ":", "if", "model", "is", "None", "or", "not", "isinstance", "(", "model", ",", "onnx_proto", ".", "ModelProto", ")", ":", "raise", "ValueError", "(", "\"Model is not a valid ONNX model.\"", ")", "if...
Sets the domain on the ONNX model. :param model: instance of an ONNX model :param domain: string containing the domain name of the model Example: :: from onnxmltools.utils import set_model_domain onnx_model = load_model("SqueezeNet.onnx") set_model_domain(onnx_model, "com.acme")
[ "Sets", "the", "domain", "on", "the", "ONNX", "model", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/utils/main.py#L57-L75
229,225
onnx/onnxmltools
onnxmltools/utils/main.py
set_model_version
def set_model_version(model, version): """ Sets the version of the ONNX model. :param model: instance of an ONNX model :param version: integer containing the version of the model Example: :: from onnxmltools.utils import set_model_version onnx_model = load_model("SqueezeNet.onnx") set_model_version(onnx_model, 1) """ if model is None or not isinstance(model, onnx_proto.ModelProto): raise ValueError("Model is not a valid ONNX model.") if not convert_utils.is_numeric_type(version): raise ValueError("Version must be a numeric type.") model.model_version = version
python
def set_model_version(model, version): if model is None or not isinstance(model, onnx_proto.ModelProto): raise ValueError("Model is not a valid ONNX model.") if not convert_utils.is_numeric_type(version): raise ValueError("Version must be a numeric type.") model.model_version = version
[ "def", "set_model_version", "(", "model", ",", "version", ")", ":", "if", "model", "is", "None", "or", "not", "isinstance", "(", "model", ",", "onnx_proto", ".", "ModelProto", ")", ":", "raise", "ValueError", "(", "\"Model is not a valid ONNX model.\"", ")", "...
Sets the version of the ONNX model. :param model: instance of an ONNX model :param version: integer containing the version of the model Example: :: from onnxmltools.utils import set_model_version onnx_model = load_model("SqueezeNet.onnx") set_model_version(onnx_model, 1)
[ "Sets", "the", "version", "of", "the", "ONNX", "model", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/utils/main.py#L78-L96
229,226
onnx/onnxmltools
onnxmltools/utils/main.py
set_model_doc_string
def set_model_doc_string(model, doc, override=False): """ Sets the doc string of the ONNX model. :param model: instance of an ONNX model :param doc: string containing the doc string that describes the model. :param override: bool if true will always override the doc string with the new value Example: :: from onnxmltools.utils import set_model_doc_string onnx_model = load_model("SqueezeNet.onnx") set_model_doc_string(onnx_model, "Sample doc string") """ if model is None or not isinstance(model, onnx_proto.ModelProto): raise ValueError("Model is not a valid ONNX model.") if not convert_utils.is_string_type(doc): raise ValueError("Doc must be a string type.") if model.doc_string and not doc and override is False: raise ValueError("Failing to overwrite the doc string with a blank string, set override to True if intentional.") model.doc_string = doc
python
def set_model_doc_string(model, doc, override=False): if model is None or not isinstance(model, onnx_proto.ModelProto): raise ValueError("Model is not a valid ONNX model.") if not convert_utils.is_string_type(doc): raise ValueError("Doc must be a string type.") if model.doc_string and not doc and override is False: raise ValueError("Failing to overwrite the doc string with a blank string, set override to True if intentional.") model.doc_string = doc
[ "def", "set_model_doc_string", "(", "model", ",", "doc", ",", "override", "=", "False", ")", ":", "if", "model", "is", "None", "or", "not", "isinstance", "(", "model", ",", "onnx_proto", ".", "ModelProto", ")", ":", "raise", "ValueError", "(", "\"Model is ...
Sets the doc string of the ONNX model. :param model: instance of an ONNX model :param doc: string containing the doc string that describes the model. :param override: bool if true will always override the doc string with the new value Example: :: from onnxmltools.utils import set_model_doc_string onnx_model = load_model("SqueezeNet.onnx") set_model_doc_string(onnx_model, "Sample doc string")
[ "Sets", "the", "doc", "string", "of", "the", "ONNX", "model", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/utils/main.py#L99-L120
229,227
onnx/onnxmltools
onnxutils/onnxconverter_common/container.py
ModelComponentContainer.add_initializer
def add_initializer(self, name, onnx_type, shape, content): ''' Add a TensorProto into the initializer list of the final ONNX model :param name: Variable name in the produced ONNX model. :param onnx_type: Element types allowed in ONNX tensor, e.g., TensorProto.FLOAT and TensorProto.STRING. :param shape: Tensor shape, a list of integers. :param content: Flattened tensor values (i.e., a float list or a float array). ''' if any(d is None for d in shape): raise ValueError('Shape of initializer cannot contain None') tensor = helper.make_tensor(name, onnx_type, shape, content) self.initializers.append(tensor)
python
def add_initializer(self, name, onnx_type, shape, content): ''' Add a TensorProto into the initializer list of the final ONNX model :param name: Variable name in the produced ONNX model. :param onnx_type: Element types allowed in ONNX tensor, e.g., TensorProto.FLOAT and TensorProto.STRING. :param shape: Tensor shape, a list of integers. :param content: Flattened tensor values (i.e., a float list or a float array). ''' if any(d is None for d in shape): raise ValueError('Shape of initializer cannot contain None') tensor = helper.make_tensor(name, onnx_type, shape, content) self.initializers.append(tensor)
[ "def", "add_initializer", "(", "self", ",", "name", ",", "onnx_type", ",", "shape", ",", "content", ")", ":", "if", "any", "(", "d", "is", "None", "for", "d", "in", "shape", ")", ":", "raise", "ValueError", "(", "'Shape of initializer cannot contain None'", ...
Add a TensorProto into the initializer list of the final ONNX model :param name: Variable name in the produced ONNX model. :param onnx_type: Element types allowed in ONNX tensor, e.g., TensorProto.FLOAT and TensorProto.STRING. :param shape: Tensor shape, a list of integers. :param content: Flattened tensor values (i.e., a float list or a float array).
[ "Add", "a", "TensorProto", "into", "the", "initializer", "list", "of", "the", "final", "ONNX", "model" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/container.py#L203-L215
229,228
onnx/onnxmltools
onnxutils/onnxconverter_common/float16.py
convert_tensor_float_to_float16
def convert_tensor_float_to_float16(tensor): ''' Convert tensor float to float16. :param tensor: TensorProto object :return tensor_float16: converted TensorProto object Example: :: from onnxmltools.utils.float16_converter import convert_tensor_float_to_float16 new_tensor = convert_tensor_float_to_float16(tensor) ''' if not isinstance(tensor, onnx_proto.TensorProto): raise ValueError('Expected input type is an ONNX TensorProto but got %s' % type(tensor)) if tensor.data_type == onnx_proto.TensorProto.FLOAT: tensor.data_type = onnx_proto.TensorProto.FLOAT16 # convert float_data (float type) to float16 and write to int32_data if tensor.float_data: int_list = _npfloat16_to_int(np.float16(tensor.float_data)) tensor.int32_data[:] = int_list tensor.float_data[:] = [] # convert raw_data (bytes type) if tensor.raw_data: # convert n.raw_data to float float32_list = np.fromstring(tensor.raw_data, dtype='float32') # convert float to float16 float16_list = np.float16(float32_list) # convert float16 to bytes and write back to raw_data tensor.raw_data = float16_list.tostring() return tensor
python
def convert_tensor_float_to_float16(tensor): ''' Convert tensor float to float16. :param tensor: TensorProto object :return tensor_float16: converted TensorProto object Example: :: from onnxmltools.utils.float16_converter import convert_tensor_float_to_float16 new_tensor = convert_tensor_float_to_float16(tensor) ''' if not isinstance(tensor, onnx_proto.TensorProto): raise ValueError('Expected input type is an ONNX TensorProto but got %s' % type(tensor)) if tensor.data_type == onnx_proto.TensorProto.FLOAT: tensor.data_type = onnx_proto.TensorProto.FLOAT16 # convert float_data (float type) to float16 and write to int32_data if tensor.float_data: int_list = _npfloat16_to_int(np.float16(tensor.float_data)) tensor.int32_data[:] = int_list tensor.float_data[:] = [] # convert raw_data (bytes type) if tensor.raw_data: # convert n.raw_data to float float32_list = np.fromstring(tensor.raw_data, dtype='float32') # convert float to float16 float16_list = np.float16(float32_list) # convert float16 to bytes and write back to raw_data tensor.raw_data = float16_list.tostring() return tensor
[ "def", "convert_tensor_float_to_float16", "(", "tensor", ")", ":", "if", "not", "isinstance", "(", "tensor", ",", "onnx_proto", ".", "TensorProto", ")", ":", "raise", "ValueError", "(", "'Expected input type is an ONNX TensorProto but got %s'", "%", "type", "(", "tens...
Convert tensor float to float16. :param tensor: TensorProto object :return tensor_float16: converted TensorProto object Example: :: from onnxmltools.utils.float16_converter import convert_tensor_float_to_float16 new_tensor = convert_tensor_float_to_float16(tensor)
[ "Convert", "tensor", "float", "to", "float16", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/float16.py#L23-L56
229,229
onnx/onnxmltools
onnxutils/onnxconverter_common/metadata_props.py
_validate_metadata
def _validate_metadata(metadata_props): ''' Validate metadata properties and possibly show warnings or throw exceptions. :param metadata_props: A dictionary of metadata properties, with property names and values (see :func:`~onnxmltools.utils.metadata_props.add_metadata_props` for examples) ''' if len(CaseInsensitiveDict(metadata_props)) != len(metadata_props): raise RuntimeError('Duplicate metadata props found') for key, value in metadata_props.items(): valid_values = KNOWN_METADATA_PROPS.get(key) if valid_values and value.lower() not in valid_values: warnings.warn('Key {} has invalid value {}. Valid values are {}'.format(key, value, valid_values))
python
def _validate_metadata(metadata_props): ''' Validate metadata properties and possibly show warnings or throw exceptions. :param metadata_props: A dictionary of metadata properties, with property names and values (see :func:`~onnxmltools.utils.metadata_props.add_metadata_props` for examples) ''' if len(CaseInsensitiveDict(metadata_props)) != len(metadata_props): raise RuntimeError('Duplicate metadata props found') for key, value in metadata_props.items(): valid_values = KNOWN_METADATA_PROPS.get(key) if valid_values and value.lower() not in valid_values: warnings.warn('Key {} has invalid value {}. Valid values are {}'.format(key, value, valid_values))
[ "def", "_validate_metadata", "(", "metadata_props", ")", ":", "if", "len", "(", "CaseInsensitiveDict", "(", "metadata_props", ")", ")", "!=", "len", "(", "metadata_props", ")", ":", "raise", "RuntimeError", "(", "'Duplicate metadata props found'", ")", "for", "key...
Validate metadata properties and possibly show warnings or throw exceptions. :param metadata_props: A dictionary of metadata properties, with property names and values (see :func:`~onnxmltools.utils.metadata_props.add_metadata_props` for examples)
[ "Validate", "metadata", "properties", "and", "possibly", "show", "warnings", "or", "throw", "exceptions", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/metadata_props.py#L13-L25
229,230
onnx/onnxmltools
onnxutils/onnxconverter_common/metadata_props.py
set_denotation
def set_denotation(onnx_model, input_name, denotation, target_opset, dimension_denotation=None): ''' Set input type denotation and dimension denotation. Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO). This information can be used by the backend. One example where it is useful is in images: Whenever data is bound to a tensor with type denotation IMAGE, the backend can process the data (such as transforming the color space and pixel format) based on model metadata properties. :param onnx_model: ONNX model object :param input_name: Name of input tensor to edit (example: `'data0'`) :param denotation: Input type denotation (`documentation <https://github.com/onnx/onnx/blob/master/docs/TypeDenotation.md#type-denotation-definition>`_) (example: `'IMAGE'`) :param target_opset: Target ONNX opset :param dimension_denotation: List of dimension type denotations. The length of the list must be the same of the number of dimensions in the tensor (`documentation https://github.com/onnx/onnx/blob/master/docs/DimensionDenotation.md#denotation-definition>`_) (example: `['DATA_BATCH', 'DATA_CHANNEL', 'DATA_FEATURE', 'DATA_FEATURE']`) ''' if target_opset < 7: warnings.warn('Denotation is not supported in targeted opset - %d' % target_opset) return for graph_input in onnx_model.graph.input: if graph_input.name == input_name: graph_input.type.denotation = denotation if dimension_denotation: dimensions = graph_input.type.tensor_type.shape.dim if len(dimension_denotation) != len(dimensions): raise RuntimeError('Wrong number of dimensions: input "{}" has {} dimensions'.format(input_name, len(dimensions))) for dimension, channel_denotation in zip(dimensions, dimension_denotation): dimension.denotation = channel_denotation return onnx_model raise RuntimeError('Input "{}" not found'.format(input_name))
python
def set_denotation(onnx_model, input_name, denotation, target_opset, dimension_denotation=None): ''' Set input type denotation and dimension denotation. Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO). This information can be used by the backend. One example where it is useful is in images: Whenever data is bound to a tensor with type denotation IMAGE, the backend can process the data (such as transforming the color space and pixel format) based on model metadata properties. :param onnx_model: ONNX model object :param input_name: Name of input tensor to edit (example: `'data0'`) :param denotation: Input type denotation (`documentation <https://github.com/onnx/onnx/blob/master/docs/TypeDenotation.md#type-denotation-definition>`_) (example: `'IMAGE'`) :param target_opset: Target ONNX opset :param dimension_denotation: List of dimension type denotations. The length of the list must be the same of the number of dimensions in the tensor (`documentation https://github.com/onnx/onnx/blob/master/docs/DimensionDenotation.md#denotation-definition>`_) (example: `['DATA_BATCH', 'DATA_CHANNEL', 'DATA_FEATURE', 'DATA_FEATURE']`) ''' if target_opset < 7: warnings.warn('Denotation is not supported in targeted opset - %d' % target_opset) return for graph_input in onnx_model.graph.input: if graph_input.name == input_name: graph_input.type.denotation = denotation if dimension_denotation: dimensions = graph_input.type.tensor_type.shape.dim if len(dimension_denotation) != len(dimensions): raise RuntimeError('Wrong number of dimensions: input "{}" has {} dimensions'.format(input_name, len(dimensions))) for dimension, channel_denotation in zip(dimensions, dimension_denotation): dimension.denotation = channel_denotation return onnx_model raise RuntimeError('Input "{}" not found'.format(input_name))
[ "def", "set_denotation", "(", "onnx_model", ",", "input_name", ",", "denotation", ",", "target_opset", ",", "dimension_denotation", "=", "None", ")", ":", "if", "target_opset", "<", "7", ":", "warnings", ".", "warn", "(", "'Denotation is not supported in targeted op...
Set input type denotation and dimension denotation. Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO). This information can be used by the backend. One example where it is useful is in images: Whenever data is bound to a tensor with type denotation IMAGE, the backend can process the data (such as transforming the color space and pixel format) based on model metadata properties. :param onnx_model: ONNX model object :param input_name: Name of input tensor to edit (example: `'data0'`) :param denotation: Input type denotation (`documentation <https://github.com/onnx/onnx/blob/master/docs/TypeDenotation.md#type-denotation-definition>`_) (example: `'IMAGE'`) :param target_opset: Target ONNX opset :param dimension_denotation: List of dimension type denotations. The length of the list must be the same of the number of dimensions in the tensor (`documentation https://github.com/onnx/onnx/blob/master/docs/DimensionDenotation.md#denotation-definition>`_) (example: `['DATA_BATCH', 'DATA_CHANNEL', 'DATA_FEATURE', 'DATA_FEATURE']`)
[ "Set", "input", "type", "denotation", "and", "dimension", "denotation", "." ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/metadata_props.py#L52-L83
229,231
onnx/onnxmltools
onnxmltools/convert/sparkml/operator_converters/common.py
concatenate_variables
def concatenate_variables(scope, variables, container): ''' This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all integer inputs would be converted to floats before concatenation. ''' # Check if it's possible to concatenate those inputs. type_set = set(type(variable.type) for variable in variables) number_type_set = {FloatType, FloatTensorType, Int64Type, Int64TensorType} if StringType in type_set and any(number_type in type_set for number_type in number_type_set): raise RuntimeError('We are not able to concatenate numerical tensor(s) and string tensor(s)') input_names = [] # input variables' names we want to concatenate input_dims = [] # dimensions of the variables that is going to be concatenated # Collect input variable names and do cast if needed for variable in variables: if isinstance(variable.type, (Int64TensorType, Int64Type)): input_names.append(convert_integer_to_float(scope, variable, container)) else: input_names.append(variable.full_name) # We assume input variables' shape are [1, C_1], ..., [1, C_n] if there are n inputs. input_dims.append(variable.type.shape[1]) if len(input_names) == 1: # No need to concatenate tensors if there is only one input return input_names[0] else: # To combine all inputs, we need a FeatureVectorizer op_type = 'FeatureVectorizer' attrs = {'name': scope.get_unique_operator_name(op_type), 'inputdimensions': input_dims} # Create a variable name to capture feature vectorizer's output concatenated_name = scope.get_unique_variable_name('concatenated') # Set up our FeatureVectorizer container.add_node(op_type, input_names, concatenated_name, op_domain='ai.onnx.ml', **attrs) return concatenated_name
python
def concatenate_variables(scope, variables, container): ''' This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all integer inputs would be converted to floats before concatenation. ''' # Check if it's possible to concatenate those inputs. type_set = set(type(variable.type) for variable in variables) number_type_set = {FloatType, FloatTensorType, Int64Type, Int64TensorType} if StringType in type_set and any(number_type in type_set for number_type in number_type_set): raise RuntimeError('We are not able to concatenate numerical tensor(s) and string tensor(s)') input_names = [] # input variables' names we want to concatenate input_dims = [] # dimensions of the variables that is going to be concatenated # Collect input variable names and do cast if needed for variable in variables: if isinstance(variable.type, (Int64TensorType, Int64Type)): input_names.append(convert_integer_to_float(scope, variable, container)) else: input_names.append(variable.full_name) # We assume input variables' shape are [1, C_1], ..., [1, C_n] if there are n inputs. input_dims.append(variable.type.shape[1]) if len(input_names) == 1: # No need to concatenate tensors if there is only one input return input_names[0] else: # To combine all inputs, we need a FeatureVectorizer op_type = 'FeatureVectorizer' attrs = {'name': scope.get_unique_operator_name(op_type), 'inputdimensions': input_dims} # Create a variable name to capture feature vectorizer's output concatenated_name = scope.get_unique_variable_name('concatenated') # Set up our FeatureVectorizer container.add_node(op_type, input_names, concatenated_name, op_domain='ai.onnx.ml', **attrs) return concatenated_name
[ "def", "concatenate_variables", "(", "scope", ",", "variables", ",", "container", ")", ":", "# Check if it's possible to concatenate those inputs.", "type_set", "=", "set", "(", "type", "(", "variable", ".", "type", ")", "for", "variable", "in", "variables", ")", ...
This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all integer inputs would be converted to floats before concatenation.
[ "This", "function", "allocate", "operators", "to", "from", "a", "float", "tensor", "by", "concatenating", "all", "input", "variables", ".", "Notice", "that", "if", "all", "integer", "inputs", "would", "be", "converted", "to", "floats", "before", "concatenation",...
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/sparkml/operator_converters/common.py#L18-L54
229,232
onnx/onnxmltools
onnxutils/onnxconverter_common/data_types.py
find_type_conversion
def find_type_conversion(source_type, target_type): """ Find the operator name for converting source_type into target_type """ if type(source_type) == type(target_type): return 'identity' elif type(target_type) == FloatTensorType: return 'imageToFloatTensor' else: raise ValueError('Unsupported type conversion from %s to %s' % ( source_type, target_type))
python
def find_type_conversion(source_type, target_type): if type(source_type) == type(target_type): return 'identity' elif type(target_type) == FloatTensorType: return 'imageToFloatTensor' else: raise ValueError('Unsupported type conversion from %s to %s' % ( source_type, target_type))
[ "def", "find_type_conversion", "(", "source_type", ",", "target_type", ")", ":", "if", "type", "(", "source_type", ")", "==", "type", "(", "target_type", ")", ":", "return", "'identity'", "elif", "type", "(", "target_type", ")", "==", "FloatTensorType", ":", ...
Find the operator name for converting source_type into target_type
[ "Find", "the", "operator", "name", "for", "converting", "source_type", "into", "target_type" ]
d4e4c31990fc2d9fd1f92139f497d360914c9df2
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/data_types.py#L219-L229
229,233
jazzband/django-axes
axes/helpers.py
get_cool_off
def get_cool_off() -> Optional[timedelta]: """ Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME. The return value is either None or timedelta. Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours, and this function offers a unified _timedelta or None_ representation of that configuration for use with the Axes internal implementations. :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type. """ cool_off = settings.AXES_COOLOFF_TIME if isinstance(cool_off, int): return timedelta(hours=cool_off) return cool_off
python
def get_cool_off() -> Optional[timedelta]: cool_off = settings.AXES_COOLOFF_TIME if isinstance(cool_off, int): return timedelta(hours=cool_off) return cool_off
[ "def", "get_cool_off", "(", ")", "->", "Optional", "[", "timedelta", "]", ":", "cool_off", "=", "settings", ".", "AXES_COOLOFF_TIME", "if", "isinstance", "(", "cool_off", ",", "int", ")", ":", "return", "timedelta", "(", "hours", "=", "cool_off", ")", "ret...
Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME. The return value is either None or timedelta. Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours, and this function offers a unified _timedelta or None_ representation of that configuration for use with the Axes internal implementations. :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type.
[ "Return", "the", "login", "cool", "off", "time", "interpreted", "from", "settings", ".", "AXES_COOLOFF_TIME", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L45-L62
229,234
jazzband/django-axes
axes/helpers.py
get_credentials
def get_credentials(username: str = None, **kwargs) -> dict: """ Calculate credentials for Axes to use internally from given username and kwargs. Axes will set the username value into the key defined with ``settings.AXES_USERNAME_FORM_FIELD`` and update the credentials dictionary with the kwargs given on top of that. """ credentials = {settings.AXES_USERNAME_FORM_FIELD: username} credentials.update(kwargs) return credentials
python
def get_credentials(username: str = None, **kwargs) -> dict: credentials = {settings.AXES_USERNAME_FORM_FIELD: username} credentials.update(kwargs) return credentials
[ "def", "get_credentials", "(", "username", ":", "str", "=", "None", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "credentials", "=", "{", "settings", ".", "AXES_USERNAME_FORM_FIELD", ":", "username", "}", "credentials", ".", "update", "(", "kwargs", ")...
Calculate credentials for Axes to use internally from given username and kwargs. Axes will set the username value into the key defined with ``settings.AXES_USERNAME_FORM_FIELD`` and update the credentials dictionary with the kwargs given on top of that.
[ "Calculate", "credentials", "for", "Axes", "to", "use", "internally", "from", "given", "username", "and", "kwargs", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L93-L103
229,235
jazzband/django-axes
axes/helpers.py
get_client_username
def get_client_username(request: AxesHttpRequest, credentials: dict = None) -> str: """ Resolve client username from the given request or credentials if supplied. The order of preference for fetching the username is as follows: 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``) 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``) :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source """ if settings.AXES_USERNAME_CALLABLE: log.debug('Using settings.AXES_USERNAME_CALLABLE to get username') if callable(settings.AXES_USERNAME_CALLABLE): return settings.AXES_USERNAME_CALLABLE(request, credentials) if isinstance(settings.AXES_USERNAME_CALLABLE, str): return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials) raise TypeError('settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None.') if credentials: log.debug('Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD') return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None) log.debug('Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD') return request.POST.get(settings.AXES_USERNAME_FORM_FIELD, None)
python
def get_client_username(request: AxesHttpRequest, credentials: dict = None) -> str: if settings.AXES_USERNAME_CALLABLE: log.debug('Using settings.AXES_USERNAME_CALLABLE to get username') if callable(settings.AXES_USERNAME_CALLABLE): return settings.AXES_USERNAME_CALLABLE(request, credentials) if isinstance(settings.AXES_USERNAME_CALLABLE, str): return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials) raise TypeError('settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None.') if credentials: log.debug('Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD') return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None) log.debug('Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD') return request.POST.get(settings.AXES_USERNAME_FORM_FIELD, None)
[ "def", "get_client_username", "(", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "str", ":", "if", "settings", ".", "AXES_USERNAME_CALLABLE", ":", "log", ".", "debug", "(", "'Using settings.AXES_USERNAME_CALLABLE to get ...
Resolve client username from the given request or credentials if supplied. The order of preference for fetching the username is as follows: 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``) 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``) :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source
[ "Resolve", "client", "username", "from", "the", "given", "request", "or", "credentials", "if", "supplied", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L106-L134
229,236
jazzband/django-axes
axes/helpers.py
get_client_ip_address
def get_client_ip_address(request: HttpRequest) -> str: """ Get client IP address as configured by the user. The django-ipware package is used for address resolution and parameters can be configured in the Axes package. """ client_ip_address, _ = ipware.ip2.get_client_ip( request, proxy_order=settings.AXES_PROXY_ORDER, proxy_count=settings.AXES_PROXY_COUNT, proxy_trusted_ips=settings.AXES_PROXY_TRUSTED_IPS, request_header_order=settings.AXES_META_PRECEDENCE_ORDER, ) return str(ip_address(client_ip_address))
python
def get_client_ip_address(request: HttpRequest) -> str: client_ip_address, _ = ipware.ip2.get_client_ip( request, proxy_order=settings.AXES_PROXY_ORDER, proxy_count=settings.AXES_PROXY_COUNT, proxy_trusted_ips=settings.AXES_PROXY_TRUSTED_IPS, request_header_order=settings.AXES_META_PRECEDENCE_ORDER, ) return str(ip_address(client_ip_address))
[ "def", "get_client_ip_address", "(", "request", ":", "HttpRequest", ")", "->", "str", ":", "client_ip_address", ",", "_", "=", "ipware", ".", "ip2", ".", "get_client_ip", "(", "request", ",", "proxy_order", "=", "settings", ".", "AXES_PROXY_ORDER", ",", "proxy...
Get client IP address as configured by the user. The django-ipware package is used for address resolution and parameters can be configured in the Axes package.
[ "Get", "client", "IP", "address", "as", "configured", "by", "the", "user", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L137-L153
229,237
jazzband/django-axes
axes/helpers.py
get_client_parameters
def get_client_parameters(username: str, ip_address: str, user_agent: str) -> dict: """ Get query parameters for filtering AccessAttempt queryset. This method returns a dict that guarantees iteration order for keys and values, and can so be used in e.g. the generation of hash keys or other deterministic functions. """ filter_kwargs = dict() if settings.AXES_ONLY_USER_FAILURES: # 1. Only individual usernames can be tracked with parametrization filter_kwargs['username'] = username else: if settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: # 2. A combination of username and IP address can be used as well filter_kwargs['username'] = username filter_kwargs['ip_address'] = ip_address else: # 3. Default case is to track the IP address only, which is the most secure option filter_kwargs['ip_address'] = ip_address if settings.AXES_USE_USER_AGENT: # 4. The HTTP User-Agent can be used to track e.g. one browser filter_kwargs['user_agent'] = user_agent return filter_kwargs
python
def get_client_parameters(username: str, ip_address: str, user_agent: str) -> dict: filter_kwargs = dict() if settings.AXES_ONLY_USER_FAILURES: # 1. Only individual usernames can be tracked with parametrization filter_kwargs['username'] = username else: if settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: # 2. A combination of username and IP address can be used as well filter_kwargs['username'] = username filter_kwargs['ip_address'] = ip_address else: # 3. Default case is to track the IP address only, which is the most secure option filter_kwargs['ip_address'] = ip_address if settings.AXES_USE_USER_AGENT: # 4. The HTTP User-Agent can be used to track e.g. one browser filter_kwargs['user_agent'] = user_agent return filter_kwargs
[ "def", "get_client_parameters", "(", "username", ":", "str", ",", "ip_address", ":", "str", ",", "user_agent", ":", "str", ")", "->", "dict", ":", "filter_kwargs", "=", "dict", "(", ")", "if", "settings", ".", "AXES_ONLY_USER_FAILURES", ":", "# 1. Only individ...
Get query parameters for filtering AccessAttempt queryset. This method returns a dict that guarantees iteration order for keys and values, and can so be used in e.g. the generation of hash keys or other deterministic functions.
[ "Get", "query", "parameters", "for", "filtering", "AccessAttempt", "queryset", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L168-L194
229,238
jazzband/django-axes
axes/helpers.py
get_query_str
def get_query_str(query: Type[QueryDict], max_length: int = 1024) -> str: """ Turns a query dictionary into an easy-to-read list of key-value pairs. If a field is called either ``'password'`` or ``settings.AXES_PASSWORD_FORM_FIELD`` it will be excluded. The length of the output is limited to max_length to avoid a DoS attack via excessively large payloads. """ query_dict = query.copy() query_dict.pop('password', None) query_dict.pop(settings.AXES_PASSWORD_FORM_FIELD, None) query_str = '\n'.join( f'{key}={value}' for key, value in query_dict.items() ) return query_str[:max_length]
python
def get_query_str(query: Type[QueryDict], max_length: int = 1024) -> str: query_dict = query.copy() query_dict.pop('password', None) query_dict.pop(settings.AXES_PASSWORD_FORM_FIELD, None) query_str = '\n'.join( f'{key}={value}' for key, value in query_dict.items() ) return query_str[:max_length]
[ "def", "get_query_str", "(", "query", ":", "Type", "[", "QueryDict", "]", ",", "max_length", ":", "int", "=", "1024", ")", "->", "str", ":", "query_dict", "=", "query", ".", "copy", "(", ")", "query_dict", ".", "pop", "(", "'password'", ",", "None", ...
Turns a query dictionary into an easy-to-read list of key-value pairs. If a field is called either ``'password'`` or ``settings.AXES_PASSWORD_FORM_FIELD`` it will be excluded. The length of the output is limited to max_length to avoid a DoS attack via excessively large payloads.
[ "Turns", "a", "query", "dictionary", "into", "an", "easy", "-", "to", "-", "read", "list", "of", "key", "-", "value", "pairs", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L235-L254
229,239
jazzband/django-axes
axes/helpers.py
is_client_ip_address_whitelisted
def is_client_ip_address_whitelisted(request: AxesHttpRequest): """ Check if the given request refers to a whitelisted IP. """ if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True return False
python
def is_client_ip_address_whitelisted(request: AxesHttpRequest): if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True return False
[ "def", "is_client_ip_address_whitelisted", "(", "request", ":", "AxesHttpRequest", ")", ":", "if", "settings", ".", "AXES_NEVER_LOCKOUT_WHITELIST", "and", "is_ip_address_in_whitelist", "(", "request", ".", "axes_ip_address", ")", ":", "return", "True", "if", "settings",...
Check if the given request refers to a whitelisted IP.
[ "Check", "if", "the", "given", "request", "refers", "to", "a", "whitelisted", "IP", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L315-L326
229,240
jazzband/django-axes
axes/helpers.py
is_client_ip_address_blacklisted
def is_client_ip_address_blacklisted(request: AxesHttpRequest) -> bool: """ Check if the given request refers to a blacklisted IP. """ if is_ip_address_in_blacklist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(request.axes_ip_address): return True return False
python
def is_client_ip_address_blacklisted(request: AxesHttpRequest) -> bool: if is_ip_address_in_blacklist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(request.axes_ip_address): return True return False
[ "def", "is_client_ip_address_blacklisted", "(", "request", ":", "AxesHttpRequest", ")", "->", "bool", ":", "if", "is_ip_address_in_blacklist", "(", "request", ".", "axes_ip_address", ")", ":", "return", "True", "if", "settings", ".", "AXES_ONLY_WHITELIST", "and", "n...
Check if the given request refers to a blacklisted IP.
[ "Check", "if", "the", "given", "request", "refers", "to", "a", "blacklisted", "IP", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L329-L340
229,241
jazzband/django-axes
axes/helpers.py
is_client_method_whitelisted
def is_client_method_whitelisted(request: AxesHttpRequest) -> bool: """ Check if the given request uses a whitelisted method. """ if settings.AXES_NEVER_LOCKOUT_GET and request.method == 'GET': return True return False
python
def is_client_method_whitelisted(request: AxesHttpRequest) -> bool: if settings.AXES_NEVER_LOCKOUT_GET and request.method == 'GET': return True return False
[ "def", "is_client_method_whitelisted", "(", "request", ":", "AxesHttpRequest", ")", "->", "bool", ":", "if", "settings", ".", "AXES_NEVER_LOCKOUT_GET", "and", "request", ".", "method", "==", "'GET'", ":", "return", "True", "return", "False" ]
Check if the given request uses a whitelisted method.
[ "Check", "if", "the", "given", "request", "uses", "a", "whitelisted", "method", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L343-L351
229,242
jazzband/django-axes
axes/helpers.py
get_client_cache_key
def get_client_cache_key(request_or_attempt: Union[HttpRequest, Any], credentials: dict = None) -> str: """ Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information :return cache_key: Hash key that is usable for Django cache backends """ if isinstance(request_or_attempt, HttpRequest): username = get_client_username(request_or_attempt, credentials) ip_address = get_client_ip_address(request_or_attempt) user_agent = get_client_user_agent(request_or_attempt) else: username = request_or_attempt.username ip_address = request_or_attempt.ip_address user_agent = request_or_attempt.user_agent filter_kwargs = get_client_parameters(username, ip_address, user_agent) cache_key_components = ''.join(filter_kwargs.values()) cache_key_digest = md5(cache_key_components.encode()).hexdigest() cache_key = f'axes-{cache_key_digest}' return cache_key
python
def get_client_cache_key(request_or_attempt: Union[HttpRequest, Any], credentials: dict = None) -> str: if isinstance(request_or_attempt, HttpRequest): username = get_client_username(request_or_attempt, credentials) ip_address = get_client_ip_address(request_or_attempt) user_agent = get_client_user_agent(request_or_attempt) else: username = request_or_attempt.username ip_address = request_or_attempt.ip_address user_agent = request_or_attempt.user_agent filter_kwargs = get_client_parameters(username, ip_address, user_agent) cache_key_components = ''.join(filter_kwargs.values()) cache_key_digest = md5(cache_key_components.encode()).hexdigest() cache_key = f'axes-{cache_key_digest}' return cache_key
[ "def", "get_client_cache_key", "(", "request_or_attempt", ":", "Union", "[", "HttpRequest", ",", "Any", "]", ",", "credentials", ":", "dict", "=", "None", ")", "->", "str", ":", "if", "isinstance", "(", "request_or_attempt", ",", "HttpRequest", ")", ":", "us...
Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information :return cache_key: Hash key that is usable for Django cache backends
[ "Build", "cache", "key", "name", "from", "request", "or", "AccessAttempt", "object", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/helpers.py#L354-L378
229,243
jazzband/django-axes
axes/handlers/database.py
AxesDatabaseHandler.user_login_failed
def user_login_failed( self, sender, credentials: dict, request: AxesHttpRequest = None, **kwargs ): # pylint: disable=too-many-locals """ When user login fails, save AccessAttempt record in database and lock user out if necessary. :raises AxesSignalPermissionDenied: if user should be locked out. """ if request is None: log.error('AXES: AxesDatabaseHandler.user_login_failed does not function without a request.') return # 1. database query: Clean up expired user attempts from the database before logging new attempts clean_expired_user_attempts(request.axes_attempt_time) username = get_client_username(request, credentials) client_str = get_client_str(username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info) get_data = get_query_str(request.GET) post_data = get_query_str(request.POST) if self.is_whitelisted(request, credentials): log.info('AXES: Login failed from whitelisted client %s.', client_str) return # 2. database query: Calculate the current maximum failure number from the existing attempts failures_since_start = 1 + self.get_failures(request, credentials) # 3. database query: Insert or update access records with the new failure data if failures_since_start > 1: # Update failed attempt information but do not touch the username, IP address, or user agent fields, # because attackers can request the site with multiple different configurations # in order to bypass the defense mechanisms that are used by the site. log.warning( 'AXES: Repeated login failure by %s. Count = %d of %d. Updating existing record in the database.', client_str, failures_since_start, settings.AXES_FAILURE_LIMIT, ) separator = '\n---------\n' attempts = get_user_attempts(request, credentials) attempts.update( get_data=Concat('get_data', Value(separator + get_data)), post_data=Concat('post_data', Value(separator + post_data)), http_accept=request.axes_http_accept, path_info=request.axes_path_info, failures_since_start=failures_since_start, attempt_time=request.axes_attempt_time, ) else: # Record failed attempt with all the relevant information. # Filtering based on username, IP address and user agent handled elsewhere, # and this handler just records the available information for further use. log.warning( 'AXES: New login failure by %s. Creating new record in the database.', client_str, ) AccessAttempt.objects.create( username=username, ip_address=request.axes_ip_address, user_agent=request.axes_user_agent, get_data=get_data, post_data=post_data, http_accept=request.axes_http_accept, path_info=request.axes_path_info, failures_since_start=failures_since_start, attempt_time=request.axes_attempt_time, ) if failures_since_start >= settings.AXES_FAILURE_LIMIT: log.warning('AXES: Locking out %s after repeated login failures.', client_str) user_locked_out.send( 'axes', request=request, username=username, ip_address=request.axes_ip_address, ) raise AxesSignalPermissionDenied('Locked out due to repeated login failures.')
python
def user_login_failed( self, sender, credentials: dict, request: AxesHttpRequest = None, **kwargs ): # pylint: disable=too-many-locals if request is None: log.error('AXES: AxesDatabaseHandler.user_login_failed does not function without a request.') return # 1. database query: Clean up expired user attempts from the database before logging new attempts clean_expired_user_attempts(request.axes_attempt_time) username = get_client_username(request, credentials) client_str = get_client_str(username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info) get_data = get_query_str(request.GET) post_data = get_query_str(request.POST) if self.is_whitelisted(request, credentials): log.info('AXES: Login failed from whitelisted client %s.', client_str) return # 2. database query: Calculate the current maximum failure number from the existing attempts failures_since_start = 1 + self.get_failures(request, credentials) # 3. database query: Insert or update access records with the new failure data if failures_since_start > 1: # Update failed attempt information but do not touch the username, IP address, or user agent fields, # because attackers can request the site with multiple different configurations # in order to bypass the defense mechanisms that are used by the site. log.warning( 'AXES: Repeated login failure by %s. Count = %d of %d. Updating existing record in the database.', client_str, failures_since_start, settings.AXES_FAILURE_LIMIT, ) separator = '\n---------\n' attempts = get_user_attempts(request, credentials) attempts.update( get_data=Concat('get_data', Value(separator + get_data)), post_data=Concat('post_data', Value(separator + post_data)), http_accept=request.axes_http_accept, path_info=request.axes_path_info, failures_since_start=failures_since_start, attempt_time=request.axes_attempt_time, ) else: # Record failed attempt with all the relevant information. # Filtering based on username, IP address and user agent handled elsewhere, # and this handler just records the available information for further use. log.warning( 'AXES: New login failure by %s. Creating new record in the database.', client_str, ) AccessAttempt.objects.create( username=username, ip_address=request.axes_ip_address, user_agent=request.axes_user_agent, get_data=get_data, post_data=post_data, http_accept=request.axes_http_accept, path_info=request.axes_path_info, failures_since_start=failures_since_start, attempt_time=request.axes_attempt_time, ) if failures_since_start >= settings.AXES_FAILURE_LIMIT: log.warning('AXES: Locking out %s after repeated login failures.', client_str) user_locked_out.send( 'axes', request=request, username=username, ip_address=request.axes_ip_address, ) raise AxesSignalPermissionDenied('Locked out due to repeated login failures.')
[ "def", "user_login_failed", "(", "self", ",", "sender", ",", "credentials", ":", "dict", ",", "request", ":", "AxesHttpRequest", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=too-many-locals", "if", "request", "is", "None", ":", "log", "...
When user login fails, save AccessAttempt record in database and lock user out if necessary. :raises AxesSignalPermissionDenied: if user should be locked out.
[ "When", "user", "login", "fails", "save", "AccessAttempt", "record", "in", "database", "and", "lock", "user", "out", "if", "necessary", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/database.py#L44-L133
229,244
jazzband/django-axes
axes/handlers/database.py
AxesDatabaseHandler.user_logged_out
def user_logged_out(self, sender, request: AxesHttpRequest, user, **kwargs): # pylint: disable=unused-argument """ When user logs out, update the AccessLog related to the user. """ # 1. database query: Clean up expired user attempts from the database clean_expired_user_attempts(request.axes_attempt_time) username = user.get_username() client_str = get_client_str(username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info) log.info('AXES: Successful logout by %s.', client_str) if username and not settings.AXES_DISABLE_ACCESS_LOG: # 2. database query: Update existing attempt logs with logout time AccessLog.objects.filter( username=username, logout_time__isnull=True, ).update( logout_time=request.axes_attempt_time, )
python
def user_logged_out(self, sender, request: AxesHttpRequest, user, **kwargs): # pylint: disable=unused-argument # 1. database query: Clean up expired user attempts from the database clean_expired_user_attempts(request.axes_attempt_time) username = user.get_username() client_str = get_client_str(username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info) log.info('AXES: Successful logout by %s.', client_str) if username and not settings.AXES_DISABLE_ACCESS_LOG: # 2. database query: Update existing attempt logs with logout time AccessLog.objects.filter( username=username, logout_time__isnull=True, ).update( logout_time=request.axes_attempt_time, )
[ "def", "user_logged_out", "(", "self", ",", "sender", ",", "request", ":", "AxesHttpRequest", ",", "user", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "# 1. database query: Clean up expired user attempts from the database", "clean_expired_user_atte...
When user logs out, update the AccessLog related to the user.
[ "When", "user", "logs", "out", "update", "the", "AccessLog", "related", "to", "the", "user", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/database.py#L165-L185
229,245
jazzband/django-axes
axes/handlers/cache.py
AxesCacheHandler.user_login_failed
def user_login_failed( self, sender, credentials: dict, request: AxesHttpRequest = None, **kwargs ): # pylint: disable=too-many-locals """ When user login fails, save attempt record in cache and lock user out if necessary. :raises AxesSignalPermissionDenied: if user should be locked out. """ if request is None: log.error('AXES: AxesCacheHandler.user_login_failed does not function without a request.') return username = get_client_username(request, credentials) client_str = get_client_str(username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info) if self.is_whitelisted(request, credentials): log.info('AXES: Login failed from whitelisted client %s.', client_str) return failures_since_start = 1 + self.get_failures(request, credentials) if failures_since_start > 1: log.warning( 'AXES: Repeated login failure by %s. Count = %d of %d. Updating existing record in the cache.', client_str, failures_since_start, settings.AXES_FAILURE_LIMIT, ) else: log.warning( 'AXES: New login failure by %s. Creating new record in the cache.', client_str, ) cache_key = get_client_cache_key(request, credentials) self.cache.set(cache_key, failures_since_start, self.cache_timeout) if failures_since_start >= settings.AXES_FAILURE_LIMIT: log.warning('AXES: Locking out %s after repeated login failures.', client_str) user_locked_out.send( 'axes', request=request, username=username, ip_address=request.axes_ip_address, ) raise AxesSignalPermissionDenied('Locked out due to repeated login failures.')
python
def user_login_failed( self, sender, credentials: dict, request: AxesHttpRequest = None, **kwargs ): # pylint: disable=too-many-locals if request is None: log.error('AXES: AxesCacheHandler.user_login_failed does not function without a request.') return username = get_client_username(request, credentials) client_str = get_client_str(username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info) if self.is_whitelisted(request, credentials): log.info('AXES: Login failed from whitelisted client %s.', client_str) return failures_since_start = 1 + self.get_failures(request, credentials) if failures_since_start > 1: log.warning( 'AXES: Repeated login failure by %s. Count = %d of %d. Updating existing record in the cache.', client_str, failures_since_start, settings.AXES_FAILURE_LIMIT, ) else: log.warning( 'AXES: New login failure by %s. Creating new record in the cache.', client_str, ) cache_key = get_client_cache_key(request, credentials) self.cache.set(cache_key, failures_since_start, self.cache_timeout) if failures_since_start >= settings.AXES_FAILURE_LIMIT: log.warning('AXES: Locking out %s after repeated login failures.', client_str) user_locked_out.send( 'axes', request=request, username=username, ip_address=request.axes_ip_address, ) raise AxesSignalPermissionDenied('Locked out due to repeated login failures.')
[ "def", "user_login_failed", "(", "self", ",", "sender", ",", "credentials", ":", "dict", ",", "request", ":", "AxesHttpRequest", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=too-many-locals", "if", "request", "is", "None", ":", "log", "...
When user login fails, save attempt record in cache and lock user out if necessary. :raises AxesSignalPermissionDenied: if user should be locked out.
[ "When", "user", "login", "fails", "save", "attempt", "record", "in", "cache", "and", "lock", "user", "out", "if", "necessary", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/cache.py#L33-L85
229,246
jazzband/django-axes
axes/middleware.py
AxesMiddleware.update_request
def update_request(self, request: HttpRequest): """ Update given Django ``HttpRequest`` with necessary attributes before passing it on the ``get_response`` for further Django middleware and view processing. """ request.axes_attempt_time = now() request.axes_ip_address = get_client_ip_address(request) request.axes_user_agent = get_client_user_agent(request) request.axes_path_info = get_client_path_info(request) request.axes_http_accept = get_client_http_accept(request)
python
def update_request(self, request: HttpRequest): request.axes_attempt_time = now() request.axes_ip_address = get_client_ip_address(request) request.axes_user_agent = get_client_user_agent(request) request.axes_path_info = get_client_path_info(request) request.axes_http_accept = get_client_http_accept(request)
[ "def", "update_request", "(", "self", ",", "request", ":", "HttpRequest", ")", ":", "request", ".", "axes_attempt_time", "=", "now", "(", ")", "request", ".", "axes_ip_address", "=", "get_client_ip_address", "(", "request", ")", "request", ".", "axes_user_agent"...
Update given Django ``HttpRequest`` with necessary attributes before passing it on the ``get_response`` for further Django middleware and view processing.
[ "Update", "given", "Django", "HttpRequest", "with", "necessary", "attributes", "before", "passing", "it", "on", "the", "get_response", "for", "further", "Django", "middleware", "and", "view", "processing", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/middleware.py#L38-L49
229,247
jazzband/django-axes
axes/middleware.py
AxesMiddleware.process_exception
def process_exception(self, request: AxesHttpRequest, exception): # pylint: disable=inconsistent-return-statements """ Exception handler that processes exceptions raised by the Axes signal handler when request fails with login. Only ``axes.exceptions.AxesSignalPermissionDenied`` exception is handled by this middleware. """ if isinstance(exception, AxesSignalPermissionDenied): return get_lockout_response(request)
python
def process_exception(self, request: AxesHttpRequest, exception): # pylint: disable=inconsistent-return-statements if isinstance(exception, AxesSignalPermissionDenied): return get_lockout_response(request)
[ "def", "process_exception", "(", "self", ",", "request", ":", "AxesHttpRequest", ",", "exception", ")", ":", "# pylint: disable=inconsistent-return-statements", "if", "isinstance", "(", "exception", ",", "AxesSignalPermissionDenied", ")", ":", "return", "get_lockout_respo...
Exception handler that processes exceptions raised by the Axes signal handler when request fails with login. Only ``axes.exceptions.AxesSignalPermissionDenied`` exception is handled by this middleware.
[ "Exception", "handler", "that", "processes", "exceptions", "raised", "by", "the", "Axes", "signal", "handler", "when", "request", "fails", "with", "login", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/middleware.py#L51-L59
229,248
jazzband/django-axes
axes/handlers/base.py
AxesHandler.is_allowed
def is_allowed(self, request: AxesHttpRequest, credentials: dict = None) -> bool: """ Checks if the user is allowed to access or use given functionality such as a login view or authentication. This method is abstract and other backends can specialize it as needed, but the default implementation checks if the user has attempted to authenticate into the site too many times through the Django authentication backends and returns ``False``if user exceeds the configured Axes thresholds. This checker can implement arbitrary checks such as IP whitelisting or blacklisting, request frequency checking, failed attempt monitoring or similar functions. Please refer to the ``axes.handlers.database.AxesDatabaseHandler`` for the default implementation and inspiration on some common checks and access restrictions before writing your own implementation. """ if self.is_blacklisted(request, credentials): return False if self.is_whitelisted(request, credentials): return True if self.is_locked(request, credentials): return False return True
python
def is_allowed(self, request: AxesHttpRequest, credentials: dict = None) -> bool: if self.is_blacklisted(request, credentials): return False if self.is_whitelisted(request, credentials): return True if self.is_locked(request, credentials): return False return True
[ "def", "is_allowed", "(", "self", ",", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "bool", ":", "if", "self", ".", "is_blacklisted", "(", "request", ",", "credentials", ")", ":", "return", "False", "if", "s...
Checks if the user is allowed to access or use given functionality such as a login view or authentication. This method is abstract and other backends can specialize it as needed, but the default implementation checks if the user has attempted to authenticate into the site too many times through the Django authentication backends and returns ``False``if user exceeds the configured Axes thresholds. This checker can implement arbitrary checks such as IP whitelisting or blacklisting, request frequency checking, failed attempt monitoring or similar functions. Please refer to the ``axes.handlers.database.AxesDatabaseHandler`` for the default implementation and inspiration on some common checks and access restrictions before writing your own implementation.
[ "Checks", "if", "the", "user", "is", "allowed", "to", "access", "or", "use", "given", "functionality", "such", "as", "a", "login", "view", "or", "authentication", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/base.py#L20-L44
229,249
jazzband/django-axes
axes/handlers/base.py
AxesHandler.is_blacklisted
def is_blacklisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument """ Checks if the request or given credentials are blacklisted from access. """ if is_client_ip_address_blacklisted(request): return True return False
python
def is_blacklisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument if is_client_ip_address_blacklisted(request): return True return False
[ "def", "is_blacklisted", "(", "self", ",", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "bool", ":", "# pylint: disable=unused-argument", "if", "is_client_ip_address_blacklisted", "(", "request", ")", ":", "return", "...
Checks if the request or given credentials are blacklisted from access.
[ "Checks", "if", "the", "request", "or", "given", "credentials", "are", "blacklisted", "from", "access", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/base.py#L71-L79
229,250
jazzband/django-axes
axes/handlers/base.py
AxesHandler.is_whitelisted
def is_whitelisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument """ Checks if the request or given credentials are whitelisted for access. """ if is_client_ip_address_whitelisted(request): return True if is_client_method_whitelisted(request): return True return False
python
def is_whitelisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument if is_client_ip_address_whitelisted(request): return True if is_client_method_whitelisted(request): return True return False
[ "def", "is_whitelisted", "(", "self", ",", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "bool", ":", "# pylint: disable=unused-argument", "if", "is_client_ip_address_whitelisted", "(", "request", ")", ":", "return", "...
Checks if the request or given credentials are whitelisted for access.
[ "Checks", "if", "the", "request", "or", "given", "credentials", "are", "whitelisted", "for", "access", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/base.py#L81-L92
229,251
jazzband/django-axes
axes/handlers/base.py
AxesHandler.is_locked
def is_locked(self, request: AxesHttpRequest, credentials: dict = None) -> bool: """ Checks if the request or given credentials are locked. """ if settings.AXES_LOCK_OUT_AT_FAILURE: return self.get_failures(request, credentials) >= settings.AXES_FAILURE_LIMIT return False
python
def is_locked(self, request: AxesHttpRequest, credentials: dict = None) -> bool: if settings.AXES_LOCK_OUT_AT_FAILURE: return self.get_failures(request, credentials) >= settings.AXES_FAILURE_LIMIT return False
[ "def", "is_locked", "(", "self", ",", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "bool", ":", "if", "settings", ".", "AXES_LOCK_OUT_AT_FAILURE", ":", "return", "self", ".", "get_failures", "(", "request", ",",...
Checks if the request or given credentials are locked.
[ "Checks", "if", "the", "request", "or", "given", "credentials", "are", "locked", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/base.py#L94-L102
229,252
jazzband/django-axes
axes/utils.py
reset
def reset(ip: str = None, username: str = None) -> int: """ Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API. """ attempts = AccessAttempt.objects.all() if ip: attempts = attempts.filter(ip_address=ip) if username: attempts = attempts.filter(username=username) count, _ = attempts.delete() log.info('AXES: Reset %s access attempts from database.', count) return count
python
def reset(ip: str = None, username: str = None) -> int: attempts = AccessAttempt.objects.all() if ip: attempts = attempts.filter(ip_address=ip) if username: attempts = attempts.filter(username=username) count, _ = attempts.delete() log.info('AXES: Reset %s access attempts from database.', count) return count
[ "def", "reset", "(", "ip", ":", "str", "=", "None", ",", "username", ":", "str", "=", "None", ")", "->", "int", ":", "attempts", "=", "AccessAttempt", ".", "objects", ".", "all", "(", ")", "if", "ip", ":", "attempts", "=", "attempts", ".", "filter"...
Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API.
[ "Reset", "records", "that", "match", "IP", "or", "username", "and", "return", "the", "count", "of", "removed", "attempts", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/utils.py#L15-L32
229,253
jazzband/django-axes
axes/attempts.py
get_cool_off_threshold
def get_cool_off_threshold(attempt_time: datetime = None) -> datetime: """ Get threshold for fetching access attempts from the database. """ cool_off = get_cool_off() if cool_off is None: raise TypeError('Cool off threshold can not be calculated with settings.AXES_COOLOFF_TIME set to None') if attempt_time is None: return now() - cool_off return attempt_time - cool_off
python
def get_cool_off_threshold(attempt_time: datetime = None) -> datetime: cool_off = get_cool_off() if cool_off is None: raise TypeError('Cool off threshold can not be calculated with settings.AXES_COOLOFF_TIME set to None') if attempt_time is None: return now() - cool_off return attempt_time - cool_off
[ "def", "get_cool_off_threshold", "(", "attempt_time", ":", "datetime", "=", "None", ")", "->", "datetime", ":", "cool_off", "=", "get_cool_off", "(", ")", "if", "cool_off", "is", "None", ":", "raise", "TypeError", "(", "'Cool off threshold can not be calculated with...
Get threshold for fetching access attempts from the database.
[ "Get", "threshold", "for", "fetching", "access", "attempts", "from", "the", "database", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L19-L30
229,254
jazzband/django-axes
axes/attempts.py
filter_user_attempts
def filter_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: """ Return a queryset of AccessAttempts that match the given request and credentials. """ username = get_client_username(request, credentials) filter_kwargs = get_client_parameters(username, request.axes_ip_address, request.axes_user_agent) return AccessAttempt.objects.filter(**filter_kwargs)
python
def filter_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: username = get_client_username(request, credentials) filter_kwargs = get_client_parameters(username, request.axes_ip_address, request.axes_user_agent) return AccessAttempt.objects.filter(**filter_kwargs)
[ "def", "filter_user_attempts", "(", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "QuerySet", ":", "username", "=", "get_client_username", "(", "request", ",", "credentials", ")", "filter_kwargs", "=", "get_client_para...
Return a queryset of AccessAttempts that match the given request and credentials.
[ "Return", "a", "queryset", "of", "AccessAttempts", "that", "match", "the", "given", "request", "and", "credentials", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L33-L42
229,255
jazzband/django-axes
axes/attempts.py
get_user_attempts
def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: """ Get valid user attempts that match the given request and credentials. """ attempts = filter_user_attempts(request, credentials) if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Getting all access attempts from database because no AXES_COOLOFF_TIME is configured') return attempts threshold = get_cool_off_threshold(request.axes_attempt_time) log.debug('AXES: Getting access attempts that are newer than %s', threshold) return attempts.filter(attempt_time__gte=threshold)
python
def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: attempts = filter_user_attempts(request, credentials) if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Getting all access attempts from database because no AXES_COOLOFF_TIME is configured') return attempts threshold = get_cool_off_threshold(request.axes_attempt_time) log.debug('AXES: Getting access attempts that are newer than %s', threshold) return attempts.filter(attempt_time__gte=threshold)
[ "def", "get_user_attempts", "(", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "QuerySet", ":", "attempts", "=", "filter_user_attempts", "(", "request", ",", "credentials", ")", "if", "settings", ".", "AXES_COOLOFF_T...
Get valid user attempts that match the given request and credentials.
[ "Get", "valid", "user", "attempts", "that", "match", "the", "given", "request", "and", "credentials", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L45-L58
229,256
jazzband/django-axes
axes/attempts.py
clean_expired_user_attempts
def clean_expired_user_attempts(attempt_time: datetime = None) -> int: """ Clean expired user attempts from the database. """ if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured') return 0 threshold = get_cool_off_threshold(attempt_time) count, _ = AccessAttempt.objects.filter(attempt_time__lt=threshold).delete() log.info('AXES: Cleaned up %s expired access attempts from database that were older than %s', count, threshold) return count
python
def clean_expired_user_attempts(attempt_time: datetime = None) -> int: if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured') return 0 threshold = get_cool_off_threshold(attempt_time) count, _ = AccessAttempt.objects.filter(attempt_time__lt=threshold).delete() log.info('AXES: Cleaned up %s expired access attempts from database that were older than %s', count, threshold) return count
[ "def", "clean_expired_user_attempts", "(", "attempt_time", ":", "datetime", "=", "None", ")", "->", "int", ":", "if", "settings", ".", "AXES_COOLOFF_TIME", "is", "None", ":", "log", ".", "debug", "(", "'AXES: Skipping clean for expired access attempts because no AXES_CO...
Clean expired user attempts from the database.
[ "Clean", "expired", "user", "attempts", "from", "the", "database", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L61-L73
229,257
jazzband/django-axes
axes/attempts.py
reset_user_attempts
def reset_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> int: """ Reset all user attempts that match the given request and credentials. """ attempts = filter_user_attempts(request, credentials) count, _ = attempts.delete() log.info('AXES: Reset %s access attempts from database.', count) return count
python
def reset_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> int: attempts = filter_user_attempts(request, credentials) count, _ = attempts.delete() log.info('AXES: Reset %s access attempts from database.', count) return count
[ "def", "reset_user_attempts", "(", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "int", ":", "attempts", "=", "filter_user_attempts", "(", "request", ",", "credentials", ")", "count", ",", "_", "=", "attempts", "...
Reset all user attempts that match the given request and credentials.
[ "Reset", "all", "user", "attempts", "that", "match", "the", "given", "request", "and", "credentials", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L76-L86
229,258
jazzband/django-axes
axes/attempts.py
is_user_attempt_whitelisted
def is_user_attempt_whitelisted(request: AxesHttpRequest, credentials: dict = None) -> bool: """ Check if the given request or credentials refer to a whitelisted username. A whitelisted user has the magic ``nolockout`` property set. If the property is unknown or False or the user can not be found, this implementation fails gracefully and returns True. """ username_field = getattr(get_user_model(), 'USERNAME_FIELD', 'username') username_value = get_client_username(request, credentials) kwargs = { username_field: username_value } user_model = get_user_model() try: user = user_model.objects.get(**kwargs) return user.nolockout except (user_model.DoesNotExist, AttributeError): pass return False
python
def is_user_attempt_whitelisted(request: AxesHttpRequest, credentials: dict = None) -> bool: username_field = getattr(get_user_model(), 'USERNAME_FIELD', 'username') username_value = get_client_username(request, credentials) kwargs = { username_field: username_value } user_model = get_user_model() try: user = user_model.objects.get(**kwargs) return user.nolockout except (user_model.DoesNotExist, AttributeError): pass return False
[ "def", "is_user_attempt_whitelisted", "(", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "bool", ":", "username_field", "=", "getattr", "(", "get_user_model", "(", ")", ",", "'USERNAME_FIELD'", ",", "'username'", ")"...
Check if the given request or credentials refer to a whitelisted username. A whitelisted user has the magic ``nolockout`` property set. If the property is unknown or False or the user can not be found, this implementation fails gracefully and returns True.
[ "Check", "if", "the", "given", "request", "or", "credentials", "refer", "to", "a", "whitelisted", "username", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L89-L113
229,259
jazzband/django-axes
axes/handlers/proxy.py
AxesProxyHandler.get_implementation
def get_implementation(cls, force: bool = False) -> AxesHandler: """ Fetch and initialize configured handler implementation and memoize it to avoid reinitialization. This method is re-entrant and can be called multiple times from e.g. Django application loader. """ if force or not cls.implementation: cls.implementation = import_string(settings.AXES_HANDLER)() return cls.implementation
python
def get_implementation(cls, force: bool = False) -> AxesHandler: if force or not cls.implementation: cls.implementation = import_string(settings.AXES_HANDLER)() return cls.implementation
[ "def", "get_implementation", "(", "cls", ",", "force", ":", "bool", "=", "False", ")", "->", "AxesHandler", ":", "if", "force", "or", "not", "cls", ".", "implementation", ":", "cls", ".", "implementation", "=", "import_string", "(", "settings", ".", "AXES_...
Fetch and initialize configured handler implementation and memoize it to avoid reinitialization. This method is re-entrant and can be called multiple times from e.g. Django application loader.
[ "Fetch", "and", "initialize", "configured", "handler", "implementation", "and", "memoize", "it", "to", "avoid", "reinitialization", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/handlers/proxy.py#L27-L36
229,260
jazzband/django-axes
axes/apps.py
AppConfig.initialize
def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.logging_initialized: return cls.logging_initialized = True if not settings.AXES_VERBOSE: return log.info('AXES: BEGIN LOG') log.info('AXES: Using django-axes %s', get_version()) if settings.AXES_ONLY_USER_FAILURES: log.info('AXES: blocking by username only.') elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: log.info('AXES: blocking by combination of username and IP.') else: log.info('AXES: blocking by IP only.')
python
def initialize(cls): if cls.logging_initialized: return cls.logging_initialized = True if not settings.AXES_VERBOSE: return log.info('AXES: BEGIN LOG') log.info('AXES: Using django-axes %s', get_version()) if settings.AXES_ONLY_USER_FAILURES: log.info('AXES: blocking by username only.') elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: log.info('AXES: blocking by combination of username and IP.') else: log.info('AXES: blocking by IP only.')
[ "def", "initialize", "(", "cls", ")", ":", "if", "cls", ".", "logging_initialized", ":", "return", "cls", ".", "logging_initialized", "=", "True", "if", "not", "settings", ".", "AXES_VERBOSE", ":", "return", "log", ".", "info", "(", "'AXES: BEGIN LOG'", ")",...
Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup.
[ "Initialize", "Axes", "logging", "and", "show", "version", "information", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/apps.py#L16-L39
229,261
jazzband/django-axes
axes/backends.py
AxesBackend.authenticate
def authenticate(self, request: AxesHttpRequest, username: str = None, password: str = None, **kwargs: dict): """ Checks user lockout status and raise a PermissionDenied if user is not allowed to log in. This method interrupts the login flow and inserts error message directly to the ``response_context`` attribute that is supplied as a keyword argument. :keyword response_context: kwarg that will be have its ``error`` attribute updated with context. :raises AxesBackendRequestParameterRequired: if request parameter is not passed. :raises AxesBackendPermissionDenied: if user is already locked out. """ if request is None: raise AxesBackendRequestParameterRequired('AxesBackend requires a request as an argument to authenticate') credentials = get_credentials(username=username, password=password, **kwargs) if AxesProxyHandler.is_allowed(request, credentials): return # Locked out, don't try to authenticate, just update response_context and return. # Its a bit weird to pass a context and expect a response value but its nice to get a "why" back. error_msg = get_lockout_message() response_context = kwargs.get('response_context', {}) response_context['error'] = error_msg # Raise an error that stops the authentication flows at django.contrib.auth.authenticate. # This error stops bubbling up at the authenticate call which catches backend PermissionDenied errors. # After this error is caught by authenticate it emits a signal indicating user login failed, # which is processed by axes.signals.log_user_login_failed which logs the attempt and raises # a second exception which bubbles up the middleware stack and produces a HTTP 403 Forbidden reply # in the axes.middleware.AxesMiddleware.process_exception middleware exception handler. raise AxesBackendPermissionDenied('AxesBackend detected that the given user is locked out')
python
def authenticate(self, request: AxesHttpRequest, username: str = None, password: str = None, **kwargs: dict): if request is None: raise AxesBackendRequestParameterRequired('AxesBackend requires a request as an argument to authenticate') credentials = get_credentials(username=username, password=password, **kwargs) if AxesProxyHandler.is_allowed(request, credentials): return # Locked out, don't try to authenticate, just update response_context and return. # Its a bit weird to pass a context and expect a response value but its nice to get a "why" back. error_msg = get_lockout_message() response_context = kwargs.get('response_context', {}) response_context['error'] = error_msg # Raise an error that stops the authentication flows at django.contrib.auth.authenticate. # This error stops bubbling up at the authenticate call which catches backend PermissionDenied errors. # After this error is caught by authenticate it emits a signal indicating user login failed, # which is processed by axes.signals.log_user_login_failed which logs the attempt and raises # a second exception which bubbles up the middleware stack and produces a HTTP 403 Forbidden reply # in the axes.middleware.AxesMiddleware.process_exception middleware exception handler. raise AxesBackendPermissionDenied('AxesBackend detected that the given user is locked out')
[ "def", "authenticate", "(", "self", ",", "request", ":", "AxesHttpRequest", ",", "username", ":", "str", "=", "None", ",", "password", ":", "str", "=", "None", ",", "*", "*", "kwargs", ":", "dict", ")", ":", "if", "request", "is", "None", ":", "raise...
Checks user lockout status and raise a PermissionDenied if user is not allowed to log in. This method interrupts the login flow and inserts error message directly to the ``response_context`` attribute that is supplied as a keyword argument. :keyword response_context: kwarg that will be have its ``error`` attribute updated with context. :raises AxesBackendRequestParameterRequired: if request parameter is not passed. :raises AxesBackendPermissionDenied: if user is already locked out.
[ "Checks", "user", "lockout", "status", "and", "raise", "a", "PermissionDenied", "if", "user", "is", "not", "allowed", "to", "log", "in", "." ]
3e215a174030e43e7ab8c2a79c395eb0eeddc667
https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/backends.py#L20-L54
229,262
joshspeagle/dynesty
dynesty/dynamicsampler.py
DynamicSampler.results
def results(self): """Saved results from the dynamic nested sampling run. All saved bounds are also returned.""" # Add all saved samples (and ancillary quantities) to the results. with warnings.catch_warnings(): warnings.simplefilter("ignore") results = [('niter', self.it - 1), ('ncall', np.array(self.saved_nc)), ('eff', self.eff), ('samples', np.array(self.saved_v)), ('samples_id', np.array(self.saved_id)), ('samples_batch', np.array(self.saved_batch, dtype='int')), ('samples_it', np.array(self.saved_it)), ('samples_u', np.array(self.saved_u)), ('samples_n', np.array(self.saved_n)), ('logwt', np.array(self.saved_logwt)), ('logl', np.array(self.saved_logl)), ('logvol', np.array(self.saved_logvol)), ('logz', np.array(self.saved_logz)), ('logzerr', np.sqrt(np.array(self.saved_logzvar))), ('information', np.array(self.saved_h)), ('batch_nlive', np.array(self.saved_batch_nlive, dtype='int')), ('batch_bounds', np.array(self.saved_batch_bounds))] # Add any saved bounds (and ancillary quantities) to the results. if self.sampler.save_bounds: results.append(('bound', copy.deepcopy(self.bound))) results.append(('bound_iter', np.array(self.saved_bounditer, dtype='int'))) results.append(('samples_bound', np.array(self.saved_boundidx, dtype='int'))) results.append(('scale', np.array(self.saved_scale))) return Results(results)
python
def results(self): # Add all saved samples (and ancillary quantities) to the results. with warnings.catch_warnings(): warnings.simplefilter("ignore") results = [('niter', self.it - 1), ('ncall', np.array(self.saved_nc)), ('eff', self.eff), ('samples', np.array(self.saved_v)), ('samples_id', np.array(self.saved_id)), ('samples_batch', np.array(self.saved_batch, dtype='int')), ('samples_it', np.array(self.saved_it)), ('samples_u', np.array(self.saved_u)), ('samples_n', np.array(self.saved_n)), ('logwt', np.array(self.saved_logwt)), ('logl', np.array(self.saved_logl)), ('logvol', np.array(self.saved_logvol)), ('logz', np.array(self.saved_logz)), ('logzerr', np.sqrt(np.array(self.saved_logzvar))), ('information', np.array(self.saved_h)), ('batch_nlive', np.array(self.saved_batch_nlive, dtype='int')), ('batch_bounds', np.array(self.saved_batch_bounds))] # Add any saved bounds (and ancillary quantities) to the results. if self.sampler.save_bounds: results.append(('bound', copy.deepcopy(self.bound))) results.append(('bound_iter', np.array(self.saved_bounditer, dtype='int'))) results.append(('samples_bound', np.array(self.saved_boundidx, dtype='int'))) results.append(('scale', np.array(self.saved_scale))) return Results(results)
[ "def", "results", "(", "self", ")", ":", "# Add all saved samples (and ancillary quantities) to the results.", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "results", "=", "[", "(", "'niter'", ","...
Saved results from the dynamic nested sampling run. All saved bounds are also returned.
[ "Saved", "results", "from", "the", "dynamic", "nested", "sampling", "run", ".", "All", "saved", "bounds", "are", "also", "returned", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/dynamicsampler.py#L514-L550
229,263
joshspeagle/dynesty
dynesty/bounding.py
randsphere
def randsphere(n, rstate=None): """Draw a point uniformly within an `n`-dimensional unit sphere.""" if rstate is None: rstate = np.random z = rstate.randn(n) # initial n-dim vector zhat = z / lalg.norm(z) # normalize xhat = zhat * rstate.rand()**(1./n) # scale return xhat
python
def randsphere(n, rstate=None): if rstate is None: rstate = np.random z = rstate.randn(n) # initial n-dim vector zhat = z / lalg.norm(z) # normalize xhat = zhat * rstate.rand()**(1./n) # scale return xhat
[ "def", "randsphere", "(", "n", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "z", "=", "rstate", ".", "randn", "(", "n", ")", "# initial n-dim vector", "zhat", "=", "z", "/", "lalg", "....
Draw a point uniformly within an `n`-dimensional unit sphere.
[ "Draw", "a", "point", "uniformly", "within", "an", "n", "-", "dimensional", "unit", "sphere", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L1133-L1143
229,264
joshspeagle/dynesty
dynesty/bounding.py
bounding_ellipsoid
def bounding_ellipsoid(points, pointvol=0.): """ Calculate the bounding ellipsoid containing a collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional The minimum volume occupied by a single point. When provided, used to set a minimum bound on the ellipsoid volume as `npoints * pointvol`. Default is `0.`. Returns ------- ellipsoid : :class:`Ellipsoid` The bounding :class:`Ellipsoid` object. """ npoints, ndim = points.shape # Check for valid `pointvol` value if provided. if pointvol < 0.: raise ValueError("You must specify a non-negative value " "for `pointvol`.") # If there is only a single point, return an n-sphere with volume # `pointvol` centered at the point. if npoints == 1: if pointvol > 0.: ctr = points[0] r = np.exp((np.log(pointvol) - logvol_prefactor(ndim)) / ndim) covar = r**2 * np.identity(ndim) return Ellipsoid(ctr, covar) else: raise ValueError("Cannot compute a bounding ellipsoid to a " "single point if `pointvol` is not specified.") # Calculate covariance of points. ctr = np.mean(points, axis=0) cov = mle_cov(points, rowvar=False) # When ndim = 1, `np.cov` returns a 0-d array. Make it a 1x1 2-d array. if ndim == 1: cov = np.atleast_2d(cov) # For a ball of uniformly distributed points, the sample covariance # will be smaller than the true covariance by a factor of 1/(n+2) # [see, e.g., goo.gl/UbsjYl]. Since we are assuming all points are # uniformly distributed within the unit cube, they are uniformly # distributed within any sub-volume within the cube. We expand # our sample covariance `cov` to compensate for this. cov *= (ndim + 2) # Define the axes of our ellipsoid. Ensures that `cov` is # nonsingular to deal with pathological cases where the ellipsoid has # "zero" volume. This can occur when `npoints <= ndim` or when enough # points are linear combinations of other points. covar = np.array(cov) for trials in range(100): try: # Check if matrix is invertible. am = lalg.pinvh(covar) l, v = lalg.eigh(covar) # compute eigenvalues/vectors if np.all((l > 0.) & (np.isfinite(l))): break else: raise RuntimeError("The eigenvalue/eigenvector decomposition " "failed!") except: # If the matrix remains singular/unstable, # suppress the off-diagonal elements. coeff = 1.1**(trials+1) / 1.1**100 covar = (1. - coeff) * cov + coeff * np.eye(ndim) pass else: warnings.warn("Failed to guarantee the ellipsoid axes will be " "non-singular. Defaulting to a sphere.") am = np.eye(ndim) # Calculate expansion factor necessary to bound each point. # Points should obey `(x-v)^T A (x-v) <= 1`, so we calculate this for # each point and then scale A up or down to make the # "outermost" point obey `(x-v)^T A (x-v) = 1`. This can be done # quickly using `einsum` and `tensordot` to iterate over all points. delta = points - ctr f = np.einsum('...i, ...i', np.tensordot(delta, am, axes=1), delta) fmax = np.max(f) # Due to round-off errors, we actually scale the ellipsoid so the # outermost point obeys `(x-v)^T A (x-v) < 1 - (a bit) < 1`. one_minus_a_bit = 1. - SQRTEPS if fmax > one_minus_a_bit: covar *= fmax / one_minus_a_bit # Initialize our ellipsoid. ell = Ellipsoid(ctr, covar) # Expand our ellipsoid to encompass a minimum volume. if pointvol > 0.: minvol = npoints * pointvol if ell.vol < minvol: ell.scale_to_vol(minvol) return ell
python
def bounding_ellipsoid(points, pointvol=0.): npoints, ndim = points.shape # Check for valid `pointvol` value if provided. if pointvol < 0.: raise ValueError("You must specify a non-negative value " "for `pointvol`.") # If there is only a single point, return an n-sphere with volume # `pointvol` centered at the point. if npoints == 1: if pointvol > 0.: ctr = points[0] r = np.exp((np.log(pointvol) - logvol_prefactor(ndim)) / ndim) covar = r**2 * np.identity(ndim) return Ellipsoid(ctr, covar) else: raise ValueError("Cannot compute a bounding ellipsoid to a " "single point if `pointvol` is not specified.") # Calculate covariance of points. ctr = np.mean(points, axis=0) cov = mle_cov(points, rowvar=False) # When ndim = 1, `np.cov` returns a 0-d array. Make it a 1x1 2-d array. if ndim == 1: cov = np.atleast_2d(cov) # For a ball of uniformly distributed points, the sample covariance # will be smaller than the true covariance by a factor of 1/(n+2) # [see, e.g., goo.gl/UbsjYl]. Since we are assuming all points are # uniformly distributed within the unit cube, they are uniformly # distributed within any sub-volume within the cube. We expand # our sample covariance `cov` to compensate for this. cov *= (ndim + 2) # Define the axes of our ellipsoid. Ensures that `cov` is # nonsingular to deal with pathological cases where the ellipsoid has # "zero" volume. This can occur when `npoints <= ndim` or when enough # points are linear combinations of other points. covar = np.array(cov) for trials in range(100): try: # Check if matrix is invertible. am = lalg.pinvh(covar) l, v = lalg.eigh(covar) # compute eigenvalues/vectors if np.all((l > 0.) & (np.isfinite(l))): break else: raise RuntimeError("The eigenvalue/eigenvector decomposition " "failed!") except: # If the matrix remains singular/unstable, # suppress the off-diagonal elements. coeff = 1.1**(trials+1) / 1.1**100 covar = (1. - coeff) * cov + coeff * np.eye(ndim) pass else: warnings.warn("Failed to guarantee the ellipsoid axes will be " "non-singular. Defaulting to a sphere.") am = np.eye(ndim) # Calculate expansion factor necessary to bound each point. # Points should obey `(x-v)^T A (x-v) <= 1`, so we calculate this for # each point and then scale A up or down to make the # "outermost" point obey `(x-v)^T A (x-v) = 1`. This can be done # quickly using `einsum` and `tensordot` to iterate over all points. delta = points - ctr f = np.einsum('...i, ...i', np.tensordot(delta, am, axes=1), delta) fmax = np.max(f) # Due to round-off errors, we actually scale the ellipsoid so the # outermost point obeys `(x-v)^T A (x-v) < 1 - (a bit) < 1`. one_minus_a_bit = 1. - SQRTEPS if fmax > one_minus_a_bit: covar *= fmax / one_minus_a_bit # Initialize our ellipsoid. ell = Ellipsoid(ctr, covar) # Expand our ellipsoid to encompass a minimum volume. if pointvol > 0.: minvol = npoints * pointvol if ell.vol < minvol: ell.scale_to_vol(minvol) return ell
[ "def", "bounding_ellipsoid", "(", "points", ",", "pointvol", "=", "0.", ")", ":", "npoints", ",", "ndim", "=", "points", ".", "shape", "# Check for valid `pointvol` value if provided.", "if", "pointvol", "<", "0.", ":", "raise", "ValueError", "(", "\"You must spec...
Calculate the bounding ellipsoid containing a collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional The minimum volume occupied by a single point. When provided, used to set a minimum bound on the ellipsoid volume as `npoints * pointvol`. Default is `0.`. Returns ------- ellipsoid : :class:`Ellipsoid` The bounding :class:`Ellipsoid` object.
[ "Calculate", "the", "bounding", "ellipsoid", "containing", "a", "collection", "of", "points", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L1146-L1253
229,265
joshspeagle/dynesty
dynesty/bounding.py
_bounding_ellipsoids
def _bounding_ellipsoids(points, ell, pointvol=0., vol_dec=0.5, vol_check=2.): """ Internal method used to compute a set of bounding ellipsoids when a bounding ellipsoid for the entire set has already been calculated. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. ell : Ellipsoid The bounding ellipsoid containing :data:`points`. pointvol : float, optional Volume represented by a single point. When provided, used to set a minimum bound on the ellipsoid volume as `npoints * pointvol`. Default is `0.`. vol_dec : float, optional The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is `0.5`. vol_check : float, optional The factor used to when checking whether the volume of the original bounding ellipsoid is large enough to warrant more trial splits via `ell.vol > vol_check * npoints * pointvol`. Default is `2.0`. Returns ------- ells : list of :class:`Ellipsoid` objects List of :class:`Ellipsoid` objects used to bound the collection of points. Used to initialize the :class:`MultiEllipsoid` object returned in :meth:`bounding_ellipsoids`. """ npoints, ndim = points.shape # Starting cluster centers are initialized using the major-axis # endpoints of the original bounding ellipsoid. p1, p2 = ell.major_axis_endpoints() start_ctrs = np.vstack((p1, p2)) # shape is (k, ndim) = (2, ndim) # Split points into two clusters using k-means clustering with k=2. try: with warnings.catch_warnings(): warnings.simplefilter("ignore") k2_res = kmeans2(points, k=start_ctrs, iter=10, minit='matrix', check_finite=False) labels = k2_res[1] # cluster identifier ; shape is (npoints,) # Get points in each cluster. points_k = [points[labels == k, :] for k in (0, 1)] # If either cluster has less than ndim+1 points, the bounding ellipsoid # will be ill-constrained. Reject the split and simply return the # original ellipsoid bounding all the points. if points_k[0].shape[0] < 2 * ndim or points_k[1].shape[0] < 2 * ndim: return [ell] # Bounding ellipsoid for each cluster, possibly enlarged # to a minimum volume. ells = [bounding_ellipsoid(points_j, pointvol=pointvol) for points_j in points_k] # If the total volume decreased by a factor of `vol_dec`, we accept # the split into subsets. We then recursively split each subset. if ells[0].vol + ells[1].vol < vol_dec * ell.vol: return (_bounding_ellipsoids(points_k[0], ells[0], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) + _bounding_ellipsoids(points_k[1], ells[1], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check)) # Otherwise, see if the total ellipsoid volume is larger than the # minimum volume by a factor of `vol_check`. If it is, this indicates # that there may be more than 2 clusters and we should try to # subdivide further. if ell.vol > vol_check * npoints * pointvol: out = (_bounding_ellipsoids(points_k[0], ells[0], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) + _bounding_ellipsoids(points_k[1], ells[1], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check)) # Only accept the split if the volume decreased significantly. if sum(e.vol for e in out) < vol_dec * ell.vol: return out except: pass # Otherwise, we are happy with the single bounding ellipsoid. return [ell]
python
def _bounding_ellipsoids(points, ell, pointvol=0., vol_dec=0.5, vol_check=2.): npoints, ndim = points.shape # Starting cluster centers are initialized using the major-axis # endpoints of the original bounding ellipsoid. p1, p2 = ell.major_axis_endpoints() start_ctrs = np.vstack((p1, p2)) # shape is (k, ndim) = (2, ndim) # Split points into two clusters using k-means clustering with k=2. try: with warnings.catch_warnings(): warnings.simplefilter("ignore") k2_res = kmeans2(points, k=start_ctrs, iter=10, minit='matrix', check_finite=False) labels = k2_res[1] # cluster identifier ; shape is (npoints,) # Get points in each cluster. points_k = [points[labels == k, :] for k in (0, 1)] # If either cluster has less than ndim+1 points, the bounding ellipsoid # will be ill-constrained. Reject the split and simply return the # original ellipsoid bounding all the points. if points_k[0].shape[0] < 2 * ndim or points_k[1].shape[0] < 2 * ndim: return [ell] # Bounding ellipsoid for each cluster, possibly enlarged # to a minimum volume. ells = [bounding_ellipsoid(points_j, pointvol=pointvol) for points_j in points_k] # If the total volume decreased by a factor of `vol_dec`, we accept # the split into subsets. We then recursively split each subset. if ells[0].vol + ells[1].vol < vol_dec * ell.vol: return (_bounding_ellipsoids(points_k[0], ells[0], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) + _bounding_ellipsoids(points_k[1], ells[1], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check)) # Otherwise, see if the total ellipsoid volume is larger than the # minimum volume by a factor of `vol_check`. If it is, this indicates # that there may be more than 2 clusters and we should try to # subdivide further. if ell.vol > vol_check * npoints * pointvol: out = (_bounding_ellipsoids(points_k[0], ells[0], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) + _bounding_ellipsoids(points_k[1], ells[1], pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check)) # Only accept the split if the volume decreased significantly. if sum(e.vol for e in out) < vol_dec * ell.vol: return out except: pass # Otherwise, we are happy with the single bounding ellipsoid. return [ell]
[ "def", "_bounding_ellipsoids", "(", "points", ",", "ell", ",", "pointvol", "=", "0.", ",", "vol_dec", "=", "0.5", ",", "vol_check", "=", "2.", ")", ":", "npoints", ",", "ndim", "=", "points", ".", "shape", "# Starting cluster centers are initialized using the ma...
Internal method used to compute a set of bounding ellipsoids when a bounding ellipsoid for the entire set has already been calculated. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. ell : Ellipsoid The bounding ellipsoid containing :data:`points`. pointvol : float, optional Volume represented by a single point. When provided, used to set a minimum bound on the ellipsoid volume as `npoints * pointvol`. Default is `0.`. vol_dec : float, optional The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is `0.5`. vol_check : float, optional The factor used to when checking whether the volume of the original bounding ellipsoid is large enough to warrant more trial splits via `ell.vol > vol_check * npoints * pointvol`. Default is `2.0`. Returns ------- ells : list of :class:`Ellipsoid` objects List of :class:`Ellipsoid` objects used to bound the collection of points. Used to initialize the :class:`MultiEllipsoid` object returned in :meth:`bounding_ellipsoids`.
[ "Internal", "method", "used", "to", "compute", "a", "set", "of", "bounding", "ellipsoids", "when", "a", "bounding", "ellipsoid", "for", "the", "entire", "set", "has", "already", "been", "calculated", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L1256-L1352
229,266
joshspeagle/dynesty
dynesty/bounding.py
bounding_ellipsoids
def bounding_ellipsoids(points, pointvol=0., vol_dec=0.5, vol_check=2.): """ Calculate a set of ellipsoids that bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional Volume represented by a single point. When provided, used to set a minimum bound on the ellipsoid volume as `npoints * pointvol`. Default is `0.`. vol_dec : float, optional The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is `0.5`. vol_check : float, optional The factor used to when checking whether the volume of the original bounding ellipsoid is large enough to warrant more trial splits via `ell.vol > vol_check * npoints * pointvol`. Default is `2.0`. Returns ------- mell : :class:`MultiEllipsoid` object The :class:`MultiEllipsoid` object used to bound the collection of points. """ if not HAVE_KMEANS: raise ValueError("scipy.cluster.vq.kmeans2 is required to compute " "ellipsoid decompositions.") # pragma: no cover # Calculate the bounding ellipsoid for the points possibly # enlarged to a minimum volume. ell = bounding_ellipsoid(points, pointvol=pointvol) # Recursively split the bounding ellipsoid until the volume of each # split no longer decreases by a factor of `vol_dec`. ells = _bounding_ellipsoids(points, ell, pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) return MultiEllipsoid(ells=ells)
python
def bounding_ellipsoids(points, pointvol=0., vol_dec=0.5, vol_check=2.): if not HAVE_KMEANS: raise ValueError("scipy.cluster.vq.kmeans2 is required to compute " "ellipsoid decompositions.") # pragma: no cover # Calculate the bounding ellipsoid for the points possibly # enlarged to a minimum volume. ell = bounding_ellipsoid(points, pointvol=pointvol) # Recursively split the bounding ellipsoid until the volume of each # split no longer decreases by a factor of `vol_dec`. ells = _bounding_ellipsoids(points, ell, pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) return MultiEllipsoid(ells=ells)
[ "def", "bounding_ellipsoids", "(", "points", ",", "pointvol", "=", "0.", ",", "vol_dec", "=", "0.5", ",", "vol_check", "=", "2.", ")", ":", "if", "not", "HAVE_KMEANS", ":", "raise", "ValueError", "(", "\"scipy.cluster.vq.kmeans2 is required to compute \"", "\"elli...
Calculate a set of ellipsoids that bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional Volume represented by a single point. When provided, used to set a minimum bound on the ellipsoid volume as `npoints * pointvol`. Default is `0.`. vol_dec : float, optional The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is `0.5`. vol_check : float, optional The factor used to when checking whether the volume of the original bounding ellipsoid is large enough to warrant more trial splits via `ell.vol > vol_check * npoints * pointvol`. Default is `2.0`. Returns ------- mell : :class:`MultiEllipsoid` object The :class:`MultiEllipsoid` object used to bound the collection of points.
[ "Calculate", "a", "set", "of", "ellipsoids", "that", "bound", "the", "collection", "of", "points", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L1355-L1400
229,267
joshspeagle/dynesty
dynesty/bounding.py
_ellipsoid_bootstrap_expand
def _ellipsoid_bootstrap_expand(args): """Internal method used to compute the expansion factor for a bounding ellipsoid based on bootstrapping.""" # Unzipping. points, pointvol = args rstate = np.random # Resampling. npoints, ndim = points.shape idxs = rstate.randint(npoints, size=npoints) # resample idx_in = np.unique(idxs) # selected objects sel = np.ones(npoints, dtype='bool') sel[idx_in] = False idx_out = np.arange(npoints)[sel] # "missing" objects if len(idx_out) < 2: # edge case idx_out = np.append(idx_out, [0, 1]) points_in, points_out = points[idx_in], points[idx_out] # Compute bounding ellipsoid. ell = bounding_ellipsoid(points_in, pointvol=pointvol) # Compute normalized distances to missing points. dists = [ell.distance(p) for p in points_out] # Compute expansion factor. expand = max(1., max(dists)) return expand
python
def _ellipsoid_bootstrap_expand(args): # Unzipping. points, pointvol = args rstate = np.random # Resampling. npoints, ndim = points.shape idxs = rstate.randint(npoints, size=npoints) # resample idx_in = np.unique(idxs) # selected objects sel = np.ones(npoints, dtype='bool') sel[idx_in] = False idx_out = np.arange(npoints)[sel] # "missing" objects if len(idx_out) < 2: # edge case idx_out = np.append(idx_out, [0, 1]) points_in, points_out = points[idx_in], points[idx_out] # Compute bounding ellipsoid. ell = bounding_ellipsoid(points_in, pointvol=pointvol) # Compute normalized distances to missing points. dists = [ell.distance(p) for p in points_out] # Compute expansion factor. expand = max(1., max(dists)) return expand
[ "def", "_ellipsoid_bootstrap_expand", "(", "args", ")", ":", "# Unzipping.", "points", ",", "pointvol", "=", "args", "rstate", "=", "np", ".", "random", "# Resampling.", "npoints", ",", "ndim", "=", "points", ".", "shape", "idxs", "=", "rstate", ".", "randin...
Internal method used to compute the expansion factor for a bounding ellipsoid based on bootstrapping.
[ "Internal", "method", "used", "to", "compute", "the", "expansion", "factor", "for", "a", "bounding", "ellipsoid", "based", "on", "bootstrapping", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L1403-L1431
229,268
joshspeagle/dynesty
dynesty/bounding.py
UnitCube.sample
def sample(self, rstate=None): """ Draw a sample uniformly distributed within the unit cube. Returns ------- x : `~numpy.ndarray` with shape (ndim,) A coordinate within the unit cube. """ if rstate is None: rstate = np.random return rstate.rand(self.n)
python
def sample(self, rstate=None): if rstate is None: rstate = np.random return rstate.rand(self.n)
[ "def", "sample", "(", "self", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "return", "rstate", ".", "rand", "(", "self", ".", "n", ")" ]
Draw a sample uniformly distributed within the unit cube. Returns ------- x : `~numpy.ndarray` with shape (ndim,) A coordinate within the unit cube.
[ "Draw", "a", "sample", "uniformly", "distributed", "within", "the", "unit", "cube", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L86-L100
229,269
joshspeagle/dynesty
dynesty/bounding.py
UnitCube.samples
def samples(self, nsamples, rstate=None): """ Draw `nsamples` samples randomly distributed within the unit cube. Returns ------- x : `~numpy.ndarray` with shape (nsamples, ndim) A collection of coordinates within the unit cube. """ if rstate is None: rstate = np.random xs = np.array([self.sample(rstate=rstate) for i in range(nsamples)]) return xs
python
def samples(self, nsamples, rstate=None): if rstate is None: rstate = np.random xs = np.array([self.sample(rstate=rstate) for i in range(nsamples)]) return xs
[ "def", "samples", "(", "self", ",", "nsamples", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "xs", "=", "np", ".", "array", "(", "[", "self", ".", "sample", "(", "rstate", "=", "rsta...
Draw `nsamples` samples randomly distributed within the unit cube. Returns ------- x : `~numpy.ndarray` with shape (nsamples, ndim) A collection of coordinates within the unit cube.
[ "Draw", "nsamples", "samples", "randomly", "distributed", "within", "the", "unit", "cube", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L102-L118
229,270
joshspeagle/dynesty
dynesty/bounding.py
Ellipsoid.scale_to_vol
def scale_to_vol(self, vol): """Scale ellipoid to a target volume.""" f = np.exp((np.log(vol) - np.log(self.vol)) / self.n) # linear factor self.expand *= f self.cov *= f**2 self.am *= f**-2 self.axlens *= f self.axes *= f self.vol = vol
python
def scale_to_vol(self, vol): f = np.exp((np.log(vol) - np.log(self.vol)) / self.n) # linear factor self.expand *= f self.cov *= f**2 self.am *= f**-2 self.axlens *= f self.axes *= f self.vol = vol
[ "def", "scale_to_vol", "(", "self", ",", "vol", ")", ":", "f", "=", "np", ".", "exp", "(", "(", "np", ".", "log", "(", "vol", ")", "-", "np", ".", "log", "(", "self", ".", "vol", ")", ")", "/", "self", ".", "n", ")", "# linear factor", "self"...
Scale ellipoid to a target volume.
[ "Scale", "ellipoid", "to", "a", "target", "volume", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L179-L188
229,271
joshspeagle/dynesty
dynesty/bounding.py
Ellipsoid.major_axis_endpoints
def major_axis_endpoints(self): """Return the endpoints of the major axis.""" i = np.argmax(self.axlens) # find the major axis v = self.paxes[:, i] # vector from center to major axis endpoint return self.ctr - v, self.ctr + v
python
def major_axis_endpoints(self): i = np.argmax(self.axlens) # find the major axis v = self.paxes[:, i] # vector from center to major axis endpoint return self.ctr - v, self.ctr + v
[ "def", "major_axis_endpoints", "(", "self", ")", ":", "i", "=", "np", ".", "argmax", "(", "self", ".", "axlens", ")", "# find the major axis", "v", "=", "self", ".", "paxes", "[", ":", ",", "i", "]", "# vector from center to major axis endpoint", "return", "...
Return the endpoints of the major axis.
[ "Return", "the", "endpoints", "of", "the", "major", "axis", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L190-L196
229,272
joshspeagle/dynesty
dynesty/bounding.py
Ellipsoid.distance
def distance(self, x): """Compute the normalized distance to `x` from the center of the ellipsoid.""" d = x - self.ctr return np.sqrt(np.dot(np.dot(d, self.am), d))
python
def distance(self, x): d = x - self.ctr return np.sqrt(np.dot(np.dot(d, self.am), d))
[ "def", "distance", "(", "self", ",", "x", ")", ":", "d", "=", "x", "-", "self", ".", "ctr", "return", "np", ".", "sqrt", "(", "np", ".", "dot", "(", "np", ".", "dot", "(", "d", ",", "self", ".", "am", ")", ",", "d", ")", ")" ]
Compute the normalized distance to `x` from the center of the ellipsoid.
[ "Compute", "the", "normalized", "distance", "to", "x", "from", "the", "center", "of", "the", "ellipsoid", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L198-L204
229,273
joshspeagle/dynesty
dynesty/bounding.py
Ellipsoid.randoffset
def randoffset(self, rstate=None): """Return a random offset from the center of the ellipsoid.""" if rstate is None: rstate = np.random return np.dot(self.axes, randsphere(self.n, rstate=rstate))
python
def randoffset(self, rstate=None): if rstate is None: rstate = np.random return np.dot(self.axes, randsphere(self.n, rstate=rstate))
[ "def", "randoffset", "(", "self", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "return", "np", ".", "dot", "(", "self", ".", "axes", ",", "randsphere", "(", "self", ".", "n", ",", "r...
Return a random offset from the center of the ellipsoid.
[ "Return", "a", "random", "offset", "from", "the", "center", "of", "the", "ellipsoid", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L211-L217
229,274
joshspeagle/dynesty
dynesty/bounding.py
Ellipsoid.sample
def sample(self, rstate=None): """ Draw a sample uniformly distributed within the ellipsoid. Returns ------- x : `~numpy.ndarray` with shape (ndim,) A coordinate within the ellipsoid. """ if rstate is None: rstate = np.random return self.ctr + self.randoffset(rstate=rstate)
python
def sample(self, rstate=None): if rstate is None: rstate = np.random return self.ctr + self.randoffset(rstate=rstate)
[ "def", "sample", "(", "self", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "return", "self", ".", "ctr", "+", "self", ".", "randoffset", "(", "rstate", "=", "rstate", ")" ]
Draw a sample uniformly distributed within the ellipsoid. Returns ------- x : `~numpy.ndarray` with shape (ndim,) A coordinate within the ellipsoid.
[ "Draw", "a", "sample", "uniformly", "distributed", "within", "the", "ellipsoid", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L219-L233
229,275
joshspeagle/dynesty
dynesty/bounding.py
Ellipsoid.unitcube_overlap
def unitcube_overlap(self, ndraws=10000, rstate=None): """Using `ndraws` Monte Carlo draws, estimate the fraction of overlap between the ellipsoid and the unit cube.""" if rstate is None: rstate = np.random samples = [self.sample(rstate=rstate) for i in range(ndraws)] nin = sum([unitcheck(x) for x in samples]) return 1. * nin / ndraws
python
def unitcube_overlap(self, ndraws=10000, rstate=None): if rstate is None: rstate = np.random samples = [self.sample(rstate=rstate) for i in range(ndraws)] nin = sum([unitcheck(x) for x in samples]) return 1. * nin / ndraws
[ "def", "unitcube_overlap", "(", "self", ",", "ndraws", "=", "10000", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "samples", "=", "[", "self", ".", "sample", "(", "rstate", "=", "rstate"...
Using `ndraws` Monte Carlo draws, estimate the fraction of overlap between the ellipsoid and the unit cube.
[ "Using", "ndraws", "Monte", "Carlo", "draws", "estimate", "the", "fraction", "of", "overlap", "between", "the", "ellipsoid", "and", "the", "unit", "cube", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L253-L263
229,276
joshspeagle/dynesty
dynesty/bounding.py
Ellipsoid.update
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, mc_integrate=False): """ Update the ellipsoid to bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoid. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective overlap of the final ellipsoid with the unit cube. Default is `False`. """ if rstate is None: rstate = np.random # Compute new bounding ellipsoid. ell = bounding_ellipsoid(points, pointvol=pointvol) self.n = ell.n self.ctr = ell.ctr self.cov = ell.cov self.am = ell.am self.vol = ell.vol self.axlens = ell.axlens self.axes = ell.axes self.paxes = ell.paxes self.expand = ell.expand # Use bootstrapping to determine the volume expansion factor. if bootstrap > 0: # If provided, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map ps = [points for it in range(bootstrap)] pvs = [pointvol for it in range(bootstrap)] args = zip(ps, pvs) expands = list(M(_ellipsoid_bootstrap_expand, args)) # Conservatively set the expansion factor to be the maximum # factor derived from our set of bootstraps. expand = max(expands) # If our ellipsoid is over-constrained, expand it. if expand > 1.: v = self.vol * expand**self.n self.scale_to_vol(v) # Estimate the fractional overlap with the unit cube using # Monte Carlo integration. if mc_integrate: self.funit = self.unitcube_overlap()
python
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, mc_integrate=False): if rstate is None: rstate = np.random # Compute new bounding ellipsoid. ell = bounding_ellipsoid(points, pointvol=pointvol) self.n = ell.n self.ctr = ell.ctr self.cov = ell.cov self.am = ell.am self.vol = ell.vol self.axlens = ell.axlens self.axes = ell.axes self.paxes = ell.paxes self.expand = ell.expand # Use bootstrapping to determine the volume expansion factor. if bootstrap > 0: # If provided, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map ps = [points for it in range(bootstrap)] pvs = [pointvol for it in range(bootstrap)] args = zip(ps, pvs) expands = list(M(_ellipsoid_bootstrap_expand, args)) # Conservatively set the expansion factor to be the maximum # factor derived from our set of bootstraps. expand = max(expands) # If our ellipsoid is over-constrained, expand it. if expand > 1.: v = self.vol * expand**self.n self.scale_to_vol(v) # Estimate the fractional overlap with the unit cube using # Monte Carlo integration. if mc_integrate: self.funit = self.unitcube_overlap()
[ "def", "update", "(", "self", ",", "points", ",", "pointvol", "=", "0.", ",", "rstate", "=", "None", ",", "bootstrap", "=", "0", ",", "pool", "=", "None", ",", "mc_integrate", "=", "False", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "="...
Update the ellipsoid to bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoid. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective overlap of the final ellipsoid with the unit cube. Default is `False`.
[ "Update", "the", "ellipsoid", "to", "bound", "the", "collection", "of", "points", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L265-L337
229,277
joshspeagle/dynesty
dynesty/bounding.py
MultiEllipsoid.scale_to_vols
def scale_to_vols(self, vols): """Scale ellipoids to a corresponding set of target volumes.""" [self.ells[i].scale_to_vol(vols[i]) for i in range(self.nells)] self.vols = np.array(vols) self.expands = np.array([self.ells[i].expand for i in range(self.nells)]) vol_tot = sum(vols) self.expand_tot *= vol_tot / self.vol_tot self.vol_tot = vol_tot
python
def scale_to_vols(self, vols): [self.ells[i].scale_to_vol(vols[i]) for i in range(self.nells)] self.vols = np.array(vols) self.expands = np.array([self.ells[i].expand for i in range(self.nells)]) vol_tot = sum(vols) self.expand_tot *= vol_tot / self.vol_tot self.vol_tot = vol_tot
[ "def", "scale_to_vols", "(", "self", ",", "vols", ")", ":", "[", "self", ".", "ells", "[", "i", "]", ".", "scale_to_vol", "(", "vols", "[", "i", "]", ")", "for", "i", "in", "range", "(", "self", ".", "nells", ")", "]", "self", ".", "vols", "=",...
Scale ellipoids to a corresponding set of target volumes.
[ "Scale", "ellipoids", "to", "a", "corresponding", "set", "of", "target", "volumes", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L391-L401
229,278
joshspeagle/dynesty
dynesty/bounding.py
MultiEllipsoid.update
def update(self, points, pointvol=0., vol_dec=0.5, vol_check=2., rstate=None, bootstrap=0, pool=None, mc_integrate=False): """ Update the set of ellipsoids to bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. vol_dec : float, optional The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is `0.5`. vol_check : float, optional The factor used when checking if the volume of the original bounding ellipsoid is large enough to warrant `> 2` splits via `ell.vol > vol_check * nlive * pointvol`. Default is `2.0`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of ellipsoids with the unit cube. Default is `False`. """ if rstate is None: rstate = np.random if not HAVE_KMEANS: raise ValueError("scipy.cluster.vq.kmeans2 is required " "to compute ellipsoid decompositions.") npoints, ndim = points.shape # Calculate the bounding ellipsoid for the points, possibly # enlarged to a minimum volume. firstell = bounding_ellipsoid(points, pointvol=pointvol) # Recursively split the bounding ellipsoid using `vol_check` # until the volume of each split no longer decreases by a # factor of `vol_dec`. ells = _bounding_ellipsoids(points, firstell, pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) # Update the set of ellipsoids. self.nells = len(ells) self.ells = ells self.ctrs = np.array([ell.ctr for ell in self.ells]) self.covs = np.array([ell.cov for ell in self.ells]) self.ams = np.array([ell.am for ell in self.ells]) self.vols = np.array([ell.vol for ell in self.ells]) self.vol_tot = sum(self.vols) # Compute expansion factor. expands = np.array([ell.expand for ell in self.ells]) vols_orig = self.vols / expands vol_tot_orig = sum(vols_orig) self.expand_tot = self.vol_tot / vol_tot_orig # Use bootstrapping to determine the volume expansion factor. if bootstrap > 0: # If provided, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map ps = [points for it in range(bootstrap)] pvs = [pointvol for it in range(bootstrap)] vds = [vol_dec for it in range(bootstrap)] vcs = [vol_check for it in range(bootstrap)] args = zip(ps, pvs, vds, vcs) expands = list(M(_ellipsoids_bootstrap_expand, args)) # Conservatively set the expansion factor to be the maximum # factor derived from our set of bootstraps. expand = max(expands) # If our ellipsoids are overly constrained, expand them. if expand > 1.: vs = self.vols * expand**ndim self.scale_to_vols(vs) # Estimate the volume and fractional overlap with the unit cube # using Monte Carlo integration. if mc_integrate: self.vol, self.funit = self.monte_carlo_vol(return_overlap=True)
python
def update(self, points, pointvol=0., vol_dec=0.5, vol_check=2., rstate=None, bootstrap=0, pool=None, mc_integrate=False): if rstate is None: rstate = np.random if not HAVE_KMEANS: raise ValueError("scipy.cluster.vq.kmeans2 is required " "to compute ellipsoid decompositions.") npoints, ndim = points.shape # Calculate the bounding ellipsoid for the points, possibly # enlarged to a minimum volume. firstell = bounding_ellipsoid(points, pointvol=pointvol) # Recursively split the bounding ellipsoid using `vol_check` # until the volume of each split no longer decreases by a # factor of `vol_dec`. ells = _bounding_ellipsoids(points, firstell, pointvol=pointvol, vol_dec=vol_dec, vol_check=vol_check) # Update the set of ellipsoids. self.nells = len(ells) self.ells = ells self.ctrs = np.array([ell.ctr for ell in self.ells]) self.covs = np.array([ell.cov for ell in self.ells]) self.ams = np.array([ell.am for ell in self.ells]) self.vols = np.array([ell.vol for ell in self.ells]) self.vol_tot = sum(self.vols) # Compute expansion factor. expands = np.array([ell.expand for ell in self.ells]) vols_orig = self.vols / expands vol_tot_orig = sum(vols_orig) self.expand_tot = self.vol_tot / vol_tot_orig # Use bootstrapping to determine the volume expansion factor. if bootstrap > 0: # If provided, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map ps = [points for it in range(bootstrap)] pvs = [pointvol for it in range(bootstrap)] vds = [vol_dec for it in range(bootstrap)] vcs = [vol_check for it in range(bootstrap)] args = zip(ps, pvs, vds, vcs) expands = list(M(_ellipsoids_bootstrap_expand, args)) # Conservatively set the expansion factor to be the maximum # factor derived from our set of bootstraps. expand = max(expands) # If our ellipsoids are overly constrained, expand them. if expand > 1.: vs = self.vols * expand**ndim self.scale_to_vols(vs) # Estimate the volume and fractional overlap with the unit cube # using Monte Carlo integration. if mc_integrate: self.vol, self.funit = self.monte_carlo_vol(return_overlap=True)
[ "def", "update", "(", "self", ",", "points", ",", "pointvol", "=", "0.", ",", "vol_dec", "=", "0.5", ",", "vol_check", "=", "2.", ",", "rstate", "=", "None", ",", "bootstrap", "=", "0", ",", "pool", "=", "None", ",", "mc_integrate", "=", "False", "...
Update the set of ellipsoids to bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. vol_dec : float, optional The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is `0.5`. vol_check : float, optional The factor used when checking if the volume of the original bounding ellipsoid is large enough to warrant `> 2` splits via `ell.vol > vol_check * nlive * pointvol`. Default is `2.0`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of ellipsoids with the unit cube. Default is `False`.
[ "Update", "the", "set", "of", "ellipsoids", "to", "bound", "the", "collection", "of", "points", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L530-L634
229,279
joshspeagle/dynesty
dynesty/bounding.py
RadFriends.scale_to_vol
def scale_to_vol(self, vol): """Scale ball to encompass a target volume.""" f = (vol / self.vol_ball) ** (1.0 / self.n) # linear factor self.expand *= f self.radius *= f self.vol_ball = vol
python
def scale_to_vol(self, vol): f = (vol / self.vol_ball) ** (1.0 / self.n) # linear factor self.expand *= f self.radius *= f self.vol_ball = vol
[ "def", "scale_to_vol", "(", "self", ",", "vol", ")", ":", "f", "=", "(", "vol", "/", "self", ".", "vol_ball", ")", "**", "(", "1.0", "/", "self", ".", "n", ")", "# linear factor", "self", ".", "expand", "*=", "f", "self", ".", "radius", "*=", "f"...
Scale ball to encompass a target volume.
[ "Scale", "ball", "to", "encompass", "a", "target", "volume", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L657-L663
229,280
joshspeagle/dynesty
dynesty/bounding.py
RadFriends.within
def within(self, x, ctrs, kdtree=None): """Check which balls `x` falls within. Uses a K-D Tree to perform the search if provided.""" if kdtree is None: # If no K-D Tree is provided, execute a brute-force # search over all balls. idxs = np.where(lalg.norm(ctrs - x, axis=1) <= self.radius)[0] else: # If a K-D Tree is provided, find all points within `self.radius`. idxs = kdtree.query_ball_point(x, self.radius, p=2.0, eps=0) return idxs
python
def within(self, x, ctrs, kdtree=None): if kdtree is None: # If no K-D Tree is provided, execute a brute-force # search over all balls. idxs = np.where(lalg.norm(ctrs - x, axis=1) <= self.radius)[0] else: # If a K-D Tree is provided, find all points within `self.radius`. idxs = kdtree.query_ball_point(x, self.radius, p=2.0, eps=0) return idxs
[ "def", "within", "(", "self", ",", "x", ",", "ctrs", ",", "kdtree", "=", "None", ")", ":", "if", "kdtree", "is", "None", ":", "# If no K-D Tree is provided, execute a brute-force", "# search over all balls.", "idxs", "=", "np", ".", "where", "(", "lalg", ".", ...
Check which balls `x` falls within. Uses a K-D Tree to perform the search if provided.
[ "Check", "which", "balls", "x", "falls", "within", ".", "Uses", "a", "K", "-", "D", "Tree", "to", "perform", "the", "search", "if", "provided", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L665-L677
229,281
joshspeagle/dynesty
dynesty/bounding.py
RadFriends.overlap
def overlap(self, x, ctrs, kdtree=None): """Check how many balls `x` falls within. Uses a K-D Tree to perform the search if provided.""" q = len(self.within(x, ctrs, kdtree=kdtree)) return q
python
def overlap(self, x, ctrs, kdtree=None): q = len(self.within(x, ctrs, kdtree=kdtree)) return q
[ "def", "overlap", "(", "self", ",", "x", ",", "ctrs", ",", "kdtree", "=", "None", ")", ":", "q", "=", "len", "(", "self", ".", "within", "(", "x", ",", "ctrs", ",", "kdtree", "=", "kdtree", ")", ")", "return", "q" ]
Check how many balls `x` falls within. Uses a K-D Tree to perform the search if provided.
[ "Check", "how", "many", "balls", "x", "falls", "within", ".", "Uses", "a", "K", "-", "D", "Tree", "to", "perform", "the", "search", "if", "provided", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L679-L685
229,282
joshspeagle/dynesty
dynesty/bounding.py
RadFriends.contains
def contains(self, x, ctrs, kdtree=None): """Check if the set of balls contains `x`. Uses a K-D Tree to perform the search if provided.""" return self.overlap(x, ctrs, kdtree=kdtree) > 0
python
def contains(self, x, ctrs, kdtree=None): return self.overlap(x, ctrs, kdtree=kdtree) > 0
[ "def", "contains", "(", "self", ",", "x", ",", "ctrs", ",", "kdtree", "=", "None", ")", ":", "return", "self", ".", "overlap", "(", "x", ",", "ctrs", ",", "kdtree", "=", "kdtree", ")", ">", "0" ]
Check if the set of balls contains `x`. Uses a K-D Tree to perform the search if provided.
[ "Check", "if", "the", "set", "of", "balls", "contains", "x", ".", "Uses", "a", "K", "-", "D", "Tree", "to", "perform", "the", "search", "if", "provided", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L687-L691
229,283
joshspeagle/dynesty
dynesty/bounding.py
RadFriends.update
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, kdtree=None, mc_integrate=False): """ Update the radii of our balls. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. kdtree : `~scipy.spatial.KDTree`, optional K-D Tree used to perform nearest neighbor searches. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of balls with the unit cube. Default is `False`. """ # If possible, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map if bootstrap == 0.: # Construct radius using leave-one-out if no bootstraps used. radii = _friends_leaveoneout_radius(points, 'balls') else: # Bootstrap radius using the set of live points. ps = [points for it in range(bootstrap)] ftypes = ['balls' for it in range(bootstrap)] args = zip(ps, ftypes) radii = list(M(_friends_bootstrap_radius, args)) # Conservatively set radius to be maximum of the set. rmax = max(radii) self.radius = rmax self.vol_ball = vol_prefactor(self.n) * self.radius**self.n self.expand = 1. # Expand our ball to encompass a minimum volume. if pointvol > 0.: v = pointvol if self.vol_ball < v: self.scale_to_vol(v) # Estimate the volume and fractional overlap with the unit cube # using Monte Carlo integration. if mc_integrate: self.vol, self.funit = self.monte_carlo_vol(points, kdtree=kdtree, return_overlap=True)
python
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, kdtree=None, mc_integrate=False): # If possible, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map if bootstrap == 0.: # Construct radius using leave-one-out if no bootstraps used. radii = _friends_leaveoneout_radius(points, 'balls') else: # Bootstrap radius using the set of live points. ps = [points for it in range(bootstrap)] ftypes = ['balls' for it in range(bootstrap)] args = zip(ps, ftypes) radii = list(M(_friends_bootstrap_radius, args)) # Conservatively set radius to be maximum of the set. rmax = max(radii) self.radius = rmax self.vol_ball = vol_prefactor(self.n) * self.radius**self.n self.expand = 1. # Expand our ball to encompass a minimum volume. if pointvol > 0.: v = pointvol if self.vol_ball < v: self.scale_to_vol(v) # Estimate the volume and fractional overlap with the unit cube # using Monte Carlo integration. if mc_integrate: self.vol, self.funit = self.monte_carlo_vol(points, kdtree=kdtree, return_overlap=True)
[ "def", "update", "(", "self", ",", "points", ",", "pointvol", "=", "0.", ",", "rstate", "=", "None", ",", "bootstrap", "=", "0", ",", "pool", "=", "None", ",", "kdtree", "=", "None", ",", "mc_integrate", "=", "False", ")", ":", "# If possible, compute ...
Update the radii of our balls. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. kdtree : `~scipy.spatial.KDTree`, optional K-D Tree used to perform nearest neighbor searches. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of balls with the unit cube. Default is `False`.
[ "Update", "the", "radii", "of", "our", "balls", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L794-L861
229,284
joshspeagle/dynesty
dynesty/bounding.py
SupFriends.scale_to_vol
def scale_to_vol(self, vol): """Scale cube to encompass a target volume.""" f = (vol / self.vol_cube) ** (1.0 / self.n) # linear factor self.expand *= f self.hside *= f self.vol_cube = vol
python
def scale_to_vol(self, vol): f = (vol / self.vol_cube) ** (1.0 / self.n) # linear factor self.expand *= f self.hside *= f self.vol_cube = vol
[ "def", "scale_to_vol", "(", "self", ",", "vol", ")", ":", "f", "=", "(", "vol", "/", "self", ".", "vol_cube", ")", "**", "(", "1.0", "/", "self", ".", "n", ")", "# linear factor", "self", ".", "expand", "*=", "f", "self", ".", "hside", "*=", "f",...
Scale cube to encompass a target volume.
[ "Scale", "cube", "to", "encompass", "a", "target", "volume", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L884-L890
229,285
joshspeagle/dynesty
dynesty/bounding.py
SupFriends.within
def within(self, x, ctrs, kdtree=None): """Checks which cubes `x` falls within. Uses a K-D Tree to perform the search if provided.""" if kdtree is None: # If no KDTree is provided, execute a brute-force search # over all cubes. idxs = np.where(np.max(np.abs(ctrs - x), axis=1) <= self.hside)[0] else: # If a KDTree is provided, find all points within r (`hside`). idxs = kdtree.query_ball_point(x, self.hside, p=np.inf, eps=0) return idxs
python
def within(self, x, ctrs, kdtree=None): if kdtree is None: # If no KDTree is provided, execute a brute-force search # over all cubes. idxs = np.where(np.max(np.abs(ctrs - x), axis=1) <= self.hside)[0] else: # If a KDTree is provided, find all points within r (`hside`). idxs = kdtree.query_ball_point(x, self.hside, p=np.inf, eps=0) return idxs
[ "def", "within", "(", "self", ",", "x", ",", "ctrs", ",", "kdtree", "=", "None", ")", ":", "if", "kdtree", "is", "None", ":", "# If no KDTree is provided, execute a brute-force search", "# over all cubes.", "idxs", "=", "np", ".", "where", "(", "np", ".", "m...
Checks which cubes `x` falls within. Uses a K-D Tree to perform the search if provided.
[ "Checks", "which", "cubes", "x", "falls", "within", ".", "Uses", "a", "K", "-", "D", "Tree", "to", "perform", "the", "search", "if", "provided", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L892-L904
229,286
joshspeagle/dynesty
dynesty/bounding.py
SupFriends.update
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, kdtree=None, mc_integrate=False): """ Update the half-side-lengths of our cubes. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. kdtree : `~scipy.spatial.KDTree`, optional K-D Tree used to perform nearest neighbor searches. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of balls with the unit cube. Default is `False`. """ if rstate is None: rstate = np.random # If possible, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map if bootstrap == 0.: # Construct radius using leave-one-out if no bootstraps used. hsides = _friends_leaveoneout_radius(points, 'cubes') else: # Bootstrap radius using the set of live points. ps = [points for it in range(bootstrap)] ftypes = ['cubes' for it in range(bootstrap)] args = zip(ps, ftypes) hsides = list(M(_friends_bootstrap_radius, args)) # Conservatively set radius to be maximum of the set. hsmax = max(hsides) self.hside = hsmax self.vol_cube = (2. * self.hside)**self.n self.expand = 1. # Expand our cube to encompass a minimum volume. if pointvol > 0.: v = pointvol if self.vol_cube < v: self.scale_to_vol(v) # Estimate the volume and fractional overlap with the unit cube # using Monte Carlo integration. if mc_integrate: self.vol, self.funit = self.monte_carlo_vol(points, kdtree=kdtree, return_overlap=True)
python
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, kdtree=None, mc_integrate=False): if rstate is None: rstate = np.random # If possible, compute bootstraps in parallel using a pool. if pool is None: M = map else: M = pool.map if bootstrap == 0.: # Construct radius using leave-one-out if no bootstraps used. hsides = _friends_leaveoneout_radius(points, 'cubes') else: # Bootstrap radius using the set of live points. ps = [points for it in range(bootstrap)] ftypes = ['cubes' for it in range(bootstrap)] args = zip(ps, ftypes) hsides = list(M(_friends_bootstrap_radius, args)) # Conservatively set radius to be maximum of the set. hsmax = max(hsides) self.hside = hsmax self.vol_cube = (2. * self.hside)**self.n self.expand = 1. # Expand our cube to encompass a minimum volume. if pointvol > 0.: v = pointvol if self.vol_cube < v: self.scale_to_vol(v) # Estimate the volume and fractional overlap with the unit cube # using Monte Carlo integration. if mc_integrate: self.vol, self.funit = self.monte_carlo_vol(points, kdtree=kdtree, return_overlap=True)
[ "def", "update", "(", "self", ",", "points", ",", "pointvol", "=", "0.", ",", "rstate", "=", "None", ",", "bootstrap", "=", "0", ",", "pool", "=", "None", ",", "kdtree", "=", "None", ",", "mc_integrate", "=", "False", ")", ":", "if", "rstate", "is"...
Update the half-side-lengths of our cubes. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. pointvol : float, optional The minimum volume associated with each point. Default is `0.`. rstate : `~numpy.random.RandomState`, optional `~numpy.random.RandomState` instance. bootstrap : int, optional The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points "left out" during each iteration is used to enlarge the resulting volumes. Default is `0`. pool : user-provided pool, optional Use this pool of workers to execute operations in parallel. kdtree : `~scipy.spatial.KDTree`, optional K-D Tree used to perform nearest neighbor searches. mc_integrate : bool, optional Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of balls with the unit cube. Default is `False`.
[ "Update", "the", "half", "-", "side", "-", "lengths", "of", "our", "cubes", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L1021-L1091
229,287
joshspeagle/dynesty
dynesty/sampling.py
sample_unif
def sample_unif(args): """ Evaluate a new point sampled uniformly from a bounding proposal distribution. Parameters are zipped within `args` to utilize `pool.map`-style functions. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) Position of the initial sample. loglstar : float Ln(likelihood) bound. **Not applicable here.** axes : `~numpy.ndarray` with shape (ndim, ndim) Axes used to propose new points. **Not applicable here.** scale : float Value used to scale the provided axes. **Not applicable here.** prior_transform : function Function transforming a sample from the a unit cube to the parameter space of interest according to the prior. loglikelihood : function Function returning ln(likelihood) given parameters as a 1-d `~numpy` array of length `ndim`. kwargs : dict A dictionary of additional method-specific parameters. **Not applicable here.** Returns ------- u : `~numpy.ndarray` with shape (npdim,) Position of the final proposed point within the unit cube. **For uniform sampling this is the same as the initial input position.** v : `~numpy.ndarray` with shape (ndim,) Position of the final proposed point in the target parameter space. logl : float Ln(likelihood) of the final proposed point. nc : int Number of function calls used to generate the sample. For uniform sampling this is `1` by construction. blob : dict Collection of ancillary quantities used to tune :data:`scale`. **Not applicable for uniform sampling.** """ # Unzipping. (u, loglstar, axes, scale, prior_transform, loglikelihood, kwargs) = args # Evaluate. v = prior_transform(np.array(u)) logl = loglikelihood(np.array(v)) nc = 1 blob = None return u, v, logl, nc, blob
python
def sample_unif(args): # Unzipping. (u, loglstar, axes, scale, prior_transform, loglikelihood, kwargs) = args # Evaluate. v = prior_transform(np.array(u)) logl = loglikelihood(np.array(v)) nc = 1 blob = None return u, v, logl, nc, blob
[ "def", "sample_unif", "(", "args", ")", ":", "# Unzipping.", "(", "u", ",", "loglstar", ",", "axes", ",", "scale", ",", "prior_transform", ",", "loglikelihood", ",", "kwargs", ")", "=", "args", "# Evaluate.", "v", "=", "prior_transform", "(", "np", ".", ...
Evaluate a new point sampled uniformly from a bounding proposal distribution. Parameters are zipped within `args` to utilize `pool.map`-style functions. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) Position of the initial sample. loglstar : float Ln(likelihood) bound. **Not applicable here.** axes : `~numpy.ndarray` with shape (ndim, ndim) Axes used to propose new points. **Not applicable here.** scale : float Value used to scale the provided axes. **Not applicable here.** prior_transform : function Function transforming a sample from the a unit cube to the parameter space of interest according to the prior. loglikelihood : function Function returning ln(likelihood) given parameters as a 1-d `~numpy` array of length `ndim`. kwargs : dict A dictionary of additional method-specific parameters. **Not applicable here.** Returns ------- u : `~numpy.ndarray` with shape (npdim,) Position of the final proposed point within the unit cube. **For uniform sampling this is the same as the initial input position.** v : `~numpy.ndarray` with shape (ndim,) Position of the final proposed point in the target parameter space. logl : float Ln(likelihood) of the final proposed point. nc : int Number of function calls used to generate the sample. For uniform sampling this is `1` by construction. blob : dict Collection of ancillary quantities used to tune :data:`scale`. **Not applicable for uniform sampling.**
[ "Evaluate", "a", "new", "point", "sampled", "uniformly", "from", "a", "bounding", "proposal", "distribution", ".", "Parameters", "are", "zipped", "within", "args", "to", "utilize", "pool", ".", "map", "-", "style", "functions", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampling.py#L30-L94
229,288
joshspeagle/dynesty
dynesty/sampling.py
sample_rwalk
def sample_rwalk(args): """ Return a new live point proposed by random walking away from an existing live point. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) Position of the initial sample. **This is a copy of an existing live point.** loglstar : float Ln(likelihood) bound. axes : `~numpy.ndarray` with shape (ndim, ndim) Axes used to propose new points. For random walks new positions are proposed using the :class:`~dynesty.bounding.Ellipsoid` whose shape is defined by axes. scale : float Value used to scale the provided axes. prior_transform : function Function transforming a sample from the a unit cube to the parameter space of interest according to the prior. loglikelihood : function Function returning ln(likelihood) given parameters as a 1-d `~numpy` array of length `ndim`. kwargs : dict A dictionary of additional method-specific parameters. Returns ------- u : `~numpy.ndarray` with shape (npdim,) Position of the final proposed point within the unit cube. v : `~numpy.ndarray` with shape (ndim,) Position of the final proposed point in the target parameter space. logl : float Ln(likelihood) of the final proposed point. nc : int Number of function calls used to generate the sample. blob : dict Collection of ancillary quantities used to tune :data:`scale`. """ # Unzipping. (u, loglstar, axes, scale, prior_transform, loglikelihood, kwargs) = args rstate = np.random # Periodicity. nonperiodic = kwargs.get('nonperiodic', None) # Setup. n = len(u) walks = kwargs.get('walks', 25) # number of steps accept = 0 reject = 0 fail = 0 nfail = 0 nc = 0 ncall = 0 drhat, dr, du, u_prop, logl_prop = np.nan, np.nan, np.nan, np.nan, np.nan while nc < walks or accept == 0: while True: # Check scale-factor. if scale == 0.: raise RuntimeError("The random walk sampling is stuck! " "Some useful output quantities:\n" "u: {0}\n" "drhat: {1}\n" "dr: {2}\n" "du: {3}\n" "u_prop: {4}\n" "loglstar: {5}\n" "logl_prop: {6}\n" "axes: {7}\n" "scale: {8}." .format(u, drhat, dr, du, u_prop, loglstar, logl_prop, axes, scale)) # Propose a direction on the unit n-sphere. drhat = rstate.randn(n) drhat /= linalg.norm(drhat) # Scale based on dimensionality. dr = drhat * rstate.rand()**(1./n) # Transform to proposal distribution. du = np.dot(axes, dr) u_prop = u + scale * du # Check unit cube constraints. if unitcheck(u_prop, nonperiodic): break else: fail += 1 nfail += 1 # Check if we're stuck generating bad numbers. if fail > 100 * walks: warnings.warn("Random number generation appears to be " "extremely inefficient. Adjusting the " "scale-factor accordingly.") fail = 0 scale *= math.exp(-1. / n) # Check proposed point. v_prop = prior_transform(np.array(u_prop)) logl_prop = loglikelihood(np.array(v_prop)) if logl_prop >= loglstar: u = u_prop v = v_prop logl = logl_prop accept += 1 else: reject += 1 nc += 1 ncall += 1 # Check if we're stuck generating bad points. if nc > 50 * walks: scale *= math.exp(-1. / n) warnings.warn("Random walk proposals appear to be " "extremely inefficient. Adjusting the " "scale-factor accordingly.") nc, accept, reject = 0, 0, 0 # reset values blob = {'accept': accept, 'reject': reject, 'fail': nfail, 'scale': scale} return u, v, logl, ncall, blob
python
def sample_rwalk(args): # Unzipping. (u, loglstar, axes, scale, prior_transform, loglikelihood, kwargs) = args rstate = np.random # Periodicity. nonperiodic = kwargs.get('nonperiodic', None) # Setup. n = len(u) walks = kwargs.get('walks', 25) # number of steps accept = 0 reject = 0 fail = 0 nfail = 0 nc = 0 ncall = 0 drhat, dr, du, u_prop, logl_prop = np.nan, np.nan, np.nan, np.nan, np.nan while nc < walks or accept == 0: while True: # Check scale-factor. if scale == 0.: raise RuntimeError("The random walk sampling is stuck! " "Some useful output quantities:\n" "u: {0}\n" "drhat: {1}\n" "dr: {2}\n" "du: {3}\n" "u_prop: {4}\n" "loglstar: {5}\n" "logl_prop: {6}\n" "axes: {7}\n" "scale: {8}." .format(u, drhat, dr, du, u_prop, loglstar, logl_prop, axes, scale)) # Propose a direction on the unit n-sphere. drhat = rstate.randn(n) drhat /= linalg.norm(drhat) # Scale based on dimensionality. dr = drhat * rstate.rand()**(1./n) # Transform to proposal distribution. du = np.dot(axes, dr) u_prop = u + scale * du # Check unit cube constraints. if unitcheck(u_prop, nonperiodic): break else: fail += 1 nfail += 1 # Check if we're stuck generating bad numbers. if fail > 100 * walks: warnings.warn("Random number generation appears to be " "extremely inefficient. Adjusting the " "scale-factor accordingly.") fail = 0 scale *= math.exp(-1. / n) # Check proposed point. v_prop = prior_transform(np.array(u_prop)) logl_prop = loglikelihood(np.array(v_prop)) if logl_prop >= loglstar: u = u_prop v = v_prop logl = logl_prop accept += 1 else: reject += 1 nc += 1 ncall += 1 # Check if we're stuck generating bad points. if nc > 50 * walks: scale *= math.exp(-1. / n) warnings.warn("Random walk proposals appear to be " "extremely inefficient. Adjusting the " "scale-factor accordingly.") nc, accept, reject = 0, 0, 0 # reset values blob = {'accept': accept, 'reject': reject, 'fail': nfail, 'scale': scale} return u, v, logl, ncall, blob
[ "def", "sample_rwalk", "(", "args", ")", ":", "# Unzipping.", "(", "u", ",", "loglstar", ",", "axes", ",", "scale", ",", "prior_transform", ",", "loglikelihood", ",", "kwargs", ")", "=", "args", "rstate", "=", "np", ".", "random", "# Periodicity.", "nonper...
Return a new live point proposed by random walking away from an existing live point. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) Position of the initial sample. **This is a copy of an existing live point.** loglstar : float Ln(likelihood) bound. axes : `~numpy.ndarray` with shape (ndim, ndim) Axes used to propose new points. For random walks new positions are proposed using the :class:`~dynesty.bounding.Ellipsoid` whose shape is defined by axes. scale : float Value used to scale the provided axes. prior_transform : function Function transforming a sample from the a unit cube to the parameter space of interest according to the prior. loglikelihood : function Function returning ln(likelihood) given parameters as a 1-d `~numpy` array of length `ndim`. kwargs : dict A dictionary of additional method-specific parameters. Returns ------- u : `~numpy.ndarray` with shape (npdim,) Position of the final proposed point within the unit cube. v : `~numpy.ndarray` with shape (ndim,) Position of the final proposed point in the target parameter space. logl : float Ln(likelihood) of the final proposed point. nc : int Number of function calls used to generate the sample. blob : dict Collection of ancillary quantities used to tune :data:`scale`.
[ "Return", "a", "new", "live", "point", "proposed", "by", "random", "walking", "away", "from", "an", "existing", "live", "point", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampling.py#L97-L236
229,289
joshspeagle/dynesty
dynesty/sampler.py
Sampler.results
def results(self): """Saved results from the nested sampling run. If bounding distributions were saved, those are also returned.""" # Add all saved samples to the results. if self.save_samples: with warnings.catch_warnings(): warnings.simplefilter("ignore") results = [('nlive', self.nlive), ('niter', self.it - 1), ('ncall', np.array(self.saved_nc)), ('eff', self.eff), ('samples', np.array(self.saved_v)), ('samples_id', np.array(self.saved_id)), ('samples_it', np.array(self.saved_it)), ('samples_u', np.array(self.saved_u)), ('logwt', np.array(self.saved_logwt)), ('logl', np.array(self.saved_logl)), ('logvol', np.array(self.saved_logvol)), ('logz', np.array(self.saved_logz)), ('logzerr', np.sqrt(np.array(self.saved_logzvar))), ('information', np.array(self.saved_h))] else: raise ValueError("You didn't save any samples!") # Add any saved bounds (and ancillary quantities) to the results. if self.save_bounds: results.append(('bound', copy.deepcopy(self.bound))) results.append(('bound_iter', np.array(self.saved_bounditer, dtype='int'))) results.append(('samples_bound', np.array(self.saved_boundidx, dtype='int'))) results.append(('scale', np.array(self.saved_scale))) return Results(results)
python
def results(self): # Add all saved samples to the results. if self.save_samples: with warnings.catch_warnings(): warnings.simplefilter("ignore") results = [('nlive', self.nlive), ('niter', self.it - 1), ('ncall', np.array(self.saved_nc)), ('eff', self.eff), ('samples', np.array(self.saved_v)), ('samples_id', np.array(self.saved_id)), ('samples_it', np.array(self.saved_it)), ('samples_u', np.array(self.saved_u)), ('logwt', np.array(self.saved_logwt)), ('logl', np.array(self.saved_logl)), ('logvol', np.array(self.saved_logvol)), ('logz', np.array(self.saved_logz)), ('logzerr', np.sqrt(np.array(self.saved_logzvar))), ('information', np.array(self.saved_h))] else: raise ValueError("You didn't save any samples!") # Add any saved bounds (and ancillary quantities) to the results. if self.save_bounds: results.append(('bound', copy.deepcopy(self.bound))) results.append(('bound_iter', np.array(self.saved_bounditer, dtype='int'))) results.append(('samples_bound', np.array(self.saved_boundidx, dtype='int'))) results.append(('scale', np.array(self.saved_scale))) return Results(results)
[ "def", "results", "(", "self", ")", ":", "# Add all saved samples to the results.", "if", "self", ".", "save_samples", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "results", "=", "[", ...
Saved results from the nested sampling run. If bounding distributions were saved, those are also returned.
[ "Saved", "results", "from", "the", "nested", "sampling", "run", ".", "If", "bounding", "distributions", "were", "saved", "those", "are", "also", "returned", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L206-L240
229,290
joshspeagle/dynesty
dynesty/sampler.py
Sampler._beyond_unit_bound
def _beyond_unit_bound(self, loglstar): """Check whether we should update our bound beyond the initial unit cube.""" if self.logl_first_update is None: # If we haven't already updated our bounds, check if we satisfy # the provided criteria for establishing the first bounding update. check = (self.ncall > self.ubound_ncall and self.eff < self.ubound_eff) if check: # Save the log-likelihood where our first update took place. self.logl_first_update = loglstar return check else: # If we've already update our bounds, check if we've exceeded the # saved log-likelihood threshold. (This is useful when sampling # within `dynamicsampler`). return loglstar >= self.logl_first_update
python
def _beyond_unit_bound(self, loglstar): if self.logl_first_update is None: # If we haven't already updated our bounds, check if we satisfy # the provided criteria for establishing the first bounding update. check = (self.ncall > self.ubound_ncall and self.eff < self.ubound_eff) if check: # Save the log-likelihood where our first update took place. self.logl_first_update = loglstar return check else: # If we've already update our bounds, check if we've exceeded the # saved log-likelihood threshold. (This is useful when sampling # within `dynamicsampler`). return loglstar >= self.logl_first_update
[ "def", "_beyond_unit_bound", "(", "self", ",", "loglstar", ")", ":", "if", "self", ".", "logl_first_update", "is", "None", ":", "# If we haven't already updated our bounds, check if we satisfy", "# the provided criteria for establishing the first bounding update.", "check", "=", ...
Check whether we should update our bound beyond the initial unit cube.
[ "Check", "whether", "we", "should", "update", "our", "bound", "beyond", "the", "initial", "unit", "cube", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L242-L259
229,291
joshspeagle/dynesty
dynesty/sampler.py
Sampler._empty_queue
def _empty_queue(self): """Dump all live point proposals currently on the queue.""" while True: try: # Remove unused points from the queue. self.queue.pop() self.unused += 1 # add to the total number of unused points self.nqueue -= 1 except: # If the queue is empty, we're done! self.nqueue = 0 break
python
def _empty_queue(self): while True: try: # Remove unused points from the queue. self.queue.pop() self.unused += 1 # add to the total number of unused points self.nqueue -= 1 except: # If the queue is empty, we're done! self.nqueue = 0 break
[ "def", "_empty_queue", "(", "self", ")", ":", "while", "True", ":", "try", ":", "# Remove unused points from the queue.", "self", ".", "queue", ".", "pop", "(", ")", "self", ".", "unused", "+=", "1", "# add to the total number of unused points", "self", ".", "nq...
Dump all live point proposals currently on the queue.
[ "Dump", "all", "live", "point", "proposals", "currently", "on", "the", "queue", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L261-L273
229,292
joshspeagle/dynesty
dynesty/sampler.py
Sampler._fill_queue
def _fill_queue(self, loglstar): """Sequentially add new live point proposals to the queue.""" # Add/zip arguments to submit to the queue. point_queue = [] axes_queue = [] while self.nqueue < self.queue_size: if self._beyond_unit_bound(loglstar): # Propose points using the provided sampling/bounding options. point, axes = self.propose_point() evolve_point = self.evolve_point else: # Propose/evaluate points directly from the unit cube. point = self.rstate.rand(self.npdim) axes = np.identity(self.npdim) evolve_point = sample_unif point_queue.append(point) axes_queue.append(axes) self.nqueue += 1 loglstars = [loglstar for i in range(self.queue_size)] scales = [self.scale for i in range(self.queue_size)] ptforms = [self.prior_transform for i in range(self.queue_size)] logls = [self.loglikelihood for i in range(self.queue_size)] kwargs = [self.kwargs for i in range(self.queue_size)] args = zip(point_queue, loglstars, axes_queue, scales, ptforms, logls, kwargs) if self.use_pool_evolve: # Use the pool to propose ("evolve") a new live point. self.queue = list(self.M(evolve_point, args)) else: # Propose ("evolve") a new live point using the default `map` # function. self.queue = list(map(evolve_point, args))
python
def _fill_queue(self, loglstar): # Add/zip arguments to submit to the queue. point_queue = [] axes_queue = [] while self.nqueue < self.queue_size: if self._beyond_unit_bound(loglstar): # Propose points using the provided sampling/bounding options. point, axes = self.propose_point() evolve_point = self.evolve_point else: # Propose/evaluate points directly from the unit cube. point = self.rstate.rand(self.npdim) axes = np.identity(self.npdim) evolve_point = sample_unif point_queue.append(point) axes_queue.append(axes) self.nqueue += 1 loglstars = [loglstar for i in range(self.queue_size)] scales = [self.scale for i in range(self.queue_size)] ptforms = [self.prior_transform for i in range(self.queue_size)] logls = [self.loglikelihood for i in range(self.queue_size)] kwargs = [self.kwargs for i in range(self.queue_size)] args = zip(point_queue, loglstars, axes_queue, scales, ptforms, logls, kwargs) if self.use_pool_evolve: # Use the pool to propose ("evolve") a new live point. self.queue = list(self.M(evolve_point, args)) else: # Propose ("evolve") a new live point using the default `map` # function. self.queue = list(map(evolve_point, args))
[ "def", "_fill_queue", "(", "self", ",", "loglstar", ")", ":", "# Add/zip arguments to submit to the queue.", "point_queue", "=", "[", "]", "axes_queue", "=", "[", "]", "while", "self", ".", "nqueue", "<", "self", ".", "queue_size", ":", "if", "self", ".", "_...
Sequentially add new live point proposals to the queue.
[ "Sequentially", "add", "new", "live", "point", "proposals", "to", "the", "queue", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L275-L308
229,293
joshspeagle/dynesty
dynesty/sampler.py
Sampler._get_point_value
def _get_point_value(self, loglstar): """Grab the first live point proposal in the queue.""" # If the queue is empty, refill it. if self.nqueue <= 0: self._fill_queue(loglstar) # Grab the earliest entry. u, v, logl, nc, blob = self.queue.pop(0) self.used += 1 # add to the total number of used points self.nqueue -= 1 return u, v, logl, nc, blob
python
def _get_point_value(self, loglstar): # If the queue is empty, refill it. if self.nqueue <= 0: self._fill_queue(loglstar) # Grab the earliest entry. u, v, logl, nc, blob = self.queue.pop(0) self.used += 1 # add to the total number of used points self.nqueue -= 1 return u, v, logl, nc, blob
[ "def", "_get_point_value", "(", "self", ",", "loglstar", ")", ":", "# If the queue is empty, refill it.", "if", "self", ".", "nqueue", "<=", "0", ":", "self", ".", "_fill_queue", "(", "loglstar", ")", "# Grab the earliest entry.", "u", ",", "v", ",", "logl", "...
Grab the first live point proposal in the queue.
[ "Grab", "the", "first", "live", "point", "proposal", "in", "the", "queue", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L310-L322
229,294
joshspeagle/dynesty
dynesty/sampler.py
Sampler._new_point
def _new_point(self, loglstar, logvol): """Propose points until a new point that satisfies the log-likelihood constraint `loglstar` is found.""" ncall, nupdate = 0, 0 while True: # Get the next point from the queue u, v, logl, nc, blob = self._get_point_value(loglstar) ncall += nc # Bounding checks. ucheck = ncall >= self.update_interval * (1 + nupdate) bcheck = self._beyond_unit_bound(loglstar) # If our queue is empty, update any tuning parameters associated # with our proposal (sampling) method. if blob is not None and self.nqueue <= 0 and bcheck: self.update_proposal(blob) # If we satisfy the log-likelihood constraint, we're done! if logl >= loglstar: break # If there has been more than `update_interval` function calls # made *and* we satisfy the criteria for moving beyond sampling # from the unit cube, update the bound. if ucheck and bcheck: pointvol = math.exp(logvol) / self.nlive bound = self.update(pointvol) if self.save_bounds: self.bound.append(bound) self.nbound += 1 nupdate += 1 self.since_update = -ncall # ncall will be added back later return u, v, logl, ncall
python
def _new_point(self, loglstar, logvol): ncall, nupdate = 0, 0 while True: # Get the next point from the queue u, v, logl, nc, blob = self._get_point_value(loglstar) ncall += nc # Bounding checks. ucheck = ncall >= self.update_interval * (1 + nupdate) bcheck = self._beyond_unit_bound(loglstar) # If our queue is empty, update any tuning parameters associated # with our proposal (sampling) method. if blob is not None and self.nqueue <= 0 and bcheck: self.update_proposal(blob) # If we satisfy the log-likelihood constraint, we're done! if logl >= loglstar: break # If there has been more than `update_interval` function calls # made *and* we satisfy the criteria for moving beyond sampling # from the unit cube, update the bound. if ucheck and bcheck: pointvol = math.exp(logvol) / self.nlive bound = self.update(pointvol) if self.save_bounds: self.bound.append(bound) self.nbound += 1 nupdate += 1 self.since_update = -ncall # ncall will be added back later return u, v, logl, ncall
[ "def", "_new_point", "(", "self", ",", "loglstar", ",", "logvol", ")", ":", "ncall", ",", "nupdate", "=", "0", ",", "0", "while", "True", ":", "# Get the next point from the queue", "u", ",", "v", ",", "logl", ",", "nc", ",", "blob", "=", "self", ".", ...
Propose points until a new point that satisfies the log-likelihood constraint `loglstar` is found.
[ "Propose", "points", "until", "a", "new", "point", "that", "satisfies", "the", "log", "-", "likelihood", "constraint", "loglstar", "is", "found", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L324-L359
229,295
joshspeagle/dynesty
dynesty/sampler.py
Sampler._remove_live_points
def _remove_live_points(self): """Remove the final set of live points if they were previously added to the current set of dead points.""" if self.added_live: self.added_live = False if self.save_samples: del self.saved_id[-self.nlive:] del self.saved_u[-self.nlive:] del self.saved_v[-self.nlive:] del self.saved_logl[-self.nlive:] del self.saved_logvol[-self.nlive:] del self.saved_logwt[-self.nlive:] del self.saved_logz[-self.nlive:] del self.saved_logzvar[-self.nlive:] del self.saved_h[-self.nlive:] del self.saved_nc[-self.nlive:] del self.saved_boundidx[-self.nlive:] del self.saved_it[-self.nlive:] del self.saved_bounditer[-self.nlive:] del self.saved_scale[-self.nlive:] else: raise ValueError("No live points were added to the " "list of samples!")
python
def _remove_live_points(self): if self.added_live: self.added_live = False if self.save_samples: del self.saved_id[-self.nlive:] del self.saved_u[-self.nlive:] del self.saved_v[-self.nlive:] del self.saved_logl[-self.nlive:] del self.saved_logvol[-self.nlive:] del self.saved_logwt[-self.nlive:] del self.saved_logz[-self.nlive:] del self.saved_logzvar[-self.nlive:] del self.saved_h[-self.nlive:] del self.saved_nc[-self.nlive:] del self.saved_boundidx[-self.nlive:] del self.saved_it[-self.nlive:] del self.saved_bounditer[-self.nlive:] del self.saved_scale[-self.nlive:] else: raise ValueError("No live points were added to the " "list of samples!")
[ "def", "_remove_live_points", "(", "self", ")", ":", "if", "self", ".", "added_live", ":", "self", ".", "added_live", "=", "False", "if", "self", ".", "save_samples", ":", "del", "self", ".", "saved_id", "[", "-", "self", ".", "nlive", ":", "]", "del",...
Remove the final set of live points if they were previously added to the current set of dead points.
[ "Remove", "the", "final", "set", "of", "live", "points", "if", "they", "were", "previously", "added", "to", "the", "current", "set", "of", "dead", "points", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L457-L480
229,296
joshspeagle/dynesty
priors.py
Prior.update
def update(self, **kwargs): """Update `params` values using alias. """ for k in self.prior_params: try: self.params[k] = kwargs[self.alias[k]] except(KeyError): pass
python
def update(self, **kwargs): for k in self.prior_params: try: self.params[k] = kwargs[self.alias[k]] except(KeyError): pass
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", "in", "self", ".", "prior_params", ":", "try", ":", "self", ".", "params", "[", "k", "]", "=", "kwargs", "[", "self", ".", "alias", "[", "k", "]", "]", "except", "(", ...
Update `params` values using alias.
[ "Update", "params", "values", "using", "alias", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/priors.py#L70-L77
229,297
joshspeagle/dynesty
priors.py
Prior.sample
def sample(self, nsample=None, **kwargs): """Draw a sample from the prior distribution. :param nsample: (optional) Unused """ if len(kwargs) > 0: self.update(**kwargs) return self.distribution.rvs(*self.args, size=len(self), loc=self.loc, scale=self.scale)
python
def sample(self, nsample=None, **kwargs): if len(kwargs) > 0: self.update(**kwargs) return self.distribution.rvs(*self.args, size=len(self), loc=self.loc, scale=self.scale)
[ "def", "sample", "(", "self", ",", "nsample", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", ">", "0", ":", "self", ".", "update", "(", "*", "*", "kwargs", ")", "return", "self", ".", "distribution", ".", "rvs", ...
Draw a sample from the prior distribution. :param nsample: (optional) Unused
[ "Draw", "a", "sample", "from", "the", "prior", "distribution", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/priors.py#L107-L116
229,298
joshspeagle/dynesty
priors.py
Prior.inverse_unit_transform
def inverse_unit_transform(self, x, **kwargs): """Go from the parameter value to the unit coordinate using the cdf. """ if len(kwargs) > 0: self.update(**kwargs) return self.distribution.cdf(x, *self.args, loc=self.loc, scale=self.scale)
python
def inverse_unit_transform(self, x, **kwargs): if len(kwargs) > 0: self.update(**kwargs) return self.distribution.cdf(x, *self.args, loc=self.loc, scale=self.scale)
[ "def", "inverse_unit_transform", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", ">", "0", ":", "self", ".", "update", "(", "*", "*", "kwargs", ")", "return", "self", ".", "distribution", ".", "cdf", "(", ...
Go from the parameter value to the unit coordinate using the cdf.
[ "Go", "from", "the", "parameter", "value", "to", "the", "unit", "coordinate", "using", "the", "cdf", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/priors.py#L135-L141
229,299
joshspeagle/dynesty
dynesty/nestedsamplers.py
UnitCubeSampler.update_slice
def update_slice(self, blob): """Update the slice proposal scale based on the relative size of the slices compared to our initial guess.""" nexpand, ncontract = blob['nexpand'], blob['ncontract'] self.scale *= nexpand / (2. * ncontract)
python
def update_slice(self, blob): nexpand, ncontract = blob['nexpand'], blob['ncontract'] self.scale *= nexpand / (2. * ncontract)
[ "def", "update_slice", "(", "self", ",", "blob", ")", ":", "nexpand", ",", "ncontract", "=", "blob", "[", "'nexpand'", "]", ",", "blob", "[", "'ncontract'", "]", "self", ".", "scale", "*=", "nexpand", "/", "(", "2.", "*", "ncontract", ")" ]
Update the slice proposal scale based on the relative size of the slices compared to our initial guess.
[ "Update", "the", "slice", "proposal", "scale", "based", "on", "the", "relative", "size", "of", "the", "slices", "compared", "to", "our", "initial", "guess", "." ]
9e482aafeb5cf84bedb896fa6f07a761d917983e
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/nestedsamplers.py#L209-L214