Esempio n. 1
0
def array2avi(A, fname, fps=25, codec='rawvideo', codec_params='', width=800,
              makelog=False):

    if A.ndim == 3:
        fmt = 'gray'
    elif A.ndim == 4:
        if A.shape[3] == 3:
            fmt = 'rgb8'
        elif A.shape[3] == 4:
            fmt = 'argb'
        else:
            raise Exception('Invalid input 4th dimension - should'
                            ' be rgb or argb')
    else:
        raise Exception('Invalid number of input dimensions (should be'
                        ' [frame,row,col] or [frame,row,col,(a)rgb]')

    A = rescale_8bit(A)

    nframes, h, w = A.shape[:3]
    aspect = float(h) / w
    width = 2 * int(width / 2.)
    height = 2 * int((width / 2.) * aspect)

    cmd = ['ffmpeg', '-y',

           '-f', 'rawvideo',
           '-pix_fmt', fmt,
           '-r', '%d' % fps,
           '-s', '%ix%i' % (w, h),
           '-i', 'pipe:0',

           '-vcodec', codec,
           # '-b:v', '%ik' %kbitrate,
           '-s', '%ix%i' % (width, height),
           fname]

    if makelog:
        logfile = open(fname + '.log', 'w')
    else:
        logfile = open(devnull, 'w')

    proc = sp.Popen(cmd, shell=False, stdin=sp.PIPE, stdout=logfile,
                    stderr=logfile)

    wbh = Waitbar(title='Writing %s' % fname, showETA=True)
    for ii, frame in enumerate(A):
        proc.stdin.write(frame.tostring())
        wbh.update((ii + 1.) / nframes)

    proc.stdin.close()
    proc.terminate()
    logfile.close()
Esempio n. 2
0
def run_sim(duration,neurons,connections,
                    display_hash=False,python=False,
                    display=None,display_period=0,
                    save=None,
                    start_time=0.0):

    neurons=[n for n in neurons if n.N]  # get rid of zero number of neurons
    connections=[c for c in connections if prod(c.shape)]  # get rid of zero number of neurons

    if _run_sim and not python:
        print "Using Cython run_sim"
        time1=time.time()
        _run_sim.run_sim(duration,neurons,connections,
                    display_hash,display,display_period,save,start_time)
        time2=time.time()
        print time2-time1,' seconds.'
        
        return
    else:
        print "Using Python run_sim"

    
    
    if display_hash:
         wb = Waitbar(False)

    monitors=[]
    for n in neurons:
        monitors.extend(n.monitors)

    for c in connections:
        monitors.extend(c.monitors)


    t=start_time
    dt=neurons[0].clock.dt  # TODO: fix multiple clocks someday

    hash_step=duration/1000
    if hash_step==0:
        hash_step=1

    time_to_next_display=0.0
    time_to_save=60*20  # 20 minutes
    
    time1=time.time()
    t1=time.time()
    while t<=(start_time+duration):

        for n in neurons:
            n.old_spikes[:]=n.spikes
            
        for n in neurons:
            n.update(t)
        
    
        for c in connections:
            c.update(t)
        
        for m in monitors:
            m.update(t)
        
        t+=dt


        if display_hash and int(t) % hash_step == 0:
            wb.updated(t/duration)

        if save:
            t2=time.time()
            if (t2-t1)>(time_to_save):  # 20 minutes
                print 'Preemptive save of ',save,'...',
                sys.stdout.flush()
                Remember(t,duration,neurons,connections,monitors,filename=save)
                print 'done.'
                sys.stdout.flush()
                t1=t2

        if display and t>=time_to_next_display:
            for m in monitors:
                m.finalize()
                
            display(t,neurons,connections)
            time_to_next_display+=display_period
            
            for m in monitors:
                m.unfinalize()


    for m in monitors:
        m.finalize()

    time2=time.time()
    print time2-time1,' seconds.'

    if save:
        print 'Saving ',save,'...',
        sys.stdout.flush()
        Remember(t,duration,neurons,connections,monitors,filename=save)
        print 'done.'
        sys.stdout.flush()
        

    if display:
        display(t,neurons,connections)
Esempio n. 3
0
def track(samples, channel, settings):
  #Create list of tracking channels results (correlations, freqs, etc)
  trackResults = [trackResults_class(settings) for i in range(len(channel))]
  #Initialize tracking variables
  codePeriods = settings.msToProcess
  ##DLL Variables##
  #Define early-late offset
  earlyLateSpc = settings.dllCorrelatorSpacing
  #Summation interval
  PDIcode = 0.001
  #Filter coefficient values
  (tau1code, tau2code) = calcLoopCoef(settings.dllNoiseBandwidth,settings.dllDampingRatio,1.0)
  ##PLL Variables##
  PDIcarr = 0.001
  (tau1carr,tau2carr) = calcLoopCoef(settings.pllNoiseBandwidth,settings.pllDampingRatio,0.25)

  progbar = Waitbar(True)
  
  #Do tracking for each channel
  for channelNr in range(len(channel)):
    trackResults[channelNr].PRN = channel[channelNr].PRN
    #Get a vector with the C/A code sampled 1x/chip
    caCode = np.array(generateCAcode(channel[channelNr].PRN))
    #Add wrapping to either end to be able to do early/late
    caCode = np.concatenate(([caCode[1022]],caCode,[caCode[0]]))
    #Initialize phases and frequencies
    codeFreq = settings.codeFreqBasis
    remCodePhase = 0.0 #residual code phase
    carrFreq = channel[channelNr].acquiredFreq
    carrFreqBasis = channel[channelNr].acquiredFreq
    remCarrPhase = 0.0 #residual carrier phase
    
    #code tracking loop parameters
    oldCodeNco = 0.0
    oldCodeError = 0.0
   
    #carrier/Costas loop parameters
    oldCarrNco = 0.0
    oldCarrError = 0.0

    #number of samples to seek ahead in file
    numSamplesToSkip = settings.skipNumberOfBytes + channel[channelNr].codePhase
  
    #Process the specified number of ms
    for loopCnt in range(settings.msToProcess):
      #Update progress every 50 loops
      if (np.remainder(loopCnt,50)==0):
        progbar.updated(float(loopCnt + channelNr*settings.msToProcess)\
                        / float(len(channel)*settings.msToProcess))
#        print "Channel %d/%d, %d/%d ms" % (channelNr+1,len(channel),loopCnt, settings.msToProcess)
      #Update the code phase rate based on code freq and sampling freq
      codePhaseStep = codeFreq/settings.samplingFreq
      codePhaseStep = codePhaseStep*(10**12) #round it in the same way we are in octave
      codePhaseStep = round(codePhaseStep)
      codePhaseStep = codePhaseStep*(10**(-12))
      blksize = int(np.ceil((settings.codeLength - remCodePhase)/codePhaseStep))
      #Read samples for this integration period
      rawSignal = np.array(getSamples.int8(settings.fileName,blksize,numSamplesToSkip))

      numSamplesToSkip = numSamplesToSkip + blksize

      #Define index into early code vector
      tcode = np.r_[(remCodePhase-earlyLateSpc) : \
                    (blksize*codePhaseStep+remCodePhase-earlyLateSpc) : \
                    codePhaseStep]
      earlyCode = caCode[np.int_(np.ceil(tcode))]
      #Define index into late code vector
      tcode = np.r_[(remCodePhase+earlyLateSpc) : \
                    (blksize*codePhaseStep+remCodePhase+earlyLateSpc) : \
                    codePhaseStep]
      lateCode = caCode[np.int_(np.ceil(tcode))]
      #Define index into prompt code vector
      tcode = np.r_[(remCodePhase) : \
                    (blksize*codePhaseStep+remCodePhase) : \
                    codePhaseStep]
      promptCode = caCode[np.int_(np.ceil(tcode))]
      
      remCodePhase = (tcode[blksize-1] + codePhaseStep) - 1023
      
      #Generate the carrier frequency to mix the signal to baseband
      time = np.r_[0:blksize+1] / settings.samplingFreq #(seconds)
      
      #Get the argument to sin/cos functions
      trigarg = (carrFreq * 2.0 * math.pi)*time + remCarrPhase
      remCarrPhase = np.remainder(trigarg[blksize],(2*math.pi))

      #Finally compute the signal to mix the collected data to baseband
      carrCos = np.cos(trigarg[0:blksize])
      carrSin = np.sin(trigarg[0:blksize])
      
      #Mix signals to baseband
      qBasebandSignal = carrCos*rawSignal
      iBasebandSignal = carrSin*rawSignal

      #Get early, prompt, and late I/Q correlations
      I_E = np.sum(earlyCode * iBasebandSignal)
      Q_E = np.sum(earlyCode * qBasebandSignal)
      I_P = np.sum(promptCode * iBasebandSignal)
      Q_P = np.sum(promptCode * qBasebandSignal)
      I_L = np.sum(lateCode * iBasebandSignal)
      Q_L = np.sum(lateCode * qBasebandSignal)

      #Find PLL error and update carrier NCO
      #Carrier loop discriminator (phase detector)
      carrError = math.atan(Q_P/I_P) / (2.0 * math.pi)
      #Carrier loop filter and NCO
      carrNco = oldCarrNco + (tau2carr/tau1carr) * \
                 (carrError-oldCarrError) + carrError*(PDIcarr/tau1carr)
      oldCarrNco = carrNco
      oldCarrError = carrError
      #Modify carrier freq based on NCO
      carrFreq = carrFreqBasis + carrNco
      trackResults[channelNr].carrFreq[loopCnt] = carrFreq

      #Find DLL error and update code NCO
      codeError = (math.sqrt(I_E*I_E + Q_E*Q_E) - math.sqrt(I_L*I_L + Q_L*Q_L)) / \
                   (math.sqrt(I_E*I_E + Q_E*Q_E) + math.sqrt(I_L*I_L + Q_L*Q_L))
      codeNco = oldCodeNco + (tau2code/tau1code)*(codeError-oldCodeError) \
                   + codeError*(PDIcode/tau1code)
      oldCodeNco = codeNco
      oldCodeError = codeError
      #Code freq based on NCO
      codeFreq = settings.codeFreqBasis - codeNco
      trackResults[channelNr].codeFreq[loopCnt] = codeFreq

      #Record stuff for postprocessing
      trackResults[channelNr].absoluteSample[loopCnt] = numSamplesToSkip

      trackResults[channelNr].dllDiscr[loopCnt] = codeError
      trackResults[channelNr].dllDiscrFilt[loopCnt] = codeNco
      trackResults[channelNr].pllDiscr[loopCnt] = carrError
      trackResults[channelNr].pllDiscrFilt[loopCnt] = carrNco

      trackResults[channelNr].I_E[loopCnt] = I_E
      trackResults[channelNr].I_P[loopCnt] = I_P
      trackResults[channelNr].I_L[loopCnt] = I_L
      trackResults[channelNr].Q_E[loopCnt] = Q_E
      trackResults[channelNr].Q_P[loopCnt] = Q_P
      trackResults[channelNr].Q_L[loopCnt] = Q_L

#      print ("tR[%d].absoluteSample[%d] = %d" % (channelNr,loopCnt,trackResults[channelNr].absoluteSample[loopCnt]))
#
#      print ("tR[%d].dllDiscr[%d]       = %f" % (channelNr,loopCnt,trackResults[channelNr].dllDiscr[loopCnt]))
#      print ("tR[%d].dllDiscrFilt[%d]   = %f" % (channelNr,loopCnt,trackResults[channelNr].dllDiscrFilt[loopCnt]))
#      print ("tR[%d].codeFreq[%d]       = %f" % (channelNr,loopCnt,trackResults[channelNr].codeFreq[loopCnt]))
#      print ("tR[%d].pllDiscr[%d]       = %f" % (channelNr,loopCnt,trackResults[channelNr].pllDiscr[loopCnt]))
#      print ("tR[%d].pllDiscrFilt[%d]   = %f" % (channelNr,loopCnt,trackResults[channelNr].pllDiscrFilt[loopCnt]))
#      print ("tR[%d].carrFreq[%d]       = %f" % (channelNr,loopCnt,trackResults[channelNr].carrFreq[loopCnt]))
#
#      print ("tR[%d].I_E[%d] = %f" % (channelNr,loopCnt,trackResults[channelNr].I_E[loopCnt]))
#      print ("tR[%d].I_P[%d] = %f" % (channelNr,loopCnt,trackResults[channelNr].I_P[loopCnt]))
#      print ("tR[%d].I_L[%d] = %f" % (channelNr,loopCnt,trackResults[channelNr].I_L[loopCnt]))
#      print ("tR[%d].Q_E[%d] = %f" % (channelNr,loopCnt,trackResults[channelNr].Q_E[loopCnt]))
#      print ("tR[%d].Q_P[%d] = %f" % (channelNr,loopCnt,trackResults[channelNr].Q_P[loopCnt]))
#      print ("tR[%d].Q_L[%d] = %f" % (channelNr,loopCnt,trackResults[channelNr].Q_L[loopCnt]))
#      print ""

    #Possibility for lock-detection later
    trackResults[channelNr].status = 'T'

  print ""

  return (trackResults,channel)
Esempio n. 4
0
    def save(self, fname, codec='rawvideo', fps=None, width=800,
             makelog=False):

        if not np.all(self.hasplayed):
            raise Exception(
                "All frames need to have been displayed at "
                "least once before writing")
        if fps is None:
            fps = self.framerate

        # make sure we start with the first frame
        self.rewind()

        # need to disconnect the first draw callback, since we'll be
        # doing draws. otherwise, we'll end up starting the animation.
        if self.animator._first_draw_id is not None:
            self.animator._fig.canvas.mpl_disconnect(
                self.animator._first_draw_id)
            reconnect_first_draw = True
        else:
            reconnect_first_draw = False

        # input pixel dimensions
        w, h = self.fig.canvas.get_width_height()
        nframes = self.data.shape[0]

        # make sure that output width and height are divisible by 2
        # (some codecs don't like odd dimensions)
        figsize = self.fig.get_size_inches()
        aspect = figsize[1] / figsize[0]
        width = 2 * int(width / 2.)
        height = 2 * int((width / 2.) * aspect)

        # spawn an ffmpeg process - we're going to pipe the frames
        # directly to ffmpeg as raw bytes

        cmd = [
                # global options
               'ffmpeg', '-y',
               '-loglevel', 'verbose',

               # input options
               '-f', 'rawvideo',
               '-pix_fmt', 'bgr24',
               '-r', '%d' % fps,
               '-s', '%ix%i' % (w, h),
               '-i', 'pipe:0',

               # output options
               '-vcodec', codec,
               '-an',
               '-pix_fmt', 'rgb24', # NB: need to reverse channel order!
               '-s', '%ix%i' % (width, height),
               fname
               ]

        # print ' '.join(cmd)

        if makelog:
            logfile = open(fname + '.log', 'w')
        else:
            logfile = open(devnull, 'w')

        proc = sp.Popen(cmd, shell=False, stdin=sp.PIPE,
                        stdout=logfile, stderr=logfile)

        # Render each frame, save it to the stdin of the spawned process
        wbh = Waitbar(title='Writing %s' % fname, showETA=True)
        for ii, data in enumerate(self.animator.new_saved_frame_seq()):
            self.animator._draw_next_frame(data, blit=True)
            # self.animator._fig.savefig(proc.stdin,format='png')
            proc.stdin.write(self.animator._fig.canvas.tostring_rgb())
            wbh.update((ii + 1.) / nframes)

        logfile.close()

        if reconnect_first_draw:
            drawid = self.animator._fig.canvas.mpl_connect(
                'draw_event', self.animator._start)
            self.animator._first_draw_id = drawid