Add Tables to Database#
Note that this code will only run locally with admin permissions. To run the code in the SciServer use
the SciServer builtin MyDB context (see SciServer help for more details).
[1]:
%load_ext autoreload
%autoreload 2
from astropathdb import AstroDB
from astropathdb.db_io import DirectDBConnection
e:\bgreen\envs\pkg_dev_env\lib\site-packages\dask\dataframe\__init__.py:31: FutureWarning: The legacy Dask DataFrame implementation is deprecated and will be removed in a future version. Set the configuration option `dataframe.query-planning` to `True` or None to enable the new Dask Dataframe implementation and silence this warning.
warnings.warn(
[ ]:
creds = {
"username": "",
"password": "",
"IP": "bki01",
"port": 1433,
}
#
db = DirectDBConnection()
db.creds = creds
db.open_connection(database='test')
[104]:
astrodb = AstroDB(database='wsi01')
[127]:
astrodb.print_sql(
astrodb.select(astrodb.wsi01.annotations.ganno).where(
astrodb.wsi01.annotations.sampleid == '1'
)
)
SELECT annotations.ganno.STAsBinary() AS ganno
FROM annotations
WHERE annotations.sampleid = '1'
[128]:
gdf = astrodb.query(
astrodb.select(astrodb.wsi01.annotations).where(
astrodb.wsi01.annotations.sampleid == '1'
),
)
gdf.head()
[128]:
| annoid | sampleid | layer | lname | color | isvisible | ganno | ganno2 | ganno3 | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 10001 | 1 | 1 | good tissue | 0xffff00 | True | 0x0106000000020000000103000000010000006f060000... | 0x0106000000020000000103000000010000002a000000... | 0x0106000000020000000103000000010000000f000000... |
| 1 | 10002 | 1 | 2 | tumor | 0x00ff00 | True | 0x01060000000d00000001030000000100000004070000... | 0x01060000000d0000000103000000010000001f000000... | 0x01060000000d00000001030000000100000010000000... |
[129]:
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String
from geoalchemy2 import Geometry
Base = declarative_base()
class Lake(Base):
__tablename__ = 'lake'
id = Column(Integer, primary_key=True)
name = Column(String)
geom = Column(Geometry(from_text="ST_GeomFromWKB"))
Lake.__table__.create(db.dbengine)
[130]:
lake = Lake(name='sampleid1', geom=gdf['ganno'][0])
[131]:
from sqlalchemy.orm import sessionmaker
#
Session = sessionmaker(bind=db.dbengine)
session = Session()
#
session.add(lake)
session.commit()
[132]:
session.close()
[ ]:
import pandas
import geopandas
from shapely import wkt
import pandas as pd
from sqlalchemy import select
#
df = pandas.read_csv('E:/astropath/final_output_7_25_24.csv')
df['geometry'] = df['geometry'].apply(wkt.loads)
gdf = geopandas.GeoDataFrame(df).set_geometry('geometry')
[ ]:
#
# note conversion is not handled automatically b/c datatypes are not set
#
db.write_to_database(data = gdf, table_name='js_ln_annos')
js_annos = db.dbmeta.tables['js_ln_annos_2']
stmt = select(js_annos.c.ganno).where(js_annos.c.sampleid == '678')
df = pd.read_sql(stmt, db.dbengine)