Connecting to AstroPath#

In this tutorial, we show how to:
  • Connect to the AstroPath database with AstroDB

  • Distinguish between raw SQL and sqlalchemy

  • Switch database contexts

  • Use built-in properties of AstroDB to quickly access key data structures

Getting Started#

To get started, the AstroDB class builds a connection to the AstroPath databases and allows queries to be run against it. This provides a basic access point for the AstroPath data and most downstream functions accept the AstroDB as an input variable.

However, much of the functionality has also been (or is in the process of being) generalized for use with data imported into the SpatialData framework using sidus. This allows much of the functionality for advanced spatial metrics or plotting functions to be applicable to local datasets. This section details the AstroDB and could be skipped for implementation with local datasets.

Below AstroDB is imported from astropathdb and an instance of AstroDB is stored as a variable db.

[1]:
from astropathdb import AstroDB
db = AstroDB(database = 'apmifwsi001_DR2')

Note

If using the package locally to access AstroPath datasets, you’ll need to input valid SciServer credentials when building AstroDB. See either AstroDB or Logging into SciServer Locally for more details on how to input your credentials. When using SciServer Compute you don’t need to worry about credentials.

Note

When running this command, the database input variable is used to specify the unique database context to connect to (above the default 'apmifwsi001_DR2' context is specified). Each public data release is given it’s own database context with the format <dataset>_<release>, where <dataset> identifies the dataset and <release> the data release (e.g. ‘apmifwsi001_DR2’, ‘apmifwsi002_DR3’). The names are accepted in any letter case. The wsiXX databases used within the AstroPath team are also accepted.

See also

AstroDB or Logging into SciServer Locally:
  • For details on how to input SciServer credentials

Introduction and AstroPath Database Schema:
  • More information about contexts

AstroDB Overview#

As noted above, the AstroDB provides the basic connection to the database and is provided as input for the downstream functionality. Moreover, AstroDB allows queries to be run directly on the database, either using raw SQL or using an ORM (Object-Relational Mapping) built using sqlalchemy. In the subsequent subsections, querying using both methods is briefly described along with a note about the advantages of both. In the example sections Query the database with raw SQL and Query the database with SQLAlchemy more advanced tutorials are provided using both methods.

Finally, the AstroDB has a few helper methods and properties for directly accessing metadata information and tables that are defined in the AstroPath databases. These properties are described at the end of this tutorial after the discussion about querying the databases directly.

Writing Your First Query#

Wait… I still have to write SQL? Yes. Well, sort of. astropathdb provides generic wrappers for many common use cases. This enables initial analysis without having to write any explicit SQL. As analyses become more complex, writing SQL will allow users to take full advantage of the computational power provided by the SciServer and SQL spatial indexing.

When working with the AstroPath databases for data analysis, there are two primary options: (1) writing raw SQL or (2) using an ORM built with sqlalchemy.

In databases, ORMs provide an abstraction between the code and database, eliminating repetive code, may improve productivity, and increases maintainability of code. For long term development, using the ORM has clear benefits, thus most of our internal operations use the ORM. However, an ORM is often more complex and less flexible than using raw SQL (especially for early users). Moreover, learning how to use an ORM takes time with a steep learning curve. Thus an infrequent or new user to the platform will likely find using raw SQL much easier. Below a brief introduction of both methods is shown below.

Note

The AstroPath databases all use Microsoft SQL Server which uses t-SQL.

See also

CasJobs Guide :
  • A great resource for some introductory examples of raw SQL commands and describes some of the nuances of working with datasets in the SciServer.

Query the database with raw SQL:
  • An advanced example of querying with raw SQL

Query the database with SQLAlchemy:

Writing Queries with Raw SQL#

Once an AstroDB object is created we can write raw SQL as a string and pass that to the AstroDB.query() method.

An example of this is below where we select the top 2 rows from the Celltag Table. This table contains all of the cell data for a given database context.

[2]:
db.query('Select top 2 * from dbo.celltag')
[2]:
cellid sampleid hpfid px py ptype CMembrane520 CMembrane540 CNucleus570 CEntireCell620 CMembrane650 CEntireCell690 exprPhenotype tdist rdist pos PDL1 PD1
0 58003601017 58 580036 30313.422988 16329.348249 3 0.120592 0.026700 0.147701 16.91381 0.998320 0.253586 0 -428.6702 32768 POINT (30313.422988093123 16329.348248621156) False False
1 58003601018 58 580036 30932.422988 16329.348249 3 0.586328 0.010012 0.166671 24.58012 1.049985 0.267110 0 -104.0547 32768 POINT (30932.422988093123 16329.348248621156) False False

Any time we run a query against the database we always store the query into a property of the AstroDB instance, called AstroDB.sql. We print that property below as an example. This can be very helpful for troubleshooting query results.

[3]:
db.sql
[3]:
'Select top 2 * from dbo.celltag'

Writing Queries with sqlalchemy Constructs#

On initialization the AstroDB will build a sqlalchemy ORM for the database input. The ORM is stored in an attribute of the AstroDB of the same name as the database input. We can then write sqlalchemy constructs from the base class directly, as shown below.

[4]:
sql = db.select(db.apmifwsi001_DR2.celltag).limit(2)
db.print_sql(sql) # we can also print out the construct itself db.print_sa_construct(sql)
SELECT TOP 2 celltag.cellid, celltag.sampleid, celltag.hpfid, celltag.px, celltag.py, celltag.ptype, celltag.cmembrane520, celltag.cmembrane540, celltag.cnucleus570, celltag.centirecell620, celltag.cmembrane650, celltag.centirecell690, celltag.exprphenotype, celltag.tdist, celltag.rdist, celltag.pos.STAsBinary() AS pos, celltag.pdl1, celltag.pd1
FROM celltag
[5]:
db.query(sql)
[5]:
cellid sampleid hpfid px py ptype cmembrane520 cmembrane540 cnucleus570 centirecell620 cmembrane650 centirecell690 exprphenotype tdist rdist pos pdl1 pd1
0 58003601017 58 580036 30313.422988 16329.348249 3 0.120592 0.026700 0.147701 16.91381 0.998320 0.253586 0 -428.6702 32768 0x0101000000a4a63c125b9add405f2b6993ace4cf40 False False
1 58003601018 58 580036 30932.422988 16329.348249 3 0.586328 0.010012 0.166671 24.58012 1.049985 0.267110 0 -104.0547 32768 0x0101000000a4a63c121b35de405f2b6993ace4cf40 False False

Note that this can also be done in one step and that the query output is exactly the same as if we passed raw SQL.

[6]:
db.query(db.select(db.apmifwsi001_DR2.celltag).limit(2))
[6]:
cellid sampleid hpfid px py ptype cmembrane520 cmembrane540 cnucleus570 centirecell620 cmembrane650 centirecell690 exprphenotype tdist rdist pos pdl1 pd1
0 58003601017 58 580036 30313.422988 16329.348249 3 0.120592 0.026700 0.147701 16.91381 0.998320 0.253586 0 -428.6702 32768 0x0101000000a4a63c125b9add405f2b6993ace4cf40 False False
1 58003601018 58 580036 30932.422988 16329.348249 3 0.586328 0.010012 0.166671 24.58012 1.049985 0.267110 0 -104.0547 32768 0x0101000000a4a63c121b35de405f2b6993ace4cf40 False False

One of the benefits here, is that we remove all the text from our code. This often reduces errors on our queries. As previously noted we’ve also added some unique filters that we can use for a given query. For example below we can filter our table by sampleid and ptype.

[7]:
db.query(db.select(db.apmifwsi001_DR2.celltag).sampleid_filter(19).ptype_filter(2).limit(2))
[7]:
cellid sampleid hpfid px py ptype cmembrane520 cmembrane540 cnucleus570 centirecell620 cmembrane650 centirecell690 exprphenotype tdist rdist pos pdl1 pd1
0 19060100257 19 190601 32125.16445 17048.462357 2 1.297197 1.088610 51.92764 9.126939 15.77287 0.010750 64 14.23974 32768 0x01010000003cab58864a5fdf409ae241971da6d040 False True
1 19060100258 19 190601 32349.16445 17086.462357 2 3.327510 1.198786 47.10973 2.022695 44.91587 0.640953 64 237.84630 32768 0x01010000003cab58864a97df409ae241979dafd040 False True
[8]:
db.query(db.select(db.apmifwsi001_DR2.celltag).sampleid_filter([19,2]).ptype_filter([0,1,2], include = False).limit(2))
[8]:
cellid sampleid hpfid px py ptype cmembrane520 cmembrane540 cnucleus570 centirecell620 cmembrane650 centirecell690 exprphenotype tdist rdist pos pdl1 pd1
0 19060100027 19 190601 32877.16445 17723.462357 5 1.785308 21.78371 23.32109 2.988694 32.97202 0.295618 64 178.14160 32768 0x01010000009e552c43a50de0409ae24197dd4ed140 False True
1 19060100044 19 190601 32585.16445 17217.462357 5 4.403443 18.21284 54.84829 4.768392 41.37410 0.028218 64 25.65819 32768 0x01010000003cab58864ad2df409ae241975dd0d040 False True

Changing Databases#

As you’ve probably noticed. We referenced the celltag table above as a property of db.apmifwsi001_DR2. This is because when we created that AstroDB object (db), a mapping to the database was created dynamically based on the tables that currently exist in that database. In databasing terms this is called the databas context. Below a new AstroDB object is created and assigned to db2 using apmifwsi002_DR3 as the context in this case (referred to in astropathdb as the database).

[9]:
db2 = AstroDB(database = 'apmifwsi002_DR3')

With this object we can now query the apmifwsi002_DR3 database, but we can no longer reference the apmifwsi001_DR2 database with our sqlalchemy constructs.

[10]:
db2.query(db2.select(db2.apmifwsi002_DR3.celltag).ptype_filter(2).limit(2))
# db2.query(db2.select(db2.apmifwsi001_DR2.celltag).sampleid_filter(19).ptype_filter(2).limit(2))
# this one won't work!!!! we can't reference apmifwsi001_DR2 anymore!!!
[10]:
cellid sampleid hpfid px py ptype cmembrane520 cmembrane540 cnucleus570 ccytomembrane620 cmembrane650 cmembrane690 exprphenotype tdist rdist pos pdl1 pd1
0 545129300043 545 5451293 17083.931205 32500.792955 2 1.210994 0.27196 59.32221 3.037047 1.086947 5.835883 0 48.60199 32768 0x010100000080ffdd98fbaed040cd78c6bf32bddf40 False False
1 545129300044 545 5451293 17016.931205 32558.792955 2 2.160510 0.27196 20.01933 2.430948 1.809567 0.463564 0 13.79003 32768 0x010100000080ffdd983b9ed040cd78c6bfb2cbdf40 False False

Referencing between databases is a big next step. We can add a session for another database, either by using the command below or by changing the database property of the object (the old database mapping will still exist).

[11]:
db2.load_db_session('apmifwsi001_DR2')
db2.query(
    db2.select(db2.apmifwsi001_DR2.celltag).sampleid_filter(19).ptype_filter(2).limit(2),
    db='apmifwsi001_DR2'
)
[11]:
cellid sampleid hpfid px py ptype cmembrane520 cmembrane540 cnucleus570 centirecell620 cmembrane650 centirecell690 exprphenotype tdist rdist pos pdl1 pd1
0 19060100257 19 190601 32125.16445 17048.462357 2 1.297197 1.088610 51.92764 9.126939 15.77287 0.010750 64 14.23974 32768 0x01010000003cab58864a5fdf409ae241971da6d040 False True
1 19060100258 19 190601 32349.16445 17086.462357 2 3.327510 1.198786 47.10973 2.022695 44.91587 0.640953 64 237.84630 32768 0x01010000003cab58864a97df409ae241979dafd040 False True
[12]:
db2.query(db2.select(db2.apmifwsi002_DR3.celltag).ptype_filter(2).limit(2))
[12]:
cellid sampleid hpfid px py ptype cmembrane520 cmembrane540 cnucleus570 ccytomembrane620 cmembrane650 cmembrane690 exprphenotype tdist rdist pos pdl1 pd1
0 545129300043 545 5451293 17083.931205 32500.792955 2 1.210994 0.27196 59.32221 3.037047 1.086947 5.835883 0 48.60199 32768 0x010100000080ffdd98fbaed040cd78c6bf32bddf40 False False
1 545129300044 545 5451293 17016.931205 32558.792955 2 2.160510 0.27196 20.01933 2.430948 1.809567 0.463564 0 13.79003 32768 0x010100000080ffdd983b9ed040cd78c6bfb2cbdf40 False False

AstroDB Unique Properties#

AstroDB also has a set of properties. The first one to note is the AstroDB.public_dbs_metadata. This contains a dictionary of the available databases and some metadata related to each database. As a demonstration we have printed the “apmifwsi001_DR2” metadata dictionary below.

[13]:
db.public_dbs_metadata['apmifwsi001_DR2']
[13]:
{'Tissue': 'melanoma',
 'cohort': 1,
 'machine': 'JHUVectra3_1',
 'method': 'Manual',
 'panel': 'PD1/PDL1 Axis Panel',
 'stainconfig': 1,
 'xlevel': 1}

Additionally, it contains properties which can be used to reference tables in the database related to the database’s meta data.

These properties are grabbed and stored when requested and are cleared when switch to a new database. The properties are grouped into three elements: AstroDB.cellmeta, AstroDB.metadata, and AstroDB.schema. Below we print out some of the referenced tables, for a more detailed summary see the full AstroDB documentation.

[14]:
# the translation of ptype to phenotype
db.cellmeta.phenotype
[14]:
ptype phenotype color
0 0 Other #888888FF
1 1 CD8 #EE4035FF
2 2 FoxP3 #F4E76FFF
3 3 Tumor #F37736FF
4 4 CD163 #B361B4FF
5 5 FoxP3CD8 #F193D2FF
[15]:
# the translation of exprphenotype to their opals
db.cellmeta.exprphenotype
[15]:
expr bit val
0 DAPI 0 1
1 Opal480 1 2
2 Opal520 2 4
3 Opal540 3 8
4 Opal570 4 16
5 Opal620 5 32
6 Opal650 6 64
7 Opal670 7 128
8 Opal690 8 256
9 Opal780 9 512
[16]:
# metadata about the panel
db.cellmeta.mergeconfig.head()
[16]:
project cohort batchid layer opal target compartment targettype coexpressionstatus segmentationstatus segmentationhierarchy numberofsegmentations imageqa color
0 1 1 3 1 DAPI DNA Nucleus NA NA 0 0 0 NA #0000FF
1 1 1 3 2 520 PDL1 Membrane Expression 620,690 1 0 1 NA #7BC043
2 1 1 3 3 540 CD8 Membrane Lineage 570 1 1 1 Immune #EE4035
3 1 1 3 4 570 FoxP3 Nucleus Lineage 540 1 1 1 NA #F4E76F
4 1 1 3 5 620 Sox10/S100 EntireCell Lineage NA 2 3 1 Tumor #F37736
[17]:
# a list of tables in the database
db.schema.wsi_tables.head()
[17]:
TABLE_CATALOG TABLE_SCHEMA TABLE_NAME TABLE_TYPE
0 apmifwsi001_DR2 dbo Affine BASE TABLE
1 apmifwsi001_DR2 dbo Align BASE TABLE
2 apmifwsi001_DR2 dbo Annotations BASE TABLE
3 apmifwsi001_DR2 dbo Batch BASE TABLE
4 apmifwsi001_DR2 dbo BoundaryType BASE TABLE
[18]:
# clinical data for the database context
db.metadata.clinical.head()
[18]:
astroid sampleid response treatment ageatcollection sex anatomicsite melanomastage lesion_type best_response os_days os status pfs_days pfs_status braf status prior immunotherapy
0 P10_D01_C01_S01_B01_L01 74 Non-Responder Ipilimumab + nivolumab 81 Female Mucosal Stage IV Primary PD 109 Deceased 91 Non-Responder no mutation detected No
1 P11_D01_C01_S01_B01_L01 8 Responder Nivolumab 80 Male Skin_soft-tissue Stage IV Metastasis PR 1428 Alive 1610 Responder no mutation detected No
2 P12_D01_C01_S01_B01_L01 76 Responder Pembrolizumab 51 Female Skin_soft-tissue Stage III unresectable CR 670 Alive 609 Non-Responder no mutation detected No
3 P13_D01_C01_S01_B01_L01 17 Responder Nivolumab 61 Male Skin_soft-tissue Stage IV Primary PR 3435 Alive 3434 Responder No
4 P14_D01_C01_S01_B01_L01 19 Responder Ipilimumab + nivolumab 63 Female Lymph-node Stage IV Metastasis PR 1219 Alive 402 Non-Responder no mutation detected No
[19]:
# a list of samples in the database
db.metadata.samples.head()
[19]:
sampleid slideid project cohort scan batchid isgood astroid
0 2 M2_3 1 1 1 9 1 P26_D01_C01_S01_B01_L01
1 3 M3_1 1 1 1 9 1 P25_D01_C01_S01_B01_L01
2 4 M4_2 1 1 1 6 1 P28_D01_C01_S01_B01_L01
3 5 M6_1 1 1 1 8 1 P38_D01_C01_S01_B01_L01
4 6 M7_2 1 1 1 9 1 P39_D01_C01_S01_B01_L01