medcat.utils.data_utils

Classes

CDB

The abstract serialisable base class.

MedCATTrainerExport

dict() -> new empty dictionary

MedCATTrainerExportProject

dict() -> new empty dictionary

MedCATTrainerExportDocument

dict() -> new empty dictionary

MutableDocument

The mutable parts of the document.

MutableEntity

The mutable part of an entity.

TestTrainSplitter

Functions

make_mc_train_test(data, cdb[, test_size])

Make train set.

get_false_positives(doc, spacy_doc)

Get the false positives within a trainer export.

Module Contents

class medcat.utils.data_utils.CDB(config)

Bases: medcat.storage.serialisables.AbstractSerialisable

The abstract serialisable base class.

This defines some common defaults.

Parameters:

config (medcat.config.Config)

__init__(config)
Parameters:

config (medcat.config.Config)

Return type:

None

config
cui2info: dict[str, medcat.cdb.concepts.CUIInfo]
name2info: dict[str, medcat.cdb.concepts.NameInfo]
type_id2info: dict[str, medcat.cdb.concepts.TypeInfo]
token_counts: dict[str, int]
addl_info: dict[str, Any]
_subnames: set[str]
is_dirty = False
has_changed_names = False
classmethod get_init_attrs()
Return type:

list[str]

_reset_subnames()
has_subname(name)

Whether the CDB has the specified subname.

Parameters:

name (str) – The subname to check.

Returns:

bool – Whether the subname is present in this CDB.

Return type:

bool

get_name(cui)

Returns preferred name if it exists, otherwise it will return the longest name assigned to the concept.

Parameters:

cui (str) – Concept ID or unique identifier in this database.

Returns:

str – The name of the concept.

Return type:

str

weighted_average_function(step)

Get the weighted average for steop.

Parameters:

step (int) – The steop.

Returns:

float – The weighted average.

Return type:

float

add_types(types)

Add type info to CDB.

Parameters:

types (Iterable[tuple[str, str]]) – The raw type info.

Return type:

None

add_names(cui, names, name_status=ST.AUTOMATIC, full_build=False)

Adds a name to an existing concept.

Parameters:
  • cui (str) – Concept ID or unique identifier in this database, all concepts that have the same CUI will be merged internally.

  • names (dict[str, NameDescriptor]) –

    Names for this concept, or the value that if found in free text can be linked to this concept. Names is an dict like: `{name: {‘tokens’: tokens, ‘snames’: snames,

    ’raw_name’: raw_name}, …}`

    Names should be generated by helper function ‘medcat.preprocessing.cleaners.prepare_name’

  • name_status (str) – One of P, N, A. Defaults to ‘A’.

  • full_build (bool) – If True the dictionary self.addl_info will also be populated, contains a lot of extra information about concepts, but can be very memory consuming. This is not necessary for normal functioning of MedCAT (Default value False).

Return type:

None

_add_concept_names(cui, names, name_status)
Parameters:
Return type:

None

_add_full_build(cui, names, ontologies, description, type_ids)
Parameters:
Return type:

None

_add_concept(cui, names, ontologies, name_status, type_ids, description, full_build=False)

Add a concept to internal Concept Database (CDB). Depending on what you are providing this will add a large number of properties for each concept.

Parameters:
  • cui (str) – Concept ID or unique identifier in this database, all concepts that have the same CUI will be merged internally.

  • names (dict[str, NameDescriptor]) –

    Names for this concept, or the value that if found in free text can be linked to this concept. Names is a dict like: `{name: {‘tokens’: tokens, ‘snames’: snames,

    ’raw_name’: raw_name}, …}`

    Names should be generated by helper function ‘medcat.preprocessing.cleaners.prepare_name’

  • ontologies (set[str]) – ontologies in which the concept exists (e.g. SNOMEDCT, HPO)

  • name_status (str) – One of P, N, A

  • type_ids (set[str]) – Semantic type identifier (have a look at TUIs in UMLS or SNOMED-CT)

  • description (str) – Description of this concept.

  • full_build (bool) – If True the dictionary self.addl_info will also be populated, contains a lot of extra information about concepts, but can be very memory consuming. This is not necessary for normal functioning of MedCAT (Default Value False).

Return type:

None

reset_training()

Will remove all training efforts - in other words all embeddings that are learnt for concepts in the current CDB. Please note that this does not remove synonyms (names) that were potentially added during supervised/online learning.

Return type:

None

filter_by_cui(cuis_to_keep)

Subset the core CDB fields (dictionaries/maps).

Note that this will potenitally keep a bit more CUIs then in cuis_to_keep. It will first find all names that link to the cuis_to_keep and then find all CUIs that link to those names and keep all of them.

This also will not remove any data from cdb.addl_info - as this field can contain data of unknown structure.

Parameters:

cuis_to_keep (Collection[str]) – CUIs that will be kept, the rest will be removed (not completely, look above).

Raises:

Exception – If no snames and subsetting is not possible.

Return type:

None

remove_cui(cui)

This function takes a CUI and removes it the CDB.

It also removes the CUI from name specific per_cui_status maps as well as well as removes all the names that do not correspond to any CUIs after the removal of this one.

Parameters:

cui (str) – The CUI to remove.

Return type:

None

_remove_names(cui, names)

Remove names from an existing concept - effect is this name will never again be used to link to this concept. This will only remove the name from the linker (namely name2cuis and name2cuis2status), the name will still be present everywhere else. Why? Because it is bothersome to remove it from everywhere, but could also be useful to keep the removed names in e.g. cui2names.

Parameters:
  • cui (str) – Concept ID or unique identifier in this database.

  • names (Iterable[str]) – Names to be removed (e.g list, set, or even a dict (in which case keys will be used)).

Return type:

None

__eq__(other)
Parameters:

other (Any)

Return type:

bool

get_cui2count_train()
Return type:

dict[str, int]

get_name2count_train()
Return type:

dict[str, int]

get_hash()
Return type:

str

get_basic_info()
Return type:

medcat.data.model_card.CDBInfo

save(save_path, serialiser=AvailableSerialisers.dill, overwrite=False)

Save CDB at path.

Parameters:
  • save_path (str) – The path to save at.

  • serialiser (Union[ str, AvailableSerialisers], optional) – The serialiser. Defaults to AvailableSerialisers.dill.

  • overwrite (bool, optional) – Whether to allow overwriting existing files. Defaults to False.

Return type:

None

classmethod load(path)
Parameters:

path (str)

Return type:

CDB

get_strategy()
Return type:

SerialisingStrategy

classmethod ignore_attrs()
Return type:

list[str]

classmethod include_properties()
Return type:

list[str]

class medcat.utils.data_utils.MedCATTrainerExport

Bases: typing_extensions.TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

projects: list[MedCATTrainerExportProject]
__contains__()

True if the dictionary has the specified key, else False.

__delattr__()

Implement delattr(self, name).

__delitem__()

Delete self[key].

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__()

x.__getitem__(y) <==> x[y]

__gt__()

Return self>value.

__init__()

Initialize self. See help(type(self)) for accurate signature.

__ior__()

Return self|=value.

__iter__()

Implement iter(self).

__le__()

Return self<=value.

__len__()

Return len(self).

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__or__()

Return self|value.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__reversed__()

Return a reverse iterator over the dict keys.

__ror__()

Return value|self.

__setattr__()

Implement setattr(self, name, value).

__setitem__()

Set self[key] to value.

__sizeof__()

D.__sizeof__() -> size of D in memory, in bytes

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

clear()

D.clear() -> None. Remove all items from D.

copy()

D.copy() -> a shallow copy of D

get()

Return the value for key if key is in the dictionary, else default.

items()

D.items() -> a set-like object providing a view on D’s items

keys()

D.keys() -> a set-like object providing a view on D’s keys

pop()

D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault()

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update()

D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

D.values() -> an object providing a view on D’s values

class medcat.utils.data_utils.MedCATTrainerExportProject

Bases: typing_extensions.TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

name: str
id: Any
cuis: str
tuis: str | None
documents: list[MedCATTrainerExportDocument]
__contains__()

True if the dictionary has the specified key, else False.

__delattr__()

Implement delattr(self, name).

__delitem__()

Delete self[key].

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__()

x.__getitem__(y) <==> x[y]

__gt__()

Return self>value.

__init__()

Initialize self. See help(type(self)) for accurate signature.

__ior__()

Return self|=value.

__iter__()

Implement iter(self).

__le__()

Return self<=value.

__len__()

Return len(self).

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__or__()

Return self|value.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__reversed__()

Return a reverse iterator over the dict keys.

__ror__()

Return value|self.

__setattr__()

Implement setattr(self, name, value).

__setitem__()

Set self[key] to value.

__sizeof__()

D.__sizeof__() -> size of D in memory, in bytes

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

clear()

D.clear() -> None. Remove all items from D.

copy()

D.copy() -> a shallow copy of D

get()

Return the value for key if key is in the dictionary, else default.

items()

D.items() -> a set-like object providing a view on D’s items

keys()

D.keys() -> a set-like object providing a view on D’s keys

pop()

D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault()

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update()

D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

D.values() -> an object providing a view on D’s values

class medcat.utils.data_utils.MedCATTrainerExportDocument

Bases: typing_extensions.TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

name: str
id: Any
last_modified: str
text: str
annotations: list[MedCATTrainerExportAnnotation]
__contains__()

True if the dictionary has the specified key, else False.

__delattr__()

Implement delattr(self, name).

__delitem__()

Delete self[key].

__dir__()

Default dir() implementation.

__eq__()

Return self==value.

__format__()

Default object formatter.

__ge__()

Return self>=value.

__getattribute__()

Return getattr(self, name).

__getitem__()

x.__getitem__(y) <==> x[y]

__gt__()

Return self>value.

__init__()

Initialize self. See help(type(self)) for accurate signature.

__ior__()

Return self|=value.

__iter__()

Implement iter(self).

__le__()

Return self<=value.

__len__()

Return len(self).

__lt__()

Return self<value.

__ne__()

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__or__()

Return self|value.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__reversed__()

Return a reverse iterator over the dict keys.

__ror__()

Return value|self.

__setattr__()

Implement setattr(self, name, value).

__setitem__()

Set self[key] to value.

__sizeof__()

D.__sizeof__() -> size of D in memory, in bytes

__str__()

Return str(self).

__subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

clear()

D.clear() -> None. Remove all items from D.

copy()

D.copy() -> a shallow copy of D

get()

Return the value for key if key is in the dictionary, else default.

items()

D.items() -> a set-like object providing a view on D’s items

keys()

D.keys() -> a set-like object providing a view on D’s keys

pop()

D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault()

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update()

D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

D.values() -> an object providing a view on D’s values

class medcat.utils.data_utils.MutableDocument

Bases: Protocol

The mutable parts of the document.

Represents parts of the document that can / should be changed by the various components.

property base: BaseDocument

The base document.

Return type:

BaseDocument

property linked_ents: list[MutableEntity]

The linked entities associated with the document.

This should be set by the linker.

Return type:

list[MutableEntity]

property ner_ents: list[MutableEntity]

All entities recognised by NER.

This should be set by the NER component.

Return type:

list[MutableEntity]

__iter__()
Return type:

Iterator[MutableToken]

__getitem__(index: int) MutableToken
__getitem__(index: slice) MutableEntity
__len__()
Return type:

int

get_tokens(start_index, end_index)

Get the tokens that span the specified character indices.

Parameters:
  • start_index (int) – The starting character index.

  • end_index (int) – The ending character index.

Returns:

list[MutableToken] – The list of tokens.

Return type:

list[MutableToken]

set_addon_data(path, val)

Used to add arbitrary data to the entity.

This is generally used by addons to keep track of their data.

NB! The path used needs to be registered using the register_addon_path class method.

Parameters:
  • path (str) – The data ID / path.

  • val (Any) – The value to be added.

Return type:

None

has_addon_data(path)

Checks whether the addon data for a specific path has been set.

Parameters:

path (str) – The path to check.

Returns:

bool – Whether the addon data had been set.

Return type:

bool

get_addon_data(path)

Get data added to the entity.

See add_data for details.

Parameters:

path (str) – The data ID / path.

Returns:

Any – The stored value.

Return type:

Any

get_available_addon_paths()

Gets the available addon data paths for this document.

This will only include paths that have values set.

Returns:

list[str] – List of available addon data paths.

Return type:

list[str]

classmethod register_addon_path(path, def_val=None, force=True)

Register a custom/arbitrary data path.

This can be used to store arbitrary data along with the entity for use in an addon (e.g MetaCAT).

PS: If using this, it is important to use paths namespaced to the component you’re using in order to avoid conflicts.

Parameters:
  • path (str) – The path to be used. Should be prefixed by component name (e.g meta_cat_id for an ID tied to the meta_cat addon)

  • def_val (Any) – Default value. Defaults to None.

  • force (bool) – Whether to forcefully add the value. Defaults to True.

Return type:

None

__slots__ = ()
_is_protocol = True
_is_runtime_protocol = False
classmethod __init_subclass__(*args, **kwargs)
classmethod __class_getitem__(params)
class medcat.utils.data_utils.MutableEntity

Bases: Protocol

The mutable part of an entity.

This represent the changeable part of an entnity. That is, parts that should be changed by the various components.

property base: BaseEntity

The base / static entity part.

Return type:

BaseEntity

property detected_name: str

The detected name (if any) for this entity.

This should be set by the NER component.

Return type:

str

set_addon_data(path, val)

Used to add arbitrary data to the entity.

This is generally used by addons to keep track of their data.

NB! The path used needs to be registered using the register_addon_path class method.

Parameters:
  • path (str) – The data ID / path.

  • val (Any) – The value to be added.

Return type:

None

has_addon_data(path)

Checks whether the addon data for a specific path has been set.

Parameters:

path (str) – The path to check.

Returns:

bool – Whether the addon data had been set.

Return type:

bool

get_addon_data(path)

Get data added to the entity.

See add_data for details.

Parameters:

path (str) – The data ID / path.

Returns:

Any – The stored value.

Return type:

Any

get_available_addon_paths()

Gets the available addon data paths for this entity.

This will only include paths that have values set.

Returns:

list[str] – List of available addon data paths.

Return type:

list[str]

The candidates for the detected name (if any) for this entity.

This should be set by the NER component.

Return type:

list[str]

property context_similarity: float

The context similarity of the lnked entity.

This should be set by the linker component.

Return type:

float

property confidence: float

The confidence for the lnked entity.

NOTE: This seems to be unused!

Return type:

float

property cui: str

The CUI of the lnked entity.

This should be set by the linker component.

Return type:

str

property id: int

The ID of the entity within the document.

This counts all the entities recognised, not just ones that were successfully linked.

This should be set by the NER.

Return type:

int

classmethod register_addon_path(path, def_val=None, force=True)

Register a custom/arbitrary data path.

This can be used to store arbitrary data along with the entity for use in an addon (e.g MetaCAT).

PS: If using this, it is important to use paths namespaced to the component you’re using in order to avoid conflicts.

Parameters:
  • path (str) – The path to be used. Should be prefixed by component name (e.g meta_cat_id for an ID tied to the meta_cat addon)

  • def_val (Any) – Default value. Defaults to None.

  • force (bool) – Whether to forcefully add the value. Defaults to True.

Return type:

None

__iter__()
Return type:

Iterator[MutableToken]

__len__()
Return type:

int

__slots__ = ()
_is_protocol = True
_is_runtime_protocol = False
classmethod __init_subclass__(*args, **kwargs)
classmethod __class_getitem__(params)
class medcat.utils.data_utils.TestTrainSplitter(data, cdb, test_size=0.2)
Parameters:
MAX_TEST_FRACTION = 0.3
MIN_CNT_FOR_TEST = 10
__init__(data, cdb, test_size=0.2)
Parameters:
data
cdb
test_size = 0.2
_reset()
Return type:

None

_count_project(project)
Parameters:

project (medcat.data.mctexport.MedCATTrainerExportProject)

Return type:

None

split()
Return type:

tuple[medcat.data.mctexport.MedCATTrainerExport, medcat.data.mctexport.MedCATTrainerExport, int, int]

_split_doc_train_test(document, cui_filter, train_project, test_project)
Parameters:
_should_add_to_test(_cnts)
Parameters:

_cnts (dict[str, int])

Return type:

bool

medcat.utils.data_utils.make_mc_train_test(data, cdb, test_size=0.2)

Make train set.

This is a disaster.

Parameters:
  • data (MedCATTrainerExport) – The data.

  • cdb (CDB) – The concept database.

  • test_size (float) – The test size. Defaults to 0.2.

Returns:

tuple – The train set, the test set, the test annotations, and the total annotations

Return type:

tuple

medcat.utils.data_utils.get_false_positives(doc, spacy_doc)

Get the false positives within a trainer export.

Parameters:
Returns:

list[MutableEntity] – The list of false positive entities.

Return type:

list[medcat.tokenizing.tokens.MutableEntity]