CellMeta#

class astropathdb.db_io.build_astrodb.CellMeta(*args, **kwargs)#

Bases: WsiMirrorBase

Mirrors the database tables with cell type metadata information.

This allows for easy access to the database tables as class properties.

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.

CellMeta Attributes#

CellMeta Properties#

mixing_matrix

A layerx3 matrix for converting images to rgb.

expression_columns

Get the target expression column names from mergeconfig for celltag.

expression_targets

Get the target expression column names from mergeconfig for celltag.

sql

The last query sent to the database.

database

The database queried when no db is given.

CellMeta Methods#

set_ptype_colors()

Set the ptype colors to the mixing matrix colors.

get_phenotype(ptype)

Select the phenotype string from ptype.

get_ptype(phenotype)

Select the ptype number from phenotype input.

get_exprphenotype(phenotype)

Select the ptype number from phenotype input.

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.

CellMeta References#

Attribute Reference#

attribute mirror_name = 'CellMeta'#
attribute mirrored_tables = ('batch', 'boundarytype', 'exprmarkers', 'exprphenotype', 'mergeconfig', 'phenotype')#

Property Reference#

property mixing_matrix#
Type:

DataFrame

Return type:

DataFrame

A layerx3 matrix for converting images to rgb.

By default the mixing matrix in the ref:mergeconfig<mergeconfig_schema> table will be used. The matrix can be changed by passing either ‘default’ or a mapping of {layer: hex color} to the property. If input mixing_matrix is set to ‘default’, it will use the mixing matrix for the foundational AstroPath paper published in Science, 2021 for the number of image layers in the mergeconfig table, and raise a ValueError if there is none. If a mapping for a matrix is supplied the mixing_matrix, that mapping will be applied to the mergeconfig table stored in the cellmeta property and used for visualization.

Note

The mixing matrix will default back to the database mixing matrix if the database is updated.

property expression_columns#
Type:

list

Return type:

list

Get the target expression column names from mergeconfig for celltag.

property expression_targets#
Type:

list

Return type:

list

Get the target expression column names from mergeconfig for celltag.

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#

method set_ptype_colors()#

Set the ptype colors to the mixing matrix colors.

Return type:

None

method get_phenotype(ptype)#

Select the phenotype string from ptype.

Parameters:

ptype (int | Sequence[int]) – A ptype or list of ptypes.

Return type:

str | list

method get_ptype(phenotype)#

Select the ptype number from phenotype input.

Parameters:

phenotype (str | Sequence[str]) – A phenotype or list of phenotypes

Return type:

int | list[int]

method get_exprphenotype(phenotype)#

Select the ptype number from phenotype input.

Parameters:

phenotype (str | Sequence[str]) – A phenotype or list of phenotypes

Return type:

int | list[str]

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.

Private Property Reference#

property _filtered_mergeconfig#
Type:

DataFrame

Return type:

DataFrame