source: branches/dev-5819/Python/src/pyjmi/optimization/thread_feval.py @ 13824

Last change on this file since 13824 was 13824, checked in by aramle, 8 weeks ago

#5819 Updating file to open to be Python 3 compatible.

File size: 3.5 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4#    Copyright (C) 2014 Modelon AB
5#
6#    This program is free software: you can redistribute it and/or modify
7#    it under the terms of the GNU General Public License as published by
8#    the Free Software Foundation, version 3 of the License.
9#
10#    This program is distributed in the hope that it will be useful,
11#    but WITHOUT ANY WARRANTY; without even the implied warranty of
12#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13#    GNU General Public License for more details.
14#
15#    You should have received a copy of the GNU General Public License
16#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17import threading
18import os
19import sys
20import numpy as N
21
22class FevalThread(threading.Thread):
23    def __init__(self,x,func_file_name,dir_name,debug):
24        self.x = x
25        self.func_file_name = func_file_name
26        self.dir_name = dir_name
27        self.debug = debug
28        threading.Thread.__init__(self)
29
30    def run(self):
31        curr_dir = os.path.dirname(os.path.abspath(__file__))
32        l = list()
33        for val in self.x:
34            l.append(str(val))
35        x_string = ' '.join(l)
36        eval_path = os.path.join(curr_dir, 'func_eval.py')
37        if not os.path.isfile(eval_path):
38            eval_path = os.path.join(curr_dir, 'func_eval.pyc')
39        python_path = sys.executable
40        cmd = ' '.join([python_path, eval_path, x_string, self.func_file_name, self.dir_name])
41        if self.debug:
42            outfile = 'out_file_' + self.dir_name + '.txt'
43            errfile = 'err_file_' + self.dir_name + '.txt'
44            cmd = ' '.join([cmd, '>', outfile, '2>', errfile])
45           
46        self.retval = os.system(cmd)
47
48def feval(func_file_name,x,debug):
49        """
50        Evaluate a function in x in a separate process. If x contains multiple
51        points (rows) then the function evaluation in each point is performed
52        in a separate process.
53       
54        Parameters::
55       
56                func_file_name --
57                        string
58                        The name of a python file containing the function definition.
59                        The function in the file must have the same name as the file
60                        itself (without ".py").
61                       
62                x --
63                        ndarray (1 or 2 dimensions)
64                        The point(s) in which to evaluate the function.
65                       
66                debug --
67                        bool
68                        Set to True to get separate error and output files for each
69                        separate process.
70               
71        Returns::
72       
73                fval --
74                        float or ndarray (1 dimension)
75                        The function value(s) in x.
76        """
77       
78        # Evaluation in one point only
79        if N.ndim(x) == 1:
80                dir_name = 'dir'
81                th = FevalThread(x,func_file_name,dir_name,debug)
82                th.start()
83                th.join()
84                retval = th.retval
85                if retval != 0:
86                        raise OSError('Something went wrong with the function evaluation: os.system did not return 0.')
87                f_string = open(dir_name+'/f_value.txt').read()
88                fval = eval(f_string)
89       
90        # Evaluation in several points 
91        else:
92                m = len(x)
93                fval = N.zeros(m)
94                # Create and start threads
95                threads = []
96                for i in range(m):
97                        dir_name = 'dir_'+str(i+1)
98                        th = FevalThread(x[i],func_file_name,dir_name,debug)
99                        th.start()
100                        threads.append(th)     
101                # Wait for all threads to complete
102                for t in threads:
103                    t.join()   
104                # Read from result files
105                for i in range(m):
106                        retval = threads[i].retval
107                        if retval != 0:
108                                raise OSError('Something went wrong with the function evaluation: os.system did not return 0.')
109                        dir_name = 'dir_'+str(i+1)
110                        f_string = open(dir_name+'/f_value.txt').read()
111                        fval[i] = eval(f_string)
112       
113        return fval
Note: See TracBrowser for help on using the repository browser.