setup sfr ASCII observations
967069
def setup_sfr_obs(self):
        """"""
        if not self.sfr_obs:
            return

        if self.m.sfr is None:
            self.logger.lraise("no sfr package found...")
        org_sfr_out_file = os.path.join(self.org_model_ws,"{0}.sfr.out".format(self.m.name))
        if not os.path.exists(org_sfr_out_file):
            self.logger.lraise("setup_sfr_obs() error: could not locate existing sfr out file: {0}".
                               format(org_sfr_out_file))
        new_sfr_out_file = os.path.join(self.m.model_ws,os.path.split(org_sfr_out_file)[-1])
        shutil.copy2(org_sfr_out_file,new_sfr_out_file)
        seg_group_dict = None
        if isinstance(self.sfr_obs,dict):
            seg_group_dict = self.sfr_obs

        df = pyemu.gw_utils.setup_sfr_obs(new_sfr_out_file,seg_group_dict=seg_group_dict,
                                          model=self.m,include_path=True)
        if df is not None:
            self.obs_dfs["sfr"] = df
        self.frun_post_lines.append("pyemu.gw_utils.apply_sfr_obs()")
570216
def ascii2h5(dirname, output_fname):
    

    import tarfile
    import sys
    from glob import glob
    from contextlib import closing

    # The datatype that will be used to store extinction, A0
    A0_dtype = 'float16'

    def load_samp_file(f, fname):
        # Parse filename
        fname_chunks = os.path.split(fname)[1].split('_')
        l = float(fname_chunks[0])
        b = float(fname_chunks[1])

        # Load ASCII data
        data_raw = np.loadtxt(f, dtype='float64')

        n_samples = data_raw.shape[1] - 1
        n_dists = data_raw.shape[0]

        # Construct output
        dtype = [
            ('dist', 'int32'),
            ('A0', A0_dtype, (n_samples,))]

        data = np.empty(n_dists, dtype=dtype)
        data['dist'][:] = data_raw[:,0]
        data['A0'][:,:] = data_raw[:,1:]

        return (l,b), data

    def process_tarball(tarball_fname):
        # Write to the progress bar
        print('.', end='')
        sys.stdout.flush()

        with closing(tarfile.open(tarball_fname, mode='r:gz')) as f_tar:
            fnames = f_tar.getnames()

            f = f_tar.extractfile(fnames[0])
            (l,b), data = load_samp_file(f, fnames[0])
            n_dists, n_samples = data['A0'].shape
            n_coords = len(fnames)

            dtype = [
                ('l', 'float32'),
                ('b', 'float32'),
                ('dist', 'int32', (n_dists,)),
                ('A0', A0_dtype, (n_dists, n_samples))]
            data_combined = np.empty(n_coords, dtype=dtype)

            for k,fn in enumerate(fnames):
                # print('File {: >4d} of {:d}'.format(k+1, n_coords))
                f = f_tar.extractfile(fn)
                (l,b), data = load_samp_file(f, fn)
                data_combined['l'][k] = l
                data_combined['b'][k] = b
                data_combined['dist'][k] = data['dist']
                data_combined['A0'][k] = data['A0']

        return data_combined

    def save_data(data, fname):
        with closing(h5py.File(fname, 'w')) as f:
            f.create_dataset(
                'samples',
                data=data,
                chunks=True,
                compression='gzip',
                compression_opts=3)

    print('Progress: ', end='')
    sys.stdout.flush()

    tar_fname_list = glob(os.path.join(dirname, 'A_samp_*.tar.gz'))
    d = np.hstack([process_tarball(fn) for fn in tar_fname_list])

    print('+', end='')
    sys.stdout.flush()

    save_data(d, output_fname)

    print('')
455976
def _strify(s):
    """"""
    if s is None:
        return None
    if isinstance(s, unicode):
        return s.encode("utf-8")
    return str(s)
205800
def load_vstr(buf, pos):
    """"""
    slen, pos = load_vint(buf, pos)
    return load_bytes(buf, slen, pos)
633029
def ascii_native_(s):
    '''
    
    '''
    if isinstance(s, text_type):
        s = s.encode('ascii')

    return str(s, 'ascii', 'strict') if PY3 else s
716470
def setup_sfr_pars(self, par_cols=None, include_temporal_pars=False):
        """"""
        assert self.m.sfr is not None, "can't find sfr package..."
        if isinstance(par_cols, str):
            par_cols = [par_cols]
        reach_pars = False  # default to False
        seg_pars = True
        par_dfs = {}
        df = pyemu.gw_utils.setup_sfr_seg_parameters(self.m, par_cols=par_cols,
                                                     include_temporal_pars=include_temporal_pars)  # now just pass model
        # self.par_dfs["sfr"] = df
        if df.empty:
            warnings.warn("No sfr segment parameters have been set up", PyemuWarning)
            par_dfs["sfr"] = []
            seg_pars = False
        else:
            par_dfs["sfr"] = [df]  # may need df for both segs and reaches
            self.tpl_files.append("sfr_seg_pars.dat.tpl")
            self.in_files.append("sfr_seg_pars.dat")
            if include_temporal_pars:
                self.tpl_files.append("sfr_seg_temporal_pars.dat.tpl")
                self.in_files.append("sfr_seg_temporal_pars.dat")
        if self.m.sfr.reachinput:
            # if include_temporal_pars:
            #     raise NotImplementedError("temporal pars is not set up for reach data style")
            df = pyemu.gw_utils.setup_sfr_reach_parameters(self.m, par_cols=par_cols)
            if df.empty:
                warnings.warn("No sfr reach parameters have been set up", PyemuWarning)
            else:
                self.tpl_files.append("sfr_reach_pars.dat.tpl")
                self.in_files.append("sfr_reach_pars.dat")
                reach_pars = True
                par_dfs["sfr"].append(df)
        if len(par_dfs["sfr"]) > 0:
            self.par_dfs["sfr"] = pd.concat(par_dfs["sfr"])
            self.frun_pre_lines.append(
                "pyemu.gw_utils.apply_sfr_parameters(seg_pars={0}, reach_pars={1})".format(seg_pars, reach_pars))
        else:
            warnings.warn("No sfr parameters have been set up!", PyemuWarning)
1134726
def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SF record already initialized!')

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        (su_len, su_entry_version_unused,) = struct.unpack_from('=BB', rrstr[:4], 2)

        if su_len == 12:
            # This is a Rock Ridge version 1.10 SF Record, which is 12 bytes.
            (virtual_file_size_le, virtual_file_size_be) = struct.unpack_from('=LL', rrstr[:12], 4)
            if virtual_file_size_le != utils.swab_32bit(virtual_file_size_be):
                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size little-endian does not match big-endian')
            self.virtual_file_size_low = virtual_file_size_le
        elif su_len == 21:
            # This is a Rock Ridge version 1.12 SF Record, which is 21 bytes.
            (virtual_file_size_high_le, virtual_file_size_high_be, virtual_file_size_low_le,
             virtual_file_size_low_be, self.table_depth) = struct.unpack_from('=LLLLB', rrstr[:21], 4)
            if virtual_file_size_high_le != utils.swab_32bit(virtual_file_size_high_be):
                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size high little-endian does not match big-endian')

            if virtual_file_size_low_le != utils.swab_32bit(virtual_file_size_low_be):
                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size low little-endian does not match big-endian')
            self.virtual_file_size_low = virtual_file_size_low_le
            self.virtual_file_size_high = virtual_file_size_high_le
        else:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on Rock Ridge SF record (expected 12 or 21)')

        self._initialized = True
1168320
def load_sound_font(self, sf2):
        
        self.sfid = self.fs.sfload(sf2)
        return not self.sfid == -1
140408
def display_output(arguments):
    ''''''
    global _ASCII
    if arguments['--alt-chars']:
        _ASCII=_ASCII_2
    try:
        im = Image.open(arguments['FILE'])
    except:
        raise IOError('Unable to open the file.')
    im = im.convert("RGBA")
    aspect_ratio    = float(im.size[0])/im.size[1]
    scaled_height   = _WIDTH / aspect_ratio
    scaled_width    = _HEIGHT * aspect_ratio*2

    if scaled_width > _WIDTH:
        width = int(_WIDTH)
        height = int(scaled_height/2)

    elif scaled_height > _HEIGHT:
        width = int(scaled_width)
        height = int(_HEIGHT)

    if arguments['--width']:
        width = int(arguments['--width'])
        height = int(width / aspect_ratio / 2)

    elif arguments['--height']:
        height = int(arguments['--height'])
        width = int(height * aspect_ratio * 2)

    if arguments['--width'] and arguments['--height']:
        height = int(arguments['--height'])
        width = int(arguments['--width'])

    im = im.resize((width,height),resample=Image.ANTIALIAS)

    enhancer = ImageEnhance.Contrast(im)
    im = enhancer.enhance(float(arguments['--contrast']))
    img = im.getdata()
    im = im.convert('L') #Grayscale

    if not arguments['--invert']:
        _ASCII = _ASCII[::-1]

    bg=None;
    if arguments['--bg']=='BLACK':
        bg=rgb(0,0,0)
        fg=rgb(5,5,5)
    elif arguments['--bg']=='WHITE':
        bg=rgb(5,5,5)
        fg=rgb(0,0,0)

    row_len=0
    if arguments['--bold']:
        bold=True
    else:
        bold=False
    for count,i in enumerate(im.getdata()):
        ascii_char = _ASCII[int(((i/255.0))*(len((_ASCII))-1))]
        try:
            if not arguments['--colors']:
                raise Exception
            color = rgb(int((img[count][0]/255.0)*5),int((img[count][1]/255.0)*5),int((img[count][2]/255.0)*5))
            print_color(ascii_char, end='', fg=color, bg=bg, bold=bold)
        except:
            if bg and bold:
                print_color(ascii_char, end='', fg=fg, bg=bg, bold=bold)
            elif bold:
                print_color(ascii_char, end='', bold=bold)
            elif bg:
                print_color(ascii_char, end='', fg=fg, bg=bg)
            else:
                print(ascii_char, end='')
        row_len+=1
        if row_len==width:
            row_len=0
            print('')
55629
def Main_Frame(self):
        

        #--------------------------------------------------------------------
        # initialize first specimen in list as current specimen
        #--------------------------------------------------------------------

        try:
            self.s = self.specimens[0]
        except:
            self.s = ""
            print("No specimens during UI build")

        #--------------------------------------------------------------------
        # create main panel in the right size
        #--------------------------------------------------------------------

        dw, dh = wx.DisplaySize()
        w, h = self.GetSize()
        r1 = dw / 1250.
        r2 = dw / 750.

        GUI_RESOLUTION = min(r1, r2, 1.3)
        if 'gui_resolution' in list(self.preferences.keys()):
            if float(self.preferences['gui_resolution']) != 1:
                self.GUI_RESOLUTION = float(
                    self.preferences['gui_resolution']) / 100
            else:
                self.GUI_RESOLUTION = min(r1, r2, 1.3)
        else:
            self.GUI_RESOLUTION = min(r1, r2, 1.3)

        #--------------------------------------------------------------------
        # adjust font size
        #--------------------------------------------------------------------

        self.font_type = "Arial"
        if sys.platform.startswith("linux"):
            self.font_type = "Liberation Serif"

        if self.GUI_RESOLUTION >= 1.1 and self.GUI_RESOLUTION <= 1.3:
            font2 = wx.Font(13, wx.SWISS, wx.NORMAL,
                            wx.NORMAL, False, self.font_type)
        elif self.GUI_RESOLUTION <= 0.9 and self.GUI_RESOLUTION < 1.0:
            font2 = wx.Font(11, wx.SWISS, wx.NORMAL,
                            wx.NORMAL, False, self.font_type)
        elif self.GUI_RESOLUTION <= 0.9:
            font2 = wx.Font(10, wx.SWISS, wx.NORMAL,
                            wx.NORMAL, False, self.font_type)
        else:
            font2 = wx.Font(12, wx.SWISS, wx.NORMAL,
                            wx.NORMAL, False, self.font_type)
        print("    self.GUI_RESOLUTION", self.GUI_RESOLUTION)

        h_space = 4
        v_space = 4

        # set font size and style
        #font1 = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Comic Sans MS')
        FONT_RATIO = self.GUI_RESOLUTION + (self.GUI_RESOLUTION - 1) * 5
        font1 = wx.Font(9 + FONT_RATIO, wx.SWISS, wx.NORMAL,
                        wx.NORMAL, False, self.font_type)
        # GUI headers

        font3 = wx.Font(11 + FONT_RATIO, wx.SWISS, wx.NORMAL,
                        wx.NORMAL, False, self.font_type)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(10 + FONT_RATIO)

        #--------------------------------------------------------------------
        # Create Figures and FigCanvas objects.
        #--------------------------------------------------------------------

        self.fig1 = Figure((5. * self.GUI_RESOLUTION, 5. *
                            self.GUI_RESOLUTION), dpi=self.dpi)
        self.canvas1 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig1)
        self.fig1.text(0.01, 0.98, "Arai plot", {
                       'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
        self.toolbar1 = NavigationToolbar(self.canvas1)
        self.toolbar1.Hide()
        self.fig1_setting = "Zoom"
        self.toolbar1.zoom()
        self.canvas1.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
        self.canvas1.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)

        self.fig2 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
                            self.GUI_RESOLUTION), dpi=self.dpi)
        self.canvas2 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig2)
        self.fig2.text(0.02, 0.96, "Zijderveld", {
                       'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
        self.toolbar2 = NavigationToolbar(self.canvas2)
        self.toolbar2.Hide()
        self.fig2_setting = "Zoom"
        self.toolbar2.zoom()
        self.canvas2.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
        self.canvas2.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)

        self.fig3 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
                            self.GUI_RESOLUTION), dpi=self.dpi)
        self.canvas3 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig3)
        #self.fig3.text(0.02,0.96,"Equal area",{'family':self.font_type, 'fontsize':10*self.GUI_RESOLUTION, 'style':'normal','va':'center', 'ha':'left' })
        self.toolbar3 = NavigationToolbar(self.canvas3)
        self.toolbar3.Hide()
        self.fig3_setting = "Zoom"
        self.toolbar3.zoom()
        self.canvas3.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
        self.canvas3.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)

        self.fig4 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
                            self.GUI_RESOLUTION), dpi=self.dpi)
        self.canvas4 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig4)
        if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'site':
            TEXT = "Site data"
        else:
            TEXT = "Sample data"
        self.fig4.text(0.02, 0.96, TEXT, {
                       'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
        self.toolbar4 = NavigationToolbar(self.canvas4)
        self.toolbar4.Hide()
        self.fig4_setting = "Zoom"
        self.toolbar4.zoom()
        self.canvas4.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
        self.canvas4.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)

        self.fig5 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
                            self.GUI_RESOLUTION), dpi=self.dpi)
        self.canvas5 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig5)
        #self.fig5.text(0.02,0.96,"M/M0",{'family':self.font_type, 'fontsize':10, 'style':'normal','va':'center', 'ha':'left' })
        self.toolbar5 = NavigationToolbar(self.canvas5)
        self.toolbar5.Hide()
        self.fig5_setting = "Zoom"
        self.toolbar5.zoom()
        self.canvas5.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
        self.canvas5.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)

        # make axes of the figures
        self.araiplot = self.fig1.add_axes([0.1, 0.1, 0.8, 0.8])
        self.zijplot = self.fig2.add_subplot(111)
        self.eqplot = self.fig3.add_subplot(111)
        self.sampleplot = self.fig4.add_axes(
            [0.2, 0.3, 0.7, 0.6], frameon=True, facecolor='None')
        self.mplot = self.fig5.add_axes(
            [0.2, 0.15, 0.7, 0.7], frameon=True, facecolor='None')

        #--------------------------------------------------------------------
        # text box displaying measurement data
        #--------------------------------------------------------------------

        self.logger = wx.ListCtrl(self.side_panel, id=wx.ID_ANY, size=(
            100 * self.GUI_RESOLUTION, 100 * self.GUI_RESOLUTION), style=wx.LC_REPORT)
        self.logger.SetFont(font1)
        self.logger.InsertColumn(0, 'i', width=45 * self.GUI_RESOLUTION)
        self.logger.InsertColumn(1, 'Step', width=45 * self.GUI_RESOLUTION)
        self.logger.InsertColumn(2, 'Tr', width=65 * self.GUI_RESOLUTION)
        self.logger.InsertColumn(3, 'Dec', width=65 * self.GUI_RESOLUTION)
        self.logger.InsertColumn(4, 'Inc', width=65 * self.GUI_RESOLUTION)
        self.logger.InsertColumn(5, 'M', width=75 * self.GUI_RESOLUTION)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,
                  self.on_click_listctrl, self.logger)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,
                  self.on_right_click_listctrl, self.logger)

        #--------------------------------------------------------------------
        # select a specimen box
        #--------------------------------------------------------------------

        # Combo-box with a list of specimen
        self.specimens_box = wx.ComboBox(self.top_panel, wx.ID_ANY, self.s, (250 * self.GUI_RESOLUTION, 25),
                                         wx.DefaultSize, self.specimens, wx.CB_DROPDOWN | wx.TE_PROCESS_ENTER, name="specimen")
        self.specimens_box.SetFont(font2)
        self.Bind(wx.EVT_COMBOBOX, self.onSelect_specimen, self.specimens_box)
        self.Bind(wx.EVT_TEXT_ENTER, self.onSelect_specimen,
                  self.specimens_box)

        # buttons to move forward and backwards from specimens
        nextbutton = wx.Button(self.top_panel, id=wx.ID_ANY, label='next', size=(
            75 * self.GUI_RESOLUTION, 25))  # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
        self.Bind(wx.EVT_BUTTON, self.on_next_button, nextbutton)
        nextbutton.SetFont(font2)

        prevbutton = wx.Button(self.top_panel, id=wx.ID_ANY, label='previous', size=(
            75 * self.GUI_RESOLUTION, 25))  # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
        prevbutton.SetFont(font2)
        self.Bind(wx.EVT_BUTTON, self.on_prev_button, prevbutton)

        #--------------------------------------------------------------------
        # select temperature bounds
        #--------------------------------------------------------------------

        try:
            if self.Data[self.s]['T_or_MW'] == "T":
                self.temperatures = np.array(
                    self.Data[self.s]['t_Arai']) - 273.
                self.T_list = ["%.0f" % T for T in self.temperatures]
            elif self.Data[self.s]['T_or_MW'] == "MW":
                self.temperatures = np.array(self.Data[self.s]['t_Arai'])
                self.T_list = ["%.0f" % T for T in self.temperatures]
        except (ValueError, TypeError, KeyError) as e:
            self.T_list = []

        self.tmin_box = wx.ComboBox(self.top_panel, wx.ID_ANY, size=(
            100 * self.GUI_RESOLUTION, 25), choices=self.T_list, style=wx.CB_DROPDOWN | wx.TE_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.get_new_T_PI_parameters, self.tmin_box)

        self.tmax_box = wx.ComboBox(self.top_panel, -1, size=(100 * self.GUI_RESOLUTION, 25),
                                    choices=self.T_list, style=wx.CB_DROPDOWN | wx.TE_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.get_new_T_PI_parameters, self.tmax_box)

        #--------------------------------------------------------------------
        # save/delete buttons
        #--------------------------------------------------------------------

        # save/delete interpretation buttons
        self.save_interpretation_button = wx.Button(self.top_panel, id=-1, label='save', size=(
            75 * self.GUI_RESOLUTION, 25))  # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
        self.save_interpretation_button.SetFont(font2)
        self.delete_interpretation_button = wx.Button(self.top_panel, id=-1, label='delete', size=(
            75 * self.GUI_RESOLUTION, 25))  # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
        self.delete_interpretation_button.SetFont(font2)
        self.Bind(wx.EVT_BUTTON, self.on_save_interpretation_button,
                  self.save_interpretation_button)
        self.Bind(wx.EVT_BUTTON, self.on_delete_interpretation_button,
                  self.delete_interpretation_button)

        self.auto_save = wx.CheckBox(self.top_panel, wx.ID_ANY, 'auto-save')
        self.auto_save_info = wx.Button(self.top_panel, wx.ID_ANY, "?")
        self.Bind(wx.EVT_BUTTON, self.on_info_click, self.auto_save_info)
        #self.auto_save_text = wx.StaticText(self.top_panel, wx.ID_ANY, label="(saves with 'next')")


        #--------------------------------------------------------------------
        # specimen interpretation and statistics window (Blab; Banc, Dec, Inc, correction factors etc.)
        #--------------------------------------------------------------------

        self.Blab_window = wx.TextCtrl(
            self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
        self.Banc_window = wx.TextCtrl(
            self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
        self.Aniso_factor_window = wx.TextCtrl(
            self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
        self.NLT_factor_window = wx.TextCtrl(
            self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
        self.CR_factor_window = wx.TextCtrl(
            self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
        self.declination_window = wx.TextCtrl(
            self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
        self.inclination_window = wx.TextCtrl(
            self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))

        for stat in ['Blab', 'Banc', 'Aniso_factor', 'NLT_factor', 'CR_factor', 'declination', 'inclination']:
            exec("self.%s_window.SetBackgroundColour(wx.WHITE)" % stat)

        self.Blab_label = wx.StaticText(
            self.top_panel, label="\nB_lab", style=wx.ALIGN_CENTRE)
        self.Blab_label.SetFont(font2)
        self.Banc_label = wx.StaticText(
            self.top_panel, label="\nB_anc", style=wx.ALIGN_CENTRE)
        self.Banc_label.SetFont(font2)
        self.aniso_corr_label = wx.StaticText(
            self.top_panel, label="Aniso\ncorr", style=wx.ALIGN_CENTRE)
        self.aniso_corr_label.SetFont(font2)
        self.nlt_corr_label = wx.StaticText(
            self.top_panel, label="NLT\ncorr", style=wx.ALIGN_CENTRE)
        self.nlt_corr_label.SetFont(font2)
        self.cr_corr_label = wx.StaticText(
            self.top_panel, label="CR\ncorr", style=wx.ALIGN_CENTRE)
        self.cr_corr_label.SetFont(font2)
        self.dec_label = wx.StaticText(
            self.top_panel, label="\nDec", style=wx.ALIGN_CENTRE)
        self.dec_label.SetFont(font2)
        self.inc_label = wx.StaticText(
            self.top_panel, label="\nInc", style=wx.ALIGN_CENTRE)
        self.inc_label.SetFont(font2)

        # handle Specimen Results Sizer
        sizer_specimen_results = wx.StaticBoxSizer(wx.StaticBox(
            self.top_panel, wx.ID_ANY, "specimen results"), wx.HORIZONTAL)
        specimen_stat_window = wx.GridSizer(2, 7, h_space, v_space)
        specimen_stat_window.AddMany([(self.Blab_label, 1, wx.ALIGN_BOTTOM),
                                      ((self.Banc_label), 1, wx.ALIGN_BOTTOM),
                                      ((self.aniso_corr_label), 1, wx.ALIGN_BOTTOM),
                                      ((self.nlt_corr_label), 1, wx.ALIGN_BOTTOM),
                                      ((self.cr_corr_label), 1, wx.ALIGN_BOTTOM),
                                      ((self.dec_label), 1,
                                       wx.TE_CENTER | wx.ALIGN_BOTTOM),
                                      ((self.inc_label), 1, wx.ALIGN_BOTTOM),
                                      (self.Blab_window, 1, wx.EXPAND),
                                      (self.Banc_window, 1, wx.EXPAND),
                                      (self.Aniso_factor_window, 1, wx.EXPAND),
                                      (self.NLT_factor_window, 1, wx.EXPAND),
                                      (self.CR_factor_window, 1, wx.EXPAND),
                                      (self.declination_window, 1, wx.EXPAND),
                                      (self.inclination_window, 1, wx.EXPAND)])
        sizer_specimen_results.Add(
            specimen_stat_window, 1, wx.EXPAND | wx.ALIGN_LEFT, 0)

        #--------------------------------------------------------------------
        # Sample interpretation window
        #--------------------------------------------------------------------

        for key in ["sample_int_n", "sample_int_uT", "sample_int_sigma", "sample_int_sigma_perc"]:
            command = "self.%s_window=wx.TextCtrl(self.top_panel,style=wx.TE_CENTER|wx.TE_READONLY,size=(50*self.GUI_RESOLUTION,25))" % key
            exec(command)
            exec("self.%s_window.SetBackgroundColour(wx.WHITE)" % key)

        sample_mean_label = wx.StaticText(
            self.top_panel, label="\nmean", style=wx.TE_CENTER)
        sample_mean_label.SetFont(font2)
        sample_N_label = wx.StaticText(
            self.top_panel, label="\nN ", style=wx.TE_CENTER)
        sample_N_label.SetFont(font2)
        sample_std_label = wx.StaticText(
            self.top_panel, label="\nstd uT", style=wx.TE_CENTER)
        sample_std_label.SetFont(font2)
        sample_std_per_label = wx.StaticText(
            self.top_panel, label="\nstd %", style=wx.TE_CENTER)
        sample_std_per_label.SetFont(font2)

        # handle samples/sites results sizers
        sizer_sample_results = wx.StaticBoxSizer(wx.StaticBox(
            self.top_panel, wx.ID_ANY, "sample/site results"), wx.HORIZONTAL)
        sample_stat_window = wx.GridSizer(2, 4, h_space, v_space)
        sample_stat_window.AddMany([(sample_mean_label, 1, wx.ALIGN_BOTTOM),
                                    (sample_N_label, 1, wx.ALIGN_BOTTOM),
                                    (sample_std_label, 1, wx.ALIGN_BOTTOM),
                                    (sample_std_per_label, 1, wx.ALIGN_BOTTOM),
                                    (self.sample_int_uT_window, 1, wx.EXPAND),
                                    (self.sample_int_n_window, 1, wx.EXPAND),
                                    (self.sample_int_sigma_window, 1, wx.EXPAND),
                                    (self.sample_int_sigma_perc_window, 1, wx.EXPAND)])
        sizer_sample_results.Add(
            sample_stat_window, 1, wx.EXPAND | wx.ALIGN_LEFT, 0)

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

        label_0 = wx.StaticText(
            self.bottom_panel, label="                    ", style=wx.ALIGN_CENTER, size=(180, 25))
        label_1 = wx.StaticText(
            self.bottom_panel, label="Acceptance criteria:", style=wx.ALIGN_CENTER, size=(180, 25))
        label_2 = wx.StaticText(
            self.bottom_panel, label="Specimen statistics:", style=wx.ALIGN_CENTER, size=(180, 25))

        for statistic in self.preferences['show_statistics_on_gui']:
            self.stat_windows[statistic] = wx.TextCtrl(
                self.bottom_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
            self.stat_windows[statistic].SetBackgroundColour(wx.WHITE)
            self.stat_windows[statistic].SetFont(font2)
            self.threshold_windows[statistic] = wx.TextCtrl(
                self.bottom_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
            self.threshold_windows[statistic].SetFont(font2)
            self.threshold_windows[statistic].SetBackgroundColour(wx.WHITE)
            label = statistic.replace("specimen_", "").replace("int_", "")
            self.stat_labels[statistic] = wx.StaticText(
                self.bottom_panel, label=label, style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ALIGN_BOTTOM)
            self.stat_labels[statistic].SetFont(font2)

        #-------------------------------------------------------------------
        # Design the panels
        #-------------------------------------------------------------------

        # Plots Panel--------------------------------------------------------
        sizer_grid_plots = wx.GridSizer(2, 2, 0, 0)
        sizer_grid_plots.AddMany([(self.canvas2, 1, wx.EXPAND),
                                  (self.canvas4, 1, wx.EXPAND),
                                  (self.canvas3, 1, wx.EXPAND),
                                  (self.canvas5, 1, wx.EXPAND)])

        sizer_plots_outer = wx.BoxSizer(wx.HORIZONTAL)
        sizer_plots_outer.Add(self.canvas1, 1, wx.EXPAND)
        sizer_plots_outer.Add(sizer_grid_plots, 1, wx.EXPAND)

        # Top Bar Sizer-------------------------------------------------------
        #-------------Specimens Sizer----------------------------------------
        sizer_prev_next_btns = wx.BoxSizer(wx.HORIZONTAL)
        sizer_prev_next_btns.Add(prevbutton, 1, wx.EXPAND | wx.RIGHT, h_space)
        sizer_prev_next_btns.Add(nextbutton, 1, wx.EXPAND | wx.LEFT, h_space)

        sizer_select_specimen = wx.StaticBoxSizer(wx.StaticBox(
            self.top_panel, wx.ID_ANY, "specimen"), wx.VERTICAL)
        sizer_select_specimen.Add(
            self.specimens_box, 1, wx.EXPAND | wx.BOTTOM, v_space)
        sizer_select_specimen.Add(
            sizer_prev_next_btns, 1, wx.EXPAND | wx.TOP, v_space)

        #-------------Bounds Sizer----------------------------------------
        sizer_grid_bounds_btns = wx.GridSizer(2, 3, 2 * h_space, 2 * v_space)
        sizer_grid_bounds_btns.AddMany([(self.tmin_box, 1, wx.EXPAND),
                                        (self.save_interpretation_button,
                                         1, wx.EXPAND), (self.auto_save, 1, wx.EXPAND),
                                        (self.tmax_box, 1, wx.EXPAND),
                                        (self.delete_interpretation_button, 1, wx.EXPAND),
                                        (self.auto_save_info, 1, wx.EXPAND)])


        if self.s in list(self.Data.keys()) and self.Data[self.s]['T_or_MW'] == "T":
            sizer_select_temp = wx.StaticBoxSizer(wx.StaticBox(
                self.top_panel, wx.ID_ANY, "temperatures"), wx.HORIZONTAL)
        else:
            sizer_select_temp = wx.StaticBoxSizer(wx.StaticBox(
                self.top_panel, wx.ID_ANY, "MW power"), wx.HORIZONTAL)
        sizer_select_temp.Add(sizer_grid_bounds_btns, 1, wx.EXPAND)

        #-------------Top Bar Outer Sizer------------------------------------
        sizer_top_bar = wx.BoxSizer(wx.HORIZONTAL)
        sizer_top_bar.AddMany([(sizer_select_specimen, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
                               (sizer_select_temp, 1, wx.EXPAND |
                                wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
                               (sizer_specimen_results, 2, wx.EXPAND |
                                wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
                               (sizer_sample_results, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.RIGHT, 0)])

        # Bottom Bar Sizer----------------------------------------------------
        #----------------Criteria Labels Sizer-------------------------------
        sizer_criteria_labels = wx.BoxSizer(wx.HORIZONTAL)
        sizer_criteria_labels.Add(label_0, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
        sizer_criteria_boxes = wx.BoxSizer(wx.HORIZONTAL)
        sizer_criteria_boxes.Add(label_1, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
        sizer_stats_boxes = wx.BoxSizer(wx.HORIZONTAL)
        sizer_stats_boxes.Add(label_2, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
        for statistic in self.preferences['show_statistics_on_gui']:
            sizer_criteria_labels.Add(
                self.stat_labels[statistic], 1, wx.ALIGN_BOTTOM, 0)

        #----------------Acceptance Criteria Boxes---------------------------
            sizer_criteria_boxes.Add(
                self.threshold_windows[statistic], 1, wx.EXPAND | wx.LEFT, h_space)

        #----------------Specimen Statistics Boxes---------------------------
            sizer_stats_boxes.Add(
                self.stat_windows[statistic], 1, wx.EXPAND | wx.LEFT, h_space)

        #----------------Bottom Outer Sizer----------------------------------
        sizer_bottom_bar = wx.BoxSizer(wx.VERTICAL)
        sizer_bottom_bar.AddMany([(sizer_criteria_labels, 1, wx.EXPAND | wx.ALIGN_BOTTOM | wx.BOTTOM, v_space),
                                  (sizer_criteria_boxes, 1, wx.EXPAND |
                                   wx.BOTTOM | wx.ALIGN_TOP, v_space),
                                  (sizer_stats_boxes, 1, wx.EXPAND | wx.ALIGN_TOP)])

        # Logger Sizer--------------------------------------------------------
        sizer_logger = wx.BoxSizer(wx.HORIZONTAL)
        sizer_logger.Add(self.logger, 1, wx.EXPAND)

        # Set Panel Sizers----------------------------------------------------
        self.plot_panel.SetSizer(sizer_plots_outer)
        self.side_panel.SetSizerAndFit(sizer_logger)
        self.top_panel.SetSizerAndFit(sizer_top_bar)
        self.bottom_panel.SetSizerAndFit(sizer_bottom_bar)

        # Outer Sizer for Frame-----------------------------------------------
        sizer_logger_plots = wx.BoxSizer(wx.HORIZONTAL)
        sizer_logger_plots.Add(self.side_panel, 1, wx.EXPAND | wx.ALIGN_LEFT)
        sizer_logger_plots.Add(self.plot_panel, 3, wx.EXPAND | wx.ALIGN_LEFT)

        sizer_outer = wx.BoxSizer(wx.VERTICAL)
        sizer_outer.AddMany([(self.top_panel, 1, wx.EXPAND | wx.ALIGN_TOP | wx.BOTTOM, v_space / 2),
                             (sizer_logger_plots, 4, wx.EXPAND |
                              wx.ALIGN_TOP | wx.BOTTOM, v_space / 2),
                             (self.bottom_panel, 1, wx.EXPAND | wx.ALIGN_TOP)])

        self.SetSizer(sizer_outer)
        sizer_outer.Fit(self)
        self.Layout()
586187
def add_particles_ascii(self, s):
        
        for l in s.split("\n"):
            r = l.split()
            if len(r):
                try:
                    r = [float(x) for x in r]
                    p = Particle(simulation=self, m=r[0], r=r[1], x=r[2], y=r[3], z=r[4], vx=r[5], vy=r[6], vz=r[7])
                    self.add(p)
                except:
                    raise AttributeError("Each line requires 8 floats corresponding to mass, radius, position (x,y,z) and velocity (x,y,z).")
890108
def pprint(self):
        

        s = u"ASF (%s) %d bps, %s Hz, %d channels, %.2f seconds" % (
            self.codec_type or self.codec_name or u"???", self.bitrate,
            self.sample_rate, self.channels, self.length)
        return s
1213666
def ascii_mode(enabled=True):
    
    global _backups, _chars, _primary_style, _secondary_style, _ascii_mode
    if not (enabled or _backups) or (enabled and _ascii_mode):
        return
    if enabled:
        _backups = _chars.copy(), _primary_style, _secondary_style
        _chars = {
            "primary": {"selected": "*", "block": "#"},
            "secondary": {"arrow": ">", "left-edge": "|", "right-edge": "|"},
            "plain": {"unselected": "."},
        }
        _primary_style = ()
        _secondary_style = ()
    else:
        _chars, _primary_style, _secondary_style = _backups
    _ascii_mode = enabled
438720
def align_buf(buf, sample_width):
    """"""
    remainder = len(buf) % sample_width
    if remainder != 0:
        buf += b'\0' * (sample_width - remainder)
    return buf
919396
def interactive_output( istr ) # :nodoc:
      str = []
      istr.bytes.each do |c|
	case c
	when 0
	  str << c.to_s + ":\\0"
	when 10
	  str << c.to_s + ":\\n"
	when 13
	  str << c.to_s + ":\\r"
	when 7
	  str << c.to_s + ":\\a"
	when 8
	  str << c.to_s + ":\\b"
	when 9
	  str << c.to_s + ":\\t"
	when 11
	  str << c.to_s + ":\\v"
	when 12
	  str << c.to_s + ":\\f"
	else
	  str << c.to_s + ":" + c.chr
	end
      end
      return str
    end
217890
def _strslices(self):
        """"""
        pad = self.padding or 0
        for sli in self.slices():
            if sli.start + 1 == sli.stop:
                yield "%0*d" % (pad, sli.start)
            else:
                assert sli.step >= 0, "Internal error: sli.step < 0"
                if sli.step == 1:
                    yield "%0*d-%0*d" % (pad, sli.start, pad, sli.stop - 1)
                else:
                    yield "%0*d-%0*d/%d" % (pad, sli.start, pad, sli.stop - 1, \
                                            sli.step)
200293
private void scanSubtitles() {
		boolean convertFPS = configuration.getConvertFPS();
		subPictures = new SubPicture[subtitleStream.getFrameCount()];
		double factTS = convertFPS ? configuration.getFPSSrc()
				/ configuration.getFpsTrg() : 1.0;

		double fx;
		double fy;
		fx = 1.0;
		fy = 1.0;

		// first run: clone source subpics, apply speedup/down,
		SubPicture picSrc;
		for (int i = 0; i < subPictures.length; i++) {
			picSrc = subtitleStream.getSubPicture(i);
			subPictures[i] = new SubPicture(picSrc);
			long ts = picSrc.getStartTime();
			long te = picSrc.getEndTime();
			// copy time stamps and apply speedup/speeddown
			int delayPTS = configuration.getDelayPTS();
			if (!convertFPS) {
				subPictures[i].setStartTime(ts + delayPTS);
				subPictures[i].setEndTime(te + delayPTS);
			} else {
				subPictures[i].setStartTime((long) (ts * factTS + 0.5)
						+ delayPTS);
				subPictures[i]
						.setEndTime((long) (te * factTS + 0.5) + delayPTS);
			}
			// synchronize to target frame rate
			subPictures[i].setStartTime(SubtitleUtils.syncTimePTS(
					subPictures[i].getStartTime(), configuration.getFpsTrg(),
					configuration.getFpsTrg()));
			subPictures[i].setEndTime(SubtitleUtils.syncTimePTS(
					subPictures[i].getEndTime(), configuration.getFpsTrg(),
					configuration.getFpsTrg()));

			// set forced flag
			SubPicture picTrg = subPictures[i];

			double scaleX;
			double scaleY;
			if (configuration.getConvertResolution()) {
				// adjust image sizes and offsets
				// determine scaling factors
				picTrg.setWidth(configuration.getOutputResolution()
						.getDimensions()[0]);
				picTrg.setHeight(configuration.getOutputResolution()
						.getDimensions()[1]);
				scaleX = (double) picTrg.getWidth() / picSrc.getWidth();
				scaleY = (double) picTrg.getHeight() / picSrc.getHeight();
			} else {
				picTrg.setWidth(picSrc.getWidth());
				picTrg.setHeight(picSrc.getHeight());
				scaleX = 1.0;
				scaleY = 1.0;
			}
			int w = (int) (picSrc.getImageWidth() * scaleX * fx + 0.5);
			if (w < MIN_IMAGE_DIMENSION) {
				w = picSrc.getImageWidth();
			} else if (w > picTrg.getWidth()) {
				w = picTrg.getWidth();
			}

			int h = (int) (picSrc.getImageHeight() * scaleY * fy + 0.5);
			if (h < MIN_IMAGE_DIMENSION) {
				h = picSrc.getImageHeight();
			} else if (h > picTrg.getHeight()) {
				h = picTrg.getHeight();
			}
			picTrg.setImageWidth(w);
			picTrg.setImageHeight(h);

			int xOfs = (int) (picSrc.getXOffset() * scaleX + 0.5);
			int spaceSrc = (int) ((picSrc.getWidth() - picSrc.getImageWidth())
					* scaleX + 0.5);
			int spaceTrg = picTrg.getWidth() - w;
			xOfs += (spaceTrg - spaceSrc) / 2;
			if (xOfs < 0) {
				xOfs = 0;
			} else if (xOfs + w > picTrg.getWidth()) {
				xOfs = picTrg.getWidth() - w;
			}
			picTrg.setOfsX(xOfs);

			int yOfs = (int) (picSrc.getYOffset() * scaleY + 0.5);
			spaceSrc = (int) ((picSrc.getHeight() - picSrc.getImageHeight())
					* scaleY + 0.5);
			spaceTrg = picTrg.getHeight() - h;
			yOfs += (spaceTrg - spaceSrc) / 2;
			if (yOfs + h > picTrg.getHeight()) {
				yOfs = picTrg.getHeight() - h;
			}
			picTrg.setOfsY(yOfs);
		}

		// 2nd run: validate times
		SubPicture picPrev = null;
		SubPicture picNext;
		for (int i = 0; i < subPictures.length; i++) {
			if (i < subPictures.length - 1) {
				picNext = subPictures[i + 1];
			} else {
				picNext = null;
			}
			picSrc = subPictures[i];
			validateTimes(i, subPictures[i], picNext, picPrev);
			picPrev = picSrc;
		}
	}