예제 #1
0
def makeOutput(game):

    gameFile = 'games/%s.txt' % game
    seqFile = 'json/%s_sequences.json' % game
    dataFile = 'json/%s_datapoints.json' % game
    
    p1, p2 = parsing.processInfosets(gameFile)
    parsing.processSeqIDs(p1, p2, seqFile)
    parsing.getData(p1, p2, dataFile)
    '''
    hm1 = hv.HoloMap({(i.player,name): genCurves(i)
                      for p in (p1,p2)
                      for name,i in p.items()},
                     kdims=['player','infoset'])
    '''
    p1 = hv.HoloMap({name: genCurves(i) for name,i in p1.items()},
                    kdims=['infoset'])
    p2 = hv.HoloMap({name: genCurves(i) for name,i in p2.items()},
                    kdims=['infoset'])
    grid1 = hv.GridSpace(p1)
    grid2 = hv.GridSpace(p2)

    layout1 = hv.NdLayout(grid1).cols(2)
    layout2 = hv.NdLayout(grid2).cols(2)
    hv.output(layout1 + layout2, size=150, filename=game)
예제 #2
0
def new_game_of_life_grid(game_size, plot_size, x_grid, y_grid, shrink_factor):
    small_plot_size = round(plot_size / shrink_factor)
    graphs = [
        new_game_of_life_graph(game_size, small_plot_size)
        for _ in range(x_grid * y_grid)
    ]
    gridspace = hv.GridSpace(group='Games', kdims=['i', 'j'])
    for i in range(x_grid):
        for j in range(y_grid):
            gridspace[i, j] = graphs[i + j]  # put the dmap in the grid
    return gridspace, graphs
예제 #3
0
def modify_doc(doc):
    def sine_curve(phase, freq):
        xvals = [0.1 * i for i in range(100)]
        return hv.Curve((xvals, [np.sin(phase + freq * x) for x in xvals]))

    phases = [0, np.pi / 2, np.pi, 3 * np.pi / 2]
    frequencies = [0.5, 0.75, 1.0, 1.25]

    curve_dict_2D = {(p, f): sine_curve(p, f)
                     for p in phases for f in frequencies}
    gridspace = hv.GridSpace(curve_dict_2D, kdims=['phase', 'frequency'])
    hv.output(size=50)
    hmap = hv.HoloMap(gridspace)

    final = hmap + hv.GridSpace(hmap)

    plot = renderer.get_plot(final)
    layout = row(plot.state)
    # renderer.server_doc(layout)

    doc.add_root(layout)
예제 #4
0
파일: holoviews.py 프로젝트: zbsun/Arsenal
def assemble_patterns_image(data_holder, row_num, col_num, index, value_range,
                            pattern_shape):
    """
    After the program has obtained the index of the patterns in the selected region,
    this function randomly choose several of the patterns to show in a grid-space.

    Specifically, each pattern in this function is a holoview image object.


    :param data_holder: The holder containing all the data shown in the diagram
    :param row_num: The row number of the grid space
    :param col_num: The column number of the grid space
    :param index: The index of all the data in the selected region
    :param value_range: The range of values to show a numpy array as RGB image.
    :param pattern_shape: The pattern shape
    :return: hv.GridSpace
    """
    index = np.array(index)
    index_num = index.shape[0]
    if index_num >= row_num * col_num:
        np.random.shuffle(index)
        sampled_index = index[:row_num * col_num]
        sampled_index = sampled_index.reshape((row_num, col_num))

        image_holder = {(x, y): hv.Image(
            data_holder[sampled_index[x, y]]).redim.range(z=(value_range[0],
                                                             value_range[1]))
                        for x in range(row_num) for y in range(col_num)}
    else:
        # When we do not have so many patterns, first layout
        # all the patterns available and then fill the other
        # positions with patterns of zeros.
        index_list = [(x, y) for x in range(row_num) for y in range(col_num)]
        image_holder = {
            index_list[l]:
            hv.Image(data_holder[index[l]]).redim.range(z=(value_range[0],
                                                           value_range[1]))
            for l in range(index_num)
        }
        image_holder.update({
            index_list[l]: hv.Image(np.zeros(pattern_shape, dtype=np.float64))
            for l in range(index_num, row_num * col_num)
        })

    return hv.GridSpace(image_holder)
예제 #5
0
def plot_phase_exploration(d, phi0=-180, phi1=185):    
    gridspace = hv.GridSpace(kdims=['type'])
    
    X_curves = {}
    Y_curves = {}
    sym_curves = {}
    
    for phi in range(-180, 185, 5):
        Xp_ph = d.Rp * np.cos(np.deg2rad(d.Tp + phi))
        Xm_ph = d.Rm * np.cos(np.deg2rad(d.Tm + phi))
        Yp_ph = d.Rp * np.sin(np.deg2rad(d.Tp + phi))
        Ym_ph = d.Rm * np.sin(np.deg2rad(d.Tm + phi))
        Xsym_ph = (Xp_ph + Xm_ph)/2
        Xasym_ph = (Xp_ph - Xm_ph)/2
        X_curves[phi] = hv.Curve((d.xum, Xp_ph), label='X+ ph') * hv.Curve((d.xum, Xm_ph), label='X- ph')
        Y_curves[phi] = hv.Curve((d.xum, Yp_ph), label='Y+ ph') * hv.Curve((d.xum, Ym_ph), label='Y- ph')
        sym_curves[phi] = hv.Curve((d.xum, Xsym_ph), label='+') * hv.Curve((d.xum, Xasym_ph), label='-')
    
    gridspace['X'] = hv.HoloMap(X_curves, kdims=['phi'], label='X')
    gridspace['Y'] = hv.HoloMap(Y_curves, kdims=['phi'], label='Y')
    gridspace['sym-asym'] = hv.HoloMap(sym_curves, kdims=['phi'], label='sym-asym')
    
    return  gridspace(plot={'show_legend': True})
예제 #6
0
def new_game_of_life_grid(game_size=10,
                          plot_size=100,
                          x_grid=1,
                          y_grid=1,
                          shrink_factor=1.0,
                          bgcolor=default_bgcolor,
                          cmap=default_cmap,
                          use_fixed_cell_sizes=default_use_fixed_cell_sizes,
                          max_cell_age=default_max_cell_age):
    small_plot_size = round(plot_size / shrink_factor)
    graphs = []
    for _ in range(x_grid * y_grid):
        graphs.append(
            new_game_of_life_graph(game_size,
                                   small_plot_size,
                                   bgcolor=bgcolor,
                                   cmap=cmap,
                                   use_fixed_cell_sizes=use_fixed_cell_sizes,
                                   max_cell_age=max_cell_age))
    gridspace = hv.GridSpace(group='Games', kdims=['i', 'j'])
    for i in range(x_grid):
        for j in range(y_grid):
            gridspace[i, j] = graphs[i + j]  # put the dmap in the grid
    return gridspace, graphs
예제 #7
0
        def gather_plot(seismic_buttons, wiggle_buttons, seismic_iline,
                        traces_iline, seismic_xline, traces_xline, time_slice,
                        time_interval):
            """
            NAME
            ----
                gather_plot
            
            DESCRIPTION
            -----------
                Constructs a grid of angle gathers.

                Collects angle gathers into one plot given a range of lines by using Holoviews
                and bokeh as backend.
                
            ARGUMENTS
            ---------
                Arguments are given by Panel's widgets through the panel's depend decorator:

                    seismic_buttons : str
                        Seismic direction to base the amplitude plotting.

                    wiggle_buttons : str
                        Desired amplitude's plot type. Can be given manually or by Panel's
                        radio button widget. "Wavelet" will plot amplitudes using only a sine
                        curve, "Black wiggle" will fill with black the area between the sin curve
                        and time_axis and "Colored wiggle", will fill with blue/red the positive/negative 
                        area between the sin curve and time_axis.
                              
                    seismic_iline : int
                        Inline number selection.

                    traces_iline : tuple
                        Range of crosslines to be intersected with seismic_iline.

                    seismic_xline : int
                        Crossline number selection.

                    traces_xline : tuple
                        Range of inlines to be intersected with seismic_xline.

                    time_slice : list
                        Time slice of interest. 

                    time_interval : int
                        Chosen time interval.

                    Survey.merge_path : str
                        Path where the merge of the PAS is located.
  
                                          
            RETURN
            ------
                GridSpace : Holviews element [GridSpace]
                    Angle gathers.
            
            """

            # f.gather[2405, 2664, :] array // f.gather[2405:2408, 2664:2667, :] generator!! Presents errores while giving atributes
            #When is not hardcoded

            #Opening seismic file (once)
            with segyio.open(Survey.merge_path) as segy:

                gather_dict = {}
                # Storing scaling fac
                WiggleModule.scaling_factor(
                    self, segyio.tools.collect(segy.trace[:]))

                # Storing time array
                WiggleModule.time(self, time_interval)

                # Segyio gather Generator
                if seismic_buttons == "Inline":
                    trace_counter = traces_iline[0]
                    for gather in segy.gather[
                            seismic_iline,
                            traces_iline[0]:traces_iline[-1] + 1, :]:
                        gather_dict[
                            f"{seismic_iline}/{trace_counter}"] = WiggleModule.wiggle_plot(
                                self, gather, time_slice, wiggle_buttons)
                        trace_counter += 1
                elif seismic_buttons == "Crossline":
                    trace_counter = traces_xline[0]
                    for gather in segy.gather[traces_xline[0]:traces_xline[1] +
                                              1, seismic_xline, :]:
                        gather_dict[
                            f"C{trace_counter}/{seismic_xline}"] = WiggleModule.wiggle_plot(
                                self, gather, time_slice, wiggle_buttons)
                        trace_counter += 1

                # Gathers
                GridSpace = hv.GridSpace(gather_dict, kdims=['Trace'])
                return (GridSpace)

                column = pn.Column('# Column', w1, w2, background='WhiteSmoke')
예제 #8
0
    def CreatePlot(ResultsNames, VerticalAxisLabel):
        "Create overlay plot of column names"

        def MyCycle(List, Enum):
            "Return a value from the list"
            RetVal = List[Enum % len(List)]
            return RetVal

        PlotList = [(holoviews.GridSpace(
            HoloviewsDataSet.to(
                holoviews.Scatter, ['Treatment Level'],
                PlotOutcome,
                label=VerticalAxisLabel,
                group=PlotOutcome).redim.label(**{
                    PlotOutcome: VerticalAxisLabel
                }).overlay(['Repetition']).options({
                    'Scatter': {
                        'color': MyCycle(ColorList, Enum),
                        'marker': MyCycle(MarkerList, Enum),
                        'size': 2,
                        'legend_position': 'right',
                        'show_legend': True
                    },
                    'NdOverlay': {
                        'legend_position': 'right',
                        'show_legend': True
                    },
                    'Overlay': {
                        'legend_position': 'right',
                        'show_legend': True
                    }
                })).options({
                    'GridSpace': {
                        'shared_yaxis': True,
                        'shared_xaxis': True
                    }
                })) for (Enum, PlotOutcome) in enumerate(ResultsNames)]
        PlotListAggregate = [(holoviews.GridSpace(
            HoloviewsAggregate.to(
                holoviews.Curve, ['Treatment Level'],
                PlotOutcome,
                label=VerticalAxisLabel,
                group=PlotOutcome).redim.label(**{
                    PlotOutcome: VerticalAxisLabel
                }).options({
                    'Curve': {
                        'color': MyCycle(ColorList, Enum),
                        'show_legend': True
                    },
                    'NdOverlay': {
                        'legend_position': 'right',
                        'show_legend': True
                    }
                })).options({
                    'GridSpace': {
                        'shared_yaxis': True,
                        'shared_xaxis': True
                    }
                })) for (Enum, PlotOutcome) in enumerate(ResultsNames)]
        HoloviewsText = [
            holoviews.Text(0.5, (Enum + 1) / (len(ResultsNames) + 1) * 0.7,
                           PlotOutcome).options({
                               'Text': {
                                   'color': MyCycle(ColorList, Enum),
                                   'xaxis': None,
                                   'yaxis': None,
                                   'show_frame': False
                               }
                           })
            for (Enum, PlotOutcome) in enumerate(ResultsNames)
        ]

        CreatedPlot = reduce(operator.mul, PlotList)
        CreatePlotAggregate = reduce(operator.mul, PlotListAggregate)
        CreatePlotTexts = reduce(operator.mul, HoloviewsText)

        return CreatedPlot, CreatePlotAggregate, CreatePlotTexts
예제 #9
0
파일: holoviews.py 프로젝트: zbsun/Arsenal
def assemble_patterns_curve(y_data_array, y_range, x_data, x_range, row_num,
                            col_num, index):
    """
    After the program has obtained the index of the patterns in the selected region,
    this function randomly choose several of the patterns to show in a grid-space.

    Specifically, each pattern in this function is a holoview curve object. This function also
    assume that all curves share the same x-axis.

    :param y_data_array: 2D numpy array of the shape [n, curve_length] where n is the pattern number in total.
    :param y_range: The y range of the pattern.
    :param x_data: The x coordinate of the curve.
    :param x_range: The x range of the pattern.
    :param row_num: The row number of the grid space
    :param col_num: The column number of the grid space
    :param index: The index of all the data in the selected region
    :return: hv.GridSpace
    """
    index = np.array(index)
    index_num = index.shape[0]

    # Get the span of x
    x_span = (x_data.max() - x_data.min())

    if y_range == 'auto' and x_range == 'auto':
        if index_num >= row_num * col_num:

            # Extract some samples from all the selected ones.
            np.random.shuffle(index)
            sampled_index = index[:row_num * col_num]
            sampled_index = sampled_index.reshape((row_num, col_num))

            # Assemble the patterns
            image_holder = {}
            for x in range(row_num):
                for y in range(col_num):
                    # Get the span of the y values
                    y_data = y_data_array[sampled_index[x, y]]
                    y_span = y_data.max() - y_data.min()

                    image_holder.update({
                        (x, y):
                        hv.Curve((x_data, y_data)).redim.range(
                            x=(x_data.min() - x_span * 0.05,
                               x_data.max() + x_span * 0.05),
                            y=(y_data.min() - y_span * 0.05,
                               y_data.max() + y_span * 0.05))
                    })
        else:
            # When we do not have so many patterns, first layout
            # all the patterns available and then fill the other
            # positions with patterns of zeros.
            index_list = [(x, y) for x in range(row_num)
                          for y in range(col_num)]

            # Assemble the True patterns
            image_holder = {}
            for l in range(index_num):
                # Get the span of the y values
                y_data = y_data_array[index[l]]
                y_span = y_data.max() - y_data.min()

                image_holder.update({
                    index_list[l]:
                    hv.Curve(
                        (x_data,
                         y_data)).redim.range(x=(x_data.min() - x_span * 0.05,
                                                 x_data.max() + x_span * 0.05),
                                              y=(y_data.min() - y_span * 0.05,
                                                 y_data.max() + y_span * 0.05))
                })

            # Assemble the psudo-image
            image_holder.update({
                index_list[l]: hv.Curve(
                    (x_data, np.zeros_like(x_data))).redim.range(
                        x=(x_data.min() - x_span * 0.05,
                           x_data.max() + x_span * 0.05),
                        y=(0, 1))
                for l in range(index_num, row_num * col_num)
            })

    elif y_range == 'auto' and x_range != 'auto':  # If y_range is auto while x is specified

        if index_num >= row_num * col_num:

            # Extract some samples from all the selected ones.
            np.random.shuffle(index)
            sampled_index = index[:row_num * col_num]
            sampled_index = sampled_index.reshape((row_num, col_num))

            # Assemble the patterns
            image_holder = {}
            for x in range(row_num):
                for y in range(col_num):
                    # Get the span of the y values
                    y_data = y_data_array[sampled_index[x, y]]
                    y_span = y_data.max() - y_data.min()

                    image_holder.update({
                        (x, y):
                        hv.Curve((x_data, y_data)).redim.range(
                            x=(x_range[0], x_range[1]),
                            y=(y_data.min() - y_span * 0.05,
                               y_data.max() + y_span * 0.05))
                    })
        else:
            # When we do not have so many patterns, first layout
            # all the patterns available and then fill the other
            # positions with patterns of zeros.
            index_list = [(x, y) for x in range(row_num)
                          for y in range(col_num)]

            # Assemble the True patterns
            image_holder = {}
            for l in range(index_num):
                # Get the span of the y values
                y_data = y_data_array[index[l]]
                y_span = y_data.max() - y_data.min()

                image_holder.update({
                    index_list[l]:
                    hv.Curve(
                        (x_data,
                         y_data)).redim.range(x=(x_range[0], x_range[1]),
                                              y=(y_data.min() - y_span * 0.05,
                                                 y_data.max() + y_span * 0.05))
                })

            # Assemble the psudo-image
            image_holder.update({
                index_list[l]: hv.Curve(
                    (x_data,
                     np.zeros_like(x_data))).redim.range(x=(x_range[0],
                                                            x_range[1]),
                                                         y=(0, 1))
                for l in range(index_num, row_num * col_num)
            })

    elif y_range != 'auto' and x_range == 'auto':

        if index_num >= row_num * col_num:

            # Extract some samples from all the selected ones.
            np.random.shuffle(index)
            sampled_index = index[:row_num * col_num]
            sampled_index = sampled_index.reshape((row_num, col_num))

            # Assemble the patterns
            image_holder = {}
            for x in range(row_num):
                for y in range(col_num):
                    # Get the span of the y values
                    y_data = y_data_array[sampled_index[x, y]]

                    image_holder.update({
                        (x, y):
                        hv.Curve((x_data, y_data)).redim.range(
                            x=(x_data.min() - x_span * 0.05,
                               x_data.max() + x_span * 0.05),
                            y=(y_range[0], y_range[1]))
                    })
        else:
            # When we do not have so many patterns, first layout
            # all the patterns available and then fill the other
            # positions with patterns of zeros.
            index_list = [(x, y) for x in range(row_num)
                          for y in range(col_num)]

            # Assemble the True patterns
            image_holder = {}
            for l in range(index_num):
                # Get the span of the y values
                y_data = y_data_array[index[l]]

                image_holder.update({
                    index_list[l]:
                    hv.Curve(
                        (x_data,
                         y_data)).redim.range(x=(x_data.min() - x_span * 0.05,
                                                 x_data.max() + x_span * 0.05),
                                              y=(y_range[0], y_range[1]))
                })

            # Assemble the psudo-image
            image_holder.update({
                index_list[l]: hv.Curve(
                    (x_data, np.zeros_like(x_data))).redim.range(
                        x=(x_data.min() - x_span * 0.05,
                           x_data.max() + x_span * 0.05),
                        y=(y_range[0], y_range[1]))
                for l in range(index_num, row_num * col_num)
            })

    else:  # If neither x_range or y_range is specified
        if index_num >= row_num * col_num:

            # Extract some samples from all the selected ones.
            np.random.shuffle(index)
            sampled_index = index[:row_num * col_num]
            sampled_index = sampled_index.reshape((row_num, col_num))

            # Assemble the patterns
            image_holder = {}
            for x in range(row_num):
                for y in range(col_num):
                    # Get the span of the y values
                    y_data = y_data_array[sampled_index[x, y]]

                    image_holder.update({
                        (x, y):
                        hv.Curve(
                            (x_data,
                             y_data)).redim.range(x=(x_range[0], x_range[1]),
                                                  y=(y_range[0], y_range[1]))
                    })
        else:
            # When we do not have so many patterns, first layout
            # all the patterns available and then fill the other
            # positions with patterns of zeros.
            index_list = [(x, y) for x in range(row_num)
                          for y in range(col_num)]

            # Assemble the True patterns
            image_holder = {}
            for l in range(index_num):
                # Get the span of the y values
                y_data = y_data_array[index[l]]

                image_holder.update({
                    index_list[l]:
                    hv.Curve((x_data,
                              y_data)).redim.range(x=(x_range[0], x_range[1]),
                                                   y=(y_range[0], y_range[1]))
                })

            # Assemble the psudo-image
            image_holder.update({
                index_list[l]: hv.Curve(
                    (x_data, np.zeros_like(x_data))).redim.range(
                        x=(x_range[0], x_range[1]), y=(y_range[0], y_range[1]))
                for l in range(index_num, row_num * col_num)
            })

    return hv.GridSpace(image_holder)
예제 #10
0
def covar_plot(x_var, y_var, x_range, y_range):
    cvs = ds.Canvas(plot_width=plot_width,
                    plot_height=plot_height,
                    x_range=x_range,
                    y_range=y_range)
    agg = cvs.points(data, x_var, y_var, ds.count(y_var))
    return hv.Image(agg).opts(colorbar=False,
                              cmap='Blues',
                              logz=True,
                              width=int(plot_width * zoom_multiplier),
                              height=int(plot_height * zoom_multiplier))


plot_dict = hv.OrderedDict([])
for yy in range(0, len(y_var)):
    # y_range = (np.nanmin(data.loc[:, yy]),np.nanmax(data.loc[:, yy]))
    y_range = (np.nanquantile(data.loc[:, y_var[yy]], .001),
               np.nanquantile(data.loc[:, y_var[yy]], .999))
    for xx in range(yy, len(x_var)):
        # x_range = (np.nanmin(data.loc[:, x_var]),np.nanmax(data.loc[:, x_var]))
        x_range = (np.nanquantile(data.loc[:, x_var[xx]], .001),
                   np.nanquantile(data.loc[:, x_var[xx]], .999))
        plot_dict[(y_var[yy], x_var[xx])] = covar_plot(y_var[yy], x_var[xx],
                                                       y_range, x_range)

kdims = [hv.Dimension(('y_var', 'yy')), hv.Dimension(('x_var', 'xx'))]
holomap = hv.HoloMap(plot_dict, kdims=kdims)
# holomap.opts(opts.Curve(width=600))

grid = hv.GridSpace(holomap, sort=False)
grid
예제 #11
0
    def view(self,
             plane='axial',
             three_planes=False,
             image_size=300,
             dynamic=True,
             cmap='gray'):
        # imopts = {'tools': ['hover'], 'width': 400, 'height': 400, 'cmap': 'gray'}
        # imopts = {'tools': ['hover'], 'cmap': 'gray'}
        opts.defaults(
            opts.GridSpace(
                shared_xaxis=False,
                shared_yaxis=False,
                fontsize={
                    'title': 16,
                    'labels': 16,
                    'xticks': 12,
                    'yticks': 12
                },
            ),
            # opts.Image(cmap='gray', tools=['hover'], xaxis=None,
            #            yaxis=None, shared_axes=False),
            # opts.Overlay(tools=['hover']),
            # opts.NdOverlay(tools=['hover']),
            opts.Image(cmap=cmap, xaxis=None, yaxis=None, shared_axes=False),
        )

        self.is2d = False
        if 'z' not in self.ds.dims:
            self.is2d = True

        self.set_size(image_size)

        if self.is2d:
            plane == '2d'
            a1, a2 = 'x', 'y'
            pane_width = self.pane_width
            pane_height = self.pane_height
        else:
            if plane == 'axial':
                a1, a2, a3 = 'x', 'y', 'z'
                # invert = True
                pane_width = self.axial_width
                pane_height = self.axial_height
            elif plane == 'coronal':
                a1, a2, a3 = 'x', 'z', 'y'
                pane_width = self.coronal_width
                pane_height = self.coronal_height
                # invert = False
            elif plane == 'sagittal':
                a1, a2, a3 = 'y', 'z', 'x'
                # invert = False
                pane_width = self.sagittal_width
                pane_height = self.sagittal_height

        contrast_start_min = np.asscalar(
            self.ds.isel(subject_id=0, ).image.quantile(0.01).values) - 1e-6
        contrast_start_max = np.asscalar(
            self.ds.isel(subject_id=0, ).image.quantile(0.99).values) + 1e-6
        contrast_min = np.asscalar(
            self.ds.isel(subject_id=0).image.min().values)
        contrast_max = np.asscalar(
            self.ds.isel(subject_id=0).image.max().values)
        ctotal = contrast_max - contrast_min
        contrast_min -= ctotal * 0.1
        contrast_max += ctotal * 0.1

        cslider = pn.widgets.RangeSlider(start=contrast_min,
                                         end=contrast_max,
                                         value=(contrast_start_min,
                                                contrast_start_max),
                                         name='contrast')
        if 'overlay' in self.ds.data_vars:
            hv_ds_image = hv.Dataset(self.ds[['image', 'overlay']])
            # hv_ds_image = hv.Dataset(self.ds['image'])
            if self.verbose:
                print(hv_ds_image)
            hv_ds_overlay = hv.Dataset(self.ds['overlay'])
            if self.verbose:
                print(hv_ds_overlay)
            # tooltips = [
            #     ('(x,y)', '($x, $y)'),
            #     ('image', '@image'),
            #     ('overlay', '@overlay')
            # ]
            # hover = HoverTool(tooltips=tooltips)
            if self.verbose:
                print('overlay_max_calc')
            if self.is2d:
                first_subj_max = self.ds.isel(subject_id=0).overlay.max(
                    dim=['x', 'y', 'label']).compute()
                first_subj_min = self.ds.isel(subject_id=0).overlay.min(
                    dim=['x', 'y', 'label']).compute()
            else:
                first_subj_max = self.ds.isel(subject_id=0).overlay.max(
                    dim=['x', 'y', 'z', 'label']).compute()
                first_subj_min = self.ds.isel(subject_id=0).overlay.min(
                    dim=['x', 'y', 'z', 'label']).compute()
            if self.verbose:
                print('overlay_max_calc ready')
                print(first_subj_max)
            overlay_max = first_subj_max.max()
            alpha_slider = pn.widgets.FloatSlider(start=0,
                                                  end=1,
                                                  value=0.7,
                                                  name='overlay transparency')
            cmap_select = pn.widgets.Select(name='Overlay Colormap',
                                            options=['Discrete', 'Continuous'])

            if self.verbose:
                print('max thresh calc')
                print(first_subj_max.max())
            max_thresholds = first_subj_max.values
            if max_thresholds.size != 1:
                max_thresholds = sorted(set(max_thresholds))
            else:
                max_thresholds = [np.asscalar(max_thresholds)]
            # max_thresholds = sorted(list(set([first_subj.overlay.sel(overlay_label=i).values.max()
            #                         for i in first_subj.overlay_label])))
            if self.verbose:
                print('min thresh calc')
            min_thresholds = first_subj_min.values + 1e-6
            if min_thresholds.size != 1:
                min_thresholds = sorted(set(min_thresholds))
            else:
                min_thresholds = [np.asscalar(min_thresholds)]
            # min_thresholds = sorted(list(set(first_subj_min.min())))
            # min_thresholds = sorted(list(set([first_subj.sel(overlay_label=i).min()+1e-6 for i in
            #                        first_subj.overlay_label])))
            # ocslider = pn.widgets.DiscreteSlider(name='overlay max threshold',
            #                                      options=max_thresholds,
            #                                     value=max_thresholds[-1])
            if len(min_thresholds) == 1 and len(max_thresholds) == 1:
                thresh_toggle = 0
                oclim = (min_thresholds[0], max_thresholds[0])

            elif len(min_thresholds) > 1 and len(max_thresholds) == 1:
                thresh_toggle = 1
                ocslider_min = pn.widgets.DiscreteSlider(
                    name='overlay min threshold',
                    options=min_thresholds,
                    value=min_thresholds[-1])

                @pn.depends(ocslider_min)
                def oclim(value):
                    return (value, max_thresholds[0])

            elif len(min_thresholds) == 1 and len(max_thresholds) > 1:
                thresh_toggle = 2
                ocslider_max = pn.widgets.DiscreteSlider(
                    name='overlay max threshold',
                    options=max_thresholds,
                    value=max_thresholds[-1])

                @pn.depends(ocslider_max)
                def oclim(value):
                    return (min_thresholds[0], value)

            else:
                thresh_toggle = 3
                ocslider_min = pn.widgets.DiscreteSlider(
                    name='overlay min threshold',
                    options=min_thresholds,
                    value=min_thresholds[-1])
                ocslider_max = pn.widgets.DiscreteSlider(
                    name='overlay max threshold',
                    options=max_thresholds,
                    value=max_thresholds[-1])

                @pn.depends(ocslider_min, ocslider_max)
                def oclim(value_min, value_max):
                    return (value_min, value_max)

            if self.verbose:
                print(thresh_toggle)

            @pn.depends(cmap_select)
            def cmap_dict(value):
                d = {'Discrete': 'glasbey_hv', 'Continuous': 'viridis'}
                return d[value]

            # subj_viewer = SubjectViewer(ds=self.ds,
            #                             subject_id_sel=list(self.ds.subject_id.values))

            if self.is2d:
                gridspace = hv_ds_image.to(
                    hv.Image, [a1, a2],
                    vdims=['image', 'overlay'],
                    dynamic=dynamic).opts(
                        frame_width=pane_width,
                        frame_height=pane_height,
                        tools=['hover'],
                    ).apply.opts(clim=cslider.param.value)
                if self.verbose:
                    print(gridspace)
                gridspace *= hv_ds_overlay.to(
                    hv.Image, [a1, a2], vdims='overlay', dynamic=dynamic).opts(
                        cmap='glasbey_hv',
                        clipping_colors={
                            'min': 'transparent',
                            'NaN': 'transparent'
                        },
                    ).redim.range(overlay=(1e-6, overlay_max)).apply.opts(
                        alpha=alpha_slider.param.value,
                        cmap=cmap_dict,
                        clim=oclim)
                # print(gridspace)
                # print(gridspace)
                # gridspace = hv.DynamicMap(subj_viewer.load_subject).grid('label')
                gridspace = gridspace.layout('label')

            elif three_planes:
                # squish_height = int(max(image_size*(len(self.ds.z)/len(self.ds.x)), image_size/2))
                # gridspace = hv.GridSpace(kdims=['plane', 'label'], label=f'{self.subject_id}')
                gridspace = hv.GridSpace(kdims=['plane', 'label'])
                for mod in self.ds.label.values:
                    gridspace['axial', mod] = hv_ds_image.select(label=mod).to(
                        hv.Image, ['x', 'y'],
                        groupby=['subject_id', 'z'],
                        vdims='image',
                        dynamic=dynamic).opts(
                            frame_width=self.axial_width,
                            frame_height=self.axial_height).apply.opts(
                                clim=cslider.param.value)
                    gridspace['coronal', mod] = hv_ds_image.select(
                        label=mod).to(
                            hv.Image, ['x', 'z'],
                            groupby=['subject_id', 'y'],
                            vdims='image',
                            dynamic=dynamic).opts(
                                frame_width=self.coronal_width,
                                frame_height=self.coronal_height).apply.opts(
                                    clim=cslider.param.value)
                    gridspace['sagittal', mod] = hv_ds_image.select(
                        label=mod).to(
                            hv.Image, ['y', 'z'],
                            groupby=['subject_id', 'x'],
                            vdims='image',
                            dynamic=dynamic).opts(
                                frame_width=self.sagittal_width,
                                frame_height=self.sagittal_height).apply.opts(
                                    clim=cslider.param.value)

                    gridspace['axial',
                              mod] *= hv_ds_overlay.select(label=mod).to(
                                  hv.Image, ['x', 'y'],
                                  groupby=['subject_id', 'z', 'overlay_label'],
                                  vdims='overlay',
                                  dynamic=dynamic).opts(
                                      cmap='glasbey_hv',
                                      clipping_colors={
                                          'min': 'transparent',
                                          'NaN': 'transparent'
                                      },
                                  ).redim.range(
                                      overlay=(0.1, overlay_max)).apply.opts(
                                          alpha=alpha_slider.param.value,
                                          cmap=cmap_dict,
                                          clim=oclim)

                    gridspace['coronal',
                              mod] *= hv_ds_overlay.select(label=mod).to(
                                  hv.Image, ['x', 'z'],
                                  groupby=['subject_id', 'y', 'overlay_label'],
                                  vdims='overlay',
                                  dynamic=dynamic).opts(
                                      cmap='glasbey_hv',
                                      clipping_colors={
                                          'min': 'transparent',
                                          'NaN': 'transparent'
                                      },
                                  ).redim.range(
                                      overlay=(0.1, overlay_max)).apply.opts(
                                          alpha=alpha_slider.param.value,
                                          cmap=cmap_dict,
                                          clim=oclim)

                    gridspace['sagittal',
                              mod] *= hv_ds_overlay.select(label=mod).to(
                                  hv.Image, ['y', 'z'],
                                  groupby=['subject_id', 'x', 'overlay_label'],
                                  vdims='overlay',
                                  dynamic=dynamic).opts(
                                      cmap='glasbey_hv',
                                      clipping_colors={
                                          'min': 'transparent',
                                          'NaN': 'transparent'
                                      },
                                  ).redim.range(
                                      overlay=(0.1, overlay_max)).apply.opts(
                                          alpha=alpha_slider.param.value,
                                          cmap=cmap_dict,
                                          clim=oclim)

            else:
                # squish_height = int(max(image_size*(len(self.ds.z)/len(self.ds.x)), image_size/2))
                # gridspace = hv.GridSpace(kdims=['label'], label=f'{self.subject_id}')
                if self.verbose:
                    print('init gridspace')
                # gridspace = hv.GridSpace(kdims=['label'])
                # for mod in self.ds.label:
                #     gridspace[mod] = hv_ds_image.select(label=mod).to(
                #         hv.Image, [a1, a2], groupby=[a3], vdims='image',
                #         dynamic=dynamic).opts(frame_width=image_size, frame_height=image_size,
                #                            ).apply.opts(clim=cslider.param.value)
                #     gridspace[mod] *= hv_ds_overlay.select(label=mod).to(
                #         hv.Image, [a1, a2], groupby=[a3, 'overlay_label'], vdims='overlay',
                #         dynamic=dynamic).opts(
                #             cmap='glasbey_hv', clipping_colors={'min': 'transparent'},
                #         ).redim.range(overlay=(1e-6, overlay_max)).apply.opts(
                #             alpha=alpha_slider.param.value, cmap=cmap_dict, clim=oclim)
                #     gridspace[mod] = gridspace[mod].opts(tools=['hover'])
                #     print(gridspace[mod])

                gridspace = hv_ds_image.to(
                    hv.Image, [a1, a2],
                    vdims=['image', 'overlay'],
                    dynamic=dynamic).opts(
                        frame_width=pane_width,
                        frame_height=pane_height,
                        tools=['hover'],
                    ).apply.opts(clim=cslider.param.value)
                if self.verbose:
                    print(gridspace)
                gridspace *= hv_ds_overlay.to(
                    hv.Image, [a1, a2], vdims='overlay', dynamic=dynamic).opts(
                        cmap='glasbey_hv',
                        clipping_colors={
                            'min': 'transparent',
                            'NaN': 'transparent'
                        },
                    ).redim.range(overlay=(1e-6, overlay_max)).apply.opts(
                        alpha=alpha_slider.param.value,
                        cmap=cmap_dict,
                        clim=oclim)
                # print(gridspace)
                # print(gridspace)
                # gridspace = hv.DynamicMap(subj_viewer.load_subject).grid('label')
                gridspace = gridspace.layout('label')

        else:
            tooltips = [
                ('(x,y)', '($x, $y)'),
                ('image', '@image'),
            ]
            hover = HoverTool(tooltips=tooltips)
            hv_ds = hv.Dataset(self.ds['image'])
            if self.is2d:
                gridspace = hv.GridSpace(kdims=['label'])
                for mod in self.ds.label.values:
                    gridspace[mod] = hv_ds.select(label=mod).to(
                        hv.Image, [a1, a2],
                        groupby=['subject_id'],
                        vdims='image',
                        dynamic=dynamic).opts(
                            frame_width=pane_width,
                            frame_height=pane_height,
                            shared_axes=False,
                            tools=[hover],
                            axiswise=True,
                            # ).apply.opts(clim=cslider.param.value)
                        )
            elif three_planes:
                # squish_height = int(max(image_size*(len(self.ds.z)/len(self.ds.x)), image_size/2))
                # gridspace = hv.GridSpace(kdims=['plane', 'label'], label=f'{self.subject_id}')
                gridspace = hv.GridSpace(kdims=['plane', 'label'])
                for mod in self.ds.label.values:
                    gridspace['axial', mod] = hv_ds.select(label=mod).to(
                        hv.Image, ['x', 'y'],
                        groupby=['subject_id', 'z'],
                        vdims='image',
                        dynamic=dynamic).opts(frame_width=self.axial_width,
                                              frame_height=self.axial_height,
                                              invert_yaxis=False).apply.opts(
                                                  clim=cslider.param.value)
                    gridspace['coronal', mod] = hv_ds.select(label=mod).to(
                        hv.Image, ['x', 'z'],
                        groupby=['subject_id', 'y'],
                        vdims='image',
                        dynamic=dynamic).opts(
                            frame_width=self.coronal_width,
                            frame_height=self.coronal_height).apply.opts(
                                clim=cslider.param.value)
                    gridspace['sagittal', mod] = hv_ds.select(label=mod).to(
                        hv.Image, ['y', 'z'],
                        groupby=['subject_id', 'x'],
                        vdims='image',
                        dynamic=dynamic).opts(
                            frame_width=self.sagittal_width,
                            frame_height=self.sagittal_height).apply.opts(
                                clim=cslider.param.value)

            else:
                # squish_height = int(max(image_size*(len(self.ds.z)/len(self.ds.x)), image_size/2))
                # gridspace = hv.GridSpace(kdims=['label'], label=f'{self.subject_id}')
                gridspace = hv.GridSpace(kdims=['label'])
                for mod in self.ds.label.values:
                    gridspace[mod] = hv_ds.select(label=mod).to(
                        hv.Image, [a1, a2],
                        groupby=['subject_id', a3],
                        vdims='image',
                        dynamic=dynamic).opts(
                            frame_width=pane_width,
                            frame_height=pane_height,
                            shared_axes=False,
                            tools=[hover],
                        ).apply.opts(clim=cslider.param.value)

        pn_layout = pn.pane.HoloViews(gridspace)
        wb = pn_layout.widget_box
        wb.append(cslider)
        if 'overlay' in self.ds.data_vars:
            wb.append(alpha_slider)
            wb.append(cmap_select)
            if thresh_toggle in [2, 3]:
                wb.append(ocslider_max)
            if thresh_toggle in [1, 3]:
                wb.append(ocslider_min)
        return pn.Row(wb, pn_layout)
예제 #12
0
        def line_stuff(time_slice, seismic_buttons, iline_input, xline_input,
                       checkbox):
            """
            NAME
            ----
                line_stuff.
                
            DESCRIPTION
            -----------
                Plots a chosen seismic line. Inherited from WiggleModule class.

                The detected anomalies in the crossplot shall be compared with the amplitude display of 
                a gather.
                
            ARGUMENTS
            ---------
                seismic_buttons : str
                     Seismic direction to base the amplitude plotting.

                wiggle_buttons : str
                     Hardcoded to "Colored wiggle".

                seismic_iline : int
                     Inline number selection.

                traces_iline : tuple
                     Range of crosslines to be intersected with seismic_iline.

                seismic_xline : int
                     Crossline number selection.

                traces_xline : tuple
                    Range of inlines to be intersected with seismic_iline.

                time_slice : list
                     Time slice of interest. 

                Survey.merge_path : str
                    Path where the merge of the PAS is located.
            
            RETURN
            ------
                GridSpace : Holviews element [GridSpace]
                    A grid compounded by angle gathers.
            
            """

            if checkbox:
                with segyio.open(Survey.merge_path) as segy:
                    self.interpolation = False
                    gather_dict = {}
                    # Storing scaling fac
                    self.scaling_factor = WiggleModule.scaling_factor(
                        self, segyio.tools.collect(segy.trace[:]))

                    # Storing time array
                    WiggleModule.time(
                        self,
                        int(
                            segy.attributes(
                                segyio.TraceField.TRACE_SAMPLE_INTERVAL)[0] /
                            1000))

                    # Line visualization
                    if seismic_buttons == "Inline":
                        trace_counter = self.crosslines[0]
                        for gather in segy.gather[int(iline_input), :, :]:
                            gather_dict[
                                f"{int(iline_input)}/{trace_counter}"] = WiggleModule.wiggle_plot(
                                    self, gather, time_slice, "Colored wiggle")
                            trace_counter += 1

                    else:
                        trace_counter = self.inlines[0]
                        for gather in segy.gather[:, int(xline_input), :]:
                            gather_dict[
                                f"C{trace_counter}/{int(xline_input)}"] = WiggleModule.wiggle_plot(
                                    self, gather, time_slice, "Colored wiggle")
                            trace_counter += 1

                grid = hv.GridSpace(gather_dict, kdims=['Trace'])
                grid.opts(fontsize={
                    "title": 16,
                    "labels": 14,
                    "xticks": 8,
                    "yticks": 8
                },
                          plot_size=(60, 240))

                return grid