예제 #1
0
    def set_genray_EC_parameters(self, input_file, t, times_parameters_list):

        times_list = times_parameters_list[0]
        alfast_list = times_parameters_list[1]
        betast_list = times_parameters_list[2]
        powtot_list = times_parameters_list[3]

        # get parameters for each launcher at this time
        n_launchers = len(times_list)
        alfast_t = []
        betast_t = []
        powtot_t = []
        for i in range(n_launchers):
            alfast_launcher_t = self.piecewise_constant(
                t, times_list[i], alfast_list[i])
            alfast_t.append(alfast_launcher_t)
            betast_launcher_t = self.piecewise_constant(
                t, times_list[i], betast_list[i])
            betast_t.append(betast_launcher_t)
            powtot_launcher_t = self.piecewise_constant(
                t, times_list[i], powtot_list[i])
            powtot_t.append(powtot_launcher_t)

        # change parameters in namelist file
        lines = get_lines(input_file)
        lines = edit_nml_file(lines, 'alfast', alfast_t, separator=',')
        lines = edit_nml_file(lines, 'betast', betast_t, separator=',')
        lines = edit_nml_file(lines, 'powtot', powtot_t, separator=',')
        put_lines(input_file, lines)
    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)
    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 step(self, timeStamp, **kwargs):
        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_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')
        cur_dql_file = services.get_config_param('CURRENT_DQL')
        cur_cql_file = services.get_config_param('CURRENT_CQL')
        cur_ImChizz_inp_file = services.get_config_param('CURRENT_ImChizz_inp')
        print('CURRENT_CQL = ', cur_cql_file)
        # 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_changeme7:
            (errno, strerror) = xxx_todo_changeme7.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_changeme8:
            (errno, strerror) = xxx_todo_changeme8.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')

# Check if LHRF power is zero (or effectively zero).  If true don't run Genray

        ps = Dataset(cur_state_file, 'r+', format='NETCDF3_CLASSIC')
        power_lh = ps.variables['power_lh'][0]

        ps.close()
        print('power = ', power_lh)
        if (power_lh > 1.0E-04):

            # Copy current Dql file to generic name -> 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')

            cql3d_mode = self.CQL3D_MODE
            cql3d_output = self.CQL3D_OUTPUT
            cql3d_nml = self.CQL3D_NML
            nsteps_str = self.NSTEPS_STR
            deltat_str = self.DELTAT_STR
            ps_add_nml = self.PS_ADD_NML

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

            #if deltat_str .eq. 0 then use timestep ramp from GENRAY/CQL sims
            t0 = float(timeStamp)
            if (deltat_str == '0'):
                if (t0 < 5):
                    deltat_str = '0.00001'
                elif (t0 < 10):
                    deltat_str = '0.0001'
                elif (t0 < 30):
                    deltat_str = '0.001'
                elif (t0 < 40):
                    deltat_str = '0.005'
                else:
                    deltat_str = '0.01'

    # 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

# If this is the first step in a pwrscale iteration, and restart = 'enabled' (e.g. this
# is a restart) save the distrfunc.nc file to initial_distrfunc.nc.
            if 'icount_arg' in kwargs:
                icount = kwargs.get('icount_arg')
                if (icount == 1) and (restart == 'enabled'):
                    shutil.copyfile('distrfunc.nc', 'initial_distrfunc.nc')
                elif (icount > 1) and (restart == 'enabled'):
                    shutil.copyfile('initial_distrfunc.nc', 'distrfunc.nc')

    # 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: ', prepare_input_bin)
                services.error('Error executing cql3d prepare_input')
                raise Exception('Error executing cql3d prepare_input')

# ptb: Need to first copy the cqlinput_new file to cqlinput
            shutil.copyfile('cqlinput_new', 'cqlinput')

            # Check if this is a pwrscale iteration such that pwrscale needs to be reset in cqlinput
            if 'pwrscale_arg' in kwargs:
                pwrscale = kwargs.get('pwrscale_arg')
                self.change_cql3d_pwrscale_dbb(pwrscale)

#     Launch cql3d - N.B: Path to executable is in config parameter CQL3D_BIN
            print('fp_cql3d: launching cql3d')
            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)

            #          command = 'srun -N 12 -n 64  -c 6 /project/projectdirs/m77/CompX/CQL3D/master/xcql3d_mpi_intel.cori 2>>log.stdErr 1>>log.stdOut'
            #          retcode = subprocess.call(command.split(), stdout = log_file,\
            #                                    stderr = subprocess.STDOUT)
            if (retcode != 0):
                print('Error executing command: ', cql3d_bin)
                services.error('Error executing cql3d')
                raise

# If this is the first step in a pwrscale iteration, and restart = 'disabled' (i.e. this
# is first time cql3d has run) save the cql3d.nc file to initial_distrfunc.nc.
            if 'icount_arg' in kwargs:
                icount = kwargs.get('icount_arg')
                if (icount == 1) and (restart == 'disabled'):
                    shutil.copyfile('cql3d.nc', 'initial_distrfunc.nc')

    # 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'
            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 cql3d process_output ',
                      process_output_bin)
                services.error('Error executing cql3d process_output')
                raise Exception('Error executing cql3d process_output')

# Copy cql3d_output_file to cql3d.nc which is the filename that imchizz is expecting
            try:
                shutil.copyfile(cql3d_output_file, 'cql3d.nc')
            except IOError as xxx_todo_changeme2:
                (errno, strerror) = xxx_todo_changeme2.args
                print('Error copying file %s to %s' %
                      (cql3d_output_file, 'cql3d.nc', strerror))
                raise

    # 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_changeme2:
                (errno, strerror) = xxx_todo_changeme2.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
    # This way it can be used concurrently without overwriting other plasma state files.
            print('CURRENT_CQL = ', cur_cql_file)
            try:
                #            services.update_plasma_state(plasma_state_files = cur_cql_file)
                services.update_state(
                    state_files=[cur_cql_file, 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

        return 0  # return on "zero" LHRF power condition