Skip to content

Traits API

Description

Traits represent measurable properties of a Population. A trait can be associated with multiple Experiments.

Module

This module defines the Trait class, which represents a trait entity, including its metadata, associations to experiments, datasets, and records, and related operations.

It includes methods for creating, retrieving, updating, and deleting traits, as well as methods for checking existence, searching, and managing associations with related entities and records.

This module includes the following methods:

  • exists: Check if a trait with the given name exists.
  • create: Create a new trait.
  • get: Retrieve a trait by its name and experiment.
  • get_by_id: Retrieve a trait by its ID.
  • get_all: Retrieve all traits.
  • search: Search for traits based on various criteria.
  • update: Update the details of a trait.
  • delete: Delete a trait.
  • refresh: Refresh the trait's data from the database.
  • get_info: Get the additional information of the trait.
  • set_info: Set the additional information of the trait.
  • Association methods for experiments, datasets, and records.

Trait

Bases: APIBase

Represents a trait entity, including its metadata, associations to experiments, datasets, and records, and related operations.

Attributes:

Name Type Description
id Optional[ID]

The unique identifier of the trait.

trait_name str

The name of the trait.

trait_units str

The units of the trait.

trait_level_id Optional[int]

The ID of the trait level.

trait_info Optional[dict]

Additional information about the trait.

trait_metrics Optional[dict]

Metrics associated with the trait.

Source code in gemini/api/trait.py
 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
class Trait(APIBase):
    """
    Represents a trait entity, including its metadata, associations to experiments, datasets, and records, and related operations.

    Attributes:
        id (Optional[ID]): The unique identifier of the trait.
        trait_name (str): The name of the trait.
        trait_units (str): The units of the trait.
        trait_level_id (Optional[int]): The ID of the trait level.
        trait_info (Optional[dict]): Additional information about the trait.
        trait_metrics (Optional[dict]): Metrics associated with the trait.
    """

    id: Optional[ID] = Field(None, validation_alias=AliasChoices("id", "trait_id"))

    trait_name: str
    trait_units: str
    trait_level_id: Optional[int] = None
    trait_info: Optional[dict] = None
    trait_metrics: Optional[dict] = None

    def __str__(self):
        """Return a string representation of the Trait object."""
        return f"Trait(trait_name={self.trait_name}, id={self.id})"

    def __repr__(self):
        """Return a detailed string representation of the Trait object."""
        return f"Trait(trait_name={self.trait_name}, id={self.id})"

    @classmethod
    def exists(
        cls,
        trait_name: str
    ) -> bool:
        """
        Check if a trait with the given name exists.

        Examples:
            >>> Trait.exists("Leaf Area Index")
            True

            >>> Trait.exists("Nonexistent Trait")
            False

        Args:
            trait_name (str): The name of the trait.
        Returns:
            bool: True if the trait exists, False otherwise.
        """
        try:
            exists = TraitModel.exists(trait_name=trait_name)
            return exists
        except Exception as e:
            logger.error(f"Error checking existence of trait: {e}")
            return False

    @classmethod
    def create(
        cls,
        trait_name: str,
        trait_units: str = None,
        trait_level: GEMINITraitLevel = GEMINITraitLevel.Plot,
        trait_info: dict = None,
        trait_metrics: dict = None,
        experiment_name: str = None
    ) -> Optional["Trait"]:
        """
        Create a new trait and associate it with an experiment if provided.

        Examples:
            >>> Trait.create("Leaf Area Index", "cm^2", GEMINITraitLevel.Plot, {"description": "Leaf area index"}, {"mean": 5.0}, "Experiment 1")
            Trait(trait_name=Leaf Area Index, id=UUID(...))

        Args:
            trait_name (str): The name of the trait.
            trait_units (str, optional): The units of the trait. Defaults to None.
            trait_level (GEMINITraitLevel, optional): The level of the trait. Defaults to Plot.
            trait_info (dict, optional): Additional information. Defaults to {{}}.
            trait_metrics (dict, optional): Metrics associated with the trait. Defaults to {{}}.
            experiment_name (str, optional): The name of the experiment to associate. Defaults to None.
        Returns:
            Optional[Trait]: The created trait, or None if an error occurred.
        """
        try:
            trait_level_id = trait_level.value if isinstance(trait_level, GEMINITraitLevel) else trait_level
            trait = TraitModel.get_or_create(
                trait_name=trait_name,
                trait_units=trait_units,
                trait_level_id=trait_level_id,
                trait_metrics=trait_metrics,
                trait_info=trait_info,
            )
            trait = cls.model_validate(trait)
            if experiment_name:
                trait.associate_experiment(experiment_name)
            return trait
        except Exception as e:
            logger.error(f"Error creating trait: {e}")
            return None

    @classmethod
    def get(
        cls,
        trait_name: str,
        experiment_name: str = None
    ) -> Optional["Trait"]:
        """
        Retrieve a trait by its name and experiment.

        Examples:
            >>> Trait.get("Leaf Area Index", "Experiment 1")
            Trait(trait_name=Leaf Area Index, id=UUID(...))

        Args:
            trait_name (str): The name of the trait.
            experiment_name (str, optional): The name of the experiment. Defaults to None.
        Returns:
            Optional[Trait]: The trait, or None if not found.
        """
        try:
            trait = ExperimentTraitsViewModel.get_by_parameters(
                trait_name=trait_name,
                experiment_name=experiment_name   
            )
            if not trait:
                logger.debug(f"Trait with name {trait_name} not found.")
                return None
            trait = cls.model_validate(trait)
            return trait
        except Exception as e:
            logger.error(f"Error getting trait: {e}")
            return None

    @classmethod
    def get_by_id(cls, id: UUID | int | str) -> Optional["Trait"]:
        """
        Retrieve a trait by its ID.

        Examples:
            >>> Trait.get_by_id(UUID('...'))
            Trait(trait_name=Leaf Area Index, id=UUID(...))

        Args:
            id (UUID | int | str): The ID of the trait.
        Returns:
            Optional[Trait]: The trait, or None if not found.
        """
        try:
            trait = TraitModel.get(id)
            if not trait:
                logger.warning(f"Trait with ID {id} does not exist.")
                return None
            trait = cls.model_validate(trait)
            return trait
        except Exception as e:
            logger.error(f"Error getting trait by ID: {e}")
            return None

    @classmethod
    def get_all(cls, limit: int = None, offset: int = None) -> Optional[List["Trait"]]:
        """
        Retrieve all traits.

        Examples:
            >>> Trait.get_all()
            [Trait(trait_name=Leaf Area Index, id=UUID(...)), Trait(trait_name=Plant Height, id=UUID(...))]

        Returns:
            Optional[List[Trait]]: List of all traits, or None if not found.
        """
        try:
            traits = TraitModel.all(limit=limit, offset=offset)
            if not traits or len(traits) == 0:
                logger.info("No traits found.")
                return None
            traits = [cls.model_validate(trait) for trait in traits]
            return traits
        except Exception as e:
            logger.error(f"Error getting all traits: {e}")
            return None

    @classmethod
    def search(
        cls, 
        trait_name: str = None,
        trait_units: str = None,
        trait_level: GEMINITraitLevel = None,
        trait_info: dict = None,
        trait_metrics: dict = None,
        experiment_name: str = None
    ) -> Optional[List["Trait"]]:
        """
        Search for traits based on various criteria.

        Examples:
            >>> Trait.search(trait_name="Leaf Area Index")
            [Trait(trait_name=Leaf Area Index, id=UUID(...))]

        Args:
            trait_name (str, optional): The name of the trait. Defaults to None.
            trait_units (str, optional): The units of the trait. Defaults to None.
            trait_level (GEMINITraitLevel, optional): The level of the trait. Defaults to None.
            trait_info (dict, optional): Additional information. Defaults to None.
            trait_metrics (dict, optional): Metrics associated with the trait. Defaults to None.
            experiment_name (str, optional): The name of the experiment. Defaults to None.
        Returns:
            Optional[List[Trait]]: List of matching traits, or None if not found.
        """
        try:
            if not any([experiment_name, trait_name, trait_units, trait_level, trait_info, trait_metrics]):
                logger.warning("At least one search parameter must be provided.")
                return None

            traits = ExperimentTraitsViewModel.search(
                experiment_name=experiment_name,
                trait_name=trait_name,
                trait_units=trait_units,
                trait_level_id=trait_level.value if trait_level else None,
                trait_info=trait_info,
                trait_metrics=trait_metrics
            )
            if not traits or len(traits) == 0:
                logger.info("No traits found with the provided search parameters.")
                return None
            traits = [cls.model_validate(trait) for trait in traits]
            return traits if traits else None
        except Exception as e:
            logger.error(f"Error searching traits: {e}")
            return None

    def update(
        self,
        trait_name: str = None, 
        trait_units: str = None,
        trait_level: GEMINITraitLevel = None,
        trait_info: dict = None,
        trait_metrics: dict = None,
    ) -> Optional["Trait"]:
        """
        Update the details of the trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> updated_trait = trait.update(trait_name="New Leaf Area Index", trait_units="m^2")
            >>> print(updated_trait)
            Trait(trait_name=New Leaf Area Index, id=UUID(...))

        Args:
            trait_name (str, optional): The new name. Defaults to None.
            trait_units (str, optional): The new units. Defaults to None.
            trait_level (GEMINITraitLevel, optional): The new level. Defaults to None.
            trait_info (dict, optional): The new information. Defaults to None.
            trait_metrics (dict, optional): The new metrics. Defaults to None.
        Returns:
            Optional[Trait]: The updated trait, or None if an error occurred.
        """
        try:
            if not any([trait_units, trait_level, trait_info, trait_metrics, trait_name]):
                logger.warning("At least one update parameter must be provided.")
                return None

            current_id = self.id
            trait = TraitModel.get(current_id)
            if not trait:
                logger.warning(f"Trait with ID {current_id} does not exist.")
                return None

            rename = trait_name is not None and trait_name != trait.trait_name

            trait = TraitModel.update(
                trait,
                trait_name=trait_name,
                trait_units=trait_units,
                trait_level_id=trait_level.value if trait_level else None,
                trait_info=trait_info,
                trait_metrics=trait_metrics
            )
            if rename:
                from gemini.api._rename_cascade import cascade_rename
                cascade_rename(current_id, "trait_id", "trait_name", trait_name)
            trait = self.model_validate(trait)
            self.refresh()
            return trait
        except Exception as e:
            logger.error(f"Error updating trait: {e}")
            return None

    def delete(self) -> bool:
        """
        Delete the trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> success = trait.delete()
            >>> print(success)
            True

        Returns:
            bool: True if the trait was deleted, False otherwise.
        """
        try:
            current_id = self.id
            trait = TraitModel.get(current_id)
            if not trait:
                logger.warning(f"Trait with ID {current_id} does not exist.")
                return False
            TraitRecordModel.delete_by_trait(self.trait_name)
            TraitModel.delete(trait)
            return True
        except Exception as e:
            logger.error(f"Error deleting trait: {e}")
            return False

    def refresh(self) -> Optional["Trait"]:
        """
        Refresh the trait's data from the database.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> refreshed_trait = trait.refresh()
            >>> print(refreshed_trait)
            Trait(trait_name=Leaf Area Index, id=UUID(...))

        Returns:
            Optional[Trait]: The refreshed trait, or None if an error occurred.
        """
        try:
            db_instance = TraitModel.get(self.id)
            if not db_instance:
                logger.warning(f"Trait with ID {self.id} does not exist.")
                return self
            instance = self.model_validate(db_instance)
            for key, value in instance.model_dump().items():
                if hasattr(self, key) and key != "id":
                    setattr(self, key, value)
            return self
        except Exception as e:
            logger.error(f"Error refreshing trait: {e}")
            return None

    def get_info(self) -> Optional[dict]:
        """
        Get the additional information of the trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> trait_info = trait.get_info()
            >>> print(trait_info)
            {'description': 'Leaf area index', 'source': 'Field measurements'}

        Returns:
            Optional[dict]: The trait's info, or None if not found.
        """
        try:
            current_id = self.id
            trait = TraitModel.get(current_id)
            if not trait:
                logger.warning(f"Trait with ID {current_id} does not exist.")
                return None
            trait_info = trait.trait_info
            if not trait_info:
                logger.info("Trait info is empty.")
                return None
            return trait_info
        except Exception as e:
            logger.error(f"Error getting trait info: {e}")
            return None

    def set_info(self, trait_info: dict) -> Optional["Trait"]:
        """
        Set the additional information of the trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> updated_trait = trait.set_info({"description": "Updated leaf area index", "source": "New measurements"})
            >>> print(updated_trait.get_info())
            {'description': 'Updated leaf area index', 'source': 'New measurements'}

        Args:
            trait_info (dict): The new information to set.
        Returns:
            Optional[Trait]: The updated trait, or None if an error occurred.
        """
        try:
            current_id = self.id
            trait = TraitModel.get(current_id)
            if not trait:
                logger.warning(f"Trait with ID {current_id} does not exist.")
                return None
            trait = TraitModel.update(
                trait,
                trait_info=trait_info
            )
            trait = self.model_validate(trait)
            self.refresh()
            return self
        except Exception as e:
            logger.error(f"Error setting trait info: {e}")
            return None

    def get_associated_experiments(self) -> Optional[List["Experiment"]]:
        """
        Get all experiments associated with this trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> experiments = trait.get_associated_experiments()
            >>> for experiment in experiments:
            ...     print(experiment)
            Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))
            Experiment(experiment_name=Experiment 2, experiment_start_date=2023-02-01, experiment_end_date=2023-11-30, id=UUID(...))

        Returns:
            Optional[List[Experiment]]: A list of associated experiments, or None if not found.
        """
        try:
            from gemini.api.experiment import Experiment
            experiment_traits = ExperimentTraitsViewModel.search(trait_id=self.id)
            if not experiment_traits or len(experiment_traits) == 0:
                logger.info("No associated experiments found.")
                return None
            experiments = [Experiment.model_validate(experiment) for experiment in experiment_traits]
            return experiments
        except Exception as e:
            logger.error(f"Error getting associated experiments: {e}")
            return None

    def associate_experiment(self, experiment_name: str) -> Optional["Experiment"]:
        """
        Associate this trait with an experiment.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> experiment = trait.associate_experiment("Experiment 1")
            >>> print(experiment)
            Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))

        Args:
            experiment_name (str): The name of the experiment to associate.
        Returns:
            Optional[Experiment]: The associated experiment, or None if an error occurred.
        """
        try:
            from gemini.api.experiment import Experiment
            experiment = Experiment.get(experiment_name)
            if not experiment:
                logger.warning(f"Experiment {experiment_name} does not exist.")
                return None
            existing_association = ExperimentTraitModel.get_by_parameters(
                experiment_id=experiment.id,
                trait_id=self.id
            )
            if existing_association:
                logger.info(f"Trait {self.trait_name} is already associated with experiment {experiment_name}.")
                return True
            new_association = ExperimentTraitModel.get_or_create(
                experiment_id=experiment.id,
                trait_id=self.id
            )
            if not new_association:
                logger.info(f"Failed to associate trait {self.trait_name} with experiment {experiment_name}.")
                return False
            self.refresh()
            return experiment
        except Exception as e:
            logger.error(f"Error associating experiment: {e}")
            return None

    def unassociate_experiment(self, experiment_name: str) -> Optional["Experiment"]:
        """
        Unassociate this trait from an experiment.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> experiment = trait.unassociate_experiment("Experiment 1")
            >>> print(experiment)
            Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))

        Args:
            experiment_name (str): The name of the experiment to unassociate.
        Returns:
            Optional[Experiment]: The unassociated experiment, or None if an error occurred.
        """
        try:
            from gemini.api.experiment import Experiment
            experiment = Experiment.get(experiment_name)
            if not experiment:
                logger.warning(f"Experiment {experiment_name} does not exist.")
                return None
            existing_association = ExperimentTraitModel.get_by_parameters(
                experiment_id=experiment.id,
                trait_id=self.id
            )
            if not existing_association:
                logger.info(f"Trait {self.trait_name} is not associated with experiment {experiment_name}.")
                return None
            is_deleted = ExperimentTraitModel.delete(existing_association)
            if not is_deleted:
                logger.info(f"Failed to unassociate trait {self.trait_name} from experiment {experiment_name}.")
                return False
            self.refresh()
            return experiment
        except Exception as e:
            logger.error(f"Error unassociating experiment: {e}")
            return None

    def belongs_to_experiment(self, experiment_name: str) -> bool:
        """
        Check if this trait is associated with a specific experiment.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> is_associated = trait.belongs_to_experiment("Experiment 1")
            >>> print(is_associated)
            True

        Args:
            experiment_name (str): The name of the experiment to check.
        Returns:
            bool: True if associated, False otherwise.
        """
        try:
            from gemini.api.experiment import Experiment
            experiment = Experiment.get(experiment_name)
            if not experiment:
                logger.warning(f"Experiment {experiment_name} does not exist.")
                return False
            association_exists = ExperimentTraitModel.exists(
                experiment_id=experiment.id,
                trait_id=self.id
            )
            return association_exists
        except Exception as e:
            logger.error(f"Error checking if trait belongs to experiment: {e}")
            return

    def get_associated_datasets(self) -> Optional[List["Dataset"]]:
        """
        Get all datasets associated with this trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> datasets = trait.get_associated_datasets()
            >>> for dataset in datasets:
            ...     print(dataset)
            Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))
            Dataset(dataset_name=Leaf Area Index Dataset 2023-02-01, dataset_type=Trait, collection_date=2023-02-01, id=UUID(...))

        Returns:
            Optional[List[Dataset]]: A list of associated datasets, or None if not found.
        """
        try:
            from gemini.api.dataset import Dataset
            datasets = TraitDatasetsViewModel.search(trait_id=self.id)
            if not datasets or len(datasets) == 0:
                logger.info("No associated datasets found.")
                return None
            datasets = [Dataset.model_validate(dataset) for dataset in datasets]
            return datasets
        except Exception as e:
            logger.error(f"Error getting associated datasets: {e}")
            return None

    def create_new_dataset(
        self,
        dataset_name: str,
        dataset_info: dict = None,
        collection_date: date = None,
        experiment_name: str = None
    ) -> Optional["Dataset"]:
        """
        Create and associate a new dataset with this trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> dataset = trait.create_new_dataset("Leaf Area Index Dataset 2023-01-01", {"description": "Dataset for leaf area index"}, date(2023, 1, 1), "Experiment 1")
            >>> print(dataset)
            Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))

        Args:
            dataset_name (str): The name of the new dataset.
            dataset_info (dict, optional): Additional information. Defaults to {{}}.
            collection_date (date, optional): The collection date. Defaults to None.
            experiment_name (str, optional): The name of the experiment. Defaults to None.
        Returns:
            Optional[Dataset]: The created and associated dataset, or None if an error occurred.
        """
        try:
            from gemini.api.dataset import Dataset
            dataset = Dataset.create(
                dataset_name=dataset_name,
                dataset_info=dataset_info,
                dataset_type=GEMINIDatasetType.Trait,
                collection_date=collection_date,
                experiment_name=experiment_name
            )
            if not dataset:
                logger.info(f"Failed to create dataset {dataset_name}.")
                return None
            dataset = self.associate_dataset(dataset_name)
            return dataset
        except Exception as e:
            logger.error(f"Error creating new dataset: {e}")
            return None

    def associate_dataset(self, dataset_name: str) -> Optional["Dataset"]:
        """
        Associate this trait with a dataset.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> dataset = trait.associate_dataset("Leaf Area Index Dataset 2023-01-01")
            >>> print(dataset)
            Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))

        Args:
            dataset_name (str): The name of the dataset to associate.
        Returns:
            Optional[Dataset]: The associated dataset, or None if an error occurred.
        """
        try:
            from gemini.api.dataset import Dataset
            dataset = Dataset.get(dataset_name)
            if not dataset:
                logger.warning(f"Dataset {dataset_name} does not exist.")
                return None
            existing_association = TraitDatasetModel.get_by_parameters(
                trait_id=self.id,
                dataset_id=dataset.id
            )
            if existing_association:
                logger.info(f"Trait {self.trait_name} is already associated with dataset {dataset_name}.")
                return True
            new_association = TraitDatasetModel.get_or_create(
                trait_id=self.id,
                dataset_id=dataset.id
            )
            if not new_association:
                logger.info(f"Failed to associate trait {self.trait_name} with dataset {dataset_name}.")
                return False
            self.refresh()
            return dataset
        except Exception as e:
            logger.error(f"Error associating dataset: {e}")
            return None

    def insert_record(
        self,
        timestamp: date = None,
        collection_date: date = None,
        dataset_name: str = None,
        trait_value: float = None,
        experiment_name: str = None,
        season_name: str = None,
        site_name: str = None,
        plot_number: int = -1,
        plot_row_number: int = -1,
        plot_column_number: int = -1,
        record_info: dict = None
    ) -> tuple[bool, List[str]]:
        """
        Insert a single trait record for this trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> success, record_ids = trait.insert_record(
            ...     timestamp=datetime.now(),
            ...     collection_date=date(2023, 1, 1),
            ...     dataset_name="Leaf Area Index Dataset 2023-01-01",
            ...     trait_value=5.0,
            ...     experiment_name="Experiment 1",
            ...     season_name="Spring 2023",
            ...     site_name="Field Site A",
            ...     plot_number=1,
            ...     plot_row_number=1,
            ...     plot_column_number=1,
            ...     record_info={"description": "Leaf area index measurement"}
            ... )
            >>> print(success, record_ids)
            True [UUID(...)]

        Args:
            timestamp (datetime, optional): The timestamp of the record. Defaults to None.
            collection_date (date, optional): The collection date. Defaults to None.
            dataset_name (str, optional): The name of the dataset. Defaults to None.
            trait_value (float, optional): The value of the trait. Defaults to None.
            experiment_name (str, optional): The name of the experiment. Defaults to None.
            season_name (str, optional): The name of the season. Defaults to None.
            site_name (str, optional): The name of the site. Defaults to None.
            plot_number (int, optional): The plot number. Defaults to -1.
            plot_row_number (int, optional): The plot row number. Defaults to -1.
            plot_column_number (int, optional): The plot column number. Defaults to -1.
            record_info (dict, optional): Additional info. Defaults to {{}}.
        Returns:
            tuple[bool, List[str]]: Success status and list of inserted record IDs.
        """
        try:
            if not experiment_name or not season_name or not site_name:
                raise ValueError("Experiment name, season name, and site name must be provided.")

            if not trait_value:
                raise ValueError("Trait value must be provided.")

            timestamp = timestamp if timestamp else datetime.now()
            collection_date = collection_date if collection_date else timestamp.date()
            trait_name = self.trait_name
            if not dataset_name:
                dataset_name = f"{trait_name} Dataset {collection_date}"
            trait_record = TraitRecord.create(
                timestamp=timestamp,
                collection_date=collection_date,
                trait_name=trait_name,
                dataset_name=dataset_name,
                trait_value=trait_value,
                experiment_name=experiment_name,
                season_name=season_name,
                site_name=site_name,
                plot_number=plot_number if plot_number != -1 else None,
                plot_row_number=plot_row_number if plot_row_number != -1 else None,
                plot_column_number=plot_column_number if plot_column_number != -1 else None,
                record_info=record_info if record_info else {},
                insert_on_create=False
            )
            success, inserted_record_ids = TraitRecord.insert([trait_record])
            if not success:
                logger.info(f"Failed to insert record for trait {trait_name}.")
                return False, []
            return success, inserted_record_ids
        except Exception as e:
            logger.error(f"Error inserting record: {e}")
            return False, []

    def insert_records(
        self,
        timestamps: List[datetime] = None,
        collection_date: date = None,
        trait_values: List[float] = None,
        dataset_name: str = None,
        experiment_name: str = None,
        season_name: str = None,
        site_name: str = None,
        plot_numbers: List[int] = None,
        plot_row_numbers: List[int] = None,
        plot_column_numbers: List[int] = None,
        record_info: List[dict] = None
    ) -> tuple[bool, List[str]]:
        """
        Insert multiple trait records for this trait.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> success, record_ids = trait.insert_records(
            ...     timestamps=[datetime.now(), datetime.now()],
            ...     collection_date=date(2023, 1, 1),
            ...     trait_values=[5.0, 6.0],
            ...     dataset_name="Leaf Area Index Dataset 2023-01-01",
            ...     experiment_name="Experiment 1",
            ...     season_name="Spring 2023",
            ...     site_name="Field Site A",
            ...     plot_numbers=[1, 2],
            ...     plot_row_numbers=[1, 2],
            ...     plot_column_numbers=[1, 2],
            ...     record_info=[{"description": "Leaf area index measurement 1"}, {"description": "Leaf area index measurement 2"}]
            ... )
            >>> print(success, record_ids)
            True [UUID(...), UUID(...)]

        Args:
            timestamps (List[datetime], optional): List of timestamps. Defaults to None.
            collection_date (date, optional): The collection date. Defaults to None.
            trait_values (List[float], optional): List of trait values. Defaults to [].
            dataset_name (str, optional): The name of the dataset. Defaults to None.
            experiment_name (str, optional): The name of the experiment. Defaults to None.
            season_name (str, optional): The name of the season. Defaults to None.
            site_name (str, optional): The name of the site. Defaults to None.
            plot_numbers (List[int], optional): List of plot numbers. Defaults to None.
            plot_row_numbers (List[int], optional): List of plot row numbers. Defaults to None.
            plot_column_numbers (List[int], optional): List of plot column numbers. Defaults to None.
            record_info (List[dict], optional): List of additional info. Defaults to [].
        Returns:
            tuple[bool, List[str]]: Success status and list of inserted record IDs.
        """
        try:
            if not experiment_name or not season_name or not site_name:
                raise ValueError("Experiment name, season name, and site name must be provided.")

            if len(timestamps) == 0:
                raise ValueError("At least one timestamp must be provided.")

            if not dataset_name:
                dataset_name = f"{self.trait_name} Dataset {collection_date}"

            collection_date = collection_date if collection_date else timestamps[0].date()
            trait_records = []
            timestamps_length = len(timestamps)

            for i in tqdm(range(timestamps_length), desc="Arranging Records for Trait: " + self.trait_name):
                trait_record = TraitRecord.create(
                    timestamp=timestamps[i],
                    collection_date=collection_date,
                    trait_name=self.trait_name,
                    trait_value=trait_values[i] if trait_values else None,
                    dataset_name=dataset_name if dataset_name else f"{self.trait_name} Dataset {collection_date}",
                    experiment_name=experiment_name,
                    season_name=season_name,
                    site_name=site_name,
                    plot_number=plot_numbers[i] if plot_numbers else None,
                    plot_row_number=plot_row_numbers[i] if plot_row_numbers else None,
                    plot_column_number=plot_column_numbers[i] if plot_column_numbers else None,
                    record_info=record_info[i] if record_info else {},
                    insert_on_create=False
                )
                trait_records.append(trait_record)

            success, inserted_record_ids = TraitRecord.insert(trait_records)
            return success, inserted_record_ids
        except ValueError:
            raise
        except DBAPIError:
            # Let database errors (trigger RAISEs, constraint violations)
            # propagate so the REST layer can surface the real cause.
            raise
        except Exception as e:
            logger.error(f"Error inserting records: {e}")
            return False, []

    def search_records(
        self,
        collection_date: date = None,
        dataset_name: str = None,
        experiment_name: str = None,
        season_name: str = None,
        site_name: str = None,
        plot_number: int = None,
        plot_row_number: int = None,
        plot_column_number: int = None,
        record_info: dict = None
    ) -> List[TraitRecord]:
        """
        Search for trait records associated with this trait based on search parameters.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> records = trait.search_records(
            ...     collection_date=date(2023, 1, 1),
            ...     dataset_name="Leaf Area Index Dataset 2023-01-01",
            ...     experiment_name="Experiment 1",
            ...     season_name="Spring 2023",
            ...     site_name="Field Site A",
            ...     plot_number=1,
            ...     plot_row_number=1,
            ...     plot_column_number=1,
            ...     record_info={"description": "Leaf area index measurement"}
            ... )
            >>> for record in records:
            ...     print(record)
            TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=1, plot_row_number=1, plot_column_number=1)
            TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=2, plot_row_number=2, plot_column_number=2)

        Args:
            collection_date (date, optional): The collection date. Defaults to None.
            dataset_name (str, optional): The name of the dataset. Defaults to None.
            experiment_name (str, optional): The name of the experiment. Defaults to None.
            season_name (str, optional): The name of the season. Defaults to None.
            site_name (str, optional): The name of the site. Defaults to None.
            plot_number (int, optional): The plot number. Defaults to None.
            plot_row_number (int, optional): The plot row number. Defaults to None.
            plot_column_number (int, optional): The plot column number. Defaults to None.
            record_info (dict, optional): Additional info. Defaults to None.
        Returns:
            List[TraitRecord]: List of matching trait records, or empty list if not found.
        """
        try:
            record_info = record_info if record_info else {}
            record_info = {k: v for k, v in record_info.items() if v is not None}

            records = TraitRecord.search(
                trait_name=self.trait_name,
                collection_date=collection_date,
                dataset_name=dataset_name,
                experiment_name=experiment_name,
                season_name=season_name,
                site_name=site_name,
                plot_number=plot_number,
                plot_row_number=plot_row_number,
                plot_column_number=plot_column_number,
                record_info=record_info
            )
            return records
        except Exception as e:
            logger.error(f"Error searching records: {e}")
            return []

    def filter_records(
        self,
        start_timestamp: Optional[datetime] = None,
        end_timestamp: Optional[datetime] = None,
        dataset_names: Optional[List[str]] = None,
        experiment_names: Optional[List[str]] = None,
        season_names: Optional[List[str]] = None,
        site_names: Optional[List[str]] = None
    ) -> List[TraitRecord]:
        """
        Filter trait records associated with this trait using a custom filter function.

        Examples:
            >>> trait = Trait.get("Leaf Area Index")
            >>> records = trait.filter_records(
            ...     start_timestamp=datetime(2023, 1, 1),
            ...     end_timestamp=datetime(2023, 12, 31),
            ...     dataset_names=["Leaf Area Index Dataset 2023-01-01"],
            ...     experiment_names=["Experiment 1"],
            ...     season_names=["Spring 2023"],
            ...     site_names=["Field Site A"]
            ... )
            >>> for record in records:
            ...     print(record)
            TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=1, plot_row_number=1, plot_column_number=1)
            TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=2, plot_row_number=2, plot_column_number=2)

        Args:
            start_timestamp (datetime, optional): Start of timestamp range. Defaults to None.
            end_timestamp (datetime, optional): End of timestamp range. Defaults to None.
            dataset_names (List[str], optional): List of dataset names. Defaults to None.
            experiment_names (List[str], optional): List of experiment names. Defaults to None.
            season_names (List[str], optional): List of season names. Defaults to None.
            site_names (List[str], optional): List of site names. Defaults to None.
        Returns:
            List[TraitRecord]: List of filtered trait records, or empty list if not found.
        """
        try:
            records = TraitRecord.filter(
                start_timestamp=start_timestamp,
                end_timestamp=end_timestamp,
                trait_names=[self.trait_name],
                dataset_names=dataset_names,
                experiment_names=experiment_names,
                season_names=season_names,
                site_names=site_names
            )
            return records
        except Exception as e:
            logger.error(f"Error filtering trait records: {e}")
            return []

__repr__()

Return a detailed string representation of the Trait object.

Source code in gemini/api/trait.py
def __repr__(self):
    """Return a detailed string representation of the Trait object."""
    return f"Trait(trait_name={self.trait_name}, id={self.id})"

__str__()

Return a string representation of the Trait object.

Source code in gemini/api/trait.py
def __str__(self):
    """Return a string representation of the Trait object."""
    return f"Trait(trait_name={self.trait_name}, id={self.id})"

associate_dataset(dataset_name)

Associate this trait with a dataset.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> dataset = trait.associate_dataset("Leaf Area Index Dataset 2023-01-01")
>>> print(dataset)
Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset to associate.

required

Returns: Optional[Dataset]: The associated dataset, or None if an error occurred.

Source code in gemini/api/trait.py
def associate_dataset(self, dataset_name: str) -> Optional["Dataset"]:
    """
    Associate this trait with a dataset.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> dataset = trait.associate_dataset("Leaf Area Index Dataset 2023-01-01")
        >>> print(dataset)
        Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))

    Args:
        dataset_name (str): The name of the dataset to associate.
    Returns:
        Optional[Dataset]: The associated dataset, or None if an error occurred.
    """
    try:
        from gemini.api.dataset import Dataset
        dataset = Dataset.get(dataset_name)
        if not dataset:
            logger.warning(f"Dataset {dataset_name} does not exist.")
            return None
        existing_association = TraitDatasetModel.get_by_parameters(
            trait_id=self.id,
            dataset_id=dataset.id
        )
        if existing_association:
            logger.info(f"Trait {self.trait_name} is already associated with dataset {dataset_name}.")
            return True
        new_association = TraitDatasetModel.get_or_create(
            trait_id=self.id,
            dataset_id=dataset.id
        )
        if not new_association:
            logger.info(f"Failed to associate trait {self.trait_name} with dataset {dataset_name}.")
            return False
        self.refresh()
        return dataset
    except Exception as e:
        logger.error(f"Error associating dataset: {e}")
        return None

associate_experiment(experiment_name)

Associate this trait with an experiment.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> experiment = trait.associate_experiment("Experiment 1")
>>> print(experiment)
Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))

Parameters:

Name Type Description Default
experiment_name str

The name of the experiment to associate.

required

Returns: Optional[Experiment]: The associated experiment, or None if an error occurred.

Source code in gemini/api/trait.py
def associate_experiment(self, experiment_name: str) -> Optional["Experiment"]:
    """
    Associate this trait with an experiment.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> experiment = trait.associate_experiment("Experiment 1")
        >>> print(experiment)
        Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))

    Args:
        experiment_name (str): The name of the experiment to associate.
    Returns:
        Optional[Experiment]: The associated experiment, or None if an error occurred.
    """
    try:
        from gemini.api.experiment import Experiment
        experiment = Experiment.get(experiment_name)
        if not experiment:
            logger.warning(f"Experiment {experiment_name} does not exist.")
            return None
        existing_association = ExperimentTraitModel.get_by_parameters(
            experiment_id=experiment.id,
            trait_id=self.id
        )
        if existing_association:
            logger.info(f"Trait {self.trait_name} is already associated with experiment {experiment_name}.")
            return True
        new_association = ExperimentTraitModel.get_or_create(
            experiment_id=experiment.id,
            trait_id=self.id
        )
        if not new_association:
            logger.info(f"Failed to associate trait {self.trait_name} with experiment {experiment_name}.")
            return False
        self.refresh()
        return experiment
    except Exception as e:
        logger.error(f"Error associating experiment: {e}")
        return None

belongs_to_experiment(experiment_name)

Check if this trait is associated with a specific experiment.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> is_associated = trait.belongs_to_experiment("Experiment 1")
>>> print(is_associated)
True

Parameters:

Name Type Description Default
experiment_name str

The name of the experiment to check.

required

Returns: bool: True if associated, False otherwise.

Source code in gemini/api/trait.py
def belongs_to_experiment(self, experiment_name: str) -> bool:
    """
    Check if this trait is associated with a specific experiment.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> is_associated = trait.belongs_to_experiment("Experiment 1")
        >>> print(is_associated)
        True

    Args:
        experiment_name (str): The name of the experiment to check.
    Returns:
        bool: True if associated, False otherwise.
    """
    try:
        from gemini.api.experiment import Experiment
        experiment = Experiment.get(experiment_name)
        if not experiment:
            logger.warning(f"Experiment {experiment_name} does not exist.")
            return False
        association_exists = ExperimentTraitModel.exists(
            experiment_id=experiment.id,
            trait_id=self.id
        )
        return association_exists
    except Exception as e:
        logger.error(f"Error checking if trait belongs to experiment: {e}")
        return

create(trait_name, trait_units=None, trait_level=GEMINITraitLevel.Plot, trait_info=None, trait_metrics=None, experiment_name=None) classmethod

Create a new trait and associate it with an experiment if provided.

Examples:

>>> Trait.create("Leaf Area Index", "cm^2", GEMINITraitLevel.Plot, {"description": "Leaf area index"}, {"mean": 5.0}, "Experiment 1")
Trait(trait_name=Leaf Area Index, id=UUID(...))

Parameters:

Name Type Description Default
trait_name str

The name of the trait.

required
trait_units str

The units of the trait. Defaults to None.

None
trait_level GEMINITraitLevel

The level of the trait. Defaults to Plot.

Plot
trait_info dict

Additional information. Defaults to {{}}.

None
trait_metrics dict

Metrics associated with the trait. Defaults to {{}}.

None
experiment_name str

The name of the experiment to associate. Defaults to None.

None

Returns: Optional[Trait]: The created trait, or None if an error occurred.

Source code in gemini/api/trait.py
@classmethod
def create(
    cls,
    trait_name: str,
    trait_units: str = None,
    trait_level: GEMINITraitLevel = GEMINITraitLevel.Plot,
    trait_info: dict = None,
    trait_metrics: dict = None,
    experiment_name: str = None
) -> Optional["Trait"]:
    """
    Create a new trait and associate it with an experiment if provided.

    Examples:
        >>> Trait.create("Leaf Area Index", "cm^2", GEMINITraitLevel.Plot, {"description": "Leaf area index"}, {"mean": 5.0}, "Experiment 1")
        Trait(trait_name=Leaf Area Index, id=UUID(...))

    Args:
        trait_name (str): The name of the trait.
        trait_units (str, optional): The units of the trait. Defaults to None.
        trait_level (GEMINITraitLevel, optional): The level of the trait. Defaults to Plot.
        trait_info (dict, optional): Additional information. Defaults to {{}}.
        trait_metrics (dict, optional): Metrics associated with the trait. Defaults to {{}}.
        experiment_name (str, optional): The name of the experiment to associate. Defaults to None.
    Returns:
        Optional[Trait]: The created trait, or None if an error occurred.
    """
    try:
        trait_level_id = trait_level.value if isinstance(trait_level, GEMINITraitLevel) else trait_level
        trait = TraitModel.get_or_create(
            trait_name=trait_name,
            trait_units=trait_units,
            trait_level_id=trait_level_id,
            trait_metrics=trait_metrics,
            trait_info=trait_info,
        )
        trait = cls.model_validate(trait)
        if experiment_name:
            trait.associate_experiment(experiment_name)
        return trait
    except Exception as e:
        logger.error(f"Error creating trait: {e}")
        return None

create_new_dataset(dataset_name, dataset_info=None, collection_date=None, experiment_name=None)

Create and associate a new dataset with this trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> dataset = trait.create_new_dataset("Leaf Area Index Dataset 2023-01-01", {"description": "Dataset for leaf area index"}, date(2023, 1, 1), "Experiment 1")
>>> print(dataset)
Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))

Parameters:

Name Type Description Default
dataset_name str

The name of the new dataset.

required
dataset_info dict

Additional information. Defaults to {{}}.

None
collection_date date

The collection date. Defaults to None.

None
experiment_name str

The name of the experiment. Defaults to None.

None

Returns: Optional[Dataset]: The created and associated dataset, or None if an error occurred.

Source code in gemini/api/trait.py
def create_new_dataset(
    self,
    dataset_name: str,
    dataset_info: dict = None,
    collection_date: date = None,
    experiment_name: str = None
) -> Optional["Dataset"]:
    """
    Create and associate a new dataset with this trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> dataset = trait.create_new_dataset("Leaf Area Index Dataset 2023-01-01", {"description": "Dataset for leaf area index"}, date(2023, 1, 1), "Experiment 1")
        >>> print(dataset)
        Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))

    Args:
        dataset_name (str): The name of the new dataset.
        dataset_info (dict, optional): Additional information. Defaults to {{}}.
        collection_date (date, optional): The collection date. Defaults to None.
        experiment_name (str, optional): The name of the experiment. Defaults to None.
    Returns:
        Optional[Dataset]: The created and associated dataset, or None if an error occurred.
    """
    try:
        from gemini.api.dataset import Dataset
        dataset = Dataset.create(
            dataset_name=dataset_name,
            dataset_info=dataset_info,
            dataset_type=GEMINIDatasetType.Trait,
            collection_date=collection_date,
            experiment_name=experiment_name
        )
        if not dataset:
            logger.info(f"Failed to create dataset {dataset_name}.")
            return None
        dataset = self.associate_dataset(dataset_name)
        return dataset
    except Exception as e:
        logger.error(f"Error creating new dataset: {e}")
        return None

delete()

Delete the trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> success = trait.delete()
>>> print(success)
True

Returns:

Name Type Description
bool bool

True if the trait was deleted, False otherwise.

Source code in gemini/api/trait.py
def delete(self) -> bool:
    """
    Delete the trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> success = trait.delete()
        >>> print(success)
        True

    Returns:
        bool: True if the trait was deleted, False otherwise.
    """
    try:
        current_id = self.id
        trait = TraitModel.get(current_id)
        if not trait:
            logger.warning(f"Trait with ID {current_id} does not exist.")
            return False
        TraitRecordModel.delete_by_trait(self.trait_name)
        TraitModel.delete(trait)
        return True
    except Exception as e:
        logger.error(f"Error deleting trait: {e}")
        return False

exists(trait_name) classmethod

Check if a trait with the given name exists.

Examples:

>>> Trait.exists("Leaf Area Index")
True
>>> Trait.exists("Nonexistent Trait")
False

Parameters:

Name Type Description Default
trait_name str

The name of the trait.

required

Returns: bool: True if the trait exists, False otherwise.

Source code in gemini/api/trait.py
@classmethod
def exists(
    cls,
    trait_name: str
) -> bool:
    """
    Check if a trait with the given name exists.

    Examples:
        >>> Trait.exists("Leaf Area Index")
        True

        >>> Trait.exists("Nonexistent Trait")
        False

    Args:
        trait_name (str): The name of the trait.
    Returns:
        bool: True if the trait exists, False otherwise.
    """
    try:
        exists = TraitModel.exists(trait_name=trait_name)
        return exists
    except Exception as e:
        logger.error(f"Error checking existence of trait: {e}")
        return False

filter_records(start_timestamp=None, end_timestamp=None, dataset_names=None, experiment_names=None, season_names=None, site_names=None)

Filter trait records associated with this trait using a custom filter function.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> records = trait.filter_records(
...     start_timestamp=datetime(2023, 1, 1),
...     end_timestamp=datetime(2023, 12, 31),
...     dataset_names=["Leaf Area Index Dataset 2023-01-01"],
...     experiment_names=["Experiment 1"],
...     season_names=["Spring 2023"],
...     site_names=["Field Site A"]
... )
>>> for record in records:
...     print(record)
TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=1, plot_row_number=1, plot_column_number=1)
TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=2, plot_row_number=2, plot_column_number=2)

Parameters:

Name Type Description Default
start_timestamp datetime

Start of timestamp range. Defaults to None.

None
end_timestamp datetime

End of timestamp range. Defaults to None.

None
dataset_names List[str]

List of dataset names. Defaults to None.

None
experiment_names List[str]

List of experiment names. Defaults to None.

None
season_names List[str]

List of season names. Defaults to None.

None
site_names List[str]

List of site names. Defaults to None.

None

Returns: List[TraitRecord]: List of filtered trait records, or empty list if not found.

Source code in gemini/api/trait.py
def filter_records(
    self,
    start_timestamp: Optional[datetime] = None,
    end_timestamp: Optional[datetime] = None,
    dataset_names: Optional[List[str]] = None,
    experiment_names: Optional[List[str]] = None,
    season_names: Optional[List[str]] = None,
    site_names: Optional[List[str]] = None
) -> List[TraitRecord]:
    """
    Filter trait records associated with this trait using a custom filter function.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> records = trait.filter_records(
        ...     start_timestamp=datetime(2023, 1, 1),
        ...     end_timestamp=datetime(2023, 12, 31),
        ...     dataset_names=["Leaf Area Index Dataset 2023-01-01"],
        ...     experiment_names=["Experiment 1"],
        ...     season_names=["Spring 2023"],
        ...     site_names=["Field Site A"]
        ... )
        >>> for record in records:
        ...     print(record)
        TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=1, plot_row_number=1, plot_column_number=1)
        TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=2, plot_row_number=2, plot_column_number=2)

    Args:
        start_timestamp (datetime, optional): Start of timestamp range. Defaults to None.
        end_timestamp (datetime, optional): End of timestamp range. Defaults to None.
        dataset_names (List[str], optional): List of dataset names. Defaults to None.
        experiment_names (List[str], optional): List of experiment names. Defaults to None.
        season_names (List[str], optional): List of season names. Defaults to None.
        site_names (List[str], optional): List of site names. Defaults to None.
    Returns:
        List[TraitRecord]: List of filtered trait records, or empty list if not found.
    """
    try:
        records = TraitRecord.filter(
            start_timestamp=start_timestamp,
            end_timestamp=end_timestamp,
            trait_names=[self.trait_name],
            dataset_names=dataset_names,
            experiment_names=experiment_names,
            season_names=season_names,
            site_names=site_names
        )
        return records
    except Exception as e:
        logger.error(f"Error filtering trait records: {e}")
        return []

get(trait_name, experiment_name=None) classmethod

Retrieve a trait by its name and experiment.

Examples:

>>> Trait.get("Leaf Area Index", "Experiment 1")
Trait(trait_name=Leaf Area Index, id=UUID(...))

Parameters:

Name Type Description Default
trait_name str

The name of the trait.

required
experiment_name str

The name of the experiment. Defaults to None.

None

Returns: Optional[Trait]: The trait, or None if not found.

Source code in gemini/api/trait.py
@classmethod
def get(
    cls,
    trait_name: str,
    experiment_name: str = None
) -> Optional["Trait"]:
    """
    Retrieve a trait by its name and experiment.

    Examples:
        >>> Trait.get("Leaf Area Index", "Experiment 1")
        Trait(trait_name=Leaf Area Index, id=UUID(...))

    Args:
        trait_name (str): The name of the trait.
        experiment_name (str, optional): The name of the experiment. Defaults to None.
    Returns:
        Optional[Trait]: The trait, or None if not found.
    """
    try:
        trait = ExperimentTraitsViewModel.get_by_parameters(
            trait_name=trait_name,
            experiment_name=experiment_name   
        )
        if not trait:
            logger.debug(f"Trait with name {trait_name} not found.")
            return None
        trait = cls.model_validate(trait)
        return trait
    except Exception as e:
        logger.error(f"Error getting trait: {e}")
        return None

get_all(limit=None, offset=None) classmethod

Retrieve all traits.

Examples:

>>> Trait.get_all()
[Trait(trait_name=Leaf Area Index, id=UUID(...)), Trait(trait_name=Plant Height, id=UUID(...))]

Returns:

Type Description
Optional[List[Trait]]

Optional[List[Trait]]: List of all traits, or None if not found.

Source code in gemini/api/trait.py
@classmethod
def get_all(cls, limit: int = None, offset: int = None) -> Optional[List["Trait"]]:
    """
    Retrieve all traits.

    Examples:
        >>> Trait.get_all()
        [Trait(trait_name=Leaf Area Index, id=UUID(...)), Trait(trait_name=Plant Height, id=UUID(...))]

    Returns:
        Optional[List[Trait]]: List of all traits, or None if not found.
    """
    try:
        traits = TraitModel.all(limit=limit, offset=offset)
        if not traits or len(traits) == 0:
            logger.info("No traits found.")
            return None
        traits = [cls.model_validate(trait) for trait in traits]
        return traits
    except Exception as e:
        logger.error(f"Error getting all traits: {e}")
        return None

get_associated_datasets()

Get all datasets associated with this trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> datasets = trait.get_associated_datasets()
>>> for dataset in datasets:
...     print(dataset)
Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))
Dataset(dataset_name=Leaf Area Index Dataset 2023-02-01, dataset_type=Trait, collection_date=2023-02-01, id=UUID(...))

Returns:

Type Description
Optional[List[Dataset]]

Optional[List[Dataset]]: A list of associated datasets, or None if not found.

Source code in gemini/api/trait.py
def get_associated_datasets(self) -> Optional[List["Dataset"]]:
    """
    Get all datasets associated with this trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> datasets = trait.get_associated_datasets()
        >>> for dataset in datasets:
        ...     print(dataset)
        Dataset(dataset_name=Leaf Area Index Dataset 2023-01-01, dataset_type=Trait, collection_date=2023-01-01, id=UUID(...))
        Dataset(dataset_name=Leaf Area Index Dataset 2023-02-01, dataset_type=Trait, collection_date=2023-02-01, id=UUID(...))

    Returns:
        Optional[List[Dataset]]: A list of associated datasets, or None if not found.
    """
    try:
        from gemini.api.dataset import Dataset
        datasets = TraitDatasetsViewModel.search(trait_id=self.id)
        if not datasets or len(datasets) == 0:
            logger.info("No associated datasets found.")
            return None
        datasets = [Dataset.model_validate(dataset) for dataset in datasets]
        return datasets
    except Exception as e:
        logger.error(f"Error getting associated datasets: {e}")
        return None

get_associated_experiments()

Get all experiments associated with this trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> experiments = trait.get_associated_experiments()
>>> for experiment in experiments:
...     print(experiment)
Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))
Experiment(experiment_name=Experiment 2, experiment_start_date=2023-02-01, experiment_end_date=2023-11-30, id=UUID(...))

Returns:

Type Description
Optional[List[Experiment]]

Optional[List[Experiment]]: A list of associated experiments, or None if not found.

Source code in gemini/api/trait.py
def get_associated_experiments(self) -> Optional[List["Experiment"]]:
    """
    Get all experiments associated with this trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> experiments = trait.get_associated_experiments()
        >>> for experiment in experiments:
        ...     print(experiment)
        Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))
        Experiment(experiment_name=Experiment 2, experiment_start_date=2023-02-01, experiment_end_date=2023-11-30, id=UUID(...))

    Returns:
        Optional[List[Experiment]]: A list of associated experiments, or None if not found.
    """
    try:
        from gemini.api.experiment import Experiment
        experiment_traits = ExperimentTraitsViewModel.search(trait_id=self.id)
        if not experiment_traits or len(experiment_traits) == 0:
            logger.info("No associated experiments found.")
            return None
        experiments = [Experiment.model_validate(experiment) for experiment in experiment_traits]
        return experiments
    except Exception as e:
        logger.error(f"Error getting associated experiments: {e}")
        return None

get_by_id(id) classmethod

Retrieve a trait by its ID.

Examples:

>>> Trait.get_by_id(UUID('...'))
Trait(trait_name=Leaf Area Index, id=UUID(...))

Parameters:

Name Type Description Default
id UUID | int | str

The ID of the trait.

required

Returns: Optional[Trait]: The trait, or None if not found.

Source code in gemini/api/trait.py
@classmethod
def get_by_id(cls, id: UUID | int | str) -> Optional["Trait"]:
    """
    Retrieve a trait by its ID.

    Examples:
        >>> Trait.get_by_id(UUID('...'))
        Trait(trait_name=Leaf Area Index, id=UUID(...))

    Args:
        id (UUID | int | str): The ID of the trait.
    Returns:
        Optional[Trait]: The trait, or None if not found.
    """
    try:
        trait = TraitModel.get(id)
        if not trait:
            logger.warning(f"Trait with ID {id} does not exist.")
            return None
        trait = cls.model_validate(trait)
        return trait
    except Exception as e:
        logger.error(f"Error getting trait by ID: {e}")
        return None

get_info()

Get the additional information of the trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> trait_info = trait.get_info()
>>> print(trait_info)
{'description': 'Leaf area index', 'source': 'Field measurements'}

Returns:

Type Description
Optional[dict]

Optional[dict]: The trait's info, or None if not found.

Source code in gemini/api/trait.py
def get_info(self) -> Optional[dict]:
    """
    Get the additional information of the trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> trait_info = trait.get_info()
        >>> print(trait_info)
        {'description': 'Leaf area index', 'source': 'Field measurements'}

    Returns:
        Optional[dict]: The trait's info, or None if not found.
    """
    try:
        current_id = self.id
        trait = TraitModel.get(current_id)
        if not trait:
            logger.warning(f"Trait with ID {current_id} does not exist.")
            return None
        trait_info = trait.trait_info
        if not trait_info:
            logger.info("Trait info is empty.")
            return None
        return trait_info
    except Exception as e:
        logger.error(f"Error getting trait info: {e}")
        return None

insert_record(timestamp=None, collection_date=None, dataset_name=None, trait_value=None, experiment_name=None, season_name=None, site_name=None, plot_number=-1, plot_row_number=-1, plot_column_number=-1, record_info=None)

Insert a single trait record for this trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> success, record_ids = trait.insert_record(
...     timestamp=datetime.now(),
...     collection_date=date(2023, 1, 1),
...     dataset_name="Leaf Area Index Dataset 2023-01-01",
...     trait_value=5.0,
...     experiment_name="Experiment 1",
...     season_name="Spring 2023",
...     site_name="Field Site A",
...     plot_number=1,
...     plot_row_number=1,
...     plot_column_number=1,
...     record_info={"description": "Leaf area index measurement"}
... )
>>> print(success, record_ids)
True [UUID(...)]

Parameters:

Name Type Description Default
timestamp datetime

The timestamp of the record. Defaults to None.

None
collection_date date

The collection date. Defaults to None.

None
dataset_name str

The name of the dataset. Defaults to None.

None
trait_value float

The value of the trait. Defaults to None.

None
experiment_name str

The name of the experiment. Defaults to None.

None
season_name str

The name of the season. Defaults to None.

None
site_name str

The name of the site. Defaults to None.

None
plot_number int

The plot number. Defaults to -1.

-1
plot_row_number int

The plot row number. Defaults to -1.

-1
plot_column_number int

The plot column number. Defaults to -1.

-1
record_info dict

Additional info. Defaults to {{}}.

None

Returns: tuple[bool, List[str]]: Success status and list of inserted record IDs.

Source code in gemini/api/trait.py
def insert_record(
    self,
    timestamp: date = None,
    collection_date: date = None,
    dataset_name: str = None,
    trait_value: float = None,
    experiment_name: str = None,
    season_name: str = None,
    site_name: str = None,
    plot_number: int = -1,
    plot_row_number: int = -1,
    plot_column_number: int = -1,
    record_info: dict = None
) -> tuple[bool, List[str]]:
    """
    Insert a single trait record for this trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> success, record_ids = trait.insert_record(
        ...     timestamp=datetime.now(),
        ...     collection_date=date(2023, 1, 1),
        ...     dataset_name="Leaf Area Index Dataset 2023-01-01",
        ...     trait_value=5.0,
        ...     experiment_name="Experiment 1",
        ...     season_name="Spring 2023",
        ...     site_name="Field Site A",
        ...     plot_number=1,
        ...     plot_row_number=1,
        ...     plot_column_number=1,
        ...     record_info={"description": "Leaf area index measurement"}
        ... )
        >>> print(success, record_ids)
        True [UUID(...)]

    Args:
        timestamp (datetime, optional): The timestamp of the record. Defaults to None.
        collection_date (date, optional): The collection date. Defaults to None.
        dataset_name (str, optional): The name of the dataset. Defaults to None.
        trait_value (float, optional): The value of the trait. Defaults to None.
        experiment_name (str, optional): The name of the experiment. Defaults to None.
        season_name (str, optional): The name of the season. Defaults to None.
        site_name (str, optional): The name of the site. Defaults to None.
        plot_number (int, optional): The plot number. Defaults to -1.
        plot_row_number (int, optional): The plot row number. Defaults to -1.
        plot_column_number (int, optional): The plot column number. Defaults to -1.
        record_info (dict, optional): Additional info. Defaults to {{}}.
    Returns:
        tuple[bool, List[str]]: Success status and list of inserted record IDs.
    """
    try:
        if not experiment_name or not season_name or not site_name:
            raise ValueError("Experiment name, season name, and site name must be provided.")

        if not trait_value:
            raise ValueError("Trait value must be provided.")

        timestamp = timestamp if timestamp else datetime.now()
        collection_date = collection_date if collection_date else timestamp.date()
        trait_name = self.trait_name
        if not dataset_name:
            dataset_name = f"{trait_name} Dataset {collection_date}"
        trait_record = TraitRecord.create(
            timestamp=timestamp,
            collection_date=collection_date,
            trait_name=trait_name,
            dataset_name=dataset_name,
            trait_value=trait_value,
            experiment_name=experiment_name,
            season_name=season_name,
            site_name=site_name,
            plot_number=plot_number if plot_number != -1 else None,
            plot_row_number=plot_row_number if plot_row_number != -1 else None,
            plot_column_number=plot_column_number if plot_column_number != -1 else None,
            record_info=record_info if record_info else {},
            insert_on_create=False
        )
        success, inserted_record_ids = TraitRecord.insert([trait_record])
        if not success:
            logger.info(f"Failed to insert record for trait {trait_name}.")
            return False, []
        return success, inserted_record_ids
    except Exception as e:
        logger.error(f"Error inserting record: {e}")
        return False, []

insert_records(timestamps=None, collection_date=None, trait_values=None, dataset_name=None, experiment_name=None, season_name=None, site_name=None, plot_numbers=None, plot_row_numbers=None, plot_column_numbers=None, record_info=None)

Insert multiple trait records for this trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> success, record_ids = trait.insert_records(
...     timestamps=[datetime.now(), datetime.now()],
...     collection_date=date(2023, 1, 1),
...     trait_values=[5.0, 6.0],
...     dataset_name="Leaf Area Index Dataset 2023-01-01",
...     experiment_name="Experiment 1",
...     season_name="Spring 2023",
...     site_name="Field Site A",
...     plot_numbers=[1, 2],
...     plot_row_numbers=[1, 2],
...     plot_column_numbers=[1, 2],
...     record_info=[{"description": "Leaf area index measurement 1"}, {"description": "Leaf area index measurement 2"}]
... )
>>> print(success, record_ids)
True [UUID(...), UUID(...)]

Parameters:

Name Type Description Default
timestamps List[datetime]

List of timestamps. Defaults to None.

None
collection_date date

The collection date. Defaults to None.

None
trait_values List[float]

List of trait values. Defaults to [].

None
dataset_name str

The name of the dataset. Defaults to None.

None
experiment_name str

The name of the experiment. Defaults to None.

None
season_name str

The name of the season. Defaults to None.

None
site_name str

The name of the site. Defaults to None.

None
plot_numbers List[int]

List of plot numbers. Defaults to None.

None
plot_row_numbers List[int]

List of plot row numbers. Defaults to None.

None
plot_column_numbers List[int]

List of plot column numbers. Defaults to None.

None
record_info List[dict]

List of additional info. Defaults to [].

None

Returns: tuple[bool, List[str]]: Success status and list of inserted record IDs.

Source code in gemini/api/trait.py
def insert_records(
    self,
    timestamps: List[datetime] = None,
    collection_date: date = None,
    trait_values: List[float] = None,
    dataset_name: str = None,
    experiment_name: str = None,
    season_name: str = None,
    site_name: str = None,
    plot_numbers: List[int] = None,
    plot_row_numbers: List[int] = None,
    plot_column_numbers: List[int] = None,
    record_info: List[dict] = None
) -> tuple[bool, List[str]]:
    """
    Insert multiple trait records for this trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> success, record_ids = trait.insert_records(
        ...     timestamps=[datetime.now(), datetime.now()],
        ...     collection_date=date(2023, 1, 1),
        ...     trait_values=[5.0, 6.0],
        ...     dataset_name="Leaf Area Index Dataset 2023-01-01",
        ...     experiment_name="Experiment 1",
        ...     season_name="Spring 2023",
        ...     site_name="Field Site A",
        ...     plot_numbers=[1, 2],
        ...     plot_row_numbers=[1, 2],
        ...     plot_column_numbers=[1, 2],
        ...     record_info=[{"description": "Leaf area index measurement 1"}, {"description": "Leaf area index measurement 2"}]
        ... )
        >>> print(success, record_ids)
        True [UUID(...), UUID(...)]

    Args:
        timestamps (List[datetime], optional): List of timestamps. Defaults to None.
        collection_date (date, optional): The collection date. Defaults to None.
        trait_values (List[float], optional): List of trait values. Defaults to [].
        dataset_name (str, optional): The name of the dataset. Defaults to None.
        experiment_name (str, optional): The name of the experiment. Defaults to None.
        season_name (str, optional): The name of the season. Defaults to None.
        site_name (str, optional): The name of the site. Defaults to None.
        plot_numbers (List[int], optional): List of plot numbers. Defaults to None.
        plot_row_numbers (List[int], optional): List of plot row numbers. Defaults to None.
        plot_column_numbers (List[int], optional): List of plot column numbers. Defaults to None.
        record_info (List[dict], optional): List of additional info. Defaults to [].
    Returns:
        tuple[bool, List[str]]: Success status and list of inserted record IDs.
    """
    try:
        if not experiment_name or not season_name or not site_name:
            raise ValueError("Experiment name, season name, and site name must be provided.")

        if len(timestamps) == 0:
            raise ValueError("At least one timestamp must be provided.")

        if not dataset_name:
            dataset_name = f"{self.trait_name} Dataset {collection_date}"

        collection_date = collection_date if collection_date else timestamps[0].date()
        trait_records = []
        timestamps_length = len(timestamps)

        for i in tqdm(range(timestamps_length), desc="Arranging Records for Trait: " + self.trait_name):
            trait_record = TraitRecord.create(
                timestamp=timestamps[i],
                collection_date=collection_date,
                trait_name=self.trait_name,
                trait_value=trait_values[i] if trait_values else None,
                dataset_name=dataset_name if dataset_name else f"{self.trait_name} Dataset {collection_date}",
                experiment_name=experiment_name,
                season_name=season_name,
                site_name=site_name,
                plot_number=plot_numbers[i] if plot_numbers else None,
                plot_row_number=plot_row_numbers[i] if plot_row_numbers else None,
                plot_column_number=plot_column_numbers[i] if plot_column_numbers else None,
                record_info=record_info[i] if record_info else {},
                insert_on_create=False
            )
            trait_records.append(trait_record)

        success, inserted_record_ids = TraitRecord.insert(trait_records)
        return success, inserted_record_ids
    except ValueError:
        raise
    except DBAPIError:
        # Let database errors (trigger RAISEs, constraint violations)
        # propagate so the REST layer can surface the real cause.
        raise
    except Exception as e:
        logger.error(f"Error inserting records: {e}")
        return False, []

refresh()

Refresh the trait's data from the database.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> refreshed_trait = trait.refresh()
>>> print(refreshed_trait)
Trait(trait_name=Leaf Area Index, id=UUID(...))

Returns:

Type Description
Optional[Trait]

Optional[Trait]: The refreshed trait, or None if an error occurred.

Source code in gemini/api/trait.py
def refresh(self) -> Optional["Trait"]:
    """
    Refresh the trait's data from the database.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> refreshed_trait = trait.refresh()
        >>> print(refreshed_trait)
        Trait(trait_name=Leaf Area Index, id=UUID(...))

    Returns:
        Optional[Trait]: The refreshed trait, or None if an error occurred.
    """
    try:
        db_instance = TraitModel.get(self.id)
        if not db_instance:
            logger.warning(f"Trait with ID {self.id} does not exist.")
            return self
        instance = self.model_validate(db_instance)
        for key, value in instance.model_dump().items():
            if hasattr(self, key) and key != "id":
                setattr(self, key, value)
        return self
    except Exception as e:
        logger.error(f"Error refreshing trait: {e}")
        return None

search(trait_name=None, trait_units=None, trait_level=None, trait_info=None, trait_metrics=None, experiment_name=None) classmethod

Search for traits based on various criteria.

Examples:

>>> Trait.search(trait_name="Leaf Area Index")
[Trait(trait_name=Leaf Area Index, id=UUID(...))]

Parameters:

Name Type Description Default
trait_name str

The name of the trait. Defaults to None.

None
trait_units str

The units of the trait. Defaults to None.

None
trait_level GEMINITraitLevel

The level of the trait. Defaults to None.

None
trait_info dict

Additional information. Defaults to None.

None
trait_metrics dict

Metrics associated with the trait. Defaults to None.

None
experiment_name str

The name of the experiment. Defaults to None.

None

Returns: Optional[List[Trait]]: List of matching traits, or None if not found.

Source code in gemini/api/trait.py
@classmethod
def search(
    cls, 
    trait_name: str = None,
    trait_units: str = None,
    trait_level: GEMINITraitLevel = None,
    trait_info: dict = None,
    trait_metrics: dict = None,
    experiment_name: str = None
) -> Optional[List["Trait"]]:
    """
    Search for traits based on various criteria.

    Examples:
        >>> Trait.search(trait_name="Leaf Area Index")
        [Trait(trait_name=Leaf Area Index, id=UUID(...))]

    Args:
        trait_name (str, optional): The name of the trait. Defaults to None.
        trait_units (str, optional): The units of the trait. Defaults to None.
        trait_level (GEMINITraitLevel, optional): The level of the trait. Defaults to None.
        trait_info (dict, optional): Additional information. Defaults to None.
        trait_metrics (dict, optional): Metrics associated with the trait. Defaults to None.
        experiment_name (str, optional): The name of the experiment. Defaults to None.
    Returns:
        Optional[List[Trait]]: List of matching traits, or None if not found.
    """
    try:
        if not any([experiment_name, trait_name, trait_units, trait_level, trait_info, trait_metrics]):
            logger.warning("At least one search parameter must be provided.")
            return None

        traits = ExperimentTraitsViewModel.search(
            experiment_name=experiment_name,
            trait_name=trait_name,
            trait_units=trait_units,
            trait_level_id=trait_level.value if trait_level else None,
            trait_info=trait_info,
            trait_metrics=trait_metrics
        )
        if not traits or len(traits) == 0:
            logger.info("No traits found with the provided search parameters.")
            return None
        traits = [cls.model_validate(trait) for trait in traits]
        return traits if traits else None
    except Exception as e:
        logger.error(f"Error searching traits: {e}")
        return None

search_records(collection_date=None, dataset_name=None, experiment_name=None, season_name=None, site_name=None, plot_number=None, plot_row_number=None, plot_column_number=None, record_info=None)

Search for trait records associated with this trait based on search parameters.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> records = trait.search_records(
...     collection_date=date(2023, 1, 1),
...     dataset_name="Leaf Area Index Dataset 2023-01-01",
...     experiment_name="Experiment 1",
...     season_name="Spring 2023",
...     site_name="Field Site A",
...     plot_number=1,
...     plot_row_number=1,
...     plot_column_number=1,
...     record_info={"description": "Leaf area index measurement"}
... )
>>> for record in records:
...     print(record)
TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=1, plot_row_number=1, plot_column_number=1)
TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=2, plot_row_number=2, plot_column_number=2)

Parameters:

Name Type Description Default
collection_date date

The collection date. Defaults to None.

None
dataset_name str

The name of the dataset. Defaults to None.

None
experiment_name str

The name of the experiment. Defaults to None.

None
season_name str

The name of the season. Defaults to None.

None
site_name str

The name of the site. Defaults to None.

None
plot_number int

The plot number. Defaults to None.

None
plot_row_number int

The plot row number. Defaults to None.

None
plot_column_number int

The plot column number. Defaults to None.

None
record_info dict

Additional info. Defaults to None.

None

Returns: List[TraitRecord]: List of matching trait records, or empty list if not found.

Source code in gemini/api/trait.py
def search_records(
    self,
    collection_date: date = None,
    dataset_name: str = None,
    experiment_name: str = None,
    season_name: str = None,
    site_name: str = None,
    plot_number: int = None,
    plot_row_number: int = None,
    plot_column_number: int = None,
    record_info: dict = None
) -> List[TraitRecord]:
    """
    Search for trait records associated with this trait based on search parameters.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> records = trait.search_records(
        ...     collection_date=date(2023, 1, 1),
        ...     dataset_name="Leaf Area Index Dataset 2023-01-01",
        ...     experiment_name="Experiment 1",
        ...     season_name="Spring 2023",
        ...     site_name="Field Site A",
        ...     plot_number=1,
        ...     plot_row_number=1,
        ...     plot_column_number=1,
        ...     record_info={"description": "Leaf area index measurement"}
        ... )
        >>> for record in records:
        ...     print(record)
        TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=1, plot_row_number=1, plot_column_number=1)
        TraitRecord(id=UUID(...), trait_name=Leaf Area Index, collection_date=2023-01-01, dataset_name=Leaf Area Index Dataset 2023-01-01, experiment_name=Experiment 1, season_name=Spring 2023, site_name=Field Site A, plot_number=2, plot_row_number=2, plot_column_number=2)

    Args:
        collection_date (date, optional): The collection date. Defaults to None.
        dataset_name (str, optional): The name of the dataset. Defaults to None.
        experiment_name (str, optional): The name of the experiment. Defaults to None.
        season_name (str, optional): The name of the season. Defaults to None.
        site_name (str, optional): The name of the site. Defaults to None.
        plot_number (int, optional): The plot number. Defaults to None.
        plot_row_number (int, optional): The plot row number. Defaults to None.
        plot_column_number (int, optional): The plot column number. Defaults to None.
        record_info (dict, optional): Additional info. Defaults to None.
    Returns:
        List[TraitRecord]: List of matching trait records, or empty list if not found.
    """
    try:
        record_info = record_info if record_info else {}
        record_info = {k: v for k, v in record_info.items() if v is not None}

        records = TraitRecord.search(
            trait_name=self.trait_name,
            collection_date=collection_date,
            dataset_name=dataset_name,
            experiment_name=experiment_name,
            season_name=season_name,
            site_name=site_name,
            plot_number=plot_number,
            plot_row_number=plot_row_number,
            plot_column_number=plot_column_number,
            record_info=record_info
        )
        return records
    except Exception as e:
        logger.error(f"Error searching records: {e}")
        return []

set_info(trait_info)

Set the additional information of the trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> updated_trait = trait.set_info({"description": "Updated leaf area index", "source": "New measurements"})
>>> print(updated_trait.get_info())
{'description': 'Updated leaf area index', 'source': 'New measurements'}

Parameters:

Name Type Description Default
trait_info dict

The new information to set.

required

Returns: Optional[Trait]: The updated trait, or None if an error occurred.

Source code in gemini/api/trait.py
def set_info(self, trait_info: dict) -> Optional["Trait"]:
    """
    Set the additional information of the trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> updated_trait = trait.set_info({"description": "Updated leaf area index", "source": "New measurements"})
        >>> print(updated_trait.get_info())
        {'description': 'Updated leaf area index', 'source': 'New measurements'}

    Args:
        trait_info (dict): The new information to set.
    Returns:
        Optional[Trait]: The updated trait, or None if an error occurred.
    """
    try:
        current_id = self.id
        trait = TraitModel.get(current_id)
        if not trait:
            logger.warning(f"Trait with ID {current_id} does not exist.")
            return None
        trait = TraitModel.update(
            trait,
            trait_info=trait_info
        )
        trait = self.model_validate(trait)
        self.refresh()
        return self
    except Exception as e:
        logger.error(f"Error setting trait info: {e}")
        return None

unassociate_experiment(experiment_name)

Unassociate this trait from an experiment.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> experiment = trait.unassociate_experiment("Experiment 1")
>>> print(experiment)
Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))

Parameters:

Name Type Description Default
experiment_name str

The name of the experiment to unassociate.

required

Returns: Optional[Experiment]: The unassociated experiment, or None if an error occurred.

Source code in gemini/api/trait.py
def unassociate_experiment(self, experiment_name: str) -> Optional["Experiment"]:
    """
    Unassociate this trait from an experiment.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> experiment = trait.unassociate_experiment("Experiment 1")
        >>> print(experiment)
        Experiment(experiment_name=Experiment 1, experiment_start_date=2023-01-01, experiment_end_date=2023-12-31, id=UUID(...))

    Args:
        experiment_name (str): The name of the experiment to unassociate.
    Returns:
        Optional[Experiment]: The unassociated experiment, or None if an error occurred.
    """
    try:
        from gemini.api.experiment import Experiment
        experiment = Experiment.get(experiment_name)
        if not experiment:
            logger.warning(f"Experiment {experiment_name} does not exist.")
            return None
        existing_association = ExperimentTraitModel.get_by_parameters(
            experiment_id=experiment.id,
            trait_id=self.id
        )
        if not existing_association:
            logger.info(f"Trait {self.trait_name} is not associated with experiment {experiment_name}.")
            return None
        is_deleted = ExperimentTraitModel.delete(existing_association)
        if not is_deleted:
            logger.info(f"Failed to unassociate trait {self.trait_name} from experiment {experiment_name}.")
            return False
        self.refresh()
        return experiment
    except Exception as e:
        logger.error(f"Error unassociating experiment: {e}")
        return None

update(trait_name=None, trait_units=None, trait_level=None, trait_info=None, trait_metrics=None)

Update the details of the trait.

Examples:

>>> trait = Trait.get("Leaf Area Index")
>>> updated_trait = trait.update(trait_name="New Leaf Area Index", trait_units="m^2")
>>> print(updated_trait)
Trait(trait_name=New Leaf Area Index, id=UUID(...))

Parameters:

Name Type Description Default
trait_name str

The new name. Defaults to None.

None
trait_units str

The new units. Defaults to None.

None
trait_level GEMINITraitLevel

The new level. Defaults to None.

None
trait_info dict

The new information. Defaults to None.

None
trait_metrics dict

The new metrics. Defaults to None.

None

Returns: Optional[Trait]: The updated trait, or None if an error occurred.

Source code in gemini/api/trait.py
def update(
    self,
    trait_name: str = None, 
    trait_units: str = None,
    trait_level: GEMINITraitLevel = None,
    trait_info: dict = None,
    trait_metrics: dict = None,
) -> Optional["Trait"]:
    """
    Update the details of the trait.

    Examples:
        >>> trait = Trait.get("Leaf Area Index")
        >>> updated_trait = trait.update(trait_name="New Leaf Area Index", trait_units="m^2")
        >>> print(updated_trait)
        Trait(trait_name=New Leaf Area Index, id=UUID(...))

    Args:
        trait_name (str, optional): The new name. Defaults to None.
        trait_units (str, optional): The new units. Defaults to None.
        trait_level (GEMINITraitLevel, optional): The new level. Defaults to None.
        trait_info (dict, optional): The new information. Defaults to None.
        trait_metrics (dict, optional): The new metrics. Defaults to None.
    Returns:
        Optional[Trait]: The updated trait, or None if an error occurred.
    """
    try:
        if not any([trait_units, trait_level, trait_info, trait_metrics, trait_name]):
            logger.warning("At least one update parameter must be provided.")
            return None

        current_id = self.id
        trait = TraitModel.get(current_id)
        if not trait:
            logger.warning(f"Trait with ID {current_id} does not exist.")
            return None

        rename = trait_name is not None and trait_name != trait.trait_name

        trait = TraitModel.update(
            trait,
            trait_name=trait_name,
            trait_units=trait_units,
            trait_level_id=trait_level.value if trait_level else None,
            trait_info=trait_info,
            trait_metrics=trait_metrics
        )
        if rename:
            from gemini.api._rename_cascade import cascade_rename
            cascade_rename(current_id, "trait_id", "trait_name", trait_name)
        trait = self.model_validate(trait)
        self.refresh()
        return trait
    except Exception as e:
        logger.error(f"Error updating trait: {e}")
        return None