Class: CodeRunner::Gs2

Inherits:
Run::FortranNamelist
  • Object
show all
Includes:
FixNormOption, GSLComplexTensors, GSLMatrices, GSLTensors, GSLVectorComplexes, GSLVectors, ReadNetcdf, GraphKits
Defined in:
lib/gs2crmod/gs2.rb,
lib/gs2crmod/ingen.rb,
lib/gs2crmod/graphs.rb,
lib/gs2crmod/test_gs2.rb,
lib/gs2crmod/properties.rb,
lib/gs2crmod/gsl_data_3d.rb,
lib/gs2crmod/read_netcdf.rb,
lib/gs2crmod/calculations.rb,
lib/gs2crmod/check_convergence.rb,
lib/gs2crmod/gsl_data.rb

Overview

This module reads data from the new diagnostics output file <run_name>.cdf.

It is intended to replace a lot of the function of gsl_data.rb which reads the old netcdf file. In particular, it defines a new generic reader function which can read any variable in the new netcdf file using a standard set of index constraints

Direct Known Subclasses

Astrogk

Defined Under Namespace

Modules: FixNormOption, GSLComplexTensors, GSLMatrices, GSLTensors, GSLVectorComplexes, GSLVectors, ReadNetcdf, TestGs2 Classes: Astrogk, GraphKits, InputFileError, ListSubmitter, NetcdfSmartReader, OldNetcdfSmartReader, Phi, Spectrogk

Constant Summary collapse

GS2_CRMOD_VERSION =

GS2_CRMOD_VERSION = Version.new(Gem.loaded_specs.version.to_s)

Version.new('0.5.0')
CODE_SCRIPT_FOLDER =
MODULE_FOLDER = File.dirname(File.expand_path(__FILE__))
NaN =
GSL::NAN
SPECIES_DEPENDENT_NAMELISTS =
eval(File.read(folder + '/species_dependent_namelists.rb'), binding, folder + '/species_dependent_namelists.rb')
SPECIES_DEPENDENT_VARIABLES_WITH_HELP =
SPECIES_DEPENDENT_NAMELISTS.values.inject({}) do |hash, namelist_hash|
  namelist_hash[:variables].each do |var, var_hash|
      hash[var] = var_hash[:help]
  end
  hash
end
SPECIES_DEPENDENT_VARIABLES =
SPECIES_DEPENDENT_VARIABLES_WITH_HELP.keys
MAX_NAME_SIZE =
310
AxisKit =

one day someone should get rid of this!

GraphKit::AxisKit
DataKit =
GraphKit::DataKit
GRAPHKIT_OPTIONS_HELP =
{
    t_index_window: "[begin, end], window of time indices to plot (e.g. t_index_window: [0,10])",
    t_index: "integer, index of time at which to plot (e.g. t_index: 20)",
    t: "float, value of time at which to plot (e.g. t: 2.45)",
    ky_index: "integer, index of ky at which to plot (e.g. ky_index: 20)",
    ky: "float, value of ky at which to plot (e.g. ky: 0.1)",
    kx_index: "integer, index of kx at which to plot (e.g. kx_index: 20)",
    kx: "float, value of kx at which to plot (e.g. kx: 0.1)",
    with: "Gnuplot Option (may not apply when using other packages), e.g. with: 'lp' or with 'pm3d palette'",
    rgbformulae: "Gnuplot Option (may not apply when using other packages), sets colour mapping. See gnuplot help set rgbformulae",
    limit: "Limit the range of quantity begin plotted - any values of the quantity outside the limits will be set to the limit: eg. limit: [0,80]",
    flip: 'Flip the y axis,  e.g. flip: true',
    rev: 'Reverse the x axis, e.g. rev: true',
    z: 'Plot quantities vs z = theta/shat rather than theta. See Beer, Cowley Hammet 1996, eg. z: true',
    norm: 'Normalise the graph so that its maximum is 1, e.g. norm: true',
    mag: 'Plot the magnitude, e.g. mag: true',
    species_index: "Which GS2 species to plot the graph for (1-based).",
  strongest_non_zonal_mode: "Plot the graph requested for the mode with the highest value of phi^2. Overrides ky, kx, ky_index, kx_index. Can be set true or false; e.g. strongest_non_zonal_mode: true",
    no_zonal: "Don't plot the ky=0 part (boolean, e.g. no_zonal: true)",
    no_kpar0: "Don't plot the kpar=0 part (boolean, e.g. no_kpar0: true)",
    log: "Plot the log of a given quantity (exact meaning varies). boolean",
    Rmaj: "The major radius in metres. This has no effect on the shape of the graph: it merely multiplies every length",
  n0: " The toroidal mode number of the longest y mode. In effect it is the number of periodic copies of the flux tube that will fit in the torus. Periodicity requires that n0 q  is also an integer. If you specify :n0 where this is not the case, q will automatically be adjusted until it is",
  rho_star: " The ratio of the reference Lamour radius to the GS2 normalising length a. Cannot be specified at the same time as n0. If specified, both n0 and q will be adjusted to ensure periodicity",
  nakx: "The number of radial wave numbers to include in the plot. In effect, it is a low pass filter which reduces the resolution in the radial direction without changing the shape of the final surface. Minimum value is 4",
  naky: "The number of kys to include in the plot. In effect, it is a low pass filter which reduces the resolution in the y direction without changing the shape of the final surface. Minimum value is 4",
  gs2_coordinate_factor: "When set to 1, plot the graph in GS2 coordinates. When set to  0 plot the graph in real space. Can be set at any value between 0 and 1: the graph will smoothly distort between the two limits",
  xmax: "The (0-based) index of the maximum value of x to include in the plot",
  xmin: "The (0-based) index of the minimum value of x to include in the plot",
  ymax: "The (0-based) index of the maximum value of y to include in the plot",
  ymin: "The (0-based) index of the minimum value of y to include in the plot",
  thetamax: "The (0-based) index of the maximum value of theta to include in the plot",
  thetamin: "The (0-based) index of the minimum value of theta to include in the plot",
    theta_index: "integer, index of theta at which to plot (e.g. theta_index: 20)",
    kxfac: "float, overrides calculation of kxfac in zonal flow velocity function",
    add_mean_flow: "bool, Adds mean flow to zonal flow velocity",
  ncopies: " The number of periodic copies of the flux tube to include",
  torphi_values: "An array of two values of the toroidal angle. The graph will be plotted in between those two values with poloidal cross sections at either end",
  magnify: " The magnification factor of the small section. It can take any value greater than or equal to 1",
}

Constants included from GSLTensors

GSLTensors::FIELD_VALUES, GSLTensors::IRRELEVANT_INDICES, GSLTensors::TIME_VARYING_INDICES, GSLTensors::TRIVIAL_INDICES

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from GSLMatrices

#es_heat_flux_over_ky_over_kx_gsl_matrix, #growth_rate_over_ky_over_kx_gsl_matrix, #phi0_over_x_over_y_gsl_matrix, #spectrum_over_ky_over_kpar_gsl_matrix, #spectrum_over_ky_over_kx_gsl_matrix, #transient_amplification_over_ky_over_kx_gsl_matrix

Methods included from GSLVectorComplexes

#phi_along_field_line_gsl_vector_complex, #phi_zonal_gsl_vector_complex

Methods included from GSLVectors

#apar2_over_time_gsl_vector, #drhodpsi_gsl_vector, #dt_gsl_vector, #es_heat_flux_by_kx_over_time_gsl_vector, #es_heat_flux_by_ky_over_time_gsl_vector, #es_heat_flux_over_kx_gsl_vector, #es_heat_flux_over_kxy_gsl_vector, #es_heat_flux_over_ky_gsl_vector, #es_heat_flux_over_time_gsl_vector, #es_heat_par_over_time_gsl_vector, #es_heat_perp_over_time_gsl_vector, #es_mom_flux_over_time_gsl_vector, #es_part_flux_over_time_gsl_vector, #frequency_by_kx_over_time_gsl_vector, #frequency_by_kxy_over_time_gsl_vector, #frequency_by_ky_over_time_gsl_vector, #growth_rate_by_kx_over_time_gsl_vector, #growth_rate_by_kxy_over_time_gsl_vector, #growth_rate_by_ky_over_time_gsl_vector, #growth_rate_over_kx_gsl_vector, #growth_rate_over_kx_slice_gsl_vector, #growth_rate_over_ky_gsl_vector, #growth_rate_over_ky_slice_gsl_vector, #hflux_tot_over_time_gsl_vector, #kpar_gsl_vector, #linked_kx_elements_gsl_vector, #lpc_energy_gsl_vector, #lpc_pitch_angle_gsl_vector, #mean_flow_velocity_over_x_gsl_vector, #par_mom_flux_over_time_gsl_vector, #perp_mom_flux_over_time_gsl_vector, #phi0_by_kx_by_ky_over_time_gsl_vector, #phi2_by_kx_over_time_gsl_vector, #phi2_by_ky_over_time_gsl_vector, #phi2_by_mode_over_time_gsl_vector, #phi2tot_over_time_gsl_vector, #phi_along_field_line_gsl_vector, #phi_for_eab_movie_gsl_vector, #scan_parameter_value_gsl_vector, #spectrum_over_kpar_gsl_vector, #spectrum_over_kx_avg_gsl_vector, #spectrum_over_kx_gsl_vector, #spectrum_over_kxy_avg_gsl_vector, #spectrum_over_kxy_gsl_vector, #spectrum_over_ky_avg_gsl_vector, #spectrum_over_ky_gsl_vector, #theta_along_field_line_gsl_vector, #tpar2_by_mode_over_time_gsl_vector, #tperp2_by_mode_over_time_gsl_vector, #transient_amplification_over_kx_gsl_vector, #transient_amplification_over_ky_gsl_vector, #transient_es_heat_flux_amplification_over_kx_gsl_vector, #transient_es_heat_flux_amplification_over_kxy_gsl_vector, #transient_es_heat_flux_amplification_over_ky_gsl_vector, #vres_energy_gsl_vector, #vres_pitch_angle_gsl_vector, #x_gsl_vector, #y_gsl_vector, #zf_velocity_over_x_gsl_vector, #zonal_spectrum_gsl_vector

Methods included from FixNormOption

#fix_heat_flux_norm, #fix_norm, #fix_norm_action

Methods included from ReadNetcdf

#new_ncclose, #new_netcdf_file, #new_netcdf_filename

Methods included from GSLComplexTensors

#field_gsl_tensor_complex, #phi_gsl_tensor_complex

Methods included from GSLTensors

#apar_gsl_tensor, #bpar_gsl_tensor, #cartesian_coordinates_gsl_tensor, #constant_torphi_surface_gsl_tensor, #correct_3d_options, #cylindrical_coordinates_gsl_tensor, #field_gsl_tensor, #field_netcdf_name, #field_real_space_gsl_tensor, #field_real_space_gsl_tensor_2, #field_species_element, #geometric_factors_gsl_tensor, #moment_gsl_tensor, #phi_real_space_gsl_tensor

Instance Attribute Details

#eigenfunctionsObject

Returns the value of attribute eigenfunctions.



372
373
374
# File 'lib/gs2crmod/gs2.rb', line 372

def eigenfunctions
  @eigenfunctions
end

#iphi00Object

Necessary for back. comp. due to an old bug



1079
1080
1081
# File 'lib/gs2crmod/gs2.rb', line 1079

def iphi00
  @iphi00
end

#ky_graphsObject

Returns the value of attribute ky_graphs.



372
373
374
# File 'lib/gs2crmod/gs2.rb', line 372

def ky_graphs
  @ky_graphs
end

#ky_listObject

Returns the value of attribute ky_list.



372
373
374
# File 'lib/gs2crmod/gs2.rb', line 372

def ky_list
  @ky_list
end

#saturation_timeObject

Necessary for back. comp. due to an old bug



1079
1080
1081
# File 'lib/gs2crmod/gs2.rb', line 1079

def saturation_time
  @saturation_time
end

#scan_index_windowObject

Returns the value of attribute scan_index_window.



373
374
375
# File 'lib/gs2crmod/gs2.rb', line 373

def scan_index_window
  @scan_index_window
end

#scan_parameter_valueObject

Returns the value of attribute scan_parameter_value.



373
374
375
# File 'lib/gs2crmod/gs2.rb', line 373

def scan_parameter_value
  @scan_parameter_value
end

#t_listObject

Returns the value of attribute t_list.



372
373
374
# File 'lib/gs2crmod/gs2.rb', line 372

def t_list
  @t_list
end

#theta_listObject

Returns the value of attribute theta_list.



372
373
374
# File 'lib/gs2crmod/gs2.rb', line 372

def theta_list
  @theta_list
end

Class Method Details

.add_variable_to_namelist(namelist, var, value) ⇒ Object



937
938
939
940
# File 'lib/gs2crmod/gs2.rb', line 937

def self.add_variable_to_namelist(namelist, var, value)
  var = :stir_ + var if namelist == :stir
  super(namelist, var, value)
end

.cacheObject



103
104
105
106
# File 'lib/gs2crmod/graphs.rb', line 103

def self.cache
    @cache ||= {}
    @cache
end

.check_and_updateObject



377
378
379
380
# File 'lib/gs2crmod/gs2.rb', line 377

def check_and_update
  old_check_and_update
  @readout_list = (@variables + @results - [:growth_rates_by_ky, :growth_rates, :real_frequencies, :real_frequencies_by_ky, :ky_list, :kx_list, :theta_list, :t_list])
end

.defaults_file_headerObject



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
# File 'lib/gs2crmod/gs2.rb', line 967

def self.defaults_file_header
  <<EOF1
######################################################################
#   Automatically generated defaults file for GS2 CodeRunner module  #
#                                                                    #
# This defaults file specifies a set of defaults for GS2 which are   #
# used by CodeRunner to set up and run GS2 simulations.              #
#                                                                    #
# Created #{Time.now.to_s}                                           #
#                                                                    #
######################################################################

@defaults_file_description = ""
EOF1
end

.generate_graphs_rdoc_fileObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/gs2crmod/graphs.rb', line 108

def self.generate_graphs_rdoc_file
    File.open('graphs_rdoc.rb', 'w') do |file|
    graphs = self.instance_methods.find_all{|m| m.to_s =~ /_graphkit$/}.sort_by{|m| m.to_s}
    run = new(nil)
    file.puts "class #{self.to_s}::GraphKits\n"
    graphs.each do |graph|
        help = run.send(graph, command: :help)
        options = run.send(graph, command: :options)
        file.puts "# #{help}"
        if options and options.size > 0
            file.puts "# Options:"
            options.each do |op|
                file.puts "#\n# #{op}: #{GRAPHKIT_OPTIONS_HELP[op]}"
            end
        end
        file.puts "def #{graph}\nend"
    end
    file.puts "end"
    end
end

.help_graphsObject



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/gs2crmod/graphs.rb', line 129

def self.help_graphs
#   @@runner ||= CodeRunner.fetch_runner(U: true, 
    string = ""
    graphs = self.instance_methods.find_all{|m| m.to_s =~ /_graphkit$/}.sort_by{|m| m.to_s}
    run = new(nil)
    string << "-------------------------------------------\n    Available Graphs For #{self.to_s}\n-------------------------------------------\n\n"
    graphs.each do |graph|
        help = run.send(graph, command: :help)
        options = run.send(graph, command: :options)
        string << "\n------------------------------------\n#{graph.to_s.sub(/_graphkit/, '')}\n------------------------------------\n\n#{help}\n"
        if options and options.size > 0
            string << "\n\tOptions:\n"
            options.each do |op|
                string << "\t\t#{op}: #{GRAPHKIT_OPTIONS_HELP[op]}\n"
            end
        end
        
    end
    string.paginate
end

.list_code_commandsObject



933
934
935
# File 'lib/gs2crmod/gs2.rb', line 933

def self.list_code_commands
  puts (methods - Run.methods).sort
end

.modify_job_script(runner, runs_in, script) ⇒ Object



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# File 'lib/gs2crmod/gs2.rb', line 735

def self.modify_job_script(runner, runs_in, script)
  if CODE_OPTIONS[:gs2] and CODE_OPTIONS[:gs2][:list]
    if (list_size = CODE_OPTIONS[:gs2][:list]).kind_of? Integer
      raise "The total number of runs must be a multiple of the list size!" unless runs_in.size % list_size == 0
      pieces = runs_in.pieces(runs_in.size/list_size)
    else
      pieces = [runs_in]
    end
    script = ""
    pieces.each do |runs|
      #ep 'there is a list'
      FileUtils.makedirs('job_lists')
      jid = "#{runs[0].id}-#{runs[-1].id}"
      list_file = "job_lists/gs2_list_#{jid}.list"
      File.open(list_file,'w') do |file|
        file.puts runs.size
        file.puts runs.map{|r| "#{r.relative_directory}/#{r.run_name}"}.join("\n")
      end
      raise "runs must all have the same nprocs" unless runs.map{|r| r.nprocs}.uniq.size == 1
      runs.each do |r|
        # Make sure the restart file name includes the relative directory for
        # list runs
        reldir = r.relative_directory
        rdir = r.restart_dir
        #puts rdir[0...reldir.size] == reldir, rdir[0...reldir.size], reldir
        #raise ""
        if rdir
          r.restart_dir = reldir + '/' + rdir if not rdir[0...reldir.size] == reldir
        else
          r.restart_dir = reldir
        end
        Dir.chdir(r.directory){r.write_input_file}
      end
      np = runs[0].nprocs.split('x').map{|n| n.to_i}
      np[0] *= runs.size
      nprocs = np.map{|n| n.to_s}.join('x')
      @runner.nprocs = nprocs
      ls = ListSubmitter.new(@runner, nprocs, list_file, jid)
      script << ls.run_command
    end
  end
  return script
end

.test_gs2(*args) ⇒ Object

See TestGs2



6
7
8
# File 'lib/gs2crmod/test_gs2.rb', line 6

def self.test_gs2(*args)
	TestGs2.test_gs2(*args)
end

Instance Method Details

#actual_number_of_processorsObject Also known as: anop



898
899
900
901
# File 'lib/gs2crmod/gs2.rb', line 898

def actual_number_of_processors
  raise "Please specify the processor layout using the -n or (n:) option" unless @nprocs
  @nprocs.split('x').map{|n| n.to_i}.inject(1){|ntot, n| ntot*n}
end

#agk?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/gs2crmod/gs2.rb', line 52

def agk?
  false
end

#approximate_grid_sizeObject Also known as: agridsze



904
905
906
907
908
909
910
911
# File 'lib/gs2crmod/gs2.rb', line 904

def approximate_grid_size
  case @grid_option
  when "box"
  (2*(@nx-1)/3+1).to_i * (@naky||(@ny-1)/3+1).to_i * @ntheta * (2 * @ngauss + @ntheta/2).to_i * @negrid * 2 * @nspec
  else
    @ntheta * (2 * @ngauss + @ntheta/2).to_i * @negrid * 2 * @nspec
  end
end

#auto_axiskits(name, options) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/gs2crmod/graphs.rb', line 11

def auto_axiskits(name, options)
    hash = cache[:auto_axiskits] ||= {'t' => ['Time', ''],
    'phi2tot_over_time' => ['Phi^2 Total', ''],
    'apar2_over_time' => ['Apar^2 Total', ''],
    'es_heat_flux_by_ky_over_time' => ['Heat flux by ky', ''],
    'es_heat_flux_by_kx_over_time' => ['Heat flux by kx', ''],  
    'es_heat_par' => ['Parallel electrostatic heat flux', ''],
    'es_heat_perp' => ['Perpendicular electrostatic heat flux', ''],
    'es_heat_flux_over_kx' => ["Heat Flux at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", 'Q_gB', 1],
    'es_heat_flux_over_ky' => ["Heat Flux at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", 'Q_gB', 1],
    'es_heat_flux_over_ky_over_kx' => ["Heat flux at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 2],
    'es_mom_flux_over_time' => ["#{species_type((options[:species_index] or 1)).capitalize} Momentum Flux", '', 1],
    'es_part_flux_over_time' => ["#{species_type((options[:species_index] or 1)).capitalize} Particle Flux", '', 1],
    'frequency_over_kx' => ['Frequency', "v_th#{species_letter}/a", 1],
    'frequency_over_ky' => ['Frequency', "v_th#{species_letter}/a", 1],
    'frequency_by_ky_over_time' => ['Real frequency by ky', ''],
    'frequency_by_kx_over_time' => ['Real frequency by kx', ''],
    'growth_rate_by_ky_over_time' => ['Growth Rate by ky', ''],
    'growth_rate_by_kx_over_time' => ['Growth Rate by kx', ''],  
    'growth_rate_by_mode_over_time' => ["Growth Rate by mode", ''],
    'growth_rate_over_kx' => ['Growth Rate', "v_th#{species_letter}/a", 1],
    'growth_rate_over_ky' => ['Growth Rate', "v_th#{species_letter}/a", 1],
    'growth_rate_over_kx_slice' => ['Growth Rate', "v_th#{species_letter}/a", 1],
    'growth_rate_over_ky_slice' => ['Growth Rate', "v_th#{species_letter}/a", 1],
    'growth_rate_over_ky_over_kx' => ["Growth Rate", "v_th#{species_letter}/a", 2],
    'hflux_tot' => ['Total Heat Flux', ''],
    'kpar' => ['kpar', "2 pi/qR"],
    'ky' => ['ky', "1/rho_#{species_letter}"],
    'kx' => ['kx', "1/rho_#{species_letter}"],
    'phi2_by_ky_over_time' => ['Phi^2 by ky', ''],
    'phi2_by_kx_over_time' => ['Phi^2 by ky', ''],  
    'phi2_by_mode_over_time' => ["Phi^2 by mode", ''],
    'tpar2_by_mode_over_time' => ["(delta T_parallel)^2 by mode", '%'],
    'tperp2_by_mode_over_time' => ["(delta T_perp)^2 by mode", '%'],
    'x' => ['x', "rho_#{species_letter}", 1],
    'spectrum_over_kx' => ["Spectrum at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 1],
    'spectrum_over_kx_avg' => ["Spectrum Averaged Over Time", '', 1],
    'spectrum_over_ky' => ["Spectrum at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 1],
    'spectrum_over_ky_avg' => ["Spectrum Averaged Over Time", '', 1],
    'spectrum_over_kpar' => ["Spectrum at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 1],
    'spectrum_over_ky_over_kx' => ["Spectrum at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 2],
    'spectrum_over_ky_over_kpar' => ["Spectrum at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 2],
    #'phi0_over_x_over_y' => ["Phi at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 2],
    'phi0_over_x_over_y' => ["Phi at theta = 0", '', 2],
    'transient_es_heat_flux_amplification_over_kx' => ['Transient Electrostatic Heat Amplification', "", 1],
    'transient_es_heat_flux_amplification_over_ky' => ['Transient Electrostatic Heat Amplification', "", 1],
    'transient_amplification_over_kx' => ['Transient Amplification', "", 1],
    'transient_amplification_over_ky' => ['Transient Amplification', "", 1],
    'zonal_spectrum' => ["Zonal spectrum at t = #{sprintf("%.3f" ,(options[:t] or list(:t)[options[:t_index]] or list(:t).values.max))}", '', 1],
    'zf_velocity_over_x' => ['Zonal Flow Velocity', "", 1],
    'mean_flow_velocity_over_x' => ['Mean Flow Velocity', "", 1]
  }
    return hash[name]
end

#axiskit(name, options = {}) ⇒ Object

Raises:

  • (CRError)


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/gs2crmod/graphs.rb', line 66

def axiskit(name, options={})
    logf :axiskit
    if info = auto_axiskits(name, options)
        if info[2] and info[2] == 2
            axis =  GraphKit::AxisKit.autocreate({data: gsl_matrix(name, options), title: info[0], units: info[1]})
        elsif !info[2] or info[2] == 1
            axis =  GraphKit::AxisKit.autocreate({data: gsl_vector(name, options), title: info[0], units: info[1]})
            log 'successfully created axis'
        end
        return axis
    end
    case name
    when 'phi_along_field_line'
        title = options[:imrc].to_s.capitalize + " Phi"
        units = ""
        return GraphKit::AxisKit.autocreate(data: gsl_vector(name, options), title: title, units: units)
    when 'theta_along_field_line'
        title =  options[:z] ? "z/l_B" : 'Theta' 
        units = options[:z] ? '' : 'radians'
        return GraphKit::AxisKit.autocreate(data: gsl_vector(name, options), title: title, units: units)
    when 'es_heat_flux'
        type = species_type(options[:species_index]).capitalize
        units = ''
        return GraphKit::AxisKit.autocreate(data: gsl_vector('es_heat_flux_over_time', options), title: "#{type} Heat Flux", units: units)
#   when 'spectrum_by_ky'
#       return AxisKit.autocreate(data: gsl_vector('spectrum_by_ky', options), title: "Phi^2 at t = #{list(:t)[options[:t_index]]}", units: '')
    when 'es_heat_par'
    puts "heat par" 
        type = species_type(options[:species_index]).capitalize
        units = ''
        return GraphKit::AxisKit.autocreate(data: gsl_vector('es_heat_par_over_time', options), title: "#{type} parallel es heat flux", units: units)
#   when 'spectrum_by_ky'
#       return AxisKit.autocreate(data: gsl_vector('spectrum_by_ky', options), title: "Phi^2 at t = #{list(:t)[options[:t_index]]}", units: '')
    end
    raise CRError.new("Unknown axis kit: #{name}")
end

#box_kx_index(physical_kx_index) ⇒ Object



1494
1495
1496
1497
# File 'lib/gs2crmod/gsl_data.rb', line 1494

def box_kx_index(physical_kx_index)

  return kx_indexed[physical_kx_index]
end

#calculate_frequenciesObject



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/gs2crmod/calculations.rb', line 270

def calculate_frequencies
  @real_frequencies = FloatHash.new
  @frequency_at_ky_at_kx ||= FloatHash.new
  omega_avg_narray = netcdf_file.var("omega_average").get('start' => [0, 0, 0, -1], 
                                                          'end' => [0, -1, -1, -1])
  omega_avg_narray.reshape!(*omega_avg_narray.shape.slice(1..2))

  if @grid_option == 'single'
    @frequency_at_ky_at_kx = omega_avg_narray[0]
  else
    list(:ky).values.sort.each_with_index do |kyv, i|
      @frequency_at_ky_at_kx[kyv] = FloatHash.new
      list(:kx).values.sort.each_with_index do |kxv, j|	
        @frequency_at_ky_at_kx[kyv][kxv] = omega_avg_narray[j, i]
      end
      write_results
    end
  end
end

#calculate_growth_rate(vector, options = {}) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/gs2crmod/calculations.rb', line 371

def calculate_growth_rate(vector, options={})
  raise "This vector should be positive definite" if vector.min < 0.0
  offset = 0
  length = vector.length
  while vector[offset] == 0.0
    offset+=1
    return 0.0 if offset == vector.length
  end
  growth_rate = GSL::Fit::linear(gsl_vector(:t).subvector(offset, length-offset), 0.5*GSL::Sf::log(vector.subvector(offset, length - offset)))[1]
  divisor = 1
  while (growth_rate.to_s == "NaN")
    #This corrects the growth rate if phi has grown all the way to NaN during the simulation
    divisor *= 2
    length = (vector.size.to_f / divisor.to_f).floor
    return "NaN" if length <= offset + 1
    growth_rate = GSL::Fit::linear(gsl_vector(:t).subvector(offset, length-offset), 0.5*GSL::Sf::log(vector.subvector(offset, length-offset)))[1]
  end	
  growth_rate
end

#calculate_growth_rates_and_frequenciesObject Also known as: cgrf



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/gs2crmod/calculations.rb', line 290

def calculate_growth_rates_and_frequencies
  return if @grid_option == "single" and @aky == 0.0 # no meaningful results
  
  Dir.chdir(@directory) do
    logf(:calculate_growth_rates_and_frequencies)
    logd

    calculate_frequencies
    
    @growth_rates= FloatHash.new
    
    # With zero magnetic shear, calculate growth rates for both kx and ky
    to_calc = [:kx, :ky]
    @growth_rate_at_kx ||= FloatHash.new
    
    @growth_rate_at_ky ||= FloatHash.new
    eputs
    to_calc.each do |kxy|
      growth_rates = send(:growth_rate_at_ + kxy)
      list(kxy).values.sort.each do |value|
      
      next if growth_rates.keys.include? value
      
      Terminal.erewind(1)
      #ep growth_rates.keys
      eputs sprintf("Calculating growth rate for #{kxy} = % 1.5e#{Terminal::CLEAR_LINE}", value) 

      # Mode has 0 growth rate at ky==0
      (growth_rates[value] = 0.0; next) if value == 0.0 and kxy == :ky 
      if @g_exb_start_timestep
          t_index_window = [1, [(g_exb_start_timestep-1)/@nwrite, list(:t).keys.max].min]
      else
          t_index_window = nil
      end
      if list(kxy).size == 1
          phi2_vec = gsl_vector("phi2tot_over_time", t_index_window: t_index_window)
      else
          phi2_vec = gsl_vector("phi2_by_#{kxy}_over_time", kxy=>value, :t_index_window=> t_index_window)
      end
      (growth_rates[value] = 0.0; next) if phi2_vec.min <= 0.0
      growth_rates[value] = calculate_growth_rate(phi2_vec)
      (eputs "\n\n----------\nIn #@run_name:\n\nphi2_by_#{kxy}_over_time is all NaN; unable to calculate growth rate\n----------\n\n"; growth_rates[value] = -1; next) if growth_rates[value] == "NaN"
    end
  end
      
    write_results
    
    if ENV['GS2_CALCULATE_ALL']
    trap(0){eputs "Calculation of spectrum did not complete: run 'cgrf' (i.e. calculate_growth_rates_and_frequencies) for this run. E.g. from the command line \n $ coderunner rc 'cgrf' -j #{@id}"; exit}
    @growth_rate_at_ky_at_kx ||= FloatHash.new
    list(:ky).values.sort.each do |kyv|
      @growth_rate_at_ky_at_kx[kyv] = FloatHash.new
      list(:kx).values.sort.each do |kxv|	
        Terminal.erewind(1)
        eputs sprintf("Calculating growth rate for kx = % 1.5e and ky = % 1.5e#{Terminal::CLEAR_LINE}", kxv, kyv) 
        (@growth_rate_at_ky_at_kx[kyv][kxv] = 0.0; next) if kyv == 0.0 # Mode has 0 growth rate at ky==0
        phi2_vec = gsl_vector("phi2_by_mode_over_time", {:kx=>kxv, :ky=>kyv})
        (@growth_rate_at_ky_at_kx[kyv][kxv] = 0.0; next) if phi2_vec.min <= 0.0
        @growth_rate_at_ky_at_kx[kyv][kxv] = calculate_growth_rate(phi2_vec)
        (eputs "\n\n----------\nIn #@run_name:\n\nphi2_by_#{kxy}_over_time is all NaN; unable to calculate growth rates\n----------\n\n"; @growth_rate_at_ky_at_kx[kyv][kxv] = -1; next) if @growth_rate_at_ky_at_kx[kyv][kxv] == "NaN" 
      end
      write_results
    end
    trap(0){}
    end
    @growth_rates = @growth_rate_at_ky
    @max_growth_rate = @growth_rates.values.max
    @fastest_growing_mode = @growth_rates.key(@max_growth_rate)
@freq_of_max_growth_rate = @real_frequencies[@fastest_growing_mode] rescue nil
    ep @max_growth_rate, @growth_rates
    @decaying = (@max_growth_rate < 0) if @max_growth_rate
    @ky = @aky if @aky
    if @grid_option == "single"
      @gamma_r = @growth_rates[@aky.to_f]
      @gamma_i = @real_frequencies[@aky.to_f]
    end
  end
end

#calculate_prandtl_numberObject



751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'lib/gs2crmod/calculations.rb', line 751

def calculate_prandtl_number
  
  @prandtl_number = {}
  @nspec.times do |i|
    @prandtl_number[i+1] = nil
  end
  write_results

  if @g_exb == 0
    eputs 'g_exb = 0 therefore Prandtl number is undefined.'
    return nil
  elsif @nonlinear_mode=="off"
    eputs 'Prandtl number only makes sense for a nonlinear run.'
    return nil
  elsif @local_eq.fortran_false?
    eputs 'Prandtl number currently only calculated for Miller equilibrium.'
    return nil
  end

  @nspec.times do |i|
    species_index = i + 1
    @prandtl_number[species_index] = - (@rhoc/@qinp/@rmaj**2) * 
                                       (eval("@tprim_#{species_index}")/@g_exb) * 
                                       (@es_mom_flux_stav[species_index]/
                                        @es_heat_flux_stav[species_index])
  end
  write_results
end

#calculate_resultsObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/gs2crmod/gs2.rb', line 230

def calculate_results
  return if ENV['CODE_RUNNER_NO_ANALYSIS'] =~ /true/

  eputs "Analysing run"

  if @nonlinear_mode == "off"
    calculate_transient_amplifications
  elsif @nonlinear_mode == "on"
    calculate_saturation_time_index
    calculate_time_averaged_fluxes
    begin
      calculate_spectral_checks
      calculate_vspace_checks
    rescue
    end
  end

  @growth_rates ||={}
  @real_frequencies ||={}
end

#calculate_saturation_time_index(show_graph = false) ⇒ Object Also known as: csti

I.e. the time at which the primary modes are saturated and the fluxes settle around a long term average.



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/gs2crmod/calculations.rb', line 126

def calculate_saturation_time_index(show_graph = false)
	
	eprint "Checking for saturation..."

	#hflux = gsl_vector('hflux_tot_over_time', {})
	hflux = gsl_vector('phi2tot_over_time', {})
	
 	#eputs 'got hflux'
	#ep 'hflux', hflux
	
	#Check if it's decayed to 0
	if hflux[-1] < 1.0e-10
		for i in 1..hflux.size
# 			raise "negative heat flux: #{hflux[-i]} " if hflux[-i] < 0
			(break) unless hflux[- i] < 1.0e-10
		end
		if i > hflux.size * 1.0/10.0 #i.e if was 0 for more than a tenth of the time
			@saturated = true
			@saturation_time_index = hflux.size - i + 1
			eputs "saturation time = #{list(:t)[@saturation_time_index]}"
			GraphKit.quick_create([gsl_vector('t',{}), hflux]).gnuplot(log_axis: 'y') if show_graph
			return
		end
	end
		
	# Get initial estimate for saturation time
	for i in 0...hflux.size
		rem = hflux.subvector(i, hflux.size - i)
		break if (hflux[i] - rem.mean).abs < rem.sd / 2.0
		break if i > 3.0/4.0*hflux.size
	end
	
	@saturation_time_index = [i + 1, hflux.size - 2].min
	
# 	fit = GSL::Fit::linear(GSL::Vector.indgen(rem.size), rem)
# 	
# 	slope, covar11 = fit[1], fit[4]
# 	range = [slope + Math.sqrt(covar11), slope - Math.sqrt(covar11)]
# 	
# 	unless range.min < 0 and range.max > 0
# 		eputs "Warning: This run (#{id}) has probably not reached a saturated state: the estimated slope of the heat flux is in this range: #{range.inspect}"
# 		@saturated = false
# 	end
# 	
# 	ep fit
	
# 	eputs "Saturation time estimate', @saturation_time_index = i + 1
# 	t_vec[@saturation_time_index - 1]
	max_t_index = list(:t).keys.max
	max_t = list(:t).values.max
	min_t = list(:t).values.min
	#hflux = gsl_vector('hflux_tot_over_time', {:t_index_window => [@saturation_time_index, max_t_index]})
	hflux = gsl_vector('phi2tot_over_time', {:t_index_window => [@saturation_time_index, max_t_index]})
	t_vec = gsl_vector('t', {:t_index_window => [@saturation_time_index, max_t_index]})
# 	p t_vec[0]
	i = 0
	t_arr = []; conf_arr = []
	loop do
		eprint '.'
		
# 		GraphKit.autocreate(x: {data: t_vec}, y: {data: hflux}).gnuplot
		
		lomb = GSL::SpectralAnalysis::Lomb.alloc(t_vec.subvector(i, t_vec.size - i),  hflux.subvector(i, hflux.size - i))
		fs, periodogram = lomb.calculate_periodogram(1.0, 4.0, [0]) #(1.0) #0.1 * hflux.size / ( hflux.size - i))
# 		lomb.graphkit.gnuplot
		
# 		eputs 'Confidence that lowest frequency is not noise is: '
		# pnoise is the probability of the strength of the lowest frequency signal in the heat flux given a hypothesis of gaussian noise. If it is high there is a low likelihood that there is a signal at the lowest frequency: ie. within that window the heat flux has reached a stationary state
		pnoise = lomb.pnull(periodogram[0])
		t_arr.push t_vec[i]; conf_arr.push pnoise
		
		(@saturated = true; break) if pnoise > 0.9
		step = (hflux.size / 25.0).to_i
		step = 1 if step==0
		i += step
		#(@saturated = false; i ; break) if (i >= t_vec.size or t_vec[i] > (max_t - min_t) * 2.0 / 3.0 + min_t )
		(@saturated = false; break) if (i >= t_vec.size or t_vec[i] > (max_t - min_t) * 2.0 / 3.0 + min_t )
		@saturation_time_index += step	
#		ep '---i,t,size',i, t_vec[i], t_vec.size
	end
	(kit = GraphKit.autocreate({x: {data: t_vec}, y: {data: hflux / hflux.max}}, {x: {data: t_arr}, y: {data: conf_arr}}); kit.data[1].with = 'lp'; kit.gnuplot) if show_graph #(log_axis: 'y')
# 	puts 
	if @saturated
# 		p i
		eputs "saturation time = #{list(:t)[@saturation_time_index]}"
	else
		eputs "run not saturated"
	end
		
	return
	exit
	# Get regularly spaced t vector
	
# 	
# 	t_delta_vec = GSL::Vector.alloc(t_vec.size - 1)
# 	t_delta_vec.size.times.each{|i| t_delta_vec[i] = t_vec[i+1] - t_vec[i]}
# 	
# 	ep t_delta_vec.max, t_delta_vec.min
# 	
# 	even_t = GSL::Vector.linspace(t_vec.min, t_vec.max, ((t_vec.max - t_vec.min) / t_delta_vec.max).round )
# 	
# # 	even_t = []
# # 	tm = t = t_vec[t_delta_vec.max_index]
# 	
# # 	loop do
# # 		even_t.push t
# 		
# # 	
# 	ep even_t.size, t_vec.size
# 	
# 	min_delt = t_delta_vec.min
# 	p even_t.any?{|el| bool = (not t_vec.any?{|ele| (ele - el).abs < 1.0e-1 * min_delt}); ep el if bool; bool}
# 	
# 	ep t_vec.dup.delete_if{|el| not (el - 71.3).abs < 0.5}
# 	
# 	exit
	
	return
	
	# Calculate a series of time averaged segments
	pieces = hflux.pieces(20) # split into 20 pieces
	avgs = GSL::Vector.alloc(pieces.map{|vec| vec.sum/vec.size})
	# Calculate their variance
	mean = (avgs.sum/avgs.size)
	sig = Math.sqrt((avgs.square - mean**2).sum/avgs.size)
	# Discount any at the start which are more than one standard deviation away from the average - they are from the linear growth phase
	t_index = 1
	kept_avgs = avgs.dup
	for i in 0...pieces.size
		if (avgs[i] - mean).abs > sig
			kept_avgs.delete_at(i)
			t_index += pieces[i].size
		else
			break
		end
	end
	eputs "Warning: probably not saturated" if [kept_avgs, kept_avgs.reverse].include? kept_avgs.sort
	ep kept_avgs
	@saturation_time_index = t_index
# 	p t_index, list(:t)[t_index]
end

#calculate_spectral_checksObject Also known as: csc



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/gs2crmod/calculations.rb', line 691

def calculate_spectral_checks
  #kx = gsl_vector('kx')
  ky = gsl_vector('ky')
  ky_spec = gsl_vector('spectrum_over_ky')
  kx_spec = gsl_vector('spectrum_over_kx')
  kpar_spec = gsl_vector('spectrum_over_kpar', ky_index: ky_spec.max_index + 1, kx_index: 1)
  
  @spectrum_check = []
  [kx_spec, ky_spec, kpar_spec].each do |spec|
    begin
      ends_max = [spec[0], spec[-1]].max + (10.0**(-9))
      p ends_max 		
      p spec.max
      check = (Math.log(spec.max/ends_max)/Math.log(10)).round
    rescue
      check= -10
    end
    @spectrum_check.push check
  end

  #Calculate peak kx, ky spectrum values and associated phi2 values
  @ky_spectrum_peak_idx = ky_spec.max_index 
  @ky_spectrum_peak_ky = ky[@ky_spectrum_peak_idx] 

  #Also want to know the phi2 at the energy containing scales and for ZFs
  #Pick phi2 at the final time step.
  phi_vec = gsl_vector('phi2_by_ky_over_time', ky_index:@ky_spectrum_peak_idx)
  @ky_spectrum_peak_phi2 = phi_vec[-1] 
  phi_vec = gsl_vector('phi2_by_ky_over_time', ky_index:1)
  @phi2_zonal = phi_vec[-1] 
end

#calculate_time_averaged_fluxesObject Also known as: ctaf



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/gs2crmod/calculations.rb', line 16

def calculate_time_averaged_fluxes
	eputs 'Calculating time averaged fluxes'
	calculate_saturation_time_index unless @saturation_time_index
	return unless FileTest.exist?(netcdf_filename)
	@hflux_tot_stav = saturated_time_average('hflux_tot_over_time', {})
	@hflux_tot_stav_error = saturated_time_average_error('hflux_tot_over_time', {})
	@hflux_tot_stav_std_dev = saturated_time_average_std_dev('hflux_tot_over_time', {})
	@phi2_tot_stav = saturated_time_average('phi2tot_over_time', {})

	@es_part_flux_stav = {}
	@es_mom_flux_stav = {}
	@es_heat_flux_stav = {}

	@es_part_flux_stav_error = {}
	@es_mom_flux_stav_error = {}
	@es_heat_flux_stav_error = {}

	@es_part_flux_stav_std_dev = {}
	@es_mom_flux_stav_std_dev = {}
	@es_heat_flux_stav_std_dev = {}

	@nspec.times do |i|
		species_index = i + 1
		@es_part_flux_stav[species_index]  = saturated_time_average('es_part_flux_over_time', {species_index: species_index})
		@es_mom_flux_stav[species_index]  = saturated_time_average('es_mom_flux_over_time', {species_index: species_index})
		@es_heat_flux_stav[species_index]  = saturated_time_average('es_heat_flux_over_time', {species_index: species_index})

		@es_part_flux_stav_error[species_index]  = saturated_time_average_error('es_part_flux_over_time', {species_index: species_index})
		@es_mom_flux_stav_error[species_index]  = saturated_time_average_error('es_mom_flux_over_time', {species_index: species_index})
		@es_heat_flux_stav_error[species_index]  = saturated_time_average_error('es_heat_flux_over_time', {species_index: species_index})

		@es_part_flux_stav_std_dev[species_index]  = saturated_time_average_std_dev('es_part_flux_over_time', {species_index: species_index})
		@es_mom_flux_stav_std_dev[species_index]  = saturated_time_average_std_dev('es_mom_flux_over_time', {species_index: species_index})
		@es_heat_flux_stav_std_dev[species_index]  = saturated_time_average_std_dev('es_heat_flux_over_time', {species_index: species_index})
	end
end

#calculate_transient_amplification(vector, options = {}) ⇒ Object



633
634
635
636
637
638
639
640
641
642
# File 'lib/gs2crmod/calculations.rb', line 633

def calculate_transient_amplification(vector, options={})
  if @g_exb and @g_exb > 0.0 and @g_exb_start_timestep
    return GSL::Sf::log(vector[(@g_exb_start_timestep/@nwrite).to_i...-1].max / 
                        vector[(@g_exb_start_timestep/@nwrite).to_i])/2
  else
    eputs "Warning: Transient amplification not calculated since g_exb and "\
          "g_exb_start_timestep not set."
    return 0
  end
end

#calculate_transient_amplificationsObject Also known as: cta



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/gs2crmod/calculations.rb', line 396

def calculate_transient_amplifications
  return if @grid_option == "single" and @aky == 0.0 # no meaningful results
	Dir.chdir(@directory) do
		# With zero magnetic shear, calculate amplifications for both kx and ky
		if @shat and @shat.abs < 1.0e-5 and @nx > 1 
			to_calc = [:kx, :ky]
			@transient_amplification_at_kx ||= FloatHash.new
		else
			to_calc = [:ky]
		end
		
		@transient_amplification_at_ky ||= FloatHash.new
		@max_transient_amplification_index_at_ky ||= FloatHash.new
 		eputs
		to_calc.each do |kxy|
			transient_amplifications = send(:transient_amplification_at_ + kxy)
			list(kxy).values.sort.each do |value|
				next if transient_amplifications.keys.include? value
				
				Terminal.erewind(1)
				eputs sprintf("Calculating transient amplification for #{kxy} = % 1.5e#{Terminal::CLEAR_LINE}", value) 
                
                # Mode has 0 growth rate at ky==0
				(transient_amplifications[value] = 0.0; next) if value == 0.0 and kxy == :ky 
				phi2_vec = gsl_vector("phi2_by_#{kxy}_over_time", {kxy=>value})
				transient_amplifications[value] = calculate_transient_amplification(phi2_vec)
				(eputs "\n\n----------\nIn #@run_name:\n\nphi2_by_#{kxy}_over_time is all NaN; unable to calculate growth rate\n----------\n\n"; transient_amplifications[value] = -1; next) if transient_amplifications[value].to_s == "NaN"
                if @g_exb and @g_exb > 0.0 and @g_exb_start_timestep
                  @max_transient_amplification_index_at_ky[value] = 
                    (@g_exb_start_timestep/@nwrite).to_i + 
                    phi2_vec[(@g_exb_start_timestep/@nwrite).to_i...-1].max_index
                else
                  @max_transient_amplification_index_at_ky[value] = nil 
                end
			end
		end
		
 		write_results
		
		if ENV['GS2_CALCULATE_ALL']
		trap(0){eputs "Calculation of spectrum did not complete: run 'cgrf' (i.e. calculate_transient_amplifications_and_frequencies) for this run. E.g. from the command line \n $ coderunner rc 'cgrf' -j #{@id}"; exit}
		@transient_amplification_at_ky_at_kx ||= FloatHash.new
		list(:ky).values.sort.each do |kyv|
			@transient_amplification_at_ky_at_kx[kyv] ||= FloatHash.new
			list(:kx).values.sort.each do |kxv|	
				next if @transient_amplification_at_ky_at_kx[kyv].keys.include? kxv
				Terminal.erewind(1)
				eputs sprintf("Calculating growth rate for kx = % 1.5e and ky = % 1.5e#{Terminal::CLEAR_LINE}", kxv, kyv) 
				(@transient_amplification_at_ky_at_kx[kyv][kxv] = 0.0; next) if kyv == 0.0 # Mode has 0 growth rate at ky==0
				phi2_vec = gsl_vector("phi2_by_mode_over_time", {:kx=>kxv, :ky=>kyv})
				@transient_amplification_at_ky_at_kx[kyv][kxv] = calculate_transient_amplification(phi2_vec)
				(eputs "\n\n----------\nIn #@run_name:\n\nphi2_by_#{kxy}_over_time is all NaN; unable to calculate growth rates\n----------\n\n"; @transient_amplification_at_ky_at_kx[kyv][kxv] = -1; next) if @transient_amplification_at_ky_at_kx[kyv][kxv].to_s == "NaN" 
			end
			write_results
		end
		trap(0){}
		end
		@transient_amplifications = @transient_amplification_at_ky
		@max_transient_amplification = @transient_amplifications.values.max
		@most_amplified_mode = @transient_amplifications.key(@max_transient_amplification)

		@ky = @aky if @aky
	end
end

#calculate_transient_es_heat_flux_amplificationsObject Also known as: ctehfa



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/gs2crmod/calculations.rb', line 463

def calculate_transient_es_heat_flux_amplifications
  return if @grid_option == "single" and @aky == 0.0 # no meaningful results

	@transient_es_heat_flux_amplification_at_species_at_kx = []
	@transient_es_heat_flux_amplification_at_species_at_ky = []
  @transient_es_heat_flux_amplification_at_species_at_ky_at_kx = []
	for species_index in 1..nspec

	Dir.chdir(@directory) do
		# With zero magnetic shear, calculate amplifications for both kx and ky
		if @shat and @shat.abs < 1.0e-5 and @nx > 1 and !@ikx_init and false
			to_calc = [:kx, :ky]
			@transient_es_heat_flux_amplification_at_species_at_kx[species_index-1] ||= FloatHash.new
		else
			to_calc = [:ky]
		end
		
		@transient_es_heat_flux_amplification_at_species_at_ky[species_index-1] ||= FloatHash.new
 		eputs
		to_calc.each do |kxy|
			transient_es_heat_flux_amplifications = send(:transient_es_heat_flux_amplification_at_species_at_ + kxy)[species_index-1]
			list(kxy).values.sort.each do |value|
			
				#p transient_es_heat_flux_amplifications.keys, value, transient_es_heat_flux_amplifications[value.to_f-0.0],
				#transient_es_heat_flux_amplifications.class, transient_es_heat_flux_amplifications.keys.include?(value); exit
		
				next if transient_es_heat_flux_amplifications.keys.include? value

				
				Terminal.erewind(1)
				#ep transient_es_heat_flux_amplifications.keys
				eputs sprintf("Calculating transient amplification for #{kxy} = % 1.5e#{Terminal::CLEAR_LINE}", value) 
				

						# Mode has 0 growth rate at ky==0
				(transient_es_heat_flux_amplifications[value] = 0.0; next) if value == 0.0 and kxy == :ky 
				phi2_vec = gsl_vector("es_heat_by_#{kxy}_over_time", {kxy=>value, species_index: species_index})
				#(transient_es_heat_flux_amplifications[value] = 0.0; next) if phi2_vec.min <= 0.0
				transient_es_heat_flux_amplifications[value] = calculate_transient_amplification(phi2_vec)
				(eputs "\n\n----------\nIn #@run_name:\n\nphi2_by_#{kxy}_over_time is all NaN; unable to calculate growth rate\n----------\n\n"; transient_es_heat_flux_amplifications[value] = -1; next) if transient_es_heat_flux_amplifications[value].to_s == "NaN"
			end
		end
		
 		write_results
		
# 		ep "transient_es_heat_flux_amplification_at_species_at_ky", @transient_es_heat_flux_amplification_at_species_at_ky
		if ENV['GS2_CALCULATE_ALL']
		trap(0){eputs "Calculation of spectrum did not complete: run 'ctehfa' (i.e. calculate_transient_es_heat_flux_amplifications) for this run. E.g. from the command line \n $ coderunner rc 'ctehfa' -j #{@id}"; exit}
		@transient_es_heat_flux_amplification_at_species_at_ky_at_kx[species_index-1] ||= FloatHash.new
		list(:ky).values.sort.each do |kyv|
			@transient_es_heat_flux_amplification_at_species_at_ky_at_kx[species_index-1][kyv] ||= FloatHash.new
			#p @transient_es_heat_flux_amplification_at_species_at_ky_at_kx[kyv]
			list(:kx).values.sort.each do |kxv|	
				next if @transient_es_heat_flux_amplification_at_species_at_ky_at_kx[species_index-1][kyv].keys.include? kxv
				Terminal.erewind(1)
				eputs sprintf("Calculating growth rate for kx = % 1.5e and ky = % 1.5e#{Terminal::CLEAR_LINE}", kxv, kyv) 
				(@transient_es_heat_flux_amplification_at_species_at_ky_at_kx[species_index-1][kyv][kxv] = 0.0; next) if kyv == 0.0 # Mode has 0 growth rate at ky==0
				phi2_vec = gsl_vector("phi2_by_mode_over_time", {:kx=>kxv, :ky=>kyv})
				#(@transient_es_heat_flux_amplification_at_species_at_ky_at_kx[kyv][kxv] = 0.0; next) if phi2_vec.min <= 0.0
				@transient_es_heat_flux_amplification_at_species_at_ky_at_kx[species_index-1][kyv][kxv] = calculate_transient_es_heat_flux_amplification(phi2_vec)
				(eputs "\n\n----------\nIn #@run_name:\n\nphi2_by_#{kxy}_over_time is all NaN; unable to calculate growth rates\n----------\n\n"; @transient_es_heat_flux_amplification_at_species_at_ky_at_kx[species_index-1][kyv][kxv] = -1; next) if @transient_es_heat_flux_amplification_at_species_at_ky_at_kx[species_index-1][kyv][kxv].to_s == "NaN" 
			end
			write_results
		end
		trap(0){}
		end
		#@max_transient_es_heat_flux_amplification = @transient_es_heat_flux_amplifications.values.max
		#@most_amplified_mode = @transient_es_heat_flux_amplifications.key(@max_transient_es_heat_flux_amplification)
		#@ky = @aky if @aky
	end
	end # for species_index in 1..nspec
end

#calculate_vspace_checksObject Also known as: cvc



723
724
725
726
727
728
# File 'lib/gs2crmod/calculations.rb', line 723

def calculate_vspace_checks
	@vspace_check = ['lpc_pitch_angle', 'vres_pitch_angle', 'lpc_energy',  'vres_energy'].map do |name|
		saturated_time_average(name, {}) 
	end
		
end

#change_id(new_id) ⇒ Object



1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
# File 'lib/gs2crmod/gs2.rb', line 1245

def change_id(new_id)
  # Change names for GS2 output files
  Dir.chdir(@directory) do
    dir_entries =  Dir.entries()
    dir_entries.each do |f|
      if f.include? 'v_'
        new_name = f.sub "id_#{@id}", "id_#{new_id}"
        `mv "#{f}" "#{new_name}"`
        next
      end
      if (f.include? 'v_' or f.include? 'gs2.')
        new_name = f.sub "gs2.#{@id}", "gs2.#{new_id}"
        `mv "#{f}" "#{new_name}"`
        next
      end
    end
  end

  begin
    # Change names for GS2 restart files
    Dir.chdir(@directory + '/' + @restart_dir) do
      dir_entries =  Dir.entries()
      dir_entries.each do |f|
        if f.include? 'v_'
          new_name = f.sub "id_#{@id}", "id_#{new_id}"
          `mv "#{f}" "#{new_name}"`
        end
      end
    end
  rescue
    eputs 'No restart files detected. Skipping...'
  end

  new_run_dir = @directory.sub "id_#{@id}", "id_#{new_id}"
  `mv "#{@directory}" "#{new_run_dir}"`
  @directory = new_run_dir

  # Rename variables which go in info and results file
  @run_name.sub! "id_#{@id}", "id_#{new_id}"
  if @restart_file
    @restart_file.sub! "id_#{@id}", "id_#{new_id}"
  end
  @output_file.sub! "gs2.#{@id}", "gs2.#{new_id}"
  @error_file.sub! "gs2.#{@id}", "gs2.#{new_id}"

  # Change instance variable and write info and results files again
  @id = new_id
  write_results
  write_info
end

#check_convergedObject

Raises:

  • (CRFatal)


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/gs2crmod/check_convergence.rb', line 5

def check_converged
	raise CRFatal.new("It is strongly recommended that you do not use the use_large_cache option (-U) while checking convergence. Doing so will lead to unpredictable results.") if @runner.use_large_cache
	Dir.chdir(@directory) do
		logf(:check_converged)
		return if @checked_converged and not @runner.recalc_all  

		log('@runner.class:', @runner.class)
		unless @runner.current_request == :check_converged
			@runner.requests.push :check_converged
			log 'check_converged requested recall'
			logi '@runner.requests', @runner.requests
			logi('@runner.object_id', @runner.object_id)
			return
		end	
		
		return unless @status == :Complete
		eputs @run_name
		eputs @checked_converged = true
		log("finding similar resolutions")
		@runner.generate_combined_ids(:real)
		case @grid_option
		when "box"	
			@similar_resolutions = @runner.similar_runs([:nx, :ny, :ntheta, :negrid, :naky, :ngauss, :nperiod, :delt, :jtwist], self)
		when "single"
			@similar_resolutions = @runner.similar_runs([:ntheta, :negrid, :naky, :ngauss, :nperiod], self)
		else
			raise CRFatal.new("Unknown grid option - can't get similar runs")
		end
			
		logi(@similar_resolutions)
		unless @similar_resolutions[1]
			eputs @run_name
			@converged = Feedback.get_boolean("This is is the biggest job with these params. Do you want to say it is converged?")
			return 
		end
		@similar_resolutions.sort! do |id1, id2|
			run1 = @runner.run_list[id1]
			run2 = @runner.run_list[id2]
			if @grid_option == "box" and @nonlinear_mode == "off" 
				(run1.jtwist*run1.nx*run1.negrid*run1.ngauss*run1.ntheta*run1.delt <=> run2.jtwist*run2.nx*run2.negrid*run2.ngauss*run2.ntheta*run2.delt)
			elsif @grid_option == "single" and @nonlinear_mode == "off"
				log("using nperiod: #{run1.nperiod}; #{run2.nperiod}")
				run1.negrid*run1.ngauss*run1.ntheta*run1.nperiod <=> run2.negrid*run2.ngauss*run2.ntheta*run2.nperiod

			elsif @naky	
				
				run1.nx*run1.negrid*run1.ngauss*run1.ntheta*run1.naky <=> run2.nx*run2.negrid*run2.ngauss*run2.ntheta*run2.naky
				
			else
				run1.nx*run1.negrid*run1.ngauss*run1.ntheta*run1.ny <=> run2.nx*run2.negrid*run2.ngauss*run2.ntheta*run2.ny

			end

		end

	# 	eputs @similar_resolutions
				
		log("finding my place")
		my_place = @similar_resolutions.index(@id);
	# 	eputs my_place; gets
		if my_place > 0 
			last_job = @runner.run_list[@similar_resolutions[my_place - 1]]
			unless last_job.status == :Complete
				@checked_converged = false
				return
			end
		else
			@converged = false
			return
		end

			
		log("Checking overall convergence")
		#graph = graphkit('phi2tot_vs_time_all_kys') + #last_job.graphkit('phi2tot_vs_time_all_kys')
		#graph.gnuplot
		eputs "\n \n Warning: there are no bigger jobs" unless @similar_resolutions[my_place + 1]  
		#@converged = Feedback.get_boolean("Is the plot converged?")
		#graph.close

		#(@checked_converged = true; return) unless @converged

		log("Checking convergence by ky")
		orn, last_job.runner = last_job.runner, nil
		log('last_job', last_job.pretty_inspect)
		last_job.runner = orn
# 		last_job.get_ky_graphs; last_job.get_eigenfunctions
	# 	logi(last_job.ky_graphs)
		catch(:quit_converge_check) do 
			options = {}
			list(:ky).each do |index, ky|
				options[:ky] = ky
				next if index == 1 and @grid_option == "box"
				graph = (graphkit('phi2_by_ky_vs_time', options)+last_job.graphkit('phi2_by_ky_vs_time', options))
				graph.gnuplot
				answer = Feedback.get_choice("Is the graph converged?", ["Yes", "No", "The whole run is converged, stop pestering me!"])
				graph.close
				case answer
				when /No/
					@converged = false
					throw(:quit_converge_check)
				when /stop/
					@converged = true
					throw(:quit_converge_check)
				when /Yes/
					@converged = true
				end
				cgraph = lgraph = 'efnnormmag'
				graph = (graphkit('efnnormmag', options)+last_job.graphkit('efnnormmag', options))
				
# 				graph.gnuplot

				loop do
					graph.gnuplot
					answer = Feedback.get_choice('Is the graph converged?', ['Yes', 'No', 'The whole run is converged, stop pestering me!', 'Show me the magnitude of the eigenfunctions', 'Show me the real part of the eigenfunctions again', 'Normalise the eigenfunctions', 'Denormalise the eigenfunctions', 'Reverse the axis of the current run', 'Flip the current run', 'Toggle xrange'])
					graph.close
					case answer
					when /^Yes$/		
						@converged = true
						break
					when /^No$/
						@converged = false
						throw(:quit_converge_check)
					when /stop/
						@converged = true
						throw(:quit_converge_check)
					when /magnitude/
						log 'checking convergence using magnitude'
						lgraph += 'mag'; cgraph += 'mag'
					when /Normalise/
						log 'normalising'
						lgraph += 'norm'; cgraph += 'norm'
					when /Denormalise/
						log 'denormalising'
						lgraph.gsub!(/norm/, ''); cgraph.gsub!(/norm/, '')
					when /real/
						lgraph.gsub!(/mag/, ''); cgraph.gsub!(/mag/, '')
					when /Reverse/
						cgraph = cgraph =~ /rev/ ? cgraph.sub!(/rev/, '') : cgraph + 'rev'
# 						graph = (@eigenfunctions[ky]+last_job.eigenfunctions[ky])
					when /Flip/
						cgraph = cgraph =~ /flip/ ? cgraph.sub!(/flip/, '') : cgraph + 'flip'
# 						graph = (@eigenfunctions[ky]+last_job.eigenfunctions[ky])
					when /xrange/
						if options[:range]
							options[:range] = nil
						else
							options[:range] = 0
						end
					else
						raise CRFatal.new("couldn't match choice #{answer}")
					end
					graph = graphkit(cgraph, options) + last_job.graphkit(lgraph, options)
					log graph.title
				end
				
				
			end
		end
		@checked_converged =true
		
		if last_job.checked_converged
			last_job.ky_graphs = nil
			last_job.eigenfunctions = nil
# 			last_job.t_list = nil
# 			last_job.kx_list = nil
		end
		
# 		finish_processing
	end
	ep self
end

#check_parametersObject

Eventually, this will be a full port of the ingen tool in the GS2 folder. At the moment it runs a limited set of tests for common errors in the input parameters (including type checking).



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/gs2crmod/ingen.rb', line 97

def check_parameters

  # Sections

  # Namelist Tests
  # Grids
  # Parallelisation
  # Initialisation
  # Diagnostics
  # Misc

  ##################
  # Namelist Tests #
  ##################

  rcp.namelists.each do |namelist, hash|
    next if hash[:should_include].kind_of? String and not eval(hash[:should_include])
    if en = hash[:enumerator]
      #ep 'en', en, namelist
      next unless send(en[:name])
      send(en[:name]).times do |i|
        run_namelist_tests(namelist, hash, i+1)
      end
    else
      run_namelist_tests(namelist, hash)
    end
  end

  ###############
  # Grid Errors #
  ###############

  # naky
  warning("Setting naky when non-linear mode is on is not recommended.") if @naky and @nonlinear_mode == "on"

  warning("You have set both ny and naky; naky will override ny.") if @ny and @naky

  error("abs(shat) should not be less that 1.0e-6") if @shat and @shat.abs < 1.0e-6 and not agk?
  error("abs(s_hat_input) should not be less that 1.0e-6") if @s_hat_input and @s_hat_input.abs < 1.0e-6 and not agk?

  # delt

  error("Please specify delt") unless @delt
  error("delt <= 0") if @delt <= 0.0
  warning("Nonlinear run with delt_minimum unspecified.") if @nonlinear_mode=="on" and not @delt_minimum

  error("delt (#@delt) < delt_minimum") if @delt and @delt_minimum and @delt < @delt_minimum

  # negrid
  warning('negrid < 8 is not a good idea!') if @negrid and @negrid < 8

    # nakx
  warning("You have set both nx and ntheta0; ntheta0 will override nx.") if @nx and @ntheta0

  warning("Do you have a reason for setting equal_arc = true (default)? If not set false.") if @equilibrium_option=="eik" and (!@equal_arc or @equal_arc.fortran_true?)

  warning("Recommend nperiod > 1 for linear runs.") if @nonlinear_mode == "off" and (!@nperiod or @nperiod == 1)
  warning("Recommend nperiod = 1 for nonlinear runs.") if @nonlinear_mode == "on" and (@nperiod > 1)

  warning("Consider using field_option = local and associated optimizations.") if @field_option and @field_option == "implicit"

  #################################
  # Parallelisation/Layout Errors #
  #################################

  # Best linear run layout is lexys
  warning("The best layout for linear runs is usually lexys.") if @nonlinear_mode=="off" and not @layout=="lexys"

  # Best nonlinear run layout is xyles
        warning("The best layout for nonlinear runs is usually xyles.") if @nonlinear_mode=="on" and not @layout=="xyles"

  # Check whether we are parallelising over x
  warning("Parallelising over x: suggest total number of processors should be: #{max_nprocs_no_x}") if actual_number_of_processors > max_nprocs_no_x and not @grid_option == "single"

  #########################
  # Initialisation Errors #
  #########################

  # Check if restart folder exists
  if @restart_file and  @restart_file =~ /^(?<folder>[^\/]+)\//
    folder = $~[:folder]
    warning("Folder #{folder}, specified in restart_file, not present. NetCDF save may fail") unless FileTest.exist?(folder)
  end

  error("Setting @restart_file as an empty string will result in hidden restart files.") if @restart_file == ""

  error("ginit_option is 'many' but is_a_restart is false") if @ginit_option == "many" and not @is_a_restart

  error("read_response is 'true' but run is not a restart. Make sure the "\
        "@response_id is set to a run with response files.") if 
        @read_response and @read_response.fortran_true? and 
        not @is_a_restart and not @response_id

  error("chop_side should not be used (remove test if default changes from T to F)") if !@chop_side or @chop_side.fortran_true?

  #####################
  # Diagnostic errors #
  #####################

  #Check whether useful diagnostics have been omitted.

  not_set = [:write_verr, :save_for_restart, :write_nl_flux, :write_final_fields, :write_final_moments].find_all do  |diagnostic|
    not (send(diagnostic) and send(diagnostic).fortran_true?)
  end

  if not_set.size > 0
    str = not_set.inject("") do |s, diagnostic|
      s + "\n\t#{diagnostic} --- " + rcp.namelists[diagnostics_namelist][:variables][diagnostic][:description] rescue s
    end
    warning("The following useful diagnostics were not set:" + str) if str.length > 0
  end

  warning("You are running in nonlinear mode but have not switched the nonlinear flux diagnostic.") if not (@write_nl_flux and @write_nl_flux.fortran_true?) and @nonlinear_mode == "on"

  #{
    #write_verr: "Velocity space diagnostics will not be output for this run"
  #}.each do |var, warn|
    #warning(v"#{var} not set or .false. --- " + warn) unless send(var) and send(var).fortran_true?
  #end

  error("Please specify nwrite") unless @nwrite
  error("Please specify nstep") unless @nstep


  warning("You will write out diagnostics less than 50 times") if @nstep/@nwrite < 50

  ########################
  # Miscellaneous errors #
  ########################

  error("The run name for this run is too long. Please move some of the variable settings to the local defaults file.") if @relative_directory.size + @run_name.size > MAX_NAME_SIZE

  warning("You are submitting a nonlinear run with no dissipation.") if @nonlinear_mode == "on" and @hyper_option=="none" and @collision_model=="none"

  warning("You have no spatial implicitness: (bakdif) for one of your species. Be prepared for numerical instabilities!") if (1..@nspec).to_a.find{|i| bd = send("bakdif_#{i}") and bd == 0}

  warning("The system will abort with rapid timestep changes...") if !@abort_rapid_time_step_change or @abort_rapid_time_step_change.fortran_true?

  warning("local_field_solve is an old variable that should not really be used.") if @local_field_solve and  @local_field_solve.fortran_true?

  #############################
  # Boundary Condition Errors #
  #############################

  warning("Boundary option should be periodic for shat = 1e-6.") if (!@boundary_option or @boundary_option != "periodic") and ((@s_hat_input and @s_hat_input.abs == 1.0e-6) or (@shat and @shat.abs == 1.0e-6))

  warning("Boundary option should be default (unconnected) for single and range mode with shat > 0.") if (@boundary_option != "default") and ((@s_hat_input and @s_hat_input.abs > 1.0e-6) or (@shat and @shat.abs > 1.0e-6)) and (@grid_option == "single" or @grid_option == "range")

  warning("Boundary option should be linked for box mode with shat > 0.") if (!@boundary_option or @boundary_option != "linked") and ((@s_hat_input and @s_hat_input.abs > 1.0e-6) or (@shat and @shat.abs > 1.0e-6)) and @grid_option == "box" 

  error("Set nonad_zero = true.") if @nonad_zero and not @nonad_zero.fortran_true?


  ###################
  # Spectrogk tests #
  ###################
  #
  if spectrogk?
    if @force_5d and @force_5d.fortran_true?
      warning("Must specify interpolation method with phi_method.") if not (@phi_method)
    end
  end

  ################
  # Damping Rate #
  ################

  error("Linear runs with hyperviscosity are NOT recommended!") if @nonlinear_mode=="off" and (@hyper_option and @hyper_option=="visc_only") and (@d_hypervisc and @d_hypervisc!=0)

  warning("Amplitude dependent part of hyperviscosity being ignored since const_amp = true") if (@hyper_option and @hyper_option=="visc_only") and (@const_amp and @const_amp.fortran_true?)

  ###################
  # Geometry Errors #
  ###################

  error("You must set bishop = 4 for Miller(local) geometry. Remember also that s_hat_input will override shat") if (@bishop!=4 and (@local_eq and @local_eq.fortran_true?))

  error("Shift should be > 0 for s-alpha equilibrium.") if @equilibrium_option=="s-alpha" and (@shift and @shift < 0)
  error("Shift should be < 0 for Miller equilibrium.") if @equilibrium_option=="eik" and @local_eq.fortran_true? and (@shift and @shift > 0)

  error("irho must be 2 for Miller equilibrium.") if @equilibrium_option=="eik" and @local_eq.fortran_true? and (@irho and @irho!=2)

  warning("Note that shat != s_hat_input") if @shat and @s_hat_input and @shat!=@s_hat_input

  ##################
  # Species Errors #
  ##################

  error("Must set z = -1 for electron species.") if (@type_2 and @z_2 and @type_2=='electron' and @z_2 != -1)


  #################
  # Optimisations #
  #################

  if CODE_OPTIONS[:gs2] and CODE_OPTIONS[:gs2][:show_opt]
    eputs("Optimisation Summary:")
    optimisation_flags.each do |flag|
      eputs("-------------------------  #{flag}: #{send(flag)}\n* #{rcp.variables_with_help[flag].gsub(/\n/, "\n\t").sub(/\A([^.]*.).*\Z/m, '\1')}") 
    end
    #not_set = [:operator, :save_for_restart, :write_nl_flux, :write_final_fields, :write_final_moments].find_all do  |diagnostic|
      #not (send(diagnostic) and send(diagnostic).fortran_true?)
    #end

    #if not_set.size > 0
      #str = not_set.inject("") do |s, diagnostic|
        #s + "\n\t#{diagnostic} --- " + rcp.namelists[diagnostics_namelist][:variables][diagnostic][:description] rescue s
      #end
      #warning("The following useful diagnostics were not set:" + str) if str.length > 0
    #end
  end
  
 


end

#copy_response_files(run) ⇒ Object



532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/gs2crmod/gs2.rb', line 532

def copy_response_files(run)
  eputs 'Copying response files...', ''
  eputs 'The following run parameters have changed. Are you sure you can use '\
  'these response files?'
  diff_run_parameters(self, run)
  FileUtils.makedirs(run.directory + '/response')
  run.response_dir = "response" 

  files = list_of_response_files.map do |file|
    @directory + "/" + file
  end

  files.each_with_index do |file , index|
    eputs "#{index+1} out of #{files.size}"
    eputs "\033[2A" # Terminal jargon - go back one line
    response_ext = file.scan(/_ik_\d+_is_\d+.response/)
    FileUtils.cp(file, run.directory + "/response/#{run.run_name}#{response_ext[0]}")
  end
end

#copy_restart_files(new_run) ⇒ Object



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/gs2crmod/gs2.rb', line 514

def copy_restart_files(new_run)
  eputs 'Copying restart files...', ''
  FileUtils.makedirs(new_run.directory + '/nc')
  #old_dir = File.dirname(@restart_file)
  new_run.restart_file = "#@run_name.nc"
  new_run.restart_dir = "nc"
  files = list_of_restart_files.map do |file|
    @directory + "/" + file
  end
  files.each_with_index do |file , index|
    eputs "#{index+1} out of #{files.size}"
    eputs "\033[2A" # Terminal jargon - go back one line
    num = file.scan(/(?:\.\d+|_ene)$/)[0]
    #FileUtils.cp("#{old_dir}/#{file}", "nc/#@restart_file#{num}")
    FileUtils.cp(file, new_run.directory + "/nc/#{new_run.restart_file}#{num}")
  end
end

#corrected_mom_flux_stavObject

Not needed for GS2 built after 16/06/2010



392
393
394
# File 'lib/gs2crmod/calculations.rb', line 392

def corrected_mom_flux_stav
	par_mom_flux_stav - perp_mom_flux_stav
end

#ctanObject



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# File 'lib/gs2crmod/calculations.rb', line 644

def ctan
	list(:ky).each do |(ky_index, ky)|
		eputs "ky: #{ky}"
		phi_vec = gsl_vector("phi2_by_ky_over_time", ky_index: ky_index)
		t_element	= 0
		old = phi_vec[0]

	  loop do 
			t_element+=1
			#print t_element, ',', phi_vec.size
			new = phi_vec[t_element]
			break if new > old or t_element == phi_vec.size - 1
			old = new
		end
		
		if t_element == phi_vec.size - 1
			@transient_amplification_at_ky[ky] = -1
			eputs "No Min"
			next
		end
		first_min = t_element

		eputs "ky: #{ky}, first_min: #{first_min}"
	  loop do 
			t_element+=1
			#print t_element, ',', phi_vec.size
			new = phi_vec[t_element]
			break if new < old or t_element == phi_vec.size - 1
		end
		if t_element == phi_vec.size - 1
			@transient_amplification_at_ky[ky] = -1
			next
		end
		@transient_amplification_at_ky[ky] = phi_vec.subvector(t_element, phi_vec.size - t_element).max
	end
end

#cumulative_gridpointsObject



346
347
348
349
350
# File 'lib/gs2crmod/ingen.rb', line 346

def cumulative_gridpoints
  c = 1
  error("Please specify layout") unless @layout
  @layout.split(//).reverse.inject({}){|hash, let| c*=gridpoints[let]; hash[let] = c; hash}
end

#data_stringObject



383
384
385
386
387
388
389
390
391
# File 'lib/gs2crmod/gs2.rb', line 383

def data_string
  logf(:data_string)
  return "" unless @converged unless @grid_option == 'single'
  logi(@ky, @growth_rates, @real_frequencies)
#   log(:@@readout_list, @@readout_list)
  return rcp.readout_list.inject(""){|str,(var,_)| str+"#{(send(var) || "0")}\t"} + "\n"

#   @ky ? (@@variables + @@results - ).inject(""){|str,(var,type_co)| str+"#{(send(var) || "0")}\t"} + sprintf("%e\t%e\t%e\n", @ky, @growth_rates[@ky], @real_frequencies[@ky]) : (@@variables + @@results).inject(""){|str,(var,type_co)| str+"#{(send(var) || "0")}\t"} + sprintf("%e\t%e\t%e\n",  @fastest_growing_mode, @max_growth_rate, @freq_of_max_growth_rate)
end

#delete_restart_files(options = {}) ⇒ Object

Delete all the restart files (irreversible!)



638
639
640
641
642
643
# File 'lib/gs2crmod/gs2.rb', line 638

def delete_restart_files(options={})
  puts 'You are about to delete the restart files for:'
  puts @run_name
  return unless Feedback.get_boolean("This action cannot be reversed. Do you wish to continue?") unless options[:no_confirm]
  list_of_restart_files.each{|file| FileUtils.rm file}
end

#diagnostics_namelistObject



358
359
360
# File 'lib/gs2crmod/ingen.rb', line 358

def diagnostics_namelist
  :gs2_diagnostics_knobs
end

#diff_run_parameters(run_1, run_2) ⇒ Object

The following function is essentially the same as the CR differences_between function without the runner loading set up code. This could possibly be moved to a more general function in CR.



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/gs2crmod/gs2.rb', line 555

def diff_run_parameters(run_1, run_2)
  runs = [run_1, run_2] 
  rcp_fetcher = (runs[0] || @runner.run_class).rcp                             
  vars = rcp.variables.dup + rcp.run_info.dup

  # Clean up output by deleting some variables
  vars.delete_if{|var| runs.map{|r| r.send(var)}.uniq.size == 1}              
  vars.delete :id                                                             
  vars.delete :run_name                                                       
  vars.delete :output_file
  vars.delete :error_file                                 
  vars.delete :executable                                                     
  vars.delete :comment
  vars.delete :naming_pars
  vars.delete :parameter_hash
  vars.delete :parameter_hash_string
  vars.delete :sys
  vars.delete :status
  vars.delete :job_no
  vars.delete :running
  vars.unshift :id

  # Fancy table printing
  table = vars.map{|var| [var] + runs.map{|r| str = r.instance_eval(var.to_s).to_s; 
                                          str.size>10?str[0..9]:str} }
  col_widths = table.map{|row| row.map{|v| v.to_s.size}}.
                         inject{|o,n| o.zip(n).map{|a| a.max}}
  eputs                                                                       
  table.each{|row| i=0; eputs row.map{|v| str = sprintf(" %#{col_widths[i]}s ",
      v.to_s); i+=1; str}.join('|'); eputs '-' * 
      (col_widths.sum + col_widths.size*3 - 1) }
end

#error(message) ⇒ Object

Raises:



14
15
16
# File 'lib/gs2crmod/ingen.rb', line 14

def error(message)
  raise InputFileError.new("Error: " + message)
end

#estimated_nodesObject Also known as: estnod

Gives a guess as to the maximum number of nodes which can be can be utilized on the current system



924
925
926
# File 'lib/gs2crmod/gs2.rb', line 924

def estimated_nodes
  parallelizable_meshpoints / max_ppn
end

#eulerian_kx_index(options) ⇒ Object

This function is used in the presence of perpendicular flow shear. It returns the (Eulerian) GS2 kx_index as a function of the Lagrangian kx, which is the kx_index of the mode in a shearing coordinate system, I.e. if you give it an Lagrangian kx (which is the same as the Eulerian kx at t=0) it will tell you where it has now got to. It may have left the box, in which case this function will return an error.

A given Lagrangian kx moves through the GS2 box, and thus for such a kx the response matrix varies in time. This is done because the effect of flow shear can be reduced by a shearing coordinate transformation to become merely a time varying kx.

At each timestep, phi(ikx_indexed(it)) is set equal to phi(ikx_indexed(it - jump(iky)) kx_indexed is defined in the following way.

do it=itmin(1), ntheta0
  ikx_indexed (it+1-itmin(1)) = it
end do

do it=1,itmin(1)-1
  ikx_indexed (ntheta0 - itmin(1) + 1 + it)= it
end do

In other words, what this means is that akx(ikx_indexed(0)) is the minimum kx, and that akx(ikx_indexed(ntheta0)) gives the maximum kx, kx_indexed moves the kxs out of box order.

So. remembering that jump is negative, phi(kx) is set equal phi(kx - jump * dkx) so the Lagrangian mode has moved to a lower kx. So get the Eulerian index, one starts with the Lagrangian index, and adds jump (which is negative!). This, however, must be done with indexes that are in the physical (not box) order. So this function first moves the indexes out of box order, then adds jump, then moves them back into box order so that the index returned will give the correct kx from the GS2 array.

Raises:

  • (ArgumentError)


1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
# File 'lib/gs2crmod/gsl_data.rb', line 1467

def eulerian_kx_index(options)
  #eputs "Start eulerian_kx_index"
  lagrangian_kx_index = options[:kx_index]
  phys = physical_kx_index(lagrangian_kx_index)
  #ep 'jump', jump(options)
  index = phys + jump(options)
  raise ArgumentError.new("Lagrangian kx out of range") if index <= 0
  box= box_kx_index(index)
  #eputs "End eulerian_kx_index"
  return box
end

#generate_component_runsObject



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/gs2crmod/gs2.rb', line 277

def generate_component_runs
  @component_runs = []
  logf(:generate_component_runs)
  return if @grid_option == "single" and @scan_type == "none"
  begin
    list(:ky) # This will fail unless the run has output the netcdf file
  rescue
    return
  end
  return unless @status == :Complete #and @converged
  log(@run_name)
  if @grid_option == "box" and @nonlinear_mode == "off"
    @ky = nil
#     raise CRFatal.new("no @ky_list") unless @ky_list
#     log list(:ky)
    list(:ky).each do |id, ky|
      component_run = create_component #self.dup
      component_run.ky = ky
      component_run.gamma_r = @growth_rates[ky]
      component_run.gamma_i = @real_frequencies[ky]
      log @runner.component_ids
#       log('@runner.class', @runner.class)
#       @runner.add_component_run(component_run)
    end
  elsif (not gryfx?) and @scan_type and @scan_type != "none"
    t = gsl_vector('t')
    scan_vals = gsl_vector('scan_parameter_value')
    current = scan_vals[0]
    start = 0
    for i in 0...t.size
      if scan_vals[i] != current
        component = create_component
        component.scan_index_window = [start+1, i] #remember indexes are elements + 1
        #ep 'scan_index_window', component.scan_index_window
        component.scan_parameter_value = current
        component.growth_rate_at_ky = nil
        component.growth_rate_at_kx = nil
        component.growth_rate_at_ky_at_kx = nil
        component.calculate_results
        current = scan_vals[i]
        start = i
      end
    end
  end
end

#generate_input_file(&block) ⇒ Object



816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# File 'lib/gs2crmod/gs2.rb', line 816

def generate_input_file(&block)
  raise CRFatal("No Input Module File Given or Module Corrupted") unless 
        methods.include? (:input_file_text)
  run_namelist_backwards_compatibility

  @user_comments = "Defaults description: #@defaults_file_description. Run description: #@comment"

  # If it is a restart default behaviour will be to copy the response files 
  # from the run being restarted. Specifying a response_id will override this.
  if not @is_a_restart and @response_id
     @read_response = ".true."

    @runner.run_list[@response_id].copy_response_files(self)
  elsif @dump_response and @dump_response.fortran_true? and 
        (not @read_response or not @read_response.fortran_true?)
    @response_dir = "response"
    FileUtils.makedirs @response_dir
  end

  # The second test checks that the restart function has not been called 
  # manually earlier (e.g. in Trinity), but we must check that it is not in 
  # fact a resubmitted run.
  if @restart_id and (not @is_a_restart or @resubmit_id)   
    @runner.run_list[@restart_id].restart(self)
  elsif ((@save_for_restart and @save_for_restart.fortran_true?) or
        (@save_for_restart_new and @save_for_restart_new.fortran_true?)) and 
        (not @is_a_restart or @resubmit_id)
    @restart_dir = "nc"
    #if CODE_OPTIONS[:gs2] and CODE_OPTIONS[:gs2][:list]
      #FileUtils.makedirs "#{@runner.root_folder}/#@restart_dir"
    #else
    FileUtils.makedirs @restart_dir
    #end
    @restart_file = "#@run_name.nc"

  end

  # Let Gs2 know how much wall clock time is available. avail_cpu_time is a GS2 input parameter.
  @avail_cpu_time = @wall_mins * 60 if @wall_mins

  #  Automatically set the number of  nodes to be the maximum possible without parallelising over x, if the user has left the number of nodes unspecified.

  set_nprocs

  if block
    ##### Allow the user to define their own pre-flight checks and changes
    instance_eval(&block)
  else
    ######### Check for errors and inconsistencies
    check_parameters
    #########
  end

  write_input_file
  
  ######### Generate a report using the ingen tool if possible
  ingen unless block
  ########
end

#get_completed_timestepsObject



342
343
344
345
346
347
348
349
350
# File 'lib/gs2crmod/gs2.rb', line 342

def get_completed_timesteps
  #raise CRFatal.new("Couldn't find outfile #{@run_name}.out") unless FileTest.exist?(@run_name + ".out")
  #p 'try to get completed_timesteps', Dir.pwd, 'nwrite', @nwrite, 'delt', @delt
  @completed_timesteps = (list(:t).size - 1) * (@nwrite || 1)
  #p 'tried to get completed_timesteps'
  #rescue
  #`grep time= #@run_name.out`.split.size
#   File.read("#@run_name.out").scan(/^\s+time\s*=\s+/).size * @nwrite
end

#get_list_of(*args) ⇒ Object Also known as: list



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/gs2crmod/gs2.rb', line 423

def get_list_of(*args)
  #args can be any list of e.g. :ky, :kx, :theta, :t ...
  logf(:get_list_of)
  refresh = args[-1] == true ? true : false
  args.pop if args[-1] == true
  logd
  Dir.chdir(@directory) do
    args.each do |var|
#       eputs "Loading #{var}"
      list_name = var + :_list
      log list_name

#       self.class.send(:attr_accessor, list_name)
      next if (cache[list_name] and [:Failed, :Complete].include? status and not refresh)

      cache[list_name] = {}
      if netcdf_file.var(var.to_s)
        netcdf_file.var(var.to_s).get.to_a.each_with_index do |value, element|
  #         print '.'
          cache[list_name][element+1]=value
        end

      else
        netcdf_file.dim(var.to_s).length.times.each do |element|
          cache[list_name][element+1]='unknown'
        end
      end

#     eputs send(var+:_list)
    end
  end
  logfc :get_list_of
  return cache[args[0] + :_list] if args.size == 1
end

#get_run_timeObject

Try to read the runtime in minutes from the GS2 standard out.



252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/gs2crmod/gs2.rb', line 252

def get_run_time
  logf(:get_run_time)
  output = @output_file || try_to_get_output_file
  return nil unless output
  begin
    Regexp.new("total from timer is:\\s*#{LongRegexen::NUMBER}", Regexp::IGNORECASE).match FileUtils.tail(output, 300)
    logi $~
    @run_time = $~[:number].to_f
  rescue
    @run_time = nil
  end
end

#get_statusObject



680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
# File 'lib/gs2crmod/gs2.rb', line 680

def get_status
#   eputs 'Checking Status'
  logf(:get_status)

  Dir.chdir(@directory) do
    if @running
      if FileTest.exist?(@run_name + ".out") and FileUtils.tail(@run_name + ".out", 5).split(/\n/).size > 4 and FileUtils.tail(@run_name + ".out", 200) =~ /t\=/
        @status = :Incomplete
      else
        @status = :NotStarted
      end

    else
      if FileTest.exist?(@run_name + ".out") and FileUtils.tail(@run_name + ".out", 5).split(/\n/).size > 4
        #eputs "HERE", @scan_type
        if  @nonlinear_mode == "off" and FileUtils.tail(@run_name + ".out",200) =~ /omega converged/
          eputs 'Omega converged...'
          @status = :Complete
        elsif @scan_type and @scan_type != "none" and FileUtils.tail(@run_name + ".par_scan",200) =~ /scan\s+is\s+complete/i
          eputs 'Scan complete...'
          @status = :Complete
        elsif @nonlinear_mode == "on" or !@omegatol or @omegatol < 0.0 or (@exit_when_converged and @exit_when_converged.fortran_false?)
            eputs 'No omegatol'
          if FileTest.exist?(@run_name + ".out.nc")
            #p ['pwd', Dir.pwd, netcdf_file, netcdf_file.dim('t'), netcdf_file.dims]
            if netcdf_file.dim('t').length > 0
              get_completed_timesteps
            else
              @status = :Failed
              return
            end
          else
            eputs "Warning: no netcdf file #@run_name.out.nc"
            @status = :Failed
            return
          end
            #ep "completed_timesteps", @completed_timesteps
          eputs "#{percent_complete}% of Timesteps Complete"
          if percent_complete >= 100.0
            @status = :Complete
          elsif percent_complete > 5 and FileUtils.tail(output_file, 200) =~ /total from timer is/
            @status = :Complete
          else
            @status = :Failed
          end
        else
          @status = :Failed
        end
      else
        @status=:Failed
      end
    end
  end
end

#get_timeObject

Raises:

  • (CRFatal)


323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/gs2crmod/gs2.rb', line 323

def get_time
  begin
    lt = list(:t)
    return lt.values.max if lt.size>0
  rescue
  end
  time = nil
#   eputs   File.readlines(@run_name +".out").slice(-4..-1).reverse.join( "\n"); gets
  raise CRFatal.new("Couldn't find outfile #{@run_name}.out") unless FileTest.exist?(@run_name + ".out")
  tail = FileUtils.tail("#@run_name.out", 4)
  #File.readlines(@run_name +".out").slice(-4..-1).reverse.join( "\n")
  tail.sub(LongRegexen::FLOAT) do
#     eputs $~.inspect
    time =   $~[:float].to_f
  end  #if FileTest.exist? (@run_name +".out")
  #raise CRFatal.new("couldn't get the time from #{tail}") unless time
  @time = time
end

#graphkit(name, options = {}) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/gs2crmod/graphs.rb', line 191

def graphkit(name, options={})
    logf :graphkit
    # If an array of t, kx or ky values is provided, plot one graph for each value and then sum the graphs together
    [:t, :kx, :ky, :X, :Y, :e, :l, :theta, :ri, :r].each do |var|
        #ep 'index', var
        if options[var].class == Symbol and options[var] == :all
            options[var] = list(var).values
        elsif options[var+:_index].class == Symbol and options[var+:_index] == :all
            #ep 'Symbol'
            options[var+:_index] = list(var).keys
        end
        if options[var].class == Array
            return options[var].map{|value| graphkit(name, options.dup.absorb({var =>  value}))}.sum
        elsif options[var+:_index].class == Array
            #ep 'Array'
            return options[var+:_index].map{|value| graphkit(name, options.dup.absorb({var+:_index =>  value}))}.sum
        end
        if options[var].class == Symbol and options[var] == :max
            options[var] = list(var).values.max
        elsif options[var+:_index].class == Symbol and options[var+:_index] == :max
            ep 'Symbol'
            options[var+:_index] = list(var).keys.max
        end
    end
    options[:t_index] ||= options[:frame_index]  if options[:frame_index]

    



    # Smart graphkits are defined in the file read_netcdf
    if name =~ /^cdf_/
        return smart_graphkit(options + {graphkit_name: name})
    elsif name =~ /^nc_/
        return old_smart_graphkit(options + {graphkit_name: name})
    end

    # If a method from the new GraphKits module can generate this graphkit use it 
    if method = self.class.instance_methods.find{|meth| (name + '_graphkit').to_sym == meth}
        options[:graphkit_name] = name
        return send(method, options)
    end

    raise "Graph #{name} not found"
    
end

#gridpointsObject

A hash which gives the actual numbers of gridpoints indexed by their corresponding letters in the layout string.



336
337
338
339
340
341
342
343
344
# File 'lib/gs2crmod/ingen.rb', line 336

def gridpoints
  gridpoints = {'l' => @ngauss, 'e' => @negrid, 's' => @nspec}
  if @grid_option == "single"
    gridpoints.absorb({'x'=>1, 'y'=>1})
  else
    gridpoints.absorb({'x' => (@ntheta0 or (2.0 * (@nx - 1.0) / 3.0  + 1.0).floor),  'y' => (@naky or ((@ny - 1.0) / 3.0  + 1.0).floor)})
  end
  return gridpoints
end

#gryfx?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/gs2crmod/gs2.rb', line 60

def gryfx?
  false
end

#gsl_complex(name, options = {}) ⇒ Object



1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
# File 'lib/gs2crmod/gsl_data.rb', line 1512

def gsl_complex(name, options={})
  options = eval(options) if options.class == String
#   p @directory
  Dir.chdir(@directory) do
#     eputs Dir.pwd
    case name
    when /correcting_phase/
#       options.convert_to_index(self, :ky)
#       theta0 = (options[:theta0] or 0)
# #       p 'options[:ky_index]', options[:ky_index]
#       phase_array = NumRu::NetCDF.open("#@directory/#@run_name.out.nc").var('phase').get({"start" => [0, options[:ky_index] - 1, theta0], 'end' => [1, options[:ky_index] - 1, theta0] }).to_a.flatten
#       p 'phase_array', phase_array
#       thetaelement0 = (list(:theta).key(0.0) - 1).to_i
#       p 'list(:theta)[thetaelement0 + 1]', list(:theta)[thetaelement0 + 1]
#       p 'thetaelement0', thetaelement0
#       p 'theta0 - jump(options)', theta0 - jump(options) % @jtwist
#       p 'list(:kx)[2] * (theta0 - jump(options)%@jtwist)', list(:kx)[2] * (theta0 - jump(options)%@jtwist)
#       kx_element = list(:kx).key(list(:kx)[2] * (theta0 - jump(options)%@jtwist)) - 1
#       at_0 = NumRu::NetCDF.open("#@directory/#@run_name.out.nc").var('phi').get({"start" => [0, thetaelement0, kx_element, options[:ky_index] - 1], 'end' => [1, thetaelement0, kx_element, options[:ky_index] - 1] }).to_a.flatten
#       p 'at_0', at_0
#       at_0 = GSL::Complex.alloc(at_0)
#       p 'at_0', at_0
#       return (at_0 / at_0.mag).conj
# #       pp 'theta0', theta0
# #       pp phase_array[5][theta0]
#       return GSL::Complex.alloc(phase_array)
# #       new_options = options.dup
#       new_options[:imrc] = :real
#       thetas = gsl_vector('theta_along_field_line', new_options)
#       at_0 = gsl_vector_complex('phi_along_field_line', new_options)[.to_a.index(0.0)]
#       p at_0
      exit
    else
      raise CRError.new("Unknown gsl_complex requested: #{name}")
    end
  #       eputs data; gets
  end
end

#gsl_matrix(name, options = {}) ⇒ Object



1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
# File 'lib/gs2crmod/gsl_data.rb', line 1175

def gsl_matrix(name, options={})
  options = eval(options) if options.class == String
  if options[:saturated_time_average] or options[:sta]
    raise "Not Saturated" unless @saturation_time_index
    tmax = list(:t).keys.max
    return ((@saturation_time_index..tmax).to_a.map do |t_index|
      gsl_matrix(name, options.dup.absorb({t_index: t_index, saturated_time_average: nil, sta: nil}))
    end).sum / (list(:t).values.max - list(:t)[@saturation_time_index])
  end
  if method = self.class.instance_methods.find{|meth| (name + '_gsl_matrix').to_sym == meth}
      options[:graphkit_name] = name
      return send(method, options)
  end
end

#gsl_tensor(name, options) ⇒ Object



132
133
134
# File 'lib/gs2crmod/gsl_data_3d.rb', line 132

def gsl_tensor(name, options)
	tensor = send((name.to_s+"_gsl_tensor").to_sym , options)
end

#gsl_vector(name, options = {}) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/gs2crmod/gsl_data.rb', line 117

def gsl_vector(name, options={})
  Dir.chdir(@directory) do
    options[:t_index_window] ||= @scan_index_window
    options.setup_time_window
    if [:ky, :kx].include? name.to_sym
      vec = fix_norm(
        GSL::Vector.alloc(netcdf_file.var(name.to_s).get.to_a.sort),
        -1, options
      ) # ky, ky are normalised to 1 / rho_i
      if i = options[:interpolate_ + name.to_s.sub(/k/, '').to_sym]
        if name.to_sym == :ky
          s = (vec.size - 1)*i + 1
          #return vec.connect(GSL::Vector.alloc((vec.size-1)*(i-1)) * 0.0)
          return (0...s).map{|k| k.to_f * vec[1]}.to_gslv
        else
          size = vec.size
          #vec = vec.to_box_order
          raise "Hmmm, kx.size should be odd" unless size%2 == 1
          s = (size-1)/2 * i
          return (-s..s).to_a.map{|ii| ii.to_f * vec.to_box_order[1]}.to_gslv
          #new_vec = GSL::Vector.alloc((s-1)*i + 1)
          #new_vec *= 0.0
          #for j in 0...((s-1)/2+1)
            #new_vec[j] = vec[j]
          #end
          #for j in 0...((s-1)/2)
            #new_vec[-j-1] = vec[-j-1]
          #end
          #return new_vec.from_box_order
        end


      else
        return vec
      end
    elsif [:theta].include? name.to_sym
      #ep options; gets
      #vec = GSL::Vector.alloc(netcdf_file.var(name.to_s).get({'start' => [options[:thetamin]||0], 'end' => [options[:thetamax]||-1]}).to_a)
      vec = GSL::Vector.alloc(netcdf_file.var(name.to_s).get.to_a)
      if gryfx? and options[:periodic]
        #vec = vec.connect([2.0*vec[-1] - vec[-2]].to_gslv)
        vec = vec.connect([-vec[0]].to_gslv)
      end
      if ith = options[:interpolate_theta]
        osize = vec.size
        newsize = (osize-1)*ith+1
        newvec = GSL::Vector.alloc(newsize)
        newvec[newsize-1] = vec[osize-1]# * ith.to_f
        for i in 0...(newsize-1)
          im = i%ith
          frac = im.to_f/ith.to_f
          #iold = (i-im)/(new_shape[-1]-1)*(shape[-1]-1)
          iold = (i-im)/ith
          newvec[i] =  (vec[iold] * (1.0-frac) + vec[iold+1] * frac)
        end
        vec = newvec
      end
      start = options[:thetamin]||0
      endv = options[:thetamax]||vec.size-1
      #ep ['options', options, 'vec.size', vec.size]
      vec = vec.subvector(start, (endv-start+1)).dup
      return vec
    elsif name.to_sym == :t
      #options.setup_time_window
      t = GSL::Vector.alloc(netcdf_file.var(name.to_s).get('start' => [options[:begin_element]], 'end' => [options[:end_element]]).to_a)
      t = t - t[0] if options[:sync_time]
      return fix_norm(t, -1, options) # t is normalised to a/v_thi
    end
    options = eval(options) if options.class == String
    if options[:saturated_time_average] or options[:sta]
      raise "Not Saturated" unless @saturation_time_index
      tmax = list(:t).keys.max
      return ((@saturation_time_index..tmax).to_a.map do |t_index|
        gsl_vector(name, options.dup.absorb({t_index: t_index, saturated_time_average: nil, sta: nil}))
      end).sum / (list(:t).values.max - list(:t)[@saturation_time_index])
    elsif options[:time_average] or options[:ta]
      tmax = list(:t).keys.max
      start_t = 2
      return ((start_t..tmax).to_a.map do |t_index|
        gsl_vector(name, options.dup.absorb({t_index: t_index, time_average: nil, ta: nil}))
      end).sum / (list(:t).values.max - list(:t)[start_t])
    end
    if method = self.class.instance_methods.find{|meth| (name + '_gsl_vector').to_sym == meth}
      options[:graphkit_name] = name
      return send(method, options)
    end
  end
  raise "GSL Vector #{name} not found"
end

#gsl_vector_complex(name, options = {}) ⇒ Object



1089
1090
1091
1092
1093
1094
1095
1096
# File 'lib/gs2crmod/gsl_data.rb', line 1089

def gsl_vector_complex(name, options={})
  options = eval(options) if options.class == String

    if method = self.class.instance_methods.find{|meth| (name + '_gsl_vector_complex').to_sym == meth}
      options[:graphkit_name] = name
      return send(method, options)
    end
end

#has_electrons?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/gs2crmod/properties.rb', line 16

def has_electrons?
	return @nspec.times.inject(false){|bool,  i| bool or send(:type_ + i.to_sym) =~ /electrons/i}
end

#hypercoll_graphkit(options) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/gs2crmod/read_netcdf.rb', line 234

def hypercoll_graphkit(options)
  case options[:command]
  when :help
    "Plot of the effect of hypercollisions"
  when :options
    return []
  else
    raise "This only works for spectrogk"  unless spectrogk?
    options[:modify_variable] = Proc.new do |varname, narray, dimhash|
      #dimnames = dimhash.keys
      p varname, dimhash
      if  varname == "gnew2_ta"
        shape = narray.shape
        m = dimhash['m']
        mmax = new_netcdf_file.var('hermite').get.to_a.size - 1
        p 'shape',shape
        for ig in 0...shape[0]
          for it in 0...shape[1]
            for ik in 0...shape[2]
              for il in 0...shape[3]
                for ie in 0...shape[4]
                  for is in 0...shape[5]
                    narray[ig,it,ik,il,ie,is]*=send(:nu_h_ + (is+1).to_sym)*(m[il]/mmax)**send(:nexp_h_ + (is+1).to_sym)
                  end
                end
              end
            end
          end
        end
      end
      narray
    end
    options[:graphkit_name] = 'cdf_gnew2_ta'
    return smart_graphkit(options)
  end
end

#hyperviscosity_graphkit(options) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/gs2crmod/read_netcdf.rb', line 197

def hyperviscosity_graphkit(options)
  case options[:command]
  when :help
    "Plot of the effect of hyperviscosity"
  when :options
    return []
  else
    raise "This only works for spectrogk"  unless spectrogk?
    options[:modify_variable] = Proc.new do |varname, narray, dimhash|
      #dimnames = dimhash.keys
      shape = narray.shape
      if  varname == "gnew2_ta"
        #p dimhash
        #p dimhash['Y']
        ky = dimhash['Y'].to_a.to_gslv
        kx = dimhash['X'].to_a.to_gslv
        shape = narray.shape
        for ig in 0...shape[0]
          for it in 0...shape[1]
            for ik in 0...shape[2]
              for il in 0...shape[3]
                for ie in 0...shape[4]
                  for is in 0...shape[5]
                    narray[ig,it,ik,il,ie,is]*=(ky[ik]**2.0 + kx[it]**2.0)**(2*@nexp)*@d_hypervisc
                  end
                end
              end
            end
          end
        end
      end
      narray
    end
    options[:graphkit_name] = 'cdf_gnew2_ta'
    return smart_graphkit(options)
  end
end

#incompleteObject



352
353
354
# File 'lib/gs2crmod/gs2.rb', line 352

def incomplete
  return (not 100 == percent_complete)
end

#ingenObject

Run the ingen tool on the input file



363
364
365
366
367
368
369
# File 'lib/gs2crmod/ingen.rb', line 363

def ingen
  Dir.chdir(@directory) do
    ing = File.dirname(File.expand_path(@executable)) + '/ingen'
    success = system "#{ing} #@run_name.in"
    warning("Could not run ingen... make sure that ingen is in the same folder as @executable and can be run on the login nodes if you want this to work") unless success
  end
end

#input_file_extensionObject



1204
1205
1206
# File 'lib/gs2crmod/gs2.rb', line 1204

def input_file_extension
  '.in'
end

#input_file_headerObject



942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
# File 'lib/gs2crmod/gs2.rb', line 942

def input_file_header
    run_namelist_backwards_compatibility
  <<EOF
!==============================================================================
!     GS2 INPUT FILE automatically generated by CodeRunner
!==============================================================================
!
!  GS2 is a gyrokinetic flux tube initial value turbulence code
!  which can be used for fusion or astrophysical plasmas.
!
!   See http://gyrokinetics.sourceforge.net
!
!  CodeRunner is a framework for the automated running and analysis
!  of large simulations.
!
!   See http://coderunner.sourceforge.net
!
!  Created on #{Time.now.to_s}
!      by CodeRunner version #{CodeRunner::CODE_RUNNER_VERSION.to_s}
!
!==============================================================================

EOF
end

#jump(options) ⇒ Object



1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
# File 'lib/gs2crmod/gsl_data.rb', line 1420

def jump(options)
# ep 'kx_shift',  kx_shift(options)
  jump =  ((kx_shift(options) / list(:kx)[2]).round)
  case options[:t_index]
  when 1
    return jump
  else
    if @g_exb and @g_exb.abs > 0
      return jump + 1
    else
      return 0
    end
  end
end

#kx_indexedObject



1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
# File 'lib/gs2crmod/gsl_data.rb', line 1479

def kx_indexed
  return cache[:kx_indexed] if cache[:kx_indexed]
  #kx = cache[:kx_array] ||= gsl_vector('kx').to_a
  #kxphys = kx.from_box_order
  #min_index = kx.min_index + 1
  #cache[:kx_indexed] ||= kx.size.times.inject({}) do |hash, kx_element|
    #hash[kx_element + 1] = kxphs
  kx = gsl_vector('kx')
  size = kx.size
  box =  GSL::Vector::Int.indgen(size) + 1
  zero_element = kx.abs.min_index
  phys = box.subvector(zero_element, size-zero_element).connect(box.subvector(0, zero_element))
  cache[:kx_indexed] = [phys.to_a, box.to_a].transpose.inject({}){|hash, (physi, boxi)| hash[physi] = boxi; hash}
end

#kx_shift(options) ⇒ Object



1413
1414
1415
1416
1417
1418
# File 'lib/gs2crmod/gsl_data.rb', line 1413

def kx_shift(options)
# ep options
  return 0 unless @g_exb and @g_exb.abs > 0.0
  #p options
  return - list(:ky)[options[:ky_index]] * list(:t)[(options[:t_index] or list(:t).keys.max)] * @g_exb
end

#latex_graphsObject

This section defines a selection of graphs which are written to a latex file when the CR function write_report is called. To add your own, simply copy one a similar looking graph and modify it to your needs. The requirements to use the latex report writing is further specified in CodeRunner.



1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
# File 'lib/gs2crmod/gs2.rb', line 1210

def latex_graphs
  #will have a different set of graphs to look at depending on whether linear or nonlinear
  if @nonlinear_mode == "off"
    #make up a list of graphs that are to be included. The order of the arguments is [code to generate graphkit, LaTeX description]
    graphs = [
      #[(kit = phi2_by_mode_vs_time({kx_index:1, ky_index:1}); kit.xlabel=%[TEST]; kit.gp.term = "post eps color enhanced size 3.5in,2.33in"; kit.gp.output = "test.eps"; kit), "This is a test graph written into a \LaTeX file. \n\n \\myfigure{test.eps}"]
      [(kit = phi2tot_vs_time_graphkit; kit.data[0].title=""; kit.gp.logscale="y"; kit.file_name = "phi2tot.eps"; kit), "Total $\\phi^2$ versus time."],
      [(kit = growth_rate_vs_ky_graphkit; kit.data[0].title=""; kit.file_name = "growth_rate_vs_ky.eps"; kit), "Growth rate $\\gamma_E$ as a function of $k_y$ averaged over $k_x$ (if applicable)."],
      if @grid_option=="range" then [(kit = graphkit('efnmag', {norm:true, kx_index:1, ky_index: :all}); kit.data.each{|dk| dk.title=""}; kit.gp.logscale="y"; kit.file_name = "efnmag.eps"; kit.data.shift; kit), "Normalized magnitude of the eigenfunction as a function of $\\theta$ for all $k_y$'s in the simulation."] end,
      if @grid_option=="single" then [(kit = graphkit('efnmag', {norm:true, kx_index:1, ky_index:1}); kit.data.each{|dk| dk.title=""}; kit.gp.logscale="y"; kit.file_name = "efnmag.eps"; kit), "Normalized magnitude of the eigenfunction as a function of $\\theta$ for all $k_y$'s in the simulation."] end,
    ].compact
  else
    graphs = [
      [(kit = ky_spectrum_graphkit; kit.gp.logscale="y"; kit.file_name = "ky_spectrum.eps"; kit), "$k_y$ spectrum at the final time step averaged over $k_x$."],
      [(kit = kx_spectrum_graphkit; kit.gp.logscale="y"; kit.file_name = "kx_spectrum.eps"; kit), "$k_x$ spectrum at the final time step averaged over $k_y$."],
      [(kit = spectrum_graphkit(no_zonal:true); kit.gp.view="map"; kit.gp.logscale="z"; kit.file_name = "spectrum.eps"; kit), "2D spectrum versus $k_x$ and $k_y$ without zonal flows."],
      [(kit = hflux_tot_vs_time_graphkit; kit.file_name = "hflux_tot_vs_time.eps"; kit), "Total heat flux $Q_{tot}$ as a function of time."],
      [(kit = es_heat_flux_vs_time_graphkit(species_index:1); kit.file_name = "es_heat_1_vs_time.eps"; kit), "Heat flux of species 1 versus time."],
      if @nspec > 1 then [(kit = es_heat_flux_vs_time_graphkit(species_index:2); kit.file_name = "es_heat_2_vs_time.eps"; kit), "Heat flux of species 2 versus time."] end,
      if @write_fluxes_by_mode then [(kit = es_heat_flux_vs_ky_graphkit(species_index:1); kit.gp.logscale="y" ; kit.file_name = "es_heat_1_vs_ky.eps"; kit), "Heat flux of species 1 as a function of $k_y$."] end,
      if (@nspec > 1 and @write_fluxes_by_mode) then [(kit = es_heat_flux_vs_ky_graphkit(species_index:2); kit.gp.logscale="y" ; kit.file_name = "es_heat_2_vs_ky.eps"; kit), "Heat flux of species 2 as a function of $k_y$."] end,
      if @write_fluxes_by_mode then [(kit = es_heat_flux_vs_ky_vs_kx_graphkit; kit.gp.view="map" ; kit.file_name = "es_heat_vs_ky_vs_kx.eps"; kit), "2D total heat flux spectrum as a function of $k_x$ and $k_y$."] end,
      [(kit = phi_real_space_graphkit(n0:1, thetamin:get_list_of(:theta).length/2, thetamax:get_list_of(:theta).length/2, gs2_coordinate_factor:1.0); kit.gp.view="map" ; kit.file_name = "phi_real_space.eps"; kit), "Potential fluctuations at the final time step vs GS2 $x$ and $y$ at the outboard midplane."],
      [(kit = density_real_space_graphkit(n0:1, species_index:1, thetamin:get_list_of(:theta).length/2, thetamax:get_list_of(:theta).length/2, gs2_coordinate_factor:1.0); kit.gp.view="map" ; kit.file_name = "density_real_space.eps"; kit), "Density fluctuations for species 1 at the final time step vs GS2 $x$ and $y$ at the outboard midplane."],
      if @nspec > 1 then [(kit = density_real_space_graphkit(n0:1, species_index:2, thetamin:get_list_of(:theta).length/2, thetamax:get_list_of(:theta).length/2, gs2_coordinate_factor:1.0); kit.gp.view="map" ; kit.file_name = "density_real_space.eps"; kit), "Density fluctuations for species 2 at the final time step vs GS2 $x$ and $y$ at the outboard midplane."] end,
      [(kit = es_mom_flux_vs_time_graphkit(species_index:1); kit.file_name = "es_mom_flux_1_vs_time.eps"; kit), "Momentum flux for species 1 as a function of time."],
      if @nspec > 1 then [(kit = es_mom_flux_vs_time_graphkit(species_index:2); kit.file_name = "es_mom_flux_2_vs_time.eps"; kit), "Momentum flux for species 2 as a function of time."] end,
      [(kit = zonal_spectrum_graphkit; kit.gp.logscale="y"; kit.file_name = "zonal_spectrum.eps"; kit), "Zonal spectrum at the final time step."],
      if @write_eigenfunc == ".true." then [(kit = zf_velocity_vs_x_graphkit(theta_index:get_list_of(:theta).length/2); kit.file_name = "zonal_flow_velocity_vs_x.eps"; kit), "Zonal flow velocity avg over time versus x."] end,
      if @write_eigenfunc == ".true." and @g_exb then [(kit = zf_velocity_vs_x_graphkit(theta_index:get_list_of(:theta).length/2, add_mean_flow:true); kit.file_name = "zonal_flow_velocity_vs_x_with_mean_flow.eps"; kit), "Zonal flow velocity with mean flow added avg over time versus x."] end,
    ].compact
  end

end

#lenardbern_graphkit(options) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/gs2crmod/read_netcdf.rb', line 270

def lenardbern_graphkit(options)
  case options[:command]
  when :help
    "Plot of the effect of Lenard Bernstein collisions"
  when :options
    return []
  else
    raise "This only works for spectrogk"  unless spectrogk?
    options[:modify_variable] = Proc.new do |varname, narray, dimhash|
      #dimnames = dimhash.keys
      if  varname == "gnew2_ta"
        m = dimhash['m']
        shape = narray.shape
        for ig in 0...shape[0]
          for it in 0...shape[1]
            for ik in 0...shape[2]
              for il in 0...shape[3]
                for ie in 0...shape[4]
                  for is in 0...shape[5]
                    narray[ig,it,ik,il,ie,is]*=send(:nu_ + (is+1).to_sym)*m[il]
                  end
                end
              end
            end
          end
        end
      end
      narray
    end
    options[:graphkit_name] = 'cdf_gnew2_ta'
    kit = smart_graphkit(options)
    return kit
  end
end

#list_of_response_filesObject

Return list of response files similar to method for restart files



609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'lib/gs2crmod/gs2.rb', line 609

def list_of_response_files
  Dir.chdir(@directory) do
    files = Dir.entries('response').grep(/\.response/).map{|file| 'response' + 
                                                           "/" + file}
    files = Dir.entries.grep(/\.response/) if files.size == 0
    if files.size == 0
      (Dir.entries.find_all{|dir| FileTest.directory? dir} - ['.', '..']).each do |dir|
        files = Dir.entries(dir).grep(/\.response/).map{|file| dir + "/" + file}
      end
    end
    return files
  end
end

#list_of_restart_filesObject Also known as: lorf

Return a list of restart file paths (relative to the run directory).



589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/gs2crmod/gs2.rb', line 589

def list_of_restart_files
  Dir.chdir(@directory) do
    files = Dir.entries.grep(/^\.\d+$/)
    files = Dir.entries.grep(/\.nc(?:\.\d|_ene)/) if files.size == 0
    if files.size == 0
      (Dir.entries.find_all{|dir| FileTest.directory? dir} - ['.', '..']).each do |dir|
        files = Dir.entries(dir).grep(/\.nc(?:\.\d|_ene)/).map{|file| dir + "/" + file}
        break if files.size == 0
      end
    end #if files.size == 0
    # Finds a .nc file (w/o a number) in 'nc' folder if using single restart file
    if files.size == 0
        files = Dir.entries('nc').grep(/\.nc/).map{|file| 'nc' + "/" + file}
    end #if files.size == 0
    return files
  end # Dir.chdir(@directory) do
end

#max_es_heat_amp(species_index) ⇒ Object



687
688
689
# File 'lib/gs2crmod/calculations.rb', line 687

def max_es_heat_amp(species_index)
	@transient_es_heat_flux_amplification_at_species_at_ky[species_index-1].values.max
end

#max_nprocs_no_xObject

ep parallelisation



352
353
354
355
# File 'lib/gs2crmod/ingen.rb', line 352

def max_nprocs_no_x
  parallelisation = cumulative_gridpoints
  parallelisation[parallelisation.keys[parallelisation.keys.index('x') - 1]]
end

#max_trans_phiObject



681
682
683
684
685
# File 'lib/gs2crmod/calculations.rb', line 681

def max_trans_phi
	phivec = gsl_vector('phi2tot_over_time')
	#offset = 30
	phivec.subvector(20, phivec.size - 20).max
end

#namelist_test_failed(namelist, tst) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/gs2crmod/ingen.rb', line 38

def namelist_test_failed(namelist, tst)
  return  <<EOF

---------------------------
  Test Failed
---------------------------

Namelist: #{namelist}
Test: #{tst[:test]}
Explanation: #{tst[:explanation]}

---------------------------
EOF

end

#nccloseObject



51
52
53
54
# File 'lib/gs2crmod/gsl_data.rb', line 51

def ncclose
  cache[:netcdf_file].close
  cache.delete(:netcdf_file)
end

#ncdump(names = nil, values = nil, extension = '.out.nc') ⇒ Object

Output useful information from the NetCDF file. If no names are provided, output a list of all variables in the NetCDF file. names can either be a symbol or an array of symbols, in which case information will be output for the variables with those names. If values are provided, for example :dims,:get, :ndims, this information is retrieved from the file for every variable named. ncdump ncdump(:hflux) ncdump([:hflux, :phi]) ncdump([:hflux, :phi], :dims)



271
272
273
274
275
# File 'lib/gs2crmod/gs2.rb', line 271

def ncdump(names=nil, values=nil, extension = '.out.nc')
  names = [names] unless !names or names.class == Array
  names.map!{|name| name.to_s} if names
  pp NumRu::NetCDF.open(@run_name + extension).vars(names).to_a.sort{|var1, var2| var1.name <=> var2.name}.map{|var| values ? [var.name, var.send(values)] : var.name.to_sym}
end

#netcdf_fileObject

def gsl_vector(name, options={})

if options[:t_index] or options[:frame_index] or not [:Failed, :Complete].include? status
  return get_gsl_vector(name, options)
else
  return cache[[:gsl_vector, name, options]] ||= get_gsl_vector(name, options)
end

end



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/gs2crmod/gsl_data.rb', line 30

def netcdf_file
  #if @runner.cache[:runs] and (open = @runner.cache[:runs].keys.find_all{|id| @runner.cache[:runs][id][:netcdf_file]}).size > 200
  #ep "my id", id
  if (open = @runner.run_list.keys.find_all{|id|  @runner.run_list[id].cache[:netcdf_file]}).size > 200
    open = open.sort_by{|id| @runner.run_list[id].cache[:netcdf_file_otime]}
    @runner.run_list[open[0]].ncclose
  end

  if cache[:netcdf_file] and not [:Complete, :Failed].include? @status
    ncclose
  end
  cache[:netcdf_file_otime] = Time.now.to_i
  cache[:netcdf_file] ||= NumRu::NetCDF.open(netcdf_filename)
  cache[:netcdf_file].sync
  cache[:netcdf_file]
end

#netcdf_filenameObject



47
48
49
# File 'lib/gs2crmod/gsl_data.rb', line 47

def netcdf_filename
  @directory + '/' +  @run_name + '.out.nc'
end

#netcdf_smart_readerObject



172
173
174
# File 'lib/gs2crmod/read_netcdf.rb', line 172

def netcdf_smart_reader
  NetcdfSmartReader.new(new_netcdf_file)
end

#no_restartsObject

Returns true if this run has not been restarted, false if it has. This allows one to get data from the final run of a series of restarts.

Raises:

  • (NoRunnerError)


661
662
663
664
# File 'lib/gs2crmod/gs2.rb', line 661

def no_restarts
  raise NoRunnerError unless @runner
  !(@runner.runs.find{|run| run.restart_id == @id})
end

#old_smart_graphkit(options) ⇒ Object



186
187
188
189
190
191
192
193
194
195
# File 'lib/gs2crmod/read_netcdf.rb', line 186

def old_smart_graphkit(options)
  case options[:command]
  when :help
    "An old smart graphkit is a direct plot of a given variable from the old netcdf file. The name of the graphkit is the name of the variable prefixed by 'nc_'. To plot, for example, the heat flux vs time, you would give the graph name nc_hflux_tot. You can use index specifiers in the the options; for example, to plot the potential as a function of kx and ky for a given time index, you would use the graph name nc_phi2_by_mode, and the options {t_index: n}. To plot the potential as function of kx for a given ky and time would use the options {t_index, n, ky_index: m}. For each dimension you can specify the index, or a minium and/or maximum."
  when :options
    [:kx_index, :ky_index, :t_index, :e_index, :l_index, :s_index, :kxmax, :kxmin, :kx_element]
  else
   return OldNetcdfSmartReader.new(netcdf_file).graphkit(options[:graphkit_name].sub(/^nc_/, ''), options)
  end
end

#optimisation_flagsObject



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/gs2crmod/ingen.rb', line 314

def optimisation_flags
  [
    :opt_redist_persist,
    :opt_redist_persist_overlap,
    :opt_redist_nbk,
    :opt_redist_init,
    :intmom_sub,
    :intspec_sub,
    #:local_field_solve,
    :do_smart_update,
    :field_subgath,
    :field_option,
    :field_local_allreduce,
    :field_local_allreduce_sub,
    :minnrow,
    :opt_init_bc,
    :opt_source
  ]
end

#parallelizable_meshpointsObject

Gives a guess as to the maximum number of meshpoints which can be parallelized (i.e. excluding ntheta)



917
918
919
# File 'lib/gs2crmod/gs2.rb', line 917

def parallelizable_meshpoints
  approximate_grid_size / ntheta
end

#parameter_stringObject



929
930
931
# File 'lib/gs2crmod/gs2.rb', line 929

def parameter_string
    return "#{@run_name}.in"
end

#parameter_transition(run) ⇒ Object



356
357
# File 'lib/gs2crmod/gs2.rb', line 356

def parameter_transition(run)
end

#percent_completeObject



393
394
395
# File 'lib/gs2crmod/gs2.rb', line 393

def percent_complete
  @completed_timesteps ? @completed_timesteps.to_f / @nstep.to_f * 100.0 : @percent_of_total_time
end

#physical_kx_index(box_kx_index) ⇒ Object



1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
# File 'lib/gs2crmod/gsl_data.rb', line 1499

def physical_kx_index(box_kx_index)
  return kx_indexed.key(box_kx_index)
  #kx = cache[:kx_gslv] ||= gsl_vector('kx')
  #return kx.from_box_order.to_a.index(kx[box_kx_index-1]) + 1
  #kx = cache[:kx_gslv] ||= gsl_vector('kx')
  #index_of_min_kx = cache[:index_of_min_kx] ||= kx.min_index + 1 # kx.min_index returns a 0-based index
  #if box_kx_index < index_of_min_kx
    #box_kx_index + (1 + kx.size - index_of_min_kx)
  #else
    #box_kx_index - (index_of_min_kx - 1)
  #end
end

#plot_efit_fileObject



1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
# File 'lib/gs2crmod/gs2.rb', line 1144

def plot_efit_file
  Dir.chdir(@directory) do
    text = File.read(@eqfile)
    text_lines = text.split("\n")
    first_line = text_lines[0].split(/\s+/)
    second_line = text_lines[1].split(/\s+/)
    nr = first_line[-2].to_i
    nz = first_line[-1].to_i
    rwidth = second_line[1].to_f
    zwidth = second_line[2].to_f
    rmag = second_line[3].to_f
    nlines = (nr.to_f/5.0).ceil
    nlines_psi = ((nr*nz).to_f/5.0).ceil
    start = 5
    f = text_lines[start...(start+=nlines)].join(" ").split(nil).map{|s| s.to_f}.to_gslv
    pres = text_lines[(start)...(start += nlines)].join(" ").split(nil).map{|s| s.to_f}.to_gslv
    _ = text_lines[(start)...(start += nlines)].join(" ").split(nil).map{|s| s.to_f}.to_gslv
    _ffprime = text_lines[(start)...(start+= nlines)].join(" ").split(nil).map{|s| s.to_f}.to_gslv
    psi = text_lines[(start)...(start += nlines_psi)].join(" ")
    q = text_lines[(start)...(start += nlines)].join(" ").split(nil).map{|s| s.to_f}.to_gslv
    nbound = text_lines[start...start+=1].join(" ").to_i
    rz = text_lines[(start)...(start += nbound*2)].join(" ").split(/\s+/)
    rz.shift
    rbound, zbound, _ = rz.inject([[], [], true]){|arr,val| arr[2] ? [arr[0].push(val), arr[1], false] : [arr[0], arr[1].push(val), true]}
    #rbound.shift

    psi = psi.split(/\s+/)
    psi.shift
    psi.map!{|v| v.to_f}
    psi_arr = SparseTensor.new(2)
    k = 0
    for i in 0...nz
      for j in 0...nr
        psi_arr[j,i] = psi[k]
        k+=1
      end
    end
    kit = GraphKit.quick_create([((0...nr).to_a.to_gslv - nr/2 - 1 )/(nr-1)*rwidth+rmag, ((0...nz).to_a.to_gslv-nz/2 + 1)/(nz-1) * zwidth, psi_arr], [rbound, zbound, rbound.map{|r| 0}])
    kit.gp.contour = ""
    kit.gp.view = "map"
    #kit.gp.nosurface = ""
    kit.gp.cntrparam = "levels 20"
    kit.data[0].gp.with = 'l'
    kit.data[1].gp.with = 'l lw 2 nocontours'
    kit.gnuplot

    kit2 = GraphKit.quick_create([pres/pres.max],[f/f.max],[q/q.max])
    kit2.data[0].title = 'Pressure/Max Pressure'
    kit2.data[1].title = 'Poloidal current function/Max poloidal current function'
    kit2.data[2].title = 'Safety factor/Max Safety factor'
    kit2.gnuplot



    #p ['f', f, 'p', pres, 'ffprime', ffprime, 'nlines', nlines, 'psi', psi, 'q', q, 'nbound', nbound, 'rbound', rbound, 'zbound', zbound]


  end
end


397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/gs2crmod/gs2.rb', line 397

def print_out_line
  logf(:print_out_line)
  name = @run_name
  name += " (res: #@restart_id)" if @restart_id
  name += " real_id: #@real_id" if @real_id
  beginning = sprintf("%2d:%d %-60s %1s:%2.1f(%s) %3s%1s %1s",  @id, @job_no, name, @status.to_s[0,1],  @run_time.to_f / 60.0, @nprocs.to_s, percent_complete, "%", @converged.to_s)
  if @ky
    beginning += sprintf("%3s %4s %4s", @ky, @growth_rates[@ky], @real_frequencies[@ky])
  elsif @nonlinear_mode == "off"
      beginning += sprintf("%3s %4s %4s",
       @fastest_growing_mode, @max_growth_rate,
      @freq_of_max_growth_rate)
  elsif @nonlinear_mode == "on"
 #      p @hflux_tot_stav
    beginning += "       sat:#{saturated.to_s[0]}"
    beginning += sprintf(" hflux:%1.2e", @hflux_tot_stav) if  @hflux_tot_stav
    beginning += sprintf("+/-%1.2e", @hflux_tot_stav_error) if  @hflux_tot_stav_error
    beginning += sprintf(" momflux:%1.2e", @es_mom_flux_stav.values.sum) if @es_mom_flux_stav and @es_mom_flux_stav.values[0]
    beginning += '  SC:' + @spectrum_check.map{|c| c.to_s}.join(',') if @spectrum_check
    beginning += '  VC:' + @vspace_check.map{|c| sprintf("%d", ((c*10.0).to_i rescue -1))}.join(',') if @vspace_check
  end
  beginning += "  ---#{@comment}" if @comment
  beginning

end

#process_directory_code_specificObject

This method, as its name suggests, is called whenever CodeRunner is asked to analyse a run directory.this happens if the run status is not :Complete, or if the user has specified recalc_all(-A on the command line) or reprocess_all (-a on the command line).

the structure of this function is very simple: first it calls get_status to determine the directory status, i.e. :Complete, :Incomplete, :NotStarted or :Failed, then it gets the time, which is the GS2 time at the end of the run, and it also gets the run_time, which is the wall clock time of the run. Finally,if non-linear mode is switched off, it calls calculate_growth_rates_and_frequencies, and if the non-linear mode is switched on, it calls calculate_time_averaged_fluxes.



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/gs2crmod/gs2.rb', line 202

def process_directory_code_specific
  run_namelist_backwards_compatibility

  unless @status == :Queueing
    get_status
  end

  eputs "Run #@status: #@run_name" if [:Complete,:Failed].include? @status

  try_to_get_error_file
  @sys = @@successful_trial_system

  return if @status == :NotStarted or @status == :Failed or @status == :Queueing
  begin
    percent_complete = get_completed_timesteps/@nstep
    @percent_of_total_time = percent_complete
  rescue
    get_time
    @percent_of_total_time = @time / (@delt*@nstep) * 100.0  rescue 0.0
  end
  return if @status == :Incomplete

  get_run_time

  calculate_results

end

#recheckObject

class ListSubmitter



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
# File 'lib/gs2crmod/gs2.rb', line 800

def recheck
  logf(:recheck)
  Dir.chdir(@directory) do
    logi('@runner.object_id', @runner.object_id)
    log('@runner.class',  @runner.class)
    #runner = @runner
    instance_variables.each{|var| instance_variable_set(var, nil) unless var == :@runner}
    begin File.delete(".code_runner_run_data") rescue Errno::ENOENT end
    begin File.delete("code_runner_results.rb") rescue Errno::ENOENT end
    logi(:@checked_converged, @checked_converged)
    logi('@runner.object_id after reset', @runner.object_id)
    log('@runner.class',  @runner.class)
    process_directory
  end
end

#renew_info_fileObject



1054
1055
1056
# File 'lib/gs2crmod/gs2.rb', line 1054

def renew_info_file
  Dir.chdir(@directory){make_info_file("#@run_name.in")}
end

#restart(new_run) ⇒ Object



483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/gs2crmod/gs2.rb', line 483

def restart(new_run)
  (rcp.variables).each{|v| new_run.set(v, send(v)) if send(v)}
  @naming_pars.delete(:preamble)
  SUBMIT_OPTIONS.each{|v| new_run.set(v, self.send(v)) unless new_run.send(v)}
  new_run.is_a_restart = true
  new_run.ginit_option = "many"
  new_run.delt_option = "check_restart"
  new_run.restart_id = @id
  new_run.restart_run_name = @run_name
  @runner.nprocs = @nprocs if @runner.nprocs == "1" # 1 is the default

  if !new_run.nprocs or new_run.nprocs != @nprocs
    raise "Restart must be on the same number of processors as the previous "\
          "run: new is #{new_run.nprocs.inspect} and old is #{@nprocs.inspect}"
  end
  new_run.run_name = nil
  new_run.naming_pars = @naming_pars
  new_run.update_submission_parameters(new_run.parameter_hash_string, false) if 
    new_run.parameter_hash
  new_run.naming_pars.delete(:restart_id)
  new_run.generate_run_name
  copy_restart_files(new_run)

  if new_run.read_response and new_run.read_response.fortran_true?
    new_run.response_id = new_run.restart_id
    copy_response_files(new_run)
  end

  new_run
end

#restart_chainObject



666
667
668
669
670
671
672
673
674
675
676
677
678
# File 'lib/gs2crmod/gs2.rb', line 666

def restart_chain
  if @restart_id
    return @runner.run_list[@restart_id].restart_chain
  end
  chain = []
  currid = @id
  loop do
    chain.push currid
    break unless (restrt = @runner.runs.find{|run| run.restart_id == currid})
    currid = restrt.id
  end
  return chain
end

#run_heuristic_analysisObject

This method overrides a method defined in heuristic_run_methods.rb in the CodeRunner source. It is called when CodeRunner cannot find any of its own files in the folder being analysed. It takes a GS2 input file and generates a CodeRunner info file. This means that GS2 runs which were not run using CodeRunner can nonetheless be analysed by it. In order for it to be called the -H flag must be specified on the command line.

Raises:

  • (CRMild)


1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
# File 'lib/gs2crmod/gs2.rb', line 1064

def run_heuristic_analysis
  ep 'run_heuristic_analysis', Dir.pwd
  infiles = Dir.entries.grep(/^[^\.].*\.in$/)
  ep infiles
  raise CRMild.new('No input file') unless infiles[0]
  raise CRError.new("More than one input file in this directory: \n\t#{infiles}") if infiles.size > 1
  input_file = infiles[0]
  ep 'asdf'
  @nprocs ||= "1"
  @executable ||= "/dev/null"
  make_info_file(input_file, false)
end

#run_namelist_backwards_compatibilityObject



1118
1119
1120
1121
1122
1123
# File 'lib/gs2crmod/gs2.rb', line 1118

def run_namelist_backwards_compatibility
  SPECIES_DEPENDENT_VARIABLES.each do |var|
    set(var + "_1".to_sym, (send(var + "_1".to_sym) or send(var + "_i".to_sym) or send(var)))
    set(var + "_2".to_sym, (send(var + "_2".to_sym) or send(var + "_e".to_sym)))
  end
end

#run_namelist_tests(namelist, hash, enum = nil) ⇒ Object

Checks input parameters for inconsistencies and prints a report.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/gs2crmod/ingen.rb', line 56

def run_namelist_tests(namelist, hash, enum = nil)
  ext = enum ? "_#{enum}" : ""
  hash[:must_pass].each do |tst|
    error(namelist_test_failed(namelist, tst)) unless instance_eval(tst[:test])
  end if hash[:must_pass]
  hash[:should_pass].each do |tst|
    warning(namelist_test_failed(namelist, tst)) unless instance_eval(tst[:test])
  end if hash[:should_pass]
  hash[:variables].each do |var, var_hash|
    #gs2_var = (var_hash[:gs2_name] or var)
    cr_var = var+ext.to_sym
    value = send(cr_var)
    if value.kind_of? Array
      value.each{|v| test_variable(namelist, var, var_hash, ext, v)}
    else
      test_variable(namelist, var, var_hash, ext, value)
    end
  end
end

#saturated_time_average(name, options) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/gs2crmod/calculations.rb', line 55

def saturated_time_average(name, options)
# 	calculate_saturation_time_index unless @saturation_time_index
# 	p 'sat', @saturation_time_index, 'max', list(:t).keys.max
	raise "saturation_time_index not calculated for #@run_name" unless @saturation_time_index
	options[:t_index_window] = [@saturation_time_index, list(:t).keys.max - 1]
	#ep gsl_vector(name, {}).size
	#ep name, options
	begin
		vec = gsl_vector(name, options)
	rescue GSL::ERROR::EINVAL
		# IF the vector doesn't have enough values for each timestep (due to run aborting early?), this error will be thrown.
		options[:t_index_window] = [@saturation_time_index, gsl_vector(name, {}).size]
		retry
	rescue NoMethodError
		eputs "Warning: could not calculate #{name} saturated time average"
		return nil
	end
	
		                                                               
		tvec = gsl_vector('t', options)

		                                                               
	dt = tvec.subvector(1, tvec.size - 1) - tvec.subvector(0, tvec.size - 1)
	trapezium = (vec.subvector(1, tvec.size - 1) + vec.subvector(0, tvec.size - 1)) / 2.0
	return trapezium.mul(dt).sum / dt.sum
end

#saturated_time_average_error(name, options) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/gs2crmod/calculations.rb', line 82

def saturated_time_average_error(name, options)
# 	calculate_saturation_time_index unless @saturation_time_index
	options[:t_index_window] = [@saturation_time_index, list(:t).keys.max]
	begin
		vec = gsl_vector(name, options)
		tavg = GSL::Vector.alloc(vec.size)
		vec.size.times.each{|i| tavg[i] = vec.subvector(i+1).mean}
	rescue NoMethodError
		eputs "Warning: could not calculate #{name} saturated_time_average_error"
		return nil
	end
# 	tavg = 0.0; i = 0
	
# 	tavg_vec = vec.collect{|val| tavg += val; tavg = tavg / (i+=1); tavg}
# 	ind = GSL::Vector.indgen(vec.size)
# 	i = 0
# 	begin 
# 		fit = GSL::Fit::linear(ind.subvector(i, ind.size - i) , vec.subvector(i, ind.size - i))
# # 		p fit[1].abs - 100.0 * fit[4].abs
# 		i += 1
# 		(eputs "Not Saturated"; break) if i > vec.size * 0.9
# 	end while (fit[1].abs - Math.sqrt(fit[4].abs)) > 0 
# 	p fit
# 	fit_vec = ind * fit[1] + fit[0]
# # 	p tavg.size
# 	# GraphKit.autocreate({x: {data: gsl_vector(name, {})}})
# 	(GraphKit.autocreate({x: {data: tavg}}) + GraphKit.autocreate({x: {data: vec}}) + GraphKit.autocreate({x: {data: fit_vec}})).gnuplot
	return tavg.sd
end

#saturated_time_average_std_dev(name, options) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
# File 'lib/gs2crmod/calculations.rb', line 112

def saturated_time_average_std_dev(name, options)
# 	calculate_saturation_time_index unless @saturation_time_index
	options[:t_index_window] = [@saturation_time_index, list(:t).keys.max]
	begin
		vec = gsl_vector(name, options)
	rescue NoMethodError
		eputs "Warning: could not calculate #{name} saturated_time_average_std_dev"
		return nil
	end
	return vec.sd
end

#sc(min) ⇒ Object



746
747
748
# File 'lib/gs2crmod/calculations.rb', line 746

def sc(min)
	return @spectrum_check.min >= min
end

#set_nprocsObject



880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
# File 'lib/gs2crmod/gs2.rb', line 880

def set_nprocs

  if (nprocs_in = @nprocs) =~ /^x/
    max = max_nprocs_no_x
    nodes = 0
    @nprocs = "#{nodes}#{nprocs_in}"
    loop do
      nodes += 1
      @nprocs = "#{nodes}#{nprocs_in}"
      if actual_number_of_processors > max
        nodes -= 1
        @nprocs = "#{nodes}#{nprocs_in}"
        break
      end
    end
  end
end

#show_graphObject



474
475
476
477
478
479
480
481
# File 'lib/gs2crmod/gs2.rb', line 474

def show_graph
  thegraph = special_graph('phi2tot_vs_time_all_kys')
  thegraph.title += " for g_exb = #{@g_exb.to_f.to_s}"
  thegraph.show
  sleep 1.5
#   @decaying = Feedback.get_boolean("Is the graph decaying?")
  thegraph.kill
end

#smart_graphkit(options) ⇒ Object



176
177
178
179
180
181
182
183
184
185
# File 'lib/gs2crmod/read_netcdf.rb', line 176

def smart_graphkit(options)
  case options[:command]
  when :help
    "A smart graphkit is a direct plot of a given variable from the new netcdf file. The name of the graphkit is the name of the variable prefixed by 'cdf_'. To plot, for example, the heat flux vs time, you would give the graph name cdf_heat_flux_tot. You can use index specifiers in the the options; for example, to plot the potential as a function of kx and ky for a given time index, you would use the graph name cdf_phi2_by_mode, and the options {t_index: n}. To plot the potential as function of kx for a given ky and time would use the options {t_index, n, Y_index: m}. For each dimension you can specify the index, or a minium and/or maximum."
  when :options
    [:X_index, :Y_index, :t_index, :e_index, :l_index, :s_index, :Xmax, :Xmin, :X_element]
  else
    netcdf_smart_reader.graphkit(options[:graphkit_name].sub(/^cdf_/, ''), options)
  end
end

#spec_chec(min, *dirns) ⇒ Object



732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/gs2crmod/calculations.rb', line 732

def spec_chec(min, *dirns)
	return @spectrum_check.zip([0, 1, 2]).inject(true) do |bool, (check,dirn)|
		unless dirns.include? dirn
			bool and true
		else
			unless check >= min
				false
			else
				bool and true
			end
		end
	end
end

#species_letterObject



645
646
647
# File 'lib/gs2crmod/gs2.rb', line 645

def species_letter
  species_type(1).downcase[0,1]
end

#species_type(index) ⇒ Object



649
650
651
652
653
654
655
656
657
# File 'lib/gs2crmod/gs2.rb', line 649

def species_type(index)
  if rcp.variables.include? :type_1
    type = send(:type_ + index.to_sym)
  else
    types = rcp.variables.find_all{|var| var.to_s =~ /^type/}.map{|var| send(var)}
    type = types[index.to_i - 1]
  end
  type
end

#spectrogk?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/gs2crmod/gs2.rb', line 56

def spectrogk?
  false
end

#standardize_restart_filesObject

Put restart files in the conventional location, i.e. nc/run_name.proc



624
625
626
627
628
629
630
631
632
633
# File 'lib/gs2crmod/gs2.rb', line 624

def standardize_restart_files
  Dir.chdir(@directory) do
    FileUtils.makedirs('nc')
    list_of_restart_files.each do |file|
      proc_id = file.scan(/\.\d+$|_ene$/)[0]
      #p 'proc_id', proc_id
      FileUtils.mv(file, "nc/#@run_name.nc#{proc_id}")
    end
  end
end

#stopObject



1125
1126
1127
# File 'lib/gs2crmod/gs2.rb', line 1125

def stop
  `touch #@directory/#@run_name.stop`
end

#test_failed(namelist, var, gs2_var, tst) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/gs2crmod/ingen.rb', line 18

def test_failed(namelist, var, gs2_var, tst)
  return  <<EOF

---------------------------
  Test Failed
---------------------------

Namelist: #{namelist}
Variable: #{var}
GS2 Name: #{gs2_var}
Value: #{send(var)}
Test: #{tst[:test]}
Explanation: #{tst[:explanation]}

---------------------------
EOF

end

#test_variable(namelist, var, var_hash, ext, value) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/gs2crmod/ingen.rb', line 76

def test_variable(namelist, var, var_hash, ext, value)
    gs2_var = (var_hash[:gs2_name] or var)
    cr_var = var+ext.to_sym
    if value and (not var_hash[:should_include] or  eval(var_hash[:should_include]))
      var_hash[:must_pass].each do |tst|
        error(test_failed(namelist, cr_var, gs2_var, tst)) unless value.instance_eval(tst[:test])
      end if var_hash[:must_pass]
      var_hash[:should_pass].each do |tst|
        warning(test_failed(namelist, cr_var, gs2_var, tst)) unless value.instance_eval(tst[:test])
      end if var_hash[:should_pass]
      if (var_hash[:allowed_values] or var_hash[:text_options])
        tst = {test: "#{(var_hash[:allowed_values] or var_hash[:text_options]).inspect}.include? self", explanation: "The variable must have one of these values"}
        error(test_failed(namelist, cr_var, gs2_var, tst)) unless value.instance_eval(tst[:test])
      end

    end
end

#update_physics_parameters_from_miller_input_file(file) ⇒ Object

def self.add_code_var

rcp.namelists.each do |namelist, hash|
  hash[:variables].each do |var, var_hash|
    p var
    var_hash[:code_name] = var_hash[:gs2_name] if var_hash[:gs2_name]
  end
end
save_namelists

end



1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
# File 'lib/gs2crmod/gs2.rb', line 1026

def update_physics_parameters_from_miller_input_file(file)
  hash = self.class.parse_input_file(file)
  hash[:parameters].each do |var, val|
    set(var,val)
  end
  hash[:theta_grid_parameters].each do |var, val|
    next if  [:ntheta, :nperiod].include? var
    set(var, val)
  end
  hash[:dist_fn_knobs].each do |var, val|
    next unless [:g_exb].include? var
    set(var, val)
  end
  hash[:theta_grid_eik_knobs].each do |var, val|
    next unless [:s_hat_input, :beta_prime_input].include? var
    set(var, val)
  end

  hash[:species_parameters_2].each do |var, val|
    #next unless [:s_hat_input, :beta_prime_input].include? var
    set((var.to_s + '_2').to_sym, val)
  end
  hash[:species_parameters_1].each do |var, val|
    #next unless [:s_hat_input, :beta_prime_input].include? var
    set((var.to_s + '_1').to_sym, val)
  end
end

#vim_inputObject Also known as: vi



1134
1135
1136
# File 'lib/gs2crmod/gs2.rb', line 1134

def vim_input
  system "vim -Ro #@directory/#@run_name.in "
end

#vim_outputObject Also known as: vo



1129
1130
1131
# File 'lib/gs2crmod/gs2.rb', line 1129

def vim_output
  system "vim -Ro #{output_file} #{error_file} #@directory/#@run_name.error #@directory/#@run_name.out "
end

#vim_stdoutObject Also known as: vo1



1139
1140
1141
# File 'lib/gs2crmod/gs2.rb', line 1139

def vim_stdout
  system "vim -Ro #{output_file} "
end

#visually_check_growth_rate(ky = nil) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/gs2crmod/gs2.rb', line 459

def visually_check_growth_rate(ky=nil)
  logf :visually_check_growth_rate
  phi_vec = gsl_vector(:phi2_by_ky_over_time, {ky: ky})
  t_vec = gsl_vector(:t)
  constant, growth_rate = GSL::Fit::linear(t_vec, 0.5*GSL::Sf::log(phi_vec)).slice(0..1)
  eputs growth_rate

  graph = @@phi2tot_vs_time_template.graph(["#{constant} * exp (2 * #{growth_rate} * x)"], [[[t_vec, phi_vec], "u 1:2 title 'phi2tot #{@run_name}' w p"]], {"set_show_commands" => "\nset log y\n", "point_size"=>'1.0'})
#   eputs graph.inline_data.inspect
  graph.show
  gets
  graph.kill

end

#warning(message) ⇒ Object



7
8
9
# File 'lib/gs2crmod/ingen.rb', line 7

def warning(message)
  eputs "Warning: " + message; sleep 0.3
end

#write_input_fileObject



876
877
878
# File 'lib/gs2crmod/gs2.rb', line 876

def write_input_file
  File.open(@run_name + ".in", 'w'){|file| file.puts input_file_text}
end