schrodinger.application.matsci.kmc module

Utilities for working with KMC charge mobility databases and results

Copyright Schrodinger, LLC. All rights reserved.

class schrodinger.application.matsci.kmc.ColumnData(type, default)

Bases: tuple

default

Alias for field number 1

type

Alias for field number 0

class schrodinger.application.matsci.kmc.MoleculeData(index, name, mtype, posx, posy, posz)

Bases: tuple

index

Alias for field number 0

mtype

Alias for field number 2

name

Alias for field number 1

posx

Alias for field number 3

posy

Alias for field number 4

posz

Alias for field number 5

class schrodinger.application.matsci.kmc.MSDInfo(field_str, charge_idx, component, sd_by_t, fit_bin_i, fit_bin_f, fit_type, fit_sd_by_t, linear_coeff, quadratic_coeff, mean_displacement_by_t, fit_mean_displacement_by_t, fit_mean_displacement_r_squared, displacement_variance_by_t, fit_displacement_variance_by_t, fit_displacement_variance_r_squared, fit_drift_velocity, fit_sd_r_squared)

Bases: tuple

charge_idx

Alias for field number 1

component

Alias for field number 2

displacement_variance_by_t

Alias for field number 13

field_str

Alias for field number 0

fit_bin_f

Alias for field number 5

fit_bin_i

Alias for field number 4

fit_displacement_variance_by_t

Alias for field number 14

fit_displacement_variance_r_squared

Alias for field number 15

fit_drift_velocity

Alias for field number 16

fit_mean_displacement_by_t

Alias for field number 11

fit_mean_displacement_r_squared

Alias for field number 12

fit_sd_by_t

Alias for field number 7

fit_sd_r_squared

Alias for field number 17

fit_type

Alias for field number 6

linear_coeff

Alias for field number 8

mean_displacement_by_t

Alias for field number 10

quadratic_coeff

Alias for field number 9

sd_by_t

Alias for field number 3

schrodinger.application.matsci.kmc.is_kmc_result_prop(prop)

Check if a property is a KMC result property

Parameters:

prop (str) – The property to check

Return type:

str or None

Returns:

If the property is a KMC result property, the type of property is returned as a module-level constant. If the property is not recognized as a KMC result property, None is returned.

schrodinger.application.matsci.kmc.parse_mobility_or_velocity_prop(prop)

Parse a property name and return the information from it if it is a KMC mobility or velocity property

Parameters:

prop (str) – The property to check

Return type:

(int, str, str) or None

Returns:

The integer is the field index, the first string is the charge (HOLE or ELECTRON) and the second string is the axis name. None is returned if the property is not a mobility or velocity property.

schrodinger.application.matsci.kmc.parse_field_prop(prop)

Parse a property name and return the information from it if it is a KMC field property

Parameters:

prop (str) – The property to check

Return type:

(int, str) or None

Returns:

The integer is the field index, the string is the axis name. None is returned if the property is not a field property.

schrodinger.application.matsci.kmc.parse_database_prop(prop)

Parse a property name and return the information from it if it is a KMC database property

Parameters:

prop (str) – The property to check

Return type:

(int, list) or None

Returns:

The integer is the field index, the list contains the charges (HOLE and/or ELECTRON). None is returned if the property is not a database property

class schrodinger.application.matsci.kmc.AxisData

Bases: object

Holds data that differs on the X, Y and Z axes

__init__()

Create an AxisData object

setComponent(axis, value)

Set the data for one axis

Parameters:

axis (str or int) – Either the capital name of an axis (X, Y, Z) or the numerical index of that axis

class schrodinger.application.matsci.kmc.SQLCursor(path)

Bases: object

Context manager for reading or modifying an SQL database. Ensures that changes are committed and the cursor/connection are closed when finished.:

cmd = "black SQL magic"
with SQLCursor(path_to_sql_file) as cursor:
    cursor.execute(cmd)
__init__(path)
class schrodinger.application.matsci.kmc.Table(filename)

Bases: object

Base table class for KMC SQL tables

TABLE_NAME = ''
COLUMNS = {}
CREATION_COMMAND = 'CREATE TABLE {name} ({columns});'
ADDROW_COMMAND = 'INSERT INTO {name} ({cols}) VALUES ({ph})'
NULL_ALLOWED = False
SQL_ID = '_id'
SQID = 'id'
NAME = 'name'
TYPE = 'type'
MOL = 'mol'
POSX = 'posX'
POSY = 'posY'
POSZ = 'posZ'
FRAME = 'frame'
TOP = 'top'
SEG = 'seg'
__init__(filename)

Create a Table instance

Parameters:

filename (str) – The path to the SQL file

setCursor(cursor)

Set the SQL cursor this table should use

Parameters:

cursor (sqlite3.Cursor) – The cursor to use for database read/writes

create()

Create this table in the database

Raises:

SQLCreationError – If the cursor is not defined

getMoleculeInfo(molecule, centroid=True)

Get common database information for a molecule object

Parameters:
  • molecule (schrodinger.structure._StructureMolecule) – The molecule object to get information for

  • centroid (bool) – Include information about the molecule’s centroid. If False, all centroid information will be 0.

Return type:

MoleculeData

Returns:

A MoleculeData object containing the information

static getSegmentType(molecule)

Get the segment type for this molecule

Segment names will be type_X, where X is the molecule number

Parameters:

molecule (_Molecule) – The molecule object

Return type:

str

Returns:

The segment type for this molecule

static getAllSegmentTypes(struct)

Get all the segment types for this structure

Parameters:

struct (Structure) – The structure object

Return type:

set

Returns:

Each item of the set is the name of a segment type

class schrodinger.application.matsci.kmc.SchrodingerTable(filename)

Bases: Table

The schrodinger table. This contains Schrodinger-specific information.

TABLE_NAME = 'schrodinger'
NULL_ALLOWED = True
MOLFORM = 'mol_formula'
VOLUME = 'pbc_volume_Ang3'
JOBID = 'jobid'
STRUCTURE_PATH = 'structure_path'
STRUCTURE_FILE = 'structure_file'
CONCENTRATIONS_FILE = 'concentrations_file'
PAIR_DISTANCE = 'pair_distance_Ang'
PAIR_TYPE = 'pair_type'
VERSION = 'version'
JUMPSUMMARY = 'jumpsummary'
RUNTIME = 'runtime'
SEED = 'seed'
FIELDX = 'fieldX'
FIELDY = 'fieldY'
FIELDZ = 'fieldZ'
AVECTOR = 'a_vector'
BVECTOR = 'b_vector'
CVECTOR = 'c_vector'
TEMPERATURE = 'temperature'
RATEFILE = 'ratefile'
CARRIERTYPE = 'carriertype'
SITE_KEYWORDS = 'site_keywords'
FIX_SITE_KEYWORDS = 'site_fix_keywords'
SUPPORTED_KMC_DATABASE = 'matsci_engine'
AVERAGE_JEFF = 'average_jeff'
CRYSTAL = 'crystal'
COLUMNS = {'a_vector': ColumnData(type='TEXT', default=None), 'average_jeff': ColumnData(type='INT', default=1), 'b_vector': ColumnData(type='TEXT', default=None), 'c_vector': ColumnData(type='TEXT', default=None), 'carriertype': ColumnData(type='TEXT', default=None), 'concentrations_file': ColumnData(type='TEXT', default=None), 'crystal': ColumnData(type='INT', default=0), 'fieldX': ColumnData(type='REAL', default=None), 'fieldY': ColumnData(type='REAL', default=None), 'fieldZ': ColumnData(type='REAL', default=None), 'jobid': ColumnData(type='TEXT', default=None), 'jumpsummary': ColumnData(type='TEXT', default=None), 'matsci_engine': ColumnData(type='INT', default=0), 'mol_formula': ColumnData(type='TEXT', default=None), 'pair_distance_Ang': ColumnData(type='REAL', default=0.0), 'pair_type': ColumnData(type='REAL', default=None), 'pbc_volume_Ang3': ColumnData(type='REAL', default=0.0), 'ratefile': ColumnData(type='TEXT', default=None), 'runtime': ColumnData(type='REAL', default=None), 'seed': ColumnData(type='INT', default=None), 'site_fix_keywords': ColumnData(type='TEXT', default=None), 'site_keywords': ColumnData(type='TEXT', default=None), 'structure_file': ColumnData(type='TEXT', default=None), 'structure_path': ColumnData(type='TEXT', default=None), 'temperature': ColumnData(type='REAL', default=None), 'version': ColumnData(type='REAL', default=0.92)}
addRow(struct)

Add a row

Parameters:

struct (schrodinger.structure.Structure) – The structure for the database

class schrodinger.application.matsci.kmc.BaseDatabaseManager(struct, filename)

Bases: object

Manage initialization and filling of SQL database tables

SITES_TABLE = None
PAIRS_TABLE = None
class Cursor(manager)

Bases: SQLCursor

Context manager for obtaining a cursor object for use by the tables. Note that when adding many rows it saves a huge amount of time to create the cursor once and then close it when finished rather than create/close a cursor for each row.

__init__(manager)
__init__(struct, filename)

Create a BaseDatabaseManager instance

Parameters:
fillSchrodinger()

Fill the schrodinger table

fillPairs(dist, pair_type='heavy')

Find all dimers in the given structure based on the normal Schrodinger dimer finding algorithm. Add all found dimers to the given SQL file.

Parameters:
  • dist (float) – The distance threshold for defining dimers

  • pair_type (str) – Either SQL_HEAVY (heavy atom distances only) or SQL_ALL (all atoms are considered when determining pair distance)

Return type:

int

Returns:

The number of dimers found

initializeDatabase()

Should be overwritten by child classes to create the tables

schrodinger.application.matsci.kmc.sql_command(cursor, cmd)

Perform the given command without closing the cursor or saving the results to the database

Parameters:
  • cursor (sqlite3.Cursor) – The cursor used

  • cmd (str) – The SQL command to perform

Return type:

bool

Returns:

True if the command executed, False if the command raised a no such table error

Raises:

sqlite3.OperationalError – in unknown circumstances

schrodinger.application.matsci.kmc.table_rows(db_path, table, orderby=None)

Generator for all the rows in a specific table of the database

Parameters:
  • db_path (str or pathlib.Path) – The path to the database

  • table (str) – The name of the table to get the rows for

Return type:

sqlite3.Row

Returns:

Yields each row in the table

schrodinger.application.matsci.kmc.delete_all_rows(db_path, table)

Delete all the rows in this table

Parameters:
  • db_path (str or pathlib.Path) – The path to the database

  • table (str) – The name of the table to get the rows for

schrodinger.application.matsci.kmc.is_no_table_error(exc)

Detect if this exception is due to the requested table not existing

Parameters:

exc (Exception) – The Exception to check

Return type:

bool

Returns:

Whether this exception is for a missing table

schrodinger.application.matsci.kmc.add_schrodinger_column(db_path, name)

Add a column to the schrodinger table. This may be needed if the SQL file was created with an older version that didn’t include this column

Parameters:
  • db_path (str or pathlib.Path) – The path to the SQL file

  • name (str) – The name of the column, must be a key in SchrodingerTable.COLUMNS

Raises:
  • DuplicateColumnError – If the column already exists

  • KeyError – If name is not a SchrodingerTable column name

exception schrodinger.application.matsci.kmc.DuplicateColumnError

Bases: OperationalError

Specific to trying to ADD COLUMN when one already exists

schrodinger.application.matsci.kmc.add_column(cursor, table_name, col_name, extra_sql=None)

Add a column to a given database using the given cursor.

Parameters:
  • cursor (sqlite3.Cursor) – The cursor to use for database read/writes

  • table_name (str) – The name of the table to add a column to

  • col_name (str) – The name of the new column

  • extra_sql (str or None) – Optional additional text to add to the sql command, for example, “REAL DEFAULT ‘0.0’”

Raises:

DuplicateColumnError – If the column already exists in the table

schrodinger.application.matsci.kmc.get_dimer_com_sep(dimer, struct)

Get the centroid separation vector for a dimer taking into account periodic boundaries.

Parameters:
Return type:

tuple(float, float, float)

Returns:

the x, y, and z components of the centroid separation between the dimer molecules, taking into account PBC.

schrodinger.application.matsci.kmc.pairs_table_has_com(db_path)

Check if the pairs table has COM distance columns or not. This is useful for validating both GUI and driver and as a check before calling add_com_to_pairs_table.

Parameters:

db_path (str) – The path to the SQL file

Return type:

bool

Returns:

True if the pairs table in the db already has COM_DX,Y,Z cols, otherwise False

schrodinger.application.matsci.kmc.matsci_pairs_table_has_periodic_z(db_path)

Check if the pairs table has PERIODIC_Z column or not. This is useful for validating / detecting outdated database.

Parameters:

db_path (str) – The path to the SQL file

Return type:

bool

Returns:

True if the pairs table in the db has PERIODIC_Z col, otherwise False

schrodinger.application.matsci.kmc.missing_periodic_z_msg(db_path)

Get the error message to send to the user about missing PERIODIC_Z column.

Parameters:

db_path – The path to the SQL file

Return type:

str

Returns:

The message to send to the user about missing PERIODIC_Z column.

schrodinger.application.matsci.kmc.add_com_to_pairs_table(db_path, struct=None)

Add center of mass (COM) distance to pairs table.

This function can work in one of two ways: provide a struct if one is available, or if a struct is not available, set struct=None and the necessary data will be gathered if available from the existing database tables.

Parameters:
  • db_path (str) – The path to the SQL file

  • struct (Structure) – the structure with associated PBC and molecule information. If None, the PBC and molecule information will be obtained from the database, if it is available.

schrodinger.application.matsci.kmc.set_schrodinger_db_value(db_path, name, value)

Set the value of the given column in the Schrodinger table.

Parameters:
  • db_path (str or pathlib.Path) – The path to the SQL file

  • name (str) – The name of the column, must be a key in SchrodingerTable.COLUMNS

  • value – The value to put into the database. The type of the parameter should be consistent with the expected type for that column.

schrodinger.application.matsci.kmc.store_schrodinger_job_props(db_path, mae_name, struct)

Store Schrodinger information about the current job in the database

Parameters:
  • db_path (str or pathlib.Path) – The path to the SQL file

  • mae_name (str) – The name of the Maestro file that will hold the structure

  • struct (schrodinger.structure.Structure) – The structure to add corresponding job info props to

schrodinger.application.matsci.kmc.get_schrodinger_db_value(db_path, name)

Get the value for the given column from the Schrodinger table in the database

Parameters:
  • db_path (str or pathlib.Path) – The path to the SQL file

  • name (str) – The name of the column to get the data from

Return type:

variable or None

Returns:

The value for the given column in the Schrodinger table, or None if no such table exists or no such column exists

schrodinger.application.matsci.kmc.get_db_structure_path(db_path, existence_check=True)

Get the path to the structure that created this database

Parameters:
  • db_path (str or pathlib.Path) – The path to the SQL file

  • existence_check (bool) – If True, return None if the path in the database does not point to an existing file. If False, return the path regardless of whether the file exists.

Return type:

pathlib.Path or None

Returns:

The Path to the structure file, or None if no path is found in the database or existence_check=True and the file does not exist

schrodinger.application.matsci.kmc.add_pairs_to_database(struct, path, dist, pair_type='heavy')

Find all dimers in the given structure based on the normal Schrodinger dimer finding algorithm. Add all found dimers to the given SQL file.

Parameters:
  • struct (schrodinger.structure.Structure) – The structure with the pairs

  • path (str) – The path to the SQL database

  • dist (float) – The distance threshold for defining dimers

  • pair_type (str) – Either SQL_HEAVY (heavy atom distances only) or SQL_ALL (all atoms are considered when determining pair distance)

Return type:

int

Returns:

The number of dimers found

schrodinger.application.matsci.kmc.get_pairs_from_database(db_path)

Get the pairs from the database

Parameters:

db_path (str or pathlib.Path) – The path to the SQL file

Return type:

list

Returns:

Each item of the list is a schrodinger.application.matsci.clusterstruct.Dimer object. The list is empty if the pairs table has not been populated. Note that the Dimer objects will not have set the home_atom or neighbor_atom properties of the neighbor_info property.

schrodinger.application.matsci.kmc.has_pair_data(db_path)

Check if the database has pair data

Parameters:

db_path (str or pathlib.Path) – The path to the database

Return type:

bool or str

Returns:

If no data, False. If data, the distance type used to find pairs - either SQL_HEAVY or SQL_ALL

schrodinger.application.matsci.kmc.get_pair_info(db_path)

Get the parameters used to determine the existing pairs in the database

Parameters:

db_path (str or pathlib.Path) – The path to the database

Return type:

(str, float) or None

Returns:

The type of distance used to find pairs (SQL_HEAVY or SQL_ALL) and the distance cutoff for pairs. None is returned if no pair data exists.

schrodinger.application.matsci.kmc.is_supported_kmc_database(db_path)

Get whether the database uses the expected KMC SQL format. Returns False if the Schrodinger metadata table is missing or neither a retained KMC sites schema nor a retained KMC pairs schema exists in the database.

Parameters:

db_path (str) – The path to database file

Return bool:

Whether the database uses the expected KMC SQL format

schrodinger.application.matsci.kmc.get_table_columns(db_path, table_name)

Get the column names for a table in an SQL database.

Parameters:
  • db_path (str) – The path to database file

  • table_name (str) – The table name

Return type:

set(str)

Returns:

The column names in the table

schrodinger.application.matsci.kmc.validate_kmc_database(db_path)

Validate that a database uses the expected KMC SQL format.

Parameters:

db_path (str) – The path to database file

Raises:

ValueError – If the database is not in the expected format

schrodinger.application.matsci.kmc.get_sites_table(db_path)

Get the sites table class for the sql file

Parameters:

db_path (str) – The path to sql file

Return type:

MatSciSitesTable

Returns:

The sites table class

schrodinger.application.matsci.kmc.get_pairs_table(db_path)

Get the pairs table class for the sql file

Parameters:

db_path (str) – The path to sql file

Return type:

MatSciPairsTable

Returns:

The pairs table class

exception schrodinger.application.matsci.kmc.MissingDataError

Bases: Exception

Raised if missing data is detected in database

schrodinger.application.matsci.kmc.check_missing_data(db_path, charges, only_pairs=False)

Function that raises MissingDataError if data is missing, for validation

Parameters:
  • db_path (str) – The path to the sql file

  • charges (list[str]) – The charges to check for

  • only_pairs (bool) – Only check pair data, not site. Use for ml hopping parameter workflow.

Raises:

MissingDataError if missing data is detected

schrodinger.application.matsci.kmc.find_missing_coupling_data(path, charge)

Find any pair couplings that are 0

Parameters:
  • path (str) – The path to the database file

  • charge (str) – Either HOLE or ELECTRON

Return type:

list

Returns:

Each item is a tuple with the molecule numbers of the two molecules involved in the missing coupling term.

schrodinger.application.matsci.kmc.find_missing_lambda_data(path, charge)

Find any pair lambdas that are 0

Parameters:
  • path (str) – The path to the database file

  • charge (str) – Either HOLE or ELECTRON

Return type:

list

Returns:

Each item is a tuple with the molecule numbers of the two molecules involved in the missing lambda term.

schrodinger.application.matsci.kmc.find_missing_site_energies(path, charge)

Find any segment that has any site energy property equal to 0

Parameters:
  • path (str) – The path to the database file

  • charge (str) – Either HOLE or ELECTRON

Return type:

list

Returns:

Each item is the integer SQID (which translates to molecule number) of any segment with missing site energy information

schrodinger.application.matsci.kmc.copy_rates_csv_to_db(db_path, e12_csv=None, e21_csv=None, h12_csv=None, h21_csv=None)

Copy rates from formatted rates csv file from ML workflow to sql database

Parameters:
  • db_path (str) – the path to the database sql file

  • e12_csv (Optional[str]) – the path to the electron 12 rate csv file

  • e21_csv (Optional[str]) – the path to the electron 21 rate csv file

  • h12_csv (Optional[str]) – the path to the hole 12 rate csv file

  • h21_csv (Optional[str]) – the path to the hole 21 rate csv file

schrodinger.application.matsci.kmc.get_h_pair_rates_from_database(db_path)

Get the hole hopping rates from the database

Parameters:

db_path (str or pathlib.Path) – The path to the SQL file

Return type:

dict (key: tuple(int,int). val: float)

Returns:

Dictionary where the key is the directed pair of site indices (source site, destination site) the val is the hole hopping rate in that direction

schrodinger.application.matsci.kmc.get_e_pair_rates_from_database(db_path)

Get the electron hopping rates from the database. Note: site indexes here are 1-indexed, taken directly from the database.

Parameters:

db_path (str or pathlib.Path) – The path to the SQL file

Return type:

dict (key: tuple(int,int). val: float)

Returns:

Dictionary where the key is the directed pair of site indices (source site, destination site), the val is the electron hopping rate in that direction

schrodinger.application.matsci.kmc.get_pair_rates_from_database(db_path, particle_type='h')

Get the hopping rates from the database. Note: site indexes here are 1-indexed, taken directly from the database.

Parameters:
  • db_path (str or pathlib.Path) – The path to the SQL file

  • particle_type (str) – H_ENDING for hole, or E_ENDING for electron

Return type:

dict (key: tuple(int,int). val: float)

Returns:

Dictionary where the key is the directed pair of site indices (source site, destination site), the val is the hopping rate in that direction

schrodinger.application.matsci.kmc.copy_sql_data(source, destination, table, columns)

Copy the column from table in the source database to the destination database

Parameters:
  • source (str or pathlib.path) – the path to the source database

  • destination (str or pathlib.path) – the path to the destination database

  • table (str) – The name of the table to copy from

  • columns (list) – A list of column names to copy

Raises:
  • IndexError – If the two databases do not have the same number of rows

  • DuplicateColumnError – If new_cals=True is used but the cols already exist in the destination table

schrodinger.application.matsci.kmc.set_column_constant(db_path, table, column, constant)

Set all rows of a given column to the value constant.

Caution: this loses all current data in that column.

Parameters:
  • db_path (str) – The path to the SQL file

  • table (str) – The name of the table to copy from

  • column (str) – The name of the column

  • constant (float or str) – The value to set

exception schrodinger.application.matsci.kmc.SQLCreationError

Bases: Exception

Raised if an issue occurs when creating the database

schrodinger.application.matsci.kmc.generate_kmc_database(struct, backend=None)

Create a KMC SQL database and include data on species and pairs.

Parameters:
  • struct (schrodinger.structure.Structure) – The structure to create a database for

  • backend (scschrodigner.job.jobcontrol._Backend) – The backend if one exists

Return type:

str

Returns:

The name of the sql file that was created

Raises:

SQLCreationError – If the sql file can’t be created

class schrodinger.application.matsci.kmc.MatSciSitesTable(filename)

Bases: Table

Sites table for KMC databases

TABLE_NAME = 'sites'
HAS_E = 'has_e'
HAS_H = 'has_h'
OCCPE = 'occPe'
OCCPH = 'occPh'
OCCP_SING = 'occP_singlet'
OCCP_TRIP = 'occP_triplet'
INJECTS_E = 'injects_e'
INJECTS_H = 'injects_h'
E_INJECTIONS = 'e_injections'
H_INJECTIONS = 'h_injections'
E_ANNIHILIATIONS = 'e_annihilations'
H_ANNIHILIATIONS = 'h_annihilations'
RAD_DECAYS = 'radiative_decays'
NONRAD_DECAYS = 'nonradiative_decays'
CURRENT_MAGNITUDE_E = 'current_magnitude_e'
CURRENT_X_E = 'current_x_e'
CURRENT_Y_E = 'current_y_e'
CURRENT_Z_E = 'current_z_e'
CURRENT_MAGNITUDE_H = 'current_magnitude_h'
CURRENT_X_H = 'current_x_h'
CURRENT_Y_H = 'current_y_h'
CURRENT_Z_H = 'current_z_h'
COLUMNS = {'UcCnNe': ColumnData(type='REAL', default=0), 'UcCnNh': ColumnData(type='REAL', default=0), 'UcNcCe': ColumnData(type='REAL', default=0), 'UcNcCh': ColumnData(type='REAL', default=0), 'UnCnNe': ColumnData(type='REAL', default=0), 'UnCnNh': ColumnData(type='REAL', default=0), 'current_magnitude_e': ColumnData(type='REAL', default=0), 'current_magnitude_h': ColumnData(type='REAL', default=0), 'current_x_e': ColumnData(type='REAL', default=0), 'current_x_h': ColumnData(type='REAL', default=0), 'current_y_e': ColumnData(type='REAL', default=0), 'current_y_h': ColumnData(type='REAL', default=0), 'current_z_e': ColumnData(type='REAL', default=0), 'current_z_h': ColumnData(type='REAL', default=0), 'e_annihilations': ColumnData(type='INT', default=0), 'e_injections': ColumnData(type='INT', default=0), 'h_annihilations': ColumnData(type='INT', default=0), 'h_injections': ColumnData(type='INT', default=0), 'has_e': ColumnData(type='INT', default=0), 'has_h': ColumnData(type='INT', default=0), 'id': ColumnData(type='INT', default=None), 'injects_e': ColumnData(type='INT', default=0), 'injects_h': ColumnData(type='INT', default=0), 'mol': ColumnData(type='INT', default=None), 'name': ColumnData(type='TEXT', default=None), 'nonradiative_decays': ColumnData(type='INT', default=0), 'occP_singlet': ColumnData(type='REAL', default=-1), 'occP_triplet': ColumnData(type='REAL', default=-1), 'occPe': ColumnData(type='REAL', default=-1), 'occPh': ColumnData(type='REAL', default=-1), 'posX': ColumnData(type='REAL', default=None), 'posY': ColumnData(type='REAL', default=None), 'posZ': ColumnData(type='REAL', default=None), 'radiative_decays': ColumnData(type='INT', default=0), 'type': ColumnData(type='TEXT', default=None)}
REQUIRED_COLUMNS = {'UcCnNe', 'UcCnNh', 'UcNcCe', 'UcNcCh', 'UnCnNe', 'UnCnNh', 'has_e', 'has_h', 'id', 'injects_e', 'injects_h', 'mol', 'name', 'occPe', 'occPh', 'posX', 'posY', 'posZ', 'type'}
addRow(molecule)

Add a row

Parameters:

molecule (schrodinger.structure._StructureMolecule) – The molecule object to add a row for

class schrodinger.application.matsci.kmc.MatSciPairsTable(filename)

Bases: Table

Pairs table for KMC databases

TABLE_NAME = 'pairs'
SITE1 = 'site1'
SITE2 = 'site2'
DRX = 'drx'
DRY = 'dry'
DRZ = 'drz'
COM_DRX = 'com_drx'
COM_DRY = 'com_dry'
COM_DRZ = 'com_drz'
PERIODIC_Z = 'periodic_z'
RATE12E = 'rate12e'
RATE21E = 'rate21e'
RATE12H = 'rate12h'
RATE21H = 'rate21h'
JEFF2_12E = 'Jeff2_12e'
JEFF2_21E = 'Jeff2_21e'
JEFF2_12H = 'Jeff2_12h'
JEFF2_21H = 'Jeff2_21h'
LAMBDA_12E = 'Lambda_12e'
LAMBDA_21E = 'Lambda_21e'
LAMBDA_12H = 'Lambda_12h'
LAMBDA_21H = 'Lambda_21h'
DELTAE_12E = 'DeltaE_12e'
DELTAE_21E = 'DeltaE_21e'
DELTAE_12H = 'DeltaE_12h'
DELTAE_21H = 'DeltaE_21h'
JUMPS_12E = 'Jumps_12e'
JUMPS_21E = 'Jumps_21e'
JUMPS_12H = 'Jumps_12h'
JUMPS_21H = 'Jumps_21h'
COUPLING_COLUMNS = {'electron': ['Jeff2_12e', 'Jeff2_21e'], 'hole': ['Jeff2_12h', 'Jeff2_21h']}
LAMBDA_COLUMNS = {'electron': ['Lambda_12e', 'Lambda_21e'], 'hole': ['Lambda_12h', 'Lambda_21h']}
DELTAE_COLUMNS = {'electron': ['DeltaE_12e', 'DeltaE_21e'], 'hole': ['DeltaE_12h', 'DeltaE_21h']}
JUMP_COLUMNS = {'electron': ['Jumps_12e', 'Jumps_21e'], 'hole': ['Jumps_12h', 'Jumps_21h']}
RATE_COLUMNS = {'electron': ['rate12e', 'rate21e'], 'hole': ['rate12h', 'rate21h']}
COLUMNS = {'DeltaE_12e': ColumnData(type='REAL', default=0), 'DeltaE_12h': ColumnData(type='REAL', default=0), 'DeltaE_21e': ColumnData(type='REAL', default=0), 'DeltaE_21h': ColumnData(type='REAL', default=0), 'Jeff2_12e': ColumnData(type='REAL', default=0), 'Jeff2_12h': ColumnData(type='REAL', default=0), 'Jeff2_21e': ColumnData(type='REAL', default=0), 'Jeff2_21h': ColumnData(type='REAL', default=0), 'Jumps_12e': ColumnData(type='INT', default=0), 'Jumps_12h': ColumnData(type='INT', default=0), 'Jumps_21e': ColumnData(type='INT', default=0), 'Jumps_21h': ColumnData(type='INT', default=0), 'Lambda_12e': ColumnData(type='REAL', default=0), 'Lambda_12h': ColumnData(type='REAL', default=0), 'Lambda_21e': ColumnData(type='REAL', default=0), 'Lambda_21h': ColumnData(type='REAL', default=0), 'com_drx': ColumnData(type='REAL', default=None), 'com_dry': ColumnData(type='REAL', default=None), 'com_drz': ColumnData(type='REAL', default=None), 'drx': ColumnData(type='REAL', default=None), 'dry': ColumnData(type='REAL', default=None), 'drz': ColumnData(type='REAL', default=None), 'id': ColumnData(type='INT', default=None), 'periodic_z': ColumnData(type='INT', default=None), 'rate12e': ColumnData(type='REAL', default=0), 'rate12h': ColumnData(type='REAL', default=0), 'rate21e': ColumnData(type='REAL', default=0), 'rate21h': ColumnData(type='REAL', default=0), 'site1': ColumnData(type='INT', default=None), 'site2': ColumnData(type='INT', default=None)}
REQUIRED_COLUMNS = {'DeltaE_12e', 'DeltaE_12h', 'DeltaE_21e', 'DeltaE_21h', 'Jeff2_12e', 'Jeff2_12h', 'Jeff2_21e', 'Jeff2_21h', 'Jumps_12e', 'Jumps_12h', 'Jumps_21e', 'Jumps_21h', 'Lambda_12e', 'Lambda_12h', 'Lambda_21e', 'Lambda_21h', 'drx', 'dry', 'drz', 'id', 'rate12e', 'rate12h', 'rate21e', 'rate21h', 'site1', 'site2'}
addRow(index, dimer, struct)

Add a row to the table

Parameters:
classmethod setRowValues(mols, val_dict, cursor)

Set the values of columns in the row for the given pair of molecules

Parameters:
  • mols (iterable) – The two mol numbers involved in this pair

  • val_dict (dict) – Dict mapping column names to their values

  • cursor (sqlite3.Cursor) – The cursor to use

Raises:

RuntimeError – If value has spaces

class schrodinger.application.matsci.kmc.MatSciDatabaseManager(struct, filename)

Bases: BaseDatabaseManager

Database manager for KMC databases

TABLE_CLASSES = (<class 'schrodinger.application.matsci.kmc.MatSciSitesTable'>, <class 'schrodinger.application.matsci.kmc.MatSciPairsTable'>, <class 'schrodinger.application.matsci.kmc.SchrodingerTable'>)
SITES_TABLE

alias of MatSciSitesTable

PAIRS_TABLE

alias of MatSciPairsTable

initializeDatabase()

Create all the tables and fill all but the pairs table with initial data

fillSites()

Fill the sites table

schrodinger.application.matsci.kmc.add_charge_flag(parser)

Add the charge flag to the parser

Parameters:

parser (parserutils.DriverParser or argparse._ArgumentGroup) – The parser or argument group to add the flag to

schrodinger.application.matsci.kmc.add_kmc_flags(parser)

Add KMC flags to the parser

Parameters:

parser (parserutils.DriverParser or argparse._ArgumentGroup) – The parser or argument group to add the flag to

schrodinger.application.matsci.kmc.type_field(value)

Type the field command line parameter

Parameters:

value (str) – The command line field parameter

Return type:

list of tuple

Returns:

Each item of the list is (X, Y, Z) field strengths in MV/m for one field. Field strengths are floats.

Raises:

argparse.ArgumentTypeError – If the argument cannot be converted to a length 3 list of floats

schrodinger.application.matsci.kmc.get_msd_fit_type_for_field(fit_type, field)

Return the applicable MSD fit type for a field.

Parameters:
  • fit_type (str) – The requested MSD fit type

  • field (list(float) or tuple(float) or numpy.ndarray) – The electric field vector

Return type:

str

Returns:

A linear fit at zero field, otherwise the requested fit type

schrodinger.application.matsci.kmc.get_msd_fit_types_for_fields(fit_type, fields)

Return the applicable MSD fit type for each field.

Parameters:
  • fit_type (str) – The requested MSD fit type

  • fields (list(list(float))) – The electric field vectors

Return type:

list(str)

Returns:

The applicable polynomial fit types in field order

schrodinger.application.matsci.kmc.get_msd_fit_fields_case(fit_type, fields)

Classify how fields affect the requested MSD fit type.

Parameters:
  • fit_type (str or None) – The requested MSD fit type

  • fields (list(list(float))) – The electric field vectors

Return type:

str

Returns:

One of the MSD_FIT_FIELDS constants

schrodinger.application.matsci.kmc.get_sql_output_name(jobname)

Get the name of the SQL file that will be created

Parameters:

jobname (str) – The name of the job

Return type:

str

Returns:

The name the output sql file will have

schrodinger.application.matsci.kmc.get_db_table_length(db_path, table)

Get the number of rows in the given table

Parameters:
  • db_path (str) – The path to the database

  • table (str) – The name of the table

Return int:

The number of rows

schrodinger.application.matsci.kmc.form_set_val_string(val_dict)

Create the string to set multiple values in a sql row

Parameters:

val_dict (dict) – Dict mapping column names to their values

Return str:

The string to put in sql comand

schrodinger.application.matsci.kmc.get_num_missing_data(sql_file, charge)

Get the number of missing sites and coupling data

Parameters:
  • sql_file (str) – The path to the sql file

  • charge (str) – The charge to check for

Return type:

tuple of int

Returns:

The number of missing sites and couplings

schrodinger.application.matsci.kmc.add_msd_arguments(parser, write_trajs=False, calc_msd=False)

Add the command line flags for the MSD(t).

Parameters:
  • parser (argparse.ArgumentParser) – parser to add the arguments to

  • write_trajs (bool) – if True then add the option to write a csv of the trajectories for each charge

  • calc_msd (bool) – if True then add the option to calculate MSD(t)

schrodinger.application.matsci.kmc.log(logger, msg, pad_above=False, pad_below=False)

Log a message.

Parameters:
  • logger (logging.Logger or None) – output logger or None if there isn’t one

  • msg (str) – the message

  • pad_above (bool) – if True then add a blank line before the message

  • pad_below (bool) – if True then add a blank line after the message

schrodinger.application.matsci.kmc.validate_time_bin_params(n_t_bins, fit_bin_if, fit_type)

Validate the time bin parameters.

Parameters:
  • n_t_bins (int) – the number of time bins

  • fit_bin_if (list[int]) – initial and final bin indices over which to fit the MSD(t)

  • fit_type (str) – module constant LINEAR, QUADRATIC, or MEAN_VARIANCE. If LINEAR, fit the MSD(t) to the equation derived from the diffusion model. If QUADRATIC, fit to that from the drift-diffusion model. If MEAN_VARIANCE, independently linear fit the mean displacement and displacement variance.

Raises:

ValueError – if invalid

exception schrodinger.application.matsci.kmc.MSDFitException

Bases: Exception

schrodinger.application.matsci.kmc.fit_polynomial_time_series(times, values, degree)

Fit time-series values to a polynomial.

Parameters:
  • times (numpy.array) – Time values (s)

  • values (numpy.array) – Displacement-derived property values corresponding to times (m or m^2)

  • degree (int) – Polynomial degree

Return type:

tuple(numpy.array, float)

Returns:

Polynomial coefficients in descending order, with units derived from the property units and polynomial order, and the dimensionless coefficient of determination

schrodinger.application.matsci.kmc.calculate_r_squared(values, fit_values)

Calculate the coefficient of determination for fitted values.

Parameters:
  • values (numpy.array) – Observed values

  • fit_values (numpy.array) – Values predicted by the fit

Return type:

float

Returns:

The dimensionless coefficient of determination

schrodinger.application.matsci.kmc.validate_matching_times(reference_times, other_times, description, exception_class)

Validate that two time arrays match exactly.

Parameters:
  • reference_times (numpy.array) – Reference times (s)

  • other_times (numpy.array) – Times (s) to compare with the reference

  • description (str) – Description used to identify the compared series

  • exception_class (type) – Exception class to raise when the times differ

Raises:

Exception – If the time arrays differ

class schrodinger.application.matsci.kmc.TimeSeriesFit(msd_info, logger=None)

Bases: object

Base class for displacement-derived time-series fits.

__init__(msd_info, logger=None)
Parameters:
  • msd_info (MSDInfo) – the MSDInfo containing the data to fit and fit parameters

  • logger (logging.Logger or None) – output logger or None if there isn’t one

log(msg, pad_above=False, pad_below=False)

Log a message.

Parameters:
  • msg (str) – the message

  • pad_above (bool) – if True then add a blank line before the message

  • pad_below (bool) – if True then add a blank line after the message

getSliceToFit(data_by_t)

Return the requested slice of time-series points to fit.

Parameters:

data_by_t (list[tuple]) – Time (s) and displacement-derived property pairs

Return type:

list[tuple]

Returns:

Time (s) and displacement-derived property pairs to fit

validate()

Validate the input.

Raises:

MSDFitException – if invalid

runRawPolyFit(times, values, degree, property_name, property_units)

Run the raw numpy polynomial fit, by raw it means the input data as is.

Parameters:
  • times (numpy.array) – Time (s)

  • values (numpy.array) – Displacement-derived property values (m or m^2)

  • degree (int) – Polynomial degree

  • property_name (str) – Property name used for error messages

  • property_units (str) – Property units used for logging

Raises:

MSDFitException – if fitting fails

Return type:

numpy.array, float

Returns:

Fit coefficients in property_units/s^n, where n is the coefficient order, and the dimensionless R^2 value. A quadratic fit has quadratic, linear, and constant coefficients; a linear fit has linear and constant coefficients.

checkFit(coefficients, r_squared, property_name=None, warn_on_negative_coefficient=False)

Return a warning describing a poor polynomial fit, if any.

Parameters:
  • coefficients (numpy.array) – Fit coefficients ordered from highest to lowest polynomial degree

  • r_squared (float) – Dimensionless R-squared value

  • property_name (str or None) – Property name to include in the warning, or None

  • warn_on_negative_coefficient (bool) – Whether a negative leading coefficient should produce a warning

Return type:

str

Returns:

Warning message, or an empty string for an acceptable fit

logWarning(message)

Log a warning when a logger is available.

Parameters:

message (str) – Warning message

class schrodinger.application.matsci.kmc.MSDFit(msd_info, logger=None)

Bases: TimeSeriesFit

Fit an MSD time series to a linear or quadratic polynomial.

runRawFit()

Run the raw fit, by raw it means the input data as is, and set attributes for the linear and quadratic coefficients of the fit as well as the fit MSD(t).

class schrodinger.application.matsci.kmc.MeanVarianceFit(msd_info, logger=None)

Bases: TimeSeriesFit

Independently fit mean displacement and displacement variance.

validate()

Validate the input time series.

Raises:

MSDFitException – if the input is invalid

runRawLinearFit(property_by_t, property_name, property_units, warn_on_negative_slope=False)

Linearly fit a displacement-derived property versus time.

Parameters:
  • property_by_t (list[tuple]) – Time (s) and property value pairs

  • property_name (str) – Property name used for logging

  • property_units (str) – Property units used for logging

  • warn_on_negative_slope (bool) – Whether to warn when the fitted slope is negative

Return type:

tuple(numpy.array, numpy.array, float, float)

Returns:

Fit times (s), fitted property values in property_units, fitted slope in property_units/s, and the dimensionless R^2 value

Raises:

MSDFitException – if fitting fails

runRawFit()

Fit the mean displacement and displacement variance time series.

schrodinger.application.matsci.kmc.get_vector_time_series_by_time(data_frame, column_template, optional=False)

Return vector values by time from a displacement diagnostic data frame.

Parameters:
  • data_frame (pandas.DataFrame) – Displacement diagnostic data

  • column_template (str) – Column-name template containing a {c} placeholder for an x, y, or z component. Vector units are encoded in the template.

  • optional (bool) – Whether to return None when all component columns are absent

Return type:

list(tuple) or None

Returns:

Time (s) and three-component vector-value pairs, or None when an optional series is absent

Raises:

ValueError – If a required series is absent or only some component columns are present

schrodinger.application.matsci.kmc.get_component_time_series(vector_by_time, axis_index)

Return one component of a vector time series.

Parameters:
  • vector_by_time (list(tuple) or None) – Time (s) and vector-value pairs, or None. Value units are retained from the input series.

  • axis_index (int) – Vector component index, 0-based

Return type:

list(tuple) or None

Returns:

Time (s) and scalar component-value pairs, or None

schrodinger.application.matsci.kmc.get_fit_r_squared(data_by_t, fit_data_by_t, fit_bin_i, fit_bin_f)

Calculate R^2 for a stored fit time series.

Parameters:
  • data_by_t (list[tuple] or None) – The observed time series

  • fit_data_by_t (list[tuple] or None) – The fitted time series, containing the fit range

  • fit_bin_i (int) – The first fitted time-bin index, 1-based. Ignored when the observed series contains only the two overall-method data points.

  • fit_bin_f (int) – The final fitted time-bin index, 1-based and inclusive

Return type:

float or None

Returns:

The dimensionless R^2 value, or None when the stored fit cannot be matched to the observed data

schrodinger.application.matsci.kmc.get_sds_by_t(msd_fn)

Return the square displacement components by time.

Parameters:

msd_fn (str) – the MSD file name

Return type:

list[tuple]

Returns:

each tuple contains a time (s) and a numpy.array of square displacement components (m^2)

schrodinger.application.matsci.kmc.get_msd_infos(msd_file_summary_fp)

Return a dictionary of MSDInfo.

Parameters:

msd_file_summary_fp (str) – the MSD file summary file path

Return type:

dict

Returns:

dictionary of MSDInfo, keyed by field string first, charge index second, and component third, values of the innermost dictionary are MSDInfo

schrodinger.application.matsci.kmc.get_overall_drift_velocities(msd_file_summary_fp)

Return a dictionary of overall drift velocities (final displacement / final time) in m/s.

Parameters:

msd_file_summary_fp (str) – the MSD file summary file path

Return type:

dict

Returns:

dictionary of overall drift velocities (final displacement / final time) in m/s, keyed by field string first and charge index (1-based) second, values of the innermost dictionary are numpy.array

schrodinger.application.matsci.kmc.get_temperature(msd_file_summary_fp)

Return the temperature.

Parameters:

msd_file_summary_fp (str) – the MSD file summary file path

Return type:

float or None

Returns:

the temperature in K, or None if it can’t be found

schrodinger.application.matsci.kmc.get_charge_sign(msd_file_summary_fp)

Return the charge sign.

Parameters:

msd_file_summary_fp (str) – the MSD file summary file path

Return type:

int or None

Returns:

the charge sign, or None if it can’t be found

schrodinger.application.matsci.kmc.calc_diffusion_tensor(msd_infos)

Calculate the diffusion tensor (m^2/s).

Parameters:

msd_infos (dict[str]=MSDInfo) – the MSDInfo keyed by MSD component

Return type:

numpy.array

Returns:

the diffusion tensor (m^2/s)

schrodinger.application.matsci.kmc.calc_drift_velocity(msd_infos)

Calculate the drift velocity (m/s).

Parameters:

msd_infos (dict[str]=MSDInfo) – the MSDInfo keyed by MSD component

Return type:

numpy.array

Returns:

the drift velocity (m/s)

schrodinger.application.matsci.kmc.carrier_avg_diffusion_tensor(all_msd_infos)

Calculate the diffusion tensor averaged over carriers (m^2/s).

Parameters:

all_msd_infos (dict[int]=dict[str]=MSDInfo) – the MSDInfo keyed by carrier index and MSD component

Return type:

numpy.array

Returns:

the diffusion tensor averaged over carriers (m^2/s)

schrodinger.application.matsci.kmc.carrier_avg_drift_velocity(all_msd_infos)

Calculate the drift velocity averaged over carriers (m/s).

Parameters:

all_msd_infos (dict[int]=dict[str]=MSDInfo) – the MSDInfo keyed by carrier index and MSD component

Return type:

numpy.array

Returns:

the drift velocity averaged over carriers (m/s)

schrodinger.application.matsci.kmc.calc_mobility_tensor_from_diffusion(temperature, msd_infos)

Calculate the mobility tensor (cm^2/Vs) from the diffusion tensor.

Parameters:
  • temperature (float) – temperature in K

  • msd_infos (dict[str]=MSDInfo) – the MSDInfo keyed by MSD component

Return type:

numpy.array

Returns:

the mobility tensor (cm^2/Vs)

schrodinger.application.matsci.kmc.get_field_axis_index(field)

Return the index of the field axis with the greatest magnitude.

KMC field vectors have at most one nonzero component, and every nonzero field has exactly one nonzero component. A zero field uses axis 0 by convention.

Parameters:

field (list(float) or tuple(float) or numpy.ndarray) – The electric field vector

Return type:

int

Returns:

The zero-based field axis index

schrodinger.application.matsci.kmc.calc_mobility_tensor_from_drift_velocity(field, charge_sign, msd_infos=None, drift_velocity=None)

Calculate the mobility tensor (cm^2/Vs) from the drift velocity.

Parameters:
  • field (numpy.array) – field in V/nm

  • charge_sign (int) – charge sign

  • msd_infos (dict[str]=MSDInfo or None) – the MSDInfo keyed by MSD component or None if using drift velocity

  • drift_velocity (numpy.array or None) – the drift velocity in m/s or None if using msd_infos

Return type:

numpy.array

Returns:

the mobility tensor (cm^2/Vs)

schrodinger.application.matsci.kmc.carrier_avg_mobility_tensor_from_diffusion(temperature, all_msd_infos)

Calculate the mobility tensor averaged over carriers (cm^2/Vs) using the diffusion tensors.

Parameters:
  • temperature (float) – temperature in K

  • all_msd_infos (dict[int]=dict[str]=MSDInfo) – the MSDInfo keyed by carrier index and MSD component

Return type:

numpy.array

Returns:

the mobility tensor averaged over carriers (cm^2/Vs)

schrodinger.application.matsci.kmc.carrier_avg_mobility_tensor_from_drift_velocity(field, charge_sign, all_msd_infos=None, drift_velocities=None)

Calculate the mobility tensor averaged over carriers (cm^2/Vs) using the drift velocities.

Parameters:
  • field (numpy.array) – field in V/nm

  • charge_sign (int) – charge sign

  • all_msd_infos (dict[int]=dict[str]=MSDInfo or None) – the MSDInfo keyed by carrier index and MSD component or None if using drift velocities

  • drift_velocities (dict[int]=numpy.array or None) – keys are carrier index (1-based), values are drift velocity in m/s or None if using all_msd_infos

Return type:

numpy.array

Returns:

the mobility tensor averaged over carriers (cm^2/Vs)

schrodinger.application.matsci.kmc.carrier_avg_tensors(tensors)

Return the carrier average of the given tensors.

Parameters:

tensors (list[numpy.array]) – the tensors to average

Return type:

float

Returns:

the carrier average

schrodinger.application.matsci.kmc.isotropic_avg_tensor(tensor)

Return the isotropic average of the given tensor.

Parameters:

tensor (numpy.array) – the tensor to average

Return type:

float

Returns:

the isotropic average

exception schrodinger.application.matsci.kmc.MSDVariableTimeStepException

Bases: Exception

class schrodinger.application.matsci.kmc.DisplacementMomentAccumulator

Bases: object

Accumulate time and displacement moments for one time bin.

__init__()
addSample(time, displacement)

Add a sampled lag time and displacement vector.

Parameters:
  • time (float) – Sampled lag time (s)

  • displacement (numpy.array) – Signed displacement components (m)

getVariance()

Return the population variance of each displacement component.

Return type:

numpy.array or None

Returns:

Displacement component variances (m^2), or None if no samples have been accumulated

getMeanSquareDisplacement()

Return the mean square displacement components.

Return type:

numpy.array or None

Returns:

Mean square displacement components (m^2), or None if no samples have been accumulated

class schrodinger.application.matsci.kmc.MSDVariableTimeStep(t_d_by_chg_idx, bin_t=True, n_t_bins=100, acc_t_bin_width=True, lags=None, lag_start=1000, lag_step=1000, n_lags=100, all_lags=False, bin_sd=False, n_sd_bins=20, bin_sd_idxs=None, fit_bin_if=None, fit_type='mean_variance', write_output=True, basename='msd', logger=None)

Bases: object

__init__(t_d_by_chg_idx, bin_t=True, n_t_bins=100, acc_t_bin_width=True, lags=None, lag_start=1000, lag_step=1000, n_lags=100, all_lags=False, bin_sd=False, n_sd_bins=20, bin_sd_idxs=None, fit_bin_if=None, fit_type='mean_variance', write_output=True, basename='msd', logger=None)
Parameters:
  • t_d_by_chg_idx (list[list[tuple]]) – inner lists are time (s) and displacement (m) pair tuples for a given charge index, outer lists are for the different charges, displacement is a numpy.array of xyz components

  • bin_t (bool) – if True then compute the MSD(t) by time binning where its accuracy is controlled by the total number of frames and the lag step; if False then compute the MSD(t) simply using the last frame, using True is more accurate and takes significant compute time, using False is less accurate but fast

  • n_t_bins (int) – the number of time bins, if this number is the total number of frames it is equivalent to the raw data

  • acc_t_bin_width (bool) – if True calculate the time bin width using the minimum and maxium difference in times over all sampled (time, displacement vector) pairs, if False calculate the time bin width using the first time as the minimum time and the last time as the maximum time

  • lags (list[int] or None) – values of the lag at which to sample (time, displacement vector) pairs, see also lag_start and lag_step, if given this parameter takes precedence

  • lag_start (int) – the initial value of the lag, see also lag_step, if both are 1 it is equivalent to sampling all (time, displacement vector) pairs

  • lag_step (int) – the step value of the lag, see also lag_start, if both are 1 it is equivalent to sampling all (time, displacement vector) pairs

  • n_lags (int) – the number of lags to consider when using lag_start and lag_step

  • all_lags (bool) – specifies to use all possible lags with the given lag_start and lag_step, if given takes precedence over n_lags

  • bin_sd (bool) – if True bin square displacement components per time bin, this is used for analysis purposes only and considerably increases calculation time

  • n_sd_bins (int) – the number of square displacement bins, this is the number of square displacement bins per time bin, applies only if bin_sd is True

  • bin_sd_idxs (list[int] or None) – if given then bin square displacement components only for these specific time bins, if None do it for all time bins, doing it for all time bins significantly increases compute time but requires little memory and vice versa for specific time bins, 1-based

  • fit_bin_if (list[int] or None) – initial and final bin indices over which to fit the MSD(t), if not given the initial and final values are 1/5 and 4/5 of the number of time bins so that the middle 3/5 of the values are used in the fit, 1-based

  • fit_type (str) – module constant LINEAR, QUADRATIC, or MEAN_VARIANCE. If LINEAR, fit the MSD(t) to the equation derived from the diffusion model. If QUADRATIC, fit to that from the drift-diffusion model. If MEAN_VARIANCE, independently linear fit the mean displacement and displacement variance.

  • write_output (bool) – if True write output files

  • basename (str) – the basename of any output files

  • logger (logging.Logger or None) – output logger or None if there isn’t one

log(msg, pad_above=False, pad_below=False)

Log a message.

Parameters:
  • msg (str) – the message

  • pad_above (bool) – if True then add a blank line before the message

  • pad_below (bool) – if True then add a blank line after the message

getFitBinIF(fit_bin_if=None)

Return the initial and final time bin indices over which to fit the MSD(t).

Parameters:

fit_bin_if (list[int] or None) – initial and final bin indices over which to fit the MSD(t), if not given the initial and final values are 1/5 and 4/5 of the number of time bins so that the middle 3/5 of the values are used in the fit, 1-based

Return type:

list[int]

Returns:

the initial and final time bin indices

validate()

Validate the input.

Raises:

MSDVariableTimeStepException – if invalid

static getNLags(n_frames, lags, lag_start, lag_step, n_lags, all_lags)

Return the number of lags.

Parameters:
  • n_frames (int) – the number of frames

  • lags (list[int]) – the lags

  • lag_start (int) – the lag start

  • lag_step (int) – the lag step size

  • n_lags (int) – the number of lags

  • all_lags (bool) – if True then consider all possible lags with the given lag_start and lag_step

Return type:

int

Returns:

the number of lags

static getNPairs(n_frames, lags, lag_start, lag_step, n_lags, all_lags)

Return the total number of (time, displacement vector) pairs that will be sampled.

Parameters:
  • n_frames (int) – the number of frames

  • lags (list[int]) – the lags

  • lag_start (int) – the lag start

  • lag_step (int) – the lag step size

  • n_lags (int) – the number of lags

  • all_lags (bool) – if True then consider all possible lags with the given lag_start and lag_step

Raises:

MSDVariableTimeStepException – if invalid

Return type:

int

Returns:

the total number of (time, displacement vector) pairs that will be sampled

static getNPairsMax(n_frames)

Return the maximum number of (time, displacement vector) pairs that can be sampled.

Parameters:

n_frames (int) – the number of frames

Return type:

int

Returns:

the maximum number of (time, displacement vector) pairs that can be sampled

getIdxPairs(chg_idx)

Return generators for all (final index, initial index) pairs.

Parameters:

chg_idx (int) – the charge index, 1-based

Return type:

list[generator]

Returns:

generators for all (final index, initial index) pairs, 0-based

getTimeDispPairs(charge_index)

Yield time and signed displacement component pairs for the given charge index.

Parameters:

charge_index (int) – the charge index, 1-based

Ytype:

tuple

Yield:

Time (float, s) and signed displacement components (numpy.array, m) for the given charge index

getTimeSqDispPairs(chg_idx)

Yield (time (float, s), square displacement components (numpy.array, m^2)) pairs for the given charge index.

Parameters:

chg_idx (int) – the charge index, 1-based

Ytype:

tuple

Yield:

(time (float, s), square displacement components (numpy.array, m^2)) pairs for the given charge index

getTimeBinWidth(chg_idx)

Return the time (s) bin width for the given charge index.

Parameters:

chg_idx (int) – the charge index, 1-based

Return type:

float, float

Returns:

time (s) bin width and minimum value

getTimeBinIdx(time, min_t, t_bin_width)

Return the time bin index.

Parameters:
  • time (float) – time (s)

  • min_t (float) – minimum time (s)

  • t_bin_width (float) – time bin width (s)

Return type:

int

Returns:

the time bin index, 1-based

getSqDispHistograms(chg_idx, t_bin_width, min_t, sd_bin_widths, sd_mins, t_sd_getter=None)

Return for each time bin a histogram of square displacement components.

Parameters:
  • chg_idx (int) – the charge index, 1-based

  • t_bin_width (float) – time (s) bin width for the given charge index

  • min_t (float) – time (s) minimum value for the given charge index

  • sd_bin_widths (list[numpy.array]) – square displacement (m^2) component bin widths for each time bin for the given charge index

  • sd_mins (list[numpy.array]) – square displacements (m^2) component minimum values for for each time bin for the given charge index

  • t_sd_getter (generator[tuple] or None) – yield (time (float, s), square displacement components (numpy.array, m^2)) pairs for which to bin the square displacement components per time bin, if not given, use all available pairs

Return type:

list[tuple]

Returns:

each tuple is for a given time bin, a given tuple first contains binned square displacement (m^2) components and second their corresponding counts

writeCountVsSqDispComps(chg_idx, counts_by_sds)

Write a csv of count versus square displacement for each component.

Parameters:
  • chg_idx (int) – the charge index, 1-based

  • counts_by_sds (list[tuple]) – each tuple is for a given time bin, a given tuple first contains binned square displacement (m^2) components and second their corresponding counts

getTimeBinMoments(charge_index, time_bin_width, minimum_time)

Return the accumulated displacement moments for each time bin.

Parameters:
  • charge_index (int) – the charge index, 1-based

  • time_bin_width (float) – time (s) bin width for the given charge index

  • minimum_time (float) – time (s) minimum value for the given charge index

Return type:

list[DisplacementMomentAccumulator]

Returns:

Displacement moment accumulators for each time bin

getDefinedData(data)

Data is a list of pair tuples where the second element of each tuple can be None which means undefined. Return data with such tuples removed.

Parameters:

data (list[tuple]) – tuples are pair tuples where the second element can be None

Return type:

list[tuple]

Returns:

tuples are pair tuples where the second elements can not be None

getDisplacementMomentTimeSeries(charge_index)

Return the populated displacement-moment time series.

Parameters:

charge_index (int) – Charge index, 1-based

Return type:

tuple(list(tuple), list(tuple))

Returns:

Mean displacement vectors (m) by time (s), followed by displacement variance vectors (m^2) by time (s)

static getVectorTimeSeriesDataFrame(time_series_by_column)

Return a data frame containing aligned vector time series.

Parameters:

time_series_by_column (dict(str, list(tuple))) – Column-name templates keyed to time (s) and vector-value pairs. Each template must contain a {c} placeholder for an x, y, or z component. Vector units are encoded in the column-name template.

Return type:

pandas.DataFrame

Returns:

Time-series data frame

Raises:

MSDVariableTimeStepException – If the series are empty or their times do not match

static combineComponentTimeSeries(msd_infos, attribute)

Combine scalar x, y, and z component series into one vector series.

Parameters:
  • msd_infos (dict(str, MSDInfo)) – MSD information keyed by tensor component

  • attribute (str) – MSDInfo time-series attribute to combine. Times are in s; value units are defined by the selected attribute.

Return type:

list(tuple)

Returns:

Time (s) and three-component vector-value pairs

Raises:

MSDVariableTimeStepException – If component times do not match

writeLogCountVsLogTime(chg_idx, log_count_by_log_t)

Write a csv of log count versus log time (s).

Parameters:
  • chg_idx (int) – the charge index, 1-based

  • log_count_by_log_t (list[tuple]) – each tuple is for a given time bin and contains the time (s) and count in log scale

writeDisplacementTimeSeries(charge_index, square_displacement_by_time, filename_template, log_message, mean_displacement_by_time=None, displacement_variance_by_time=None, pad_log=False)

Write displacement-derived vector time series to a CSV file.

Parameters:
  • charge_index (int) – Charge index, 1-based

  • square_displacement_by_time (list(tuple)) – Time (s) and square displacement vectors (m^2)

  • filename_template (str) – Output filename template

  • log_message (str) – Message describing the output

  • mean_displacement_by_time (list(tuple) or None) – Time (s) and mean displacement vectors (m), or None

  • displacement_variance_by_time (list(tuple) or None) – Time (s) and displacement variance vectors (m^2), or None

  • pad_log (bool) – Whether to pad the log message with blank lines

writeSqDispVsTime(charge_index, square_displacement_by_time, mean_displacement_by_time=None, displacement_variance_by_time=None)

Write a csv of square displacement components (m^2) versus time (s).

Parameters:
  • charge_index (int) – Charge index, 1-based

  • square_displacement_by_time (list(tuple)) – Each tuple contains time (s) and square displacement components (m^2) as a numpy.array

  • mean_displacement_by_time (list(tuple) or None) – Time (s) and mean displacement vectors (m), or None

  • displacement_variance_by_time (list(tuple) or None) – Time (s) and displacement variance vectors (m^2), or None

getSqDispByTime(chg_idx)

Return the MSD(t) curve for the given charge index.

Parameters:

chg_idx (int) – the charge index, 1-based

Return type:

list[tuple]

Returns:

each tuple contains a time (s) and a numpy.array of square displacement components (m^2)

writeFitSqDispVsTime(charge_index, fit_square_displacement_by_time, fit_mean_displacement_by_time=None, fit_displacement_variance_by_time=None)

Write a csv of fit square displacement components (m^2) versus time (s).

Parameters:
  • charge_index (int) – Charge index, 1-based

  • fit_square_displacement_by_time (list(tuple)) – Each tuple contains time (s) and fitted square displacement components (m^2) as a numpy.array

  • fit_mean_displacement_by_time (list(tuple) or None) – Time (s) and fitted mean displacement vectors (m), or None

  • fit_displacement_variance_by_time (list(tuple) or None) – Time (s) and fitted displacement variance vectors (m^2), or None

fitMSD(chg_idx, sd_by_t)

Fit the MSD(t) for the given charge index.

Parameters:
  • chg_idx (int) – the charge index, 1-based

  • sd_by_t (list[tuple]) – each tuple contains a time (s) and a numpy.array of square displacement components (m^2)

Raises:

MSDVariableTimeStepException – if there is an issue

writeMSDFileSummary(field, temperature, charge_sign, overall_drift_velocities)

Write a csv that for each carrier points to its unfit and fit MSD output files along with the fit parameters.

Parameters:
  • field (list) – the field in MV/m

  • temperature (float) – temperature in K

  • charge_sign (int) – the charge sign

  • overall_drift_velocities (dict[int]=numpy.array) – keys are carrier index (1-based), values are overall drift velocities (final displacement / final time) in m/s

run()

Run it.