Ejemplo n.º 1
0
 def get_data_indexes(self):
     OM = ObjectManager()
     curve_sets = OM.list('curve_set', self.uid)
     ret = OrderedDict()
     for curve_set in curve_sets:
         dis = OM.list('data_index', curve_set.uid)
         ret[curve_set.uid] = dis
     return ret
Ejemplo n.º 2
0
    def get_equivalent_index(self, datatype, dim_idx=-1):
        """
        Metodo usado para se obter um DataIndex de equivalencia (e.g. obter
        um TWT quando self.datatype == 'MD').
        
        Valido somente para dados de pocos, devido a busca por CurveSet.
        
        Retorna uma tupla onde o primeiro elemento informa se foi encontrado
        objeto equivalente diferente o DataIndex mask sendo aplicado. Em caso 
        afirmativo, o segundo elemento da tupla contem o objeto encontrado.
        Caso nao tenha sido obtido index equivalente, o segundo elemento 
        retornara o proprio objeto, se este tiver o datatype procurado. 
        Se o datatype desejado nao for encontrado, sera retornado (False, None).
        """
        dim_di_uid, _ = self.get_index_for_dimension(dim_idx)
        OM = ObjectManager()
        di = OM.get(dim_di_uid)

        if di.datatype == datatype:
            return False, di
        OM = ObjectManager()
        curve_set_uid = OM._getparentuid(di.uid)
        if curve_set_uid[0] != 'curve_set':
            msg = 'ERROR DataIndex.get_equivalent_data_index: curve_set not found.'
            raise Exception(msg)
        for possible_di in OM.list('data_index', curve_set_uid):
            if possible_di.uid == di.uid:
                continue
            if possible_di.datatype == datatype:
                # Found it!
                return True, possible_di
        return False, None
Ejemplo n.º 3
0
    def reload_tree(self, *args):

        print()

        logging.debug("reload_tree " + str(args))

        self.DeleteChildren(self._rootid)
        OM = ObjectManager()

        lista = OM.list()
        print(lista)

        print()

        for obj in OM.list():
            self._add_tree_node(obj.uid, OM._getparentuid(obj.uid))
Ejemplo n.º 4
0
def on_save_image(*args, **kwargs):
    
    OM = ObjectManager()
    UIM = UIManager()
    #
    images_od = OrderedDict()
    images = OM.list('image')
    for image in images:
        images_od[image.name] = image.uid    

    #
    dlg = UIM.create('dialog_controller', title='Save image file')
    ctn_image = dlg.view.AddCreateContainer('StaticBox', label='Select Image', 
                                            orient=wx.VERTICAL, proportion=0, 
                                            flag=wx.EXPAND|wx.TOP, border=5)


    dlg.view.AddChoice(ctn_image, proportion=0, flag=wx.EXPAND|wx.TOP, 
                       border=5, widget_name='images_choice', options=images_od,
                       initial=0) 
    #
    
    dlg.view.SetSize((300, 180))
    result = dlg.view.ShowModal()

  
    
    if result == wx.ID_OK:
        results = dlg.get_results()  
            
        print(results)    
    
        image_uid = results.get("images_choice")
    
    
        wildcard = "Save image file (*.png, *.tif)|*.png;*.tif"
    
        fdlg = wx.FileDialog(wx.App.Get().GetTopWindow(), 
                             "Save file", 
                             wildcard=wildcard, 
                             style=wx.FD_SAVE
        )
        
        if fdlg.ShowModal() == wx.ID_OK:
            file_name = fdlg.GetFilename()
            dir_name = fdlg.GetDirectory()
            fdlg.Destroy()
        else:
            fdlg.Destroy()
            return
        
        fullfilename = os.path.join(dir_name, file_name)        
        
        print("fullfilename: ", fullfilename)

        image = OM.get(image_uid)
        img = Image.fromarray(image.data)
        img.save(fullfilename)
Ejemplo n.º 5
0
 def get_data_indexes(self, dimension=None):
     """
     """
     OM = ObjectManager()
     data_index_maps = OM.list('data_index_map', self.uid)
     if not data_index_maps:
         raise Exception('Object without DataIndexMap: {}'.format(self.uid))
     data_index_map = data_index_maps[0]
     data_indexes = data_index_map._get_data_indexes()
     if dimension is None:
         return data_indexes
     return data_indexes[dimension]
Ejemplo n.º 6
0
 def get_z_axis_datatype_range(self, datatype):
     """Given a Well index datatype (e.g. `MD`), returns a tuple with its 
     minimal and maximum values, considering all occurences.
     """
     min_ = 100000
     max_ = -1
     OM = ObjectManager()
     data_indexes = OM.list('data_index', self.uid, True)
     for data_index in data_indexes:
         if data_index.datatype == datatype:
             if data_index.start < min_:
                 min_ = data_index.start
             if data_index.end > max_:
                 max_ = data_index.end
     return (min_, max_)
Ejemplo n.º 7
0
 def create_new_curve_set(self, curve_set_name=None):
     OM = ObjectManager()
     existing_csets = OM.list('curve_set', self.uid)
     #
     if curve_set_name:
         for cset in existing_csets:
             if cset.name == curve_set_name:
                 curve_set_name = None
                 break
     #
     if not curve_set_name:
         curve_set_idx = len(existing_csets) + 1
         curve_set_name = 'Run ' + str(curve_set_idx)
     #
     curve_set = OM.new('curve_set', name=curve_set_name)
     OM.add(curve_set, self.uid)
     return curve_set
Ejemplo n.º 8
0
    def get_z_axis_datatypes(self, inverted=False):
        """Returns a dict with valid Z axis data types for this Well. Dict key
        will be a long description for the data type (e.g. 'Measured Depth') 
        and value will be a short identification (e.g. 'MD'). Returned dict 
        will contain information from all DataIndex objects that are children 
        of this Well.
        
        """
        OM = ObjectManager()
        z_axis = OrderedDict()
        data_indexes = OM.list('data_index', self.uid, True)

        for z_axis_dt, z_axis_dt_desc in VALID_Z_AXIS_DATATYPES:
            for data_index in data_indexes:
                if (data_index.datatype == z_axis_dt) and \
                                            z_axis_dt not in z_axis.values():
                    z_axis[z_axis_dt] = z_axis_dt_desc
        if not inverted:
            return z_axis
        return OrderedDict(zip(z_axis.values(), z_axis.keys()))
Ejemplo n.º 9
0
    def OnPopupItemSelected(self, event):
        print('OnPopupItemSelected', self.popup_obj)

        # tree_item = event.GetItem()
        # item_data = self.GetItemData(tree_item)

        (node_type, node_main_info, node_extra_info) = self.popup_obj
        OM = ObjectManager()

        if node_type == ID_TYPE_OBJECT:
            print('ID_TYPE_OBJECT remove:', node_main_info)
            OM.remove(node_main_info)

        elif node_type == ID_TYPE_TID:
            # if node_info == 'well':
            #    items = OM.list(node_main_info)
            # else:
            items = OM.list(node_main_info, node_extra_info)
            for item in items:
                print('ID_TYPE_TID remove:', item.uid)

                OM.remove(item.uid)
        print('FIM OnPopupItemSelected')
Ejemplo n.º 10
0
class RockTable(wx.grid.GridTableBase):
    @debugdecorator
    def __init__(self, rocktableuid):
        super(RockTable, self).__init__()

        self.OM = ObjectManager()
        self.rocktypeuid = []
        self.rocktableuid = rocktableuid

        self.rocktypemap = [
            rocktype.uid
            for rocktype in self.OM.list('rocktype', self.rocktableuid)
        ]
        self.N_COLS = 4
        self.N_ROWS = 0

    @debugdecorator
    def AppendRows(self, numRows=1):
        rocktype = self.GrainEntry()
        #        rocktype = self.OM.new('rocktype')
        rocktype.defaultdata = np.nan
        self.OM.add(rocktype, self.rocktableuid)

        self.rocktypemap.append(rocktype.uid)
        color = self.get_color(0)
        self.set_color(-1, color)

        self.GetView().BeginBatch()
        msg = wx.grid.GridTableMessage(self,
                                       wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED,
                                       numRows)
        self.GetView().ProcessTableMessage(msg)
        self.GetView().EndBatch()

        return True

    @debugdecorator
    def GrainEntry(self):
        UIM = UIManager()
        dlg = UIM.create('dialog_controller', title='Rock creator')
        cont_grain = dlg.view.AddCreateContainer('StaticBox',
                                                 label='Grain Parts',
                                                 orient=wx.VERTICAL,
                                                 proportion=0,
                                                 flag=wx.EXPAND | wx.TOP,
                                                 border=5)
        cont_matr = dlg.view.AddCreateContainer('StaticBox',
                                                label='Matrix Parts',
                                                orient=wx.VERTICAL,
                                                proportion=0,
                                                flag=wx.EXPAND | wx.TOP,
                                                border=5)

        json_file = '\\Temp\\min.json'
        #        fullpath_json = 'C:\\Users\\rtabelini\\Documents\\Github\\GRIPy'+json_file
        fullpath_json = cwd() + json_file

        dictmin = app.app_utils.read_json_file(fullpath_json)

        def on_change_mineral(name, old_value, new_value, **kwargs):
            print('new\n', name, new_value, new_value['name'],
                  dictmin.iterkeys())
            if name == 'mineralgrain':
                textctrl_k = dlg.view.get_object('kmod1')
                textctrl_g = dlg.view.get_object('gmod1')
                textctrl_rho = dlg.view.get_object('dens1')
            elif name == 'mineralmatrix':
                textctrl_k = dlg.view.get_object('kmod2')
                textctrl_g = dlg.view.get_object('gmod2')
                textctrl_rho = dlg.view.get_object('dens2')

            if new_value['name'] in dictmin.iterkeys():
                textctrl_k.set_value(new_value['K'])
                textctrl_g.set_value(new_value['G'])
                textctrl_rho.set_value(new_value['Dens'])

        dlg.view.AddChoice(cont_grain,
                           widget_name='mineralgrain',
                           options=dictmin,
                           flag=wx.EXPAND)
        choice_grain = dlg.view.get_object('mineralgrain')
        choice_grain.set_trigger(on_change_mineral)

        dlg.view.AddChoice(cont_matr,
                           widget_name='mineralmatrix',
                           options=dictmin,
                           flag=wx.EXPAND)
        choice_matrix = dlg.view.get_object('mineralmatrix')
        choice_matrix.set_trigger(on_change_mineral)

        gr_frac = dlg.view.AddCreateContainer('BoxSizer',
                                              cont_grain,
                                              orient=wx.HORIZONTAL,
                                              proportion=1,
                                              flag=wx.EXPAND | wx.ALL,
                                              border=5)
        dlg.view.AddStaticText(gr_frac,
                               proportion=1,
                               initial='Fraction ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(gr_frac,
                             proportion=1,
                             widget_name='frac1',
                             initial='0.8',
                             flag=wx.ALIGN_RIGHT)

        gr_poro = dlg.view.AddCreateContainer('BoxSizer',
                                              cont_grain,
                                              orient=wx.HORIZONTAL,
                                              proportion=1,
                                              flag=wx.EXPAND | wx.ALL,
                                              border=5)
        dlg.view.AddStaticText(gr_poro,
                               proportion=1,
                               initial='Porosity ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(gr_poro,
                             proportion=1,
                             widget_name='poro1',
                             initial='0.20',
                             flag=wx.ALIGN_RIGHT)

        gr_kmod = dlg.view.AddCreateContainer('BoxSizer',
                                              cont_grain,
                                              orient=wx.HORIZONTAL,
                                              proportion=1,
                                              flag=wx.EXPAND | wx.ALL,
                                              border=5)
        dlg.view.AddStaticText(gr_kmod,
                               proportion=1,
                               widget_name='K_Modulus',
                               initial='K Modulus (GPa) ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(gr_kmod,
                             proportion=1,
                             widget_name='kmod1',
                             initial='36.5',
                             flag=wx.ALIGN_RIGHT)

        gr_gmod = dlg.view.AddCreateContainer('BoxSizer',
                                              cont_grain,
                                              orient=wx.HORIZONTAL,
                                              proportion=1,
                                              flag=wx.EXPAND | wx.ALL,
                                              border=5)
        dlg.view.AddStaticText(gr_gmod,
                               proportion=1,
                               widget_name='G_Modulus',
                               initial='G Modulus (GPa) ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(gr_gmod,
                             proportion=1,
                             widget_name='gmod1',
                             initial='78.6',
                             flag=wx.ALIGN_RIGHT)

        gr_dens = dlg.view.AddCreateContainer('BoxSizer',
                                              cont_grain,
                                              orient=wx.HORIZONTAL,
                                              proportion=1,
                                              flag=wx.EXPAND | wx.ALL,
                                              border=5)
        dlg.view.AddStaticText(gr_dens,
                               proportion=1,
                               widget_name='Density',
                               initial='Density (g/cc) ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(gr_dens,
                             proportion=1,
                             widget_name='dens1',
                             initial='2.65',
                             flag=wx.ALIGN_RIGHT)

        mtr_frac = dlg.view.AddCreateContainer('BoxSizer',
                                               cont_matr,
                                               orient=wx.HORIZONTAL,
                                               proportion=1,
                                               flag=wx.EXPAND | wx.ALL,
                                               border=5)
        dlg.view.AddStaticText(mtr_frac,
                               proportion=1,
                               widget_name='fraction2',
                               initial='Fraction ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(mtr_frac,
                             proportion=1,
                             widget_name='frac2',
                             initial='0.2',
                             flag=wx.ALIGN_LEFT)

        mtr_poro = dlg.view.AddCreateContainer('BoxSizer',
                                               cont_matr,
                                               orient=wx.HORIZONTAL,
                                               proportion=1,
                                               flag=wx.EXPAND | wx.ALL,
                                               border=5)
        dlg.view.AddStaticText(mtr_poro,
                               proportion=1,
                               initial='Porosity ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(mtr_poro,
                             proportion=1,
                             widget_name='poro2',
                             initial='0.10',
                             flag=wx.ALIGN_RIGHT)

        mtr_kmod = dlg.view.AddCreateContainer('BoxSizer',
                                               cont_matr,
                                               orient=wx.HORIZONTAL,
                                               proportion=1,
                                               flag=wx.EXPAND | wx.ALL,
                                               border=5)
        dlg.view.AddStaticText(mtr_kmod,
                               proportion=1,
                               widget_name='K_Modulus2',
                               initial='K Modulus (GPa) ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(mtr_kmod,
                             proportion=1,
                             widget_name='kmod2',
                             initial='36.5',
                             flag=wx.ALIGN_LEFT)

        mtr_gmod = dlg.view.AddCreateContainer('BoxSizer',
                                               cont_matr,
                                               orient=wx.HORIZONTAL,
                                               proportion=1,
                                               flag=wx.EXPAND | wx.ALL,
                                               border=5)
        dlg.view.AddStaticText(mtr_gmod,
                               proportion=1,
                               widget_name='G_Modulus2',
                               initial='G Modulus (GPa) ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(mtr_gmod,
                             proportion=1,
                             widget_name='gmod2',
                             initial='78.6',
                             flag=wx.ALIGN_LEFT)

        mtr_dens = dlg.view.AddCreateContainer('BoxSizer',
                                               cont_matr,
                                               orient=wx.HORIZONTAL,
                                               proportion=1,
                                               flag=wx.EXPAND | wx.ALL,
                                               border=5)
        dlg.view.AddStaticText(mtr_dens,
                               proportion=1,
                               widget_name='Density2',
                               initial='Density (g/cc) ',
                               flag=wx.ALIGN_RIGHT)
        dlg.view.AddTextCtrl(mtr_dens,
                             proportion=1,
                             widget_name='dens2',
                             initial='2.65',
                             flag=wx.ALIGN_LEFT)
        #
        try:
            if dlg.view.ShowModal() == wx.ID_OK:
                results = dlg.get_results()
                gr_f = results.get('frac1')
                mtr_f = results.get('frac2')
                ngrain = results.get('mineralgrain')['name']
                nmatrix = results.get('mineralmatrix')['name']
                gr_phi = results.get('poro1')
                gr_k = results.get('kmod1')
                gr_mi = results.get('gmod1')
                gr_rho = results.get('dens1')
                mtr_phi = results.get('poro2')
                mtr_k = results.get('kmod2')
                mtr_mi = results.get('gmod2')
                mtr_rho = results.get('dens2')
                #                kk = RP.VRHill (gr_k, gr_f, mtr_k)
                #                g = RP.VRHill (gr_mi, gr_f, mtr_mi)
                print('\ngrd', gr_k, gr_f, mtr_k, type(float(mtr_k)))
                rocktype = self.OM.new(
                    'rocktype',
                    fracgrain=gr_f,
                    fracmatrix=mtr_f,
                    grain=ngrain,
                    matrix=nmatrix,
                    k=10,
                    mi=20)  #vp=vp, vs=vs, rho = rho, k=k, mi=mi, poi=poi
                return rocktype

        except Exception as e:
            print('ERROR:', str(e))
        finally:
            UIM.remove(dlg.uid)

    @debugdecorator
    def DeleteRows(self, pos=0, numRows=1):
        if pos >= self.N_ROWS:
            i = pos - self.N_ROWS
            for j in range(numRows)[::-1]:
                self.OM.remove(self.rocktypemap.pop(i + j))

            self.GetView().BeginBatch()
            msg = wx.grid.GridTableMessage(
                self, wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, pos, numRows)
            self.GetView().ProcessTableMessage(msg)
            self.GetView().EndBatch()

            return True
        else:
            return False

    @debugdecorator
    def GetColLabelValue(self, col):
        if col == 0:
            return "Nome"
        elif col == 1:
            return "Cor"
        elif col == 2:
            return "Grain"
        elif col == 3:
            return "Matrix"
        else:
            return

    @debugdecorator
    def GetRowLabelValue(self, row):
        return str(row + 1)

    @debugdecorator
    def SetRowLabelValue(self, row, label):
        return

    @debugdecorator
    def GetNumberCols(self):
        return self.N_COLS


#        return len(self.propmap) + self.N_COLS

    @debugdecorator
    def GetNumberRows(self):
        return len(self.rocktypemap)

    @debugdecorator
    def GetAttr(self, row, col, kind):

        #if _iswxphoenix:
        attr = wx.grid.GridCellAttr().Clone()

        if col >= self.N_COLS:
            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
        elif col == 0:
            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
        elif col == 1:
            rocktype = self.OM.get(self.rocktypemap[row])
            attr.SetBackgroundColour(rocktype.color)
            attr.SetReadOnly(True)
        elif col == 2:
            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
        elif col == 3:
            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
        return attr

    @debugdecorator
    def GetValue(self, row, col):
        if col >= self.N_COLS:
            i = col - self.N_COLS
            prop = self.OM.get(self.propmap[i])
            value = prop.getdata(self.rocktypemap[row])
            if not np.isnan(value):
                return str(value)
            else:
                return ''
        elif col == 0:
            rocktype = self.OM.get(self.rocktypemap[row])
            return rocktype.name
        elif col == 1:
            return ''
        elif col == 2:
            rocktype = self.OM.get(self.rocktypemap[row])
            return rocktype.fracgrain + ' ' + rocktype.grain
        elif col == 3:
            rocktype = self.OM.get(self.rocktypemap[row])
            return rocktype.fracmatrix + ' ' + rocktype.matrix

    @debugdecorator
    def SetValue(self, row, col, value):
        if col >= self.N_COLS:
            i = col - self.N_COLS
            if value:
                value = float(value)
            else:
                value = np.nan
            prop = self.OM.get(self.propmap[i])
            prop.setdata(self.rocktypemap[row], value)
        elif col == 0:
            rocktype = self.OM.get(self.rocktypemap[row])
            rocktype.name = value
        elif col == 1:
            return
        elif col == 2:
            return
        elif col == 3:
            return

    @debugdecorator
    def set_color(self, row, color):
        rocktype = self.OM.get(self.rocktypemap[row])
        rocktype.color = color

    @debugdecorator
    def get_color(self, row):
        rocktype = self.OM.get(self.rocktypemap[row])
        return rocktype.color

    @debugdecorator
    def get_nameunit(self, col):
        if col >= self.N_COLS:
            i = col - self.N_COLS
            prop = self.OM.get(self.propmap[i])
            return prop.name, prop.unit

    @debugdecorator
    def set_nameunit(self, col, name, unit):
        if col >= self.N_COLS:
            i = col - self.N_COLS
            prop = self.OM.get(self.propmap[i])
            prop.name = name
            prop.unit = unit
Ejemplo n.º 11
0
 def get_curve_sets(self):
     OM = ObjectManager()
     curve_sets = OM.list('curve_set', self.uid)
     return curve_sets
Ejemplo n.º 12
0
class Dialog(wx.Dialog):
    def __init__(self, *args, **kwargs):
        if 'on_ok_callback' in kwargs:
            self.on_ok_callback = kwargs.pop('on_ok_callback')
        else:
            self.on_ok_callback = None

        if 'on_cancel_callback' in kwargs:
            self.on_cancel_callback = kwargs.pop('on_cancel_callback')
        else:
            self.on_cancel_callback = None

        super(Dialog, self).__init__(*args, **kwargs)

        self._OM = ObjectManager()
        self._OM.subscribe(self.on_wells_changed, 'add')
        self._OM.subscribe(self.on_wells_changed, 'post_remove')
        #self._OM.addcallback('add_object', self.on_wells_changed)
        #self._OM.addcallback('post_remove_object', self.on_wells_changed)

        self.well_selector = wx.Choice(self)
        self.well_selector.Bind(wx.EVT_CHOICE, self.on_well_select)

        self.export_panel = Panel(self)

        button_sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL)
        self.Bind(wx.EVT_BUTTON, self.on_button)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.well_selector, proportion=0, flag=wx.ALIGN_CENTER)
        vbox.Add(self.export_panel, proportion=1, flag=wx.ALL | wx.EXPAND)
        vbox.Add(button_sizer, flag=wx.ALIGN_RIGHT)
        self.SetSizer(vbox)

        self.SetSize((400, 600))
        self.SetTitle(u"Exportar:")

        self.welluid = None
        self.wellmap = []
        self.iwellmap = {}

        self.on_wells_changed(None)

    def get_welluid(self):
        return self.welluid

    def set_welluid(self, welluid):
        self.welluid = welluid
        self.well_selector.SetSelection(
            self.iwellmap.get(welluid, wx.NOT_FOUND))
        self.export_panel.set_welluid(welluid)

    def set_depth_selection(self, selection):
        self.export_panel.set_depth_selection(selection)

    def get_depth_selection(self):
        return self.export_panel.get_depth_selection()

    def set_log_selection(self, selection):
        self.export_panel.set_log_selection(selection)

    def get_log_selection(self):
        return self.export_panel.get_log_selection()

    def set_partition_selection(self, selection):
        self.export_panel.set_partition_selection(selection)

    def get_partition_selection(self):
        return self.export_panel.get_partition_selection()

    def set_property_selection(self, selection):
        self.export_panel.set_property_selection(selection)

    def get_property_selection(self):
        return self.export_panel.get_property_selection()

    def on_well_select(self, event):
        i = event.GetSelection()
        self.set_welluid(self.wellmap[i])

    def on_wells_changed(self, objuid):
        wellnames = []
        self.wellmap = []
        self.iwellmap.clear()
        self.well_selector.Clear()
        self.set_welluid(None)

        for i, well in enumerate(self._OM.list('well')):
            self.wellmap.append(well.uid)
            self.iwellmap[well.uid] = i
            wellnames.append(well.name)

        self.well_selector.AppendItems(wellnames)

        if len(self.wellmap) == 1:
            self.set_welluid(self.wellmap[0])

    def on_button(self, event):
        evt_id = event.GetId()
        if evt_id == wx.ID_OK and self.on_ok_callback is not None:
            self.on_ok_callback(event)
        elif evt_id == wx.ID_CANCEL and self.on_cancel_callback is not None:
            self.on_cancel_callback(event)
        event.Skip(True)

    def __del__(self):
        self._OM.removecallback("add", self.on_wells_changed)
        self._OM.removecallback("post-remove", self.on_wells_changed)
        super(Dialog, self).__del__()
Ejemplo n.º 13
0
def on_create_simulation(*args, **kwargs):
    OM = ObjectManager()
    UIM = UIManager()
    #
    models_od = OrderedDict()
    models = OM.list('acoustic_2d_model')
    for model in models:
        models_od[model.name] = model.uid    
    #
    wavelets_od = OrderedDict()
    wavelets = OM.list('wavelet')
    for wavelet in wavelets:
        wavelets_od[wavelet.name] = wavelet.uid    
    #
    dlg = UIM.create('dialog_controller', title='Create Staggered Grid Simulation')
    #
    ctn_models = dlg.view.AddCreateContainer('StaticBox', label='Select Model', 
                                              orient=wx.VERTICAL, proportion=0, 
                                              flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddChoice(ctn_models, proportion=0, flag=wx.EXPAND|wx.TOP, 
                       border=5, widget_name='model', options=models_od,
                       initial=0) 
    #
    ctn_wavelet = dlg.view.AddCreateContainer('StaticBox', label='Select Wavelet', 
                                              orient=wx.VERTICAL, proportion=0, 
                                              flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddChoice(ctn_wavelet, proportion=0, flag=wx.EXPAND|wx.TOP, 
                       border=5, widget_name='wavelet', options=wavelets_od,
                       initial=0)
    # #
    # ctn_dt = dlg.view.AddCreateContainer('StaticBox', 
    #                                 label='Wavelet Time Step (dt)', 
    #                                 orient=wx.VERTICAL, 
    #                                 proportion=0, 
    #                                 flag=wx.EXPAND|wx.TOP, border=5)
    # dlg.view.AddTextCtrl(ctn_dt, proportion=0, flag=wx.EXPAND|wx.TOP, 
    #                      border=5, widget_name='dt', initial='0.01') 
    # #

    # ctn_time_stop = dlg.view.AddCreateContainer('StaticBox', 
    #                                 label='Wavelet Time Stop', 
    #                                 orient=wx.VERTICAL, 
    #                                 proportion=0, 
    #                                 flag=wx.EXPAND|wx.TOP, border=5)
    # dlg.view.AddTextCtrl(ctn_time_stop, proportion=0, flag=wx.EXPAND|wx.TOP, 
    #                      border=5, widget_name='time_stop', initial='1.0') 
    # #   

    #
    ctn_soux = dlg.view.AddCreateContainer('StaticBox', 
                                    label='Source point X', 
                                    orient=wx.VERTICAL, 
                                    proportion=0, 
                                    flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_soux, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='soux', initial='0') 
    #
    ctn_souy = dlg.view.AddCreateContainer('StaticBox', 
                                    label='Source point Y', 
                                    orient=wx.VERTICAL, 
                                    proportion=0, 
                                    flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_souy, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='souy', initial='0') 
    #
    ctn_sim_steps = dlg.view.AddCreateContainer('StaticBox', 
                                    label='Simulation Steps', 
                                    orient=wx.VERTICAL, 
                                    proportion=0, 
                                    flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_sim_steps, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='sim_steps', initial='200') 
    #    
    
    #    
    ctn_name = dlg.view.AddCreateContainer('StaticBox', 
                                           label='Simulation name', 
                                           orient=wx.VERTICAL, 
                                           proportion=0, 
                                           flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_name, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='simulation_name', 
                         initial='Staggered Grid 2 Layers Model')     
    #    
    
    
    dlg.view.SetSize((300, 500))
    result = dlg.view.ShowModal()
    #
    try:
        #disableAll = wx.WindowDisabler()
        #wait = wx.BusyInfo("Creating simulation. Wait...")
        if result == wx.ID_OK:
            results = dlg.get_results()          
            #print (results)
            
            
            dialog = wx.ProgressDialog("Staggered grid simulation", "Time remaining", 
                                int(results.get('sim_steps')),
                                style=wx.PD_CAN_ABORT|wx.PD_ELAPSED_TIME|wx.PD_REMAINING_TIME
            )
            
            wavefield, dx, dy, dt, cfl, c1 = staggeredGrid(results.get('model'),
                                                  results.get('wavelet'),
                                                  int(results.get('sim_steps')),
                                                  sou_x=int(results.get('soux')),
                                                  sou_y=int(results.get('souy')),
                                                  progress_dialog=dialog
            )
            #
            
            #
            simulation = OM.new('simulation', wavefield,
                                dx=dx, dy=dy, dt=dt,
                                sou_x=int(results.get('soux')),
                                sou_y=int(results.get('souy')),            
                                model_uid= results.get('model'),
                                wavelet_uid= results.get('wavelet'),
                                name=results.get('simulation_name'),
                                cfl=cfl, 
                                c1=c1)
            
                                #_type="Ricker", 
            # wavelet = OM.new('wavelet', _type="Ricker", 
            #                  f0=results.get('f0'), 
            #                  amp=results.get('amp'), 
            #                  name=results.get('wavelet_name'))
                             
            result = OM.add(simulation)
            
            print ('result simulation:', result, args, kwargs)
            
            
    except Exception as e:
        print ('ERROR [on_create_model]:', str(e))
        #raise
        
    finally:
        dialog.Destroy()
        #del wait
        #del disableAll
        UIM.remove(dlg.uid)            
Ejemplo n.º 14
0
def staggeredGrid(model_uid, wavelet_uid, sim_steps, **kwargs):

    OM = ObjectManager()
    model = OM.get(model_uid)
    wavelet = OM.get(wavelet_uid)

    layers = OM.list(parent_uid=model.uid)
    geo_layer_1 = layers[0]

    if len(layers) == 2:
        geo_layer_2 = layers[1]
    elif len(layers) == 1:
        geo_layer_2 = layers[0]
    else:
        raise Exception()

    # Discretization
    c1 = 20  # Number of grid points per dominant wavelength
    c2 = 0.5  # CFL-Number

    progress_dialog = kwargs.get("progress_dialog")

    #dx = kwargs['dx']
    #dy = kwargs['dy']
    #dt = kwargs['dt']

    #f0 = kwargs['f0']
    #amp = kwargs['amp']

    # nx = input_vec.shape[0]  # Number of grid points in X
    # ny = input_vec.shape[1]  # Number of grid points in Y
    T = 1.0  # Total propagation time

    # Source Position
    sou_x = kwargs['sou_x']  # Source position (in grid points) in X
    sou_y = kwargs['sou_y']  # Source position (in grid points) in Y

    # No vetor grid, pontos com valor 1 estao associados a Fase 1 (rocha,
    # cor preta). Os pontos com valor 0 estao associados a Fase 2 (poros,
    # de cor branca).
    # rho1 = 3.0
    # vp1 = 4000.0
    # #
    # rho2 = 2.2
    # vp2 = 2500.0

    image = model._get_image()

    vp_grid = np.where(image.data == geo_layer_1.value, geo_layer_1.vp,
                       geo_layer_2.vp)
    rho_grid = np.where(image.data == geo_layer_1.value, geo_layer_1.rho,
                        geo_layer_2.rho)

    ## Preparation

    # Init wavefields
    vx = np.zeros((model.ny, model.nx))
    vy = np.zeros((model.ny, model.nx))
    #
    wavefield = np.zeros((sim_steps, model.ny, model.nx))
    #

    # Calculate first Lame-Paramter
    lambda1 = geo_layer_1.rho * geo_layer_1.vp * geo_layer_1.vp
    lambda2 = geo_layer_2.rho * geo_layer_2.vp * geo_layer_2.vp

    lame_lambda = np.where(image.data == geo_layer_1.value, lambda1, lambda2)

    cmin = min(vp_grid.flatten())  # Lowest P-wave velocity
    cmax = max(vp_grid.flatten())  # Highest P-wave velocity

    fmax = 2 * wavelet.f0  # Maximum frequency

    #dx = 15.0 #0.000001 * 74 * 4
    #dy = dx                         # Spatial discretization (in m)
    dt = model.dx / (cmax) * c2  # Temporal discretization (in s)

    dt_dx = dt / model.dx

    #CFL_number = (cmax * dt) / dx
    CFL_number = cmax * dt_dx

    print()
    print("CFL_number: ")
    print(CFL_number)
    print("vx dtype: " + str(vx.dtype))
    print("vy dtype: " + str(vy.dtype))
    print("wavefield dtype: " + str(wavefield.dtype))
    print("rho_grid dtype: " + str(rho_grid.dtype))
    print("lame_lambda dtype: " + str(lame_lambda.dtype))

    lampda_min = cmin / fmax  # Smallest wavelength

    #dx = cmin/(fmax*c1)             # Spatial discretization (in m)
    #dy = dx                         # Spatial discretization (in m)

    # ## Create space and time vector
    x = np.arange(0, model.dx * model.nx, model.dx)  # Space vector in X
    y = np.arange(0, model.dy * model.ny, model.dy)  # Space vector in Y

    time_ = np.arange(0, T, dt)  # Time vector
    nt = np.size(time_)  # Number of time steps

    print()
    print('time_.shape:')
    print(time_.shape, T, dt, time_[0], time_[-1])
    print()

    print(model.dx, model.dy, dt)

    significance = 0.0000001
    wavelet_data = wavelet.get_amplitude_data(time_)

    ###
    idx = len(wavelet_data) - 1
    segue = True
    for i in range(len(wavelet_data) - 1, -1, -1):
        #print(str(i) + " - " + str(wavelet[i]))
        if np.absolute(
                wavelet_data[i]) > (wavelet.amp * significance) and segue:
            idx = i
            segue = False

    print("\n\n")
    print("last idx: " + str(len(wavelet_data) - 1))
    print("idx: ", idx)
    print("time: ", time_[idx])

    print("\n\n")

    time_ = np.arange(0, (idx + 2) * dt, dt)  # Time vector
    nt = np.size(time_)  # Number of time steps

    wavelet_data = wavelet.get_amplitude_data(time_)

    ###

    # # ## Source signal - Ricker-wavelet
    # tau = np.pi * f0 * (t - 1.5 / f0)

    # print('tau')
    # print(tau.min(), tau.max())

    print()
    print('wavelet_data.shape:')
    print(wavelet_data.shape)
    print()

    # ## Source signal - Ricker-wavelet

    #    tau = np.pi*f0*(t-1.5/f0)
    #    q = q0*(1.0-2.0*tau**2.0)*np.exp(-tau**2)

    #c1 = cmin/(fmax*model.dx)
    n_gp_wl = cmin / (fmax * model.dx)
    print("Number of gridpoints per minimum wavelength: ", n_gp_wl)

    # print("Number of grid points per dominant wavelength: ", lampda_min/model.dx)

    # Calculation of coefficients c1 and c2.
    # These are used to obtain a second-order accurate time, fourth-order
    # accurate space. (Levander, 1988)
    c1 = 9.0 / 8.0
    c2 = 1.0 / 24.0
    #
    # c1_dx = c1 / dx
    # c2_dx = c2 / dx
    # #
    # c1_dy = c1 / dy
    # c2_dy = c2 / dy
    #

    # The true calculation starts here...
    #
    for it in range(sim_steps):

        # Update Progress Dialog if exists
        if progress_dialog:
            if progress_dialog.WasCancelled():
                raise Exception("wx.ProgressDialog.WasCancelled")
            progress_dialog.Update(it)

        # First step is just for reference
        if it == 0:
            continue

        # Wavefield at step it is based on step it-1
        wavefield[it, :, :] = wavefield[it - 1, :, :]

        # Update velocity
        for kx in range(5, model.nx - 4):
            for ky in range(5, model.ny - 4):
                #
                # Calculate stress derivatives, p_dx(+) e p_dy(+)
                p_x = c1 * (wavefield[it, ky, kx+1] - wavefield[it, ky, kx]) - \
                      c2 * (wavefield[it, ky, kx+2] - wavefield[it, ky, kx-1])  # Eq. A-2 Lavender, 1988
                #
                p_y = c1 * (wavefield[it, ky+1, kx] - wavefield[it, ky, kx]) - \
                      c2 * (wavefield[it, ky+2, kx] - wavefield[it, ky-1, kx])
                #
                #
                # Now, based on stress derivatives, calculate vx and vy for all grid points.
                try:
                    vx[ky, kx] -= (dt_dx / rho_grid[ky, kx]) * p_x
                    vy[ky, kx] -= (dt_dx / rho_grid[ky, kx]) * p_y
                except:
                    print("rho_grid[ky, kx]: ", ky, kx, rho_grid[ky, kx])
                    print("vx[ky, kx]: ", ky, kx, vx[ky, kx])
                    print("vy[ky, kx]: ", ky, kx, vy[ky, kx])
                    pass

        # boundary condition clears velocities on boundaries
        # Boundaries V
        # if ky == 5:
        #     p_x = p_y = 0

        # # Boundaries
        # for kx in range(0, model.nx):
        #     for ky in range(0, 5):
        #         wavefield[it, ky, kx] = 0.0

        # Boundaries - Free surface at top at Pos y=4
        # top_bnd_top_pos = 4
        # for kx in range(0, model.nx):
        #     vy[top_bnd_top_pos, kx]   = vy[top_bnd_top_pos+1, kx]
        #     vy[top_bnd_top_pos-1, kx] = vy[top_bnd_top_pos+2, kx]

        # Inject source wavelet
        if it < np.size(wavelet_data):
            wavefield[it, sou_y, sou_x] += wavelet_data[it]

        # Update wavefield
        for kx in range(5, model.nx - 4):
            for ky in range(5, model.ny - 4):

                # Velocity derivatives, vx_dx(-) e vy_dy(-)  # Qian et al 2013
                vx_x = c1 * (vx[ky, kx] - vx[ky, kx - 1]) - c2 * (
                    vx[ky, kx + 1] - vx[ky, kx - 2])  # Dx-,
                vy_y = c1 * (vy[ky, kx] - vy[ky - 1, kx]) - c2 * (
                    vy[ky + 1, kx] - vy[ky - 2, kx])  # Dy-,

                # if ky == 5:
                #     vx_x = vy_y = 0.0

                #
                wavefield[it, ky,
                          kx] -= (dt_dx * lame_lambda[ky, kx]) * (vx_x + vy_y)

        # Boundaries
        # for kx in range(0, model.nx):
        # #     for ky in range(0, 5):
        #     wavefield[it, 4, kx] = 0.0
        #     wavefield[it, 3, kx] = 0.0

    print("Wavefield Min-Max: ", np.min(wavefield), " - ", np.max(wavefield))
    print(model.dx, model.dy, dt)
    return wavefield, model.dx, model.dy, dt, CFL_number, n_gp_wl
Ejemplo n.º 15
0
class Dialog(wx.Dialog):
    @debugdecorator
    def __init__(self, *args, **kwargs):
        if 'size' not in kwargs:
            kwargs['size'] = (640, 480)

        super(Dialog, self).__init__(*args, **kwargs)

        self.OM = ObjectManager()

        self.currentwellindex = 0
        self.currentrocktableindex = 0

        self.tables = []

        self.rocktablemap = [
            rocktable.uid for rocktable in self.OM.list('rocktable')
        ]
        work_table = []
        for rocktable in self.OM.list('rocktable'):
            work_table.append(RockTable(rocktable.uid))
        self.tables.append(work_table)
        self.grid = wx.grid.Grid(self)
        self.grid.SetDefaultColSize(100)

        #        else:
        self.grid.SetTable(
            self.tables[self.currentwellindex][self.currentrocktableindex])
        self.grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.on_cell_dlclick)
        self.grid.Bind(wx.grid.EVT_GRID_LABEL_LEFT_DCLICK,
                       self.on_label_dlclick)

        toolbar_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.rocktable_choice = wx.Choice(self)
        self.rocktable_choice.AppendItems([
            self.OM.get(rocktableuid).name
            for rocktableuid in self.rocktablemap
        ])
        self.rocktable_choice.SetSelection(self.currentrocktableindex)
        self.rocktable_choice.Bind(wx.EVT_CHOICE, self.on_rocktable_choice)

        add_rocktype_button = wx.Button(self, label='ADD ROCK TYPE')
        add_rocktype_button.Bind(wx.EVT_BUTTON, self.on_add_rocktype)

        remove_rocktype_button = wx.Button(self, label='REM ROCK TYPE')
        remove_rocktype_button.Bind(wx.EVT_BUTTON, self.on_remove_rocktype)

        toolbar_sizer.Add(self.rocktable_choice, 1, wx.ALIGN_LEFT)
        toolbar_sizer.Add(add_rocktype_button, 0, wx.ALIGN_LEFT)
        toolbar_sizer.Add(remove_rocktype_button, 0, wx.ALIGN_LEFT)

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(toolbar_sizer, proportion=0, flag=wx.EXPAND)
        main_sizer.Add(self.grid, proportion=1, flag=wx.EXPAND)

        self.SetSizer(main_sizer)

    @debugdecorator
    def on_rocktable_choice(self, event):
        idx = event.GetSelection()
        if idx != self.currentrocktableindex:
            self.currentrocktableindex = idx
            self.grid.SetTable(
                self.tables[self.currentwellindex][self.currentrocktableindex])

            self.grid.ForceRefresh()

    @debugdecorator
    def on_add_rocktype(self, event):
        self.grid.AppendRows()
        self.grid.ForceRefresh()

    def on_remove_rocktype(self, event):
        to_remove = self.grid.GetSelectedRows()
        self.grid.ClearSelection()
        for i in to_remove[::-1]:
            self.grid.DeleteRows(i)
        self.grid.ForceRefresh()

    @debugdecorator
    def on_cell_dlclick(self, event):
        if event.GetCol() == 1:
            row = event.GetRow()
            table = self.tables[self.currentwellindex][
                self.currentrocktableindex]
            color = table.get_color(row)

            global COLOUR_DATA
            COLOUR_DATA.SetColour(color)

            dlg = wx.ColourDialog(self, COLOUR_DATA)

            if dlg.ShowModal() == wx.ID_OK:
                COLOUR_DATA = dlg.GetColourData()
                color = COLOUR_DATA.GetColour().Get(True)
                # TODO: alpha
                table.set_color(row, color)
                self.grid.ForceRefresh()
            dlg.Destroy()
        else:
            event.Skip()

    @debugdecorator
    def on_label_dlclick(self, event):
        row = event.GetRow()
        col = event.GetCol()
        table = self.tables[self.currentwellindex][self.currentrocktableindex]
        if row == -1 and col >= table.N_COLS:
            name, unit = table.get_nameunit(col)
            dlg = PropertyEntryDialog(self)
            dlg.set_value(name, unit)

            if dlg.ShowModal() == wx.ID_OK:
                name, unit = dlg.get_value()
                table.set_nameunit(col, name, unit)
                self.grid.ForceRefresh()
Ejemplo n.º 16
0
def on_create_model(*args, **kwargs):
    
    OM = ObjectManager()
    UIM = UIManager()
    
    

    #
    images_od = OrderedDict()
    images = OM.list('image')
    for image in images:
        images_od[image.name] = image.uid    

    #
    dlg = UIM.create('dialog_controller', title='Chose image for model input')
    ctn_image = dlg.view.AddCreateContainer('StaticBox', label='Select Image', 
                                            orient=wx.VERTICAL, proportion=0, 
                                            flag=wx.EXPAND|wx.TOP, border=5)


    dlg.view.AddChoice(ctn_image, proportion=0, flag=wx.EXPAND|wx.TOP, 
                       border=5, widget_name='images_choice', options=images_od,
                       initial=0) 
    #
    
    dlg.view.SetSize((300, 180))
    result = dlg.view.ShowModal()

  
    
    if result == wx.ID_OK:
        results = dlg.get_results()  
            
        print(results)    
    
        image_uid = results.get("images_choice")    
        
        if not image_uid:
            return
        
        image = OM.get(image_uid)    
    
    
        values = np.unique(image.data)
        print(values)
        print(values.size)
    
        if values.size > 2:
            raise Exception("ERRO!")
    
    
        #
        dlg = UIM.create('dialog_controller', title='Create model')


        ctn_model = dlg.view.AddCreateContainer('StaticBox', label='Model', orient=wx.VERTICAL, 
                                                  proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
        #
        box_img_input = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                               orient=wx.HORIZONTAL, proportion=1, 
                                               flag=wx.EXPAND|wx.ALL, border=5)
        dlg.view.AddStaticText(box_img_input, label='Image input:', proportion=1)        
        dlg.view.AddTextCtrl(box_img_input, proportion=1, flag=wx.ALIGN_LEFT, border=5, 
                             widget_name='image_name', initial=image.name)         
        textctrl_image_name = dlg.view.get_object('image_name')
        textctrl_image_name.disable()        
        #
        box_name = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                               orient=wx.HORIZONTAL, proportion=1, 
                                               flag=wx.EXPAND|wx.ALL, border=5)
        dlg.view.AddStaticText(box_name, label='Name:', proportion=1)
        dlg.view.AddTextCtrl(box_name, proportion=1, flag=wx.ALIGN_LEFT, border=5, 
                             widget_name='model_name', initial="My model") 
        #
    
    
    # X Axis
    #
    def on_change_x_size(name, old_value, new_value, **kwargs):
        try:
            x_samples = float(dlg.view.get_object('x_samples').get_value())
            x_spacing = float(dlg.view.get_object('x_spacing').get_value())
            res = str(x_samples * x_spacing) 
        except:
            res = ""
        textctrl_x_size = dlg.view.get_object('x_size')
        textctrl_x_size.set_value(res)      
    #
    #
    ctn_x_axis = dlg.view.AddCreateContainer('StaticBox', label='X axis', 
        orient=wx.HORIZONTAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    #
    ctn_x_samples = dlg.view.AddCreateContainer('StaticBox', ctn_x_axis, 
            label='Samples(pixels)', orient=wx.VERTICAL, proportion=1, 
            flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_x_samples, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='x_samples', initial=image.width)
    textctrl_x_pixels = dlg.view.get_object('x_samples')
    textctrl_x_pixels.disable()
    #textctrl_x_samples.set_trigger(on_change_x_size)
    #
    ctn_x_spacing = dlg.view.AddCreateContainer('StaticBox', ctn_x_axis, 
                label='Spacing(m)', orient=wx.VERTICAL, proportion=1, 
                flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_x_spacing, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='x_spacing', initial=1)
    
    
    textctrl_x_spacing = dlg.view.get_object('x_spacing')
    textctrl_x_spacing.set_trigger(on_change_x_size)
    #
    ctn_x_size = dlg.view.AddCreateContainer('StaticBox', ctn_x_axis, 
                label='Size(m)', orient=wx.VERTICAL, proportion=1, 
                flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_x_size, proportion=1, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='x_size')
    textctrl_x_size = dlg.view.get_object('x_size')
    textctrl_x_size.disable()
    #
    on_change_x_size(None, None, None)
    #    
          
    
    # Y Axis
    #   
    def on_change_y_size(name, old_value, new_value, **kwargs):
        try:
            y_samples = float(dlg.view.get_object('y_samples').get_value())
            y_spacing = float(dlg.view.get_object('y_spacing').get_value())
            res = str(y_samples * y_spacing) 
        except:
            res = ""
        textctrl_y_size = dlg.view.get_object('y_size')
        textctrl_y_size.set_value(res)      
    #
    #
    ctn_y_axis = dlg.view.AddCreateContainer('StaticBox', label='Y axis', 
                                             orient=wx.HORIZONTAL, 
                                             proportion=0, 
                                             flag=wx.EXPAND|wx.TOP, border=5)
    #
    ctn_y_samples = dlg.view.AddCreateContainer('StaticBox', ctn_y_axis, 
                                                label='Samples(pixels)', 
                                                orient=wx.VERTICAL, 
                                                proportion=1, 
                                                flag=wx.EXPAND|wx.TOP, 
                                                border=5)
    dlg.view.AddTextCtrl(ctn_y_samples, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='y_samples', initial=image.height)
    textctrl_y_pixels = dlg.view.get_object('y_samples')
    textctrl_y_pixels.disable()
    #textctrl_y_samples.set_trigger(on_change_y_size)
    #
    ctn_y_spacing = dlg.view.AddCreateContainer('StaticBox', ctn_y_axis, 
                                                label='Spacing(m)', 
                                                orient=wx.VERTICAL, 
                                                proportion=1, 
                                                flag=wx.EXPAND|wx.TOP, 
                                                border=5)
    dlg.view.AddTextCtrl(ctn_y_spacing, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='y_spacing', initial=1)
    textctrl_y_spacing = dlg.view.get_object('y_spacing')
    textctrl_y_spacing.set_trigger(on_change_y_size)
    #
    ctn_y_size = dlg.view.AddCreateContainer('StaticBox', ctn_y_axis, 
                                                label='Size(m)', 
                                                orient=wx.VERTICAL, 
                                                proportion=1, 
                                                flag=wx.EXPAND|wx.TOP, 
                                                border=5)
    dlg.view.AddTextCtrl(ctn_y_size, proportion=1, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='y_size')
    textctrl_y_size = dlg.view.get_object('y_size')
    textctrl_y_size.disable()
    #
    on_change_y_size(None, None, None)
    #    
    
    if values[0] == 0:
        value_layer_1_text = "color: Black"
    elif values[0] == 255:    
        value_layer_1_text = "color: White"
    else:    
        value_layer_1_text = "value: " + str(values[0])
    
    ctn_prop_matrix = dlg.view.AddCreateContainer('StaticBox', 
            label="Layer 1 properties (" + value_layer_1_text + ")", 
            orient=wx.HORIZONTAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    #
    ctn_matrix_vp = dlg.view.AddCreateContainer('StaticBox', ctn_prop_matrix, 
                                                label='Vp(m/s)', orient=wx.VERTICAL, proportion=1, flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_matrix_vp, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='matrix_vp', initial=4000.0)  
    #
    ctn_matrix_rho = dlg.view.AddCreateContainer('StaticBox', ctn_prop_matrix, 
                                                label='Rho(m/s)', orient=wx.VERTICAL, proportion=1, flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_matrix_rho, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='matrix_rho', initial=3.0)  
    #
    
    if values.size == 2:
        if values[1] == 0:
            value_layer_2_text = "color: Black"
        elif values[1] == 255:    
            value_layer_2_text = "color: White"
        else:    
            value_layer_2_text = "value: " + str(values[1])
            
        ctn_prop_pores = dlg.view.AddCreateContainer('StaticBox',
                label="Layer 2 properties (" + value_layer_2_text + ")", 
                orient=wx.HORIZONTAL, 
                proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
        #          
        ctn_pores_vp = dlg.view.AddCreateContainer('StaticBox', ctn_prop_pores, 
                label='Vp(m/s)', orient=wx.VERTICAL, 
                proportion=1, flag=wx.EXPAND|wx.TOP, border=5)
        dlg.view.AddTextCtrl(ctn_pores_vp, proportion=0, flag=wx.EXPAND|wx.TOP, 
                             border=5, widget_name='pores_vp', initial=2500.0)  
        #
        ctn_pores_rho = dlg.view.AddCreateContainer('StaticBox', ctn_prop_pores, 
                label='Rho(m/s)', orient=wx.VERTICAL, proportion=1, 
                flag=wx.EXPAND|wx.TOP, border=5)
        dlg.view.AddTextCtrl(ctn_pores_rho, proportion=0, flag=wx.EXPAND|wx.TOP, 
                             border=5, widget_name='pores_rho', initial=2.2)  
        #    
    
    dlg.view.SetSize((400, 580))
    result = dlg.view.ShowModal()

    try:
        disableAll = wx.WindowDisabler()
        wait = wx.BusyInfo("Creating model. Wait...")
        if result == wx.ID_OK:
            results = dlg.get_results()  
            
            print(results)


            am = OM.new('acoustic_2d_model', 
                        image_uid=image.uid,
                        dx=results.get('x_spacing'), 
                        dy=results.get('y_spacing'), 
                        name=results.get('model_name'))
            result = OM.add(am)
            
            print ('result acoustic_2d_model:', result, args, kwargs)
    

    
            layer1 = OM.new('geolayer', value=values[0], 
                    vp=results.get('matrix_vp'), rho=results.get('matrix_rho'),
                    name="Layer 1")
            result = OM.add(layer1, am.uid)
            print ('result layer 1:', result)
            
            
            if values.size == 2:
                layer2 = OM.new('geolayer', value=values[1], 
                    vp=results.get('pores_vp'), rho=results.get('pores_rho'), 
                    name="Layer 2")
                result = OM.add(layer2, am.uid)
                print ('result layer 2:', result)    
    
    

            
            
    except Exception as e:
        print ('ERROR [on_create_model]:', str(e))
        raise
    finally:
        del wait
        del disableAll
        UIM.remove(dlg.uid)
Ejemplo n.º 17
0
class ReflectivityModel():
    def __init__(self):
        self.OM = ObjectManager()

        self.flagRB = 1

        self.modtype = OrderedDict()
        self.modtype['PP Seismogram'] = 0
        self.modtype['PS Seismogram'] = 1

        self.modresponse = OrderedDict()
        self.modresponse['Complete Response'] = 1
        self.modresponse['Primaries and Internal Multiples'] = 2
        self.modresponse['Only Primaries Reflections'] = 3

        self.wellOptions = OrderedDict()

        for well in self.OM.list('well'):
            self.wellOptions[well.name] = well.uid

        self.outtype = OrderedDict()
        self.outtype['T-X Seismogram'] = 1
        self.outtype['T-X NMO-Corrected Seismogram'] = 2
        self.outtype['Tau-P Seismogram'] = 3
        self.outtype['Tau-P NMO-Corrected Seismogram'] = 4
        self.outtype['Angle Gather'] = 5

        self.dlg = wx.Dialog(None, title='Reflectivity Modeling')
        ico = GripyIcon('logo-transp.ico', wx.BITMAP_TYPE_ICO)
        self.dlg.SetIcon(ico)

        modStatLin = wx.StaticText(self.dlg, -1, "Modeling Type:")
        modStatLin.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.modChoiceBox = wx.Choice(self.dlg,
                                      -1,
                                      choices=self.modtype.keys())

        respStatLin = wx.StaticText(self.dlg, -1, "Response Type:")
        respStatLin.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.respChoiceBox = wx.Choice(self.dlg,
                                       -1,
                                       choices=self.modresponse.keys())

        logStatLin = wx.StaticText(self.dlg, -1, "Input Logs from Well:")
        logStatLin.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))

        self.logOptions = OrderedDict()

        self.wellChoiceBox = wx.Choice(self.dlg,
                                       -1,
                                       choices=self.wellOptions.keys())
        self.wellChoiceBox.Bind(wx.EVT_CHOICE, self.on_well_choice)

        outStatLin = wx.StaticText(self.dlg, -1, "Output Type")
        outStatLin.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.outChoiceBox = wx.Choice(self.dlg,
                                      -1,
                                      choices=self.outtype.keys())

        objStatLin = wx.StaticText(self.dlg, -1, "Output Name")
        objStatLin.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.objTxtCtrl = wx.TextCtrl(self.dlg, -1, "NEW_NAME")

        vpStatLin = wx.StaticText(self.dlg, -1, "P-Wave Velocity")
        self.vpChoiceBox = wx.Choice(self.dlg,
                                     -1,
                                     choices=self.logOptions.keys())

        vsStatLin = wx.StaticText(self.dlg, -1, "S-Wave Velocity")
        self.vsChoiceBox = wx.Choice(self.dlg,
                                     -1,
                                     choices=self.logOptions.keys())

        rhoStatLin = wx.StaticText(self.dlg, -1, "Density")
        self.rhoChoiceBox = wx.Choice(self.dlg,
                                      -1,
                                      choices=self.logOptions.keys())

        qvalueStatLin = wx.StaticText(self.dlg, -1, "Use Q values from logs?")
        qvalueStatLin.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.yesQvalueRB = wx.RadioButton(self.dlg, -1, 'Yes')
        self.noQvalueRB = wx.RadioButton(self.dlg, -1, 'No')

        self.dlg.Bind(wx.EVT_RADIOBUTTON,
                      self.on_yes_rb,
                      id=self.yesQvalueRB.GetId())
        self.dlg.Bind(wx.EVT_RADIOBUTTON,
                      self.on_no_rb,
                      id=self.noQvalueRB.GetId())

        parStatLin = wx.StaticText(
            self.dlg,
            -1,
            "Parameters List",
        )
        parStatLin.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))

        nsampStatLin = wx.StaticText(self.dlg, -1, "Number of Samples:")
        self.nsampTxtCtrl = wx.TextCtrl(self.dlg, -1, "256")

        dtStatLin = wx.StaticText(self.dlg, -1, "Sample Rate:")
        self.dtTxtCtrl = wx.TextCtrl(self.dlg, -1, "0.004")

        fwavStatLin = wx.StaticText(self.dlg, -1,
                                    "Wavelet Peak Frequency (Hz):")
        self.fwavTxtCtrl = wx.TextCtrl(self.dlg, -1, "30.0")

        ntrcsStatLin = wx.StaticText(self.dlg, -1, "Number of Traces:")
        self.ntrcsTxtCtrl = wx.TextCtrl(self.dlg, -1, "50")

        trc1StatLin = wx.StaticText(self.dlg, -1, "Trace 1 Cordinate:")
        self.trc1TxtCtrl = wx.TextCtrl(self.dlg, -1, "10.0")

        latdtStatLin = wx.StaticText(self.dlg, -1, "Lateral Cordenate Rate:")
        self.latdtTxtCtrl = wx.TextCtrl(self.dlg, -1, "12.5")

        cam1velStatLin = wx.StaticText(self.dlg, -1,
                                       "First Layer Velocity (m/s):")
        self.cam1velTxtCtrl = wx.TextCtrl(self.dlg, -1, "1500")

        cam1thickStatLin = wx.StaticText(self.dlg, -1,
                                         "First Layer Thickness (m):")
        self.cam1thickTxtCtrl = wx.TextCtrl(self.dlg, -1, "0.0")

        nsupStatLin = wx.StaticText(self.dlg, -1, "Number of Sup Layers:")
        self.nsupTxtCtrl = wx.TextCtrl(self.dlg, -1, "40")

        zsupStatLin = wx.StaticText(self.dlg, -1, "Thickness of Sup Layers:")
        self.zsupTxtCtrl = wx.TextCtrl(self.dlg, -1, "20.0")

        firstLayerStatLin = wx.StaticText(
            self.dlg, -1, "Depth of First Layer to be Modeled:")
        self.firstLayerTxtCtrl = wx.TextCtrl(self.dlg, -1, "100.00")

        lastLayerStatLin = wx.StaticText(self.dlg, -1,
                                         "Depth of Last Layer to be Modeled:")
        self.lastLayerTxtCtrl = wx.TextCtrl(self.dlg, -1, "270")

        pnumStatLin = wx.StaticText(self.dlg, -1, "Number of Ray Parameters:")
        self.pnumTxtCtrl = wx.TextCtrl(self.dlg, -1, "1000")

        angmaxStatLin = wx.StaticText(self.dlg, -1,
                                      "Maximum Angle of Incidence:")
        self.angmaxTxtCtrl = wx.TextCtrl(self.dlg, -1, "75.0")

        vpSupStatLin = wx.StaticText(self.dlg, -1, "Sup Layers P velocity:")
        self.vpSupTxtCtrl = wx.TextCtrl(self.dlg, -1, "3100.00")

        vsSupStatLin = wx.StaticText(self.dlg, -1, "Sup Layers S velocity:")
        self.vsSupTxtCtrl = wx.TextCtrl(self.dlg, -1, "1640.00")

        wellSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=3)
        wellSizer.Add(logStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        wellSizer.Add(self.wellChoiceBox, 0, wx.EXPAND | wx.ALL, 5)

        logSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=3)
        logSizer.AddGrowableCol(1)
        logSizer.Add(vpStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        logSizer.Add(self.vpChoiceBox, 0, wx.EXPAND | wx.ALL, 5)
        logSizer.Add(vsStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        logSizer.Add(self.vsChoiceBox, 0, wx.EXPAND | wx.ALL, 5)
        logSizer.Add(rhoStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        logSizer.Add(self.rhoChoiceBox, 0, wx.EXPAND | wx.ALL, 5)

        rbSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=3)
        rbSizer.Add(qvalueStatLin, 0,
                    wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        rbSizer.Add(self.yesQvalueRB, 0)
        rbSizer.Add(self.noQvalueRB, 0)

        parSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
        parSizer.Add(nsampStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.nsampTxtCtrl,
            0,
        )
        parSizer.Add(cam1velStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.cam1velTxtCtrl,
            0,
        )
        parSizer.Add(dtStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.dtTxtCtrl,
            0,
        )
        parSizer.Add(cam1thickStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.cam1thickTxtCtrl,
            0,
        )
        parSizer.Add(ntrcsStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.ntrcsTxtCtrl,
            0,
        )
        parSizer.Add(vpSupStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.vpSupTxtCtrl,
            0,
        )
        parSizer.Add(trc1StatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.trc1TxtCtrl,
            0,
        )
        parSizer.Add(vsSupStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.vsSupTxtCtrl,
            0,
        )
        parSizer.Add(latdtStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.latdtTxtCtrl,
            0,
        )
        parSizer.Add(nsupStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.nsupTxtCtrl,
            0,
        )
        parSizer.Add(fwavStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.fwavTxtCtrl,
            0,
        )
        parSizer.Add(zsupStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.zsupTxtCtrl,
            0,
        )
        parSizer.Add(firstLayerStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.firstLayerTxtCtrl,
            0,
        )
        parSizer.Add(angmaxStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.angmaxTxtCtrl,
            0,
        )
        parSizer.Add(lastLayerStatLin, 0,
                     wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.lastLayerTxtCtrl,
            0,
        )
        parSizer.Add(pnumStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        parSizer.Add(
            self.pnumTxtCtrl,
            0,
        )

        outSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        outSizer.AddGrowableCol(1)
        outSizer.Add(outStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        outSizer.Add(self.outChoiceBox, 0, wx.EXPAND | wx.ALL, 5)
        outSizer.Add(objStatLin, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        outSizer.Add(self.objTxtCtrl, 0, wx.EXPAND | wx.ALL, 5)

        self.dlg.Bind(wx.EVT_BUTTON, self.on_ok, id=wx.ID_OK)
        btnSizer = self.dlg.CreateButtonSizer(wx.OK | wx.CANCEL)

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.mainSizer.Add(modStatLin, 0, wx.ALL, 5)
        self.mainSizer.Add(self.modChoiceBox, 0, wx.EXPAND | wx.ALL, 5)
        self.mainSizer.Add(respStatLin, 0, wx.ALL, 5)
        self.mainSizer.Add(self.respChoiceBox, 0, wx.EXPAND | wx.ALL, 5)
        self.mainSizer.Add(wx.StaticLine(self.dlg), 0,
                           wx.EXPAND | wx.TOP | wx.BOTTOM, 5)
        self.mainSizer.Add(wellSizer, 0, wx.ALL, 5)
        self.mainSizer.Add(logSizer, 0, wx.EXPAND | wx.ALL, 10)
        self.mainSizer.Add(rbSizer, 0, wx.ALL, 5)
        self.mainSizer.Add(wx.StaticLine(self.dlg), 0,
                           wx.EXPAND | wx.TOP | wx.BOTTOM, 5)
        self.mainSizer.Add(parStatLin, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL,
                           5)
        self.mainSizer.Add(parSizer, 0, wx.EXPAND | wx.ALL, 10)
        self.mainSizer.Add(wx.StaticLine(self.dlg), 0,
                           wx.EXPAND | wx.TOP | wx.BOTTOM, 5)
        self.mainSizer.Add(outSizer, 0, wx.EXPAND | wx.ALL, 10)
        self.mainSizer.Add(btnSizer,
                           flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM,
                           border=10)

        self.dlg.SetSizer(self.mainSizer)
        self.dlg.SetSize((610, 780))
        self.dlg.ShowModal()

    def on_yes_rb(self, event):

        if self.flagRB == 1:
            self.qpStatLin = wx.StaticText(self.dlg, -1, "Q value for P-Wave:")
            self.qpChoiceBox = wx.Choice(self.dlg,
                                         -1,
                                         choices=self.logOptions.keys())
            self.qsStatLin = wx.StaticText(self.dlg, -1, "Q value for S-Wave:")
            self.qsChoiceBox = wx.Choice(self.dlg,
                                         -1,
                                         choices=self.logOptions.keys())
            self.qSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=3)
            self.qSizer.AddGrowableCol(1)
            self.qSizer.Add(self.qpStatLin, 0, wx.ALL, 5)
            self.qSizer.Add(self.qpChoiceBox, 0, wx.EXPAND | wx.ALL, 5)
            self.qSizer.Add(self.qsStatLin, 0, wx.ALL, 5)
            self.qSizer.Add(self.qsChoiceBox, 0, wx.EXPAND | wx.ALL, 5)
            self.mainSizer.Insert(8, self.qSizer, 0, wx.EXPAND | wx.ALL, 5)
            self.flagRB = 0

        self.dlg.SetSize((610, 860))

    def on_no_rb(self, event):

        if self.flagRB == 0:
            self.mainSizer.Remove(self.qSizer)
            self.qpStatLin.Destroy()
            self.qpChoiceBox.Destroy()
            self.qsStatLin.Destroy()
            self.qsChoiceBox.Destroy()

            self.dlg.SetSize((610, 780))
            self.flagRB = 1

    def on_well_choice(self, event):
        wellname = self.wellChoiceBox.GetStringSelection()
        wellUid = self.wellOptions[wellname]
        self.vpChoiceBox.Clear()
        self.vsChoiceBox.Clear()
        self.rhoChoiceBox.Clear()
        self.logOptions.clear()
        for log in self.OM.list('log', wellUid):
            self.logOptions[log.name] = log.uid
        self.vpChoiceBox.AppendItems(self.logOptions.keys())
        self.vsChoiceBox.AppendItems(self.logOptions.keys())
        self.rhoChoiceBox.AppendItems(self.logOptions.keys())

    def on_ok(self, event):

        parDict = OrderedDict()
        parDict['Qvalue'] = 0
        if self.modChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a type of Seismogram to be modeled!")
            raise Exception(
                "Please choose a type of Seismogram to be modeled!")
        parDict['modFlag'] = self.modtype[
            self.modChoiceBox.GetStringSelection()]
        if self.respChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a type of Response!")
            raise Exception("Please choose a type of Response!")
        parDict['respFlag'] = self.modtype[
            self.modChoiceBox.GetStringSelection()]
        if self.wellChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Well!")
            raise Exception("Please choose a Well!")
        parDict['wellID'] = self.wellOptions[
            self.wellChoiceBox.GetStringSelection()]
        if self.vpChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Vp log!")
            raise Exception("Please choose a Vp log!")
        parDict['vpLogID'] = self.logOptions[
            self.vpChoiceBox.GetStringSelection()]
        if self.vsChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Vs log!")
            raise Exception("Please choose a Vs log!")
        parDict['vsLogID'] = self.logOptions[
            self.vsChoiceBox.GetStringSelection()]
        if self.rhoChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Density log!")
            raise Exception("Please choose a Density log!")
        parDict['rhoLogID'] = self.logOptions[
            self.rhoChoiceBox.GetStringSelection()]
        if not self.yesQvalueRB.GetValue() and not self.noQvalueRB.GetValue():
            wx.MessageBox("Please choose the Q-value option!")
            raise Exception("Please choose the Q-value option!")
            parDict['Qvalue'] = self.yesQvalueRB.GetValue()
        if self.flagRB == 0:
            parDict['Qvalue'] = 1
            if self.qpChoiceBox.GetStringSelection() == "":
                wx.MessageBox("Please choose a Q-value log for P-Wave!")
                raise Exception("Please choose a Q-value log for P-Wave!")
            parDict['Pwav_QvalueID'] = self.logOptions[
                self.qpChoiceBox.GetStringSelection()]
            if self.qsChoiceBox.GetStringSelection() == "":
                wx.MessageBox("Please choose a Q-value log for S-Wave!")
                raise Exception("Please choose a Q-value log for S-Wave!")
            parDict['Swav_QvalueID'] = self.logOptions[
                self.qsChoiceBox.GetStringSelection()]
        if self.nsampTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Number of Samples!")
            raise Exception("Please choose the Number of Samples!")
        parDict['numsamps'] = int(float(self.nsampTxtCtrl.GetValue()))
        if self.dtTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Sample Rate Interval!")
            raise Exception("Please choose the Sample Rate Interval!")
        parDict['dt'] = float(self.dtTxtCtrl.GetValue())
        if self.fwavTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose Peak Frequency of the Wavelet to be Used!")
            raise Exception(
                "Please choose Peak Frequency of the Wavelet to be Used!")
        parDict['fWav'] = float(self.fwavTxtCtrl.GetValue())
        if self.ntrcsTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Number of Traces of the Output!")
            raise Exception(
                "Please choose the Number of Traces of the Output!")
        parDict['ntraces'] = int(float(self.ntrcsTxtCtrl.GetValue()))
        if self.trc1TxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the 1st trace cordinate!")
            raise Exception("Please choose the 1st trace cordinate!")
        parDict['trc1'] = float(self.trc1TxtCtrl.GetValue())
        if self.latdtTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Lateral Sample Rate!")
            raise Exception("Please choose the Lateral Sample Rate!")
        parDict['dlat'] = float(self.latdtTxtCtrl.GetValue())
        if self.cam1velTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Velocity of the 1st Layer!")
            raise Exception("Please choose the Velocity of the 1st Layer!")
        parDict['vel1'] = float(self.cam1velTxtCtrl.GetValue())
        if self.cam1thickTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Thickness of 1st Layer!")
            raise Exception("Please choose the Thickness of 1st Layer!")
        parDict['z1'] = float(self.cam1thickTxtCtrl.GetValue())
        if self.nsupTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Number of Superior Layers!")
            raise Exception("Please choose the Number of Superior Layers!")
        parDict['nsup'] = int(float(self.nsupTxtCtrl.GetValue()))
        if self.zsupTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Thickness of Each Superior Layers!")
            raise Exception(
                "Please choose the Thickness of Each Superior Layers!")
        parDict['zsup'] = float(self.zsupTxtCtrl.GetValue())
        if self.firstLayerTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Depth of the 1st Layer to be Modeled!")
            raise Exception(
                "Please choose the Depth of the 1st Layer to be Modeled!")
        parDict['firstLayer'] = float(self.firstLayerTxtCtrl.GetValue())
        if self.lastLayerTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Depth of the Last Layer to be Modeled!")
            raise Exception(
                "Please choose the Depth of the Last Layer to be Modeled!")
        parDict['lastLayer'] = float(self.lastLayerTxtCtrl.GetValue())
        if self.pnumTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Number Ray Parameters to Integration!")
            raise Exception(
                "Please choose the Number Ray Parameters to Integration!")
        parDict['pNum'] = int(float(self.pnumTxtCtrl.GetValue()))
        if self.angmaxTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Maximum Angle of Incidence!")
            raise Exception("Please choose the Maximum Angle of Incidence!")
        parDict['angMax'] = float(self.angmaxTxtCtrl.GetValue())
        if self.vpSupTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the P velocity of Superior Layers!")
            raise Exception("Please choose the P velocity of Superior Layers!")
        parDict['vpSup'] = float(self.vpSupTxtCtrl.GetValue())
        if self.vsSupTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Maximum Angle of Incidence!")
            raise Exception("Please choose the Maximum Angle of Incidence!")
        parDict['vsSup'] = float(self.vsSupTxtCtrl.GetValue())
        if self.outChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a type of Output!")
            raise Exception("Please choose a type of Output!")
        parDict['outFlag'] = self.outtype[
            self.outChoiceBox.GetStringSelection()]
        if self.objTxtCtrl.GetValue() == "":
            wx.MessageBox("Please Choose an Output Name!")
            raise Exception("Please Choose an Output Name!")
        parDict['outName'] = self.objTxtCtrl.GetValue()

        return_flag = -1

        try:
            disableAll = wx.WindowDisabler()
            wait = wx.BusyInfo("Running the Modeling...")
            return_flag = Reflectivity(self.OM, parDict)
        except Exception as e:
            print('ERROR:', e)
            pass
        finally:
            del wait
            del disableAll
            self.dlg.Destroy()

        if return_flag == 1:
            wx.MessageBox('Vp and Vs logs have different sizes!')
        elif return_flag == 2:
            wx.MessageBox('Vp and Density logs have different sizes!')
        elif return_flag == 3:
            wx.MessageBox('Vp and Depth indexes have different sizes!')
        elif return_flag == 4:
            wx.MessageBox('Insuficient Number of Layer!')
        elif return_flag == 5:
            wx.MessageBox(
                'The Q-values Logs have different sizes than Vp and VS!')
        elif return_flag == 6:
            wx.MessageBox('Done!')
        else:
            wx.MessageBox('Other problems has occurred.')
Ejemplo n.º 18
0
class Panel(wx.Panel
            ):  # TODO: enxugar métodos repetidos (getblabla, setblabla)
    def __init__(self, *args, **kwargs):
        super(Panel, self).__init__(*args, **kwargs)

        self._OM = ObjectManager()

        self.welluid = None

        nb = wx.Notebook(self)

        self.pages = OrderedDict()
        self.pages["depth"] = wx.CheckListBox(nb)
        self.pages["log"] = wx.CheckListBox(nb)
        self.pages["partition"] = wx.CheckListBox(nb)

        agwStyle = CT.TR_DEFAULT_STYLE | CT.TR_HIDE_ROOT
        self.pages["property"] = CT.CustomTreeCtrl(nb, agwStyle=agwStyle)

        self.depthmap = []
        self.idepthmap = {}

        self.logmap = []
        self.ilogmap = {}

        self.partitionmap = []
        self.ipartitionmap = {}

        self.ipropertymap = OrderedDict()

        self.pagenames = {}
        self.pagenames["depth"] = u"Profundidade"
        self.pagenames["log"] = u"Perfil"
        self.pagenames["partition"] = u"Partição"
        self.pagenames["property"] = u"Propriedade"

        for key in iter(self.pages.keys()):
            nb.AddPage(self.pages[key], self.pagenames[key])

        sizer = wx.BoxSizer()
        sizer.Add(nb, 1, wx.EXPAND)
        self.SetSizer(sizer)

    def set_welluid(self, welluid):
        self.welluid = welluid
        self.reset_depth_page()
        self.reset_log_page()
        self.reset_partition_page()
        self.reset_property_page()

    def reset_depth_page(self):
        self.depthmap = []
        self.idepthmap.clear()
        self.pages['depth'].Clear()
        if self.welluid is None:
            return
        depthitems = []
        for i, depth in enumerate(self._OM.list('data_index', self.welluid)):
            depthitems.append(depth.name)
            self.depthmap.append(depth.uid)
            self.idepthmap[depth.uid] = i
        self.pages['depth'].AppendItems(depthitems)

    def reset_log_page(self):
        self.logmap = []
        self.ilogmap.clear()
        self.pages['log'].Clear()
        if self.welluid is None:
            return
        logitems = []
        for i, log in enumerate(self._OM.list('log', self.welluid)):
            logitems.append(log.name)
            self.logmap.append(log.uid)
            self.ilogmap[log.uid] = i

        self.pages['log'].AppendItems(logitems)

    def reset_partition_page(self):
        self.partitionmap = []
        self.ipartitionmap = {}
        self.pages['partition'].Clear()
        if self.welluid is None:
            return
        partitionitems = []
        for i, partition in enumerate(self._OM.list('partition',
                                                    self.welluid)):
            partitionitems.append(partition.name)
            self.partitionmap.append(partition.uid)
            self.ipartitionmap[partition.uid] = i

        self.pages['partition'].AppendItems(partitionitems)

    def reset_property_page(self):
        tree = self.pages['property']
        self.ipropertymap.clear()
        tree.DeleteAllItems()

        root = tree.AddRoot('root')
        for partition in self._OM.list('partition', self.welluid):
            properties = self._OM.list('property', partition.uid)
            if not properties:
                continue
            item = tree.AppendItem(root, partition.name)
            ipropmap = OrderedDict()
            for prop in properties:
                propitem = tree.AppendItem(item, prop.name, ct_type=1)
                tree.SetPyData(propitem, prop.uid)
                ipropmap[prop.uid] = propitem
            self.ipropertymap[partition.uid] = ipropmap

    def set_depth_selection(self, selection):
        if self.welluid is None:
            return
        checked = sorted(self.idepthmap[depthuid] for depthuid in selection)
        self.pages['depth'].SetChecked(checked)

    def get_depth_selection(self):
        selection = [
            self.depthmap[i] for i in self.pages['depth'].GetChecked()
        ]
        return selection

    def set_log_selection(self, selection):
        if self.welluid is None:
            return
        checked = sorted(self.ilogmap[loguid] for loguid in selection)
        self.pages['log'].SetChecked(checked)

    def get_log_selection(self):
        selection = [self.logmap[i] for i in self.pages['log'].GetChecked()]
        return selection

    def set_partition_selection(self, selection):
        if self.welluid is None:
            return
        checked = sorted(self.ipartitionmap[partitionuid]
                         for partitionuid in selection)
        self.pages['partition'].SetChecked(checked)

    def get_partition_selection(self):
        selection = [
            self.partitionmap[i] for i in self.pages['partition'].GetChecked()
        ]
        return selection

    def set_property_selection(self, selection):
        if self.welluid is None:
            return
        for value in iter(self.ipropertymap.values()):
            for item in iter(value.values()):
                self.pages['property'].CheckItem(item, False)
        for partitionuid, propertiesuids in selection:
            for propertyuid in propertiesuids:
                item = self.ipropertymap[partitionuid][propertyuid]
                self.pages['property'].CheckItem(item, True)

    def get_property_selection(self):
        selection = OrderedDict()
        for partitionuid, value in iter(self.ipropertymap.items()):
            propselection = []
            for propertyuid, item in iter(value.items()):
                if self.pages['property'].IsItemChecked(item):
                    propselection.append(propertyuid)
            if propselection:
                selection[partitionuid] = propselection
        return selection