コード例 #1
0
ファイル: varmapping.py プロジェクト: qunox/arah
    def __init__(self, cellmap_df, normalizedsource_df, projectpath, paramlist, type, normalize = True ,plot=False, log=False):

        self.cellmap_df = cellmap_df
        self.source_df = normalizedsource_df
        self.projectpath = projectpath

        self.paramlist = paramlist


        if type not in ['euclidean','cityblock', 'correlation',  'chebyshev', 'cosine', 'canberra', 'braycurtis', 'mahalanobis']:
            raise Exception('Unknown mapping type: %s' % type)
        else:
            self.trainingtype = type

        if plot:
            self.plot = True
            self.draw_func = draw.draw()
            self.drawingdir = os.path.join(projectpath, 'mapcountour')

            if not os.path.exists(self.drawingdir):
                os.mkdir(self.drawingdir)
        else:
            self.plot = False

        self.normalize = normalize
        if normalize is True:
            self.dfutil_func = dfutil.dfutil()

        if log:
            self.log = log
        else:
            self.log = False
コード例 #2
0
def start_show_words():
    global word_index
    word = words[word_index]

    if (word_index + 1 < len(words)):
        word_index += 1
    else:
        word_index = 0

    img = draw(word)
    img = img.transpose(Image.ROTATE_180)

    try:
        epd = Epd.EPD()
        epd.display(epd.getbuffer(img))
    except IOError as e:
        logging.info(e)

    except KeyboardInterrupt:
        logging.info("ctrl + c:")
        Epd.epdconfig.module_exit()
        exit()

    t = Timer(interval, start_show_words)
    t.start()
コード例 #3
0
ファイル: mapping.py プロジェクト: qunox/arah
    def __init__(self, cellmap_df, normalizedsource_df, projectpath, paramlist, plot=False, log=False, probmap = False,
                 secondary=False, type='cossim'):

        self.cellmap_df = cellmap_df
        self.source_df = normalizedsource_df
        self.projectpath = projectpath

        self.paramlist = paramlist

        if secondary:
            self.secondary = True
        else:
            self.secondary = False

        if type not in ['cossim', 'euclide', 'dot', 'rbf']:
            raise Exception('Unknown mapping type: %s' % type)
        else:
            self.trainingtype = type

        if plot:
            self.plot = True
            self.draw_func = draw.draw()
            self.drawingdir = os.path.join(projectpath, 'mapcountour')
            if not secondary:
                if os.path.exists(self.drawingdir) and not probmap:
                    raise IOError('ERROR: Drawing path already exist:%s' % self.drawingdir)
                elif not probmap:
                    os.mkdir(self.drawingdir)

        if log:
            self.log = log
コード例 #4
0
ファイル: test.py プロジェクト: keyan/metro_coloring
    def test_draw(self):
        constraint_graph = construct_constraint_graph(
            self.routes_for_stops,
            self.stops_for_routes,
        )
        coloring = greedy_vertex_color(constraint_graph)
        nodes = draw(constraint_graph, coloring)

        self.assertEqual(4, nodes)
コード例 #5
0
def generate_graph() -> None:
    """
    Load GTFS data from local sqlite storage and construct the constraint graph
    and coloring for the network. Output DOT graph visualizations for the network.
    """
    routes_for_stops, stops_for_routes, route_names = construct_data()
    print(f'Done constructing raptor data')

    graph = construct_constraint_graph(routes_for_stops, stops_for_routes)
    print(f'Done constructing constraint graph')

    coloring = greedy_vertex_color(graph)
    print(f'Done coloring graph')

    draw(
        graph=graph,
        colors=coloring,
        # Don't use GTFS route names because it will confuse casual users.
        route_names=None,
        filename_prefix='mta_',
        view=True,
    )
コード例 #6
0
def start_show_words():
    global word_index
    word = words[word_index]

    if (word_index + 1 < len(words)):
        word_index += 1
    else:
        word_index = 0

    img = draw(word)
    img.show()
    t = Timer(interval, start_show_words)
    t.start()
コード例 #7
0
ファイル: training3.py プロジェクト: qunox/arah
    def __init__(self, samplevec_df, cellmap_df, radius_list, learningconstant_list, paramlist,project_dir, normalize=True, log=False,
                 plot=False,cpucount=-1, type = 'cossim', logcycle = False):

        self.irr_list = range(len(radius_list))
        self.samplevec_df = samplevec_df
        self.cellmap_df = cellmap_df
        self.radius_list = radius_list
        self.learningconst_list = learningconstant_list
        self.log = log
        self.draw_func = draw.draw()
        self.project_dir = project_dir

        self.normalize = normalize
        if normalize is True:
            self.dfutil_func = dfutil.dfutil()

        if type not in ['euclidean','cityblock', 'correlation',  'chebyshev', 'cosine', 'canberra', 'braycurtis', 'mahalanobis']:
            raise Exception('Unknown training type: %s' % type)
        else:
            self.traintype = type

        if cpucount == -1:
            self.cpucount = multiprocessing.cpu_count()-1
        elif cpucount == 1:
            raise Exception('Single core processing is not implemented yet')
        else:
            self.cpucount = cpucount-1

        self.param_list = paramlist

        if not logcycle is False:
            if isinstance(logcycle, int):
                self.logcylce = logcycle
            else:
                raise Exception('ERROR: logcycle should be int')

        if plot is True:
            self.plot = True
            pertubplotdir = os.path.join(self.project_dir, 'mappertub')
            if os.path.exists(pertubplotdir):
                raise IOError('ERROR: Plot directory already exist:%s' % pertubplotdir)
            os.mkdir(pertubplotdir)
            self.pertubplotdir = pertubplotdir
        else: self.plot = False
コード例 #8
0
ファイル: training2.py プロジェクト: qunox/arah
def _drawplot(inputQ):

    status = True
    waittime = 0
    draw_func = draw.draw()

    while status:
        try:
            packet = inputQ.get()
            waittime = 0
            #dftodraw, irr, drawpath, irrlist, learninglist, radiuslis, exectimelist
            draw_func.trainplot(packet[0], packet[1], packet[2],packet[3], packet[4], packet[5], packet[6])
        except(EOFError, IOError):
            time.sleep(0.5)
            if waittime > 18000:
                status = 'stop'
                break
            else:
                waittime += 1
コード例 #9
0
ファイル: training2.py プロジェクト: qunox/arah
    def __init__(self, samplevec_df, cellmap_df, radius_list, learningconstant_list, paramlist,  log=False,
                 plot=False, project_dir=False, cpucount=-1, type = 'cossim', logcycle = False):

        self.irr_list = range(len(radius_list))
        self.samplevec_df = samplevec_df
        self.cellmap_df = cellmap_df
        self.radius_list = radius_list
        self.learningconst_list = learningconstant_list
        self.log = log

        if type not in ['cossim', 'dot', 'euclide', 'rbf']:
            raise Exception('Unknown training type: %s' % type)
        else:
            self.traintype = type

        if cpucount == -1:
            self.cpucount = multiprocessing.cpu_count()-1
        elif cpucount == 1:
            raise Exception('Single core processing is not implemented yet')
        else:
            self.cpucount = cpucount-1

        self.param_list = paramlist

        if not logcycle is False:
            if isinstance(logcycle, int):
                self.logcylce = logcycle
            else:
                raise Exception('ERROR: logcycle should be int')

        if project_dir:
            self.project_dir = project_dir

        if plot is True:
            self.plot = True
            self.draw_func = draw.draw()
            pertubplotdir = os.path.join(self.project_dir, 'mappertub')
            if os.path.exists(pertubplotdir):
                raise IOError('ERROR: Plot directory already exist:%s' % pertubplotdir)
            os.mkdir(pertubplotdir)
            self.pertubplotdir = pertubplotdir
        else: self.plot = False
コード例 #10
0
ファイル: training.py プロジェクト: qunox/arah
    def __init__(self, samplevec_df, cellmap_df, radius_list, learningconstant_list, log=False, excludedcol=False,
                 plot=False, project_dir=False, cpucount = 1):

        self.irr_list = range(len(radius_list))
        self.samplevec_df = samplevec_df
        self.cellmap_df = cellmap_df
        self.radius_list = radius_list
        self.learningconst_list = learningconstant_list
        self.log = log

        if cpucount == -1:
            self.mppool = multiprocessing.Pool()
        else:
            self.mppool = multiprocessing.Pool(cpucount)

        if excludedcol:
            self.excludedcol = ['id', 'x_position', 'y_position', 'pick_count']
            self.excludedcol.extend(excludedcol)
        else:
            self.excludedcol = ['id', 'x_position', 'y_position', 'pick_count']

        self.accpcoll_list = []
        for col in cellmap_df.columns.values:
            if not col in self.excludedcol:
                self.accpcoll_list.append(col)

        if project_dir:
            self.project_dir = project_dir

        if plot:
            self.plot = True
            self.draw_func = draw.draw()
            pertubplotdir = os.path.join(self.project_dir, 'mappertub')
            if os.path.exists(pertubplotdir):
                raise IOError('ERROR: Plot directory already exist:%s' % pertubplotdir)
            os.mkdir(pertubplotdir)
            self.pertubplotdir = pertubplotdir
コード例 #11
0
def battle(player1: list, player2: list, backend_sim: Aer) -> Tuple:
    """Battle game.
    Args:
        player1: player
        player2: player if 2 player
        backend_sim: backend for quantum
    Return: winner, looser
    """

    play = True

    computer = [False, False]
    nb_player = str(input("How many player ? 1/2 : "))
    if nb_player == "1":
        computer[1] = True

    begin = str(input("Player1 start ? y/n : "))
    if begin == "y":
        player1[0] = True
    else:
        player2[0] = True
        computer[0] = True

    while play:
        # Generation of the first circuit with 11 qubits
        stick = 11
        nb_qubit = stick
        drawing_add = ""
        draw.draw(stick, drawing_add)

        stick_qubit = QuantumRegister(nb_qubit, "stick")
        qc_board = QuantumCircuit(stick_qubit)

        # Game
        while stick > 0:
            if player1[0]:
                player_name = player1[1]
            else:
                player_name = player2[1]

            # Player choice
            if computer[1] is False or player1[0] is True:
                print(player_name, "- You take : ")
                control = False
                while not control:
                    nbstick = int(input())
                    control = control_input(stick, nbstick)
                for i in range(nbstick):
                    print(
                        player_name,
                        "- Which gate do you want to use on stick[",
                        i + 1,
                        "] ?",
                    )
                    control = False
                    while not control:
                        if stick - i == 1 and nb_qubit == 1:
                            gate = str(input("x : "))
                            control = control_input(["x"], gate)
                        elif stick - i == 1:
                            gate = str(input("x, cx : "))
                            control = control_input(["x", "cx"], gate)
                        elif stick - i == nb_qubit:
                            gate = str(input("h, x : "))
                            control = control_input(["x", "h"], gate)
                        elif stick - i > 1:
                            gate = str(input("h, x, cx : "))
                            control = control_input(["x", "h", "cx"], gate)

                    if gate == "h":
                        qc_board.h(stick - (1 + i))
                        drawing_add = "/ " + drawing_add
                    if gate == "x":
                        qc_board.x(stick - (1 + i))
                        drawing_add = "x " + drawing_add
                    if gate == "cx":
                        qc_board.cx(stick - i, stick - (1 + i))
                        drawing_add = "¬ " + drawing_add

            # Computer choice
            if computer[0] is True and computer[1] is True:
                if stick == 1 and nb_qubit == 1:
                    qc_board.x(stick - 1)
                    drawing_add = "x " + drawing_add
                    nbstick = 1
                else:
                    past = drawing_add.split(" ")
                    result_analyse = ia.quantum_ia(stick, past, backend_sim)
                    for i, gate in enumerate(result_analyse):
                        if gate == "x":
                            qc_board.x(stick - (1 + i))
                            drawing_add = "x " + drawing_add
                        if gate == "sup":
                            qc_board.h(stick - (1 + i))
                            drawing_add = "/ " + drawing_add
                        if gate == "intric":
                            qc_board.cx(stick - i, stick - (1 + i))
                            drawing_add = "¬ " + drawing_add

                    nbstick = len(result_analyse)

            stick -= nbstick

            # Check if board is clean
            if stick < 1:
                # Run circuit
                qc_board.measure_all()
                print(qc_board.draw())
                job = execute(qc_board, backend_sim, shots=1, memory=True)
                result_memory = job.result().get_memory()
                result = result_memory[0]
                for i in range(len(result)):
                    if result[i] == "0":
                        stick += 1
                print("stick left : ", stick)

                # Check circuit result
                if stick < 1:
                    if player1[0] and nb_player == "2":
                        print(
                            "\n\n##################\n  Player 2 win !\n##################"
                        )
                    if player2[0]:
                        print(
                            "\n\n##################\n  Player 1 win !\n##################"
                        )
                        return "human", "robot"
                    if computer[0] is False and computer[1] is True:
                        print(
                            "\n\n##################\n  Machine win !\n##################"
                        )
                        return "robot", "human"
                else:
                    # Generation of new circuit with qubits left
                    nb_qubit = stick
                    drawing_add = ""
                    stick_qubit = QuantumRegister(nb_qubit, "stick")
                    qc_board = QuantumCircuit(stick_qubit)

            # Inverse turn
            if stick > 0:
                draw.draw(stick, drawing_add)
                player2[0] = not player2[0]
                player1[0] = not player1[0]
                if computer[1]:
                    computer[0] = not computer[0]
コード例 #12
0
def main():
    global window
    global mode

    print("$  ")
    print("$   Welcome to Cody Draw(TM)!")
    print("$  ")
    print(
        "$   Cody draw is very simple to use, here is a list of all the controls"
    )
    print("$      - Press & Drag 'Left Mouse Button' to draw")
    print("$      - Press & Drag 'Right Mouse Button' to erase")
    print(
        "$      - Press 'tab' to toggle the UI (color picker, timeline, exc)")
    print("$      - Press 'c' to clear the canvas / frame")
    print("$      - Press 's' to save your work")
    print("$      - Press 'o' to open saved work")
    print("$      - Press 'e' to export your work into a PNG")
    print("$      - Press '1' to draw in the color white")
    print("$      - Press '2' to draw in the color red")
    print("$      - Press '3' to draw in the color green")
    print("$      - Press '4' to draw in the color blue")
    print("$      - Press '6' to draw in the color orange")
    print("$   ")
    print(
        "$   These next controls might get a little bit complicated, they will allow you to mix colors"
    )
    print(
        "$   You can see your RGB color value in the title, its 3 numbers valued at 0 - 1 in order"
    )
    print("$      - Press '7' to toggle the color blue")
    print("$      - Press '8' to toggle the color green")
    print("$      - Press '9' to toggle the color red")
    print("$      - Press 'b' to increase the red value by 0.05")
    print("$      - Press 'n' to increase the green value by 0.05")
    print("$      - Press 'm' to increase the blue value by 0.05")
    print("$  ")
    print("$  When animating these additional keybinds exist")
    print("$      - Press 'space' to play/pause")
    print(
        "$      - Press '>' to goto the next frame, or create another frame if one doesnt exist"
    )
    print("$      - Press '<' to goto the previous frame")
    print(
        "$      - Press 'a' to toggle the onionskin (preview of the previous frame / next frame)"
    )
    print("$  ")
    print(
        "$   There are a few example paintings bundled with your copy of Cody Draw(TM)"
    )
    print("$   Access them using the 'o' keybind to open a Cody Draw(TM) file")
    print("$      - 'welcome'")
    print("$      - 'earth'")
    print("$      - 'intheair'")
    print("$      - 'chart'")
    print("$      - 'colors'")
    print("$  ")

    if not glfw.init():
        return

    window = glfw.create_window(window_width, window_height,
                                "Welcome to Cody Draw(TM)", None, None)
    glfw.set_window_size_limits(window, window_width, window_height,
                                window_width, window_height)
    if not window:
        glfw.terminate()
        return

    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, cursor_position_callback)
    glfw.set_mouse_button_callback(window, mouse_button_callback)

    glfw.make_context_current(window)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, window_width, window_height, 0, 0, 1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    glClear(GL_COLOR_BUFFER_BIT)

    while not glfw.window_should_close(window):
        # Rendering
        glClear(GL_COLOR_BUFFER_BIT)

        if mode == 1:
            mainmenu.draw(window_width, window_height)
        elif mode == 2:
            draw.draw()
        elif mode == 3:
            draw.draw()

        # Other
        glfw.swap_buffers(window)
        glfw.poll_events()

    print("$  ")
    print("$  Cody Draw(TM) has been terminated!")
    print("$  Goodbye!")
    print("$  ")

    glfw.terminate()
コード例 #13
0
def main(args):
    graph = load_graph(args.graph.name)
    figure = draw(graph)
    plt.savefig(args.image_output.name)
コード例 #14
0
def test_show_word():
    word = query('good')
    img = draw(word)
    img.show()
コード例 #15
0
ファイル: pretraining.py プロジェクト: qunox/arah
 def __init__(self):
     self.drawfunc = draw.draw()
コード例 #16
0
# 用于在树莓派上测试电子墨水屏与单词的显示
import logging
import sys
from PIL import Image
from src.draw import draw
from src.dict import query
from lib.epd import epd as Epd

img = draw(query('good'))
img = img.transpose(Image.ROTATE_180)

try:
    logging.info("Demo")

    epd = Epd.EPD()
    logging.info("init and Clear")
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)

    epd.display(epd.getbuffer(img))
except IOError as e:
    logging.info(e)

except KeyboardInterrupt:
    logging.info("ctrl + c:")
    Epd.epdconfig.module_exit()
    exit()