def sent_if(sentence: ast.If, f=""): elif_list = [] #Make Elif Block list tmp = sentence.orelse while len(tmp) != 0 and type(tmp[0]) == ast.If and len(tmp[0].orelse) != 0: elif_list.append(tmp) tmp = tmp[0].orelse blocks = [a[0] for a in elif_list] elseblock = tmp tmp = "" #If Block tmp += "if(" + util.conv(sentence.test, mode=util.modes.EXPR) + "){\n" tmp += util.walk_shallow(sentence.body, f=f + " ") tmp += "}" #Elif Blocks for block in blocks: tmp += f + "else if(" + util.conv(block.test, mode=util.modes.EXPR) + "){\n" tmp += util.walk_shallow(block.body, f + " ") tmp += f + "}" #Else Block if len(elseblock) != 0: tmp += f + "else{\n" tmp += util.walk_shallow(elseblock, f + " ") tmp += f + "}" return tmp + "\n"
def sent_AnnAssign(sentence: ast.AnnAssign, f=""): value = "" if sentence.value: value = "=" + util.conv(sentence.value, mode=util.modes.EXPR) annotation = util.conv(sentence.annotation, mode=util.modes.EXPR) name = util.conv(sentence.target, mode=util.modes.EXPR) return annotation + " " + name + value + ";\n"
def sent_classdef(sentence: ast.ClassDef, f=""): tmp = "" tmp += f + "class _" + sentence.name if len(sentence.bases) != 0: tmp += ": " tmp += ", ".join([ "public " + util.conv(base, mode=util.modes.EXPR) for base in sentence.bases ]) tmp += "\n" tmp += "{\n" tmp += util.walk_shallow(sentence.body, f=f + " ") tmp += "}\n" decor_proc = "_" + sentence.name decors = [ util.conv(a, mode=util.modes.EXPR) for a in sentence.decorator_list ] decors.reverse() for decor in decors: decor_proc = f"{decor}({decor_proc})" tmp += f"#define {sentence.name} {decor_proc}\n" return tmp
def __init__(self, dim: int): super(ResnetBlock, self).__init__() self.conv_block = None ### Residual block # You have to implement the residual block with 2 convolutional layers. # Note 1: Recommend to use 'conv' and 'deconv' function implemented in 'util.py'. # Note 2: You have to use 'nn.ReflectionPad2d' for padding. # Note 3: You have to use instance normalization for normalizing the feature maps. ### YOUR CODE HERE (~ 4 lines) model = [ nn.ReflectionPad2d(1), conv(256, 256, 3, stride=1, pad=0, bias=True, norm='in', activation='relu'), nn.ReflectionPad2d(1), conv(256, 256, 3, stride=1, pad=0, bias=True, norm='in', activation=None) ] self.conv_block = nn.Sequential(*model)
def expr_Slice(val: ast.slice): tmp = "" if val.lower != None: tmp += util.conv(val.lower, mode=util.modes.EXPR) tmp += ":" if val.upper != None: tmp += util.conv(val.upper, mode=util.modes.EXPR) tmp += ":" if val.step != None: tmp += util.conv(val.step, mode=util.modes.EXPR) return "[" + tmp + "]"
def sent_assign(sentence: ast.Assign, f=""): ret = "" value = util.conv(sentence.value, mode=util.modes.EXPR) for i, target in enumerate(sentence.targets): ret += f #if util.conv(target,mode=util.modes.EXPR) not in datamgr.dictmgr.get("session","definedVariables"): if type(target) != ast.Attribute: ret += "Any " ret += util.conv(target, mode=util.modes.EXPR) ret += " = " + value if len(sentence.targets) != 1: ret += "[" + str(i) + "]" ret += ";\n" return ret
def expr_dict(val: ast.Dict): tmp = "" tmp += "Core::make_dict(" keys = [] values = [] for k, v in zip(val.keys, val.values): keys.append(util.conv(k, mode=util.modes.EXPR)) values.append(util.conv(v, mode=util.modes.EXPR)) tmp += "{" + ",".join(keys) + "}" tmp += ", " tmp += "{" + ",".join(values) + "}" tmp += ")" return tmp
def d_net(self, x, batch_size, phase): gf_dim = 64 kenel_size = 5 conv1 = conv(x, (kenel_size, kenel_size, 6, gf_dim), 'conv1', phase) conv2 = conv(conv1, (kenel_size, kenel_size, gf_dim, gf_dim * 2), 'conv2', phase) conv3 = conv(conv2, (kenel_size, kenel_size, gf_dim * 2, gf_dim * 4), 'conv3', phase) conv4 = conv(conv3, (kenel_size, kenel_size, gf_dim * 4, gf_dim * 8), 'conv4', phase) flatten = tf.reshape(conv4, (batch_size, -1)) liner1 = liner(flatten, 1, 'liner1') return liner1
def sent_YieldFrom(sentence: ast.YieldFrom, f=""): s = "" s += f + "for(Any value:" + util.conv(sentence.value, mode=util.modes.EXPR) + "){" s += f + " yield value" s += f + "}\n" return s
def drh_connect(init, goal, region, obsts, t_max, x_label="x", decomp=False): out = StringIO() for i in range(region.n): print >>out, "[{0[0]}, {0[1]}] {1}_{2};".format( region.constraints[i], x_label, i) print >>out, "[0, {0}] time;".format(t_max) print >>out, "[0, 3.15] z;" expanded_obsts = [expansion(obs, 0.001) for obs in obsts] if decomp: if region.n > 2: raise Exception() r = conv([init, goal]) dec = [init] + cdecomp(r, expanded_obsts) + [goal] jumps = adj_matrix(dec) for i, invt in enumerate(dec): print >>out, drh_mode(i, x_label, invt, jumps) else: #FIXME obsts print >>out, drh_mode(0, x_label, obsts, dict()) print >>out, "init:" print >>out, "@1 {0};".format(c_shape(init, x_label)) print >>out, "goal:" print >>out, "@{1} {0};".format(c_shape(goal, x_label), 1 if not decomp else len(dec)) s = out.getvalue() out.close() return s
def expr_list(val: ast.List): tmp = "" tmp += "{" tmp += ", ".join( [util.conv(elt, mode=util.modes.EXPR) for elt in val.elts]) tmp += "}" return tmp
def _conv(filename: str): """ Convert python to c++ source code Parameter Name | Description|Type ---------+------------+----- filename | source | str Returns:None """ src_abs = os.path.abspath(filename) src_rel = os.path.relpath(filename) if basemode: tmp = os.path.basename(src_rel)[:-3] else: tmp = os.path.splitext(src_rel)[0] out_file = out + os.path.sep + tmp + ".cpp" src_file = src_abs if src_file not in datamgr.dictmgr.get("internal", "converted"): #Read src(python) with open(src_file, "r") as fp: src = ast.parse(fp.read(), src_file) #Write src(C++) fp = open(out_file, "w") fp.write("#include <base>\n") for sentence in src.body: fp.write(util.conv(sentence, mode=util.modes.SENT)) fp.close() datamgr.dictmgr.get("internal", "converted").add(src_file)
def sent_with(sentence: ast.With, f=""): tmp = "" tmp += f + "\n" for item in sentence.items: tmp += f + util.conv( item.optional_vars, mode=util.modes.EXPR) + " = " + util.conv( item.context_expr, mode=util.modes.EXPR) + ".__enter__();\n" tmp += util.walk_shallow(sentence.body, f) for item in sentence.items: tmp += f + util.conv( item.optional_vars, mode=util.modes.EXPR) + " = " + util.conv( item.context_expr, mode=util.modes.EXPR) + ".__exit__(nullptr,nullptr,nullptr);\n" tmp += f + "\n" return tmp
def expr_DictComp(val: ast.DictComp): s = "" s += "Core::DictComp(" s += "{" args = set() for gen in val.generators: s += "{" s += util.conv(gen.iter, mode=util.modes.EXPR) + "," s += "{" s += ",".join( [util.conv(ifb, mode=util.modes.EXPR) for ifb in gen.ifs]) s += "}" args.add(util.conv(gen.target, mode=util.modes.EXPR)) s += "}" s += "}," args = ",".join([f"Any {b}" for b in args]) s += f"[]({args}){{{util.conv(val.key,mode=util.modes.EXPR)}}}," s += f"[]({args}){{{util.conv(val.value,mode=util.modes.EXPR)}}}" s += ")" return s
def expr_ListComp(val: ast.ListComp): tmp = "Core::ListComp(" chars = ", ".join([ util.conv(gen.target, mode=util.modes.EXPR) for gen in val.generators ]) tmp += f"[]({chars})" tmp += "{return " + util.conv(val.elt, mode=util.modes.EXPR) + ";}, " tmp += "{ " for i, gen in enumerate(val.generators): tmp += "{" tmp += str(i) + "," tmp += util.conv(gen.iter, mode=util.modes.EXPR) tmp += "}," tmp += "},{" for i, gen in enumerate(val.generators): tmp += "{" for cond in gen.ifs: tmp += "[](" + util.conv( gen.target, mode=util.modes.EXPR) + "){return " + util.conv( cond, mode=util.modes.EXPR) + ";}" tmp += "}, " tmp = tmp[:-2] tmp += "});" return tmp
def sent_try(sentence: ast.Try, f=""): s = "" s += f + "try{\n" s += util.walk_shallow(sentence.body, f + " ") s += util.walk_shallow(sentence.finalbody, f + " ") s += f + "}" for handler in sentence.handlers: name = handler.name if not name: name = "ex" s += f + "catch(" + util.conv( handler.type, mode=util.modes.EXPR) + " " + name + "){\n" s += util.walk_shallow(handler.body, f + " ") s += util.walk_shallow(sentence.finalbody, f + " ") s += f + "}" if len(sentence.orelse) != 0: s += util.walk_shallow(sentence.orelse, f) return s
def expr_args(val: ast.arguments): defaults = [None] * (len(val.args) - len(val.defaults)) + val.defaults tmp = [] tmp += [ util.conv(a[0], mode=util.modes.EXPR) + "=" + util.conv(a[1], mode=util.modes.EXPR) for a in zip(val.args, defaults) ] if val.vararg != None: tmp += ["*" + util.conv(val.vararg, mode=util.modes.EXPR)] tmp += [ util.conv(a[0], mode=util.modes.EXPR) + "=" + util.conv(a[1], mode=util.modes.EXPR) for a in zip(val.kwonlyargs, val.kw_defaults) ] if val.kwarg != None: tmp += ["**" + util.conv(val.kwarg, mode=util.modes.EXPR)] return ", ".join(tmp)
def expr_UnaryOp(val: ast.UnaryOp): return util.conv(val.op, mode=util.modes.EXPR) + " " + util.conv( val.operand, mode=util.modes.EXPR)
def expr_comp(val: ast.Compare): return \ util.conv(val.left,mode=util.modes.EXPR)+" "+\ " ".join([util.conv(op,mode=util.modes.EXPR)+" "+util.conv(val,mode=util.modes.EXPR)+" " for (op,val) in zip(val.ops,val.comparators)])[:-1]
def expr_arg(val: ast.arg): ret = val.arg if val.annotation: return util.conv(val.annotation, mode=util.modes.EXPR) + " " + ret else: return "Any " + ret
def conv(val): a = val.__class__.__name__ if a == "Call": return expr_call(val) else: return util.conv(val, mode=util.modes.EXPR)
def expr_attr(val: ast.Attribute): return util.conv(val.value, mode=util.modes.EXPR) + "." + val.attr
def expr_BoolOp(val: ast.BoolOp): vals = [util.conv(a, mode=util.modes.EXPR) for a in val.values] return vals[0] + " " + util.conv(val.op, mode=util.modes.EXPR) + " " + vals[1]
def expr_Subscript(val: ast.Subscript): return util.conv(val.value, mode=util.modes.EXPR) + util.conv( val.slice, util.modes.EXPR)
def expr_NamedExpr(val: ast.NamedExpr): return util.conv(val.target, mode=util.modes.EXPR) + "=" + util.conv( val.value, mode=util.modes.EXPR)
def expr_starred(val: ast.Starred): return "*" + util.conv(val.value, mode=util.modes.EXPR)
def expr_ifexp(val: ast.IfExp): return util.conv(val.test, mode=util.modes.EXPR) + " ? " + util.conv( val.body, mode=util.modes.EXPR) + " : " + util.conv( val.orelse, mode=util.modes.EXPR)
def expr_Index(val: ast.Index): return "[" + util.conv(val.value, mode=util.modes.EXPR) + "]"
def expr_set(val: ast.Set): vals = [util.conv(a, mode=util.modes.EXPR) for a in val.elts] return "[" + ",".join(vals) + "]"
def expr_BinOp(val: ast.BinOp): return util.conv(val.left, mode=util.modes.EXPR) + util.conv( val.op, mode=util.modes.EXPR) + util.conv(val.right, mode=util.modes.EXPR)
def expr_Yield(sentence: ast.Yield, f=""): return f + "yield" + util.conv(sentence.value, mode=util.modes.EXPR) + "\n"