예제 #1
0
def get_ccp4_map(xmap_path):
    m = gemmi.read_ccp4_map(str(xmap_path))
    m.grid.spacegroup = gemmi.find_spacegroup_by_name("P 1")

    m.setup()

    return m
예제 #2
0
def main():
    config = Config.from_config()

    m = gemmi.read_ccp4_map(str(config.xmap_in))
    print(dir(m))
    # m.spacegroup = gemmi.find_spacegroup_by_name('P1')
    print(m.grid.spacegroup)
    m.grid.spacegroup = gemmi.find_spacegroup_by_name('P1')
    print(m.grid.spacegroup)

    m.setup()
    print(m.grid.spacegroup)

    m.grid.spacegroup = gemmi.find_spacegroup_by_name('P1')
    print(m.grid.spacegroup)
    sf = gemmi.transform_map_to_f_phi(m.grid, half_l=True)
    print(sf.spacegroup)
    # data = sf
    print(dir(sf))
    data = sf.prepare_asu_data(dmin=config.resolution, with_000=True)

    mtz = gemmi.Mtz(with_base=True)
    # mtz = gemmi.Mtz()
    print(dir(mtz))
    mtz.spacegroup = sf.spacegroup
    # mtz.spacegroup = gemmi.find_spacegroup_by_name('P1')
    # mtz.set_cell_for_all(sf.unit_cell)
    mtz.cell = sf.unit_cell
    mtz.add_dataset('unknown')
    mtz.add_column('FWT', 'F')
    mtz.add_column('PHWT', 'P')
    mtz.set_data(data)
    mtz.write_to_file(str(config.mtz_out))
예제 #3
0
    def test_reading(self):
        path = os.path.join(os.path.dirname(__file__), '5i55_tiny.ccp4')
        m = gemmi.read_ccp4_map(path)
        self.assertEqual(m.grid.nu, 8)
        self.assertEqual(m.grid.nv, 6)
        self.assertEqual(m.grid.nw, 10)
        self.assertEqual(m.header_i32(28), 0)
        m.set_header_i32(28, 20140)  # set NVERSION
        self.assertEqual(m.header_i32(28), 20140)
        dmax = m.header_float(21)
        self.assertEqual(dmax, max(p.value for p in m.grid))
        self.assertNotEqual(m.grid.axis_order, gemmi.AxisOrder.XYZ)
        m.setup()
        self.assertEqual(m.grid.axis_order, gemmi.AxisOrder.XYZ)
        self.assertEqual(m.grid.nu, 60)
        self.assertEqual(m.grid.nv, 24)
        self.assertEqual(m.grid.nw, 60)
        self.assertEqual(m.grid.point_count, 60 * 24 * 60)
        self.assertEqual(m.header_float(14), 90.0)  # 14 - alpha angle
        self.assertEqual(m.grid.unit_cell.alpha, 90.0)
        self.assertEqual(m.grid.spacegroup.ccp4, 4)  # P21

        pos = gemmi.Position(19.4, 3., 21.)
        frac = m.grid.unit_cell.fractionalize(pos)
        pos_value = 2.1543798446655273
        self.assertAlmostEqual(m.grid.interpolate_value(pos), pos_value)
        self.assertAlmostEqual(m.grid.interpolate_value(frac), pos_value)

        # this spacegroup has symop -x, y+1/2, -z
        m.grid.set_value(60 - 3, 24 // 2 + 4, 60 - 5,
                         100)  # image of (3, 4, 5)
        self.assertEqual(m.grid.get_value(60 - 3, 24 // 2 + 4, 60 - 5), 100)
        self.assertTrue(math.isnan(m.grid.get_value(3, 4, 5)))
        m.grid.symmetrize_max()
        self.assertEqual(m.grid.get_value(3, 4, 5), 100)
        m.grid.set_value(3, 4, 5, float('nan'))
        self.assertTrue(math.isnan(m.grid.get_value(3, 4, 5)))
        m.grid.symmetrize_min()
        self.assertEqual(m.grid.get_value(3, 4, 5), 100)
        m.grid.set_value(60 - 3, 24 // 2 + 4, 60 - 5, float('nan'))
        m.grid.symmetrize_max()
        self.assertEqual(m.grid.get_value(60 - 3, 24 // 2 + 4, 60 - 5), 100)
        if numpy:
            arr = numpy.array(m.grid, copy=False)
            self.assertEqual(arr.shape, (60, 24, 60))
            self.assertEqual(arr[3][4][5], 100)
            grid2 = gemmi.FloatGrid(arr)
            self.assertTrue(
                numpy.allclose(m.grid, grid2, atol=0.0, rtol=0,
                               equal_nan=True))
예제 #4
0
파일: test_grid.py 프로젝트: dimar/gemmi
 def test_reading(self):
     path = os.path.join(os.path.dirname(__file__), '5i55_tiny.ccp4')
     m = gemmi.read_ccp4_map(path)
     self.assertEqual(m.grid.nu, 8)
     self.assertEqual(m.grid.nv, 6)
     self.assertEqual(m.grid.nw, 10)
     self.assertEqual(m.header_i32(28), 0)
     m.set_header_i32(28, 20140)  # set NVERSION
     self.assertEqual(m.header_i32(28), 20140)
     dmax = m.header_float(21)
     self.assertEqual(dmax, max(m.grid))
     m.setup()
     self.assertEqual(m.grid.nu, 60)
     self.assertEqual(m.grid.nv, 24)
     self.assertEqual(m.grid.nw, 60)
     self.assertEqual(m.header_float(14), 90.0)  # 14 - alpha angle
     self.assertEqual(m.grid.unit_cell.alpha, 90.0)
예제 #5
0
파일: test_grid.py 프로젝트: mcs07/gemmi
 def test_reading(self):
     path = os.path.join(os.path.dirname(__file__), '5i55_tiny.ccp4')
     m = gemmi.read_ccp4_map(path)
     self.assertEqual(m.grid.nu, 8)
     self.assertEqual(m.grid.nv, 6)
     self.assertEqual(m.grid.nw, 10)
     self.assertEqual(m.header_i32(28), 0)
     m.set_header_i32(28, 20140)  # set NVERSION
     self.assertEqual(m.header_i32(28), 20140)
     dmax = m.header_float(21)
     self.assertEqual(dmax, max(m.grid))
     self.assertFalse(m.grid.full_canonical)
     m.setup()
     self.assertTrue(m.grid.full_canonical)
     self.assertEqual(m.grid.nu, 60)
     self.assertEqual(m.grid.nv, 24)
     self.assertEqual(m.grid.nw, 60)
     self.assertEqual(m.grid.point_count, 60 * 24 * 60)
     self.assertEqual(m.header_float(14), 90.0)  # 14 - alpha angle
     self.assertEqual(m.grid.unit_cell.alpha, 90.0)
     self.assertEqual(m.grid.spacegroup.ccp4, 4)  # P21
     # this spacegroup has symop -x, y+1/2, -z
     m.grid.set_value(60 - 3, 24 // 2 + 4, 60 - 5,
                      100)  # image of (3, 4, 5)
     self.assertEqual(m.grid.get_value(60 - 3, 24 // 2 + 4, 60 - 5), 100)
     self.assertTrue(math.isnan(m.grid.get_value(3, 4, 5)))
     m.grid.symmetrize_max()
     self.assertEqual(m.grid.get_value(3, 4, 5), 100)
     m.grid.set_value(3, 4, 5, float('nan'))
     self.assertTrue(math.isnan(m.grid.get_value(3, 4, 5)))
     m.grid.symmetrize_min()
     self.assertEqual(m.grid.get_value(3, 4, 5), 100)
     m.grid.set_value(60 - 3, 24 // 2 + 4, 60 - 5, float('nan'))
     m.grid.symmetrize_max()
     self.assertEqual(m.grid.get_value(60 - 3, 24 // 2 + 4, 60 - 5), 100)
     if numpy:
         arr = numpy.array(m.grid, copy=False)
         self.assertEqual(arr.shape, (60, 24, 60))
         self.assertEqual(arr[3][4][5], 100)
예제 #6
0
def get_event_map(event_map_file: Path) -> gemmi.FloatGrid:
    m = gemmi.read_ccp4_map(str(event_map_file))
    print(m.grid.spacegroup.xhm())

    # m.grid.spacegroup = gemmi.find_spacegroup_by_name("P 21 21 21")
    m.grid.spacegroup = gemmi.find_spacegroup_by_name("P 1")
    print(m.grid.spacegroup.xhm())

    m.setup()

    grid_array = np.array(m.grid, copy=True)

    print(m.grid.spacegroup.xhm())
    print(m.grid)
    print(grid_array.shape)

    new_grid = gemmi.FloatGrid(*grid_array.shape)
    new_grid.spacegroup = m.grid.spacegroup  # gemmi.find_spacegroup_by_name("P 1")
    new_grid.set_unit_cell(m.grid.unit_cell)

    new_grid_array = np.array(new_grid, copy=False)
    new_grid_array[:, :, :] = grid_array[:, :, :]

    return new_grid
예제 #7
0
#!/usr/bin/env python

import numpy
from matplotlib import pyplot
import gemmi

# toxd_aupatt.map is generated by $CCP4/examples/unix/runnable/patterson
ccp4 = gemmi.read_ccp4_map('/tmp/wojdyr/toxd_aupatt.map')
ccp4.setup()
arr = numpy.array(ccp4.grid, copy=False)
x = numpy.linspace(0, ccp4.grid.unit_cell.a, num=arr.shape[0], endpoint=False)
y = numpy.linspace(0, ccp4.grid.unit_cell.b, num=arr.shape[1], endpoint=False)
X, Y = numpy.meshgrid(x, y, indexing='ij')
pyplot.contour(X, Y, arr[:, :, 40])
pyplot.gca().set_aspect('equal', adjustable='box')
pyplot.show()
예제 #8
0
    def __getitem__(self, item):
        event_record = self.table.iloc[item]

        event = Event.from_record(event_record)
        # print(event.viewed)
        # print(type(event.viewed))

        if bool(event.viewed) is False:
            sample_dict = {
                "id": {
                    "pandda_name": event.pandda_name,
                    "dtag": event.dtag,
                    "event_idx": event.event_idx,
                },
                "data":
                np.zeros(
                    (
                        2,
                        self.sample_shape[0],
                        self.sample_shape[1],
                        self.sample_shape[2],
                    ),
                    dtype=np.float32,
                ),
                "label":
                np.array([1, 0], dtype=np.float32),
                "event_map_path":
                str(event.event_map_path),
                "model_path":
                str(event.initial_model_path),
                "coords":
                str([event.x, event.y, event.z])
            }

            return sample_dict
        try:

            event_centroid = np.array([
                event.x,
                event.y,
                event.z,
            ])

            data_map = get_map_from_mtz_path(event.data_path)
            event_map: gemmi.Grid = gemmi.read_ccp4_map(event.event_map_path)

            rotation = sample_rotation()
            translation = sample_translation()

            data_map_layer = sample_map(
                data_map,
                event_centroid,
                rotation,
                translation,
                self.sample_shape,
            )
            event_map_layer = sample_event_map(
                event_map,
                event_centroid,
                rotation,
                translation,
                self.sample_shape,
            )
            data = np.stack(
                [data_map_layer, event_map_layer],
                axis=0,
            )

            label = get_label(event)

            sample_dict = {
                "id": {
                    "pandda_name": event.pandda_name,
                    "dtag": event.dtag,
                    "event_idx": event.event_idx,
                },
                "data": data,
                "label": label,
                "event_map_path": str(event.event_map_path),
                "model_path": str(event.initial_model_path),
                "coords": str([event.x, event.y, event.z])
            }

            return sample_dict
        except Exception as e:
            # Null result
            # print(e)
            sample_dict = {
                "id": {
                    "pandda_name": event.pandda_name,
                    "dtag": event.dtag,
                    "event_idx": event.event_idx,
                    # "initial_model_dir": ,
                },
                "data":
                np.zeros(
                    (
                        2,
                        self.sample_shape[0],
                        self.sample_shape[1],
                        self.sample_shape[2],
                    ),
                    dtype=np.float32,
                ),
                "label":
                np.array([1, 0], dtype=np.float32),
                "event_map_path":
                str(event.event_map_path),
                "model_path":
                str(event.initial_model_path),
                "coords":
                str([event.x, event.y, event.z])
            }

            return sample_dict
예제 #9
0
def prepare_training_data(
    mtz_directory: str,
    mtz_file: str,
    xyz_limits: List[int],
    output_directory: str,
    db_file: str,
    delete_temp: bool = True,
):
    """Convert both the original and inverse hands of a structure into a regular map file based on information
    about the cell info and space group and the xyz dimensions. Return True if no exceptions"""

    logging.info("Preparing training data")

    # Check all directories exist
    try:
        mtz_dir = Path(mtz_directory)
        assert mtz_dir.exists()
    except Exception:
        logging.error(f"Could not find mtz directory at {mtz_directory}")
        raise

    try:
        output_dir = Path(output_directory)
        assert output_dir.exists()
    except Exception:
        logging.error(f"Could not find output directory at {output_directory}")
        raise

    # Check xyz limits are of correct format
    try:
        assert type(xyz_limits) == list or type(xyz_limits) == tuple
        assert len(xyz_limits) == 3
        assert all(type(values) == int for values in xyz_limits)
    except AssertionError:
        logging.error(
            "xyz_limits muste be provided as a list or tupls of three integer values"
        )
        raise

    # Innitialise connection to database
    try:
        conn = sqlite3.connect(db_file)
        cur = conn.cursor()
    except Exception:
        logging.error(f"Could not connect to database at {db_file}")
        raise

    if not os.path.exists(os.path.join(output_dir, "conv_map_list.csv")):
        with open(os.path.join(output_dir, "conv_map_list.csv"),
                  "w") as out_csv:
            writer = csv.writer(out_csv)
            writer.writerow(["filename", "ai_lable"])

    # Get lists of child directories
    mtz_structs = [struct.stem for struct in mtz_dir.iterdir()]
    mtz_structs = sorted(mtz_structs)
    logging.debug(f"Following structures found to transform: {mtz_structs}")

    #this below works but runs serial
    for struct in mtz_structs:
        struct_dir = Path(os.path.join(mtz_dir, struct))
        homo_lst = [h**o.stem for h**o in struct_dir.iterdir()]
        for h**o in homo_lst:
            homo_dir = os.path.join(struct_dir, h**o)
            logging.info(
                f"Converting results for structure {struct}, {mtz_structs.index(struct)+1}/{len(mtz_structs)}"
            )
            if mtz_file in os.listdir(homo_dir):
                logging.info(
                    f"Collecting info for {h**o}, {homo_lst.index(h**o)+1}/{len(homo_lst)}"
                )
                homo_mtz = Path(os.path.join(homo_dir, mtz_file))

                try:
                    homo_mtz = Path(os.path.join(homo_dir, mtz_file))
                    assert homo_mtz.exists()
                except Exception:
                    logging.error(
                        f"Could not find homologue phased MTZ file {homo_mtz}")
                    raise

                try:
                    data = gemmi.read_mtz_file(str(homo_mtz))
                    cell = data.cell
                    sg = data.spacegroup
                except Exception:
                    logging.error(f"Could not read {homo_mtz}")
                    # raise
                    pass

                temp_out_file = os.path.join(
                    output_dir, "temp_" + struct + "_" + h**o + ".ccp4")
                try:
                    data_to_map = gemmi.Ccp4Map()
                    print("Grid of MTZ file", data_to_map.grid)

                    data_to_map.grid = data.transform_f_phi_to_map(
                        'FWT', 'PHWT', sample_rate=4)
                    #            shape = [round(a/1.2/2)*2 for a in data.cell.parameters[:3]]
                    #            data_to_map.grid = data.transform_f_phi_to_map('FWT', 'PHWT', exact_size=shape)
                    print("Grid after converting MTZ to MAP", data_to_map.grid)

                    data_to_map.update_ccp4_header(2, True)
                    data_to_map.write_ccp4_map(temp_out_file)
                except Exception:
                    logging.error(f"Could not create map from {homo_mtz}")
                    raise

                try:
                    # opening temporary map file which shouldn't be neccessary to be written out
                    map_to_map = gemmi.read_ccp4_map(temp_out_file)
                    map_to_map.setup()

                    print("Grid after loading temp file", map_to_map.grid)

                    #this bit here expands the unit cell to be 200A^3;
                    #Can I expand the unit cell to standard volume and then extract a
                    #grid cube (200, 200, 200)
                    #            xyz_limits = [200, 200, 200]
                    #            xyz_limits = [100, 100, 100]
                    xyz_limits = [50, 50, 50]
                    upper_limit = gemmi.Position(*xyz_limits)
                    box = gemmi.FractionalBox()
                    box.minimum = gemmi.Fractional(0, 0, 0)
                    box.maximum = map_to_map.grid.unit_cell.fractionalize(
                        upper_limit)
                    #            box.maximum = map_to_map.grid.point_to_fractional(map_to_map.grid.get_point(200, 200, 200))
                    #            box.maximum = map_to_map.grid.point_to_fractional(map_to_map.grid.get_point(100, 100, 100))
                    box.maximum = map_to_map.grid.point_to_fractional(
                        map_to_map.grid.get_point(50, 50, 50))
                    box.add_margin(1e-5)
                    map_to_map.set_extent(box)

                    print("Grid after setting XYZ limits for MAP",
                          map_to_map.grid)

                    #create a grid with extend x=0-->200, y=0-->200, z=0-->200
                    #currently problems as the 200 limit not always reached for all axes;
                    #adding a margin maybe that will help
                # new_map.setup()
                # box1 = gemmi.FractionalBox()
                # box1.minimum = gemmi.Fractional(0, 0, 0)
                # box1.maximum = new_map.grid.point_to_fractional(new_map.grid.get_point(200, 200, 200))
                # map_to_map.setup()
                # new_map.set_extent(box1)

                # print("Grid after setting grid dimensions", new_map.grid)

                except Exception:
                    logging.error(f"Could not expand map {map_to_map}")
                    raise
#
#          try:
#            map_to_map = gemmi.read_ccp4_map(temp_out_file)
#            map_to_map.setup()
#            print(map_to_map.grid)
#            grid = map_to_map.grid
#            print(grid)
#            new_grid = grid.set_value(200, 200, 200, 4.0)
#            print(new_grid.get_value)
#            xyz_limits = [200, 200, 200]
#            upper_limit = gemmi.Position(*xyz_limits)
#            box = gemmi.FractionalBox()
#            box.minimum = gemmi.Fractional(0, 0, 0)
#            box.maximum = map_to_map.grid.unit_cell.fractionalize(upper_limit)
#            map_to_map.set_extent(box)
#          except Exception:
#            logging.error(f"Could not expand map {map_to_map}")
#            raise

                mtz_state = str(mtz_file).strip(".mtz")
                final_name = struct + "_" + h**o + "_" + mtz_state + ".ccp4"
                final = os.path.join(output_dir, final_name)
                #          final = os.path.join(output_dir, struct+"_"+h**o+"_"+mtz_state+".ccp4")
                try:
                    map_to_map.write_ccp4_map(final)
                    #            data_to_map.write_ccp4_map(final)
                    cur.execute('''
                         SELECT refinement_success_lable, homologue_name_id
                         FROM homologue_stats
                         INNER JOIN homologue_name
                         ON homologue_name.id = homologue_stats.homologue_name_id
                         INNER JOIN pdb_id
                         ON pdb_id.id = homologue_name.pdb_id_id
                         WHERE homologue_name = "%s"
                         AND pdb_id.pdb_id = "%s"
                         ''' % (h**o, struct))
                    lable = (cur.fetchone())[0]
                    print(lable)
                    #set for MR works and building works
                    if lable == "1a":
                        new_lable = 1
                    else:
                        new_lable = 0

#focus on the MR solution with building first and then work on the other options
#            #set for MR works and building doesn't work
#            if lable == "1b":
#              new_lable = 1
#            else:
#              new_lable = 0
#            #set for superpositioning works and building works
#            if lable == "2a":
#              new_lable = 1
#            else:
#              new_lable = 0
#            #set for superpositioning works and building doesn't work
#            if lable == "2b":
#              new_lable = 1
#            else:
#              new_lable = 0

                    print(new_lable)
                    with open(os.path.join(output_dir, "conv_map_list.csv"),
                              "a",
                              newline="") as out_csv:
                        writer = csv.writer(out_csv)
                        writer.writerow([final, new_lable])


#              writer.writerow([final_name, new_lable])
                except Exception:
                    logging.error(f"Could not write final map {final}")

    return True
예제 #10
0
#!/usr/bin/env python
# Convert CCP4 map to map coefficients in MTZ

import sys
import gemmi

RESOLUTION_LIMIT = 1.5  # set 0 for no limit

if len(sys.argv) != 3:
    sys.exit('Usage: map2mtz.py input.ccp4 output.mtz')

m = gemmi.read_ccp4_map(sys.argv[1])
m.setup()
sf = gemmi.transform_map_to_f_phi(m.grid, half_l=True)
data = sf.prepare_asu_data(dmin=RESOLUTION_LIMIT)

mtz = gemmi.Mtz(with_base=True)
mtz.spacegroup = sf.spacegroup
mtz.set_cell_for_all(sf.unit_cell)
mtz.add_dataset('unknown')
mtz.add_column('FWT', 'F')
mtz.add_column('PHWT', 'P')
mtz.set_data(data)
mtz.write_to_file(sys.argv[2])
예제 #11
0
    def __getitem__(self, item):
        event_record = self.table.iloc[item]

        event = Event.from_record(event_record)
        rscc = self.rscc_dict[(event.pandda_name, event.dtag, event.event_idx)]

        # if bool(event.viewed) is False:
        #     sample_dict = {"id": {"pandda_name": event.pandda_name,
        #                           "dtag": event.dtag,
        #                           "event_idx": event.event_idx,
        #                           },
        #                    "data": np.zeros((2,
        #                                      self.sample_shape[0],
        #                                      self.sample_shape[1],
        #                                      self.sample_shape[2],
        #                                      ),
        #                                     dtype=np.float32,
        #                                     ),
        #                    "label": np.array([1, 0], dtype=np.float32),
        #                    "event_map_path": str(event.event_map_path),
        #                    "model_path": str(event.initial_model_path),
        #                    "coords": str([event.x, event.y, event.z]),
        #                    "rscc": 0,
        #                    }
        #
        #     return sample_dict

        if float(rscc) == 0.0:
            sample_dict = {"id": {"pandda_name": event.pandda_name,
                                  "dtag": event.dtag,
                                  "event_idx": event.event_idx,
                                  },
                           "data": np.zeros((2,
                                             self.sample_shape[0],
                                             self.sample_shape[1],
                                             self.sample_shape[2],
                                             ),
                                            dtype=np.float32,
                                            ),
                           "label": np.array([1, 0], dtype=np.float32),
                           "event_map_path": str(event.event_map_path),
                           "model_path": str(event.initial_model_path),
                           "coords": str([event.x, event.y, event.z]),
                           "rscc": 0.0,
                           "rscc_class": np.array([1.0,0.0], dtype=np.float32),
                           }

            return sample_dict

        try:

            event_centroid = np.array([event.x,
                                       event.y,
                                       event.z,
                                       ])

            data_map = get_map_from_mtz_path(event.data_path)
            event_map: gemmi.Grid = gemmi.read_ccp4_map(event.event_map_path)

            rotation = sample_rotation()
            translation = sample_translation()

            data_map_layer = sample_map(data_map,
                                        event_centroid,
                                        rotation,
                                        translation,
                                        self.sample_shape,
                                        )
            event_map_layer = sample_event_map(event_map,
                                               event_centroid,
                                               rotation,
                                               translation,
                                               self.sample_shape,
                                               )
            data = np.stack([data_map_layer, event_map_layer],
                            axis=0,
                            )

            label = get_label(event)

            if rscc <0.7:
                rscc_class = np.array([1.0, 0.0], dtype=np.float32)
            else:
                rscc_class = np.array([0.0,1.0], dtype=np.float32)

            sample_dict = {"id": {"pandda_name": event.pandda_name,
                                  "dtag": event.dtag,
                                  "event_idx": event.event_idx,
                                  },
                           "data": data,
                           "label": label,
                           "event_map_path": str(event.event_map_path),
                           "model_path": str(event.initial_model_path),
                           "coords": str([event.x, event.y, event.z]),
                           "rscc": rscc,
                           "rscc_class": rscc_class,
                           }

            return sample_dict
        except Exception as e:
            # Null result
            # print(e)
            sample_dict = {"id": {"pandda_name": event.pandda_name,
                                  "dtag": event.dtag,
                                  "event_idx": event.event_idx,
                                  # "initial_model_dir": ,
                                  },
                           "data": np.zeros((2,
                                             self.sample_shape[0],
                                             self.sample_shape[1],
                                             self.sample_shape[2],
                                             ),
                                            dtype=np.float32,
                                            ),
                           "label": np.array([1, 0], dtype=np.float32),
                           "event_map_path": str(event.event_map_path),
                           "model_path": str(event.initial_model_path),
                           "coords": str([event.x, event.y, event.z]),
                           "rscc": 0.0,
                           "rscc_class": np.array([1, 0], dtype=np.float32),
                           }

            return sample_dict
예제 #12
0
    resolution_key = 'high_resolution=' + str(high_res)
    file_name_key = 'map_file_name = k_patt_plot_' + str(kk) + '.ccp4'
    label_key = 'labels =' + '\'' + I_base + str(kk) + ',' + sig_base + str(
        kk) + '\''
    if generate_maps == 'y':
        subprocess.call([
            'cctbx.patterson_map', mtz_name, file_name_key, label_key,
            resolution_key
        ])
    else:
        break
    k = k + 1

#Read in CCP4 format Patterson maps as 3D Numpy arrays and

ccp4 = gemmi.read_ccp4_map('k_patt_plot_000.ccp4')
ccp4.setup()
arr = np.array(ccp4.grid, copy=False)
x = np.linspace(0, ccp4.grid.unit_cell.a, num=arr.shape[0], endpoint=False)
y = np.linspace(0, ccp4.grid.unit_cell.b, num=arr.shape[1], endpoint=False)
plt.plot(y, arr[0, :, 0], label='k = 0')

ccp4 = gemmi.read_ccp4_map('k_patt_plot_015.ccp4')
ccp4.setup()
arr = np.array(ccp4.grid, copy=False)
plt.plot(y, arr[0, :, 0], label='k = 15')

ccp4 = gemmi.read_ccp4_map('k_patt_plot_018.ccp4')
ccp4.setup()
arr = np.array(ccp4.grid, copy=False)
plt.plot(y, arr[0, :, 0], label='k = 18')
예제 #13
0
    def __getitem__(self, item):
        event_record = self.table.iloc[item]

        event = Event.from_record(event_record)
        # print(event.viewed)
        # print(type(event.viewed))

        if bool(event.viewed) is False:
            sample_dict = {
                "id": {
                    "pandda_name": event.pandda_name,
                    "dtag": event.dtag,
                    "event_idx": event.event_idx,
                },
                "data": np.zeros(
                    self.sample_shape,
                    dtype=np.float32,
                ),
                "label": np.array([1, 0], dtype=np.float32),
            }

            return sample_dict
        try:

            event_centroid = np.array([
                event.x,
                event.y,
                event.z,
            ])

            event_map: gemmi.Grid = gemmi.read_ccp4_map(event.event_map_path)

            rotation = sample_rotation()
            translation = sample_translation()

            event_map_layer = sample_event_map(
                event_map,
                event_centroid,
                rotation,
                translation,
                self.sample_shape,
            )
            data = event_map_layer

            label = get_label(event)

            sample_dict = {
                "id": {
                    "pandda_name": event.pandda_name,
                    "dtag": event.dtag,
                    "event_idx": event.event_idx,
                },
                "data": data,
                "label": label,
            }

            return sample_dict
        except:
            # Null result
            sample_dict = {
                "id": {
                    "pandda_name": event.pandda_name,
                    "dtag": event.dtag,
                    "event_idx": event.event_idx,
                },
                "data": np.zeros(
                    self.sample_shape,
                    dtype=np.float32,
                ),
                "label": np.array([1, 0], dtype=np.float32),
            }

            return sample_dict
예제 #14
0
    def __getitem__(self, item):
        build_record = self.table.iloc[item]

        build: Build = Build(
            system=build_record["system"],
            dtag=build_record["dtag"],
            event_idx=build_record["event_idx"],
            resolution=float(build_record["resolution"]),
            ligand_build_path=Path(build_record["ligand_build_path"]),
            stripped_receptor_path=Path(
                build_record["stripped_receptor_path"]),
            x=float(build_record["x"]),
            y=float(build_record["y"]),
            z=float(build_record["z"]),
            data_path=Path(build_record["data_path"]),
            human_build=bool(build_record["human_build"]),
            rmsd=float(build_record["rmsd"]),
        )

        event_centroid = np.array([
            build.x,
            build.y,
            build.z,
        ])

        event_map: gemmi.Grid = gemmi.read_ccp4_map(build.data_path)

        if build.human_build:
            receptor_model, ligand_model = get_human_build_models(
                build.ligand_build_path,
                event_centroid=event_centroid,
            )
        else:
            receptor_model = get_receptor_model(build.stripped_receptor_path)
            ligand_model = get_ligand_model(build.ligand_build_path)

        rotation = sample_rotation()
        translation = sample_translation()

        event_map_layer = sample_event_map(
            event_map,
            event_centroid,
            rotation,
            translation,
            self.shape,
        )
        receptor_layers = sample_receptor_layers(
            event_map,
            receptor_model,
            event_centroid,
            rotation,
            translation,
            self.shape,
        )
        ligand_layers = sample_ligand_layers(
            event_map,
            ligand_model,
            event_centroid,
            rotation,
            translation,
            self.shape,
        )

        data = np.concatenate([event_map_layer] + receptor_layers +
                              ligand_layers)

        label = get_label(
            build.human_build,
            build.rmsd,
            event_centroid,
            ligand_model,
        )

        return {
            "id": {
                "dtag": build.dtag,
                "event_idx": build.event_idx
            },
            "data": data,
            "label": label
        }