Skip to content

Trait Records API

Description

A trait record is a record that belongs to a specific Trait, a specific Experiment, Season, Site, and Plot.

It is defined by the following properties:

Property Type Description
id UUID The unique identifier of the trait record.
timestamp datetime The timestamp of the record.
collection_date date The collection date of the record.
trait_name string The name of the associated trait.
trait_id UUID The ID of the associated trait.
trait_value float The value associated with the trait record.
dataset_id UUID The ID of the associated dataset.
dataset_name string The name of the associated dataset.
experiment_name string The name of the associated experiment.
experiment_id UUID The ID of the associated experiment.
season_name string The name of the associated season.
season_id UUID The ID of the associated season.
site_name string The name of the associated site.
site_id UUID The ID of the associated site.
plot_id UUID The ID of the associated plot.
plot_number integer The number of the associated plot.
plot_row_number integer The row number of the associated plot.
plot_column_number integer The column number of the associated plot.
record_info dict Additional information about the record.

A trait record is uniquely identified within a trait by its timestamp, trait_name, dataset_name, experiment_name, season_name, site_name, plot_number, plot_row_number and plot_column_number. There will be no two trait records with the same timestamp and belonging to the same trait, dataset, experiment, season and site.

Module

This module defines the TraitRecord class, which represents a record of a trait, including metadata, associations to datasets, experiments, sites, seasons, and plots, and related operations.

It includes methods for creating, retrieving, updating, and deleting trait records, as well as methods for checking existence, searching, filtering, and managing additional information.

This module includes the following methods:

  • exists: Check if a trait record with the given parameters exists.
  • create: Create a new trait record.
  • insert: Insert a list of trait records into the database.
  • get: Retrieve a trait record by its parameters.
  • get_by_id: Retrieve a trait record by its ID.
  • get_all: Retrieve all trait records.
  • search: Search for trait records based on various criteria.
  • filter: Filter trait records based on custom logic.
  • update: Update the details of a trait record.
  • delete: Delete a trait record.
  • refresh: Refresh the trait record's data from the database.
  • get_info: Get the additional information of the trait record.
  • set_info: Set the additional information of the trait record.

TraitRecord

Bases: APIBase

Represents a record of a trait, including metadata, associations to datasets, experiments, sites, seasons, and plots, and related operations.

Attributes:

Name Type Description
id Optional[ID]

The unique identifier of the trait record.

timestamp Optional[datetime]

The timestamp of the record.

collection_date Optional[date]

The collection date of the record.

dataset_id Optional[ID]

The ID of the associated dataset.

dataset_name Optional[str]

The name of the associated dataset.

trait_id Optional[ID]

The ID of the associated trait.

trait_name Optional[str]

The name of the associated trait.

trait_value Optional[float]

The value of the trait.

experiment_id Optional[ID]

The ID of the associated experiment.

experiment_name Optional[str]

The name of the associated experiment.

season_id Optional[ID]

The ID of the associated season.

season_name Optional[str]

The name of the associated season.

site_id Optional[ID]

The ID of the associated site.

site_name Optional[str]

The name of the associated site.

plot_id Optional[ID]

The ID of the associated plot.

plot_number Optional[int]

The number of the associated plot.

plot_row_number Optional[int]

The row number of the associated plot.

plot_column_number Optional[int]

The column number of the associated plot.

record_info Optional[dict]

Additional information about the record.

Source code in gemini/api/trait_record.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
class TraitRecord(APIBase):
    """
    Represents a record of a trait, including metadata, associations to datasets, experiments, sites, seasons, and plots, and related operations.

    Attributes:
        id (Optional[ID]): The unique identifier of the trait record.
        timestamp (Optional[datetime]): The timestamp of the record.
        collection_date (Optional[date]): The collection date of the record.
        dataset_id (Optional[ID]): The ID of the associated dataset.
        dataset_name (Optional[str]): The name of the associated dataset.
        trait_id (Optional[ID]): The ID of the associated trait.
        trait_name (Optional[str]): The name of the associated trait.
        trait_value (Optional[float]): The value of the trait.
        experiment_id (Optional[ID]): The ID of the associated experiment.
        experiment_name (Optional[str]): The name of the associated experiment.
        season_id (Optional[ID]): The ID of the associated season.
        season_name (Optional[str]): The name of the associated season.
        site_id (Optional[ID]): The ID of the associated site.
        site_name (Optional[str]): The name of the associated site.
        plot_id (Optional[ID]): The ID of the associated plot.
        plot_number (Optional[int]): The number of the associated plot.
        plot_row_number (Optional[int]): The row number of the associated plot.
        plot_column_number (Optional[int]): The column number of the associated plot.
        record_info (Optional[dict]): Additional information about the record.
    """

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

    timestamp: Optional[datetime] = None
    collection_date: Optional[date] = None
    dataset_id: Optional[ID] = None
    dataset_name: Optional[str] = None
    trait_id: Optional[ID] = None
    trait_name: Optional[str] = None
    trait_value: Optional[float] = None
    experiment_id: Optional[ID] = None
    experiment_name : Optional[str] = None
    season_id: Optional[ID] = None
    season_name: Optional[str] = None
    site_id: Optional[ID] = None
    site_name: Optional[str] = None
    plot_id: Optional[ID] = None
    plot_number: Optional[int] = None
    plot_row_number: Optional[int] = None
    plot_column_number: Optional[int] = None
    record_info: Optional[dict] = None

    def __str__(self):
        """Return a string representation of the TraitRecord object."""
        return f"TraitRecord(id={self.id}, timestamp={self.timestamp}, trait_name={self.trait_name}, dataset_name={self.dataset_name}, experiment_name={self.experiment_name}, site_name={self.site_name}, season_name={self.season_name}, plot_number={self.plot_number}, plot_row_number={self.plot_row_number}, plot_column_number={self.plot_column_number})"

    def __repr__(self):
        """Return a detailed string representation of the TraitRecord object."""
        return f"TraitRecord(id={self.id}, timestamp={self.timestamp}, trait_name={self.trait_name}, dataset_name={self.dataset_name}, experiment_name={self.experiment_name}, site_name={self.site_name}, season_name={self.season_name}, plot_number={self.plot_number}, plot_row_number={self.plot_row_number}, plot_column_number={self.plot_column_number})"

    @classmethod
    def exists(
        cls,
        timestamp: datetime,
        trait_name: str,
        dataset_name: str,
        experiment_name: str,
        site_name: str,
        season_name: str,
        plot_number: int = None,
        plot_row_number: int = None,
        plot_column_number: int = None
    ) -> bool:
        """
        Check if a trait record with the given parameters exists.

        Examples:
            >>> TraitRecord.exists(
            ...     timestamp=datetime(2023, 10, 1, 12, 0),
            ...     trait_name="Height",
            ...     dataset_name="Plant Growth Study",
            ...     experiment_name="Growth Experiment 1",
            ...     site_name="Research Farm A",
            ...     season_name="Spring 2023",
            ...     plot_number=1,
            ...     plot_row_number=2,
            ...     plot_column_number=3
            ... )
            True


        Args:
            timestamp (datetime): The timestamp of the record.
            trait_name (str): The name of the trait.
            dataset_name (str): The name of the dataset.
            experiment_name (str): The name of the experiment.
            season_name (str): The name of the season.
            site_name (str): The name of the site.
            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.
        Returns:
            bool: True if the trait record exists, False otherwise.
        """
        try:
            exists = TraitRecordModel.exists(
                timestamp=timestamp,
                trait_name=trait_name,
                dataset_name=dataset_name,
                experiment_name=experiment_name,
                site_name=site_name,
                season_name=season_name,
                plot_number=plot_number,
                plot_row_number=plot_row_number,
                plot_column_number=plot_column_number
            )
            return exists
        except Exception as e:
            logger.error(f"Error checking existence of TraitRecord: {e}")
            raise e

    @classmethod
    def create(
        cls,
        timestamp: datetime = datetime.now(),
        collection_date: date = None,
        dataset_name: str = None,
        trait_name: str = None,
        trait_value: float = None,
        experiment_name: str = None,
        site_name: str = None,
        season_name: str = None,
        plot_number: int = None,
        plot_row_number: int = None,
        plot_column_number: int = None,
        record_info: dict = None,
        insert_on_create: bool = True
    ) -> Optional["TraitRecord"]:
        """
        Create a new trait record.

        Examples:
            >>> TraitRecord.create(
            ...     timestamp=datetime(2023, 10, 1, 12, 0),
            ...     collection_date=date(2023, 10, 1),
            ...     dataset_name="Plant Growth Study",
            ...     trait_name="Height",
            ...     trait_value=150.0,
            ...     experiment_name="Growth Experiment 1",
            ...     site_name="Research Farm A",
            ...     season_name="Spring 2023",
            ...     plot_number=1,
            ...     plot_row_number=2,
            ...     plot_column_number=3,
            ...     record_info={"notes": "Initial measurement"},
            ...     insert_on_create=True
            ... )
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

        Args:
            timestamp (datetime, optional): The timestamp of the record. Defaults to now.
            collection_date (date, optional): The collection date. Defaults to None.
            dataset_name (str, optional): The name of the dataset. Defaults to None.
            trait_name (str, optional): The name of the trait. 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.
            site_name (str, optional): The name of the site. Defaults to None.
            season_name (str, optional): The name of the season. 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 {{}}.
            insert_on_create (bool, optional): Whether to insert on create. Defaults to True.
        Returns:
            Optional[TraitRecord]: The created trait record, or None if an error occurred.
        """
        try:
            if not any([experiment_name, site_name, season_name]):
                raise ValueError("At least one of experiment_name, site_name, or season_name must be provided.")
            if not trait_name:
                raise ValueError("Trait name is required.")
            if not dataset_name:
                raise ValueError("Dataset name is required.")
            # Plot row/column may only be provided together with a plot_number.
            # plot_number by itself is valid (row/column are optional).
            if (plot_row_number is not None or plot_column_number is not None) and plot_number is None:
                raise ValueError("plot_number is required when plot_row_number or plot_column_number is provided.")
            if not timestamp:
                timestamp = datetime.now()
            if not collection_date:
                collection_date = timestamp.date()
            # Allow 0.0 and negative values — only reject None/missing.
            if trait_value is None:
                raise ValueError("Trait value is required.")
            trait_record = TraitRecord(
                timestamp=timestamp,
                collection_date=collection_date,
                dataset_name=dataset_name,
                trait_name=trait_name,
                trait_value=trait_value,
                experiment_name=experiment_name,
                site_name=site_name,
                season_name=season_name,
                plot_number=plot_number,
                plot_row_number=plot_row_number,
                plot_column_number=plot_column_number,
                record_info=record_info
            )
            if insert_on_create:
                insert_success, inserted_record_ids = cls.insert([trait_record])
                if not insert_success:
                    logger.info(f"Failed to insert TraitRecord: {trait_record}")
                    return None
                if not inserted_record_ids or len(inserted_record_ids) == 0:
                    logger.info(f"No TraitRecord IDs returned after insertion.")
                    return None
                inserted_record_id = inserted_record_ids[0]
                trait_record = cls.get_by_id(inserted_record_id)
            return trait_record
        except Exception as e:
            logger.error(f"Error creating TraitRecord: {e}")
            return None

    @classmethod
    def insert(cls, records: List["TraitRecord"]) -> tuple[bool, List[str]]:
        """
        Insert a list of trait records into the database.

        Args:
            records (List[TraitRecord]): The records to insert.
        Returns:
            tuple[bool, List[str]]: Success status and list of inserted record IDs.
        """
        if not records or len(records) == 0:
            logger.info(f"No records provided to insert.")
            return False, []
        records_to_insert = []
        for record in records:
            record_dict = record.model_dump()
            record_dict = {k: v for k, v in record_dict.items() if v is not None}
            records_to_insert.append(record_dict)
        logger.info(f"Inserting {len(records_to_insert)} TraitRecords.")
        # Deliberately does NOT swallow DB errors: Postgres trigger RAISEs
        # (e.g. "No matching plot found for the given parameters") carry the
        # actual cause the caller needs to surface to the user.
        inserted_record_ids = TraitRecordModel.insert_bulk('trait_records_unique', records_to_insert)
        logger.info(f"Inserted {len(inserted_record_ids)} TraitRecords.")
        return True, inserted_record_ids

    @classmethod
    def get(
        cls,
        timestamp: datetime,
        trait_name: str,
        dataset_name: str,
        experiment_name: str,
        site_name: str,
        season_name: str,
        plot_number: int = None,
        plot_row_number: int = None,
        plot_column_number: int = None
    ) -> Optional["TraitRecord"]:
        """
        Retrieve a trait record by its parameters.

        Examples:
            >>> TraitRecord.get(
            ...     timestamp=datetime(2023, 10, 1, 12, 0),
            ...     trait_name="Height",
            ...     dataset_name="Plant Growth Study",
            ...     experiment_name="Growth Experiment 1",
            ...     site_name="Research Farm A",
            ...     season_name="Spring 2023",
            ...     plot_number=1,
            ...     plot_row_number=2,
            ...     plot_column_number=3
            ... )
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

        Args:
            timestamp (datetime): The timestamp of the record.
            trait_name (str): The name of the trait.
            dataset_name (str): The name of the dataset.
            experiment_name (str): The name of the experiment.
            site_name (str): The name of the site.
            season_name (str): The name of the season.
            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.
        Returns:
            Optional[TraitRecord]: The trait record, or None if not found.
        """
        try:
            if not timestamp:
                logger.warning("Timestamp is required to get TraitRecord.")
                return None
            if not trait_name:
                logger.warning("Trait name is required to get TraitRecord.")
                return None
            if not dataset_name:
                logger.warning("Dataset name is required to get TraitRecord.")
                return None
            if not experiment_name and not site_name and not season_name:
                logger.warning("At least one of experiment_name, site_name, or season_name is required to get TraitRecord.")
                return None
            if not all([plot_number, plot_row_number, plot_column_number]):
                logger.warning("Plot information (number, row, column) is required if any is provided.")
                return None
            trait_record = TraitRecordsIMMVModel.get_by_parameters(
                timestamp=timestamp,
                trait_name=trait_name,
                dataset_name=dataset_name,
                experiment_name=experiment_name,
                site_name=site_name,
                season_name=season_name,
                plot_number=plot_number,
                plot_row_number=plot_row_number,
                plot_column_number=plot_column_number
            )
            if not trait_record:
                logger.debug("TraitRecord not found with the provided parameters.")
                return None
            trait_record = cls.model_validate(trait_record)
            return trait_record
        except Exception as e:
            logger.error(f"Error getting TraitRecord: {e}")
            return None

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

        Examples:
            >>> TraitRecord.get_by_id(UUID('...'))
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

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

    @classmethod
    def get_all(cls, limit: int = 100) -> Optional[List["TraitRecord"]]:
        """
        Retrieve all trait records, up to a specified limit.

        Examples:
            >>> TraitRecord.get_all(limit=10)
            >>> for record in TraitRecord.get_all(limit=10):
            ...     print(record)
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 2, 12, 0), trait_name='Width', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

        Args:
            limit (int, optional): The maximum number of records to retrieve. Defaults to 100.
        Returns:
            Optional[List[TraitRecord]]: List of trait records, or None if not found.
        """
        try:
            records = TraitRecordModel.all(limit=limit)
            if not records or len(records) == 0:
                logger.info(f"No TraitRecords found")
                return None
            records = [cls.model_validate(instance) for instance in records]
            return records
        except Exception as e:
            logger.error(f"Error getting all TraitRecords: {e}")
            return None

    @classmethod
    def search(
        cls,
        dataset_name: str = None,
        trait_name: str = None,
        trait_value: float = None,
        experiment_name: str = None,
        site_name: str = None,
        season_name: str = None,
        plot_number: int = None,
        plot_row_number: int = None,
        plot_column_number: int = None,
        collection_date: date = None,
        record_info: dict = None
    ) -> Generator["TraitRecord", None, None]:
        """
        Search for trait records based on various criteria.

        Examples:
            >>> for record in TraitRecord.search(dataset_name="Plant Growth Study", trait_name="Height"):
            ...     print(record)
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 2, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

        Args:
            dataset_name (str, optional): The name of the dataset. Defaults to None.
            trait_name (str, optional): The name of the trait. 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.
            site_name (str, optional): The name of the site. Defaults to None.
            season_name (str, optional): The name of the season. 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.
            collection_date (date, optional): The collection date. Defaults to None.
            record_info (dict, optional): Additional info. Defaults to None.
        Yields:
            TraitRecord: Matching trait records.
        """
        try:
            if not any([dataset_name, trait_name, trait_value, experiment_name, site_name, season_name, plot_number, plot_row_number, plot_column_number, collection_date, record_info]):
                logger.warning("At least one search parameter must be provided.")
                return
            records = TraitRecordsIMMVModel.stream(
                dataset_name=dataset_name,
                trait_name=trait_name,
                trait_value=trait_value,
                experiment_name=experiment_name,
                site_name=site_name,
                season_name=season_name,
                plot_number=plot_number,
                plot_row_number=plot_row_number,
                plot_column_number=plot_column_number,
                collection_date=collection_date,
                record_info=record_info
            )
            for record in records:
                record = cls.model_validate(record)
                yield record
        except Exception as e:
            logger.error(f"Error searching TraitRecords: {e}")
            yield from []


    @classmethod
    def filter(
        cls,
        start_timestamp: Optional[datetime] = None,
        end_timestamp: Optional[datetime] = None,
        trait_names: Optional[List[str]] = 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
    ) -> Generator["TraitRecord", None, None]:
        """
        Filter trait records based on custom logic.

        Examples:
            >>> records = TraitRecord.filter(
            ...     start_timestamp=datetime(2023, 10, 1, 0, 0),
            ...     end_timestamp=datetime(2023, 10, 31, 23, 59),
            ...     trait_names=["Height", "Width"],
            ...     dataset_names=["Plant Growth Study"],
            ...     experiment_names=["Growth Experiment 1"],
            ...     season_names=["Spring 2023"],
            ...     site_names=["Research Farm A"]
            ... )
            >>> for record in records:
            ...     print(record)
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

        Args:
            start_timestamp (datetime, optional): Start of timestamp range. Defaults to None.
            end_timestamp (datetime, optional): End of timestamp range. Defaults to None.
            trait_names (List[str], optional): List of trait names. 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.
        Yields:
            TraitRecord: Filtered trait records.
        """
        try:
            if not any([start_timestamp, end_timestamp, trait_names, dataset_names, experiment_names, season_names, site_names]):
                logger.warning("At least one filter parameter must be provided.")
                return
            records = TraitRecordModel.filter_records(
                start_timestamp=start_timestamp,
                end_timestamp=end_timestamp,
                trait_names=trait_names,
                dataset_names=dataset_names,
                experiment_names=experiment_names,
                season_names=season_names,
                site_names=site_names
            )
            for record in records:
                record = cls.model_validate(record)
                yield record
        except Exception as e:
            logger.error(f"Error filtering TraitRecords: {e}")
            yield from []

    def update(
        self,
        trait_value: float = None,
        record_info: dict = None
    ) -> Optional["TraitRecord"]:
        """
        Update the details of the trait record.

        Examples:
            >>> trait_record = TraitRecord.get_by_id(UUID('...'))
            >>> updated_record = trait_record.update(
            ...     trait_value=160.0,
            ...     record_info={"notes": "Updated measurement"}
            ... )
            >>> print(updated_record)
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

        Args:
            trait_value (float, optional): The new trait value. Defaults to None.
            record_info (dict, optional): The new record information. Defaults to None.
        Returns:
            Optional[TraitRecord]: The updated trait record, or None if an error occurred.
        """
        try:
            if not any([trait_value, record_info]):
                logger.warning("At least one parameter must be provided to update TraitRecord.")
                return None
            current_id = self.id
            trait_record = TraitRecordModel.get(current_id)
            if not trait_record:
                logger.debug(f"TraitRecord with ID {current_id} not found.")
                return None
            trait_record = TraitRecordModel.update(
                trait_record,
                trait_value=trait_value,
                record_info=record_info
            )
            trait_record = self.model_validate(trait_record)
            self.refresh()
            return trait_record
        except Exception as e:
            logger.error(f"Error updating TraitRecord: {e}")
            return None

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

        Examples:
            >>> trait_record = TraitRecord.get_by_id(UUID('...'))
            >>> success = trait_record.delete()
            >>> print(success)
            True

        Returns:
            bool: True if the trait record was deleted, False otherwise.
        """
        try:
            current_id = self.id
            trait_record = TraitRecordModel.get(current_id)
            if not trait_record:
                logger.debug(f"TraitRecord with ID {current_id} not found.")
                return False
            TraitRecordModel.delete(trait_record)
            return True
        except Exception as e:
            logger.error(f"Error deleting TraitRecord: {e}")
            return False

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

        Examples:
            >>> trait_record = TraitRecord.get_by_id(UUID('...'))
            >>> refreshed_record = trait_record.refresh()
            >>> print(refreshed_record)
            TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

        Returns:
            Optional[TraitRecord]: The refreshed trait record, or None if an error occurred.
        """
        try:
            db_instance = TraitRecordModel.get(self.id)
            if not db_instance:
                logger.debug(f"TraitRecord with ID {self.id} not found.")
                return None
            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 TraitRecord: {e}")
            return None

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

        Examples:
            >>> trait_record = TraitRecord.get_by_id(UUID('...'))
            >>> record_info = trait_record.get_info()
            >>> print(record_info)
            {'notes': 'Initial measurement', 'source': 'Field observation'}

        Returns:
            Optional[dict]: The record's info, or None if not found.
        """
        try:
            current_id = self.id
            trait_record = TraitRecordModel.get(current_id)
            if not trait_record:
                logger.debug(f"TraitRecord with ID {current_id} not found.")
                return None
            record_info = trait_record.record_info
            if not record_info:
                logger.info(f"No record info found for TraitRecord with ID {current_id}.")
                return None
            return record_info
        except Exception as e:
            logger.error(f"Error getting record info for TraitRecord: {e}")
            return None

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

        Examples:
            >>> trait_record = TraitRecord.get_by_id(UUID('...'))
            >>> updated_record = trait_record.set_info(
            ...     record_info={"notes": "Updated measurement", "source": "Field observation"}
            ... )
            >>> print(updated_record.record_info)
            {'notes': 'Updated measurement', 'source': 'Field observation'}

        Args:
            record_info (dict): The new information to set.
        Returns:
            Optional[TraitRecord]: The updated trait record, or None if an error occurred.
        """
        try:
            current_id = self.id
            trait_record = TraitRecordModel.get(current_id)
            if not trait_record:
                logger.debug(f"TraitRecord with ID {current_id} not found.")
                return None
            TraitRecordModel.update(
                trait_record,
                record_info=record_info
            )
            trait_record = self.model_validate(trait_record)
            self.refresh()
            return trait_record
        except Exception as e:
            logger.error(f"Error setting record info for TraitRecord: {e}")
            return None

__repr__()

Return a detailed string representation of the TraitRecord object.

Source code in gemini/api/trait_record.py
def __repr__(self):
    """Return a detailed string representation of the TraitRecord object."""
    return f"TraitRecord(id={self.id}, timestamp={self.timestamp}, trait_name={self.trait_name}, dataset_name={self.dataset_name}, experiment_name={self.experiment_name}, site_name={self.site_name}, season_name={self.season_name}, plot_number={self.plot_number}, plot_row_number={self.plot_row_number}, plot_column_number={self.plot_column_number})"

__str__()

Return a string representation of the TraitRecord object.

Source code in gemini/api/trait_record.py
def __str__(self):
    """Return a string representation of the TraitRecord object."""
    return f"TraitRecord(id={self.id}, timestamp={self.timestamp}, trait_name={self.trait_name}, dataset_name={self.dataset_name}, experiment_name={self.experiment_name}, site_name={self.site_name}, season_name={self.season_name}, plot_number={self.plot_number}, plot_row_number={self.plot_row_number}, plot_column_number={self.plot_column_number})"

create(timestamp=datetime.now(), collection_date=None, dataset_name=None, trait_name=None, trait_value=None, experiment_name=None, site_name=None, season_name=None, plot_number=None, plot_row_number=None, plot_column_number=None, record_info=None, insert_on_create=True) classmethod

Create a new trait record.

Examples:

>>> TraitRecord.create(
...     timestamp=datetime(2023, 10, 1, 12, 0),
...     collection_date=date(2023, 10, 1),
...     dataset_name="Plant Growth Study",
...     trait_name="Height",
...     trait_value=150.0,
...     experiment_name="Growth Experiment 1",
...     site_name="Research Farm A",
...     season_name="Spring 2023",
...     plot_number=1,
...     plot_row_number=2,
...     plot_column_number=3,
...     record_info={"notes": "Initial measurement"},
...     insert_on_create=True
... )
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

Parameters:

Name Type Description Default
timestamp datetime

The timestamp of the record. Defaults to now.

now()
collection_date date

The collection date. Defaults to None.

None
dataset_name str

The name of the dataset. Defaults to None.

None
trait_name str

The name of the trait. 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
site_name str

The name of the site. Defaults to None.

None
season_name str

The name of the season. 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
insert_on_create bool

Whether to insert on create. Defaults to True.

True

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

Source code in gemini/api/trait_record.py
@classmethod
def create(
    cls,
    timestamp: datetime = datetime.now(),
    collection_date: date = None,
    dataset_name: str = None,
    trait_name: str = None,
    trait_value: float = None,
    experiment_name: str = None,
    site_name: str = None,
    season_name: str = None,
    plot_number: int = None,
    plot_row_number: int = None,
    plot_column_number: int = None,
    record_info: dict = None,
    insert_on_create: bool = True
) -> Optional["TraitRecord"]:
    """
    Create a new trait record.

    Examples:
        >>> TraitRecord.create(
        ...     timestamp=datetime(2023, 10, 1, 12, 0),
        ...     collection_date=date(2023, 10, 1),
        ...     dataset_name="Plant Growth Study",
        ...     trait_name="Height",
        ...     trait_value=150.0,
        ...     experiment_name="Growth Experiment 1",
        ...     site_name="Research Farm A",
        ...     season_name="Spring 2023",
        ...     plot_number=1,
        ...     plot_row_number=2,
        ...     plot_column_number=3,
        ...     record_info={"notes": "Initial measurement"},
        ...     insert_on_create=True
        ... )
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

    Args:
        timestamp (datetime, optional): The timestamp of the record. Defaults to now.
        collection_date (date, optional): The collection date. Defaults to None.
        dataset_name (str, optional): The name of the dataset. Defaults to None.
        trait_name (str, optional): The name of the trait. 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.
        site_name (str, optional): The name of the site. Defaults to None.
        season_name (str, optional): The name of the season. 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 {{}}.
        insert_on_create (bool, optional): Whether to insert on create. Defaults to True.
    Returns:
        Optional[TraitRecord]: The created trait record, or None if an error occurred.
    """
    try:
        if not any([experiment_name, site_name, season_name]):
            raise ValueError("At least one of experiment_name, site_name, or season_name must be provided.")
        if not trait_name:
            raise ValueError("Trait name is required.")
        if not dataset_name:
            raise ValueError("Dataset name is required.")
        # Plot row/column may only be provided together with a plot_number.
        # plot_number by itself is valid (row/column are optional).
        if (plot_row_number is not None or plot_column_number is not None) and plot_number is None:
            raise ValueError("plot_number is required when plot_row_number or plot_column_number is provided.")
        if not timestamp:
            timestamp = datetime.now()
        if not collection_date:
            collection_date = timestamp.date()
        # Allow 0.0 and negative values — only reject None/missing.
        if trait_value is None:
            raise ValueError("Trait value is required.")
        trait_record = TraitRecord(
            timestamp=timestamp,
            collection_date=collection_date,
            dataset_name=dataset_name,
            trait_name=trait_name,
            trait_value=trait_value,
            experiment_name=experiment_name,
            site_name=site_name,
            season_name=season_name,
            plot_number=plot_number,
            plot_row_number=plot_row_number,
            plot_column_number=plot_column_number,
            record_info=record_info
        )
        if insert_on_create:
            insert_success, inserted_record_ids = cls.insert([trait_record])
            if not insert_success:
                logger.info(f"Failed to insert TraitRecord: {trait_record}")
                return None
            if not inserted_record_ids or len(inserted_record_ids) == 0:
                logger.info(f"No TraitRecord IDs returned after insertion.")
                return None
            inserted_record_id = inserted_record_ids[0]
            trait_record = cls.get_by_id(inserted_record_id)
        return trait_record
    except Exception as e:
        logger.error(f"Error creating TraitRecord: {e}")
        return None

delete()

Delete the trait record.

Examples:

>>> trait_record = TraitRecord.get_by_id(UUID('...'))
>>> success = trait_record.delete()
>>> print(success)
True

Returns:

Name Type Description
bool bool

True if the trait record was deleted, False otherwise.

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

    Examples:
        >>> trait_record = TraitRecord.get_by_id(UUID('...'))
        >>> success = trait_record.delete()
        >>> print(success)
        True

    Returns:
        bool: True if the trait record was deleted, False otherwise.
    """
    try:
        current_id = self.id
        trait_record = TraitRecordModel.get(current_id)
        if not trait_record:
            logger.debug(f"TraitRecord with ID {current_id} not found.")
            return False
        TraitRecordModel.delete(trait_record)
        return True
    except Exception as e:
        logger.error(f"Error deleting TraitRecord: {e}")
        return False

exists(timestamp, trait_name, dataset_name, experiment_name, site_name, season_name, plot_number=None, plot_row_number=None, plot_column_number=None) classmethod

Check if a trait record with the given parameters exists.

Examples:

>>> TraitRecord.exists(
...     timestamp=datetime(2023, 10, 1, 12, 0),
...     trait_name="Height",
...     dataset_name="Plant Growth Study",
...     experiment_name="Growth Experiment 1",
...     site_name="Research Farm A",
...     season_name="Spring 2023",
...     plot_number=1,
...     plot_row_number=2,
...     plot_column_number=3
... )
True

Parameters:

Name Type Description Default
timestamp datetime

The timestamp of the record.

required
trait_name str

The name of the trait.

required
dataset_name str

The name of the dataset.

required
experiment_name str

The name of the experiment.

required
season_name str

The name of the season.

required
site_name str

The name of the site.

required
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

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

Source code in gemini/api/trait_record.py
@classmethod
def exists(
    cls,
    timestamp: datetime,
    trait_name: str,
    dataset_name: str,
    experiment_name: str,
    site_name: str,
    season_name: str,
    plot_number: int = None,
    plot_row_number: int = None,
    plot_column_number: int = None
) -> bool:
    """
    Check if a trait record with the given parameters exists.

    Examples:
        >>> TraitRecord.exists(
        ...     timestamp=datetime(2023, 10, 1, 12, 0),
        ...     trait_name="Height",
        ...     dataset_name="Plant Growth Study",
        ...     experiment_name="Growth Experiment 1",
        ...     site_name="Research Farm A",
        ...     season_name="Spring 2023",
        ...     plot_number=1,
        ...     plot_row_number=2,
        ...     plot_column_number=3
        ... )
        True


    Args:
        timestamp (datetime): The timestamp of the record.
        trait_name (str): The name of the trait.
        dataset_name (str): The name of the dataset.
        experiment_name (str): The name of the experiment.
        season_name (str): The name of the season.
        site_name (str): The name of the site.
        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.
    Returns:
        bool: True if the trait record exists, False otherwise.
    """
    try:
        exists = TraitRecordModel.exists(
            timestamp=timestamp,
            trait_name=trait_name,
            dataset_name=dataset_name,
            experiment_name=experiment_name,
            site_name=site_name,
            season_name=season_name,
            plot_number=plot_number,
            plot_row_number=plot_row_number,
            plot_column_number=plot_column_number
        )
        return exists
    except Exception as e:
        logger.error(f"Error checking existence of TraitRecord: {e}")
        raise e

filter(start_timestamp=None, end_timestamp=None, trait_names=None, dataset_names=None, experiment_names=None, season_names=None, site_names=None) classmethod

Filter trait records based on custom logic.

Examples:

>>> records = TraitRecord.filter(
...     start_timestamp=datetime(2023, 10, 1, 0, 0),
...     end_timestamp=datetime(2023, 10, 31, 23, 59),
...     trait_names=["Height", "Width"],
...     dataset_names=["Plant Growth Study"],
...     experiment_names=["Growth Experiment 1"],
...     season_names=["Spring 2023"],
...     site_names=["Research Farm A"]
... )
>>> for record in records:
...     print(record)
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

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
trait_names List[str]

List of trait names. 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

Yields: TraitRecord: Filtered trait records.

Source code in gemini/api/trait_record.py
@classmethod
def filter(
    cls,
    start_timestamp: Optional[datetime] = None,
    end_timestamp: Optional[datetime] = None,
    trait_names: Optional[List[str]] = 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
) -> Generator["TraitRecord", None, None]:
    """
    Filter trait records based on custom logic.

    Examples:
        >>> records = TraitRecord.filter(
        ...     start_timestamp=datetime(2023, 10, 1, 0, 0),
        ...     end_timestamp=datetime(2023, 10, 31, 23, 59),
        ...     trait_names=["Height", "Width"],
        ...     dataset_names=["Plant Growth Study"],
        ...     experiment_names=["Growth Experiment 1"],
        ...     season_names=["Spring 2023"],
        ...     site_names=["Research Farm A"]
        ... )
        >>> for record in records:
        ...     print(record)
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

    Args:
        start_timestamp (datetime, optional): Start of timestamp range. Defaults to None.
        end_timestamp (datetime, optional): End of timestamp range. Defaults to None.
        trait_names (List[str], optional): List of trait names. 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.
    Yields:
        TraitRecord: Filtered trait records.
    """
    try:
        if not any([start_timestamp, end_timestamp, trait_names, dataset_names, experiment_names, season_names, site_names]):
            logger.warning("At least one filter parameter must be provided.")
            return
        records = TraitRecordModel.filter_records(
            start_timestamp=start_timestamp,
            end_timestamp=end_timestamp,
            trait_names=trait_names,
            dataset_names=dataset_names,
            experiment_names=experiment_names,
            season_names=season_names,
            site_names=site_names
        )
        for record in records:
            record = cls.model_validate(record)
            yield record
    except Exception as e:
        logger.error(f"Error filtering TraitRecords: {e}")
        yield from []

get(timestamp, trait_name, dataset_name, experiment_name, site_name, season_name, plot_number=None, plot_row_number=None, plot_column_number=None) classmethod

Retrieve a trait record by its parameters.

Examples:

>>> TraitRecord.get(
...     timestamp=datetime(2023, 10, 1, 12, 0),
...     trait_name="Height",
...     dataset_name="Plant Growth Study",
...     experiment_name="Growth Experiment 1",
...     site_name="Research Farm A",
...     season_name="Spring 2023",
...     plot_number=1,
...     plot_row_number=2,
...     plot_column_number=3
... )
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

Parameters:

Name Type Description Default
timestamp datetime

The timestamp of the record.

required
trait_name str

The name of the trait.

required
dataset_name str

The name of the dataset.

required
experiment_name str

The name of the experiment.

required
site_name str

The name of the site.

required
season_name str

The name of the season.

required
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

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

Source code in gemini/api/trait_record.py
@classmethod
def get(
    cls,
    timestamp: datetime,
    trait_name: str,
    dataset_name: str,
    experiment_name: str,
    site_name: str,
    season_name: str,
    plot_number: int = None,
    plot_row_number: int = None,
    plot_column_number: int = None
) -> Optional["TraitRecord"]:
    """
    Retrieve a trait record by its parameters.

    Examples:
        >>> TraitRecord.get(
        ...     timestamp=datetime(2023, 10, 1, 12, 0),
        ...     trait_name="Height",
        ...     dataset_name="Plant Growth Study",
        ...     experiment_name="Growth Experiment 1",
        ...     site_name="Research Farm A",
        ...     season_name="Spring 2023",
        ...     plot_number=1,
        ...     plot_row_number=2,
        ...     plot_column_number=3
        ... )
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

    Args:
        timestamp (datetime): The timestamp of the record.
        trait_name (str): The name of the trait.
        dataset_name (str): The name of the dataset.
        experiment_name (str): The name of the experiment.
        site_name (str): The name of the site.
        season_name (str): The name of the season.
        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.
    Returns:
        Optional[TraitRecord]: The trait record, or None if not found.
    """
    try:
        if not timestamp:
            logger.warning("Timestamp is required to get TraitRecord.")
            return None
        if not trait_name:
            logger.warning("Trait name is required to get TraitRecord.")
            return None
        if not dataset_name:
            logger.warning("Dataset name is required to get TraitRecord.")
            return None
        if not experiment_name and not site_name and not season_name:
            logger.warning("At least one of experiment_name, site_name, or season_name is required to get TraitRecord.")
            return None
        if not all([plot_number, plot_row_number, plot_column_number]):
            logger.warning("Plot information (number, row, column) is required if any is provided.")
            return None
        trait_record = TraitRecordsIMMVModel.get_by_parameters(
            timestamp=timestamp,
            trait_name=trait_name,
            dataset_name=dataset_name,
            experiment_name=experiment_name,
            site_name=site_name,
            season_name=season_name,
            plot_number=plot_number,
            plot_row_number=plot_row_number,
            plot_column_number=plot_column_number
        )
        if not trait_record:
            logger.debug("TraitRecord not found with the provided parameters.")
            return None
        trait_record = cls.model_validate(trait_record)
        return trait_record
    except Exception as e:
        logger.error(f"Error getting TraitRecord: {e}")
        return None

get_all(limit=100) classmethod

Retrieve all trait records, up to a specified limit.

Examples:

>>> TraitRecord.get_all(limit=10)
>>> for record in TraitRecord.get_all(limit=10):
...     print(record)
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 2, 12, 0), trait_name='Width', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

Parameters:

Name Type Description Default
limit int

The maximum number of records to retrieve. Defaults to 100.

100

Returns: Optional[List[TraitRecord]]: List of trait records, or None if not found.

Source code in gemini/api/trait_record.py
@classmethod
def get_all(cls, limit: int = 100) -> Optional[List["TraitRecord"]]:
    """
    Retrieve all trait records, up to a specified limit.

    Examples:
        >>> TraitRecord.get_all(limit=10)
        >>> for record in TraitRecord.get_all(limit=10):
        ...     print(record)
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 2, 12, 0), trait_name='Width', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

    Args:
        limit (int, optional): The maximum number of records to retrieve. Defaults to 100.
    Returns:
        Optional[List[TraitRecord]]: List of trait records, or None if not found.
    """
    try:
        records = TraitRecordModel.all(limit=limit)
        if not records or len(records) == 0:
            logger.info(f"No TraitRecords found")
            return None
        records = [cls.model_validate(instance) for instance in records]
        return records
    except Exception as e:
        logger.error(f"Error getting all TraitRecords: {e}")
        return None

get_by_id(id) classmethod

Retrieve a trait record by its ID.

Examples:

>>> TraitRecord.get_by_id(UUID('...'))
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

Parameters:

Name Type Description Default
id UUID | int | str

The ID of the trait record.

required

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

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

    Examples:
        >>> TraitRecord.get_by_id(UUID('...'))
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

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

get_info()

Get the additional information of the trait record.

Examples:

>>> trait_record = TraitRecord.get_by_id(UUID('...'))
>>> record_info = trait_record.get_info()
>>> print(record_info)
{'notes': 'Initial measurement', 'source': 'Field observation'}

Returns:

Type Description
Optional[dict]

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

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

    Examples:
        >>> trait_record = TraitRecord.get_by_id(UUID('...'))
        >>> record_info = trait_record.get_info()
        >>> print(record_info)
        {'notes': 'Initial measurement', 'source': 'Field observation'}

    Returns:
        Optional[dict]: The record's info, or None if not found.
    """
    try:
        current_id = self.id
        trait_record = TraitRecordModel.get(current_id)
        if not trait_record:
            logger.debug(f"TraitRecord with ID {current_id} not found.")
            return None
        record_info = trait_record.record_info
        if not record_info:
            logger.info(f"No record info found for TraitRecord with ID {current_id}.")
            return None
        return record_info
    except Exception as e:
        logger.error(f"Error getting record info for TraitRecord: {e}")
        return None

insert(records) classmethod

Insert a list of trait records into the database.

Parameters:

Name Type Description Default
records List[TraitRecord]

The records to insert.

required

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

Source code in gemini/api/trait_record.py
@classmethod
def insert(cls, records: List["TraitRecord"]) -> tuple[bool, List[str]]:
    """
    Insert a list of trait records into the database.

    Args:
        records (List[TraitRecord]): The records to insert.
    Returns:
        tuple[bool, List[str]]: Success status and list of inserted record IDs.
    """
    if not records or len(records) == 0:
        logger.info(f"No records provided to insert.")
        return False, []
    records_to_insert = []
    for record in records:
        record_dict = record.model_dump()
        record_dict = {k: v for k, v in record_dict.items() if v is not None}
        records_to_insert.append(record_dict)
    logger.info(f"Inserting {len(records_to_insert)} TraitRecords.")
    # Deliberately does NOT swallow DB errors: Postgres trigger RAISEs
    # (e.g. "No matching plot found for the given parameters") carry the
    # actual cause the caller needs to surface to the user.
    inserted_record_ids = TraitRecordModel.insert_bulk('trait_records_unique', records_to_insert)
    logger.info(f"Inserted {len(inserted_record_ids)} TraitRecords.")
    return True, inserted_record_ids

refresh()

Refresh the trait record's data from the database.

Examples:

>>> trait_record = TraitRecord.get_by_id(UUID('...'))
>>> refreshed_record = trait_record.refresh()
>>> print(refreshed_record)
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

Returns:

Type Description
Optional[TraitRecord]

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

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

    Examples:
        >>> trait_record = TraitRecord.get_by_id(UUID('...'))
        >>> refreshed_record = trait_record.refresh()
        >>> print(refreshed_record)
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

    Returns:
        Optional[TraitRecord]: The refreshed trait record, or None if an error occurred.
    """
    try:
        db_instance = TraitRecordModel.get(self.id)
        if not db_instance:
            logger.debug(f"TraitRecord with ID {self.id} not found.")
            return None
        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 TraitRecord: {e}")
        return None

search(dataset_name=None, trait_name=None, trait_value=None, experiment_name=None, site_name=None, season_name=None, plot_number=None, plot_row_number=None, plot_column_number=None, collection_date=None, record_info=None) classmethod

Search for trait records based on various criteria.

Examples:

>>> for record in TraitRecord.search(dataset_name="Plant Growth Study", trait_name="Height"):
...     print(record)
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 2, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset. Defaults to None.

None
trait_name str

The name of the trait. 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
site_name str

The name of the site. Defaults to None.

None
season_name str

The name of the season. 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
collection_date date

The collection date. Defaults to None.

None
record_info dict

Additional info. Defaults to None.

None

Yields: TraitRecord: Matching trait records.

Source code in gemini/api/trait_record.py
@classmethod
def search(
    cls,
    dataset_name: str = None,
    trait_name: str = None,
    trait_value: float = None,
    experiment_name: str = None,
    site_name: str = None,
    season_name: str = None,
    plot_number: int = None,
    plot_row_number: int = None,
    plot_column_number: int = None,
    collection_date: date = None,
    record_info: dict = None
) -> Generator["TraitRecord", None, None]:
    """
    Search for trait records based on various criteria.

    Examples:
        >>> for record in TraitRecord.search(dataset_name="Plant Growth Study", trait_name="Height"):
        ...     print(record)
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 2, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

    Args:
        dataset_name (str, optional): The name of the dataset. Defaults to None.
        trait_name (str, optional): The name of the trait. 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.
        site_name (str, optional): The name of the site. Defaults to None.
        season_name (str, optional): The name of the season. 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.
        collection_date (date, optional): The collection date. Defaults to None.
        record_info (dict, optional): Additional info. Defaults to None.
    Yields:
        TraitRecord: Matching trait records.
    """
    try:
        if not any([dataset_name, trait_name, trait_value, experiment_name, site_name, season_name, plot_number, plot_row_number, plot_column_number, collection_date, record_info]):
            logger.warning("At least one search parameter must be provided.")
            return
        records = TraitRecordsIMMVModel.stream(
            dataset_name=dataset_name,
            trait_name=trait_name,
            trait_value=trait_value,
            experiment_name=experiment_name,
            site_name=site_name,
            season_name=season_name,
            plot_number=plot_number,
            plot_row_number=plot_row_number,
            plot_column_number=plot_column_number,
            collection_date=collection_date,
            record_info=record_info
        )
        for record in records:
            record = cls.model_validate(record)
            yield record
    except Exception as e:
        logger.error(f"Error searching TraitRecords: {e}")
        yield from []

set_info(record_info)

Set the additional information of the trait record.

Examples:

>>> trait_record = TraitRecord.get_by_id(UUID('...'))
>>> updated_record = trait_record.set_info(
...     record_info={"notes": "Updated measurement", "source": "Field observation"}
... )
>>> print(updated_record.record_info)
{'notes': 'Updated measurement', 'source': 'Field observation'}

Parameters:

Name Type Description Default
record_info dict

The new information to set.

required

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

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

    Examples:
        >>> trait_record = TraitRecord.get_by_id(UUID('...'))
        >>> updated_record = trait_record.set_info(
        ...     record_info={"notes": "Updated measurement", "source": "Field observation"}
        ... )
        >>> print(updated_record.record_info)
        {'notes': 'Updated measurement', 'source': 'Field observation'}

    Args:
        record_info (dict): The new information to set.
    Returns:
        Optional[TraitRecord]: The updated trait record, or None if an error occurred.
    """
    try:
        current_id = self.id
        trait_record = TraitRecordModel.get(current_id)
        if not trait_record:
            logger.debug(f"TraitRecord with ID {current_id} not found.")
            return None
        TraitRecordModel.update(
            trait_record,
            record_info=record_info
        )
        trait_record = self.model_validate(trait_record)
        self.refresh()
        return trait_record
    except Exception as e:
        logger.error(f"Error setting record info for TraitRecord: {e}")
        return None

update(trait_value=None, record_info=None)

Update the details of the trait record.

Examples:

>>> trait_record = TraitRecord.get_by_id(UUID('...'))
>>> updated_record = trait_record.update(
...     trait_value=160.0,
...     record_info={"notes": "Updated measurement"}
... )
>>> print(updated_record)
TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

Parameters:

Name Type Description Default
trait_value float

The new trait value. Defaults to None.

None
record_info dict

The new record information. Defaults to None.

None

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

Source code in gemini/api/trait_record.py
def update(
    self,
    trait_value: float = None,
    record_info: dict = None
) -> Optional["TraitRecord"]:
    """
    Update the details of the trait record.

    Examples:
        >>> trait_record = TraitRecord.get_by_id(UUID('...'))
        >>> updated_record = trait_record.update(
        ...     trait_value=160.0,
        ...     record_info={"notes": "Updated measurement"}
        ... )
        >>> print(updated_record)
        TraitRecord(id=UUID('...'), timestamp=datetime(2023, 10, 1, 12, 0), trait_name='Height', dataset_name='Plant Growth Study', experiment_name='Growth Experiment 1', site_name='Research Farm A', season_name='Spring 2023', plot_number=1, plot_row_number=2, plot_column_number=3)

    Args:
        trait_value (float, optional): The new trait value. Defaults to None.
        record_info (dict, optional): The new record information. Defaults to None.
    Returns:
        Optional[TraitRecord]: The updated trait record, or None if an error occurred.
    """
    try:
        if not any([trait_value, record_info]):
            logger.warning("At least one parameter must be provided to update TraitRecord.")
            return None
        current_id = self.id
        trait_record = TraitRecordModel.get(current_id)
        if not trait_record:
            logger.debug(f"TraitRecord with ID {current_id} not found.")
            return None
        trait_record = TraitRecordModel.update(
            trait_record,
            trait_value=trait_value,
            record_info=record_info
        )
        trait_record = self.model_validate(trait_record)
        self.refresh()
        return trait_record
    except Exception as e:
        logger.error(f"Error updating TraitRecord: {e}")
        return None