Example #1
0
    def test_init(self):
        drawer1 = Drawer.Drawer("total production", ["STATE"], [100])
        self.assertEqual(drawer1.state_array, ["STATE"])
        self.assertEqual(drawer1.total_production_array, [100])
        self.assertEqual(drawer1.production_value_array, [])
        self.assertEqual(drawer1.mode, "total production")
        drawer2 = Drawer.Drawer("production value", ["STATE"], [100])
        self.assertEqual(drawer2.state_array, ["STATE"])
        self.assertEqual(drawer2.total_production_array, [])
        self.assertEqual(drawer2.production_value_array, [100])
        self.assertEqual(drawer2.mode, "production value")

        with self.assertRaises(SystemExit) as cm:
            drawer3 = Drawer.Drawer("zly mode", ["STATE"], [100])
        self.assertEqual(cm.exception.code, 1)
Example #2
0
def subTask1():
    rows, columns = -1, -1
    while rows < 0 or columns < 0:
        try:
            rows = int(input("\t•Number of rows: "))
            columns = int(input("\t•Number of columns: "))
        except ValueError:
            print(
                "##ERROR: Please write a positive number for both variables.")

    my_maze = Maze.Maze()
    my_maze.generateRandomMaze(rows, columns)
    Drawer.drawMaze(my_maze)
    JsonManager.write(my_maze)
    print("Maze generated on \\mazes folder.\n")
Example #3
0
def test_month_5(market, year, month, count=0, skips=0):

    candles = Currency.Markets.candelOfMarket(market)

    types = Hunter.Type_Container(candles)

    pens = Hunter.Pen_Container(types)

    hubs = Hunter.Five_Min_Hub_Container(pens)

    # 初始化Tran_Container对象
    trans = Hunter.Tran_Container()

    s = S1.S(candles.container, types.container, pens.container,
             hubs.container)

    candles.loadDB(year, month, count, skips, types, pens, hubs, s)

    S1.S._trans.clear()

    print(hubs.size())

    ax_1 = plt.subplot(1, 1, 1)

    drawer = Drawer.Five_Min_Drawer(candles.container)

    drawer.draw_stocks(candles.container, ax_1, trans)

    drawer.draw_pens(pens.container, ax_1)

    drawer.draw_hub(hubs.container, hubs, ax_1)

    plt.show()
    """
Example #4
0
    def to_ansi(self):
        """
        this method starts the drawer class with ansi
        """

        try:
            _tuple = self.get_ascii_img()

            drawer = DrCls.Drawer(self.filename)
            ansi_image = drawer.to_ansi_art(_tuple)

            with open("%s.txt" % self.name, "w") as f:
                f.write(ansi_image)

            msg = QMessageBox()
            msg.setText("Now you can find your image on %s.txt \n" % self.name)
            msg.exec_()
            print("Now you can find your image on %s.txt \n" % self.name)

        except Exception as e:
            if self.name == "":
                msg = QMessageBox()
                msg.setText("Empty name \n")
                msg.exec_()
                print("Empty name")
                print(e)
            else:
                msg = QMessageBox()
                msg.setText("Choose file at first \n")
                msg.exec_()
                print("Choose file at first")
Example #5
0
    def to_ascii(self):
        """
        this method starts the drawer class with ascii
        """

        try:
            drawer = DrCls.Drawer(self.filename)
            _tuple = self.get_ascii_img()
            self.ascii_img = drawer.to_ascii_art(_tuple[0], _tuple[1][0])

            with open("%s.txt" % self.name, "w") as f:
                f.write(self.ascii_img)

            self.result_window = Result(ascii_img=self.ascii_img)
            self.result_window.show()
            msg = QMessageBox()
            msg.setText("Now you can find your image on %s.txt \n" % self.name)
            msg.exec_()
            print("Now you can find your image on %s.txt \n" % self.name)
            print(self.ascii_img)

        except Exception as e:
            print(e)
            if self.name == "":
                msg = QMessageBox()
                msg.setText("Empty name \n")
                msg.exec_()
                print("Empty name")
                print(e)
            else:
                msg = QMessageBox()
                msg.setText("Choose file at first \n")
                msg.exec_()
                print("Choose file at first")
Example #6
0
 def setUp(self):
     self.drawer = DrCls.Drawer("test.png")
     self.incorrect_asciiArt = "BBBBBBBBBBBBBBBBBBBBB" \
                               "BBSSSSSSS#######&&&&&&" \
                               "@@@@@@$$$$$$%%%%%%****" \
                               "***!!!!!!!:::::::::::" \
                               ".............."
     self.name = 'test'
Example #7
0
	def GetPixmapFromMap(self,map,contents):
		drawer=Drawer.DrawerForCairo(contents,map)
		[width,height]=drawer.GetRect()
		pixmap=gtk.gdk.Pixmap(None,width,height,24)
		cr=pixmap.cairo_create()
		cr.set_source_rgb(200,200,200)
		cr.set_operator (cairo.OPERATOR_SOURCE)
		cr.paint()
		drawer.Draw(cr)
		return [pixmap,drawer]
Example #8
0
 def drawLissajou(self, canvas, labels, scales):
     #stop the Draw
     Drawer.Draw.drawNr += 1
     #getting Values from Scales
     sValues = [None] * 6
     for i in range(0, 6):
         sValues[i] = scales[i].get()
     #refresh the lable
     self.labelRefresh(labels, sValues)
     #start drawing
     drawer = Drawer.Draw(canvas, sValues)
Example #9
0
    def draw(self, start_position: Vector2 = None):
        Printer.print_once("Initialized " + self.id + " in " + self.position.to_string() + " with size " +
                           self.size.to_string() + ". " + self.zone.to_string())

        if pygame.mouse.get_pressed()[0]:
            if self.zone.point_over(Vector2(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])):
                self.focused = True
            else:
                self.focused = False

        if self.focused:
            # Drawer.draw_border_rect(self.zone, self.style.focused_background_color, BorderStyle(
            #     self.style.focused_border_color, self.style.border_width), self.window)
            Drawer.draw_rounded_rect(self.zone, self.style.focused_background_color, self.window)

            if Time.millis() - self.__last_blink_shown > self.__blink_time:
                if self.__last_blink_shown:
                    # draw down line
                    pass
                else:
                    # don't draw line
                    pass
                self.__last_blink_shown = not self.__last_blink_shown

            Drawer.draw_text(self.zone.vector1 + Vector2(5, 5), Colors.black, self.text, self.font, self.window)

            print("Focused!")
        else:
            # Drawer.draw_border_rect(self.zone, self.style.background_color, BorderStyle(
            #     self.style.border_color, self.style.border_width), self.window)
            Drawer.draw_rounded_rect(self.zone, self.style.background_color, self.window)
            print("Unfocused!")
Example #10
0
    def draw(self, start_position: Vector2 = None):
        if self.window is not None:
            if start_position is not None:
                self.new_pos = start_position + self.position
                self.__update_zone(self.new_pos)

            mousepos = ArrayPosition(pygame.mouse.get_pos())
            if self.zone.point_over(mousepos):
                self.__left = False
                if pygame.mouse.get_pressed()[0]:
                    self.current_color = self.click_background_color
                    if not self.__clicked:
                        self.__clicked = True
                        if self.on_click is not None:
                            self.on_click()
                else:
                    self.__clicked = False
                    self.current_color = self.hover_background_color
                    if not self.__hovered:
                        self.__hovered = True
                        if self.on_hover is not None:
                            self.on_hover()
            else:
                self.__hovered = False
                self.current_color = self.background_color
                if not self.__left:
                    self.__left = True
                    if self.on_leave is not None:
                        self.on_leave()

            Printer.print_once("Initialized " + self.id + " in " + self.position.to_string() + " with size " +
                               self.size.to_string() + ". " + self.zone.to_string())

            Drawer.draw_rect(self.zone, self.current_color, self.window)
        else:
            Printer.print_once(self.id + " has not a window to be on.")
Example #11
0
 def __init__(self):
     
     self.dt = 0.01
     self.discoveryRadius = 40
     self.maxConnectionsPerMass = 4
     
     self.pointMasses = []
     self.spheres = []
     
     self.connections = []
     
     self.drawer = Drawer()
     self.drawer.spheres = self.spheres
     self.drawer.connections = self.connections
     
     self.thread = threading.Thread(target=self.run)
     self.thread.daemon = True
Example #12
0
    def save_as_img(self, name=None):
        """
        this method saves an image
        """

        image = DrCls.Drawer(self.filename).get_img(self.name)

        while name is None or name == '':
            name, ok = QInputDialog.getText(self, "Name",
                                            "Enter your filename")
            if name == '':
                msg = QMessageBox()
                msg.setText("Please type filename!!!")
                msg.exec_()

        image.save("%s.png" % name)
        msg = QMessageBox()
        msg.setText("Done!")
        msg.exec_()
Example #13
0
    def get_ascii_img(self):
        """
        this method gets an ascii string with picture
        """

        while self.name == '':
            self.name, ok = QInputDialog.getText(self, "Name",
                                                 "Enter your filename")
            if self.name == '':
                msg = QMessageBox()
                msg.setText("Please type filename!!!")
                msg.exec_()

        drawer = DrCls.Drawer(self.filename)
        res = drawer.resize_image(self.res)
        pixels = drawer.get_image_data()
        arr = drawer.draw_picture(pixels)

        return arr, res
Example #14
0
def test_month_10(market, year, month, count=0, skips=0):

    candles = Currency.CAD_Ten_Min_Candle_Container()

    types = Hunter.Type_Container(candles)

    pens = Hunter.Pen_Container(types)

    hubs = Hunter.Ten_Min_Hub_Container(pens)

    # 初始化Tran_Container对象
    trans = Hunter.Tran_Container()

    #s1 = S1.S1(candles.container,types.container,pens.container,hubs.container)

    s2 = S1.S2()

    m = Event.Monitor(s2)

    candles.loadDB(year, month, count, skips, types, pens, hubs, m)

    #S1.S1._trans.clear()
    #S1.S2._trans.clear()

    ax_1 = plt.subplot(1, 1, 1)

    drawer = Drawer.Ten_Min_Drawer(candles.container)

    drawer.draw_stocks(candles.container, types.container, ax_1, trans)

    drawer.draw_pens(pens.container, ax_1)

    drawer.draw_hub(hubs.container, hubs, ax_1)

    #for _, hub in enumerate(hubs.container):

    #    print(hub.pens())

    plt.show()
    """
Example #15
0
    def createDrawing(self, reducedWidth=500, reducedHeight=200):
        # get list of chars from selected file and store in object field
        if len(self.filesBox.curselection()) is 0:
            print("Please upload or select a file first")
            return
        selectedFileNumber = self.filesBox.curselection()[0]
        characters = self.filenameList[selectedFileNumber]
        self.characterList = characters

        # create turtle if needed, else clear canvas
        if not self.createdTurtle:
            self.makeTurtle()
        else:
            self.clearCanvas()

        # draw picture and update canvas
        self.turt.getscreen().tracer(0)
        self.drawer = drawer.Drawer(self.characterList, self.turt,
                                    self.initDx - reducedWidth,
                                    self.initDy - reducedHeight)
        self.drawer.draw()
        self.turt.getscreen().update()
    def __init__(self):
        self.logger = ObjectLogger.ObjectLogger("WordCloudGenerator")
        self.logger.log("Initialising pygame")
        pygame.init()

        self.windowHeight = 800
        self.windowWidth = 800

        self.logger.log("Creating DISPLAYSURF with dimensions %dx%d" %
                        (self.windowWidth, self.windowHeight))
        self.DISPLAYSURF = pygame.display.set_mode(
            (self.windowWidth, self.windowHeight))

        self.logger.log("Creating wordCloudContainerRect")
        self.wordCloudContainerRect = self.DISPLAYSURF.get_rect()
        self.wordCloudContainerRect.width -= 150
        self.wordCloudContainerRect.height -= 150
        self.wordCloudContainerRect.topleft = (75, 75)

        self.logger.log("Creating drawer object")
        self.drawer = Drawer.Drawer(self.DISPLAYSURF)

        self.drawer.fillBackground()
Example #17
0
import sys, pygame
from pygame.locals import *
from PyGame import *
from Drawer import *
import random

if __name__ == "__main__":
    pygame.init()
    clock = pygame.time.Clock()
    window = pygame.display.set_mode((640, 480))
    # Use Drawer Class to deal with drawing
    drawer = Drawer(window)
    count = 0
    new_line = True
    pygame.display.set_caption("PyGame")
    content = Content(12, 6)
    window.fill(Drawer.BG_COLOR)
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.__dict__['key'] == K_UP:
                    random_column = random.randint(0, 5)
                    random_list = random.sample(range(1, 9),
                                                random.randint(1, 5))
                    content.add_line(random_column, random_list)
                if event.__dict__['key'] == K_SPACE:
                    content.rotate()
                if event.__dict__['key'] == K_LEFT:
Example #18
0
import turtle
import random
import Drawer
import time

don = turtle.Turtle()
don.speed(0)
don.hideturtle()
don.width(2)
screen = turtle.Screen()
screen.bgcolor('orange')
screen.colormode(255)
screen.delay(0)
screen.tracer(0)

drawer = Drawer.Drawer(don)


class Card:
    def __init__(self, color, number):
        self.face = 'up'
        self.color = color
        self.number = number

    def get_color(self):
        return self.color

    def get_number(self):
        return self.number

    def flip(self):
Example #19
0
import io
import socket
import struct
import cv2
import numpy as np
import pygame
from Drawer import *
from utils import *
import time

if __name__ == '__main__':

    print("START SERVER")
    ####### pygame #######
    drawer = Drawer()
    joy = pygame.joystick.Joystick(0)
    joy.init()
    ####### end of pygame #######

    ####### socket ########
    server_socket = socket.socket()
    server_socket.bind((IP_Address, Port))
    server_socket.listen(1)
    client_socket, address = server_socket.accept()
    ###### end of socket #######

    ###### recording data set  ######
    frames = []
    angles = []
    ###### end of recording data set ######
Example #20
0
from CNN import *
from Drawer import *

cnn = CNN('models/mnist_cnn.h5')
drawer = Drawer()


def on_key(key):
    if key == 13:
        img = drawer.get(28, 28)
        number, pred = cnn.predict(img)
        print(number)
        print(pred)
        drawer.clear()


drawer.on_key(on_key)
drawer.run()
Example #21
0
class SimEngine(object):

    def __init__(self):
        
        self.dt = 0.01
        self.discoveryRadius = 40
        self.maxConnectionsPerMass = 4
        
        self.pointMasses = []
        self.spheres = []
        
        self.connections = []
        
        self.drawer = Drawer()
        self.drawer.spheres = self.spheres
        self.drawer.connections = self.connections
        
        self.thread = threading.Thread(target=self.run)
        self.thread.daemon = True
    
    def addConnections(self):
        for thisPointMass in self.pointMasses:
            
            nerby = []
            for otherPointMass in self.pointMasses:
                if thisPointMass is otherPointMass:
                    continue
                if len(thisPointMass.connections) > self.maxConnectionsPerMass:
                    continue
                
                r = np.linalg.norm(thisPointMass.pos - otherPointMass.pos)
                if r < self.discoveryRadius:
                    
                    if not thisPointMass in (connection.ends for connection in otherPointMass.connections):
                        nerby.append([r,otherPointMass])
            
            nerby.sort(key = lambda x: x[0])
            
            for i in range(0, min(len(nerby), self.maxConnectionsPerMass)):
                
                otherPointMass = nerby[i][1]
                
                # Create a new connection
                newConnection = Connection()
                newConnection.attach(thisPointMass, otherPointMass)
                self.connections.append(newConnection)
                
                print "added connection"

                
    def updateVelocities(self):
        for connection in self.connections:
            if connection.connected:
                
                # Connection forces
                force = connection.getForce()
                connection.ends[0].vel -= force/connection.ends[0].mass
                connection.ends[1].vel += force/connection.ends[1].mass
                
            else:
                self.connections.remove(connection)
                
        for pointMass in self.pointMasses:
            
            # Drag
            pointMass.vel *= (1-pointMass.drag)/pointMass.mass

    def updatePositions(self):
        for pointMass in self.pointMasses:
            pointMass.pos += pointMass.vel*self.dt
            
    def updateSpheres(self):
        for i in range(0,len(self.pointMasses)):
            self.spheres[i].pos = self.pointMasses[i].pos
    
    def run(self):
        print "running sim"
        self.addConnections()
        self.pointMasses[0].vel = [0, 10, 0]
        while True:
            self.updateVelocities()
            
            self.updatePositions()
            
            
            self.updateSpheres()
            
            
    
    def start(self):
        self.thread.start()
        print "running gui"
        self.drawer.run()

    def addPointMass(self, pointMass):
        if type(pointMass) is PointMass:
            self.pointMasses.append(pointMass)
            
            newSphere = Sphere()
            self.spheres.append(newSphere)
Example #22
0
from turtle import *
from Drawer import *
from ArgCreator import *

argType = [
    ArgType.LINE, ArgType.TRIANGLE, ArgType.SQUARE, ArgType.CIRCLE,
    ArgType.MANY_ANGLE
]


def ChooseFigure():
    return int(
        input(
            "1: Отрезок\n2: Треугольник\n3: Квадрат\n4: Круг\n5: Многоугольник\n\nНомер:"
        ))


tr = Turtle()
tr.begin_fill()

drawer = Drawer(tr)
argCreator = ArgCreator()

choosen = ChooseFigure()
while (choosen >= 1 and choosen <= 5):
    index = choosen - 1
    drawer.Draw(argType[index], argCreator.CreateArg)
    choosen = ChooseFigure()

tr.end_fill()
print("Выход из программы...")
Example #23
0
	def savesvg(self, path = None):
		drawer = Drawer(self)
		drawer.gen()
		print "save as svg file"
		drawer.save()
Example #24
0
    def draw(self, start_position: Vector2 = None):
        super().draw(start_position)

        Drawer.draw_text(self.zone.vector1 + Vector2(5, 5), Colors.black, self.text, self.font, self.window)
Example #25
0
 def draw(self, start_position: Vector2 = None):
     Drawer.draw_text(self.position, self.color, self.text, self.font, self.window)
Example #26
0
    def drawDXF(self):

        if hasattr(self, 'printFile'):
            drawer = Drawer.Drawer(self.printFile, self.cnc)
        else:
            self.addLogMessage("ERROR: No file selected.")
Example #27
0
def RunTest(network_graph, model_original, model_decomposer, solvers, 
            solve_original = False, solve_decomposed = False, max_iter = 100,
            validate_feasability = False, recover_feasible = False, recover_feasible_original = False,
            draw_progress = False, draw_solution = False):
    
    #overall results connection
    results = {}

    #solve decomposed problem
    if solve_decomposed:
        #solve decomposed problem
        solver_master = solvers['Master']
        solvers_local = solvers['Decomposed']
        start_time_decomposed = t.perf_counter()
        solution = model_decomposer.Solve(solver_master, solvers_local, max_iter)
        elapsed_time_decomposed = t.perf_counter() - start_time_decomposed

        #show decomposition iterating data
        if draw_progress:
            data = model_decomposer.RecordedData
            dr.PlotIterationData('Objective', data['MasterObj'])
            for name, data in data['Multipliers'].items():
                dr.PlotIterationData(name, data)

        if solution is None:
            results['Decomposed'] = None
            print('###################!RESULTS!#############################')
            print('Decomposed:\nSolution was not found!')
            print('__________________________________________________________')
        else:
            objective, objective_dual, strains, routes, time = ( solution['Objective'], solution['ObjectiveDual'], 
                                                                solution['Strain'], solution['Route'], 
                                                                solution['Time'] )

            results['Decomposed'] = { 'Objective': objective, 'ObjectiveDual': objective_dual, 'Time': time, 
                                        'Total time': elapsed_time_decomposed}

            print('###################!RESULTS!#############################')
            print(f'Decomposed:\nObjective: {objective}, Objective Dual: {objective_dual}, Time: {time}, Total time: {elapsed_time_decomposed}')
            
            #validate constraints violations
            if validate_feasability:
                violations = mp.FindConstraintsViolation(model_original.cmodel, strains, routes)
                cc_vn = violations['capacity_constraints'][1]
                rc_vn = violations['route_constraints'][1]
                if cc_vn == 0 and rc_vn == 0:
                    print('Feasible')
                else:
                    print(f'Capacity constraint violations number: {cc_vn}')
                    print(f'Route constraint violations number: {rc_vn}')
            print('__________________________________________________________')

            #draw if needed
            if draw_solution:
                path_list_sol =  [ [edge for edge, value in route.items() if abs(value - 1) <= 1e-6] for route in routes ]
                flow_list_sol = strains
                network_graph.SetPath(*path_list_sol)
                network_graph.SetFlows(*flow_list_sol)
                dr.PlotNetwork(network_graph, 'DECOMPOSED')

            #recover feasible for given routes
            if recover_feasible:
                solver = solvers['Recovered']
                start_time_recovered = t.perf_counter()
                solution = mp.RecoverFeasibleStrain(model_original, routes, solver)
                elapsed_time_recovered = t.perf_counter() - start_time_recovered
                if solution is None:
                    results['Recovered'] = None
                    print('###################!RESULTS!#############################')
                    print('Recovered:\nSolution was not found!')
                    print('__________________________________________________________')
                else:
                    objective, strains, routes, time = ( solution['Objective'], solution['Strain'], 
                                                        solution['Route'], solution['Time'] )

                    results['Recovered'] = { 'Objective': objective, 'Time': time, 'Total time': elapsed_time_recovered }

                    print('###################!RESULTS!#############################')
                    print(f'Recovered:\nObjective: {objective}, Time: {time}, Total time: {elapsed_time_recovered}')
                    
                    #validate constraints violations
                    if validate_feasability:
                        violations = mp.FindConstraintsViolation(model_original.cmodel, strains, routes)
                        cc_vn = violations['capacity_constraints'][1]
                        rc_vn = violations['route_constraints'][1]
                        if cc_vn == 0 and rc_vn == 0:
                            print('Feasible')
                        else:
                            print(f'Capacity constraint violations number: {cc_vn}')
                            print(f'Route constraint violations number: {rc_vn}')
                    print('__________________________________________________________')

                    #draw if needed
                    if draw_solution:
                        path_list_sol =  [ [edge for edge, value in route.items() if abs(value - 1) <= 1e-6] for route in routes ]
                        flow_list_sol = strains
                        network_graph.SetPath(*path_list_sol)
                        network_graph.SetFlows(*flow_list_sol)
                        dr.PlotNetwork(network_graph, 'RECOVERED')

    #solve original problem
    if solve_original:
        network_graph = cp.deepcopy(network_graph)
        solver = solvers['Original']
        start_time_original = t.perf_counter()
        solution = solver.Solve(model_original.cmodel)
        elapsed_time_original = t.perf_counter() - start_time_original
        if solution is None:
            results['Original'] = None
            print('###################!RESULTS!#############################')
            print(f'Original:\nSolution was not found!, Total time: {elapsed_time_original}')
            print('__________________________________________________________')
        else:
            objective, strains, routes, time = ( solution['Objective'], solution['Strain'], 
                                                solution['Route'], solution['Time'] )

            results['Original'] = { 'Objective': objective, 'Time': time, 'Total time': elapsed_time_original }
                        
            print('###################!RESULTS!#############################')
            print(f'Original:\nObjective: {objective}, Time: {time}, Total time: {elapsed_time_original}')

            #validate constraints violations
            if validate_feasability:
                violations = mp.FindConstraintsViolation(model_original.cmodel, strains, routes)
                cc_vn = violations['capacity_constraints'][1]
                rc_vn = violations['route_constraints'][1]
                if cc_vn == 0 and rc_vn == 0:
                    print('Feasible')
                else:
                    print(f'Capacity constraint violations number: {cc_vn}')
                    print(f'Route constraint violations number: {rc_vn}')
            print('__________________________________________________________')
            
            #recover feasible for given primal routes
            if recover_feasible_original:
                solver = solvers['Recovered']
                start_time_recovered = t.perf_counter()
                solution = mp.RecoverFeasibleStrain(model_original, routes, solver)
                elapsed_time_recovered = t.perf_counter() - start_time_recovered
                if solution is None:
                    results['Recovered_from_primal'] = None
                    print('###################!RESULTS!#############################')
                    print('Recovered_from_primal:\nSolution was not found!')
                    print('__________________________________________________________')
                else:
                    objective, strains, routes, time = ( solution['Objective'], solution['Strain'], 
                                                        solution['Route'], solution['Time'] )

                    results['Recovered_from_primal'] = { 'Objective': objective, 'Time': time, 'Total time': elapsed_time_recovered }

                    print('###################!RESULTS!#############################')
                    print(f'Recovered_from_primal:\nObjective: {objective}, Time: {time}, Total time: {elapsed_time_recovered}')
                    
                    #validate constraints violations
                    if validate_feasability:
                        violations = mp.FindConstraintsViolation(model_original.cmodel, strains, routes)
                        cc_vn = violations['capacity_constraints'][1]
                        rc_vn = violations['route_constraints'][1]
                        if cc_vn == 0 and rc_vn == 0:
                            print('Feasible')
                        else:
                            print(f'Capacity constraint violations number: {cc_vn}')
                            print(f'Route constraint violations number: {rc_vn}')
                    print('__________________________________________________________')


            #draw if needed
            if draw_solution:
                path_list_sol =  [ [edge for edge, value in route.items() if abs(value - 1) <= 1e-6] for route in routes ]
                flow_list_sol = strains
                network_graph.SetPath(*path_list_sol)
                network_graph.SetFlows(*flow_list_sol)
                dr.PlotNetwork(network_graph, 'ORIGINAL')

    #show figures if needed
    if draw_solution or draw_progress:
        dr.ShowAll()

    return results
Example #28
0

angles, triangles = Opt.optimize(Data.getAngles(), 0.05 , 100, 10)
print(angles)
print(triangles)
print(Opt.getPoints(angles))
triError, pointError = Opt.getError(triangles, Opt.getPoints(angles))
print(triError)
print(pointError)


triError, pointError = Opt.getError(Opt.getTriangles(Data.getAngles()), Opt.getPoints(Data.getAngles()))
print(triError)
print(pointError)
"""


angles = Data.getAngles()
print(Opt.getErrors(angles))
#angles, triangles = Opt.optimize(angles, 0.05 , 100, 10)
print(Opt.getErrors(angles))
angles = LF.makeConcatonatedAngles(angles,10)
lengths = LF.findAllLengths(angles, "GJK", 330.0025)
print(lengths)
#print(angles)
azi = Co.findAllAzimuths(angles, "FH", 257.78)
#print(azi)
coords = Co.findCoordinates(azi, lengths, "F")
print(coords)
Draw.drawPoints(coords)
Draw.drawSides(azi ,coords)
Example #29
0
def main(arg, width):
    """
    this method runs the app
    """

    if arg == "" and width == 0:
        try:
            arg = str(parser.parse_args()).split("'")[1]
            width = parser.parse_args().w
            save_name = parser.parse_args().save_name
            ansi_flag = parser.parse_args().ansi_flag
            image_flag = parser.parse_args().img_flag
            if save_name is None:
                sys.stdout.write('!!!Type filename to save in!!!\n'
                                 'Use -s *filename*')
                sys.exit(1)

        except Exception as e:
            print(e)
            app = GuiCls.QApplication(sys.argv)
            GuiCls.Window()
            parser.parse_args()
            sys.exit(app.exec_())
    try:
        drawer = DrCls.Drawer(arg)
        res = drawer.resize_image(width)
        pixels = drawer.get_image_data()
        arr = drawer.draw_picture(pixels)
        img = drawer.to_ascii_art(arr, res[0])
        with open("%s.txt" % save_name, "w") as f:
            f.write(img)

        print('\n------------------------------------\n'
              'Now you can find your image on %s.txt!'
              '\n------------------------------------\n' % save_name)
        print(img + '\n')

        if ansi_flag:
            _tuple = (arr, res)
            ansi_img = drawer.to_ansi_art(_tuple)
            sys.stdout.write('Type filename to save ansi in: ')
            ansi_name = input()
            with open("%s.txt" % ansi_name, "w") as f:
                f.write(ansi_img)

            print('\n------------------------------------\n'
                  'Now you can find your ansi image on %s.txt!'
                  '\n------------------------------------\n' % ansi_name)

        if image_flag:
            sys.stdout.write('Type filename to save image in: ')
            image_name = input()
            result_image = drawer.get_img(save_name)
            result_image.save("%s.png" % image_name)

            print('\n------------------------------------\n'
                  'Now you can find your png image on %s.png!'
                  '\n------------------------------------\n' % image_name)

        return img

    except Exception as e:
        print(e)
        raise
Example #30
0
 def drawblocks(self,scr):
     drawsize = [self.size[0]-self.hide,self.size[1]]
     drawpos = [self.nowpos[0]-self.hide, self.nowpos[1]]
     Drawer.draw_blocks(scr, drawsize, self.map[self.hide:], self.now, drawpos)
def subTask2():
    my_maze = Maze.Maze()
    my_maze.generateMazeJSON(JsonManager.read(choose_file("./mazes")))
    Drawer.drawMaze(my_maze)
    print("Solution storage on \\results folder.")
Example #32
0
 def drawtips(self,scr):
     Drawer.draw_tips(scr, self.next)
Example #33
0
	# Initialize nodes and walls, scan
	#nodes = from_files()
	#walls = [Wall.Wall(Point(0,0), Point(0,0))]
#
	#Drawer.draw(nodes, walls)
#
	##for n in nodes:
	##	n.pred_x = 0
	##	n.pred_y = 0
	##	n.pred_angle = 0
	##	n.real_x = 0
	##	n.real_y = 0
	##	n.real_angle = 0
	#Drawer.draw(nodes, [])
	#s = SLAM.SLAM(nodes)
	#print(s.solve_multi())
	##s.gravitate()
	#Drawer.draw(nodes, walls)
	#Drawer.draw(nodes, [])

	for i in range(3):
		i = 'samapt/data%d.txt' % i
		for j in range(3):
			j = 'samapt/data%d.txt' % (j + 3)
			for k in range(3):
				k = 'samapt/data%d.txt' % (k + 6)
				nodes = from_files([i, j, k])
				s = SLAM.SLAM(nodes)
				print(s.solve_multi())
				Drawer.draw(nodes, [], quickclose=True)
Example #34
0
 def drawinfo(self,scr):
     Drawer.draw_info(scr, [self.level,self.line,self.score])
Example #35
0
def subTask2():

    my_maze = Maze.Maze()
    my_maze.generateMazeJSON(JsonManager.read(askopenfilename()))
    Drawer.drawMaze(my_maze)
Example #36
0
import ImageAnalyzer
import random
import time

pygame.init()

screen = pygame.display.set_mode((1200, 700))
drawings = ["apple", "bird", "candle", "clock", "coffee mug", "finger", "moustache", "smiley face"]

textColor = (10, 10, 10)
largeFont = pygame.font.SysFont("leelawadeeuisemilight", 48)
smallFont = pygame.font.SysFont("leelawadeeuisemilight", 36)
inactiveButtonColor = (255, 220, 84)
activeButtonColor = (255, 204, 0)

pen = Drawer.Drawer(textColor, largeFont, smallFont, inactiveButtonColor, activeButtonColor)
analyzer = ImageAnalyzer.ImageAnalyzer()

def clearScreen(backgroundColor = (255, 112, 112)):
    """Fills entire screen with a single color"""
    screen.fill(backgroundColor)

def homeScreen():
    """Displays Home screen"""
    
    clearScreen()
    homeScreenLoop = True
    
    path = os.path.abspath('Stats.txt')
    statsFile = open(path, "r")
    successRate = int(int(statsFile.readlines(1)[0]) / int(statsFile.readlines(2)[0]) * 100)