| 1 |
import sqlite3 |
| 2 |
import xml.etree.ElementTree as et |
| 3 |
from pymzml import spec |
| 4 |
from pymzml.run import Reader |
| 5 |
|
| 6 |
|
| 7 |
def create_database_from_file(db_name, file_path): |
| 8 |
conn = sqlite3.connect(db_name + ".db") |
| 9 |
Run = Reader("./tests/data/example.mzML") |
| 10 |
with conn: |
| 11 |
cursor = conn.cursor() |
| 12 |
cursor.execute("CREATE TABLE Spectra(ID INT, xml TEXT)") |
| 13 |
for spectrum in Run: |
| 14 |
params = (spectrum.ID, spectrum.to_string()) |
| 15 |
cursor.execute("INSERT INTO Spectra VALUES(?, ?)", params) |
| 16 |
return True |
| 17 |
|
| 18 |
|
| 19 |
class SQLiteDatabase(object): |
| 20 |
""" |
| 21 |
Example implementation of a database Connector, |
| 22 |
which can be used to make :py:func:`pymzml.run.Reader` accept paths to |
| 23 |
sqlite db files. |
| 24 |
|
| 25 |
We initialize with a path to a database and implement |
| 26 |
a custom __getitem__ function to retrieve the spectra |
| 27 |
""" |
| 28 |
|
| 29 |
def __init__(self, path): |
| 30 |
""" """ |
| 31 |
connection = sqlite3.connect(path) |
| 32 |
self.cursor = connection.cursor() |
| 33 |
|
| 34 |
def __getitem__(self, key): |
| 35 |
""" |
| 36 |
Execute a SQL request, process the data and return a spectrum object. |
| 37 |
|
| 38 |
Args: |
| 39 |
key (str or int): unique identifier for the given spectrum in the |
| 40 |
database |
| 41 |
""" |
| 42 |
self.cursor.execute("SELECT * FROM spectra WHERE id=?", key) |
| 43 |
ID, element = self.cursor.fetchone() |
| 44 |
|
| 45 |
element = et.XML(element) |
| 46 |
if "spectrum" in element.tag: |
| 47 |
spectrum = spec.Spectrum(element) |
| 48 |
elif "chromatogram" in element.tag: |
| 49 |
spectrum = spec.Chromatogram(element) |
| 50 |
return spectrum |
| 51 |
|
| 52 |
def get_spectrum_count(self): |
| 53 |
self.cursor.execute("SELECT COUNT(*) from spectra") |
| 54 |
num = self.cursor.fetchone()[0] |
| 55 |
return num |
| 56 |
|
| 57 |
def read(self, size=-1): |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
return '<spectrum index="0" id="controllerType=0 controllerNumber=1 scan=1" defaultArrayLength="917"></spectrum>\n' |
| 62 |
|
| 63 |
|
| 64 |
if __name__ == "__main__": |
| 65 |
|
| 66 |
my_iter = iter(et.iterparse(SQLiteDatabase("test.db"))) |
| 67 |
|
| 68 |
for x in my_iter: |
| 69 |
print(x) |
| 70 |
|
| 71 |
|
| 72 |
db = SQLiteDatabase("test.db") |
| 73 |
unique_id = 5 |
| 74 |
my_spec = db[unique_id] |