コード例 #1
0
ファイル: sliputil.py プロジェクト: MMaus/mutils
def simCSLIP_xp(x0, x0R, x0L, p0R, p0L, AR, AL, SLIP_param0, n=50):
    """
    simulates the controlled 2step-SLIP, using [x,p]-referenced control
    input:
        x0 - initial (augmented) state, e.g. [x0L, p0R].T
        x0R - reference right apex (y, vx, vz)
        x0L - reference left apex     -"-
        p0R - reference right parameters
        p0L - reference left parameters
        AR - parameter control right leg
        AL - parameter control left leg
        SLIP_param0: dict, containing {'m': ..., 'g': ... }
        n - number of strides to simulate at most
    """
    res = []
    refStateL = hstack([x0L, squeeze(sp_d2a(p0R))])[:,newaxis]
    refStateR = hstack([x0R, squeeze(sp_d2a(p0L))])[:,newaxis]
    currState = array(x0)
    slip_params = copy.deepcopy(SLIP_param0)
    if currState.ndim == 1:
        currState = currState[:,newaxis]
    elif currState.shape[0] == 1:
        currState = currState.T
    for step in range(n):
        #print 'AL: ', AL.shape, 'p0L: ', sp_d2a(p0L).shape
        pL = sp_d2a(p0L) + dot(AL, currState - refStateL)
        #print 'pL changed:', not allclose(pL,sp_d2a(p0L))
        slip_params.update(sp_a2d(pL))
        try:
            resL = sl.SLIP_step3D(currState[:3,0], slip_params)
        except ValueError:
            print 'simulation aborted (l1)\n'
            break
        if resL['sim_fail']:
            print 'simulation aborted (l2)\n'
            break
        res.append(resL)
        currState = hstack([resL['y'][-1],
                            resL['vx'][-1],
                            resL['vz'][-1],
                            squeeze(pL)])[:,newaxis]
        pR = sp_d2a(p0R) + dot(AR, currState - refStateR)
        #print 'pR changed:', not allclose(pR,sp_d2a(p0R))
        slip_params.update(sp_a2d(pR))
        try:
            resR = sl.SLIP_step3D(currState[:3,0], slip_params)
        except ValueError:
            print 'simulation aborted (r1)\n'
            break
        if resR['sim_fail']:
            print 'simulation aborted (r2)\n'
            break
        res.append(resR)
        currState = hstack([resR['y'][-1],
                            resR['vx'][-1],
                            resR['vz'][-1],
                            squeeze(pR)])[:,newaxis]
    return res
コード例 #2
0
def simCSLIP_xp(x0, x0R, x0L, p0R, p0L, AR, AL, SLIP_param0, n=50):
    """
    simulates the controlled 2step-SLIP, using [x,p]-referenced control
    input:
        x0 - initial (augmented) state, e.g. [x0L, p0R].T
        x0R - reference right apex (y, vx, vz)
        x0L - reference left apex     -"-
        p0R - reference right parameters
        p0L - reference left parameters
        AR - parameter control right leg
        AL - parameter control left leg
        SLIP_param0: dict, containing {'m': ..., 'g': ... }
        n - number of strides to simulate at most
    """
    res = []
    refStateL = hstack([x0L, squeeze(sp_d2a(p0R))])[:, newaxis]
    refStateR = hstack([x0R, squeeze(sp_d2a(p0L))])[:, newaxis]
    currState = array(x0)
    slip_params = copy.deepcopy(SLIP_param0)
    if currState.ndim == 1:
        currState = currState[:, newaxis]
    elif currState.shape[0] == 1:
        currState = currState.T
    for step in range(n):
        #print 'AL: ', AL.shape, 'p0L: ', sp_d2a(p0L).shape
        pL = sp_d2a(p0L) + dot(AL, currState - refStateL)
        #print 'pL changed:', not allclose(pL,sp_d2a(p0L))
        slip_params.update(sp_a2d(pL))
        try:
            resL = sl.SLIP_step3D(currState[:3, 0], slip_params)
        except ValueError:
            print 'simulation aborted (l1)\n'
            break
        if resL['sim_fail']:
            print 'simulation aborted (l2)\n'
            break
        res.append(resL)
        currState = hstack(
            [resL['y'][-1], resL['vx'][-1], resL['vz'][-1],
             squeeze(pL)])[:, newaxis]
        pR = sp_d2a(p0R) + dot(AR, currState - refStateR)
        #print 'pR changed:', not allclose(pR,sp_d2a(p0R))
        slip_params.update(sp_a2d(pR))
        try:
            resR = sl.SLIP_step3D(currState[:3, 0], slip_params)
        except ValueError:
            print 'simulation aborted (r1)\n'
            break
        if resR['sim_fail']:
            print 'simulation aborted (r2)\n'
            break
        res.append(resR)
        currState = hstack(
            [resR['y'][-1], resR['vx'][-1], resR['vz'][-1],
             squeeze(pR)])[:, newaxis]
    return res
コード例 #3
0
ファイル: curve_tools.py プロジェクト: du-lab/ADAP-3D
def estimate_fwhm_ms(int_matrix, numberOfScansForFWHMCalc):
    """
    This function is going to randomly select a variety of spectra and estimate a FWHM using a
    gaussian fit on some of the most intense peaks in the selected spectra.
    
    :param int_matrix: Matrix of all data points
    :param numberOfScansForFWHMCalc: how many scans will we use for estimate
    :return: estimate of full-width-half-max in number of points
    """

    # keep the values to be averaged over
    fwhm_arr = pl.array([])

    print "Estimating FWHM of profile MS"
    print "..."
    for i in range(numberOfScansForFWHMCalc):
        # randomly select a scan to investigate.
        spec_index = random.randint(
            0,
            len(pl.squeeze(pl.asarray(int_matrix[0, :].todense()))) - 1)
        cur_spec = pl.squeeze(pl.asarray(int_matrix[:, spec_index].todense()))
        # could be 0 intensity points in good spectra becuase of the way the int_matrix is bui
        # lets work in units of scan number
        x = pl.arange(0, len(cur_spec))
        # Only going to be looking at the highest peak in each scan. Get the location of that peak.
        max_y = max(cur_spec)
        scan_max_y = pl.where(cur_spec == max_y)[0][0]
        popt, pcov = curve_fit(curves.gaussian,
                               x,
                               cur_spec,
                               bounds=([
                                   max_y * 0.8, scan_max_y - 1, 0.25 / 2.35482
                               ], [max_y * 1.2, scan_max_y + 1, 5 / 2.35482]))
        tmp_x = x
        tmp_y = curves.gaussian(x, popt[0], popt[1], popt[2])

        #pl.plot(tmp_x[scan_max_y-20:scan_max_y+20],tmp_y[scan_max_y-20:scan_max_y+20],c='r')
        #pl.plot(x[scan_max_y-20:scan_max_y+20],cur_spec[scan_max_y-20:scan_max_y+20],c='b',marker='o')
        #pl.show()

        # with the right fit parameter you can determine the full width at half max.
        # 2.35... is a known value to take this parameter and get the FWHM with.
        fwhm = 2.35482 * popt[2]
        fwhm_arr = pl.append(fwhm_arr, fwhm)

    avg_fwhm = fwhm_arr.mean()
    print "Done estimating FWHM of profile MS"
    print("avg_fwhm: " + str(avg_fwhm))

    # round up
    return int(avg_fwhm + 0.5)
コード例 #4
0
ファイル: IDEComponents.py プロジェクト: parhamaram/MRAIDE
	def plot(self,width,color='k'):
		temp1=[]
		space=pb.linspace(-width,width,1000)
		for i in range(self.Lambda.shape[0]):
			temp2=[]
			for s in space:
				temp2.append(self.weights[i]*self.Lambda[i,0](s))
			temp1.append(temp2)
		pb.plot(space,pb.sum(pb.squeeze(temp1),axis=0),color)
コード例 #5
0
def getcodar_edge(url, id, lat_max_i, lon_max_i, lat_min_i, lon_min_i):
    id = str(id)
    dataset = open_url(url + '?u[' + id + ':1:' + id + '][0:1:' + lat_max_i +
                       '][0:1:' + lon_max_i + '],v[' + id + ':1:' + id +
                       '][0:1:' + lat_max_i + '][0:1:' + lon_max_i +
                       '],lat[0:1:' + lat_max_i + '],lon[0:1:' + lon_max_i +
                       ']')
    #print url+'?u['+str(int(id))+'],v['+str(int(id))+'],lat,lon,time['+str(int(id))+']'
    #dataset=open_url(url)

    lat_array = dataset['lat']
    id = int(id)
    lon_array = dataset['lon']
    u1 = dataset['u']
    #print u1.u[id]
    #print np.size(lat_array)
    #print np.size(lon_array)

    v1 = dataset['v']
    #print list(u1.u[id])
    #print np.size(v1)
    #jdmat_1=dataset['time']
    #jdmat_1=dataset['time']
    #change array to list: lat & lon
    lat_vel, lon_vel, jdmat_2, jdmat_m, u, v = [], [], [], [], [], []
    for i in lat_array:
        lat_vel.append(i)
    for j in lon_array:
        lon_vel.append(j)
    #print lon_vel
    [lon_vel, lat_vel] = pylab.squeeze(list(np.meshgrid(lon_vel, lat_vel)))
    #print lat_vel[0],lat_vel[-1],lon_vel[0],lon_vel[-1]
    u1 = pylab.squeeze(list(np.array(u1.u[id])))
    #u1=np.array(u1.u.data)
    v1 = pylab.squeeze(list(np.array(v1.v[id])))
    #print "size of v1 "+str(np.size(v1))
    #print list(u1)
    for y in range(len(u1)):
        u.append(u1[y] / 100)  # converting to m/s
        v.append(v1[y] / 100)
    #print u[0],u[-1]
    #print np.shape(u1)
    return lat_vel, lon_vel, u, v
コード例 #6
0
 def getTrials(self,tdata):
     subdict = {};
     subdict['targ_contrasts'] = tdata['targ_contrasts'];
     subdict['targ_locs'] = tdata['targ_locs'];
     subdict['selected_interval'] = tdata['selected_interval'];
     subdict['results'] = tdata['results'];
     
     dict_keys = subdict.keys();
     dict_vals = pl.array([pl.squeeze(vals) for vals in subdict.values()]).T;
     trials = [GDTrial(dict(zip(dict_keys,vals))) for vals in dict_vals];
     return trials;
コード例 #7
0
ファイル: sliputil.py プロジェクト: MMaus/mutils
def sp_a2d(parameter):
    """
    transforms a given SLIP parameter set (array) into a dict
    *NOTE*: here, the array must have format k|alpha|L0|beta|dE
    """
    params = squeeze(parameter)
    return { 'k' : params[0],
             'alpha' : params[1],
             'L0' : params[2],
             'beta' : params[3],
             'dE' : params[4],
           }
コード例 #8
0
ファイル: hx.py プロジェクト: jian-cui/pyocean
def getcodar_edge(url,id,lat_max_i,lon_max_i,lat_min_i,lon_min_i):
  id=str(id)
  dataset=open_url(url+'?u['+id+':1:'+id+'][0:1:'+lat_max_i+'][0:1:'+lon_max_i+'],v['+id+':1:'+id+'][0:1:'+lat_max_i+'][0:1:'+lon_max_i+'],lat[0:1:'+lat_max_i+'],lon[0:1:'+lon_max_i+']')
   #print url+'?u['+str(int(id))+'],v['+str(int(id))+'],lat,lon,time['+str(int(id))+']'   
   #dataset=open_url(url)

  lat_array=dataset['lat']
  id=int(id)   
  lon_array=dataset['lon']
  u1=dataset['u']
  #print u1.u[id]
   #print np.size(lat_array)
   #print np.size(lon_array)
  
   
  v1=dataset['v']
#print list(u1.u[id])  
   #print np.size(v1)
   #jdmat_1=dataset['time']
   #jdmat_1=dataset['time']
   #change array to list: lat & lon
  lat_vel,lon_vel,jdmat_2,jdmat_m,u,v=[],[],[],[],[],[]
  for i in lat_array:
      lat_vel.append(i)
  for j in lon_array:
      lon_vel.append(j)
  #print lon_vel    
  [lon_vel,lat_vel]=pylab.squeeze(list(np.meshgrid(lon_vel,lat_vel)))   
  #print lat_vel[0],lat_vel[-1],lon_vel[0],lon_vel[-1]  
  u1=pylab.squeeze(list(np.array(u1.u[id])))
   #u1=np.array(u1.u.data)
  v1=pylab.squeeze(list(np.array(v1.v[id])))
   #print "size of v1 "+str(np.size(v1))
  #print list(u1)
  for y in range(len(u1)): 
      u.append(u1[y]/100)# converting to m/s
      v.append(v1[y]/100)
  #print u[0],u[-1]
  #print np.shape(u1)
  return lat_vel,lon_vel,u,v
コード例 #9
0
def getcodar(url, datetime_wanted):
    """
    Routine to track particles very crudely though the codar fields
    by extracting data from their respective OPeNDAP/THREDDS archives via the pyDAP method
    Example input: 
    datetime_wanted = datetime.datetime(2007,10,2)                     
    url = "http://tashtego.marine.rutgers.edu:8080/thredds/dodsC/cool/codar/totals/sw06"
    """
    print datetime_wanted

    dtime = open_url(url + '?time')
    id = ml.find(
        np.array(dtime['time']) == date2num(datetime_wanted) -
        date2num(dt.datetime(2001, 1, 1, 0, 0)))

    dataset = open_url(url + '?u[' + str(int(id)) + '],v[' + str(int(id)) +
                       '],lat,lon,time[' + str(int(id)) + ']')
    print url + '?u[' + str(int(id)) + '],v[' + str(
        int(id)) + '],lat,lon,time[' + str(int(id)) + ']'

    lat_array = dataset['lat']
    lon_array = dataset['lon']
    u1 = dataset['u']
    v1 = dataset['v']
    print lat_array
    u, v = [], []

    lat_vel = [lat for lat in lat_array]
    lon_vel = [lon for lon in lon_array]

    [lon_vel, lat_vel] = pylab.squeeze(list(np.meshgrid(lon_vel, lat_vel)))

    u1 = pylab.squeeze(list(np.array(u1.u[id])))
    v1 = pylab.squeeze(list(np.array(v1.v[id])))

    for y in range(len(u1)):
        u.append(u1[y] / 100)  # converting to m/s
        v.append(v1[y] / 100)

    return lat_vel, lon_vel, u, v
コード例 #10
0
def sp_a2d(parameter):
    """
    transforms a given SLIP parameter set (array) into a dict
    *NOTE*: here, the array must have format k|alpha|L0|beta|dE
    """
    params = squeeze(parameter)
    return {
        'k': params[0],
        'alpha': params[1],
        'L0': params[2],
        'beta': params[3],
        'dE': params[4],
    }
コード例 #11
0
ファイル: getdata.py プロジェクト: jian-cui/pyocean
def getcodar(url, datetime_wanted):
    """
    Routine to track particles very crudely though the codar fields
    by extracting data from their respective OPeNDAP/THREDDS archives via the pyDAP method
    Example input: 
    datetime_wanted = datetime.datetime(2007,10,2)                     
    url = "http://tashtego.marine.rutgers.edu:8080/thredds/dodsC/cool/codar/totals/sw06"
    """
    print datetime_wanted                
    
    dtime = open_url(url + '?time')
    id = ml.find(np.array(dtime['time']) == date2num(datetime_wanted) - date2num(dt.datetime(2001, 1, 1, 0, 0)))
    
    dataset = open_url(url + '?u[' + str(int(id)) + '],v[' + str(int(id)) + '],lat,lon,time[' + str(int(id)) + ']')
    print url + '?u[' + str(int(id)) + '],v[' + str(int(id)) + '],lat,lon,time[' + str(int(id)) + ']'   
    
    lat_array = dataset['lat']
    lon_array = dataset['lon']
    u1 = dataset['u']
    v1 = dataset['v']
    print lat_array
    u, v = [], []
    
    lat_vel = [lat for lat in lat_array]
    lon_vel = [lon for lon in lon_array] 
    
    [lon_vel, lat_vel] = pylab.squeeze(list(np.meshgrid(lon_vel, lat_vel)))   
    
    u1 = pylab.squeeze(list(np.array(u1.u[id])))
    v1 = pylab.squeeze(list(np.array(v1.v[id])))

    for y in range(len(u1)): 
        u.append(u1[y] / 100)    # converting to m/s
        v.append(v1[y] / 100)
        
    return lat_vel, lon_vel, u, v
コード例 #12
0
def tc(X,A,lbda,adapt,eta,iter,soft):
    L,batch_size = shape(X)
    M = shape(A)[1]

    a = zeros([M,batch_size],'d')
    u = zeros([M,batch_size],'d')

    C = asarray(matrix(A).T * matrix(A))
    for i in range(M): C[i,i] = 0

    for n in range(batch_size):
        print '\r', n,
        sys.stdout.flush()

        b = squeeze(A.T * X[:,n])
        thresh = abs(b).max()

        a[:,n], u[:,n] = tc_fast(C,b,lbda,adapt,eta,iter,soft,thresh)
    print '\r',
    
    return (a,u)
コード例 #13
0
ファイル: proc_video3.py プロジェクト: jianghongping/PyECLOUD
flag_log = True

N_dec = 2

i_photog = 0

for pass_ind in range(firs_pass, last_pass):

    filename_rho = 'rho_video/rho_pass%d.mat' % pass_ind

    dict_ecl_video = sio.loadmat(filename_rho)
    dict_pyecltest = sio.loadmat('Pyecltest.mat')

    rho_video = dict_ecl_video['rho_video']
    t_video = squeeze(dict_ecl_video['t_video'].real)
    b_spac = squeeze(dict_pyecltest['b_spac'].real)
    (nphotog, _, _) = rho_video.shape

    #subprocess.check_call(('rm',  '*.png'))

    for ii in range(0, nphotog, N_dec):
        print('Pass %d %d/%d' % (pass_ind, ii, nphotog))
        imm = np.squeeze(rho_video[ii, :, :])
        if flag_log:
            imm = np.log10(np.abs(imm))
        imshow(imm.T,
               cmap=None,
               norm=None,
               aspect=None,
               interpolation=None,
コード例 #14
0
    0.3383625266019055, 0.3383625190626729, 0.3383625129203459,
    0.33836250815864527, 0.3383625047650565, 0.338362502730721,
    0.33836250205035523
])
t = 240 * pl.arange(0, b_rel.size + 1)

dt = t[1:] - t[:-1]

max_switches = [4]

combina = Combina(t, b_rel)

# Solve the problem using different solution methods/solvers

combina.solve(solver="bnb", max_switches=max_switches)
b_bin_bnb = pl.squeeze(combina.b_bin)

try:
    combina.solve(solver="scip", max_switches=max_switches)
    b_bin_scip = pl.squeeze(combina.b_bin)

except KeyError:
    b_bin_scip = pl.zeros(b_rel.shape)

try:
    combina.solve(solver="gurobi", max_switches=max_switches)
    b_bin_gurobi = pl.squeeze(combina.b_bin)

except KeyError:
    b_bin_gurobi = pl.zeros(b_rel.shape)
コード例 #15
0
    yN = yN, \
    # linear_solver = "ma97", \
    wv = wv)

lsqpe.run_parameter_estimation(hessian="gauss-newton")
# lsqpe.run_parameter_estimation(hessian = "exact-hessian")
lsqpe.show_results()

lsqpe.compute_covariance_matrix()
lsqpe.show_results()

t = pl.linspace(0, 10, 1000)
lsqpe.run_simulation(x0=yN[:, 0], tsim=t)

pl.figure()

pl.scatter(T, yN[0, :], color="b", label="$x_{1,meas}$")
pl.scatter(T, yN[1, :], color="r", label="$x_{2,meas}$")

pl.plot(t, pl.squeeze(lsqpe.Xsim[0, :]), color="b", label="$x_{1,sim}$")
pl.plot(t, pl.squeeze(lsqpe.Xsim[1, :]), color="r", label="$x_{2,sim}$")

pl.xlabel("$t$")
pl.ylabel("$x_1, x_2$", rotation=0)
pl.xlim(0.0, 10.0)

pl.legend(loc="upper left")
pl.grid()

pl.show()
コード例 #16
0
    fdate = hrs_since_day1CE_todate(int(t)) 
    dates.append(fdate.strftime('%Y%m%d%H'))
if YYYYMMDDHH1 not in dates or YYYYMMDDHH2 not in dates:
    raise ValueError, 'date1 or date2 not a valid date (must be in form YYYYMMDDHH, where HH is 00,06,12 or 18)'
# find indices bounding desired times.
ntime1 = dates.index(YYYYMMDDHH1)
ntime2 = dates.index(YYYYMMDDHH2)
print 'ntime1,ntime2:',ntime1,ntime2
if ntime1 >= ntime2:
    raise ValueError,'date2 must be greater than date1'
# get sea level pressure and 10-m wind data.
slpdata = data['slp']
udata = datau['uwnd']
vdata = datav['vwnd']
# mult slp by 0.01 to put in units of millibars.
slpin = 0.01*(slpdata.scale_factor*p.squeeze(slpdata[ntime1:ntime2+1,:,:]) + slpdata.add_offset)
uin = udata.scale_factor*p.squeeze(udata[ntime1:ntime2+1,:,:]) + udata.add_offset
vin = vdata.scale_factor*p.squeeze(vdata[ntime1:ntime2+1,:,:]) + vdata.add_offset
datelabels = dates[ntime1:ntime2+1]
# add cyclic points
slp = p.zeros((slpin.shape[0],slpin.shape[1],slpin.shape[2]+1),p.Float64)
slp[:,:,0:-1] = slpin; slp[:,:,-1] = slpin[:,:,0]
u = p.zeros((uin.shape[0],uin.shape[1],uin.shape[2]+1),p.Float64)
u[:,:,0:-1] = uin; u[:,:,-1] = uin[:,:,0]
v = p.zeros((vin.shape[0],vin.shape[1],vin.shape[2]+1),p.Float64)
v[:,:,0:-1] = vin; v[:,:,-1] = vin[:,:,0]
longitudes.append(360.); longitudes = p.array(longitudes)
# make 2-d grid of lons, lats
lons, lats = p.meshgrid(longitudes,latitudes)
print 'min/max slp,u,v'
print min(p.ravel(slp)),max(p.ravel(slp))
コード例 #17
0
ファイル: pnganim.py プロジェクト: jtomase/matplotlib
    dates.append(fdate.strftime('%Y%m%d%H'))
if YYYYMMDDHH1 not in dates or YYYYMMDDHH2 not in dates:
    raise ValueError, 'date1 or date2 not a valid date (must be in form YYYYMMDDHH, where HH is 00,06,12 or 18)'
# find indices bounding desired times.
ntime1 = dates.index(YYYYMMDDHH1)
ntime2 = dates.index(YYYYMMDDHH2)
print 'ntime1,ntime2:', ntime1, ntime2
if ntime1 >= ntime2:
    raise ValueError, 'date2 must be greater than date1'
# get sea level pressure and 10-m wind data.
slpdata = data['slp']
udata = datau['uwnd']
vdata = datav['vwnd']
# mult slp by 0.01 to put in units of millibars.
slpin = 0.01 * (
    slpdata.scale_factor * p.squeeze(slpdata[ntime1:ntime2 + 1, :, :]) +
    slpdata.add_offset)
uin = udata.scale_factor * p.squeeze(
    udata[ntime1:ntime2 + 1, :, :]) + udata.add_offset
vin = vdata.scale_factor * p.squeeze(
    vdata[ntime1:ntime2 + 1, :, :]) + vdata.add_offset
datelabels = dates[ntime1:ntime2 + 1]
# add cyclic points
slp = p.zeros((slpin.shape[0], slpin.shape[1], slpin.shape[2] + 1), p.Float64)
slp[:, :, 0:-1] = slpin
slp[:, :, -1] = slpin[:, :, 0]
u = p.zeros((uin.shape[0], uin.shape[1], uin.shape[2] + 1), p.Float64)
u[:, :, 0:-1] = uin
u[:, :, -1] = uin[:, :, 0]
v = p.zeros((vin.shape[0], vin.shape[1], vin.shape[2] + 1), p.Float64)
v[:, :, 0:-1] = vin
コード例 #18
0
    fdate = hrs_since_day1CE_todate(int(t))
    dates.append(fdate.strftime('%Y%m%d%H'))
if YYYYMMDDHH1 not in dates or YYYYMMDDHH2 not in dates:
    raise ValueError, 'date1 or date2 not a valid date (must be in form YYYYMMDDHH, where HH is 00,06,12 or 18)'
# find indices bounding desired times.
ntime1 = dates.index(YYYYMMDDHH1)
ntime2 = dates.index(YYYYMMDDHH2)
print 'ntime1,ntime2:', ntime1, ntime2
if ntime1 >= ntime2:
    raise ValueError, 'date2 must be greater than date1'
# get sea level pressure and 10-m wind data.
slpdata = data['presmsl']
udata = datau['ugrdprs']
vdata = datau['vgrdprs']
# mult slp by 0.01 to put in units of millibars.
slpin = 0.01 * p.squeeze(slpdata[ntime1:ntime2 + 1, :, :])
uin = p.squeeze(udata[ntime1:ntime2 + 1, 0, :, :])
vin = p.squeeze(vdata[ntime1:ntime2 + 1, 0, :, :])
datelabels = dates[ntime1:ntime2 + 1]
# add cyclic points
slp = p.zeros((slpin.shape[0], slpin.shape[1], slpin.shape[2] + 1), p.Float64)
slp[:, :, 0:-1] = slpin
slp[:, :, -1] = slpin[:, :, 0]
u = p.zeros((uin.shape[0], uin.shape[1], uin.shape[2] + 1), p.Float64)
u[:, :, 0:-1] = uin
u[:, :, -1] = uin[:, :, 0]
v = p.zeros((vin.shape[0], vin.shape[1], vin.shape[2] + 1), p.Float64)
v[:, :, 0:-1] = vin
v[:, :, -1] = vin[:, :, 0]
longitudes.append(360.)
longitudes = p.array(longitudes)
コード例 #19
0
ファイル: hamming.py プロジェクト: lgarcin/TIPE
def bitsToString(mat):
    return bitarray(squeeze(asarray(mat.transpose().flatten())).tolist()).tobytes()
コード例 #20
0
}

r = requests.post(server_address, json=problem_definition)

print("Status:", r.status_code)

solution = r.json()

print("Errors:", solution["errors"])

print("Solver:", solution["solver"])
print("Solver status:", solution["solver_status"])
print("Objective value:", solution["eta"])

if r.status_code == 200:

    b_bin = pl.squeeze(r.json()["b_bin"])

    pl.figure()
    pl.step(t[:-1],
            b_rel,
            label="b_rel",
            color="C0",
            linestyle="dashed",
            where="post")
    pl.step(t[:-1], b_bin, label="b_bin", color="C0", where="post")
    pl.xlabel("t")
    pl.ylabel("b")
    pl.legend(loc="upper left")
    pl.show()
コード例 #21
0
ファイル: peak_plotting.py プロジェクト: du-lab/ADAP-3D
def plot_these_peaks(allPeakObjects,int_matrix,rt,plotDirStr,listOfAllPeakMZAndRT,countRepeats):
    """
    Plots the input set of peaks (allPeakObjects) in the correct directory.
    
    :param allPeakObjects: List of peak objects (see datamodel for peak objects)
    :param int_matrix: matrix of intensities. Rows are m/z, columns are RT.
    :param rt: Array of retention times.
    :param plotDirStr: Where are the plots going? Which directory?
    :param listOfAllPeakMZAndRT: To keep track of which peaks have been plotted already.
    :param countRepeats: Count of the number of repeats. Function will update the count.
    :return: updated: listOfAllPeakMZAndRT and countRepeats.
    """

    for k in range(len(allPeakObjects)):
        curPeak = allPeakObjects[k]
        mzIndex = allPeakObjects[k].mzIndex
        rtIndex = allPeakObjects[k].rtIndex
        mzMaxIndex = allPeakObjects[k].mzMaxIndex
        mzMinIndex = allPeakObjects[k].mzMinIndex
        rtMaxIndex = allPeakObjects[k].rtMaxIndex
        rtMinIndex = allPeakObjects[k].rtMinIndex

        cur_peak_mz = allPeakObjects[k].mz
        cur_peak_rt = allPeakObjects[k].rt

        if didWePlotThisPeakAlready(listOfAllPeakMZAndRT, cur_peak_mz, cur_peak_rt):
            countRepeats += 1
            continue
        listOfAllPeakMZAndRT.append((cur_peak_mz, cur_peak_rt))

        # show beyond the peak
        eicMin = rtMinIndex - 40
        eicMax = rtMaxIndex + 40

        # print "eicMin before " + str(eicMin )
        # print "eicMax before " + str(eicMax )
        # print "len(pl.squeeze(pl.asarray(int_matrix[0,:].todense()))) " + str(len(pl.squeeze(pl.asarray(int_matrix[0,:].todense()))))

        lenIntMatrix = len(pl.squeeze(pl.asarray(int_matrix[0, :].todense())))

        if eicMin < 0: eicMin = 0
        if eicMax > lenIntMatrix: eicMax = lenIntMatrix
        # print "eicMin after " + str(eicMin )
        # print "eicMax after " + str(eicMax )

        cur_eic_int = pl.squeeze(pl.asarray(int_matrix[mzIndex, eicMin:eicMax].todense()))
        peak_only_eic_int = pl.squeeze(pl.asarray(int_matrix[mzIndex, rtMinIndex:rtMaxIndex].todense()))

        fig = matplotlib.pyplot.gcf()
        fig.set_size_inches(cm2inch(8.9), cm2inch(5.5))
        ax = fig.add_subplot(111)

        fig.subplots_adjust(bottom=0.14, left=0.12, right=0.98, top=0.92)
        # Set axis labels and locations
        ax.xaxis.set_label_coords(0.5, -0.1)
        ax.yaxis.set_label_coords(-0.085, 0.5)

        ax.yaxis.get_major_formatter().set_powerlimits((0, 1))
        ax.ticklabel_format(style='sci', useOffset=False)

        ax.set_xlabel("rt")
        ax.set_ylabel("intensity")
        # ax.set_ylim([most_min,most_max])
        # ax.set_xlim([min_rt_arr[0],min_rt_arr[-1]])

        # ax.plot(min_rt_arr,cur_eic_int,c='k',linewidth=linewidth,marker='o',markersize=markersize)
        # ax.plot(pl.arange(eicMin,eicMax),cur_eic_int,c='k',linewidth=linewidth,marker='o',markersize=markersize)
        ax.plot(rt[eicMin:eicMax], cur_eic_int, c='k', linewidth=linewidth, marker='o', markersize=markersize)
        # ax.fill_between(peak_only_rt_arr,peak_only_eic_int,color='red',interpolate=True)
        # ax.fill_between(pl.arange(rtMinIndex,rtMaxIndex),peak_only_eic_int,color='red',interpolate=True)
        ax.fill_between(rt[rtMinIndex:rtMaxIndex], peak_only_eic_int, color='red', interpolate=True)

        ax.annotate("C/A=%.2f" % (curPeak.coefOverArea), xy=(0.130, .870), xycoords='figure fraction', fontsize=8)
        ax.annotate("AsymFit=%.2f" % (curPeak.asymGausFit), xy=(0.130, .80), xycoords='figure fraction', fontsize=8)
        # ax.annotate("RT=%.2f"%(curPeak.rt),xy=(0.130,.73),xycoords='figure fraction',fontsize=8)
        yloc = 0.73
        for simIdx in range(len(curPeak.similarityAdjMZ)):
            ax.annotate("Sim=%.2f" % (curPeak.similarityAdjMZ[simIdx]), xy=(0.130, yloc), xycoords='figure fraction',
                        fontsize=8)
            yloc -= 0.07

        pl.savefig(plotDirStr + "/" + str(k) + "_mz" + str(cur_peak_mz)+"_rt"+ str(cur_peak_rt) + ".pdf", dpi=300)
        pl.close(fig)

    return listOfAllPeakMZAndRT, countRepeats
コード例 #22
0
ファイル: plot_test.py プロジェクト: cdd1969/ascii2cdl
#from mpl_toolkits.basemap import Basemap
# --------------------------------------------------
#                   User Input
# --------------------------------------------------
OUTPATH = '//Widar/home/ak2stud/Nick/python_scripts/ascii2netcdf/work_in_progress/general/'


OUTFILE = 'test_unlim.nc'
a = Dataset(str(OUTPATH+OUTFILE), mode='r')

# ----------------------------
# -------- bathymetry --------
# ----------------------------
vars = a.variables

z = squeeze(vars['z'][:, :])
z = np.fliplr(z)  # flip horizontally
x = squeeze(vars['GridX'][:])
y = squeeze(vars['GridY'][:])

f = plt.figure()
f.suptitle('Bathymetry', fontsize=20)
ax = plt.gca()
im = ax.imshow(z.T, extent=(x.min(), x.max(), y.min(), y.max()),
           interpolation='nearest', cmap=cm.gist_rainbow)
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="2%", pad=0.05)
plt.colorbar(im, cax=cax)
plt.show()
コード例 #23
0
    ydata = yN, wv = wv, discretization_method = "collocation")

pe.run_parameter_estimation()
pe.print_estimation_results()

pe.compute_covariance_matrix()
pe.print_estimation_results()

T_sim = pl.linspace(0, 10, 101)
x0 = yN[:,0]

sim = cp.sim.Simulation(system, pe.estimated_parameters)
sim.run_system_simulation(time_points = T_sim, x0 = x0)

pl.figure()

pl.scatter(T, yN[0,:], color = "b", label = "$x_{1,meas}$")
pl.scatter(T, yN[1,:], color = "r", label = "$x_{2,meas}$")

pl.plot(T_sim, pl.squeeze(sim.simulation_results[0,:]), color="b", label = "$x_{1,sim}$")
pl.plot(T_sim, pl.squeeze(sim.simulation_results[1,:]), color="r", label = "$x_{2,sim}$")

pl.xlabel("$t$")
pl.ylabel("$x_1, x_2$", rotation = 0)
pl.xlim(0.0, 10.0)

pl.legend(loc = "upper left")
pl.grid()

pl.show()
コード例 #24
0
ファイル: IDE.py プロジェクト: mikedewar/BrainIDE
	def gen_ssmodel(self):

		'''Generates non-linear, Integro-Difference, discrete-time state space model.

		Atributes:
		----------
		Gamma: matrix
			Inner product of field basis functions
		Sigma_e: matrix
			Covariance matrix of the field disturbance
		Sigma_e_c: matrix
			cholesky decomposiotion of field disturbance covariance matrix
		
		Sigma_varepsilon_c: matrix
			cholesky decomposiotion of observation noise covariance matrix

		Phi_values: matrix
			field basis functions values over the spatial field

		psi0_conv_Phi_values: list
			convolution of the central excitatory connectivity kernel basis function with the field basis functions
			evaluate over space

		psi1_conv_Phi_values: list
			convolution of the surround inhibition connectivity kernel basis function with the field basis functions
			evaluate over space

		psi2_conv_Phi_values: list
			convolution of the longer range excitatory connectivity kernel basis function with the field basis functions
			evaluate over space

		C: matrix
			Observation matrix
		'''


		print 'Generating state space model'
		# unpack the kernel
 		psi0,psi1,psi2=self.kernel.Psi[0],self.kernel.Psi[1],self.kernel.Psi[2]
		psi0_weight,psi1_weight,psi2_weight=self.kernel.weights[0],self.kernel.weights[1],self.kernel.weights[2]
		#centers
		psi0_center=psi0.center
		psi1_center=psi1.center
		psi2_center=psi2.center
		#widths
		psi0_width=psi0.width
		psi1_width=psi1.width
		psi2_width=psi2.width


		#Generate Gamma
		if hasattr(self,'Gamma'):
			pass
		else:

			#calculate Gamma=PhixPhi.T; inner product of the field basis functions
			Gamma=pb.matrix(self.field.Phi*self.field.Phi.T,dtype=float)
			Gamma_inv=Gamma.I
			self.Gamma=Gamma
			self.Gamma_inv=Gamma_inv

		#Generate field covariance matrix and its Cholesky decomposition
		if hasattr(self,'Sigma_e'):
			pass
		else:

			gamma_convolution_vecrorized=pb.vectorize(self.gamma.conv)
			gamma_conv_Phi=gamma_convolution_vecrorized(self.field.Phi).T 
			Pi=pb.matrix(self.field.Phi*gamma_conv_Phi,dtype=float) #nx by nx matrix
			Sigma_e=self.gamma_weight*Gamma_inv*Pi*Gamma_inv.T
			Sigma_e_c=pb.matrix(sp.linalg.cholesky(Sigma_e)).T
			self.Sigma_e=Sigma_e
			self.Sigma_e_c=Sigma_e_c
			#calculate Cholesky decomposition of observation noise covariance matrix
			Sigma_varepsilon_c=pb.matrix(sp.linalg.cholesky(self.Sigma_varepsilon)).T
			self.Sigma_varepsilon_c=Sigma_varepsilon_c


		if hasattr(self,'Phi_values'):
			pass
		else:

		

			#vectorizing convolution function of the kernel basis functions
			psi0_convolution_vectorized=pb.vectorize(psi0.conv) 	
			psi1_convolution_vectorized=pb.vectorize(psi1.conv) 	
			psi2_convolution_vectorized=pb.vectorize(psi2.conv) 	
			#convolving each kernel basis function with the field basis functions
			psi0_conv_Phi=psi0_convolution_vectorized(self.field.Phi) 
			psi1_conv_Phi=psi1_convolution_vectorized(self.field.Phi) 
			psi2_conv_Phi=psi2_convolution_vectorized(self.field.Phi)

			Psi_conv_Phi=pb.hstack((psi0_conv_Phi,psi1_conv_Phi,psi2_conv_Phi))
	
			#Finding the convolution of the kernel basis functions with field basis functions at discritized spatial points
			psi0_conv_Phi_values=[]
			psi1_conv_Phi_values=[]
			psi2_conv_Phi_values=[]
			Phi_values=[]

			psi0_conv_Phi_values_temp=[]
			psi1_conv_Phi_values_temp=[]
			psi2_conv_Phi_values_temp=[]
			Phi_values_temp=[]

			t_Gamma_inv_Psi_sep=time.time()
			for m in range(self.nx):
				for i in self.field_space:
					for j in self.field_space:
						psi0_conv_Phi_values_temp.append(psi0_conv_Phi[m,0](pb.matrix([[i],[j]])))
						psi1_conv_Phi_values_temp.append(psi1_conv_Phi[m,0](pb.matrix([[i],[j]])))
						psi2_conv_Phi_values_temp.append(psi2_conv_Phi[m,0](pb.matrix([[i],[j]])))


						Phi_values_temp.append(self.field.Phi[m,0](pb.matrix([[i],[j]])))


				psi0_conv_Phi_values.append(psi0_conv_Phi_values_temp)
				psi1_conv_Phi_values.append(psi1_conv_Phi_values_temp)
				psi2_conv_Phi_values.append(psi2_conv_Phi_values_temp)
				Phi_values.append(Phi_values_temp)

				psi0_conv_Phi_values_temp=[]
				psi1_conv_Phi_values_temp=[]
				psi2_conv_Phi_values_temp=[]
				Phi_values_temp=[]


			Phi_values=pb.matrix(Phi_values)

			self.psi0_conv_Phi_values=psi0_conv_Phi_values
			self.psi1_conv_Phi_values=psi1_conv_Phi_values
			self.psi2_conv_Phi_values=psi2_conv_Phi_values		


			self.Phi_values=Phi_values 
			Gamma_inv_psi0_conv_Phi=self.Gamma_inv*psi0_conv_Phi_values 
			Gamma_inv_psi1_conv_Phi=self.Gamma_inv*psi1_conv_Phi_values 
			Gamma_inv_psi2_conv_Phi=self.Gamma_inv*psi2_conv_Phi_values  			

			self.Gamma_inv_psi0_conv_Phi=Gamma_inv_psi0_conv_Phi
			self.Gamma_inv_psi1_conv_Phi=Gamma_inv_psi1_conv_Phi
			self.Gamma_inv_psi2_conv_Phi=Gamma_inv_psi2_conv_Phi



		#Calculate observation matrix
			
		if hasattr(self,'C'):
			pass
		else:
			sensor_kernel_convolution_vecrorized=pb.vectorize(self.sensor_kernel.conv)
			sensor_kernel_conv_Phi=sensor_kernel_convolution_vecrorized(self.field.Phi).T 
			sensor_kernel_conv_Phi_values_temp=[]
			sensor_kernel_conv_Phi_values=[]
			for m in range(self.nx):
				for n in self.obs_locns:
					sensor_kernel_conv_Phi_values_temp.append(sensor_kernel_conv_Phi[0,m](n))
				sensor_kernel_conv_Phi_values.append(sensor_kernel_conv_Phi_values_temp)
				sensor_kernel_conv_Phi_values_temp=[]
			C=pb.matrix(pb.squeeze(sensor_kernel_conv_Phi_values).T)
			self.C=C


	
		#Finding the convolution of the kernel  with field basis functions at discritized spatial points
		self.Gamma_inv_Psi_conv_Phi=psi0_weight*self.Gamma_inv_psi0_conv_Phi+ \
		psi1_weight*self.Gamma_inv_psi1_conv_Phi+psi2_weight*self.Gamma_inv_psi2_conv_Phi
コード例 #25
0
ファイル: silverbox.py プロジェクト: vishalbelsare/PECas
lsqpe_dummy.run_simulation(x0=[0.0, 0.0], psim=p_true / scale)

y_data = lsqpe_dummy.Xsim
y_data += 1e-3 * pl.random((x.shape[0], N + 1))

wv = pl.ones(y_data.shape)

lsqpe = pecas.LSq( \
    system = odesys, \
    tu = ty, \
    uN = u_data, \
    yN = y_data, \
    pinit = p_guess, \
    xinit = y_data, \
    # linear_solver = "ma97", \
    wv = wv)

lsqpe.run_parameter_estimation()
lsqpe.run_simulation(x0=[0.0, 0.0])

pl.close("all")
pl.figure()

pl.scatter(ty, pl.squeeze(y_data[0, :]))
pl.plot(ty, lsqpe.Xsim[0, :].T)

pl.scatter(ty, pl.squeeze(y_data[1, :]))
pl.plot(ty, lsqpe.Xsim[1, :].T)

pl.show()
コード例 #26
0
data = pl.loadtxt("data/data_example_1.csv", delimiter = " ", skiprows = 1)

t = data[:,0]
b_rel = data[:-1, 1]
n_max_switches = [4]

binapprox = BinApprox(t = t, b_rel = b_rel, binary_threshold = 1e-3, \
    off_state_included = False)

binapprox.set_n_max_switches(n_max_switches = max_switches)
#binapprox.set_min_up_times(min_up_times = [10])
#binapprox.set_min_down_times(min_down_times = [10])
#binapprox.set_cia_norm("column_sum_norm")


combina = CombinaMILP(binapprox)

#combina.solve(gurobi_opts = {"TimeLimit": 20, "MIPGap": 0.8})
combina.solve(use_warm_start=False)

b_bin = pl.squeeze(binapprox.b_bin)

pl.figure()
pl.step(t[:-1], b_rel, label = "b_rel", color = "C0", linestyle = "dashed", where = "post")
pl.step(t[:-1], b_bin, label = "b_bin", color = "C0", where = "post")
pl.xlabel("t")
pl.ylabel("b")
pl.legend(loc = "upper left")
pl.show()
コード例 #27
0
from ClusterMap import *
from LoadRastRadar import *
from RadarPlotUtils import *
import MapUtils

from mpl_toolkits.basemap import Basemap

import pylab

theFile = 'TestData.nc'
rasterized = False
namestem = ""

rastData = LoadRastRadar(theFile)

print pylab.nanmin(pylab.squeeze(rastData['vals']))

mapLayers = MapUtils.mapLayers

# Map domain
map = Basemap(projection='cyl',
              resolution='i',
              suppress_ticks=False,
              llcrnrlat=rastData['lats'].min(),
              llcrnrlon=rastData['lons'].min(),
              urcrnrlat=rastData['lats'].max(),
              urcrnrlon=rastData['lons'].max())

fig = pylab.figure(figsize=(15.0, 6.0))

ax = fig.add_subplot(1, 2, 1)
コード例 #28
0
ファイル: hamming.py プロジェクト: lgarcin/TIPE
def correct(mat):
    S = remainder(H * mat, 2)
    pos = squeeze(asarray(matrix([4, 2, 1]) * S))
    cor = fromfunction(lambda i, j:i == pos - 1, mat.shape) * 1
    return mat + cor
コード例 #29
0
           data["TSH2"].values[int_start::500],
           marker="x",
           label=r"meas TSH2",
           color="g")
pl.scatter(time_points[::500],
           data["TSH3"].values[int_start::500],
           marker="x",
           label=r"meas TSH3",
           color="r")
pl.scatter(time_points[::500],
           data["TSH1"].values[int_start::500],
           marker="x",
           label=r"meas TSH1",
           color="c")
pl.plot(time_points,
        pl.squeeze(sim_est.simulation_results[0, :]),
        label=r"sim TSH0",
        color="b")
pl.plot(time_points,
        pl.squeeze(sim_est.simulation_results[1, :]),
        label=r"sim TSH2",
        color="g")
pl.plot(time_points,
        pl.squeeze(sim_est.simulation_results[2, :]),
        label=r"sim TSH3",
        color="r")
pl.plot(time_points,
        pl.squeeze(sim_est.simulation_results[3, :]),
        label=r"sim TSH1",
        color="c")
pl.plot(time_points[::500],
コード例 #30
0
        fine_labels = dataset['labels/train_set'][:20]
        coarse_labels = dataset['coarse_labels/train_set'][:20]
        for im, coarse, fine, cpt in zip(images, coarse_labels, fine_labels,
                                         range(20)):
            pl.subplot(2, 10, cpt + 1)
            pl.title(str(coarse)+', '+str(fine)+': '\
                    +dataset.classes[fine])
            plotting.imshow(im)
    else:
        labels = dataset['labels/train_set'][:20]
        if 'images' in dataset.variables:
            images = dataset['images/train_set'][:20]
        else:
            images = dataset['signals/train_set'][:20]
        for im, label, cpt in zip(images, labels, range(20)):
            pl.subplot(2, 10, cpt + 1)
            if len(im) > 2:
                plotting.imshow(im)
            else:
                signal = pl.squeeze(im)
                pl.plot(signal)
                pl.xlim([0, len(signal)])
                pl.xticks([])
                pl.yticks([])
            pl.title(str(label) + ": " + dataset.classes[label])

    # Reduce side margins and save fig
    pl.tight_layout()
    pl.savefig('../sknet/docs/source/_static/' + dataset.name + '_samples.png')
    pl.close()
コード例 #31
0
    def run(self, batch_size=1000, num_trials=10):
        L, M = shape(self.A)
        display_every = self.display_every
        sz = int(sqrt(L))

        for t in range(num_trials):
            tictime = time()
            X = choose_patches(self.IMAGES, L, batch_size)
            time_ch = time() - tictime

            tictime = time()
            S,U = tc(X, self.A, self.lbda, self.adapt, self.eta,
                     self.iter, self.soft)
            S = matrix(S)
            time_tc = time() - tictime

            tictime = time()
            args = (S, X, self.gamma)

            if (self.run_gd):
                x0 = squeeze(asarray(reshape(self.A,[L*M,1])))
                obj0 = f_l2_wd(x0, S, X, self.gamma)
                E = X - self.A*S
                dA = E*S.T/batch_size
                A1 = self.A + self.eta_gd * dA
                x1 = squeeze(asarray(reshape(A1,[L*M,1])))
                obj1 = f_l2_wd(x1, S, X, self.gamma)

            if (self.run_cg):
                x0 = squeeze(asarray(reshape(self.A,[L*M,1])))
                obj0 = f_l2_wd(x0, S, X, self.gamma)
#                x1 = fmin_ncg(f_l2_wd, x0, g_l2_wd,
#                              None, None, args, maxiter=self.cg_maxiter,
#                              epsilon=self.cg_epsilon)
#                x1 = fmin_cg(f_l2_wd, x0, g_l2_wd,
#                             args, maxiter=self.cg_maxiter,
#                             epsilon=self.cg_epsilon, gtol=self.cg_gtol,
#                             norm=2)
                x1 = fmin_cg(f_l2_wd, x0, g_l2_wd,
                             args, maxiter=self.cg_maxiter)

#                x1,fX,i = minimize.f_min(x0, objfun_l2_wd, 5, args)

                obj1 = f_l2_wd(x1, S, X, self.gamma)
                A1 = matrix(reshape(x1,[L,M]))

            time_ud = time() - tictime

            tictime = time()
            if ( display_every == 1 or (self.update % display_every == 0)):
                if ( self.display_bf ):
                    array = render_network(self.A)
                    figure(1)
                    imshow(transpose(array),cm.gray,interpolation='nearest')

                if ( self.display_recon ):
                    Ihat = matrix(self.A)*S
                    figure(2)
                    subplot(1,2,1)
                    imshow(reshape(Ihat[:,0],[sz,sz]),cm.gray,
                           interpolation='nearest')
                    subplot(1,2,2)
                    imshow(reshape(X[:,0],[sz,sz]),cm.gray,
                           interpolation='nearest')

                if ( self.display_norm ):
                    normA = sum(A1.A**2)
                    figure(3)
                    bar(arange(M),normA,0.1,color='b',hold=False)

            time_dy = time() - tictime

            # normalize to unit length
            A1 = A1*matrix(eye(M)*1/sqrt(sum(A1.A**2)))
            self.A = asarray(A1)
	
            print "update", self.update, "ch", '%.4f'% time_ch,
            print "if", '%.4f'% time_tc, "ud", '%.4f'% time_ud,
            print "dy", '%.4f'% time_dy, "o0", '%.4f'% obj0,
            print "o1", '%.4f'% obj1

            self.update += 1
コード例 #32
0
ファイル: hamming.py プロジェクト: lgarcin/TIPE
def bitsToImage(mat, shape):
    s = bitarray(squeeze(asarray(mat.transpose().flatten())).tolist()).tobytes()
    return resize(array(bytearray(s)).astype('uint8'), shape)
コード例 #33
0
ファイル: proc_video3.py プロジェクト: jsopouse/PyECLOUD
flag_log=True

N_dec=2

i_photog=0

for pass_ind in range(firs_pass,last_pass):
    
    filename_rho='rho_video/rho_pass%d.mat'%pass_ind
            
    dict_ecl_video=sio.loadmat(filename_rho)
    dict_pyecltest=sio.loadmat('Pyecltest.mat')
    
    rho_video=dict_ecl_video['rho_video']
    t_video=squeeze(dict_ecl_video['t_video'].real)
    b_spac=squeeze(dict_pyecltest['b_spac'].real)
    (nphotog,_,_)=rho_video.shape
    
    #subprocess.check_call(('rm',  '*.png'))
    
    for ii in xrange(0, nphotog, N_dec):
        print 'Pass %d %d/%d'%(pass_ind,ii,nphotog)
        imm=np.squeeze(rho_video[ii,:,:])
        if flag_log:
            imm = np.log10(np.abs(imm))
        imshow(imm.T, cmap=None, norm=None, aspect=None, interpolation=None,
           alpha=None, vmin=None, vmax=None, origin='lower', extent=None)
        colorbar()
        title(('passage = %d'% floor(t_video[ii]/b_spac)))
        #xlabel('x [m]')
コード例 #34
0
    system = odesys, pdata = p_true / scale)
simulation_true_parameters.run_system_simulation( \
    x0 = [0.0, 0.0], time_points = tN, udata = udata)

ydata = simulation_true_parameters.simulation_results
ydata += 1e-3 * pl.random((x.shape[0], N + 1))

wv = pl.ones(ydata.shape)

pe = cp.pe.LSq(system = odesys, \
    time_points = tN, xinit = ydata, \
    ydata = ydata, wv = wv, udata = udata, pinit = p_guess)

pe.run_parameter_estimation()

simulation_estimated_parameters = cp.sim.Simulation( \
    system = odesys, pdata = pe.estimated_parameters)
simulation_estimated_parameters.run_system_simulation( \
    x0 = [0.0, 0.0], time_points = tN, udata = udata)

pl.close("all")
pl.figure()

pl.scatter(tN, pl.squeeze(ydata[0, :]))
pl.plot(tN, simulation_estimated_parameters.simulation_results[0, :].T)

pl.scatter(tN, pl.squeeze(ydata[1, :]))
pl.plot(tN, simulation_estimated_parameters.simulation_results[1, :].T)

pl.show()
コード例 #35
0
ファイル: IDEModel.py プロジェクト: mikedewar/BrainIDE
	def gen_ssmodel(self):

		'''Generates non-linear, Integro-Difference, discrete-time state space model.

		Atributes:
		----------
		Gamma: ndarray
			Inner product of field basis functions

		Gamma_inv: ndarray
			Inverse of Gamma

		Sigma_e: ndarray
			Covariance matrix of the field disturbance

		Sigma_e_inv: ndarray
			Inverse of Sigma_e

		Sigma_e_c: ndarray
			cholesky decomposiotion of field disturbance covariance matrix
		
		Sigma_varepsilon_c: ndarray
			cholesky decomposiotion of observation noise covariance matrix

		Phi_values: ndarray  nx by number of spatial locations
			field basis functions values over the spatial field

		psi_conv_Phi_values: ndarray ; each ndarray is nx by number of spatial locations
			convolution of the  connectivity kernel basis functions with the field basis functions
			evaluate over space


		Gamma_inv_psi_conv_Phi:ndarray; each ndarray is nx by number of spatial locations
			the product of inverse gamme withe psi0_conv_Phi



		C: ndarray
			Observation matrix

		Gamma_inv_Psi_conv_Phi: ndarray nx by number of spatial locations
			the convolution of the kernel  with field basis functions at discritized spatial points

		'''

		#Generate Gamma
		if hasattr(self,'Gamma'):
			pass
		else:
			t_total=time.time()
			#calculate Gamma=PhixPhi.T; inner product of the field basis functions
			Gamma=pb.dot(self.field.Phi,self.field.Phi.T)
			Gamma_inv=pb.inv(Gamma)
			self.Gamma=Gamma.astype('float')
			self.Gamma_inv=Gamma_inv


		#Generate field covariance matrix
		if hasattr(self,'Sigma_e'):
			pass
		else:

			gamma_convolution_vecrorized=pb.vectorize(self.gamma.conv)
			gamma_conv_Phi=gamma_convolution_vecrorized(self.field.Phi).T 
			#[gamma*phi1 gamma*phi2 ... gamma*phin] 1 by nx
			Pi=pb.dot(self.field.Phi,gamma_conv_Phi) #nx by nx ndarray
			Pi=Pi.astype('float')
			Sigma_e=pb.dot(pb.dot(self.gamma_weight*Gamma_inv,Pi),Gamma_inv.T)
			Sigma_e_c=sp.linalg.cholesky(Sigma_e,lower=1)
			self.Sigma_e=Sigma_e
			self.Sigma_e_inv=pb.inv(Sigma_e)
			self.Sigma_e_c=Sigma_e_c
			Sigma_varepsilon_c=sp.linalg.cholesky(self.Sigma_varepsilon,lower=1)
			self.Sigma_varepsilon_c=Sigma_varepsilon_c



		if hasattr(self,'Phi_values'):
			pass
		else:

		
			#Generate field meshgrid
			estimation_field_space_x,estimation_field_space_y=pb.meshgrid(self.estimation_space_x_y,self.estimation_space_x_y)
			estimation_field_space_x=estimation_field_space_x.ravel()
			estimation_field_space_y=estimation_field_space_y.ravel()

			#calculate Phi_values
			#Phi_values is like [[phi1(r1) phi1(r2)...phi1(rn_r)],[phi2(r1) phi2(r2)...phi2(rn_r)],..[phiL(r1) phiL(r2)...phiL(rn_r)]]
			Phi_values=[self.field.Phi[i,0](estimation_field_space_x,estimation_field_space_y) for i in range(self.nx)]
			self.Phi_values=pb.squeeze(Phi_values) #it's nx by number of apatial points

			#vectorizing kernel convolution method
			psi_convolution_vectorized=pb.empty((self.n_theta,1),dtype=object)
			for i in range(self.n_theta):
				psi_convolution_vectorized[i,0]=pb.vectorize(self.kernel.Psi[i].conv)

			#find convolution between kernel and field basis functions analytically
			psi_conv_Phi=pb.empty((self.nx,self.n_theta),dtype=object)#nx by n_theta
			for i in range(self.n_theta):
				psi_conv_Phi[:,i]=psi_convolution_vectorized[i,0](self.field.Phi).ravel()


			#ecaluate convolution between kernel and field basis functions at spatial locations
			psi_conv_Phi_values=pb.empty((self.n_theta,self.nx,len(self.estimation_space_x_y)**2),dtype=float)
			for i in range(self.n_theta):
				for j in range(self.nx):
					psi_conv_Phi_values[i,j,:]=psi_conv_Phi[j,i](estimation_field_space_x,estimation_field_space_y)
			self.psi_conv_Phi_values=psi_conv_Phi_values



			self.Gamma_inv_psi_conv_Phi=pb.dot(self.Gamma_inv,self.psi_conv_Phi_values)
				

		


		#Calculate observation matrix
			
		if hasattr(self,'C'):
			pass
		else:
			#Generate Observation locations grid
			obs_locns_x=self.obs_locns[:,0]
			obs_locns_y=self.obs_locns[:,1]
			sensor_kernel_convolution_vecrorized=pb.vectorize(self.sensor_kernel.conv)
			sensor_kernel_conv_Phi=sensor_kernel_convolution_vecrorized(self.field.Phi).T #first row 
			#[m*phi_1 m*phi2 ... m*phin]
			C=pb.empty(([self.ny,self.nx]),dtype=float)
			for i in range(self.nx):
				C[:,i]=sensor_kernel_conv_Phi[0,i](obs_locns_x,obs_locns_y)

			self.C=C
			print 'Elapsed time in seconds to generate the stat-space model',time.time()-t_total


		#We need to calculate this bit at each iteration	
		#Finding the convolution of the kernel  with field basis functions at discritized spatial points
		self.Gamma_inv_Psi_conv_Phi=pb.sum(self.kernel.weights[pb.newaxis,:,pb.newaxis]*self.Gamma_inv_psi_conv_Phi,axis=1)
コード例 #36
0
    fdate = hrs_since_day1CE_todate(int(t))
    dates.append(fdate.strftime('%Y%m%d%H'))
if YYYYMMDDHH1 not in dates or YYYYMMDDHH2 not in dates:
    raise ValueError, 'date1 or date2 not a valid date (must be in form YYYYMMDDHH, where HH is 00,06,12 or 18)'
# find indices bounding desired times.
ntime1 = dates.index(YYYYMMDDHH1)
ntime2 = dates.index(YYYYMMDDHH2)
print 'ntime1,ntime2:',ntime1,ntime2
if ntime1 >= ntime2:
    raise ValueError,'date2 must be greater than date1'
# get sea level pressure and 10-m wind data.
slpdata = data['presmsl']
udata = datau['ugrdprs']
vdata = datau['vgrdprs']
# mult slp by 0.01 to put in units of millibars.
slpin = 0.01*p.squeeze(slpdata[ntime1:ntime2+1,:,:])
uin = p.squeeze(udata[ntime1:ntime2+1,0,:,:]) 
vin = p.squeeze(vdata[ntime1:ntime2+1,0,:,:]) 
datelabels = dates[ntime1:ntime2+1]
# add cyclic points
slp = p.zeros((slpin.shape[0],slpin.shape[1],slpin.shape[2]+1),p.Float64)
slp[:,:,0:-1] = slpin; slp[:,:,-1] = slpin[:,:,0]
u = p.zeros((uin.shape[0],uin.shape[1],uin.shape[2]+1),p.Float64)
u[:,:,0:-1] = uin; u[:,:,-1] = uin[:,:,0]
v = p.zeros((vin.shape[0],vin.shape[1],vin.shape[2]+1),p.Float64)
v[:,:,0:-1] = vin; v[:,:,-1] = vin[:,:,0]
longitudes.append(360.); longitudes = p.array(longitudes)
# make 2-d grid of lons, lats
lons, lats = p.meshgrid(longitudes,latitudes)
print 'min/max slp,u,v'
print min(p.ravel(slp)),max(p.ravel(slp))
コード例 #37
0
        F, pp, cohe, Fx2y, Fy2x, Fxy = granger(
            lfpdata[:, layerA, 0], lfpdata[:, layerB, 0],
            order=20)  # Pick out LFPs from layers (default 2/3 and 5)
        results.append(Fx2y)

print "Plotting..."
figh = figure(figsize=(10, 6))  # Open figure and store its handle

# Plot Granger spectra
hold(True)
labels = list()
labels = ['Baseline', 'With damage', 'With prosthesis']
alldata = list()
colors = [[0, 0, 1], [1, 0, 0], [0, 0.5, 0]]
for i in range(nscenarios):
    data = squeeze(results[i])
    plot(F, data, label=labels[i], linewidth=2, c=colors[i])
    alldata.append(data)
    xlim(0, 50)
    ylim(0, 0.5)  # Need to define explicitly since otherwise
xlabel('Frequency (Hz)')
ylabel('Granger causality')
legend()

toc = time.clock()
print 'Done; elapsed time was %0.1f seconds.' % (toc - tic)

# Do stats
endpt = size(alldata[0], 0) / 1.2  # Only go out to 50 Hz
startpt = size(alldata[0], 0) / 12  # Start at 5 Hz
totals = zeros((nscenarios))
コード例 #38
0
ファイル: basemap.py プロジェクト: jtomase/matplotlib
    def drawmeridians(self,ax,meridians,color='k',linewidth=1., \
                      linestyle='--',dashes=[1,1],labels=[0,0,0,0],\
                      font='rm',fontsize=12):
        """
 draw meridians (longitude lines).

 ax - current axis instance.
 meridians - list containing longitude values to draw (in degrees).
 color - color to draw meridians (default black).
 linewidth - line width for meridians (default 1.)
 linestyle - line style for meridians (default '--', i.e. dashed).
 dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
  1 pixel off).
 labels - list of 4 values (default [0,0,0,0]) that control whether
  meridians are labelled where they intersect the left, right, top or 
  bottom of the plot. For example labels=[1,0,0,1] will cause meridians
  to be labelled where they intersect the left and bottom of the plot,
  but not the right and top. Labels are located with a precision of 0.1
  degrees and are drawn using mathtext.
 font - mathtext font used for labels ('rm','tt','it' or 'cal', default 'rm'.
 fontsize - font size in points for labels (default 12).
        """
        # don't draw meridians past latmax, always draw parallel at latmax.
        latmax = 80.  # not used for cyl, merc projections.
        # offset for labels.
        yoffset = (self.urcrnry - self.llcrnry) / 100. / self.aspect
        xoffset = (self.urcrnrx - self.llcrnrx) / 100.

        if self.projection not in ['merc', 'cyl']:
            lats = N.arange(-latmax, latmax + 1).astype('f')
        else:
            lats = N.arange(-90, 91).astype('f')
        xdelta = 0.1 * (self.xmax - self.xmin)
        ydelta = 0.1 * (self.ymax - self.ymin)
        for merid in meridians:
            lons = merid * N.ones(len(lats), 'f')
            x, y = self(lons, lats)
            # remove points outside domain.
            testx = N.logical_and(x >= self.xmin - xdelta,
                                  x <= self.xmax + xdelta)
            x = N.compress(testx, x)
            y = N.compress(testx, y)
            testy = N.logical_and(y >= self.ymin - ydelta,
                                  y <= self.ymax + ydelta)
            x = N.compress(testy, x)
            y = N.compress(testy, y)
            if len(x) > 1 and len(y) > 1:
                # split into separate line segments if necessary.
                # (not necessary for mercator or cylindrical).
                xd = (x[1:] - x[0:-1])**2
                yd = (y[1:] - y[0:-1])**2
                dist = N.sqrt(xd + yd)
                split = dist > 500000.
                if N.sum(split) and self.projection not in ['merc', 'cyl']:
                    ind = (N.compress(
                        split, pylab.squeeze(split * N.indices(xd.shape))) +
                           1).tolist()
                    xl = []
                    yl = []
                    iprev = 0
                    ind.append(len(xd))
                    for i in ind:
                        xl.append(x[iprev:i])
                        yl.append(y[iprev:i])
                        iprev = i
                else:
                    xl = [x]
                    yl = [y]
                # draw each line segment.
                for x, y in zip(xl, yl):
                    # skip if only a point.
                    if len(x) > 1 and len(y) > 1:
                        l = Line2D(x,
                                   y,
                                   linewidth=linewidth,
                                   linestyle=linestyle)
                        l.set_color(color)
                        l.set_dashes(dashes)
                        ax.add_line(l)
        # draw labels for meridians.
        # search along edges of map to see if parallels intersect.
        # if so, find x,y location of intersection and draw a label there.
        if self.projection == 'cyl':
            dx = 0.01
            dy = 0.01
        elif self.projection == 'merc':
            dx = 0.01
            dy = 1000
        else:
            dx = 1000
            dy = 1000
        for dolab, side in zip(labels, ['l', 'r', 't', 'b']):
            if not dolab: continue
            # for cyl or merc, don't draw meridians on left or right.
            if self.projection in ['cyl', 'merc'] and side in ['l', 'r']:
                continue
            if side in ['l', 'r']:
                nmax = int((self.ymax - self.ymin) / dy + 1)
                if self.urcrnry < self.llcrnry:
                    yy = self.llcrnry - dy * N.arange(nmax)
                else:
                    yy = self.llcrnry + dy * N.arange(nmax)
                if side == 'l':
                    lons, lats = self(self.llcrnrx * N.ones(yy.shape, 'f'),
                                      yy,
                                      inverse=True)
                else:
                    lons, lats = self(self.urcrnrx * N.ones(yy.shape, 'f'),
                                      yy,
                                      inverse=True)
                lons = N.where(lons < 0, lons + 360, lons)
                lons = [int(lon * 10) for lon in lons.tolist()]
                lats = [int(lat * 10) for lat in lats.tolist()]
            else:
                nmax = int((self.xmax - self.xmin) / dx + 1)
                if self.urcrnrx < self.llcrnrx:
                    xx = self.llcrnrx - dx * N.arange(nmax)
                else:
                    xx = self.llcrnrx + dx * N.arange(nmax)
                if side == 'b':
                    lons, lats = self(xx,
                                      self.llcrnry * N.ones(xx.shape, 'f'),
                                      inverse=True)
                else:
                    lons, lats = self(xx,
                                      self.urcrnry * N.ones(xx.shape, 'f'),
                                      inverse=True)
                lons = N.where(lons < 0, lons + 360, lons)
                lons = [int(lon * 10) for lon in lons.tolist()]
                lats = [int(lat * 10) for lat in lats.tolist()]
            for lon in meridians:
                if lon < 0: lon = lon + 360.
                # find index of meridian (there may be two, so
                # search from left and right).
                try:
                    nl = lons.index(int(lon * 10))
                except:
                    nl = -1
                try:
                    nr = len(lons) - lons[::-1].index(int(lon * 10)) - 1
                except:
                    nr = -1
                if lon > 180:
                    lonlab = r'$\%s{%g\/^{\circ}\/W}$' % (font,
                                                          N.fabs(lon - 360))
                elif lon < 180 and lon != 0:
                    lonlab = r'$\%s{%g\/^{\circ}\/E}$' % (font, lon)
                else:
                    lonlab = r'$\%s{%g\/^{\circ}}$' % (font, lon)
                # meridians can intersect each map edge twice.
                for i, n in enumerate([nl, nr]):
                    lat = lats[n] / 10.
                    # no meridians > latmax for projections other than merc,cyl.
                    if self.projection not in ['merc', 'cyl'] and lat > latmax:
                        continue
                    # don't bother if close to the first label.
                    if i and abs(nr - nl) < 100: continue
                    if n > 0:
                        if side == 'l':
                            pylab.text(self.llcrnrx - xoffset,
                                       yy[n],
                                       lonlab,
                                       horizontalalignment='right',
                                       verticalalignment='center',
                                       fontsize=fontsize)
                        elif side == 'r':
                            pylab.text(self.urcrnrx + xoffset,
                                       yy[n],
                                       lonlab,
                                       horizontalalignment='left',
                                       verticalalignment='center',
                                       fontsize=fontsize)
                        elif side == 'b':
                            pylab.text(xx[n],
                                       self.llcrnry - yoffset,
                                       lonlab,
                                       horizontalalignment='center',
                                       verticalalignment='top',
                                       fontsize=fontsize)
                        else:
                            pylab.text(xx[n],
                                       self.urcrnry + yoffset,
                                       lonlab,
                                       horizontalalignment='center',
                                       verticalalignment='bottom',
                                       fontsize=fontsize)

        # make sure axis ticks are turned off
        ax.set_xticks([])
        ax.set_yticks([])
コード例 #39
0
def intersect_sparse(h1, h2):
    if h1.ambiant_dimension != h2.ambiant_dimension:
        raise ValueError("Different ambiant\
            spaces dimensions ({}!={})".format(len(w1), len(w2)))
#    elif pl.allclose(w1,w2) and pl.allclose(b1,b2):
#        print("return same object")
#        return copy(h1)
#    elif pl.allclose(w1,w2) and not pl.allclose(b1,b2):
#        print("return empty set")
#        return None

#Now that the trivial cases have been removed there exists an
#intersection of the two hyperplanes to obtain the new form of
#the hyperplane we perform the following 3 steps:
# (1)consider the intersection of two affine spaces as the intersection
#    of a linear space and an affine space with modified bias
# (2)express the bias of the affine space in the linear space,
#    this gives us the bias that will be for the new affine space
# (3)compute the basis of the intersection of the two linear spaces
#    this gives us the span of the linear space, jointly with the above
#    bias corresponding to the affine space from the intersection
#(1)
    bp = h2.bias - h1.bias
    #(2)
    A = sp.hstack([h1.basis, h2.basis])
    output = sparse_lsqr(A, bp)
    alpha_beta_star, istop, itn = output[:3]
    if (istop == 2):
        warnings.warn("In Intersection of {} with {},\
                least square solution is approximate".format(h1.name, h2.name))
    bpp = h2.basis.dot(alpha_beta_star[h1.dim:])
    print("New bias is {}".format(bpp))
    # (3) --------- Implement the Zassenhaus algorithm -------------
    # assumes each space basis is in the same basis
    # first need to create the original matrix
    print(h1.basis.todense(), '\n\n')
    print(h2.basis.todense(), '\n\n')
    matrix = sp.bmat([[h1.basis, h2.basis], [h1.basis, None]]).T
    # Now we need to put the top left half in row echelon form
    # loop over the columns of the left half
    for column in range(h1.ambiant_dimension - 1):
        print('start column:{}\nmatrix:\n{}\n\n'.format(
            column, matrix.todense()))
        # compute current index and value of pivot A_{column,column}
        pivot_index = pl.flatnonzero((matrix.col == column)
                                     & (matrix.row == column))
        pivot = pl.squeeze(matrix.data[pivot_index])
        # compute indices to act upon
        current_indices = pl.flatnonzero((matrix.col == column)
                                         & (matrix.row > column))
        current_data = matrix.data[current_indices]
        # check for active pivoting to switch current row
        # with the one with maximum value
        maximum_index = current_indices[current_data.argmax()]
        maximum_value = matrix.data[maximum_index]
        print('maximum value', maximum_value, 'pivot', pivot)
        if abs(maximum_value) > abs(pivot):
            print('needs preventive pivoting')
            row_w_maximum = matrix.row[maximum_index]
            matrix.row[matrix.row == row_w_maximum] = column
            matrix.row[matrix.row == column] = row_w_maximum
            pivot = pl.squeeze(maximum_value)
            print('\tstart column:{}\n\tmatrix:\n\t{}\n\n'.format(
                column, matrix.todense()))
        # create a buffer to add new values
        to_add = {'row': [], 'col': [], 'data': []}
        considered_column_indices = pl.flatnonzero((matrix.col >= column)
                                                   & (matrix.row == column))
        # Loop over the rows
        for row, value in zip(matrix.row[current_indices],
                              matrix.data[current_indices]):
            multiplicator = value / pivot
            print('Multiplicator={}'.format(multiplicator))
            # Compute which column of the current row are nonzeros
            pivot_nonzero_indices = pl.flatnonzero((matrix.col >= column)
                                                   & (matrix.row == row))
            # Find the columns that are both nonzeros at row column and row row
            both_nonzero = pl.array([
                i for i in pivot_nonzero_indices
                if i in considered_column_indices
            ])
            print(both_nonzero)
            # Find here zero but pivot row nonzero, this corresponds to the column that will
            # need to have new values in it
            hereonly_nonzero = pl.array([
                i for i in considered_column_indices
                if i not in pivot_nonzero_indices
            ])
            # Loop over the columns which are both nonzeros
            if (len(both_nonzero) > 0):
                for pos, val in zip(
                        both_nonzero,
                        pl.nditer(matrix.data[both_nonzero],
                                  op_flags=['readwrite'])):
                    val -= multiplicator * value
                    print('New Value', val)
            # Loop over column that are here zero and thus need a new placeholder
            if (len(hereonly_nonzero) > 0):
                for pos in hereonly_nonzero:
                    to_add['row'].append(row)
                    to_add['data'].append(-value)
                    to_add['col'].append(pos)
        print(matrix.todense())
        # add the newly introduces nonzero values ot the sparse matrix
        matrix.row = pl.concatenate([matrix.row, to_add['row']])
        matrix.col = pl.concatenate([matrix.col, to_add['col']])
        matrix.data = pl.concatenate([matrix.data, to_add['data']])
        print(matrix.todense())
        matrix.eliminate_zeros()
        #        # now need to remove the entries that are now 0
        #        # first from the ones explicitly reduces
        #        to_delete        = pl.flatnonzero((matrix.col==column) & (matrix.row > column))
        #        # now form the possible ones that became 0 during row operations
        #        indices          = pl.flatnonzero(matrix.row<column)
        #        data             = matrix.data[indices]
        #        extras_to_delete = pl.flatnonzero(pl.isclose(data,0))
        #        # merge both lists
        #        to_delete        = pl.concatenate([to_delete,extras_to_delete])
        #        # delete the corresponding indices alternative: matrix.eliminate_zeros()
        #        matrix.col  = pl.delete(matrix.col,to_delete, None)
        #        matrix.row  = pl.delete(matrix.row,to_delete, None)
        #        matrix.data = pl.delete(matrix.data,to_delete, None)
        #        # end of this procedure, move over to the next column
        #        # check if completed
        block_indices = pl.flatnonzero((matrix.col < h1.ambiant_dimension)
                                       & (matrix.row > column))
        if (len(current_indices) == 0): return matrix.to_dense()
コード例 #40
0
    def drawmeridians(self,ax,meridians,color='k',linewidth=1., \
                      linestyle='--',dashes=[1,1],labels=[0,0,0,0],\
                      font='rm',fontsize=12):
        """
 draw meridians (longitude lines).

 ax - current axis instance.
 meridians - list containing longitude values to draw (in degrees).
 color - color to draw meridians (default black).
 linewidth - line width for meridians (default 1.)
 linestyle - line style for meridians (default '--', i.e. dashed).
 dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
  1 pixel off).
 labels - list of 4 values (default [0,0,0,0]) that control whether
  meridians are labelled where they intersect the left, right, top or 
  bottom of the plot. For example labels=[1,0,0,1] will cause meridians
  to be labelled where they intersect the left and bottom of the plot,
  but not the right and top. Labels are located with a precision of 0.1
  degrees and are drawn using mathtext.
 font - mathtext font used for labels ('rm','tt','it' or 'cal', default 'rm'.
 fontsize - font size in points for labels (default 12).
        """
        # don't draw meridians past latmax, always draw parallel at latmax.
        latmax = 80. # not used for cyl, merc projections.
        # offset for labels.
	yoffset = (self.urcrnry-self.llcrnry)/100./self.aspect
	xoffset = (self.urcrnrx-self.llcrnrx)/100.

        if self.projection not in ['merc','cyl']:
            lats = N.arange(-latmax,latmax+1).astype('f')
        else:
            lats = N.arange(-90,91).astype('f')
        xdelta = 0.1*(self.xmax-self.xmin)
        ydelta = 0.1*(self.ymax-self.ymin)
        for merid in meridians:
            lons = merid*N.ones(len(lats),'f')
            x,y = self(lons,lats)
            # remove points outside domain.
            testx = N.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta)
            x = N.compress(testx, x)
            y = N.compress(testx, y)
            testy = N.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta)
            x = N.compress(testy, x)
            y = N.compress(testy, y)
            if len(x) > 1 and len(y) > 1:
                # split into separate line segments if necessary.
                # (not necessary for mercator or cylindrical).
                xd = (x[1:]-x[0:-1])**2
                yd = (y[1:]-y[0:-1])**2
                dist = N.sqrt(xd+yd)
                split = dist > 500000.
                if N.sum(split) and self.projection not in ['merc','cyl']:
                   ind = (N.compress(split,pylab.squeeze(split*N.indices(xd.shape)))+1).tolist()
                   xl = []
                   yl = []
                   iprev = 0
                   ind.append(len(xd))
                   for i in ind:
                       xl.append(x[iprev:i])
                       yl.append(y[iprev:i])
                       iprev = i
                else:
                    xl = [x]
                    yl = [y]
                # draw each line segment.
                for x,y in zip(xl,yl):
                    # skip if only a point.
                    if len(x) > 1 and len(y) > 1:
                        l = Line2D(x,y,linewidth=linewidth,linestyle=linestyle)
                        l.set_color(color)
                        l.set_dashes(dashes)
                        ax.add_line(l)
        # draw labels for meridians.
        # search along edges of map to see if parallels intersect.
        # if so, find x,y location of intersection and draw a label there.
        if self.projection == 'cyl':
            dx = 0.01; dy = 0.01
        elif self.projection == 'merc':
            dx = 0.01; dy = 1000
        else:
            dx = 1000; dy = 1000
        for dolab,side in zip(labels,['l','r','t','b']):
            if not dolab: continue
            # for cyl or merc, don't draw meridians on left or right.
            if self.projection in ['cyl','merc'] and side in ['l','r']: continue
            if side in ['l','r']:
	        nmax = int((self.ymax-self.ymin)/dy+1)
                if self.urcrnry < self.llcrnry:
	            yy = self.llcrnry-dy*N.arange(nmax)
                else:
	            yy = self.llcrnry+dy*N.arange(nmax)
                if side == 'l':
	            lons,lats = self(self.llcrnrx*N.ones(yy.shape,'f'),yy,inverse=True)
                else:
	            lons,lats = self(self.urcrnrx*N.ones(yy.shape,'f'),yy,inverse=True)
                lons = N.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            else:
	        nmax = int((self.xmax-self.xmin)/dx+1)
                if self.urcrnrx < self.llcrnrx:
	            xx = self.llcrnrx-dx*N.arange(nmax)
                else:
	            xx = self.llcrnrx+dx*N.arange(nmax)
                if side == 'b':
	            lons,lats = self(xx,self.llcrnry*N.ones(xx.shape,'f'),inverse=True)
                else:
	            lons,lats = self(xx,self.urcrnry*N.ones(xx.shape,'f'),inverse=True)
                lons = N.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            for lon in meridians:
                if lon<0: lon=lon+360.
                # find index of meridian (there may be two, so
                # search from left and right).
                try:
                    nl = lons.index(int(lon*10))
                except:
                    nl = -1
                try:
                    nr = len(lons)-lons[::-1].index(int(lon*10))-1
                except:
                    nr = -1
        	if lon>180:
        	    lonlab = r'$\%s{%g\/^{\circ}\/W}$'%(font,N.fabs(lon-360))
        	elif lon<180 and lon != 0:
        	    lonlab = r'$\%s{%g\/^{\circ}\/E}$'%(font,lon)
        	else:
        	    lonlab = r'$\%s{%g\/^{\circ}}$'%(font,lon)
                # meridians can intersect each map edge twice.
                for i,n in enumerate([nl,nr]):
                    lat = lats[n]/10.
                    # no meridians > latmax for projections other than merc,cyl.
                    if self.projection not in ['merc','cyl'] and lat > latmax: continue
                    # don't bother if close to the first label.
                    if i and abs(nr-nl) < 100: continue
                    if n > 0:
                        if side == 'l':
        	            pylab.text(self.llcrnrx-xoffset,yy[n],lonlab,horizontalalignment='right',verticalalignment='center',fontsize=fontsize)
                        elif side == 'r':
        	            pylab.text(self.urcrnrx+xoffset,yy[n],lonlab,horizontalalignment='left',verticalalignment='center',fontsize=fontsize)
                        elif side == 'b':
        	            pylab.text(xx[n],self.llcrnry-yoffset,lonlab,horizontalalignment='center',verticalalignment='top',fontsize=fontsize)
                        else:
        	            pylab.text(xx[n],self.urcrnry+yoffset,lonlab,horizontalalignment='center',verticalalignment='bottom',fontsize=fontsize)

        # make sure axis ticks are turned off
        ax.set_xticks([]) 
        ax.set_yticks([])
コード例 #41
0
from LoadRastRadar import *
from RadarPlotUtils import *
import MapUtils

from mpl_toolkits.basemap import Basemap

import pylab

theFile = 'TestData.nc'
rasterized = False
namestem = ""


rastData = LoadRastRadar(theFile)

print pylab.nanmin(pylab.squeeze(rastData['vals']))

mapLayers = MapUtils.mapLayers


# Map domain
map = Basemap(projection='cyl', resolution='i', suppress_ticks=False,
                                llcrnrlat = rastData['lats'].min(), llcrnrlon = rastData['lons'].min(),
                                urcrnrlat = rastData['lats'].max(), urcrnrlon = rastData['lons'].max())

fig = pylab.figure(figsize = (15.0, 6.0))

ax = fig.add_subplot(1, 2, 1)

#map.drawstates(ax=ax, linewidth=1.5, color='k')
#map.drawrivers(ax=ax, linewidth=0.5, color='b')
コード例 #42
0
ファイル: cl_map_region.py プロジェクト: platipodium/glues
                         dpi=dpi,
                         facecolor=None,
                         edgecolor=None,
                         frameon=True)
        pylab.clf()

        gdata = numpy.zeros((nlat, nlon)) + numpy.NaN
        for ir in range(nreg):
            ireg = pylab.where(region == ir)
            gdata[ireg] = data[it, ir]

        mdata = numpy.ma.masked_array(gdata, numpy.isnan(gdata))

        pc = proj.contourf(x,
                           y,
                           pylab.squeeze(mdata[:, :]),
                           extend='max',
                           levels=pylab.linspace(mindata, maxdata, 10))
        pylab.hold(True)
        cb = pylab.colorbar(mappable=pc,
                            cax=None,
                            ax=None,
                            orientation='vertical',
                            format='%.2f')

        # todo: check for existence of attribute
        if pylab.size(ncv[varname].ncattrs()) > 0:
            cb.set_label(ncv[varname].units)

        proj.drawcoastlines(linewidth=0.1)
        proj.drawmapboundary()
コード例 #43
0
ファイル: lotka_volterra.py プロジェクト: adbuerger/PECas
    yN = yN, \
    # linear_solver = "ma97", \
    wv = wv)

lsqpe.run_parameter_estimation(hessian = "gauss-newton")
# lsqpe.run_parameter_estimation(hessian = "exact-hessian")
lsqpe.show_results()

lsqpe.compute_covariance_matrix()
lsqpe.show_results()

t = pl.linspace(0,10,1000)
lsqpe.run_simulation(x0 = yN[:,0], tsim = t)

pl.figure()

pl.scatter(T, yN[0,:], color = "b", label = "$x_{1,meas}$")
pl.scatter(T, yN[1,:], color = "r", label = "$x_{2,meas}$")

pl.plot(t, pl.squeeze(lsqpe.Xsim[0,:]), color="b", label = "$x_{1,sim}$")
pl.plot(t, pl.squeeze(lsqpe.Xsim[1,:]), color="r", label = "$x_{2,sim}$")

pl.xlabel("$t$")
pl.ylabel("$x_1, x_2$", rotation = 0)
pl.xlim(0.0, 10.0)

pl.legend(loc = "upper left")
pl.grid()

pl.show()
コード例 #44
0
ファイル: silverbox_pe.py プロジェクト: adbuerger/casiopeia
    system = odesys, pdata = p_true / scale)
simulation_true_parameters.run_system_simulation( \
    x0 = [0.0, 0.0], time_points = tN, udata = udata)

ydata = simulation_true_parameters.simulation_results
ydata += 1e-3 * pl.random((x.shape[0], N+1))

wv = pl.ones(ydata.shape)

pe = cp.pe.LSq(system = odesys, \
    time_points = tN, xinit = ydata, \
    ydata = ydata, wv = wv, udata = udata, pinit = p_guess)
    
pe.run_parameter_estimation()

simulation_estimated_parameters = cp.sim.Simulation( \
    system = odesys, pdata = pe.estimated_parameters)
simulation_estimated_parameters.run_system_simulation( \
    x0 = [0.0, 0.0], time_points = tN, udata = udata)

pl.close("all")
pl.figure()

pl.scatter(tN, pl.squeeze(ydata[0,:]))
pl.plot(tN, simulation_estimated_parameters.simulation_results[0,:].T)

pl.scatter(tN, pl.squeeze(ydata[1,:]))
pl.plot(tN, simulation_estimated_parameters.simulation_results[1,:].T)

pl.show()
コード例 #45
0
    ydata = yN, wv = wv, discretization_method = "collocation")

pe.run_parameter_estimation()
pe.print_estimation_results()

pe.compute_covariance_matrix()
pe.print_estimation_results()

T_sim = pl.linspace(0, 10, 101)
x0 = yN[:,0]

sim = cp.sim.Simulation(system, pe.estimated_parameters)
sim.run_system_simulation(time_points = T_sim, x0 = x0)

pl.figure()

pl.scatter(T, yN[0,:], color = "b", label = "$x_{1,meas}$")
pl.scatter(T, yN[1,:], color = "r", label = "$x_{2,meas}$")

pl.plot(T_sim, pl.squeeze(sim.simulation_results[0,:]), color="b", label = "$x_{1,sim}$")
pl.plot(T_sim, pl.squeeze(sim.simulation_results[1,:]), color="r", label = "$x_{2,sim}$")

pl.xlabel("$t$")
pl.ylabel("$x_1, x_2$", rotation = 0)
pl.xlim(0.0, 10.0)

pl.legend(loc = "upper left")
pl.grid()

pl.show()