コード例 #1
0
 def drawStuff(self, background=False):
     Samp = Sampler()
     if background:
         Points = [-2, -1, 4, -1, 4, 1, -2, 1]
     else:
         Points = [-1, -1, 1, -1, 1, 1, -1, 1]
     Indicies = [0, 1, 2, 0, 2, 3]
     for i in range(len(Points)):
         Points[i] = Points[i] * self.scale
     Array = array.array("f", Points)
     ArrayBuffer = Buffer(Array)
     IndicieArray = array.array("I", Indicies)
     IndicieBuffer = Buffer(IndicieArray)
     TextureBuffer = Buffer(array.array("f", [0, 0, 1, 0, 1, 1, 0, 1]))
     tmp = array.array("I", [0])
     glGenVertexArrays(1, tmp)
     vao = tmp[0]
     glBindVertexArray(vao)
     ArrayBuffer.bind(GL_ARRAY_BUFFER)
     IndicieBuffer.bind(GL_ELEMENT_ARRAY_BUFFER)
     glEnableVertexAttribArray(0)
     glVertexAttribPointer(0, 2, GL_FLOAT, False, 2 * 4, 0)
     TextureBuffer.bind(GL_ARRAY_BUFFER)
     glEnableVertexAttribArray(1)
     glVertexAttribPointer(1, 2, GL_FLOAT, False, 2 * 4, 0)
     glBindVertexArray(0)
     self.samp = Samp
     self.vao = vao
コード例 #2
0
 def __init__(self, settings, input_stream=None, output_stream=None):
     self.settings = settings
     self.input_stream = input_stream
     self.output_stream = output_stream
     self.carr_buffer = Buffer.Buffer(self.settings.CHUNK)
     self.mod_buffer = Buffer.Buffer(self.settings.CHUNK)
     self.output_buffer = Buffer.Buffer(self.settings.CHUNK)
     self.carrier_threshold = -40
コード例 #3
0
def main():
    """"
    Test functionality
    """
    _buffer_ = Buffer.Buffer(4)

    threads = []

    for i in range(3):
        _aux_ = Producer.Producer(_buffer_)
        threads.append(_aux_)

    for i in range(5):
        _aux_ = Consumer.Consumer(30, _buffer_)
        threads.append(_aux_)

    for i in range(8):
        threads[i].start()

    for i in range(8):
        threads[i].join()

    Consumer.Consumer._ans_.sort(key=lambda x: x[1])
    print map(lambda x: x[0], Consumer.Consumer._ans_)
    print _buffer_._check_ans_
コード例 #4
0
 def startChatTo(self, username):
     addr = self.requestPort(username)
     if addr is None:
         return False
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     buff = Buffer.Buffer(self.lock)
     if username in self.message_list_dict:
         service = Service_client.Service_client(
             s,
             buff,
             self.message_list_dict[username],
             self.username,
             peer=username,
             ip=self.ip)
         self.buff_dict[username] = service.buffer
     else:
         message_list = GUII.Message_list(self.chatui.Message_box_frame)
         service = Service_client.Service_client(s,
                                                 buff,
                                                 message_list,
                                                 self.username,
                                                 peer=username,
                                                 ip=self.ip)
         self.buff_dict[username] = service.buffer
         self.message_list_dict[username] = service.message_list
     print(addr)
     service.connectTo(addr)
     service.start()
     self.chatui.update()
     return True
コード例 #5
0
 def __init__(self):
     self.relations = {}
     self.selection_algorithms = ['scanning', 'binary', 'indexed']
     self.buf_size = 512
     self.blk_size = 64
     self.buffer = Buffer(self.buf_size, self.blk_size)
     self.tree = ''
     self.routing_table_join = {'nested_loop_join', 'sort_merge_join', 'hash_join'}
コード例 #6
0
 def getBlob(self, fp, tag):
     line = fp.readline().decode()
     lst = line.split()
     assert lst[0] == tag
     numbytes = int(lst[1])
     B = fp.read(numbytes)
     buf = Buffer(B)
     fp.readline()  # discard empty line
     return buf
コード例 #7
0
 def readBlob(self, fp, name):
     line = fp.readline().decode()
     assert line.startswith(name)
     lst = line.split()
     numbytes = int(lst[1])
     blob = fp.read(numbytes)
     fp.readline()
     B = Buffer(blob)
     return B
コード例 #8
0
def main():
    # Read the inputs from the file
    buf_size, num_pkts, packets = read_input('./testcases.txt')

    # Create the packet buffer
    buffer = Buffer.Buffer(buf_size)

    # Process the packets
    process_packets(buffer, packets)
コード例 #9
0
    def __init__(self, fontname, size):
        if Text.prog == None:
            Text.prog = Program("TextVertexShader.txt",
                                "TextFragmentShader.txt")

        self.txt = "temp"
        self.samp = Sampler()
        self.font = TTF_OpenFont(
            os.path.join("assets", fontname).encode(), size)
        open(os.path.join("assets", fontname))
        vbuff = Buffer(array.array("f", [0, 0, 1, 0, 1, 1, 0, 1]))
        ibuff = Buffer(array.array("I", [0, 1, 2, 0, 2, 3]))
        tmp = array.array("I", [0])
        glGenVertexArrays(1, tmp)
        self.vao = tmp[0]
        glBindVertexArray(self.vao)
        ibuff.bind(GL_ELEMENT_ARRAY_BUFFER)
        vbuff.bind(GL_ARRAY_BUFFER)
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 2, GL_FLOAT, False, 2 * 4, 0)
        glBindVertexArray(0)
        self.tex = DataTexture2DArray(1, 1, 1, array.array("B", [0, 0, 0, 0]))
        self.textQuadSize = vec2(0, 0)
        self.pos = vec2(0, 0)
        self.dirty = False
        surf1p = TTF_RenderUTF8_Blended(self.font, self.txt.encode(),
                                        SDL_Color(255, 255, 255, 255))
        surf2p = SDL_ConvertSurfaceFormat(surf1p, SDL_PIXELFORMAT_ABGR8888, 0)
        w = surf2p.contents.w
        h = surf2p.contents.h
        pitch = surf2p.contents.pitch
        if pitch != w * 4:
            print("Uh Oh!", pitch, w)
        pix = surf2p.contents.pixels
        B = string_at(pix, pitch * h)
        self.tex.setData(w, h, 1, B)
        SDL_FreeSurface(surf2p)
        SDL_FreeSurface(surf1p)
        self.textQuadSize = vec2(w, h)
        self.dirty = False

        Program.setUniform("textPosInPixels", self.pos)
        Program.setUniform("textQuadSizeInPixels", self.textQuadSize)
        Program.updateUniforms()
コード例 #10
0
def makeSquare(xsz, ysz, flipTextureY):
    vbuff = Buffer(
        array.array("f", [-xsz, -ysz, xsz, -ysz, xsz, ysz, -xsz, ysz]))
    if flipTextureY:
        tbuff = Buffer(array.array("f", [0, 1, 1, 1, 1, 0, 0, 0]))
    else:
        tbuff = Buffer(array.array("f", [0, 0, 1, 0, 1, 1, 0, 1]))
    ibuff = Buffer(array.array("I", [0, 1, 2, 0, 2, 3]))
    tmp = array.array("I", [0])
    glGenVertexArrays(1, tmp)
    vao = tmp[0]
    glBindVertexArray(vao)
    ibuff.bind(GL_ELEMENT_ARRAY_BUFFER)
    vbuff.bind(GL_ARRAY_BUFFER)
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 2, GL_FLOAT, False, 2 * 4, 0)
    tbuff.bind(GL_ARRAY_BUFFER)
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, False, 2 * 4, 0)
    glBindVertexArray(0)
    return vao
コード例 #11
0
 def __init__(self, fontname, size):
     if Text.prog == None:
         Text.prog = Program("textvs.txt", "textfs.txt")
         TTF_Init()
     self.font = TTF_OpenFont(
         os.path.join("assets", fontname).encode(), size)
     vbuff = Buffer(array.array("f", [0, 0, 1, 0, 1, 1, 0, 1]))
     ibuff = Buffer(array.array("I", [0, 1, 2, 0, 2, 3]))
     tmp = array.array("I", [0])
     glGenVertexArrays(1, tmp)
     self.vao = tmp[0]
     glBindVertexArray(self.vao)
     ibuff.bind(GL_ELEMENT_ARRAY_BUFFER)
     vbuff.bind(GL_ARRAY_BUFFER)
     glEnableVertexAttribArray(0)
     glVertexAttribPointer(0, 2, GL_FLOAT, False, 2 * 4, 0)
     glBindVertexArray(0)
     self.tex = DataTexture2DArray(1, 1, 1, array.array("B", [0, 0, 0, 0]))
     self.textQuadSize = vec2(0, 0)
     self.pos = vec2(0, 0)
     self.dirty = False
コード例 #12
0
    def bindVao(self, vArray, iArray = None):
        vBuff = Buffer(vArray)
        # GenerateVAO
        tmp = array.array("I", [0])
        glGenVertexArrays(1, tmp)
        vao = tmp[0]
        glBindVertexArray(vao)

        # Tell GL about buffer layout and use the buffer
        # Bind index buffer to point at vertexbuffers indicies if available
        if iArray != None and len(iArray) != 0:
            ibuff = Buffer(iArray)
            ibuff.bind(GL_ELEMENT_ARRAY_BUFFER)

        vBuff.bind(GL_ARRAY_BUFFER)

        glEnableVertexAttribArray(0)

        # which pipe, items per vertex, type per item, auto-normalize, data size per item in bytes, start in buffer
        # numPoints = len(arrayOfPoints)
        glVertexAttribPointer(0, 2, GL_FLOAT, False, 2 * 4, 0)
コード例 #13
0
    def __init__(self, sizeOfBuffer, numberOfCores, numberOfThreads,
                 timeQuantum, contextSwitchTime):
        Buffer.Buffer.initBufferCount()
        self.buffer = Buffer.Buffer(sizeOfBuffer)
        self.numberOfCores = numberOfCores
        self.cores = []

        for y in list(range(numberOfCores)):
            self.cores.append(Core.Core(y, 0))

        self.threadPool = ThreadPool.ThreadPool(numberOfThreads)
        self.timeQuantum = timeQuantum
        self.contextSwitchTime = contextSwitchTime
コード例 #14
0
    def setupUniforms(prog):
        tmp = array.array("I", [0])
        glGetProgramiv(prog, GL_ACTIVE_UNIFORMS, tmp)
        numuniforms = tmp[0]
        uniformsToQuery = array.array("I", range(numuniforms))
        offsets = array.array("I", [0] * numuniforms)
        sizes = array.array("I", [0] * numuniforms)
        types = array.array("I", [0] * numuniforms)
        glGetActiveUniformsiv(prog, numuniforms, uniformsToQuery,
                              GL_UNIFORM_OFFSET, offsets)
        glGetActiveUniformsiv(prog, numuniforms, uniformsToQuery,
                              GL_UNIFORM_SIZE, sizes)
        glGetActiveUniformsiv(prog, numuniforms, uniformsToQuery,
                              GL_UNIFORM_TYPE, types)

        sizeForType = {
            GL_FLOAT_VEC4: 4 * 4,
            GL_FLOAT_VEC3: 3 * 4,
            GL_FLOAT_VEC2: 2 * 4,
            GL_FLOAT: 1 * 4,
            GL_INT: 1 * 4,
            GL_FLOAT_MAT4: 4 * 16,
            GL_FLOAT_MAT3: 3 * 16,
            GL_FLOAT_MAT2: 2 * 16
        }

        nameBytes = bytearray(256)
        Program.totalUniformBytes = 0
        for i in range(numuniforms):
            glGetActiveUniformName(prog, i, len(nameBytes), tmp, nameBytes)
            nameLen = tmp[0]
            name = nameBytes[:nameLen].decode()
            if offsets[i] != 0xffffffff:
                assert sizes[i] == 1 or types[i] == GL_FLOAT_VEC4
                numBytes = sizeForType[types[i]] * sizes[i]
                Program.uniforms[name] = (offsets[i], numBytes, types[i],
                                          sizes[i])
                end = offsets[i] + numBytes
                if end > Program.totalUniformBytes:
                    Program.totalUniformBytes = end
        #create_string_buffer is inside the ctypes package
        Program.uboBackingMemory = create_string_buffer(
            Program.totalUniformBytes)
        #addressof is from ctypes too
        Program.uboBackingAddress = addressof(Program.uboBackingMemory)
        Program.ubo = Buffer(data=None,
                             size=Program.totalUniformBytes,
                             usage=GL_DYNAMIC_DRAW)

        Program.ubo.bindBase(GL_UNIFORM_BUFFER, 0)
コード例 #15
0
def makeStars():
    starPoints = []
    for i in range(3 * globs.numStars):
        starPoints.append(random.uniform(-1, 1))
    buff = Buffer(array.array("f", starPoints))

    tmp = array.array("I", [0])
    glGenVertexArrays(1, tmp)
    starVao = tmp[0]
    glBindVertexArray(starVao)
    buff.bind(GL_ARRAY_BUFFER)
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, False, 3 * 4, 0)
    glBindVertexArray(0)
    return starVao
コード例 #16
0
ファイル: Project.py プロジェクト: AaizAhmed/HubbleSimulator
def RunSatellite():

    # Add the FOR loops first

    buffer = Buffer.Buffer(10)
    buff = buffer.getBuffer()

    satellie = Satellite.Satellite(buff, 10)
    satellie.start()

    satellie.join()

    receiver = Receiver.Receiver(buff, 10)
    receiver.start()

    receiver.join()
コード例 #17
0
    def listen_run(self):
        self.listen_socket.listen()
        while self.listen_flag:
            print('accept1')
            conn, addr = self.listen_socket.accept()
            if self.listen_flag:
                buff = Buffer.Buffer(self.lock)
                message_list = GUII.Message_list(self.chatui.Message_box_frame)
                service = Service_client.Service_client(conn,
                                                        buff,
                                                        message_list,
                                                        self.username,
                                                        ip=self.ip)
                self.buff_dict[service.peer] = service.buffer
                if service.peer in self.message_list_dict:
                    service.message_list = self.message_list_dict[service.peer]
                else:
                    self.message_list_dict[service.peer] = service.message_list
                self.chatui.update()
                service.start()

        print('closed')
コード例 #18
0
ファイル: main.py プロジェクト: ThomasMGilman/ETGG-2801_2
def setup(pointArray):
    glEnable(GL_MULTISAMPLE)
    glClearColor(0, 0, 0, 1.0)

    my_buffer = Buffer(pointArray)#array.array("f", [0, 0]))
    # GenerateVAO
    tmp = array.array("I", [0])
    glGenVertexArrays(1, tmp)
    vao = tmp[0]
    glBindVertexArray(vao)

    # Tell GL about buffer layout and use the buffer
    my_buffer.bind(GL_ARRAY_BUFFER)
    glEnableVertexAttribArray(0)
    # which pipe, items per vertex, type per item, auto-normalize, data size per item in bytes, start in buffer
    # numPoints = len(arrayOfPoints)
    glVertexAttribPointer(0, 2, GL_FLOAT, False, 2 * 4, 0)

    # unbind
    # glBindVertexArray(0)

    prog = Program("vs.txt", "fs.txt")
    prog.use()
コード例 #19
0
    def connectToCamera(self):
        # We cannot connect to a camera if devices are already connected and stream synchronization is in progress
        if (self.actionSynchronizeStreams.isChecked()
                and len(self.deviceUrlDict) > 0
                and self.sharedImageBuffer.getSyncEnabled()):
            # Prompt user
            QMessageBox.warning(
                self, "pyqt5-cv2-multithreaded",
                "Stream synchronization is in progress.\n\n"
                "Please close all currently open streams "
                "before attempting to open a new stream.",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        # Attempt to connect to camera
        else:
            # Get next tab index
            nextTabIndex = 0 if len(
                self.deviceUrlDict) == 0 else self.tabWidget.count()
            # Show dialog
            cameraConnectDialog = CameraConnectDialog(
                self, self.actionSynchronizeStreams.isChecked())
            if cameraConnectDialog.exec() == QDialog.Accepted:
                # Save user-defined device deviceUrl
                deviceUrl = cameraConnectDialog.getDeviceUrl()
                # Check if this camera is already connected
                if deviceUrl not in self.deviceUrlDict:
                    # Create ImageBuffer with user-defined size
                    imageBuffer = Buffer(
                        cameraConnectDialog.getImageBufferSize())
                    # Add created ImageBuffer to SharedImageBuffer object
                    self.sharedImageBuffer.add(
                        deviceUrl, imageBuffer,
                        self.actionSynchronizeStreams.isChecked())
                    # Create CameraView
                    cameraView = CameraView(self.tabWidget, deviceUrl,
                                            self.sharedImageBuffer,
                                            self.cameraNum)

                    # Check if stream synchronization is enabled
                    if self.actionSynchronizeStreams.isChecked():
                        # Prompt user
                        ret = QMessageBox.question(
                            self, "pyqt5-cv2-multithreaded",
                            "Stream synchronization is enabled.\n\n"
                            "Do you want to start processing?\n\n"
                            "Choose 'No' if you would like to open "
                            "additional streams.",
                            QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                        # Start processing
                        if ret == QMessageBox.Yes:
                            self.sharedImageBuffer.setSyncEnabled(True)
                        # Defer processing
                        else:
                            self.sharedImageBuffer.setSyncEnabled(False)

                    # Attempt to connect to camera
                    if cameraView.connectToCamera(
                            cameraConnectDialog.getDropFrameCheckBoxState(),
                            cameraConnectDialog.getApiPreference(),
                            cameraConnectDialog.getCaptureThreadPrio(),
                            cameraConnectDialog.getProcessingThreadPrio(),
                            cameraConnectDialog.
                            getEnableFrameProcessingCheckBoxState(),
                            cameraConnectDialog.getResolutionWidth(),
                            cameraConnectDialog.getResolutionHeight(),
                            cameraConnectDialog.getVideoSetting()):

                        self.cameraNum += 1
                        # Save tab label
                        tabLabel = cameraConnectDialog.getTabLabel()
                        # Allow tabs to be closed
                        self.tabWidget.setTabsClosable(True)
                        # If start tab, remove
                        if nextTabIndex == 0:
                            self.tabWidget.removeTab(0)
                        # Add tab
                        self.tabWidget.addTab(
                            cameraView, '%s [%s]' % (tabLabel, deviceUrl))
                        self.tabWidget.setCurrentWidget(cameraView)
                        # Set tooltips
                        self.setTabCloseToolTips(self.tabWidget,
                                                 "Disconnect Camera")
                        # Prevent user from enabling/disabling stream synchronization
                        # after a camera has been connected
                        self.actionSynchronizeStreams.setEnabled(False)
                        # Add to map
                        self.cameraViewDict[deviceUrl] = cameraView
                        self.deviceUrlDict[deviceUrl] = nextTabIndex
                    # Could not connect to camera
                    else:
                        # Display error message
                        QMessageBox.warning(
                            self, "ERROR:", "Could not connect to camera. "
                            "Please check device deviceUrl.")
                        # Explicitly delete widget
                        cameraView.delete()
                        # Remove from shared buffer
                        self.sharedImageBuffer.removeByDeviceUrl(deviceUrl)
                        # Explicitly delete ImageBuffer object
                        del imageBuffer
                # Display error message
                else:
                    QMessageBox.warning(
                        self, "ERROR:",
                        "Could not connect to camera. Already connected.")
コード例 #20
0
# Instantiate conveyor belts
# (a conveyor belt carries individual PCBs)
from ConveyorBelt import *
belt_1 = ConveyorBelt(env=env, name="belt_1", capacity=3)
belt_2 = ConveyorBelt(env=env, name="belt_2", capacity=3)
belt_3 = ConveyorBelt(env=env, name="belt_3", capacity=3)
belt_4 = ConveyorBelt(env=env, name="belt_4", capacity=3)
belt_5 = ConveyorBelt(env=env, name="belt_5", capacity=3)

belts = [belt_1, belt_2, belt_3, belt_4, belt_5]

# Instantiate buffers
# (a buffer holds a stack of PCBs)
from Buffer import *
buff_11 = Buffer(env, name="buff_11", capacity=1)
buff_12 = Buffer(env, name="buff_12", capacity=1)

buff_21 = Buffer(env, name="buff_21", capacity=1)
buff_22 = Buffer(env, name="buff_22", capacity=1)

buff_3 = Buffer(env, name="buff_3", capacity=1)
buff_4 = Buffer(env, name="buff_4", capacity=1)
buff_5 = Buffer(env, name="buff_5", capacity=1)
buff_6 = Buffer(env, name="buff_6", capacity=1)

# Instantiate machines and connect them using conveyor belts/buffers

from Source import *
source_1 = Source(env=env, name="source_1", outp=buff_11)
source_2 = Source(env=env, name="source_2", outp=buff_12)
コード例 #21
0
 def bufferStarter(self):
     self.buffer = Buffer(10, 10, 10)
コード例 #22
0
def setup():
    global starAmount
    global starsVao
    global quadProg
    global StarProgram
    global ShipProg
    global beep
    global enemyProg
    global enemy1Prog
    global backgroundProg
    global main_program
    global monster_program
    global ship
    global fire
    global enemy
    global enemy1
    global nebula
    global powerup
    global powerup1
    global cam
    global monster
    global starList
    global bullet1
    global myShip
    global skyboxProg
    global skybox
    global skyboxTexture

    beep = Mix_LoadWAV(os.path.join("assets", "Beep-09.ogg").encode())

    glEnable(GL_MULTISAMPLE)
    glClearColor(0.0, 0.0, 0.0, 1.0)

    starAmount = 50
    starList = []
    star_points = []
    for i in range(starAmount):
        starList.append(Star())

    for i in range(len(starList)):
        star_points.append(starList[i].x)
        star_points.append(starList[i].y)

    A = array.array("f", star_points)
    b = Buffer(A)
    tmp = array.array("I", [0])
    glGenVertexArrays(1, tmp)
    starsVao = tmp[0]
    glBindVertexArray(starsVao)
    b.bind(GL_ARRAY_BUFFER)
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 2, GL_FLOAT, False, 2 * 4, 0)
    glBindVertexArray(0)

    myShip = Ship()

    cam = Camera(myShip.pos, myShip.up, myShip.facing)

    for i in range(3):
        asteroid_list.append(Asteroid(vec4(0, 0, 0, 0)))

    skyboxTexture = ImageTextureCube("nebula-%04d.jpg")
    skybox = Mesh("cube.obj.mesh")
    skybox.materials[0].tex = skyboxTexture

    skyboxProg = Program("skyboxVertexShader.txt", "skyboxFragmentShader.txt")
    StarProgram = Program("StarsVertexShader.txt", "StarsFragmentShader.txt")
    main_program = Program("MainVS.txt", "MainFS.txt")

    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LEQUAL)

    Program.setUniform("lightPos",
                       vec3(0, 1, -1) + myShip.pos.xyz)  #vec3(0,1,-1)
    Program.updateUniforms()

    print("Setup Done")
コード例 #23
0
ファイル: input_tests.py プロジェクト: jakubWrobel94/Vocoder
input_stream = p.open(format=pyaudio.paFloat32,
                      channels=2,
                      rate=44100,
                      input=True,
                      frames_per_buffer=CHUNK,
                      input_device_index=3)

out_stream = p.open(format=pyaudio.paFloat32,
                    channels=1,
                    rate=44100,
                    output=True,
                    frames_per_buffer=CHUNK,
                    input_device_index=5)
data = []
carr_buffer = Buffer.Buffer(CHUNK)
mod_buffer = Buffer.Buffer(CHUNK)
out_buffer = Buffer.Buffer(CHUNK)
window = signal.windows.hann(2 * CHUNK)

spectr_filters, filt_freqs = Buffer.get_spectrum_filters(
    FILT_LOW, FILT_UP, N_FILT, N_FFT, RATE)
filt_coefs = np.zeros((N_FILT, N_FFT))

for i in range(0, 2000):
    data = input_stream.read(CHUNK)
    signal_from_device = np.frombuffer(data, dtype='f4').reshape(-1, 2)

    carr_frame = signal_from_device[:, 0]
    mod_frame = signal_from_device[:, 1]
コード例 #24
0
ファイル: teste1.py プロジェクト: allanedgard/pdss
import Buffer
import time
y = int(time.time() * 1000)
time.sleep(.001)
x = Buffer.Buffer()
x.add(int(time.time() * 1000) % y, 'teste 1')
x.add(int(time.time() * 1000) % y, 'teste 2')
time.sleep(.001)
x.add(int(time.time() * 1000) % y, 'prova 3')
x.add(int(time.time() * 1000) % y, 'prova 4')
print x.getMsgs(int(time.time() * 1000) % y)
time.sleep(.001)
x.add(int(time.time() * 1000) % y, 'teste 1')
x.add(int(time.time() * 1000) % y, 'teste 2')
time.sleep(.001)
x.add(int(time.time() * 1000) % y, 'prova 3')
print x.getMsgs(int(time.time() * 1000) % y)
コード例 #25
0
        intensor = buf.getTensor()
        intensor = tf.expand_dims(intensor, 0)
        predictions = new_model.predict(intensor, steps=1)[0]
        thread = PredictionThread()
        thread.start()


if __name__ == "__main__":
    # print(tf.version.VERSION)

    # Recreate the exact same model, including its weights and the optimizer

    # create a video object capturing from device with id 0
    vid = cv2.VideoCapture(0)
    print("width: {} height: {}".format(vid.get(3), vid.get(4)))
    buf = Buffer.Buffer()
    new_model = tf.keras.models.load_model('test.h5')

    # Show the model architecture
    # new_model.summary()
    RESLABELS = {}
    CNT = 0
    check = [0, '']
    # print("initializing")
    # time.sleep(3)

    while True:
        if ret1 == 1:
            buf.clear()
            time.sleep(3)
            ret1 = None
コード例 #26
0
from Buffer import *
""" Testing Functions """
print("Testing Functions")
b = Buffer(10)
it = b.iterator()
print("b = Buffer(10)\nit = b.iterator()")
print("--" * 10)
for i in range(10):
    print("b.enqueue(", i, ")")
    b.enqueue(i)
print("--" * 10)
print("Printing Buffer via iterator")
while it.hasNext():
    print(it.Next(), end=" ")
print()
print("--" * 10)
for i in range(3):
    print("b.dequeue(", i, ")")
    b.dequeue()
print("--" * 10)
print("Printing Buffer via iterator")
it.init()
while it.hasNext():
    print(it.Next(), end=" ")
print("\n")
""" Testing Exceptions """

print("Testing Exceptions")
try:
    for i in range(100):
        print("b.dequeue(", i, ")")
コード例 #27
0
    def run_simulation(self,simulation_time, generate_activity_log):
        
        #check arguments:
        assert(simulation_time >= 1)
        assert(isinstance(self.model_parameters,dict))

        # Create a SimPy Environment:
        env=simpy.Environment()

        # We use the following timing convention:
        #   All machines operate at integer time-instants n = 0, 1, 2, 3,...
        #   All conveyor belts move in the middle of the integer instants t = 0.5, 1.5, 2.5, ...


        # Instantiate conveyor belts
        # (a conveyor belt carries individual PCBs)
        belt_1 = ConveyorBelt(env=env, name="belt_1", capacity=3)
        belt_2 = ConveyorBelt(env=env, name="belt_2", capacity=3)
        belt_3 = ConveyorBelt(env=env, name="belt_3", capacity=3)
        belt_4 = ConveyorBelt(env=env, name="belt_4", capacity=3)
        belt_5 = ConveyorBelt(env=env, name="belt_5", capacity=3)

        belts = [belt_1, belt_2, belt_3, belt_4, belt_5]

        # Instantiate buffers
        # (a buffer holds a stack of PCBs)
        buff_11=Buffer(env, name="buff_11", capacity=1)
        buff_12=Buffer(env, name="buff_12", capacity=1)
        buff_21=Buffer(env, name="buff_21", capacity=1)
        buff_22=Buffer(env, name="buff_22", capacity=1)
        buff_3=Buffer(env, name="buff_3", capacity=1)
        buff_4=Buffer(env, name="buff_4", capacity=1)
        buff_5=Buffer(env, name="buff_5", capacity=1)
        buff_6=Buffer(env, name="buff_6", capacity=1)


        # Instantiate machines and connect them using conveyor belts/buffers
        source_1         = Source (env=env, name="source_1", outp=buff_11)
        source_2         = Source (env=env, name="source_2", outp=buff_12)

        baking_oven_1    = BakingOven (env=env, name="baking_oven_1", inp=buff_11, outp=buff_21)
        baking_oven_2    = BakingOven (env=env, name="baking_oven_2", inp=buff_12, outp=buff_22)

        human_loader     = HumanLoader (env=env, name="human_loader", inp_list=[buff_21,buff_22], outp=buff_3 )
        line_loader      = LineLoader (env=env, name="line_loader", inp=buff_3, outp=belt_1 )
        screen_printer   = ScreenPrinter (env=env, name="screen_printer", inp=belt_1, outp=belt_2 )
        pick_and_place_1 = PickAndPlace (env=env, name="pick_and_place_1", inp=belt_2, outp=belt_3 )
        pick_and_place_2 = PickAndPlace (env=env, name="pick_and_place_2", inp=belt_3, outp=belt_4 )
        reflow_oven      = ReflowOven (env=env, name="reflow_oven", inp=belt_4, outp=belt_5 )
        line_downloader  = LineDownloader (env=env, name="line_downloader", inp=belt_5, outp=buff_6 )
        sink_1             = Sink (env=env, name="sink_1", inp=buff_6)
        sink_1.delay=0

        machines= [line_loader, screen_printer, pick_and_place_1, pick_and_place_2, reflow_oven, line_downloader]

        # human operators
        human_operator_1 = HumanOperator (env=env, name="human_operator_1")
        human_operator_2 = HumanOperator (env=env, name="human_operator_2")

        
        
        # Set machine parameters
        #
        # Source:
        # A source creates a PCB stack of a given type 
        # periodically after a certain delay, 
        # and places the stack at its output.
        # The source stalls if there's no place at the output.
        source_1.delay = 100
        source_1.PCB_type = 1
        source_1.PCB_stack_size=10

        source_2.delay = 10
        source_2.PCB_type = 2
        source_2.PCB_stack_size=10

        # BakingOven:
        #
        # A baking oven waits until there is a stack
        # of PCBs at it's input, then bakes the stack
        # for 'delay' time and then places the stack 
        # at its output. 
        baking_oven_1.delay = self.model_parameters["baking_oven_1"]["parameters"]["delay"]["value"]
        baking_oven_1.on_temp = self.model_parameters["baking_oven_1"]["parameters"]["on_temperature"]["value"]
        baking_oven_2.delay = self.model_parameters["baking_oven_2"]["parameters"]["delay"]["value"]
        baking_oven_2.on_temp = self.model_parameters["baking_oven_2"]["parameters"]["on_temperature"]["value"]

        #
        # HumanLoader:
        #
        # The human loader keeps checking
        # if jobs are available in a given list
        # of input buffers, and places them
        # as they arrive at the input of the line loader.
        # delay: time between picking up a job and 
        #placing it near the line loader.
        human_loader.delay = 1 

        # LineLoader:
        # 
        # A line loader waits until there is a stack of PCBs
        # at its input. Then, it picks up PCBs from the stack
        # one at a time and places them on the conveyor belt.
        # parameters: 
        #   delay (between picking up and placing each pcb)
        line_loader.delay= self.model_parameters["line_loader"]["parameters"]["delay"]["value"]

        # ScreenPrinter:
        #
        #   The ScreenPrinter performs printing, one PCB at a time.
        #   Each PCB consumes a certain amount of solder and adhesive
        #   and incurs a certain amount of delay depending on the PCB's type_ID.
        #   When the solder or adhesive levels falls below a certain threshold, 
        #   a human operator is informed and the printing is paused 
        #   until a refill is made by the operator.
        #   Parameters:
        screen_printer.solder_capacity=200
        screen_printer.solder_initial_amount=2

        screen_printer.adhesive_capacity=200
        screen_printer.adhesive_initial_amount=200

        screen_printer.delay= self.model_parameters["screen_printer"]["parameters"]["delay"]["value"]


        # Assign some human operators to 
        # handle refilling tasks in the screen printer.
        # A human operator remains idle until interrupted
        # by a machine and then performs the assigned task.
        screen_printer.set_refill_operator(human_operator_1)

        human_operator_1.assign_task(task_name="solder_refill",machine_name="screen_printer", task_ptr=solder_refill_task, machine_ptr=screen_printer, delay=3)
        human_operator_1.assign_task(task_name="adhesive_refill",machine_name="screen_printer", task_ptr=adhesive_refill_task, machine_ptr=screen_printer, delay=3)



        ## PickAndPlace:
        ##
        ##  The PickAndPlace machine performs component placement one PCB at a time.
        ##  Each PCB consumes a certain number of components from the reels.
        ##  The time required to process a PCB is proportional
        ##  to the number of components in it
        ##   Parameters:
        pick_and_place_1.delay=self.model_parameters["pick_and_place_1"]["parameters"]["delay"]["value"]
        pick_and_place_2.delay=self.model_parameters["pick_and_place_2"]["parameters"]["delay"]["value"]

        # ReflowOven:
        # 
        # The ReflowOven is similar to a conveyor belt.
        # The entire length of the belt is divided into a fixed number of stages, 
        # with each stage representing the placeholder for a single job.
        # After each 'delay' amounts of time, the conveyor belt moves right,
        # (akin to a shift-right operation) and a job that was 
        # in stage i moves to stage i+1.
        # However, unlike a conveyour belt, the ReflowOven's belt
        # does not stall. 
        # Parameters:
        reflow_oven.num_stages= self.model_parameters["reflow_oven"]["parameters"]["num_stages"]["value"]
        reflow_oven.delay=self.model_parameters["reflow_oven"]["parameters"]["delay"]["value"]

        # LineDownloader.py
        #
        # Collects PCBS one by one from the conveyor belt
        # and loads them into a stack
        # Parameters:
        line_downloader.PCB_stack_size=source_1.PCB_stack_size 


        
        # Run simulation, 
        T = int(simulation_time)
        assert(T>1)
        print("Running simulation for", T," seconds")

        #Generate the activity log into a file
        if(generate_activity_log==True):
            activity_log_file = open("activity_log.txt","w")
            sys.stdout = activity_log_file
            current_time = datetime.datetime.now()
            current_time_str = current_time.strftime("%Y-%m-%d %H:%M")
            print("==============================================")
            print("Activity Log generated on ",current_time_str)
            print("Simulation time = ",T)
            print("==============================================")
        else:
            nothing = open(os.devnull, 'w')
            sys.stdout = nothing

        # run the simulation
        env.run(until=T)
        sys.stdout = sys.__stdout__

        if(generate_activity_log==True):
            print("Activity log generated in file: activity_log.txt")
        
        # Generate results into a string object
        results_string = StringIO()
        sys.stdout = results_string

        print("\n================================")
        print("Stats:")
        print("================================")
        print ("Total time elapsed = ",env.now," seconds")
        print ("Total number of stacks processed =",sink_1.num_stacks_completed)
        print ("Average cycle-time per stack = ",sink_1.average_cycle_time, "seconds")
        print ("Average throughput = ",sink_1.num_stacks_completed/float(env.now)*60," stacks per minute")

        machines = [baking_oven_1, baking_oven_2, line_loader, screen_printer, pick_and_place_1, pick_and_place_2,reflow_oven,line_downloader]
        humans = [human_loader, human_operator_1, human_operator_2]

        print("\n================================")
        print("Utilization Report (operators): ")
        print("================================")
        for i in machines:
            i.print_utilization()
        for i in humans:
            i.print_utilization()

        print("\n================================")
        print("Utilization Report (conveyor belts): ")
        print("================================")
        for i in belts:
            i.print_utilization()

        print("\n================================")
        print("Energy Consumption: ")
        print("================================")
        for i in machines:
            i.print_energy_consumption()
        for i in belts:
            i.print_energy_consumption()
        print("================================")
        sys.stdout = sys.__stdout__
        return results_string
コード例 #28
0
ファイル: my_lpc.py プロジェクト: jakubWrobel94/Vocoder
def play():

    p = pyaudio.PyAudio()

    CHUNK = 1024
    PRE_EMP_COEF = 0.8

    for i in range(p.get_device_count()):
        print(p.get_device_info_by_index(i))

    carrier_path = 'wavs/carrier_2.wav'
    modulator_path = 'wavs/modulator_2.wav'

    mod_wave = wave.open(modulator_path, 'rb')
    carr_wave = wave.open(carrier_path, 'rb')

    FORMAT = p.get_format_from_width(carr_wave.getsampwidth())
    CHANNELS = carr_wave.getnchannels()
    RATE = carr_wave.getframerate()

    out_stream = p.open(format=pyaudio.paFloat32,
                    channels=CHANNELS,
                    rate=RATE,
                    output=True,
                    frames_per_buffer=CHUNK,
                    input_device_index=5)
    data = []
    carr_buffer = Buffer.Buffer(CHUNK)
    mod_buffer = Buffer.Buffer(CHUNK)
    out_buffer = Buffer.Buffer(CHUNK)
    window = signal.windows.hann(2*CHUNK)
    int16max = np.iinfo(np.int16).max
    for i in range(0, 100):
        carr_frame = carr_wave.readframes(1024)
        mod_frame = mod_wave.readframes(1024)
        carr_frame = np.frombuffer(carr_frame, np.int16)/int16max
        mod_frame = np.fromstring(mod_frame, np.int16)/int16max
        carr_buffer.add_new_chunk(carr_frame)
        mod_buffer.add_new_chunk(mod_frame)

        carr_signal = carr_buffer.get_whole_buffer()
        mod_signal = mod_buffer.get_whole_buffer()

        carr_rms = sqrt(mean(square(carr_signal)))
        mod_rms = sqrt(mean(square(carr_signal)))
        mod_signal = signal.lfilter([1, -PRE_EMP_COEF], 1, mod_signal)
        #plt.plot(mod_signal)

        X = np.fft.fft(mod_signal)
        R = np.fft.ifft(np.square(np.abs(X)))
        R2 = np.real(R)/len(X)
        ret = levinson_durbin(R2, nlags=20, isacov=False)
        error = ret[0]
        lpc_coef = ret[2]
        plt.plot(lpc_coef)
        output_signal = signal.lfilter([error], lpc_coef,  carr_signal)
        plt.plot(carr_signal)
        plt.plot(output_signal)

        out_rms = sqrt(mean(square(output_signal)))
        gain_factor = mod_rms/out_rms
        output_signal_windowed = np.float32(output_signal * window * gain_factor)


        out_buffer.add_to_whole_buffer(output_signal_windowed)
        out = out_buffer.get_old_chunk()
        out_stream.write(out.astype(np.float32).tobytes())

        carr_buffer.move_chunks()
        mod_buffer.move_chunks()
        out_buffer.move_chunks()

    out_stream.stop_stream()
    out_stream.close()
    p.terminate()
コード例 #29
0
	def __init__(self,fichero):
		self.__counter=0
		self.__bottom=Bottom(0x00);
		self.__top=Top(0xFF);
		self.__bits=Buffer(fichero)
コード例 #30
0
from Buffer import *
if __name__ == '__main__':
    buf_size, blk_size = 520, 64
    buffer = Buffer(buf_size, blk_size)
    # print(buffer.blk_available)
    # print(buffer.data)

    blk = buffer.get_new_block()
    # print(buffer.blk_available)
    # print(buffer.data)

    for i in range(blk_size):
        buffer.data[blk + i] = 1

    print(buffer.blk_available)
    print(buffer.data)
    print(buffer.num_free_blk)

    buffer.write_blk_to_disk(0, 334455)
    print(buffer.blk_available)
    print(buffer.num_free_blk)

    buffer.get_new_block()
    buffer.get_new_block()

    print(buffer.blk_available)
    print(buffer.num_free_blk)

    buffer.read_blk_from_disk(blk)
    print(buffer.data)