<commit_before>#!/usr/bin/env python

import glob
import locale
import logging
import os
import re

# Our imports
import printTable

class MrBumpResult(object):
    """
    Class to hold the result of running a MRBUMP job
    """
    def __init__(self):
        """
        
        """
        self.jobDir = None # directory jobs ran in
        self.resultDir = None # where the actual results are
        self.name = None
        self.program = None
        self.solution = None
        self.rfact = None
        self.rfree = None
        self.shelxCC = None
        
        self.header = None # The header format for this table

class ResultsSummary(object):
    """
    Summarise the results for a series of MRBUMP runs
    """
    
    def __init__(self, mrbump_dir):
        
        self.mrbump_dir = mrbump_dir
        self.results = []
        
        self.logger = logging.getLogger()

    def extractResults( self ):
        """
        Find the results from running MRBUMP and sort them
        """

        # reset any results
        self.results = []
        
        # how we recognise a job directory
        dir_re = re.compile("^search_.*_mrbump$")
        jobDirs = []
        #jobDirs = glob.glob( os.path.join( self.mrbump_dir, "search_*_mrbump" ) )
        for adir in os.listdir( self.mrbump_dir ):
            # REM only returns relative path
            dpath = os.path.join( self.mrbump_dir, adir )
            if dir_re.match( adir ) and os.path.isdir( dpath ):
                jobDirs.append( dpath )
        
        if not len(jobDirs):
            self.logger.warn("Could not extract any results from directory: {0}".format( self.mrbump_dir ) )
            return False
        
        header = None
        for jobDir in jobDirs:
            
            self.logger.debug(" -- checking directory for results: {0}".format( jobDir ) )
            
            # Check if finished
            if not os.path.exists( os.path.join( jobDir, "results", "finished.txt" ) ):
                self.logger.debug(" Found unfinished job: {0}".format( jobDir ) )
                result = self.getUnfinishedResult( jobDir, jtype="unfinished" )
                self.results.append( result )
                continue
            
            resultsTable = os.path.join( jobDir,"results", "resultsTable.dat" )
            if not os.path.exists(resultsTable):
                self.logger.debug(" -- Could not find file: {0}".format( resultsTable ) )
                result = self.getUnfinishedResult( jobDir, jtype="no-resultsTable.dat" )
                self.results.append( result )
                continue
            
            firstLine = True
            # Read results table to get the results
            for line in open(resultsTable):
                
                line = line.strip()
                
                if firstLine:
                    # probably overkill...
                    if line != "Model_Name   MR_Program   Solution_Type   final_Rfact   final_Rfree   SHELXE_CC":
                        raise RuntimeError,"Problem getting headerline: {0}".format(line)
                    header = line
                    firstLine=False
                    continue
                
                result = MrBumpResult()
                result.jobDir = jobDir
                
                fields = line.split()
                
                # Strip loc0_ALL_ from front and strip  _UNMOD from end from (e.g.): loc0_ALL_All_atom_trunc_0.34524_rad_1_UNMOD
                #result.name = fields[0][9:-6]
                # Don't do the above yet till we've finsihed the next set of runs
                result.name = fields[0]
                result.program = fields[1].lower()
                result.solution = fields[2]
                result.rfact = fields[3]
                result.rfree = fields[4]
                result.shelxCC = fields[5]
                result.header = header
                
                if result.program not in ['phaser','molrep']:
                    raise RuntimeError,"getResult, unrecognised program in line: {0}".format(line)
                
                # Rebuild the path that generated the result
                # Add loc0_ALL_ and strip  _UNMOD from (e.g.): loc0_ALL_All_atom_trunc_0.34524_rad_1_UNMOD 
                #dirName = "loc0_ALL_" + result.name + "_UNMOD"
                # While using old names - just strip _UNMOD
                dirName = result.name[:-6]
                resultDir = os.path.join( result.jobDir,'data',dirName,'unmod','mr',result.program,'refine' )
                #print resultDir
                result.resultDir = resultDir
                
                self.results.append( result )
                
        if not len(self.results):
            self.logger.warn("Could not extract any results from directory: {0}".format( self.mrbump_dir ) )
            return False
        
        # Sort the results
        self.sortResults()
        
        return True
    
    def getUnfinishedResult(self, jobDir, jtype="unfinished" ):
        """Return a result for an unfinished job"""
        
        result = MrBumpResult()
        result.jobDir = jobDir
        
        # Use directory name for job name
        dlist = os.listdir( os.path.join( jobDir, "data") )
        if len( dlist ) != 1:
            result.name = "Error with dir: {0}".format( jobDir )

        # Use dirname but remove "loc0_ALL_" from front
        #result.name = os.path.basename( dlist[0] )[9:]
        # Use dirname but add "_UNMOD" to back
        result.name = os.path.basename( dlist[0] )+"_UNMOD"
        result.program = "unknown"
        result.solution = jtype<commit_msg>Minor changes to handle things when MRBUMP runs fail.<commit_after>#!/usr/bin/env python

import glob
import locale
import logging
import os
import re

# Our imports
import printTable

class MrBumpResult(object):
    """
    Class to hold the result of running a MRBUMP job
    """
    def __init__(self):
        """
        
        """
        self.jobDir = None # directory jobs ran in
        self.resultDir = None # where the actual results are
        self.name = None
        self.program = None
        self.solution = None
        self.rfact = None
        self.rfree = None
        self.shelxCC = None
        
        self.header = None # The header format for this table

class ResultsSummary(object):
    """
    Summarise the results for a series of MRBUMP runs
    """
    
    def __init__(self, mrbump_dir):
        
        self.mrbump_dir = mrbump_dir
        self.results = []
        
        self.logger = logging.getLogger()

    def extractResults( self ):
        """
        Find the results from running MRBUMP and sort them
        """

        # reset any results
        self.results = []
        
        # how we recognise a job directory
        dir_re = re.compile("^search_.*_mrbump$")
        jobDirs = []
        #jobDirs = glob.glob( os.path.join( self.mrbump_dir, "search_*_mrbump" ) )
        for adir in os.listdir( self.mrbump_dir ):
            # REM only returns relative path
            dpath = os.path.join( self.mrbump_dir, adir )
            if dir_re.match( adir ) and os.path.isdir( dpath ):
                jobDirs.append( dpath )
        
        if not len(jobDirs):
            self.logger.warn("Could not extract any results from directory: {0}".format( self.mrbump_dir ) )
            return False
        
        header = None
        for jobDir in jobDirs:
            
            self.logger.debug(" -- checking directory for results: {0}".format( jobDir ) )
            
            # Check if finished
            if not os.path.exists( os.path.join( jobDir, "results", "finished.txt" ) ):
                self.logger.debug(" Found unfinished job: {0}".format( jobDir ) )
                result = self.getUnfinishedResult( jobDir, jtype="unfinished" )
                self.results.append( result )
                continue
            
            resultsTable = os.path.join( jobDir,"results", "resultsTable.dat" )
            if not os.path.exists(resultsTable):
                self.logger.debug(" -- Could not find file: {0}".format( resultsTable ) )
                result = self.getUnfinishedResult( jobDir, jtype="no-resultsTable.dat" )
                self.results.append( result )
                continue
            
            firstLine = True
            # Read results table to get the results
            for line in open(resultsTable):
                
                line = line.strip()
                
                if firstLine:
                    # probably overkill...
                    if line != "Model_Name   MR_Program   Solution_Type   final_Rfact   final_Rfree   SHELXE_CC":
                        #raise RuntimeError,"jobDir {0}: Problem getting headerline: {1}".format(jobDir,line)
                        self.logger.critical("jobDir {0}: Problem getting headerline: {1}".format(jobDir,line) )
                        result = self.getUnfinishedResult( jobDir, jtype="corrupted-resultsTable.dat" )
                        self.results.append( result )
                        break
                    header = line
                    firstLine=False
                    continue
                
                result = MrBumpResult()
                result.jobDir = jobDir
                
                fields = line.split()
                
                # Strip loc0_ALL_ from front and strip  _UNMOD from end from (e.g.): loc0_ALL_All_atom_trunc_0.34524_rad_1_UNMOD
                #result.name = fields[0][9:-6]
                # Don't do the above yet till we've finsihed the next set of runs
                result.name = fields[0]
                result.program = fields[1].lower()
                result.solution = fields[2]
                result.rfact = fields[3]
                result.rfree = fields[4]
                result.shelxCC = fields[5]
                result.header = header
                
                if result.program not in ['phaser','molrep']:
                    raise RuntimeError,"getResult, unrecognised program in line: {0}".format(line)
                
                # Rebuild the path that generated the result
                # Add loc0_ALL_ and strip  _UNMOD from (e.g.): loc0_ALL_All_atom_trunc_0.34524_rad_1_UNMOD 
                #dirName = "loc0_ALL_" + result.name + "_UNMOD"
                # While using old names - just strip _UNMOD
                dirName = result.name[:-6]
                resultDir = os.path.join( result.jobDir,'data',dirName,'unmod','mr',result.program,'refine' )
                #print resultDir
                result.resultDir = resultDir
                
                self.results.append( result )
                
        if not len(self.results):
            self.logger.warn("Could not extract any results from directory: {0}".format( self.mrbump_dir ) )
            return False
        
        # Sort the results
        self.sortResults()
        
        return True
    
    def getUnfinishedResult(self, jobDir, jtype="unfinished" ):
        """Return a result for an unfinished job"""
        
        result = MrBumpResult()
        result.jobDir = jobDir
        
        # Use directory name for job name
        dlist = os.listdir( os.path.join( jobDir, "data") )
        if len( dlist ) != 1:
            # something has gone really wrong...
            # Need to work out name from MRBUMP directory structure - search_poly_ala_trunc_6.344502_rad_3_phaser_mrbump
            dname = os.path.basename(jobDir)[7:-7]
            # Horrible - check if we were run with split_mr - in which case _phaser or _molrep are appended to the name
            if dname.endswith("_molrep") or dname.endswith("_phaser"):
                dname = dname[:-7]
            # Add loc0_ALL_ and append _UNMOD. shudder...
            result.name = "loc0_ALL_" + dname + "_UNMOD"
            result.solution = "ERROR"
        else:
            # Use dirname but remove "loc0_ALL_" from front
            #result.name = os.path.basename( dlist[0] )[9:]
            # Use dirname but add "_UNMOD" to back
            result.name = os.path.basename( dlist[0] )+"_UNMOD"
            result.solution = jtype

        result.program = "unknown"
{'fraction_non_alphanumeric': 0.09037025008119519, 'fraction_numerical': 0.008038324131211432, 'mean_word_length': 1.541683862979777, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5596683', 'n_tokens_mistral': 3476, 'n_tokens_neox': 3323, 'n_words': 909}