当前位置: 首页>>代码示例>>Python>>正文


Python Stream.trim方法代码示例

本文整理汇总了Python中obspy.core.stream.Stream.trim方法的典型用法代码示例。如果您正苦于以下问题:Python Stream.trim方法的具体用法?Python Stream.trim怎么用?Python Stream.trim使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在obspy.core.stream.Stream的用法示例。


在下文中一共展示了Stream.trim方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getCatData

# 需要导入模块: from obspy.core.stream import Stream [as 别名]
# 或者: from obspy.core.stream.Stream import trim [as 别名]
def getCatData(date, opt):

    """
    Download data from IRIS or Earthworm waveserver with padding and filter it. This is
    a specialized version getData() for catalog events, pulling a smaller amount of time
    around a known event.

    date: UTCDateTime of known catalog event
    opt: Options object describing station/run parameters
    
    Returns ObsPy stream objects, one for cutting and the other for triggering
    """    
    
    nets = opt.network.split(',')
    stas = opt.station.split(',')
    locs = opt.location.split(',')
    chas = opt.channel.split(',')
    
    if opt.server == "IRIS":
        client = Client("IRIS")
    else:
        client = EWClient(opt.server, opt.port)
        
    st = Stream()
    for n in range(len(stas)):
        try:
            stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                    date - opt.atrig, date + 3*opt.atrig)
            stmp = stmp.filter("bandpass", freqmin=opt.fmin, freqmax=opt.fmax,
                corners=2, zerophase=True)
            stmp = stmp.merge(method=1, fill_value='interpolate')
        except (obspy.fdsn.header.FDSNException):
            try: # try again
                stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                        date - opt.atrig, date + 3*opt.atrig)
                stmp = stmp.filter("bandpass", freqmin=opt.fmin, freqmax=opt.fmax,
                    corners=2, zerophase=True)
                stmp = stmp.merge(method=1, fill_value='interpolate')
            except (obspy.fdsn.header.FDSNException):
                print('No data found for {0}.{1}'.format(stas[n],nets[n]))
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                stmp = Stream().extend([trtmp.copy()])
        # Resample to ensure all traces are same length
        if stmp[0].stats.sampling_rate != opt.samprate:
            stmp = stmp.resample(opt.samprate)
        st.extend(stmp.copy()) 
    
    st = st.trim(starttime=date-opt.atrig, endtime=date+3*opt.atrig, pad=True,
        fill_value=0)
    stC = st.copy() 

    return st, stC
开发者ID:iceseismic,项目名称:REDPy,代码行数:56,代码来源:trigger.py

示例2: get_preview

# 需要导入模块: from obspy.core.stream import Stream [as 别名]
# 或者: from obspy.core.stream.Stream import trim [as 别名]
 def get_preview(self, trace_ids=[], starttime=None, endtime=None,
                 network=None, station=None, location=None, channel=None,
                 pad=False):
     """
     Returns the preview trace.
     """
     # build up query
     session = self.session()
     query = session.query(WaveformChannel)
     # start and end time
     try:
         starttime = UTCDateTime(starttime)
     except:
         starttime = UTCDateTime() - 60 * 20
     finally:
         query = query.filter(WaveformChannel.endtime > starttime.datetime)
     try:
         endtime = UTCDateTime(endtime)
     except:
         # 10 minutes
         endtime = UTCDateTime()
     finally:
         query = query.filter(WaveformChannel.starttime < endtime.datetime)
     # process arguments
     if trace_ids:
         # filter over trace id list
         trace_filter = or_()
         for trace_id in trace_ids:
             temp = trace_id.split('.')
             if len(temp) != 4:
                 continue
             trace_filter.append(and_(
                 WaveformChannel.network == temp[0],
                 WaveformChannel.station == temp[1],
                 WaveformChannel.location == temp[2],
                 WaveformChannel.channel == temp[3]))
         if trace_filter.clauses:
             query = query.filter(trace_filter)
     else:
         # filter over network/station/location/channel id
         kwargs = {'network': network, 'station': station,
                   'location': location, 'channel': channel}
         for key, value in kwargs.items():
             if value is None:
                 continue
             col = getattr(WaveformChannel, key)
             if '*' in value or '?' in value:
                 value = value.replace('?', '_')
                 value = value.replace('*', '%')
                 query = query.filter(col.like(value))
             else:
                 query = query.filter(col == value)
     # execute query
     results = query.all()
     session.close()
     # create Stream
     st = Stream()
     for result in results:
         preview = result.get_preview()
         st.append(preview)
     # merge and trim
     st = merge_previews(st)
     st.trim(starttime, endtime, pad=pad)
     return st
开发者ID:3rdcycle,项目名称:obspy,代码行数:66,代码来源:client.py

示例3: max

# 需要导入模块: from obspy.core.stream import Stream [as 别名]
# 或者: from obspy.core.stream.Stream import trim [as 别名]
AC.detrend(type='linear')
AC.taper(max_percentage=0.05)


paz_sts2 = {'poles': [(-0.0367429 + 0.036754j), (-0.0367429 - 0.036754j)],
            'sensitivity': 0.944019640,
            'zeros': [0j],
            'gain': 1.0}

AC.simulate(paz_remove=paz_sts2, remove_sensitivity=True)

startaim = max([tr.stats.starttime for tr in (AC + RLAS)])
endtaim = min([tr.stats.endtime for tr in (AC + RLAS)])

AC.trim(startaim, endtaim, nearest_sample=True)
RLAS.trim(startaim, endtaim, nearest_sample=True)


# **Resample, Filter and Rotate**

# In[4]:



RLAS.decimate(factor=4)
AC.decimate(factor=4)
f_cutoff = 1.0

RLAS.filter('lowpass', freq=f_cutoff, corners=2, zerophase=True)
AC.filter('lowpass', freq=f_cutoff, corners=2, zerophase=True)
开发者ID:salve-,项目名称:RLdatabase,代码行数:32,代码来源:Rotational_Seismology_BAZ.py

示例4: GetIIData

# 需要导入模块: from obspy.core.stream import Stream [as 别名]
# 或者: from obspy.core.stream.Stream import trim [as 别名]

#.........这里部分代码省略.........
						self.CHANWILD = True	
                				DupChannels.append(self.tr.stats.channel)
		    			elif self.channel != '*':
						self.CHANWILD = False 
		#except TimeoutError:
			#print 'Get waveform timeout, exiting...'
			#sys.exit(0)	
		except:
			print 'Trouble getting data'
			sys.exit(0)
		
		# Takes duplicate stations out of list and 
		# makes station, location, and channel into an array 
		# for looping( probably easier way but it works)
		self.stations = list(set(DupStations))
		if self.station != '*':
			self.stations.append(self.station)
		self.locations = list(set(DupLocations))
		if self.location != '*':
			self.locations.append(self.location)
		self.channels = list(set(DupChannels))
		if self.channel != '*':	
			self.channels.append(self.channel)
		print
		print "Station(s) being pulled: " + str(self.stations)
		print "Location(s) being pulled: " + str(self.locations)
		print "Channel(s) being pulled: " + str(self.channels)
			
		# Now call code to store streams in mseed files
		self.storeMSEED()
	
	def storeMSEED(self):
		#Main program
		#code for storing MSEED files
		codepath = '/home/mkline/dev/getIIdataBackup/TEST_ARCHIVE/'
		self.stFinal = Stream()
		for self.channel in self.channels:
			self.trace2 = self.st.select(channel = self.channel)
			for self.location in self.locations:
				self.trace1 = self.trace2.select(location = self.location)
				for self.station in self.stations:
					print
					print "For station, location, and channel: " \
						+ self.station +" "+ self.location +" "+ self.channel
					trace = self.trace1.select(station = self.station)
					trace.merge()
					trace.sort()
					trace.count()
					for dayIndex in range(0,self.days):
						print "Day properties: "
						#startTime works better than trace[0].stats.starttime
						trimStart = self.startTime + (dayIndex)*24*60*60
						trimEnd = self.startTime + (dayIndex+1)*24*60*60
						print "Start of day: " + str(trimStart)
						print "End of day:   " + str(trimEnd)
						#Converting date into julian day to store in directory
						timesplit = re.split('T', str(trimStart))
						s = timesplit[0]
						fmt = '%Y-%m-%d'
						dt = datetime.datetime.strptime(s, fmt)
						tt = dt.timetuple()
						NewStartDay = str(tt.tm_yday).zfill(3)
						self.stFinal = trace.copy()
						self.stFinal.trim(starttime = trimStart, endtime = trimEnd)
						# This if statement is used to make sure traces with no 
						# data dont get added to the directory structure
						if not self.stFinal or str(self.stFinal[0].max()) == '--':
							print "No trace for given day"
						else:
							#Added the directory structures in here since you won't want to
							#add directory structures that you don't use
							self.stFinal = self.stFinal.split()
							if not os.path.exists(codepath + self.network + '_' + self.station  + '/'):
								os.mkdir(codepath + self.network + '_' + self.station  + '/')
							if not os.path.exists(codepath + self.network + '_' + self.station  + '/' \
								+ self.year + '/'):
								os.mkdir(codepath + self.network + '_' + self.station  + '/' \
								+ self.year + '/')
							stpath = codepath + self.network + '_' + self.station  + '/' + self.year + \
								'/' + self.year + '_' + NewStartDay + '/'
							if not os.path.exists(stpath):
								os.mkdir(stpath)
							# Here we write the data using STEIM 2 and 512 record lengths
							self.stFinal.write(stpath + self.stFinal[0].stats.location + '_' + \
								self.stFinal[0].stats.channel + '.512.seed', format='MSEED', \
								reclen = 512, encoding='STEIM2')
							print self.stFinal
						
							

	# convert optional boolean strings to boolean vars
	def toBool(self, value):
		"""
		Converts 'string' to boolean. Raises exception for invalid formats
			True values: 1, True, true, "1", "True", "true", "yes", "y", "t"
			False values: 0, False, false, "0", "False", "false", "no", "n", "f" 
		"""
		if str(value).lower() in ("true", "yes", "t", "y", "1"): return True
		if str(value).lower() in ("false", "no", "f", "n", "0"): return False
		raise Exception('Invalid value for boolean conversion: ' + str(value))
开发者ID:aringler-usgs,项目名称:getIIdata,代码行数:104,代码来源:getIIdata.py

示例5: getData

# 需要导入模块: from obspy.core.stream import Stream [as 别名]
# 或者: from obspy.core.stream.Stream import trim [as 别名]

#.........这里部分代码省略.........
                if (ststart<=tstart and tstart<=stend) or (ststart<=tend and
                    tend<=stend) or (tstart<=stend and ststart<=tend):
                    flist_sub.append(f)
        
        # Fully load data from file
        stmp = Stream()
        for f in flist_sub:
            tmp = obspy.read(f, starttime=tstart, endtime=tend+opt.maxdt)
            if len(tmp) > 0:
                stmp = stmp.extend(tmp)
    
        # Filter and merge
        stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax, corners=2,
            zerophase=True)
        stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
        for m in range(len(stmp)):
            if stmp[m].stats.sampling_rate != opt.samprate:
                stmp[m] = stmp[m].resample(opt.samprate)
        stmp = stmp.merge(method=1, fill_value=0)
        
        # Only grab stations/channels that we want and in order
        netlist = []
        stalist = []
        chalist = []
        loclist = []
        for s in stmp:
            stalist.append(s.stats.station)
            chalist.append(s.stats.channel)
            netlist.append(s.stats.network)
            loclist.append(s.stats.location)
            
        # Find match of SCNL in header or fill empty
        for n in range(len(stas)):
            for m in range(len(stalist)):
                if (stas[n] in stalist[m] and chas[n] in chalist[m] and nets[n] in
                    netlist[m] and locs[n] in loclist[m]):
                    st = st.append(stmp[m])
            if len(st) == n:
                print("Couldn't find "+stas[n]+'.'+chas[n]+'.'+nets[n]+'.'+locs[n])
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                st = st.append(trtmp.copy())
    
    else:   
     
        if '.' not in opt.server:
            client = Client(opt.server)
        else:
            client = EWClient(opt.server, opt.port)
        
        for n in range(len(stas)):
            try:
                stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                        tstart, tend+opt.maxdt)
                stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax,
                    corners=2, zerophase=True)
                stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
                for m in range(len(stmp)):
                    if stmp[m].stats.sampling_rate != opt.samprate:
                        stmp[m] = stmp[m].resample(opt.samprate)
                stmp = stmp.merge(method=1, fill_value=0)
            except (obspy.clients.fdsn.header.FDSNException):
                try: # try again
                    stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                            tstart, tend+opt.maxdt)
                    stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax,
                        corners=2, zerophase=True)
                    stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
                    for m in range(len(stmp)):
                        if stmp[m].stats.sampling_rate != opt.samprate:
                            stmp[m] = stmp[m].resample(opt.samprate)
                    stmp = stmp.merge(method=1, fill_value=0)
                except (obspy.clients.fdsn.header.FDSNException):
                    print('No data found for {0}.{1}'.format(stas[n],nets[n]))
                    trtmp = Trace()
                    trtmp.stats.sampling_rate = opt.samprate
                    trtmp.stats.station = stas[n]
                    stmp = Stream().extend([trtmp.copy()])
                                            
            # Last check for length; catches problem with empty waveserver
            if len(stmp) != 1:
                print('No data found for {0}.{1}'.format(stas[n],nets[n]))
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                stmp = Stream().extend([trtmp.copy()])
                
            st.extend(stmp.copy()) 
    
    # Edit 'start' time if using offset option
    if opt.maxdt:
        dts = np.fromstring(opt.offset, sep=',')
        for n, tr in enumerate(st):
            tr.stats.starttime = tr.stats.starttime-dts[n]
    
    st = st.trim(starttime=tstart, endtime=tend, pad=True, fill_value=0)
    stC = st.copy()
    
    return st, stC
开发者ID:ahotovec,项目名称:REDPy,代码行数:104,代码来源:trigger.py

示例6: _read

# 需要导入模块: from obspy.core.stream import Stream [as 别名]
# 或者: from obspy.core.stream.Stream import trim [as 别名]
        fname = os.path.join(rec['path'], rec['file'])
        for tr in _read(fname, fformat, headonly=False, **kwargs).traces:
            if (networks_ok) and (tr.stats.network not in networks):
                continue
            if (stations_ok) and (tr.stats.station not in stations):
                continue
            if (locations_ok) and (tr.stats.location not in locations):
                continue
            if (channels_ok) and (tr.stats.channel not in channels):
                continue
            st.append(tr)

    if st.count() > 0:
        # If the starttime is given then it trims the resulting traces
        if starttime:
            st.trim(starttime=starttime, endtime=endtime,
                    nearest_sample=nearest_sample)

        st.merge(method=1, fill_value=0, interpolation_samples=1)
    else:
        print "Empty stream"

    n_trace = st.count()
    return st, n_trace


if BC_UI:
    class _stream_dbread_view(HasTraits):
    
        time_interval = Float(30.0)
        networks = List(Str, value=['PF', 'YA'])
        stations = List(Str, value=['FOR', 'UV05'])
开发者ID:ftilmann,项目名称:miic,代码行数:34,代码来源:db.py

示例7: GetIIData

# 需要导入模块: from obspy.core.stream import Stream [as 别名]
# 或者: from obspy.core.stream.Stream import trim [as 别名]

#.........这里部分代码省略.........
			print 'Trouble getting data'
			sys.exit(0)
		#takes duplicate stations out of list
		self.stations = list(set(DupStations))
		self.locations = list(set(DupLocations))
		self.channels = list(set(DupChannels))
		print self.stations
		print self.locations
		print self.channels
		# Now call code to store streams in mseed files
		self.storeMSEED()
	
	#LAST THING TO DO!!!!
	def storeMSEED(self):
		#code for storing MSEED files
		#Need to check if the directories exist and if not make them
		#Main program
		codepath = '/home/mkline/dev/getIIdata/TEST_ARCHIVE/'
		self.days = int(round((self.st[-1].stats.endtime \
			- self.st[0].stats.starttime)/(24*60*60)))
		self.stFinal = Stream()

		if self.STAWILD:
			for self.station in self.stations:
				print
				print "For station: " + self.station
				trace = self.st.select(station = self.station)
				trace.merge()
				trace.sort()
				trace.count()
				for dayIndex in range(0,self.days):
					print "Day properties: "
					#startTime works better than trace[0].stats.starttime
					trimStart = self.startTime + (dayIndex)*24*60*60
					trimEnd = self.startTime + (dayIndex+1)*24*60*60
					print "Start of day: " + str(trimStart)
					print "End of day:   " + str(trimEnd)
					#Converting date into julian day
					timesplit = re.split('T', str(trimStart))
					s = timesplit[0]
					fmt = '%Y-%m-%d'
					dt = datetime.datetime.strptime(s, fmt)
					tt = dt.timetuple()
					if tt.tm_yday < 10:
						NewStartDay = '00' + str(tt.tm_yday)
					elif tt.tm_yday < 100:
						NewStartDay = '0' + str(tt.tm_yday)
					else:
						NewStartDay = str(tt.tm_yday)
					self.stFinal = trace.copy()
					self.stFinal.trim(starttime = trimStart, endtime = trimEnd)	
					self.stFinal = self.stFinal.split()
					if not self.stFinal:
						print "No trace for given day"
					else:
						#Added the directory structures in here since you won't want to
						#add directory structures that you don't use
						if not os.path.exists(codepath + self.network + '_' + self.station  + '/'):
							os.mkdir(codepath + self.network + '_' + self.station  + '/')
						if not os.path.exists(codepath + self.network + '_' + self.station  + '/' \
							+ self.year + '/'):
							os.mkdir(codepath + self.network + '_' + self.station  + '/' \
							+ self.year + '/')
						stpath = codepath + self.network + '_' + self.station  + '/' + self.year + \
							'/' + self.year + '_' + NewStartDay + '/'
						if not os.path.exists(stpath):
开发者ID:mkline-usgs,项目名称:getIIdata,代码行数:70,代码来源:getIIdata.py


注:本文中的obspy.core.stream.Stream.trim方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。