def runTest(self):
        protocol = Protocol()
        resource = protocol.ref("resource", None, "96-flat", discard=True)
        pcr = protocol.ref("pcr", None, "96-flat", discard=True)
        bacteria = protocol.ref("bacteria", None, "96-flat", discard=True)
        self.assertEqual(len(protocol.as_dict()['refs']), 3,
                         'incorrect number of refs')
        self.assertEqual(protocol.as_dict()['refs']['resource'], {
            "new": "96-flat",
            "discard": True
        })

        bacteria_wells = WellGroup([
            bacteria.well("B1"),
            bacteria.well("C5"),
            bacteria.well("A5"),
            bacteria.well("A1")
        ])

        protocol.distribute(
            resource.well("A1").set_volume("40:microliter"),
            pcr.wells_from('A1', 5), "5:microliter")
        protocol.distribute(
            resource.well("A1").set_volume("40:microliter"), bacteria_wells,
            "5:microliter")

        self.assertEqual(len(protocol.instructions), 1)
        self.assertEqual(protocol.instructions[0].op, "pipette")
        self.assertEqual(len(protocol.instructions[0].groups), 2)

        protocol.incubate(bacteria, "warm_37", "30:minute")

        self.assertEqual(len(protocol.instructions), 2)
        self.assertEqual(protocol.instructions[1].op, "incubate")
        self.assertEqual(protocol.instructions[1].duration, "30:minute")
    def runTest(self):
        protocol = Protocol()
        resource = protocol.ref("resource", None, "96-flat", discard=True)
        pcr = protocol.ref("pcr", None, "96-flat", discard=True)
        bacteria = protocol.ref("bacteria", None, "96-flat", discard=True)
        self.assertEqual(len(protocol.as_dict()['refs']), 3, 'incorrect number of refs')
        self.assertEqual(protocol.as_dict()['refs']['resource'], {"new": "96-flat",
                        "discard": True})

        bacteria_wells = WellGroup([bacteria.well("B1"), bacteria.well("C5"),
                                    bacteria.well("A5"), bacteria.well("A1")])

        protocol.distribute(resource.well("A1").set_volume("40:microliter"),
                            pcr.wells_from('A1',5), "5:microliter")
        protocol.distribute(resource.well("A1").set_volume("40:microliter"),
                            bacteria_wells, "5:microliter")

        self.assertEqual(len(protocol.instructions), 1)
        self.assertEqual(protocol.instructions[0].op, "pipette")
        self.assertEqual(len(protocol.instructions[0].groups), 2)

        protocol.incubate(bacteria, "warm_37", "30:minute")

        self.assertEqual(len(protocol.instructions), 2)
        self.assertEqual(protocol.instructions[1].op, "incubate")
        self.assertEqual(protocol.instructions[1].duration, "30:minute")
 def test_outs(self):
     p = Protocol()
     self.assertFalse('outs' in p.as_dict())
     plate = p.ref("plate", None, "96-pcr", discard=True)
     plate.well(0).set_name("test_well")
     self.assertTrue(plate.well(0).name == "test_well")
     self.assertTrue(list(p.as_dict()['outs'].keys()) == ['plate'])
     self.assertTrue(list(list(p.as_dict()['outs'].values())[0].keys()) == ['0'])
     self.assertTrue(list(p.as_dict()['outs'].values())[0]['0'] == {'name': 'test_well'})
def generate_autoprotocol(instructions_dict):
    p = Protocol()
    part_ref_dict = {}  # ref name: ref_object
    # add destination plate to ref dict
    moclo_dest_plate_name = 'MoCloDestinationPlate'
    moclo_dest_plate_ref = p.ref(moclo_dest_plate_name,
                                 cont_type="96-pcr",
                                 discard=True)
    part_ref_dict[moclo_dest_plate_name] = moclo_dest_plate_ref

    # create refs
    for num, part_name in instructions_dict['parts'].items():
        part_ref = p.ref(part_name, cont_type="96-pcr", discard=True)
        part_ref_dict[part_name] = part_ref

    # create instructions
    for x in range(0, len(instructions_dict['source_wells'])):
        from_well = instructions_dict['source_wells'][x]
        part_name = instructions_dict['parts'][
            from_well]  # get part name in that well
        source_plate = part_ref_dict[part_name]  # get ref object
        volume = instructions_dict['volumes'][x]  # get volume
        volume_str = str(volume) + ':microliter'
        to_well = instructions_dict['dest_wells'][
            x]  # get destination well num

        p.transfer(source_plate.wells_from(from_well, 1),
                   moclo_dest_plate_ref.wells_from(to_well, 1), volume_str)

    return p.as_dict()
Example #5
0
    def test_flow(self):
        """
        Desired Output:
        1. Perform flow cytometry on well0 with the respective FSC and SSC channel parameters
        """

        p = Protocol()
        dataref = "test_ref"
        well0 = p.ref("test_plate", None, "96-pcr",
                      discard=True).well(0)
        FSC = {"voltage_range": {"low": "230:volt", "high": "280:volt"},
               "area": True, "height": True, "weight": False}
        SSC = {"voltage_range": {"low": "230:volt", "high": "280:volt"},
               "area": True, "height": True, "weight": False}
        channel0 = [FSC, SSC]
        neg_controls = [{"well": well0, "volume": "100:microliter",
                         "captured_events": 5, "channel": channel0}]
        samples = [{"well": well0,
                    "volume": "100:microliter", "captured_events": 9}]

        p.flow_analyze(dataref, FSC, SSC, neg_controls,
                       samples)

        pjsonString = json.dumps(p.as_dict(), indent=2)
        pjson = json.loads(pjsonString)
        parser_instance = english.AutoprotocolParser(pjson)
        parser_instance.job_tree()

        parsed_output = parser_instance.parsed_output
        steps = parser_instance.object_list
        forest = parser_instance.forest_list

        self.assertEqual(
            parsed_output, ["Perform flow cytometry on test_plate/0 with the respective FSC and SSC channel parameters"])
        self.assertEqual(forest, [[1]])
Example #6
0
    def test_web_example(self):

        p = Protocol()

        bacterial_sample = p.ref("bacteria", None, "micro-1.5", discard=True)
        test_plate = p.ref("test_plate", None, "96-flat", storage="cold_4")

        p.dispense_full_plate(test_plate, "lb-broth-noAB", "50:microliter")
        w = 0
        amt = 1
        while amt < 20:
            p.transfer(bacterial_sample.well(
                0), test_plate.well(w), "%d:microliter" % amt)
            amt += 2
            w += 1

        pjsonString = json.dumps(p.as_dict(), indent=2)
        pjson = json.loads(pjsonString)
        parser_instance = english.AutoprotocolParser(pjson)
        parser_instance.job_tree()

        parsed_output = parser_instance.parsed_output
        steps = parser_instance.object_list
        forest = parser_instance.forest_list

        self.assertEqual(forest, [[1], [2], [3], [4], [5], [
                         6], [7], [8], [9], [10], [11]])
 def test_distribute_one_well(self):
     p = Protocol()
     c = p.ref("test", None, "96-flat", discard=True)
     p.distribute(
         c.well(0).set_volume("20:microliter"), c.well(1), "5:microliter")
     self.assertEqual(1, len(p.instructions))
     self.assertEqual("distribute",
                      p.as_dict()["instructions"][0]["groups"][0].keys()[0])
     self.assertTrue(5, c.well(1).volume.value)
     self.assertTrue(15, c.well(0).volume.value)
 def test_distribute_one_well(self):
     p = Protocol()
     c = p.ref("test", None, "96-flat", discard=True)
     p.distribute(c.well(0).set_volume("20:microliter"),
                  c.well(1),
                  "5:microliter")
     self.assertEqual(1, len(p.instructions))
     self.assertEqual("distribute",
                      list(p.as_dict()["instructions"][0]["groups"][0].keys())[0])
     self.assertTrue(5, c.well(1).volume.value)
     self.assertTrue(15, c.well(0).volume.value)
 def test_distribute_multiple_wells(self):
     p = Protocol()
     c = p.ref("test", None, "96-flat", discard=True)
     p.distribute(c.well(0).set_volume("20:microliter"),
                  c.wells_from(1,3),
                  "5:microliter")
     self.assertEqual(1, len(p.instructions))
     self.assertEqual("distribute",
                      p.as_dict()["instructions"][0]["groups"][0].keys()[0])
     for w in c.wells_from(1,3):
         self.assertTrue(5, w.volume.value)
     self.assertTrue(5, c.well(0).volume.value)
 def test_distribute_multiple_wells(self):
     p = Protocol()
     c = p.ref("test", None, "96-flat", discard=True)
     p.distribute(
         c.well(0).set_volume("20:microliter"), c.wells_from(1, 3),
         "5:microliter")
     self.assertEqual(1, len(p.instructions))
     self.assertEqual(
         "distribute",
         list(p.as_dict()["instructions"][0]["groups"][0].keys())[0])
     for w in c.wells_from(1, 3):
         self.assertTrue(5, w.volume.value)
     self.assertTrue(5, c.well(0).volume.value)
Example #11
0
def get_synthesized_oligo_tube_protocol(tube_name, sequence):
    """

    Synthesize and prepare an oligo tube
    25nm seems to be more than enough for most downstream work (25pmol seems to be all that is used for transcriptic's pcr)
    
    """
    global inv

    scale = '25nm'

    p = Protocol()

    dna_tube = p.ref(tube_name,
                     cont_type="micro-1.5",
                     storage="cold_20",
                     discard=False)

    dna_tube.well(0).properties = {
        'Molar Concentration': '100uM',
        'original moles': '25nm'
    }

    p.oligosynthesize([{
        "sequence": sequence,
        "destination": dna_tube.well(0),
        "scale": scale,
        "purification": "standard"
    }])

    #spin
    p.spin(dna_tube, '2000:g', '30:second')

    #dilute to 100uM
    #safe min volume of 1.5uL is 20uL so we want a lot more than this so we don't lose too much
    #how do you go from scale and desired concentration to volume --> n = CV --> V = n/C --> V = 25nmol / 100uM = 25nmol / (100E3 nmol / 1L)
    #          = 2.5E-4 L = 250 uL

    #convert 100uM to nM #convert to uL
    te_volume = 25 / (100 * pow(10, 3)) * pow(10, 6)

    #add 250uL
    p.provision(inv["te"], dna_tube.well(0), ul(te_volume))

    #spin
    p.spin(dna_tube, '2000:g', '30:second')

    return json.dumps(p.as_dict(), indent=2)
def get_synthesized_oligo_tube_protocol(tube_name, sequence):
    """

    Synthesize and prepare an oligo tube
    25nm seems to be more than enough for most downstream work (25pmol seems to be all that is used for transcriptic's pcr)
    
    """
    global inv
    
    scale = '25nm'
    
    p = Protocol()

    dna_tube = p.ref(tube_name, 
                       cont_type="micro-1.5",
                       storage="cold_20", discard=False)
    
    dna_tube.well(0).properties = {'Molar Concentration':'100uM',
                                   'original moles':'25nm'}
    
    p.oligosynthesize([{"sequence": sequence,
                        "destination": dna_tube.well(0),
                        "scale": scale,
                        "purification": "standard"}]
                      )
    
    #spin
    p.spin(dna_tube, '2000:g', '30:second')
    
    
    #dilute to 100uM
    #safe min volume of 1.5uL is 20uL so we want a lot more than this so we don't lose too much
    #how do you go from scale and desired concentration to volume --> n = CV --> V = n/C --> V = 25nmol / 100uM = 25nmol / (100E3 nmol / 1L)
    #          = 2.5E-4 L = 250 uL
    
                      #convert 100uM to nM #convert to uL
    te_volume = 25 / (100 * pow(10, 3)) * pow(10, 6) 
    
    #add 250uL
    p.provision(inv["te"], dna_tube.well(0), ul(te_volume))

    #spin
    p.spin(dna_tube, '2000:g', '30:second')
    
    return json.dumps(p.as_dict(), indent=2)
Example #13
0
    def test_mag_collect(self):
        """
        Desired Output:
        1. Magnetically release pcr_0 beads for 30.0 seconds at an amplitude of 0
        2. Distribute from test/1 into wells test/7, test/8, test/9
        3. Distribute from test/2 into wells test/10
        4. Distribute from test/0 into wells test/1
        5. Magnetically collect pcr_0 beads for 5 cycles with a pause duration of 30.0 seconds
        """

        p = Protocol()
        pcrs = [p.ref("pcr_%s" % i, None, "96-pcr", storage="cold_20")
                for i in range(7)]
        pcr = pcrs[0]

        p.mag_release("96-pcr", pcr, "30:second", "1:hertz",
                      center=float(5) / 100, amplitude=0)

        c = p.ref("test", None, "96-flat", discard=True)
        srcs = c.wells_from(1, 2).set_volume("100:microliter")
        dests = c.wells_from(7, 4)
        p.distribute(srcs, dests, "30:microliter", allow_carryover=True)
        p.distribute(c.well("A1").set_volume(
            "20:microliter"), c.well("A2"), "5:microliter")

        p.mag_collect("96-pcr", pcr, 5, "30:second",
                      bottom_position=float(5) / 100)

        pjsonString = json.dumps(p.as_dict(), indent=2)
        pjson = json.loads(pjsonString)
        parser_instance = english.AutoprotocolParser(pjson)
        parser_instance.job_tree()

        parsed_output = parser_instance.parsed_output
        steps = parser_instance.object_list
        forest = parser_instance.forest_list

        self.assertEqual(
            parsed_output, ["Magnetically release pcr_0 beads for 30.0 seconds at an amplitude of 0",
                            "Distribute from test/1 into wells test/7, test/8, test/9",
                            "Distribute from test/2 into wells test/10",
                            "Distribute from test/0 into wells test/1",
                            "Magnetically collect pcr_0 beads for 5 cycles with a pause duration of 30.0 seconds"])
        self.assertEqual(forest, [[1, [5]], [2, [4]], [3]])
Example #14
0
    def test_purify(self):
        """
        Desired Output:
        1. Perform gel purification on the 0.8% agarose gel with band range(s) 0-10
        2. Perform gel purification on the 0.8% agarose gel with band range(s) 0-10
        3. Perform gel purification on the 0.8% agarose gel with band range(s) 0-10
        """

        p = Protocol()
        sample_wells = p.ref("sample_wells", None, "96-pcr",
                             discard=True).wells_from(0, 20)
        extract_wells = [p.ref("extract_%s" % i, None, "micro-1.5",
                               storage="cold_4").well(0) for i in sample_wells]
        extract = [
            {
                "source": sample_wells[i],
                "band_list": [{
                    "band_size_range": {"min_bp": 0, "max_bp": 10},
                    "elution_volume": Unit("5:microliter"),
                    "elution_buffer": "water",
                    "destination": d
                }],
                "lane": None,
                "gel": None
            } for i, d in enumerate(extract_wells)
        ]

        p.gel_purify(extract, "10:microliter",
                     "size_select(8,0.8%)", "ladder1", "gel_purify_test")

        pjsonString = json.dumps(p.as_dict(), indent=2)
        pjson = json.loads(pjsonString)
        parser_instance = english.AutoprotocolParser(pjson)
        parser_instance.job_tree()

        parsed_output = parser_instance.parsed_output
        steps = parser_instance.object_list
        forest = parser_instance.forest_list

        self.assertEqual(
            parsed_output, ["Perform gel purification on the 0.8% agarose gel with band range(s) 0-10",
                            "Perform gel purification on the 0.8% agarose gel with band range(s) 0-10",
                            "Perform gel purification on the 0.8% agarose gel with band range(s) 0-10"])
        self.assertEqual(forest, [[1, [2, [3]]]])
Example #15
0
    def test_dispense_suite(self):
        """
        Desired Output:
        1. Dispense 100 microliters of water to the full plate of sample_plate5
        2. Dispense corresponding amounts of water to 12 column(s) of sample_plate5
        3. Dispense 50 microliters of reagent with resource ID rs17gmh5wafm5p to the full plate of sample_plate5
        """

        p = Protocol()
        sample_plate5 = p.ref("sample_plate5", None,
                              "96-flat", storage="warm_37")

        p.dispense_full_plate(sample_plate5, "water", "100:microliter")
        p.dispense(sample_plate5,
                   "water",
                   [{"column": 0, "volume": "10:microliter"},
                    {"column": 1, "volume": "20:microliter"},
                    {"column": 2, "volume": "30:microliter"},
                    {"column": 3, "volume": "40:microliter"},
                    {"column": 4, "volume": "50:microliter"},
                    {"column": 5, "volume": "60:microliter"},
                    {"column": 6, "volume": "70:microliter"},
                    {"column": 7, "volume": "80:microliter"},
                    {"column": 8, "volume": "90:microliter"},
                    {"column": 9, "volume": "100:microliter"},
                    {"column": 10, "volume": "110:microliter"},
                    {"column": 11, "volume": "120:microliter"}
                    ])
        p.dispense_full_plate(sample_plate5, "rs17gmh5wafm5p", "50:microliter", is_resource_id=True)
        pjsonString = json.dumps(p.as_dict(), indent=2)
        pjson = json.loads(pjsonString)
        parser_instance = english.AutoprotocolParser(pjson)
        parser_instance.job_tree()

        parsed_output = parser_instance.parsed_output
        forest = parser_instance.forest_list

        self.assertEqual(
            parsed_output, ["Dispense 100 microliters of water to the full plate of sample_plate5",
                            "Dispense corresponding amounts of water to 12 column(s) of sample_plate5",
                            "Dispense 50 microliters of resource with resource ID rs17gmh5wafm5p to the full plate of sample_plate5"])
        self.assertEqual(forest, [[1, [2, [3]]]])
Example #16
0
    def test_measure_suite(self):
        """
        Desired Output:
        1. Measure concentration of 2.0 microliters DNA source aliquots
        2. Measure mass of test_plate2
        3. Measure volume of 12 wells from test_plate
        4. Measure volume of 8 wells from test_plate2
        """

        p = Protocol()
        test_plate = p.ref("test_plate", None, "96-flat", storage="cold_4")
        test_plate2 = p.ref("test_plate2", id=None,
                            cont_type="96-flat", storage=None, discard=True)
        for well in test_plate2.all_wells():
            well.set_volume("150:microliter")

        p.measure_concentration(wells=test_plate2.wells_from(
            0, 96), dataref="mc_test", measurement="DNA", volume=Unit(2, "microliter"))
        p.measure_mass(test_plate2, "test_ref")
        p.measure_volume(test_plate.wells_from(0, 12), "test_ref")
        p.measure_volume(test_plate2.wells_from(1, 8), "test_ref2")

        pjsonString = json.dumps(p.as_dict(), indent=2)
        pjson = json.loads(pjsonString)
        parser_instance = english.AutoprotocolParser(pjson)
        parser_instance.job_tree()

        parsed_output = parser_instance.parsed_output
        steps = parser_instance.object_list
        forest = parser_instance.forest_list

        self.assertEqual(
            parsed_output, ["Measure concentration of 2.0 microliters DNA source aliquots of test_plate2",
                            "Measure mass of test_plate2",
                            "Measure volume of 12 wells from test_plate",
                            "Measure volume of 8 wells from test_plate2"])
        self.assertEqual(forest, [[1, [2, [4]]], [3]])
Example #17
0
    def test_illumina(self):
        """
        Desired Output:
        1. Illumina sequence wells test_plate6/0, test_plate6/1 with library size 34
        """

        p = Protocol()
        sample_wells6 = p.ref(
            "test_plate6", None, "96-pcr", discard=True).wells_from(0, 8)
        p.illuminaseq("PE", [{"object": sample_wells6[0], "library_concentration": 1.0},
                             {"object": sample_wells6[1], "library_concentration": 2}],
                      "nextseq", "mid", 'none', 34, "dataref")
        pjsonString = json.dumps(p.as_dict(), indent=2)
        pjson = json.loads(pjsonString)
        parser_instance = english.AutoprotocolParser(pjson)
        parser_instance.job_tree()

        parsed_output = parser_instance.parsed_output
        steps = parser_instance.object_list
        forest = parser_instance.forest_list

        self.assertEqual(
            parsed_output, ["Illumina sequence wells test_plate6/0, test_plate6/1 with library size 34"])
        self.assertEqual(forest, [[1]])
    'gblock_dna': 'ct18vs7cmjat2c',  # my inventory
    'te': 'rs17pwyc754v9t',  # catalog; TE
}

p = Protocol()

#existing inventory
dna_sample = p.ref("gblock_dna",
                   id=inv['gblock_dna'],
                   cont_type="micro-1.5",
                   storage='cold_20')

#tubes are thawed before being placed into workcell

#Centrifuge the tube for 3-5 sec at a minimum of 3000 x g to pellet the material to the bottom of the tube.
p.spin(dna_sample, '3000:g', '5:second')

#Add 500uL TE (to reach 1 ng/uL)
p.provision(inv["te"], dna_sample.well(0), ul(500))

#Briefly vortex (here we have to use mix) and centrifuge

p.mix(dna_sample.well(0),
      '480:microliter',
      speed='480:microliter/second',
      repetitions=10)

p.spin(dna_sample, '3000:g', '3:second')

print(json.dumps(p.as_dict(), indent=2))
Example #19
0
class TestProvision(object):
    @pytest.fixture(autouse=True)
    def setup(self):
        # pylint: disable=attribute-defined-outside-init
        self.p = Protocol()
        # pylint: disable=attribute-defined-outside-init
        self.w1 = (self.p.ref("w1", None, cont_type="96-pcr",
                              discard=True).well(0).set_volume("2:microliter"))

    def test_provision_well_capacity(self):
        self.p.provision("rs17gmh5wafm5p", self.w1, "50:microliter")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "expected_provision.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_attempt_to_provision_more_than_well_capacity(self):
        with pytest.raises(ValueError):
            self.p.provision("rs17gmh5wafm5p", self.w1, "500:microliter")

    def test_with_invalid_resource_id(self):
        with pytest.raises(TypeError):
            self.p.provision(100, self.w1, "50:microliter")

    def test_with_destinations_count_not_same_as_volumes(self):
        volumes = ["50:microliter", "20:microliter"]
        with pytest.raises(RuntimeError):
            self.p.provision("rs17gmh5wafm5p", self.w1, volumes)

    def test_with_volume_above_max(self):
        with pytest.raises(ValueError):
            self.p.provision("rs17gmh5wafm5p", self.w1, "200:microliter")

    def test_with_multiple_wells(self):
        w2 = (self.p.ref("w2", None, cont_type="96-pcr",
                         discard=True).well(0).set_volume("2:microliter"))
        w3 = (self.p.ref("w3", None, cont_type="96-pcr",
                         discard=True).well(0).set_volume("2:microliter"))
        wells = [self.w1, w2, w3]
        self.p.provision("rs17gmh5wafm5p", wells, "50:microliter")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_multiple_wells.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_with_consecutive_repeated_wells(self):
        wells = [self.w1, self.w1]
        self.p.provision("rs17gmh5wafm5p", wells, "50:microliter")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_with_consecutive_repeated_wells.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_with_repeated_wells_but_discontinuous(self):
        w2 = (self.p.ref("w2", None, cont_type="96-pcr",
                         discard=True).well(0).set_volume("2:microliter"))
        wells = [self.w1, w2, self.w1]
        self.p.provision("rs17gmh5wafm5p", wells, "50:microliter")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_with_repeated_wells_but_discontinuous.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_with_multiple_wells_with_different_cont_types(self):
        self.p.refs.clear()
        w1 = (self.p.ref("w1", None, cont_type="1-flat",
                         discard=True).well(0).set_volume("2:microliter"))
        w2 = (self.p.ref("w2", None, cont_type="6-flat-tc",
                         discard=True).well(0).set_volume("2:microliter"))
        wells = [w1, w2]
        self.p.provision("rs17gmh5wafm5p", wells, "1500:microliter")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_multiple_wells_with_diff_cont_types.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_provision_with_covered_container(self):
        self.p.refs.clear()
        w1 = (self.p.ref("w1",
                         None,
                         cont_type="96-pcr",
                         discard=True,
                         cover="standard").well(0).set_volume("2:microliter"))
        self.p.provision("rs17gmh5wafm5p", w1, "50:microliter")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_with_cover.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_provision_with_sealed_container(self):
        self.p.refs.clear()
        w1 = (self.p.ref("w1",
                         None,
                         cont_type="96-pcr",
                         discard=True,
                         cover="foil").well(0).set_volume("2:microliter"))
        self.p.provision("rs17gmh5wafm5p", w1, "50:microliter")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_with_seal.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_for_multiple_dispenses_of_resource_in_containers_larger_than_900ml(
            self):
        self.p.refs.clear()
        w1 = (self.p.ref("w1", None, cont_type="micro-2.0",
                         discard=True).well(0).set_volume("2:microliter"))
        self.p.provision("rs17gmh5wafm5p", w1, volumes="1500:microliter")

        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "split_provisions_by_volume.json")
        assert expected_instruction_as_json == actual_instruction_as_json

    def test_provision_well_with_mass(self):
        self.p.provision("rs17gmh5wafm5p", self.w1, amounts="50:ug")
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_for_mass.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_provision_multiple_wells_with_diff_masses(self):
        w2 = (self.p.ref("w2", None, cont_type="96-pcr",
                         discard=True).well(0).set_volume("2:microliter"))
        self.p.provision("rs17gmh5wafm5p", [self.w1, w2], ["50:ug", "25:mg"])
        actual_instruction_as_json = json.dumps(
            self.p.as_dict()["instructions"], indent=2, sort_keys=True)
        expected_instruction_as_json = TestUtils.read_json_file(
            "provision_with_more_than_one_mass.json")

        assert expected_instruction_as_json == actual_instruction_as_json

    def test_provision_wells_with_amounts_of_varying_measurement_modes(self):
        w2 = (self.p.ref("w2", None, cont_type="96-pcr",
                         discard=True).well(0).set_volume("2:microliter"))
        with pytest.raises(ValueError):
            self.p.provision("rs17gmh5wafm5p", [self.w1, w2],
                             ["50:lb", "50:gallon"])

    def test_provision_passing_both_volumes_and_amounts(self):
        with pytest.raises(ValueError):
            self.p.provision("rs17gmh5wafm5p", self.w1, "25:ul", "50:mg")

    def test_provision_well_with_neither_mass_nor_volume(self):
        with pytest.raises(ValueError):
            self.p.provision("rs17gmh5wafm5p", self.w1)
import json
from autoprotocol.protocol import Protocol
from utils import ul

inv = {
    'gblock_dna':'ct18vs7cmjat2c',     # my inventory
    'te': 'rs17pwyc754v9t',           # catalog; TE
}

p = Protocol()

#existing inventory
dna_sample = p.ref("gblock_dna", id=inv['gblock_dna'], cont_type="micro-1.5", storage='cold_20')

#tubes are thawed before being placed into workcell

#Centrifuge the tube for 3-5 sec at a minimum of 3000 x g to pellet the material to the bottom of the tube.
p.spin(dna_sample, '3000:g', '5:second')

#Add 500uL TE (to reach 1 ng/uL)
p.provision(inv["te"], dna_sample.well(0), ul(500))

#Briefly vortex (here we have to use mix) and centrifuge

p.mix(dna_sample.well(0),'480:microliter',speed='480:microliter/second',repetitions=10)

p.spin(dna_sample, '3000:g', '3:second')

print(json.dumps(p.as_dict(), indent=2))
Example #21
0
protocol.incubate(growth_plate, "warm_37", "5:hour", shaking=True)

# Step 12 - Store the measurement plate in the fridge
# This step is being run in series instead of parallel.  Will uncomment it when it runs in parallel.
# The measurement plate remains covered and in room temperature while the growth plate is in the incubator.
#protocol.incubate(measurement_plate, "cold_4", "4:hour")

# Step 13 - Uncover the growth plate
protocol.uncover(growth_plate)

# Step 14 - Uncover the measurement plate
protocol.uncover(measurement_plate)

# Step 15 - Add engineered cells to the measurement plate again
protocol.distribute(growth_plate.well("A1"), measurement_plate.wells_from("A10", 3, columnwise=False), "100:microliter")

# Step 16 - Add negative control cells to the measurement plate again
protocol.distribute(growth_plate.well("H1"), measurement_plate.wells_from("C10", 3, columnwise=False), "100:microliter")

# Step 17 - Add LB medium to the measurement plate again
protocol.distribute(lb_medium_c.well("A1"), measurement_plate.wells_from("E10", 3, columnwise=False), "100:microliter")

# Step 18 - Cover the growth plate
protocol.cover(growth_plate, lid="standard")

# Step 19 - Measure indirectly cell concentrations
protocol.absorbance(measurement_plate, ["A10", "A11", "A12", "C10", "C11", "C12", "E10", "E11", "E12",], "600:nanometer","After Incubation")


print json.dumps(protocol.as_dict(), indent=2)
Example #22
0
class AutoprotocolSpecialization(BehaviorSpecialization):
    def __init__(self, out_path, api: StrateosAPI = None, resolutions: Dict[sbol3.Identified, str] = None) -> None:
        super().__init__()
        self.out_path = out_path
        self.resolutions = resolutions
        self.api = api
        self.var_to_entity = {}
        self.container_api_addl_conditions = "(cont:availableAt value <https://sift.net/container-ontology/strateos-catalog#Strateos>)"


    def _init_behavior_func_map(self) -> dict:
        return {
            "https://bioprotocols.org/paml/primitives/sample_arrays/EmptyContainer" : self.define_container,
            "https://bioprotocols.org/paml/primitives/liquid_handling/Provision" : self.provision_container,
            "https://bioprotocols.org/paml/primitives/sample_arrays/PlateCoordinates" : self.plate_coordinates,
            "https://bioprotocols.org/paml/primitives/spectrophotometry/MeasureAbsorbance" : self.measure_absorbance,
        }

    def on_begin(self):
        protocol_name = self.execution.protocol.lookup().name
        self.protocol = Protocol()

    def on_end(self):
        with open(self.out_path, "w") as f:
            json.dump(self.protocol.as_dict(), f, indent=2)

    def define_container(self, record: paml.ActivityNodeExecution):
        results = {}
        call = record.call.lookup()
        parameter_value_map = call.parameter_value_map()

        spec = parameter_value_map["specification"]['value']
        samples_var = parameter_value_map["samples"]['value']

        if "container_id" in self.resolutions:
            container_id = self.resolutions["container_id"]
        else:
            container_type = self.get_container_type_from_spec(spec)
            container_name = f"{self.execution.protocol.lookup().name} Container {samples_var}"
            container_id = self.create_new_container(container_name, container_type)

        #container_id = tx.inventory("flat test")['results'][1]['id']
        #container_id = "ct1g9q3bndujat5"
        tx = self.api.get_strateos_connection() # Make sure that connection is alive for making the container object
        tx_container = transcriptic.Container(container_id)
        container = self.protocol.ref(samples_var.name, id=tx_container.id, cont_type=tx_container.container_type, discard=True)
        self.var_to_entity[samples_var] = container

        l.debug(f"define_container:")
        l.debug(f" specification: {spec}")
        l.debug(f" samples: {samples_var}")


        #spec_term = UnresolvedTerm(None, samples_var, spec)
        #self.unresolved_terms.append(spec_term)

        return results

    def get_container_type_from_spec(self, spec):
        short_names = [v.shortname
                       for v in [getattr(ctype, x) for x in dir(ctype)]
                       if isinstance(v, ctype.ContainerType)]
        try:
            possible_container_types = self.resolve_container_spec(spec,
                                                                   addl_conditions=self.container_api_addl_conditions)
            possible_short_names = [strateos_id(x) for x in possible_container_types]
            matching_short_names = [x for x in short_names if x in possible_short_names]
            name_map = {
                '96-ubottom-clear-tc': "96-flat",
                '96-flat-clear-clear-tc': "96-flat"
            }
            mapped_names = [name_map[x] for x in matching_short_names]
            return mapped_names[0]
            # return matching_short_names[0] # FIXME need some error handling here

        except Exception as e:
            l.warning(e)
            container_type = "96-flat"
            l.warning(f"Defaulting container to {container_type}")
            return container_type



    def create_new_container(self, name, container_type):
        container_spec = {
                "name": name,
                "cont_type": container_type, # resolve with spec here
                "volume": "100:microliter", # FIXME where does this come from?
                "properties": [
                    {
                        "key": "concentration",
                        "value": "10:millimolar"
                    }
                ]
            }
        container_ids = self.api.make_containers([container_spec])
        container_id = container_ids[name]
        #tx = self.api.get_transcriptic_connection()
        #container_id = tx.inventory("flat test")['results'][1]['id']
        #container_id = "ct1g9q3bndujat5"
        return container_id

    # def provision_container(self, wells: WellGroup, amounts = None, volumes = None, informatics = None) -> Provision:
    def provision_container(self, record: paml.ActivityNodeExecution) -> Provision:
        results = {}
        call = record.call.lookup()
        parameter_value_map = call.parameter_value_map()

        destination = parameter_value_map["destination"]["value"]
        dest_wells = self.var_to_entity[destination]
        value = parameter_value_map["amount"]["value"].value
        units = parameter_value_map["amount"]["value"].unit
        units = tyto.OM.get_term_by_uri(units)
        resource = parameter_value_map["resource"]["value"]
        resource = self.resolutions[resource]
        l.debug(f"provision_container:")
        l.debug(f" destination: {destination}")
        l.debug(f" amount: {value} {units}")
        l.debug(f" resource: {resource}")
        [step] = self.protocol.provision(
            resource,
            dest_wells,
            amounts=Unit(value, units)
        )
        #resource_term = UnresolvedTerm(step, "resource_id", resource)
        #self.unresolved_terms.append(resource_term)
        return results

    def plate_coordinates(self, record: paml.ActivityNodeExecution) -> WellGroup:
        results = {}
        call = record.call.lookup()
        parameter_value_map = call.parameter_value_map()

        source = parameter_value_map["source"]["value"]
        container = self.var_to_entity[source]
        coords = parameter_value_map["coordinates"]["value"]
        wells = pc.coordinate_rect_to_well_group(container, coords)

        self.var_to_entity[parameter_value_map['samples']["value"]] = wells
        l.debug(f"plate_coordinates:")
        l.debug(f"  source: {source}")
        l.debug(f"  coordinates: {coords}")
        #results[outputs['samples']] = ('samples', pc.coordinate_rect_to_well_group(source, coords))
        return results

    def measure_absorbance(self, record: paml.ActivityNodeExecution):
        results = {}
        call = record.call.lookup()
        parameter_value_map = call.parameter_value_map()

        wl = parameter_value_map["wavelength"]["value"]
        wl_units = tyto.OM.get_term_by_uri(wl.unit)
        samples = parameter_value_map["samples"]["value"]
        wells = self.var_to_entity[samples]
        measurements = parameter_value_map["measurements"]["value"]

        # HACK extract contrainer from well group since we do not have it as input
        container = wells[0].container

        l.debug(f"measure_absorbance:")
        l.debug(f"  container: {container}")
        l.debug(f"  samples: {samples}")
        l.debug(f"  wavelength: {wl.value} {wl_units}")

        self.protocol.spectrophotometry(
            dataref=measurements,
            obj=container,
            groups=Spectrophotometry.builders.groups([
                Spectrophotometry.builders.group(
                    "absorbance",
                    Spectrophotometry.builders.absorbance_mode_params(
                        wells=wells,
                        wavelength=Unit(wl.value, wl_units),
                        num_flashes=None,
                        settle_time=None,
                        read_position=None,
                        position_z=None
                    )
                )
            ])
        )
        return results