docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Average a series of datetime objects. .. note:: This function assumes all datetime objects are naive and in the same time zone (UTC). Args: dt_list (iterable): Datetime objects to average Returns: Average datetime as a datetime object
def average_datetimes(dt_list): if sys.version_info < (3, 3): # timestamp added in python 3.3 import time def timestamp_func(dt): return time.mktime(dt.timetuple()) else: timestamp_func = datetime.timestamp total = [timestamp_func(dt) for dt in dt_list] ...
293,768
Return if two wavelengths are equal. Args: a (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl b (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
def wavelength_match(a, b): if type(a) == (type(b) or isinstance(a, numbers.Number) and isinstance(b, numbers.Number)): return a == b elif a is None or b is None: return False elif isinstance(a, (list, tuple)) and len...
293,773
Configure reader behavior. Args: mask_surface (boolean): mask anything below the surface pressure mask_quality (boolean): mask anything where the `Quality_Flag` metadata is ``!= 1``.
def __init__(self, config_files, mask_surface=True, mask_quality=True, **kwargs): self.pressure_dataset_names = defaultdict(list) super(NUCAPSReader, self).__init__(config_files, **kwargs) self.mask_surface = self.info.get('mask_surface', mask_...
293,808
Test calibration coefficients against NOAA reference pages Currently the reference pages are: ir_url = https://www.ospo.noaa.gov/Operations/GOES/calibration/gvar-conversion.html vis_url = https://www.ospo.noaa.gov/Operations/GOES/calibration/goes-vis-ch-calibration.html Args: ir_url: Path or ...
def test_coefs(ir_url, vis_url): reader = GOESCoefficientReader(ir_url=ir_url, vis_url=vis_url) for platform in CALIB_COEFS.keys(): for channel, coefs in CALIB_COEFS[platform].items(): coefs_expected = reader.get_coefs(platform=platform, ch...
293,924
Find the nadir pixel Args: earth_mask: Mask identifying earth and space pixels sector: Specifies the scanned sector Returns: nadir row, nadir column
def _get_nadir_pixel(earth_mask, sector): if sector == FULL_DISC: logger.debug('Computing nadir pixel') # The earth is not centered in the image, compute bounding box # of the earth disc first rmin, rmax, cmin, cmax = bbox(earth_mask) # The ...
293,929
Convert IR counts to radiance Reference: [IR]. Args: counts: Raw detector counts scale: Scale [mW-1 m2 cm sr] offset: Offset [1] Returns: Radiance [mW m-2 cm-1 sr-1]
def _ircounts2radiance(counts, scale, offset): rad = (counts - offset) / scale return rad.clip(min=0)
293,937
Convert VIS counts to radiance References: [VIS] Args: counts: Raw detector counts slope: Slope [W m-2 um-1 sr-1] offset: Offset [W m-2 um-1 sr-1] Returns: Radiance [W m-2 um-1 sr-1]
def _viscounts2radiance(counts, slope, offset): rad = counts * slope + offset return rad.clip(min=0)
293,939
Apply `func` to the provided data. Args: data (xarray.DataArray): Data to be modified inplace. func (callable): Function to be applied to an xarray exclude (iterable): Bands in the 'bands' dimension to not include in the calculations. separate (bool): App...
def apply_enhancement(data, func, exclude=None, separate=False, pass_dask=False): attrs = data.attrs bands = data.coords['bands'].values if exclude is None: exclude = ['A'] if 'A' in bands else [] if separate: data_arrs = [] for idx, band_name in enume...
293,974
Convert convolution layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for...
def convert_conv(params, w_name, scope_name, inputs, layers, weights, names): print('Converting convolution ...') if names == 'short': tf_name = 'C' + random_string(7) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) bias_name = '{0}...
294,116
Convert transposed convolution layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use shor...
def convert_convtranspose(params, w_name, scope_name, inputs, layers, weights, names): print('Converting transposed convolution ...') if names == 'short': tf_name = 'C' + random_string(7) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) ...
294,117
Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
def convert_sum( params, w_name, scope_name, inputs, layers, weights, names ): print('Converting Sum ...') def target_layer(x): import keras.backend as K return K.sum(x) lambda_layer = keras.layers.Lambda(target_layer) layers[scope_name] = lambda_layer(layers[inputs[0]])
294,118
Convert reduce_sum layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ...
def convert_reduce_sum(params, w_name, scope_name, inputs, layers, weights, names): print('Converting reduce_sum ...') keepdims = params['keepdims'] > 0 axis = params['axes'] def target_layer(x, keepdims=keepdims, axis=axis): import keras.backend as K return K.sum(x, keepdims=keep...
294,119
Convert concatenation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ker...
def convert_concat(params, w_name, scope_name, inputs, layers, weights, names): print('Converting concat ...') concat_nodes = [layers[i] for i in inputs] if len(concat_nodes) == 1: # no-op layers[scope_name] = concat_nodes[0] return if names == 'short': tf_name = '...
294,120
Convert slice operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for k...
def convert_slice(params, w_name, scope_name, inputs, layers, weights, names): print('Converting slice ...') if len(params['axes']) > 1: raise AssertionError('Cannot convert slice by multiple dimensions') if params['axes'][0] not in [0, 1, 2, 3]: raise AssertionError('Slice by dimensi...
294,121
Convert clip operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ke...
def convert_clip(params, w_name, scope_name, inputs, layers, weights, names): print('Converting clip ...') if params['min'] == 0: print("using ReLU({0})".format(params['max'])) layer = keras.layers.ReLU(max_value=params['max']) else: def target_layer(x, vmin=params['min'], vmax...
294,122
Convert elementwise addition. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names ...
def convert_elementwise_add( params, w_name, scope_name, inputs, layers, weights, names ): print('Converting elementwise_add ...') if 'broadcast' in params: model0 = layers[inputs[0]] model1 = layers[inputs[1]] if names == 'short': tf_name = 'A' + random_string(7) ...
294,123
Convert elementwise multiplication. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short ...
def convert_elementwise_mul( params, w_name, scope_name, inputs, layers, weights, names ): print('Converting elementwise_mul ...') model0 = layers[inputs[0]] model1 = layers[inputs[1]] if names == 'short': tf_name = 'M' + random_string(7) elif names == 'keep': tf_name = w_n...
294,124
Convert elementwise multiplication. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short ...
def convert_elementwise_div( params, w_name, scope_name, inputs, layers, weights, names ): print('Converting elementwise_div ...') if names == 'short': tf_name = 'D' + random_string(7) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) ...
294,125
Convert elementwise subtraction. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short nam...
def convert_elementwise_sub( params, w_name, scope_name, inputs, layers, weights, names ): print('Converting elementwise_sub ...') model0 = layers[inputs[0]] model1 = layers[inputs[1]] if names == 'short': tf_name = 'S' + random_string(7) elif names == 'keep': tf_name = w_n...
294,126
Convert Linear. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras laye...
def convert_gemm(params, w_name, scope_name, inputs, layers, weights, names): print('Converting Linear ...') if names == 'short': tf_name = 'FC' + random_string(6) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) bias_name = '{0}.bia...
294,127
Convert matmul layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for kera...
def convert_matmul(params, w_name, scope_name, inputs, layers, weights, names): print('Converting matmul ...') if names == 'short': tf_name = 'MMUL' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) if len(inputs) =...
294,128
Convert constant layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ke...
def convert_constant(params, w_name, scope_name, inputs, layers, weights, names): print('Converting constant ...') params_list = params['value'].numpy() def target_layer(x, value=params_list): return tf.constant(value.tolist(), shape=value.shape) lambda_layer = keras.layers.Lambda(target...
294,129
Convert reshape(view). Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ker...
def convert_flatten(params, w_name, scope_name, inputs, layers, weights, names): print('Converting flatten ...') if names == 'short': tf_name = 'R' + random_string(7) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) reshape = keras.l...
294,130
Convert transpose layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ke...
def convert_transpose(params, w_name, scope_name, inputs, layers, weights, names): print('Converting transpose ...') if params['perm'][0] != 0: if inputs[0] in layers: print('!!! Cannot permute batch dimension. Result may be wrong !!!') layers[scope_name] = layers[inputs[0]]...
294,131
Convert reshape layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for kera...
def convert_reshape(params, w_name, scope_name, inputs, layers, weights, names): print('Converting reshape ...') if names == 'short': tf_name = 'RESH' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) if len(inputs) ...
294,132
Convert squeeze operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for...
def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names): print('Converting squeeze ...') if len(params['axes']) > 1: raise AssertionError('Cannot convert squeeze by multiple dimensions') def target_layer(x, axis=int(params['axes'][0])): import tensorflow as tf ...
294,133
Convert unsqueeze operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names f...
def convert_unsqueeze(params, w_name, scope_name, inputs, layers, weights, names): print('Converting unsqueeze ...') if names == 'short': tf_name = 'UNSQ' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) def target...
294,134
Convert shape operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for k...
def convert_shape(params, w_name, scope_name, inputs, layers, weights, names): print('Converting shape ...') def target_layer(x): import tensorflow as tf return tf.shape(x) lambda_layer = keras.layers.Lambda(target_layer) layers[scope_name] = lambda_layer(layers[inputs[0]])
294,135
Convert Average pooling. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for k...
def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names): print('Converting pooling ...') if names == 'short': tf_name = 'P' + random_string(7) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) if 'kernel_shape'...
294,136
Convert 3d Max pooling. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ke...
def convert_maxpool3(params, w_name, scope_name, inputs, layers, weights, names): print('Converting pooling ...') if names == 'short': tf_name = 'P' + random_string(7) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) if 'kernel_shap...
294,137
Convert convert_adaptive_max_pool2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use...
def convert_adaptive_max_pool2d(params, w_name, scope_name, inputs, layers, weights, names): print('Converting adaptive_avg_pool2d...') if names == 'short': tf_name = 'APOL' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random...
294,138
Convert padding layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ker...
def convert_padding(params, w_name, scope_name, inputs, layers, weights, names): print('Converting padding...') if params['mode'] == 'constant': # raise AssertionError('Cannot convert non-constant padding') if params['value'] != 0.0: raise AssertionError('Cannot convert non-ze...
294,139
Convert batch normalization layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short n...
def convert_batchnorm(params, w_name, scope_name, inputs, layers, weights, names): print('Converting batchnorm ...') if names == 'short': tf_name = 'BN' + random_string(6) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) bias_name = ...
294,140
Convert instance normalization layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use shor...
def convert_instancenorm(params, w_name, scope_name, inputs, layers, weights, names): print('Converting instancenorm ...') if names == 'short': tf_name = 'IN' + random_string(6) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) assert...
294,141
Convert dropout. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras lay...
def convert_dropout(params, w_name, scope_name, inputs, layers, weights, names): print('Converting dropout ...') if names == 'short': tf_name = 'DO' + random_string(6) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) dropout = keras....
294,142
Convert relu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras ...
def convert_relu(params, w_name, scope_name, inputs, layers, weights, names): print('Converting relu ...') if names == 'short': tf_name = 'RELU' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) relu = keras.layers....
294,143
Convert leaky relu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for k...
def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names): print('Converting lrelu ...') if names == 'short': tf_name = 'lRELU' + random_string(3) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) leakyrelu = \ ...
294,144
Convert sigmoid layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ker...
def convert_sigmoid(params, w_name, scope_name, inputs, layers, weights, names): print('Converting sigmoid ...') if names == 'short': tf_name = 'SIGM' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) sigmoid = kera...
294,145
Convert softmax layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ker...
def convert_softmax(params, w_name, scope_name, inputs, layers, weights, names): print('Converting softmax ...') if names == 'short': tf_name = 'SMAX' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) def target_lay...
294,146
Convert tanh layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras ...
def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names): print('Converting tanh ...') if names == 'short': tf_name = 'TANH' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) tanh = keras.layers....
294,147
Convert hardtanh layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for ke...
def convert_hardtanh(params, w_name, scope_name, inputs, layers, weights, names): print('Converting hardtanh (clip) ...') def target_layer(x, max_val=float(params['max_val']), min_val=float(params['min_val'])): return tf.minimum(max_val, tf.maximum(min_val, x)) lambda_layer = keras.layers.Lam...
294,148
Convert selu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras ...
def convert_selu(params, w_name, scope_name, inputs, layers, weights, names): print('Converting selu ...') if names == 'short': tf_name = 'SELU' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) selu = keras.layers....
294,149
Convert upsample_bilinear2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short n...
def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names): print('Converting upsample...') if names == 'short': tf_name = 'UPSL' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) outp...
294,150
Convert nearest upsampling layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short na...
def convert_upsample(params, w_name, scope_name, inputs, layers, weights, names): print('Converting upsample...') if params['mode'] != 'nearest': raise AssertionError('Cannot convert non-nearest upsampling') if names == 'short': tf_name = 'UPSL' + random_string(4) elif names == 'k...
294,151
Convert gather (embedding) layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short na...
def convert_gather(params, w_name, scope_name, inputs, layers, weights, names): print('Converting embedding ...') if names == 'short': tf_name = 'EMBD' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) weights_name ...
294,152
By given pytorch model convert layers with specified convertors. Args: model: pytorch model args: pytorch model arguments input_shapes: keras input shapes (using for each InputLayer) change_ordering: change CHW to HWC training: switch model to training mode verbose: ...
def pytorch_to_keras( model, args, input_shapes, change_ordering=False, training=False, verbose=False, names=False, ): # PyTorch JIT tracing if isinstance(args, torch.autograd.Variable): args = (args, ) # Workaround for previous versions if isinstance(input_shapes, tuple): ...
294,155
Compile by saving to file and importing that. Compiling the AST/source code this way ensures that the source code is readable by e.g. `pdb` or `inspect`. Args: source: The code to compile, either as a string or as an AST. globals_: A dictionary of variables that should be available as globals in ...
def compile_file(source, globals_=None): if isinstance(source, gast.AST): source = quoting.to_source(source) # Write source to temporary file tempdir = tempfile.mkdtemp() uuid = str(uuid4().hex[:4]) tmpname = os.path.join(tempdir, 'tangent_%s.py' % uuid) with open(tmpname, 'w') as f: f.write(sou...
297,393
Perform AD on a single function and return the AST. Args: See `grad`. Returns: node: The AST of a module containing the adjoint and primal function definitions. required: A list of non-built in functions that this function called, and of which the primals and adjoints need to be made a...
def autodiff_ast(func, wrt, motion, mode, preserve_result, check_dims, verbose): node = annotate.resolve_calls(func) node = desugar.explicit_loop_indexes(node) fence.validate(node, inspect.getsource(func)) node = anf_.anf(node) if verbose >= 2: print('ANF') print(quoting.to_source(node)) if mode ...
297,396
Create a user-friendly forward function. Ensures that a single value instead of a tuple is returned if the user asked for the gradient with respect to only one input. Args: out_node: The function definition AST. Returns: The function definition with potentially changed return statement.
def _create_forward(out_node): retval = out_node.body[0].body[-1] if len(retval.value.elts) == 1: retval.value = retval.value.elts[0] return out_node
297,402
A decorator which removes the `with insert_grad_of` statement. This allows the function to be called as usual. Args: f: A function Returns: A function with any `with insert_grad_of` context managers removed.
def tangent(f): node = annotate.resolve_calls(f) RemoveWith().visit(node) wrapped = functools.wraps(f)(compile_.compile_function(node)) wrapped.tangent = f return wrapped
297,403
Build a CFG for a function. Args: node: A function definition the body of which to analyze. Returns: A CFG object. Raises: TypeError: If the input is not a function definition.
def build_cfg(cls, node): if not isinstance(node, gast.FunctionDef): raise TypeError('input must be a function definition') cfg = cls() cfg.entry = Node(node.args) cfg.head = [cfg.entry] cfg.visit_statements(node.body) cfg.exit = Node(None) cfg.set_head(cfg.exit) cfg.backlink(...
297,407
Perform a series of optimization passes. This function performs a series of optimizations (dead code elimination, constant folding, variable folding) on the given AST. It optimizes the code repeatedly until reaching a fixed point. The fixed point is determine roughly by checking whether the number of lines of ...
def optimize(node): node = dead_code_elimination(node) node = constant_folding(node) node = assignment_propagation(node) return node
297,421
Check how many times a variable definition was used. Args: node: An AST to analyze. Returns: A dictionary from assignment nodes to the number of times the assigned to variable was used.
def read_counts(node): cfg.forward(node, cfg.ReachingDefinitions()) rc = ReadCounts() rc.visit(node) return rc.n_read
297,423
Perform assignment propagation. Assignment propagation is not a compiler optimization as much as a readability optimization. If a variable name is used only once, it gets renamed when possible e.g. `y = x; z = y` will become `z = x`. Args: node: The AST to optimize. Returns: The optimized AST.
def assignment_propagation(node): n_reads = read_counts(node) to_remove = [] for succ in gast.walk(node): # We found an assignment of the form a = b # - Left-hand side is a Name, right-hand side is a Name. if (isinstance(succ, gast.Assign) and isinstance(succ.value, gast.Name) and len(succ...
297,424
Reverse the broadcasting operation. See utils.py. Args: tensor: A Tensor. shape: A shape that could have been broadcasted to the shape of tensor. Returns: Tensor with dimensions summed to match `shape`.
def unbroadcast_tfe_to(tensor, shape): axis = utils.create_unbroadcast_axis(shape, shape_as_list(tensor)) return tf.reshape(tf.reduce_sum(tensor, axis=axis), shape)
297,430
Reverse summing over a dimension. See utils.py. Args: tensor: The tensor that was reduced. shape: A list, the original shape of the tensor before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: A tensor with axes broadca...
def unreduce_tensor(tensor, shape, axis, keepdims): if not keepdims: if axis is None: axis = range(len(shape)) elif isinstance(axis, int): axis = axis, for ax in sorted(axis): tensor = tf.expand_dims(tensor, ax) tile_shape = np.array(shape) / np.array(shape_as_list(tensor)) return...
297,431
Ensure a variable name is valid. Note: Assumes variable names are ASCII, which isn't necessarily true in Python 3. Args: name: A proposed variable name. Returns: A valid version of the name.
def valid(self, name): name = re.sub('[^0-9a-zA-Z_]', '', name) if re.match('[0-9]', name): name = '_' + name return name
297,476
Reverse the broadcasting operation. Args: array: An array. like: An array that could have been broadcasted to the shape of array. Returns: Tensor with certain dimensions summed to match the shape of `like`.
def unbroadcast(array, like): unbroadcaster = unbroadcasters[type(array)] return unbroadcaster(array, like)
297,496
Creates the reduction axis for unbroadcasting. Args: shape: A list. The shape after the broadcast operation. broadcast_shape: A list. The original shape the array being unbroadcast had. Returns: A list. The axes along which the array needs to be reduced. These axes will be distributed evenly ...
def create_unbroadcast_axis(shape, broadcast_shape): return tuple( -(1 + i) for i in range(len(broadcast_shape)) if i >= len(shape) or broadcast_shape[-(1 + i)] > shape[-(1 + i)])
297,497
Reverse the broadcasting operation. Args: array: An array. shape: A shape that could have been broadcasted to the shape of array. Returns: Array with dimensions summed to match `shape`.
def unbroadcast_numpy_to(array, shape): axis = create_unbroadcast_axis(shape, numpy.shape(array)) return numpy.reshape(numpy.sum(array, axis=axis), shape)
297,498
Reverse summing over a dimension. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An array with axes broadcast to match the shape of the...
def unreduce(array, shape, axis, keepdims): unreducer = unreducers[type(array)] return unreducer(array, shape, axis, keepdims)
297,499
Reverse summing over a dimension. Args: array: The array that was reduced. original_array: An array whose shape to unreduce to. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An array with axes broadcast to match the shape of the ori...
def unreduce_like(array, original_array, axis, keepdims): atype = type(array) unreducer = unreducers[atype] shape = shape_functions[atype] return unreducer(array, shape(original_array), axis, keepdims)
297,500
Reverse summing over a dimension, NumPy implementation. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An array with axes broadcast to ...
def unreduce_array(array, shape, axis, keepdims): # NumPy uses a special default value for keepdims, which is equivalent to # False. if axis is not None and (not keepdims or keepdims is numpy._NoValue): # pylint: disable=protected-access if isinstance(axis, int): axis = axis, for ax in sorted(ax...
297,501
A functional form of the `astype` method. Args: array: The array or number to cast. y: An array or number, as the input, whose type should be that of array. Returns: An array or number with the same dtype as `y`.
def astype(array, y): if isinstance(y, autograd.core.Node): return array.astype(numpy.array(y.value).dtype) return array.astype(numpy.array(y).dtype)
297,502
Initialize the gradient for an object. Args: obj: The object to initialize the gradient for, can be either a number, array, tuple, list, or dictionary. allow_lazy_initializer: Whether to allow using the ZeroGradient wrapper, for efficiency. Returns: An object of the same type, shape, etc. ...
def init_grad(obj, allow_lazy_initializer=False): if obj is None: # TODO: fixes.py appears to pass None value and expect 0.0 back. Bug? return 0.0 initializer, supports_lazy_initializer = grad_initializers[type(obj)] if supports_lazy_initializer: if isinstance(obj, ZeroGradient): if allow_la...
297,503
Recursively add the gradient of two objects. Args: left: The left value to add. Can be either an array, a number, list or dictionary. right: The right value. Must be of the same type (recursively) as the left. Returns: The sum of the two gradients, which will of the same type.
def add_grad(left, right): # We assume that initial gradients are always identity WRT add_grad. # We also assume that only init_grad could have created None values. assert left is not None and right is not None left_type = type(left) right_type = type(right) if left_type is ZeroGradient: return right...
297,510
Recursively check if shapes of object `a` and `b` match. Will walk lists, tuples and dicts. Args: a: object of type (numpy.ndarray,tf.Tensor,list,tuple,dict) to check for matching shapes against `b`. b: object to check for matching shape against `a`. Returns: A boolean indicating whether th...
def shapes_match(a, b): if isinstance(a, (tuple, list)) and isinstance(b, (tuple, list)): if len(a) != len(b): return False return all([shapes_match(ia, ib) for ia, ib in zip(a, b)]) elif isinstance(a, dict) and isinstance(b, dict): if len(a) != len(b): return False match = True f...
297,513
Push a value onto the stack (i.e. record it on the tape). Args: stack: The stack object, which must support appending values. x: The value to append. If it is a mutable object like an array or list, it will be copied before being added onto the stack. op_id: A unique variable that is also passed ...
def push(stack, x, op_id): if isinstance(x, numpy.ndarray): x = x.copy() elif isinstance(x, list): x = x[:] if __debug__: stack.append((x, op_id)) else: stack.append(x)
297,514
Pop a value from the stack (i.e. read it from the tape). Args: stack: The stack to pop from. op_id: A unique variable that is also passed into the matching push. Allows optimization passes to track pairs of pushes and pops. Returns: The last value.
def pop(stack, op_id): if __debug__: pushed_value, pushed_op_id = stack.pop() assert pushed_op_id == op_id, 'Wanted %s, got %s' % (op_id, pushed_op_id) else: pushed_value = stack.pop() return pushed_value
297,515
Proxy of pop, where we know we're popping a stack off of a stack. We know that we don't need to differentiate through this. See pop() for more. Args: stack: The stack to pop from. op_id: A unique variable that is also passed into the matching push. Allows optimization passes to track pairs of pu...
def pop_stack(stack, op_id): if __debug__: pushed_stack, pushed_op_id = stack.pop() assert pushed_op_id == op_id, 'Wanted %s, got %s' % (op_id, pushed_op_id) else: pushed_stack = stack.pop() return pushed_stack
297,516
Proxy of push, where we know we're pushing a stack onto a stack. Used when differentiating call trees,where sub-functions get their own stack. See push() for more. Args: stack: The stack object, which must support appending values. substack: The stack to append. op_id: A unique variable that is also...
def push_stack(stack, substack, op_id): if substack is not None and not isinstance(substack, Stack): raise ValueError( 'Substack should be type tangent.Stack or None, instead found %s' % type(substack)) if __debug__: stack.append((substack, op_id)) else: stack.append(substack)
297,517
Gradient of NumPy dot product w.r.t. to the left hand side. Args: dy: The gradient with respect to the output. x1: The left hand side of the `numpy.dot` function. x2: The right hand side Returns: The gradient with respect to `x1` i.e. `x2.dot(dy.T)` with all the broadcasting involved.
def grad_dot(dy, x1, x2): if len(numpy.shape(x1)) == 1: dy = numpy.atleast_2d(dy) elif len(numpy.shape(x2)) == 1: dy = numpy.transpose(numpy.atleast_2d(dy)) x2 = numpy.transpose(numpy.atleast_2d(x2)) x2_t = numpy.transpose(numpy.atleast_2d( numpy.sum(x2, axis=tuple(numpy.arange(numpy.ndim(x2)...
297,518
Creates a LanguageFence. Args: source: String, the source code of the AST that will be verified. strict: Boolean, set to False to allow unsafe constructs. Raises: ValueError: if source code has not been supplied.
def __init__(self, source, strict=True): self._visited_top_module = False if not source: raise ValueError('The source code of the tree is required.') self._source = source self._strict = strict # Location information is used to locate the offending elements # in the source code. ...
297,566
Get the name of a variable. Args: node: A `Name`, `Subscript` or `Attribute` node. Returns: The name of the variable e.g. `'x'` for `x`, `x.i` and `x[i]`.
def get_name(node): if isinstance(node, gast.Name): return node.id elif isinstance(node, (gast.Subscript, gast.Attribute)): return get_name(node.value) else: raise TypeError
297,600
Return the variable names created or mutated by this statement. This function considers assign statements, augmented assign statements, and the targets of for loops, as well as function arguments. For example, `x[0] = 2` will return `x`, `x, y = 3, 4` will return `x` and `y`, `for i in range(x)` will return `...
def get_updated(node): if isinstance(node, gast.Assign): return set.union(*(_get_target(target) for target in node.targets)) elif isinstance(node, (gast.For, gast.AugAssign)): return _get_target(node.target) elif isinstance(node, gast.arguments): targets = set(arg.id for arg ...
297,602
Check whether a context manager calls `insert_grad_of`. Args: node: The context manager node. Returns: Whether or not this node contains `insert_grad_of` calls. Raises: ValueError: If the `insert_grad_of` calls are mixed with other calls.
def is_insert_grad_of_statement(node): tangent_calls = [anno.getanno(item.context_expr, 'func', None) is utils.insert_grad_of for item in node.items] if all(tangent_calls): return True elif any(tangent_calls): raise ValueError else: return False
297,605
Remove comments that repeat themselves. Multiple statements might be annotated with the same comment. This way if one of the statements is deleted during optimization passes, the comment won't be lost. This pass removes sequences of identical comments, leaving only the first one. Args: node: An AST R...
def remove_repeated_comments(node): last_comment = {'text': None} for _node in gast.walk(node): if anno.hasanno(_node, 'comment'): comment = anno.getanno(_node, 'comment') if comment['text'] == last_comment['text']: anno.delanno(_node, 'comment') last_comment = comment return node
297,608
Create a variable to store partial gradients. Args: node: See `create_grad`. namer: See `create_grad`. tangent: See `create_grad`. Returns: node: See `create_grad`. Returns a node representing the partial gradient. Note that this is always a simple variable e.g. the temporary partial ...
def create_temp_grad(node, namer, tangent=False): if not isinstance(node, (gast.Subscript, gast.Name)): raise TypeError def _name_temp_grad(node): name = namer.temp_grad(node.id, tangent) temp_node = gast.Name(id=name, annotation=None, ctx=None) return temp_node if isinstance(node, gast.Subscr...
297,624
Create a temporary variable. Args: node: Create a temporary variable to store this variable in. namer: A naming object that guarantees the names are unique. Returns: node: See `create_grad`. Returns a temporary variable, which is always a simple variable annotated with `temp_var`.
def create_temp(node, namer): if isinstance(node, gast.Name): name = node.id elif isinstance(node, (gast.Attribute, gast.Subscript)): name = node.value.id else: raise TypeError temp_node = gast.Name(id=namer.temp(name), annotation=None, ctx=None) anno.setanno(temp_node, 'temp_var', node) retu...
297,625
Go from source code to AST nodes. This function returns a tree without enclosing `Module` or `Expr` nodes. Args: src_string: The source code to parse. return_expr: Whether or not to return a containing expression. This can be set to `True` if the result is to be part of a series of statements. ...
def quote(src_string, return_expr=False): node = parse_string(src_string) body = node.body if len(body) == 1: if isinstance(body[0], gast.Expr) and not return_expr: out = body[0].value else: out = body[0] else: out = node return out
297,647
Carry over the state from the primal to the adjoint. Args: node: A module with the primal and adjoint function definitions as returned by `reverse_ad`. stack: The stack node to use for storing and restoring state. Returns: func: A `Module` node with two function definitions containing the prim...
def split(node, stack): node, defined, reaching = _fix(node) # Store and restore the state node = store_state(node, reaching, defined, stack) # Clean up anno.clearanno(node) return node
297,655
Merge the bodies of primal and adjoint into a single function. Args: node: A module with the primal and adjoint function definitions as returned by `reverse_ad`. Returns: func: A `Module` node with a single function definition containing the combined primal and adjoint.
def joint(node): node, _, _ = _fix(node) body = node.body[0].body[:-1] + node.body[1].body func = gast.Module(body=[gast.FunctionDef( name=node.body[0].name, args=node.body[1].args, body=body, decorator_list=[], returns=None)]) # Clean up anno.clearanno(func) return func
297,656
Visit a node. This method is largely modelled after the ast.NodeTransformer class. Args: node: The node to visit. Returns: A tuple of the primal and adjoint, each of which is a node or a list of nodes.
def visit(self, node): method = 'visit_' + node.__class__.__name__ if not hasattr(self, method): raise ValueError('Unknown node type: %s' % node.__class__.__name__) visitor = getattr(self, method) # If this node is a statement, inform all child nodes what the active # variables in this s...
297,659
Checks whether a statement is active. An assignment is active when its right hand side contains active variables. Args: node: an instance of gast.Assign Returns: Whether the statement is active.
def is_active(self, node): # Special case: If the right hand side is a pop statement, we want to # process it if (isinstance(node.value, gast.Call) and anno.getanno(node.value, 'func', False) == utils.pop): return True for succ in gast.walk(node.value): if (isinstance(succ, gast...
297,662
Build the primal and adjoint of a traceable function. Args: node: ast.Call node of a function we wish to trace, instead of transform Returns: primal: new ast.Assign node to replace the original primal call adjoint: new ast.Assign node using the VJP generated in primal to calculate th...
def primal_and_adjoint_for_tracing(self, node): primal_template = grads.primals[tracing.Traceable] adjoint_template = grads.adjoints[tracing.Traceable] # Prep to_pack = node.args target = ast_.copy_node(self.orig_target) vjp = quoting.quote(self.namer.unique('%s_grad' % node.func.id)) ...
297,675
Prepend a statement to the current statement. Note that multiple calls to prepend will result in the last statement to be prepended to end up at the top. Args: node: The statement to prepend. Raises: ValueError: If the given node is not a statement.
def prepend(self, node): if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_prepend[-1].appendleft(node)
297,679
Append a statement to the current statement. Note that multiple calls to append will result in the last statement to be appended to end up at the bottom. Args: node: The statement to append. Raises: ValueError: If the given node is not a statement.
def append(self, node): if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_append[-1].append(node)
297,680
Insert statements at the top of the function body. Note that multiple calls to `insert_top` will result in the statements being prepended in that order; this is different behavior from `prepend`. Args: node: The statement to prepend. Raises: ValueError: If the given node is not a statemen...
def insert_top(self, node): if not isinstance(node, grammar.STATEMENTS): raise ValueError self.to_insert_top.append(node)
297,681
Prepend a statement to the current block. Args: node: The statement to prepend. reverse: When called multiple times, this flag determines whether the statement should be prepended or appended to the already inserted statements. Raises: ValueError: If the given node is not...
def prepend_block(self, node, reverse=False): if not isinstance(node, grammar.STATEMENTS): raise ValueError if reverse: self.to_prepend_block[-1].appendleft(node) else: self.to_prepend_block[-1].append(node)
297,682
Append a statement to the current block. Args: node: The statement to prepend. reverse: When called multiple times, this flag determines whether the statement should be prepended or appended to the already inserted statements. Raises: ValueError: If the given node is not ...
def append_block(self, node, reverse=False): if not isinstance(node, grammar.STATEMENTS): raise ValueError if reverse: self.to_append_block[-1].appendleft(node) else: self.to_append_block[-1].append(node)
297,683
Visit a series of nodes in a node body. This function is factored out so that it can be called recursively on statements that are appended or prepended. This allows e.g. a nested expression to prepend a statement, and that statement can prepend a statement again, etc. Args: nodes: A list of ...
def visit_statements(self, nodes): for node in nodes: if isinstance(node, gast.AST): self.to_prepend.append(deque()) self.to_append.append(deque()) node = self.visit(node) self.visit_statements(self.to_prepend.pop()) if isinstance(node, gast.AST): self.to...
297,684
Find pushes and pops to the stack and annotate them as such. Args: node: An AST node that might contain stack pushes and pops. strict: A boolean indicating whether to stringently test whether each push and pop are matched. This is not always possible when taking higher-order derivatives of co...
def find_stacks(node, strict=False): # First, find all stack operation IDs. fso = FindStackOps() fso.visit(node) # Using those IDs, make annotations onto the push and pop nodes. AnnotateStacks(fso.push_pop_pairs, strict).visit(node) return node
297,697
Find unused definitions that can be remove. This runs reaching definitions analysis followed by a walk over the AST to find all variable definitions that are not used later on. Args: node: The AST of e.g. a function body to find unused variable definitions. Returns: unused: After visiting all the nod...
def unused(node): cfg.forward(node, cfg.ReachingDefinitions()) unused_obj = Unused() unused_obj.visit(node) return unused_obj.unused
297,698
Initializes logging. Prints logs to console with level defined by loglevel Also prints verbose log to the multiqc data directory if available. (multiqc_data/multiqc.log) Args: loglevel (str): Determines the level of the log output.
def init_log(logger, loglevel=0): # File for logging global log_tmp_dir, log_tmp_fn log_tmp_dir = tempfile.mkdtemp() log_tmp_fn = os.path.join(log_tmp_dir, 'multiqc.log') # Logging templates debug_template = '[%(asctime)s] %(name)-50s [%(levelname)-7s] %(message)s' info_template = '[%...
298,367
Make an HTTP connection using connection_class. This is an internal method that should be called from open_http() or open_https(). Arguments: - connection_factory should take a host name and return an HTTPConnection instance. - url is the url to retrieval or a host, r...
def _open_generic_http(self, connection_factory, url, data): user_passwd = None proxy_passwd= None if isinstance(url, str): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) ...
298,987
Constructor. Arguments: year, month, day (required, base 1)
def __new__(cls, year, month=None, day=None): if (isinstance(year, bytes) and len(year) == 4 and 1 <= year[2] <= 12 and month is None): # Month is sane # Pickle support self = object.__new__(cls) self.__setstate(year) return self _che...
299,252
Constructor. Arguments: hour, minute (required) second, microsecond (default to zero) tzinfo (default to None)
def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): self = object.__new__(cls) if isinstance(hour, bytes) and len(hour) == 6: # Pickle support self.__setstate(hour, minute or None) return self _check_tzinfo_arg(tzinfo) _c...
299,267
Create a new profile looter. Arguments: username (str): the username of the profile. See `InstaLooter.__init__` for more details about accepted keyword arguments.
def __init__(self, username, **kwargs): # type: (str, **Any) -> None super(ProfileLooter, self).__init__(**kwargs) self._username = username self._owner_id = None
299,773
Create a new hashtag looter. Arguments: username (str): the hashtag to search for. See `InstaLooter.__init__` for more details about accepted keyword arguments.
def __init__(self, hashtag, **kwargs): # type: (str, **Any) -> None super(HashtagLooter, self).__init__(**kwargs) self._hashtag = hashtag
299,775
Create a new hashtag looter. Arguments: code (str): the code of the post to get. See `InstaLooter.__init__` for more details about accepted keyword arguments.
def __init__(self, code, **kwargs): # type: (str, **Any) -> None super(PostLooter, self).__init__(**kwargs) self._info = None # type: Optional[dict] match = self._RX_URL.match(code) if match is not None: self.code = match.group(1) elif self._RX_CO...
299,776