pydent.models.Collection

class pydent.models.Collection(object_type=None, location=None, data_associations=None, parts=None, part_associations=None, **kwargs)[source]

Bases: pydent.models.inventory.ItemLocationMixin, pydent.models.data_associations.DataAssociatorMixin, pydent.models.crud_mixin.SaveMixin, pydent.models.controller_mixin.ControllerMixin, pydent.base.ModelBase

A Collection model, such as a 96-well plate, which contains many parts, each of which can be associated with a different sample.

Initialize a new Collection.

Changed in version 0.1.5a10: Advanced indexing added for setting and getting samples and data associations

Setting samples using new advanced indexing

object_type = session.ObjectType.one(query='rows > 2 AND columns > 2')
collection = session.Collection.new(object_type=object_type)

# assign sample '1' to (0, 0) row=0, column=0
collection[0, 0] = 1

# assign sample '2' to (1, 2) row=1, column=2
collection[1, 2] = 2

# assign sample '3234' to row 3
collection[3] = 3234

# assign sample '444' to column 1
collection[:, 1] = 444

# assign sample '6' to the whole collection
collection[:, :] = 6

# assign sample using Sample instance
collection[2, 2] = session.Sample.one()

Getting samples using new advanced indexing

# get 2d matrix of sample ids
print(collection.matrix)  # or collection.sample_id_matrix

# get 2d matrix of Samples assigned at each location
print(collection.sample_matrix)

# get 2d matrix of Parts assigned at each location
print(collection.part_matrix)

# get 2d matrix of PartAssociations assigned at each location
collection.part_associations_matrix

# get 2d matrix of values of DataAssociations at each location
collection.data_matrix

# get 2d matrix of DataAssociations at each location
collection.data_association_matrix

Assigning data to locations

To assign data, you can use the advanced indexing on the data_matrix

collection.data_matrix[0, 0] = {'key': 'value'}

collection.data_matrix[1] = {'key': 'value2'}

collection.associate_to('key', 'value3', 3, 3)

You can delete associations using the following:

# delete 3, 3
collection.delete_association_at('key', 3, 3)

# delete first three rows at column 3
collection.delete_association_at('key', slice(None, 3, None), 3)

# delete all of the 'key' associations
collection.delete_association_at('key', slice(None, None, None), slice(None, None, None))
Parameters
  • object_type (Optional[ObjectType]) –

  • location (Optional[str]) –

  • data_associations (Optional[List]) –

  • parts (Optional[List]) –

  • part_associations (Optional[List]) –

  • kwargs

__init__(object_type=None, location=None, data_associations=None, parts=None, part_associations=None, **kwargs)[source]

Initialize a new Collection.

Changed in version 0.1.5a10: Advanced indexing added for setting and getting samples and data associations

Setting samples using new advanced indexing

object_type = session.ObjectType.one(query='rows > 2 AND columns > 2')
collection = session.Collection.new(object_type=object_type)

# assign sample '1' to (0, 0) row=0, column=0
collection[0, 0] = 1

# assign sample '2' to (1, 2) row=1, column=2
collection[1, 2] = 2

# assign sample '3234' to row 3
collection[3] = 3234

# assign sample '444' to column 1
collection[:, 1] = 444

# assign sample '6' to the whole collection
collection[:, :] = 6

# assign sample using Sample instance
collection[2, 2] = session.Sample.one()

Getting samples using new advanced indexing

# get 2d matrix of sample ids
print(collection.matrix)  # or collection.sample_id_matrix

# get 2d matrix of Samples assigned at each location
print(collection.sample_matrix)

# get 2d matrix of Parts assigned at each location
print(collection.part_matrix)

# get 2d matrix of PartAssociations assigned at each location
collection.part_associations_matrix

# get 2d matrix of values of DataAssociations at each location
collection.data_matrix

# get 2d matrix of DataAssociations at each location
collection.data_association_matrix

Assigning data to locations

To assign data, you can use the advanced indexing on the data_matrix

collection.data_matrix[0, 0] = {'key': 'value'}

collection.data_matrix[1] = {'key': 'value2'}

collection.associate_to('key', 'value3', 3, 3)

You can delete associations using the following:

# delete 3, 3
collection.delete_association_at('key', 3, 3)

# delete first three rows at column 3
collection.delete_association_at('key', slice(None, 3, None), 3)

# delete all of the 'key' associations
collection.delete_association_at('key', slice(None, None, None), slice(None, None, None))
Parameters
  • object_type (Optional[ObjectType]) –

  • location (Optional[str]) –

  • data_associations (Optional[List]) –

  • parts (Optional[List]) –

  • part_associations (Optional[List]) –

  • kwargs

Methods

__init__([object_type, location, …])

Initialize a new Collection.

add_data(data)

Initializes fake attributes that correspond to data.

anonymize()

Resets the primary key of the model and assigns a new rid.

append_to_many(name, model)

Appends a model to the many relationship.

as_item()

Returns the Item object with the ID of this Collection.

associate(key, value[, upload, create_new, save])

Adds a data association with the key and value to this object.

associate_file(key, value, file[, job_id])

Associate a file.

associate_file_from_path(key, value, filepath)

Associate a file from a filepath.

connect_to_session(session)

Connect model to a session.

copy([keep])

Provides a deepcopy of the model, but annonymizes the primary and global keys unless class is a metatype (e.g.

create()

Create a new empty collection on the server.

create_interface()

rtype

Union[QueryInterface, BrowserInterface]

dump([only, include, ignore, …])

Dump (serialize) the Aquarium model instance to JSON.

find(session, model_id)

Finds a model instance by its model_id.

find_callback(model_name, model_id)

Finds a model using the model interface and model_id.

get(key)

get_data_associations(key)

get_deserialized(name)

Get deserialized data by name.

get_relationships()

get_server_model_name()

get_tableized_name()

interface(session)

Creates a model interface from this class and a session.

is_deserialized(name)

Check if a given key has already been deserialized.

load(*args, **kwargs)

Deserialize the data to a model.

load_from(data[, owner])

Create a new model instance from loaded attributes.

no_getter(*_)

Callback that always returns None.

one(session, query, **kwargs)

rtype

ModelBase

one_callback(model_name, *args, **kwargs)

rtype

ModelBase

part(row, col)

Returns the part Item at (row, col) of this Collection (zero- based).

print()

refresh()

Refresh this model from data from the server.

reload(data)

Reload model attributes from new data.

reset_field(name)

Reset the field descriptor to its placeholder value, returning the behavior.

save()

update()

Updates the item.

where(session, params)

Finds a list of models by some parameters.

where_callback(model_name, *args, **kwargs)

Finds models using a model interface and a set of parameters.

Attributes

DEFAULT_COPY_KEEP_UNANONYMOUS

GLOBAL_KEY

PRIMARY_KEY

SERVER_MODEL_NAME

counter

Collection.data_associations

fields

id

matrix

Returns the matrix of Samples for this Collection.

Collection.object_type

Collection.part_associations

Collection.parts

query_hook

rid

rtype

int

session

The connected session instance.

_check_for_session()

Raises error if model is not connected to a session.

:raises NoSessionError

classmethod _flatten_deserialized_data(models, memo)

Flattens all of the relationships found in the models, returning a rid: model dictionary.

Return type

dict

_get_data()

Return the model’s data.

_get_deserialized_data()

Return the deserialized model data.

_model_schema

alias of pydent.marshaller.base.CollectionSchema

property _primary_key

Returns the primary key (e.g. ‘id’) or the rid if id does not exist or is None.

_rid_dict()

Dictionary of all models attached to this model keyed by their rid.

add_data(data)

Initializes fake attributes that correspond to data.

anonymize()

Resets the primary key of the model and assigns a new rid.

Metatypes cannot be annonymized.

Returns

self

append_to_many(name, model)

Appends a model to the many relationship.

Parameters
  • name (str) – name of the relationship or attribute

  • model (ModelBase) – model to append

Returns

None

Return type

None

as_item()[source]

Returns the Item object with the ID of this Collection.

assign_sample(sample_id, pairs)[source]

Assign sample id to the (row, column) pairs for the collection.

Parameters
  • sample_id (int) – the sample id to assign

  • pairs (List[Tuple[int, int]]) – list of (row, column) tuples

Returns

self

associate(key, value, upload=None, create_new=False, save=None)

Adds a data association with the key and value to this object.

Parameters
  • key (str) – Key of the association

  • value (dict | str | int | float) – a json serializable object

  • upload (File) – optional file to upload

  • create_new – if True (default) will create a new association instead of updating the existing association.

Tuype create_new

bool

Returns

newly created or updated data association

Return type

DataAssociation

associate_file(key, value, file, job_id=None)

Associate a file.

Parameters
  • key (str or json) – association key

  • value (str or json) – association value

  • file (file object) – file to create Upload

  • job_id (int) – optional job_id to associate the Upload

Returns

new data association

Return type

DataAssociation

associate_file_from_path(key, value, filepath, job_id=None)

Associate a file from a filepath.

Parameters
  • key (str or json) – association key

  • value (str or json) – association value

  • filepath (str) – path to file to create Upload

  • job_id (int) – optional job_id to associate the Upload

Returns

new data association

Return type

DataAssociation

connect_to_session(session)

Connect model to a session.

Parameters

session (SessionABC) – the AqSession

Returns

None

Raises
controller_method(controller_method, table, model_id, data, params=None)

Method for create, updating, and deleting models.

Parameters
  • controller_method (str) – Name of the controller method

  • table (str) – Table name of model (e.g. ‘samples’ or ‘data_associations’)

  • model_id (Union[str, int, None]) – Optional model_id (not required for ‘post’)

  • data (Optional[dict]) – data

  • params – controller parameters

Returns

json formatted server response

Return type

dict

copy(keep=None)

Provides a deepcopy of the model, but annonymizes the primary and global keys unless class is a metatype (e.g. OperationType, SampleType, FieldType) or class name is found in list of ‘keep’.

By default, inventory classes such as Sample, Item, and Collection are ‘kept’.

This specific usecase is that when copying whole plans, that the integrity of the inventory used in the operations is maintained. These are the items that refer to physical inventory in the laboratory and are referred to by their rids, and so it is important to that any of these inventory are always maintain their rids. Meaning in the lab, their is only ONE instance of the inventory. In Trident and Aquarium, there is only ONE instance of inventory that is referred to by its rid.

Similarly, any metatype model must also maintain their rid.

Parameters

keep (Optional[bool]) – list of model classes (as a list of strings) to keep un-anonymous

Return type

ModelBase

Returns

copied model

create()[source]

Create a new empty collection on the server.

property data_association_matrix

Return a view of.

DataAssociation

New in version 0.1.5a9.

Return type

MatrixMapping[DataAssociation]

Returns

collection as a view of DataAssociations

property data_matrix

Return a view of values from the.

DataAssociation

New in version 0.1.5a9.

Return type

MatrixMapping[Any]

Returns

collection as a view of DataAssociation values

dump(only=None, include=None, ignore=None, include_model_type=False, include_uri=False)

Dump (serialize) the Aquarium model instance to JSON.

Parameters
  • only (Union[str, List[str], Tuple[str], Dict[str, Any], None]) – dump only the provided keys

  • include (Union[str, List[str], Tuple[str], Dict[str, Any], None]) – include the provided nested dump keys

  • ignore (Union[str, List[str], Tuple[str], Dict[str, Any], None]) – ignore the provided keys

  • include_model_type (bool) – if True, include the model class type for each entry using the __model__ key

  • include_uri (bool) – if True, include a URI using the session URL and the tableized model class name using the __uri__ key. If a session is not attached, look for the url namespace in the ModelBase.DEFAULT_NAMESPACE class attribute, as in http://aquarium.org/samples/10.

Return type

dict

Returns

serialized model instance

classmethod find(session, model_id)

Finds a model instance by its model_id.

Return type

ModelBase

find_callback(model_name, model_id)

Finds a model using the model interface and model_id.

Used to find models in model relationships.

Return type

ModelBase

get_deserialized(name)

Get deserialized data by name.

Deprecated since version 0.1.5a7: method will be removed in 0.2. Use self._get_deserialized_data[name] instead.

Parameters

name – name of attribute

Returns

classmethod interface(session)

Creates a model interface from this class and a session.

This method can be overridden in model definitions for special cases.

Return type

Union[QueryInterface, BrowserInterface]

is_deserialized(name)

Check if a given key has already been deserialized.

New in version 0.1.5a7: Method added

Parameters

name (str) – name of the attribute

Return type

bool

Returns

True if key has been deserialized.

classmethod load(*args, **kwargs)

Deserialize the data to a model.

Parameters

data (dict) – data to deserialize

Returns

the deserialized model

Return type

SchemaModel

classmethod load_from(data, owner=None)

Create a new model instance from loaded attributes.

‘obj’ should have a o

Return type

Union[List[ModelBase], ModelBase]

make()

Makes the Item on the Aquarium server.

Requires this Item to be connected to a session.

property matrix

Returns the matrix of Samples for this Collection.

(Consider using samples of parts directly.)

Changed in version 0.1.5a9: Refactored using MatrixMapping

model_schema

alias of pydent.marshaller.base.CollectionSchema

no_getter(*_)

Callback that always returns None.

part(row, col)[source]

Returns the part Item at (row, col) of this Collection (zero- based).

Return type

Item

property part_association_matrix

Return a view of part associations.

New in version 0.1.5a9.

Return type

MatrixMapping[PartAssociation]

Returns

collection as a view of PartAssociations

property part_matrix

Return a view of Item

New in version 0.1.5a9.

Return type

MatrixMapping[Item]

Returns

collection as a view of Items (Parts)

refresh()

Refresh this model from data from the server.

Returns

self

Return type

self

reload(data)

Reload model attributes from new data.

Parameters

data (dict) – data to update model instance

Returns

model instance

Return type

ModelBase

remove_sample(pairs)[source]

Clear the sample_id assigment in the (row, column) pairs for the collection.

Parameters

pairs (List[Tuple[int, int]]) – list of (row, column) tuples

Returns

self

reset_field(name)

Reset the field descriptor to its placeholder value, returning the behavior.

New in version 0.1.5a7: Method added to reset deserialized attributes

Parameters

name (str) – name of the attribute

Returns

None

property sample_id_matrix

Return a view of sample_ids Sample

New in version 0.1.5a9.

Return type

MatrixMapping[int]

Returns

collection as a view of Sample.ids

property sample_matrix

Return a view of Sample

New in version 0.1.5a9.

Return type

MatrixMapping[Sample]

Returns

collection as a view of Samples

property session

The connected session instance.

update()[source]

Updates the item.

Will update the data associations and its location.

property uri

Return a URI for this model using the attached session url and tableized model name. For example, http://aquarium.org/samples/. If no session is attached, use the ModelBase.DEFAULT_NAMESPACE key for the url.

Return type

str

Returns

the instance URI

classmethod where(session, params)

Finds a list of models by some parameters.

Return type

Optional[List[ModelBase]]

where_callback(model_name, *args, **kwargs)

Finds models using a model interface and a set of parameters.

Used to find models in model relationships.

Return type

Optional[List[ModelBase]]