Exemplo n.º 1
0
def main(benchmarks, name, tsp, cores, timeout, sequential, prio_conflicts,
         debug, verbose, official):
    if not name:
        name = f"pc={'T' if prio_conflicts else 'F'}," \
               f"ord={'T' if sequential else 'F'}"
        if not sequential:
            name = f"tsp={tsp}," + name
    if official:
        name += ' (TU)'

    def prepped_solver(problem: Problem) -> List:
        return solver(problem, {
            "tsp": tsp.lower(),
            "pc": prio_conflicts,
            "ord": sequential
        })

    api_key = open("api_key.txt", "r").read().strip()
    benchmark = MapfwBenchmarker(api_key,
                                 benchmarks,
                                 "A*+OD+ID",
                                 name,
                                 debug,
                                 prepped_solver,
                                 cores=cores,
                                 timeout=timeout)
    logger.start(info=debug, debug=verbose)
    benchmark.run()
    logger.stop()
Exemplo n.º 2
0
def shutdown():
    if lp_events.timer != None:                          # cancel any outstanding events
        lp_events.timer.cancel()

    scripts.to_run = []                                  # remove anything from the list of scripts scheduled to run

    for x in range(9):
        for y in range(9):
            if scripts.buttons[x][y].thread != None:
                scripts.buttons[x][y].thread.kill.set()  # request to kill any running threads

    if window.lp_connected or window.IsStandalone:
        scripts.Unbind_all()                             # unbind all the buttons
        lp_events.timer.cancel()                         # cancel all the timers
        if LP != None and LP != -1:
            launchpad_connector.disconnect(LP)           # disconnect from the launchpad
        window.lp_connected = False

    logger.stop()                                        # stop logging

    if window.restart:
        window.restart = False                           # don't do this forever
        if IS_EXE:
            os.startfile(sys.argv[0])
        else:
            os.execv(sys.executable, ["\"" + sys.executable + "\""] + sys.argv)

    sys.exit("[LPHK] Shutting down...")
Exemplo n.º 3
0
def main():
    log.init()

    my_gui = MainWindow()

    log.init(my_gui)
    my_gui.run()
    log.stop()
Exemplo n.º 4
0
def shutdown():
    if lp_events.timer != None:
        lp_events.timer.cancel()
    scripts.to_run = []
    for x in range(9):
        for y in range(9):
            if scripts.threads[x][y] != None:
                scripts.threads[x][y].kill.set()
    if window.lp_connected:
        scripts.unbind_all()
        lp_events.timer.cancel()
        launchpad_connector.disconnect(lp)
        window.lp_connected = False
    logger.stop()
    if window.restart:
        if IS_EXE:
            os.startfile(sys.argv[0])
        else:
            os.execv(sys.executable, ["\"" + sys.executable + "\""] + sys.argv)
    sys.exit("[LPHK] Shutting down...")
Exemplo n.º 5
0
            t11 = time.perf_counter()
            log.message(DEFINES.LOG_MESSAGE_PRIORITY_INFO, 0,
                        'Launching calibration plotting')
            calibration.plot_calib(calibrationResults,
                                   programParameters.fileParameters)
            (days, hours, minutes,
             seconds) = mm.decompose_time(time.perf_counter() - t11)
            log.message(DEFINES.LOG_MESSAGE_PRIORITY_DEBUG_INFO, 0,
                        f'Done in {seconds:5.2f}s')

    #close all handles and multiprocessing instances
    log.message(DEFINES.LOG_MESSAGE_PRIORITY_INFO, 0, 'Stopping the program')
    programParameters.stop_all()

    (days, hours, minutes,
     seconds) = mm.decompose_time(time.perf_counter() - t0)
    log.message(
        DEFINES.LOG_MESSAGE_PRIORITY_INFO, 0,
        f'All done in {days:02d}d {hours:02d}h{minutes:02d}m{seconds:04.1f}s')

    log.message(DEFINES.LOG_MESSAGE_PRIORITY_INFO, 0,
                'Holding for figures display...')
    # plt.show()

    return True

if __name__ == '__main__':
    log.init()
    main()
    log.stop()
Exemplo n.º 6
0
def main():
    import matplotlib.image as mpimg
    import matplotlib.pyplot as plt
    from computeCentroid import compute_centroid as compute_centroid
    import classConfig

    # try:
    #   try:
    #       raise OSError
    #   except OSError:
    #       raise errors.CameraError("error1")

    #   try:
    #       raise OSError
    #   except OSError:
    #       raise errors.CameraError("error2")
    # except Exception as e:
    #   print(e)

    #Set the default values
    im_path = os.path.join('Python_garbage', 'garbage.png')

    nbCentroidsLoop = 1000
    ncComputationsPerCentroid = 1
    centroids_txt_path = os.path.join('Python_garbage', 'centroids.mat')

    image_ID = 1
    exposure_time = 250
    gain = 0.0
    black_level = 1.25
    gamma = 1.0

    ROI = np.zeros(5, dtype=np.uint16)

    #python grab_image.py "" "..\41000-Matlab-Calibration_and_test\calibration_data_cam1_XY.mat" 1 12345 4 11111 2 2.5 1.5 1.5
    nb_args = len(sys.argv) - 1

    if nb_args > 0:
        im_path = sys.argv[1]
    if nb_args > 1:
        cam_path = sys.argv[2]
    if nb_args > 2:
        camera_ID = int(sys.argv[3])
    if nb_args > 3:
        image_ID = int(sys.argv[4])
    if nb_args > 4:
        nb_images = int(sys.argv[5])
    if nb_args > 5:
        exposure_time = float(sys.argv[6])
    if nb_args > 6:
        gain = float(sys.argv[7])
    if nb_args > 7:
        black_level = float(sys.argv[8])
    if nb_args > 8:
        gamma = float(sys.argv[9])

    if im_path != '' or image_ID > -1:
        centroid = (0, 0, 0, 0, 0, 0, 0, 0)

        try:
            #create camera instance
            camera = Camera(cameraType=DEFINES.PC_CAMERA_TYPE_XY,
                            compatibleCameraID=22289804)  #22942361 #22994237

            #_=os.system('echo Taking picture')
            camera.setMaxROI()
            exposure_time = camera.getOptimalExposure(exposure_time)
            log.message(DEFINES.LOG_MESSAGE_PRIORITY_INFO, 0,
                        f'Exposure time is: {exposure_time:.1f}')
            if exposure_time >= DEFINES.PC_CAMERA_XY_MAX_EXPOSURE:
                log.message(DEFINES.LOG_MESSAGE_PRIORITY_ERROR, 0,
                            f'Max exposure was reached')
                camera.close()
                return
            camera.setProperties(exposure_time, gain, black_level, gamma)

            if image_ID > -1:
                config = classConfig.Config()
                camera.setDistortionCorrection(config)

            centroids = np.zeros((nbCentroidsLoop, 3))
            minimum = 1000000 * np.ones(2)
            maximum = 0 * np.ones(2)
            mean = 0 * np.ones(2)
            std = 0 * np.ones(2)

            #Get first centroid to set ROI
            picture = camera.getImage()

            #Save the image
            if im_path != '':
                mpimg.imsave(im_path, picture)

            #compute the centroid
            if image_ID > -1:
                centroid = compute_centroid(picture, camera.parameters,
                                            image_ID)

            if np.isnan(centroid[0]):
                log.message(DEFINES.LOG_MESSAGE_PRIORITY_WARNING, 0,
                            "No centroid detected")
                return

            ROI[0] = int(centroid[2])
            ROI[1] = int(centroid[3])
            ROI[2] = camera.parameters.minCropWindow + 20
            ROI[3] = camera.parameters.minCropWindow
            ROI[4] = np.sqrt(ROI[2]**2 + ROI[3]**2)

            camera.setROI(ROI)
            print("camera params", camera.parameters)

            for i in range(0, nbCentroidsLoop):
                currentComputation = []
                for j in range(0, ncComputationsPerCentroid):
                    t0 = time.perf_counter()
                    picture = camera.getImage()

                    #Save the image
                    if im_path != '':
                        mpimg.imsave(im_path, picture)

                    #compute the centroid
                    t1 = time.perf_counter()
                    if image_ID > -1:
                        currentComputation.append(
                            compute_centroid(picture, camera.parameters,
                                             image_ID))

                    # log.message(DEFINES.LOG_MESSAGE_PRIORITY_WARNING, 0, f'Image: {t1-t0:4.3f} s. Centroid: {time.perf_counter()-t1:4.3f} s')

                    if np.isnan(centroid[0]):
                        log.message(DEFINES.LOG_MESSAGE_PRIORITY_WARNING, 0,
                                    "No centroid detected")
                        raise errors.CameraError("Fiber light went out")

                currentComputation = np.array(currentComputation)
                # print(currentComputation)
                # print(currentComputation[0])
                # print(currentComputation[0,0])

                centroid = (np.mean(currentComputation[:,0]),\
                            np.mean(currentComputation[:,1]),\
                            np.mean(currentComputation[:,2]),\
                            np.mean(currentComputation[:,3]),\
                            np.mean(currentComputation[:,4]),\
                            np.mean(currentComputation[:,5]),\
                            np.mean(currentComputation[:,6]),\
                            currentComputation[0,7])

                centroids[i, 2] = i
                for j in range(0, 2):
                    centroids[i, j] = centroid[j]
                    if centroid[j] < minimum[j]:
                        minimum[j] = centroid[j]
                    if centroid[j] > maximum[j]:
                        maximum[j] = centroid[j]
                    mean[j] = np.mean(centroids[0:(i + 1), j])
                    std[j] = np.std(centroids[0:(i + 1), j])

                log.message(DEFINES.LOG_MESSAGE_PRIORITY_INFO, 0,   f'{centroid[0]:.6f},{centroid[1]:.6f},{centroid[6]:.6f}'+\
                                                                    f' Centroid {i+1:4}/{nbCentroidsLoop:4}'+\
                                                                    f' Max diff: {maximum[0]-minimum[0]:.6f},{maximum[1]-minimum[1]:.6f}'+\
                                                                    f' Mean: {mean[0]:.6f},{mean[1]:.6f}'+\
                                                                    f' STD: {std[0]:.6f},{std[1]:.6f}')

            centroids[:, 0] = centroids[:, 0] - np.nanmean(centroids[:, 0])
            centroids[:, 1] = centroids[:, 1] - np.nanmean(centroids[:, 1])

        except errors.CameraError as e:
            log.message(DEFINES.LOG_MESSAGE_PRIORITY_CRITICAL, 0, str(e))
            log.stop()
            return

        try:
            io.savemat(centroids_txt_path, \
                {'centroids': centroids})
        except OSError as e:
            log.message(DEFINES.LOG_MESSAGE_PRIORITY_CRITICAL, 0, str(e))
            log.stop()
            return

        camera.close()

        plt.figure()

        plt.scatter(centroids[:, 0],
                    centroids[:, 1],
                    color='red',
                    marker='x',
                    s=1)
        plt.show()
Exemplo n.º 7
0
def __send_email_measurement_error(mailto, step):
    """
    Sends an email to the recipient to notify that an execution error has occurred during the measurement.

    :param mailto: Recipient's email address.
    :param step: Step where the error has occurred.
    """

    global ERRORTEMPLATEPATH, FROM, LOGFILE_DIR, LOGFILE, attachError, session

    # Variable
    attachError = None

    print(Fore.CYAN + "     Sending email to the following email address: " +
          mailto + " to notify the measurement"
          " error" + Fore.RESET),

    # Subject of the email
    subject = "HYOT - Measurement error - Step: " + step

    # Message of the email in HTML format
    try:
        message = __read_template(
            os.path.dirname(os.path.abspath(__file__)) + "/" +
            ERRORTEMPLATEPATH).substitute(STEP=step)

    except Exception as templateError:
        print(Fore.RED + " ✖ Error in the email template. Exception: " +
              str(templateError) + ".\n" + Fore.RESET)
        sys.exit(1)

    time.sleep(0.5)

    # Creates an instance of MIMEMultipart
    email_instance = MIMEMultipart()

    # Constructs the email
    email_instance["From"] = FROM  # Sender's email address
    email_instance["To"] = mailto  # Recipient's email address
    email_instance["Subject"] = subject

    # Creates and attaches the message in HTML text
    email_instance.attach(MIMEText(message, 'html'))

    try:
        # Stops the logger and returns print functionality to normal. Also, the log file is closed
        logger.stop()

        # Opens the file to attach
        attachment = open(LOGFILE_DIR + "/" + LOGFILE, "rb")

        # Creates an instance of MIMEBase
        part = MIMEBase('application', 'octet-stream')

        # Steps to convert the file into a Base64
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        "attachment; filename= %s" % LOGFILE)

        # Closes the open file
        attachment.close()

        # Attaches the file
        email_instance.attach(part)

    except IOError as attachedError:  # Error to open the file
        attachError = "     Could not open the log file so it is not attached to the email. Exception: "\
                      + str(attachedError) + ".\n"

    try:
        # Sends the message via a SMTP server
        session.sendmail(FROM, mailto, email_instance.as_string())

        print(Fore.GREEN + " ✓" + Fore.RESET)

        if not (attachError is None):
            print(Fore.YELLOW + attachError + Fore.RESET)

    except Exception as sendError:
        print(Fore.RED + " ✖ Error to send the email. Exception: " +
              str(sendError) + ".\n" + Fore.RESET)
        sys.exit(1)