File: xtp_modify_jobfile

package info (click to toggle)
votca 2025.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 132,420 kB
  • sloc: xml: 345,964; cpp: 80,067; python: 15,957; sh: 4,580; perl: 2,169; javascript: 202; makefile: 34
file content (191 lines) | stat: -rwxr-xr-x 6,202 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#! /usr/bin/env python3
#
# Copyright 2009-2024 The VOTCA Development Team (http://www.votca.org)
#
# 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.
#

VERSION = '@PROJECT_VERSION@ #VOTCA_GIT_ID#'
import sys
import argparse
import re
import lxml.etree as lxml
import fnmatch


PROGTITLE = 'THE VOTCA::XTP MODIFY JOBFILE'
PROGDESCR = 'Creates a subset Jobfile from a larger Jobfile using selection criteria'
VOTCAHEADER = '''\
==================================================
========   VOTCA (http://www.votca.org)   ========
==================================================

{progtitle}

please read and cite: @PROJECT_CITATION@
and submit bugs to @PROJECT_CONTACT@
xtp_update_mapfile, version {version}

'''.format(version=VERSION, progtitle=PROGTITLE)


def okquit(what=''):
    if what != '':
        print(what)
    sys.exit(0)
# =============================================================================
# PROGRAM OPTIONS
# =============================================================================


class XtpHelpFormatter(argparse.HelpFormatter):
    def _format_usage(self, usage, action, group, prefix):
        return VOTCAHEADER


progargs = argparse.ArgumentParser(prog='xtp_modify_jobfile',
                                   formatter_class=lambda prog: XtpHelpFormatter(
                                       prog, max_help_position=70),
                                   description=PROGDESCR)

progargs.add_argument('-i', '--input',
                      dest='j_input',
                      action='store',
                      required=True,
                      type=argparse.FileType('r'),
                      default='',
                      help='Jobfile file to select from.')

progargs.add_argument('-o', '--output',
                      dest='j_output',
                      action='store',
                      required=True,
                      type=argparse.FileType('w'),
                      default='',
                      help='Filename to write new jobfile to.')

progargs.add_argument('-l', '--job_ids',
                      dest='job_ids',
                      action='store',
                      type=str,
                      nargs="+",
                      help='Either a list of ids \'1 3 5\' or a range \'1-5\' or a combination thereof')

progargs.add_argument('-s', '--selector',
                      dest='selector',
                      action='store',
                      type=str,
                      help='A more flexible way to select jobs can be combined with ranges. Specify the xml tag you want inside the job via e.g. \'input/regions/region.id:0\'. The tag must exist and the value behind the colon supports \'?\' and \'*\' wildcards ')


OPTIONS = progargs.parse_args()


# =============================================================================
# LXML
# =============================================================================
def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


def parseIds(parseroutput):

    specific_ids = []
    if parseroutput is not None:
        if len(parseroutput) == 0:
            parseroutput = [parseroutput]
        print("Extracting jobs with ids:{}".format(" ".join(parseroutput)))
        for element in parseroutput:
            if "-" not in element:
                if RepresentsInt(element):
                    specific_ids.append(int(element))
                else:
                    okquit(
                        "Cannot parse {}, either specify an integer or a range".format(element))

            else:
                parts = element.split("-")
                if len(parts) != 2 or not RepresentsInt(parts[0]) or not RepresentsInt(parts[1]):
                    okquit(
                        "Cannot parse {}, range should be of the form x-y".format(element))

                startrange = int(parts[0])
                endrange = int(parts[1])+1
                if endrange < startrange:
                    okquit("Range {} should start with smaller element".format(parts))
                specific_ids.extend(range(startrange, endrange))

    return sorted(set(specific_ids))


def parseSelector(parseroutput):

    if parseroutput is not None:
        parts = parseroutput.split(":")
        pattern = "".join(parts[1:])
        path = parts[0]
        print("Extracting jobs with tag:\'{}\' and valuepattern:\'{}\''".format(
            path, pattern))
        return[path, pattern]
    else:
        return []


def check_id(job, specific_ids):
    id = int(job.find("id").text)
    if id in specific_ids:
        specific_ids.remove(id)
        return True
    return False


def check_selector(job, selector):
    path, pattern = selector
    return fnmatch.fnmatch(job.find(path).text, pattern)


specific_ids = parseIds(OPTIONS.job_ids)
selector = parseSelector(OPTIONS.selector)


selected_jobs = []
do_id_check = len(specific_ids) > 0
print("Reading in {}".format(OPTIONS.j_input.name))
Tree = lxml.parse(OPTIONS.j_input.name)
Root = Tree.getroot()
for job in Root.iter('job'):

    id_check = True
    selector_check = True
    if do_id_check:
        id_check = check_id(job, specific_ids)
    if selector:
        selector_check = check_selector(job, selector)
    if id_check and selector_check:
        selected_jobs.append(job)

if(selected_jobs):
    print("Writing to {}".format(OPTIONS.j_output.name))
    Newroot = lxml.Element("jobs")
    for job in selected_jobs:
        Newroot.append(job)
    Newtree = lxml.ElementTree(Newroot)
    Newtree.write(OPTIONS.j_output.name, pretty_print=True)
else:
    print("No jobs in the jobfile match the criteria.")

sys.exit(0)