This repository has been archived by the owner on Jan 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodels.py
3231 lines (2564 loc) · 110 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import sys
from collections import defaultdict
# has to be here for the type hinting to work
from datetime import datetime # noqa
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Literal,
NamedTuple,
overload,
)
from django.db import models
from django.db.models import CASCADE, PROTECT, Field
from django.db.models.base import ModelBase
from django.db.models.fields.related import (
ManyToManyField,
ManyToManyRel,
ManyToOneRel,
)
from lamin_utils import colors
from lamindb_setup import _check_instance_setup
from lamindb_setup.core._docs import doc_args
from lamindb_setup.core.hashing import HASH_LENGTH
from lnschema_core.fields import (
BigIntegerField,
BooleanField,
CharField,
DateTimeField,
ForeignKey,
IntegerField,
OneToOneField,
TextField,
)
from lnschema_core.types import (
ArtifactType,
FeatureDtype,
FieldAttr,
ListLike,
StrField,
TransformType,
VisibilityChoice,
)
from .ids import base62_8, base62_12, base62_20
from .users import current_user_id
if TYPE_CHECKING:
from pathlib import Path
import numpy as np
import pandas as pd
from anndata import AnnData
from lamin_utils._inspect import InspectResult
from lamindb.core import LabelManager
from lamindb_setup.core.types import UPathStr
from mudata import MuData
from pyarrow.dataset import Dataset as PyArrowDataset
from tiledbsoma import Collection as SOMACollection
from tiledbsoma import Experiment as SOMAExperiment
from upath import UPath
from lnschema_core.mocks import (
AnnDataAccessor,
BackedAccessor,
MappedCollection,
QuerySet,
RecordList,
)
_TRACKING_READY: bool | None = None
class IsVersioned(models.Model):
"""Base class for versioned models."""
class Meta:
abstract = True
_len_stem_uid: int
version: str | None = CharField(max_length=30, null=True, db_index=True)
"""Version (default `None`).
Defines version of a family of records characterized by the same `stem_uid`.
Consider using `semantic versioning <https://semver.org>`__
with `Python versioning <https://peps.python.org/pep-0440/>`__.
"""
is_latest: bool = BooleanField(default=True, db_index=True)
"""Boolean flag that indicates whether a record is the latest in its version family."""
@overload
def __init__(self): ...
@overload
def __init__(
self,
*db_args,
): ...
def __init__(
self,
*args,
**kwargs,
):
self._revises = kwargs.pop("revises") if "revises" in kwargs else None
super().__init__(*args, **kwargs)
@property
def stem_uid(self) -> str:
"""Universal id characterizing the version family.
The full uid of a record is obtained via concatenating the stem uid and version information::
stem_uid = random_base62(n_char) # a random base62 sequence of length 12 (transform) or 16 (artifact, collection)
version_uid = "0000" # an auto-incrementing 4-digit base62 number
uid = f"{stem_uid}{version_uid}" # concatenate the stem_uid & version_uid
"""
return self.uid[: self._len_stem_uid] # type: ignore
@property
def versions(self) -> QuerySet:
"""Lists all records of the same version family.
>>> new_artifact = ln.Artifact(df2, revises=artifact).save()
>>> new_artifact.versions()
"""
db = self._state.db
if db is not None and db != "default":
return self.__class__.using(db).filter(uid__startswith=self.stem_uid) # type: ignore
else:
return self.__class__.filter(uid__startswith=self.stem_uid) # type: ignore
def _add_to_version_family(self, revises: IsVersioned, version: str | None = None):
"""Add current record to a version family.
Args:
revises: a record that belongs to the version family.
version: semantic version of the record.
"""
pass
def current_run() -> Run | None:
global _TRACKING_READY
if not _TRACKING_READY:
_TRACKING_READY = _check_instance_setup()
if _TRACKING_READY:
import lamindb.core
return lamindb.context.run
else:
return None
class TracksRun(models.Model):
"""Base class tracking latest run, creating user, and `created_at` timestamp."""
class Meta:
abstract = True
created_at: datetime = DateTimeField(auto_now_add=True, db_index=True)
"""Time of creation of record."""
created_by: User = ForeignKey(
"lnschema_core.User", PROTECT, default=current_user_id, related_name="+"
)
"""Creator of record."""
run: Run | None = ForeignKey(
"lnschema_core.Run", PROTECT, null=True, default=current_run, related_name="+"
)
"""Last run that created or updated the record."""
@overload
def __init__(self): ...
@overload
def __init__(
self,
*db_args,
): ...
def __init__(
self,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
class TracksUpdates(models.Model):
"""Base class tracking previous runs and `updated_at` timestamp."""
class Meta:
abstract = True
updated_at: datetime = DateTimeField(auto_now=True, db_index=True)
"""Time of last update to record."""
# no default related_name below because it'd clash with the reverse accessor
# of the .run field
_previous_runs: Run = models.ManyToManyField("lnschema_core.Run", related_name="+")
"""Sequence of runs that created or updated the record."""
@overload
def __init__(self): ...
@overload
def __init__(
self,
*db_args,
): ...
def __init__(
self,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
class CanCurate:
"""Base class providing :class:`~lamindb.core.Record`-based validation."""
@classmethod
def inspect(
cls,
values: ListLike,
field: str | StrField | None = None,
*,
mute: bool = False,
organism: str | Record | None = None,
source: Record | None = None,
) -> InspectResult:
"""Inspect if values are mappable to a field.
Being mappable means that an exact match exists.
Args:
values: Values that will be checked against the field.
field: The field of values. Examples are `'ontology_id'` to map
against the source ID or `'name'` to map against the ontologies
field names.
mute: Whether to mute logging.
organism: An Organism name or record.
source: A `bionty.Source` record that specifies the version to inspect against.
See Also:
:meth:`~lamindb.core.CanCurate.validate`
Examples:
>>> import bionty as bt
>>> bt.settings.organism = "human"
>>> ln.save(bt.Gene.from_values(["A1CF", "A1BG", "BRCA2"], field="symbol"))
>>> gene_symbols = ["A1CF", "A1BG", "FANCD1", "FANCD20"]
>>> result = bt.Gene.inspect(gene_symbols, field=bt.Gene.symbol)
>>> result.validated
['A1CF', 'A1BG']
>>> result.non_validated
['FANCD1', 'FANCD20']
"""
pass
@classmethod
def validate(
cls,
values: ListLike,
field: str | StrField | None = None,
*,
mute: bool = False,
organism: str | Record | None = None,
source: Record | None = None,
) -> np.ndarray:
"""Validate values against existing values of a string field.
Note this is strict validation, only asserts exact matches.
Args:
values: Values that will be validated against the field.
field: The field of values.
Examples are `'ontology_id'` to map against the source ID
or `'name'` to map against the ontologies field names.
mute: Whether to mute logging.
organism: An Organism name or record.
source: A `bionty.Source` record that specifies the version to validate against.
Returns:
A vector of booleans indicating if an element is validated.
See Also:
:meth:`~lamindb.core.CanCurate.inspect`
Examples:
>>> import bionty as bt
>>> bt.settings.organism = "human"
>>> ln.save(bt.Gene.from_values(["A1CF", "A1BG", "BRCA2"], field="symbol"))
>>> gene_symbols = ["A1CF", "A1BG", "FANCD1", "FANCD20"]
>>> bt.Gene.validate(gene_symbols, field=bt.Gene.symbol)
array([ True, True, False, False])
"""
pass
def from_values(
cls,
values: ListLike,
field: StrField | None = None,
create: bool = False,
organism: Record | str | None = None,
source: Record | None = None,
mute: bool = False,
) -> RecordList:
"""Bulk create validated records by parsing values for an identifier such as a name or an id).
Args:
values: A list of values for an identifier, e.g.
`["name1", "name2"]`.
field: A `Record` field to look up, e.g., `bt.CellMarker.name`.
create: Whether to create records if they don't exist.
organism: A `bionty.Organism` name or record.
source: A `bionty.Source` record to validate against to create records for.
mute: Whether to mute logging.
Returns:
A list of validated records. For bionty registries. Also returns knowledge-coupled records.
Notes:
For more info, see tutorial: :doc:`docs:bio-registries`.
Examples:
Bulk create from non-validated values will log warnings & returns empty list:
>>> ulabels = ln.ULabel.from_values(["benchmark", "prediction", "test"], field="name")
>>> assert len(ulabels) == 0
Bulk create records from validated values returns the corresponding existing records:
>>> ln.save([ln.ULabel(name=name) for name in ["benchmark", "prediction", "test"]])
>>> ulabels = ln.ULabel.from_values(["benchmark", "prediction", "test"], field="name")
>>> assert len(ulabels) == 3
Bulk create records from public reference:
>>> import bionty as bt
>>> records = bt.CellType.from_values(["T cell", "B cell"], field="name")
>>> records
"""
pass
@classmethod
def standardize(
cls,
values: Iterable,
field: str | StrField | None = None,
*,
return_field: str | StrField | None = None,
return_mapper: bool = False,
case_sensitive: bool = False,
mute: bool = False,
public_aware: bool = True,
keep: Literal["first", "last", False] = "first",
synonyms_field: str = "synonyms",
organism: str | Record | None = None,
source: Record | None = None,
) -> list[str] | dict[str, str]:
"""Maps input synonyms to standardized names.
Args:
values: Identifiers that will be standardized.
field: The field representing the standardized names.
return_field: The field to return. Defaults to field.
return_mapper: If `True`, returns `{input_value: standardized_name}`.
case_sensitive: Whether the mapping is case sensitive.
mute: Whether to mute logging.
public_aware: Whether to standardize from Bionty reference. Defaults to `True` for Bionty registries.
keep: When a synonym maps to multiple names, determines which duplicates to mark as `pd.DataFrame.duplicated`:
- `"first"`: returns the first mapped standardized name
- `"last"`: returns the last mapped standardized name
- `False`: returns all mapped standardized name.
When `keep` is `False`, the returned list of standardized names will contain nested lists in case of duplicates.
When a field is converted into return_field, keep marks which matches to keep when multiple return_field values map to the same field value.
synonyms_field: A field containing the concatenated synonyms.
organism: An Organism name or record.
source: A `bionty.Source` record that specifies the version to validate against.
Returns:
If `return_mapper` is `False`: a list of standardized names. Otherwise,
a dictionary of mapped values with mappable synonyms as keys and
standardized names as values.
See Also:
:meth:`~lamindb.core.CanCurate.add_synonym`
Add synonyms.
:meth:`~lamindb.core.CanCurate.remove_synonym`
Remove synonyms.
Examples:
>>> import bionty as bt
>>> bt.settings.organism = "human"
>>> ln.save(bt.Gene.from_values(["A1CF", "A1BG", "BRCA2"], field="symbol"))
>>> gene_synonyms = ["A1CF", "A1BG", "FANCD1", "FANCD20"]
>>> standardized_names = bt.Gene.standardize(gene_synonyms)
>>> standardized_names
['A1CF', 'A1BG', 'BRCA2', 'FANCD20']
"""
pass
def add_synonym(
self,
synonym: str | ListLike,
force: bool = False,
save: bool | None = None,
):
"""Add synonyms to a record.
Args:
synonym: The synonyms to add to the record.
force: Whether to add synonyms even if they are already synonyms of other records.
save: Whether to save the record to the database.
See Also:
:meth:`~lamindb.core.CanCurate.remove_synonym`
Remove synonyms.
Examples:
>>> import bionty as bt
>>> bt.CellType.from_source(name="T cell").save()
>>> lookup = bt.CellType.lookup()
>>> record = lookup.t_cell
>>> record.synonyms
'T-cell|T lymphocyte|T-lymphocyte'
>>> record.add_synonym("T cells")
>>> record.synonyms
'T cells|T-cell|T-lymphocyte|T lymphocyte'
"""
pass
def remove_synonym(self, synonym: str | ListLike):
"""Remove synonyms from a record.
Args:
synonym: The synonym values to remove.
See Also:
:meth:`~lamindb.core.CanCurate.add_synonym`
Add synonyms
Examples:
>>> import bionty as bt
>>> bt.CellType.from_source(name="T cell").save()
>>> lookup = bt.CellType.lookup()
>>> record = lookup.t_cell
>>> record.synonyms
'T-cell|T lymphocyte|T-lymphocyte'
>>> record.remove_synonym("T-cell")
'T lymphocyte|T-lymphocyte'
"""
pass
def set_abbr(self, value: str):
"""Set value for abbr field and add to synonyms.
Args:
value: A value for an abbreviation.
See Also:
:meth:`~lamindb.core.CanCurate.add_synonym`
Examples:
>>> import bionty as bt
>>> bt.ExperimentalFactor.from_source(name="single-cell RNA sequencing").save()
>>> scrna = bt.ExperimentalFactor.get(name="single-cell RNA sequencing")
>>> scrna.abbr
None
>>> scrna.synonyms
'single-cell RNA-seq|single-cell transcriptome sequencing|scRNA-seq|single cell RNA sequencing'
>>> scrna.set_abbr("scRNA")
>>> scrna.abbr
'scRNA'
>>> scrna.synonyms
'scRNA|single-cell RNA-seq|single cell RNA sequencing|single-cell transcriptome sequencing|scRNA-seq'
>>> scrna.save()
"""
pass
class HasParents:
"""Base class for hierarchical registries (ontologies)."""
def view_parents(
self,
field: StrField | None = None,
with_children: bool = False,
distance: int = 5,
):
"""View parents in an ontology.
Args:
field: Field to display on graph
with_children: Whether to also show children.
distance: Maximum distance still shown.
Ontological hierarchies: :class:`~lamindb.ULabel` (project & sub-project), :class:`~bionty.CellType` (cell type & subtype).
Examples:
>>> import bionty as bt
>>> bt.Tissue.from_source(name="subsegmental bronchus").save()
>>> record = bt.Tissue.get(name="respiratory tube")
>>> record.view_parents()
>>> tissue.view_parents(with_children=True)
"""
pass
def query_parents(self) -> QuerySet:
"""Query parents in an ontology."""
pass
def query_children(self) -> QuerySet:
"""Query children in an ontology."""
pass
RECORD_REGISTRY_EXAMPLE = """Example::
from lnschema_core import Record, fields
# sub-classing `Record` creates a new registry
class Experiment(Record):
name: str = fields.CharField()
# instantiating `Experiment` creates a record `experiment`
experiment = Experiment(name="my experiment")
# you can save the record to the database
experiment.save()
# `Experiment` refers to the registry, which you can query
df = Experiment.filter(name__startswith="my ").df()
"""
# this is the metaclass for Record
@doc_args(RECORD_REGISTRY_EXAMPLE)
class Registry(ModelBase):
"""Metaclass for :class:`~lamindb.core.Record`.
Each `Registry` *object* is a `Record` *class* and corresponds to a table in the metadata SQL database.
You work with `Registry` objects whenever you use *class methods* of `Record`.
You call any subclass of `Record` a "registry" and their objects "records". A `Record` object corresponds to a row in the SQL table.
If you want to create a new registry, you sub-class `Record`.
{}
Note: `Registry` inherits from Django's `ModelBase`.
"""
def __new__(cls, name, bases, attrs, **kwargs):
new_class = super().__new__(cls, name, bases, attrs, **kwargs)
return new_class
# below creates a sensible auto-complete behavior that differs across the
# class and instance level in Jupyter Editors it doesn't have any effect for
# static type analyzer like pylance used in VSCode
def __dir__(cls):
# this is needed to bring auto-complete on the class-level back
# https://laminlabs.slack.com/archives/C04FPE8V01W/p1717535625268849
# Filter class attributes, excluding instance methods
exclude_instance_methods = "sphinx" not in sys.modules
# https://laminlabs.slack.com/archives/C04FPE8V01W/p1721134595920959
def include_attribute(attr_name, attr_value):
if attr_name.startswith("__"):
return False
if exclude_instance_methods and callable(attr_value):
return isinstance(attr_value, (classmethod, staticmethod, type))
return True
# check also inherited attributes
if hasattr(cls, "mro"):
attrs = chain(*(c.__dict__.items() for c in cls.mro()))
else:
attrs = cls.__dict__.items()
result = []
for attr_name, attr_value in attrs:
if attr_name not in result and include_attribute(attr_name, attr_value):
result.append(attr_name)
# Add non-dunder attributes from Registry
for attr in dir(Registry):
if not attr.startswith("__") and attr not in result:
result.append(attr)
return result
def __repr__(cls) -> str:
return registry_repr(cls)
def lookup(
cls,
field: StrField | None = None,
return_field: StrField | None = None,
) -> NamedTuple:
"""Return an auto-complete object for a field.
Args:
field: The field to look up the values for. Defaults to first string field.
return_field: The field to return. If `None`, returns the whole record.
Returns:
A `NamedTuple` of lookup information of the field values with a
dictionary converter.
See Also:
:meth:`~lamindb.core.Record.search`
Examples:
>>> import bionty as bt
>>> bt.settings.organism = "human"
>>> bt.Gene.from_source(symbol="ADGB-DT").save()
>>> lookup = bt.Gene.lookup()
>>> lookup.adgb_dt
>>> lookup_dict = lookup.dict()
>>> lookup_dict['ADGB-DT']
>>> lookup_by_ensembl_id = bt.Gene.lookup(field="ensembl_gene_id")
>>> genes.ensg00000002745
>>> lookup_return_symbols = bt.Gene.lookup(field="ensembl_gene_id", return_field="symbol")
"""
pass
def filter(cls, *queries, **expressions) -> QuerySet:
"""Query records.
Args:
queries: One or multiple `Q` objects.
expressions: Fields and values passed as Django query expressions.
Returns:
A :class:`~lamindb.core.QuerySet`.
See Also:
- Guide: :doc:`docs:registries`
- Django documentation: `Queries <https://docs.djangoproject.com/en/stable/topics/db/queries/>`__
Examples:
>>> ln.ULabel(name="my label").save()
>>> ln.ULabel.filter(name__startswith="my").df()
"""
pass
def get(
cls,
idlike: int | str | None = None,
**expressions,
) -> Record:
"""Get a single record.
Args:
idlike: Either a uid stub, uid or an integer id.
expressions: Fields and values passed as Django query expressions.
Returns:
A record.
Raises:
:exc:`docs:lamindb.core.exceptions.DoesNotExist`: In case no matching record is found.
See Also:
- Guide: :doc:`docs:registries`
- Django documentation: `Queries <https://docs.djangoproject.com/en/stable/topics/db/queries/>`__
Examples:
>>> ulabel = ln.ULabel.get("FvtpPJLJ")
>>> ulabel = ln.ULabel.get(name="my-label")
"""
pass
def df(
cls,
include: str | list[str] | None = None,
features: bool | list[str] = False,
limit: int = 100,
) -> pd.DataFrame:
"""Convert to `pd.DataFrame`.
By default, shows all direct fields, except `updated_at`.
Use arguments `include` or `feature` to include other data.
Args:
include: Related fields to include as columns. Takes strings of
form `"ulabels__name"`, `"cell_types__name"`, etc. or a list
of such strings.
features: If `True`, map all features of the
:class:`~lamindb.Feature` registry onto the resulting
`DataFrame`. Only available for `Artifact`.
limit: Maximum number of rows to display from a Pandas DataFrame.
Defaults to 100 to reduce database load.
Examples:
Include the name of the creator in the `DataFrame`:
>>> ln.ULabel.df(include="created_by__name"])
Include display of features for `Artifact`:
>>> df = ln.Artifact.df(features=True)
>>> ln.view(df) # visualize with type annotations
Only include select features:
>>> df = ln.Artifact.df(features=["cell_type_by_expert", "cell_type_by_model"])
"""
pass
def search(
cls,
string: str,
*,
field: StrField | None = None,
limit: int | None = 20,
case_sensitive: bool = False,
) -> QuerySet:
"""Search.
Args:
string: The input string to match against the field ontology values.
field: The field or fields to search. Search all string fields by default.
limit: Maximum amount of top results to return.
case_sensitive: Whether the match is case sensitive.
Returns:
A sorted `DataFrame` of search results with a score in column `score`.
If `return_queryset` is `True`. `QuerySet`.
See Also:
:meth:`~lamindb.core.Record.filter`
:meth:`~lamindb.core.Record.lookup`
Examples:
>>> ulabels = ln.ULabel.from_values(["ULabel1", "ULabel2", "ULabel3"], field="name")
>>> ln.save(ulabels)
>>> ln.ULabel.search("ULabel2")
"""
pass
def using(
cls,
instance: str | None,
) -> QuerySet:
"""Use a non-default LaminDB instance.
Args:
instance: An instance identifier of form "account_handle/instance_name".
Examples:
>>> ln.ULabel.using("account_handle/instance_name").search("ULabel7", field="name")
uid score
name
ULabel7 g7Hk9b2v 100.0
ULabel5 t4Jm6s0q 75.0
ULabel6 r2Xw8p1z 75.0
"""
pass
def __get_schema_name__(cls) -> str:
schema_module_name = cls.__module__.split(".")[0]
schema_name = schema_module_name.replace("lnschema_", "")
return schema_name
def __get_name_with_schema__(cls) -> str:
schema_name = cls.__get_schema_name__()
if schema_name == "core":
schema_prefix = ""
else:
schema_prefix = f"{schema_name}."
return f"{schema_prefix}{cls.__name__}"
@doc_args(RECORD_REGISTRY_EXAMPLE)
class Record(models.Model, metaclass=Registry):
"""Base class for metadata records.
Every `Record` is a data model that comes with a registry in form of a SQL
table in your database.
Sub-classing `Record` creates a new registry while instantiating a `Record`
creates a new record.
{}
`Record`'s metaclass is :class:`~lamindb.core.Registry`.
`Record` inherits from Django's `Model` class. Why does LaminDB call it `Record`
and not `Model`? The term `Record` can't lead to confusion with statistical,
machine learning or biological models.
"""
def save(self, *args, **kwargs) -> Record:
"""Save.
Always saves to the default database.
"""
# we need this here because we're using models also from plain
# django outside of lamindb
super().save(*args, **kwargs)
return self
def delete(self) -> None:
"""Delete."""
pass
class Meta:
abstract = True
class FeatureManager:
"""Feature manager."""
pass
class ParamManager:
"""Param manager."""
pass
class ParamManagerArtifact(ParamManager):
"""Param manager."""
pass
class ParamManagerRun(ParamManager):
"""Param manager."""
pass
# -------------------------------------------------------------------------------------
# A note on required fields at the Record level
#
# As Django does most of its validation on the Form-level, it doesn't offer functionality
# for validating the integrity of an Record object upon instantation (similar to pydantic)
#
# For required fields, we define them as commonly done on the SQL level together
# with a validator in Record (validate_required_fields)
#
# This goes against the Django convention, but goes with the SQLModel convention
# (Optional fields can be null on the SQL level, non-optional fields cannot)
#
# Due to Django's convention where CharFieldAttr has pre-configured (null=False, default=""), marking
# a required field necessitates passing `default=None`. Without the validator it would trigger
# an error at the SQL-level, with it, it triggers it at instantiation
# -------------------------------------------------------------------------------------
# A note on class and instance methods of core Record
#
# All of these are defined and tested within lamindb, in files starting with _{orm_name}.py
# -------------------------------------------------------------------------------------
# A note on maximal lengths of char fields
#
# 100 characters:
# "Raindrops pitter-pattered on the windowpane, blurring the"
# "city lights outside, curled up with a mug."
# A good maximal length for a name (title).
#
# 150 characters: We choose this for name maximal length because some users like long names.
#
# 255 characters:
# "In creating a precise 255-character paragraph, one engages in"
# "a dance of words, where clarity meets brevity. Every syllable counts,"
# "illustrating the skill in compact expression, ensuring the essence of the"
# "message shines through within the exacting limit."
# This is a good maximal length for a description field.
class User(Record, CanCurate):
"""Users.
All data in this registry is synched from `lamin.ai` to ensure a universal
user identity. There is no need to manually create records.
Examples:
Query a user by handle:
>>> user = ln.User.get(handle="testuser1")
>>> user
"""
_name_field: str = "handle"
id: int = models.AutoField(primary_key=True)
"""Internal id, valid only in one DB instance."""
uid: str = CharField(unique=True, db_index=True, max_length=8)
"""Universal id, valid across DB instances."""
handle: str = CharField(max_length=30, unique=True, db_index=True)
"""Universal handle, valid across DB instances (required)."""
name: str | None = CharField(max_length=150, db_index=True, null=True)
"""Name (optional).""" # has to match hub specification, where it's also optional
created_artifacts: Artifact
"""Artifacts created by user."""
created_transforms: Transform
"""Transforms created by user."""
created_runs: Run
"""Runs created by user."""
created_at: datetime = DateTimeField(auto_now_add=True, db_index=True)
"""Time of creation of record."""
updated_at: datetime = DateTimeField(auto_now=True, db_index=True)
"""Time of last update to record."""
@overload
def __init__(
self,
handle: str,
email: str,
name: str | None,
): ...
@overload
def __init__(
self,
*db_args,
): ...
def __init__(
self,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
class Storage(Record, TracksRun, TracksUpdates):
"""Storage locations.
A storage location is either a directory/folder (local or in the cloud) or
an entire S3/GCP bucket.
A LaminDB instance can manage and link multiple storage locations. But any
storage location is managed by *at most one* LaminDB instance.
.. dropdown:: Managed vs. linked storage locations
The LaminDB instance can update & delete artifacts in managed storage
locations but merely read artifacts in linked storage locations.
When you transfer artifacts from another instance, the default is to
only copy metadata into the target instance, but merely link the data.
The `instance_uid` field indicates the managing LaminDB instance of a
storage location.
When you delete a LaminDB instance, you'll be warned about data in managed
storage locations while data in linked storage locations is ignored.
See Also:
:attr:`~lamindb.core.Settings.storage`
Default storage.
:attr:`~lamindb.setup.core.StorageSettings`
Storage settings.
Examples:
Configure the default storage location upon initiation of a LaminDB instance::
lamin init --storage ./mydata # or "s3://my-bucket" or "gs://my-bucket"
View the default storage location:
>>> ln.settings.storage
PosixPath('/home/runner/work/lamindb/lamindb/docs/guide/mydata')
Dynamically change the default storage:
>>> ln.settings.storage = "./storage_2" # or a cloud bucket
"""
class Meta(Record.Meta, TracksRun.Meta, TracksUpdates.Meta):
abstract = False
_name_field: str = "root"
id: int = models.AutoField(primary_key=True)