cc_web.py 12.8 KB
Newer Older
1 2 3 4 5 6
"""Pipeline to update the CC web resource.

The steps (a.k.a. tasks) for CC web update are the following:

1. Generate a universe file (i.e. HDF5 with all inchikeys sorted)
2. Create a new web DB
7 8 9 10 11
3. Drop/Create/Fill the `pubchem` table (used e.g. for drug synonyms)
4. Drop/Create/Fill the `showtargets` and `showtargets_description` tables (known drug tagets)
5. Drop/Create/Fill the `coordinates` and `coordinate_stats` tables (spaces description and projection xy limits)
6. Drop/Create/Fill the `projections` table (xy for each proj2 molecule)
7. Create 2d svg molecule images for each molecule
12 13 14
8. Drop/Create/Fill the `molecular_info` table (popularity singularity mappability etc.)
9. Drop/Create/Fill the `libraries` and `library_description` tables (used to fetch 100 landmark molecules)
10. Generate explore.json file for each molecule (info for explore drug page)
15
11. Link/copy generated files to webpage repository (mosaic)
16
12. Export signature 3 to ftp directory
17

18
FINAL MANUAL STEPS:
19

20 21 22
1. Update mosaic/app/shared/data/local_parameters*.json with newly generated NEWDB on aloy-dbsrv
2. Test the website
3. Copy NEWDB to aloy-dbwebsrv
23 24 25
$ pg_dump -h aloy-dbsrv -U 'sbnb-adm' NEWDB | gzip -c > NEWDB.sql.gz
$ createdb -h aloy-dbwebsrv -U 'sbnb-adm' NEWDB
$ gunzip -c NEWDB.sql.gz | psql -h aloy-dbwebsrv -U 'sbnb-adm' NEWDB
26
4. Update db host in mosaic/app/shared/data/local_parameters*.json to aloy-dbwebsrv
27

28
"""
Oriol Guitart's avatar
Oriol Guitart committed
29
import os
30
import sys
Oriol Guitart's avatar
Oriol Guitart committed
31
import h5py
32 33
import json
import shutil
34 35 36 37
import logging
import argparse
import numpy as np

Oriol Guitart's avatar
Oriol Guitart committed
38
from chemicalchecker import ChemicalChecker
Oriol Guitart's avatar
Oriol Guitart committed
39
from chemicalchecker.core import DataSignature
40 41 42 43 44
from chemicalchecker.util import psql
from chemicalchecker.util import logged, Config
from chemicalchecker.util.pipeline import Pipeline, PythonCallable, Pubchem
from chemicalchecker.util.pipeline import ShowTargets, Libraries, Similars
from chemicalchecker.util.pipeline import Coordinates, Projections, Plots
45
from chemicalchecker.util.pipeline import MolecularInfo
46 47 48 49 50 51 52 53 54


def pipeline_parser():
    """Parse pipeline arguments."""
    description = 'Run the full CC update pipeline.'
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument(
        'cc_root', type=str,
        help='Directory of the CC instance the web will refere to '
55
        '(e.g. `/aloy/web_checker/package_cc/miniCC`)')
56 57 58 59
    parser.add_argument(
        'pipeline_dir', type=str,
        help='Directory where the pipeline will run '
        '(e.g. `/aloy/scratch/mbertoni/pipelines/miniCC_web`)')
60 61 62 63 64 65 66 67 68 69 70 71 72 73
    parser.add_argument(
        'molecule_path', type=str,
        help='Directory where the molecule images will be stored '
        '(e.g. `/aloy/web_checker/molecules`)')
    parser.add_argument(
        'old_web_db', type=str,
        help='Previous web database '
        '(e.g. `mosaic` or `cc_web_2019_05`)')
    parser.add_argument(
        'new_web_db', type=str,
        help='Web database to generate '
        '(e.g. `cc_web_2020_01`)')
    parser.add_argument(
        'uniprot_db', type=str,
74
        help='Uniprot db to use '
75
        '(e.g. `2019_01`)')
76 77 78 79
    parser.add_argument(
        'web_repo_path', type=str,
        help='Path to the mosaic web repository '
        '(e.g. `/aloy/home/mbertoni/code/mosaic`)')
Martino Bertoni's avatar
Martino Bertoni committed
80 81 82 83 84 85 86 87
    parser.add_argument(
        '-t', '--only_tasks', type=str, nargs="+", default=[],
        required=False,
        help='Names of tasks that will `exclusively` run by the pipeline.')
    parser.add_argument(
        '-s', '--exclude_tasks', type=str, nargs="+", default=[],
        required=False,
        help='Names of tasks that will be skipped.')
88 89 90 91 92 93
    parser.add_argument(
        '-c', '--config', type=str, required=False,
        default=os.environ["CC_CONFIG"],
        help='Config file to be used. If not specified CC_CONFIG enviroment'
        ' variable is used.')
    parser.add_argument(
Martino Bertoni's avatar
Martino Bertoni committed
94
        '-d', '--dry_run', action='store_true',
95 96 97 98 99 100 101
        help='Execute pipeline script without running the pipeline.')
    return parser


@logged(logging.getLogger("[ PIPELINE %s ]" % os.path.basename(__file__)))
def main(args):
    # initialize Pipeline
Martino Bertoni's avatar
Martino Bertoni committed
102
    cfg = Config(args.config)
103
    pp = Pipeline(pipeline_path=args.pipeline_dir, keep_jobs=True,
Martino Bertoni's avatar
Martino Bertoni committed
104 105
                  config=cfg, only_tasks=args.only_tasks,
                  exclude_tasks=args.exclude_tasks)
106

107 108 109 110
    # print arguments
    for arg in vars(args):
        main._log.info('[ ARGS ] {:<25s}: {}'.format(arg, getattr(args, arg)))

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
    libraries = {
        "apd": [
            'Approved drugs',
            'Approved drug molecules from DrugBank',
            'http://zinc15.docking.org/catalogs/dbap/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "exd": [
            'Experimental drugs',
            'Experimental and investigational drug molecules from DrugBank',
            'http://zinc15.docking.org/catalogs/dbex/'
            'items.txt?count=all&output_fields=smiles%20zinc_id;'
            'http://zinc15.docking.org/catalogs/dbin/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "met": [
            'Human metabolites',
            'Endogenous metabolites from Human Metabolome Database (HMDb)',
            'http://zinc15.docking.org/catalogs/hmdbendo/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "tcm": [
            'Tradicional Chinese medicines',
            'Compounds extracted from traditional Chinese medicinal plants',
            'http://zinc15.docking.org/catalogs/tcmnp/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "lincs": [
            'LINCS compounds',
            'Collection of compounds of the LINCS initiative',
            'http://zinc15.docking.org/catalogs/lincs/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "pwck": [
            'Prestwick chemical library',
            'Prestwick commercial collection',
            'http://zinc15.docking.org/catalogs/prestwick/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "nihcc": [
            'NIH clinical collection',
            'NIH clinical collection',
            'http://zinc15.docking.org/catalogs/nihcc/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "ncidiv": [
            'NCI diversity collection',
            'NCI diversity collection',
            'http://zinc15.docking.org/catalogs/ncidiv/'
            'items.txt?count=all&output_fields=smiles%20zinc_id',
            'zinc'],
        "tool": [
            'Tool compounds',
            'Tool compounds',
            'http://zinc15.docking.org/toolcompounds.smi?count=all',
            'zinc']
    }

    # TASK: Create universe file (used by most of following steps)
170
    def create_uni_fn(cc_root, cachedir):
171
        cc = ChemicalChecker(args.cc_root)
172
        universe_list = cc.get_signature('sign3', 'full', 'A1.001').keys
173 174 175 176
        universe_file = os.path.join(cachedir, "universe.h5")
        with h5py.File(universe_file, "w") as h5:
            h5.create_dataset("keys", data=np.array(
                universe_list, DataSignature.string_dtype()))
177 178 179
        # also save as json (used by the web)
        bioactive_mol_set = os.path.join(cachedir, "bioactive_mol_set.json")
        json.dump(universe_list, open(bioactive_mol_set, 'w'))
180 181

    universe_task = PythonCallable(name="create_universe",
182
                                   python_callable=create_uni_fn,
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
                                   op_args=[args.cc_root, pp.cachedir])
    pp.add_task(universe_task)

    # TASK: Create DB
    def create_db_fn():
        con = psql.get_connection(args.old_web_db)
        con.autocommit = True
        success = False
        cur = con.cursor()
        try:
            cur.execute('CREATE DATABASE {};'.format(args.new_web_db))
            success = True
        except Exception as e:
            print(e)
        finally:
            con.close()
        if not success:
            raise Exception("Cannot create DB.")

    db_task = PythonCallable(name="create_db",  python_callable=create_db_fn)
    pp.add_task(db_task)

    # TASK: Fill Pubchem table
    pbchem_task = Pubchem(name='pubchem',
                          DB=args.new_web_db, OLD_DB=args.old_web_db)
    pp.add_task(pbchem_task)

210
    # TASK: Find targets on uniprot and fill local table
211 212 213 214 215 216 217 218 219 220
    targets_task = ShowTargets(name='showtargets',
                               DB=args.new_web_db, CC_ROOT=args.cc_root,
                               uniprot_db_version=args.uniprot_db)
    pp.add_task(targets_task)

    # TASK: Fill coordinates
    coords_task = Coordinates(name='coordinates',
                              DB=args.new_web_db, CC_ROOT=args.cc_root)
    pp.add_task(coords_task)

221
    # TASK: Fill projecions
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    projs_task = Projections(name='projections',
                             DB=args.new_web_db, CC_ROOT=args.cc_root)
    pp.add_task(projs_task)

    # TASK: Create all plots
    plots_task = Plots(name='plots',
                       DB=args.new_web_db, CC_ROOT=args.cc_root,
                       MOLECULES_PATH=args.molecule_path)
    pp.add_task(plots_task)

    # TASK: Generate molecular info
    minfo_task = MolecularInfo(name='molinfo',
                               DB=args.new_web_db, CC_ROOT=args.cc_root)
    pp.add_task(minfo_task)

Martino Bertoni's avatar
Martino Bertoni committed
237
    # TASK: Generate libraries set
238 239 240 241 242
    libs_task = Libraries(name='libraries',
                          DB=args.new_web_db, CC_ROOT=args.cc_root,
                          libraries=libraries)
    pp.add_task(libs_task)

Martino Bertoni's avatar
Martino Bertoni committed
243
    # TASK: Create json of similar molecules for explore page
244 245 246 247 248
    similars_task = Similars(name='similars',
                             DB=args.new_web_db, CC_ROOT=args.cc_root,
                             MOLECULES_PATH=args.molecule_path)
    pp.add_task(similars_task)

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
    # TASK: Link/copy generated files to webpage repository (mosaic)
    def links_to_web_repo(cc_root, web_repo_path, tmpdir):
        # link plots dir
        src_dir = os.path.join(cc_root, 'plots_web')
        if not os.path.isdir(src_dir):
            raise Exception(
                "%s not found! Did cc_update.py finish correctly?" %
                src_dir)
        dst_dir = os.path.join(web_repo_path, 'app', 'images', 'plots')
        if os.path.isdir(dst_dir):
            os.remove(dst_dir)
        os.symlink(src_dir, dst_dir)
        # link molecule dir
        src_dir = args.molecule_path
        if not os.path.isdir(src_dir):
            raise Exception(
                "%s not found! Did cc_update.py finish correctly?" %
                src_dir)
        dst_dir = os.path.join(web_repo_path, 'app', 'images', 'molecules')
        if os.path.isdir(dst_dir):
            os.remove(dst_dir)
        os.symlink(src_dir, dst_dir)
        # copy bioactive_mol_set.json (aka cc universe)
        src_path = os.path.join(tmpdir, 'bioactive_mol_set.json')
        dst_path = os.path.join(web_repo_path, 'app',
                                'shared', 'data', 'bioactive_mol_set.json')
        shutil.copyfile(src_path, dst_path)
        # copy inchies_names.json (aka molecule common names)
        src_path = os.path.join(tmpdir, 'inchies_names.json')
        dst_path = os.path.join(web_repo_path, 'app',
                                'shared', 'data', 'inchies_names.json')
        shutil.copyfile(src_path, dst_path)
281 282 283 284 285 286 287 288 289
        # generate all inchikeys per coordinate
        cc = ChemicalChecker(args.cc_root)
        ink_coord = {}
        for ds in cc.datasets_exemplary():
            s1 = cc.get_signature('sign1', 'full', ds)
            ink_coord[ds[:2]] = list(s1.keys)
        dst_path = os.path.join(web_repo_path, 'app',
                                'shared', 'data', 'iks_coord.json')
        json.dump(ink_coord, open(dst_path, 'w'))
290 291 292 293 294 295 296

    links_task = PythonCallable(
        name="links_to_web_repo",
        python_callable=links_to_web_repo,
        op_args=[args.cc_root, args.web_repo_path, pp.tmpdir])
    pp.add_task(links_task)

297 298 299 300 301 302 303 304 305 306
    # TASK: Export signature 3 to ftp directory
    def export_sign3_ftp(cc_root, ftp_path='/aloy/web_checker/ftp_data'):
        cc = ChemicalChecker(args.cc_root)
        for ds in cc.datasets_exemplary():
            s3 = cc.get_signature('sign3', 'full', ds)
            dst = os.path.join(ftp_path, cc.name, '%s.h5' % ds[:2])
            cc.export(dst, s3, h5_filter=['keys', 'V', 'confidence', 'known'],
                      h5_names_map={'confidence': 'applicability'})

    export_task = PythonCallable(name="export_sign3_ftp",
Martino Bertoni's avatar
Martino Bertoni committed
307 308
                                 python_callable=export_sign3_ftp,
                                 op_args=[args.cc_root])
309 310
    pp.add_task(export_task)

311
    # RUN the pipeline!
Martino Bertoni's avatar
Martino Bertoni committed
312
    main._log.info('TASK SEQUENCE: %s' % ', '.join([t.name for t in pp.tasks]))
313 314
    if not args.dry_run:
        pp.run()
315 316 317 318 319 320


if __name__ == '__main__':
    # parse arguments
    args = pipeline_parser().parse_args(sys.argv[1:])
    main(args)