예제 #1
0
 def jsSetNavigationIndex(self, index):
     """
         Creates the javascript to switch to a different position within the items:
         index - the first item you want to appear in your pages results
     """
     return "WebElements.get('%(id)sIndex').value = '%(index)d';%(handlers)s;" % {
         "id": self.fullId(),
         "index": index,
         "handlers": "\n".join([ClientSide.var(result) for result in self.emit("jsIndexChanged")]),
     }
예제 #2
0
    def __init__(self,host,port, screen):

        self.sock = socket()

        try:
            #Connecting to socket
            self.sock.connect((host, port)) #Connect takes tuple of host and port
        except Exception as msg:
            print "Could not connect to server.\nError msg : ", msg
            ClientSide.PokerClient(screen)
예제 #3
0
def combination_peaks(peak_batch,temp_name,user_info,URL,fam):
    outpath = "Ready"
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    
    find_valid_peaks = list(powerset(peak_batch["vec"]))
    find_valid_peaks = [item for item in find_valid_peaks if len(item) > 3 and len(item) < 6]
    print(len(find_valid_peaks),"valid peak combinations")

    valid_peaks_combinations = [{"vec":proto_combo} for proto_combo in find_valid_peaks]
    found = False
    threshold = 0
    guesses = {"species_1":[],
                "species_2":[],
                "species_3":[],
                "species_4":[]}

    common_peaks = []
    failed_combos = valid_peaks_combinations
    #peak_locs,user_info,URL,fam
    persistance = 0
    LIMIT = 3

    while len(failed_combos) > 0 and persistance < LIMIT:
        for combo in failed_combos:
            try:
                classificated = ClientSide.Send_For_Classification(combo, user_info, URL, fam)
                print(classificated)
                classificated["file_name"] = temp_name
                write_to_csv(os.path.join(outpath,temp_name) + ".csv", classificated)

                guesses['species_1'].append(classificated["species_1"])
                guesses['species_2'].append(classificated["species_2"])
                guesses['species_3'].append(classificated["species_3"])
                guesses['species_4'].append(classificated["species_4"])
                
                common_peaks.append(classificated["species_1"])
                common_peaks.append(classificated["species_2"])
                common_peaks.append(classificated["species_3"])
                common_peaks.append(classificated["species_4"])
                
                # remove the classified combination
                failed_combos.remove(combo)
            except KeyboardInterrupt:
                raise
            except:
                print("An error occured this combination was not classified.\nIt will be retried {} more times".format(LIMIT-persistance))

        persistance += 1

    if len(failed_combos)>0:
        print("there were {} failed combinations".format(len(failed_combos)))

    return common_peaks, guesses
예제 #4
0
파일: main.py 프로젝트: alchem9st/Poker
    def __init__(self):

        pygame.init()
        pygame.display.set_caption(CAPTION)
        screen = pygame.display.set_mode((WIDTH,HEIGHT))#Create Window
        self.load_stuff()

        screen.blit(BG0, (0,0)) #Set background image
        screen.blit(self.TXT_WELCOME, self.TXT_WELCOME_RECT) #Write Welcome

        #Parameters:      surface,      color,       x,   y,   length, height, width,    text,      text_color
        self.BUT_SERVER.create_button(screen, BACK_BUTTON, WIDTH/3, HEIGHT/3.55, WIDTH/3.2,    HEIGHT/6.85,    0,        "Server", TEXT_BUTTON)
        self.BUT_CLIENT.create_button(screen, BACK_BUTTON, WIDTH/3, HEIGHT/1.88, WIDTH/3.2,    HEIGHT/6.85,    0,        "Client", TEXT_BUTTON)

        quit = False
        while not quit :
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

                elif event.type == MOUSEBUTTONDOWN:
                    if self.BUT_SERVER.pressed(pygame.mouse.get_pos()):
                        state = 1
                        quit = True
                        break

                    if self.BUT_CLIENT.pressed(pygame.mouse.get_pos()):
                        state = 2
                        quit = True
                        break
            pygame.display.update()

        if state == 1:
            ServerSide.PokerServer(screen)
        elif state == 2:
            ClientSide.PokerClient(screen)
예제 #5
0
 def getNotificationPermission(self):
     return ClientSide.getNotificationPermission()
예제 #6
0
 def selectedOption(self):
     return ClientSide.selectedOption(self)
예제 #7
0
 def deincrement(self, min=None):
     return ClientSide.deincrement(self, min)
예제 #8
0
 def addOptions(self, options):
     return ClientSide.addOptions(self, options)
예제 #9
0
 def increment(self, max=None):
     return ClientSide.increment(self, max)
예제 #10
0
 def showIfSelected(self, elementToShow):
     return ClientSide.showIfSelected(self.element.parent.clientSide, self, elementToShow)
예제 #11
0
 def callOpener(self, method):
     return ClientSide.callOpener(method)
예제 #12
0
 def confirm(self, message, action):
     return ClientSide.confirm(message, action)
예제 #13
0
 def serializeAll(self):
     return ClientSide.serializeAll(self)
예제 #14
0
 def serializeElements(self, elements):
     return ClientSide.serializeElements(self, elements)
예제 #15
0
 def stopOperation(self, event):
     return ClientSide.stopOperation(event)
예제 #16
0
 def showNotification(self, title, content, icon=IMAGES_URL + "info.png"):
     return ClientSide.showNotification(title, content, icon)
예제 #17
0
 def scrolledToBottom(self):
     return ClientSide.scrolledToBottom(self)
예제 #18
0
 def select(self):
     return ClientSide.selectOption(self.element.parent.clientSide, self)
예제 #19
0
 def updateParent(self):
     return ClientSide.updateParent()
예제 #20
0
 def value(self):
     return ClientSide.getValue(self)
예제 #21
0
 def focus(self, selectText=False):
     return ClientSide.focus(self, selectText)
예제 #22
0
 def addOption(self, optionName, optionValue=None):
     return ClientSide.addOption(self, optionName, optionValue)
예제 #23
0
 def redirect(self, to):
     return ClientSide.redirect(to)
예제 #24
0
 def sort(self, sortByValue=False):
     return ClientSide.sortSelect(self, sortByValue)
예제 #25
0
 def expandTemplate(self, template, valueDictionary):
     return ClientSide.expandTemplate(template, valueDictionary)
예제 #26
0
 def setOptions(self, options):
     return ClientSide.setOptions(self, options)
예제 #27
0
 def showIfSelected(self, option, elementToShow):
     return ClientSide.showIfSelected(option, elementToShow, self)
예제 #28
0
 def selectOption(self, option):
     return ClientSide.selectOption(self, option)
예제 #29
0
 def toggleClass(self, className):
     return ClientSide.toggleClass(self, className)
예제 #30
0
 def selectText(self, start, end):
     return ClientSide.selectText(self, start, end)
예제 #31
0
 def showIfChecked(self, elementToShow):
     return ClientSide.showIfChecked(elementToShow, self)
예제 #32
0
def main():

    parser = build_parser()
    options = parser.parse_args()

    print(options.session)

    # opens the user specified session
    if options.session:
        with open(os.path.join("Sessions",options.session),'r') as f:
            session = json.load(f)

    # opens the default session    
    else:
        with open(DEFAULT_SESSION,'r') as f:

            session = json.load(f)

    # set variables from loaded session data
    fam = session["crystal_family"]
    provide_family = session["known_family"]
    display_type = session["display_type"]
    auto_calibrate = session["auto_calibrate"]
    file_path = session["file_path"]
    output_file = session["output_file"]
    is_profile = session["is_profile"]
    manual_peak_selection = session["manual_peak_selection"]
    scale_bar = session["scale_bar"]
    
    # Load calibration from specified file (json)
    try:
        print("Loading calibration from {}".format(os.path.join("Calibrations",auto_calibrate)))  
        with open(os.path.join("Calibrations",auto_calibrate),'r') as f:
            calibration = json.load(f)

    except:
        print("No calibration could be loaded from {}\nPlease check the file exists and is formatted properly".format(auto_calibrate))
        calibration = cf.set_calibration(is_profile)
    print(calibration)

    with open(SERVER_INFO,'r') as f:
        server_info = json.load(f)
        
    if server_info['URL']:
        URL = server_info['URL']
    else:
        raise ValueError('you need to have the server URL provided to you')
        

    # Load user from provided path, [IN PROGRESS]
    with open(USER_INFO) as f:
        user_info = json.load(f)
    
    if not os.path.exists(file_path):
        print("The path provided could not be found. Please check your session file path")
        return

    # Determine if the path is a directory or a file
    if os.path.isdir(file_path):
        print("loading files from directory")
        file_paths = []
        for dirpath,dirnames,fpath in os.walk(file_path):
            for path in fpath:
                file_paths.append(os.path.join(dirpath,path))
        print("found {} files to load.".format(len(file_paths)))

    else:
        file_paths = [file_path]
    
    print(file_paths)
    for f_path in file_paths:

        # Load Data from specified file (DM3, TIFF, CSV etc....)
        try:
            print("loading data from {}".format(f_path))
            image_data = ClientSide.Load_Image(f_path)
            print("I successfully loaded the data")
        except:
            print("Invalid file path given ({}).\n Please enter filepath to your data".format(f_path))
            options.fpath = input()

        # Change the processing based on data type
        if is_profile:

            # Choose which profile if there are multiple
            image_data,scale = cf.choose_profile(image_data)
        
        else:
            pass
            #plt.imshow(np.log(image_data))
            #plt.show(block=False)
            #plt.show()

        # Change the Processing based on the type of data
        if is_profile:
            print("identifying from profile")
            radial_profile = {"brightness":image_data,
                                "pixel_range":scale}

        else:
            radial_profile = ClientSide.Extract_Profile(image_data)    

       
        peak_locs = ClientSide.Find_Peaks(radial_profile,calibration,is_profile,display_type,scale_bar)
        print(peak_locs)

        
        # Choose which peaks to classify on
        if manual_peak_selection:
            peak_locs = cf.choose_peaks(peak_locs,display_type)


        if provide_family =="yes":

            while fam is None:
                temp_fam = input("What family does the Crystal belong to?\n")
                if temp_fam in FAMILIES:
                    fam = temp_fam
                else:
                    print("Invalid choice. choose from {}\n".format(str(FAMILIES)[1:-1]))
        elif provide_family == "no":
            fam = None
            
        print(peak_locs)

        with open(os.path.join("Results",f_path.split(os.sep)[-1][:-4]+".json"), "w") as o:
            o.write(json.dumps(peak_locs))                
        
        lower_gen = SpGr.edges["genus"][fam][0]
        upper_gen = SpGr.edges["genus"][fam][1]
        fam_range = range(SpGr.edges["species"][lower_gen][0],1+SpGr.edges["species"][upper_gen][1])
        
        common_peaks,guesses = combination_peaks(peak_locs,f_path.split(os.sep)[-1][:-4],user_info,URL,fam)
        
        plt.figure(figsize=(len(fam_range)//2,4))
        prev_histograms = []
        plots = []

        for rank in range(1,5):
            histo = np.histogram([int(g) for g in guesses["species_{}".format(rank)]],bins=fam_range)
            #histo[0] = histo[0]*(2-(rank/5.0))
           
            if rank > 1:
                plot = plt.bar(histo[1][:-1],histo[0],
                    bottom=np.sum(np.vstack(prev_histograms),axis=0),align="center")
            else:
                plot = plt.bar(histo[1][:-1],histo[0],align="center",color='red')

            plots.append(plot)
            plt.yticks(rotation='vertical')
            plt.xticks(histo[1][:-1],rotation='vertical')
            prev_histograms.append(histo[0])

        plt.xlabel("Prediction",fontsize=10,rotation='vertical')
        plt.ylabel("Counts",fontsize=10)
        #plt.legend(plots,("species_1","species_2","species_3","species_4"))
        if not os.path.exists("Results"):
            os.makedirs("Results")
        print("Results/"+f_path.split(os.sep)[-1][:-4]+"gen1.png")
        plt.savefig("Results/" + f_path.split(os.sep)[-1][:-4] + "_gen1.png")
        plt.show(block=False)
예제 #33
0
 def actLikeRadio(self, pair):
     return ClientSide.checkboxActsLikeRadioButton(self, pair)
def main():

    parser = build_parser()
    options = parser.parse_args()

    print(options.session)

    # opens the user specified session
    if options.session:
        with open(os.path.join("Sessions", options.session), 'r') as f:
            session = json.load(f)

    # opens the default session
    else:
        with open(DEFAULT_SESSION, 'r') as f:

            session = json.load(f)

    # set variables from loaded session data
    fam = session["crystal_family"]
    provide_family = session["known_family"]
    display_type = session["display_type"]
    auto_calibrate = session["auto_calibrate"]
    file_path = session["file_path"]
    output_file = session["output_file"]
    is_profile = session["is_profile"]
    manual_peak_selection = session["manual_peak_selection"]
    scale_bar = session["scale_bar"]

    # Load calibration from specified file (json)
    try:
        print("Loading calibration from {}".format(
            os.path.join("Calibrations", auto_calibrate)))
        with open(os.path.join("Calibrations", auto_calibrate), 'r') as f:
            calibration = json.load(f)

    except:
        print(
            "No calibration could be loaded from {}\nPlease check the file exists and is formatted properly"
            .format(auto_calibrate))
        calibration = cf.set_calibration(is_profile)
    print(calibration)

    with open(SERVER_INFO, 'r') as f:
        server_info = json.load(f)

    if server_info['URL']:
        URL = server_info['URL']
    else:
        raise ValueError('you need to have the server URL provided to you')

    # Load user from provided path, [IN PROGRESS]
    with open(USER_INFO) as f:
        user_info = json.load(f)

    # Determine if the path is a directory or a file
    if os.path.isdir(file_path):
        print("loading files from directory")
        file_paths = []
        for dirpath, dirnames, fpath in os.walk(file_path):
            for path in fpath:
                file_paths.append(os.path.join(dirpath, path))
        print("found {} files to load.".format(len(file_paths)))

    else:
        file_paths = [file_path]

    print(file_paths)
    for f_path in file_paths:

        # Load Data from specified file (DM3, TIFF, CSV etc....)
        try:
            print("loading data from {}".format(f_path))
            image_data = ClientSide.Load_Image(f_path)
            print("I successfully loaded the data")
        except:
            print(
                "Invalid file path given ({}).\n Please enter filepath to your data"
                .format(f_path))
            options.fpath = input()

        # Change the processing based on data type
        if is_profile:

            # Choose which profile if there are multiple
            image_data, scale = cf.choose_profile(image_data)

        else:
            plt.imshow(np.log(image_data))
            plt.show(block=False)
            #plt.show()

        # Change the Processing based on the type of data
        if is_profile:
            print("identifying from profile")
            radial_profile = {"brightness": image_data, "pixel_range": scale}

        else:
            radial_profile = ClientSide.Extract_Profile(image_data)

        peak_locs = ClientSide.Find_Peaks(radial_profile, calibration,
                                          is_profile, display_type, scale_bar)

        # Choose which peaks to classify on
        if manual_peak_selection:
            peak_locs = cf.choose_peaks(peak_locs, display_type)

        if provide_family == "yes":

            while fam is None:
                temp_fam = input("What family does the Crystal belong to?\n")
                if temp_fam in FAMILIES:
                    fam = temp_fam
                else:
                    print("Invalid choice. choose from {}\n".format(
                        str(FAMILIES)[1:-1]))
        elif provide_family == "no":
            fam = None

        classificated = ClientSide.Send_For_Classification(
            peak_locs, user_info, URL, fam)

        classificated["file_name"] = f_path

        # update the user on the results before saving
        print(classificated)

        # write results out to the specified file
        if not os.path.exists("Results"):
            os.makedirs("Results")
        cf.write_to_csv(os.path.join("Results", output_file), classificated)
예제 #35
0
 def setValue(self, value):
     return ClientSide.setValue(self, value)