Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def hms_string(secs): l = hms(secs) def extend10(n): if n < 10: return '0' + str(n) else: return str(n) return extend10(l[0]) + ':' + extend10(l[1]) + ':' + extend10(l[2])
[ "return hours,minutes and seconds string, e.g. 02:00:45" ]
Please provide a description of the function:def get_enclosing_orthorhombic_box(cell): # Cell vectors cx, cy, cz = cell # The cell has eight corners, one is at the origin, three at cx, cy, cz # and the last ones are... c1 = cx+cy c2 = cx+cz c3 = cy+cz c4 = cx+cy+cz ...
[ "\n Return lower and upper bounds of the orthorhombic box that encloses\n the parallelepiped spanned by the three cell vectors of cell.\n " ]
Please provide a description of the function:def voropp_for_non_orthorhombic_cells(_a, q='%v', voropp_path=VOROPP_PATH, fast=False, dump=None): # Make a copy because we will modify the Atoms object a = _a.copy() nat = len(a) # Wrap into cell a.set_scal...
[ "\n Run voro++ on current configuration and return selected quantities.\n Parameter *q* can be a list of voro++ output quantities.\n Run 'voro++ -hc' to see options. Will take care of Lees-Edwards boundary\n conditions by embedding a sheared cell in its periodic images and then\n throwing away the bo...
Please provide a description of the function:def voropp(a, q='%v', voropp_path=VOROPP_PATH, fast=False, dump=None): cx, cy, cz = a.get_cell() lx, ly, lz = np.linalg.norm(cx), np.linalg.norm(cy), np.linalg.norm(cz) if abs(lx*ly*lz - a.get_volume()) > 1e-6 or 'shear_dx' in a.info: return voropp_f...
[ "\n Run voro++ on current configuration and return selected quantities.\n Parameter *q* can be a list of voro++ output quantities.\n Run 'voro++ -hc' to see options.\n " ]
Please provide a description of the function:def stress_invariants(s): s = np.asarray(s) if s.shape == (6,): s = s.reshape(1,-1) elif s.shape == (3,3): s = s.reshape(1,-1,-1) if len(s.shape) == 3: s = np.transpose([s[:,0,0],s[:,1,1],s[:,2,2], (s[:,0...
[ "Receives a list of stress tensors and returns the three invariants.\n Return hydrostatic pressure, octahedral shear stress and J3\n " ]
Please provide a description of the function:def convpar(p): if 'el' not in p: return p els = p['el'] nel = len(els) q = { } for name, values in p.items(): if isinstance(values, dict): # This is a dictionary. We need to first understand what it is and ...
[ "\n Convert a parameter set from convenient Python dictionary to the format\n expected by the Fortran kernels.\n " ]
Please provide a description of the function:def scanmeta(f): print(f) if isinstance(f, str): f = io.open(f, mode='r', encoding='latin-1') done = False l = f.readline() s = None while l and s is None: i = l.find('!') if i >= 0: l = l[i+1:] i...
[ "Scan file headers for @meta ... @endmeta information and store that into\n a dictionary.\n " ]
Please provide a description of the function:def mic(dr, cell, pbc=None): # Check where distance larger than 1/2 cell. Particles have crossed # periodic boundaries then and need to be unwrapped. rec = np.linalg.inv(cell) if pbc is not None: rec *= np.array(pbc, dtype=int).reshape(3,1) d...
[ "\n Apply minimum image convention to an array of distance vectors.\n " ]
Please provide a description of the function:def s_from_dhms(time): dhms_s = { 's' : 1, 'm' : 60, 'h' : 3600, 'd' : 86400 } time = time.lower() word_list = re.findall('\d*[^\d]*',time) seconds=0 for word in word_list: if word != '': sec = 1 for t in list(dhms_s....
[ "return seconds from dhms" ]
Please provide a description of the function:def read_atoms(fn, cycfn=None, pos_only=False, conv=1.0): f = paropen(fn, "r") l = f.readline().lstrip() while len(l) > 0 and ( l[0] == '#' or l[0] == '<' ): l = f.readline().lstrip() n_atoms = int(l) l = f.readline().lstrip() while le...
[ "\n Read atom information from an atoms.dat file (i.e., tblmd, MDCORE input file)\n " ]
Please provide a description of the function:def read_cyc(this, fn, conv=1.0): f = paropen(fn, "r") f.readline() f.readline() f.readline() f.readline() cell = np.array( [ [ 0.0, 0.0, 0.0 ], [ 0.0, 0.0, 0.0 ], [ 0.0, 0.0, 0.0 ] ] ) l = f.readline() s = map(float, l.split()) cell[...
[ " Read the lattice information from a cyc.dat file (i.e., tblmd input file)\n " ]
Please provide a description of the function:def write_atoms(fn, this, cycfn=None, conv=1.0, symbols=True): f = paropen(fn, "w") f.write("<--- Number of atoms\n") f.write("%i\n" % len(this)) f.write("<--- Number of occupied orbitals\n") f.write("%f\n" % 0.0) f.write("<--- Atom positions\n"...
[ "\n Write atom information to an atoms.dat file (i.e., tblmd, MDCORE input file)\n " ]
Please provide a description of the function:def write_cyc(fn, this, conv=1.0): lattice = this.get_cell() f = paropen(fn, "w") f.write("<------- Simulation box definition\n") f.write("<------- Barostat (on = 1, off = 0)\n") f.write(" 0\n") f.write("<------- Box vectors (start)\n") f....
[ " Write the lattice information to a cyc.dat file (i.e., tblmd input file)\n " ]
Please provide a description of the function:def get_forces(self, a): f = np.zeros( [ len(a), 3 ], dtype=float ) for c in self.calcs: f += c.get_forces(a) return f
[ "Calculate atomic forces." ]
Please provide a description of the function:def get_potential_energy(self, a): e = 0.0 for c in self.calcs: e += c.get_potential_energy(a) return e
[ "Calculate potential energy." ]
Please provide a description of the function:def get_stress(self, a): s = np.zeros( 6, dtype=float ) for c in self.calcs: s += c.get_stress(a) return s
[ "Calculate stress tensor." ]
Please provide a description of the function:def set_atoms(self, a): for c in self.calcs: if hasattr(c, "set_atoms"): c.set_atoms(a)
[ "Assign an atoms object." ]
Please provide a description of the function:def get_forces(self, a=None): if a is None: a = self.a forces = np.zeros([len(a), 3], dtype=float) if self.mask is None: forces[self.mask] = self.force else: forces[:] = self.force return fo...
[ "Calculate atomic forces." ]
Please provide a description of the function:def get_potential_energy(self, a=None): if a is None: a = self.a if self.mask is None: return -np.sum(np.dot(a.get_positions()[self.mask], self.force)) else: return -np.sum(np.dot(a.get_positions(), self.fo...
[ "Calculate potential energy." ]
Please provide a description of the function:def delete_node(self, node_name, graph=None): if not graph: graph = self.graph if node_name not in graph: raise KeyError('node %s does not exist' % node_name) graph.pop(node_name) for node, edges in six.iterit...
[ " Deletes this node and all edges referencing it. " ]
Please provide a description of the function:def rename_edges(self, old_task_name, new_task_name, graph=None): if not graph: graph = self.graph for node, edges in graph.items(): if node == old_task_name: graph[new_task_name] = copy(edges) ...
[ " Change references to a task in existing edges. " ]
Please provide a description of the function:def predecessors(self, node, graph=None): if graph is None: graph = self.graph return [key for key in graph if node in graph[key]]
[ " Returns a list of all predecessors of the given node " ]
Please provide a description of the function:def all_downstreams(self, node, graph=None): if graph is None: graph = self.graph nodes = [node] nodes_seen = set() i = 0 while i < len(nodes): downstreams = self.downstream(nodes[i], graph) ...
[ "Returns a list of all nodes ultimately downstream\n of the given node in the dependency graph, in\n topological order." ]
Please provide a description of the function:def all_leaves(self, graph=None): if graph is None: graph = self.graph return [key for key in graph if not graph[key]]
[ " Return a list of all leaves (nodes with no downstreams) " ]
Please provide a description of the function:def from_dict(self, graph_dict): self.reset_graph() for new_node in six.iterkeys(graph_dict): self.add_node(new_node) for ind_node, dep_nodes in six.iteritems(graph_dict): if not isinstance(dep_nodes, list): ...
[ " Reset the graph and build it from the passed dictionary.\n\n The dictionary takes the form of {node_name: [directed edges]}\n " ]
Please provide a description of the function:def ind_nodes(self, graph=None): if graph is None: graph = self.graph dependent_nodes = set( node for dependents in six.itervalues(graph) for node in dependents ) return [node for node in graph.keys() if node ...
[ " Returns a list of all nodes in the graph with no dependencies. " ]
Please provide a description of the function:def validate(self, graph=None): graph = graph if graph is not None else self.graph if len(self.ind_nodes(graph)) == 0: return (False, 'no independent nodes detected') try: self.topological_sort(graph) except Va...
[ " Returns (Boolean, message) of whether DAG is valid. " ]
Please provide a description of the function:def constant(name, shape, value=0, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r shape = shape if isinstance(shape, (tuple, list)) else [shape] x = tf.get_variable(name, shape, dtype=dtype, initializer=tf.constant_...
[ "Creates a tensor variable of which initial values are `value` and shape is `shape`.\n\n Args:\n name: The name of new variable.\n shape: A tuple/list of integers or an integer. \n If shape is an integer, it is converted to a list.\n value: A Python scalar. All elements of the initialized v...
Please provide a description of the function:def uniform(name, shape, scale=0.05, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r shape = shape if isinstance(shape, (tuple, list)) else [shape] x = tf.get_variable(name, shape, dtype=dtype, initializer=tf.random_...
[ "Creates a tensor variable of which initial values are \n random numbers based on uniform distribution.\n \n Note that the default value of `scale` (=0.05) is different from \n the min/max values (=0.0, 1.0) of tf.random_uniform_initializer.\n \n Args:\n name: The name of the new variable.\n ...
Please provide a description of the function:def he_uniform(name, shape, scale=1, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r fin, _ = _get_fans(shape) s = np.sqrt(1. * scale / fin) return uniform(name, shape, s, dtype, summary, regularizer, trainable)
[ "See [He et al. 2015](http://arxiv.org/pdf/1502.01852v1.pdf)\n\n Args:\n name: The name of new variable\n shape: A tuple/list of integers.\n scale: A Python scalar. Scale to initialize. Default is 1.\n dtype: The data type. Default is float32.\n summary: If True, add this constant to ten...
Please provide a description of the function:def identity(name, dim, scale=1, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r x = tf.get_variable(name, initializer=tf.constant(np.eye(dim) * scale, dtype=dtype), regularizer=regularizer, train...
[ "Creates a tensor variable of which initial values are of\n an identity matrix.\n \n Note that the default value of `scale` (=0.05) is different from \n the min/max values (=0.0, 1.0) of tf.random_uniform_initializer.\n \n For example,\n \n ```\n identity(\"identity\", 3, 2) =>\n [[2. ...
Please provide a description of the function:def orthogonal(name, shape, scale=1.1, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # pick the...
[ "Creates a tensor variable of which initial values are of\n an orthogonal ndarray.\n \n See [Saxe et al. 2014.](http://arxiv.org/pdf/1312.6120.pdf)\n \n Args:\n name: The name of new variable.\n shape: A tuple/list of integers. \n scale: A Python scalar.\n dtype: Either float32 or...
Please provide a description of the function:def external(name, value, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r # create variable x = tf.get_variable(name, initializer=tf.constant(value, dtype=dtype), regularizer=regularizer, trai...
[ "Creates a tensor variable of which initial values are `value`.\n \n For example,\n \n ```\n external(\"external\", [3,3,1,2])\n => [3. 3. 1. 2.]\n ```\n \n Args:\n name: The name of new variable.\n value: A constant value (or list) of output type `dtype`.\n dtype: The type...
Please provide a description of the function:def _get_fans(shape): r if len(shape) == 2: fan_in = shape[0] fan_out = shape[1] elif len(shape) == 4 or len(shape) == 5: # assuming convolution kernels (2D or 3D). kernel_size = np.prod(shape[:2]) fan_in = shape[-2] * kern...
[ "Returns the size of input dimension and output dimension, given `shape`.\n \n Args:\n shape: A list of integers.\n \n Returns:\n fan_in: An int. The value of input dimension.\n fan_out: An int. The value of output dimension.\n " ]
Please provide a description of the function:def sg_producer_func(func): r @wraps(func) def wrapper(**kwargs): r # default option opt = tf.sg_opt(kwargs) + tf.sg_opt(dtypes=[tf.sg_floatx], capacity=32, num_threads=1) # source queue list check assert opt.source is no...
[ "Decorates a function `func` as sg_producer_func.\n\n Args:\n func: A function to decorate.\n ", "Manages arguments of `tf.sg_opt`.\n\n Args:\n **kwargs:\n source: A source queue list to enqueue\n dtypes: Input data types of each tensor\n out_dtypes: Out...
Please provide a description of the function:def sg_dense(tensor, opt): r # parameter initialize w = tf.sg_initializer.he_uniform('W', (opt.in_dim, opt.dim), regularizer=opt.regularizer, summary=opt.summary) b = tf.sg_initializer.constant('b', opt.dim, summary=opt.su...
[ "Applies a full connection.\n \n Args:\n tensor: A 2-D tensor (automatically passed by decorator).\n opt:\n in_dim: An `integer`. The size of input dimension.\n dim: An `integer`. The size of output dimension.\n bias: Boolean. If True, biases are added.\n regularizer: A ...
Please provide a description of the function:def sg_conv1d(tensor, opt): r # default options opt += tf.sg_opt(size=2, stride=1, pad='SAME') # parameter tf.sg_initializer w = tf.sg_initializer.he_uniform('W', (opt.size, opt.in_dim, opt.dim), regularizer=opt.regul...
[ "Applies a 1-D convolution.\n \n Args:\n tensor: A 3-D `Tensor` (automatically passed by decorator).\n opt:\n size: A positive `integer` representing `[kernel width]`.\n If not specified, 2 is set implicitly.\n stride: A positive `integer`. The number of entries by which\n ...
Please provide a description of the function:def sg_aconv(tensor, opt): r # default options opt += tf.sg_opt(size=(3, 3), rate=2, pad='SAME') opt.size = opt.size if isinstance(opt.size, (tuple, list)) else [opt.size, opt.size] # parameter tf.sg_initializer w = tf.sg_initializer.he_uniform('W', ...
[ "Applies a 2-D atrous (or dilated) convolution.\n \n Args:\n tensor: A 4-D `Tensor` (automatically passed by decorator).\n opt:\n size: A tuple/list of positive integers of length 2 representing `[kernel height, kernel width]`.\n Can be an integer if both values are the same.\n ...
Please provide a description of the function:def sg_aconv1d(tensor, opt): r # default options opt += tf.sg_opt(size=(2 if opt.causal else 3), rate=1, pad='SAME') # parameter tf.sg_initializer w = tf.sg_initializer.he_uniform('W', (1, opt.size, opt.in_dim, opt.dim), ...
[ "Applies 1-D atrous (or dilated) convolution.\n \n Args:\n tensor: A 3-D `Tensor` (automatically passed by decorator).\n opt:\n causal: Boolean. If True, zeros are padded before the time axis such that\n each activation unit doesn't have receptive neurons beyond the equivalent time s...
Please provide a description of the function:def sg_upconv(tensor, opt): r # default options opt += tf.sg_opt(size=(4, 4), stride=(1, 2, 2, 1), pad='SAME') opt.size = opt.size if isinstance(opt.size, (tuple, list)) else [opt.size, opt.size] opt.stride = opt.stride if isinstance(opt.stride, (tuple, l...
[ "Applies a up convolution (or convolution transpose).\n \n Args:\n tensor: A 4-D `Tensor` (automatically passed by decorator).\n opt:\n size: A tuple/list of integers of length 2 representing `[kernel height, kernel width]`.\n Can be an integer if both values are the same.\n ...
Please provide a description of the function:def sg_upconv1d(tensor, opt): r # default options opt += tf.sg_opt(size=4, stride=2, pad='SAME') opt.size = [opt.size, 1] opt.stride = [1, opt.stride, 1, 1] # parameter tf.sg_initializer w = tf.sg_initializer.he_uniform('W', (opt.size[0], opt.siz...
[ "Applies 1-D a up convolution (or convolution transpose).\n\n Args:\n tensor: A 3-D `Tensor` (automatically passed by decorator).\n opt:\n size: A positive `integer` representing `[kernel width]`. As a default it is set to 4\n stride: A positive `integer` representing stride dimension. A...
Please provide a description of the function:def sg_espcn(tensor, opt): r # default options opt += tf.sg_opt(size=(3, 3), stride=(1, 1, 1, 1), pad='SAME', factor=2) opt.size = opt.size if isinstance(opt.size, (tuple, list)) else [opt.size, opt.size] opt.stride = opt.stride if isinstance(opt.stride, ...
[ "Applies a 2-D efficient sub pixel convolution.\n (see [Shi et al. 2016](http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Shi_Real-Time_Single_Image_CVPR_2016_paper.pdf)\n\n Args:\n tensor: A 4-D `Tensor` (automatically passed by decorator).\n opt:\n size: A tuple/list of p...
Please provide a description of the function:def sg_emb(**kwargs): r opt = tf.sg_opt(kwargs) assert opt.name is not None, 'name is mandatory.' if opt.emb is None: # initialize embedding matrix assert opt.voca_size is not None, 'voca_size is mandatory.' assert opt.dim is not None...
[ "Returns a look-up table for embedding.\n \n kwargs:\n name: A name for the layer.\n emb: A 2-D array (optional). \n If None, the resulting tensor should have the shape of \n `[vocabulary size, embedding dimension size]`.\n Note that its first row is filled with 0's associated w...
Please provide a description of the function:def _ln_rnn(x, gamma, beta): r # calc layer mean, variance for final axis mean, variance = tf.nn.moments(x, axes=[len(x.get_shape()) - 1], keep_dims=True) # apply layer normalization x = (x - mean) / tf.sqrt(variance + tf.sg_eps) # apply parameter ...
[ "Applies layer normalization.\n Normalizes the last dimension of the tensor `x`.\n \n Args:\n x: A `Tensor`.\n gamma: A constant `Tensor`. Scale parameter. Default is 1.\n beta: A constant `Tensor`. Offset parameter. Default is 0.\n\n Returns:\n A `Tensor` with the same shape as `x`....
Please provide a description of the function:def sg_rnn(tensor, opt): r # layer normalization # noinspection PyPep8 ln = lambda v: _ln_rnn(v, gamma, beta) if opt.ln else v # step function def step(hh, x): # simple rnn y = ln(tf.matmul(x, w) + tf.matmul(hh, u) + (b if opt.bias el...
[ "Applies a simple rnn.\n \n Args:\n tensor: A 3-D `Tensor` (automatically passed by decorator).\n opt:\n in_dim: A positive `integer`. The size of input dimension.\n dim: A positive `integer`. The size of output dimension.\n bias: Boolean. If True, biases are added.\n ln:...
Please provide a description of the function:def sg_gru(tensor, opt): r # layer normalization # noinspection PyPep8 ln = lambda v: _ln_rnn(v, gamma, beta) if opt.ln else v # step func def step(hh, x): # update gate z = tf.sigmoid(ln(tf.matmul(x, w_z) + tf.matmul(hh, u_z) + (b_z...
[ "Applies a GRU.\n \n Args:\n tensor: A 3-D `Tensor` (automatically passed by decorator).\n opt:\n in_dim: A positive `integer`. The size of input dimension.\n dim: A positive `integer`. The size of output dimension.\n bias: Boolean. If True, biases are added.\n ln: Boolea...
Please provide a description of the function:def sg_lstm(tensor, opt): r # layer normalization # noinspection PyPep8 ln = lambda v: _ln_rnn(v, gamma, beta) if opt.ln else v # step func def step(hh, cc, x): # forget gate f = tf.sigmoid(ln(tf.matmul(x, w_f) + tf.matmul(hh, u_f) + ...
[ "Applies an LSTM.\n\n Args:\n tensor: A 3-D `Tensor` (automatically passed by decorator).\n opt:\n in_dim: A positive `integer`. The size of input dimension.\n dim: A positive `integer`. The size of output dimension.\n bias: Boolean. If True, biases are added.\n ln: Boolean....
Please provide a description of the function:def sg_ce(tensor, opt): r opt += tf.sg_opt(one_hot=False) assert opt.target is not None, 'target is mandatory.' if opt.one_hot: out = tf.identity(tf.nn.softmax_cross_entropy_with_logits(labels=opt.target, logits=tensor), 'ce') else: out =...
[ "Returns softmax cross entropy loss between `tensor` and `target`.\n \n Args:\n tensor: A `Tensor`. Logits. Unscaled log probabilities.\n opt:\n target: A `Tensor` with the same length in the first dimension as the `tensor`. Labels. \n one_hot: Boolean. Whether to treat the labels as o...
Please provide a description of the function:def sg_bce(tensor, opt): r assert opt.target is not None, 'target is mandatory.' out = tf.identity(tf.nn.sigmoid_cross_entropy_with_logits(labels=opt.target, logits=tensor), 'bce') # add summary tf.sg_summary_loss(out, name=opt.name) return ou...
[ "Returns sigmoid cross entropy loss between `tensor` and `target`.\n \n Args:\n tensor: A `Tensor`. Logits. Unscaled log probabilities.\n opt:\n target: A `Tensor` with the same shape and dtype as `tensor`. Labels.\n name: A `string`. A name to display in the tensor board web UI.\n ...
Please provide a description of the function:def sg_mse(tensor, opt): r assert opt.target is not None, 'target is mandatory.' # squared error out = tf.identity(tf.square(tensor - opt.target), 'mse') # add summary tf.sg_summary_loss(out, name=opt.name) return out
[ "Returns squared error between `tensor` and `target`.\n \n Args:\n tensor: A `Tensor`.\n opt:\n target: A `Tensor` with the same shape and dtype as `tensor`.\n name: A `string`. A name to display in the tensor board web UI.\n \n Returns:\n A `Tensor` of the same shape and...
Please provide a description of the function:def sg_mae(tensor, opt): r assert opt.target is not None, 'target is mandatory.' # absolute error out = tf.identity(tf.abs(tensor - opt.target), 'mae') # add summary tf.sg_summary_loss(out, name=opt.name) return out
[ "Returns absolute error between `tensor` and `target`.\n \n Args:\n tensor: A `Tensor`.\n opt:\n target: A `Tensor` with the same shape and dtype as `tensor`.\n name: A `string`. A name to display in the tensor board web UI.\n \n Returns:\n A `Tensor` of the same shape and...
Please provide a description of the function:def sg_hinge(tensor, opt): r assert opt.target is not None, 'target is mandatory.' # default margin opt += tf.sg_opt(margin=1) # reshape target shape = tensor.get_shape().as_list() broadcast_shape = [-1] + [1] * (len(shape) - 2) + [shape[-1]] ...
[ "Returns hinge loss between `tensor` and `target`.\n \n Args:\n tensor: A `Tensor`.\n opt:\n target: A `Tensor`. Labels.\n margin: An int. Maximum margin. Default is 1.\n name: A `string`. A name to display in the tensor board web UI.\n \n Returns:\n A `Tensor`.\n ...
Please provide a description of the function:def sg_ctc(tensor, opt): r assert opt.target is not None, 'target is mandatory.' # default sequence length shape = tf.shape(tensor) opt += tf.sg_opt(seq_len=tf.ones((shape[0],), dtype=tf.sg_intx) * shape[1], merge=True) # ctc loss out = tf.nn.ct...
[ "Computes the CTC (Connectionist Temporal Classification) Loss between `tensor` and `target`.\n\n Args:\n tensor: A 3-D `float Tensor`.\n opt:\n target: A `Tensor` with the same length in the first dimension as the `tensor`. Labels. ( Dense tensor )\n name: A `string`. A name to display i...
Please provide a description of the function:def sg_cast(tensor, opt): r assert opt.dtype is not None, 'dtype is mandatory.' return tf.cast(tensor, opt.dtype, name=opt.name)
[ "Casts a tensor to a new type.\n \n See `tf.cast()` in tensorflow.\n\n Args:\n tensor: A `Tensor` or `SparseTensor` (automatically given by chain).\n opt:\n dtype : The destination type.\n name : If provided, it replaces current tensor's name\n\n Returns:\n A `Tensor` or `Sp...
Please provide a description of the function:def sg_float(tensor, opt): r return tf.cast(tensor, tf.sg_floatx, name=opt.name)
[ "Casts a tensor to floatx.\n \n See `tf.cast()` in tensorflow.\n\n Args:\n tensor: A `Tensor` or `SparseTensor` (automatically given by chain).\n opt:\n name : If provided, it replaces current tensor's name\n\n Returns:\n A `Tensor` or `SparseTensor` with same shape as `tensor`.\n ...
Please provide a description of the function:def sg_int(tensor, opt): r return tf.cast(tensor, tf.sg_intx, name=opt.name)
[ "Casts a tensor to intx.\n \n See `tf.cast()` in tensorflow.\n\n Args:\n tensor: A `Tensor` or `SparseTensor` (automatically given by chain).\n opt:\n name: If provided, it replaces current tensor's name.\n\n Returns:\n A `Tensor` or `SparseTensor` with same shape as `tensor`.\n ...
Please provide a description of the function:def sg_expand_dims(tensor, opt): r opt += tf.sg_opt(axis=-1) return tf.expand_dims(tensor, opt.axis, name=opt.name)
[ "Inserts a new axis.\n \n See tf.expand_dims() in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : Dimension to expand. Default is -1.\n name: If provided, it replaces current tensor's name.\n\n Returns:\n A `Tensor`.\n " ]
Please provide a description of the function:def sg_squeeze(tensor, opt): r opt += tf.sg_opt(axis=[-1]) opt.axis = opt.axis if isinstance(opt.axis, (tuple, list)) else [opt.axis] return tf.squeeze(tensor, opt.axis, name=opt.name)
[ "Removes axis of size 1 from the shape of a tensor.\n \n See `tf.squeeze()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer.\n axis to remove. Default is -1.\n name: If provided, it re...
Please provide a description of the function:def sg_flatten(tensor, opt): r dim = np.prod(tensor.get_shape().as_list()[1:]) return tf.reshape(tensor, [-1, dim], name=opt.name)
[ "Reshapes a tensor to `batch_size x -1`.\n \n See `tf.reshape()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n name: If provided, it replaces current tensor's name.\n\n Returns:\n A 2-D tensor.\n\n " ]
Please provide a description of the function:def sg_reshape(tensor, opt): r assert opt.shape is not None, 'shape is mandatory.' return tf.reshape(tensor, opt.shape, name=opt.name)
[ "Reshapes a tensor.\n \n See `tf.reshape()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n shape: A tuple/list of integers. The destination shape.\n name: If provided, replace current tensor's name.\n\n Returns:\n A `Tensor`.\n " ]
Please provide a description of the function:def sg_transpose(tensor, opt): r assert opt.perm is not None, 'perm is mandatory' return tf.transpose(tensor, opt.perm, name=opt.name)
[ "Permutes the dimensions according to `opt.perm`.\n\n See `tf.transpose()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n perm: A permutation of the dimensions of `tensor`. The target shape.\n name: If provided, replace current tensor's name.\n\n...
Please provide a description of the function:def sg_argmax(tensor, opt): r opt += tf.sg_opt(axis=tensor.get_shape().ndims-1) return tf.argmax(tensor, opt.axis, opt.name)
[ "Returns the indices of the maximum values along the specified axis.\n \n See `tf.argmax()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis: Target axis. Default is the last one.\n name: If provided, replace current tensor's name.\n\n R...
Please provide a description of the function:def sg_argmin(tensor, opt): r opt += tf.sg_opt(axis=tensor.get_shape().ndims - 1) return tf.argmin(tensor, opt.axis, opt.name)
[ "Returns the indices of the minimum values along the specified axis.\n\n See `tf.argin()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis: Target axis. Default is the last one.\n name: If provided, replace current tensor's name.\n\n Return...
Please provide a description of the function:def sg_concat(tensor, opt): r assert opt.target is not None, 'target is mandatory.' opt += tf.sg_opt(axis=tensor.get_shape().ndims-1) target = opt.target if isinstance(opt.target, (tuple, list)) else [opt.target] return tf.concat([tensor] + target, opt.ax...
[ "Concatenates tensors along a axis.\n\n See `tf.concat()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n target: A `Tensor`. Must have the same rank as `tensor`, and\n all dimensions except `opt.dim` must be equal.\n axis : Target axis. ...
Please provide a description of the function:def sg_one_hot(tensor, opt): r assert opt.depth is not None, 'depth is mandatory.' return tf.one_hot(tensor, opt.depth, name=opt.name)
[ "Converts a tensor into a one-hot tensor.\n \n See `tf.one_hot()` in tensorflow.\n\n Args:\n tensor: A `Tensor` ( automatically given by chain )\n opt:\n depth: The number of classes.\n name: If provided, replace current tensor's name.\n\n Returns:\n A `Tensor`.\n " ]
Please provide a description of the function:def sg_to_sparse(tensor, opt): r indices = tf.where(tf.not_equal(tensor.sg_float(), 0.)) return tf.SparseTensor(indices=indices, values=tf.gather_nd(tensor, indices) - 1, # for zero-based index dense_shape=tf...
[ "Converts a dense tensor into a sparse tensor.\n \n See `tf.SparseTensor()` in tensorflow.\n\n Args:\n tensor: A `Tensor` with zero-padding (automatically given by chain).\n opt:\n name: If provided, replace current tensor's name.\n\n Returns:\n A `SparseTensor`.\n " ]
Please provide a description of the function:def sg_log(tensor, opt): r return tf.log(tensor + tf.sg_eps, name=opt.name)
[ "Log transform a dense tensor\n\n See `tf.log()` in tensorflow.\n\n Args:\n tensor: A `Tensor` ( automatically given by chain )\n opt:\n name: If provided, replace current tensor's name.\n\n Returns:\n A `Tensor`.\n " ]
Please provide a description of the function:def sg_sum(tensor, opt): r return tf.reduce_sum(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)
[ "Computes the sum of elements across axis of a tensor.\n \n See `tf.reduce_sum()` in tensorflow.\n\n Args:\n tensor: A `Tensor` with zero-padding (automatically given by chain).\n opt:\n axis: A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains ...
Please provide a description of the function:def sg_mean(tensor, opt): r return tf.reduce_mean(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)
[ "Computes the mean of elements across axis of a tensor.\n \n See `tf.reduce_mean()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduced dimensi...
Please provide a description of the function:def sg_prod(tensor, opt): r return tf.reduce_prod(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)
[ "Computes the product of elements across axis of a tensor.\n\n See `tf.reduce_prod()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduced dimensio...
Please provide a description of the function:def sg_min(tensor, opt): r return tf.reduce_min(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)
[ "Computes the minimum of elements across axis of a tensor.\n\n See `tf.reduce_min()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduced dimension...
Please provide a description of the function:def sg_max(tensor, opt): r return tf.reduce_max(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)
[ "Computes the maximum of elements across axis of a tensor.\n\n See `tf.reduce_max()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduced dimension...
Please provide a description of the function:def sg_all(tensor, opt): r return tf.reduce_all(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)
[ "Computes the \"logical and\" of elements across axis of a tensor.\n \n See `tf.reduce_all()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduc...
Please provide a description of the function:def sg_any(tensor, opt): r return tf.reduce_any(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)
[ "Computes the \"logical or\" of elements across axis of a tensor.\n\n See `tf.reduce_any()` in tensorflow.\n\n Args:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduced di...
Please provide a description of the function:def sg_pool(tensor, opt): r # default stride and pad opt += tf.sg_opt(stride=(1, 2, 2, 1), pad='VALID') # shape stride opt.stride = opt.stride if isinstance(opt.stride, (list, tuple)) else [1, opt.stride, opt.stride, 1] opt.stride = [1, opt.stride[0...
[ "Performs the 2-D pooling on the `tensor`.\n Mostly used with sg_conv().\n\n Args:\n tensor: A 4-D `Tensor` (automatically given by chain).\n opt:\n size: A tuple or list of integers of length 2 representing `[kernel height, kernel width]`.\n Can be an int if both values are the same...
Please provide a description of the function:def sg_pool1d(tensor, opt): r # default stride and pad opt += tf.sg_opt(stride=2, pad='VALID') opt += tf.sg_opt(size=opt.stride) if opt.avg: out = tf.nn.avg_pool(tensor.sg_expand_dims(axis=2), (1, opt.size, 1, 1), (1...
[ "Performs the 1-D pooling on the `tensor`.\n \n Args:\n tensor: A 3-D `Tensor` (automatically passed by decorator).\n opt:\n size: A positive `integer` representing `[kernel width]`.\n Default is 2.\n stride: A positive `integer`. The number of entries by which\n the ...
Please provide a description of the function:def sg_lookup(tensor, opt): r assert opt.emb is not None, 'emb is mandatory.' return tf.nn.embedding_lookup(opt.emb, tensor, name=opt.name)
[ "Looks up the `tensor`, which is the embedding matrix.\n\n Args:\n tensor: A tensor ( automatically given by chain )\n opt:\n emb: A 2-D `Tensor`. An embedding matrix.\n name: If provided, replace current tensor's name.\n\n Returns:\n A `Tensor`.\n\n " ]
Please provide a description of the function:def sg_reverse_seq(tensor, opt): r # default sequence dimension opt += tf.sg_opt(axis=1) seq_len = tf.not_equal(tensor, tf.zeros_like(tensor)).sg_int().sg_sum(axis=opt.axis) return tf.reverse_sequence(tensor, seq_len, opt.axis, name=opt.name)
[ "Reverses variable length slices.\n\n Before applying the pure tensorflow function tf.reverse_sequence,\n this function calculates sequence lengths by counting non-zeros.\n\n For example,\n \n ```\n tensor = [[1, 2, 3, 0, 0], [4, 5, 0, 0, 0]]\n tensor.sg_reverse_seq()\n => [[3 2 1 0 0]\n ...
Please provide a description of the function:def sg_periodic_shuffle(tensor, opt): r # default factor opt += tf.sg_opt(factor=2) # get current shape batch, row, col, channel = tensor.get_shape().as_list() # get target channel num channel_target = channel // (opt.factor * opt.factor) ch...
[ " Periodic shuffle transformation for SubPixel CNN.\n (see [Shi et al. 2016](http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Shi_Real-Time_Single_Image_CVPR_2016_paper.pdf)\n \n Args:\n tensor: A tensor (automatically given by chain).\n opt:\n factor: factor to mul...
Please provide a description of the function:def sg_accuracy(tensor, opt): r assert opt.target is not None, 'target is mandatory.' opt += tf.sg_opt(k=1) # # calc accuracy out = tf.identity(tf.equal(tensor.sg_argmax(), tf.cast(opt.target, tf.int64)).sg_float(), name='acc') # out = tf.identity(tf...
[ "Returns accuracy of predictions.\n \n Args:\n tensor: A `Tensor`. Probability distributions or unscaled prediction scores.\n opt:\n target: A 'Tensor`. Labels.\n \n Returns:\n A `Tensor` of the same shape as `tensor`. Each value will be 1 if correct else 0. \n \n For examp...
Please provide a description of the function:def sg_gpus(): r global _gpus if _gpus is None: local_device_protos = device_lib.list_local_devices() _gpus = len([x.name for x in local_device_protos if x.device_type == 'GPU']) return max(_gpus, 1)
[ " Gets current available GPU nums\n\n Returns:\n A integer : total # of GPUs available\n " ]
Please provide a description of the function:def sg_context(**kwargs): r global _context # set options when enter context_now = tf.sg_opt(kwargs) _context += [context_now] # if named context if context_now.name: context_now.scope_name = context_now.name context_now.name = N...
[ "Context helper for computational graph building.\n Makes all elements within the with Block share the parameters.\n\n For example, in the following example, the default value of parameter `bn` will be set to True\n in the all layers within the with block.\n\n ```\n with tf.sg_context(bn=True):\n ...
Please provide a description of the function:def sg_get_context(): r global _context # merge current context res = tf.sg_opt() for c in _context: res += c return res
[ "Get current context information\n\n Returns:\n tf.sg_opt class object which contains all context information\n " ]
Please provide a description of the function:def sg_sugar_func(func): r @wraps(func) def wrapper(tensor, **kwargs): # call sugar function out = func(tensor, tf.sg_opt(kwargs)) # save node info for reuse out._sugar = tf.sg_opt(func=func, arg=tf.sg_opt(kwargs)+sg_get_context(),...
[ " Decorates a function `func` so that it can be a sugar function.\n Sugar function can be used in a chainable manner.\n\n Args:\n func: function to decorate\n\n Returns:\n A sugar function.\n\n " ]
Please provide a description of the function:def sg_layer_func(func): r @wraps(func) def wrapper(tensor, **kwargs): r from . import sg_initializer as init from . import sg_activation # kwargs parsing opt = tf.sg_opt(kwargs) + sg_get_context() # set default ...
[ "Decorates a function `func` as a sg_layer function.\n\n Args:\n func: function to decorate\n ", "Manages arguments of `tf.sg_opt`.\n\n Args:\n tensor: A `tensor` (automatically passed by decorator).\n kwargs:\n shape: A list of integers. The shape of `tensor`. In...
Please provide a description of the function:def sg_rnn_layer_func(func): r @wraps(func) def wrapper(tensor, **kwargs): r # kwargs parsing opt = tf.sg_opt(kwargs) + sg_get_context() # set default argument try: shape = tensor.get_shape().as_list() ...
[ "Decorates function as sg_rnn_layer functions.\n Args:\n func: function to decorate\n ", "Manages arguments of `tf.sg_opt`.\n\n Args:\n tensor: automatically passed by decorator\n kwargs:\n in_dim: An integer. The size of input dimension, which is set to the last...
Please provide a description of the function:def sg_reuse(tensor, **opt): r opt = tf.sg_opt(opt) assert hasattr(tensor, '_sugar'), 'cannot reuse this node.' assert opt.input is not None, 'input is mandatory.' # get all nodes in this graph nodes, prev = [tensor], tensor._sugar.prev while pre...
[ " Reconstruct computational graph of `tensor` so all the parameters\n can be reused and replace its input tensor with `opt.input`.\n\n Args:\n tensor: A `Tensor` (automatically given by chaining).\n **opt:\n input: A `Tensor` that will replace the original input tensor.\n\n Returns:\n ...
Please provide a description of the function:def sg_input(shape=None, dtype=sg_floatx, name=None): r if shape is None: return tf.placeholder(dtype, shape=None, name=name) else: if not isinstance(shape, (list, tuple)): shape = [shape] return tf.placeholder(dtype, shape=[No...
[ "Creates a placeholder.\n\n Args:\n shape: A tuple/list of integers. If an integers is given, it will turn to a list.\n dtype: A data type. Default is float32.\n name: A name for the placeholder.\n\n Returns:\n A wrapped placeholder `Tensor`.\n " ]
Please provide a description of the function:def sg_inject(path, mod_name): r # import module import sys if path not in list(sys.path): sys.path.append(path) globals()[mod_name] = importlib.import_module(mod_name) # find functions for func_name in dir(globals()[mod_name]): if...
[ "Converts all functions in the given Python module to sugar functions\n so that they can be used in a chainable manner.\n\n Args:\n path: A string. Path to the Python module\n mod_name: A string. The name of the Python module to inject.\n\n Returns:\n None\n " ]
Please provide a description of the function:def sg_queue_context(sess=None): r # default session sess = tf.get_default_session() if sess is None else sess # thread coordinator coord = tf.train.Coordinator() try: # start queue thread threads = tf.train.start_queue_runners(sess,...
[ "Context helper for queue routines.\n\n Args:\n sess: A session to open queues. If not specified, a new session is created.\n\n Returns:\n None\n " ]
Please provide a description of the function:def sg_parallel(func): r @wraps(func) def wrapper(**kwargs): r # parse option opt = tf.sg_opt(kwargs) # loop for all available GPUs res = [] for i in range(sg_gpus()): # specify device with ...
[ "Decorates function as multiple gpu support towers.\n Args:\n func: function to decorate\n ", "Manages arguments of `tf.sg_opt`.\n\n Args:\n kwargs: keyword arguments. The wrapped function will be provided with gpu_index argument.\n " ]
Please provide a description of the function:def sg_arg(): r if not tf.app.flags.FLAGS.__dict__['__parsed']: tf.app.flags.FLAGS._parse_flags() return tf.sg_opt(tf.app.flags.FLAGS.__dict__['__flags'])
[ "Gets current command line options\n\n Returns:\n tf.sg_opt instance that is updated with current commandd line options.\n " ]
Please provide a description of the function:def sg_arg_def(**kwargs): r for k, v in kwargs.items(): if type(v) is tuple or type(v) is list: v, c = v[0], v[1] else: c = k if type(v) is str: tf.app.flags.DEFINE_string(k, v, c) elif type(v) is in...
[ "Defines command line options\n\n Args:\n **kwargs:\n key: A name for the option.\n value : Default value or a tuple of (default value, description).\n\n Returns:\n None\n\n For example,\n\n ```\n # Either of the following two lines will define `--n_epoch` command line argumen...
Please provide a description of the function:def sg_summary_loss(tensor, prefix='losses', name=None): r # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name(tensor) if name is None else prefix + name # summary statistics _scalar(name, tf.redu...
[ "Register `tensor` to summary report as `loss`\n\n Args:\n tensor: A `Tensor` to log as loss\n prefix: A `string`. A prefix to display in the tensor board web UI.\n name: A `string`. A name to display in the tensor board web UI.\n\n Returns:\n None\n " ]
Please provide a description of the function:def sg_summary_gradient(tensor, gradient, prefix=None, name=None): r # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name(tensor) if name is None else prefix + name # summary statistics # noinspect...
[ "Register `tensor` to summary report as `gradient`\n\n Args:\n tensor: A `Tensor` to log as gradient\n gradient: A 0-D `Tensor`. A gradient to log\n prefix: A `string`. A prefix to display in the tensor board web UI.\n name: A `string`. A name to display in the tensor board web UI.\n\n Ret...
Please provide a description of the function:def sg_summary_activation(tensor, prefix=None, name=None): r # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name(tensor) if name is None else prefix + name # summary statistics _scalar(name + '/ra...
[ "Register `tensor` to summary report as `activation`\n\n Args:\n tensor: A `Tensor` to log as activation\n prefix: A `string`. A prefix to display in the tensor board web UI.\n name: A `string`. A name to display in the tensor board web UI.\n\n Returns:\n None\n " ]
Please provide a description of the function:def sg_summary_param(tensor, prefix=None, name=None): r # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name(tensor) if name is None else prefix + name # summary statistics _scalar(name + '/abs', t...
[ "Register `tensor` to summary report as `parameters`\n\n Args:\n tensor: A `Tensor` to log as parameters\n prefix: A `string`. A prefix to display in the tensor board web UI.\n name: A `string`. A name to display in the tensor board web UI.\n\n Returns:\n None\n " ]
Please provide a description of the function:def sg_summary_image(tensor, prefix=None, name=None): r # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name(tensor) if name is None else prefix + name # summary statistics if not tf.get_variable_s...
[ "Register `tensor` to summary report as `image`\n\n Args:\n tensor: A tensor to log as image\n prefix: A `string`. A prefix to display in the tensor board web UI.\n name: A `string`. A name to display in the tensor board web UI.\n\n Returns:\n None\n " ]
Please provide a description of the function:def sg_summary_audio(tensor, sample_rate=16000, prefix=None, name=None): r # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name(tensor) if name is None else prefix + name # summary statistics if no...
[ "Register `tensor` to summary report as audio\n\n Args:\n tensor: A `Tensor` to log as audio\n sample_rate : An int. Sample rate to report. Default is 16000.\n prefix: A `string`. A prefix to display in the tensor board web UI.\n name: A `string`. A name to display in the tensor board web UI....
Please provide a description of the function:def sg_leaky_relu(x, opt): r return tf.where(tf.greater(x, 0), x, 0.01 * x, name=opt.name)
[ "\"See [Xu, et al. 2015](https://arxiv.org/pdf/1505.00853v2.pdf)\n\n Args:\n x: A tensor\n opt:\n name: A name for the operation (optional).\n \n Returns:\n A `Tensor` with the same type and shape as `x`.\n " ]