def convolute(self, kernel, fourier=None): """ The implement of convolution. It will choose a better algorithm to do it depends on the size of kernel and image. :param kernel: :param fourier:Whether use fourier transform to calculate the convolution :return: """ if not isinstance(kernel, Kernel.Kernel): try: kernel = Kernel.Kernel(kernel) except Exception: raise Exception('The input must be a kernel') kernel_size = kernel.shape[0] * kernel.shape[1] image_size = np.sqrt(self.shape[0] * self.shape[1]) if fourier is not None: if fourier: return self.__fourier_convolution(kernel) else: return self.__base_convolution(kernel) # According to the Mark Nixon's book(p.87 3rd version),If m² < 4*log(N) + 1, # then we should use direct implementation, otherwise the fourier transform should be considered. else: if kernel_size < 4 * np.log(image_size) + 1: return self.__base_convolution(kernel) else: return self.__fourier_convolution(kernel)
def createcobs(self, clustertype="kmeans", stats=False): ''' looks at all the files in self.directory and finds and with the same base name as self.name. each file is turned into a cob object, and add to self.cobs ''' for cobfile in os.listdir(self.directory): if '_' + self.name + "." in cobfile: filenamewithoutlastextension = os.path.splitext(cobfile)[0] basename = os.path.splitext(filenamewithoutlastextension)[0] kernellist = [] with open(self.directory + "/" + cobfile) as csvfile: csvreader = csv.reader(csvfile) csvlist = list(csvreader) listofpixels = [] currentkernel = 1 for line in csvlist[:-1]: try: if line[0] == 'Image': pass elif int(line[1] ) != currentkernel and line[4] != '': kernellist.append( Kernel.Kernel(listofpixels, name=currentkernel, clustertype="dbscan", stats=stats)) listofpixels = [] currentkernel = int(line[1]) currentpixel = [ int(line[2]), int(line[3]), int(line[4]) ] listofpixels.append(currentpixel) elif int(line[1]) == currentkernel: currentpixel = [ int(line[2]), int(line[3]), int(line[4]) ] listofpixels.append(currentpixel) except Exception, e: print str(e), "in create cobs" IndexError currentcob = Cob.Cob(kernellist, basename, pixelcluster=False, clustertype=clustertype, stats=stats) print "Finished Cob: ", basename self.coblist.append(currentcob)
def setKernelsandRGB(self, show=False): ''' For each entry in self.cobs, it will open the file with that name in repDirectory. The file is a csv file of the format "accessionName, Kernel, R, G, B". This function will return a list of ints that correspond to the number of kernels that are associated with the Cob file. ''' print "Creating Kernels and Pixels" progressBar = 0 for key in self.cobs: progressBar += 1 kernelList = [] filePath = self.repDirectory + "/" + key + ".tif.csv" with open(filePath) as csvFile: csvReader = csv.reader(csvFile) csvList = list(csvReader) print "Cob: ", progressBar, "/", len(self.cobs) listofpixels = [] currentKernel = 1 for line in csvList: try: if line[0] == 'Image': pass elif int(line[1]) != currentKernel and line[4] != '': kernelList.append( Kernel.Kernel(listofpixels, name=currentKernel)) if show == True: print "Kernel: %s" % currentKernel listofpixels = [] currentKernel = int(line[1]) currentPixel = Pixel.Pixel(int(line[2]), int(line[3]), int(line[4])) listofpixels.append(currentPixel) elif int(line[1]) == currentKernel: currentPixel = Pixel.Pixel(int(line[2]), int(line[3]), int(line[4])) listofpixels.append(currentPixel) except: IndexError self.cobs[key] = Cob.Cob(kernelList) print "Kernel's Initialized for %s" % key print "All Cob's Initialized"
space = [] count = 0 for i in range(100): space.append([]) for j in range(100): if rr(100) < 20: space[i].append(1) else: space[i].append(0) patterns = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [1, 1, 1], [0, 0, 0]], [[0, 1, 0], [0, 1, 0], [0, 1, 0]]] system = Kernel(3, 3, patterns) system['x'] = 20 system['y'] = 20 mover = Mover() target = [50, 40] for i in range(1000): input = extract(space, system) system.compute(target + [input]) mover.compute([system['output']]) target = [system['x'], system['y']] output = mover['output'] if output == 0: target[1] = system['y'] - 1
Programa5.add(IoInstruccion1) Programa5.add(IoInstruccion5) Programa5.add(CpuInstruccion4) myCDROM = CDROM() myPrinter = Printer() myMMU = MMU() myDiskWithPrograms = Disk() myDiskWithPrograms.load(Programa1) myDiskWithPrograms.load(Programa2) myDiskWithPrograms.load(Programa3) myDiskWithPrograms.load(Programa4) myDiskWithPrograms.load(Programa5) myEmptyDisk = Disk() asignacionContinua = AsignacionContinua(PrimerAjuste(),myMMU) myMMU.setLogicalMemory(asignacionContinua) #myKernel = Kernel(Fifo, myMMU, myEmptyDisk) myKernel = Kernel(Fifo, myMMU, myDiskWithPrograms) myKernel.addDevice(myCDROM) myKernel.addDevice(myPrinter) myKernel.initializeThread() myKernel.runProcess("Programa1") myKernel.runProcess("Programa2") myKernel.runProcess("Programa3") myKernel.runProcess("Programa4") myKernel.runProcess("Programa5")
import ParseGraph try: import xml.etree.cElementTree as ET except ImportError: import cElementTree as ET import sys import gzip from numpy import * from numpy.linalg import * import Kernel from MatrixBuilders import * floattype = float64 parser = "split_parse" tokenizer = "split" kernel = Kernel.Kernel() feature_counter = 0 def readInstances(a_file): """Parses the analysis file to extract the analyses on which the graphs will be based on""" result = {} print >> sys.stderr, "\rParsing file '%s' " %(a_file), acontent = iter(ET.iterparse(a_file,events=("start","end"))) event, root = acontent.next() for event, elem in [(a,b) for a,b in acontent if a=="end" and b.tag=="document"]: doc_id = elem.get("id") result[doc_id] = elem return result
# import sys # sys.path.append("../") import Kernel Seyana = Kernel.Kernel() Seyana.learn("other.aiml") Seyana.learn("wxAndroid-life.aiml") def dialogue(Content): response = Seyana.respond(Content) if response == "": response = "对不起,我没明白您在说什么" return response
# -*- coding: utf-8 -*- ''' @author: [email protected] @license: (C) Copyright 2017 @desc: python3 版本中文Alice,暂时简单添加空格 @DateTime: Created on 2017/11/15,at 10:20 ''' import Kernel import opencc alice = Kernel.Kernel() alice.learn("cn-test.aiml") while True: input_data = input('Alice请您提问...>>') response = alice.respond(input_data) response = response.replace(" ", "") print(response)
from plot_data import * import Kernel import train if __name__ == '__main__': # Work on multiple traces of the same subject extract_data_files(1) # 1 - indicates that consider only the first subject #print(train_file_names) for file in train_file_names: frames_list, x_coordinates_list = file_wise_extract_data( file, 1, is_training=True) test_frames_list, test_x_coordinates_list = file_wise_extract_data( file, 1, is_training=False) gp = None kernel = Kernel.Kernel(1.0, 1.0) for frames, coordinates in zip(frames_list, x_coordinates_list): #plot_marker('1', np.reshape(frames, (-1, 1)), coordinates) #plot_show() if gp: gp = train.train(gp, kernel, frames, coordinates, sigma2=1.0) else: gp = train.train(None, kernel, frames, coordinates, sigma2=1.0) define_labels(file, '1') plot_marker_test(np.reshape(test_frames_list, (-1, 1)), np.reshape(test_x_coordinates_list, (-1, 1)), None, 'bo', labels='Observations') for test_frames, test_coordinates in zip(test_frames_list,
#coding:utf-8 import Kernel if __name__ == '__main__': Kia = Kernel.Kernel() #Kia.learn("cn-test.aiml") #Kia.learn("bye.aiml") #Kia.learn("Common conversation.aiml") #Kia.learn("funny.aiml") Kia.learn("Kia.aiml") #Kia.learn("OrdinaryQuestion.aiml") #Kia.learn("personname.aiml") Kia.learn("nk.aiml") #Kia.learn("tools.aiml") #Kia.learn("tuling.aiml") while True: print('>>' + Kia.respond(input('问小开>>')))
def main(argv): #path="C:\\Temp\\tmp_qqbot" #存放临时文件和aiml文件的路径 path=this_path+"\\temp" isDebug=True question='null' msid='null' try: opts,args=getopt.getopt(argv,"hc:s:",["content=","sid="]) except getopt.GetoptError: print('Error: Kia.py -c <content> -s <sid>') print(' or: Kia.py --content=<content> --sid=<sid>') sys.exit(2) for opt,arg in opts: if opt=="-h": print('usage:Kia.py -c <content> -s <sid>') print(' or: Kia.py --content=<content> --sid=<sid>') sys.exit() elif opt in ("-s","--sid"): msid=arg elif opt in ("-c","--content"): question=arg print('q='+question) print('sid='+msid) if (question=='null' or msid=='null'): print('Error: Kia.py -c <content> -s <sid>') print(' or: Kia.py --content=<content> --sid=<sid>') sys.exit(2) #——————————————学习初始化————————_ Kia=Kernel.Kernel() Kia.learn(path+"\\Kia.aiml") Kia.learn(path+"\\nk.aiml") Kia.learn(path+"\\learnNewU.aiml") os.chdir(path) if isDebug : print(os.getcwd()) print(os.listdir()) #QandSID=input('问小开>>').split(' ') #question=QandSID[0] #sid=QandSID[1] #——————添加本次对话———————— caches=os.listdir() cache=open(msid+'.txt','a+') cache.write(question+'\n') cache.close() #----------复原对话---------- cache=open(msid+'.txt','r') lines=cache.readlines() res1=RunQA.major(question) if (res1.find('#fail')>-1): for line in lines: respond=Kia.respond(line.strip()) #最后一次respond即为答案 if isDebug: print('usr:'******'Kia:'+respond) else: respond=res1 print('ans='+respond.strip())
import Kernel import Processo import time def varius(*arg): st = "a " for i in arg: st = st + "%i " print(st % arg) varius(1, 2, 4, 5, 6) kn = Kernel.Kernel(usuario, quantum, escalonador[0]) kn.start() def recuperar(nome, identidade): global kn return kn.encontrar(nome, identidade) ##print(software["fibonacciN"]) ##Processos com busy wait Peterson kn.novoProcesso("mulB", 2, software["mulB"], 2.4, 20, "A") kn.novoProcesso("mulB", 2, software["mulB"], 2.1, 21, "A") kn.novoProcesso("adB", 2, software["adB"], 2.4, 20, "B")
def main(self): memoria = Memory() file_system = FileSystem() kernel = Kernel(memoria, file_system) kernel.execute()
try: from math import tau except ImportError: from math import pi tau = pi * 2 """ Laser software for the Stock-LIHUIYU laserboard. MeerK40t (pronounced MeerKat) is a built-from-the-ground-up MIT licensed open-source laser cutting software. See https://github.com/meerk40t/meerk40t for full details. """ kernel = Kernel() # TODO: CLI Needs an option to change default speed, etc, parameters. # TODO: CLI Needs home command / lock, unlock. # TODO: CLI Needs command for load special module. parser = argparse.ArgumentParser() parser.add_argument('-l', '--list', type=str, nargs="*", help='list all device properties') parser.add_argument('-z', '--no_gui', action='store_true', help='run without gui')