示例#1
0
def phys_info(properties_path):
    # set reader
    if os.path.isfile(properties_path) or os.path.isfile(os.path.join(properties_path, "data.h5")):
        reader = H5Reader(path = properties_path, use_cache=False, verbose=False)
    else:
        raise EnvironmentError("There is no corresponding data files in the path " + args.properties_path + ". Can not continue.")

    config = reader.meta

    for i in config.species:
        if i.name.lower() == 'electrons':
            el_density = (i.density[0] + i.density[1]) / 2
            el_temperature = i.temperature
        if i.name.lower() == 'ions':
            ion_density = (i.density[0] + i.density[1]) / 2
            ion_temperature = i.temperature

    if not el_density:
        print("Incorrect {} file (no particles->particle_kind->electrons section)".format(properties_path))
    elif not ion_density:
        print("Incorrect {} file (no particles->particle_kind->ions section)".format(properties_path))
    else:
        bunch_duration = config.beams[0].bunch_length / config.beams[0].velocity
        interval_bunches_duration = config.beams[0].bunches_distance / config.beams[0].velocity
        beam_length = config.beams[0].bunch_length * config.beams[0].bunch_amount + config.beams[0].bunches_distance * (config.beams[0].bunch_amount - 1)
        beam_duration = beam_length / config.beams[0].velocity
        w_p = langmur_freq(el_density)
        wake_len = wake_length(el_density, config.beams[0].velocity)
        debye = debye_length(el_density, ion_density, el_temperature, ion_temperature)
        bunch_part_number = math.pi * math.pow(config.beams[0].bunch_radius, 2) * bunch_duration * config.beams[0].velocity * config.beams[0].bunch_density

        print("General:")
        print("Expected plasma frequency:\t %.4g Hz"%(w_p/(2 * math.pi)))
        print("Expected wake wavelength:\t %.2g m"%(wake_len))
        print("Expected Debye length:\t\t %.4g m"%(debye))
        print("Estimated beam passage time:\t %.4g s"%(config.geometry_size[1] / config.beams[0].velocity + beam_duration))
        print("Number of calculation steps is\t %.4g"%((config.time[1] - config.time[0]) / float(config.time[2])))
        print()

        print("Beam:")
        print("Initial beam velocity:\t\t\t %.4g m/s"%(config.beams[0].velocity))
        if config.beams[0].bunch_amount > 1: print("Single bunch duration:\t\t\t %.4g s"%bunch_duration)
        print("Whole beam duration:\t\t\t %.4g s"%beam_duration)
        if config.beams[0].bunch_amount > 1:
            print("Bunch dimensions:\t\t\t length: %.4g m radius: %.4g m"%(config.beams[0].bunch_length, config.beams[0].bunch_radius))

        print("Beam dimensions:\t\t\t length: %.4g m radius: %.4g m"%(beam_length, config.beams[0].bunch_radius))
        if config.beams[0].bunch_amount > 1: print("Distance between bunch beginings:\t %.4g m"%(config.beams[0].bunches_distance + config.beams[0].bunch_length))
        if config.beams[0].bunch_amount > 1: print("Number of bunches in beam:\t\t %.4g"%config.beams[0].bunch_amount)
        if config.beams[0].bunch_amount > 1: print("Number of particles in single bunch:\t %.2g"%(bunch_part_number))
        print("Number of particles in beam:\t\t %.2g"%(bunch_part_number * config.beams[0].bunch_amount))
        print()
示例#2
0
def run(config_path,
        specie,
        clim,
        video_file=None,
        time_range=None,
        cmap=None,
        frame_step=1,
        frame_size=None,
        dry_run=False,
        view=False,
        use_grid=False,
        plot_image_interpolation='bicubic'):

    ##  configuration options
    x_axis_label = r'$\mathit{Z (m)}$'
    y_axis_label = r'$\mathit{R (m)}$'
    cbar_axis_label = r'$m^{-3}$'

    plot_name = r'$\mathbf{Density\enspace T(eV)}$'

    # calculate/update video file path
    video_file = os.path.join(
        config_path, 'density_movie.avi') if not video_file else video_file

    autoselect = True
    use_cache = False

    # set reader
    if os.path.isfile(os.path.join(config_path, "data.h5")):
        reader = H5Reader(path=config_path, use_cache=use_cache, verbose=False)
    else:
        raise EnvironmentError(
            "There is no corresponding data/metadata files in the path " +
            config_path + ". Can not continue.")

    # TODO: estimate clim
    if not clim: clim = [0, 2]

    if not frame_size:
        frame_size = [
            0, 0, reader.meta.geometry_grid[0], reader.meta.geometry_grid[1]
        ]
    frame_src_size = [-1, -1, -1, -1]

    # detect probe shape
    for probe in reader.meta.probes:
        if (probe.shape == 'rec') and (probe.specie == specie) and (
                probe.size[0]
                == frame_size[0]) and (probe.size[1] == frame_size[1]) and (
                    probe.size[2] == frame_size[2]) and (probe.size[3]
                                                         == frame_size[3]):
            frame_src_size = probe.size
    # try bigger frames, if autoselect enabled
    if frame_src_size[0] == -1 and frame_src_size[1] == -1 and frame_src_size[
            2] == -1 and frame_src_size[3] == -1 and autoselect:
        for probe in reader.meta.probes:
            if (probe.shape == 'rec') and (probe.specie == specie) and (
                    probe.size[0] <=
                    frame_size[0]) and (probe.size[1] <= frame_size[1]) and (
                        probe.size[2] >= frame_size[2]) and (probe.size[3] >=
                                                             frame_size[3]):
                frame_src_size = probe.size

    r_scale = (frame_size[2] - frame_size[0]) / reader.meta.geometry_grid[0]
    z_scale = (frame_size[3] - frame_size[1]) / reader.meta.geometry_grid[1]
    # define plot builder
    plot = PlotBuilder(frame_size[3] - frame_size[1],
                       frame_size[2] - frame_size[0],
                       fig_color=reader.meta.figure_color,
                       fig_width=reader.meta.figure_width,
                       fig_height=reader.meta.figure_height,
                       fig_dpi=reader.meta.figure_dpi,
                       font_family=reader.meta.figure_font_family,
                       font_name=reader.meta.figure_font_name,
                       font_size=reader.meta.figure_font_size,
                       x_ticklabel_end=reader.meta.geometry_size[1] * z_scale,
                       y_ticklabel_end=reader.meta.geometry_size[0] * r_scale,
                       tickbox=True,
                       grid=use_grid,
                       is_invert_y_axe=False,
                       aspect='equal',
                       image_interpolation=plot_image_interpolation,
                       guess_number_ticks=20)

    # add subplots
    plot.add_subplot_cartesian_2d(plot_name,
                                  111,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)

    # add initial image with zeros and colorbar
    initial_image = np.zeros(
        [frame_size[2] - frame_size[0], frame_size[3] - frame_size[1]])
    plot.add_image(plot_name, initial_image, cmap=cmap, clim=clim)
    plot.add_colorbar(plot_name, ticks=clim, title=cbar_axis_label)

    if view: plot.show()

    # dirty hack
    for p in reader.meta.probes:
        if p.component == 'density':
            dump_interval = p.schedule
            break

    if not time_range:
        start_frame = reader.meta.get_frame_number_by_timestamp(
            reader.meta.time[0], dump_interval)
        end_frame = reader.meta.get_frame_number_by_timestamp(
            reader.meta.time[1], dump_interval)
    else:
        if time_range[0] > time_range[1]:
            raise ValueError(
                "End time should not be less, than start time. The values were: {}, {}"
                .format(time_range[0], time_range[1]))
        if time_range[1] > reader.meta.time[1]:
            raise IndexError(
                "End time is out of simulation range {}. The value was {}".
                format(reader.meta.end_time, time_range[1]))

        start_frame = reader.meta.get_frame_number_by_timestamp(
            time_range[0], dump_interval)
        end_frame = reader.meta.get_frame_number_by_timestamp(
            time_range[1], dump_interval)

    FFMpegWriter = ani.writers['ffmpeg']
    metadata = dict(title='Plasma Density Evolution Movie',
                    artist='Matplotlib',
                    comment='Movie support!')
    writer = FFMpegWriter(fps=reader.meta.video_fps,
                          metadata=metadata,
                          codec=reader.meta.video_codec,
                          bitrate=reader.meta.video_bitrate)

    if dry_run: video_file = '/dev/null'
    fig = plot.get_figure()

    with writer.saving(fig, video_file, reader.meta.figure_dpi):
        for i in range(start_frame, end_frame):
            if i % frame_step == 0:
                sys.stdout.write('Loading dataset ' + str(i) + '... ')
                sys.stdout.flush()
                data = reader.rec("density/{}".format(specie), frame_src_size,
                                  i)[frame_size[0]:frame_size[2],
                                     frame_size[1]:frame_size[3]]

                # add timestamp to each frame
                timestamp = reader.meta.get_timestamp_by_frame_number(
                    i, dump_interval)
                fig.suptitle("Time: {:.2e} s".format(timestamp), x=.85, y=.95)

                plot.add_image(plot_name, data, cmap=cmap, clim=clim)

                if view: plot.redraw()
                if not dry_run: writer.grab_frame()
                print('DONE')
示例#3
0
def main():
    parser = argparse.ArgumentParser(description='Parser of output files metadata for PiCoPiC.')
    parser.add_argument('properties_path', metavar='properties_path', type=str,
                        help='Full path to properties.xml')
    parser.add_argument('--subtree', type=str,
                        help='Config`s subtree', default=None)
    parser.add_argument('--color-style', type=str,
                        help='Style of metadata colorization (works only with "--colorize" option)', default='autumn')
    parser.add_argument('--help-colors', action='store_true',
                        help='Output list of available color style names and exits', default=False)
    parser.add_argument('--colorize', action='store_true',
                        help='Make metadata output colorful',
                        default=False)
    parser.add_argument('--bo', action='store_true',
                        help='Display build options of PiCoPiC package, generated the data. Shortcut for `--subtree=[build_options]`',
                        default=False)
    parser.add_argument('--phys-info', action='store_true',
                        help='Display useful physical info about background plasma and particle beams',
                        default=False)
    parser.add_argument('-c', '--comment', action='store_true',
                        help='Display comment for datafile',
                        default=False)

    args = parser.parse_args()

    ## display physical info and exit
    if args.phys_info:
        phys_info(args.properties_path)
        sys.exit(0)

    ## display help about color schemes and exit
    if args.help_colors:
        print(list(STYLE_MAP.keys()))
        sys.exit(0)

    # set reader
    if os.path.isfile(args.properties_path) or os.path.isfile(os.path.join(args.properties_path, "data.h5")):
        reader = H5Reader(path = args.properties_path, use_cache=False, verbose=False)
    else:
        raise EnvironmentError("There is no corresponding data files in the path " + args.properties_path + ". Can not continue.")

    config = reader.meta.json
    if args.comment:
        args.bo = False
        args.subtree = False
        try:
            config = config['comment']
        except KeyError:
            print("Invalid metadata subtree key >>", args.comment, "<< can not continue")
            sys.exit(1)

    if args.bo: args.subtree = False
    if args.subtree:
        try:
            config = eval('config' + str(args.subtree).replace('[', '["').replace(']', '"]'))
        except KeyError:
            print("Invalid metadata subtree key >>", args.subtree, "<< can not continue")
            sys.exit(1)

    if args.bo:
        try:
            config = config['build_options']
        except KeyError:
            print("ERROR: Build options are absent. Seems, metadata is incomplete (is it configfile?).")
            sys.exit(1)

    json_dumped = json.dumps(config, indent=2, sort_keys=True)
    if args.colorize:
        print(highlight(json_dumped, JsonLexer(), Terminal256Formatter(style=args.color_style)))
    else:
        print(json_dumped)
示例#4
0
def run(config_path,
        specie,
        clim,
        video_file=None,
        time_range=None,
        cmap=None,
        frame_step=1,
        frame_size=None,
        dry_run=False,
        view=False,
        use_grid=False,
        plot_image_interpolation='bicubic'):

    ##  configuration options
    x_axis_label = r'$\mathit{Z (m)}$'
    y_axis_label = r'$\mathit{R (m)}$'
    cbar_axis_label = r'$m^{-3}$'

    plot_name_1 = r'$\mathbf{Beam\enspace Electrons\enspace Density}$'
    plot_name_2 = r'$\mathbf{Ions\enspace Density}$'
    plot_name_3 = r'$\mathbf{Electrons\enspace Density}$'
    plot_name_4 = r'$\mathbf{Ions\enspace Temperature}$'
    plot_name_5 = r'$\mathbf{Electrons\enspace Temperature}$'

    # calculate/update video file path
    video_file = os.path.join(
        config_path, 'multiplot_movie.avi') if not video_file else video_file

    autoselect = True
    use_cache = False

    # set reader
    if os.path.isfile(os.path.join(config_path, "data.h5")):
        reader = H5Reader(path=config_path, use_cache=use_cache, verbose=False)
    else:
        raise EnvironmentError(
            "There is no corresponding data/metadata files in the path " +
            config_path + ". Can not continue.")

    # TODO: estimate clim
    # if not clim: clim = [0,2]
    clim_1 = [0, 1e15]
    clim_2 = [5e16, 1.5e17]
    clim_3 = [5e16, 1.5e17]
    clim_4 = [0, 20]
    clim_5 = [0, 10000]

    if not frame_size:
        frame_size = [
            0, 0, reader.meta.geometry_grid[0], reader.meta.geometry_grid[1]
        ]
    frame_src_size = [-1, -1, -1, -1]

    # detect probe shape
    for probe in reader.meta.probes:
        if (probe.shape == 'rec') and (probe.specie == specie) and (
                probe.size[0]
                == frame_size[0]) and (probe.size[1] == frame_size[1]) and (
                    probe.size[2] == frame_size[2]) and (probe.size[3]
                                                         == frame_size[3]):
            frame_src_size = probe.size
    # try bigger frames, if autoselect enabled
    if frame_src_size[0] == -1 and frame_src_size[1] == -1 and frame_src_size[
            2] == -1 and frame_src_size[3] == -1 and autoselect:
        for probe in reader.meta.probes:
            if (probe.shape == 'rec') and (probe.specie == specie) and (
                    probe.size[0] <=
                    frame_size[0]) and (probe.size[1] <= frame_size[1]) and (
                        probe.size[2] >= frame_size[2]) and (probe.size[3] >=
                                                             frame_size[3]):
                frame_src_size = probe.size

    r_scale = (frame_size[2] - frame_size[0]) / reader.meta.geometry_grid[0]
    z_scale = (frame_size[3] - frame_size[1]) / reader.meta.geometry_grid[1]
    # define plot builder
    plot = PlotBuilder(
        frame_size[3] - frame_size[1],
        frame_size[2] - frame_size[0],
        fig_color=reader.meta.figure_color,
        fig_width=19.2,
        fig_height=10.8,
        fig_dpi=150,
        font_family=reader.meta.figure_font_family,
        font_name=reader.meta.figure_font_name,
        font_size=12,  # reader.meta.figure_font_size,
        x_ticklabel_end=reader.meta.geometry_size[1] * z_scale,
        y_ticklabel_end=reader.meta.geometry_size[0] * r_scale,
        tickbox=True,
        grid=use_grid,
        is_invert_y_axe=False,
        aspect='equal',
        image_interpolation=plot_image_interpolation,
        number_y_ticks=3,
        guess_number_ticks=20)

    # plt.rcParams['axes.titlesize'] = 10
    # plt.rcParams["axes.titlepad"] = 3

    # add subplots
    plot.add_subplot_cartesian_2d(plot_name_1,
                                  511,
                                  x_axe_label="",
                                  y_axe_label=y_axis_label)
    plot.get_subplot(plot_name_1).set_xticklabels([])
    for tic in plot.get_subplot(plot_name_1).xaxis.get_major_ticks():
        tic.tick1On = tic.tick2On = False

    plot.add_subplot_cartesian_2d(plot_name_2,
                                  512,
                                  x_axe_label="",
                                  y_axe_label=y_axis_label)
    plot.get_subplot(plot_name_2).set_xticklabels([])
    for tic in plot.get_subplot(plot_name_2).xaxis.get_major_ticks():
        tic.tick1On = tic.tick2On = False

    plot.add_subplot_cartesian_2d(plot_name_3,
                                  513,
                                  x_axe_label="",
                                  y_axe_label=y_axis_label)
    plot.get_subplot(plot_name_3).set_xticklabels([])
    for tic in plot.get_subplot(plot_name_3).xaxis.get_major_ticks():
        tic.tick1On = tic.tick2On = False

    plot.add_subplot_cartesian_2d(plot_name_4,
                                  514,
                                  x_axe_label="",
                                  y_axe_label=y_axis_label)
    plot.get_subplot(plot_name_4).set_xticklabels([])
    for tic in plot.get_subplot(plot_name_4).xaxis.get_major_ticks():
        tic.tick1On = tic.tick2On = False

    plot.add_subplot_cartesian_2d(plot_name_5,
                                  515,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)

    # add initial image with zeros and colorbar
    initial_image = np.zeros(
        [frame_size[2] - frame_size[0], frame_size[3] - frame_size[1]])

    cmap_r = "{}_r".format(cmap)
    print(cmap_r)
    plot.add_image(plot_name_1, initial_image, cmap=cmap_r, clim=clim_1)
    plot.add_colorbar(plot_name_1, ticks=clim_1, title=cbar_axis_label)

    plot.add_image(plot_name_2, initial_image, cmap=cmap, clim=clim_2)
    plot.add_colorbar(plot_name_2, ticks=clim_2, title=cbar_axis_label)

    plot.add_image(plot_name_3, initial_image, cmap=cmap, clim=clim_3)
    plot.add_colorbar(plot_name_3, ticks=clim_3, title=cbar_axis_label)

    plot.add_image(plot_name_4, initial_image, cmap=cmap, clim=clim_4)
    plot.add_colorbar(plot_name_4, ticks=clim_4, title=cbar_axis_label)

    plot.add_image(plot_name_5, initial_image, cmap=cmap, clim=clim_5)
    plot.add_colorbar(plot_name_5, ticks=clim_5, title=cbar_axis_label)

    if view: plot.show()

    # dirty hack
    for p in reader.meta.probes:
        if p.component == 'density':
            dump_interval = p.schedule
            break

    if not time_range:
        start_frame = reader.meta.get_frame_number_by_timestamp(
            reader.meta.time[0], dump_interval)
        end_frame = reader.meta.get_frame_number_by_timestamp(
            reader.meta.time[1], dump_interval)
    else:
        if time_range[0] > time_range[1]:
            raise ValueError(
                "End time should not be less, than start time. The values were: {}, {}"
                .format(time_range[0], time_range[1]))
        if time_range[1] > reader.meta.time[1]:
            raise IndexError(
                "End time is out of simulation range {}. The value was {}".
                format(reader.meta.end_time, time_range[1]))

        start_frame = reader.meta.get_frame_number_by_timestamp(
            time_range[0], dump_interval)
        end_frame = reader.meta.get_frame_number_by_timestamp(
            time_range[1], dump_interval)

    FFMpegWriter = ani.writers['ffmpeg']
    metadata = dict(title='Plasma Multiplot Movie',
                    artist='Matplotlib',
                    comment='Movie support!')
    writer = FFMpegWriter(fps=reader.meta.video_fps,
                          metadata=metadata,
                          codec=reader.meta.video_codec,
                          bitrate=reader.meta.video_bitrate)

    if dry_run: video_file = '/dev/null'
    fig = plot.get_figure()

    with writer.saving(fig, video_file, reader.meta.figure_dpi):
        for i in range(start_frame, end_frame):
            if i % frame_step == 0:
                sys.stdout.write('Loading dataset ' + str(i) + '... ')
                sys.stdout.flush()
                data_1 = reader.rec("density/beam_electrons", frame_src_size,
                                    i)[frame_size[0]:frame_size[2],
                                       frame_size[1]:frame_size[3]]
                data_2 = reader.rec("density/ions", frame_src_size,
                                    i)[frame_size[0]:frame_size[2],
                                       frame_size[1]:frame_size[3]]
                data_3 = reader.rec("density/electrons", frame_src_size,
                                    i)[frame_size[0]:frame_size[2],
                                       frame_size[1]:frame_size[3]]
                data_4 = reader.rec("temperature/ions", frame_src_size,
                                    i)[frame_size[0]:frame_size[2],
                                       frame_size[1]:frame_size[3]]
                data_5 = reader.rec("temperature/electrons", frame_src_size,
                                    i)[frame_size[0]:frame_size[2],
                                       frame_size[1]:frame_size[3]]

                # add timestamp to each frame
                timestamp = reader.meta.get_timestamp_by_frame_number(
                    i, dump_interval)
                fig.suptitle("Time: {:.2e} s".format(timestamp), x=.85, y=.95)

                plot.add_image(plot_name_1, data_1, cmap=cmap_r, clim=clim_1)
                plot.add_image(plot_name_2, data_2, cmap=cmap, clim=clim_2)
                plot.add_image(plot_name_3, data_3, cmap=cmap, clim=clim_3)
                plot.add_image(plot_name_4, data_4, cmap=cmap, clim=clim_4)
                plot.add_image(plot_name_5, data_5, cmap=cmap, clim=clim_5)

                if view: plot.redraw()
                if not dry_run: writer.grab_frame()
                print('DONE')
示例#5
0
def run(config_path,
        clim_e_r,
        clim_e_z,
        rho_beam_scale,
        video_file=None,
        time_range=None,
        cmap=None,
        frame_step=1,
        frame_size=None,
        dry_run=False,
        view=False,
        use_grid=False):

    ##  configuration options
    x_axis_label = r'$\mathit{Z (m)}$'
    y_axis_label = r'$\mathit{R (m)}$'
    cbar_axis_label = r'$\frac{V}{m}$'
    cbar_bunch_density_axis_label = r'$eV$'

    e_r_plot_name = r'$\mathbf{Electrical\enspace Field\enspace Radial\enspace Component}\enspace(E_r)$'
    e_z_plot_name = r'$\mathbf{Electrical\enspace Field\enspace Longitudal\enspace Component}\enspace(E_z)$'
    rho_beam_plot_name = r'$\mathbf{Temperature\enspace T\enspace (eV)}$'

    # calculate/update video file path
    video_file = os.path.join(
        config_path, 'field_movie.avi') if not video_file else video_file

    autoselect = True
    use_cache = False

    # set reader
    if os.path.isfile(os.path.join(config_path, "data.h5")):
        reader = H5Reader(path=config_path, use_cache=use_cache, verbose=False)
    else:
        raise EnvironmentError(
            "There is no corresponding data/metadata files in the path " +
            config_path + ". Can not continue.")

    clim_rho_beam = [
        0, 2.5
    ]  # 0-2.5:0-5e-10, 0-5:5e-10-1e-9, 0-40:1e-9-1.5e-9, 0-100:1.5e-9-2e-9, 0-200:2e-9-2.5e-9, 0-400:2.5e-9-3e-9 # [-(cfg.bunch_density * el_charge * rho_beam_scale), 0]
    clim_estimation = reader.meta.get_clim_estimation()

    if not clim_e_r: clim_e_r = [-clim_estimation, clim_estimation]
    if not clim_e_z: clim_e_z = [-clim_estimation, clim_estimation]
    if not rho_beam_scale: rho_beam_scale = 1

    if not frame_size:
        frame_size = [
            0, 0, reader.meta.geometry_grid[0], reader.meta.geometry_grid[1]
        ]
    frame_src_size = [-1, -1, -1, -1]

    # detect probe shape
    for probe in reader.meta.probes:
        if (probe.shape == 'rec') and (probe.size[0] == frame_size[0]) and (
                probe.size[1] == frame_size[1]) and (
                    probe.size[2] == frame_size[2]) and (probe.size[3]
                                                         == frame_size[3]):
            frame_src_size = probe.size
    # try bigger frames, if autoselect enabled
    if frame_src_size[0] == -1 and frame_src_size[1] == -1 and frame_src_size[
            2] == -1 and frame_src_size[3] == -1 and autoselect:
        for probe in reader.meta.probes:
            if (probe.shape
                    == 'rec') and (probe.size[0] <= frame_size[0]) and (
                        probe.size[1] <= frame_size[1]) and (
                            probe.size[2] >= frame_size[2]) and (
                                probe.size[3] >= frame_size[3]):
                frame_src_size = probe.size

    # define plot builder
    plot = PlotBuilder(
        frame_size[3] - frame_size[1],
        frame_size[2] - frame_size[0],
        fig_color=reader.meta.figure_color,
        fig_width=9,  # reader.meta.figure_width,
        fig_height=9.2,  # reader.meta.figure_height,
        fig_dpi=reader.meta.figure_dpi + 10,
        font_family=reader.meta.figure_font_family,
        font_name=reader.meta.figure_font_name,
        font_size=10,  # reader.meta.figure_font_size,
        x_ticklabel_start=reader.meta.geometry_size[1] /
        reader.meta.geometry_grid[1] * frame_size[1],
        y_ticklabel_start=reader.meta.geometry_size[0] /
        reader.meta.geometry_grid[0] * frame_size[0],
        x_ticklabel_end=reader.meta.geometry_size[1] /
        reader.meta.geometry_grid[1] * frame_size[3],
        y_ticklabel_end=reader.meta.geometry_size[0] /
        reader.meta.geometry_grid[0] * frame_size[2],
        number_x_ticks=20,
        number_y_ticks=10,
        number_cbar_ticks=3,
        tickbox=True,
        grid=use_grid,
        is_invert_y_axe=False,
        aspect='equal',
        image_interpolation='bicubic')

    # add subplots
    plot.add_subplot_cartesian_2d(e_r_plot_name,
                                  312,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)
    plot.add_subplot_cartesian_2d(e_z_plot_name,
                                  311,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)
    plot.add_subplot_cartesian_2d(rho_beam_plot_name,
                                  313,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)

    # add initial image with zeros and colorbar
    initial_image = np.zeros(
        [frame_size[2] - frame_size[0], frame_size[3] - frame_size[1]])

    plot.add_image(e_r_plot_name, initial_image, cmap=cmap, clim=clim_e_r)
    plot.add_colorbar(e_r_plot_name, ticks=clim_e_r, title=cbar_axis_label)

    plot.add_image(e_z_plot_name, initial_image, cmap=cmap, clim=clim_e_z)
    plot.add_colorbar(e_z_plot_name, ticks=clim_e_z, title=cbar_axis_label)

    plot.add_image(rho_beam_plot_name,
                   initial_image,
                   cmap="{}_r".format(cmap),
                   clim=clim_rho_beam)
    plot.add_colorbar(rho_beam_plot_name,
                      ticks=clim_rho_beam,
                      title=cbar_bunch_density_axis_label)

    if view: plot.show()

    # dirty hack
    for p in reader.meta.probes:
        if p.component == 'E/r' or p.component == 'E/z' or (
                p.component == 'density' and p.specie == 'beam_electrons'):
            dump_interval = p.schedule
            break

    if not time_range:
        start_frame = reader.meta.get_frame_number_by_timestamp(
            reader.meta.time[0], dump_interval)
        end_frame = reader.meta.get_frame_number_by_timestamp(
            reader.meta.time[1], dump_interval)
    else:
        if time_range[0] > time_range[1]:
            raise ValueError(
                "End time should not be less, than start time. The values were: {}, {}"
                .format(time_range[0], time_range[1]))
        if time_range[1] > reader.meta.time[1]:
            raise IndexError(
                "End time is out of simulation range {}. The value was {}".
                format(reader.meta.time[1], time_range[1]))

        start_frame = reader.meta.get_frame_number_by_timestamp(
            time_range[0], dump_interval)
        end_frame = reader.meta.get_frame_number_by_timestamp(
            time_range[1], dump_interval)

    FFMpegWriter = ani.writers['ffmpeg']
    metadata = dict(title='Field Components and Beam Evolution Movie',
                    artist='Matplotlib',
                    comment='Movie support!')
    writer = FFMpegWriter(fps=reader.meta.video_fps,
                          metadata=metadata,
                          codec=reader.meta.video_codec,
                          bitrate=reader.meta.video_bitrate)

    if dry_run: video_file = '/dev/null'
    fig = plot.get_figure()

    with writer.saving(fig, video_file, reader.meta.figure_dpi):
        for i in range(start_frame, end_frame):
            if i % frame_step == 0:
                sys.stdout.write('Loading dataset ' + str(i) + '... ')
                sys.stdout.flush()
                data_r = reader.rec('E/r', frame_src_size,
                                    i)[frame_size[0]:frame_size[2],
                                       frame_size[1]:frame_size[3]]
                data_z = reader.rec('E/z', frame_src_size,
                                    i)[frame_size[0]:frame_size[2],
                                       frame_size[1]:frame_size[3]]
                data_beam = reader.rec('temperature/electrons', frame_src_size,
                                       i)[frame_size[0]:frame_size[2],
                                          frame_size[1]:frame_size[3]]

                # add timestamp to each frame
                timestamp = reader.meta.get_timestamp_by_frame_number(
                    i, dump_interval)
                fig.suptitle("Time: {:.2e} s".format(timestamp), x=.85, y=.95)
                plot.add_image(e_r_plot_name, data_r, cmap=cmap, clim=clim_e_r)
                plot.add_image(e_z_plot_name, data_z, cmap=cmap, clim=clim_e_z)
                plot.add_image(rho_beam_plot_name,
                               data_beam,
                               cmap="{}_r".format(cmap),
                               clim=clim_rho_beam)

                if view: plot.redraw()
                if not dry_run: writer.grab_frame()
                print('DONE')
示例#6
0
def regression_test_example(template_name,
                            accept_ieee=True,
                            verbose=False,
                            debug=False):
    status = True

    # regression_dir

    b = bootstrap(
        testdir='testingdir',
        parameters_template_name=template_name,
        keep_working_dir=debug,  # if debug, keep working dir for analysis
        accept_ieee=accept_ieee,
        verbose=verbose,
        debug=debug)

    utils = Util()

    meta = MetaReader(os.path.join(b.testdir, 'PiCoPiC.json'))

    el_charge = 1.6e-19
    rho_beam_scale = 1
    clim_estimation = meta.get_clim_estimation()
    shape = [0, 0, 100, 500]
    temperature_shape = [90, 1000, 130, 1200]  # 90,130,1000,1200]

    timestamp = 1e-8
    time_range = [meta.start_time, meta.end_time]

    use_cache = False
    use_grid = True
    cmap = 'terrain'
    temperature_component = 'electrons'

    clim_e_r = [-clim_estimation, clim_estimation]
    clim_e_z = [-clim_estimation, clim_estimation]
    clim_rho_beam = [-(meta.bunch_density * el_charge * rho_beam_scale), 0]
    autoselect = True
    x_axis_label = r'$\mathit{Z (m)}$'
    y_axis_label = r'$\mathit{R (m)}$'
    temperature_x_axis_label = r'$\mathit{t (s)}$'
    temperature_y_axis_label = r'$\mathit{T ( K^\circ )}$'
    e_x_axis_label = r'$\mathit{t (s)}$'
    e_y_r_axis_label = r'$\mathit{E_r (\frac{V}{m})}$'
    e_y_z_axis_label = r'$\mathit{E_z (\frac{V}{m})}$'
    cbar_axis_label = r'$\frac{V}{m}$'
    cbar_bunch_density_axis_label = r'$m^{-3}$'

    e_r_plot_name = r'$\mathbf{Electrical\enspace Field\enspace Radial\enspace Component}\enspace(E_r)$'
    e_z_plot_name = r'$\mathbf{Electrical\enspace Field\enspace Longitudal\enspace Component}\enspace(E_z)$'
    rho_beam_plot_name = r'$\mathbf{Electron\enspace Bunch\enspace Density}\enspace (\rho_{bunch})$'
    temperature_plot_name = r'$\mathbf{Temperature-time \enspace Dependency}\enspace(T)$'
    e_e_r_plot_name = r'$\mathbf{Electrical\enspace Field\enspace Radial\enspace Component}\enspace(E_r)$'
    e_e_z_plot_name = r'$\mathbf{Electrical\enspace Field\enspace Longitudal\enspace Component}\enspace(E_z)$'

    e_shape = [34, 341]

    r_scale = (shape[2] - shape[0]) / meta.number_r_grid
    z_scale = (shape[3] - shape[1]) / meta.number_z_grid

    if os.path.isfile(os.path.join(self.config_path, "data.h5")):
        reader = H5Reader(path=self.config_path,
                          use_cache=use_cache,
                          verbose=verbose)
    else:
        raise EnvironmentError(
            "There is no corresponding data/metadata files in the path " +
            config_path + ". Can not continue.")

    ############################################################################

    plot = PlotBuilder(shape[3] - shape[1],
                       shape[2] - shape[0],
                       fig_color=meta.figure_color,
                       fig_width=meta.figure_width,
                       fig_height=meta.figure_height,
                       fig_dpi=meta.figure_dpi,
                       font_family=meta.figure_font_family,
                       font_name=meta.figure_font_name,
                       font_size=meta.figure_font_size,
                       x_ticklabel_end=meta.z_size * z_scale,
                       y_ticklabel_end=meta.r_size * r_scale,
                       tickbox=True,
                       grid=use_grid,
                       is_invert_y_axe=False,
                       aspect='equal',
                       image_interpolation='nearest',
                       guess_number_ticks=20)

    # add subplots
    plot.add_subplot_cartesian_2d(e_r_plot_name,
                                  311,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)
    plot.add_subplot_cartesian_2d(e_z_plot_name,
                                  312,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)
    plot.add_subplot_cartesian_2d(rho_beam_plot_name,
                                  313,
                                  x_axe_label=x_axis_label,
                                  y_axe_label=y_axis_label)

    # add initial image with zeros and colorbar
    initial_image = np.zeros([shape[2] - shape[0], shape[3] - shape[1]])

    # add dummy images
    plot.add_image(e_r_plot_name, initial_image, cmap=cmap, clim=clim_e_r)
    plot.add_image(e_z_plot_name, initial_image, cmap=cmap, clim=clim_e_z)
    plot.add_image(rho_beam_plot_name,
                   initial_image,
                   cmap=cmap,
                   clim=clim_rho_beam)

    # add colorbars
    plot.add_colorbar(e_r_plot_name, ticks=clim_e_r, title=cbar_axis_label)
    plot.add_colorbar(e_z_plot_name, ticks=clim_e_z, title=cbar_axis_label)
    plot.add_colorbar(rho_beam_plot_name,
                      ticks=clim_rho_beam,
                      title=cbar_bunch_density_axis_label)
    # plot.show()

    data_r = data_z = data_beam = []

    for probe in meta.probes:
        frame = meta.get_frame_number_by_timestamp(timestamp, probe.schedule)
        if (probe.type == 'frame') and (probe.r_start == shape[0]) and (
                probe.z_start == shape[1]) and (probe.r_end
                                                == shape[2]) and (probe.z_end
                                                                  == shape[3]):
            if probe.component == 'E_r':
                data_r = reader.get_frame('E_r', shape, frame)
            if probe.component == 'E_z':
                data_z = reader.get_frame('E_z', shape, frame)
            if probe.component == 'rho_beam':
                data_beam = reader.get_frame('rho_beam', shape, frame)

    # add timestamp to plot
    plot.get_figure().suptitle("Time: {:.2e} s".format(timestamp),
                               x=.85,
                               y=.95)

    # add images
    plot.add_image(e_r_plot_name, data_r, cmap=cmap, clim=clim_e_r)
    plot.add_image(e_z_plot_name, data_z, cmap=cmap, clim=clim_e_z)
    plot.add_image(rho_beam_plot_name,
                   data_beam,
                   cmap=cmap,
                   clim=clim_rho_beam)

    plot.save(os.path.join(b.rootdir, 'image.png'))

    ############################################################################

    start_frame = None
    end_frame = None
    dump_interval = None
    temperature = []

    temperature_r = []
    temperature_phi = []
    temperature_z = []

    for probe in meta.probes:
        if (probe.type == 'mpframe') and (
                probe.component == temperature_component) and (
                    probe.r_start == temperature_shape[0]) and (
                        probe.z_start == temperature_shape[1]) and (
                            probe.r_end == temperature_shape[2]) and (
                                probe.z_end == temperature_shape[3]):
            dump_interval = probe.schedule
            start_frame = meta.get_frame_number_by_timestamp(
                time_range[0], dump_interval)
            end_frame = meta.get_frame_number_by_timestamp(
                time_range[1], dump_interval) - 1
            for i in range(start_frame, end_frame):
                el_sum_r = 0
                el_sum_phi = 0
                el_sum_z = 0
                # calculating element
                r = np.fromfile(
                    "{}/{}/{}/mpframe_{}:{}_{}:{}/{}_vel_r.dat".format(
                        meta.config_path, meta.data_root, probe.component,
                        temperature_shape[0], temperature_shape[1],
                        temperature_shape[2], temperature_shape[3], i),
                    dtype='float',
                    sep=' ')
                phi = np.fromfile(
                    "{}/{}/{}/mpframe_{}:{}_{}:{}/{}_vel_phi.dat".format(
                        meta.config_path, meta.data_root, probe.component,
                        temperature_shape[0], temperature_shape[1],
                        temperature_shape[2], temperature_shape[3], i),
                    dtype='float',
                    sep=' ')
                z = np.fromfile(
                    "{}/{}/{}/mpframe_{}:{}_{}:{}/{}_vel_z.dat".format(
                        meta.config_path, meta.data_root, probe.component,
                        temperature_shape[0], temperature_shape[1],
                        temperature_shape[2], temperature_shape[3], i),
                    dtype='float',
                    sep=' ')
                print("processing frame", i)
                for i in range(0, len(r) - 1):
                    # el_sum_sq += r[i]*r[i]+phi[i]*phi[i]+z[i]*z[i]
                    el_sum_r += abs(r[i])
                    el_sum_phi += abs(phi[i])
                    el_sum_z += abs(z[i])

                # temperature.append(math.sqrt(el_sum_sq / len(r)))
                temperature_r.append(el_sum_r / len(r))
                temperature_phi.append(el_sum_phi / len(r))
                temperature_z.append(el_sum_z / len(r))

    data_timeline = np.linspace(time_range[0], time_range[1],
                                len(temperature_r))

    # define plot builder
    plot = PlotBuilder(
        0,
        0,  # let the system detects sizes automatically
        fig_color=meta.figure_color,
        fig_width=meta.figure_width,
        fig_height=meta.figure_height,
        fig_dpi=meta.figure_dpi,
        font_family=meta.figure_font_family,
        font_name=meta.figure_font_name,
        font_size=meta.figure_font_size,
        tickbox=True,
        grid=use_grid,
        is_invert_y_axe=False,
        aspect='auto',
        guess_number_ticks=20,
        x_ticklabel_start=time_range[0],
        x_ticklabel_end=time_range[1])

    # add subplots
    plot_t = plot.add_subplot_cartesian_2d(
        temperature_plot_name,
        111,
        x_axe_label=temperature_x_axis_label,
        y_axe_label=temperature_y_axis_label)

    plot_t.plot(data_timeline, temperature_r, label="r")
    plot_t.plot(data_timeline, temperature_phi, label="phi")
    plot_t.plot(data_timeline, temperature_z, label="z")
    plot_t.legend(loc='upper left')

    plot.save(os.path.join(b.rootdir, 'image_temperature.png'))

    ############################################################################

    # get data
    start_frame = None  # meta.get_frame_number_by_timestamp(time_range[0])
    end_frame = None  # 460 # meta.get_frame_number_by_timestamp(time_range[1])

    data_r = data_z = []

    for probe in meta.probes:
        if (probe.type == 'dot') and (probe.r_start
                                      == e_shape[0]) and (probe.z_start
                                                          == e_shape[1]):
            start_frame = meta.get_frame_number_by_timestamp(
                time_range[0], probe.schedule)
            end_frame = meta.get_frame_number_by_timestamp(
                time_range[1], probe.schedule) - 1
            if probe.component == 'E_r':
                data_r = reader.get_frame_range_dot('E_r', e_shape[0],
                                                    e_shape[1], start_frame,
                                                    end_frame)
            if probe.component == 'E_z':
                data_z = reader.get_frame_range_dot('E_z', e_shape[0],
                                                    e_shape[1], start_frame,
                                                    end_frame)

    data_timeline = np.linspace(time_range[0], time_range[1], len(data_r))

    # define plot builder
    plot = PlotBuilder(
        0,
        0,  # let the system detects sizes automatically
        fig_color=meta.figure_color,
        fig_width=meta.figure_width,
        fig_height=meta.figure_height,
        fig_dpi=meta.figure_dpi,
        font_family=meta.figure_font_family,
        font_name=meta.figure_font_name,
        font_size=meta.figure_font_size,
        tickbox=True,
        grid=use_grid,
        is_invert_y_axe=False,
        aspect='auto',
        guess_number_ticks=20,
        # number_x_ticks=10, number_y_ticks=10
        x_ticklabel_end=1e-9,
        y_ticklabel_end=1e-9)

    # add subplots
    plot_r = plot.add_subplot_cartesian_2d(e_e_r_plot_name,
                                           121,
                                           x_axe_label=e_x_axis_label,
                                           y_axe_label=e_y_r_axis_label)
    plot_z = plot.add_subplot_cartesian_2d(e_e_z_plot_name,
                                           122,
                                           x_axe_label=e_x_axis_label,
                                           y_axe_label=e_y_z_axis_label)

    plot_r.plot(data_timeline, data_r)
    plot_z.plot(data_timeline, data_z)

    plot.save(os.path.join(b.rootdir, 'image_e.png'))

    return status