Пример #1
0
def tajima_widget2():
    style = {'description_width': '350px'}
    layout = Layout(width='55%')

    a = widgets.Text(value='linear-a03-w10.txt',
                     description='Template Input File:',
                     style=style,
                     layout=layout)
    b = widgets.Text(value='linear-a03-w7_2.txt',
                     description='New Output File:',
                     style=style,
                     layout=layout)
    c = widgets.BoundedFloatText(value=1e-4,
                                 min=0.0,
                                 max=2.0,
                                 description='v_e/c:',
                                 style=style,
                                 layout=layout)
    d = widgets.FloatText(value=0.3,
                          description='a0:',
                          style=style,
                          layout=layout)
    e = widgets.BoundedFloatText(value=10,
                                 min=0,
                                 max=15,
                                 description='omega0:',
                                 style=style,
                                 layout=layout)
    f = widgets.BoundedFloatText(value=3.14159,
                                 min=0,
                                 max=100,
                                 description='Lt:',
                                 style=style,
                                 layout=layout)
    g = widgets.BoundedFloatText(value=0,
                                 min=0,
                                 max=100,
                                 description='t_rise:',
                                 style=style,
                                 layout=layout)
    h = widgets.BoundedFloatText(value=0,
                                 min=0,
                                 max=100,
                                 description='t_fall:',
                                 style=style,
                                 layout=layout)
    nx_pw = widgets.IntText(value=1600,
                            description='nx_p:',
                            style=style,
                            layout=layout)
    xmaxw = widgets.FloatText(value=24.0,
                              description='xmax:',
                              style=style,
                              layout=layout)
    ndumpw = widgets.IntText(value=2,
                             description='ndump:',
                             style=style,
                             layout=layout)
    ppc = widgets.IntText(value=10,
                          description='Particles per cell:',
                          style=style,
                          layout=layout)
    print('d=' + repr(d))
    im = interact_calc(newifile,
                       iname=a,
                       oname=b,
                       uth=c,
                       a0=d,
                       omega0=e,
                       t_flat=f,
                       t_rise=g,
                       t_fall=h,
                       nx_p=nx_pw,
                       xmax=xmaxw,
                       ndump=ndumpw,
                       ppc=ppc)
    im.widget.manual_button.layout.width = '250px'
Пример #2
0
def Create_form():
    '''Display the widget for creation and printing of the experiment form.'''    
    
    short_layout = widgets.Layout(width='200px', height='40px')
    medium_layout = widgets.Layout(width='300px', height='40px')
    long_layout = widgets.Layout(width='800px', height='40px')
    style = {'description_width': 'initial'}

    title = widgets.Text(
            placeholder='Title',
            description='Experiment title:',
            layout=long_layout,
            style=style)

    number = widgets.Text(
            placeholder='Number',
            description='Experiment number:',
            layout=medium_layout,
            style=style)

    ttype = widgets.Text(
            placeholder='Proposal, Commissioning, ...',
            description='Type:',
            layout=medium_layout,
            style=style)

    safety = widgets.Dropdown(
            options=['Green', 'Yellow', 'Red'],
            value='Yellow',
            description='Safety:',
            layout=widgets.Layout(width='150px'),
            style=style)

    date  = widgets.Text(
            placeholder='DD/MM/YYYY - DD/MM/YYYY',
            description='Date:',
            layout=medium_layout,
            style=style)

    proposer = widgets.Text(
               placeholder='Name',
               description='Main proposer:',
               layout=short_layout,
               style=style)

    contact = widgets.Text(
               placeholder='Name',
               description='Local contact:',
               layout=medium_layout,
               style=style)

    users = widgets.Text(
            placeholder='Names',
            description='Users (on site):',
            layout=long_layout,
            style=style)

    recording = widgets.Text(
               placeholder='Full path to the recording directory',
               description='Recording directory:',
               layout=long_layout,
               style=style)


    current = widgets.Text(
               placeholder='450 mA, 500 mA, ...',
               description='Current:',
               layout=medium_layout,
               style=style)

    mode     = widgets.Text(
               placeholder='Hybrid, Top-up, ...',
               description='Mode:',
               layout=medium_layout,
               style=style)

    dcm   = widgets.Dropdown(
            options=['Si111', 'InSb', 'Not Used'],
            value='Si111',
            description='DCM:',
            layout=widgets.Layout(width='150px'),
            style=style)

    mgm   = widgets.Dropdown(
            options=['In use', 'Not used'],
            value='Not used',
            description='MGM:',
            layout=widgets.Layout(width='150px'),
            style=style)

    energy  = widgets.Text(
               placeholder='Value(s)',
               description='Energy (keV):',
               layout=medium_layout,
               style=style)

    energy_type = widgets.Dropdown(
                  options=['Fixed', 'Variable'],
                  value='Fixed',
                  description='Fixed/Variable energy:',
                  layout=widgets.Layout(width='300px'),
                  style=style)

    wavelength = widgets.Text(
                 placeholder='Value(s)',
                 description='Wavelength (nm):',
                 layout=medium_layout,
                 style=style)

    harmonic  =  widgets.Text(
                 placeholder='Value(s)',
                 description='Harmonic:',
                 layout=short_layout,
                 style=style)

    polarisation = widgets.Text(
                 placeholder='Value(s)',
                 value='LH',
                 description='Polarisation:',
                 layout=short_layout,
                 style=style)

    phase = widgets.Text(
                 placeholder='Value(s)',
                 value='0',
                 description='Phase (deg):',
                 layout=short_layout,
                 style=style)

    m1  = widgets.Dropdown(
          options=['M1-A Pt Track', 'M1-A B4C Track', 'M1-B (B4C)', 'No M1'],
          value='M1-A Pt Track',
          description='M1:',
          layout=widgets.Layout(width='200px'),
          style=style)

    m2  = widgets.Dropdown(
          options=['M2 Pt Track', 'M2 B4C Track', 'No M2'],
          value='M2 Pt Track',
          description='M2:',
          layout=widgets.Layout(width='200px'),
          style=style)

    m3  = widgets.Dropdown(
          options=['M3 Pt Track', 'M3 B4C Track', 'No M3'],
          value='No M3',
          description='M3:',
          layout=widgets.Layout(width='200px'),
          style=style)

    m4  = widgets.Dropdown(
          options=['M4 Pt Track', 'M4 Si Track', 'No M4'],
          value='M4 Pt Track',
          description='M4:',
          layout=widgets.Layout(width='200px'),
          style=style)

    horizontal_foc = widgets.Checkbox(
                     value=True,
                     description='Horizontal focalisation:',
                     layout=long_layout,
                     style=style)

    vertical_foc = widgets.Checkbox(
                   value=True,
                   description='Vertical focalisation:',
                   layout=long_layout,
                   style=style)


    horizontal_size = widgets.Text(
                      placeholder='Value(s)',
                      description='Horizontal beamsize (mm):',
                      layout=medium_layout,
                      style=style)

    vertical_size   = widgets.Text(
                      placeholder='Value(s)',
                      description='Vertical beamsize (mm):',
                      layout=medium_layout,
                      style=style)

    mon1  = widgets.Text(
            placeholder='Empty or type of mon',
            description='mon1:',
            layout=short_layout,
            style=style)

    mon2  = widgets.Text(
            placeholder='Empty or type of mon',
            description='mon2:',
            layout=short_layout,
            style=style)

    mon3  = widgets.Text(
            placeholder='Empty or type of mon',
            description='mon3:',
            layout=short_layout,
            style=style)

    mon4  = widgets.Text(
            placeholder='Empty or type of mon',
            description='mon4:',
            layout=short_layout,
            style=style)

    detectors  = widgets.Textarea(
                 placeholder='Type of detectors',
                 description='Detectors:',
                 layout=long_layout,
                 style=style)

    remarks     = widgets.Textarea(
                 placeholder='Remarks',
                 description='Remarks:',
                 layout=long_layout,
                 style=style)

    display(title)
    display(widgets.HBox([date, number]))
    display(widgets.HBox([ttype, safety]))
    print('-'*100)
    display(widgets.HBox([proposer, contact]))
    display(users)
    print('-'*100)
    display(recording)
    print('\033[1m'+'Machine:')
    display(widgets.HBox([current, mode]))
    print('\033[1m'+'Optics:')
    display(widgets.HBox([dcm, mgm]))
    display(widgets.HBox([m1, m2, m3, m4]))
    print('\033[1m'+'Beam:')
    display(widgets.HBox([energy_type, energy, wavelength]))
    display(widgets.HBox([harmonic, polarisation, phase]))
    display(widgets.HBox([horizontal_foc, vertical_foc]))
    display(widgets.HBox([horizontal_size, vertical_size]))
    print('\033[1m'+'Monitors and XBPM:')
    display(widgets.HBox([mon1, mon2, mon3, mon4]))
    display(detectors)
    print('\033[1m'+'Remarks:')
    display(remarks)
    
    def on_button_clicked(b):
        
        txt = []
        txt.append('$\LARGE \\textbf{SIRIUS Beamline}:\\textbf{Experiment %s}$'%number.value)

        ########################################
        # Prepare the title in several parts
        # Avoid having a line larger than the page

        # Max number of characters allowed by line
        max_length = 70

       
        title_split = title.value.split(' ')
        title_blocks = [] 

        j=0
        for k in range(0,len(title_split)):
            title_part = ''
            for i in range(j,len(title_split)): 
                if len(title_part)<max_length:
                    title_part += title_split[i]+' '
                    j=j+1
                else:
                    break
            title_blocks.append(title_part)        

        for title_block in title_blocks:
            if title_block != '':        
                txt.append('$\Large \\color{red}{\\bf %s}$'%('\ '.join(title_block.split(' '))))

        
        # Former (simpler version), but allows line longer than the page width
        #ptitle = ('\ '.join(title.value.split(' ')))
        #txt.append('$\Large \\color{red}{\\bf %s}$'%ptitle)
        ########################################
        
        txt.append('* %s %s'%(ttype.description,ttype.value)+'\n'
                    +'* %s %s'%(safety.description,safety.value)+'\n'
                    +'* %s %s'%(date.description,date.value))

        txt.append('* %s %s'%(proposer.description,proposer.value)+'\n'
                    +'* %s %s'%(contact.description,contact.value)+'\n'
                    +'* %s %s'%(users.description,users.value)+'\n'
                    +'* %s %s'%(recording.description,recording.value))

        txt.append('* Machine:'+'\n'
                    +'\t * %s %s'%(current.description,current.value)+'\n'
                    +'\t * %s %s'%(mode.description,mode.value))

        txt.append('* Optics:'+'\n'
                    +'\t * %s %s'%(dcm.description,dcm.value)+'\n'
                    +'\t * %s %s'%(mgm.description,mgm.value)+'\n'
                    +'\t * %s %s'%(m1.description,m1.value)+'\n'
                    +'\t * %s %s'%(m2.description,m2.value)+'\n'
                    +'\t * %s %s'%(m3.description,m3.value)+'\n'
                    +'\t * %s %s'%(m4.description,m4.value))

        txt.append('* Beam:'+'\n'
                    +'\t * %s %s'%(energy_type.description,energy_type.value)+'\n'
                    +'\t * %s %s'%(energy.description,energy.value)+'\n'
                    +'\t * %s %s'%(wavelength.description,wavelength.value)+'\n'
                    +'\t * %s %s'%(harmonic.description,harmonic.value)+'\n'
                    +'\t * %s %s'%(polarisation.description,polarisation.value)+'\n'
                    +'\t * %s %s'%(phase.description,phase.value)+'\n'
                    +'\t * %s %s'%(horizontal_foc.description,horizontal_foc.value)+'\n'
                    +'\t * %s %s'%(vertical_foc.description,vertical_foc.value)+'\n'
                    +'\t * %s %s'%(horizontal_size.description,horizontal_size.value)+'\n'
                    +'\t * %s %s'%(vertical_size.description,vertical_size.value))

        txt.append('* Monitors and XBPM:'+'\n'
                    +'\t * %s %s'%(mon1.description,mon1.value)+'\n'
                    +'\t * %s %s'%(mon2.description,mon2.value)+'\n'
                    +'\t * %s %s'%(mon3.description,mon3.value)+'\n'
                    +'\t * %s %s'%(mon4.description,mon4.value)+'\n'
                    +'\t * %s %s'%(detectors.description,detectors.value))

        txt.append('* %s %s'%(remarks.description,remarks.value))

        txt.reverse()
        
        for elem in txt:
            Utils.Create_cell(code=elem, position ='below', celltype='markdown', is_print=True)
        
        Utils.Create_cell(code='# Experimental setup', position ='below', celltype='markdown', is_print=True)
        
        # Remove the widget when done
        Utils.Delete_current_cell()
        
    button = widgets.Button(description="Print form")
    out = widgets.Output()
    display(button,out)
    button.on_click(on_button_clicked)
Пример #3
0
def Insert_image(expt):
    '''
    Insert an image in the notebook.

    Parameters
    ----------
    expt : object
        object from the class Expt
    '''  

    # Check if there is already a path for images directories
    # If not, use the recording directory
    try:
        path_to_img_default = expt.path_to_img
    except:
        path_to_img_default = expt.recording_dir

    # Widget to write path
    w_path_to_img = widgets.Text(
            value=path_to_img_default,
            description='Images directory:',
            layout=widgets.Layout(width='800px', height='40px'),
            style={'description_width': 'initial'})

    def on_button_validate_path_clicked(b):
        """
        Validate the path of the images folder. Open selection for the image.
        """

        if not os.path.exists(w_path_to_img.value):
            print(PN._RED+"Wrong folder name."+PN._RESET)
            print("")
            return

        # Pass the current value of the directory to the default one
        expt.path_to_img = w_path_to_img.value

        # Define the list of img files in the directory
        list_img_files = [file for file in sorted(os.listdir(expt.path_to_img))][::-1]

        if len(list_img_files) < 1:
            print(PN._RED+"There is no image in this folder."+PN._RESET)
            print("")
            return                

        # Widget to select image
        w_select_img = widgets.Dropdown(
             options=list_img_files,
             value=list_img_files[-1],
             layout=widgets.Layout(width='300px'),
             style={'description_width': 'Image:'})

        def on_button_insert_image_clicked(b):
            """
            Insert an image in a markdown cell.
            """ 

            # Get and insert the image
            path_to_img = w_path_to_img.value+w_select_img.value

            Utils.Create_cell(code='![]('+ path_to_img+')', position ='above', celltype='markdown', is_print=True)
            
            Utils.Delete_current_cell()
        
            Utils.Create_cell(code='FE.Action.Choose(expt)',
                        position ='at_bottom', celltype='code', is_print=False)  

        button_insert_image = widgets.Button(description="Insert image")
        button_insert_image.on_click(on_button_insert_image_clicked)

        display(widgets.HBox([w_select_img, button_insert_image]))

    button_validate_path = widgets.Button(description="Validate path")
    button_validate_path.on_click(on_button_validate_path_clicked)
    display(widgets.HBox([w_path_to_img, button_validate_path]))
Пример #4
0
class Parameters(traitlets.HasTraits):
    """The physical and computational parameters are built on top of `traitlets`_.

    It is a framework that lets Python classes have attributes with type checking,
    dynamically calculated default values, and ‘on change’ callbacks.
    In addition, there are `ipywidgets`_ for a friendly user interface.

    .. warning:: There is a bug reported affecting the widgets `#2`_,
        they are not working properly at the moment.

    .. _traitlets:
        https://traitlets.readthedocs.io/en/stable/index.html
    .. _ipywidgets:
        https://ipywidgets.readthedocs.io/en/latest/
    .. _#2:
        https://github.com/fschuch/xcompact3d_toolbox/issues/2

    Attributes
    ----------
    nclx1 : int
        Boundary condition for velocity field where :math:`x=0`, the options are:

        * 0 - Periodic;
        * 1 - Free-slip;
        * 2 - Inflow.

    nclxn : int
        Boundary condition for velocity field where :math:`x=L_x`, the options are:

        * 0 - Periodic;
        * 1 - Free-slip;
        * 2 - Convective outflow.

    ncly1 : int
        Boundary condition for velocity field where :math:`y=0`, the options are:

        * 0 - Periodic;
        * 1 - Free-slip;
        * 2 - No-slip.

    nclyn : int
        Boundary condition for velocity field where :math:`y=L_y`, the options are:

        * 0 - Periodic;
        * 1 - Free-slip;
        * 2 - No-slip.

    nclz1 : int
        Boundary condition for velocity field where :math:`z=0`, the options are:

        * 0 - Periodic;
        * 1 - Free-slip;
        * 2 - No-slip.

    nclzn : int
        Boundary condition for velocity field where :math:`z=L_z`, the options are:

        * 0 - Periodic;
        * 1 - Free-slip;
        * 2 - No-slip.

    nclxS1 : int
        Boundary condition for scalar field(s) where :math:`x=0`, the options are:

        * 0 - Periodic;
        * 1 - No-flux;
        * 2 - Inflow.

    nclxSn : int
        Boundary condition for scalar field(s) where :math:`x=L_x`, the options are:

        * 0 - Periodic;
        * 1 - No-flux;
        * 2 - Convective outflow.

    nclyS1 : int
        Boundary condition for scalar field(s) where :math:`y=0`, the options are:

        * 0 - Periodic;
        * 1 - No-flux;
        * 2 - Dirichlet.

    nclySn : int
        Boundary condition for scalar field(s) where :math:`y=L_y`, the options are:

        * 0 - Periodic;
        * 1 - No-flux;
        * 2 - Dirichlet.

    nclzS1 : int
        Boundary condition for scalar field(s) where :math:`z=0`, the options are:

        * 0 - Periodic;
        * 1 - No-flux;
        * 2 - Dirichlet.

    nclzSn : int
        Boundary condition for scalar field(s) where :math:`z=L_z`, the options are:

        * 0 - Periodic;
        * 1 - No-flux;
        * 2 - Dirichlet.

    ivisu : bool
        Enables store snapshots if :obj:`True`.

    ipost : bool
        Enables online postprocessing if :obj:`True`.

    ilesmod : bool
        Enables Large-Eddy methodologies if :obj:`True`.

    ifirst : int
        The number for the first iteration.

    ilast : int
        The number for the last iteration.

    icheckpoint : int
        Frequency for writing restart file.

    ioutput : int
        Frequency for visualization (3D snapshots).

    iprocessing : int
        Frequency for online postprocessing.

        Notes
        -----
            The exactly output may be different according to each flow configuration.
    """

    #
    # # BasicParam
    #

    p_row, p_col = [
        traitlets.Int(default_value=0,
                      min=0).tag(group="BasicParam",
                                 widget=widgets.Dropdown(description=name,
                                                         options=[0]))
        for name in ["p_row", "p_col"]
    ]
    """int: Defines the domain decomposition for (large-scale) parallel computation.

    Notes
    -----
        The product ``p_row * p_col`` must be equal to the number of
        computational cores where Xcompact3d will run.
        More information can be found at `2DECOMP&FFT`_.

        ``p_row = p_col = 0`` activates auto-tunning.

    .. _2DECOMP&FFT:
        http://www.2decomp.org
    """

    itype = traitlets.Int(default_value=10, min=0, max=10).tag(
        group="BasicParam",
        widget=widgets.Dropdown(
            description="itype",
            disabled=True,
            options=[
                ("User", 0),
                ("Lock-exchange", 1),
                ("Taylor-Green Vortex", 2),
                ("Channel", 3),
                ("Periodic Hill", 4),
                ("Cylinder", 5),
                ("Debug Schemes", 6),
                ("Mixing Layer", 7),
                ("Turbulent Jet", 8),
                ("Turbulent Boundary Layer", 9),
                ("Sandbox", 10),
            ],
        ),
    )
    """int: Sets the flow configuration, each one is specified in a different
    ``BC.<flow-configuration>.f90`` file (see `Xcompact3d/src`_), they are:

    * 0 - User configuration;
    * 1 - Turbidity Current in Lock-Release;
    * 2 - Taylor-Green Vortex;
    * 3 - Periodic Turbulent Channel;
    * 5 - Flow around a Cylinder;
    * 6 - Debug Schemes (for developers);
    * 7 - Mixing Layer;
    * 9 - Turbulent Boundary Layer;
    * 10 - `Sandbox`_.

    .. _Xcompact3d/src:
        https://github.com/fschuch/Xcompact3d/tree/master/src
    """

    iin = traitlets.Int(default_value=0, min=0, max=2).tag(
        group="BasicParam",
        widget=widgets.Dropdown(
            description="iin",
            options=[
                ("No random noise", 0),
                ("Random noise", 1),
                ("Random noise with fixed seed", 2),
            ],
        ),
    )
    """int: Defines perturbation at the initial condition:

    * 0 - No random noise (default);
    * 1 - Random noise with amplitude of :obj:`init_noise`;
    * 2 - Random noise with fixed seed
      (important for reproducibility, development and debugging)
      and amplitude of :obj:`init_noise`.

    Notes
    -----
        The exactly behavior may be different according to each flow configuration.
    """

    nx, ny, nz = [
        traitlets.Int(default_value=17, min=0).tag(
            group="BasicParam",
            widget=widgets.Dropdown(description=name, options=possible_mesh),
        ) for name in ["nx", "ny", "nz"]
    ]
    """int: Number of mesh points.

    Notes
    -----
        See :obj:`possible_mesh` and :obj:`possible_mesh_p`.
    """

    xlx, yly, zlz = [
        traitlets.Float(default_value=1.0, min=0).tag(
            group="BasicParam",
            widget=widgets.BoundedFloatText(description=name, min=0.0,
                                            max=1e6),
        ) for name in ["xlx", "yly", "zlz"]
    ]
    """float: Domain size.
    """

    # Docstrings included together with the class
    nclx1 = traitlets.Int(default_value=2, min=0, max=2).tag(
        group="BasicParam",
        widget=widgets.Dropdown(
            description="nclx1",
            options=[("Periodic", 0), ("Free-slip", 1), ("Inflow", 2)],
        ),
    )

    # Docstrings included together with the class
    nclxn = traitlets.Int(default_value=2, min=0, max=2).tag(
        group="BasicParam",
        widget=widgets.Dropdown(
            description="nclxn",
            options=[("Periodic", 0), ("Free-slip", 1), ("Outflow", 2)],
        ),
    )

    # Docstrings included together with the class
    ncly1, nclyn, nclz1, nclzn = [
        traitlets.Int(default_value=2, min=0, max=2).tag(
            group="BasicParam",
            widget=widgets.Dropdown(
                description=name,
                options=[("Periodic", 0), ("Free-slip", 1), ("No-slip", 2)],
            ),
        ) for name in "ncly1 nclyn nclz1 nclzn".split()
    ]

    # Docstrings included together with the class
    ivisu, ipost, ilesmod = [
        traitlets.Bool(default_value=True) for i in range(3)
    ]

    istret = traitlets.Int(default_value=0, min=0, max=3).tag(
        group="BasicParam",
        widget=widgets.Dropdown(
            description="istret",
            options=[
                ("No refinement", 0),
                ("Refinement at the center", 1),
                ("Both sides", 2),
                ("Just near the bottom", 3),
            ],
        ),
    )
    """int: Controls mesh refinement in **y**:

    * 0 - No refinement (default);
    * 1 - Refinement at the center;
    * 2 - Both sides;
    * 3 - Just near the bottom.

    Notes
    -----
        See :obj:`beta`.
    """

    beta = traitlets.Float(default_value=1.0, min=0).tag(
        group="BasicParam",
        widget=widgets.BoundedFloatText(description="beta", min=0.0, max=1e6),
    )
    """float: Refinement factor in **y**.

    Notes
    -----
        Only necessary if :obj:`istret` :math:`\\ne` 0.
    """

    dt = traitlets.Float(default_value=1e-3, min=0.0).tag(
        group="BasicParam",
        widget=widgets.BoundedFloatText(description="dt", min=0.0, max=1e6),
    )
    """float: Time step :math:`(\\Delta t)`.
    """

    # Docstrings included together with the class
    ifirst, ilast = [
        traitlets.Int(default_value=0,
                      min=0).tag(group="BasicParam",
                                 widget=widgets.IntText(description=name))
        for name in ["ifirst", "ilast"]
    ]

    re = traitlets.Float(default_value=1e3).tag(
        group="BasicParam", widget=widgets.FloatText(description="re"))
    """float: Reynolds number :math:`(Re)`.
    """

    init_noise = traitlets.Float(default_value=0.0).tag(
        group="BasicParam", widget=widgets.FloatText(description="init_noise"))
    """float: Random number amplitude at initial condition.

    Notes
    -----
        The exactly behavior may be different according to each flow configuration.

        Only necessary if :obj:`iin` :math:`\\ne` 0.
    """

    inflow_noise = traitlets.Float(default_value=0.0).tag(
        group="BasicParam",
        widget=widgets.FloatText(description="inflow_noise"))
    """float: Random number amplitude at inflow boundary (where :math:`x=0`).

    Notes
    -----
        Only necessary if :obj:`nclx1` is equal to 2.
    """

    ilesmod, ivisu, ipost = [
        traitlets.Int(default_value=1, min=0, max=1).tag(
            group="BasicParam",
            widget=widgets.Dropdown(description=name,
                                    options=[("Off", 0), ("On", 1)]),
        ) for name in ["ilesmod", "ivisu", "ipost"]
    ]

    iibm = traitlets.Int(default_value=0, min=0, max=2).tag(
        group="BasicParam",
        widget=widgets.Dropdown(
            description="iibm",
            options=[("Off", 0), ("Forced to zero", 1),
                     ("Interpolated to zero", 2)],
        ),
    )
    """int: Enables Immersed Boundary Method (IBM):

    * 0 - Off (default);
    * 1 - On with direct forcing method, i.e.,
      it sets velocity to zero inside the solid body;
    * 2 - On with alternating forcing method, i.e, it uses
      Lagrangian Interpolators to define the velocity inside the body
      and imposes no-slip condition at the solid/fluid interface.
    """

    numscalar = traitlets.Int(default_value=0, min=0, max=9).tag(
        group="BasicParam",
        widget=widgets.IntSlider(min=0,
                                 max=9,
                                 description="numscalar",
                                 continuous_update=False),
    )
    """int: Number of scalar fraction, which can have different properties.

    Notes
    -----
        More than 9 will bug Xcompact3d, because it handles the I/O for
        scalar fields with just one digit
    """

    gravx, gravy, gravz = [
        traitlets.Float(default_value=0.0).tag(
            group="BasicParam",
            widget=widgets.FloatText(description=name, disabled=True),
        ) for name in ["gravx", "gravy", "gravz"]
    ]
    """float: Component of the unitary vector pointing in the gravity's direction.
    """

    #
    # # NumOptions
    #

    ifirstder = traitlets.Int(default_value=4, min=1, max=4).tag(
        group="NumOptions",
        widget=widgets.Dropdown(
            description="ifirstder",
            disabled=True,
            options=[
                ("2nd central", 1),
                ("4th central", 1),
                ("4th compact", 1),
                ("6th compact", 4),
            ],
        ),
    )
    """int: Scheme for first order derivative:

    * 1 - 2nd central;
    * 2 - 4th central;
    * 3 - 4th compact;
    * 4 - 6th compact (default).
    """

    isecondder = traitlets.Int(default_value=4, min=1, max=5).tag(
        group="NumOptions",
        widget=widgets.Dropdown(
            description="isecondder",
            disabled=True,
            options=[
                # '2nd central', 1),
                ("6th compact", 4),
                ("hyperviscous 6th", 5),
            ],
        ),
    )
    """int: Scheme for second order derivative:

    * 1 - 2nd central;
    * 2 - 4th central;
    * 3 - 4th compact;
    * 4 - 6th compact (default);
    * 5 - Hyperviscous 6th.
    """

    ipinter = traitlets.Int(3)

    itimescheme = traitlets.Int(default_value=3, min=1, max=7).tag(
        group="NumOptions",
        widget=widgets.Dropdown(
            description="itimescheme",
            options=[
                ("Euler", 1),
                ("AB2", 2),
                ("AB3", 3),
                ("RK3", 5),
                ("Semi-implicit", 7),
            ],
        ),
    )
    """int: Time integration scheme:

    * 1 - Euler;
    * 2 - AB2;
    * 3 - AB3 (default);
    * 5 - RK3;
    * 7 - Semi-implicit.
    """

    nu0nu = traitlets.Float(default_value=4, min=0.0).tag(
        group="NumOptions",
        widget=widgets.BoundedFloatText(description="nu0nu",
                                        min=0.0,
                                        max=1e6,
                                        disabled=True),
    )
    """float: Ratio between hyperviscosity/viscosity at nu.
    """

    cnu = traitlets.Float(default_value=0.44, min=0.0).tag(
        group="NumOptions",
        widget=widgets.BoundedFloatText(description="cnu",
                                        min=0.0,
                                        max=1e6,
                                        disabled=True),
    )
    """float: Ratio between hypervisvosity at :math:`k_m=2/3\\pi` and :math:`k_c= \\pi`.
    """

    #
    # # InOutParam
    #

    irestart = traitlets.Int(default_value=0, min=0, max=1).tag(
        group="InOutParam",
        widget=widgets.Dropdown(description="irestart",
                                options=[("Off", 0), ("On", 1)]),
    )
    """int: Reads initial flow field if equals to 1.
    """

    nvisu = traitlets.Int(default_value=1, min=1).tag(
        group="InOutParam",
        widget=widgets.BoundedIntText(description="nvisu",
                                      min=1,
                                      max=1e9,
                                      disabled=True),
    )
    """int: Size for visual collection.
    """

    icheckpoint, ioutput, iprocessing = [
        traitlets.Int(default_value=1000, min=1).tag(
            group="InOutParam",
            widget=widgets.BoundedIntText(description=name, min=1, max=1e9),
        ) for name in ["icheckpoint", "ioutput", "iprocessing"]
    ]

    ifilenameformat = traitlets.Int(default_value=9, min=1)

    #
    # # ScalarParam
    #

    _iscalar = traitlets.Bool(False)

    # Include widgets for list demands some planning about code design
    sc = traitlets.List(trait=traitlets.Float()).tag(group="ScalarParam")
    """:obj:`list` of :obj:`float`: Schmidt number(s).
    """

    ri = traitlets.List(trait=traitlets.Float()).tag(group="ScalarParam")
    """:obj:`list` of :obj:`float`: Richardson number(s).
    """

    uset = traitlets.List(trait=traitlets.Float()).tag(group="ScalarParam")
    """:obj:`list` of :obj:`float`: Settling velocity(s).
    """

    cp = traitlets.List(trait=traitlets.Float()).tag(group="ScalarParam")
    """:obj:`list` of :obj:`float`: Initial concentration(s).
    """

    scalar_lbound = traitlets.List(trait=traitlets.Float(
        default_value=-1e6)).tag(group="ScalarParam")
    """:obj:`list` of :obj:`float`: Lower scalar bound(s), for clipping methodology.
    """

    scalar_ubound = traitlets.List(trait=traitlets.Float(
        default_value=1e6)).tag(group="ScalarParam")
    """:obj:`list` of :obj:`float`: Upper scalar bound(s), for clipping methodology.
    """

    iibmS = traitlets.Int(default_value=0, min=0, max=3).tag(
        group="ScalarParam",
        widget=widgets.Dropdown(
            description="iibmS",
            options=[
                ("Off", 0),
                ("Forced to zero", 1),
                ("Interpolated to zero", 2),
                ("Interpolated to no-flux", 3),
            ],
        ),
    )
    """int: Enables Immersed Boundary Method (IBM) for scalar field(s):

    * 0 - Off (default);
    * 1 - On with direct forcing method, i.e.,
      it sets scalar concentration to zero inside the solid body;
    * 2 - On with alternating forcing method, i.e, it uses
      Lagrangian Interpolators to define the scalar field inside the body
      and imposes zero value at the solid/fluid interface.
    * 3 - On with alternating forcing method, but now the Lagrangian
      Interpolators are set to impose no-flux for the scalar field at the
      solid/fluid interface.

      .. note:: It is only recommended if the normal vectors to the object's
            faces are aligned with one of the coordinate axes.
    """

    # Docstrings included together with the class
    nclxS1, nclxSn, nclyS1, nclySn, nclzS1, nclzSn = [
        traitlets.Int(default_value=2, min=0, max=2).tag(
            group="ScalarParam",
            widget=widgets.Dropdown(
                description=name,
                options=[("Periodic", 0), ("No-flux", 1), ("Dirichlet", 2)],
            ),
        ) for name in
        ["nclxS1", "nclxSn", "nclyS1", "nclySn", "nclzS1", "nclzSn"]
    ]

    #
    # # LESModel
    #

    jles = traitlets.Int(default_value=0, min=0, max=4).tag(
        group="LESModel",
        widget=widgets.Dropdown(
            description="ilesmod",
            options=[
                ("DNS", 0),
                ("Phys Smag", 1),
                ("Phys WALE", 2),
                ("Phys dyn. Smag", 3),
                ("iSVV", 4),
            ],
        ),
    )
    """int: Chooses LES model, they are:

    * 0 - No model (DNS);
    * 1 - Phys Smag;
    * 2 - Phys WALE;
    * 3 - Phys dyn. Smag;
    * 4 - iSVV.

    """
    #
    # # ibmstuff
    #

    nobjmax = traitlets.Int(default_value=1, min=0).tag(
        group="ibmstuff",
        widget=widgets.IntText(description="nobjmax", disabled=True))
    """int: Maximum number of objects in any direction. It is defined
        automatically at :obj:`gene_epsi_3D`.
    """

    nraf = traitlets.Int(default_value=10, min=1).tag(group="ibmstuff",
                                                      widget=widgets.IntSlider(
                                                          min=1,
                                                          max=25,
                                                          description="nraf"))
    """int: Refinement constant.
    """

    # Auxiliar
    filename = traitlets.Unicode(default_value="input.i3d").tag(
        widget=widgets.Text(description="filename"))
    """str: Filename for the ``.i3d`` file.
    """

    _i3d = traitlets.Dict(
        default_value={
            "BasicParam": {},
            "NumOptions": {},
            "InOutParam": {},
            "Statistics": {},
            "ScalarParam": {},
            "LESModel": {},
            "WallModel": {},
            "ibmstuff": {},
            "ForceCVs": {},
            "CASE": {},
        })

    _mx, _my, _mz = [traitlets.Int(default_value=1, min=1) for i in range(3)]

    dx, dy, dz = [
        traitlets.Float(default_value=0.0625,
                        min=0.0).tag(widget=widgets.BoundedFloatText(
                            description=name, min=0.0, max=1e6))
        for name in ["dx", "dy", "dz"]
    ]
    """float: Mesh resolution.
    """

    _nclx, _ncly, _nclz = [traitlets.Bool() for i in range(3)]
    """bool: Auxiliar variable for boundary condition,
        it is :obj:`True` if Periodic and :obj:`False` otherwise.
    """

    _possible_mesh_x, _possible_mesh_y, _possible_mesh_z = [
        traitlets.List(trait=traitlets.Int(), default_value=possible_mesh)
        for i in range(3)
    ]
    """:obj:`list` of :obj:`int`: Auxiliar variable for mesh points widgets,
        it stores the avalilable options according to the boudary conditions.
    """

    ncores = traitlets.Int(default_value=4,
                           min=1).tag(widget=widgets.BoundedIntText(
                               value=0, min=0, description="ncores", max=1e9))
    """int: Number of computational cores where Xcompact3d will run.
    """

    _possible_p_row, _possible_p_col = [
        traitlets.List(trait=traitlets.Int(),
                       default_value=list(divisorGenerator(4)))
        for i in range(2)
    ]
    """:obj:`list` of :obj:`int`: Auxiliar variable for parallel domain decomposition,
        it stores the avalilable options according to :obj:`ncores`.
    """

    # cfl = traitlets.Float(0.0)
    _size_in_disc = traitlets.Unicode().tag(
        widget=widgets.Text(value="", description="Size", disabled=True))
    """str: Auxiliar variable indicating the demanded space in disc
    """
    def __init__(self, **kwargs):
        """Initializes the Parameters Class.

        Parameters
        ----------
        **kwargs
            Keyword arguments for valid atributes.

        Raises
        -------
        KeyError
            Exception is raised when an Keyword arguments is not a valid atribute.

        Examples
        -------

        There are a few ways to initialize the class.

        First, calling it with no
        arguments initializes all variables with default value:

        >>> prm = xcompact3d_toolbox.Parameters()

        It is possible to set any values afterwards (including new atributes):

        >>> prm.re = 1e6

        Second, we can specify some values, and let the missing ones be
        initialized with default value:

        >>> prm = x3d.Parameters(
        ...     filename = 'example.i3d',
        ...     itype = 10,
        ...     nx = 257,
        ...     ny = 129,
        ...     nz = 32,
        ...     xlx = 15.0,
        ...     yly = 10.0,
        ...     zlz = 3.0,
        ...     nclx1 = 2,
        ...     nclxn = 2,
        ...     ncly1 = 1,
        ...     nclyn = 1,
        ...     nclz1 = 0,
        ...     nclzn = 0,
        ...     re = 300.0,
        ...     init_noise = 0.0125,
        ...     dt = 0.0025,
        ...     ilast = 45000,
        ...     ioutput = 200,
        ...     iprocessing = 50
        ... )

        And finally, it is possible to read the parameters from the disc:

        >>> prm = xcompact3d_toolbox.Parameters(filename = 'example.i3d')
        >>> prm.read()

        """

        super(Parameters, self).__init__()

        # Boundary conditions are high priority in order to avoid bugs
        for bc in "nclx1 nclxn ncly1 nclyn nclz1 nclzn".split():
            if bc in kwargs:
                setattr(self, bc, kwargs[bc])

        for key, arg in kwargs.items():
            if key not in self.trait_names():
                raise KeyError(f"There is no parameter named {key}!")
            setattr(self, key, arg)

        # self.link_widgets()

    def __call__(self, *args):
        """Returns widgets on demand.

        Parameters
        ----------
        *args : str
            Name(s) for the desired widget(s).

        Returns
        -------
        :obj:`ipywidgets.VBox`
            Widgets for an user friendly interface.

        Raises
        -------
        KeyError
            Exception is raised if an argument is not a valid atribute.
            An attribute is considered valid if it has a ``tag`` named ``widget``.

        Examples
        -------

        >>> prm = xcompact3d_toolbox.Parameters()
        >>> prm()

        >>> prm('nx', 'xlx', 'dx', 'nclx1', 'nclxn')

        """

        if len(args) == 0:
            dim = "x y z".split()

            return widgets.VBox([
                widgets.HTML(value="<h1>Xcompact3d Parameters</h1>"),
                widgets.HBox([
                    self.trait_metadata("filename", "widget"),
                    widgets.Button(description="Read",
                                   disabled=True,
                                   icon="file-upload"),
                    widgets.Button(description="Write",
                                   disabled=True,
                                   icon="file-download"),
                    widgets.Button(description="Run",
                                   disabled=True,
                                   icon="rocket"),
                    widgets.Button(description="Sync",
                                   disabled=True,
                                   icon="sync"),
                ]),
                widgets.HTML(value="<h2>BasicParam</h2>"),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "itype re".split()
                ]),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "iin init_noise inflow_noise".split()
                ]),
                widgets.HTML(value="<h3>Domain Decomposition</h3>"),
                widgets.HBox([
                    self.trait_metadata(f"{d}", "widget")
                    for d in "ncores p_row p_col".split()
                ]),
                widgets.HTML(value="<h3>Temporal discretization</h3>"),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "ifirst ilast dt".split()
                ]),
                widgets.HTML(value="<h3>InOutParam</h3>"),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "irestart nvisu _size_in_disc".split()
                ]),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "icheckpoint ioutput iprocessing".split()
                ]),
                widgets.HTML(value="<h3>Spatial discretization</h3>"),
                widgets.HBox(
                    [self.trait_metadata(f"n{d}", "widget") for d in dim]),
                widgets.HBox(
                    [self.trait_metadata(f"{d}l{d}", "widget") for d in dim]),
                widgets.HBox(
                    [self.trait_metadata(f"d{d}", "widget") for d in dim]),
                widgets.HBox(
                    [self.trait_metadata(f"ncl{d}1", "widget") for d in dim]),
                widgets.HBox(
                    [self.trait_metadata(f"ncl{d}n", "widget") for d in dim]),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "istret beta".split()
                ]),
                widgets.HTML(value="<h2>NumOptions</h2>"),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "ifirstder isecondder itimescheme".split()
                ]),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "ilesmod nu0nu cnu".split()
                ]),
                widgets.HTML(value="<h2>ScalarParam</h2>"),
                widgets.HBox([self.trait_metadata("numscalar", "widget")]),
                widgets.HBox(
                    [self.trait_metadata(f"ncl{d}S1", "widget") for d in dim]),
                widgets.HBox(
                    [self.trait_metadata(f"ncl{d}Sn", "widget") for d in dim]),
                widgets.HBox(
                    [self.trait_metadata(f"grav{d}", "widget") for d in dim]),
                widgets.HBox([
                    self.trait_metadata(d, "widget") for d in "iibmS".split()
                ]),
                widgets.HTML(
                    value=
                    "<strong>cp, us, sc, ri, scalar_lbound & scalar_ubound</strong> are lists with length numscalar, set them properly on the code."
                ),
                widgets.HTML(value="<h2>IBMStuff</h2>"),
                widgets.HBox([
                    self.trait_metadata(d, "widget")
                    for d in "iibm nraf nobjmax".split()
                ]),
            ])

        widgets_list = []
        for name in args:
            if name not in self.trait_names():
                raise KeyError(f"There is no parameter named {name}!")
            widget = self.trait_metadata(name, "widget")
            if widget != None:
                widgets_list.append(widget)

        return widgets.VBox(widgets_list)

    @traitlets.validate("nx")
    def _validade_mesh_nx(self, proposal):
        _validate_mesh(proposal["value"], self._nclx, self.nclx1, self.nclxn,
                       "x")
        return proposal["value"]

    @traitlets.validate("ny")
    def _validade_mesh_ny(self, proposal):
        _validate_mesh(proposal["value"], self._ncly, self.ncly1, self.nclyn,
                       "y")
        return proposal["value"]

    @traitlets.validate("nz")
    def _validade_mesh_nz(self, proposal):
        _validate_mesh(proposal["value"], self._nclz, self.nclz1, self.nclzn,
                       "z")
        return proposal["value"]

    @traitlets.observe("dx", "nx", "xlx", "dy", "ny", "yly", "dz", "nz", "zlz")
    def _observe_resolution(self, change):
        # for name in "name new old".split():
        #     print(f"    {name:>5} : {change[name]}")

        dim = change["name"][-1]  # It will be x, y or z
        #
        if change["name"] == f"n{dim}":
            if getattr(self, f"_ncl{dim}"):
                setattr(self, f"_m{dim}", change["new"])
            else:
                setattr(self, f"_m{dim}", change["new"] - 1)
            setattr(
                self,
                f"d{dim}",
                getattr(self, f"{dim}l{dim}") / getattr(self, f"_m{dim}"),
            )
        if change["name"] == f"d{dim}":
            new_l = change["new"] * getattr(self, f"_m{dim}")
            if new_l != getattr(self, f"{dim}l{dim}"):
                setattr(self, f"{dim}l{dim}", new_l)
        if change["name"] == f"{dim}l{dim}":
            new_d = change["new"] / getattr(self, f"_m{dim}")
            if new_d != getattr(self, f"d{dim}"):
                setattr(self, f"d{dim}", new_d)

    @traitlets.observe(
        "nclx1",
        "nclxn",
        "nclxS1",
        "nclxSn",
        "ncly1",
        "nclyn",
        "nclyS1",
        "nclySn",
        "nclz1",
        "nclzn",
        "nclzS1",
        "nclzSn",
    )
    def _observe_bc(self, change):
        #
        dim = change["name"][3]  # It will be x, y or z
        #
        if change["new"] == 0:
            for i in f"ncl{dim}1 ncl{dim}n ncl{dim}S1 ncl{dim}Sn".split():
                setattr(self, i, 0)
            setattr(self, f"_ncl{dim}", True)
        if change["old"] == 0 and change["new"] != 0:
            for i in f"ncl{dim}1 ncl{dim}n ncl{dim}S1 ncl{dim}Sn".split():
                setattr(self, i, change["new"])
            setattr(self, f"_ncl{dim}", False)

    @traitlets.observe("_nclx", "_ncly", "_nclz")
    def _observe_periodicity(self, change):
        #
        dim = change["name"][-1]  # It will be x, y or z
        #
        if change["new"]:
            tmp = getattr(self, f"n{dim}") - 1
            setattr(self, f"_possible_mesh_{dim}", possible_mesh_p)
            setattr(self, f"n{dim}", tmp)
        else:
            tmp = getattr(self, f"n{dim}") + 1
            setattr(self, f"_possible_mesh_{dim}", possible_mesh)
            setattr(self, f"n{dim}", tmp)

    @traitlets.observe("p_row", "p_col", "ncores")
    def _observe_2Decomp(self, change):
        if change["name"] == "ncores":
            possible = list(divisorGenerator(change["new"]))
            self._possible_p_row = possible
            self._possible_p_col = possible
            self.p_row, self.p_col = 0, 0
        elif change["name"] == "p_row":
            try:
                self.p_col = self.ncores // self.p_row
            except:
                self.p_col = 0
        elif change["name"] == "p_col":
            try:
                self.p_row = self.ncores // self.p_col
            except:
                self.p_row = 0

    @traitlets.observe("ilesmod")
    def _observe_ilesmod(self, change):
        if change["new"] == 0:
            self.nu0nu, self.cnu, self.isecondder = 4.0, 0.44, 4
            self.trait_metadata("nu0nu", "widget").disabled = True
            self.trait_metadata("cnu", "widget").disabled = True
            self.trait_metadata("isecondder", "widget").disabled = True
        else:
            self.trait_metadata("nu0nu", "widget").disabled = False
            self.trait_metadata("cnu", "widget").disabled = False
            self.trait_metadata("isecondder", "widget").disabled = False

    @traitlets.observe("numscalar")
    def _observe_numscalar(self, change):
        self._iscalar = True if change["new"] == 0 else False

    @traitlets.observe(
        "numscalar",
        "nx",
        "ny",
        "nz",
        "nvisu",
        "icheckpoint",
        "ioutput",
        "iprocessing",
        "ilast",
    )
    def _observe_size_in_disc(self, change):
        def convert_bytes(num):
            """
            this function will convert bytes to MB.... GB... etc
            """
            step_unit = 1000.0  # 1024 bad the size

            for x in ["bytes", "KB", "MB", "GB", "TB"]:
                if num < step_unit:
                    return "%3.1f %s" % (num, x)
                num /= step_unit

        prec = 4 if param["mytype"] == np.float32 else 8

        # Restart Size from tools.f90
        count = 3 + self.numscalar  # ux, uy, uz, phi
        # Previous time-step if necessary
        if self.itimescheme in [3, 7]:
            count *= 3
        elif self.itimescheme == 2:
            count *= 2
        count += 1  # pp
        count *= (self.nx * self.ny * self.nz * prec *
                  (self.ilast // self.icheckpoint - 1))

        # 3D from visu.f90: ux, uy, uz, pp and phi
        count += ((4 + self.numscalar) * self.nx * self.ny * self.nz * prec *
                  self.ilast // self.ioutput)

        # 2D planes from BC.Sandbox.f90
        if self.itype == 10:
            # xy planes avg and central plane for ux, uy, uz and phi
            count += (2 * (3 + self.numscalar) * self.nx * self.ny * prec *
                      self.ilast // self.iprocessing)
            # xz planes avg, top and bot for ux, uy, uz and phi
            count += (3 * (3 + self.numscalar) * self.nx * self.nz * prec *
                      self.ilast // self.iprocessing)

        self._size_in_disc = convert_bytes(count)

    def _class_to_dict(self):
        for name in self.trait_names():
            group = self.trait_metadata(name, "group")
            if group != None:
                if group not in self._i3d.keys():
                    self._i3d[group] = {}
                self._i3d[group][name] = getattr(self, name)

    def _dict_to_class(self):

        # Boundary conditions are high priority in order to avoid bugs
        for bc in "nclx1 nclxn ncly1 nclyn nclz1 nclzn".split():
            if bc in self._i3d["BasicParam"]:
                setattr(self, bc, self._i3d["BasicParam"][bc])

        for name in self.trait_names():
            try:
                group = self.trait_metadata(name, "group")
                setattr(self, name, self._i3d[group][name])
            except:
                # print(f'{name} not in dictionary')
                pass

    def get_boundary_condition(self, var=""):
        """This method returns the appropriate boundary parameters that are
        expected by the derivative functions.

        Parameters
        ----------
        var : str
            Variable name (the default is ""). The supported options are `ux`,
            `uy`, `uz`, `pp` and `phi`, otherwise the method returns a default
            option.

        Returns
        -------
        dict
            Constants the boundary conditions for the desired variable.

        Examples
        -------

        >>> prm = x3d.Parameters()
        >>> prm.get_boundary_condition('ux')
        {'x': {'ncl1': 1, 'ncln': 1, 'npaire': 0},
        'y': {'ncl1': 1, 'ncln': 2, 'npaire': 1, 'istret': 0, 'beta': 0.75},
        'z': {'ncl1': 0, 'ncln': 0, 'npaire': 1}}

        >>> DataArray.attrs['BC'] = prm.get_boundary_condition('ux')

        >>> DataArray.x3d.first_derivative('x')
        """

        return boundary_condition(self, var)

    def read(self):
        """Reads all valid attributes from an ``.i3d`` file.

        An attribute is considered valid if it has a ``tag`` named ``group``,
        witch assigns it to the respective namespace at the ``.i3d`` file.

        Examples
        -------

        >>> prm = xcompact3d_toolbox.Parameters(filename = 'example.i3d')
        >>> prm.read()

        """
        self._i3d = i3d_to_dict(self.filename)
        self._dict_to_class()

    def write(self):
        """Writes all valid attributes to an ``.i3d`` file.

        An attribute is considered valid if it has a ``tag`` named ``group``,
        witch assigns it to the respective namespace at the ``.i3d`` file.

        Examples
        -------

        >>> prm = xcompact3d_toolbox.Parameters(filename = 'example.i3d')
        >>> prm.write()

        """
        self._class_to_dict()
        dict_to_i3d(self._i3d, self.filename)

    def link_widgets(self, silence=True):
        """Creates a two-way link between the value of an attribute and its widget.

        This method is called at initialization, but provides an easy way to link
        any new variable.

        Parameters
        ----------
        silence : bool
            Print error to screen if :obj:`True`.

        Examples
        -------

        >>> prm = xcompact3d_toolbox.Parameters(filename = 'example.i3d')
        >>> prm.link_widgets()

        """
        # Create two-way link between variable and widget
        for name in self.trait_names():
            try:
                traitlets.link((self, name),
                               (self.trait_metadata(name, "widget"), "value"))
            except:
                if not silence:
                    print(f"Widget not linked for {name}")

        for dim in ["x", "y", "z"]:
            traitlets.link(
                (self, f"_possible_mesh_{dim}"),
                (self.trait_metadata(f"n{dim}", "widget"), "options"),
            )
        for name in ["p_row", "p_col"]:
            traitlets.link(
                (self, f"_possible_{name}"),
                (self.trait_metadata(f"{name}", "widget"), "options"),
            )

        for name in self.trait_names():
            if name == "numscalar":
                continue
            group = self.trait_metadata(name, "group")
            if group == "ScalarParam":
                try:
                    traitlets.link(
                        (self, "_iscalar"),
                        (self.trait_metadata(name, "widget"), "disabled"),
                    )
                except:
                    if not silence:
                        print(f"Widget not linked to numscalar for {name}")
        # Try adding a description
        for name in self.trait_names():
            if name in description:
                try:
                    self.trait_metadata(
                        name, "widget").description_tooltip = description[name]
                except:
                    pass

    def write_xdmf(self):
        """Writes four xdmf files:

        * ``./data/3d_snapshots.xdmf`` for 3D snapshots in ``./data/3d_snapshots/*``;
        * ``./data/xy_planes.xdmf`` for planes in ``./data/xy_planes/*``;
        * ``./data/xz_planes.xdmf`` for planes in ``./data/xz_planes/*``;
        * ``./data/yz_planes.xdmf`` for planes in ``./data/yz_planes/*``.

        Shape and time are inferted from folder structure and filenames.
        File list is obtained automatically with :obj:`glob`.

        .. note:: This is only compatible with the new filename structure,
            the conversion is exemplified in `convert_filenames_x3d_toolbox`_.

        .. _`convert_filenames_x3d_toolbox`: https://gist.github.com/fschuch/5a05b8d6e9787d76655ecf25760e7289

        Parameters
        ----------
        prm : :obj:`xcompact3d_toolbox.parameters.Parameters`
            Contains the computational and physical parameters.

        Examples
        -------

        >>> prm = x3d.Parameters()
        >>> prm.write_xdmf()

        """
        write_xdmf(self)

    @property
    def get_mesh(self):
        """Get mesh point locations for the three coordinates.

        Returns
        -------
        :obj:`dict` of :obj:`numpy.ndarray`
            It contains the mesh point locations at three dictionary keys,
            for **x**, **y** and **z**.

        Examples
        -------

        >>> prm = xcompact3d_toolbox.Parameters()
        >>> prm.get_mesh

        """
        return get_mesh(self)
Пример #5
0
    disabled=False
)
w_platform = widgets.RadioButtons(
    options=['Both','A','B'],
     value='Both',
    description='Platform:',
    disabled=False
)
w_relativeorbitnumber = widgets.IntText(
    value=0,
    description='Rel orbit:',
    disabled=False
)
w_exportname = widgets.Text(
    value='users/<username>/<path>',
    placeholder=' ',
    disabled=False
)
w_startdate = widgets.Text(
    value='2017-04-01',
    placeholder=' ',
    description='Start date:',
    disabled=False
)
w_enddate = widgets.Text(
    value='2017-10-01',
    placeholder=' ',
    description='End date:',
    disabled=False
)
w_median = widgets.Checkbox(
    return prediction, labels[np.argmax(prediction[0])]


#print(run_prediction(jpg_path2array("jpg_path")))

import cv2

import ipywidgets
from IPython.display import display as ipydisplay

image_widget = ipywidgets.Image(
    format='jpg',
    width=300,
    height=400,
)
prediction_text_widget = ipywidgets.Text(description='Prediction')
ipydisplay(image_widget)
ipydisplay(prediction_text_widget)
prediction_text_widget.value = "3"
# cap = cv2.VideoCapture('http://172.16.11.10:8080/stream.mjpeg')
# cap = cv2.VideoCapture('http://172.16.11.10:8080/video')
cap = cv2.VideoCapture('http://172.16.11.10:4747/video')
cap.set(cv2.CAP_PROP_FPS, 10)

count_frame = 0
while True:
    ret, frame = cap.read()
    count_frame = count_frame + 1
    cap.set(cv2.CAP_PROP_FPS, 30)
    fps = cap.get(cv2.CAP_PROP_FPS)
    #   cv2.imshow('Video', frame)
def widget_text_shortresponse(box_text, box_description):
    w1 = widgets.Text(value='',
                      placeholder=box_text,
                      description=box_description,
                      disabled=False)
    return w1
Пример #8
0
    "shapeOptions": {
        "fillColor": "#0000ff",
        "color": "#0000ff",
        "fillOpacity": 0.1
    }
}
dc.on_draw(handle_draw)


def GetTileLayerUrl(ee_image_object):
    map_id = ee.Image(ee_image_object).getMapId()
    return map_id["tile_fetcher"].url_format


w_collection = widgets.Text(value='COPERNICUS/S1_GRD',
                            placeholder=' ',
                            description='Collection:',
                            disabled=False)
w_enl = widgets.BoundedFloatText(value='4.4',
                                 min=3.0,
                                 max=20.0,
                                 step=0.1,
                                 description='ENL:',
                                 disabled=False)
w_location = widgets.Text(value='Jülich, Germany',
                          placeholder=' ',
                          description='',
                          disabled=False)
w_orbitpass = widgets.RadioButtons(options=['ASCENDING', 'DESCENDING'],
                                   value='ASCENDING',
                                   description='Orbit pass:',
                                   disabled=False)
Пример #9
0
def table_app(df):
    def save_filtered_data(_):
        filtered_df = filter_df(df,
                                order_by=order_by.value,
                                ascending=ascending.value,
                                required=filter_selector.value,
                                search_column=search_column.value,
                                search_term=search_term.value)
        filtered_df.to_csv(save_fn.value)
        save_status.value = '\t  sucessfully saved {} rows as {}.'.format(
            len(filtered_df), save_fn.value)

    def plot_filtered(df, required, search_column, search_term, plot_column):
        filtered_df = filter_df(df,
                                order_by=order_by.value,
                                required=required,
                                search_column=search_column,
                                search_term=search_term)
        plot_column_dist(df=filtered_df, column=plot_column)

    nb_items = widgets.Dropdown(options=[10, 20, 50],
                                description='items per page',
                                layout=Layout(width='20%'))
    order_by = widgets.Dropdown(options=sorted(df.keys()),
                                description='order by')
    ascending = widgets.ToggleButton(value=True, description='ascending')
    sorting = widgets.HBox([order_by, ascending, nb_items],
                           layout=Layout(height='50px'))

    filter_selector = widgets.SelectMultiple(options=sorted(df.keys()))

    filter_tip = widgets.VBox([
        widgets.HTML('Select multiple by dragging or ctrl + click'),
        widgets.HTML('Deselect with ctrl + click')
    ])
    filtering = widgets.HBox([filter_selector, filter_tip])

    save_button = widgets.Button(description='save')
    save_fn = widgets.Text('filtered_data.csv')
    save_button.on_click(save_filtered_data)
    save_status = widgets.Label()
    saving = widgets.HBox([save_fn, save_button, save_status])

    search_term = widgets.Text('', tooltip='Search')
    search_column = widgets.Dropdown(options=df.keys())
    plot_column = widgets.Dropdown(options=df.keys())

    column_dist = interactive_output(
        plot_filtered,
        dict(df=fixed(df),
             search_column=search_column,
             required=filter_selector,
             search_term=search_term,
             plot_column=plot_column))
    column_plot_box = widgets.VBox(
        [widgets.Label('Plot Columns'), plot_column, column_dist])
    search_box = widgets.VBox(
        [widgets.Label('Search Columns'), search_column, search_term])
    searching = widgets.TwoByTwoLayout(top_left=search_box,
                                       top_right=column_plot_box)
    widgets.dlink((search_column, 'value'), (plot_column, 'value'))

    accordion = widgets.Tab(children=[sorting, filtering, searching, saving])
    accordion.set_title(0, 'Sorting')
    accordion.set_title(1, 'Required Values')
    accordion.set_title(2, 'Searching')
    accordion.set_title(3, 'Save filtered Data')

    interactive_table = interactive_output(
        show_filtered_df,
        dict(df=fixed(df),
             order_by=order_by,
             nb_items=nb_items,
             required=filter_selector,
             ascending=ascending,
             search_column=search_column,
             search_term=search_term))
    display(widgets.VBox([accordion, interactive_table]))
Пример #10
0
def inputwidget(model,df,slidedef={},radiodef=[],checkdef=[],modelopt={},varpat='RFF XGDPN RFFMIN GFSRPN DMPTRSH XXIBDUMMY'
                 ,showout=1,trans={}):
    '''Creates an input widgets for updating variables 
    
    :df: Baseline dataframe 
    :slidedef: dict with definition of variables to be updated by slider
    :radiodef: dict of lists. each at first level defines a collection of radiobuttoms
               second level defines the text for each leved and the variable to set or reset to 0
    :varpat: the variables to show in the output widget
    :showout: 1 if the output widget is to be called '''
    
    lradiodef= len(radiodef)
    lslidedef = len(slidedef)
    lcheckdef = len(checkdef)
    basename ='Baseline'
    
    if lradiodef: 
        wradiolist = [widgets.RadioButtons(options=[i for i,j in cont],description=des,layout={'width':'70%'},
                                           style={'description_width':'37%'}) for des,cont in radiodef.items()]
        if len(wradiolist) <=2:
            wradio = widgets.HBox(wradiolist)
        else: 
            wradio = widgets.VBox(wradiolist)

            

# define slidesets 
    if lslidedef:     
        wexp  = widgets.Label(value="Input new parameter ",layout={'width':'41%'})
        walt  = widgets.Label(value="Alternative",layout={'width':'8%'})
        wbas  = widgets.Label(value="Baseline",layout={'width':'8%'})
        whead = widgets.HBox([wexp,walt,wbas])
        
        wset  = [widgets.FloatSlider(description=des,
                                    min=cont['min'],max=cont['max'],value=cont['value'],step=cont.get('step',0.01),
                                    layout={'width':'60%'},style={'description_width':'40%'})
                 for des,cont in slidedef.items()]
        waltval= [widgets.Label(value=f"{cont['value']:>.2f}",layout={'width':'8%'})
                  for des,cont  in slidedef.items()]
        wslide = [widgets.HBox([s,v]) for s,v in zip(wset,waltval)]
       
# cheklist  
    if lcheckdef:         
        wchecklist = [widgets.Checkbox(description=des,value=val)   for des,var,val in checkdef]
        wcheck  = widgets.HBox(wchecklist)   

# some buttons and text     
    wname = widgets.Text(value='Alternative',placeholder='Type something',description='Name of experiment:',
                        layout={'width':'30%'},style={'description_width':'50%'})
    wpat = widgets.Text(value=varpat,placeholder='Type something',description='Output variables:',
                        layout={'width':'65%'},style={'description_width':'30%'})
    winputstring = widgets.HBox([wname,wpat])
    
    wgo   = widgets.Button(description="Run")
    wreset   = widgets.Button(description="Reset to default")
    wsetbas   = widgets.Button(description="Use as baseline")
    wbut  = widgets.HBox([wgo,wreset,wsetbas])
    
    wvar = [whead]+wslide if lslidedef else []
    if lradiodef: wvar = wvar + [wradio]
    if lcheckdef: wvar = wvar + [wcheck]
        
    w     = widgets.VBox(wvar+[winputstring] +[wbut])

    # This function is run when the button is clecked 
    def run(b):
        mulstart       = model.basedf.copy()
        
        # First update from the sliders 
        if lslidedef:
            for i,(des,cont) in enumerate(slidedef.items()):
                op = cont.get('op','=')
                var = cont['var']
                for var in cont['var'].split():
                    if  op == '+':
                        mulstart.loc[model.current_per,var]    =  mulstart.loc[model.current_per,var] + wset[i].value
                    elif op == '+impulse':    
                        mulstart.loc[model.current_per[0],var] =  mulstart.loc[model.current_per[0],var] + wset[i].value
                    elif op == '=':    
                        mulstart.loc[model.current_per,var] =   wset[i].value
                    elif op == '=impuse':    
                        mulstart.loc[model.current_per,var] =   wset[i].value
                    else:
                        print(f'Wrong operator in {cont}.\nNot updated')
                        
                
        # now  update from the radio buttons 
        if lradiodef:
            for wradio,(des,cont) in zip(wradiolist,radiodef.items()):
                print(des,wradio.value,wradio.index,cont[wradio.index])
                for v in cont:
                    mulstart.loc[model.current_per,v[1]] = 0.0
                mulstart.loc[model.current_per,cont[wradio.index][1]] = 1.0  
 
        if lcheckdef:           
            for box,(des,var,_) in zip(wchecklist,checkdef):
                mulstart.loc[model.current_per,var] = 1.0 * box.value

        #with out:
        clear_output()
        mul = model(mulstart,**modelopt)

        clear_output()
        display(w)
        #_ = mfrbus['XGDPN RFF RFFMIN GFSRPN'].dif.rename(trans).plot(colrow=1,sharey=0)
        if showout:
            a = vis_alt3(get_alt(model,wpat.value),model,basename=basename,altname=wname.value,trans=trans)

    def reset(b):
        if lslidedef:
            for i,(des,cont) in enumerate(slidedef.items()):
                wset[i].value  =   cont['value']
            
        if lradiodef:
            for wradio in wradiolist:
                wradio.index = 0
            
        if lcheckdef:           
            for box,(des,var,defvalue) in zip(wchecklist,checkdef):
                box.value = defvalue

    def setbas(b):
        nonlocal basename
        model.basedf = model.lastdf.copy(deep=True)
        basename = wname.value
        
    # Assign the function to the button  
    wgo.on_click(run)
    wreset.on_click(reset)
    wsetbas.on_click(setbas)
    out = widgets.Output()
    
    return w
sv2_dropdown = widgets.Dropdown(
    options=['None', 'Aging Relation', 'Slowness Relation'],
    value='None',
    decription='State Relation:')

simType_buttons = widgets.ToggleButtons(
    description='Simulation Type',
    options=['Velocity-Displacement', 'Velocity-Time'])

calculate_button = widgets.Button(description="Calculate")

reset_button = widgets.Button(description="Reset")

step_sequence_string = widgets.Text(
    description='Sequence:',
    value='1,10,10,200',
)

# + {"extensions": {"jupyter_dashboards": {"version": 1, "views": {"grid_default": {"hidden": true}, "report_default": {"hidden": false}}}}}
sv1_label = widgets.Label(value="First State Variable", )

sv2_label = widgets.Label(value="Second State Variable", )

kc_label = widgets.Label(value="k$_c$ [$\mu$m$^{-1}$]: ")

kappa_label = widgets.Label(value="k/k$_c$: ")

# + {"extensions": {"jupyter_dashboards": {"version": 1, "views": {"grid_default": {"col": 0, "height": 4, "hidden": false, "row": 0, "width": 4}, "report_default": {"hidden": false}}}}}
display(kc_label, kappa_label)

# + {"extensions": {"jupyter_dashboards": {"version": 1, "views": {"grid_default": {"col": 4, "height": 4, "hidden": false, "row": 0, "width": 4}, "report_default": {"hidden": false}}}}}
Пример #12
0
def trade_review_in_notebook3(symbol,
                              executions: list = None,
                              pnlType='session'):
    import ipywidgets as widgets
    from IPython.display import display
    from .HKData import HKFuture

    if executions:
        executions.sort(key=lambda e: e['datetime'])  # 交易执行排序

    open_close_match = []
    if pnlType == 'session':
        from collections import deque
        pos_queue = deque()
        match = []
        for i, e in enumerate(executions):
            pos_queue.append((i, e['size']) if e['direction'] == 'long' else (
                i, -e['size']))
            match.append(i)
            if sum(p[1] for p in pos_queue) == 0:
                pos_queue.clear()
                open_close_match.append(match)
                match = []
        else:
            if match:
                open_close_match.append(match)

    ktype = widgets.RadioButtons(options=[('1 min', 1), ('5 min', 5),
                                          ('15 min', 15), ('30 min', 30),
                                          ('60 min', 30)],
                                 description='ktype')
    annotate = widgets.Checkbox(value=False, description='annotate')
    matchSelection = widgets.SelectMultiple(
        options=[(str(m), m) for m in open_close_match],
        rows=20,
        layout=widgets.Layout(width='100%', height='100px'),
        description='match',
        disabled=False)
    symbolWidget = widgets.Text(value=str(symbol),
                                description='symbol',
                                disable=True)
    figSuffixWidget = widgets.Text(value='', description='figSuffix')
    offsetWidget = widgets.IntSlider(min=0,
                                     max=500,
                                     step=10,
                                     value=60,
                                     continuous_update=False,
                                     description='expand_offset')

    fig = None

    def save_fig(b):
        if fig is not None:
            try:
                fig.savefig(f'{symbol}_{figSuffixWidget.value}.png')
            except Exception as e:
                print('errSaveFig:', e)

    saveFigButton = widgets.Button(description='保存图片')
    saveFigButton.on_click(save_fig)

    savfig_box = widgets.HBox([saveFigButton, figSuffixWidget])

    hf = HKFuture()

    def show_data(match, ktype, expand_offset, annotate):
        nonlocal fig
        es = []
        for m in match:
            for i in m:
                es.append(executions[i])
        if not es:
            print('请选择execution')
            return
        fig = hf.display_trades(symbol,
                                es,
                                period=ktype,
                                expand_offset=expand_offset,
                                annotate=annotate)

    params = {
        'match': matchSelection,
        'ktype': ktype,
        'expand_offset': offsetWidget,
        'annotate': annotate
    }

    out = widgets.interactive_output(show_data, params)
    display(symbolWidget, matchSelection, ktype, annotate, offsetWidget,
            savfig_box, out)
Пример #13
0
def trade_review_in_notebook2(symbol=None,
                              mkdata=None,
                              period=1,
                              executions: list = None,
                              account=None,
                              date_from=None,
                              date_to=None,
                              expand_offset=120,
                              source='IB'):
    import ipywidgets as widgets
    from IPython.display import display
    from dateutil import parser
    import datetime as dt
    import talib
    import pandas as pd
    import mpl_finance as mpf

    if isinstance(expand_offset, tuple):
        s_offset = expand_offset[0]
        e_offset = expand_offset[1]
    else:
        s_offset = e_offset = expand_offset

    if account and date_from and symbol:
        # 在只填写accout与date_from的情况下,找出date_from当天,account中的所有交易记录
        from KRData.IBData import IBTrade
        ibt = IBTrade(account)
        date_from = parser.parse(date_from) if isinstance(date_from,
                                                          str) else date_from
        date_to = date_from + dt.timedelta(days=1) if date_to is None else (
            parser.parse(date_to) if isinstance(date_to, str) else date_to)
        fills = ibt[date_from:date_to:symbol]
        if fills.count() < 1:
            raise Exception(f'账户:{account}在{date_from}-{date_to}不存在交易记录')
        conId = fills[0].contract.conId
        executions = [{
            'datetime':
            f.time.replace(second=0) + dt.timedelta(hours=8),
            'price':
            f.execution.price,
            'size':
            f.execution.shares,
            'direction':
            'long' if f.execution.side == 'BOT' else 'short'
        } for f in fills]
        executions.sort(key=lambda e: e['datetime'])
        start = executions[0]['datetime'] - dt.timedelta(minutes=s_offset)
        end = executions[-1]['datetime'] + dt.timedelta(minutes=e_offset)
        if source == 'IB':
            barTypeMap = {
                1: '1 min',
                5: '5 mins',
                15: '15 mins',
                30: '30 mins',
                60: '1 hour'
            }
            mkdata = ibt._ib_market.get_bars_from_ib(conId,
                                                     barType=barTypeMap.get(
                                                         period, '1 min'),
                                                     start=start,
                                                     end=end)
        elif source == 'HK':
            from KRData.HKData import HKFuture
            hf = HKFuture()
            mkdata = hf.get_bars(symbol,
                                 start=start,
                                 end=end,
                                 ktype=f'{period}min',
                                 queryByDate=False)
            del hf
        del ibt
    elif mkdata is None and symbol:
        # 在只填写execution的情况下,自动根据source获取数据

        start = executions[0]['datetime'] - dt.timedelta(minutes=s_offset)
        end = executions[-1]['datetime'] + dt.timedelta(minutes=e_offset)

        if source == 'IB':
            from KRData.IBData import IBMarket
            ibm = IBMarket()
            barTypeMap = {
                1: '1 min',
                5: '5 mins',
                15: '15 mins',
                30: '30 mins',
                60: '1 hour'
            }
            mkdata = ibm.get_bars_from_ib(symbol,
                                          barType=barTypeMap.get(
                                              period, '1 min'),
                                          start=start,
                                          end=end)
            del ibm
        elif source == 'HK':
            from KRData.HKData import HKFuture
            hf = HKFuture()
            mkdata = hf.get_bars(symbol,
                                 start=start,
                                 end=end,
                                 ktype=f'{period}min',
                                 queryByDate=False)
            del hf

    mkdata = _concat_executions(mkdata, executions)
    mkdata['ma5'] = talib.MA(mkdata['close'].values, timeperiod=5)
    mkdata['ma10'] = talib.MA(mkdata['close'].values, timeperiod=10)
    mkdata['ma30'] = talib.MA(mkdata['close'].values, timeperiod=30)
    mkdata['ma60'] = talib.MA(mkdata['close'].values, timeperiod=60)

    symbolWidget = widgets.Text(value=str(symbol),
                                description='symbol',
                                disable=True)

    fromWidget = widgets.Text(value='',
                              placeholder='yyyymmdd HH:MM:SS',
                              description='From:',
                              disabled=True)
    toWidget = widgets.Text(value='',
                            placeholder='yyyymmdd HH:MM:SS',
                            description='To:',
                            disabled=True)
    time_range_box = widgets.HBox([fromWidget, toWidget])
    annotate = widgets.Checkbox(value=False, description='annotate')

    offsetWidget = widgets.IntSlider(min=0,
                                     max=500,
                                     step=10,
                                     value=60,
                                     description='expand_offset')

    executionSelection = widgets.SelectionRangeSlider(
        options=[(str(_e['datetime']), _e['datetime']) for _e in executions],
        index=(0, len(executions) - 1),
        description='execution',
        disabled=False,
        continuous_update=False,
    )

    fig = None

    def save_fig(b):
        if fig is not None:
            try:
                fig.savefig('fig.png')
            except Exception as e:
                print('errSaveFig:', e)

    saveFigButton = widgets.Button(description='保存图片')
    saveFigButton.on_click(save_fig)

    def show_data(e_select, offset, annotate):
        nonlocal fig
        s = e_select[0] - dt.timedelta(minutes=offset)
        e = e_select[-1] + dt.timedelta(minutes=offset)

        fromWidget.value = str(s)
        toWidget.value = str(e)

        temp_mkdata = mkdata[s:e]

        fig = draw_klines(temp_mkdata, annotate=annotate)

    params = {
        'e_select': executionSelection,
        'offset': offsetWidget,
        'annotate': annotate
    }

    out = widgets.interactive_output(show_data, params)
    display(symbolWidget, time_range_box, annotate, executionSelection,
            offsetWidget, saveFigButton, out)
Пример #14
0
def trade_review_in_notebook(trades=None):
    """
    用于查看某账户的具体日期的成交明细
    :return:
    """
    from .IBData import IBTrade
    import ipywidgets as widgets
    from IPython.display import display

    ibt = IBTrade()

    account = widgets.Text(continuous_update=False, description='account')
    symbol = widgets.Text(continuous_update=False, description='symbol')
    source = widgets.RadioButtons(options=['IB', 'HK'], description='source')
    ktype = widgets.RadioButtons(options=[('1 min', 1), ('5 min', 5),
                                          ('15 min', 15), ('30 min', 30),
                                          ('60 min', 30)],
                                 description='ktype')
    annotate = widgets.Checkbox(value=False, description='annotate')
    range_ = widgets.IntRangeSlider(continuous_update=False,
                                    description='range')
    expand_offset = widgets.IntSlider(min=0,
                                      max=500,
                                      step=10,
                                      value=60,
                                      continuous_update=False,
                                      description='expand_offset')

    start_date = widgets.DatePicker()
    end_date = widgets.DatePicker()

    time_box = widgets.HBox([start_date, end_date])

    def update_time_range(*args):
        sd = start_date.value
        ed = end_date.value
        if sd and ed:
            start = dt.datetime(sd.year, sd.month, sd.day)
            end = dt.datetime(ed.year, ed.month, ed.day)
            minute_count = (end - start).total_seconds() // 60
            range_.set_trait('max', minute_count)
            range_.set_trait('value', (0, minute_count))
            print(range_.max)

    def update_time_range_str(*args):
        sd = start_date.value
        ed = end_date.value
        if sd and ed:
            start = dt.datetime(sd.year, sd.month, sd.day)
            _from.value = str(start + dt.timedelta(minutes=range_.value[0]))
            _to.value = str(start + dt.timedelta(minutes=range_.value[1]))

    _from = widgets.Text(value='',
                         placeholder='yyyymmdd HH:MM:SS',
                         description='From:',
                         disabled=True)
    _to = widgets.Text(value='',
                       placeholder='yyyymmdd HH:MM:SS',
                       description='To:',
                       disabled=True)
    time_range_box = widgets.HBox([_from, _to])

    start_date.observe(update_time_range, 'value')
    end_date.observe(update_time_range, 'value')
    start_date.observe(update_time_range_str, 'value')
    end_date.observe(update_time_range_str, 'value')
    range_.observe(update_time_range_str, 'value')

    def show_data(account, symbol, start_date, end_date, ktype, range_,
                  expand_offset, source, annotate):
        print(account, symbol, start_date, end_date, range_, expand_offset,
              source)
        if account and symbol and start_date and end_date:
            start = dt.datetime(start_date.year, start_date.month,
                                start_date.day)
            end = dt.datetime(end_date.year, end_date.month, end_date.day)
            ibt.account = account
            fills = ibt[start + dt.timedelta(minutes=range_[0]):start +
                        dt.timedelta(minutes=range_[1]):symbol]
            ibt.display_trades(fills,
                               period=ktype,
                               expand_offset=expand_offset,
                               mkdata_source=source,
                               annotate=annotate)

    params = {
        'account': account,
        'symbol': symbol,
        'start_date': start_date,
        'end_date': end_date,
        'ktype': ktype,
        'range_': range_,
        'expand_offset': expand_offset,
        'source': source,
        'annotate': annotate
    }
    out = widgets.interactive_output(show_data, params)
    display(account, symbol, source, ktype, annotate, time_box, range_,
            expand_offset, time_range_box, out)
Пример #15
0
from IPython.core.display import display, HTML, Markdown, clear_output
import json
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets

# Defining Widgets:
equation = widgets.Text(
    value='seno(X*Y)+coseno(X+Y)',
    placeholder='Escribe la ecuación que quieras visualizar',
    description='Ecuación:')
range_ = widgets.FloatRangeSlider(
    value=[-5, 5],
    min=-100,
    step=0.1,
    description='Rango:',
    orientation='horizontal',
    readout=True,
    readout_format='d',
)
points = widgets.IntText(value=50, description='Detalle:')


# DEFINING FUNCTIONS
def plot2D(x_points):
    # I find where the letter X is in my equation text and replace by placeholders {}

    number_of_placeholders = equation.value.count('X')
    decomposed_equation = equation.value.replace('X', '{}')
    y = []
    for point in x_points:
Пример #16
0
    def _repr_ipyw_(self, add_header=True):
        import ipywidgets as ipw
        vlist = []
        if add_header:
            vlist.append(ipw.HTML("<h3>Dataset</h3>"))
            header = ipw.HBox([
                ipw.HTML('<b>%s</b>' % txt[0], layout=ipw.Layout(width=txt[1]))
                for txt in [('Name', '30ex'), ('show',
                                               '6ex'), ('use',
                                                        '6ex'), ('error',
                                                                 '6ex')]
            ])
            vlist.append(header)

        entries = []
        entries.append(ipw.Text(self.name, layout=ipw.Layout(width='30ex')))
        entries.append(
            ipw.Checkbox(self.show,
                         indent=False,
                         layout=ipw.Layout(width='6ex')))
        entries.append(
            ipw.Checkbox(self.use,
                         indent=False,
                         layout=ipw.Layout(width='6ex')))
        entries.append(
            ipw.Checkbox(self.use_error,
                         indent=False,
                         layout=ipw.Layout(width='6ex')))
        items = ['name', 'show', 'use', 'use_error']
        for j, entr in enumerate(entries):
            entr._child_val = items[j]
            entr.observe(self._ipyw_change, names='value')
        vlist.append(ipw.HBox(entries))
        cbox = ipw.VBox()
        plotbox = ipw.VBox()
        clist = []
        commands = ipw.Accordion(children=[cbox, plotbox],
                                 selected_index=None,
                                 layout=ipw.Layout(width='46x'))
        commands.set_title(0, 'Commands')
        commands.set_title(1, 'Plotting')
        vlist.append(commands)
        for col in ['x', 'y', 'error']:
            entr = ipw.Text(eval('self.%s_command' % col, globals(), locals()),
                            description=col)
            entr._command = col
            entr.observe(self._ipyw_command, names='value')
            clist.append(entr)
        for key, value in self.extra_commands.items():
            entr = ipw.Text(value, description=key)
            entr._command = key
            clist.append(entr)
            entr.observe(self._ipyw_command, names='value')
        cbox.children = tuple(clist)
        clist = []
        clist.append(
            ipw.ColorPicker(description="Sim Color",
                            value=c2html(self.sim_color)))
        clist[-1]._child_val = 'sim_color'
        clist[-1].observe(self._ipyw_change_color)
        clist.append(
            ipw.ColorPicker(description="Data Color",
                            value=c2html(self.data_color)))
        clist[-1]._child_val = 'data_color'
        clist[-1].observe(self._ipyw_change_color)

        plotbox.children = tuple(clist)
        return ipw.VBox(vlist)
Пример #17
0
class TTreeHnBrowser:
    def __init__(self):
        self.addQueryButton.on_click(self.funAddQuery)
        self.addSelectionButton.on_click(self.funAddSelection)
        self.addSliderButton.on_click(self.funAddSlider)
        self.regExpButton.on_click(self.funUpdateMask)
        self.drawSliderButton.on_click(self.funAddNewSlider)
        self.drawQueryButton.on_click(self.funAddNewQuery)
        self.loadSelectionButton.on_click(self.loadDataInMemory)

    def initTree(self, tree):
        """
        initialize browser using tree ()
        :param tree:
        :return:
        """
        self.fTree = tree
        self.friendListROOT = tree.GetListOfFriends()
        self.branchListROOT = tree.GetListOfBranches()
        self.aliasListROOT = tree.GetListOfAliases()
        self.funUpdateList()
        #        if ROOT.TStatToolkit.GetMetadata(tree): self.loadMetadata(tree)
        if GetMetadata(tree): self.loadMetadata(tree)
        return 0

    def loadDataInMemory(self, b):
        """
        Load numpy array with selected entries from tree into memory
        Temporary data.csv file created
        TODO: make in memory transformation
        :return: success stratus
        """
        varSet = set()
        for var in self.sliderArray.fVariableList:
            varSet.add(var)
        for var in self.drawVarArray.fVariableList:
            varSet.add(var)
        variables = ""
        for var in varSet:
            variables += var + ":"
        value = ROOT.AliTreePlayer.selectWhatWhereOrderBy(
            self.fTree, str(variables), str(self.drawSelection.value), "", 0,
            10000000, "csvroot", "data.csv")
        print(value)
        if value <= 0: return value
        self.fDataFrame = readDataFrame('data.csv')
        self.boxAll.children = [
            x for x in self.boxAll.children if x != self.fQgrid
        ]
        self.fQgrid = qgrid.show_grid(self.fDataFrame)
        self.boxAll.children += (self.fQgrid, )

    def loadMetadata(self, tree):
        """ Load sliders according description in tree metadata
        """
        #        treeMeta = ROOT.TStatToolkit.GetMetadata(tree)
        treeMeta = GetMetadata(tree)
        for index in range(treeMeta.GetEntries()):
            j = treeMeta.At(index)
            if ROOT.TString(j.GetName()).Contains(".Slider"):
                slider = str(j.GetName())
                slider = re.sub(".Slider$", "", slider)
                slider += j.GetTitle()
                self.sliderArray.addSlider(slider)

    def funUpdateList(self):
        """
        update lists according to  RegExp selections
        :return:
        """
        friendMaskReg = ROOT.TPRegexp(self.friendRegExp)
        branchMaskReg = ROOT.TPRegexp(self.branchRegExp)
        self.friendList[:] = ['']
        if (self.friendListROOT != None):
            for i in range(0, self.friendListROOT.GetEntries()):
                if friendMaskReg.GetPattern().Length() > 0:
                    if friendMaskReg.Match(
                            self.friendListROOT.At(i).GetName()):
                        self.friendList.append(
                            self.friendListROOT.At(i).GetName())
                else:
                    self.friendList.append(self.friendListROOT.At(i).GetName())
        self.branchList[:] = ['']
        for i in range(0, self.branchListROOT.GetEntries()):
            if branchMaskReg.GetPattern().Length() > 0:
                if branchMaskReg.Match(self.branchListROOT.At(i).GetName()):
                    self.branchList.append(self.branchListROOT.At(i).GetName())
            else:
                self.branchList.append(self.branchListROOT.At(i).GetName())
        # for i in range(0,self.aliasListROOT.GetEntries()):
        #    self.aliasList.append(self.aliasListROOT.At(i).GetName())
        self.friendDropDown.options = self.friendList
        self.branchDropDown.options = self.branchList

    def funAddQuery(self, b):
        self.drawQuery.value += self.friendDropDown.value
        self.drawQuery.value += '.'
        self.drawQuery.value += self.branchDropDown.value

    def funAddSelection(self, b):
        self.drawSelection.value += self.friendDropDown.value
        self.drawSelection.value += '.'
        self.drawSelection.value += self.branchDropDown.value

    def funAddSlider(self, b):
        self.drawSlider.value += self.friendDropDown.value
        self.drawSlider.value += '.'
        self.drawSlider.value += self.branchDropDown.value

    def funUpdateMask(self, b):
        self.branchRegExp = str(self.branchRegExpWidget.value)
        self.friendRegExp = str(self.friendRegExpWidget.value)
        # print(branchMask)
        self.funUpdateList()

    def funAddNewSlider(self, b):
        self.sliderArray.addSlider(self.drawSlider.value)
        with self.fOut:
            print('funAddNewSlider')

    def funAddNewQuery(self, b):
        self.drawVarArray.addVariable(self.drawQuery.value)
        with self.fOut:
            print('funAddNewQuery')

    # data members
    # root tree
    tree = ROOT.TTree()
    friendListROOT = []
    branchListROOT = []
    aliasListROOT = []
    # tree variables selection
    friendList = ['']
    branchList = []
    aliasList = ['']
    friendRegExp = '.*'
    branchRegExp = '.*'
    aliasRegExp = '.*'
    # regular expression selection
    friendRegExpWidget = widgets.Text(description='Friend RegExp',
                                      value=friendRegExp)
    branchRegExpWidget = widgets.Text(description='Branch RegExp',
                                      value=branchRegExp)
    aliasRegExpWidget = widgets.Text(description='Alias RegExp')
    regExpButton = widgets.Button(description='RegExp', tooltip="RegExp")
    # drop-down list of variables
    friendDropDown = widgets.Dropdown(options=friendList,
                                      description='Friend list:')
    branchDropDown = widgets.Dropdown(options=branchList,
                                      description='Branch list:')
    aliasDropDown = widgets.Dropdown(options=aliasList,
                                     description='Alias list:')
    # tree expression Text box
    drawSelection = widgets.Text(description='Selection',
                                 layout=Layout(width='66%'))
    addSelectionButton = widgets.Button(description='Copy selection',
                                        tooltip="Copy selection")
    loadSelectionButton = widgets.Button(
        description='Load selection',
        tooltip="Load selected entries from tree to memory")
    drawSelectionBox = widgets.HBox(
        [drawSelection, addSelectionButton, loadSelectionButton])
    #
    drawQuery = widgets.Text(description='Query', layout=Layout(width='66%'))
    addQueryButton = widgets.Button(description='Copy Query',
                                    tooltip="Copy query")
    drawQueryButton = widgets.Button(description='Append query',
                                     tooltip="Append query")
    drawQueryBox = widgets.HBox([drawQuery, addQueryButton, drawQueryButton])
    #
    drawSlider = widgets.Text(description='Slider', layout=Layout(width='66%'))
    addSliderButton = widgets.Button(description='Copy slider',
                                     tooltip="Copy slider")
    drawSliderButton = widgets.Button(description='Append slider',
                                      tooltip="Append slider")
    drawSliderBox = widgets.HBox(
        [drawSlider, addSliderButton, drawSliderButton])
    #
    boxMask = widgets.HBox([
        friendRegExpWidget, branchRegExpWidget, aliasRegExpWidget, regExpButton
    ])
    boxSelect = widgets.HBox([friendDropDown, branchDropDown, aliasDropDown])
    # boxButton = widgets.HBox([addQueryButton, addSelectionButton, addSliderButton])
    boxDraw = widgets.VBox([drawQueryBox, drawSliderBox, drawSelectionBox],
                           width=1000)
    sliderArray = TSliderArray()
    drawVarArray = TDrawVarArray()
    fTree = ROOT.TTree()
    fDataFrame = 0
    fQgrid = 0
    fOut = widgets.Output()
    boxAll = widgets.VBox([
        boxMask, boxSelect, boxDraw, drawVarArray.fDrawVarWidgets,
        sliderArray.fSliderWidgets, fOut
    ])
Пример #18
0
    def _addInputJupyter(self, name, input, reset=False):
        """Add an input requirement for Jupyter.

           Parameters
           ----------

           name : str
               The name of the input.

           input : :class:`Requirement <BioSimSpace.Gateway._requirement.Requirement>`
               The input requirement object.

           reset : bool
               Whether to reset the widget data.
        """

        # Create a widget button to indicate whether the requirement value
        # has been set.
        button = _widgets.Button(
            tooltip="The input requirement is unset.",
            button_style="warning",
            icon="fa-exclamation-triangle",
            layout=_widgets.Layout(flex="1 1 auto", width="auto"),
            disabled=False,
        )

        # Add a Jupyter widget for each of the supported requirement types.

        # Boolean.
        if type(input) is _Boolean:
            # Create a Jupyter toggle button.
            widget = _widgets.ToggleButton(value=False,
                                           description=name,
                                           tooltip=input.getHelp(),
                                           button_style="",
                                           icon="check",
                                           disabled=False)

            # Add the 'set' indicator button to the widget.
            widget._button = button

            # Flag that the widget is unset.
            widget._is_set = False

            # Get the default value.
            default = input.getDefault()

            if default is not None:
                widget.value = default
                widget._is_set = True
                widget._button.tooltip = "The input requirement is set."
                widget._button.button_style = "success"
                widget._button.icon = "fa-check"

            # Store the requirement name.
            widget._name = name

            # Bind the callback function.
            widget.observe(_on_value_change, names="value")

            # Store the widget.
            self._widgets[name] = widget

        # Integer.
        elif type(input) is _Integer:
            # Get the list of allowed values.
            allowed = input.getAllowedValues()

            # Get the default value.
            default = input.getDefault()

            if allowed is not None:
                # Set the default.
                if default is None:
                    default = allowed[0]

                # Create a dropdown for the list of allowed values.
                widget = _widgets.Dropdown(options=allowed,
                                           value=default,
                                           description=name,
                                           tooltip=input.getHelp(),
                                           disabled=False)

            else:
                # Get the range of the input.
                _min = input.getMin()
                _max = input.getMax()

                # Whether the integer is unbounded.
                is_unbounded = True

                if _min is not None:
                    # Set the default.
                    if default is None:
                        default = _min

                    # Bounded integer.
                    if _max is not None:
                        step = int((_max - _min) / 100)
                        # Create an int slider widget.
                        widget = _widgets.IntSlider(value=default,
                                                    min=_min,
                                                    max=_max,
                                                    step=step,
                                                    description=name,
                                                    tooltip=input.getHelp(),
                                                    continuous_update=False,
                                                    orientation="horizontal",
                                                    readout=True,
                                                    readout_format="d",
                                                    disabled=False)

                        # Flag that the integer is bounded.
                        is_unbounded = False

                # Unbounded integer.
                if is_unbounded:
                    # Create an integer widget.
                    widget = _widgets.IntText(value=default,
                                              description=name,
                                              tooltip=input.getHelp(),
                                              disabled=False)

            # Add the 'set' indicator button to the widget.
            widget._button = button

            # Flag that the widget is unset.
            widget._is_set = False

            # Add an attribute to flag whether the widget value has
            # been set by the user.
            if input.getDefault() is not None:
                widget._is_set = True
                widget._button.tooltip = "The input requirement is set."
                widget._button.button_style = "success"
                widget._button.icon = "fa-check"

            # Store the requirement name.
            widget._name = name

            # Bind the callback function.
            widget.observe(_on_value_change, names="value")

            # Store the widget.
            self._widgets[name] = widget

        # Float types (including those with units).
        elif type(input) in _float_types:
            # Get the list of allowed values.
            allowed = input.getAllowedValues()

            # Get the default value.
            default = input.getDefault()

            # Get the magnitude of types with units.
            if isinstance(default, _Type):
                default = default.magnitude()

            if allowed is not None:
                # Set the default.
                if default is None:
                    default = allowed[0]

                    # Get the magnitude of types with units.
                    if isinstance(default, _Type):
                        default = default.magnitude()

                # Create a dropdown for the list of allowed values.
                widget = _widgets.Dropdown(options=allowed,
                                           value=default,
                                           description=name,
                                           tooltip=input.getHelp(),
                                           disabled=False)

            else:
                # Get the range of the input.
                _min = input.getMin()
                _max = input.getMax()

                # Get the magnitude of types with units.
                if isinstance(_min, _Type):
                    _min = _min.magnitude()
                if isinstance(_max, _Type):
                    _max = _max.magnitude()

                # Whether the float is unbounded.
                is_unbounded = True

                if _min is not None:
                    # Set the default.
                    if default is None:
                        default = _min

                    # Bounded float.
                    if _max is not None:
                        step = (_max - _min) / 100
                        # Create a float slider widget.
                        widget = _widgets.FloatSlider(value=default,
                                                      min=_min,
                                                      max=_max,
                                                      step=step,
                                                      description=name,
                                                      tooltip=input.getHelp(),
                                                      continuous_update=False,
                                                      orientation="horizontal",
                                                      readout=True,
                                                      readout_format=".1f",
                                                      disabled=False)

                        # Flag that the float is bounded.
                        is_unbounded = False

                # Unbounded float.
                if is_unbounded:
                    # Create a float widget.
                    widget = _widgets.FloatText(value=default,
                                                description=name,
                                                tooltip=input.getHelp(),
                                                disabled=False)

            # Add the 'set' indicator button to the widget.
            widget._button = button

            # Flag that the widget is unset.
            widget._is_set = False

            # Add an attribute to flag whether the widget value has
            # been set by the user.
            if input.getDefault() is not None:
                widget._is_set = True
                widget._button.tooltip = "The input requirement is set."
                widget._button.button_style = "success"
                widget._button.icon = "fa-check"

            # Store the requirement name.
            widget._name = name

            # Bind the callback function.
            widget.observe(_on_value_change, names="value")

            # Store the widget.
            self._widgets[name] = widget

        # String.
        elif type(input) is _String:
            # Get the list of allowed values.
            allowed = input.getAllowedValues()

            # Get the default value.
            default = input.getDefault()

            if allowed is not None:
                # Set the default.
                if default is None:
                    default = allowed[0]

                # Create a dropdown for the list of allowed values.
                widget = _widgets.Dropdown(options=allowed,
                                           value=default,
                                           description=name,
                                           tooltip=input.getHelp(),
                                           disabled=False)

            else:
                if default is None:
                    # Create a text widget without a default.
                    widget = _widgets.Text(placeholder="Type something",
                                           description=name,
                                           tooltip=input.getHelp(),
                                           disabled=False)
                else:
                    # Create a text widget.
                    widget = _widgets.Text(value=default,
                                           placeholder="Type something",
                                           description=name,
                                           tooltip=input.getHelp(),
                                           disabled=False)

            # Add the 'set' indicator button to the widget.
            widget._button = button

            # Flag that the widget is unset.
            widget._is_set = False

            # Add an attribute to flag whether the widget value has
            # been set by the user.
            if input.getDefault() is not None:
                widget._is_set = True
                widget._button.tooltip = "The input requirement is set."
                widget._button.button_style = "success"
                widget._button.icon = "fa-check"

            # Store the requirement name.
            widget._name = name

            # Bind the callback function.
            widget.observe(_on_value_change, names="value")

            # Store the widget.
            self._widgets[name] = widget

        # File / File set.
        elif type(input) is _File or type(input) is _FileSet:

            # Create a fileupload widget.
            if type(input) is _FileSet:
                widget = _widgets.FileUpload(multiple=True)
            else:
                widget = _widgets.FileUpload(multiple=False)

            # Make the widget dynamically resize to the content.
            widget.layout = {"width": "max-content"}

            # Add the 'set' indicator button to the widget.
            widget._button = button

            # Flag that the widget is unset.
            widget._is_set = False

            # Flag that this widget references files.
            widget._is_file = True

            # Store the requirement name.
            widget._name = name

            # Bind the callback function.
            widget.observe(_on_file_upload, names="data")

            # Store the widget.
            self._widgets[name] = widget

        # Unsupported input.
        else:
            raise ValueError("Unsupported requirement type '%s'" % type(input))
Пример #19
0
    def __init__(self):

        self.model = None
        self.sim_model = None
        self.models_compare = {}
        self.models_total_population = {}
        self.data_description = None
        self.pd_dict = None
        self.model_folder_text_widget = None
        self.main_tab_widget = None
        self.open_tab_widget = None
        self.edit_tab_widget = None
        self.last_plot = None
        self.transitions_chooser = None
        self.region_dropdowns = []
        self.param_dropdown = None
        self.val_text_widget = None
        self.seed_text_widget = None
        self.seed_value = None
        self.pop_data = None
        self.pop_dropdown = None
        self.date_range_text = None
        self.skip_data_text = None
        self.local_start_inttext = None
        self.full_par_dropdown = None
        self.full_pop_name = None
        self.optimizer = None
        self.chain = None
        self.edit_model = None
        self.new_parameters = {}
        self.delays = {}
        self.new_delays = {}
        self.new_populations = {}
        self.new_propagators = {}
        self.region_model_folders = None
        self.model_filenames = None
        self.region_data_folders = None
        self.data_fit_statistics = None
        self.cumul_reset = True
        self.cumul_reset_checkbox = None
        self.skip_zeros = True
        self.skip_zeros_checkbox = None
        self.mod_last_transition = None
        self.mod_alphas_std = None

        # widgets shared on more than one tab:

        self.model_name = widgets.Text(description='Name:')
        self.model_description = widgets.Textarea(description='Description:')
        self.model_t0 = widgets.DatePicker(description='t_0:',
                                           value=date(2020, 3, 1),
                                           tooltip='Defines day 0 on plots',
                                           disabled=True)
        self.model_time_step = widgets.FloatText(
            description='time_step:',
            value=1.,
            disabled=True,
            tooltip='Duration of one time step. Units: days')
        self.open_model_output = widgets.Output(layout={'width': '60%'})
        self.open_data_output = widgets.Output()
        self.region_data_output = widgets.Output(layout={'width': '60%'})
        self.region_dropdown = widgets.Dropdown(description='Region data:',
                                                options=['None', 'Simulation'])
        n_days = (date.today() - self.model_t0.value).days
        n_days = n_days - n_days % 10 + 10
        self.n_days_widget = widgets.BoundedIntText(
            value=n_days,
            min=10,
            max=999,
            step=1,
            description='n_days:',
            tooltip=
            'number of days to model: sets the upper time range of plots')
        # Compare A and B
        self.model_names = [
            widgets.Text(value='', description='Model A:', disabled=True),
            widgets.Text(value='', description='Model B:', disabled=True)
        ]
        self.model_descriptions = [
            widgets.Textarea(value='',
                             description='Description:',
                             disabled=True),
            widgets.Textarea(value='',
                             description='Description:',
                             disabled=True)
        ]
x = np.linspace(0, 2 * np.pi, 100)

# default line color
initial_color = '#FF00DD'

with output:
    fig, ax = plt.subplots(constrained_layout=True, figsize=(6, 4))
    # move the toolbar to the bottom
fig.canvas.toolbar_position = 'bottom'
ax.grid(True)    
line, = ax.plot(x, np.sin(x), initial_color)

# create some control elements
int_slider = widgets.IntSlider(value=1, min=0, max=10, step=1, description='freq')
color_picker = widgets.ColorPicker(value=initial_color, description='pick a color')
text_xlabel = widgets.Text(value='', description='xlabel', continuous_update=False)
text_ylabel = widgets.Text(value='', description='ylabel', continuous_update=False)
reset_button = widgets.Button(description="Reset values!", layout=Layout(align_self='flex-end')) #center flex-end flex-start
#reset_button.layout.align_self='center'

# callback functions
def update(change):
    """redraw line (update plot)"""
    line.set_ydata(np.sin(change.new * x))
    fig.canvas.draw()
    
def line_color(change):
    """set line color"""
    line.set_color(change.new)
    
def update_xlabel(change):
Пример #21
0
 def input_layer_type(self):
     self.k = wg.Text(description='Layer Type')
     display(self.k)
Пример #22
0
    def view_selection(self):
        maxZ = self.volume.shape[2] - 1

        style = {'description_width': 'initial'}

        # Adjustable variables
        z = ipyw.IntSlider(min=0,
                           max=maxZ,
                           step=1,
                           value=0,
                           descritpion='z',
                           style=style,
                           continuous_update=False)
        sigma = ipyw.FloatSlider(min=0,
                                 max=10,
                                 step=0.5,
                                 value=2.0,
                                 continuous_update=False)
        R = ipyw.IntSlider(min=1,
                           max=20,
                           step=3,
                           value=10,
                           continuous_update=False)
        z_lower = ipyw.BoundedIntText(value=0,
                                      min=0,
                                      max=maxZ,
                                      step=1,
                                      description='',
                                      disabled=False)
        z_upper = ipyw.BoundedIntText(value=0,
                                      min=0,
                                      max=maxZ,
                                      step=1,
                                      description='',
                                      disabled=False)
        label = ipyw.Text(value='Enter label here',
                          placeholder='Type something',
                          description='',
                          disabled=False)
        NewBox = ipyw.ToggleButton(
            value=False,
            description='Click me',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Start a new box',
            icon='check',
            layout=Layout(width="30%", height='30px'))
        FinishCurrentBox = ipyw.ToggleButton(
            value=False,
            description='Click me',
            disabled=False,
            button_style='info',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Finish the current box',
            icon='check',
            layout=Layout(width="30%", height='30px'))

        H1 = HBox([HBox([Label('sigma'), sigma]), HBox([Label('R'), R])])
        H2 = HBox([Label('z'), z])
        H3 = HBox([
            HBox([Label('z_lower'), z_lower]),
            HBox([Label('z_upper'), z_upper])
        ])
        H4 = HBox([Label('label'), label])
        H5 = HBox([Label('NewBox'), NewBox])
        H6 = HBox([Label('FinishCurrentBox'), FinishCurrentBox])
        ui = VBox([H1, H2, H3, H4, H5, H6])

        out = widgets.interactive_output(
            self.plot_slice, {
                'sigma': sigma,
                'R': R,
                'z_lower': z_lower,
                'z_upper': z_upper,
                'NewBox': NewBox,
                'FinishCurrentBox': FinishCurrentBox,
                'label': label,
                'z': z
            })

        display(ui, out)
Пример #23
0
    def __init__(self, topic, ontologies, required=False, value_changed=None,
                 bioportal_api_key='efa3babf-b23c-4399-89f7-689bb9d576fb'):
        """Provide bioportal key, create widgets.

        Create (but not display) needed widgets. If the topic is required
        before upload, highlight the text box red.

        :param topic: The topic name to be associated with the key words
        :param ontolgies: The ontolgies to be searched.
        :param required: Whether or not the topic is required to have at least
                         one key word added before upload.
        :param value_changed: Callback which is called everytime the first word
                              is added to an empty added words widget or when
                              the last word is removed from the added words
                              widget.
        :param bioportal_api_key: The key used to access the bioportal REST API

        """
        self._topic = topic
        self._required = required
        self._ontologies = ontologies
        self._value_changed = value_changed
        self._color = 'red'
        # self._results_info stores keywords as keys and bioportal
        # results as values
        self._results_info = dict()
        # self._final_results stores only the info for added words
        self._final_results = dict()
        self._selected = None
        self._ready = False

        results_name = topic + " results:"
        self._search_input_widget = widgets.Text(description=topic,
                                                 value='', width='49%')
        self._search_results_widget = widgets.Select(description=results_name,
                                                     options=[],
                                                     width='300')
        self._added_word_widget = widgets.Select(description='selected words:',
                                                 options=[],
                                                 width='300')
        self._add_button = widgets.Button(description='add', width='100%',
                                          disabled=True)
        self._remove_button = widgets.Button(description='remove',
                                             width='100%',
                                             disabled=True)
        if required:
            self._search_input_widget.background_color = self._color

        search_contains = [self._search_input_widget]
        search_container = widgets.HBox(children=search_contains)
        button_contains = [self._add_button, self._remove_button]
        button_container = widgets.VBox(children=button_contains)
        bottom_contains = [self._search_results_widget, button_container,
                           self._added_word_widget]
        bottom_container = widgets.HBox(children=bottom_contains)

        self._container = widgets.VBox(children=[search_container,
                                                 bottom_container])
        self._api_url = 'http://data.bioontology.org/'
        self._key = bioportal_api_key
        self._headers = {'Authorization': 'apikey token=' + self._key}
    def __init__(self,
                 apiKey,
                 rdir=None,
                 procedures=None,
                 anatomy=None,
                 finding=None,
                 fmodifier=None,
                 diagnosis=None,
                 dmodifier=None):
        if not rdir:
            rdir = "."
        self._rdir = rdir

        if not procedures:
            raise ValueError("Must provide at least one procedure ontology")
        if not anatomy:
            raise ValueError("Must provide at least one anatomy ontology")
        if not finding:
            raise ValueError("Must provide at leat one finding ontology")
        if not fmodifier:
            raise VaueError(
                "Must provide at least one finding modifier ontology")
        if not diagnosis:
            raise ValueError("Must provide at least one diagnosis ontology")
        if not dmodifier:
            raise ValueError(
                "Must provide at least one diagnosis modifier ontology")

        self._report = defaultdict(list)
        self.report = ipw.HTML()

        self.date = ipw.DatePicker(description="Procedure Data",
                                   value=datetime.datetime.today().date())
        self.date.observe(self.render_report)

        self.provider = ipw.Text(description="Provider")
        self.date.observe(self.render_report)

        self.addProc = ipw.Button(description='Add Procedure', )
        self.addProc.on_click(self.add_proc)
        self.remProc = ipw.Button(description='Remove Procedure', )
        self.remProc.on_click(self.rem_proc)
        procBox = ipw.HBox([self.addProc, self.remProc])
        self.procs = ConceptSelector('Procedure',
                                     procedures,
                                     bioportal_api_key=apiKey)
        # findings
        self.addFinding = ipw.Button(description='Add Finding')
        self.addFinding.on_click(self.add_finding)
        self.remFinding = ipw.Button(description='Remove Finding')
        self.remFinding.on_click(self.rem_finding)
        findBox = ipw.HBox([self.addFinding, self.remFinding])
        self.findings = RadFinding(apiKey,
                                   anatomy=anatomy,
                                   finding=finding,
                                   modifier=fmodifier)
        # diagnosis
        self.addDiagnosis = ipw.Button(description='Add Diagnosis')
        self.addDiagnosis.on_click(self.add_diagnosis)
        self.remDiagnosis = ipw.Button(description='Remove Diagnosis')
        self.remDiagnosis.on_click(self.rem_diagnosis)
        diagBox = ipw.HBox([self.addDiagnosis, self.remDiagnosis])
        # signature
        self.diagnosis = RadDiagnosis(apiKey,
                                      diagnosis=diagnosis,
                                      modifier=dmodifier)
        self.create = ipw.Button(description='Create Report')
        self.create.on_click(self.create_report)
        super(RadiologyReport,
              self).__init__(children=[
                  ipw.VBox([
                      ipw.HBox([self.date, self.provider]),
                      ipw.VBox([procBox, self.procs],
                               layout=ipw.Layout(border="solid")),
                      ipw.VBox([findBox, self.findings],
                               layout=ipw.Layout(border="dashed")),
                      ipw.VBox([diagBox, self.diagnosis],
                               layout=ipw.Layout(border="solid")), self.create
                  ],
                           layout=ipw.Layout(width="50%")), self.report
              ],
                             layout=ipw.Layout(border="solid"))
Пример #25
0
 def __init__(self, name, value, **kwargs):
     self.dd = widgets.Text(value=value)
     FormValue.__init__(self, name, **kwargs)
Пример #26
0
def glimpseUI(out, DEFAULTS):
    """
    Glimpse command layout.
    """
    layout = inputBox()
    layout.add_child(
        "dataset",
        widgets.Text(
            value=DEFAULTS["dataset"],
            description="Dataset name",
            style={"description_width": "initial"},
        ),
    )
    layout.add_child(
        "P",
        widgets.BoundedIntText(
            value=DEFAULTS["P"],
            min=5,
            max=50,
            description="AOI image size",
            style={"description_width": "initial"},
        ),
    )
    layout.add_child(
        "offset_x",
        widgets.IntText(
            value=DEFAULTS["offset-x"],
            description="Offset region top-left corner (x-axis)",
            style={"description_width": "initial"},
        ),
    )
    layout.add_child(
        "offset_y",
        widgets.IntText(
            value=DEFAULTS["offset-y"],
            description="Offset region top-left corner (y-axis)",
            style={"description_width": "initial"},
        ),
    )
    layout.add_child(
        "offset_P",
        widgets.IntText(
            value=DEFAULTS["offset-P"],
            description="Offset region size",
            style={"description_width": "initial"},
        ),
    )
    layout.add_child(
        "bin_size",
        widgets.BoundedIntText(
            value=DEFAULTS["bin-size"],
            min=1,
            max=21,
            step=2,
            description="Offset histogram bin size (odd number)",
            style={"description_width": "initial"},
        ),
    )
    layout.add_child(
        "frame_range",
        widgets.Checkbox(
            value=DEFAULTS["frame-range"],
            description="Specify frame range?",
            indent=False,
        ),
    )
    layout.add_child(
        "frame_start",
        widgets.IntText(
            value=DEFAULTS["frame-start"],
            description="Starting frame",
            style={"description_width": "initial"},
        ),
        hide=not DEFAULTS["frame-range"],
    )
    layout.add_child(
        "frame_end",
        widgets.IntText(
            value=DEFAULTS["frame-end"],
            description="Ending frame",
            style={"description_width": "initial"},
        ),
        hide=not DEFAULTS["frame-range"],
    )
    layout.add_child(
        "use_offtarget",
        widgets.Checkbox(
            value=DEFAULTS["use-offtarget"],
            description="Use off-target AOI locations?",
            indent=False,
        ),
    )
    layout.add_child(
        "num_channels",
        widgets.BoundedIntText(
            value=DEFAULTS["num-channels"],
            min=1,
            max=4,
            step=1,
            description="Number of color channels",
            style={"description_width": "initial"},
        ),
    )
    layout.add_child("channels", widgets.Tab())
    channelUI(
        layout["num_channels"].value,
        layout["channels"],
        layout["use_offtarget"],
        DEFAULTS,
    )
    layout.add_child("extract_aois", widgets.Button(description="Extract AOIs"))
    # Callbacks
    layout["num_channels"].observe(
        partial(
            channelUI,
            channelTabs=layout["channels"],
            useOfftarget=layout["use_offtarget"],
            DEFAULTS=DEFAULTS,
        ),
        names="value",
    )
    layout["use_offtarget"].observe(
        partial(toggleUseOffTarget, channelTabs=layout["channels"]),
        names="value",
    )
    layout["extract_aois"].on_click(partial(glimpseCmd, layout=layout, out=out))
    layout["frame_range"].observe(
        partial(layout.toggle_hide, names=("frame_start", "frame_end")),
        names="value",
    )
    return layout
Пример #27
0
    def on_button_validate_path_clicked(b):
        """
        Validate the path of the script folder. Open selection for the script.
        """

        if not os.path.exists(w_path_to_dir.value):
            print(PN._RED+"Wrong folder name."+PN._RESET)
            print("")
            return

        # Pass the current value of the directory to the default one
        expt.path_to_dir = w_path_to_dir.value

        # Define the list of log files in the log directory
        list_scripts_files = [file for file in sorted(os.listdir(expt.path_to_dir)) if '.ipy' in file][::-1]

        if len(list_scripts_files) < 1:
            print(PN._RED+"There is no script in this folder."+PN._RESET)
            print("")
            return                

        # Widget to select script
        w_select_script = widgets.Dropdown(
             options=list_scripts_files,
             value=list_scripts_files[-1],
             layout=widgets.Layout(width='300px'),
             style={'description_width': 'Script:'})

        def on_button_insert_script_clicked(b):
            """
            Display a script in a markdown cell.
            Add scan numbers if asked.
            """ 

            # Get and insert the script
            path_to_dir = w_path_to_dir.value
            script_name = w_select_script.value
            text_file = open(path_to_dir+script_name)
            
            # Import original script
            script_init = text_file.read()
            
            # Split the different lines
            script_split = script_init.split('\n')
            
            # Replace the empty strings with \n
            script_split = ['\n'  if elem=='' else elem for elem in script_split]
            
            
            # Check if the value of first script is a number
            # If not, do not add the counting
            
            if np.char.isnumeric(w_index_first_scan.value):

                
                ###################################
                # Add scan number
                ###################################

                # List of names which triggers an increment of the scan number
                list_trig = ['cont_regh', 'scan']

                count = int(w_index_first_scan.value)

                is_loop = False
                for i in range(len(script_split)):

                    if is_loop:

                        # Fist run on the loop to collect info
                        loop_length = 0
                        nb_scan_in_loop = 0
                        is_first_run = True
                        for k in range(i,len(script_split)):
                            if is_first_run: 
                                if any(match in script_split[k] for match in ['    ','\t','\n']):
                                    loop_length +=1
                                    if any(elem in script_split[k] for elem in list_trig):
                                        nb_scan_in_loop+=1
                                else:
                                    is_first_run = False

                        # Attribute the scan numbers
                        for j in range(repet_nb-1):
                            for k in range(i,i+loop_length):
                                if any(elem in script_split[k] for elem in list_trig):
                                        script_split[k] = script_split[k]+' #'+str(count)
                                        count+=1

                        is_loop = False

                    # Detect a loop
                    if ('in range' in script_split[i]):
                        repet_nb = int(''.join([str(s) for s in script_split[i] if s.isdigit()]))
                        is_loop = True

                    # Regular scan not in a loop
                    if any(elem in script_split[i] for elem in list_trig):
                        script_split[i] = script_split[i]+' #'+str(count)
                        count+=1

                ##################################
            
            
            # Put back the empty strings by replacing \n with ''
            script_split = [''  if elem=='\n' else elem for elem in script_split]
            
            # Re-create the script with added scan numbers
            script_modif ='\n'.join(script_split)
            
            text_file.close()
            
            
            code = '```python\n'+script_modif+'```'

            Utils.Create_cell(code='### '+ script_name, position ='above', celltype='markdown', is_print=True)
            Utils.Create_cell(code=code, position ='above', celltype='markdown', is_print=True)
            
            Utils.Delete_current_cell()
        
            Utils.Create_cell(code='FE.Action.Choose(expt)',
                        position ='at_bottom', celltype='code', is_print=False)  

        
        # Get number of the first scan
        w_index_first_scan = widgets.Text(value='',
                                             style = {'description_width': 'initial'},
                                             layout = widgets.Layout(width='200px'),
                                             description='Index first scan')
        

        button_insert_script = widgets.Button(description="Insert script")
        button_insert_script.on_click(on_button_insert_script_clicked)

        display(widgets.HBox([w_select_script, w_index_first_scan, button_insert_script]))
Пример #28
0
        prng_seed.disabled = False
    else:
        prng_seed.disabled = True
    
toggle_prng.observe(toggle_prng_cb)

#prng_row = widgets.HBox([toggle_prng, prng_seed])

#----- Output ------
# TODO: this changes when running on nanoHUB (= $RESULTSDIR)
output_dir_str = os.getenv('RESULTSDIR') + "/pc4nanobio/"
# output_dir_str = 'output'  # match the "value" of the widget below

# NOTE: not used anymore
output_dir = widgets.Text(
#     value='output',
    description='Output Dir',
)
def config_output_dir_cb(w):
    global output_dir_str
    output_dir_str = w.value
    print(output_dir_str)
    
output_dir.on_submit(config_output_dir_cb)

toggle_svg = widgets.Checkbox(
    description='SVG',
    layout = Layout(width = constWidth),
)
svg_t0 = widgets.BoundedFloatText (
    min=0,
    description='$T_0$',
Пример #29
0
def preProcessingInterface(video_dropdown, json_dropdown, data_dropdown,
                           frame_n):
    persons = wg.RadioButtons(options=['Biggest', 'Unsorted', 'All'],
                              value='Biggest',
                              rows=3,
                              description='Choose:',
                              disabled=False)

    custom = wg.BoundedIntText(value=0,
                               min=0,
                               max=10,
                               step=1,
                               description='Person:',
                               disabled=False,
                               layout=wg.Layout(display='flex',
                                                flex_flow='line',
                                                align_items='flex-start',
                                                justify_content='flex-start',
                                                width='90%'))

    joint_pose = wg.RadioButtons(
        options=['Sagittal Left', 'Sagittal Right', 'Whole Body'],
        value='Sagittal Left',
        rows=4,
        description='Pose: ',
        disabled=False,
        layout=wg.Layout(display='flex', flex_flow='line', width='90%'))

    frame_slider = wg.IntSlider()

    preprocess_vid = wg.Button(description='Pre Process Video')

    paf_score_th = wg.FloatText(value=0.1,
                                step=0.1,
                                description='PAF Thres:',
                                layout=wg.Layout(display='flex',
                                                 flex_flow='line',
                                                 align_items='flex-start',
                                                 justify_content='flex-start',
                                                 width='90%'))
    conf_th = wg.FloatText(value=0.7,
                           step=0.1,
                           description='Conf. Thres:',
                           layout=wg.Layout(display='flex',
                                            flex_flow='line',
                                            align_items='flex-start',
                                            justify_content='flex-start',
                                            width='90%'))
    n_interp_samples = wg.IntText(value=10,
                                  description='Samples Interpolated:',
                                  layout=wg.Layout(
                                      display='flex',
                                      flex_flow='line',
                                      align_items='flex-start',
                                      justify_content='flex-start',
                                      width='90%'))
    joint_n = wg.Dropdown(options=keypoints_mapping,
                          value='Nose',
                          description='Joint:',
                          disabled=False)
    threshold = wg.FloatText(value=0.1,
                             step=0.1,
                             description='Threshold:',
                             layout=wg.Layout(display='flex',
                                              flex_flow='line',
                                              align_items='flex-start',
                                              justify_content='flex-start',
                                              width='80%'))
    alpha = wg.FloatText(value=0.6,
                         step=0.1,
                         description='Transparency:',
                         layout=wg.Layout(display='flex',
                                          flex_flow='line',
                                          align_items='flex-start',
                                          justify_content='flex-start',
                                          width='80%'))
    show_point = wg.Checkbox(value=False,
                             description='Show Point',
                             disabled=False,
                             layout=wg.Layout(display='flex',
                                              flex_flow='line',
                                              align_items='flex-start',
                                              justify_content='flex-start',
                                              width='80%'))
    binary = wg.Checkbox(value=False,
                         description='Binary',
                         disabled=False,
                         layout=wg.Layout(display='flex',
                                          flex_flow='line',
                                          align_items='flex-start',
                                          justify_content='flex-start',
                                          width='80%'))

    wg.jslink((frame_n, 'value'), (frame_slider, 'value'))

    show_heatmap = wg.ToggleButtons(
        options=['Keypoints', 'Heatmap'],
        value='Keypoints',
        disabled=False,
        button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        tooltips=['Show keypoints', 'Show heatmap'],
        #     icons=['check'] * 3
    )

    summary = wg.Textarea(value='',
                          placeholder='description',
                          description='Summary:',
                          disabled=False)

    output_name = wg.Text(value='',
                          placeholder='File output name',
                          description='Output:',
                          disabled=False)

    def onPreProcessClicked(b):
        if (video_dropdown.value == "None"):
            print("Choose a video")
            return

        video_path = videos_dir + video_dropdown.value
        video_name = (video_dropdown.value).split(sep='.')[0]

        file_dir = data_dir + video_name + '/'
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)

        files_list = os.listdir(file_dir)
        json_list = ["None"]
        for names in files_list:
            if names.endswith(".json"):
                json_list.append(names)
        mp4_list = ["None"]
        for names in files_list:
            if names.endswith(".mp4"):
                mp4_list.append(names)
        data_list = ["None"]
        for names in files_list:
            if names.endswith(".data"):
                data_list.append(names)
        json_dropdown.options = json_list
        mp4_dropdown.options = mp4_list
        data_dropdown.options = data_list

        saveJointFile(video_dropdown.value, json_dropdown.value,
                      output_name.value, threshold.value,
                      n_interp_samples.value, paf_score_th.value,
                      conf_th.value, summary.value)

    preprocess_vid.on_click(onPreProcessClicked)

    ht_vbox_1 = wg.VBox([joint_n, show_point, alpha, binary, threshold],
                        layout=wg.Layout(display='flex',
                                         flex_flow='line',
                                         align_items='flex-start',
                                         justify_content='flex-start'))

    hbox_play = wg.HBox([video_dropdown, json_dropdown, frame_n, frame_slider])
    vbox_params = wg.VBox([paf_score_th, conf_th, n_interp_samples])
    vbox_per = wg.VBox([persons, custom, joint_pose],
                       layout=wg.Layout(display='flex',
                                        flex_flow='column',
                                        align_items='flex-start',
                                        justify_content='flex-start'))

    def preprocessView(show_heatmap, video_name, file_name, persons, custom,
                       joint_pose, joint_n, alpha, binary, threshold,
                       n_interp_samples, paf_score_th, conf_th, frame_n,
                       show_point):
        if (show_heatmap == 'Keypoints'):
            keypointsFromJSON(video_name, file_name, persons, custom,
                              joint_pose, threshold, n_interp_samples,
                              paf_score_th, conf_th, frame_n)
        else:
            heatmapFromJSON(video_name, file_name,
                            keypoints_mapping.index(joint_n), threshold, alpha,
                            binary, n_interp_samples, paf_score_th, conf_th,
                            frame_n, show_point)

    out_res = wg.interactive_output(
        preprocessView, {
            "show_heatmap": show_heatmap,
            "video_name": video_dropdown,
            "file_name": json_dropdown,
            "persons": persons,
            "custom": custom,
            "joint_pose": joint_pose,
            "joint_n": joint_n,
            "alpha": alpha,
            "binary": binary,
            "threshold": threshold,
            "n_interp_samples": n_interp_samples,
            "paf_score_th": paf_score_th,
            "conf_th": conf_th,
            "frame_n": frame_n,
            "show_point": show_point
        })

    tabs = ['Choose Person', 'Heatmap', 'PAF Parameters']
    children = []
    children.append(vbox_per)
    children.append(ht_vbox_1)
    children.append(vbox_params)
    tab = wg.Tab()
    tab.children = children
    for i in range(len(children)):
        tab.set_title(i, tabs[i])

    hbox_out = wg.HBox([output_name, summary, preprocess_vid])
    vbox_res = wg.VBox([show_heatmap, tab])
    hbox_res = wg.HBox([out_res, vbox_res])
    vbox_vid = wg.VBox([hbox_play, hbox_res, hbox_out])

    return vbox_vid
Пример #30
0
def tajima_moving_widget():

    style = {'description_width': '350px'}
    layout = Layout(width='55%')

    a = widgets.Text(value='casea-moving-24.txt',
                     description='Template Input File:',
                     style=style,
                     layout=layout)
    b = widgets.Text(value='case1-moving.txt',
                     description='New Output File:',
                     style=style,
                     layout=layout)
    c = widgets.BoundedFloatText(value=0.0001,
                                 min=0.0,
                                 max=2.0,
                                 description='v_e/c:',
                                 style=style,
                                 layout=layout)
    d = widgets.FloatText(value=1.0,
                          description='a0:',
                          style=style,
                          layout=layout)
    e = widgets.BoundedFloatText(value=10.0,
                                 min=0,
                                 max=30,
                                 description='omega0:',
                                 style=style,
                                 layout=layout)
    f = widgets.BoundedFloatText(value=3.14,
                                 min=0,
                                 max=100,
                                 description='t_flat:',
                                 style=style,
                                 layout=layout)
    g = widgets.BoundedFloatText(value=0,
                                 min=0,
                                 max=100,
                                 description='t_rise:',
                                 style=style,
                                 layout=layout)
    h = widgets.BoundedFloatText(value=0,
                                 min=0,
                                 max=100,
                                 description='t_fall:',
                                 style=style,
                                 layout=layout)
    xmaxw = widgets.FloatText(value=24,
                              description='xmax:',
                              style=style,
                              layout=layout)
    ndumpw = widgets.IntText(value=2,
                             description='ndump:',
                             style=style,
                             layout=layout)
    ppc = widgets.IntText(value=10,
                          description='Particles per cell:',
                          style=style,
                          layout=layout)
    tmaxw = widgets.FloatText(value=200,
                              description='tmax:',
                              style=style,
                              layout=layout)

    im_moving = interact_calc(newifile2,
                              iname=a,
                              oname=b,
                              uth=c,
                              a0=d,
                              omega0=e,
                              t_flat=f,
                              t_rise=g,
                              t_fall=h,
                              xmax=xmaxw,
                              ndump=ndumpw,
                              ppc=ppc,
                              tmax=tmaxw)
    im_moving.widget.manual_button.layout.width = '250px'