def main(dataset = 'proton-beam', read_file = False, rand_shuffle = None): global mat, rel, turk_data, turk_data_uncer, turk_data_id, dic_workers if read_file and dataset == 'RCT': f = open('start_RCT.pkl') (turk_data_id, rel) = pickle.load(f) f.close() return if dataset.startswith('sim'): # simulated data (rel, turk_data_id, dic_workers) = simulate(dataset) return util.main(dataset) mat = util.mat rel = util.rel if dataset.startswith('RCT'): turk_data_id = sorted(util.turk_dic.items()) turk_data_id = map(lambda x: zip(*x), list(zip(*turk_data_id)[1])) turk_data_id = map(lambda a: ( list(a[0]), list(a[1]) ), turk_data_id ) else: util2.main(dataset, util.turk_dic) turk_data = util2.turk_data turk_data_uncer = util2.turk_data_uncer turk_data_id = util2.turk_data_id if rand_shuffle != None: random.shuffle(turk_data_id, lambda : rand_shuffle) random.shuffle(rel, lambda : rand_shuffle)
def main(dataset='proton-beam'): global mat, rel, turk_data, turk_data_uncer util.main(dataset) mat = util.mat rel = util.rel util2.main(dataset, util.turk_dic) turk_data = util2.turk_data turk_data_uncer = util2.turk_data_uncer
def test_remove_my_folder_cmd(self): # folder present; would have been removed self.assertTrue( util.main(['remove_my_folder', 'CCDev/tmp', '--dry-run']).startswith('=== ' + self._home + '/Library/CCDev/tmp:')) # syntax errors for invalid input with self.assertRaises(SyntaxError): util.main(['rf', 'aFolder', '-p', "parent", '--dry-run']) with self.assertRaises(SyntaxError): util.main([])
@classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the transparent latch. Note that you MUST have multiclock on in the sby file, because there is more than one clock in the system -- the default formal clock and the local clock inside the transparent latch. """ m = Module() m.submodules.latch = latch = TransparentLatch(32) m.d.sync += Cover((latch.data_out == 0xAAAAAAAA) & (latch.le == 0) & (Past(latch.data_out, 2) == 0xBBBBBBBB) & (Past(latch.le, 2) == 0)) with m.If(latch.n_oe == 1): m.d.comb += Assert(latch.data_out == 0) with m.If((latch.n_oe == 0) & (latch.le == 1)): m.d.comb += Assert(latch.data_out == latch.data_in) with m.If((latch.n_oe == 0) & Fell(latch.le)): m.d.sync += Assert(latch.data_out == Past(latch.data_in)) return m, [latch.data_in, latch.le, latch.n_oe] if __name__ == "__main__": main(TransparentLatch)
""" from openmdao.main.api import Component from openmdao.lib.datatypes.api import Float # lines will be auto-indented by ace editor class Plane(Component): x1 = Float(0.0, iotype='in') x2 = Float(0.0, iotype='in') x3 = Float(0.0, iotype='in') f_x = Float(0.0, iotype='out') """, ) # Back to workspace. browser.close() browser.switch_to_window(workspace_window) # Drag over Plane. workspace_page.show_dataflow("top") workspace_page.set_library_filter("In Project") workspace_page.add_library_item_to_dataflow("plane.Plane", "plane") # Clean up. closeout(projects_page, project_info_page, project_dict, workspace_page) if __name__ == "__main__": main()
] m.d.comb += [ self.output[0].eq(c[0].output), self.output[1].eq(c[1].output), self.output[2].eq(c[2].output), self.output[3].eq(c[3].output), ] return m @classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the Cell4x4 module.""" m = Module() m.submodules.c = c = cls() m.d.comb += Cover((c.output[0] == c.input[5]) & (c.output[1] == c.input[6]) & (c.output[2] == c.input[9]) & (c.output[3] == c.input[10]) & (c.output != 0)) with m.If((c.output == 0b1111) & (c.input[5:7] == 0b11) & (c.input[9:11] == 0b11)): m.d.comb += Assert(c.input == 0b0000011001100000) return m, [c.input] if __name__ == "__main__": main(Cell4x4)
with m.If(middle): with m.If((neighbors == 2) | (neighbors == 3)): m.d.comb += self.output.eq(1) with m.Else(): with m.If(neighbors == 3): m.d.comb += self.output.eq(1) return m @classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the Cell3x3 module.""" m = Module() m.submodules.c = c = cls() s = 0 for n in range(9): if n != 4: s += c.input[n] with m.If(s == 3): m.d.comb += Assert(c.output) with m.If(s == 2): m.d.comb += Assert(c.output == c.input[4]) return m, [c.input] if __name__ == "__main__": main(Cell3x3)
import sys from util import main if len(sys.argv) < 2: print("No verb supplied") else: verb = sys.argv[1] main(verb)
self.my_input = Signal() # Outputs self.my_output = Signal() def elaborate(self, _: Platform) -> Module: """Implements the logic for my module.""" m = Module() m.d.comb += self.my_output.eq(self.my_input) return m @classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for my module.""" m = Module() m.submodules.my_class = my_class = cls() # Make sure that the output is always the same as the input m.d.comb += Assert(my_class.my_input == my_class.my_output) # Cover the case where the output is 1. m.d.comb += Cover(my_class.my_output == 1) return m, [my_class.my_input] if __name__ == "__main__": main(MyClass)
m.submodules.shifter = shifter = ShiftCard() shamt = Signal(5) m.d.comb += shamt.eq(shifter.data_y[:5]) with m.If(shamt > 0): m.d.comb += Cover(shifter.data_z == 0xFFFFAAA0) with m.Switch(shifter.alu_op): with m.Case(AluOp.SLL): m.d.comb += Assert( shifter.data_z == (shifter.data_x << shamt)[:32]) with m.Case(AluOp.SRL): m.d.comb += Assert(shifter.data_z == (shifter.data_x >> shamt)) with m.Case(AluOp.SRA): m.d.comb += Assert( shifter.data_z == (shifter.data_x.as_signed() >> shamt)) with m.Default(): m.d.comb += Assert(shifter.data_z == 0) return m, [ shifter.alu_op, shifter.data_x, shifter.data_y, shifter.data_z ] if __name__ == "__main__": main(ShiftCard)
self._faster = faster def elaborate(self, _: Platform) -> Module: """Implements the logic of an N-input 32-bit multiplexer.""" m = Module() if self._faster: m.d.comb += self.y.eq(0) for i in range(self.N): with m.If(~self.n_sel[i]): m.d.comb += self.y.eq(self.a[i]) return m buffs = [IC_buff32() for _ in range(self.N)] m.submodules += buffs for i in range(self.N): m.d.comb += buffs[i].a.eq(self.a[i]) m.d.comb += buffs[i].n_oe.eq(self.n_sel[i]) combine = 0 for i in range(0, self.N): combine |= buffs[i].y m.d.comb += self.y.eq(combine) return m if __name__ == "__main__": main(IC_7416244)
from torch.autograd import Variable import idm class RandPol: def __init__(self, args, model): self.model = model self.args = args def policy(self, i): if i % self.args.light_ticks == 0: self.model.set_phase( Variable(self.model.random_phase(), volatile=True)) if __name__ == '__main__': import util util.main(RandPol)
# OE_B = 1100011 # OE_J = 1100111 | 1101111 # OE_SYS = 1110011 m.d.comb += [ self.i_n_oe.eq(1), self.s_n_oe.eq(1), self.u_n_oe.eq(1), self.b_n_oe.eq(1), self.j_n_oe.eq(1), self.sys_n_oe.eq(1), ] with m.Switch(self.opcode): with m.Case(0b0000011, 0b0001111, 0b0010011): # I m.d.comb += self.i_n_oe.eq(0) with m.Case(0b0100011): # S m.d.comb += self.s_n_oe.eq(0) with m.Case(0b0010111, 0b0110111): # U m.d.comb += self.u_n_oe.eq(0) with m.Case(0b1100011): m.d.comb += self.b_n_oe.eq(0) with m.Case(0b1100111, 0b1101111): m.d.comb += self.j_n_oe.eq(0) with m.Default(): m.d.comb += self.sys_n_oe.eq(0) return m if __name__ == "__main__": main(IC_GAL_imm_format_decoder)
from summaries import Summary from rg import mc import torch from torch.autograd import Variable class ConstPolicy: def __init__(self, opts, model): self.opts = opts self.model = model self.scores = [] self.score_summary = Summary(opts.vis, "Const Score") greens = Variable(mc(torch.ones(model.graph.intersections))) if opts.render: greens.volatile = True # self.phase = torch.stack((greens, 1 - greens), 1) self.phase = torch.stack((1 - greens, greens), 1) self.episode = 0 def policy(self, i): if (i % self.opts.episode_ticks) == (-1 % self.opts.episode_ticks): self.scores.append(self.model.score().data) if self.episode % self.opts.refresh_rate == 0 and len(self.scores) > 1: self.score_summary.hist(torch.cat(self.scores, 0)) self.episode += 1 if i % self.opts.episode_ticks == 0: self.model.reset() if i % self.opts.light_ticks == 0: self.model.set_phase(self.phase) if __name__ == '__main__': util.main(ConstPolicy)
@with_setup(setup_server, teardown_server) def test_generator(): for _test, browser in generate(__name__): yield _test, browser def _test_global(browser): # 'global' view should be populated (originally was blank). projects_page, project_info_page, project_dict, workspace_page = startup( browser) filename = pkg_resources.resource_filename('openmdao.gui.test.functional', 'rosen_suzuki.py') workspace_page.add_file(filename) # Add a NestedSimulation. workspace_page.set_library_filter('In Project') workspace_page.add_library_item_to_dataflow( 'rosen_suzuki.NestedSimulation', 'nested', offset=(300, 300)) # Verify full workflow shown. workspace_page('workflow_tab').click() eq(len(workspace_page.get_workflow_figures()), 3) eq(len(workspace_page.get_workflow_component_figures()), 6) # Clean up. closeout(projects_page, project_info_page, project_dict, workspace_page) if __name__ == '__main__': main()
return m @classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the active high 74182 chip. Used with an active high 74181. """ m = Module() m.submodules.clu = clu = IC_74182_active_high() m.submodules.alu = alu = IC_74181() add_mode = (alu.s == 9) & (alu.m == 0) m.d.comb += Assume(add_mode) m.d.comb += [ clu.x[0].eq(alu.x), clu.y[0].eq(alu.y), clu.x[1:].eq(0), clu.y[1:].eq(0), clu.n_carryin.eq(alu.n_carryin), ] m.d.comb += Assert(clu.n_carryout_x == alu.n_carryout) return m, clu.ports() + alu.ports() if __name__ == "__main__": main(IC_74182_active_high)
neg1 = Signal(64) m.d.comb += neg1.eq(-1) # n # 1111111111000000 # mask = -1 << n # 0000000000111111 # lower_mask = ~(-1 << n) # 0000000001000000 # 1 << n mask = Signal(64) m.d.comb += mask.eq(neg1 << enc.o) lower_mask = ~mask m.d.comb += self.output3.eq((~self.input & mask) | (self.input & lower_mask) | (1 << enc.o)) return m @classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the Negate module.""" m = Module() m.submodules.c = c = cls() m.d.comb += Assert(c.output1 == c.output2) m.d.comb += Assert(c.output2 == c.output3) m.d.comb += Assert(c.output1[63] == (c.output1.as_signed() < 0)) return m, [c.input] if __name__ == "__main__": main(Negate)
ult.eq(ucmp.lt), ] is_a_neg = self.a[15] is_b_neg = self.b[15] with m.If(~is_a_neg & ~is_b_neg): m.d.comb += self.lt.eq(ult) with m.Elif(is_a_neg & ~is_b_neg): m.d.comb += self.lt.eq(1) with m.Elif(~is_a_neg & is_b_neg): m.d.comb += self.lt.eq(0) with m.Else(): m.d.comb += self.lt.eq(ult) return m @classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the SignedComparator module.""" m = Module() m.submodules.c = c = cls() m.d.comb += Assert(c.lt == (c.a.as_signed() < c.b.as_signed())) return m, [c.a, c.b] if __name__ == "__main__": main(SignedComparator)
from decimal import getcontext, Decimal from util import main def Bernoulli( n: int = 100, prec: int = 100 ) -> Decimal: # https://en.wikipedia.org/wiki/E_(mathematical_constant) """ not effient at all at n = 1000000000000000000000000000 return 2.7182818284590452353602874 69993521583527724476019815... """ getcontext().prec = prec return (1 + Decimal(1) / Decimal(n))**n def factorial_method(n: int = 100, prec: int = 100) -> Decimal: getcontext().prec = prec sum = Decimal(0) accumulate_factorial = 1 for i in range(1, n): sum = sum + Decimal(1) / Decimal(accumulate_factorial) accumulate_factorial = accumulate_factorial * i return sum if __name__ == "__main__": fn_list = [Bernoulli, factorial_method] main(fn_list, "e")
#!/usr/bin/env python # -*- coding: utf-8 -*- import rospy from util import Dummy, main """ Tree Structure --------------------------------- (state) ( ): registered { }: unregistered """ def get_instance(): return Dummy('root') if __name__ == '__main__': rospy.init_node('test_single_state', log_level=rospy.DEBUG) main(get_instance())
def test_parse_cmdlist_cmd(self): with self.assertRaises(SyntaxError): util.main(['ps', 'abc'])
def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the NextDay module.""" m = Module() m.submodules.nd = nd = cls() # We don't have to create a signal here. Using is_zero is like just copying the logic. is_zero = ((nd.next_year == 0) & (nd.next_month == 0) & (nd.next_day == 0)) m.d.comb += Assert(nd.invalid == is_zero) all_nonzero = ((nd.next_year != 0) & (nd.next_month != 0) & (nd.next_day != 0)) m.d.comb += Assert(all_nonzero | is_zero) with m.If(~nd.invalid): with m.If(nd.day == 31): m.d.comb += Assert(nd.next_day == 1) with m.If((nd.month == 12) & (nd.day == 31)): m.d.comb += Assert(nd.next_month == 1) with m.If(((nd.year % 2) == 1) & (nd.month == 2) & (nd.day == 29)): m.d.comb += Assert(nd.invalid) m.d.comb += Cover((nd.next_month == 2) & (nd.next_day == 29)) return m, [nd.year, nd.month, nd.day] if __name__ == "__main__": main(NextDay)
import app as app #os.environ['LB-TESTING'] = '1' # setup files # store testing copies in temp/ folder #ConfigurationDictFileDatabaseMock().write() #ConfigurationDictFileTableMock().write() #TemplateFileCreateTableMock().write() # Mockups #mockups_generate.main() #mockups.main() # util classes util.main() app_settings.main() # this runs AppSettingsTests # link.main() step.main() # helper # file classes file.main() script_file.main() #template_file.main()
# for writing now contains the data we wrote. with m.If(Rose(mem.n_wr)): m.d.comb += Assert(mem._mem[Past(mem.addr)] == Past(mem.data_in)) # Pick an address, any address. check_addr = AnyConst(5) # We assert that unless that address is written, its data will not # change. To know when we've written the data, we have to create # a clock domain to let us save the data when written. saved_data_clk = ClockDomain("saved_data_clk") m.domains.saved_data_clk = saved_data_clk saved_data_clk.clk = mem.n_wr saved_data = Signal(32) with m.If(mem.addr == check_addr): m.d.saved_data_clk += saved_data.eq(mem.data_in) with m.If(Initial()): m.d.comb += Assume(saved_data == mem._mem[check_addr]) m.d.comb += Assume(mem.n_wr == 1) with m.Else(): m.d.comb += Assert(saved_data == mem._mem[check_addr]) return m, [mem.addr, mem.data_in, mem.n_wr, mem.n_oe] if __name__ == "__main__": main(AsyncMemory)
m.submodules += s sync_clk = ClockSignal("sync") sync_rst = ResetSignal("sync") with m.If(s.n_oe): m.d.comb += Assert(s.q == 0) with m.Else(): with m.If(~Past(s.n_oe) & ~Past(s.load)): m.d.comb += Assert(s.q == Past(s.q)) with m.If(Past(s.load) & Rose(clk)): m.d.comb += Assert(s.q == Past(s.d)) with m.If(~Past(s.n_oe) & Fell(clk)): m.d.comb += Assert(s.q == Past(s.q)) # Make sure the clock is clocking m.d.comb += Assume(sync_clk == ~Past(sync_clk)) # Don't want to test what happens when we reset. m.d.comb += Assume(~sync_rst) m.d.comb += Assume(~ResetSignal("ph")) return m, [sync_clk, sync_rst, s.n_oe, s.load, s.d] if __name__ == "__main__": main(IC_reg32_with_mux)
@classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the ToPennies module.""" m = Module() m.submodules.to_pennies = to_pennies = cls() m.d.comb += Cover((to_pennies.pennies == 37) & (to_pennies.nickels == 3) & (to_pennies.dimes == 10) & (to_pennies.quarters == 5) & (to_pennies.dollars == 2)) m.d.comb += Cover(to_pennies.pennies_out == 548) m.d.comb += Cover((to_pennies.pennies_out == 64) & (to_pennies.nickels == 2 * to_pennies.dimes) & (to_pennies.dimes > 0)) m.d.comb += Assert((to_pennies.pennies_out % 5) == (to_pennies.pennies % 5)) with m.If(to_pennies.pennies == 0): m.d.comb += Assert((to_pennies.pennies % 5) == 0) return m, [to_pennies.pennies, to_pennies.nickels, to_pennies.dimes, to_pennies.quarters, to_pennies.dollars] if __name__ == "__main__": main(ToPennies)
class Counter(Elaboratable): """Logic for the Counter module.""" def __init__(self): self.count = Signal(4, reset=1) def elaborate(self, _: Platform) -> Module: """Implements the logic for the Counter module.""" m = Module() with m.If(self.count == 9): m.d.sync += self.count.eq(1) with m.Else(): m.d.sync += self.count.eq(self.count + 1) return m @classmethod def formal(cls) -> Tuple[Module, List[Signal]]: """Formal verification for the Counter module.""" m = Module() m.submodules.c = c = cls() m.d.comb += Assert((c.count >= 1) & (c.count <= 9)) m.d.comb += Cover(c.count == 3) return m, [] if __name__ == "__main__": main(Counter)
order[inp_key] = order[key] + 1 change = True if not change: break for fuel in range(2700000, 3300000): if fuel % 10000 == 0: print("progress", fuel) inventory = {'FUEL': fuel} for _, chemical in sorted([(value, key) for key, value in order.items()]): if chemical in inventory: reactions = math.ceil(inventory[chemical] / target_output[chemical]) del inventory[chemical] for source, input_amount in inputs[chemical]: inventory[source] = inventory.get( source, 0) + input_amount * reactions if inventory['ORE'] > 1_000_000_000_000: print("part 2 answer", fuel - 1) break print("part 2 answer", inventory) if __name__ == '__main__': util.main(__file__, part1, part2)
def run(options, args): port = options.port util.main(port)
def home(): return render_template('table.html', data=util.main())
enqueue(State(s.next_word(), rhs, s.loc)) def scan(s): if s.loc + 1 <= len(sentence) and sentence[s.loc] == s.next_word(): enqueue(s.incr_word(s.loc + 1)) def complete(s): for c in [ c for c in chart if (not c.finished()) and c.next_word() == s.lhs and c.loc == s.origin ]: enqueue(c.incr_word(s.loc)) for rhs in grammar['START']: enqueue(State('START', rhs, 0)) while not work.empty(): (loc, s) = work.get() if not s.finished(): if s.next_word() in grammar: predict(s) else: scan(s) else: complete(s) return chart if __name__ == '__main__': main(parse)
if opts.visdom: from summaries import Summary self.avg_score = Summary(opts.vis, "Score") self.grads = Summary(opts.vis, "Grads") self.optimizer = optim.Adam(self.net.parameters(), lr=1e-4) self.optimizer.zero_grad() def policy(self, i): episode = i // self.opts.episode_ticks k = i // self.opts.light_ticks if (i % self.opts.episode_ticks) == (-1 % self.opts.episode_ticks): print("Score is", self.model.score.data[0]) self.model.score.backward(self.dreward) if episode % self.opts.summary_rate == 0: if self.opts.visdom: gs = [p.grad.data.cpu().view(-1) for p in self.net.parameters()] self.grads.hist(torch.cat(gs,0)) self.avg_score.plot(torch.Tensor([episode]), self.model.score.data.cpu()) if episode % self.opts.step_rate == 0: self.optimizer.step() self.optimizer.zero_grad() if i % self.opts.episode_ticks == 0: self.model.reset() if i % self.opts.light_ticks == 0: pos = self.model.obs().unsqueeze(0) logits, action = self.net(pos, temp=to_temp(episode)) self.model.set_phase(action) if __name__ == '__main__': util.main(TrainedPolicy)
simCoords = self.creaSimetrico(coor) self.p1.translation.setValue(coor) self.p2.translation.setValue(simCoords) self.segmento = Segmento(coor,simCoords) self.p3.translation.setValue(self.segmento.eval(.5)) self.animaLinea(1.0) def getValue(self): return self.p1.translation.getValue() def getValueReflex(self): return self.p2.translation.getValue() if __name__ == "__main__": app = main(sys.argv) window = SoQtExaminerViewer() root = SoSeparator() sim = Simetria() ptos = [] ptos.append( PuntoReflejado((1, 0, 0), sim) ) ptos.append( PuntoReflejado((0, 1, 0), sim) ) ptos.append( PuntoReflejado((0, 0, 1), sim) ) for p in ptos: root.addChild(p) p.start(40) o = creaPunto(.02, (.5, .5, .5) ) root.addChild(o) window.setSceneGraph(root) window.show() SoQt.mainLoop()