AstroSample#

class astropathdb.db_io.load_sample.AstroSample(*args, sdata, sampleid, **kwargs)#

Bases: AstroDB

Helper class loading samples into SpatialData.

The class enables loading AstroPath image, cell, and annotation data into a SpatialData to seemlessly adopt the framework.

Parameters:
  • database (str) – The database to query by default, given in any letter case (see canonical_database_name()). Defaults to a public database.

  • username (str | None) – The SciServer account. With password, it takes priority over every other source. Alone, it ranks below credential_filename, and a missing password may be completed from this account’s keyring.

  • password (str | None) – The selected account’s password, preserved exactly when supplied directly.

  • credential_filename (str | Path | None) – A local .env, JSON, or two-line text credential file, used unless username and password are both given. Relative paths use the current directory; home-directory paths may start with ~.

  • db_connection (bool | CasJobsUrllib3Client) – True to authenticate and open a client, or an existing CasJobsUrllib3Client to reuse its connection pool.

  • sdata (SpatialData) – A SpatialData object to load the data into.

  • sampleid (str | int | list[str | int]) – A single or list of sampleids to load the data from.

See also

load_astrosample() for details on the implementation.

AstroSample Attributes#

parsed_init

wsi_dbs_metadata

A dictionary with primary keys denoting the available private astropath databases.

public_dbs_metadata

A dictionary with primary keys denoting the available public databases.

AstroSample Properties#

cellmeta

A collection of properties that mirrors data related to cohort cells.

metadata

A collection of properties that mirrors data related to cohort metadata.

schema

A collection of properties that mirrors data related to cohort schema.

sql

The last query sent to the database.

database

The database queried when no db is given.

AstroSample Methods#

from_astrodb(sdata, astrodb, sampleid)

Build an instance from a predefined AstroDB.

samples(element)

List of sampleids for the element to load.

should_load(element)

Whether or not to load the element.

results_key(element)

Results keys for the element.

structured_query(element)

Returns a structured query for the element.

load_element(element)

Load the element into the SpatialData object.

load_astrosample(*, image, annotations, cells_table, ...)

Load sample data into the SpatialData framework.

load_db_session([db, reload])

Create an ORM mapping of db and store as a named attribute.

update_ptype_filter([ptype])

Updates the ptype_filter to allow for phenotype key.

update_exprphenotype_filter([exprphenotype])

Updates the ptype_filter to allow for phenotype key.

update_filter_dict(**filters)

Group update on some defaults on specific filters.

sci_login([username, password, credential_filename])

Authenticate or reuse the process-wide SciServer session.

query([sql, long, db, output_format, nthreads, ...])

Query a database with a SQL statement.

print_sql([sql, construct, as_string])

Print, or return, a SQL statement as the SQL sent to the database.

dbstring(sql_str)

Wrap a string in single quotes for use as a SQL string literal.

convert_to_geom(df, geometry_id)

Convert DataFrame to GeoDataFrame.

gquery(*args[, geometry_id])

Run query() and convert a geometry column.

select(*columns[, table_name, context])

Custom wrapper for select().

get_table([context, table_name])

If a table name is passed this will get that ORM attribute.

add_sql_filters(construct, **filter_mappings)

Using mappings add our custom filters to a Select construct.

load_query_init(*columns[, table_name, top_n, where, sql])

The basic initialization for load_<element>_queries.

AstroSample References#

Attribute Reference#

attribute parsed_init: dict[str, DataFrame | GeoDataFrame | None]#
attribute wsi_dbs_metadata: dict#

A dictionary with primary keys denoting the available private astropath databases.

Each database contains a subsequent mappping for related metadata.

wsi_dbs_metadata keys:
  • tissue: The cancer tissue type.

  • cohort: A unique number denoting a set of patients.

  • machine: The microscope that was used to image the slides.

  • method: The method for staining, denoted as ‘Manual’ or ‘Automated’.

  • panel: A descriptive string denoting the antibody-fluor pairings, each panel is given a unique string.

  • stainconfig: A number denoting a combination of machine, method, and panel.

  • xlevel: The numeric cut level from the block that was used for each slide.

attribute public_dbs_metadata: dict#

A dictionary with primary keys denoting the available public databases.

The databases are named <dataset>_<release>. The metadata of each one is the metadata of the wsiXX database it was built from, with the same keys as wsi_dbs_metadata.

Property Reference#

property cellmeta#
Type:

CellMeta

Return type:

CellMeta

A collection of properties that mirrors data related to cohort cells.

Has the following table attributes:
property metadata#
Type:

MetaDat

Return type:

MetaDat

A collection of properties that mirrors data related to cohort metadata.

Has the following table attributes:

The extendedclinical and slides tables exist only in the private databases. Reading them on a public database raises CasJobsConnectionError.

property schema#
Type:

WsiSchema

Return type:

WsiSchema

A collection of properties that mirrors data related to cohort schema.

Has the following table attributes:
  • wsi_tables

  • wsi_procedures

  • wsi_functions

Has the following methods:
property sql#
Type:

str | ClauseElement | Sequence[str | ClauseElement]

Return type:

str | ClauseElement | Sequence[str | ClauseElement]

The last query sent to the database.

Holds the SQL string, or list of strings, most recently sent by query(). Set it to a SQL string, a SQLAlchemy construct, or a sequence of either, then call query() with no sql to run it; the attribute then holds the SQL that was sent.

property database#
Type:

str

Return type:

str

The database queried when no db is given.

Always the registered spelling of the name (see canonical_database_name()). Setting it calls _database_setter(), which subclasses override.

Method Reference#

classmethod from_astrodb(sdata, astrodb, sampleid)#

Build an instance from a predefined AstroDB.

Parameters:
Return type:

Self

method samples(element)#

List of sampleids for the element to load.

Parameters:

element (str)

Return type:

list[str]

method should_load(element)#

Whether or not to load the element.

Parameters:

element (str)

Return type:

bool

method results_key(element)#

Results keys for the element.

Parameters:

element (str)

Return type:

list[str]

method structured_query(element)#

Returns a structured query for the element.

Parameters:

element (str) – The element to query.

Returns:

A StructuredQuery object for the element.

Return type:

StructuredQuery

method load_element(element)#

Load the element into the SpatialData object.

Parameters:

element (str) – The element to load.

Return type:

None

method load_astrosample(*, image, annotations, cells_table, cells_positions, cells_boundaries)#

Load sample data into the SpatialData framework.

Parameters:
  • image (bool) – Load image data into the object (Defaults to True).

  • annotations (bool) – A logical value to load annotations or a mapping for what to load. Allowed arguments are columns, instance_id, geometry_id, table_name, and any of the sql filters. Defaults to True. Annotations are loaded from the Annotations Table by default.

  • cells_table (bool) – A logical value to load cell tables or a mapping for what to load. Allowed arguments are columns, instance_id, coordinate_ids, table_name, and any of the sql filters. (Defaults to False). Cells are loaded from the Celltag Table by default.

  • cells_positions (bool) – A logical value to load cell centriods into the shapes element or a mapping for what to load. Allowed arguments are columns, instance_id, geometry_id, table_name, and any of the sql filters. (Defaults to False). Cells positions are loaded from the Celltag Table by default.

  • cells_boundaries (bool) – A logical value to load cell centriods into the shapes element or a mapping for what to load. Allowed arguments are columns, instance_id, geometry_id, table_name, and any of the sql filters. (Defaults to False). Cells boundaries are loaded from the Cellgeom Table by default and only membranes are loaded using btype.

Return type:

None

See also

load_astrosample() for additional details and implementation.

method load_db_session(db=None, *, reload=False, **kwargs)#

Create an ORM mapping of db and store as a named attribute.

The ORM attribute will be named by the db specified.

Only generates the ORM attribute if it did not previously exist. Will default to the active database if no db is provided.

Parameters:
  • db (str | None) – The database to load a new session for (Defaults to the database attribute value).

  • reload (bool) – Reload the ORM, useful if the database changes during analysis.

  • **kwargs – Additional keyword arguments to pass to the database connection.

Return type:

None

method update_ptype_filter(ptype=MappingProxyType({}))#

Updates the ptype_filter to allow for phenotype key.

Parameters:

ptype (Mapping[str, Any]) – A mapping for a filter generated by _create_dynamic_filter() which will be applied by add_sql_filters(). Values to filter can either be supplied to the ‘ptype’ or ‘phenotype’ key, do not add both. The code will perform the appropriate ‘ptype’ lookup if a ‘phenotype’ is supplied.

Return type:

dict

See also

Phenotype Table:
  • A description of the ‘ptype’ and ‘phenotype’ keys.

_create_dynamic_filter():
  • For a description of the filters.

add_sql_filters()
  • For a description of how the filters are added to the select() statements when using a mappings.

method update_exprphenotype_filter(exprphenotype=MappingProxyType({}))#

Updates the ptype_filter to allow for phenotype key.

Parameters:

exprphenotype (Mapping[str, Any]) – A mapping for a filter generated by _create_dynamic_filter() which will be applied by add_sql_filters(). Values to filter can either be supplied to the ‘exprphenotype’ or ‘phenotype’ key, do not add both. The code will perform the appropriate ‘exprphenotype’ bit value lookup if a ‘phenotype’ is supplied.

Return type:

dict

See also

Exprmarkers Table:
  • A description of the ‘exprphenotype’ and ‘phenotype’ keys.

_create_dynamic_filter():
  • For a description of the filters.

add_sql_filters()
  • For a description of how the filters are added to the select() statements when using a mappings.

method update_filter_dict(**filters)#

Group update on some defaults on specific filters.

Return type:

Any

method sci_login(username=None, password=None, *, credential_filename=None)#

Authenticate or reuse the process-wide SciServer session.

Automatic local discovery selects an environment token, the existing session, a configured file, environment credentials, then scicreds/sciserver_creds.txt in a source checkout. Supply explicit credentials to reauthenticate after a rejected query; a bare call may reuse the rejected session. Reused tokens are not validated against the server. Compute uses its managed session only.

Parameters:
  • username (str | None) – The SciServer account. With password, it takes priority over every other source. Alone, it ranks below credential_filename, and a missing password may be completed from this account’s keyring.

  • password (str | None) – The selected account’s password, preserved exactly when supplied directly.

  • credential_filename (str | Path | None) – A local .env, JSON, or two-line text credential file, used unless username and password are both given. Relative paths use the current directory; home-directory paths may start with ~.

Raises:
Return type:

None

Examples

db.sci_login(username="account", password=password)
method query(sql=None, *, long=False, db=None, output_format=CASJOBSDCONST.DEFAULT_RETURNTYPE, nthreads=CASJOBSDCONST.DEFAULT_THREADS, _force_sciscript=False)#

Query a database with a SQL statement.

sql is a SQL string, a SQLAlchemy construct, or a sequence of either. Constructs are compiled to SQL strings. A sequence is run as separate queries in parallel, and the results are returned in completion order, not input order. Splitting a large query into a sequence, or joining several queries with ‘;’, usually returns data faster.

Output formats:
  • “pandas”: A dataframe for a single result set, otherwise a list of the non-empty dataframes.

  • “pandas_concat”: The non-empty result sets concatenated into one dataframe. All result sets must have the same columns.

  • “json” or “dict”: The raw result set dictionaries.

  • “list”: A (columns, rows) tuple with the rows of every result set. All result sets must have the same columns.

  • “csv”, “readable”, “StringIO”, “fits”, and “BytesIO”: Supported only with _force_sciscript; see the SciScript-Python documentation.

Parameters:
  • sql (str | ClauseElement | Sequence[str | ClauseElement] | None) – The query or queries to run. Defaults to sql.

  • long (bool) – Submit sql as a long-running CasJobs job and wait for it. Use for queries that exceed the synchronous time limit; the query must write its results to a table in ‘MyDB’, and the job status is returned instead of data.

  • db (str | None) – The database context. Defaults to database.

  • output_format (str) – The output format; see above.

  • nthreads (int) – Number of threads used to run a sequence of queries.

  • _force_sciscript (bool) – Run the query through SciScript-Python instead of the package’s parallel client.

Returns:

The query results in the output_format output format.

Return type:

dict | list[dict] | tuple[list, list] | DataFrame | list[DataFrame]

Examples

Query a table, then run two queries in parallel and join their results:

from astropathdb import AstroDB

astrodb = AstroDB(database="apmifwsi001_DR2")
samples = astrodb.query("SELECT sampleid, astroid FROM Samples")
df = astrodb.query(
    [
        "SELECT sampleid, astroid FROM Samples WHERE sampleid < 10",
        "SELECT sampleid, astroid FROM Samples WHERE sampleid >= 10",
    ],
    output_format="pandas_concat",
)
method print_sql(sql=None, *, construct=False, as_string=False)#

Print, or return, a SQL statement as the SQL sent to the database.

Defaults to the last SQLAlchemy construct passed to query(), then to sql.

Parameters:
  • sql (str | ClauseElement | Sequence[str] | None) – A SQL string, a SQLAlchemy construct, or a sequence of SQL strings.

  • construct (bool) – Keep a SQLAlchemy construct as is instead of compiling it to SQL.

  • as_string (bool) – Return the statement instead of printing it.

Returns:

The statement if as_string is True, otherwise None.

Return type:

str | ClauseElement | Sequence[str] | None

static dbstring(sql_str)#

Wrap a string in single quotes for use as a SQL string literal.

Parameters:

sql_str (str) – The string to quote.

Returns:

sql_str wrapped in single quotes.

Return type:

str

static convert_to_geom(df, geometry_id)#

Convert DataFrame to GeoDataFrame.

The database returns geometry values as well-known text (MSSQL .STAsText()) or as hex-encoded well-known binary (.STAsBinary()). The geometry_id column is parsed as WKB when its values start with ‘0x’, otherwise as WKT, and replaced by a ‘geometry’ column. Rows with empty geometries are removed.

Parameters:
  • df (DataFrame | list[DataFrame]) – The query result. A list of dataframes is concatenated first.

  • geometry_id (str) – The column holding the geometry values. Cannot be ‘geometry’.

Returns:

The query result with a ‘geometry’ column in place of geometry_id.

Raises:

ValueError – geometry_id is ‘geometry’.

Return type:

GeoDataFrame

See also

gquery() to query and convert in one call.

method gquery(*args, geometry_id=APDBREF.GEOM_WKT_NAME, **kwargs)#

Run query() and convert a geometry column.

The geometry_id column of the result becomes the ‘geometry’ column of a GeoDataFrame; see convert_to_geom().

Parameters:
  • *args – Positional arguments for query().

  • geometry_id (str | None) – The column holding the geometry values. If None, the query result is returned unconverted.

  • **kwargs – Keyword arguments for query().

Returns:

The query result, converted when geometry_id is given.

Return type:

DataFrame | GeoDataFrame

See also

query() for query inputs and output formats, and convert_to_geom() for the geometry conversion.

method select(*columns, table_name=None, context=None)#

Custom wrapper for select().

We do this so that we can use text expressions in Object Relational Mapping (ORM) clauses vs always having to use explicit expressions.

If sqlalchemy constructs are passed as the initial arguments, it returns the sqlalchemy select() as normal.

Optionally, you can provide a list of columns, a table_name, and/or a context as strings and the method will perform an attribute lookup on the instance of the class to find the corresponding ORM contructs. Thus when writing a SQL.select() statement the ORM select() for the sampleid and cellid columns from the Celltag Table can be built with obj.select('sampleid', 'cellid', table_name = 'celltag'). This may become simpler for longer queries than the fully qualified version: obj.select(obj.apmifwsi001_DR2.celltag.sampleid, obj.apmifwsi001_DR2.celltag.cellid).

Warning

If the attribute for the context does not exist this will return an attribute not found error.

Parameters:
  • *columns – Positional arguments are interpretted list of columns to be selected in the database (e.g. 'sampleid', 'ptype') or a declarative base object for a table (e.g. obj.apmifwsi001_DR2.celltag.sampleid, obj.apmifwsi001_DR2.celltag.cellid).

  • table_name (str | DeclarativeBase | None) – The table name to query as either the mapping object (e.g. table_name=obj.apmifwsi001_DR2.celltag) or as text (e.g. table_name='celltag').

  • context (str | DeclarativeBase | None) – The database context to query as either the mapping object (e.g. context=obj.apmifwsi001_DR2) or as text (e.g. context='apmifwsi001_DR2') (defaults to database attribute of the object).

Return type:

Select

See also

sqlalchemy.sql.expression.select():
_get_context() and get_table():
  • Methods used for the lookup.

_create_dynamic_filter():
  • The custom filter implementation provided as an extension.

APFilters:
  • A list of the custom filters themselves.

method get_table(context=None, table_name=None)#

If a table name is passed this will get that ORM attribute.

Will include the context using _get_context() for a lookup. If the context is not provided we use the database attribute of the object.

Parameters:
  • table_name (str | DeclarativeBase | None) – The table name to query as either the mapping object (e.g. table_name=obj.apmifwsi001_DR2.celltag) or as text (e.g. table_name='celltag'). If a string is passed the ORM object is looked up in the class.

  • context (str | DeclarativeBase | None) – The database context to query as either the mapping object (e.g. context=obj.apmifwsi001_DR2) or as text (e.g. context='apmifwsi001_DR2'). If a string is passed the ORM object is looked up in the class. (defaults to database attribute of the object).

Returns:

Returns the table attribute itself with the context.

Return type:

DeclarativeBase

static add_sql_filters(construct, **filter_mappings)#

Using mappings add our custom filters to a Select construct.

We extend the Select adding keyword arguments as filter mappings, where the argument name is one of the filters in APFilters and the value is a mapping of argument:value pairs for the filter.

For example, to filter on the current sampleid we can add sampleid = self.sampleid. By default this is already done for us in some methods, to remove the filter we can pass the keyword argument sampleid = '*', where ‘*’ is a special value we use to specify all values. Optionally, filters

Note

When default filters are denoted by query and loading methods they typically implement those defaults with this method.

Parameters:
  • construct (Select) – The sqlalchemy contruct to add the filter to. Must have been derived from SQL.select().

  • **filter_mappings – The argument name is the name of a filter in the APFilters and the value is a mapping of argument:value pairs.

Return type:

Select

See also

load_query_init()
  • Additional details on implementation

APFilters:
  • For a list of the available filter mappings

_create_dynamic_filter():
  • Additional internal details on the mapping arguments and logic

method load_query_init(*columns, table_name=None, top_n=None, where=None, sql=None, **kwargs)#

The basic initialization for load_<element>_queries.

If sql is not empty, will return the query. Otherwise it will use our custom SQL.select() to generate a Select construct using the positional arguments as columns and applying the table_name, where, and top_n arguments when applicable. We always add the sampleid to the list of columns to query.

We then extend the Select adding any other keyword arguments as filter mappings using add_sql_filters().

Note

When default filters are denoted by query and loading methods they typically implement those defaults with the add_sql_filters() method.

Parameters:
  • *columns – Positional arguments are interpretted list of columns to be selected in the database (e.g. (‘sampleid’, ‘ptype’)) or a declarative base object for a table (e.g. obj.apmifwsi001_DR2.celltag). The latter would return all columns in the provided table. By default the “sampleid” column is always added.

  • table_name (str | DeclarativeBase | None) – The table name to query as either the mapping object (e.g. table_name=obj.apmifwsi001_DR2.celltag) or as text (e.g. table_name='celltag').

  • where (Any | None) – Provide a custom ‘where’ clause to filter the table. This is passed to where() and should be a ColumnExpressionArgument.

  • top_n (int | None) – If applied will only return the top n rows and is applied using limit() from sqlalchemy.

  • sql (str | Select | None) – Provide a custom sql query for the element instead of using the default filters options, supersedes and skips all other input arguments.

  • **kwargs – Keyword arguments passed to add_sql_filters() (Defaults to sampleid = {'sampleid':self.sampleid}).

Return type:

str | Select

See also

Implementation examples:
add_sql_filters():
  • For the dictionary implementation of custom filters.

Returns:

If sql is provided will return a string, otherwise we return the updated Select contruct.

Parameters:
Return type:

str | Select

Private Attribute Reference#

attribute __sdata: SpatialData#
attribute __elements: dict[str, SamplesToLoad]#
attribute _sampleids#

Private Method Reference#

method _parse_element_inputs(**kwargs)#
Return type:

None

method _query_init_elements()#
Return type:

list[StructuredQuery]

method _parse_init_queries(query_results)#

Parse the queries for the elements requested.

Returns:

A dictionary with the parsed results for each element.

Parameters:

query_results (list[StructuredQuery])

Return type:

None

method _load_cells(sample, element)#
Parameters:
Return type:

tuple[list[DataFrame], StructuredQuery]

method _add_cells_shapes(sample, element_id)#
Parameters:
  • sample (str)

  • element_id (str)

Return type:

None

method _load_cells_boundaries(sample, *_)#

Load the cell boundaries into the shapes element.

Parameters:

sample (str) – The sample to load the cell boundaries for.

Return type:

None

method _load_cells_positions(sample, *_)#

Load the cell boundaries into the shapes element.

Parameters:

sample (str) – The sample to load the cell boundaries for.

Return type:

None

method _load_cell_points(sample, cells, pos_cols)#
Parameters:
Return type:

None

method _astropath_keys()#

Returns a dictionary of keys used in the Astropath database.

Return type:

dict[str, dict[str, str]]

method _load_cells_table(sample, *_)#
Parameters:

sample (str)

Return type:

None

method _load_annotations(sample, geom_key)#
Parameters:
Return type:

None

method _load_image(sample, *_)#
Parameters:

sample (str)

Return type:

None