# Path: e3fp_paper/sea_utils/util.py
# def molecules_to_lists_dicts(molecules_file, first=-1, merge_proto=True):
#     """Read molecules file to dict of mol names to list of native tuples."""
#     proto_smiles_dict = {}
#     proto_lists_dict = {}
#     smiles_dict = {}
#     mol_lists_dict = {}
#     mol_iter = read_csv_mols(molecules_file, has_fp=True)
#     fp_type = mol_iter.next()
#     while True:
#         try:
#             row = mol_iter.next()
#         except StopIteration:
#             break
#         if row is None:
#             continue
#         fp_name, smiles = row[:2]
# 
#         proto_name = MolItemName.from_str(
#             MolItemName.from_str(fp_name).proto_name)
#         proto_smiles_dict[proto_name] = smiles
#         try:
#             fp_native = row[2]
#             proto_lists_dict.setdefault(proto_name, []).append((fp_native,
#                                                                 fp_name))
#             # mol_lists_dict.setdefault(mol_name, []).append((fp_native,
#             #                                                 fp_name))
#         except IndexError:
#             logging.warning("%s has no native fingerprint. Will not be added to dict." % fp_name)
# 
#     if first > 0:
#         proto_lists_dict = dict([(k, v[:first])
#                                  for k, v in proto_lists_dict.iteritems()])
# 
#     if merge_proto:
#         for mol_item_name, native_tuples in sorted(proto_lists_dict.items()):
#             mol_name = mol_item_name.mol_name
#             mol_lists_dict.setdefault(mol_name, []).extend(native_tuples)
#             smiles_dict.setdefault(mol_name,
#                                    proto_smiles_dict[mol_item_name])
#     else:
#         for mol_item_name, native_tuples in proto_lists_dict.iteritems():
#             proto_name = mol_item_name.proto_name
#             mol_lists_dict[proto_name] = native_tuples
#             smiles_dict[proto_name] = proto_smiles_dict[mol_item_name]
# 
#     return smiles_dict, mol_lists_dict, fp_type
# 
# def lists_dicts_to_molecules(molecules_file, smiles_dict, mol_lists_dict,
#                              fp_type):
#     """Write dict of mol names to list of native tuples to a molecules file."""
#     with smart_open(molecules_file, "wb") as f:
#         writer = csv.writer(f)
#         fp_type.write(writer)
#         writer.writerow(("molecule id", "smiles", "fingerprint"))
#         for mol_name in sorted(smiles_dict.keys()):
#             smiles = smiles_dict[mol_name]
#             fp_list = mol_lists_dict.get(mol_name, [])
#             for fp_native, fp_name in fp_list:
#                 writer.writerow((fp_name, smiles, fp_native))


import os
import glob
import random
import logging
import argparse
import rdkit.Chem
from python_utilities.io_tools import smart_open
from e3fp.conformer.util import mol_from_sdf
from e3fp_paper.sea_utils.util import molecules_to_lists_dicts, \
    lists_dicts_to_molecules
    except ValueError:
        proto_name = conf_name
    mol_name, proto_id = proto_name.split("-")
    try:
        return mol_name, int(proto_id), int(conf_id)
    except NameError:
        return mol_name, int(proto_id)


def join_conf_name(mol_name, proto_id, conf_id=None):
    if conf_id is None:
        return "{}-{}".format(mol_name, proto_id)
    else:
        return "{}-{}_{}".format(mol_name, proto_id, conf_id)


def main(sdf_dir, mol_file, num_confs=10000,
         out_conf_file="random_conformers.txt",
         out_sdf_file="random_conformers.sdf.bz2",
         out_mol_file="random_conformers.csv.bz2"):
    confs = set()
    if os.path.isfile(out_mol_file):
        logging.info("Loading existing random molecules.")
        _, conf_mol_list_dict, _ = molecules_to_lists_dicts(out_mol_file,
                                                            merge_proto=False)
        for proto_name in conf_mol_list_dict:
            for _, conf_name in conf_mol_list_dict[proto_name]:
                confs.add(split_conf_name(conf_name))
    else:
        logging.info("Loading molecules file.")

# Path: e3fp_paper/sea_utils/util.py
# def molecules_to_lists_dicts(molecules_file, first=-1, merge_proto=True):
#     """Read molecules file to dict of mol names to list of native tuples."""
#     proto_smiles_dict = {}
#     proto_lists_dict = {}
#     smiles_dict = {}
#     mol_lists_dict = {}
#     mol_iter = read_csv_mols(molecules_file, has_fp=True)
#     fp_type = mol_iter.next()
#     while True:
#         try:
#             row = mol_iter.next()
#         except StopIteration:
#             break
#         if row is None:
#             continue
#         fp_name, smiles = row[:2]
# 
#         proto_name = MolItemName.from_str(
#             MolItemName.from_str(fp_name).proto_name)
#         proto_smiles_dict[proto_name] = smiles
#         try:
#             fp_native = row[2]
#             proto_lists_dict.setdefault(proto_name, []).append((fp_native,
#                                                                 fp_name))
#             # mol_lists_dict.setdefault(mol_name, []).append((fp_native,
#             #                                                 fp_name))
#         except IndexError:
#             logging.warning("%s has no native fingerprint. Will not be added to dict." % fp_name)
# 
#     if first > 0:
#         proto_lists_dict = dict([(k, v[:first])
#                                  for k, v in proto_lists_dict.iteritems()])
# 
#     if merge_proto:
#         for mol_item_name, native_tuples in sorted(proto_lists_dict.items()):
#             mol_name = mol_item_name.mol_name
#             mol_lists_dict.setdefault(mol_name, []).extend(native_tuples)
#             smiles_dict.setdefault(mol_name,
#                                    proto_smiles_dict[mol_item_name])
#     else:
#         for mol_item_name, native_tuples in proto_lists_dict.iteritems():
#             proto_name = mol_item_name.proto_name
#             mol_lists_dict[proto_name] = native_tuples
#             smiles_dict[proto_name] = proto_smiles_dict[mol_item_name]
# 
#     return smiles_dict, mol_lists_dict, fp_type
# 
# def lists_dicts_to_molecules(molecules_file, smiles_dict, mol_lists_dict,
#                              fp_type):
#     """Write dict of mol names to list of native tuples to a molecules file."""
#     with smart_open(molecules_file, "wb") as f:
#         writer = csv.writer(f)
#         fp_type.write(writer)
#         writer.writerow(("molecule id", "smiles", "fingerprint"))
#         for mol_name in sorted(smiles_dict.keys()):
#             smiles = smiles_dict[mol_name]
#             fp_list = mol_lists_dict.get(mol_name, [])
#             for fp_native, fp_name in fp_list:
#                 writer.writerow((fp_name, smiles, fp_native))


# Path: project/fingerprint_comparison/random_conformers/get_random_confomers.py
import os
import glob
import random
import logging
import argparse
import rdkit.Chem
from python_utilities.io_tools import smart_open
from e3fp.conformer.util import mol_from_sdf
from e3fp_paper.sea_utils.util import molecules_to_lists_dicts, \
    lists_dicts_to_molecules

    except ValueError:
        proto_name = conf_name
    mol_name, proto_id = proto_name.split("-")
    try:
        return mol_name, int(proto_id), int(conf_id)
    except NameError:
        return mol_name, int(proto_id)


def join_conf_name(mol_name, proto_id, conf_id=None):
    if conf_id is None:
        return "{}-{}".format(mol_name, proto_id)
    else:
        return "{}-{}_{}".format(mol_name, proto_id, conf_id)


def main(sdf_dir, mol_file, num_confs=10000,
         out_conf_file="random_conformers.txt",
         out_sdf_file="random_conformers.sdf.bz2",
         out_mol_file="random_conformers.csv.bz2"):
    confs = set()
    if os.path.isfile(out_mol_file):
        logging.info("Loading existing random molecules.")
        _, conf_mol_list_dict, _ = molecules_to_lists_dicts(out_mol_file,
                                                            merge_proto=False)
        for proto_name in conf_mol_list_dict:
            for _, conf_name in conf_mol_list_dict[proto_name]:
                confs.add(split_conf_name(conf_name))
    else:
        logging.info("Loading molecules file.")

        smiles_dict, mol_list_dict, fp_type = molecules_to_lists_dicts(