# Copyright (c) 2013-2020, SIB - Swiss Institute of Bioinformatics and
#                          Biozentrum - University of Basel
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


'''
Automatically build a model from alignments and template structures.

Example usage:
  pm build-model -f aln.fasta -p tpl.pdb
    This reads a target-template alignment from aln.fasta and a matching
    structure from tpl.pdb and produces a gap-less model which is stored
    as model.pdb.

Please see the ProMod3 documentation for details on more advanced usage.
'''

import os
import ost
from ost import io, settings
from promod3 import modelling
from promod3.core import pm3argparse, helper

# make sure we see output when passing '-h'
ost.PushVerbosityLevel(2)

# parse command line
parser = pm3argparse.PM3ArgumentParser(__doc__, action=True)
parser.AddAlignment()
parser.AddStructure(attach_views=True)
parser.AddProfile()
parser.AddFragments()
parser.AssembleParser()
parser.add_argument('-o', '--model-file', metavar='<FILENAME>', type=str,
                    default='model.pdb', help='File to store model coordinates'+
                                              ' (default: %(default)s).')
parser.add_argument('-t', '--model-termini', help="Enforce modelling of " +
                    "terminal stretches without template coverage with a " +
                    "crude Monte Carlo approach. The accuracy of those " +
                    "termini is likely to be limited.", action="store_true")


# lots of checking being done here -> see PM3ArgumentParser
opts = parser.Parse()

# report alignments and add dssp
ost.PushVerbosityLevel(3)
if len(opts.alignments) == 1:
    ost.LogInfo("Build model with the following alignment:")
elif len(opts.alignments) > 1:
    ost.LogInfo("Build " + str(len(opts.alignments)) + " models with the "+
                "following alignments:")

for aln in opts.alignments:
    ost.LogInfo(aln.ToString(80))
    for i in range(1, aln.GetCount()):
        ost.mol.alg.AssignSecStruct(aln.GetSequence(i).GetAttachedView())

# model it
try:
    # get raw model
    mhandle = modelling.BuildRawModel(opts.alignments)
    # add profiles if any
    # no psipred predictions are added, as the default modelling pipeline
    # we're using here never looks at them. If we need psipred predictions,
    # pssm files would not be sufficient and we would be restricted to hhm.
    if len(opts.profiles) > 0:
        modelling.SetSequenceProfiles(mhandle, opts.profiles)
    # add fragment support for Monte Carlo sampling. The fragment search
    # is setup in the argument parser. If activated you get fragment support
    # in any case but for optimal performance you should provide profiles
    # in hhm format (for profile AND secondary structure information).
    if len(opts.fragger_handles) > 0:
        modelling.SetFraggerHandles(mhandle, opts.fragger_handles)
    # build final model
    final_model = modelling.BuildFromRawModel(mhandle, 
                                              model_termini=opts.model_termini)
except Exception as ex:
    helper.MsgErrorAndExit("Failed to perform modelling! An exception of type "+
                           type(ex).__name__ + " occured: " + str(ex), 3)

# output
ost.PopVerbosityLevel()
try:
    io.SavePDB(final_model, opts.model_file)
    if not os.path.isfile(opts.model_file):
        raise IOError("Failed to write model file.")
except Exception as ex:
    helper.MsgErrorAndExit("Failed to write model file '%s'." % opts.model_file, 4)
