def test(): import numpy as np oracle = lambda x: x.T oracle = transpose3 ex_set = [] example = np.array([[1, 2], [1, 2]]) # TODO: to add more than one formal parameter make sure to make first element of tuple a list ex_set.append((example, oracle(example))) input_shape = example.shape components = Components( { 'transpose': 1, 'eye_like': 1, 'ones_like': 0, 'multiply': 0, 'add': 0, 'matmul': 0 }, input_shape) f = Formulate(ex_set, components.get_list()) model = f.synthesize() f.Lval2Prog(model, components)
def __init__(self): self.nets = list() self.components = Components() self.component_instances = list() self.design_attributes = DesignAttributes() self.version = dict() self.set_version("0.1.0", "Upverter converter")
def __init__(self): self.server = Flask(__name__) self.app = dash.Dash( name="dashboard", server=self.server, external_stylesheets=[dbc.themes.BOOTSTRAP], routes_pathname_prefix="/somethingsomethin/", suppress_callback_exceptions=True, ) #makes sure that the login is required for data vis for view_func in self.server.view_functions: if view_func.startswith("/dashboard/"): print(view_func) self.server.view_functions[view_func] = login_required( self.server.view_functions[view_func]) self.comp = Components() # self.pi = Pi_Control() self.data = {} self.latLng = {} self.prev_data = {} self.default_plant_img = "https://ichef.bbci.co.uk/news/976/cpsprodpb/10ECF/production/_107772396_treesmall.jpg" self.water_button_counter = 0 self.suggestions = None #ending variables #basic layout for the dash app dashboard self.app.layout = html.Div([ self.comp.navbar, ])
def test_synthesize(): oracle = lambda x: x + x ogis(oracle) return ex_set = [] example = np.array([1, 2, 3, 4]).reshape((2, 2)) example = np.array([[1]]) ex_set.append((example, oracle(example))) input_shape = example.shape components = Components( { 'transpose': 0, 'eye_like': 0, 'ones_like': 0, 'multiply': 0, 'add': 1, 'matmul': 0 }, input_shape).get_list() program = synthesize(ex_set, components) print(program)
def start_level(self, level): self.components = Components(self, level) self.route = self.calculate_route() self.components.new_runner(self) self.level_name = f'Level {level[5:]}' self.wealth = 100 self.score = 0 self.start_time = datetime.datetime.now()
def bridge(G, v, u): G[v][u] = 0 G[u][v] = 0 components = Components() [comp, nr] = components.find_components(G) G[v][u] = 1 G[u][v] = 1 if comp[v] != comp[u]: return True else: return False
def test_find_comp(): print("\nTask 3: Connected components:\n") G = [[0, 0, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0]] components = Components() [comp, nr] = components.find_components(G) comp_lists = [[] for x in range(nr)] for v in range(len(G)): comp_lists[comp[v] - 1].append(v) for count, item in enumerate(comp_lists): print(count + 1, item) print("Biggest connected component: " + str(components.max_component)) print("has " + str(components.max_count) + " vertices")
def rotated_components(components, angle): ''' ... Args: components: angle: Returns: ''' img = components.img stencil = components.get_stencil() rotated_stencil = rotate(stencil, angle*180/np.pi, order=0) rotated_image = np.clip(rotate(img, angle*180/np.pi, order=2), 0, 1) boxes = get_bboxes(rotated_stencil) return Components(boxes, rotated_image, stencil=rotated_stencil)
def choose_biggest_comp(self): adjacency = self.adj.tolist() components = Components() [comp, nr] = components.find_components(adjacency) for v in range(self.n): if comp[v] == components.max_component: self.biggest_comp.append(v) for i in reversed(range(self.n)): if i not in self.biggest_comp: adjacency.pop(i) else: for j in reversed(range(self.n)): if j not in self.biggest_comp: adjacency[i].pop(j) self.n -= (self.n - len(self.biggest_comp)) self.adj = np.array(adjacency)
def ogis(oracle): ex_set = [] ishape = (2, 2) components = Components( { 'transpose': 0, 'eye_like': 1, 'ones_like': 0, 'multiply': 0, 'add': 1, 'matmul': 0 }, ishape) ex_set.append((np.ones((2, 2)), oracle(np.ones((2, 2))))) example = np.eye(ishape[0]) program_candidate = None while example is not None: ex_set.append((example, oracle(example))) f = Formulate(ex_set, components.get_list()) satisfying_constraints = f.Behave_E() s = z3.Solver() s.add(satisfying_constraints) if (s.check() == z3.sat): I, unique_constraints = f.dist_constraint() s2 = z3.Solver() s2.add(unique_constraints) if (s2.check() == z3.sat): print("nonunique; getting new example") model = s2.model() example = np.array([[model.evaluate(i) for i in il] for il in I]) else: print("unsat") #done program_candidate = f.Lval2Prog(s.model(), components) break else: print("No valid program candidate found") return False return program_candidate
def choose_biggest_comp(G): biggest_comp = [] components = Components() [comp, nr] = components.find_components(G.adjacency) adj = G.adjacency.tolist() for v in range(G.size): if comp[v] == components.max_component: biggest_comp.append(v) for i in reversed(range(G.size)): if i not in biggest_comp: adj.pop(i) else: for j in reversed(range(G.size)): if j not in biggest_comp: adj[i].pop(j) G.size -= (G.size - len(biggest_comp)) G.adjacency = np.array(adj)
def __init__(self): self._module_info = Components(MODULE_INFO) self._components = set() self._rolled_up_components = {} self._rollup_counters = {} self.set_version('min')
def before_all(context): context.config = TestConfig() context.config.driver = None context.config.components = Components()
from tkinter import * from components import Components app = Tk() app.title("Faça Login") app.minsize("300", "400") app.maxsize("500", "400") app.geometry("500x400") app.configure(background="#393939") Components().render_components(app) app.mainloop()
from json import load as json_load from utime import sleep from components import Components from network_wrapper import NetworkWrapper with open('config.json') as json_data: config = json_load(json_data) nw = NetworkWrapper(wifi_config=config['wifi'], ubidots_config=config['ubidots']) components = Components(config) bottle_capacity = config['bottle']['bottle_capacity_ml'] while True: sensors_data = components.measure_from_periodic_sensors() sensors_data['bottle-capacity'] = bottle_capacity nw.try_sending_sensors_data(sensors_data) sleep(config['behavior']['measurements_interval_sec'])
def find_blobs(raw_img, args): '''function performing two dimensional connected component analysis on an image. Args: img (ndarray): original image to be analyzed args (Arguments instance): defined the threshold value to binarze the image Returns: an instance of the Components class, a stencil containing the final labels of components, and a stencil containing the labels before eliminating equivalences ''' # dimensions height = raw_img.shape[0] width = raw_img.shape[1] img = processing.threshold(raw_img, args) # adding column of zeros to prevent left and right most blob # form being mistaken as one zeros = np.zeros((height, 1)) img = np.concatenate((img, zeros), axis=1) width += 1 size = height * width img = img.reshape(size) stencil = np.zeros(size, dtype=int) labels = DisjointSet(n_labels=1) # first pass for i in range(size): if img[i] != 0: # if a neighboring pixel is labeled the investigated pixel is given the same label # Note: when iterating from top left to bottom right indices to the right bottom of investigated # pixel cannot be labeled before this pixel for j in [i - 1, i - width, i - width - 1, i - width + 1]: if j < 0 or j >= size: continue if stencil[j] != 0 and stencil[i] == 0: # connection stencil[i] = stencil[j] elif stencil[j] != 0 and stencil[j] != stencil[i]: # conflict labels.unite(stencil[i], stencil[j]) else: # no connection nor conflict continue # if no neighboring pixel is labeled the investigated pixel is give a new label if stencil[i] == 0: new_label = labels.next() stencil[i] = new_label labels.add(new_label) # uncomment to print show labels after first pass # first_pass = deepcopy(stencil.reshape((height, width))) # second pass to eliminate equivalences eq = labels.get_equivalents() for label in eq.keys(): stencil[stencil == label] = eq[label] # reshaping stencil stencil = stencil.reshape((height, width)) # SCIPY VARIANT #stencil = measure.label(img, background=0) # count pixels in blobs, calculate median to filter blobs final_labels = np.arange(1, np.max(stencil) + 1) pixel_counts = [] for label in final_labels: pixel_counts.append(np.sum(stencil == label)) pixel_counts = np.array(pixel_counts) min_allowed_pixels = np.median( pixel_counts[pixel_counts > 0]) / 5 # arbitrary; seems to work well # filter final lables and stencil final_labels = np.array(final_labels)[pixel_counts >= min_allowed_pixels] new_stencil = np.zeros_like(stencil) for i, label in enumerate(final_labels): new_stencil[stencil == label] = i + 1 stencil = new_stencil # construct boxes around letters bounding_boxes = get_bboxes(stencil) # chars = get_chars_from_boxes(raw, bounding_boxes) # extract characters from image in correct order #chars = [] #bounding_boxes = [] #while boxes: # box = heappop(boxes) # chars.append(raw[box[2]:box[3], box[0]:box[1]]) # bounding_boxes.append(box) return Components(boxes=bounding_boxes, img=raw_img, stencil=stencil)
def main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-s', '--sequence', action='store_true', help='''Check if given sequence is graphic. Sequence consisting of ints separated by spaces''') group.add_argument( '-r', '--randomize', action='store_true', help='''Randomize edges n times where n(int) is first parameter after -r/--randomize flag in graph given by the graphical sequence(ints separated by spaces)''') group.add_argument('-c', '--components', action='store_true', help='''Find all connected components in graph given by the graphical sequence(ints separated by spaces) and mark the greatest''') group.add_argument( '-e', '--euler', action='store_true', help='''Make random Euler's graph with given n(int) nodes or with random number of them if not specified''') group.add_argument( '-kr', '--regular', action='store_true', help='''Make k-regular graph with n nodes where n(int) is first parameter and k(int) the second one''') group.add_argument( '-H', '--hamilton', action='store_true', help='''Check Hamilton's cycle exists in graph given by the graphical sequence(ints separated by spaces) and prints it''' ) arg = parser.parse_known_args() if arg[0].sequence: parser2 = argparse.ArgumentParser() parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) try: g = Graph.from_sequence(np.array(args.seq)) g.show() except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return return if arg[0].randomize: parser2 = argparse.ArgumentParser() parser2.add_argument('n', type=int) parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) if args.n < 0: print('Number of randomization n must be positive integer ') return try: g = Graph.from_sequence(np.array(args.seq)) except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return print("Randomized edges:") for i in range(0, args.n): p1, p2 = g.randomize_edges() print(f"{p1}, {p2} => ({p1[0]}, {p2[1]}), ({p1[1]}, {p2[0]})") print() g.show() return if arg[0].components: parser2 = argparse.ArgumentParser() parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) try: g = Graph.from_sequence(np.array(args.seq)) except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return G = g.adjacency components = Components() [comp, nr] = components.find_components(G) comp_lists = [[] for x in range(nr)] for v in range(len(G)): comp_lists[comp[v] - 1].append(v) for count, item in enumerate(comp_lists): print(count + 1, item) print("Biggest connected component: " + str(components.max_component)) print("has " + str(components.max_count) + " vertices") return if arg[0].euler: parser2 = argparse.ArgumentParser() parser2.add_argument('n', type=int, nargs='?', default=random.randint(4, 30)) args = parser2.parse_args(arg[1]) find_euler_random(args.n) return if arg[0].regular: print(5) parser2 = argparse.ArgumentParser() parser2.add_argument('n', type=int) parser2.add_argument('k', type=int) args = parser2.parse_args(arg[1]) gen_k_regular(args.n, args.k) return if arg[0].hamilton: parser2 = argparse.ArgumentParser() parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) try: g = Graph.from_sequence(np.array(args.seq)) except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return adj_list = convert_matrix_to_adj_list(g.adjacency) print(adj_list) check_hamilton_cycle(adj_list) return
#-*- coding: UTF-8 -*- from pymatgen import MPRester from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter import collections import sys, os import time from components import Components Comps = Components() os.system('rm -rf structure; mkdir structure') ChemicalSymbols = [ 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr' ] #M = ['Sc', 'Ti', 'V', 'Cr', 'Mn', # 'Zr', 'Nb', 'Mo', # 'Hf', 'Ta', 'W'] #A = ['Al', 'Si', 'P', 'S', # 'Ga', 'Ge', 'As', # 'Cd', 'In', 'Sn', # 'Ti', 'Pb'] M = ['Sc'] A = ['Al']
return (True, False, False) # Hot - Red light elif external_temperature + external_temperature_allowed_offset < temperature_range[ 'min']: return (False, False, True) # Cold - Blue light else: return (False, True, False) # Good - Green light with open('config.json') as json_data: config = json_load(json_data) nw = NetworkWrapper(wifi_config=config['wifi'], ubidots_config=config['ubidots']) time_utils.sync_ntp(nw) components = Components() components.rgb_led.set_colors(False, False, False) last_notification_timestamp_sec = 0 while True: sensors_data = nw.get_sensors_data() # Color-by-temperature LED r, g, b = calculate_temperature_color( float(sensors_data['internal-temperature']), float(sensors_data['external-temperature'])) components.rgb_led.set_colors(r, g, b) # Water level display components.seven_segment.number(int(sensors_data['water-level']))