def step(self, timeStamp):
        print('TORIC_basic.step() called')
        services = self.services
        workdir = services.get_working_dir()

        # Get global configuration parameters (none for this example)

        # Get component-specific configuration parameters.
        BIN_PATH = config.get_component_param(self, services, 'BIN_PATH')
        NPROC = config.get_component_param(self, services, 'NPROC')
        toric_bin = config.get_component_param(self, services, 'EXECUTABLE')

        # Copy state files over to working directory (none for this example)

        # Get input files
        try:
            services.stage_input_files(self.INPUT_FILES)
        except Exception:
            print('Error in call to stageInputFiles()')
            self.services.error('Error in call to stageInputFiles()')
            raise

        try:
            self.toric_log = os.path.join(workdir, 'log.toric')
        except:
            logMsg = 'rf_ic_toric_mcmd: error in getting log.toric path'
            self.services.exception(logMsg)
            raise
        toric_log = self.toric_log

        # Launch TORIC executable
        print(('toric processors = ', self.NPROC))
        cwd = services.get_working_dir()
        task_id = services.launch_task(self.NPROC,
                                       cwd,
                                       toric_bin,
                                       logfile=toric_log)
        retcode = services.wait_task(task_id)
        if (retcode != 0):
            logMsg = 'Error executing command: ' + toric_bin
            self.services.error(logMsg)
            raise Exception(logMsg)

        # Rename default fort.* to expected names by component method as of toric5 r918 from ipp
        os.rename('fort.9', 'toric_cfg.nc')
        os.rename('fort.21', 'toric.nc')

        # "Archive" output files in history directory
        try:
            services.stage_output_files(timeStamp, self.OUTPUT_FILES)
        except Exception:
            message = 'Error in call to stage_output_files()'
            print(message)
            services.error(message)
            raise

        return
    def step(self, timeStamp):
        print('GENRAY_basic.step() called')
        services = self.services

    # Get global configuration parameters (none for this example)
 
    # Get component-specific configuration parameters.
        BIN_PATH = config.get_component_param(self, services, 'BIN_PATH')
        NPROC = config.get_component_param(self, services, 'NPROC')
        EXECUTABLE = config.get_component_param(self, services, 'EXECUTABLE')
        GENRAYNML = config.get_component_param(self, services, 'GENRAYNML')

    # Copy state files over to working directory (none for this example)
      
    # Get input files  
        try:
          services.stage_input_files(self.INPUT_FILES)
        except Exception:
          print('Error in call to stageInputFiles()')
          self.services.error('Error in call to stageInputFiles()')
          raise

    # Copy genray input namelist file to generic name "genray.dat"
        try:
            shutil.copyfile(GENRAYNML, 'genray.dat')
        except IOError as xxx_todo_changeme:
            (errno, strerror) = xxx_todo_changeme.args
            print('Error copying file %s to %s' % (GENRAYNML, 'genray.dat'), strerror)
            services.error('Error copying GENRAYNM -> genray.dat')
            raise Exception('Error copying GENRAYNM -> genray.dat')

      
#     Launch GENRAY - N.B: Path to executable is in config parameter EXECUTABLE
        print('rf_genray: launching GENRAY')
        cwd = services.get_working_dir()
        task_id = services.launch_task(self.NPROC, cwd, self.EXECUTABLE, logfile='log.genray')
        retcode = services.wait_task(task_id)
        if (retcode != 0):
            print('Error executing command: ', self.EXECUTABLE)
            services.error('Error executing genray')
            raise Exception('Error executing genray')
        print('rf_genray: finished GENRAY')

# "Archive" output files in history directory
        try:
            services.stage_output_files(timeStamp, self.OUTPUT_FILES)
        except Exception:
            message = 'Error in call to stage_output_files()'
            print(message)
            services.error(message)
            raise

        return
    def step(self, timeStamp):
        print('CQL3D_basic.step() called')
        services = self.services

    # Get global configuration parameters (none for this example)
 
    # Get component-specific configuration parameters.
        BIN_PATH = config.get_component_param(self, services, 'BIN_PATH')
        NPROC = config.get_component_param(self, services, 'NPROC')
        EXECUTABLE = config.get_component_param(self, services, 'EXECUTABLE')

    # Copy state files over to working directory (none for this example)
      
    # Get input files  
        try:
          services.stage_input_files(self.INPUT_FILES)
        except Exception:
          print('Error in call to stageInputFiles()')
          self.services.error('Error in call to stageInputFiles()')
          raise
      
#     Launch CQL3D - N.B: Path to executable is in config parameter EXECUTABLE
        print('rf_CQL3D: launching CQL3D')
        cwd = services.get_working_dir()
        task_id = services.launch_task(self.NPROC, cwd, self.EXECUTABLE, logfile='log.CQL3D')
        retcode = services.wait_task(task_id)
        if (retcode != 0):
            print('Error executing command: ', CQL3D_bin)
            services.error('Error executing CQL3D')
            raise Exception('Error executing CQL3D')
        print('rf_CQL3D: finished CQL3D')

# "Archive" output files in history directory
        try:
            services.stage_output_files(timeStamp, self.OUTPUT_FILES)
        except Exception:
            message = 'Error in call to stage_output_files()'
            print(message)
            services.error(message)
            raise

        return
Ejemplo n.º 4
0
    def step(self, timeStamp):
        print('genray.step() called')

        if (self.services is None):
            print('Error in genray: step (): No services')
            raise Exception('Error in genray: step (): No services')
        services = self.services
        global programming, times_parameters_list

        prepare_input_bin = os.path.join(self.BIN_PATH, 'prepare_genray_input')
        process_output_bin = os.path.join(
            self.BIN_PATH, 'process_genray_output')

    # Copy plasma state files over to working directory
        try:
            services.stage_plasma_state()
        except Exception as e:
            print('Error in call to stage_plasma_state()', e)
            services.error('Error in call to stage_plasma_state()')
            raise Exception('Error in call to stage_plasma_state()')

        cur_state_file = services.get_config_param('CURRENT_STATE')
        cur_eqdsk_file = services.get_config_param('CURRENT_EQDSK')

    # Copy current plasma state file to generic name -> cur_state.cdf
        try:
            shutil.copyfile(cur_state_file, 'cur_state.cdf')
        except IOError as e3:
            (errno, strerror) = e3.args
            print('Error copying file %s to %s' %
                  (cur_state_file, 'cur_state.cdf'), strerror)
            raise

    # Copy current eqdsk file to generic name -> eqdsk
        try:
            shutil.copyfile(cur_eqdsk_file, 'eqdsk')
        except IOError as e4:
            (errno, strerror) = e4.args
            print('Error copying file %s to %s' %
                  (cur_eqdsk_file, 'eqdsk'), strerror)
            services.error('Error copying cur_eqdsk_file -> eqdsk')
            raise Exception('Error copying cur_eqdsk_file -> eqdsk')

        rfmode = self.RFMODE
        isource_string = self.ISOURCE_STRING
        genraynml = self.GENRAYNML
        adj_read = self.ADJ_READ
        ps_add_nml = self.PS_ADD_NML

# Check if RF power is zero (or effectively zero).  If true don't run GENRAY just
# run zero_RF_power fortran code
        zero_rf_power_threshold = 0.001
        print('cur_state_file = ', cur_state_file)
        ps = Dataset(cur_state_file, 'r', format='NETCDF3_CLASSIC')
        if rfmode == 'EC':
            rf_power = ps.variables['power_ec'][:]
            ps.close()
            total_rf_power = sum(rf_power)
            print('Total EC power = ', total_rf_power)
            zero_rf_power_bin_string = 'ZERO_EC_POWER_BIN'

        # If EC parameters are programmed from config file, set parameters in
        # genray.in
            if programming:
                # Get t0 from plasma state
                ps = Dataset(cur_state_file, 'r', format='NETCDF3_CLASSIC')
                t0 = ps.variables['t0'].getValue()
                ps.close()
                # set parameters those for time = t0
                self.set_genray_EC_parameters(
                    "genray.in", t0, times_parameters_list)

        if rfmode == 'LH':
            rf_power = ps.variables['power_lh'][:]
            ps.close()
            total_rf_power = sum(rf_power)
            print('Total LH power = ', total_rf_power)
            zero_rf_power_bin_string = 'ZERO_LH_POWER_BIN'

        if rfmode not in ['EC', 'LH']:
            message = 'rf_genray.py: Unimplemented rfmode = ' + rfmode
            print(message)
            services.exception(message)
            raise

        if(total_rf_power < zero_rf_power_threshold):
            zero_RF_power = get_component_param(
                self, services, zero_rf_power_bin_string)
            retcode = subprocess.call([zero_RF_power, cur_state_file])
            if (retcode != 0):
                message = 'Error executing ', zero_rf_power_bin
                self.services.error(message)
                raise Exception(message)

            # N.B. zero_RF_power does not produce a complete set of GENRAY output
            #      files.  This causes an error in stage_output_files().  To
            #      solve this we generate a dummy set of output files here with
            #      system call 'touch'
            for file in self.OUTPUT_FILES.split():
                subprocess.call(['touch', file])

    # Or actually run GENRAY
        if(total_rf_power > zero_rf_power_threshold):
            # Call prepare_input - step
            print('rf_genray step: calling prepare_input')

            log_file = open('log_prepare_genray_input_step', 'w')
            mode = 'step'
            command = prepare_input_bin + ' ' + mode + ' ' + rfmode + ' ' +\
                isource_string + ' ' + genraynml + ' ' + adj_read + ' ' + ps_add_nml

            print('running = ', command)
            services.send_portal_event(event_type='COMPONENT_EVENT',
                                       event_comment=command)

            retcode = subprocess.call(command.split(), stdout=log_file,
                                      stderr=subprocess.STDOUT)
            if (retcode != 0):
                print('Error executing genray: ', prepare_input_bin)
                services.error('Error executing genray prepare_input')
                raise Exception('Error executing genray prepare_input')

    # Launch genray - N.B: Path to executable is in config parameter
    # GENRAY_BIN
            print('rf_genray: launching genray')
            cwd = services.get_working_dir()
            task_id = services.launch_task(
                self.NPROC, cwd, self.GENRAY_BIN, logfile='log.genray')
            retcode = services.wait_task(task_id)
            if (retcode != 0):
                print('Error executing command: ', self.GENRAY_BIN)
                services.error('Error executing genray')
                raise Exception('Error executing genray')

        # Call process_output - step
            print('rf_genray step: calling process_output')

            log_file = open('log_process_genray_output', 'w')
            mode = 'step'
            command = process_output_bin + ' ' + rfmode + ' ' + isource_string

            print('running', command)
            services.send_portal_event(event_type='COMPONENT_EVENT',
                                       event_comment=command)

            retcode = subprocess.call(command.split(), stdout=log_file,
                                      stderr=subprocess.STDOUT)
            if (retcode != 0):
                print('Error executing genray init ', process_output_bin)
                services.error('Error executing genray process_output')
                raise Exception('Error executing genray process_output')

    # Copy generic genray output to  partial plasma state file
        try:
            cwd = services.get_working_dir()
            partial_file = cwd + '/RF_EC_' + cur_state_file
            if rfmode == 'LH':
                partial_file = cwd + '/RF_LH_' + cur_state_file
            shutil.copyfile('RF_GENRAY_PARTIAL_STATE', partial_file)
        except IOError as e5:
            (errno, strerror) = e5.args
            print('Error copying file %s to %s' %
                  ('cur_state.cdf', cur_state_file), strerror)
            raise


# Merge partial plasma state containing updated EC data
        try:
            services.merge_current_plasma_state(
                partial_file, logfile='log.update_state')
            print('merged GENRAY plasma state data ', partial_file)
        except Exception as e:
            (errno, strerror) = e.args
            print('Error in call to merge_current_plasma_state(', partial_file, ')'\
            , strerror)
            self.services.error('Error in call to merge_current_plasma_state')
            raise Exception('Error in call to merge_current_plasma_state')

        # Update plasma state files in plasma_state work directory, but only dql_file
        # if there is one. This way it will not overwrite the current partial plasma state
        # that was just merged
        dql_file = get_global_param(
            self, services, 'CURRENT_DQL', optional=True)
        try:
            if dql_file is not None:
                services.update_plasma_state([dql_file])
        except Exception:
            logMsg = 'Error in call to update_plasma_state ' + cur_dql_file
            self.services.exception(logMsg)
            raise

    # Archive output files
        try:
            services.stage_output_files(timeStamp, self.OUTPUT_FILES)
        except Exception as e:
            print('Error in call to stage_output_files()', e)
            services.error('Error in call to stage_output_files()')
            raise Exception('Error in call to stage_output_files()')

#     rename the log file so that it is not appended next step
#        os.rename('log.genray', this_logfile)

        return 0
Ejemplo n.º 5
0
    def init(self, timeStamp=0):
        print('genray.init() called')

        services = self.services
        global programming, times_parameters_list

    # Get global configuration parameters
        cur_state_file = get_global_param(self, services, 'CURRENT_STATE')
        cur_eqdsk_file = get_global_param(self, services, 'CURRENT_EQDSK')
#         cql_file = get_global_param(
#             self, services, 'CURRENT_CQL', optional=True)
        dql_file = get_global_param(
            self, services, 'CURRENT_DQL', optional=True)

    # Get component-specific configuration parameters. Note: Not all of these are
    # used in 'init' but if any are missing we get an exception now instead of
    # later
        NPROC = get_component_param(self, services, 'NPROC')
        BIN_PATH = get_component_param(self, services, 'BIN_PATH')
        INPUT_FILES = get_component_param(self, services, 'INPUT_FILES')
        OUTPUT_FILES = get_component_param(self, services, 'OUTPUT_FILES')
        RESTART_FILES = get_component_param(self, services, 'RESTART_FILES')
        BIN_PATH = get_component_param(self, services, 'BIN_PATH')
        GENRAY_BIN = get_component_param(self, services, 'GENRAY_BIN')
        RFMODE = get_component_param(self, services, 'RFMODE')
        ISOURCE_STRING = get_component_param(self, services, 'ISOURCE_STRING')
        GENRAYNML = get_component_param(self, services, 'GENRAYNML')
        ADJ_READ = get_component_param(self, services, 'ADJ_READ')
        PS_ADD_NML = get_component_param(self, services, 'PS_ADD_NML')

        # Get [rf_genray_EC] programming configuration parameters, if present
        n_launchers = 0
        programming = False
        try:
            n_launchers = int(self.N_LAUNCHERS_PROGRAMMED)
        except BaseException:
            print('\nNo launcher programming in config file')

        if n_launchers > 0:
            programming = True
            print('Programming for ', n_launchers, ' launchers')
            times_parameters_list = self.time_points_and_parameters(
                n_launchers)
        else:
            print('\nUsing launcher parmeters in plasma state')

    # Copy plasma state files over to working directory
        try:
            services.stage_plasma_state()
        except Exception as e:
            print('Error in call to stage_plasma_state()', e)
            services.error('Error in call to stage_plasma_state()')
            raise Exception('Error in call to stage_plasma_state()')

    # Get input files
        try:
            services.stage_input_files(INPUT_FILES)
        except Exception as e:
            print('Error in call to stageInputFiles()', e)
            services.error('Error in call to stageInputFiles()')
            raise Exception('Error in call to stageInputFiles()')

    # Copy current plasma state file to generic name -> cur_state.cdf
        try:
            shutil.copyfile(cur_state_file, 'cur_state.cdf')
        except IOError as e:
            (errno, strerror) = e.args
            print('Error copying file %s to %s' %
                  (cur_state_file, 'cur_state.cdf'), strerror)
            services.error('Error copying cur_state_file -> cur_state.cdf')
            raise Exception('Error copying cur_state_file -> cur_state.cdf')

    # Copy current eqdsk file to generic name -> eqdsk
        try:
            shutil.copyfile(cur_eqdsk_file, 'eqdsk')
        except IOError as e1:
            (errno, strerror) = e1.args
            print('Error copying file %s to %s' %
                  (cur_eqdsk_file, 'eqdsk'), strerror)
            services.error('Error copying cur_eqdsk_file -> eqdsk')
            raise Exception('Error copying cur_eqdsk_file -> eqdsk')

        prepare_input_bin = os.path.join(self.BIN_PATH, 'prepare_genray_input')

        rfmode = self.RFMODE
        isource_string = self.ISOURCE_STRING
        genraynml = self.GENRAYNML
        adj_read = self.ADJ_READ
        ps_add_nml = self.PS_ADD_NML

    # Call prepare_input - init
        print('rf_genray: calling prepare_input init')
        log_file = open('log_prepare_genray_input_init', 'w')
        mode = 'init'
        command = prepare_input_bin + ' ' + mode + ' ' + rfmode + ' ' +\
            isource_string + ' ' + genraynml + ' ' + adj_read + ' ' + ps_add_nml

        print('running = ', command)
        services.send_portal_event(event_type='COMPONENT_EVENT',
                                   event_comment=command)

        retcode = subprocess.call(command.split(), stdout=log_file,
                                  stderr=subprocess.STDOUT)
        if (retcode != 0):
            print('Error executing genray init ', prepare_input_bin)
            services.error('Error executing genray init')
            raise Exception('Error executing genray init')

    # If parameters are programmed from config file set parameters in genray.in
        if programming:
            # Get t0 from plasma state
            ps = Dataset(cur_state_file, 'r', format='NETCDF3_CLASSIC')
            t0 = ps.variables['t0'].getValue()
            ps.close()
            # set parameters those for time = t0
            self.set_genray_EC_parameters(
                "genray.in", t0, times_parameters_list)

    # Copy generic cur_state.cdf -> current plasma state file
        try:
            shutil.copyfile('cur_state.cdf', cur_state_file)
        except IOError as e2:
            (errno, strerror) = e2.args
            print('Error copying file %s to %s' %
                  ('cur_state.cdf', cur_state_file), strerror)
            services.error('Error copying cur_state.cdf -> cur_state_file')
            raise Exception('Error copying cur_state.cdf -> cur_state_file')

    # Update plasma state files in plasma_state work directory
        try:
            services.update_plasma_state()
        except Exception as e:
            print('Error in call to update_plasma_state()', e)
            services.error('Error in call to update_plasma_state()')
            raise Exception('Error in call to update_plasma_state()')

    # Archive output files
    # N.B.  prepare_genray_input in init mode does not produce a complete set
    #       of ourput files.  This causes an error in stage_output_files().
    #       To solve this we generate a dummy set of output files here with
    #       system call 'touch'
        for file in self.OUTPUT_FILES.split():
            print('touching ', file)
            subprocess.call(['touch', file])
    # Now stage them
        try:
            services.stage_output_files(timeStamp, self.OUTPUT_FILES)
        except Exception as e:
            print('Error in call to stage_output_files()', e)
            services.error('Error in call to stage_output_files()')
            raise Exception('Error in call to stage_output_files()')

        return 0
    def init(self, timeStamp=0):
        print 'cql3d.init() called'

        services = self.services

        # Get global configuration parameters
        cur_state_file = get_global_param(self, services, 'CURRENT_STATE')
        cur_eqdsk_file = get_global_param(self, services, 'CURRENT_EQDSK')
        cur_dql_file = get_global_param(self, services, 'CURRENT_DQL')
        cur_cql_file = get_global_param(self, services, 'CURRENT_CQL')
        cur_ImChizz_inp_file = get_global_param(self,
                                                services,
                                                'CURRENT_ImChizz_inp',
                                                optional=True)

        # Get component-specific configuration parameters. Note: Not all of these are
        # used in 'init' but if any are missing we get an exception now instead of
        # later

        NPROC = get_component_param(self, services, 'NPROC')
        BIN_PATH = get_component_param(self, services, 'BIN_PATH')
        INPUT_FILES = get_component_param(self, services, 'INPUT_FILES')
        OUTPUT_FILES = get_component_param(self, services, 'OUTPUT_FILES')
        RESTART_FILES = get_component_param(self, services, 'RESTART_FILES')
        BIN_PATH = get_component_param(self, services, 'BIN_PATH')
        CQL3D_BIN = get_component_param(self, services, 'CQL3D_BIN')
        cql3d_mode = get_component_param(self, services, 'CQL3D_MODE')
        cql3d_output = get_component_param(self, services, 'CQL3D_OUTPUT')
        cql3d_nml = get_component_param(self, services, 'CQL3D_NML')
        nsteps_str = get_component_param(self, services, 'NSTEPS_STR')
        deltat_str = get_component_param(self, services, 'DELTAT_STR')
        ps_add_nml = get_component_param(self, services, 'PS_ADD_NML')

        # enorm which is used here and in cql3d
        arg_enorm = get_component_param(self, services, 'ENORM', optional=True)

        # Copy plasma state files over to working directory
        try:
            services.stage_plasma_state()
        except Exception, e:
            print 'Error in call to stage_plasma_state()', e
            services.error('Error in call to stage_plasma_state()')
            raise Exception, 'Error in call to stage_plasma_state()'
        power_lh = ps.variables['power_lh'].getValue()[0]
        ps.close()
        print 'power = ', power_lh
        if (power_lh > 1.0E-04):

            # Copy current Dql file to generic name -> genray.nc
            if cur_dql_file != 'genray.nc':
                try:
                    shutil.copyfile(cur_dql_file, 'genray.nc')
                except IOError, (errno, strerror):
                    print 'Error copying file %s to %s' % (
                        cur_dql_file, 'genray.nc', strerror)
                    services.error('Error copying cur_dql_file -> genray.nc')
                    raise Exception, 'Error copying cur_dql_file -> genray.nc'

            cql3d_mode = get_component_param(self, services, 'CQL3D_MODE')
            cql3d_output = get_component_param(self, services, 'CQL3D_OUTPUT')
            cql3d_nml = get_component_param(self, services, 'CQL3D_NML')
            nsteps_str = get_component_param(self, services, 'NSTEPS_STR')
            deltat_str = get_component_param(self, services, 'DELTAT_STR')
            ps_add_nml = get_component_param(self, services, 'PS_ADD_NML')
            cur_ImChizz_inp_file = get_global_param(self,
                                                    services,
                                                    'CURRENT_ImChizz_inp',
                                                    optional=True)

            # enorm which is used here and in cql3d
            arg_enorm = get_component_param(self,
                                            services,
                                            'ENORM',
                                            optional=True)
    def step(self, timeStamp):
        print('cql3d.step() called')

        if (self.services == None) :
           print('Error in cql3d: step (): No services')
           raise Exception('Error in cql3d: step (): No services')
        services = self.services

        prepare_input_bin = os.path.join(self.BIN_PATH, 'prepare_cql3d_input')
        process_output_bin  = os.path.join(self.BIN_PATH, 'process_cql3d_output')
        cql3d_bin = os.path.join(self.BIN_PATH, 'cql3d')

    # Copy plasma state files over to working directory
        try:
          services.stage_plasma_state()
        except Exception as e:
          print('Error in call to stage_plasma_state()' , e)
          services.error('Error in call to stage_plasma_state()')
          raise Exception('Error in call to stage_plasma_state()')

    # Get global configuration parameters
        cur_state_file = get_global_param(self, services, 'CURRENT_STATE')
        cur_eqdsk_file = get_global_param(self, services, 'CURRENT_EQDSK')
        cur_dql_file = get_global_param(self, services, 'CURRENT_DQL')
        cur_cql_file = get_global_param(self, services,'CURRENT_CQL', optional = True)
        cur_ImChizz_inp_file = get_global_param(self, services,'CURRENT_ImChizz_inp', optional = True)
        
    # Copy current plasma state file to generic name -> cur_state.cdf
        try:
            shutil.copyfile(cur_state_file, 'cur_state.cdf')
        except IOError as xxx_todo_changeme6:
            (errno, strerror) = xxx_todo_changeme6.args
            print('Error copying file %s to %s' % (cur_state_file, 'cur_state.cdf', strerror))
            raise

    # Copy current eqdsk file to generic name -> eqdsk
        try:
            shutil.copyfile(cur_eqdsk_file, 'eqdsk')
        except IOError as xxx_todo_changeme7:
            (errno, strerror) = xxx_todo_changeme7.args
            print('Error copying file %s to %s' % (cur_eqdsk_file, 'eqdsk', strerror))
            services.error('Error copying cur_eqdsk_file -> eqdsk')
            raise Exception('Error copying cur_eqdsk_file -> eqdsk')

# Copy current Dql file to generic name -> genray.nc
        if cur_dql_file != 'genray.nc':
          try:
            shutil.copyfile(cur_dql_file, 'genray.nc')
          except IOError as xxx_todo_changeme2:
            (errno, strerror) = xxx_todo_changeme2.args
            print('Error copying file %s to %s' % (cur_dql_file, 'genray.nc', strerror))
            services.error('Error copying cur_dql_file -> genray.nc')
            raise Exception('Error copying cur_dql_file -> genray.nc')

        cql3d_mode = get_component_param(self, services, 'CQL3D_MODE')
        cql3d_output = get_component_param(self, services, 'CQL3D_OUTPUT')
        cql3d_nml = get_component_param(self, services, 'CQL3D_NML')
        nsteps_str = get_component_param(self, services, 'NSTEPS_STR',optional=True)
        deltat_str = get_component_param(self, services, 'DELTAT_STR',optional=True)
        ps_add_nml = get_component_param(self, services, 'PS_ADD_NML')
        cur_ImChizz_inp_file = get_global_param(self, services,'CURRENT_ImChizz_inp', optional = True)

    # enorm which is used here and in cql3d
        arg_enorm = get_component_param(self, services, 'ENORM', optional = True)
      
# Call prepare_input - step
        print('fp_cql3d step: calling prepare_input')
      
        log_file = open('log_prepare_cql3d_input_step', 'w')
        ips_mode = 'step'

# ptb: Set restart depending on whether the distribution function file from cql3d
# already exist
        restart = 'disabled'
#ptb&SS      if os.path.isfile('./cql3d.nc'): restart = 'enabled'
#ptb&SS      if os.path.isfile('./cql3d.nc'): shutil.copyfile('cql3d.nc','distrfunc.nc')

        if os.path.isfile('./cql3d.nc'): 
          if os.stat('./cql3d.nc')[6] != 0:
               restart = 'enabled'
               shutil.copyfile('cql3d.nc','distrfunc.nc')


# ptb: End of ptb hack

# ptb:    command = prepare_input_bin + ' ' + ips_mode + ' ' + cql3d_mode  + ' ' +\
# ptb:    cql3d_output + ' ' + cql3d_nml + ' ' + nsteps_str + ' ' + ps_add_nml
        command = prepare_input_bin + ' ' + ips_mode + ' ' + cql3d_mode  + ' ' +\
        cql3d_output + ' ' + cql3d_nml + ' ' + restart + ' ' + ps_add_nml
        if nsteps_str != None:
            command = command+ ' ' + steps_str

        if deltat_str != None:
            command = command+' ' + deltat_str

        if arg_enorm != None:
          command = command  + ' ' + arg_enorm

        print('running', command)
        services.send_portal_event(event_type = 'COMPONENT_EVENT',\
          event_comment =  command)

        retcode = subprocess.call(command.split(), stdout = log_file,\
                                stderr = subprocess.STDOUT)
        if (retcode != 0):
          print('Error executing cql3d: ', prepare_input_bin)
          services.error('Error executing cql3d prepare_input')
          raise Exception('Error executing cql3d prepare_input')
    
#     Launch cql3d - N.B: Path to executable is in config parameter CQL3D_BIN
        print('fp_cql3d: launching cql3d')
# ptb: Need to first copy the cqlinput_new file to cqlinput
        shutil.copyfile('cqlinput_new', 'cqlinput')
        cwd = services.get_working_dir()
        task_id = services.launch_task(self.NPROC, cwd, self.CQL3D_BIN, task_ppn=self.NPPN, logfile='log.cql3d')
        retcode = services.wait_task(task_id)
        if (retcode != 0):
          print('Error executing command: ', cql3d_bin)
          services.error('Error executing cql3d')
          raise Exception('Error executing cql3d')

# Call process_output - step
        print('fp_cql3d step: calling process_output')

# Get cql3d_output_file file name <--> mnemonic from cqlinput file
        lines = get_lines('cqlinput')
        cql3d_output_file = lines_to_variable_dict(lines)['MNEMONIC'].strip("'") + ".nc"
        print('cql3d_output_file = ', cql3d_output_file)
  
        log_file = open('log_process_cql3d_output', 'w')
        mode = 'step'
# ptb;          command = process_output_bin + ' ' +  cql3d_mode
        command = process_output_bin + ' ' +  cql3d_output+ ' ' +  cql3d_output_file   

        print('running', command)
        services.send_portal_event(event_type = 'COMPONENT_EVENT',\
          event_comment =  command)

        retcode = subprocess.call(command.split(), stdout = log_file,\
                                stderr = subprocess.STDOUT)                                  
        if (retcode != 0):
          print('Error executing cql3d init ', process_output_bin)
          services.error('Error executing cql3d process_output')
          raise Exception('Error executing cql3d process_output')
    
# Copy generic cql3d partial plasma state file -> FP_CQL3D_cur_state_file  [correct??, BH]
        try:
          partial_file = cwd + '/FP_CQL3D_' + cur_state_file
          shutil.copyfile('FP_CQL3D_PARTIAL_STATE', partial_file )
        except IOError as xxx_todo_changeme8:
          (errno, strerror) = xxx_todo_changeme8.args
          print('Error copying file %s to %s' % ('cur_state.cdf', cur_state_file, strerror))
          raise


# Merge partial plasma state containing updated CQL3D data  [BH]
        try:
           services.merge_current_plasma_state(partial_file, logfile='log.update_state')
           print('merged CQL3D plasma state data ', partial_file)
        except Exception as e:
           print('Error in call to merge_current_plasma_state(' , partial_file, ')')
           self.services.error('Error in call to merge_current_plasma_state')
           raise Exception('Error in call to merge_current_plasma_state')

  # Update plasma state files in plasma_state work directory, but only cur_cql_file
  # and cur_ImChizz_inp_file if there is one.
  # This way it can be used concurrently without overwriting other plasma state files.
        print('CURRENT_CQL = ', cur_cql_file, '  cur_ImChizz_inp_file = ', cur_ImChizz_inp_file)
        try:
           if cur_cql_file != None:
             services.update_plasma_state([cur_cql_file])
        except Exception:
           logMsg = 'Error in call to update_plasma_state()'
           self.services.exception(logMsg)
           raise 
        try:
           if cur_ImChizz_inp_file != None:
             services.update_plasma_state([cur_ImChizz_inp_file])
        except Exception:
           logMsg = 'Error in call to update_plasma_state()'
           self.services.exception(logMsg)
           raise 
        
# Archive output files
        try:
           services.stage_output_files(timeStamp, self.OUTPUT_FILES)
        except Exception as e:
           print('Error in call to stage_output_files()', e)
           services.error('Error in call to stage_output_files()')
           raise Exception('Error in call to stage_output_files()')
    
#     rename the log file so that it is not appended next step
#        os.rename('log.cql3d', this_logfile)

        return 0
    def init(self, timeStamp=0):
        print('cql3d.init() called')

        services = self.services

    # Get global configuration parameters
        cur_state_file = get_global_param(self, services, 'CURRENT_STATE')
        cur_eqdsk_file = get_global_param(self, services, 'CURRENT_EQDSK')
        cur_dql_file = get_global_param(self, services, 'CURRENT_DQL')
        cur_cql_file = get_global_param(self, services,'CURRENT_CQL', optional = True)
        cur_ImChizz_inp_file = get_global_param(self, services,'CURRENT_ImChizz_inp', optional = True)

    # Get component-specific configuration parameters. Note: Not all of these are
    # used in 'init' but if any are missing we get an exception now instead of
    # later

        NPROC = get_component_param(self, services, 'NPROC')
        NPPN = get_component_param(self, services, 'NPPN')
        BIN_PATH = get_component_param(self, services, 'BIN_PATH')
        INPUT_FILES = get_component_param(self, services, 'INPUT_FILES')
        OUTPUT_FILES = get_component_param(self, services, 'OUTPUT_FILES')
        RESTART_FILES = get_component_param(self, services, 'RESTART_FILES')
        BIN_PATH = get_component_param(self, services, 'BIN_PATH')
        CQL3D_BIN = get_component_param(self, services, 'CQL3D_BIN')
        cql3d_mode = get_component_param(self, services, 'CQL3D_MODE')
        cql3d_output = get_component_param(self, services, 'CQL3D_OUTPUT')
        cql3d_nml = get_component_param(self, services, 'CQL3D_NML')
        nsteps_str = get_component_param(self, services, 'NSTEPS_STR',optional=True)
        deltat_str = get_component_param(self, services, 'DELTAT_STR',optional=True)
        ps_add_nml = get_component_param(self, services, 'PS_ADD_NML')

        # enorm which is used here and in cql3d
        arg_enorm = get_component_param(self, services, 'ENORM', optional = True)

    # Copy plasma state files over to working directory
        try:
          services.stage_plasma_state()
        except Exception as e:
          print('Error in call to stage_plasma_state()' , e)
          services.error('Error in call to stage_plasma_state()')
          raise Exception('Error in call to stage_plasma_state()')
        
    # Get input files  
        try:
          services.stage_input_files(INPUT_FILES)
        except Exception as e:
          print('Error in call to stageInputFiles()' , e)
          services.error('Error in call to stageInputFiles()')
          raise Exception('Error in call to stageInputFiles()')
            
    # Copy cqlinput_<suffix> to generic file name -> cqlinput if there is
    # a suffix
        try:
          suffix = self.INPUT_SUFFIX
          have_suffix = True
        # If suffix is not empty put an underscore in front of it.
          if len(suffix) > 0:
              print('cql3d INPUT_SUFFIX = ', suffix)      
              suffix = '_' + suffix
        # If suffix is empty you don't really have one
          else:
              have_suffix = False
        except:
          have_suffix = False
      
      # If there is a non-empty suffix, copy to generic filename 'cqlinput'
        if have_suffix:      
          try:
              shutil.copyfile('cqlinput' + suffix, 'cqlinput')
          except IOError as xxx_todo_changeme:
              (errno, strerror) = xxx_todo_changeme.args
              print('Error copying file %s to %s' % ('cqlinput' + suffix, 
              'cqlinput', strerror))
              services.error('Error copying cqlinput_<suffix> -> cqlinput')
              raise Exception('Error copying cqlinput_<suffix> -> cqlinput')

    # Copy current plasma state file to generic name -> cur_state.cdf
        try:
            shutil.copyfile(cur_state_file, 'cur_state.cdf')
        except IOError as xxx_todo_changeme3:
            (errno, strerror) = xxx_todo_changeme3.args
            print('Error copying file %s to %s' % (cur_state_file, 'cur_state.cdf', strerror))
            services.error('Error copying cur_state_file -> cur_state.cdf')
            raise Exception('Error copying cur_state_file -> cur_state.cdf')

    # Copy current eqdsk file to generic name -> eqdsk
        try:
            shutil.copyfile(cur_eqdsk_file, 'eqdsk')
        except IOError as xxx_todo_changeme4:
            (errno, strerror) = xxx_todo_changeme4.args
            print('Error copying file %s to %s' % (cur_eqdsk_file, 'eqdsk', strerror))
            services.error('Error copying cur_eqdsk_file -> eqdsk')
            raise Exception('Error copying cur_eqdsk_file -> eqdsk')

    # Copy current Dql file to generic name -> genray.nc
        if cur_dql_file != 'genray.nc':
            try:
                shutil.copyfile(cur_dql_file, 'genray.nc')
            except IOError as xxx_todo_changeme1:
                (errno, strerror) = xxx_todo_changeme1.args
                print('Error copying file %s to %s' % (cur_dql_file, 'genray.nc', strerror))
                services.error('Error copying cur_dql_file -> genray.nc')
                raise Exception('Error copying cur_dql_file -> genray.nc')

        prepare_input_bin = os.path.join(self.BIN_PATH, 'prepare_cql3d_input')

    # Call prepare_input - init
        print('fp_cql3d: calling prepare_input init')        
        log_file = open('log_prepare_cql3d_input_init', 'w')
        ips_mode = 'init'

    # ptb: Set restart depending on whether the distribution function file from cql3d
    # already exist
        restart = 'disabled'
    #ptb&SS    if os.path.isfile('./cql3d.nc'): restart = 'enabled'
    #ptb&SS    if os.path.isfile('./cql3d.nc'): shutil.copyfile('cql3d.nc','distrfunc.nc')

        if os.path.isfile('./cql3d.nc'): 
            if os.stat('./cql3d.nc')[6] != 0:
                 restart = 'enabled'
                 shutil.copyfile('cql3d.nc','distrfunc.nc')

    # ptb: End of ptb hack

    # ptb:    command = prepare_input_bin + ' ' + ips_mode + ' ' + cql3d_mode  + ' ' +\
    # ptb:    cql3d_output + ' ' + cql3d_nml + ' ' + nsteps_str + ' ' + ps_add_nml
        command = prepare_input_bin + ' ' + ips_mode + ' ' + cql3d_mode  + ' ' +\
        cql3d_output + ' ' + cql3d_nml + ' ' + restart + ' '+ ps_add_nml
        if nsteps_str != None:
            command = command + ' ' + nsteps_str

        if deltat_str != None:
            command = command + ' ' + deltat_str
             
        if arg_enorm != None:
            command = command  + ' ' + arg_enorm

        print('running = ', command)
        services.send_portal_event(event_type = 'COMPONENT_EVENT',\
          event_comment =  command)
        
        retcode = subprocess.call(command.split(), stdout = log_file,\
                                  stderr = subprocess.STDOUT)
        if (retcode != 0):
            print('Error executing cql3d init ', prepare_input_bin)
            services.error('Error executing cql3d init')
            raise Exception('Error executing cql3d init')

    # Copy generic cur_state.cdf -> current plasma state file
        try:
            shutil.copyfile('cur_state.cdf', cur_state_file)
        except IOError as xxx_todo_changeme5:
            (errno, strerror) = xxx_todo_changeme5.args
            print('Error copying file %s to %s' % ('cur_state.cdf', cur_state_file, strerror))
            services.error('Error copying cur_state.cdf -> cur_state_file')
            raise Exception('Error copying cur_state.cdf -> cur_state_file')

    # Update plasma state files in plasma_state work directory
        try:
          services.update_plasma_state()
        except Exception as e:
          print('Error in call to update_plasma_state()', e)
          services.error('Error in call to update_plasma_state()')
          raise Exception('Error in call to update_plasma_state()')
     
    # Archive output files
    # N.B.  prepare_cql3d_input in init mode does not produce a complete set 
    #       of ourput files.  This causes an error in stage_output_files().
    #       To solve this we generate a dummy set of output files here with 
    #       system call 'touch'
        for file in self.OUTPUT_FILES.split():
          print('touching ', file)
          subprocess.call(['touch', file])
    # Now stage them      
        try:
          services.stage_output_files(timeStamp, self.OUTPUT_FILES)
        except Exception as e:
          print('Error in call to stage_output_files()', e)
          services.error('Error in call to stage_output_files()')
          raise Exception('Error in call to stage_output_files()')

        return 0
Ejemplo n.º 10
0
    def step(self, timeStamp):
        print(' ')
        print('generic_ps_init.step() called')

        services = self.services

        # Get timeloop for simulation
        timeloop = services.get_time_loop()
        tlist_str = ['%.3f' % t for t in timeloop]
        t = tlist_str[0]
        tinit = tlist_str[0]
        tfinal = tlist_str[-1]

        # Check if this is a restart simulation
        simulation_mode = get_global_param(self, services, 'SIMULATION_MODE')

        if simulation_mode == 'RESTART':
            print('generic_ps_init: RESTART')
        if simulation_mode not in ['RESTART', 'NORMAL']:
            logMsg = 'generic_ps_init: unrecoginzed SIMULATION_MODE: ' + mode
            self.services.error(logMsg)
            raise ValueError(logMsg)

# ------------------------------------------------------------------------------
#
# RESTART simulation mode
#
# ------------------------------------------------------------------------------

        if simulation_mode == 'RESTART':
            # Get restart files listed in config file. Here just the plasma state files.
            restart_root = get_global_param(self, services, 'RESTART_ROOT')
            restart_time = get_global_param(self, services, 'RESTART_TIME')
            try:
                services.get_restart_files(restart_root, restart_time,
                                           self.RESTART_FILES)
            except:
                logMsg = 'Error in call to get_restart_files()'
                self.services.exception(logMsg)
                raise

            cur_state_file = self.services.get_global_param('CURRENT_STATE')

            # Update ps%t0, ps%t1 and ps%tfinal.
            # Note ps%tinit stays the same in the plasma state file,
            # tinit from the config file timeloop is the restart time
            ps = Dataset(cur_state_file, 'r+', format='NETCDF3_CLASSIC')
            ps.variables['t0'].assignValue(float(tinit))
            ps.variables['t1'].assignValue(float(tinit))
            ps.variables['tfinal'].assignValue(float(tfinal))
            ps.close()

# ------------------------------------------------------------------------------
#
# NORMAL simulation mode
#
# ------------------------------------------------------------------------------

        else:

            print('generic_ps_init: simulation mode NORMAL')
            nml_lines = ['&ps_init_nml\n']
            ps_file_list = get_global_param(self, services,
                                            'PLASMA_STATE_FILES').split(' ')

            init_mode = get_component_param(self, services, 'INIT_MODE')
            nml_lines.append(' init_mode = \"' + init_mode + '\"\n')

            # Generate state files as dummies so framework will have a complete set
            for file in ps_file_list:
                print('touching plasma state file = ', file)
                try:
                    subprocess.call(['touch', file])
                except Exception:
                    print('No file ', file)
            if init_mode in ['touch_only', 'TOUCH_ONLY']:
                # Update plasma state
                try:
                    services.update_plasma_state()
                except Exception as e:
                    print('Error in call to updatePlasmaState()', e)
                    raise
                return

            try:
                services.stage_input_files(self.INPUT_FILES)
            except Exception:
                message = 'generic_ps_init: Error in staging input files'
                print(message)
                services.exception(message)
                raise

            cur_state_file = get_global_param(self, services, 'CURRENT_STATE')
            cur_eqdsk_file = get_global_param(self, services, 'CURRENT_EQDSK')
            nml_lines.append(' cur_state_file = \"' + cur_state_file + '\"\n')
            nml_lines.append(' cur_eqdsk_file = \"' + cur_eqdsk_file + '\"\n')

            INPUT_EQDSK_FILE = get_component_param(self, services, 'INPUT_EQDSK_FILE', \
            optional = True)
            if (INPUT_EQDSK_FILE is None) or (len(INPUT_EQDSK_FILE) == 0):
                INPUT_EQDSK_FILE = ' '
            else:
                nml_lines.append(' input_eqdsk_file = \"' + INPUT_EQDSK_FILE +
                                 '\"\n')

                # If there is an INPUT_EQDSK_FILE copy it to CURRENT_EQDSK although
                # CURRENT_EQDSK will be overwritten with plasma state data if
                # GENERATE_EQDSK is True
                try:
                    subprocess.call(['cp', INPUT_EQDSK_FILE, cur_eqdsk_file])
                except Exception:
                    message = 'generic_ps_init: Error copying INPUT_EQDSK_FILE to CURRENT_EQDSK'
                    print(message)
                    services.exception(message)
                    raise

# ------------------------------------------------------------------------------
# init from existing plasma state file
            if init_mode in [
                    'existing_ps_file', 'EXISTING_PS_FILE', 'mixed', 'MIXED'
            ]:
                INPUT_STATE_FILE = get_component_param(self, services,
                                                       'INPUT_STATE_FILE')

                # Copy INPUT_STATE_FILE to current state file
                try:
                    subprocess.call(['cp', INPUT_STATE_FILE, cur_state_file])
                except Exception:
                    message = 'generic_ps_init: Error in copying INPUT_STATE_FILE \
                        to current state file'

                    print(message)
                    services.exception(message)
                    raise

                # Generate cur_eqdsk_file from cur_state_file if GENERATE_EQDSK is True
                GENERATE_EQDSK = get_component_param(self, services, 'GENERATE_EQDSK', \
                optional = True)
                if GENERATE_EQDSK in ['true', 'TRUE', 'True']:
                    nml_lines.append(' generate_eqdsk = \"True\"')
                    nml_lines.append('/\n')
                    put_lines('generic_ps_init.nml', nml_lines)

                    init_bin = os.path.join(self.BIN_PATH, 'generic_ps_init')
                    print('Executing ', init_bin)
                    retcode = subprocess.call(init_bin)
                    if (retcode != 0):
                        print('Error executing ', init_bin)
                        raise

            # Copy INPUT_EQDSK_FILE, if there is one, to cur_eqdsk_file.
            # Nota Bene: If there is an INPUT_EQDSK_FILE specified in config this copy
            # will overwrite any eqdsk generated in the block above.
                if INPUT_EQDSK_FILE != ' ':
                    try:
                        subprocess.call(
                            ['cp', INPUT_EQDSK_FILE, cur_eqdsk_file])
                    except Exception as e:
                        message = 'generic_ps_init: Error in copying input_eqdsk_file'
                        print(message)
                        services.exception(message)
                        raise e

# ------------------------------------------------------------------------------
# init from machine description file and possibly sconfig file
            if init_mode in ['mdescr', 'MDESCR', 'mixed', 'MIXED']:
                MDESCR_FILE = get_component_param(self, services,
                                                  'MDESCR_FILE')
                nml_lines.append(' mdescr_file = ' + MDESCR_FILE + '\n')
                SCONFIG_FILE = get_component_param(self, services, 'SCONFIG_FILE', \
                optional = 'TRUE')

                if (SCONFIG_FILE is None) or (len(SCONFIG_FILE) == 0):
                    SCONFIG_FILE = ' '
                else:
                    nml_lines.append(' sconfig_file = \"' + SCONFIG_FILE +
                                     '\"\n')

                INPUT_EQDSK_FILE = get_component_param(self, services, 'INPUT_EQDSK_FILE', \
                optional = True)
                if (INPUT_EQDSK_FILE is None) or (len(INPUT_EQDSK_FILE) == 0):
                    INPUT_EQDSK_FILE = ' '
                else:
                    nml_lines.append(' input_eqdsk_file = \"' +
                                     INPUT_EQDSK_FILE + '\"\n')

# ------------------------------------------------------------------------------
# For init_mode = mixed add input_state_file to namelist
            if init_mode in ['mixed', 'MIXED']:
                nml_lines.append(' input_state_file = \"' + INPUT_STATE_FILE +
                                 '\"\n')

                # Retrieve list of IPS components which are to be initialized from
                # mdescr/sconfig and construct cclist for generic_ps_init.f90
                mdescr_components = get_component_param(
                    self, services, 'MDESCR_COMPONENTS')
                if isinstance(mdescr_components, type('str')):
                    mdescr_components = [mdescr_components]
                cclist = [0 for i in range(len(component_dict))]
                for comp in mdescr_components:
                    if comp not in list(component_dict.keys()):
                        message = 'generic_ps_init: Unknown IPS component ' + comp
                        print(message)
                        services.exception(message)
                        raise
                    cclist[component_dict[comp] - 1] = 1
                print('cclist = ', cclist)
                cclist_string = ''
                for i in range(len(cclist)):
                    cclist_string = cclist_string + str(cclist[i]) + ', '
                nml_lines.append(' cclist = ' + cclist_string + '\n')

# ------------------------------------------------------------------------------
# For 'minimal', 'mdescr' and 'mixed' modes generate namelist for the fortran
# helper code generic_ps_init.f90 and execute it
            if init_mode in [
                    'minimal', 'MINIMAL', 'mdescr', 'MDESCR', 'mixed', 'MIXED'
            ]:
                nml_lines.append('/\n')
                put_lines('generic_ps_init.nml', nml_lines)

                init_bin = os.path.join(self.BIN_PATH, 'generic_ps_init')
                print('Executing ', init_bin)
                retcode = subprocess.call(init_bin)
                if (retcode != 0):
                    print('Error executing ', init_bin)
                    raise

# ------------------------------------------------------------------------------
# For all init init modes insert run identifiers and time data
# (do it here in python instead of in minimal_state_init.f90 as before)
# For minimal mode this is the only data in initial state
            tokamak = get_global_param(self, services, 'TOKAMAK_ID')
            shot_number = get_global_param(self, services, 'SHOT_NUMBER')
            run_id = get_global_param(self, services, 'RUN_ID')

            timeloop = services.get_time_loop()
            t0 = timeloop[0]
            t1 = t0
            tfinal = timeloop[-1]

            # Put into current plasma state
            plasma_state = Dataset(cur_state_file,
                                   'r+',
                                   format='NETCDF3_CLASSIC')
            plasma_state.variables['tokamak_id'][:] = stringtoarr(tokamak, 32)
            plasma_state.variables['RunID'][:] = stringtoarr(run_id, 32)
            plasma_state.variables['shot_number'][0] = shot_number
            plasma_state.variables['t0'][0] = t0
            plasma_state.variables['t1'][0] = t1
            plasma_state.variables['tinit'][0] = t0
            plasma_state.variables['tfinal'][0] = tfinal
            plasma_state.close()

        # Preserve initial plasma state file
        try:
            shutil.copyfile(cur_state_file, 'initial_PLASMA_STATE.nc')
        except Exception as e:
            print('Copy to initial_PLASMA_STATE file failed ', e)

        # For benefit of framework file handling generate dummy dakota.out file
        subprocess.call(['touch', 'dakota.out'])

        # Update plasma state
        try:
            services.update_plasma_state()
        except Exception as e:
            print('Error in call to updatePlasmaState()', e)
            raise

# "Archive" output files in history directory
        services.stage_output_files(timeStamp, self.OUTPUT_FILES)
Ejemplo n.º 11
0
    def step(self, timeStamp):
        services = self.services
        init_only = get_component_param(self,
                                        services,
                                        'INIT_ONLY',
                                        optional=True)
        if init_only in ['TRUE', 'True', 'true']: return

        print('model_EPA_mdescr.step() called')
        global parameterList

        # Copy current and prior state over to working directory
        services.stage_plasma_state()
        cur_state_file = get_global_param(self, services, 'CURRENT_STATE')
        ps = Dataset(cur_state_file, 'r+', format='NETCDF3_CLASSIC')
        tinit = ps.variables['tinit'].getValue()

        # Time evolution of parameters
        # get lines from namelist file
        inputLines = get_lines('model_EPA_mdescr_input.nml')
        initial_nml_Lines = get_lines('initial_input.nml')

        evolution_models = {'linear_DT': self.linear_DT,\
                            'ramp_initial_to_final': self.ramp_initial_to_final}
        print(' ')
        print('evolution_models = ', list(evolution_models.keys()))

        # Look in config file for parameters to evolve, get the evolution model and its
        # arguments
        params_to_change = False
        for param in parameterList:
            model_name = get_component_param(self, services, param + '_DT_model', \
                optional = True)
            if model_name != None:
                model_name = model_name.strip()
                params_to_change = True

                if model_name == 'ramp_initial_to_final':
                    print('model_EPA_mdescr: ramp_initial_to_final')
                    DT_paramsList = get_component_param(
                        self, services, param + '_DT_params').split()
                    t_initial = float(DT_paramsList[0])
                    t_final = float(DT_paramsList[1])

                    # Get initial value of parameter from the initial namelist file
                    Value_init = read_var_from_nml_lines(initial_nml_Lines,
                                                         param,
                                                         separator=',')
                    print('intial ' + param, ' = ', Value_init)

                    #Value_init = float(DT_paramsList[2])
                    Value_final = float(DT_paramsList[2])
                    print('t_initial = ',t_initial, ' t_final = ', t_final,\
                    '  Value_init =  ', Value_init, '  Value_final =  ', Value_final)
                    newValue = self.ramp_initial_to_final(float(timeStamp), t_initial,\
                               t_final, Value_init, Value_final)

                if model_name == 'exp_initial_to_final':
                    print('model_EPA_mdescr: exp_initial_to_final')
                    DT_paramsList = get_component_param(
                        self, services, param + '_DT_params').split()
                    t_initial = float(DT_paramsList[0])
                    tau = float(DT_paramsList[1])
                    Value_final = float(DT_paramsList[2])

                    # Get initial value of parameter from the initial namelist file
                    Value_init = read_var_from_nml_lines(initial_nml_Lines,
                                                         param,
                                                         separator=',')
                    print('intial ' + param, ' = ', Value_init)

                    print('t_initial = ',t_initial, \
                    '  Value_init =  ', Value_init, '  Value_final =  ', Value_final)

                    newValue = self.exp_initial_to_final(float(timeStamp), t_initial,\
                               tau, Value_init, Value_final)

                print('t = ', float(timeStamp), ' ', param, ' = ', newValue)
                # modify that parameter in namelist file
                lines = edit_nml_file(inputLines,
                                      param, [newValue],
                                      separator=',')

        # write modified namelist file
        if params_to_change:
            put_lines('model_EPA_mdescr_input.nml', lines)

# Call model_EPA_mdescr
        bin = os.path.join(self.BIN_PATH, 'model_EPA_mdescr')
        print('Executing ', [bin, cur_state_file, 'STEP', timeStamp])
        retcode = subprocess.call([bin, cur_state_file, 'STEP', timeStamp])
        if (retcode != 0):
            message = 'generic_ps_init: Error executing' + bin
            print(message)
            services.exception(message)
            raise

# Update plasma state
        services.update_plasma_state()

        # "Archive" output files in history directory
        services.stage_output_files(timeStamp, self.OUTPUT_FILES)
Ejemplo n.º 12
0
    def step(self, timestamp=0):

        services = self.services
        services.stage_state()
        services.stage_input_files(self.INPUT_FILES)

        # get list of ports
        #        ports = services.getGlobalConfigParameter('PORTS')
        ports = config.get_global_param(self, services, 'PORTS')
        port_names = ports['NAMES'].split()
        print('PORTS =', port_names)
        port_dict = {}
        port_id_list = []

        # Instantiate components in port_names list, except DRIVER itself which is done
        # by the framework
        print(' ')

        for port_name in port_names:
            if port_name in ["DRIVER"]: continue
            port = services.get_port(port_name)
            if (port == None):
                logMsg = 'Error accessing ' + port_name + ' component'
                services.error(logMsg)
                raise Exception(logMsg)
            port_dict[port_name] = port
            port_id_list.append(port)
            print(' ')

    # Is this a simulation startup or restart
        sim_mode = config.get_global_param(self, services, 'SIMULATION_MODE')

        # Get timeloop for simulation
        timeloop = services.get_time_loop()
        tlist_str = ['%.3f' % t for t in timeloop]
        t = tlist_str[0]

        # Initialize components in PORTS list for startup or restart
        print(' ')

        init_mode = 'init'
        if sim_mode == 'RESTART': init_mode = 'restart'

        for port_name in port_names:
            if port_name in ['INIT', 'DRIVER']: continue
            self.component_call(services, port_name, port_dict[port_name],
                                init_mode, t)

    # Get state files into driver work directory
        services.stage_state()
        cur_state_file = config.get_global_param(self, services,
                                                 'CURRENT_STATE')

        # Get Portal RUNID and save to a file
        run_id = config.get_global_param(self, services, 'PORTAL_RUNID')
        sym_root = config.get_global_param(self, services, 'SIM_ROOT')
        path = os.path.join(sym_root, 'PORTAL_RUNID')
        runid_file = open(path, 'a')
        runid_file.writelines(run_id + '\n')
        runid_file.close()

        # Check if there is a config parameter CURRENT_STATE and add data if so.
        # In this case set t0 = t1 = tinit
        cur_state_file = config.get_global_param(self,
                                                 services,
                                                 'CURRENT_STATE',
                                                 optional=True)
        if cur_state_file != None and len(cur_state_file) > 0:
            timeloop = services.get_time_loop()
            variable_dict = {'t0': timeloop[0], 't1': timeloop[0]}
            if sim_mode == 'NORMAL':
                edit.add_variables_to_output_file(variable_dict,
                                                  cur_state_file)
            if sim_mode == 'RESTART':
                edit.modify_variables_in_file(variable_dict, cur_state_file)
            if sim_mode not in ['NORMAL', 'RESTART']:
                message = 'Unknown Simulation mode ' + sim_mode
                print(message)
                services.exception(message)
                raise

            services.update_state()

    # Post init processing: stage  state, stage output
        services.stage_output_files(t, self.OUTPUT_FILES)

        print(' init sequence complete--ready for time loop')

        INIT_ONLY = config.get_component_param(self,
                                               services,
                                               'INIT_ONLY',
                                               optional=True)
        if INIT_ONLY in [True, 'true', 'True', 'TRUE']:
            message = 'INIT_ONLY: Intentional stop after INIT phase'
            print(message)
            return

# ------------------------------------------------------------------------------
#
# Start Physics Layer
#
# ------------------------------------------------------------------------------

# Iterate through the timeloop
        for t in tlist_str[1:len(timeloop)]:
            print(' ')
            print('Driver: step to time = ', t)
            services.update_time_stamp(t)

            # pre_step_logic
            # It is sometimes necessary to do some tasks before starting a new time step.
            # This could entail evaluating logic based on results of last time step, or
            # calculations not part of any of the components.  If there is a current state
            # file it usually at least involves setting the start time of this time step, t0,
            # equal to the end time of the last step, t1, and setting t1 = t.

            # call pre_step_logic
            services.stage_state()
            self.pre_step_logic(services, float(t))
            services.update_state()
            print(' ')

            # Call step for each component

            print(' ')
            for port_name in port_names:
                if port_name in ['INIT', 'DRIVER']: continue
                self.component_call(services, port_name, port_dict[port_name],
                                    'step', t)

            services.stage_state()

            # Post step processing: stage  state, checkpoint components and self
            services.stage_output_files(t, self.OUTPUT_FILES)
            services.checkpoint_components(port_id_list, t)
            self.checkpoint(t)

# ------------------------------------------------------------------------------
#
# End of Physics Layer
#
# ------------------------------------------------------------------------------

# Post simulation: call checkpoint on each component

        services.checkpoint_components(port_id_list, t, Force=True)
        self.checkpoint(t)

        # Post simulation: call finalize on each component
        print(' ')
        for port_name in port_names:
            if port_name in ['INIT', 'DRIVER']: continue
            self.component_call(services, port_name, port_dict[port_name],
                                'finalize', t)
Ejemplo n.º 13
0
    def step(self, timestamp=0):

        services = self.services
        services.stage_plasma_state()
        services.stage_input_files(self.INPUT_FILES)

      # get list of ports
#        ports = services.getGlobalConfigParameter('PORTS')
        ports = get_global_param(self, services,'PORTS')
        port_names = ports['NAMES'].split()
        print('PORTS =', port_names)
        port_dict = {}
        port_id_list = []

      # Instantiate components in port_names list, except DRIVER itself
        print (' ')

        # INIT is already instantiated by the framework. This adds it to port_dict
        if 'INIT' in port_names:
            initComp = services.get_port('INIT') 
            if(initComp == None):
                print('Error accessing INIT component')
                raise
            port_dict['INIT'] = initComp
            port_id_list.append(initComp)
            print (' ')

        if 'EPA' in port_names:
            epaComp = services.get_port('EPA')
            if(epaComp == None):
                print('Error accessing EPA component')
                raise
            port_dict['EPA'] = epaComp
            port_id_list.append(epaComp)
            print (' ')
       
        if 'RF_EC' in port_names:
            rf_ecComp = services.get_port('RF_EC')
            if(rf_ecComp == None):
                print('Error accessing RF_EC component')
                raise
            port_dict['RF_EC'] = rf_ecComp
            port_id_list.append(rf_ecComp)
            print (' ')
        
        if 'RF_IC' in port_names:
            rf_icComp = services.get_port('RF_IC')
            if(rf_icComp == None):
                print('Error accessing RF_IC component')
                raise
            port_dict['RF_IC'] = rf_icComp
            port_id_list.append(rf_icComp)
            print (' ')
        
        if 'RF_LH' in port_names:
            rf_lhComp = services.get_port('RF_LH')
            if(rf_lhComp == None):
                print('Error accessing RF_LH component')
                raise
            port_dict['RF_LH'] = rf_lhComp
            port_id_list.append(rf_lhComp)
            print (' ')

        if 'NB' in port_names:
            nbComp = services.get_port('NB')
            if(nbComp == None):
                print('Error accessing NB component')
                raise
            port_dict['NB'] = nbComp
            port_id_list.append(nbComp)
            print (' ')

        if 'FUS' in port_names:
            fusComp = services.get_port('FUS')
            if(fusComp == None):
                print('Error accessing FUS component')
                raise
            port_dict['FUS'] = fusComp
            port_id_list.append(fusComp)
            print (' ')
 
        if 'FP' in port_names:
            fpComp = services.get_port('FP')
            if(fpComp == None):
                print('Error accessing FP component')
                raise
            port_dict['FP'] = fpComp
            port_id_list.append(fpComp)
            print (' ')

        if 'MONITOR' in port_names:
            monitorComp = services.get_port('MONITOR')
            if(monitorComp == None):
                print('Error accessing MONITOR component')
                raise       
            port_dict['MONITOR'] = monitorComp
            port_id_list.append(monitorComp)
            print (' ')

      # Is this a simulation startup or restart
        sim_mode = get_global_param(self, services,'SIMULATION_MODE')

      # Get timeloop for simulation
        timeloop = services.get_time_loop()
        tlist_str = ['%.3f'%t for t in timeloop]
        t = tlist_str[0]

      # Initialize components in PORTS list for startup or restart
        print (' ')
        
        init_mode = 'init'
        if sim_mode == 'RESTART' : init_mode = 'restart'

        if 'EPA' in port_names:
            self.component_call(services, 'EPA', epaComp, init_mode, t)
        
        if 'RF_EC' in port_names:
            self.component_call(services, 'RF_EC', rf_ecComp, init_mode, t)
        
        if 'RF_IC' in port_names:
            self.component_call(services, 'RF_IC', rf_icComp, init_mode, t)
        
        if 'RF_LH' in port_names:
            self.component_call(services, 'RF_LH', rf_lhComp, init_mode, t)

        if 'NB' in port_names:
            self.component_call(services, 'NB', nbComp, init_mode, t)

        if 'FUS' in port_names:
            self.component_call(services, 'FUS', fusComp, init_mode, t)

        if 'FP' in port_names:
            self.component_call(services, 'FP', fpComp, init_mode, t)

        if 'MONITOR' in port_names:
            self.component_call(services, 'MONITOR', monitorComp, init_mode, t)

      # Get plasma state files into driver work directory and copy to psn if there is one
        services.stage_plasma_state()
        cur_state_file = get_global_param(self, services, 'CURRENT_STATE')

       # Get Portal RUNID and save to a file
        run_id = get_global_param(self, services,'PORTAL_RUNID')
        sym_root = get_global_param(self, services,'SIM_ROOT')
        path = os.path.join(sym_root, 'PORTAL_RUNID')
        runid_file = open(path, 'a')
        runid_file.writelines(run_id + '\n')
        runid_file.close()

       # Post init processing: stage plasma state, stage output
        services.stage_output_files(t, self.OUTPUT_FILES)

        print(' init sequence complete--ready for time loop')

        INIT_ONLY = get_component_param(self, services, 'INIT_ONLY', optional = True)
        if INIT_ONLY in [True, 'true', 'True', 'TRUE']:   
            message = 'INIT_ONLY: Intentional stop after INIT phase'
            print(message)
            return

# ------------------------------------------------------------------------------
#
# Start Physics Layer
#
# ------------------------------------------------------------------------------


        # Iterate through the timeloop
        for t in tlist_str[1:len(timeloop)]:
            print (' ')
            print('Driver: step to time = ', t)
            services.update_time_stamp(t)

        # call pre_step_logic
            services.stage_plasma_state()
            self.pre_step_logic(services, float(t))
            services.update_plasma_state()
            print (' ')

       # Call step for each component

            print (' ')
            if 'RF_EC' in port_names:
                self.component_call(services, 'RF_EC', rf_ecComp, 'step', t)

            if 'RF_IC' in port_names:
                self.component_call(services, 'RF_IC', rf_icComp, 'step', t)

            if 'RF_LH' in port_names:
                self.component_call(services, 'RF_LH', rf_lhComp, 'step', t)

            if 'NB' in port_names:
                self.component_call(services, 'NB', nbComp, 'step', t)

            if 'FUS' in port_names:
                self.component_call(services, 'FUS', fusComp, 'step', t)

            if 'FP' in port_names:
                self.component_call(services, 'FP', fpComp, 'step', t)

            if 'EPA' in port_names:
                self.component_call(services, 'EPA', epaComp, 'step', t)

            if 'MONITOR' in port_names:
                self.component_call(services, 'MONITOR', monitorComp, 'step', t)

            services.stage_plasma_state()

         # Post step processing: stage plasma state, checkpoint components and self
            services.stage_output_files(t, self.OUTPUT_FILES)
            services.checkpoint_components(port_id_list, t)
            self.checkpoint(t)

# ------------------------------------------------------------------------------
#
# End of Physics Layer
#
# ------------------------------------------------------------------------------

      # Post simulation: call checkpoint on each component

        services.checkpoint_components(port_id_list, t, Force = True)
        self.checkpoint(t)
      
      # Post simulation: call finalize on each component
        print (' ')

        if 'RF_EC' in port_names:
            self.component_call(services, 'RF_EC', rf_ecComp, 'finalize', t)

        if 'RF_IC' in port_names:
            self.component_call(services, 'RF_IC', rf_icComp, 'finalize', t)

        if 'RF_LH' in port_names:
            self.component_call(services, 'RF_LH', rf_lhComp, 'finalize', t)

        if 'NB' in port_names:
            self.component_call(services, 'NB', nbComp, 'finalize', t)

        if 'FUS' in port_names:
            self.component_call(services, 'FUS', fusComp, 'finalize', t)

        if 'FP' in port_names:
            self.component_call(services, 'FP', fpComp, 'finalize', t)

        if 'EPA' in port_names:
            self.component_call(services, 'EPA', epaComp, 'finalize', t)

        if 'MONITOR' in port_names:
            self.component_call(services, 'MONITOR', monitorComp, 'finalize', t)