def makeAll(self, toCut=False): parts = [] fh = self.feetHolder() lh = self.legHolder(toCut) s = self.seat(toCut) b = self.back(toCut) r = self.rod() fh.rotate(Base.Vector(0,0,0), Base.Vector(0,1,0), -(90+self.alpha)) tx = (-math.cos(math.radians(90 - self.alpha)) + math.cos(self.r_alpha))*self.thickness tz = (math.sin(math.radians(90 - self.alpha)) + math.sin(self.r_alpha))*self.thickness fh.translate(Base.Vector(tx,0,tz)) lh.rotate(Base.Vector(0,0,0), Base.Vector(0,1,0), -(self.alpha)) tx = math.cos(self.r_alpha)*self.legHolderLength tz= math.sin(self.r_alpha)*(self.legHolderLength) -self.thickness s.rotate(Base.Vector(0,0,self.thickness), Base.Vector(0,1,0), self.alphaseat) s.translate(Base.Vector(tx,0,tz)) b.rotate(Base.Vector(0,0,0), Base.Vector(0,1,0), -(70)) tz += -self.seatLength*math.sin(self.r_alphaseat)+(1-math.cos(self.r_alpha))*self.thickness tx += self.seatLength*math.cos(self.r_alphaseat) +math.sin(self.r_alpha)*self.thickness b.translate(Base.Vector(tx,0,tz)) util.concat(parts, fh) util.concat(parts, lh) util.concat(parts, s) util.concat(parts, b) tr = Base.Vector(215,0,45) for p in parts: p.translate(tr) r.translate(Base.Vector(200,0,400)) util.concat(parts, r) return parts
def visit_function(self, function_): function = copy.deepcopy(function_) tokens = function.tokens[:cpp.get_declaration_end_index( function.name, function.tokens)] index, offset = cpp.find_function_name(function.name, tokens) cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, tokens[:index]) function_name = cpp_file_parser.get_function_name_for_type_erasure( function) code = util.concat(tokens[:index], ' ') + function_name + ' ( ' cpp_file_parser.replace_in_tokens(function.classname, 'HandleBase', tokens[index:]) code += cpp_file_parser.const_specifier( function) + self.data.interface_type + ' & ' for arg in cpp.get_function_arguments(function): code += ' , ' + arg.in_declaration() code += util.concat( tokens[cpp.get_arguments_end_index(function.name, tokens):cpp. get_declaration_end_index(function.name, tokens)], ' ') if not code.startswith('virtual '): code = 'virtual ' + code if not code.endswith('= 0'): code += ' = 0' code += ' ;' self.scope.add( cpp_file_parser.get_function_from_text(function.classname, function_name, function.return_str, code))
def allParts(): parts = [] util.concat(parts,mainWalls()) return util.concats([ util.common(houseBox(),parts), stairs() \ .common(houseBox()) \ .withTexture('/home/francois/Downloads/wall-1733680_1920.jpg') ])
def showAll(self,pnt=Base.Vector(0,0,0),dir=Base.Vector(0, 0, 1)): parts = []; util.concat(parts,self.makeAll()) doc=FreeCAD.activeDocument() grp=doc.addObject("App::DocumentObjectGroup", "middle") for p in parts: o = doc .addObject("Part::Feature", "Part") o.Shape = p grp.addObject(o) pass
def find_function_name(name, tokens): ntokens_for_name_and_bracket = get_name_size_in_tokens(name) + 1 name_tokens = [SimpleToken(tokens[i].spelling) for i in range(ntokens_for_name_and_bracket)] if util.concat(name_tokens) == name + '(': return 0, ntokens_for_name_and_bracket for i in range(ntokens_for_name_and_bracket, len(tokens)): name_tokens.pop(0) name_tokens.append(SimpleToken(tokens[i].spelling)) if util.same_signature(util.concat(name_tokens, ' '), name + '('): return i-ntokens_for_name_and_bracket+1, ntokens_for_name_and_bracket
def __init__(self,axisLength = TruckParams.axis['length'], axleFront = 0, axleBack = 2): self.axisLength = axisLength self.p_axles = [] self.p_axis = self.makeAxis() for i in range (axleFront): xOff = TruckParams.axle['fxoffset'] + i * (TruckParams.wheel['radius']*2 + TruckParams.axle['betweenMargin']) util.concat(self.p_axles,self.makeAxle(xOff)) for i in range (axleBack): xOff = self.axisLength - TruckParams.axle['bxoffset'] - i * (TruckParams.wheel['radius']*2 + TruckParams.axle['betweenMargin']) util.concat(self.p_axles,self.makeAxle(xOff))
def showAll(self,pnt=Base.Vector(0,0,0),dir=Base.Vector(0, 0, 1)): util.clear() parts = []; util.concat(parts,self.makeDrawerHolder()) util.concat(parts,self.makeShelf1()) doc=FreeCAD.activeDocument() grp=doc.addObject("App::DocumentObjectGroup", "Workbench") for p in parts: o = doc.addObject("Part::Feature", "Part") o.Shape = p grp.addObject(o) pass
def get_table_return_type(function): index, offset = cpp.find_function_name(function.name, function.tokens) return_type = util.concat(function.tokens[:index], ' ') if return_type in ['const ' + function.classname + ' & ', function.classname + ' & ']: return 'void ' if return_type == function.classname + ' ': return if returns_this(function): return 'void ' return util.concat(function.tokens[:index], ' ')
def find_function_name(name, tokens): ntokens_for_name_and_bracket = get_name_size_in_tokens(name) + 1 name_tokens = [ SimpleToken(tokens[i].spelling) for i in range(ntokens_for_name_and_bracket) ] if util.concat(name_tokens) == name + '(': return 0, ntokens_for_name_and_bracket for i in range(ntokens_for_name_and_bracket, len(tokens)): name_tokens.pop(0) name_tokens.append(SimpleToken(tokens[i].spelling)) if util.same_signature(util.concat(name_tokens, ' '), name + '('): return i - ntokens_for_name_and_bracket + 1, ntokens_for_name_and_bracket
def makeTrailerChassis(self): parts = []; util.concat(parts,self.makeFloor()) util.concat(parts,self.makeAxis()) util.concat(parts,self.makePivot()) util.concat(parts,self.makeBackAxle(2)) return parts;
def allWindows(): parts = [] util.concat(parts,gardenWindows()) util.concat(parts,windowDoor()) util.concat(parts,hallDoor()) util.concat(parts,workplanWindow()) return parts
def func_call(func_label, nargs): return_address = get_func_end_label(func_label) return concat( # push dummy value onto stack to allocate space for return value when nargs = 0 load_constant_into_d(0), push_d_onto_stack(), incr_sp(), push_stack_frame(return_address), set_segment_to_sp('ARG'), concat(load_constant_into_d(5), ['@ARG', 'M=M-D']), concat(load_constant_into_d(int(nargs) + 1), ['@ARG', 'M=M-D']), set_segment_to_sp('LCL'), goto(func_label), label(return_address), )
def visit_function(self,function_): function = copy.deepcopy(function_) tokens = function.tokens[:cpp.get_declaration_end_index(function.name, function.tokens)] index, offset = cpp.find_function_name(function.name, function.tokens) cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, tokens[:index]) function_name = cpp_file_parser.get_function_name_for_type_erasure(function) code = util.concat(tokens[:index], ' ') + function_name + ' ( ' cpp_file_parser.replace_in_tokens(function.classname, 'HandleBase', tokens[index:]) code += cpp_file_parser.const_specifier(function) + self.data.interface_type + ' & ' + self.data.interface_variable + ' ' for arg in cpp.get_function_arguments(function): if 'HandleBase' in arg.type(): cpp_file_parser.replace_in_tokens('HandleBase', self.data.handle_base_type, arg.tokens) code += ' , ' + arg.in_declaration() code += util.concat(tokens[cpp.get_arguments_end_index(function.name, tokens): cpp.get_declaration_end_index(function.name, tokens)], ' ') if code.startswith('virtual '): code = code[len('virtual '):] if code.endswith(' = 0'): code = code[:-len(' = 0')] code += 'override { ' contains_class_ref = util.concat(tokens[:index], ' ') in ['const ' + self.data.interface_type + ' & ', self.data.interface_type + ' & '] if not contains_class_ref: code += function.return_str code += 'value_ . ' + function.name + ' ( ' arguments = cpp.get_function_arguments(function) for arg in arguments: if arg.type() == 'const HandleBase & ': code += 'static_cast < ' + 'const ' + self.data.handle_type + ' & > ( ' code += arg.name() + ' ) . value_ ' elif arg.type() == 'HandleBase & ': code += 'static_cast < ' + self.data.handle_type + ' & > ( ' code += arg.name() + ' ) . value_ ' else: code += arg.in_single_function_call() if arg is not arguments[-1]: code += ' , ' code += ' ) ; ' if contains_class_ref: code += 'return ' + self.data.interface_variable + ' ;' code += ' }' self.scope.add(cpp_file_parser.get_function_from_text(function.classname, function_name, function.return_str, code))
def visit_function(self,function): if self.in_private_section: return code = util.concat(function.tokens[:cpp.get_declaration_end_index(function.name, function.tokens)], ' ') code += ' { assert ( ' + self.data.impl_member + ' ) ; ' + function.return_str if self.data.copy_on_write: if cpp.is_const(function): code += 'read ( ) . ' else: code += 'write ( ) . ' else: code += self.data.impl_member + ' -> ' code += cpp_file_parser.get_function_name_for_type_erasure(function) + ' ( * this ' arguments = cpp.get_function_arguments(function) for arg in arguments: code += ' , ' if self.scope.get_open_scope().name + ' &' in arg.type(): code += ' * ' + arg.in_single_function_call() + ' . ' + self.data.impl_member + ' ' elif self.scope.get_open_scope().name + ' *' in arg.type(): code += arg.in_single_function_call() + ' -> ' + self.data.impl_member else: code += arg.in_single_function_call() code += ' ) ; }' self.scope.add(cpp_file_parser.get_function_from_text(function.classname, function.name, function.return_str, code))
def visit_function(self,function_): function = copy.deepcopy(function_) name = cpp_file_parser.get_function_name_for_type_erasure(function) function_pointer_alias = name + '_function' function_pointer_alias_definition = 'using ' + function_pointer_alias + ' = ' index, offset = cpp.find_function_name(function.name, function.tokens) returns_self = util.contains(function.tokens[:index], function.classname) returns_self_by_reference = cpp.contains_sequence(function.tokens[:index], [cpp.SimpleToken(function.classname), cpp.SimpleToken('&')]) if returns_self: cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, function.tokens[:index]) function_pointer_alias_definition += util.concat(function.tokens[:index], ' ') function_pointer_alias_definition += '( * ) ( ' if returns_self_by_reference: interface_type = ('const ' if cpp.is_const(function) else '') + self.data.interface_type + ' &' function_pointer_alias_definition += interface_type + ' , ' function_pointer_alias_definition += 'void * ' arguments = cpp.get_function_arguments(function) adjust_table_arguments_tokens(function.classname, arguments) for arg in arguments: function_pointer_alias_definition += ' , ' + arg.in_declaration() # Seems to be redundant, TODO Verify #start_index = cpp_file_parser.get_arguments_end_index(function.name, function.tokens) #end_index = cpp_file_parser.get_declaration_end_index(function.name, function.tokens) #for token in function.tokens[start_index:end_index]: # if token.spelling not in ['const','noexcept']: # function_pointer_alias_definition += token.spelling + ' ' function_pointer_alias_definition += ');' self.scope.add(cpp_file_parser.get_alias_from_text(function_pointer_alias, function_pointer_alias_definition)) self.scope.add(cpp.Variable(function_pointer_alias + ' ' + name + ';'))
def id_str(self, u): def repl(char): if char in string.punctuation: return '_' else: return char return util.concat(map(repl, str(u)))
def adadelta(allparams, nat_stepsize, num_epochs, seq_len, num_seqs=None, rho=0.95, epsilon=1e-6, num_samples=1, permute=True): natparams, params = allparams[:1], allparams[1:] sum_gsq = zeros_like(params) # accumulated sq. grads sum_usq = zeros_like(params) # accumulated sq. updates accumulate = lambda a, b: add(scale(rho, a), scale(1 - rho, b)) for epoch in xrange(num_epochs): vals = [] batches, num_batches = split_into_batches(data, seq_len, num_seqs) for y in batches: val, grad = scale( 1. / num_datapoints, val_and_grad(y, num_batches, num_samples, *allparams)) natgrad, grad = grad[:1], grad[1:] sum_gsq = accumulate(sum_gsq, square(grad)) diag_scaling = div(sqrt(add_scalar(epsilon, sum_usq)), sqrt(add_scalar(epsilon, sum_gsq))) update = mul(diag_scaling, grad) sum_usq = accumulate(sum_usq, square(update)) natparams = add(natparams, scale(nat_stepsize, natgrad)) params = add(params, update) allparams = concat(natparams, params) vals.append(val) if callback: callback(epoch, vals, natgrad, allparams) return allparams
def func_def(func_label, nvars): return concat( label(func_label), set_segment_to_sp('LCL'), push_constant(_, '0') * int(nvars) # this can be optimized by writing 0 directly )
def visit_function(self, function): if self.in_private_section: return code = util.concat( function.tokens[:cpp.get_declaration_end_index( function.name, function.tokens)], ' ') code += ' { assert ( ' + self.data.impl_member + ' ) ; ' + function.return_str if self.data.copy_on_write: if cpp.is_const(function): code += 'read ( ) . ' else: code += 'write ( ) . ' else: code += self.data.impl_member + ' -> ' code += cpp_file_parser.get_function_name_for_type_erasure( function) + ' ( * this ' arguments = cpp.get_function_arguments(function) for arg in arguments: code += ' , ' if self.scope.get_open_scope().name + ' &' in arg.type(): code += ' * ' + arg.in_single_function_call( ) + ' . ' + self.data.impl_member + ' ' elif self.scope.get_open_scope().name + ' *' in arg.type(): code += arg.in_single_function_call( ) + ' -> ' + self.data.impl_member else: code += arg.in_single_function_call() code += ' ) ; }' self.scope.add( cpp_file_parser.get_function_from_text(function.classname, function.name, function.return_str, code))
def pop_heap(segment, index): return concat( load_constant_into_d(index), [f'@{segment}', 'D=M+D'], # load addr into D ['@R13', 'M=D'], # store addr into mem decr_sp(), load_stack_top_into_d(), ['@R13', 'A=M', 'M=D'])
def windowsToCut(): return util.concat( map(lambda x: x.box(),workplanWindow()), box(150,150,windowHeight) \ .transO(v(width-150, length-150, wallMinHeight - 50 - windowHeight)) )
def makeAxle(self,xOffset,directed=False): parts = [] pnt=Base.Vector(xOffset, TruckParams.wheel['width'],TruckParams.wheel['radius']-TruckParams.axle['side']/2) p = Part.makeBox(TruckParams.axle['side'],TruckParams.axle['width'],TruckParams.axle['side'],pnt) w1 = self.makeWheel(pnt + Base.Vector(TruckParams.axle['side']/2.0, -TruckParams.wheel['width'],TruckParams.axle['side']/2.0)) w2 = self.makeWheel(pnt + Base.Vector(TruckParams.axle['side']/2.0, TruckParams.axle['width'],TruckParams.axle['side']/2.0)) if directed: pntMidSteering = Base.Vector(pnt.x + TruckParams.axle['side']/2,pnt.y + TruckParams.axle['width']/2,pnt.z+TruckParams.axle['side']-TruckParams.steering['axlePenetration']) h = Part.makeCylinder(TruckParams.steering['stickRadius'],TruckParams.steering['axlePenetration']+TruckParams.axis['height'], pntMidSteering) p = p.cut(h) Part.show(h) self.p_axis = self.p_axis.cut(h) util.concat(parts,self.makeSteeringStick(pntMidSteering)) parts += [p,w1,w2] return parts
def func_return(): return concat( decr_sp(), load_stack_top_into_d(), ['@ARG', 'A=M', 'M=D'], # *ARG = D ['@ARG', 'D=M', '@SP', 'M=D+1'], # SP = ARG + 1 unpack_stack_frame(), ['@R13', 'A=M', '0;JMP'] # JMP *R13 )
def showAll(pnt=Base.Vector(0, 0, 0), dir=Base.Vector(0, 0, 1)): util.clear() parts = [partFromVectors([O, x(1000), xy(1000, 1000), y(1000)], O - z(thickness))] util.concat(parts, util.translate(chair(), x(0))) # util.concat(parts,util.translate(chair('sym'), x(1500))) # util.concat(parts,util.translate(chair('tri'), x(3000))) doc = FreeCAD.activeDocument() grp = doc.addObject("App::DocumentObjectGroup", "Workbench") print(parts) for p in parts: o = doc.addObject("Part::Feature", "Part") if(hasattr(p, 'delegate')): o.Shape = p.delegate else: o.Shape = p grp.addObject(o) pass
def nesterov(cost, params): grads = T.grad(cost=cost, wrt=params) vs = [shared_zeros_like(p) for p in params] def make_update(p, g, v): v_new = gamma*v - rate*g p_new = p + gamma**2*v - (1.+gamma)*rate*g return [(v, v_new), (p, p_new)] return concat(make_update(p, g, v) for p,g,v in zip(params, grads, vs))
def rmsprop(cost, params): grads = T.grad(cost=cost, wrt=params) sumsq = [shared_zeros_like(p) for p in params] def make_update(p, g, c): c_new = rho*c + (1.-rho)*g**2 p_new = p - rate * g / T.sqrt(c_new + epsilon) return [(c, c_new), (p, p_new)] return concat(make_update(p, g, c) for p, g, c in zip(params, grads, sumsq))
def momentum_sgd(cost, params): grads = T.grad(cost=cost, wrt=params) vs = [shared_zeros_like(p) for p in params] def make_update(p, g, v): v_new = gamma*v - rate*g p_new = p + v_new return [(v, v_new), (p, p_new)] return concat(make_update(p, g, v) for p,g,v in zip(params, grads, vs))
def showAll(pnt=Base.Vector(0, 0, 0), dir=Base.Vector(0, 0, 1)): parts = [] #util.clear() util.concat(parts,chair()) doc = FreeCAD.activeDocument() grp = doc.addObject("App::DocumentObjectGroup", "Workbench") util.concat(parts,side(doc,grp)) print(parts) for p in parts: o = doc.addObject("Part::Feature", "Part") if(hasattr(p, 'delegate')): o.Shape = p.delegate else: o.Shape = p grp.addObject(o) pass
def rmsprop(cost, params): grads = T.grad(cost=cost, wrt=params) sumsq = [shared_zeros_like(p) for p in params] def make_update(p, g, c): c_new = rho * c + (1. - rho) * g**2 p_new = p - rate * g / T.sqrt(c_new + epsilon) return [(c, c_new), (p, p_new)] return concat( make_update(p, g, c) for p, g, c in zip(params, grads, sumsq))
def nesterov(cost, params): grads = T.grad(cost=cost, wrt=params) vs = [shared_zeros_like(p) for p in params] def make_update(p, g, v): v_new = gamma * v - rate * g p_new = p + gamma**2 * v - (1. + gamma) * rate * g return [(v, v_new), (p, p_new)] return concat( make_update(p, g, v) for p, g, v in zip(params, grads, vs))
def momentum_sgd(cost, params): grads = T.grad(cost=cost, wrt=params) vs = [shared_zeros_like(p) for p in params] def make_update(p, g, v): v_new = gamma * v - rate * g p_new = p + v_new return [(v, v_new), (p, p_new)] return concat( make_update(p, g, v) for p, g, v in zip(params, grads, vs))
def visit_function(self,function_): function = copy.deepcopy(function_) tokens = function.tokens[:cpp.get_declaration_end_index(function.name, function.tokens)] index, offset = cpp.find_function_name(function.name, tokens) cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, tokens[:index]) function_name = cpp_file_parser.get_function_name_for_type_erasure(function) code = util.concat(tokens[:index], ' ') + function_name + ' ( ' cpp_file_parser.replace_in_tokens(function.classname, 'HandleBase', tokens[index:]) code += cpp_file_parser.const_specifier(function) + self.data.interface_type + ' & ' for arg in cpp.get_function_arguments(function): code += ' , ' + arg.in_declaration() code += util.concat(tokens[cpp.get_arguments_end_index(function.name, tokens): cpp.get_declaration_end_index(function.name, tokens)], ' ') if not code.startswith('virtual '): code = 'virtual ' + code if not code.endswith('= 0'): code += ' = 0' code += ' ;' self.scope.add(cpp_file_parser.get_function_from_text(function.classname, function_name, function.return_str, code))
def get_handle_interface_function(data, function): code = util.concat( function.tokens[:cpp_file_parser.get_declaration_end_index( function.name, function.tokens)], ' ') code += ' { assert ( ' + data.impl_member + ' ) ; ' + function.return_str + ' ' + data.impl_member + ' -> ' + function.name + ' ( ' arguments = cpp_file_parser.get_function_arguments(function) for arg in arguments: code += arg.in_single_function_call() if arg is not arguments[-1]: code += ' , ' return code + ' ) ; }'
def binary_comp(comp): return concat( decr_sp(), load_stack_top_into_d(), decr_sp(), ['@SP', 'A=M', 'D=M-D'], if_else( comparator=comp, true_block=['@SP', 'A=M', 'M=-1'], # recall: in HW -1 represents true, 0 false false_block=['@SP', 'A=M', 'M=0']), incr_sp())
def adadelta(cost, params): grads = T.grad(cost=cost, wrt=params) sum_gsq = [shared_zeros_like(p) for p in params] # accumulated sq. grads sum_usq = [shared_zeros_like(p) for p in params] # accumulated sq. updates def make_update(p, g, cg2, cu2): cg2_new = rho*cg2 + (1.-rho)*g**2 ud = -T.sqrt(cu2 + epsilon) / T.sqrt(cg2_new + epsilon) * g cu2_new = rho*cu2 + (1.-rho)*ud**2 p_new = p + ud return [(cg2, cg2_new), (cu2, cu2_new), (p, p_new)] return concat(make_update(p, g, g2, up2) for p, g, g2, up2 in zip(params, grads, sum_gsq, sum_usq))
def unpack_stack_frame(): """ precondition: LCL points to right after the stack frame postcondition: stack frame values written into lcl, arg, this, that return address is written into R13 """ return concat( pop_segment_pointer('THAT'), pop_segment_pointer('THIS'), pop_segment_pointer('ARG'), # set R13 = *(LCL - 2) before overwritting LCL ['@LCL', 'D=M', '@R13', 'M=D-1', 'M=M-1', 'A=M', 'D=M', '@R13', 'M=D'], pop_segment_pointer('LCL'), )
def apply_ctc_loss(floss, output, target: List[List[int]]): target_lengths = length_tensor(target) target = concat(target) target = torch.Tensor(target) target = target.long() target = target.view((-1, )) target = target.to(device) # Calculate lengths input_lengths = torch.full((output.shape[1], ), output.shape[0], dtype=torch.long) return floss(output, target, input_lengths, target_lengths)
def add_comments(scope, comments): new_content = [] for entry in scope.content: if cpp.is_namespace(entry): add_comment(new_content, 'namespace ' + entry.name, comments) add_comments(entry, comments) elif cpp.is_class(entry) or cpp.is_struct(entry): add_comment(new_content, entry.type + ' ' + entry.name, comments) add_comments(entry, comments) elif entry.type in [cpp.FUNCTION, cpp.CONSTRUCTOR, cpp.DESTRUCTOR, cpp.FUNCTION_TEMPLATE, cpp.ASSIGNMENT_OPERATOR]: add_comment(new_content, entry.get_declaration(), comments) elif entry.type == cpp.ALIAS: add_comment(new_content, util.concat(entry.tokens, ' '), comments) new_content.append(entry) scope.content = new_content
def visit_class(self,class_): if cpp.is_forward_declaration(class_): return util.concat(class_.tokens, ' ') str = '' self.current_class = class_.get_name( ) for entry in class_.content: if entry.type == cpp.ALIAS: self.current_class_aliases.append(entry.name) for entry in class_.content: str += entry.visit(self) self.current_class = None self.current_class_aliases = [] return str
def visit_class(self, class_): if cpp.is_forward_declaration(class_): return util.concat(class_.tokens, ' ') str = '' self.current_class = class_.get_name() for entry in class_.content: if entry.type == cpp.ALIAS: self.current_class_aliases.append(entry.name) for entry in class_.content: str += entry.visit(self) self.current_class = None self.current_class_aliases = [] return str
def adam(cost, params): grads = T.grad(cost=cost, wrt=params) ms = [shared_zeros_like(p) for p in params] vs = [shared_zeros_like(p) for p in params] t = theano.shared(floatX(1)) def make_update(p, g, m, v, t): m_new = beta_1*m + (1.-beta_1)*g v_new = beta_2*v + (1.-beta_2)*g**2 mhat = m / (1.-beta_1**t) vhat = v / (1.-beta_2**t) p_new = p - alpha * mhat / (T.sqrt(vhat) + epsilon) return [(m, m_new), (v, v_new), (p, p_new)] return [(t, t+1)] + concat( make_update(p, g, m, v, t) for p,g,m,v in zip(params, grads, ms, vs))
def process_variable_declaration(self,data,cursor): tokens = clang_util.get_tokens(data.tu, cursor) if tokens[-1].spelling != clang_util.semicolon and self.scope.get_open_scope().get_tokens(): tokens = clang_util.get_all_variable_tokens(tokens, self.scope.get_open_scope().get_tokens()) variable_declaration = util.concat(tokens, ' ') # in case that an underlying type is specified, # clang interprets enums at variables. # filter out these cases: if 'enum ' in variable_declaration: #TODO try to find a workaround for this return if clang_util.get_tokens(data.tu, cursor)[0].spelling == 'static': self.scope.add(cpp.StaticVariable(variable_declaration)) else: self.scope.add(cpp.Variable(variable_declaration))
def toso(graf): # implementasi pendekatan topological sort # dengan decrease and conquer (rekursi) # basis if(len(graf)==1): return graf # rekuren else: # akan dipilih simpul tanpa sisi masuk for data in graf: if len(data["masuk"])==0: simpul = data["simpul"] # decreasing decrease = updategraf(removefromgraf(graf, simpul), simpul) # conquering + recursion return concat([data], toso(decrease))
def adam(cost, params): grads = T.grad(cost=cost, wrt=params) ms = [shared_zeros_like(p) for p in params] vs = [shared_zeros_like(p) for p in params] t = theano.shared(floatX(1)) def make_update(p, g, m, v, t): m_new = beta_1 * m + (1. - beta_1) * g v_new = beta_2 * v + (1. - beta_2) * g**2 mhat = m / (1. - beta_1**t) vhat = v / (1. - beta_2**t) p_new = p - alpha * mhat / (T.sqrt(vhat) + epsilon) return [(m, m_new), (v, v_new), (p, p_new)] return [(t, t + 1)] + concat( make_update(p, g, m, v, t) for p, g, m, v in zip(params, grads, ms, vs))
def adadelta(cost, params): grads = T.grad(cost=cost, wrt=params) sum_gsq = [shared_zeros_like(p) for p in params] # accumulated sq. grads sum_usq = [shared_zeros_like(p) for p in params] # accumulated sq. updates def make_update(p, g, cg2, cu2): cg2_new = rho * cg2 + (1. - rho) * g**2 ud = -T.sqrt(cu2 + epsilon) / T.sqrt(cg2_new + epsilon) * g cu2_new = rho * cu2 + (1. - rho) * ud**2 p_new = p + ud return [(cg2, cg2_new), (cu2, cu2_new), (p, p_new)] return concat( make_update(p, g, g2, up2) for p, g, g2, up2 in zip(params, grads, sum_gsq, sum_usq))
def adam(allparams, nat_stepsize, stepsize, num_epochs, seq_len, num_seqs=None, b1=0.9, b2=0.999, eps=1e-8, num_samples=1): natparams, params = allparams[:1], allparams[1:] m = zeros_like(params) v = zeros_like(params) i = 0 accumulate = lambda rho, a, b: add(scale(1 - rho, a), scale(rho, b)) for epoch in xrange(num_epochs): vals = [] batches, num_batches = split_into_batches(data, seq_len, num_seqs) for y in batches: val, grad = scale( 1. / num_datapoints, val_and_grad(y, num_batches, num_samples, *allparams)) natgrad, grad = grad[:1], grad[1:] m = accumulate(b1, grad, m) # first moment estimate v = accumulate(b2, square(grad), v) # second moment estimate mhat = scale(1. / (1 - b1**(i + 1)), m) # bias correction vhat = scale(1. / (1 - b2**(i + 1)), v) update = scale(stepsize, div(mhat, add_scalar(eps, sqrt(vhat)))) natparams = add(natparams, scale(nat_stepsize, natgrad)) params = add(params, update) allparams = concat(natparams, params) vals.append(val) i += 1 if callback: callback(epoch, vals, natgrad, allparams) return allparams
def adam(gradfun, allparams, num_iters, step_size, b1=0.9, b2=0.999, eps=1e-8): natparams, params = allparams[:1], allparams[1:] m = zeros_like(params) v = zeros_like(params) i = 0 accumulate = lambda rho, a, b: add(scale(1-rho, a), scale(rho, b)) for i in xrange(num_iters): grad = gradfun(allparams, i) natgrad, grad = grad[:1], grad[1:] m = accumulate(b1, grad, m) # first moment estimate v = accumulate(b2, square(grad), v) # second moment estimate mhat = scale(1./(1 - b1**(i+1)), m) # bias correction vhat = scale(1./(1 - b2**(i+1)), v) update = scale(step_size, div(mhat, add_scalar(eps, sqrt(vhat)))) natparams = sub(natparams, scale(step_size, natgrad)) params = sub(params, update) allparams = concat(natparams, params) return allparams
def get_declaration(self): return util.concat(self.tokens[:get_declaration_end_index(self.name, self.tokens)], ' ')
def getParts(self): parts = [] util.concat(parts, self.p_axis) util.concat(parts, self.p_axles) return parts;
def addSteering(self, xOffset = 40): util.concat(self.p_axles,self.makeAxle(xOffset,True))
def returns_class_ref(classname,function): index, offset = find_function_name(function.name, function.tokens) return util.concat(function.tokens[:index], ' ') in ['const ' + classname + ' & ', classname + ' & ']
def visit_function(self, function_): function = copy.deepcopy(function_) tokens = function.tokens[:cpp.get_declaration_end_index( function.name, function.tokens)] index, offset = cpp.find_function_name(function.name, function.tokens) cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, tokens[:index]) function_name = cpp_file_parser.get_function_name_for_type_erasure( function) code = util.concat(tokens[:index], ' ') + function_name + ' ( ' cpp_file_parser.replace_in_tokens(function.classname, 'HandleBase', tokens[index:]) code += cpp_file_parser.const_specifier( function ) + self.data.interface_type + ' & ' + self.data.interface_variable + ' ' for arg in cpp.get_function_arguments(function): if 'HandleBase' in arg.type(): cpp_file_parser.replace_in_tokens('HandleBase', self.data.handle_base_type, arg.tokens) code += ' , ' + arg.in_declaration() code += util.concat( tokens[cpp.get_arguments_end_index(function.name, tokens):cpp. get_declaration_end_index(function.name, tokens)], ' ') if code.startswith('virtual '): code = code[len('virtual '):] if code.endswith(' = 0'): code = code[:-len(' = 0')] code += 'override { ' contains_class_ref = util.concat(tokens[:index], ' ') in [ 'const ' + self.data.interface_type + ' & ', self.data.interface_type + ' & ' ] if not contains_class_ref: code += function.return_str code += 'value_ . ' + function.name + ' ( ' arguments = cpp.get_function_arguments(function) for arg in arguments: if arg.type() == 'const HandleBase & ': code += 'static_cast < ' + 'const ' + self.data.handle_type + ' & > ( ' code += arg.name() + ' ) . value_ ' elif arg.type() == 'HandleBase & ': code += 'static_cast < ' + self.data.handle_type + ' & > ( ' code += arg.name() + ' ) . value_ ' else: code += arg.in_single_function_call() if arg is not arguments[-1]: code += ' , ' code += ' ) ; ' if contains_class_ref: code += 'return ' + self.data.interface_variable + ' ;' code += ' }' self.scope.add( cpp_file_parser.get_function_from_text(function.classname, function_name, function.return_str, code))
def is_defaulted(function): return len(function.tokens) > 5 and util.concat(function.tokens[-3:], ' ') == '= default ; '
def visit_function(self,function_): function = copy.deepcopy(function_) name = cpp_file_parser.get_function_name_for_type_erasure(function) index, offset = cpp.find_function_name(function.name, function.tokens) returns_self = util.contains(function.tokens[:index], function.classname) returns_self_by_reference = cpp.contains_sequence(function.tokens[:index], [cpp.SimpleToken(function.classname), cpp.SimpleToken('&')]) if returns_self: cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, function.tokens[:index]) arguments = copy.deepcopy(cpp.get_function_arguments(function)) wrapper = 'static ' + util.concat(function.tokens[:index], ' ') wrapper += name + ' ( ' if returns_self_by_reference: wrapper += cpp_file_parser.const_specifier(function) + self.data.interface_type + ' & ' + self.data.interface_variable + ' , ' wrapper += ' void * impl ' for arg in arguments: if cpp_file_parser.contains(function.classname, arg.tokens): wrapper += ' , void * ' + arg.tokens[-1].spelling else: wrapper += ' , ' + arg.in_declaration() wrapper += ' ) ' if 'noexcept' in function.tokens[cpp.get_arguments_end_index(function.name, function.tokens): cpp.get_declaration_end_index(function.name, function.tokens)]: wrapper += 'noexcept ' wrapper += '{ ' returns_class_ref = cpp.returns_class_ref(self.data.interface_type, function) if not returns_class_ref: wrapper += function.return_str + ' ' wrapper += 'static_cast ' const = 'const ' if cpp.is_const(function) else '' if self.for_reference_wrapper: wrapper += '< std :: reference_wrapper < Impl > * > ( impl ) -> get ( ) . ' else: wrapper += '< ' + const + ' Impl * > ( impl ) -> ' wrapper += function.name + ' ( ' for arg in arguments: if cpp_file_parser.contains(function.classname, arg.tokens): typename = util.concat(arg.tokens[:-1], ' ') typename = typename.replace(' ' + function.classname + ' ', ' Impl ') if self.for_reference_wrapper: if typename.endswith('* '): wrapper += '& ' wrapper += 'static_cast < std :: reference_wrapper < Impl > * > ( ' + arg.in_single_function_call() wrapper += ' ) -> get ( )' else: if typename.endswith('& '): wrapper += '* ' wrapper += 'static_cast< ' + ('const ' if cpp.is_const(function) else '') wrapper += 'Impl * > ( ' + arg.in_single_function_call() + ' )' else: wrapper += arg.in_single_function_call() if arg is not arguments[-1]: wrapper += ' , ' wrapper += ' ) ; ' if returns_class_ref: wrapper += 'return interface ; ' wrapper += '}' self.scope.add(cpp_file_parser.get_function_from_text('execution_wrapper', name, function.return_str, wrapper))
def test(model, test_X, test_y, label_set): data_set_size = len(test_X) pred_res = model.predict(test_X) if type(test_y) is list: top_nbs = [[2, 10, 10, 6], [2, 10, 10, 10]] thresholds = [[0.2,0.2,0.2,0.2], [0.3,0.3,0.3,0.3],[0.4, 0.4, 0.4, 0.4]] # top_nbs = product(range(6,11), repeat=4) # thresholds = [[0.2,0.2,0.2,0.2],[0.4,0.4,0.4,0.3]] test_y = concat(test_y) test_y = [flatten([n_hot_decoder(j, label_set[idx]) for idx,j in enumerate(i)]) for i in test_y] pred_res = concat(pred_res) else: top_nbs = [5, 10] thresholds = np.arange(0,0.5,0.2) test_y = [n_hot_decoder(i, label_set) for i in test_y] top_recall_f1 = (0,None,None) top_f1 = (0,None,None) for top_nb in top_nbs: for threshold in thresholds: decode_res = decode(pred_res, label_set, top_nb, threshold) precision = 0 recall = 0 test_len = 0.0 pred_len = 0.0 n1 = 0 n2 = 0 for i in range(data_set_size): test_set = set(test_y[i]) pred_set = set(decode_res[i]) #print(test_set) test_len += len(test_set) pred_len += len(pred_set) if len(pred_set) == 0 and len(test_set) == 0: precision += 1.0 recall += 1.0 continue if len(test_set) == 0 or len(pred_set)== 0: continue common_set = test_set & pred_set cnt = len(common_set) precision += float(cnt) / len(pred_set) recall += float(cnt) / len(test_set) precision /= data_set_size recall /= data_set_size test_len /= data_set_size pred_len /= data_set_size f1 = 2 * precision * recall / (precision + recall) if recall+f1 > top_recall_f1[0]: top_recall_f1 = (recall+f1, top_nb, threshold) if f1 > top_f1[0]: top_f1 = (f1, top_nb, threshold) print('(top %s, threshold %s) Precision: %.3lf' % (top_nb, threshold, precision)) print('(top %s, threshold %s) Recall: %.3lf' % (top_nb, threshold, recall)) print('(top %s, threshold %s) f1: %.3lf' % (top_nb, threshold, f1)) print('(top %s, threshold %s) test_len %.2lf, pred_len %.2lf\n' % (top_nb, threshold, test_len, pred_len)) print('top (recall+f1)', top_recall_f1) print('top f1', top_f1)
def showAll(self,pnt=Base.Vector(0,0,0),dir=Base.Vector(0, 0, 1)): parts = []; util.concat(parts,self.makeFloor()) util.concat(parts,self.makeBackAxle()) util.concat(parts,self.makeFront()) util.concat(parts,self.makeBack()) util.concat(parts,self.makeTop()) util.concat(parts,self.makePlate()) util.concat(parts,self.makeAxis()) util.concat(parts,self.makeSteeringAxle()) util.concat(parts,self.makeBackAxle()) util.concat(parts,self.makeSteeringStick()) util.concat(parts,self.make5Wheel()) util.concat(parts,self.makeSeats()) doc=FreeCAD.activeDocument() grp=doc.addObject("App::DocumentObjectGroup", "Tractor") for p in parts: o = doc.addObject("Part::Feature", "Part") o.Shape = p grp.addObject(o) pass
def makeSide(self): parts = [] util.concat(parts,self.makeMane()) util.concat(parts,self.makeHead()) util.concat(parts,self.makeVCurveL()) util.concat(parts,self.makePatin()) util.concat(parts,self.makeVCurveR()) util.concat(parts,self.makeBack()) w = Part.Wire(parts) f = Part.Face(w) p = f.extrude(Base.Vector(0,self.thickness,0)) return p
def binary_op(op): return concat(decr_sp(), load_stack_top_into_d(), decr_sp(), ['@SP', 'A=M', f'M=M{op}D'], incr_sp())
def unary_op(op): return concat(decr_sp(), ['@SP', 'A=M', f'M={op}M'], incr_sp())
#!/usr/bin/python from asyncio import run from config import bar from util import async_map, drain, concat def echo(text): print(text, flush=True) if __name__ == '__main__': run(drain(async_map(echo, concat(bar))))