示例#1
0
文件: phot.py 项目: indebetouw/pyphot
    def imextents(self, im, buffer=1.):
        """
        extents in pixel space - buffer in units of inner ap radius
        """
        ca = self.imcoords(im, reg="ap")
        c1 = self.imcoords(im, reg="bg1")  # outer bg
        if self.type == "circle":
            dr = ca[2]
            xra = c1[0] + (dr * buffer + c1[2]) * pl.array([-1, 1])
            yra = c1[1] + (dr * buffer + c1[2]) * pl.array([-1, 1])
        elif self.type == "polygon":
            dx = minmax(ca[0, :])
            dy = minmax(ca[1, :])
            ctr = [mean(dx), mean(dy)]
            dx = dx[1] - dx[0]
            dy = dy[1] - dy[0]
            dr = 0.5 * max(dx, dy)
            xra = minmax(c1[0, :]) + dr * buffer * pl.array([-1, 1])
            yra = minmax(c1[1, :]) + dr * buffer * pl.array([-1, 1])

        xra[0] = pl.floor(xra[0]) + 1
        yra[0] = pl.floor(yra[0]) + 1
        xra[1] = pl.ceil(xra[1]) + 1
        yra[1] = pl.ceil(yra[1]) + 1

        if xra[0] < 0: xra[0] = 0
        if yra[0] < 0: yra[0] = 0
        s = im.shape - pl.array([1, 1])  # remember, transposed y,x
        if xra[1] > s[1]: xra[1] = s[1]
        if yra[1] > s[0]: yra[1] = s[0]

        return int(xra[0]), int(yra[0]), int(xra[1]), int(yra[1])
示例#2
0
 def stack_vectors(data, win=1, hop=1, zero_pad=True):
     """
     ::
        create an overlapping stacked vector sequence from a series of vectors
         data - row-wise multidimensional data to stack
         win  - number of consecutive vectors to stack [1]
         hop  - number of vectors to advance per stack [1]
         zero_pad - zero pad if incomplete stack at end 
     """
     data = pylab.atleast_2d(data)
     nrows, dim = data.shape
     hop = min(hop, nrows)
     nvecs = nrows / int(hop) if not zero_pad else int(
         pylab.ceil(nrows / float(hop)))
     features = pylab.zeros((nvecs, win * dim))
     i = 0
     while i < nrows - win + 1:
         features[i / hop, :] = data[i:i + win, :].reshape(1, -1)
         i += hop
     if i / hop < nvecs:
         x = data[i::, :].reshape(1, -1)
         features[i / hop, :] = pylab.c_[x,
                                         pylab.zeros(
                                             (1, win * dim - x.shape[1]))]
     return features
示例#3
0
def main(argv):
  #if len(argv) < 4:
  #  print """Usage:
  #  """
  #  sys.exit(1)
  #nlayers = int(argv[1])

  # get number of layers
  f = open(FLAGS.dir+"weights/nlayers.txt")
  nlayers = int(f.readlines()[0])
  f.close()
  print str(nlayers) + " layer(s) detected."

  pylab.figure(figsize=(32, 24), dpi=320, facecolor='w', edgecolor='k')

  # Make a picture with the filters
  [n_inputs, n_neurons, weights] = visualizing.weights_filename_to_array(FLAGS.dir+"weights/W0.txt")

  image_side_length = int(pylab.sqrt(n_inputs))
  nsubplot = pylab.ceil(pylab.sqrt(n_neurons))
  for i in range(n_neurons):
    filter = pylab.resize(weights[i], [image_side_length, image_side_length])
    pylab.subplot(nsubplot, nsubplot, i+1)
    pylab.imshow(filter, interpolation='nearest')
    pylab.gray()

  pylab.savefig(FLAGS.dir + "filters" + ".png")
  pylab.clf()

  # Make a picture with the all weights
  nsubplot_vertical = nlayers+1
  nsubplot_horizontal = 4
  for i in range(nlayers):
    # V
    location = 1+(nlayers-i)*nsubplot_horizontal+0
    filename = FLAGS.dir+"weights/V" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal, location,
                       filename, True, "V"+str(i))

    # W
    location = 1+(nlayers-i)*nsubplot_horizontal+1
    filename = FLAGS.dir+"weights/W" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                   location, filename, False, "W"+str(i))

    # F
    location = 1+(nlayers-i)*nsubplot_horizontal+2
    filename = FLAGS.dir+"weights/F" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                   location, filename, False, "F"+str(i))

    # G
    location = 1+(nlayers-i)*nsubplot_horizontal+3
    filename = FLAGS.dir+"weights/G" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                   location, filename, True, "G"+str(i))

  # Last layer
  location = 1+1
  filename = FLAGS.dir+"weights/W" + str(nlayers) + ".txt"
  visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                 location, filename, False, "W"+str(nlayers))

  pylab.savefig(FLAGS.dir + "weights" + ".png")

  # Make pictures with examples and representations
  visualizing.visualize_representations(FLAGS.dir, nlayers)
示例#4
0
def cons_vac(T):
    """
    consentration is given by n(T)/N 
    (vacant parrticle-spaces divided 
    by total particle-spaces)
    """
    k_b=8.617332478*1e-5;#[eV/K] boltzmanns constant 
    deltaeps=1; #[eV] infitisemial energy for each "particle-jump"
    
    exponential = plt.exp( deltaeps/(T*k_b) ); #these values are way large.
    return 1.0/(exponential);

try:
    pot = int(sys.argv[1]);#power of number of particles
except:
    pot = input("give the power of the temperature you want in your system")

tot_temp = 1*10**(pot); #total vacancies in system
plot_points = 1.0/float(tot_temp+1)
x = plt.linspace(0,int(tot_temp), plt.ceil(plot_points)); 
n_cons = cons_vac(x);

plt.plot(x,n_cons,"k-",label="n(T)/N");
plt.xlabel("temperature [K]");
plt.ylabel("consentration of vacancies");
plt.legend(numpoints=1, loc="lower right", borderpad=0.5);

plt.savefig("exercise_g_img"+str(self_int)+".png");
plt.show();
示例#5
0
def main(argv):
    #if len(argv) < 4:
    #  print """Usage:
    #  """
    #  sys.exit(1)
    #nlayers = int(argv[1])

    # get number of layers
    f = open(FLAGS.dir + "weights/nlayers.txt")
    nlayers = int(f.readlines()[0])
    f.close()
    print str(nlayers) + " layer(s) detected."

    pylab.figure(figsize=(32, 24), dpi=320, facecolor='w', edgecolor='k')

    # Make a picture with the filters
    [n_inputs, n_neurons, weights
     ] = visualizing.weights_filename_to_array(FLAGS.dir + "weights/W0.txt")

    image_side_length = int(pylab.sqrt(n_inputs))
    nsubplot = pylab.ceil(pylab.sqrt(n_neurons))
    for i in range(n_neurons):
        filter = pylab.resize(weights[i],
                              [image_side_length, image_side_length])
        pylab.subplot(nsubplot, nsubplot, i + 1)
        pylab.imshow(filter, interpolation='nearest')
        pylab.gray()

    pylab.savefig(FLAGS.dir + "filters" + ".png")
    pylab.clf()

    # Make a picture with the all weights
    nsubplot_vertical = nlayers + 1
    nsubplot_horizontal = 4
    for i in range(nlayers):
        # V
        location = 1 + (nlayers - i) * nsubplot_horizontal + 0
        filename = FLAGS.dir + "weights/V" + str(i) + ".txt"
        visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                       location, filename, True, "V" + str(i))

        # W
        location = 1 + (nlayers - i) * nsubplot_horizontal + 1
        filename = FLAGS.dir + "weights/W" + str(i) + ".txt"
        visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                       location, filename, False, "W" + str(i))

        # F
        location = 1 + (nlayers - i) * nsubplot_horizontal + 2
        filename = FLAGS.dir + "weights/F" + str(i) + ".txt"
        visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                       location, filename, False, "F" + str(i))

        # G
        location = 1 + (nlayers - i) * nsubplot_horizontal + 3
        filename = FLAGS.dir + "weights/G" + str(i) + ".txt"
        visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                       location, filename, True, "G" + str(i))

    # Last layer
    location = 1 + 1
    filename = FLAGS.dir + "weights/W" + str(nlayers) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                   location, filename, False,
                                   "W" + str(nlayers))

    pylab.savefig(FLAGS.dir + "weights" + ".png")

    # Make pictures with examples and representations
    visualizing.visualize_representations(FLAGS.dir, nlayers)
示例#6
0
def plotConn (include = ['all'], feature = 'strength', orderBy = 'gid', figSize = (10,10), groupBy = 'pop', groupByInterval = None, saveData = None, saveFig = None, showFig = True): 
    ''' 
    Plot network connectivity
        - include (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]): Cells to show (default: ['all'])
        - feature ('weight'|'delay'|'numConns'|'probability'|'strength'|'convergence'|'divergence'): Feature to show in connectivity matrix; 
            the only features applicable to groupBy='cell' are 'weight', 'delay' and 'numConns';  'strength' = weight * probability (default: 'strength')
        - groupBy ('pop'|'cell'|'y'|: Show matrix for individual cells, populations, or by other numeric tag such as 'y' (default: 'pop')
        - groupByInterval (int or float): Interval of groupBy feature to group cells by in conn matrix, e.g. 100 to group by cortical depth in steps of 100 um   (default: None)
        - orderBy ('gid'|'y'|'ynorm'|...): Unique numeric cell property to order x and y axes by, e.g. 'gid', 'ynorm', 'y' (requires groupBy='cells') (default: 'gid')
        - figSize ((width, height)): Size of figure (default: (10,10))
        - saveData (None|True|'fileName'): File name where to save the final data used to generate the figure; 
            if set to True uses filename from simConfig (default: None)
        - saveFig (None|True|'fileName'): File name where to save the figure; 
            if set to True uses filename from simConfig (default: None)
        - showFig (True|False): Whether to show the figure or not (default: True)

        - Returns figure handles
    '''

    print('Plotting connectivity matrix...')
    
    cells, cellGids, netStimPops = getCellsInclude(include)    

    # Create plot
    fig = figure(figsize=figSize)
    fig.subplots_adjust(right=0.98) # Less space on right
    fig.subplots_adjust(top=0.96) # Less space on top
    fig.subplots_adjust(bottom=0.02) # Less space on bottom

    h = axes()

    # Calculate matrix if grouped by cell
    if groupBy == 'cell': 
        if feature in ['weight', 'delay', 'numConns']: 
            connMatrix = zeros((len(cellGids), len(cellGids)))
            countMatrix = zeros((len(cellGids), len(cellGids)))
        else: 
            print 'Conn matrix with groupBy="cell" only supports features= "weight", "delay" or "numConns"'
            return fig
        cellInds = {cell['gid']: ind for ind,cell in enumerate(cells)}

        # Order by
        if len(cells) > 0:
            if orderBy not in cells[0]['tags']:  # if orderBy property doesn't exist or is not numeric, use gid
                orderBy = 'gid'
            elif not isinstance(cells[0]['tags'][orderBy], Number): 
                orderBy = 'gid' 
        
            if orderBy == 'gid': 
                yorder = [cell[orderBy] for cell in cells]
            else:
                yorder = [cell['tags'][orderBy] for cell in cells]
            
            sortedGids = {gid:i for i,(y,gid) in enumerate(sorted(zip(yorder,cellGids)))}
            cellInds = sortedGids

        # Calculate conn matrix
        for cell in cells:  # for each postsyn cell
            for conn in cell['conns']:
                if conn['preGid'] != 'NetStim' and conn['preGid'] in cellInds:
                    if feature in ['weight', 'delay']: 
                        if conn['preGid'] in cellInds:
                            connMatrix[cellInds[conn['preGid']], cellInds[cell['gid']]] += conn[feature]
                    countMatrix[cellInds[conn['preGid']], cellInds[cell['gid']]] += 1

        if feature in ['weight', 'delay']: connMatrix = connMatrix / countMatrix 
        elif feature in ['numConns']: connMatrix = countMatrix 

    # Calculate matrix if grouped by pop
    elif groupBy == 'pop': 
        
        # get list of pops
        popsTemp = list(set([cell['tags']['popLabel'] for cell in cells]))
        pops = [pop for pop in sim.net.allPops if pop in popsTemp]+netStimPops
        popInds = {pop: ind for ind,pop in enumerate(pops)}
        
        # initialize matrices
        if feature in ['weight', 'strength']: 
            weightMatrix = zeros((len(pops), len(pops)))
        elif feature == 'delay': 
            delayMatrix = zeros((len(pops), len(pops)))
        countMatrix = zeros((len(pops), len(pops)))
        
        # calculate max num conns per pre and post pair of pops
        numCellsPop = {}
        for pop in pops:
            if pop in netStimPops:
                numCellsPop[pop] = -1
            else:
                numCellsPop[pop] = len([cell for cell in cells if cell['tags']['popLabel']==pop])

        maxConnMatrix = zeros((len(pops), len(pops)))
        if feature == 'convergence': maxPostConnMatrix = zeros((len(pops), len(pops)))
        if feature == 'divergence': maxPreConnMatrix = zeros((len(pops), len(pops)))
        for prePop in pops:
            for postPop in pops: 
                if numCellsPop[prePop] == -1: numCellsPop[prePop] = numCellsPop[postPop]
                maxConnMatrix[popInds[prePop], popInds[postPop]] = numCellsPop[prePop]*numCellsPop[postPop]
                if feature == 'convergence': maxPostConnMatrix[popInds[prePop], popInds[postPop]] = numCellsPop[postPop]
                if feature == 'divergence': maxPreConnMatrix[popInds[prePop], popInds[postPop]] = numCellsPop[prePop]
        
        # Calculate conn matrix
        for cell in cells:  # for each postsyn cell
            for conn in cell['conns']:
                if conn['preGid'] == 'NetStim':
                    prePopLabel = conn['preLabel']
                else:
                    preCell = next((cell for cell in cells if cell['gid']==conn['preGid']), None)
                    prePopLabel = preCell['tags']['popLabel'] if preCell else None
                
                if prePopLabel in popInds:
                    if feature in ['weight', 'strength']: 
                        weightMatrix[popInds[prePopLabel], popInds[cell['tags']['popLabel']]] += conn['weight']
                    elif feature == 'delay': 
                        delayMatrix[popInds[prePopLabel], popInds[cell['tags']['popLabel']]] += conn['delay'] 
                    countMatrix[popInds[prePopLabel], popInds[cell['tags']['popLabel']]] += 1    
    
    # Calculate matrix if grouped by numeric tag (eg. 'y')
    elif groupBy in sim.net.allCells[0]['tags'] and isinstance(sim.net.allCells[0]['tags'][groupBy], Number):
        if not isinstance(groupByInterval, Number):
            print 'groupByInterval not specified'
            return
  
        # group cells by 'groupBy' feature (eg. 'y') in intervals of 'groupByInterval')
        cellValues = [cell['tags'][groupBy] for cell in cells]
        minValue = _roundFigures(groupByInterval * floor(min(cellValues) / groupByInterval), 3)
        maxValue  = _roundFigures(groupByInterval * ceil(max(cellValues) / groupByInterval), 3)
        
        groups = arange(minValue, maxValue, groupByInterval)
        groups = [_roundFigures(x,3) for x in groups]
        print groups

        if len(groups) < 2: 
            print 'groupBy %s with groupByInterval %s results in <2 groups'%(str(groupBy), str(groupByInterval))
            return
        groupInds = {group: ind for ind,group in enumerate(groups)}
        
        # initialize matrices
        if feature in ['weight', 'strength']: 
            weightMatrix = zeros((len(groups), len(groups)))
        elif feature == 'delay': 
            delayMatrix = zeros((len(groups), len(groups)))
        countMatrix = zeros((len(groups), len(groups)))

        # calculate max num conns per pre and post pair of pops
        numCellsGroup = {}
        for group in groups:
            numCellsGroup[group] = len([cell for cell in cells if group <= cell['tags'][groupBy] < (group+groupByInterval)])

        maxConnMatrix = zeros((len(groups), len(groups)))
        if feature == 'convergence': maxPostConnMatrix = zeros((len(groups), len(groups)))
        if feature == 'divergence': maxPreConnMatrix = zeros((len(groups), len(groups)))
        for preGroup in groups:
            for postGroup in groups: 
                if numCellsGroup[preGroup] == -1: numCellsGroup[preGroup] = numCellsGroup[postGroup]
                maxConnMatrix[groupInds[preGroup], groupInds[postGroup]] = numCellsGroup[preGroup]*numCellsGroup[postGroup]
                if feature == 'convergence': maxPostConnMatrix[groupInds[prePop], groupInds[postGroup]] = numCellsPop[postGroup]
                if feature == 'divergence': maxPreConnMatrix[groupInds[preGroup], groupInds[postGroup]] = numCellsPop[preGroup]
        
        # Calculate conn matrix
        for cell in cells:  # for each postsyn cell
            for conn in cell['conns']:
                if conn['preGid'] == 'NetStim':
                    prePopLabel = -1  # maybe add in future
                else:
                    preCell = next((cell for cell in cells if cell['gid']==conn['preGid']), None)
                    if preCell:
                        preGroup = _roundFigures(groupByInterval * floor(preCell['tags'][groupBy] / groupByInterval), 3)
                    else:
                        None

                postGroup = _roundFigures(groupByInterval * floor(cell['tags'][groupBy] / groupByInterval), 3)

                #print groupInds
                if preGroup in groupInds:
                    if feature in ['weight', 'strength']: 
                        weightMatrix[groupInds[preGroup], groupInds[postGroup]] += conn['weight']
                    elif feature == 'delay': 
                        delayMatrix[groupInds[preGroup], groupInds[postGroup]] += conn['delay'] 
                    countMatrix[groupInds[preGroup], groupInds[postGroup]] += 1    

    # no valid groupBy
    else:  
        print 'groupBy (%s) is not valid'%(str(groupBy))
        return

    if groupBy != 'cell':
        if feature == 'weight': 
            connMatrix = weightMatrix / countMatrix  # avg weight per conn (fix to remove divide by zero warning) 
        elif feature == 'delay': 
            connMatrix = delayMatrix / countMatrix
        elif feature == 'numConns':
            connMatrix = countMatrix
        elif feature in ['probability', 'strength']:
            connMatrix = countMatrix / maxConnMatrix  # probability
            if feature == 'strength':
                connMatrix = connMatrix * weightMatrix  # strength
        elif feature == 'convergence':
            connMatrix = countMatrix / maxPostConnMatrix
        elif feature == 'divergence':
            connMatrix = countMatrix / maxPreConnMatrix

    imshow(connMatrix, interpolation='nearest', cmap='jet', vmin=nanmin(connMatrix), vmax=nanmax(connMatrix))  #_bicolormap(gap=0)


    # Plot grid lines
    hold(True)
    if groupBy == 'cell':
        # Make pretty
        step = int(len(cells)/10.0)
        base = 100 if step>100 else 10
        step = int(base * floor(float(step)/base))
        h.set_xticks(arange(0,len(cells),step))
        h.set_yticks(arange(0,len(cells),step))
        h.set_xticklabels(arange(0,len(cells),step))
        h.set_yticklabels(arange(0,len(cells),step))
        h.xaxis.set_ticks_position('top')
        xlim(-0.5,len(cells)-0.5)
        ylim(len(cells)-0.5,-0.5)
        clim(nanmin(connMatrix),nanmax(connMatrix))

    elif groupBy == 'pop':
        for ipop, pop in enumerate(pops):
            plot(array([0,len(pops)])-0.5,array([ipop,ipop])-0.5,'-',c=(0.7,0.7,0.7))
            plot(array([ipop,ipop])-0.5,array([0,len(pops)])-0.5,'-',c=(0.7,0.7,0.7))

        # Make pretty
        h.set_xticks(range(len(pops)))
        h.set_yticks(range(len(pops)))
        h.set_xticklabels(pops)
        h.set_yticklabels(pops)
        h.xaxis.set_ticks_position('top')
        xlim(-0.5,len(pops)-0.5)
        ylim(len(pops)-0.5,-0.5)
        clim(nanmin(connMatrix),nanmax(connMatrix))

    else:
        for igroup, group in enumerate(groups):
            plot(array([0,len(groups)])-0.5,array([igroup,igroup])-0.5,'-',c=(0.7,0.7,0.7))
            plot(array([igroup,igroup])-0.5,array([0,len(groups)])-0.5,'-',c=(0.7,0.7,0.7))

        # Make pretty
        h.set_xticks([i-0.5 for i in range(len(groups))])
        h.set_yticks([i-0.5 for i in range(len(groups))])
        h.set_xticklabels([int(x) if x>1 else x for x in groups])
        h.set_yticklabels([int(x) if x>1 else x for x in groups])
        h.xaxis.set_ticks_position('top')
        xlim(-0.5,len(groups)-0.5)
        ylim(len(groups)-0.5,-0.5)
        clim(nanmin(connMatrix),nanmax(connMatrix))

    colorbar(label=feature, shrink=0.8) #.set_label(label='Fitness',size=20,weight='bold')
    xlabel('post')
    h.xaxis.set_label_coords(0.5, 1.06)
    ylabel('pre')
    title ('Connection '+feature+' matrix', y=1.08)

    #save figure data
    if saveData:
        figData = {'connMatrix': connMatrix, 'feature': feature, 'groupBy': groupBy,
         'include': include, 'saveData': saveData, 'saveFig': saveFig, 'showFig': showFig}
    
        _saveFigData(figData, saveData, 'conn')
 
    # save figure
    if saveFig: 
        if isinstance(saveFig, str):
            filename = saveFig
        else:
            filename = sim.cfg.filename+'_'+'conn.png'
        savefig(filename)

    # show fig 
    if showFig: _showFigure()

    return fig
示例#7
0
文件: phot.py 项目: indebetouw/pyphot
    def setmask(self, im):
        """
        input an image (for now an HDU) and set self.mask to 
        an array the size of the image with the phot region =1
          and expanded background annulus =2
        for now we also create a mask the size of the image, so I recommend
          to extract a subimage and call this method with that input
        this method well trim the polyon to fit in the image
        """
        imshape = im.shape
        mask = pl.zeros(imshape)

        if self.type == "circle":
            x, y, r = self.imcoords(im)
            x0 = int(x)
            y0 = int(y)
            dx = x - x0
            dy = y - y0
            # grr pixel centers again - is this right?
            #            dx=dx-0.5; dy=dy-0.5

            bg0_r = self.imcoords(im, reg="bg0")[2]  #-0.2 # fudge
            bg1_r = self.imcoords(im, reg="bg1")[2]  #+0.2 # fudge
            bg1_r0 = int(pl.ceil(bg1_r))
            r2 = r**2
            bg0_r2 = bg0_r**2
            bg1_r2 = bg1_r**2
            for i in pl.array(range(2 * bg1_r0 + 1)) - bg1_r0:
                for j in pl.array(range(2 * bg1_r0 + 1)) - bg1_r0:
                    if y0 + j >= 0 and x0 + i >= 0 and y0 + j < (
                            imshape[0] - 1) and x0 + i < (imshape[1] - 1):
                        d2 = (1. * i - dx)**2 + (1. * j - dy)**2
                        # d2 = (i-x)**2 + (j-y)**2 -> (i-x0-(x-x0))**2 + ...
                        if d2 <= r2:
                            mask[y0 + j,
                                 x0 + i] = 1  # remember indices inverted
                        if d2 >= bg0_r2 and d2 <= bg1_r2:
                            mask[y0 + j,
                                 x0 + i] = 2  # remember indices inverted
#                        if x0+i==6:
#                           print i,j,x0+i,y0+j,dx,dy,d2,bg0_r2,bg1_r2

        elif self.type == "polygon":
            # turn annulus back into mask, will trim at edges of image
            from matplotlib.path import Path
            from matplotlib import __version__ as mpver
            v = mpver.split('.')
            if v[0] < 1:
                raise Exception(
                    "need matplotlib >=1.3.1, or tell remy to add fallback nxutils option for Path.contains_points"
                )
            elif v[1] < 3:
                raise Exception(
                    "need matplotlib >=1.3.1, or tell remy to add fallback nxutils option for Path.contains_points"
                )
            elif v[2] < 1:
                raise Exception(
                    "need matplotlib >=1.3.1, or tell remy to add fallback nxutils option for Path.contains_points"
                )

            # Create vertex coordinates for each grid cell
            x, y = pl.meshgrid(pl.arange(imshape[1]), pl.arange(imshape[0]))
            x, y = x.flatten(), y.flatten()
            points = pl.vstack((x, y)).T
            mask1 = Path(self.imcoords(im, reg="bg1")).contains_points(points)
            mask1 = mask1.reshape((imshape[0], imshape[1]))
            mask0 = Path(self.imcoords(im, reg="bg0")).contains_points(points)
            #,radius=1)
            mask0 = mask0.reshape((imshape[0], imshape[1]))
            mask = Path(self.imcoords(im, reg="ap")).contains_points(points)
            mask = mask.reshape((imshape[0], imshape[1]))

            mask = mask + (1 * mask1 - 1 * mask0) * 2
        else:
            raise Exception("unknown region type %s" % self.type)
        self.mask = mask
        return mask
示例#8
0
    self_int = int(self_name[7])
except:
    print "error in integer: exg_att#.py"

def cons_vac(T):
    """
    consentration is given by n(T)/N 
    (vacant parrticle-spaces divided 
    by total particle-spaces)
    """
    k_b=8.617332478*1e-5;#[eV/K] boltzmanns constant 
    deltaeps=1; #[eV] infitisemial energy for each "particle-jump"
    
    exponential = plt.exp( deltaeps/(T*k_b) ); #these values are way large.
    return 1.0/(1 + exponential);

pot = 5;#power of number of particles
tot_vac = 1*10**(pot); #total vacancies in system
jumps = plt.ceil(tot_vac/float(1e+3)); #frequency of points on x-axis

x = plt.array(range(1,int(tot_vac),int(jumps)));
n_cons = cons_vac(x);

plt.plot(x,n_cons,"k-",label="n(T)/N");
plt.xlabel("temperature [K]");
plt.ylabel("consentration of vacancies");
plt.legend(numpoints=1, loc="upper right", borderpad=0.5);

plt.savefig("exercise_g_img"+str(self_int)+".png");
plt.show();
示例#9
0
def plotcalng(caltable='',
              xaxis='',
              yaxis='',
              poln='',
              field='',
              antenna='',
              spw='',
              timerange='',
              plotncolumns=2,
              subplot='',
              overwrite=False,
              clearpanel='Auto',
              iteration='',
              plotrange=[],
              showflags=False,
              plotsymbol='.',
              plotcolor='blue',
              markersize=5.0,
              fontsize=10.0,
              showgui=False,
              figfile=''):
    if subplot != "":
        print("Warning, the subplot parameter is ignored")

    selection = __parse_input(caltable, xaxis, yaxis, field, spw, antenna,
                              poln, timerange)
    data = __get_data(caltable, selection['xaxis'], selection['yaxis'],
                      iteration, selection['poln'], selection['field'],
                      selection['antenna'], selection['spw'],
                      selection['timerange'])

    # Create grid of subplots
    nplots = max(1, len(data))
    ncolumns = min(nplots, plotncolumns)
    nrows = int(pl.ceil(nplots / ncolumns))
    # Unfortunately, matplot doesn't properly scale fig size with nrows / ncolumns
    if nplots == 1:
        figsize = (4, 3)
    else:
        figsize = (8, 3 * nrows)

    fig, axs = pl.subplots(nrows,
                           ncolumns,
                           figsize=figsize,
                           constrained_layout=True)
    if not isinstance(axs, pl.ndarray):
        axs = pl.array([[axs]])
    elif len(axs.shape) == 1:
        axs = axs.reshape([1, axs.shape[0]])
    nremove = nrows * ncolumns - nplots
    for i in range(0, nremove):
        axs[-1][ncolumns - i - 1].set_visible(False)

    ticklocator = dates.AutoDateLocator()
    tickformatter = dates.AutoDateFormatter(ticklocator)
    #print(data.keys())
    #print('nplots = {}, ncolumns = {}, nrows = {}, nremove = {}'.format(nplots, ncolumns, nrows, nremove))
    #print(len(axs), len(axs[-1]))
    for i, key in enumerate(data):
        row = i // ncolumns
        column = i % ncolumns
        ax = axs[row][column]
        f = data[key]
        for plotkey in f:
            if (plotkey == "label"):
                ax.set_title(f[plotkey])
                continue
            xy = f[plotkey]
            axislabels = []
            for j, axistype in enumerate(
                (selection['xaxis'], selection['yaxis'])):
                if axistype == "TIME":
                    ax.xaxis.set_major_locator(ticklocator)
                    ax.xaxis.set_major_formatter(tickformatter)
                    xy[j] = dates.date2num(xy[j])
                    axislabels.append('Time')
                elif axistype == "CHAN":
                    axislabels.append("Channel")
                elif axistype == "ANTENNA":
                    axislabels.append("Antenna")
                elif axistype == "FREQ":
                    maxval = max(xy[j])
                    if maxval >= 1e10:
                        xy[j] /= 1e9
                        unit = "GHz"
                    elif maxval > 1e7:
                        xy[j] /= 1e6
                        unit = "MHz"
                    elif maxval > 1e4:
                        xy[j] /= 1000
                        unit = "KHz"
                    else:
                        unit = "Hz"
                    axislabels.append("Frequency [{}]".format(unit))
                elif axistype == "DELAY":
                    axislabels.append("Delay [ns]")
                elif axistype == "RATE":
                    xy[j] *= 1e12
                    axislabels.append("Delay rate [ps / s]")
                elif axistype == "DISP":
                    # TEC conversion parameter from Mevius LOFAR school notes
                    xy /= 1.334537
                    axislabels.append("Dispersive delay [miliTEC]")
                elif axistype == "AMP":
                    axislabels.append("Gain Amplitude")
                elif axistype == "PHASE":
                    axislabels.append("Gain Phase [degrees]")
                elif axistype == "TSYS":
                    axislabels.append("TSYS [K]")
                else:
                    print("Unknown axis type:", axistype)
                    raise ValueError()

            ax.plot(xy[0], xy[1], plotsymbol, label=xy[2])
            ax.set_xlabel(axislabels[0])
            ax.set_ylabel(axislabels[1])

            if plotrange != []:
                # CASA convention: if min==max in plotrange for axis then autoscale that axis
                if plotrange[0] != plotrange[1]:
                    ax.set_xlim(plotrange[0], plotrange[1])
                if plotrange[2] != plotrange[3]:
                    ax.set_ylim(plotrange[2], plotrange[3])

    if xaxis.upper() == "TIME":
        fig.autofmt_xdate()
    if figfile != "":
        fig.savefig(figfile)