Exemplo n.º 1
0
    def _initialize_window(self, parent, wxid):
        """ Initialize the window with the specified Id. """

        window = parent.FindWindowById(wxid)
        sizer = wx.BoxSizer(wx.VERTICAL)
        window.SetSizer(sizer)
        window.SetAutoLayout(True)

        window.SetBackgroundColour('white')
        window.SetWindowStyleFlag(wx.CLIP_CHILDREN)
        window.Refresh()
        image = ImageResource('closed_folder_24x24')
        bitmap = image.create_image().ConvertToBitmap()

        image_widget = ImageWidget(window, bitmap=bitmap)
        image_widget.control.SetBackgroundColour('white')
        sizer.Add(image_widget.control, 0, wx.EXPAND)

        text = wx.StaticText(window, -1, "Blah", style=wx.ALIGN_CENTRE)
        sizer.Add(text, 0, wx.EXPAND)

        # Resize the window to match the sizer's minimum size.
        sizer.Fit(window)

        return
Exemplo n.º 2
0
    def image_resource ( self, image_name ):
        """ Returns the ImageResource object for the specified **image_name**.
        """
        # Get the name of the image file:
        volume_name, file_name = split_image_name( image_name )

        if self.is_zip_file:
            # See if we already have the image file cached in the file system:
            cache_file = self._check_cache( file_name )
            if cache_file is None:
                # If not cached, then create a zip file reference:
                ref = ZipFileReference(
                          resource_factory = resource_manager.resource_factory,
                          zip_file         = self.zip_file,
                          path             = self.path,
                          volume_name      = self.name,
                          file_name        = file_name )
            else:
                # Otherwise, create a cache file reference:
                ref = ImageReference( resource_manager.resource_factory,
                                      filename = cache_file )
        else:
            # Otherwise, create a normal file reference:
            ref = ImageReference( resource_manager.resource_factory,
                                  filename = join( self.path, file_name ) )

        # Create the ImageResource object using the reference (note that the
        # ImageResource class will not allow us to specify the reference in the
        # constructor):
        resource = ImageResource( file_name )
        resource._ref = ref

        # Return the ImageResource:
        return resource
Exemplo n.º 3
0
    def __init__(self, parent, tool_bar, image_cache, item, controller,
                 show_labels):
        """ Creates a new tool bar tool for an action item. """

        self.item = item
        self.tool_bar = tool_bar

        # Create an appropriate tool depending on the style of the action.
        action  = self.item.action

        # If the action has an image then convert it to a bitmap (as required
        # by the toolbar).
        if action.image is not None:
            image = action.image.create_image()
            path = action.image.absolute_path
            bmp  = image_cache.get_bitmap(path)

        else:
            from pyface.api import ImageResource
            image = ImageResource('foo')
            bmp  = image.create_bitmap()

        self.control_id = 1
        self.control = None
        if controller is not None:
            self.controller = controller
            controller.add_to_toolbar(self)

        return
Exemplo n.º 4
0
 def _get_image ( self ):
     path, name = split( self.file_name )
     if splitext( name )[1] in ( '.png', '.gif', '.jpg', '.jpeg' ):
         image = ImageResource( name, search_path = [ path ] )
     else:
         image = ImageResource( 'unknown' )
     self._cur_image = image.create_image()
     return image
Exemplo n.º 5
0
 def show_minibuffer(self, minibuffer, **kwargs):
     # minibuffer_pane_info is stored in the TaskWindow instance because all
     # tasks use the same minibuffer pane in the AUI manager
     try:
         info = self.window.minibuffer_pane_info
     except AttributeError:
         panel = wx.Panel(self.window.control, style=wx.NO_BORDER)
         sizer = wx.BoxSizer(wx.HORIZONTAL)
         close_image = ImageResource('cancel')
         bmp = close_image.create_bitmap()
         close = wx.BitmapButton(panel, -1, bmp, size=(bmp.GetWidth()+10, bmp.GetHeight()+10), style=wx.NO_BORDER)
         close.Bind(wx.EVT_BUTTON, self.on_hide_minibuffer_or_cancel)
         sizer.Add(close, 0, wx.EXPAND)
         panel.SetSizer(sizer)
         info = self.create_minibuffer_info()
         self.window._aui_manager.AddPane(panel, info)
         # info.window is set to panel in the AUI code
         self.window.minibuffer_pane_info = info
     repeat = False
     if info.minibuffer is not None:
         if info.minibuffer.is_repeat(minibuffer):
             log.debug("Reusing old minibuffer control: %s" % info.minibuffer.control)
             repeat = True
         else:
             log.debug("Removing old minibuffer control: %s" % info.minibuffer.control)
             info.window.GetSizer().Hide(0)
             info.window.GetSizer().Remove(0)
             info.minibuffer.destroy_control()
             log.debug("Children: %s" % info.window.GetSizer().Children)
     if not repeat:
         minibuffer.create_control(info.window)
         info.window.GetSizer().Insert(0, minibuffer.control, 1, wx.EXPAND)
         info.window.GetSizer().Layout()
         minibuffer.focus()
         info.minibuffer = minibuffer
         log.debug("Window: %s, info: %s" % (self.window, info))
     else:
         info.minibuffer.focus()
         info.minibuffer.repeat(minibuffer)  # Include new minibuffer
     if not info.IsShown():
         info.Show()
         self.window._aui_manager.Update()
Exemplo n.º 6
0
class ExampleTask(Task):
    """ A simple task for opening a blank editor.
    """

    #### Task interface #######################################################

    id = 'example.example_task'
    name = 'Multi-Tab Editor'

    active_editor = Property(Instance(IEditor),
                             depends_on='editor_area.active_editor')

    editor_area = Instance(IEditorAreaPane)

    menu_bar = SMenuBar(
        SMenu(TaskAction(name='New', method='new', accelerator='Ctrl+N'),
              id='File',
              name='&File'),
        SMenu(DockPaneToggleGroup(),
              TaskToggleGroup(),
              id='View',
              name='&View'))

    tool_bars = [
        SToolBar(TaskAction(method='new',
                            tooltip='New file',
                            image=ImageResource('document_new')),
                 image_size=(32, 32)),
    ]

    ###########################################################################
    # 'Task' interface.
    ###########################################################################

    def _default_layout_default(self):
        return TaskLayout(top=PaneItem('steps.example_pane'))

    def create_central_pane(self):
        """ Create the central pane: the script editor.
        """
        self.editor_area = EditorAreaPane()
        return self.editor_area

    def create_dock_panes(self):
        """ Create the file browser and connect to its double click event.
        """
        pane = ExamplePane()
        return [pane]

    ###########################################################################
    # 'ExampleTask' interface.
    ###########################################################################

    def new(self):
        """ Opens a new empty window
        """
        editor = Editor()
        self.editor_area.add_editor(editor)
        self.editor_area.activate_editor(editor)
        self.activated()

    #### Trait property getter/setters ########################################

    def _get_active_editor(self):
        if self.editor_area is not None:
            return self.editor_area.active_editor
        return None
Exemplo n.º 7
0
 def get_icon(self):
     return ImageResource('logicle')
Exemplo n.º 8
0
 def get_icon(self):
     return ImageResource('bead_calibration')
Exemplo n.º 9
0
 def get_icon(self):
     return ImageResource('bleedthrough_piecewise')
Exemplo n.º 10
0
 def get_icon(self):
     return ImageResource('radviz')
Exemplo n.º 11
0
class NodeType(HasPrivateTraits):
    """ The base class for all node types. """

    # The default image used to represent nodes that DO NOT allow children.
    DOCUMENT = ImageResource("document")

    # The default image used to represent nodes that allow children and are NOT
    # expanded.
    CLOSED_FOLDER = ImageResource("closed_folder")

    # The default image used to represent nodes that allow children and ARE
    # expanded.
    OPEN_FOLDER = ImageResource("open_folder")

    # 'NodeType' interface -------------------------------------------------

    # The node manager that the type belongs to.
    node_manager = Instance("pyface.tree.node_manager.NodeManager")

    # The image used to represent nodes that DO NOT allow children.
    image = Image(DOCUMENT)

    # The image used to represent nodes that allow children and are NOT
    # expanded.
    closed_image = Image(CLOSED_FOLDER)

    # The image used to represent nodes that allow children and ARE expanded.
    open_image = Image(OPEN_FOLDER)

    # The default actions/groups/menus available on nodes of this type (shown
    # on the context menu).
    actions = Any  # List

    # The default action for nodes of this type.  The default action is
    # performed when a node is activated (i.e., double-clicked).
    default_action = Instance(Action)

    # The default actions/groups/menus for creating new children within nodes
    # of this type (shown in the 'New' menu of the context menu).
    new_actions = Any  # List

    # ------------------------------------------------------------------------
    # 'NodeType' interface.
    # ------------------------------------------------------------------------

    # These methods are specific to the 'NodeType' interface ---------------

    def is_type_for(self, node):
        """ Returns True if a node is deemed to be of this type. """

        raise NotImplementedError()

    def allows_children(self, node):
        """ Does the node allow children (ie. a folder vs a file). """

        return False

    def get_actions(self, node):
        """ Returns the node-specific actions for a node. """

        return self.actions

    def get_context_menu(self, node):
        """ Returns the context menu for a node. """

        sat = Group(id="SystemActionsTop")
        nsa = Group(id="NodeSpecificActions")
        sab = Group(id="SystemActionsBottom")

        # The 'New' menu.
        new_actions = self.get_new_actions(node)
        if new_actions is not None and len(new_actions) > 0:
            sat.append(MenuManager(name="New", *new_actions))

        # Node-specific actions.
        actions = self.get_actions(node)
        if actions is not None and len(actions) > 0:
            for item in actions:
                nsa.append(item)

        # System actions (actions available on ALL nodes).
        system_actions = self.node_manager.system_actions
        if len(system_actions) > 0:
            for item in system_actions:
                sab.append(item)

        context_menu = MenuManager(sat, nsa, sab)
        context_menu.dump()

        return context_menu

    def get_copy_value(self, node):
        """ Get the value that is copied for a node.

        By default, returns the node itself.

        """

        return node

    def get_default_action(self, node):
        """ Returns the default action for a node. """

        return self.default_action

    def get_new_actions(self, node):
        """ Returns the new actions for a node. """

        return self.new_actions

    def get_paste_value(self, node):
        """ Get the value that is pasted for a node.

        By default, returns the node itself.

        """

        return node

    def get_monitor(self, node):
        """ Returns a monitor that detects changes to a node.

        Returns None by default,  which indicates that the node is not
        monitored.

        """

        return None

    # These methods are exactly the same as the 'TreeModel' interface -----#

    def has_children(self, node):
        """ Returns True if a node has children, otherwise False.

        You only need to implement this method if children are allowed for the
        node (ie. 'allows_children' returns True).

        """

        return False

    def get_children(self, node):
        """ Returns the children of a node.

        You only need to implement this method if children are allowed for the
        node.

        """

        raise NotImplementedError()

    def get_drag_value(self, node):
        """ Get the value that is dragged for a node.

        By default, returns the node itself.

        """

        return node

    def can_drop(self, node, data):
        """ Returns True if a node allows an object to be dropped onto it. """

        return False

    def drop(self, obj, data):
        """ Drops an object onto a node. """

        raise NotImplementedError()

    def get_image(self, node, selected, expanded):
        """ Returns the label image for a node. """

        if self.allows_children(node):
            if expanded:
                order = ["open_image", "closed_image", "image"]
                default = self.OPEN_FOLDER

            else:
                order = ["closed_image", "open_image", "image"]
                default = self.CLOSED_FOLDER

        else:
            order = ["image", "open_image", "closed_image"]
            default = self.DOCUMENT

        # Use the search order to look for a trait that is NOT None.
        for name in order:
            image = getattr(self, name)
            if image is not None:
                break

        # If no such trait is found then use the default image.
        else:
            image = default

        return image

    def get_selection_value(self, node):
        """ Get the value that is used when a node is selected.

        By default the selection value is the node itself.

        """

        return node

    def get_text(self, node):
        """ Returns the label text for a node. """

        return str(node)

    def can_set_text(self, node, text):
        """ Returns True if the node's label can be set. """

        return len(text.strip()) > 0

    def set_text(self, node, text):
        """ Sets the label text for a node. """

        pass

    def is_collapsible(self, node):
        """ Returns True if the node is collapsible, otherwise False. """

        return True

    def is_draggable(self, node):
        """ Returns True if the node is draggablee, otherwise False. """

        return True

    def can_rename(self, node):
        """ Returns True if the node can be renamed, otherwise False. """

        return False

    def is_editable(self, node):
        """ Returns True if the node is editable, otherwise False.

        If the node is editable, its text can be set via the UI.

        DEPRECATED: Use 'can_rename'.

        """

        return self.can_rename(node)

    def is_expandable(self, node):
        """ Returns True if the node is expandanble, otherwise False. """

        return True
Exemplo n.º 12
0
 def get_icon(self):
     return ImageResource('parallel_coords')
Exemplo n.º 13
0
def get_image_resource(name):
    path = os.path.dirname(os.path.abspath(__file__))
    return ImageResource(name=name, search_path=[path])
Exemplo n.º 14
0
class MATSCalibDamageFn(MATSExplore):
    '''
    Fitting algorithm for the damage function of the
    quasi-ductile anisotropic material model.

    The algorithm uses the TLoop instance to proceed step
    by step with the computation. The value of the damage function
    for the time step t_n is identified iteratively by adjusting
    the values and evaluating the corresponding equilibrated stresses.

    The control parameters of the algorithm are:

    @param step_size: time step for fitting the damage parameter.
    @param tmax: end time for fitting, it might be also be set implicitly
    for integrity = 1 - full damage of the material.
    '''

    # store the fitted 'PhiFn' in the data base, i.e. 'CCSUniteCell'
    store_fitted_phi_fn = Bool(True)

    # default settings are overloaded with settings specified in 'ec_config'

    max_eps = Property(Float)

    def _get_max_eps(self):
        # return 0.007  # set explicit value when calibration is aborted (mean
        # value of strain)
        return self.mfn_line_array_target.xdata[-1]

    n_steps = Int(1)

    log = Bool(False)

    # TLine parameter
    #
    KMAX = Int
    tolerance = Float
    RESETMAX = Float

    step_size = Property(Float, depends_on='max_eps,n_steps')

    @cached_property
    def _get_step_size(self):
        print('step_size = ', self.max_eps / self.n_steps)
        return self.max_eps / self.n_steps

    def run_through(self):
        '''Run the computation without fitting from the start to the end
        '''
        self.tloop.tline.max = self.tmax
        self.tloop.tline.step = self.step_size
        self.tloop.eval()
        print('ending time', self.tloop.t_n1)
        # show the response

    def run_step_by_step(self):
        '''Run the computation step by step from the start to the end
        '''
        n_steps = int(self.tmax / self.step_size)
        self.tloop.tline.step = self.step_size
        current_time = 0.
        tmax = 0.
        for i in range(n_steps):
            print('STEP', i)
            self.run_one_step()

    def run_trial_step(self):
        '''Run the computation one step starting from the
        current time t_n to iterate the value for phi_new
        which gives a fit with macroscopic stress curve.
        NOTE: The trial step does not update 'U_n' or 't_n'!
        '''
        if self.log:
            print('--------- run trial step: --------- ')
        if len(self.tloop.U_n) == 0:
            current_U_n = self.tloop.tstepper.new_cntl_var()
            print('U_n = None: tloop.tstepper.new_cntl_var()',
                  self.tloop.tstepper.new_cntl_var())
        else:
            current_U_n = self.tloop.U_n[:]
        current_time = self.tloop.t_n
        self.run_one_step()

        # reset the current time back
        self.tloop.t_n = current_time
        self.tloop.U_n[:] = current_U_n[:]
        if self.log:
            print('--------- end of trial step --------- ')

        self.tloop.tstepper.sctx.update_state_on = False

    def run_one_step(self):
        '''Run the computation one step starting from the
        current time t_n with the iterated value for phi_new
        in order to update TLoop and save the new phi value in
        the array ydata of PhiFnGeneral
        NOTE: The calculated step does update 'U_n' or 't_n'!
        '''
        self.tloop.tline.step = self.step_size
        current_time = self.tloop.t_n
        tmax = current_time + self.step_size
        self.tloop.tline.max = tmax
        self.tloop.eval()
        self.update_e_max_value_new = True

    #--------------------------------------------------
    # Data source for calibration within simdb
    #--------------------------------------------------

    ex_run = Instance(ExRun)

    composite_tensile_test = Property

    def _get_composite_tensile_test(self):
        return self.ex_run.ex_type

    composite_cross_section = Property

    def _get_composite_cross_section(self):
        return self.composite_tensile_test.ccs

    def get_target_data_exdb_tensile_test(self):
        '''Use the data from the ExDB
        '''
        ctt = self.composite_tensile_test

        # save 'sig_eps_arr' in directory "/simdb/simdata/mats_calib_damage_fn"
        simdata_dir = os.path.join(simdb.simdata_dir, 'mats_calib_damage_fn')
        if os.path.isdir(simdata_dir) == False:
            os.makedirs(simdata_dir)
        ctt_key = str(self.composite_tensile_test.key)
        filename = os.path.join(simdata_dir, 'eps-sig-arr_' + ctt_key + '.csv')

        xdata, ydata = ctt.eps_c_interpolated_smoothed[:, None], \
            ctt.sig_c_interpolated_smoothed[:, None]
        eps_sig_arr = np.hstack([xdata, ydata])
        print('eps_sig_arr')
        np.savetxt(filename, eps_sig_arr, delimiter=';')
        print('eps-sig-data saved to file %s' % (filename))

        # smoothed data without jumps with interpolated starting point in the
        # origin
        return ctt.eps_c_interpolated_smoothed, ctt.sig_c_interpolated_smoothed
#        return ctt.eps_c_interpolated, ctt.sig_c_interpolated  # original data without jumps with interpolated starting point in the origin
#        return ctt.eps_ironed, ctt.sig_c_ironed  # original data without smoothing (without jumps)
#        return ctt.eps_smooth, ctt.sig_c_smooth #smoothed data

#--------------------------------------------------
# interpolation function for fitting data:
#--------------------------------------------------

    mfn_line_array_target = Property(Instance(MFnLineArray),
                                     depends_on='ex_run')

    @cached_property
    def _get_mfn_line_array_target(self):
        xdata, ydata = self.get_target_data_exdb_tensile_test()
        print('xdata[-1]', xdata[-1])
        return MFnLineArray(xdata=xdata, ydata=ydata)

    fitted_phi_fn = Instance(MFnLineArray)

    #---------------------------------------------------------------
    # PLOT OBJECT
    #-------------------------------------------------------------------
    figure = Instance(Figure)

    def _figure_default(self):
        figure = Figure(facecolor='white')
        figure.add_axes([0.12, 0.13, 0.85, 0.74])
        return figure

    data_changed = Event

    def init(self):
        #--------------------------------------------------
        # for fitting use 'General'-function for 'phi_fn':
        #--------------------------------------------------
        # The value pair for the piecewise linear definition
        # of 'phi_fn' value consists of current strain and the
        # iterated 'phi_value'. The microplanes with a lower
        # microplane strain level use an interpolated value
        # for 'phi'
        self.fitted_phi_fn = self.dim.mats_eval.phi_fn.mfn
        self.fitted_phi_fn.xdata = [0]
        self.fitted_phi_fn.ydata = [1]
        self.fitted_phi_fn.data_changed = True
        # initialize TLoop parameters:
        self.tloop.setup()
        self.tloop.tstepper.sctx.mats_state_array[:] = 0.0
        self.tloop.U_n[:] = 0.0
        self.tloop.rtrace_mngr.clear()
        self.tloop.verbose_iteration = False
        self.tloop.verbose_load_step = False
        self.tloop.verbose_time = False
        # set TLine parameters
        self.tloop.tline.KMAX = self.KMAX
        self.tloop.tline.tolerance = self.tolerance
        self.tloop.tline.RESETMAX = self.RESETMAX

    # store trial step data in the lists if trial steps are to be stored
    # for the plotting method 'plot_trail_steps'
    #
    rec_trial_steps = True
    phi_trial_list_i = []
    sig_trial_list_i = []
    phi_trial_list_n = []
    sig_trial_list_n = []

    def get_lack_of_fit(self, phi_trial):
        '''Return the difference between the macroscopic stress calculated
        based on the value of phi_trial (damage at the next step) and the
        macroscopic stress defined as target data (=fitting curve)
        '''
        if self.log:
            print('\n')
            print("#'get_lack_of_fit' for the trial value # START")
            print('    phi_trial    = ', phi_trial)

        # value of the principle macroscopic strain corresponds to control
        # variable
        current_time = self.tloop.t_n

        if self.log:
            print('    current_time = ', current_time)
            print('    step_size    = ', self.step_size)

        # ------------------------------------
        # add new pair in fitted_phi_fn
        # ------------------------------------
        # consisting of 'e_max_value_new' and 'phi_trial'
        x = np.hstack(
            [self.fitted_phi_fn.xdata[:], current_time + self.step_size])
        y = np.hstack([self.fitted_phi_fn.ydata[:], phi_trial])
        self.fitted_phi_fn.set(xdata=x, ydata=y)
        self.fitted_phi_fn.data_changed = True

        # ------------------------------------
        # get state array before trial:
        # ------------------------------------
        mats_state_array_old = copy(self.tloop.tstepper.sctx.mats_state_array)

        # ------------------------------------
        # run trial step:
        # ------------------------------------
        if self.log:
            print('    reset current_U_n   =', self.tloop.U_n)
            print('CURRENT PHI', self.dim.mats_eval.phi_fn.mfn.ydata)
        # try the next equilibrium
        self.run_trial_step()

        # ------------------------------------
        # reset mats_state_array:
        # ------------------------------------
        # Note: the material state array (i.e. the maximum microstrains) are
        # updated within the iterations of each trial step, therefore a reset
        # is necessary in order to start each trial step with the same state
        # variables
        self.tloop.tstepper.sctx.mats_state_array[:] = mats_state_array_old[:]
        if self.log:
            print('    reset state array')

        # ------------------------------------
        # remove trial value in fitted_phi_fn
        # ------------------------------------
        x = self.fitted_phi_fn.xdata[:-1]
        y = self.fitted_phi_fn.ydata[:-1]
        self.fitted_phi_fn.set(xdata=x, ydata=y)
        self.fitted_phi_fn.data_changed = True

        # ------------------------------------
        # get the lack of fit
        # ------------------------------------
        # get calculated value for 'sig_app' based on the current value of 'phi_trial':
        # and evaluate the difference between the obtained stress and the
        # measured response
        self.tloop.rtrace_mngr.rtrace_bound_list[0].redraw()
        sig_app_trial = self.tloop.rtrace_mngr.rtrace_bound_list[
            0].trace.ydata[-1]
        # get corresponding value from the target data:
        sig_app_target = self.mfn_line_array_target.get_value(current_time +
                                                              self.step_size)
        # absolut error:
        lack_of_fit_absolut = sig_app_trial - sig_app_target
        # relative error:
        lack_of_fit_relative = lack_of_fit_absolut / sig_app_target

        if self.log:
            print('    sig_app_trial ', sig_app_trial)
            print('    sig_app_target', sig_app_target)
            print('    lack_of_fit_absolute  ', lack_of_fit_absolut)
            print('    lack_of_fit_relative  ', lack_of_fit_relative)
            print('# get_lack_of_fit # END ')

        if self.rec_trial_steps:
            # store all trial values of 'phi_trail' and 'sig_app_trail' within each iteration to a global list
            #
            self.phi_trial_list_i.append(phi_trial)
            self.sig_trial_list_i.append(sig_app_trial)

        return lack_of_fit_relative

    param_key = Str('')

    phi_max_factor = Float(1.0)

    xtol = Float(1e-6, label='lack-of-fit tolerance')

    def fit_response(self):
        '''iterate phi_trial in each incremental step such that the
        lack of fit between the calculated stress and the target
        curve is smaller then xtol defined in function 'brentq'.
        NOTE: the method 'get_lack_of_fit' returns the relative error.
        '''

        self.tloop.reset()

        phi_old = 1.0

        # map the array dimensions to the plot axes
        #
        figure = self.figure

        axes = figure.axes[0]

        print('n_steps', self.n_steps)
        for n in range(self.n_steps):

            axes.clear()

            phi_new = phi_old

            # use scipy-functionality to get the iterated value of phi_new
            # If the trial value calculated with phi_trial = phi_old
            # is smaller then target value get_lack_of_fit has no sign change
            # for phi_trial = phi_old and phi_trial = 0. which is a requirement
            # for the function call 'brentq'. In this case the old value
            # for phi_trial is used and tloop moves on one step
            try:
                # The method brentq has optional arguments such as
                #   'xtol'    - absolut error (default value = 1.0e-12)
                #   'rtol'    - relative error (not supported at the time)
                #   'maxiter' - maximum numbers of iterations used
                #
                # Here xtol is used to specify the allowed RELATIVE error!
                # therefore the relative lack of fit is returned in
                # method 'get_lack_of_fit'
                _xtol = self.xtol
                phi_max = min(1.0, phi_old * self.phi_max_factor)
                phi_min = phi_old * 0.2  # 0.0  # phi_old * 0.3
                phi_new = brentq(self.get_lack_of_fit,
                                 phi_min,
                                 phi_max,
                                 xtol=_xtol)
                # @todo: check if 'brenth' gives better fitting results; faster?
                #                phi_new = brenth( self.get_lack_of_fit, 0., phi_old )
                print('(#) n = ', n, phi_new, phi_max, phi_old,
                      phi_old - phi_new)
            except ValueError:

                if self.log:
                    lof_0 = self.get_lack_of_fit(0.)
                    lof_phi_old = self.get_lack_of_fit(phi_old)
                    print('No sign change between get_lack_of_fit(phi_old) = ',
                          lof_phi_old, ' and ')
                    print('get_lack_of_fit(0.) = ', lof_0)
                    print('Use old value for phi_trial. phi_old = ', phi_old)
                else:
                    print('(!) n = ', n, phi_new, phi_max, phi_old,
                          phi_old - phi_new)
                    phi_new = phi_old

            # current time corresponds to the current strain applied
            #
            current_time = self.tloop.t_n

            # replace old 'phi_value' with iterated value:
            #
            phi_old = phi_new

            # get mats_state_array:
            #            mats_state_array = copy(self.tloop.tstepper.sctx.mats_state_array)

            # update phi_data:
            #
            x = np.hstack(
                [self.fitted_phi_fn.xdata[:], current_time + self.step_size])
            y = np.hstack([self.fitted_phi_fn.ydata[:], phi_new])

            axes.plot(x, y, color='blue', linewidth=2)
            self.data_changed = True

            self.fitted_phi_fn.set(xdata=x, ydata=y)
            self.fitted_phi_fn.data_changed = True

            # run one step with the iterated value for phi in order to
            # update the state array and to move forward one step:
            if self.log:
                print('\n')
                print('### run_one_step ###')
                print('### step', n, '###')
                print('### current time:', current_time)

            if self.rec_trial_steps:
                # add entries of the iterations ('i') in the current step ('n')
                # (yields a list of lists)
                #
                self.phi_trial_list_n.append(self.phi_trial_list_i)
                self.sig_trial_list_n.append(self.sig_trial_list_i)
                # delete the entries of the iterations ('i') in the last step ('n')
                # and fill it with the iterations of the next step ('n+1')
                #
                self.phi_trial_list_i = []
                self.sig_trial_list_i = []

            self.run_one_step()


#            print '(g%)' %(n)

        self.fitted_phi_fn.changed = True

    def store(self):
        mats_key = self.dim.mats_eval.__class__.__name__
        ctt_key = str(self.composite_tensile_test.key)
        if self.store_fitted_phi_fn:
            print(
                "stored 'fitted_phi_fn' in CCSUnitCell with material model %s and calibration test %s"
                % (mats_key, ctt_key))
            print('ctt_key + self.param_key', ctt_key + self.param_key)
            self.composite_cross_section.set_param(
                mats_key,
                ctt_key + self.param_key,
                # self.composite_cross_section.set_param(mats_key,
                # ctt_key,
                copy(self.fitted_phi_fn))
            # save 'sig_eps_arr' in directory
            # "/simdb/simdata/mats_calib_damage_fn"
            simdata_dir = os.path.join(simdb.simdata_dir,
                                       'mats_calib_damage_fn')
            if os.path.isdir(simdata_dir) == False:
                os.makedirs(simdata_dir)
            ctt_key = str(self.composite_tensile_test.key)
            filename = os.path.join(
                simdata_dir,
                'eps-phi-arr_' + ctt_key + self.param_key + '.csv')

            xdata, ydata = self.fitted_phi_fn.xdata[:,
                                                    None], self.fitted_phi_fn.ydata[:,
                                                                                    None]
            eps_phi_arr = np.hstack([xdata, ydata])
            np.savetxt(filename, eps_phi_arr, delimiter=';')
            print('eps-phi-data saved to file %s' % (filename))

    format_ticks = Bool(False)

    def plot_trial_steps(self):
        '''Plot target (sig-eps-curve of the tensile test) and trial curves
        and corresponding phi function together with trail steps from the iteration process.
        NOTE: the global variable 'rec_trial_steps' must be set to 'True' in order to store the iteration values
              within the global variables 'phi_trial_list_n' and 'sig_trial_list_n'
        n - index of the time steps to be considered
        i - index of the iteration steps performed in order to fit the target curve
        '''
        #-------------------------------------------------------------------
        # configure the style of the font to be used for labels and ticks
        #-------------------------------------------------------------------
        #
        from matplotlib.font_manager import FontProperties
        font = FontProperties()
        #        font.serif         : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman
        #        font.sans-serif    : Helvetica, Avant Garde, Computer Modern Sans serif
        #        font.cursive       : Zapf Chancery
        #        font.monospace     : Courier, Computer Modern Typewriter
        font.set_name('Script MT')
        # name = ['Times New Roman', 'Helvetica', 'Script MT'] #?
        font.set_family('serif')
        # family = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
        font.set_style('normal')
        # style  = ['normal', 'italic', 'oblique']
        font.set_size('small')
        # size  = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '11']
        font.set_variant('normal')
        # variant= ['normal', 'small-caps']
        font.set_weight('medium')
        # weight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']

        #-------------------------------------------------------------------

        p.figure(facecolor='white', dpi=600,
                 figsize=(8, 6))  # white background

        # time list corresponding to the specified numbers of steps and step size
        #
        step_list = [n * self.step_size for n in range(self.n_steps + 1)]

        # get list of lists containing the trial values of 'sig_app' and 'phi_trail'
        # the lists are defined as global variables of 'MATSCalibDamageFn' and are filled
        # within the iteration process when the method 'get_lack_of_fit" is called
        #
        phi_trial_list_n = [[1.]] + self.phi_trial_list_n
        sig_trial_list_n = [[0.]] + self.sig_trial_list_n

        xrange = 10.  # plotting range for strain [mm/m]
        yrange = 15.  # plotting range for stress [MPa]

        for n in range(self.n_steps):
            for i in range(len(phi_trial_list_n[n + 1])):
                x = np.array([step_list[n], step_list[n + 1]])
                eps = 1000. * x  # plot strains in permil on the x-axis
                #--------------------------------------
                # sig-eps trial
                #--------------------------------------
                # plot the numerically calculated sig-eps-curve (tensile test)
                # (with trial steps)
                #
                sig_trail = np.array(
                    [sig_trial_list_n[n][-1], sig_trial_list_n[n + 1][i]])
                p.subplot(222)
                p.plot(eps, sig_trail, color='k', linewidth=1)
                p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
                p.ylabel('stress $\sigma$ [MPa]', fontproperties=font)
                if self.format_ticks:
                    # format ticks for plot
                    p.axis([0, xrange, 0., yrange], fontproperties=font)
                    locs, labels = p.xticks()
                    p.xticks(locs, ["%.0f" % x for x in locs],
                             fontproperties=font)
                    locs, labels = p.yticks()
                    p.yticks(locs, ["%.0f" % x for x in locs],
                             fontproperties=font)

                #--------------------------------------
                # phi_trail
                #--------------------------------------
                # plot the fitted phi-function
                # (with trial steps)
                #
                p.subplot(224)
                phi_trail = np.array(
                    [phi_trial_list_n[n][-1], phi_trial_list_n[n + 1][i]])
                p.plot(eps, phi_trail, color='k', linewidth=1)
                p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
                p.ylabel('integrity $\phi$ [-]', fontproperties=font)
                if self.format_ticks:
                    # format ticks for plot
                    p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
                    p.axis([0, xrange, 0., 1.])
                    locs, labels = p.xticks()
                    p.xticks(locs, ["%.0f" % x for x in locs],
                             fontproperties=font)
                    locs, labels = p.yticks()
                    p.yticks(locs, ["%.1f" % x for x in locs],
                             fontproperties=font)

        #--------------------------------------
        # sig-eps target
        #--------------------------------------
        # plot the sig-eps-target curve (tensile test)
        #
        p.subplot(221)
        eps = 1000. * self.mfn_line_array_target.xdata[:-1]
        sig_target = self.mfn_line_array_target.ydata[:-1]
        p.plot(eps, sig_target, color='black', linewidth=1)
        p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
        p.ylabel('stress $\sigma$ [MPa]', fontproperties=font)
        if self.format_ticks:
            # format ticks for plot
            p.axis([0, xrange, 0., yrange])
            locs, labels = p.xticks()
            p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font)
            locs, labels = p.yticks()
            p.yticks(locs, ["%.0f" % x for x in locs], fontproperties=font)

        #--------------------------------------
        # phi_trail (final)
        #--------------------------------------
        # plot the corresponding fitted phi-function
        # (without trial steps)
        #
        p.subplot(223)
        eps = 1000. * self.fitted_phi_fn.xdata[:-1]
        phi_fn = self.fitted_phi_fn.ydata[:-1]
        p.plot(eps, phi_fn, color='black', linewidth=1)
        p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
        p.ylabel('integrity $\phi$ [-]', fontproperties=font)
        if self.format_ticks:
            # format ticks for plot
            p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
            p.axis([0, xrange, 0., 1.])
            locs, labels = p.xticks()
            p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font)
            locs, labels = p.yticks()
            p.yticks(locs, ["%.1f" % x for x in locs], fontproperties=font)

        # save figure with calibration process in directory
        # "/simdb/simdata/lcc_table/output_images/save_fig_to_file.png"
        simdata_dir = os.path.join(simdb.simdata_dir, 'mats_calib_damage_fn')
        if os.path.isdir(simdata_dir) == False:
            os.makedirs(simdata_dir)

        ctt_key = self.test_key
        filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.pdf')
        p.savefig(filename)
        print('plot_trail_steps.png saved to file %s' % (filename))
        filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.png')
        p.savefig(filename, dpi=600)
        print('plot_trail_steps.png saved to file %s' % (filename))

        p.show()

    test_key = Property

    def _get_test_key(self):
        return str(self.composite_tensile_test.key)

    #-------------------------------------------------------------------------
    # User interaction
    #-------------------------------------------------------------------------
    toolbar = ToolBar(Action(
        name="Run Calibration",
        tooltip='Run damage function calibration for the current parameters',
        image=ImageResource('kt-start'),
        action="run_calibration"),
                      image_size=(22, 22),
                      show_tool_names=False,
                      show_divider=True,
                      name='calibration_toolbar')

    traits_view = View(
        HSplit(
            Item('ex_run@', show_label=False),
            VSplit(
                Item('dim@',
                     id='mats_calib_damage_fn.run.split',
                     dock='tab',
                     resizable=True,
                     label='experiment run',
                     show_label=False),
                id='mats_calib_damage_fn.mode_plot_data.vsplit',
                dock='tab',
            ),
            VSplit(
                Group(
                    Item('figure',
                         editor=MPLFigureEditor(),
                         resizable=True,
                         show_label=False),
                    id='mats_calib_damage_fn.plot_sheet',
                    label='fitted damage function',
                    dock='tab',
                ),
                id='mats_calib_damage_fn.plot.vsplit',
                dock='tab',
            ),
            id='mats_calib_damage_fn.hsplit',
            dock='tab',
        ),
        #                        menubar = self.default_menubar(),
        resizable=True,
        toolbar=toolbar,
        handler=MATSCalibDamageFnController(),
        title='Simvisage: damage function calibration',
        id='mats_calib_damage_fn',
        dock='tab',
        buttons=[OKButton, CancelButton],
        height=0.8,
        width=0.8)
Exemplo n.º 15
0
 def get_icon(self):
     return ImageResource('gauss_2d')
Exemplo n.º 16
0
 def get_icon(self):
     return ImageResource('bar_chart')
Exemplo n.º 17
0
 def get_icon(self):
     return ImageResource('scatterplot')
 def _menu_bar_default(self):
     menu_bar = SMenuBar(
         SMenu(SMenu(SGroup(
             TaskAction(name='New Simulation',
                        method='new_simulation_from_datasource',
                        image=ImageResource('office-chart-pie')),
             TaskAction(name='New Simulation from Experiment',
                        method='new_simulation_from_experiments',
                        image=ImageResource('kchart'),
                        accelerator='Ctrl+N'),
             id='NewSimulationGroup',
             name='NewSimulationGroup',
         ),
                     id='NewMenu',
                     name='&New Simulation'),
               SGroup(TaskAction(name='Save Project',
                                 accelerator='Ctrl+S',
                                 method='save',
                                 image=ImageResource('document-save')),
                      TaskAction(name='Save Project As...',
                                 accelerator='Ctrl+Shift+S',
                                 method='save_request',
                                 image=ImageResource('document-save-as')),
                      id='SaveGroup',
                      name='SaveGroup'),
               SGroup(
                   TaskAction(name='Save User Data',
                              method='save_user_ds',
                              image=ImageResource('drive-harddisk')),
                   TaskAction(name='Export User Data As...',
                              method='request_export_user_ds',
                              image=ImageResource('document-import')),
                   id='SaveUserDataGroup',
                   name='SaveUserDataGroup',
               ),
               SGroup(
                   TaskWindowAction(
                       name='Close',
                       accelerator='Ctrl+W',
                       method='close',
                   ),
                   id='CloseGroup',
                   name='CloseGroup',
               ),
               id='File',
               name='&File'), SMenu(id='Edit', name='&Edit'),
         SMenu(DockPaneToggleGroup(), id='View', name='&View'),
         SMenu(
             SGroup(
                 TaskAction(name='Parameter Explorer',
                            accelerator='Ctrl+Shift+N',
                            method='new_simulation_grid',
                            enabled_name='simulations_exist'),
                 TaskAction(name='Parameter Optimizer',
                            accelerator='Ctrl+Shift+M',
                            method='new_optimizer',
                            enabled_name='experiments_and_sim_exist'),
                 id='ParamExplorationGroup',
                 name='ParamExplorationGroup',
             ),
             SGroup(
                 TaskAction(name='Run Simulations',
                            method='run_simulations',
                            accelerator='Ctrl+R',
                            enabled_name='simulations_exist',
                            image=ImageResource('arrow-right')),
                 TaskAction(name='Run Simulation Group',
                            method='run_simulation_groups',
                            accelerator='Ctrl+Shift+R',
                            enabled_name='simulation_groups_exist',
                            image=ImageResource('arrow-right-double')),
                 id='RunSimulationGroup',
                 name='RunSimulationGroup',
             ),
             SGroup(
                 TaskAction(name='Plot Chomatogram(s)',
                            method='new_model_calibration_plot',
                            accelerator='Ctrl+P',
                            image=ImageResource('office-chart-line')),
                 TaskAction(name='Particle data animation',
                            method='new_animation_plot'),
                 id='PlotsGroup',
                 name='PlotsGroup',
             ),
             SGroup(
                 TaskAction(name=STRIP_TOOL_NAME,
                            method='open_strip_fraction_editor',
                            enabled_name='_strip_component_exist'),
                 id='ConfigurationGroup',
                 name='ConfigurationGroup',
             ),
             SGroup(TaskAction(name='Custom Python script...',
                               accelerator='Ctrl+I',
                               method='request_run_python_script',
                               tooltip='Modify the current project with '
                               'custom script.',
                               image=ImageResource('text-x-python')),
                    TaskAction(name='Interactive Python console...',
                               accelerator='Ctrl+J',
                               tooltip="(Jupyter) Python console to "
                               "interactively explore Reveal's code "
                               "and develop new tools/scripts.",
                               method='request_launch_python_console',
                               image=ImageResource('ipython_icon')),
                    id='RunPythonGroup',
                    name='RunPythonGroup'),
             id='Tools',
             name='&Tools',
         ), SMenu(id='Help', name='&Help'))
     return menu_bar
Exemplo n.º 19
0
 class MyDocumentedItem(DocumentedItem):
     add = ToolbarButton('%s' % name, orientation='horizontal',
                     image=ImageResource('add.ico'))
Exemplo n.º 20
0
class DiffusionPipeline(Pipeline):
    now = datetime.datetime.now().strftime("%Y%m%d_%H%M")
    pipeline_name = Str("diffusion_pipeline")
    #input_folders = ['DSI','DTI','HARDI','T1','T2']
    input_folders = ['anat', 'dwi']
    process_type = Str
    diffusion_imaging_model = Str
    subject = Str
    subject_directory = Directory
    derivatives_directory = Directory
    ordered_stage_list = [
        'Preprocessing', 'Registration', 'Diffusion', 'Connectome'
    ]  # ,'MRTrixConnectome']

    parcellation_scheme = Str
    atlas_info = Dict()

    global_conf = Global_Configuration()

    view_mode = Enum('config_view', ['config_view', 'inspect_outputs_view'])

    preprocessing = Button('Preprocessing')
    #preprocessing.setIcon(QIcon(QPixmap("preprocessing.png")))

    diffusion = Button('Diffusion')
    #diffusion.setIcon(QIcon(QPixmap("diffusion.png")))

    registration = Button('Registration')
    #registration.setIcon(QIcon(QPixmap("registration.png")))

    connectome = Button('Connectome')
    #connectome.setIcon(QIcon(QPixmap("connectome.png")))

    config_file = Str

    pipeline_group = VGroup(HGroup(spring,
                                   UItem('preprocessing',
                                         style='custom',
                                         width=450,
                                         height=130,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('preprocessing'),
                                             'label':
                                             ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('registration',
                                         style='custom',
                                         width=500,
                                         height=110,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('registration'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('diffusion',
                                         style='custom',
                                         width=450,
                                         height=240,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('diffusion'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('connectome',
                                         style='custom',
                                         width=450,
                                         height=130,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('connectome'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            spring,
                            springy=True)

    def __init__(self, project_info):
        self.stages = {
            'Preprocessing': PreprocessingStage(),
            'Registration': RegistrationStage(pipeline_mode="Diffusion"),
            'Diffusion': DiffusionStage(),
            'Connectome': ConnectomeStage()
        }
        Pipeline.__init__(self, project_info)

        self.diffusion_imaging_model = project_info.diffusion_imaging_model
        self.subject = project_info.subject

        self.global_conf.subjects = project_info.subjects
        self.global_conf.subject = self.subject

        if len(project_info.subject_sessions) > 0:
            self.global_conf.subject_session = project_info.subject_session
            self.subject_directory = os.path.join(self.base_directory,
                                                  self.subject,
                                                  project_info.subject_session)
        else:
            self.global_conf.subject_session = ''
            self.subject_directory = os.path.join(self.base_directory,
                                                  self.subject)

        self.derivatives_directory = os.path.join(self.base_directory,
                                                  'derivatives')

        self.stages['Connectome'].config.subject = self.subject
        self.stages['Connectome'].config.on_trait_change(
            self.update_vizualization_layout, 'circular_layout')
        self.stages['Connectome'].config.on_trait_change(
            self.update_vizualization_logscale, 'log_visualization')
        self.stages['Diffusion'].config.on_trait_change(
            self.update_outputs_recon, 'recon_processing_tool')
        self.stages['Diffusion'].config.on_trait_change(
            self.update_outputs_tracking, 'tracking_processing_tool')
        # self.anat_flow = anat_flow

    def update_outputs_recon(self, new):
        self.stages['Diffusion'].define_inspect_outputs()

    def update_outputs_tracking(self, new):
        self.stages['Diffusion'].define_inspect_outputs()

    def update_vizualization_layout(self, new):
        self.stages['Connectome'].define_inspect_outputs()
        self.stages['Connectome'].config.subject = self.subject

    def update_vizualization_logscale(self, new):
        self.stages['Connectome'].define_inspect_outputs()
        self.stages['Connectome'].config.subject = self.subject

    def _subject_changed(self, new):
        self.stages['Connectome'].config.subject = new

    def _diffusion_imaging_model_changed(self, new):
        print "diffusion model changed"
        self.stages['Diffusion'].config.diffusion_imaging_model = new

    def check_config(self):
        if self.stages['Connectome'].config.output_types == []:
            return (
                '\n\tNo output type selected for the connectivity matrices.\t\n\tPlease select at least one output type in the connectome configuration window.\t\n'
            )
        return ''

    def _preprocessing_fired(self, info):
        self.stages['Preprocessing'].configure_traits(view=self.view_mode)

    def _diffusion_fired(self, info):
        self.stages['Diffusion'].configure_traits(view=self.view_mode)

    def _registration_fired(self, info):
        self.stages['Registration'].configure_traits(view=self.view_mode)

    def _connectome_fired(self, info):
        # self.stages['MRTrixConnectome'].configure_traits()
        self.stages['Connectome'].configure_traits(view=self.view_mode)

    def _atlas_info_changed(self, new):
        print "Atlas info changed : "
        print new

    def check_input1(self, gui=True):
        print '**** Check Inputs  ****'
        diffusion_available = False
        bvecs_available = False
        bvals_available = False
        t1_available = False
        t2_available = False
        valid_inputs = False

        dwi_file = os.path.join(self.subject_directory, 'dwi',
                                self.subject + '_dwi.nii.gz')
        bval_file = os.path.join(self.subject_directory, 'dwi',
                                 self.subject + '_dwi.bval')
        bvec_file = os.path.join(self.subject_directory, 'dwi',
                                 self.subject + '_dwi.bvec')
        T1_file = os.path.join(self.subject_directory, 'anat',
                               self.subject + '_T1w.nii.gz')
        T2_file = os.path.join(self.subject_directory, 'anat',
                               self.subject + '_T2w.nii.gz')

        print "Looking for...."
        print "dwi_file : %s" % dwi_file
        print "bvecs_file : %s" % bvec_file
        print "bvals_file : %s" % bval_file
        print "T1_file : %s" % T1_file
        print "T2_file : %s" % T2_file

        try:
            layout = BIDSLayout(self.base_directory)
            print "Valid BIDS dataset with %s subjects" % len(
                layout.get_subjects())
            for subj in layout.get_subjects():
                self.global_conf.subjects.append('sub-' + str(subj))
            # self.global_conf.subjects = ['sub-'+str(subj) for subj in layout.get_subjects()]
            self.global_conf.modalities = [
                str(mod) for mod in layout.get_modalities()
            ]
            # mods = layout.get_modalities()
            types = layout.get_types()
            # print "Available modalities :"
            # for mod in mods:
            #     print "-%s" % mod

            for typ in types:
                if typ == 'dwi' and os.path.isfile(dwi_file):
                    print "%s available" % typ
                    diffusion_available = True

                if typ == 'T1w' and os.path.isfile(T1_file):
                    print "%s available" % typ
                    t1_available = True

                if typ == 'T2w' and os.path.isfile(T2_file):
                    print "%s available" % typ
                    t2_available = True
        except:
            error(
                message=
                "Invalid BIDS dataset. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)
            return

        if os.path.isfile(bval_file): bvals_available = True

        if os.path.isfile(bvec_file): bvecs_available = True

        mem = Memory(base_dir=os.path.join(self.derivatives_directory, 'cmp',
                                           self.subject, 'tmp', 'nipype'))
        swap_and_reorient = mem.cache(SwapAndReorient)

        if diffusion_available:
            if bvals_available and bvecs_available:
                self.stages[
                    'Diffusion'].config.diffusion_imaging_model_choices = self.diffusion_imaging_model

                #Copy diffusion data to derivatives / cmp  / subject / dwi
                out_dwi_file = os.path.join(self.derivatives_directory, 'cmp',
                                            self.subject, 'dwi',
                                            self.subject + '_dwi.nii.gz')
                out_bval_file = os.path.join(self.derivatives_directory, 'cmp',
                                             self.subject, 'dwi',
                                             self.subject + '_dwi.bval')
                out_bvec_file = os.path.join(self.derivatives_directory, 'cmp',
                                             self.subject, 'dwi',
                                             self.subject + '_dwi.bvec')

                shutil.copy(src=dwi_file, dst=out_dwi_file)
                shutil.copy(src=bvec_file, dst=out_bvec_file)
                shutil.copy(src=bval_file, dst=out_bval_file)

                if t2_available:
                    print "Swap and reorient T2"
                    swap_and_reorient(
                        src_file=os.path.join(self.subject_directory, 'anat',
                                              self.subject + '_T2w.nii.gz'),
                        ref_file=os.path.join(self.subject_directory, 'dwi',
                                              self.subject + '_dwi.nii.gz'),
                        out_file=os.path.join(self.derivatives_directory,
                                              'cmp', self.subject, 'anat',
                                              self.subject + '_T2w.nii.gz'))
                if t1_available:
                    swap_and_reorient(
                        src_file=os.path.join(self.subject_directory, 'anat',
                                              self.subject + '_T1w.nii.gz'),
                        ref_file=os.path.join(self.subject_directory, 'dwi',
                                              self.subject + '_dwi.nii.gz'),
                        out_file=os.path.join(self.derivatives_directory,
                                              'cmp', self.subject, 'anat',
                                              self.subject + '_T1w.nii.gz'))
                    valid_inputs = True
                    input_message = 'Inputs check finished successfully.\nDiffusion and morphological data available.'
                else:
                    input_message = 'Error during inputs check.\nMorphological data (T1) not available.'
            else:
                input_message = 'Error during inputs check.\nDiffusion bvec or bval files not available.'
        elif t1_available:
            input_message = 'Error during inputs check. \nDiffusion data not available (DSI/DTI/HARDI).'
        else:
            input_message = 'Error during inputs check. No diffusion or morphological data available in folder ' + os.path.join(
                self.base_directory, 'RAWDATA') + '!'

        #diffusion_imaging_model = diffusion_imaging_model[0]

        if gui:
            #input_notification = Check_Input_Notification(message=input_message, diffusion_imaging_model_options=diffusion_imaging_model,diffusion_imaging_model=diffusion_imaging_model)
            #input_notification.configure_traits()
            print input_message
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model
            # diffusion_file = os.path.join(self.subject_directory,'dwi',self.subject+'_dwi.nii.gz')
            # n_vol = nib.load(diffusion_file).shape[3]
            # if self.stages['Preprocessing'].config.end_vol == 0 or self.stages['Preprocessing'].config.end_vol == self.stages['Preprocessing'].config.max_vol or self.stages['Preprocessing'].config.end_vol >= n_vol-1:
            #     self.stages['Preprocessing'].config.end_vol = n_vol-1
            # self.stages['Preprocessing'].config.max_vol = n_vol-1
            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model
        else:
            print input_message
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model
            # diffusion_file = os.path.join(self.subject_directory,'dwi',self.subject+'_dwi.nii.gz')
            # n_vol = nib.load(diffusion_file).shape[3]
            # if self.stages['Preprocessing'].config.end_vol == 0 or self.stages['Preprocessing'].config.end_vol == self.stages['Preprocessing'].config.max_vol or self.stages['Preprocessing'].config.end_vol >= n_vol-1:
            #     self.stages['Preprocessing'].config.end_vol = n_vol-1
            # self.stages['Preprocessing'].config.max_vol = n_vol-1
            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model

        if t2_available:
            self.stages['Registration'].config.registration_mode_trait = [
                'Linear + Non-linear (FSL)'
            ]  #,'BBregister (FS)','Nonlinear (FSL)']

        if (t1_available and diffusion_available):
            valid_inputs = True
        else:
            print "Missing required inputs."
            error(
                message=
                "Missing required inputs. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)

        for stage in self.stages.values():
            if stage.enabled:
                print stage.name
                print stage.stage_dir

        self.fill_stages_outputs()

        return valid_inputs

    def check_input(self, layout, gui=True):
        print '**** Check Inputs  ****'
        diffusion_available = False
        bvecs_available = False
        bvals_available = False
        valid_inputs = False

        if self.global_conf.subject_session == '':
            subject = self.subject
        else:
            subject = "_".join(
                (self.subject, self.global_conf.subject_session))

        dwi_file = os.path.join(self.subject_directory, 'dwi',
                                subject + '_dwi.nii.gz')
        bval_file = os.path.join(self.subject_directory, 'dwi',
                                 subject + '_dwi.bval')
        bvec_file = os.path.join(self.subject_directory, 'dwi',
                                 subject + '_dwi.bvec')

        subjid = self.subject.split("-")[1]

        try:
            layout = BIDSLayout(self.base_directory)
            print "Valid BIDS dataset with %s subjects" % len(
                layout.get_subjects())
            for subj in layout.get_subjects():
                self.global_conf.subjects.append('sub-' + str(subj))
            # self.global_conf.subjects = ['sub-'+str(subj) for subj in layout.get_subjects()]
            self.global_conf.modalities = [
                str(mod) for mod in layout.get_modalities()
            ]
            # mods = layout.get_modalities()
            types = layout.get_types()
            # print "Available modalities :"
            # for mod in mods:
            #     print "-%s" % mod

            if self.global_conf.subject_session == '':

                files = layout.get(subject=subjid,
                                   type='dwi',
                                   extensions='.nii.gz')
                if len(files) > 0:
                    dwi_file = files[0].filename
                    print dwi_file
                else:
                    error(message="Diffusion image not found for subject %s." %
                          (subjid),
                          title="Error",
                          buttons=['OK', 'Cancel'],
                          parent=None)
                    return

                files = layout.get(subject=subjid,
                                   type='dwi',
                                   extensions='.bval')
                if len(files) > 0:
                    bval_file = files[0].filename
                    print bval_file
                else:
                    error(
                        message="Diffusion bval image not found for subject %s."
                        % (subjid),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   type='dwi',
                                   extensions='.bvec')
                if len(files) > 0:
                    bvec_file = files[0].filename
                    print bvec_file
                else:
                    error(
                        message="Diffusion bvec image not found for subject %s."
                        % (subjid),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return
            else:
                sessid = self.global_conf.subject_session.split("-")[1]

                files = layout.get(subject=subjid,
                                   type='dwi',
                                   extensions='.nii.gz',
                                   session=sessid)
                if len(files) > 0:
                    dwi_file = files[0].filename
                    print dwi_file
                else:
                    error(
                        message=
                        "Diffusion image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   type='dwi',
                                   extensions='.bval',
                                   session=sessid)
                if len(files) > 0:
                    bval_file = files[0].filename
                    print bval_file
                else:
                    error(
                        message=
                        "Diffusion bval image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   type='dwi',
                                   extensions='.bvec',
                                   session=sessid)
                if len(files) > 0:
                    bvec_file = files[0].filename
                    print bvec_file
                else:
                    error(
                        message=
                        "Diffusion bvec image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

            print "Looking for...."
            print "dwi_file : %s" % dwi_file
            print "bvecs_file : %s" % bvec_file
            print "bvals_file : %s" % bval_file

            for typ in types:
                if typ == 'dwi' and os.path.isfile(dwi_file):
                    print "%s available" % typ
                    diffusion_available = True

        except:
            error(
                message=
                "Invalid BIDS dataset. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)
            return

        if os.path.isfile(bval_file): bvals_available = True

        if os.path.isfile(bvec_file): bvecs_available = True

        if diffusion_available:
            if bvals_available and bvecs_available:
                self.stages[
                    'Diffusion'].config.diffusion_imaging_model_choices = self.diffusion_imaging_model

                #Copy diffusion data to derivatives / cmp  / subject / dwi
                if self.global_conf.subject_session == '':
                    out_dwi_file = os.path.join(self.derivatives_directory,
                                                'cmp', self.subject, 'dwi',
                                                subject + '_dwi.nii.gz')
                    out_bval_file = os.path.join(self.derivatives_directory,
                                                 'cmp', self.subject, 'dwi',
                                                 subject + '_dwi.bval')
                    out_bvec_file = os.path.join(self.derivatives_directory,
                                                 'cmp', self.subject, 'dwi',
                                                 subject + '_dwi.bvec')
                else:
                    out_dwi_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.nii.gz')
                    out_bval_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.bval')
                    out_bvec_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.bvec')

                if not os.path.isfile(out_dwi_file):
                    shutil.copy(src=dwi_file, dst=out_dwi_file)
                if not os.path.isfile(out_bvec_file):
                    shutil.copy(src=bvec_file, dst=out_bvec_file)
                if not os.path.isfile(out_bval_file):
                    shutil.copy(src=bval_file, dst=out_bval_file)

                valid_inputs = True
                input_message = 'Inputs check finished successfully.\nDiffusion and morphological data available.'
            else:
                input_message = 'Error during inputs check.\nDiffusion bvec or bval files not available.'
        else:
            if self.global_conf.subject_session == '':
                input_message = 'Error during inputs check. No diffusion data available in folder ' + os.path.join(
                    self.base_directory, self.subject, 'dwi') + '!'
            else:
                input_message = 'Error during inputs check. No diffusion data available in folder ' + os.path.join(
                    self.base_directory, self.subject,
                    self.global_conf.subject_session, 'dwi') + '!'
        #diffusion_imaging_model = diffusion_imaging_model[0]

        if gui:
            #input_notification = Check_Input_Notification(message=input_message, diffusion_imaging_model_options=diffusion_imaging_model,diffusion_imaging_model=diffusion_imaging_model)
            #input_notification.configure_traits()
            print input_message
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model

            # if diffusion_available:
            #     n_vol = nib.load(dwi_file).shape[3]
            #     if self.stages['Preprocessing'].config.end_vol == 0 or self.stages['Preprocessing'].config.end_vol == self.stages['Preprocessing'].config.max_vol or self.stages['Preprocessing'].config.end_vol >= n_vol-1:
            #         self.stages['Preprocessing'].config.end_vol = n_vol-1
            #     self.stages['Preprocessing'].config.max_vol = n_vol-1

            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model
        else:
            print input_message
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model

            # if diffusion_available:
            #     n_vol = nib.load(dwi_file).shape[3]
            #     if self.stages['Preprocessing'].config.end_vol == 0 or self.stages['Preprocessing'].config.end_vol == self.stages['Preprocessing'].config.max_vol or self.stages['Preprocessing'].config.end_vol >= n_vol-1:
            #         self.stages['Preprocessing'].config.end_vol = n_vol-1
            #     self.stages['Preprocessing'].config.max_vol = n_vol-1

            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model

        if (diffusion_available):
            valid_inputs = True
        else:
            print "Missing required inputs."
            error(
                message=
                "Missing diffusion inputs. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)

        for stage in self.stages.values():
            if stage.enabled:
                print stage.name
                print stage.stage_dir

        self.fill_stages_outputs()

        return valid_inputs
Exemplo n.º 21
0
 def get_icon(self):
     return ImageResource('range')
Exemplo n.º 22
0
    def _about_dialog_default(self):
        """ Trait initializer. """

        return AboutDialog(image=ImageResource("about"))
Exemplo n.º 23
0
class FlowTask(Task):
    """
    classdocs
    """
    
    id = "edu.mit.synbio.cytoflowgui.flow_task"
    name = "Cytometry analysis"
    
    # the main workflow instance.
    model = Instance(Workflow)
        
    # the center pane
    workflow_pane = Instance(WorkflowDockPane)
    view_pane = Instance(ViewDockPane)
    help_pane = Instance(HelpDockPane)
    plot_params_pane = Instance(PlotParamsPane)
    
    # plugin lists, to setup the interface
    op_plugins = List(IOperationPlugin)
    view_plugins = List(IViewPlugin)
    
    menu_bar = SMenuBar(SMenu(TaskAction(name='Open...',
                                         method='on_open',
                                         accelerator='Ctrl+O'),
                              TaskAction(name='Save',
                                         #image='save', 
                                         method='on_save',
                                         accelerator='Ctrl+S'),
                              TaskAction(name='Save As...',
                                         method='on_save_as',
                                         accelerator='Ctrl+e'),
                              TaskAction(name='Save Plot...',
                                         method='on_export',
                                         accelerator='Ctrl+x'),
                              TaskAction(name='Export Jupyter notebook...',
                                         method='on_notebook',
                                         accelerator='Ctrl+I'),                              
#                               TaskAction(name='Preferences...',
#                                          method='on_prefs',
#                                          accelerator='Ctrl+P'),
                              id='File', name='&File'),
                        SMenu(TaskToggleGroup(),
                              id = 'View', name = '&View'),
                        SMenu(TaskAction(name = 'Online documentation...',
                                         method = 'on_docs'),
                                         TaskAction(name = 'Report a problem....',
                                         method = 'on_problem'),
                              TaskAction(name='About...',
                                         method='on_about'),
                              id="Help", name ="&Help"))
    
    tool_bars = [ SToolBar(TaskAction(method='on_new',
                                      name = "New",
                                      tooltip='New workflow',
                                      image=ImageResource('new')),
                           TaskAction(method='on_open',
                                      name = "Open",
                                      tooltip='Open a file',
                                      image=ImageResource('open')),
                           TaskAction(method='on_save',
                                      name = "Save",
                                      tooltip='Save the current file',
                                      image=ImageResource('save')),
                           TaskAction(method='on_export',
                                      name = "Save Plot",
                                      tooltip='Save the current plot',
                                      image=ImageResource('export')),
                           TaskAction(method='on_notebook',
                                       name='Notebook',
                                       tooltip="Export to an Jupyter notebook...",
                                       image=ImageResource('jupyter')),
                           TaskAction(method = "on_calibrate",
                                      name = "Calibrate FCS...",
                                      tooltip = "Calibrate FCS files",
                                      image = ImageResource('tasbe')),
                           TaskAction(method = 'on_problem',
                                      name = "Report a bug...",
                                      tooltib = "Report a bug",
                                      image = ImageResource('bug')))]
#                            TaskAction(method='on_prefs',
#                                       name = "Prefs",
#                                       tooltip='Preferences',
#                                       image=ImageResource('prefs')),
    
    # the file to save to if the user clicks "save" and has already clicked
    # "open" or "save as".
    filename = Str
        
    def initialized(self):
        if self.filename:
            self.open_file(self.filename)

        
    def activated(self):
        
        # if we're coming back from the TASBE task, re-load the saved
        # workflow
        if self.model.backup_workflow:
            self.model.workflow = self.model.backup_workflow
            self.model.backup_workflow = []
            return
        
        # else, set up a new workflow
        # add the import op
        if not self.model.workflow:
            self.add_operation(ImportPlugin().id) 
            self.model.selected = self.model.workflow[0]
                    
        self.model.modified = False
    
    def _default_layout_default(self):
        return TaskLayout(left = VSplitter(PaneItem("edu.mit.synbio.cytoflowgui.workflow_pane", width = 350),
                                           PaneItem("edu.mit.synbio.cytoflowgui.help_pane", width = 350, height = 350)),
                          right = VSplitter(PaneItem("edu.mit.synbio.cytoflowgui.view_traits_pane", width = 350),
                                            PaneItem("edu.mit.synbio.cytoflowgui.params_pane", width = 350, height = 350)),
                          top_left_corner = 'left',
                          bottom_left_corner = 'left',
                          top_right_corner = 'right',
                          bottom_right_corner = 'right')
     
    def create_central_pane(self):   
        # set the toolbar image size
        # this isn't really the right place for this, but it's the only
        # place control passes back to user code before the toolbar
        # is created.
        
        dpi = self.window.control.physicalDpiX()
        self.tool_bars[0].image_size = (int(0.4 * dpi), int(0.4 * dpi))
        return self.application.plot_pane
     
    def create_dock_panes(self):
        self.workflow_pane = WorkflowDockPane(model = self.model, 
                                              plugins = self.op_plugins,
                                              task = self)
        
        self.view_pane = ViewDockPane(model = self.model,
                                      plugins = self.view_plugins,
                                      task = self)
        
        self.help_pane = HelpDockPane(view_plugins = self.view_plugins,
                                      op_plugins = self.op_plugins,
                                      task = self)
        
        self.plot_params_pane = PlotParamsPane(model = self.model,
                                               task = self)
        
        return [self.workflow_pane, self.view_pane, self.help_pane, self.plot_params_pane]
        
    def on_new(self):
        if self.model.modified:
            ret = confirm(parent = None,
                          message = "Are you sure you want to discard the current workflow?",
                          title = "Clear workflow?")
            
            if ret != YES:
                return
            
        self.filename = ""
        self.window.title = "Cytoflow"
        
        # clear the workflow
        self.model.workflow = []
        
        # add the import op
        self.add_operation(ImportPlugin().id) 
        
        # and select the operation
        self.model.selected = self.model.workflow[0]
        
        self.model.modified = False
     
        
    def on_open(self):
        """ 
        Shows a dialog to open a file.
        """
        
        if self.model.modified:
            ret = confirm(parent = None,
                          message = "Are you sure you want to discard the current workflow?",
                          title = "Clear workflow?")
            
            if ret != YES:
                return
        
        dialog = FileDialog(parent = self.window.control, 
                            action = 'open',
                            wildcard = (FileDialog.create_wildcard("Cytoflow workflow", "*.flow") + ';' +  #@UndefinedVariable  
                                        FileDialog.create_wildcard("All files", "*"))) #@UndefinedVariable  
        if dialog.open() == OK:
            self.open_file(dialog.path)
            self.filename = dialog.path
            self.window.title = "Cytoflow - " + self.filename
            

    def open_file(self, path):
        
        try:
            new_workflow = load_yaml(path)

            # a few things to take care of when reloading.
            # we do this in the try block to catch people who
            # load valid YAML files that aren't from cytoflow.
            
            for wi_idx, wi in enumerate(new_workflow):
                
                # get wi lock
                wi.lock.acquire()
                
                # clear the wi status
                wi.status = "loading"
    
                # re-link the linked list.
                if wi_idx > 0:
                    wi.previous_wi = new_workflow[wi_idx - 1]
                
                if wi_idx < len(new_workflow) - 1:
                    wi.next_wi = new_workflow[wi_idx + 1]

        except yaml.parser.ParserError as e:
            error(None,
                  "Parser error loading {} -- is it a Cytoflow file?\n\n{}"
                  .format(path, str(e)))
            return
        except Exception as e:
            error(None,
                  "{} loading {} -- is it a Cytoflow file?\n\n{}"
                  .format(e.__class__.__name__, path, str(e)))
            return
        
        # are we just running a smoke test?
        if 'startup_test' in new_workflow[0].metadata:
            def quit_app(app):
                app.exit(force = True)
                
            from pyface.timer.api import do_after
            do_after(5*1000, quit_app, self.application)
            return
            
        # check that the FCS files are all there
        
        wi = new_workflow[0]
        assert(wi.operation.id == "edu.mit.synbio.cytoflow.operations.import")
        missing_tubes = 0
        for tube in wi.operation.tubes:
            file = pathlib.Path(tube.file)
            if not file.exists():
                missing_tubes += 1
                
        if missing_tubes == len(wi.operation.tubes):
            warning(self.window.control,
                    "Cytoflow couldn't find any of the FCS files from that "
                    "workflow.  If they've been moved, please open one FCS "
                    "file to show Cytoflow where they've been moved to.")
            
            dialog = FileDialog(parent = self.window.control, 
                                action = 'open',
                                wildcard = (FileDialog.create_wildcard("FCS files", "*.fcs *.lmd")))  # @UndefinedVariable
            
            if dialog.open() == OK:
                # find the "best" file match -- ie, the one with the longest
                # tail match
                fcs_path = pathlib.Path(dialog.path).parts
                best_path_len = -1
                                
                for tube in wi.operation.tubes:
                    tube_path = pathlib.Path(tube.file).parts
                    
                    for i in range(len(fcs_path)):
                        if list(reversed(fcs_path))[:i] == list(reversed(tube_path))[:i] and i > best_path_len:
                            best_path_len = i
                            
                if best_path_len >= 0:
                    for tube in wi.operation.tubes:
                        tube_path = pathlib.Path(tube.file).parts
                        new_path = fcs_path[:-1 * best_path_len] + tube_path[-1 * best_path_len :]
                        tube.file = str(pathlib.Path(*new_path))
                        
        elif missing_tubes > 0:
            warning(self.window.control,
                    "Cytoflow couldn't find some of the FCS files from that "
                    "workflow.  You'll need to re-load them from the Import "
                    "operation.")

        # replace the current workflow with the one we just loaded
        
        if False:  # for debugging the loading of things
            from .event_tracer import record_events 
            
            with record_events() as container:
                self.model.workflow = new_workflow
                                
            container.save_to_directory(os.getcwd()) 
        else:
            self.model.workflow = new_workflow
            self.model.modified = False
            
        for wi in self.model.workflow:
            wi.lock.release()
            
        if self.model.debug:
            self.model.run_all()
        else:
            ret = confirm(parent = None,
                          message = "Do you want to execute the workflow now?",
                          title = "Run workflow?")
            
            if ret == YES:
                self.model.run_all()

        
    def on_save(self):
        """ Save the file to the previous filename  """
        if self.filename:
            save_yaml(self.model.workflow, self.filename)
            self.model.modified = False
        else:
            self.on_save_as()
            
    def on_save_as(self):
        dialog = DefaultFileDialog(parent = self.window.control,
                                   action = 'save as', 
                                   default_suffix = "flow",
                                   wildcard = (FileDialog.create_wildcard("Cytoflow workflow", "*.flow") + ';' + #@UndefinedVariable  
                                               FileDialog.create_wildcard("All files", "*")))                    #@UndefinedVariable  
        
        if dialog.open() == OK:
            save_yaml(self.model.workflow, dialog.path)
            self.filename = dialog.path
            self.model.modified = False
            self.window.title = "Cytoflow - " + self.filename
            
    @on_trait_change('model.modified', post_init = True)
    def _on_model_modified(self, val):
        if val:
            if not self.window.title.endswith("*"):
                self.window.title += "*"
        else:
            if self.window.title.endswith("*"):
                self.window.title = self.window.title[:-1]
        

    def on_export(self):
        task = next(x for x in self.window.tasks if x.id == 'edu.mit.synbio.cytoflowgui.export_task')
        self.window.activate_task(task)        


    def on_calibrate(self):
        task = next(x for x in self.window.tasks if x.id == 'edu.mit.synbio.cytoflowgui.tasbe_task')
        self.window.activate_task(task)
        
            
    def on_notebook(self):
        """
        Shows a dialog to export the workflow to an Jupyter notebook
        """

        dialog = DefaultFileDialog(parent = self.window.control,
                                   action = 'save as',
                                   default_suffix = "ipynb",
                                   wildcard = (FileDialog.create_wildcard("Jupyter notebook", "*.ipynb") + ';' + #@UndefinedVariable  
                                               FileDialog.create_wildcard("All files", "*")))  # @UndefinedVariable
        if dialog.open() == OK:
            save_notebook(self.model.workflow, dialog.path)

    
    def on_prefs(self):
        pass
    
    def on_docs(self):
        webbrowser.open_new_tab("https://cytoflow.readthedocs.io/en/stable/manual.html")

    
    def on_problem(self):

        log = str(self._get_package_versions()) + "\n" + self.application.application_log.getvalue()
        
        msg = "The best way to report a problem is send an application log to " \
              "the developers.  If you click 'Yes' below, you will be given then " \
              "opportunity to save the log to a file and then file a " \
              "new issue on GitHub at " \
              "https://github.com/bpteague/cytoflow/issues/new" 
        
        dialog = ConfirmationDialog(message = msg,
                                    informative = "Would you like to report an issue to the developers?")
                
        if dialog.open() == YES:
            dialog = DefaultFileDialog(parent = self.window.control,
                                       action = 'save as', 
                                       default_suffix = "log",
                                       wildcard = (FileDialog.create_wildcard("Log files", "*.log") + ';' + #@UndefinedVariable  
                                                   FileDialog.create_wildcard("All files", "*")))                    #@UndefinedVariable  
            
            if dialog.open() == OK:
                with open(dialog.path, 'w') as f:
                    f.write(log)
                  
                webbrowser.open_new_tab("https://github.com/bpteague/cytoflow/issues/new")
                  
            return
    
    def _get_package_versions(self):    
        from cytoflow import __version__ as cf_version
        from fcsparser import __version__ as fcs_version
        from pandas import __version__ as pd_version
        from numpy import __version__ as np_version
        from numexpr import __version__ as nxp_version
        from bottleneck import __version__ as btl_version
        from seaborn import __version__ as sns_version
        from matplotlib import __version__ as mpl_version
        from scipy import __version__ as scipy_version
        from sklearn import __version__ as skl_version
        from statsmodels import __version__ as stats_version
        from pyface import __version__ as pyf_version
        from envisage import __version__ as env_version
        from traits import __version__ as trt_version
        from traitsui import __version__ as trt_ui_version
        from yapf import __version__ as yapf_version
        from nbformat import __version__ as nb_version
        from yaml import __version__ as yaml_version
        
        return {"python" : sys.version,
                "cytoflow" : cf_version,
                "fcsparser" : fcs_version,
                "pandas" : pd_version,
                "numpy" : np_version,
                "numexpr" : nxp_version,
                "bottleneck" : btl_version,
                "seaborn" : sns_version,
                "matplotlib" : mpl_version,
                "scipy" : scipy_version,
                "scikit-learn" : skl_version,
                "statsmodels" : stats_version,
                "pyface" : pyf_version,
                "envisage" : env_version,
                "traits" : trt_version,
                "traitsui" : trt_ui_version,
                "nbformat" : nb_version,
                "yapf" : yapf_version,
                "yaml" : yaml_version}
        
        
    def on_about(self):
        versions = self._get_package_versions()
        text = ["<b>Cytoflow {0}</b>".format(versions['cytoflow']),
                "<p>"]
        
        ver_text = ["{0} {1}".format(key, value) for key, value in versions.items()]
        
        text.extend(ver_text)
        
        text.extend(["Icons from the <a href=http://tango.freedesktop.org>Tango Desktop Project</a>",
                "<a href=https://thenounproject.com/search/?q=setup&i=14287>Settings icon</a> by Paulo Sa Ferreira from <a href=https://thenounproject.com>The Noun Project</a>",
                "<a href=https://thenounproject.com/search/?q=processing&i=849831>Processing icon</a> by Gregor Cresnar from <a href=https://thenounproject.com>The Noun Project</a>",
                "<a href=http://www.freepik.com/free-photos-vectors/background>App icon from Starline - Freepik.com</a>",
                "Cuvette image from Wikimedia Commons user <a href=http://commons.wikimedia.org/wiki/File:Hellma_Large_cone_cytometry_cell.JPG>HellmaUSA</a>"])
        
        dialog = AboutDialog(text = text,
                             parent = self.window.control,
                             title = "About",
                             image = ImageResource('cuvette'),
                             additions = text)
        dialog.open()
        
    @on_trait_change('model.selected', post_init = True)
    def _on_select_op(self, selected):
        if selected:
            self.view_pane.enabled = (selected is not None)
            self.view_pane.default_view = selected.default_view.id if selected.default_view else ""
            self.view_pane.selected_view = selected.current_view.id if selected.current_view else ""
            self.help_pane.help_id = selected.operation.id
        else:
            self.view_pane.enabled = False
            
    @on_trait_change('view_pane.selected_view', post_init = True)
    def _on_select_view(self, view_id):
        
        if not view_id:
            return
        
        # if we already have an instantiated view object, find it
        try:
            self.model.selected.current_view = next((x for x in self.model.selected.views if x.id == view_id))
        except StopIteration:
            # else make the new view
            plugin = next((x for x in self.view_plugins if x.view_id == view_id))
            view = plugin.get_view()
            self.model.selected.views.append(view)
            self.model.selected.current_view = view
            
        self.help_pane.help_id = view_id
    
    def add_operation(self, op_id):
        # first, find the matching plugin
        plugin = next((x for x in self.op_plugins if x.id == op_id))
        
        # next, get an operation
        op = plugin.get_operation()
        
        # make a new workflow item
        wi = WorkflowItem(operation = op,
                          deletable = (op_id != 'edu.mit.synbio.cytoflowgui.op_plugins.import'))
        
        # if the op has a default view, add it to the wi
        try:
            wi.default_view = op.default_view()
            wi.views.append(wi.default_view)
            wi.current_view = wi.default_view
        except AttributeError:
            pass
        
        # figure out where to add it
        if self.model.selected:
            idx = self.model.workflow.index(self.model.selected) + 1
        else:
            idx = len(self.model.workflow)
             
        # the add_remove_items handler takes care of updating the linked list
        self.model.workflow.insert(idx, wi)
        
        # and make sure to actually select the new wi
        self.model.selected = wi
Exemplo n.º 24
0
class WorkbenchApplication(Application):
    """ The entry point for an Envisage Workbench application.

    i.e. a GUI application whose user interface is provided by the workbench
    plugin.

    This class handles the common case for Workbench applications, and it is
    intended to be subclassed to change start/stop behaviour etc. In fact, I
    generally create a subclass for every Workbench application I write since
    it is a good place to put branding information etc.

    """

    #### 'WorkbenchApplication' interface #####################################

    # The Pyface GUI for the application (this is here to make it easy for
    # parts of the application to get a reference to the GUI so they can get
    # system metrics, etc.
    gui = Instance(GUI)

    # The workbench.
    workbench = Instance(IWorkbench)

    # The factory for creating the workbench (used *instead* of providing a
    # workbench explicitly).
    workbench_factory = Callable(Workbench)

    # Branding information.
    #
    # The 'About' dialog.
    about_dialog = Instance(Dialog)

    # The icon used on window title bars etc.
    icon = Instance(ImageResource, ImageResource("application.ico"))

    # The name of the application (also used on window title bars etc).
    name = Str("Workbench")

    # The splash screen (None, the default, if no splash screen is required).
    splash_screen = Instance(SplashScreen)

    # The default position of the main window.
    window_position = Tuple((200, 200))

    # The default size of the main window.
    window_size = Tuple((800, 600))

    ###########################################################################
    # 'IApplication' interface.
    ###########################################################################

    def run(self):
        """ Run the application.

        This does the following (so you don't have to ;^):-

        1) Starts the application
        2) Creates and opens a workbench window
        3) Starts the GUI event loop
        4) When the event loop terminates, stops the application

        """

        logger.debug("---------- workbench application ----------")

        # Make sure the GUI has been created (so that, if required, the splash
        # screen is shown).
        gui = self.gui

        # Start the application.
        if self.start():
            # Create and open the first workbench window.
            window = self.workbench.create_window(
                position=self.window_position, size=self.window_size
            )
            window.open()

            # We stop the application when the workbench has exited.
            self.workbench.on_trait_change(self._on_workbench_exited, "exited")

            # Start the GUI event loop.
            #
            # THIS CALL DOES NOT RETURN UNTIL THE GUI IS CLOSED.
            gui.start_event_loop()

    ###########################################################################
    # 'WorkbenchApplication' interface.
    ###########################################################################

    #### Initializers #########################################################

    def _about_dialog_default(self):
        """ Trait initializer. """

        return AboutDialog(image=ImageResource("about"))

    def _gui_default(self):
        """ Trait initializer. """

        return GUI(splash_screen=self.splash_screen)

    def _workbench_default(self):
        """ Trait initializer. """

        return self.create_workbench()

    #### Methods ##############################################################

    def about(self):
        """ Display the about dialog. """

        # fixme: We really need to create a new 'about dialog' every time so
        # that it can have the active window as its parent.
        self.about_dialog.open()

    # fixme: Is this needed on the public API? Why can't we just do this in
    # the default initializer (_workbench_default)?
    def create_workbench(self):
        """ Create the workbench. """

        logger.debug("workbench factory %s", self.workbench_factory)

        return self.workbench_factory(application=self)

    def exit(self):
        """ Exit the application.

        This closes all open windows and hence exits the GUI event loop.

        """

        self.workbench.exit()

    ###########################################################################
    # Private interface.
    ###########################################################################

    def _on_workbench_exited(self):
        """ Dynamic trait change handler. """

        # We don't invoke 'stop' directly because:-
        #
        # The workbench is often exited via a user action (either by closing
        # the last open window, or by choosing 'File/Exit'). If this happens
        # then the workbench 'exit' method is called from within an event
        # handler which would cause the 'stop' method to get called *before*
        # the handling of the window 'closed' event is complete. Hance, this
        # might mean that somebody listening for the window being closed would
        # get the event *after* the application had already stopped!
        self.gui.invoke_later(self.stop)
Exemplo n.º 25
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ------------------------------------------------------------------------------
"""
Handle image and file resources.
"""

import os
from pyface.api import ImageResource
from traits.api import *
from traitsui.api import *

search_path = os.path.join(
    os.path.split(os.path.abspath(__file__))[0], 'resources')

APPICON = ImageResource(name='appicon.png', search_path=search_path)

USER_GUIDE = os.path.join(search_path, 'docs', 'optoConfig96_guide.html')


class opView(View):
    """
    Set the default icon.
    """

    icon = Instance(ImageResource, APPICON)


class Examples(HasTraits):
    _available_examples = Property
Exemplo n.º 26
0
    def trait_view(self, name='default'):
        file_menu = Menu(
            ActionGroup(Action(name='New \t Ctrl+N', action='new'),
                        Action(name='Open \t Ctrl+O', action='open'),
                        Action(name='Close \t Ctrl+W', action='close_tab')),
            ActionGroup(Action(name='Save \t Ctrl+S', action='save'),
                        Action(name='Save As', action='saveAs')),
            ActionGroup(Action(name='Exit \t Ctrl+Q', action='exit')),
            name='File')
        edit_menu = Menu(
            ActionGroup(Action(name='Undo \t Ctrl+Z', action='undo'),
                        Action(name='Redo \t Ctrl+Y', action='redo')),
            ActionGroup(Action(name='Cut \t Ctrl+X', action='cut'),
                        Action(name='Copy \t Ctrl+C', action='copy'),
                        Action(name='Paste \t Ctrl+V', action='paste')),
            ActionGroup(
                Action(name='Select All \t Ctrl+A', action='select_all')),
            name='Edit')

        search_menu = Menu(ActionGroup(
            Action(name='Find \t Ctrl+F', action='enable_find'),
            Action(name='Replace \t Ctrl+R', action='enable_replace')),
                           name='Search')

        view_menu = Menu(ActionGroup(
            Action(name='Toggle File Browser', action='toggle_file_browser')),
                         name='View')
        prefs_menu = Menu(Action(name='Sync view on change',
                                 action='toggle_sync_on_change',
                                 checked=self.sync_on_change,
                                 style='toggle'),
                          Action(name='Auto fix table',
                                 action='toggle_auto_table_fix',
                                 checked=self.auto_table_fix,
                                 style='toggle'),
                          Action(name='Use Sphinx',
                                 action='toggle_sphinx',
                                 checked=self.use_sphinx,
                                 style='toggle'),
                          Action(name='Set Sphinx resources path...',
                                 action='change_sphinx_static_path'),
                          Action(name='Change font', action='change_font'),
                          name='Preferences')
        help_menu = Menu(Action(name='About', action='about'), name='Help')
        convert_menu = Menu(Action(name='Docutils - HTML',
                                   action='docutils_rst2html'),
                            Action(name='Docutils - LaTeX',
                                   action='docutils_rst2latex'),
                            Action(name='Sphinx - HTML',
                                   action='sphinx_rst2html'),
                            Action(name='rst2pdf', action='rst2pdf'),
                            name='Convert')
        menu_bar = MenuBar(file_menu, edit_menu, search_menu, view_menu,
                           prefs_menu, convert_menu, help_menu)

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

        file_group = ActionGroup(
            Action(tooltip='New', action='new', image=ImageResource('new')),
            Action(tooltip='Open', action='open', image=ImageResource('open')),
            Action(tooltip='Save', action='save', image=ImageResource('save')),
            Action(tooltip='Save As',
                   action='saveAs',
                   image=ImageResource('save-as')),
            Action(tooltip='Close',
                   action='close_tab',
                   image=ImageResource('close')))

        edit_group = ActionGroup(
            Action(tooltip='Cut', action='cut', image=ImageResource('cut')),
            Action(tooltip='Copy', action='copy', image=ImageResource('copy')),
            Action(tooltip='Paste',
                   action='paste',
                   image=ImageResource('paste')))

        undo_group = ActionGroup(
            Action(tooltip='Undo', action='undo', image=ImageResource('undo')),
            Action(tooltip='Redo', action='redo', image=ImageResource('redo')))

        search_group = ActionGroup(
            Action(tooltip='Find',
                   action='enable_find',
                   image=ImageResource('find')),
            Action(tooltip='Replace',
                   action='enable_replace',
                   image=ImageResource('replace')))

        markup_group = ActionGroup(
            Action(tooltip='Bold', action='bold', image=ImageResource('bold')),
            Action(tooltip='Italic',
                   action='italic',
                   image=ImageResource('italic')),
            Action(tooltip='Inline Literal',
                   action='inline_literal',
                   image=ImageResource('literal')),
            Action(tooltip='Fix underline (Ctrl+D)',
                   action='fix_underline',
                   image=ImageResource('underline')),
            Action(tooltip='Fix underline and overline (Ctrl+Shift+D)',
                   action='fix_under_overline',
                   image=ImageResource('under-over')))

        sync_group = ActionGroup(
            Action(tooltip='Sync rst2html',
                   action='sync_scrollbar_rst2html',
                   image=ImageResource('sync_rst2html')),
            Action(tooltip='Sync html2rst',
                   action='sync_scrollbar_html2rst',
                   image=ImageResource('sync_html2rst')))

        tool_bar = ToolBar(file_group, edit_group, undo_group, search_group,
                           markup_group, sync_group)

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

        key_bindings = KeyBindings(
            KeyBinding(binding1='Ctrl-n', method_name='new'),
            KeyBinding(binding1='Ctrl-o', method_name='open'),
            KeyBinding(binding1='Ctrl-s', method_name='save'),
            KeyBinding(binding1='Ctrl-w', method_name='close_tab'),
            KeyBinding(binding1='Ctrl-q', method_name='exit'),
            KeyBinding(binding1='Ctrl-d', method_name='fix_underline'),
            KeyBinding(binding1='Ctrl-Shift-d',
                       method_name='fix_under_overline'),
            # The following are identical to the already set hotkeys in
            # the source editor. We just want them to work regardless of
            # whether the editor has focus.
            KeyBinding(binding1='Ctrl-z', method_name='undo'),
            KeyBinding(binding1='Ctrl-y', method_name='redo'),
            KeyBinding(binding1='Ctrl-x', method_name='cut'),
            KeyBinding(binding1='Ctrl-c', method_name='copy'),
            KeyBinding(binding1='Ctrl-v', method_name='paste'),
            KeyBinding(binding1='Ctrl-a', method_name='select_all'),
            KeyBinding(binding1='Ctrl-f', method_name='enable_find'),
            KeyBinding(binding1='Ctrl-r', method_name='enable_replace'))

        return View(Group(Item('_tree',
                               style='custom',
                               width=0.25,
                               editor=InstanceEditor()),
                          Item('open_views',
                               style='custom',
                               editor=ListEditor(use_notebook=True,
                                                 deletable=True,
                                                 dock_style='tab',
                                                 ui_kind='panel',
                                                 selected='selected_view',
                                                 page_name='.title')),
                          id='rest_editor_view.EditorSplit',
                          orientation='horizontal',
                          layout='split',
                          show_labels=False),
                    id='rest_editor_view.EditorView',
                    handler=ReSTHTMLEditorHandler(),
                    width=1024,
                    height=786,
                    resizable=True,
                    menubar=menu_bar,
                    toolbar=tool_bar,
                    key_bindings=key_bindings,
                    title="reStructured Text Editor",
                    icon=self.icon)
Exemplo n.º 27
0
 def get_icon(self):
     return ImageResource('tasbe')
Exemplo n.º 28
0
 def get_icon(self):
     return ImageResource('stats_1d')
Exemplo n.º 29
0
 def get_icon(self):
     return ImageResource('ratio')
Exemplo n.º 30
0
    def __init__(self, parent, tool_bar, image_cache, item, controller,
                 show_labels):
        """ Creates a new tool bar tool for an action item. """

        self.item = item
        self.tool_bar = tool_bar

        # Create an appropriate tool depending on the style of the action.
        action  = self.item.action
        label   = action.name

        # Tool bar tools never have '...' at the end!
        if label.endswith('...'):
            label = label[:-3]

        # And they never contain shortcuts.
        label = label.replace('&', '')

        # If the action has an image then convert it to a bitmap (as required
        # by the toolbar).
        if action.image is not None:
            image = action.image.create_image(
                self.tool_bar.GetToolBitmapSize()
            )
            path = action.image.absolute_path
            bmp  = image_cache.get_bitmap(path)

        else:
            from pyface.api import ImageResource
            image = ImageResource('foo')
            bmp  = image.create_bitmap()

        kind    = _STYLE_TO_KIND_MAP[action.style]
        tooltip = action.tooltip
        longtip = action.description

        if not show_labels:
            label = ''

        else:
            self.tool_bar.SetSize((-1, 50))

        self.control_id = wx.NewId()
        self.control = tool_bar.AddLabelTool(
            self.control_id, label, bmp, wx.NullBitmap, kind, tooltip, longtip, None
        )

        # Set the initial checked state.
        tool_bar.ToggleTool(self.control_id, action.checked)

        if hasattr(tool_bar, 'ShowTool'):
            # Set the initial enabled/disabled state of the action.
            tool_bar.EnableTool(self.control_id, action.enabled)

            # Set the initial visibility
            tool_bar.ShowTool(self.control_id, action.visible)
        else:
            # Set the initial enabled/disabled state of the action.
            tool_bar.EnableTool(
                self.control_id, action.enabled and action.visible)

        # Wire it up.
        wx.EVT_TOOL(parent, self.control_id, self._on_tool)

        # Listen for trait changes on the action (so that we can update its
        # enabled/disabled/checked state etc).
        action.on_trait_change(self._on_action_enabled_changed, 'enabled')
        action.on_trait_change(self._on_action_visible_changed, 'visible')
        action.on_trait_change(self._on_action_checked_changed, 'checked')

        if controller is not None:
            self.controller = controller
            controller.add_to_toolbar(self)
Exemplo n.º 31
0
 def get_icon(self):
     return ImageResource(u'quad')
Exemplo n.º 32
0
 def get_icon(self):
     return ImageResource('histogram')
Exemplo n.º 33
0
 def get_icon(self):
     return ImageResource('autofluorescence')
Exemplo n.º 34
0
            view=demo_content_view
        ),
        ObjectTreeNode(
            node_for=[DemoVirtualDirectory],
            label="nice_name",
            view=demo_virtual_dir_view,
        ),
    ],
    hide_root=True,
    selected='selected_node',
)


next_tool = Action(
    name='Next',
    image=ImageResource("next"),
    tooltip="Go to next file",
    action="do_next",
    enabled_when="_next_node is not None",
)

previous_tool = Action(
    name='Previous',
    image=ImageResource("previous"),
    tooltip="Go to next file",
    action="do_previous",
    enabled_when="_previous_node is not None",
)

parent_tool = Action(
    name='Parent',
Exemplo n.º 35
0
 def get_icon(self):
     return ImageResource('violin')
Exemplo n.º 36
0
 def get_icon(self):
     return ImageResource('xform_stat')