예제 #1
0
    def preprocess(self):
        """Comment"""
            
		# Following code only runs when project uses template/sample files
        if self.jobdict:
            # Get template file search string and look for them
            tmp_sstr = self.config['templatefile_searchstring']	
            temp_abspathlist = util.get_file_paths([tmp_sstr], self.abspath)
	        # Once we have a list of paths to template files, loop through 
            for temp_abspath in temp_abspathlist:
                # Build name for simulation file 
                #(same name as tmp, without search string)
                match = re.search(r'(.*)' + tmp_sstr + r'(.*)', 
                            os.path.basename(temp_abspath))
                if match:
                    siminput_abspath = os.path.join(
                                           os.path.dirname(temp_abspath), 
                                           match.group(1) + match.group(2))
                # Replace parameters with sample values in template file 
                with open(temp_abspath, 'rU') as tmp_f:
                    # Read the entire file and store it in a temp variable
                    temp = tmp_f.read()
                    # Find parameters to be replaced in template files and
                    # replace them
                    for p in self.temp_params:
		                # If search string is found, replace with 
                        # corresponding parameter value			
                        temp = temp.replace('%' + p + '%', 
                                   str(self.jobdict[p]))
                    # Replace special &PROJECT_DIR& var with cur dir path 
                    temp = temp.replace('&PROJ_DIR&', str(self.abspath))
                    # Proper way to manage existing model files
                    if os.path.exists(siminput_abspath):
                        try:
                            os.remove(siminput_abspath)
                        except:
                            print("Exception: ", str(sys.exc_info()))
                    # Open output file and write replaced content to it
                    with open(siminput_abspath, 'w') as sim_f:
                        sim_f.write(temp)
                # Remove template file, which is not needed anymore
                try:
                    os.remove(temp_abspath)
                except:
                    print("Exception: ", str(sys.exc_info()))            
			
            # If simtool is TRNSYS, generate TRNBUILD shading/insolation, 
            # view factor matrices and IDF file corresponding to .b17 file
            if self.simtool == 'TRNSYS':
                wait_t = uniform(0,3)
                #print("Waiting %.2f seconds before calling TRNBUILD" % wait_t)
                sleep(wait_t)
                model_abspath = os.path.join(self.abspath, self.model_relpath)
                trnsys_pre.gen_type56(model_abspath)
            # If simtool is DAYSIM, rotate scene and generate material and
            # geometry radiance files required by Daysim
            if self.simtool == 'DAYSIM':
                model_abspath = os.path.join(self.abspath, self.model_relpath)
                daysim_pre.rotate_scene(model_abspath)
                daysim_pre.radfiles2daysim(model_abspath)
예제 #2
0
파일: core.py 프로젝트: LuisM78/PyBPS
    def close(self):
        """Close job by copying result and log files to main results folder 
        and delete temporary job folder"""

        # Parse info about simulation run from TRNSYS lst and log files
        if self.simtool == 'TRNSYS':
            # Get TRNSYS error/warning count from log file
            log_fname = os.path.splitext(self.model_relpath)[0] + '.log'
            log_abspath = os.path.join(self.abspath, log_fname)
            self.runsumdict = trnsys_post.parse_log(log_abspath)

        # Save jobID and simulation time in run summary dict
        self.runsumdict['JobID'] = self.seriesID + '_' + self.jobID
        self.runsumdict['SimulTime(sec)'] = self.simtime

        # Create a subfolder in main results folder to store simulation results
        simresdir_abspath = os.path.join(self.resultsdir_abspath,
                                         self.seriesID + '_' + self.jobID)
        util.tmp_dir('create', simresdir_abspath)

        # Get extensions of results files
        results_ext = self.config['resultfile_extensions']
        results_ext = results_ext.split(',')
        # Get list of paths to job results files
        jobresfile_abspathlist = util.get_file_paths(results_ext, self.abspath)
        # Copy job results files to simulation results folder
        for jobresfile_abspath in jobresfile_abspathlist:
            copy(jobresfile_abspath, simresdir_abspath)

        # Get extensions of log files
        log_ext = self.config['logfile_extensions']
        log_ext = log_ext.split(',')
        # Get list of paths to job log files
        joblogfile_abspathlist = util.get_file_paths(log_ext, self.abspath)
        # Copy log files to simulation results folder
        for joblogfile_abspath in joblogfile_abspathlist:
            copy(joblogfile_abspath, simresdir_abspath)

        # Remove temporary simulation folder
        util.tmp_dir('remove', self.abspath)
예제 #3
0
    def close(self):
        """Close job by copying results and log file to main results
        directory and removing temporary job directory"""
	
        # Parse info about simulation run from TRNSYS lst and log files
        if self.simtool == 'TRNSYS':
            # Get TRNSYS error/warning count from log file
            log_fname = os.path.splitext(self.model_relpath)[0]+'.log'
            log_abspath = os.path.join(self.abspath, log_fname)
            self.runsumdict = trnsys_post.parse_log(log_abspath)
	
        # Save jobID and simulation time in run summary dict
        self.runsumdict['JobID'] = self.seriesID + '_' + '%0*d' % (5, self.jobID)
        self.runsumdict['SimulTime(sec)'] = self.simtime
	
        # Create a subfolder in main results folder to store simulation results
        simresdir_abspath = os.path.join(self.resultsdir_abspath, 
                             self.seriesID + '_' + '%0*d' % (5, self.jobID))
        util.tmp_dir('create', simresdir_abspath)
				
        # Get extensions of results files
        results_ext = self.config['resultfile_extensions']
        results_ext = results_ext.split(',')	
        # Get list of paths to job results files
        jobresfile_abspathlist = util.get_file_paths(results_ext, self.abspath)
	    # Copy job results files to simulation results folder
        for jobresfile_abspath in jobresfile_abspathlist:
            copy(jobresfile_abspath, simresdir_abspath)
	
        # Get extensions of log files
        log_ext = self.config['logfile_extensions']
        log_ext = log_ext.split(',')
        # Get list of paths to job log files
        joblogfile_abspathlist = util.get_file_paths(log_ext, self.abspath)
	    # Copy log files to simulation results folder
        for joblogfile_abspath in joblogfile_abspathlist:
            copy(joblogfile_abspath, simresdir_abspath)

        # Remove temporary simulation folder
        util.tmp_dir('remove', self.abspath)
예제 #4
0
    def get_sample(self, src='samplefile', seriesID=None):
        """Get sample from external source (csv file or sqlite database)

        Args:
            src: external source that contains sample, either
                - "samplefile" (in CSV format)
                - "database" (PyBPS-generated SQlite format, NOT IMPLEMENTED!)
            seriesID: when getting sample from database, allows to specify the
                seriesID of the sample (database can contain multiple samples)

        """

        # Empty any previously created jobs list
        self.sample = []

        if src == 'samplefile':
            # Get information needed to find jobs file in folder
            samp_sstr = self.config['samplefile_searchstring']
            samp_abspathlist = util.get_file_paths([samp_sstr], self.abspath)

            # Check if there is no more than 1 sample file in directory
            if len(samp_abspathlist) > 0:
                samp_relpathlist = [
                    os.path.relpath(fname, self.abspath)
                    for fname in samp_abspathlist
                ]
                if len(samp_relpathlist) > 1:
                    print('\nVarious sample files found in directory' +
                          '\nPlease select sample to be used in current run:')
                    for i, path in enumerate(samp_relpathlist):
                        print("(%d) %s" % (i + 1, os.path.splitext(path)[0]))
                    select = int(raw_input("Sample ID number: "))
                    self.samp_relpath = samp_relpathlist[select - 1]
                    print("You selected %s" % self.samp_relpath)
                else:
                    self.samp_relpath = samp_relpathlist[0]
                # Build list of dicts with parameter values for all job runs
                samp_abspath = os.path.join(self.abspath, self.samp_relpath)
                sample_data = pd.read_csv(samp_abspath)
                self.sample = list(sample_data.transpose().to_dict().values())
                # Add model and sample file names as parameters
                for s in self.sample:
                    s['ModelFile'] = self.model_relpath
                    s['SampleFile'] = self.samp_relpath
            else:
                sys.stderr.write(
                    "Could not find any sample file in " +
                    "project directory\nPlease put a \'" + samp_sstr +
                    "\' file in directory and re-run 'get_sample' method\n")
        elif src == 'database' and not seriesID:
            print("\nPlease provide a seriesID to retrieve parameter list" +
                  " from database")
예제 #5
0
파일: core.py 프로젝트: dtavan/PyBPS
    def get_sample(self, src='samplefile', seriesID=None):
        """Get sample from external source (csv file or sqlite database)

        Args:
            src: external source that contains sample, either
                - "samplefile" (in CSV format)
                - "database" (PyBPS-generated SQlite format, NOT IMPLEMENTED!)
            seriesID: when getting sample from database, allows to specify the
                seriesID of the sample (database can contain multiple samples)

        """

        # Empty any previously created jobs list
        self.sample = []

        if src == 'samplefile':
		    # Get information needed to find jobs file in folder
            samp_sstr = self.config['samplefile_searchstring']
            samp_abspathlist = util.get_file_paths([samp_sstr], self.abspath)

            # Check if there is no more than 1 sample file in directory
            if len(samp_abspathlist) > 0:
                samp_relpathlist = [os.path.relpath(fname, self.abspath)
                                       for fname in samp_abspathlist]
                if len(samp_relpathlist) > 1:
                    print('\nVarious sample files found in directory' +
                        '\nPlease select sample to be used in current run:')
                    for i, path in enumerate(samp_relpathlist):
                        print("(%d) %s" % (i+1, os.path.splitext(path)[0]))
                    select = int(raw_input("Sample ID number: "))
                    self.samp_relpath = samp_relpathlist[select - 1]
                    print("You selected %s" % self.samp_relpath)
                else:
                    self.samp_relpath = samp_relpathlist[0]
                # Build list of dicts with parameter values for all job runs
                samp_abspath = os.path.join(self.abspath, self.samp_relpath)
                sample_data = pd.read_csv(samp_abspath)
                self.sample = list(sample_data.transpose().to_dict().values())
                # Add model and sample file names as parameters
                for s in self.sample:
                    s['ModelFile'] = self.model_relpath
                    s['SampleFile'] = self.samp_relpath
            else:
                sys.stderr.write("Could not find any sample file in " +
                    "project directory\nPlease put a \'" + samp_sstr +
                    "\' file in directory and re-run 'get_sample' method\n")
        elif src == 'database' and not seriesID:
            print("\nPlease provide a seriesID to retrieve parameter list" +
                " from database")
예제 #6
0
    def results2df(self):
        """Create pandas DataFrame from simulation results"""

        # Get extensions of results files
        results_ext = self.config['resultfile_extensions']
        results_ext = results_ext.split(',')	
        # Get list of paths to results files
        results_abspathlist = util.get_file_paths(results_ext, 
                                  self.resultsdir_abspath)
        # Go through all results files from all simulated jobs
        df_exists = False
        for results_abspath in results_abspathlist:
            # Get Series/Job IDs 
            match = re.search(r'([A-Z0-9]{8})_[0-9]{5}', results_abspath)
            if match:
                # Only parse results within sub-folders pertaining to
                # current batch run identified by seriesID
                if match.group(1) == self.seriesID:
                    # Build a 'pandas' dataframe with results from all jobs
                    if self.simtool == 'TRNSYS':
                        dict_list = trnsys_post.parse_type46(
                                               results_abspath)
                    elif self.simtool == 'DAYSIM':
                        if (os.path.splitext(os.path.basename(
                            results_abspath))[1] == '.htm'):
                            dict_list = daysim_post.parse_el_lighting(
                                            results_abspath)
                    if dict_list:
                        for dict in dict_list:
                            dict['JobID'] = match.group()
                        colnames = dict_list[0].keys()
                        colnames.sort(key = sort_key_dfcolnames)
                        if not df_exists:
                            self.results_df = pd.DataFrame(dict_list, 
                                              columns=colnames)
                            df_exists = True
                        else:
                            df = pd.DataFrame(dict_list, columns=colnames)
                            self.results_df = self.results_df.append(df, 
                                                  ignore_index=True)
                    else:
                        print("No results dataframe created")                    
예제 #7
0
파일: core.py 프로젝트: LuisM78/PyBPS
    def results2df(self):
        """Create pandas DataFrame from simulation results"""

        # Get extensions of results files
        results_ext = self.config['resultfile_extensions']
        results_ext = results_ext.split(',')
        # Get list of paths to results files
        results_abspathlist = util.get_file_paths(results_ext,
                                                  self.resultsdir_abspath)
        # Go through all results files from all simulated jobs
        df_exists = False
        for results_abspath in results_abspathlist:
            # Get Series/Job IDs
            match = re.search(r'([A-Z0-9]{8})_[0-9]{5}', results_abspath)
            if match:
                # Only parse results within sub-folders pertaining to
                # current batch run identified by seriesID
                if match.group(1) == self.seriesID:
                    # Build a 'pandas' dataframe with results from all jobs
                    if self.simtool == 'TRNSYS':
                        dict_list = trnsys_post.parse_type46(results_abspath)
                    elif self.simtool == 'DAYSIM':
                        if (os.path.splitext(os.path.basename(results_abspath))
                            [1] == '.htm'):
                            dict_list = daysim_post.parse_el_lighting(
                                results_abspath)
                    if dict_list:
                        for dict in dict_list:
                            dict['JobID'] = match.group()
                        colnames = dict_list[0].keys()
                        colnames.sort(key=sort_key_dfcolnames)
                        if not df_exists:
                            self.results_df = pd.DataFrame(dict_list,
                                                           columns=colnames)
                            df_exists = True
                        else:
                            df = pd.DataFrame(dict_list, columns=colnames)
                            self.results_df = self.results_df.append(
                                df, ignore_index=True)
                    else:
                        print("No results dataframe created")
예제 #8
0
    def get_sample(self, src='samplefile', seriesID=None):
        """Comment"""
		
        # Empty any previously created jobs list
        self.sample = []
		
        if src == 'samplefile':
		    # Get information needed to find jobs file in folder
            samp_sstr = self.config['samplefile_searchstring']
            samp_abspathlist = util.get_file_paths([samp_sstr], self.abspath)
            
            # Check if there is no more than 1 sample file in directory
            if len(samp_abspathlist) > 0:
                samp_relpathlist = [os.path.relpath(fname, self.abspath) 
                                       for fname in samp_abspathlist]
                if len(samp_relpathlist) > 1:
                    print('\nVarious sample files found in directory' +
                        '\nPlease select sample to be used in current run:')
                    for i, path in enumerate(samp_relpathlist):
                        print("(%d) %s" % (i+1, os.path.splitext(path)[0]))
                    select = int(raw_input("Sample ID number: "))
                    self.samp_relpath = samp_relpathlist[select - 1]
                    print("You selected %s" % self.samp_relpath)
                else:					
                    self.samp_relpath = samp_relpathlist[0]
                # Build list of dicts with parameter values for all job runs
                samp_abspath = os.path.join(self.abspath, self.samp_relpath)
                self.sample = util.csv2dict(samp_abspath)
                # Add model and sample file names as parameters
                for s in self.sample:
                    s['ModelFile'] = self.model_relpath
                    s['SampleFile'] = self.samp_relpath					
            else:
                sys.stderr.write("Could not find any sample file in " +
                    "project directory\nPlease put a \'" + samp_sstr +
                    "\' file in directory and re-run 'get_sample' method\n")                
        elif src == 'database' and not seriesID:
            print("\nPlease provide a seriesID to retrieve parameter list" +
                " from database")
예제 #9
0
파일: core.py 프로젝트: LuisM78/PyBPS
    def preprocess(self, pretool=False):
        """Preprocess simulation job
        
        Replaces parameters found in template files with values from sample.
        When using TRNSYS simulation tool, if a Type56 is found in deck,
            the "gen_type56" preprocessing function is called to generate the
            necessary matrices for the 3D model.
        When using DAYSIM simulation tool, if the scene rotation angel is
            different from zero, the "rotate_scene" function is called.
        Args:
            pretool: if True, activates tool-specific preprocessing
                For example, matrix generation for TRNSYS Type56 or
                scene rotation for DAYSIM
        
        """

        # Following code only runs when project uses template/sample files
        if self.jobdict:
            # Get template file search string and look for them
            tmp_sstr = self.config['templatefile_searchstring']
            temp_abspathlist = util.get_file_paths([tmp_sstr], self.abspath)
            # Once we have a list of paths to template files, loop through
            for temp_abspath in temp_abspathlist:
                # Build name for simulation file
                #(same name as tmp, without search string)
                match = re.search(r'(.*)' + tmp_sstr + r'(.*)',
                                  os.path.basename(temp_abspath))
                if match:
                    siminput_abspath = os.path.join(
                        os.path.dirname(temp_abspath),
                        match.group(1) + match.group(2))
                # Replace parameters with sample values in template file
                with open(temp_abspath, 'rU') as tmp_f:
                    # Read the entire file and store it in a temp variable
                    temp = tmp_f.read()
                    # Find parameters to be replaced in template files and
                    # replace them
                    for p in self.temp_params:
                        # If search string is found, replace with
                        # corresponding parameter value
                        temp = temp.replace('%' + p + '%',
                                            str(self.jobdict[p]))
                    # Replace special &PROJECT_DIR& var with cur dir path
                    temp = temp.replace('&PROJ_DIR&', str(self.abspath))
                    # Proper way to manage existing model files
                    if os.path.exists(siminput_abspath):
                        try:
                            os.remove(siminput_abspath)
                        except:
                            print("Exception: ", str(sys.exc_info()))
                    # Open output file and write replaced content to it
                    with open(siminput_abspath, 'w') as sim_f:
                        sim_f.write(temp)
                # Remove template file, which is not needed anymore
                try:
                    os.remove(temp_abspath)
                except:
                    print("Exception: ", str(sys.exc_info()))

            if pretool == True:
                # If simtool is TRNSYS, generate TRNBUILD shading/insolation,
                # view factor matrices and IDF file corresponding to .b17 file
                if self.simtool == 'TRNSYS':
                    #wait_t = uniform(0,3)
                    #print("Waiting %.2f seconds before calling TRNBUILD" % wait_t)
                    #sleep(wait_t)
                    model_abspath = os.path.join(self.abspath,
                                                 self.model_relpath)
                    trnsys_pre.gen_type56(model_abspath)
                # If simtool is DAYSIM, rotate scene and generate material and
                # geometry radiance files required by Daysim
                if self.simtool == 'DAYSIM':
                    model_abspath = os.path.join(self.abspath,
                                                 self.model_relpath)
                    daysim_pre.rotate_scene(model_abspath)
                    daysim_pre.radfiles2daysim(model_abspath)
예제 #10
0
파일: core.py 프로젝트: LuisM78/PyBPS
    def check(self):
        """Check for simulation files in project directory
        
        Checks whether the necessary files are found in the indicated project
        directory. Based on file extensions, simulation tool to be used is
        detected.
        
        Args:
            No args
            
        Returns:
            Warning messages if some important files are missing that make it
            impossible to run the parametric simulation project
        
        """

        # Get information from config file
        conf = SafeConfigParser()
        conf_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                 'config.ini')
        for file in os.listdir(self.abspath):
            if file.endswith('config.ini'):
                conf_file = os.path.join(self.abspath, file)
                print('Custom ' + file + ' config file will ' +
                      'be used instead of default config.ini')
        conf.read(conf_file)
        sections = conf.sections()

        # Detect simulation tool used for current simulation job and check if
        # basic simulation input files are there
        found = 0  # Variable to store whether a simulation project was found

        for section in sections:
            # Get information needed to find model files in folder
            model_ext = conf.get(section, 'ModelFile_Extensions')
            model_ext = model_ext.split(',')
            tmp_sstr = conf.get(section, 'TemplateFile_SearchString')
            # Check if we can find a model file for the selected simtool
            model_abspathlist = util.get_file_paths(model_ext, self.abspath)
            if model_abspathlist:
                model_relpathlist = [
                    os.path.relpath(fname, self.abspath)
                    for fname in model_abspathlist
                ]
                # If another simtool was already detected, raise an error
                if found > 0:
                    sys.stderr.write(
                        "\nInput files for different BPS " +
                        "tools found\nNo more than 1 kind of simulation " +
                        "file allowed in a same folder")
                    sys.exit(1)
                # If not, store the name of detected simulation tool
                self.simtool = section
                print(self.simtool + " simulation project found in directory")
                # Strip search string from model file names
                for i, relpath in enumerate(model_relpathlist):
                    match = re.search(r'(.*)' + tmp_sstr + r'(.*)',
                                      os.path.basename(relpath))
                    if match:
                        relpath = os.path.join(os.path.dirname(relpath),
                                               match.group(1) + match.group(2))
                        model_relpathlist[i] = relpath
                # If more than 1 model file found, ask user to select 1 model
                if len(model_relpathlist) > 1:
                    if (len(model_relpathlist) == 2
                            and model_relpathlist[0] == model_relpathlist[1]):
                        self.model_relpath = model_relpathlist[0]
                    else:
                        print(
                            '\nVarious model files found in directory' +
                            '\nPlease select model to be used in current run:')
                        print("(%d) %s" % (0, 'all models'))
                        for i, path in enumerate(model_relpathlist):
                            print(
                                "(%d) %s" %
                                (i + 1, os.path.splitext(
                                    os.path.basename(path))[0]))
                        select = int(raw_input("Model ID number: "))
                        if select == 0:
                            self.model_relpath = model_relpathlist
                            print('You selected all models')
                        else:
                            self.model_relpath = model_relpathlist[select - 1]
                            print("You selected %s" % self.model_relpath)
                else:
                    self.model_relpath = model_relpathlist[0]
                found += 1

        if found == 0:
            sys.stderr.write(
                "\nNo BPS project found in the specified " +
                "folder\nPlease check the folder path is correct and " +
                "simulation files are in given folder")
            sys.exit(1)

        # Once simulation tool has been detected, store config info in 'config'
        items = conf.items(self.simtool)
        for (name, value) in items:
            self.config[name] = value

# Once we have found a simulation project and stored config info,
# let's see if we can find a template file for this project
        tmpfile_sstr = self.config['templatefile_searchstring']
        temp_abspathlist = util.get_file_paths([tmpfile_sstr], self.abspath)

        if temp_abspathlist:
            self._batch = True
            self.temp_relpaths = [
                os.path.relpath(f_name, self.abspath)
                for f_name in temp_abspathlist
            ]
            # If template(s) found, check directory for sample file
            self.get_sample()
        # Identify project as batch run if user selected to run all models
        elif len(self.model_relpath) > 1:
            print("All model files will be run in batch mode when 'run' " +
                  "method is called.")
            self._batch = True
            # Add model and sample files relative paths as parameters
            for i, (m,
                    s) in enumerate(zip(self.model_relpath,
                                        self.samp_relpath)):
                self.sample.append({})
                self.sample[i]['ModelFile'] = m
                self.sample[i]['SampleFile'] = s
# If no template file was found, give message to user
        else:
            print("No template found. BPS project identified as single run")
예제 #11
0
    def check(self):
        """Comment"""
	
	    # Get information from config file
        conf = SafeConfigParser()
        conf_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
            'config.ini')
        conf.read(conf_file)
        sections = conf.sections()
		
        # Detect simulation tool used for current simulation job and check if
        # basic simulation input files are there
        found = 0 # Variable to store whether a simulation project was found

        for section in sections:
		    # Get information needed to find model files in folder
            model_ext = conf.get(section, 'ModelFile_Extensions')
            model_ext = model_ext.split(',')
            tmp_sstr = conf.get(section, 'TemplateFile_SearchString')
	        # Check if we can find a model file for the selected simtool
            model_abspathlist = util.get_file_paths(model_ext, self.abspath)
            if model_abspathlist:
                model_relpathlist = [os.path.relpath(fname, self.abspath)
                                        for fname in model_abspathlist]
                # If another simtool was already detected, raise an error            
                if found > 0:
                    sys.stderr.write("\nInput files for different BPS " +
                        "tools found\nNo more than 1 kind of simulation " +
                        "file allowed in a same folder")
                    sys.exit(1)
                # If not, store the name of detected simulation tool
                self.simtool = section
                print(self.simtool + " simulation project found in directory")
                # Strip search string from model file names
                for i, relpath in enumerate(model_relpathlist):
                    match = re.search(r'(.*)' + tmp_sstr + r'(.*)',
                                os.path.basename(relpath))
                    if match:
                        relpath = os.path.join(os.path.dirname(
                            relpath), match.group(1) + match.group(2))
                        model_relpathlist[i] = relpath
                # If more than 1 model file found, ask user to select 1 model
                if len(model_relpathlist) > 1:
                    if (len(model_relpathlist) == 2 and 
                           model_relpathlist[0] == model_relpathlist[1]):
                        self.model_relpath = model_relpathlist[0]
                    else:
                        print('\nVarious model files found in directory' +
                            '\nPlease select model to be used in current run:')
                        print("(%d) %s" % (0, 'all models'))
                        for i, path in enumerate(model_relpathlist):
                            print("(%d) %s" % (i+1, os.path.splitext(
                                os.path.basename(path))[0]))
                        select = int(raw_input("Model ID number: "))
                        if select == 0:
                            self.model_relpath = model_relpathlist
                            print('You selected all models')
                        else:
                            self.model_relpath = model_relpathlist[select - 1]
                            print("You selected %s" % self.model_relpath)
                else:
                    self.model_relpath = model_relpathlist[0]
                found += 1

        if found == 0:
            sys.stderr.write("\nNo BPS project found in the specified " +
                "folder\nPlease check the folder path is correct and " +
                "simulation files are in given folder")
            sys.exit(1)
				
        # Once simulation tool has been detected, store config info in 'config'
        items = conf.items(self.simtool)
        for (name, value) in items:
            self.config[name] = value
				
		# Once we have found a simulation project and stored config info,
        # let's see if we can find a template file for this project	
        tmpfile_sstr = self.config['templatefile_searchstring']
        temp_abspathlist = util.get_file_paths([tmpfile_sstr], self.abspath)
        
        if temp_abspathlist:
            self._batch = True
            self.temp_relpaths = [os.path.relpath(f_name, self.abspath) 
                                     for f_name in temp_abspathlist]            
	        # If template(s) found, check directory for sample file 
            self.get_sample()
        # Identify project as batch run if user selected to run all models
        elif len(self.model_relpath) > 1:
            print("All model files will be run in batch mode when 'run' " +
                "method is called.")
            self._batch = True
            # Add model and sample files relative paths as parameters
            for i,(m,s) in enumerate(zip(self.model_relpath,self.samp_relpath)):
                self.sample.append({})
                self.sample[i]['ModelFile'] = m
                self.sample[i]['SampleFile'] = s				
		# If no template file was found, give message to user
        else:
            print("No template found. BPS project identified as single run")
예제 #12
0
파일: core.py 프로젝트: dtavan/PyBPS
    def preprocess(self, pretool=False):
        """Preprocess simulation job

        Replaces parameters found in template files with values from sample.
        When using TRNSYS simulation tool, if a Type56 is found in deck,
            the "gen_type56" preprocessing function is called to generate the
            necessary matrices for the 3D model.
        When using DAYSIM simulation tool, if the scene rotation angel is
            different from zero, the "rotate_scene" function is called.
        Args:
            pretool: if True, activates tool-specific preprocessing
                For example, matrix generation for TRNSYS Type56 or
                scene rotation for DAYSIM

        """

		# Following code only runs when project uses template/sample files
        if self.jobdict:
            # Get template file search string and look for them
            tmp_sstr = self.config['templatefile_searchstring']
            temp_abspathlist = util.get_file_paths([tmp_sstr], self.abspath)
	        # Once we have a list of paths to template files, loop through
            for temp_abspath in temp_abspathlist:
                # Build name for simulation file
                #(same name as tmp, without search string)
                match = re.search(r'(.*)' + tmp_sstr + r'(.*)',
                            os.path.basename(temp_abspath))
                if match:
                    siminput_abspath = os.path.join(
                                           os.path.dirname(temp_abspath),
                                           match.group(1) + match.group(2))
                # Replace parameters with sample values in template file
                with open(temp_abspath, 'rU') as T:
                    # Read the entire file and store it in a temp variable
                    template = Template(T.read())
                    # Substitute the dollar-sign variables with values
                    temp = template.safe_substitute(self.jobdict)
                    # Replace special &PROJECT_DIR& var with cur dir path
                    #temp = temp.replace('&PROJ_DIR&', str(self.abspath))
                    # Proper way to manage existing model files
                    if os.path.exists(siminput_abspath):
                        try:
                            os.remove(siminput_abspath)
                        except:
                            print("Exception: ", str(sys.exc_info()))
                    # Open output file and write replaced content to it
                    with open(siminput_abspath, 'w') as sim_f:
                        sim_f.write(temp)
                # Remove template file, which is not needed anymore
                try:
                    os.remove(temp_abspath)
                except:
                    print("Exception: ", str(sys.exc_info()))

            if pretool == True:
                # If simtool is TRNSYS, generate TRNBUILD shading/insolation,
                # view factor matrices and IDF file corresponding to .b17 file
                if self.simtool == 'TRNSYS':
                    #wait_t = uniform(0,3)
                    #print("Waiting %.2f seconds before calling TRNBUILD" % wait_t)
                    #sleep(wait_t)
                    model_abspath = os.path.join(self.abspath, self.model_relpath)
                    trnsys_pre.gen_type56(model_abspath)
                # If simtool is DAYSIM, rotate scene and generate material and
                # geometry radiance files required by Daysim
                if self.simtool == 'DAYSIM':
                    model_abspath = os.path.join(self.abspath, self.model_relpath)
                    daysim_pre.rotate_scene(model_abspath)
                    daysim_pre.radfiles2daysim(model_abspath)