Skip to main content

sbol_utilities/
lib.rs

1//! Biology-first construction helpers for sbol-rs, in the spirit of the Python
2//! `sbol_utilities` package.
3//!
4//! The verbs read as inherent methods on [`sbol3::design::Design`] via the
5//! [`ComponentVerbs`] extension trait. Import the [`prelude`] to light them up:
6//!
7//! ```
8//! use sbol3::design::Design;
9//! use sbol_utilities::prelude::*;
10//!
11//! let mut d = Design::new("https://example.org/lab").unwrap();
12//! let plac = d.promoter("pLac", "caatacg").description("LacI-repressible").add();
13//! let b0034 = d.rbs("B0034", "ttgaac").add();
14//! d.engineered_region("pLac_tu", [plac, b0034]).add();
15//! let doc = d.finish().unwrap();
16//! assert_eq!(doc.components().count(), 3); // pLac, B0034, pLac_tu
17//! ```
18
19#![forbid(unsafe_code)]
20
21use sbol3::Iri;
22use sbol3::constants::{SO_CDS, SO_ENGINEERED_REGION, SO_PROMOTER, SO_RBS, SO_TERMINATOR};
23use sbol3::design::{ComponentId, Design, FeatureId};
24use sbol3::prelude::SbolIdentified;
25
26pub mod combinatorial;
27pub mod compute_sequence;
28pub mod verbs;
29
30pub use combinatorial::{ExpandError, expand_derivation, expand_derivations};
31pub use compute_sequence::{ComputeSequenceError, compute_all_sequences, compute_sequence};
32pub use verbs::{FunctionalComponentDraft, MoleculeVerbs};
33
34/// Common imports for authoring designs with the biology verbs.
35pub mod prelude {
36    pub use crate::combinatorial::{expand_derivation, expand_derivations};
37    pub use crate::compute_sequence::{compute_all_sequences, compute_sequence};
38    pub use crate::{ComponentVerbs, FunctionalComponentDraft, Molecule, MoleculeVerbs};
39    pub use crate::{Part, PartDraft, RegionDraft};
40}
41
42/// A member of an [`engineered_region`](ComponentVerbs::engineered_region):
43/// either a `Component` (wrapped in a fresh sub-component with its roles
44/// copied) or a detached feature (used as configured). This mirrors the Python
45/// `Union[Component, SubComponent]`.
46#[derive(Clone, Copy, Debug)]
47pub enum Part {
48    /// A component to instantiate as a new sub-component, copying its roles.
49    Component(ComponentId),
50    /// A detached feature (from
51    /// [`Design::detached_sub_component`](sbol3::design::Design::detached_sub_component)),
52    /// placed under the region as configured.
53    Feature(FeatureId),
54}
55
56impl From<ComponentId> for Part {
57    fn from(value: ComponentId) -> Self {
58        Part::Component(value)
59    }
60}
61
62impl From<FeatureId> for Part {
63    fn from(value: FeatureId) -> Self {
64        Part::Feature(value)
65    }
66}
67
68/// The molecule type of a biological part. It sets both the `Component` type
69/// (`SBO_DNA` / `SBO_RNA` / `SBO_PROTEIN`) and the matching sequence encoding,
70/// so a part verb states its chemistry once.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Molecule {
73    /// DNA: `SBO_DNA` component type, IUPAC nucleic-acid sequence encoding.
74    Dna,
75    /// RNA: `SBO_RNA` component type, IUPAC nucleic-acid sequence encoding.
76    Rna,
77    /// Protein: `SBO_PROTEIN` component type, IUPAC amino-acid sequence encoding.
78    Protein,
79}
80
81/// Biology-first construction verbs, implemented on [`Design`].
82pub trait ComponentVerbs {
83    /// A promoter (`SO:0000167`) DNA part with its sequence.
84    fn promoter<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d>;
85    /// A ribosome entry site (`SO:0000139`) DNA part with its sequence.
86    fn rbs<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d>;
87    /// A coding sequence (`SO:0000316`) DNA part with its sequence.
88    fn cds<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d>;
89    /// A terminator (`SO:0000141`) DNA part with its sequence.
90    fn terminator<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d>;
91    /// An engineered region (`SO:0000804`) whose parts are chained head-to-tail
92    /// with `meets` constraints, each part's roles copied onto its
93    /// sub-component.
94    fn engineered_region<'d, I>(&'d mut self, display_id: &str, parts: I) -> RegionDraft<'d>
95    where
96        I: IntoIterator,
97        I::Item: Into<Part>;
98}
99
100impl ComponentVerbs for Design {
101    fn promoter<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d> {
102        PartDraft::new(self, display_id, SO_PROMOTER, Molecule::Dna, elements)
103    }
104
105    fn rbs<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d> {
106        PartDraft::new(self, display_id, SO_RBS, Molecule::Dna, elements)
107    }
108
109    fn cds<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d> {
110        PartDraft::new(self, display_id, SO_CDS, Molecule::Dna, elements)
111    }
112
113    fn terminator<'d>(&'d mut self, display_id: &str, elements: &str) -> PartDraft<'d> {
114        PartDraft::new(self, display_id, SO_TERMINATOR, Molecule::Dna, elements)
115    }
116
117    fn engineered_region<'d, I>(&'d mut self, display_id: &str, parts: I) -> RegionDraft<'d>
118    where
119        I: IntoIterator,
120        I::Item: Into<Part>,
121    {
122        RegionDraft {
123            design: self,
124            display_id: display_id.to_string(),
125            parts: parts.into_iter().map(Into::into).collect(),
126            name: None,
127            description: None,
128        }
129    }
130}
131
132/// In-progress DNA part (a `Component` plus its `Sequence`), created by the
133/// part verbs. The sequence is registered automatically; `.add()` returns only
134/// the component handle.
135#[must_use = "call `.add()` to register the part in the design"]
136pub struct PartDraft<'d> {
137    design: &'d mut Design,
138    display_id: String,
139    role: Iri,
140    molecule: Molecule,
141    elements: String,
142    name: Option<String>,
143    description: Option<String>,
144}
145
146impl<'d> PartDraft<'d> {
147    pub(crate) fn new(
148        design: &'d mut Design,
149        display_id: &str,
150        role: Iri,
151        molecule: Molecule,
152        elements: &str,
153    ) -> Self {
154        Self {
155            design,
156            display_id: display_id.to_string(),
157            role,
158            molecule,
159            elements: elements.to_string(),
160            name: None,
161            description: None,
162        }
163    }
164
165    /// Sets the human-readable name.
166    pub fn name(mut self, name: impl Into<String>) -> Self {
167        self.name = Some(name.into());
168        self
169    }
170
171    /// Sets the description.
172    pub fn description(mut self, description: impl Into<String>) -> Self {
173        self.description = Some(description.into());
174        self
175    }
176
177    /// Registers the part (component + sequence) and returns the component.
178    pub fn add(self) -> ComponentId {
179        let Self {
180            design,
181            display_id,
182            role,
183            molecule,
184            elements,
185            name,
186            description,
187        } = self;
188
189        let sequence = design
190            .sequence(&format!("{display_id}_seq"))
191            .elements(elements);
192        let sequence = match molecule {
193            Molecule::Dna => sequence.dna(),
194            Molecule::Rna => sequence.rna(),
195            Molecule::Protein => sequence.protein(),
196        }
197        .add();
198
199        let component = design.component(&display_id);
200        let component = match molecule {
201            Molecule::Dna => component.dna(),
202            Molecule::Rna => component.rna(),
203            Molecule::Protein => component.protein(),
204        };
205        let mut component = component.role(role).sequence(sequence);
206        if let Some(name) = name {
207            component = component.name(name);
208        }
209        if let Some(description) = description {
210            component = component.description(description);
211        }
212        component.add()
213    }
214}
215
216/// In-progress engineered region, created by
217/// [`engineered_region`](ComponentVerbs::engineered_region).
218#[must_use = "call `.add()` to register the region in the design"]
219pub struct RegionDraft<'d> {
220    design: &'d mut Design,
221    display_id: String,
222    parts: Vec<Part>,
223    name: Option<String>,
224    description: Option<String>,
225}
226
227impl RegionDraft<'_> {
228    /// Sets the human-readable name.
229    pub fn name(mut self, name: impl Into<String>) -> Self {
230        self.name = Some(name.into());
231        self
232    }
233
234    /// Sets the description.
235    pub fn description(mut self, description: impl Into<String>) -> Self {
236        self.description = Some(description.into());
237        self
238    }
239
240    /// Registers the region, its sub-components, and their `meets` ordering.
241    /// Returns the region component.
242    pub fn add(self) -> ComponentId {
243        let Self {
244            design,
245            display_id,
246            parts,
247            name,
248            description,
249        } = self;
250
251        let mut region = design
252            .component(&display_id)
253            .dna()
254            .role(SO_ENGINEERED_REGION);
255        if let Some(name) = name {
256            region = region.name(name);
257        }
258        if let Some(description) = description {
259            region = region.description(description);
260        }
261        let region = region.add();
262
263        let mut features = Vec::with_capacity(parts.len());
264        for (index, part) in parts.into_iter().enumerate() {
265            match part {
266                Part::Component(component) => {
267                    let (roles, source_name) = match design.resolve_component(component) {
268                        Some(component) => (
269                            component.roles.clone(),
270                            component.display_id().map(str::to_string),
271                        ),
272                        None => (Vec::new(), None),
273                    };
274                    if roles.is_empty() {
275                        design.report(format!(
276                            "engineered_region `{display_id}` includes a part with no roles; \
277                             DNAplotlib requires roles on the sub-component"
278                        ));
279                    }
280                    let mut sub = design
281                        .sub_component(region, &format!("{display_id}_sub{index}"))
282                        .instance_of(component)
283                        .roles(roles);
284                    if let Some(source_name) = source_name {
285                        sub = sub.name(source_name);
286                    }
287                    features.push(sub.add());
288                }
289                Part::Feature(feature) => {
290                    // A pre-built (detached) feature is placed under the region
291                    // as configured — its own roles and roleIntegration are
292                    // kept, not copied from a component. Mirrors the Python
293                    // `add_feature`, which appends a supplied SubComponent as-is.
294                    features.push(design.place_feature(region, feature));
295                }
296            }
297        }
298
299        for pair in features.windows(2) {
300            design.meets(region, pair[0], pair[1]);
301        }
302
303        region
304    }
305}
306
307#[cfg(test)]
308mod tests;