Last active
August 12, 2021 05:24
-
-
Save yudhastyawan/afa0f207645167425d506ebe538a4d3e to your computer and use it in GitHub Desktop.
convert xml data to polezeros using obspy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import glob | |
import shutil | |
from obspy import read_inventory | |
xmlFiles = glob.glob("./*.xml") | |
for xmlFile in xmlFiles: | |
print(xmlFile) | |
inventory = read_inventory(xmlFile) | |
inventory.write("temp.txt", | |
format="SACPZ") | |
file = open("temp.txt", "r") | |
data = file.readlines() | |
file.close() | |
total = [i for i in range(len(data)) if (data[i] == '* **************************************************\n' and data[i - 1] == '\n')] | |
if (os.path.isdir("./pazdir") == False): | |
os.mkdir("./pazdir") | |
name = [] | |
for idx in total: | |
net = data[idx + 1].split()[-1] | |
stat = data[idx + 2].split()[-1] | |
loc = data[idx + 3].split()[-1] if data[idx + 3].split()[-1] != ":" else "" | |
chan = data[idx + 4].split()[-1] | |
name.append(f"PZ_{net}_{stat}_{loc}_{chan}") | |
for i in range(len(total)): | |
file = open(f"./pazdir/{name[i]}", "w") | |
new = "".join(data[total[i]:total[i+1]]) if i != (len(total) - 1) else "".join(data[total[i]::]) | |
file.write(new) | |
file.close() | |
os.remove("temp.txt") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
file = open("test1.txt", "r") | |
data = file.readlines() | |
file.close() | |
total = [i for i in range(len(data)) if (data[i] == '* **************************************************\n' and data[i - 1] == '\n')] | |
if (os.path.isdir("./pazdir") == False): | |
os.mkdir("./pazdir") | |
name = [] | |
for idx in total: | |
net = data[idx + 1].split()[-1] | |
stat = data[idx + 2].split()[-1] | |
loc = data[idx + 3].split()[-1] if data[idx + 3].split()[-1] != ":" else "" | |
chan = data[idx + 4].split()[-1] | |
name.append(f"PZ_{net}_{stat}_{loc}_{chan}") | |
for i in range(len(total)): | |
file = open(f"./pazdir/{name[i]}", "w") | |
new = "".join(data[total[i]:total[i+1]]) if i != (len(total) - 1) else "".join(data[total[i]::]) | |
file.write(new) | |
file.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
import getopt | |
from cmd import Cmd | |
from obspy import read_inventory | |
helpstring = """XML to Poles-Zeros Program | |
--------------------------- | |
USAGE: | |
python xml2pz.py -i <input_file> | |
OR | |
python xml2pz.py --ifile <input_file> | |
THE ALLOWED FILE EXTENSIONS: | |
*.XML OR *.xml | |
""" | |
def polezero_f(NETWORK, STATION, CHANNEL, CREATED, START, END, DESCRIPTION, LATITUDE, LONGITUDE, ELEVATION, DEPTH, | |
DIP, AZIMUTH, SAMPLE_RATE, INPUT_UNIT, INSTTYPE, INSTGAIN, COMMENT, SENSITIVITY, A0, SACPZ): | |
polezero=f"""* ********************************** | |
* NETWORK (KNETWK): {NETWORK} | |
* STATION (KSTNM): {STATION} | |
* LOCATION (KHOLE): | |
* CHANNEL (KCMPNM): {CHANNEL} | |
* CREATED : {CREATED} | |
* START : {START} | |
* END : {END} | |
* DESCRIPTION : {DESCRIPTION} | |
* LATITUDE : {LATITUDE:.6f} | |
* LONGITUDE : {LONGITUDE:.6f} | |
* ELEVATION : {ELEVATION:.1f} | |
* DEPTH : {DEPTH:.1f} | |
* DIP : {DIP:.1f} | |
* AZIMUTH : {AZIMUTH:.1f} | |
* SAMPLE RATE : {SAMPLE_RATE:.1f} | |
* INPUT UNIT : {INPUT_UNIT} | |
* OUTPUT UNIT : COUNTS | |
* INSTTYPE : {INSTTYPE} | |
* INSTGAIN : {INSTGAIN:.6e} (M/S) | |
* COMMENT : {COMMENT} | |
* SENSITIVITY : {SENSITIVITY:.6e} (M/S) | |
* A0 : {A0:.6e} | |
* ********************************** | |
{SACPZ}""" | |
return polezero | |
def polezero_f_mod(NETWORK, STATION, CHANNEL, SACPZ): | |
polezero=f"""* ********************************** | |
* NETWORK (KNETWK): {NETWORK} | |
* STATION (KSTNM): {STATION} | |
* LOCATION (KHOLE): | |
* CHANNEL (KCMPNM): {CHANNEL} | |
* ********************************** | |
{SACPZ}""" | |
return polezero | |
def convert2pz(inv): | |
currdir = os.getcwd() | |
destdir = os.path.join(currdir,'output') | |
if not os.path.isdir(destdir): | |
os.mkdir(destdir) | |
for i in range(len(inv)): | |
NETWORK = inv[i].code | |
for j in range(len(inv[i])): | |
STATION = inv[i][j].code | |
for k in range(len(inv[i][j])): | |
CHANNEL = inv[i][j][k].code | |
LOCATION_CODE = inv[i][j][k].location_code | |
SACPZ = inv[i][j][k].response.get_sacpz() | |
FILENAME = f'SAC_PZs_{NETWORK}_{STATION}_{LOCATION_CODE}_{CHANNEL}' | |
CONTENT = polezero_f_mod(NETWORK,STATION,CHANNEL,SACPZ) | |
file = open(os.path.join(destdir,FILENAME),'w') | |
file.write(CONTENT) | |
file.close() | |
print(f'{FILENAME} has been created!') | |
class xml2pz(Cmd): | |
prompt = 'xml2pz> ' | |
intro = """XML to Poles-Zeros Program\n---------------------------\n""" | |
inputfile = None | |
inv = None | |
def __init__(self, arg=None): | |
super(xml2pz, self).__init__() | |
if arg != None: | |
if arg.split('.')[-1] in ('xml', 'XML'): | |
self.inputfile = arg | |
self.intro += f"file = {self.inputfile}" | |
self.inv = read_inventory(self.inputfile) | |
else: | |
print("""THE ALLOWED FILE EXTENSIONS:\n\t*.XML OR *.xml""") | |
sys.exit(2) | |
def do_exit(self, arg): | |
return True | |
def do_quit(self, arg): | |
return True | |
def do_read(self, arg): | |
arg = arg.split()[0] | |
if arg.split('.')[-1] in ('xml', 'XML'): | |
if os.path.isfile(arg): | |
self.inputfile = arg | |
self.intro += f"file = {self.inputfile}" | |
self.inv = read_inventory(self.inputfile) | |
else: | |
print("""File Is Not Found.""") | |
else: | |
print("""THE ALLOWED FILE EXTENSIONS:\n\t*.XML OR *.xml""") | |
def do_print(self, arg): | |
if self.inputfile != None: | |
print(self.inv) | |
else: | |
print("You Do Not Input The File!\nUse 'read <input_file>' First To Do This") | |
def do_convert(self, arg): | |
if self.inputfile != None: | |
convert2pz(self.inv) | |
else: | |
print("You Do Not Input The File!\nUse 'read <input_file>' First To Do This") | |
def main(argv): | |
inputfile = None | |
try: | |
opts, args = getopt.getopt(argv, "hi:co",["ifile="]) | |
except getopt.GetoptError: | |
print("""python xml2pz.py -i <input_file>""") | |
sys.exit(2) | |
if not opts: | |
xml2pz().cmdloop() | |
else: | |
for opt, arg in opts: | |
if opt == '-h': | |
print(helpstring) | |
sys.exit() | |
elif opt in ("-i", "--ifile"): | |
if arg.split('.')[-1] in ('xml', 'XML'): | |
inputfile = arg | |
else: | |
print("""THE ALLOWED FILE EXTENSIONS:\n\t*.XML OR *.xml""") | |
sys.exit(2) | |
elif opt == "-c": | |
if inputfile != None: | |
xml2pz(inputfile).cmdloop() | |
sys.exit() | |
elif opt == "-o": | |
# THE MAIN SCRIPT | |
inv = read_inventory(inputfile) | |
convert2pz(inv) | |
sys.exit() | |
if inputfile != None: | |
# THE MAIN SCRIPT | |
inv = read_inventory(inputfile) | |
print(inv) | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
An alternative way to create SACPZ files
how to create a file for the whole data in Station XML and convert to SACPZ files:
change filename.xml
into your filename, change filename.txt
into your output filename and then run this program:
from obspy import read_inventory
inventory = read_inventory("filename.xml")
inventory.write("filename.txt",
format="SACPZ")
after this, use splitxml.py
(after changing test1.txt
into your output filename previously) to split a file into separate files.
If having multiple XML files, we can use multiplexml2sacpz.py
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage in Terminal:
python xml2pz.py -i FILENAME.xml -o
Requirement:
pip install obspy