Instruction:
Can you write a function in Python 3 where it
names eqarea_magic.py DESCRIPTION makes equal area projections from declination/inclination data SYNTAX eqarea_magic.py [command line options] INPUT takes magic formatted sites, samples, specimens, or measurements OPTIONS -h prints help message and quits -f FILE: specify input magic format file from magic, default='sites.txt' supported types=[measurements, specimens, samples, sites] -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample) default='specimens.txt' -fsa FILE: specify sample file name, (required if you want to plot specimens by site) default='samples.txt' -fsi FILE: specify site file name, default='sites.txt' -flo FILE: specify location file name, default='locations.txt' -obj OBJ: specify level of plot [all, sit, sam, spc], default is all -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is geographic, unspecified assumed geographic -fmt [svg,png,jpg] format for output plots -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors -c plot as colour contour -cm CM use color map CM [default is coolwarm] -sav save plot and quit quietly -no-tilt data are unoriented, allows plotting of measurement dec/inc NOTE all: entire file; sit: site; sam: sample; spc: specimen

Response:
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted sites, samples, specimens, or measurements

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic, default='sites.txt'
         supported types=[measurements, specimens, samples, sites]
        -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample)
                default='specimens.txt'
        -fsa FILE: specify sample file name, (required if you want to plot specimens by site)
                default='samples.txt'
        -fsi FILE: specify site file name, default='sites.txt'
        -flo FILE: specify location file name, default='locations.txt'

        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour
        -cm CM use color map CM [default is coolwarm]
        -sav save plot and quit quietly
        -no-tilt data are unoriented, allows plotting of measurement dec/inc
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    # extract arguments from sys.argv
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", default_val=".")
    input_dir_path = pmag.get_named_arg('-ID', '')
    if not input_dir_path:
        input_dir_path = dir_path
    in_file = pmag.get_named_arg("-f", default_val="sites.txt")
    in_file = pmag.resolve_file_name(in_file, input_dir_path)
    if "-ID" not in sys.argv:
        input_dir_path = os.path.split(in_file)[0]

    plot_by = pmag.get_named_arg("-obj", default_val="all").lower()
    spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg("-fsi", default_val="sites.txt")
    loc_file = pmag.get_named_arg("-flo", default_val="locations.txt")
    ignore_tilt = False
    if '-no-tilt' in sys.argv:
        ignore_tilt = True
    color_map = "coolwarm"
    if '-c' in sys.argv:
        contour = True
        if '-cm' in sys.argv:
            ind = sys.argv.index('-cm')
            color_map = sys.argv[ind+1]
        else:
            color_map = 'coolwarm'
    else:
        contour = False
    interactive = True
    save_plots = False
    if '-sav' in sys.argv:
        save_plots = True
        interactive = False
    plot_ell = False
    if '-ell' in sys.argv:
        plot_ell = pmag.get_named_arg("-ell", "F")
    crd = pmag.get_named_arg("-crd", default_val="g")
    fmt = pmag.get_named_arg("-fmt", "svg")
    ipmag.eqarea_magic(in_file, dir_path, input_dir_path, spec_file, samp_file, site_file, loc_file,
                       plot_by, crd, ignore_tilt, save_plots, fmt, contour, color_map,
                       plot_ell, "all", interactive)


Instruction:
Implement a Python 3 function for
initializing the main UI for the current resource class

Response:
def InitUI(self):
        """
        initialize window
        """
        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        self.init_grid_headers()
        self.grid_builder = GridBuilder(self.er_magic, self.grid_type, self.grid_headers,
                                        self.panel, self.parent_type)
        self.grid = self.grid_builder.make_grid()
        self.grid.InitUI()

        ## Column management buttons
        self.add_cols_button = wx.Button(self.panel, label="Add additional columns",
                                         name='add_cols_btn')
        self.Bind(wx.EVT_BUTTON, self.on_add_cols, self.add_cols_button)
        self.remove_cols_button = wx.Button(self.panel, label="Remove columns",
                                            name='remove_cols_btn')
        self.Bind(wx.EVT_BUTTON, self.on_remove_cols, self.remove_cols_button)

        ## Row management buttons
        self.remove_row_button = wx.Button(self.panel, label="Remove last row",
                                           name='remove_last_row_btn')
        self.Bind(wx.EVT_BUTTON, self.on_remove_row, self.remove_row_button)
        many_rows_box = wx.BoxSizer(wx.HORIZONTAL)
        self.add_many_rows_button = wx.Button(self.panel, label="Add row(s)",
                                              name='add_many_rows_btn')
        self.rows_spin_ctrl = wx.SpinCtrl(self.panel, value='1', initial=1,
                                          name='rows_spin_ctrl')
        many_rows_box.Add(self.add_many_rows_button, flag=wx.ALIGN_CENTRE)
        many_rows_box.Add(self.rows_spin_ctrl)
        self.Bind(wx.EVT_BUTTON, self.on_add_rows, self.add_many_rows_button)

        self.deleteRowButton = wx.Button(self.panel, id=-1, label='Delete selected row(s)', name='delete_row_btn')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_remove_row(event, False), self.deleteRowButton)
        self.deleteRowButton.Disable()

        ## Data management buttons
        self.importButton = wx.Button(self.panel, id=-1,
                                      label='Import MagIC-format file', name='import_btn')
        self.Bind(wx.EVT_BUTTON, self.onImport, self.importButton)
        self.exitButton = wx.Button(self.panel, id=-1,
                                    label='Save and close grid', name='save_and_quit_btn')
        self.Bind(wx.EVT_BUTTON, self.onSave, self.exitButton)
        self.cancelButton = wx.Button(self.panel, id=-1, label='Cancel', name='cancel_btn')
        self.Bind(wx.EVT_BUTTON, self.onCancelButton, self.cancelButton)

        ## Help message and button
        # button
        self.toggle_help_btn = wx.Button(self.panel, id=-1, label="Show help",
                                         name='toggle_help_btn')
        self.Bind(wx.EVT_BUTTON, self.toggle_help, self.toggle_help_btn)
        # message
        self.help_msg_boxsizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, name='help_msg_boxsizer'), wx.VERTICAL)
        self.default_msg_text = 'Edit {} here.\nYou can add or remove both rows and columns, however required columns may not be deleted.\nControlled vocabularies are indicated by **, and will have drop-down-menus.\nTo edit all values in a column, click the column header.\nYou can cut and paste a block of cells from an Excel-like file.\nJust click the top left cell and use command "v".\nColumns that pertain to interpretations will be marked with "++".'.format(self.grid_type + 's')
        txt = ''
        if self.grid_type == 'location':
            txt = '\n\nNote: you can fill in location start/end latitude/longitude here.\nHowever, if you add sites in step 2, the program will calculate those values automatically,\nbased on site latitudes/logitudes.\nThese values will be written to your upload file.'
        if self.grid_type == 'sample':
            txt = "\n\nNote: you can fill in lithology, class, and type for each sample here.\nHowever, if the sample's class, lithology, and type are the same as its parent site,\nthose values will propagate down, and will be written to your sample file automatically."
        if self.grid_type == 'specimen':
            txt = "\n\nNote: you can fill in lithology, class, and type for each specimen here.\nHowever, if the specimen's class, lithology, and type are the same as its parent sample,\nthose values will propagate down, and will be written to your specimen file automatically."
        if self.grid_type == 'age':
            txt = "\n\nNote: only ages for which you provide data will be written to your upload file."
        self.default_msg_text += txt
        self.msg_text = wx.StaticText(self.panel, label=self.default_msg_text,
                                      style=wx.TE_CENTER, name='msg text')
        self.help_msg_boxsizer.Add(self.msg_text)
        self.help_msg_boxsizer.ShowItems(False)

        ## Code message and button
        # button
        self.toggle_codes_btn = wx.Button(self.panel, id=-1, label="Show method codes",
                                          name='toggle_codes_btn')
        self.Bind(wx.EVT_BUTTON, self.toggle_codes, self.toggle_codes_btn)
        # message
        self.code_msg_boxsizer = pw.MethodCodeDemystifier(self.panel, vocab)
        self.code_msg_boxsizer.ShowItems(False)

        ## Add content to sizers
        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        col_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Columns',
                                                      name='manage columns'), wx.VERTICAL)
        row_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Rows',
                                                      name='manage rows'), wx.VERTICAL)
        main_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Manage data',
                                                       name='manage data'), wx.VERTICAL)
        col_btn_vbox.Add(self.add_cols_button, 1, flag=wx.ALL, border=5)
        col_btn_vbox.Add(self.remove_cols_button, 1, flag=wx.ALL, border=5)
        row_btn_vbox.Add(many_rows_box, 1, flag=wx.ALL, border=5)
        row_btn_vbox.Add(self.remove_row_button, 1, flag=wx.ALL, border=5)
        row_btn_vbox.Add(self.deleteRowButton, 1, flag=wx.ALL, border=5)
        main_btn_vbox.Add(self.importButton, 1, flag=wx.ALL, border=5)
        main_btn_vbox.Add(self.exitButton, 1, flag=wx.ALL, border=5)
        main_btn_vbox.Add(self.cancelButton, 1, flag=wx.ALL, border=5)
        self.hbox.Add(col_btn_vbox, 1)
        self.hbox.Add(row_btn_vbox, 1)
        self.hbox.Add(main_btn_vbox, 1)

        self.panel.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)
        self.Bind(wx.EVT_KEY_DOWN, self.on_key_down)
        self.panel.Bind(wx.EVT_TEXT_PASTE, self.do_fit)

        # add actual data!
        self.grid_builder.add_data_to_grid(self.grid, self.grid_type)
        if self.grid_type == 'age':
            self.grid_builder.add_age_data_to_grid()

        # add drop_down menus
        if self.parent_type:
            belongs_to = sorted(self.er_magic.data_lists[self.parent_type][0], key=lambda item: item.name)
        else:
            belongs_to = ''
        self.drop_down_menu = drop_down_menus.Menus(self.grid_type, self, self.grid, belongs_to)

        self.grid_box = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, name='grid container'), wx.VERTICAL)
        self.grid_box.Add(self.grid, 1, flag=wx.ALL|wx.EXPAND, border=5)

        # a few special touches if it is a location grid
        if self.grid_type == 'location':
            lat_lon_dict = self.er_magic.get_min_max_lat_lon(self.er_magic.locations)
            for loc in self.er_magic.locations:
                # try to fill in min/max latitudes/longitudes from sites
                d = lat_lon_dict[loc.name]
                col_labels = [self.grid.GetColLabelValue(col) for col in range(self.grid.GetNumberCols())]
                row_labels = [self.grid.GetCellValue(row, 0) for row in range(self.grid.GetNumberRows())]
                for key, value in list(d.items()):
                    if value:
                        if str(loc.er_data[key]) == str(value):
                            # no need to update
                            pass
                        else:
                            # update
                            loc.er_data[key] = value
                            col_ind = col_labels.index(key)
                            row_ind = row_labels.index(loc.name)
                            self.grid.SetCellValue(row_ind, col_ind, str(value))
                            if not self.grid.changes:
                                self.grid.changes = set([row_ind])
                            else:
                                self.grid.changes.add(row_ind)

        # a few special touches if it is an age grid
        if self.grid_type == 'age':
            self.remove_row_button.Disable()
            self.add_many_rows_button.Disable()
            self.grid.SetColLabelValue(0, 'er_site_name')
            toggle_box = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Ages level', name='Ages level'), wx.VERTICAL)

            levels = ['specimen', 'sample', 'site', 'location']
            age_level = pw.radio_buttons(self.panel, levels, 'Choose level to assign ages')
            level_ind = levels.index(self.er_magic.age_type)
            age_level.radio_buttons[level_ind].SetValue(True)

            toggle_box.Add(age_level)

            self.Bind(wx.EVT_RADIOBUTTON, self.toggle_ages)
            self.hbox.Add(toggle_box)

        # a few special touches if it is a result grid
        if self.grid_type == 'result':
            # populate specimen_names, sample_names, etc.
            self.drop_down_menu.choices[2] = [sorted([spec.name for spec in self.er_magic.specimens if spec]), False]
            self.drop_down_menu.choices[3] = [sorted([samp.name for samp in self.er_magic.samples if samp]), False]
            self.drop_down_menu.choices[4] = [sorted([site.name for site in self.er_magic.sites if site]), False]
            self.drop_down_menu.choices[5] = [sorted([loc.name for loc in self.er_magic.locations if loc]), False]
            for row in range(self.grid.GetNumberRows()):
                result_name = self.grid.GetCellValue(row, 0)
                result = self.er_magic.find_by_name(result_name, self.er_magic.results)
                if result:
                    if result.specimens:
                        self.grid.SetCellValue(row, 2, ' : '.join([pmag.get_attr(spec) for spec in result.specimens]))
                    if result.samples:
                        self.grid.SetCellValue(row, 3, ' : '.join([pmag.get_attr(samp) for samp in result.samples]))
                    if result.sites:
                        self.grid.SetCellValue(row, 4, ' : '.join([pmag.get_attr(site) for site in result.sites]))
                    if result.locations:
                        self.grid.SetCellValue(row, 5, ' : '.join([pmag.get_attr(loc) for loc in result.locations]))
                    self.drop_down_menu.choices[5] = [sorted([loc.name for loc in self.er_magic.locations if loc]), False]

        # final layout, set size
        self.main_sizer.Add(self.hbox, flag=wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, border=20)
        self.main_sizer.Add(self.toggle_help_btn, .5, flag=wx.BOTTOM|wx.ALIGN_CENTRE|wx.SHAPED, border=5)
        self.main_sizer.Add(self.help_msg_boxsizer, .5, flag=wx.BOTTOM|wx.ALIGN_CENTRE|wx.SHAPED, border=10)
        self.main_sizer.Add(self.toggle_codes_btn, .5, flag=wx.BOTTOM|wx.ALIGN_CENTRE|wx.SHAPED, border=5)
        self.main_sizer.Add(self.code_msg_boxsizer, .5, flag=wx.BOTTOM|wx.ALIGN_CENTRE|wx.SHAPED, border=5)
        self.main_sizer.Add(self.grid_box, 2, flag=wx.ALL|wx.EXPAND, border=10)
        self.panel.SetSizer(self.main_sizer)
        self.main_sizer.Fit(self)
        ## this keeps sizing correct if the user resizes the window manually
        #self.Bind(wx.EVT_SIZE, self.do_fit)
        self.Centre()
        self.Show()


Instruction:
Here you have a function in Python 3, explain what it does
def do_fit(self, event):
        #self.grid.ShowScrollbars(wx.SHOW_SB_NEVER, wx.SHOW_SB_NEVER)
        if event:
            event.Skip()
        self.main_sizer.Fit(self)
        disp_size = wx.GetDisplaySize()
        actual_size = self.GetSize()
        rows = self.grid.GetNumberRows()
        # if there isn't enough room to display new content
        # resize the frame
        if disp_size[1] - 75 < actual_size[1]:
            self.SetSize((actual_size[0], disp_size[1] * .95))
        self.Centre()

Response: Re - fit the window to the size of the content.


Instruction:
Explain what the following Python 3 code does
def toggle_ages(self, event):
        if self.grid.changes:
            self.onSave(None)

        label = event.GetEventObject().Label

        self.er_magic.age_type = label
        self.grid.Destroy()

        # normally grid_frame is reset to None when grid is destroyed
        # in this case we are simply replacing the grid, so we need to
        # reset grid_frame
        self.parent.Parent.grid_frame = self
        self.parent.Parent.Hide()
        self.grid = self.grid_builder.make_grid()
        self.grid.InitUI()
        self.panel.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)
        self.grid_builder.add_data_to_grid(self.grid, self.grid_type)
        self.grid_builder.add_age_data_to_grid()
        self.drop_down_menu = drop_down_menus.Menus(self.grid_type, self, self.grid, None)
        self.grid.SetColLabelValue(0, 'er_' + label + '_name')
        self.grid.size_grid()
        self.grid_box.Add(self.grid, flag=wx.ALL, border=5)
        self.main_sizer.Fit(self)
        if self.parent.Parent.validation_mode:
            if 'age' in self.parent.Parent.validation_mode:
                self.grid.paint_invalid_cells(self.parent.Parent.warn_dict['age'])
                self.grid.ForceRefresh()
        # the grid show up if it's the same size as the previous grid
        # awkward solution (causes flashing):
        if self.grid.Size[0] < 100:
            if self.grid.GetWindowStyle() != wx.DOUBLE_BORDER:
                self.grid.SetWindowStyle(wx.DOUBLE_BORDER)
            self.main_sizer.Fit(self)
            self.grid.SetWindowStyle(wx.NO_BORDER)
            self.main_sizer.Fit(self)

Response: Switch the type of grid between site and sample ages


Instruction:
Create a Python 3 function for
removing a column from the grid

Response:
def remove_col_label(self, event):#, include_pmag=True):
        """
        check to see if column is required
        if it is not, delete it from grid
        """
        er_possible_headers = self.grid_headers[self.grid_type]['er'][2]
        pmag_possible_headers = self.grid_headers[self.grid_type]['pmag'][2]
        er_actual_headers = self.grid_headers[self.grid_type]['er'][0]
        pmag_actual_headers = self.grid_headers[self.grid_type]['pmag'][0]
        col = event.GetCol()
        label = self.grid.GetColLabelValue(col)
        if '**' in label:
            label = label.strip('**')
        if label in self.grid_headers[self.grid_type]['er'][1]:
            pw.simple_warning("That header is required, and cannot be removed")
            return False
        #elif include_pmag and label in self.grid_headers[self.grid_type]['pmag'][1]:
        #    pw.simple_warning("That header is required, and cannot be removed")
        #    return False
        else:
            print('That header is not required:', label)
            self.grid.remove_col(col)
            #if label in er_possible_headers:
            try:
                print('removing {} from er_actual_headers'.format(label))
                er_actual_headers.remove(label)
            except ValueError:
                pass
            #if label in pmag_possible_headers:
            try:
                pmag_actual_headers.remove(label)
            except ValueError:
                pass
        # causes resize on each column header delete
        # can leave this out if we want.....
        self.main_sizer.Fit(self)


Instruction:
Can you write a function in Python 3 where it
shows simple dialog that allows user to add a new column name

Response:
def on_add_cols(self, event):
        """
        Show simple dialog that allows user to add a new column name
        """
        col_labels = self.grid.col_labels
        # do not list headers that are already column labels in the grid
        er_items = [head for head in self.grid_headers[self.grid_type]['er'][2] if head not in col_labels]
        # remove unneeded headers
        er_items = builder.remove_list_headers(er_items)
        pmag_headers = sorted(list(set(self.grid_headers[self.grid_type]['pmag'][2]).union(self.grid_headers[self.grid_type]['pmag'][1])))
        # do not list headers that are already column labels in the grid
        # make sure that pmag_specific columns are marked with '++'
        to_add = [i + '++' for i in self.er_magic.double if i in pmag_headers and i + '++' not in col_labels]
        pmag_headers.extend(to_add)
        pmag_items = [head for head in pmag_headers if head not in er_items and head not in col_labels]
        # remove unneeded headers
        pmag_items = sorted(builder.remove_list_headers(pmag_items))
        dia = pw.HeaderDialog(self, 'columns to add', items1=er_items, items2=pmag_items)
        dia.Centre()
        result = dia.ShowModal()
        new_headers = []
        if result == 5100:
            new_headers = dia.text_list
        if not new_headers:
            return
        errors = self.add_new_grid_headers(new_headers, er_items, pmag_items)
        if errors:
            errors_str = ', '.join(errors)
            pw.simple_warning('You are already using the following headers: {}\nSo they will not be added'.format(errors_str))

        # problem: if widgets above the grid are too wide,
        # the grid does not re-size when adding columns
        # awkward solution (causes flashing):
        if self.grid.GetWindowStyle() != wx.DOUBLE_BORDER:
            self.grid.SetWindowStyle(wx.DOUBLE_BORDER)
        self.main_sizer.Fit(self)
        self.grid.SetWindowStyle(wx.NO_BORDER)
        self.Centre()
        self.main_sizer.Fit(self)
        #
        self.grid.changes = set(range(self.grid.GetNumberRows()))
        dia.Destroy()


Instruction:
Implement a Python 3 function for
adding in all user - added headers.

Response:
def add_new_grid_headers(self, new_headers, er_items, pmag_items):
        """
        Add in all user-added headers.
        If those new headers depend on other headers, add the other headers too.
        """

        def add_pmag_reqd_headers():
            if self.grid_type == 'result':
                return []
            add_in = []
            col_labels = self.grid.col_labels
            for reqd_head in self.grid_headers[self.grid_type]['pmag'][1]:
                if reqd_head in self.er_magic.double:
                    if reqd_head + "++"  not in col_labels:
                        add_in.append(reqd_head + "++")
                else:
                    if reqd_head not in col_labels:
                        add_in.append(reqd_head)
            add_in = builder.remove_list_headers(add_in)
            return add_in
        #
        already_present = []
        for name in new_headers:
            if name:
                if name not in self.grid.col_labels:
                    col_number = self.grid.add_col(name)
                    # add to appropriate headers list
                    if name in er_items:
                        self.grid_headers[self.grid_type]['er'][0].append(str(name))
                    if name in pmag_items:
                        name = name.strip('++')
                        if name not in self.grid_headers[self.grid_type]['pmag'][0]:
                            self.grid_headers[self.grid_type]['pmag'][0].append(str(name))
                            # add any required pmag headers that are not in the grid already
                            for header in add_pmag_reqd_headers():
                                col_number = self.grid.add_col(header)
                                # add drop_down_menus for added reqd columns
                                if header in vocab.possible_vocabularies:
                                    self.drop_down_menu.add_drop_down(col_number, name)
                                if header in ['magic_method_codes++']:
                                    self.drop_down_menu.add_method_drop_down(col_number, header)
                    # add drop down menus for user-added column
                    if name in vocab.possible_vocabularies:
                        self.drop_down_menu.add_drop_down(col_number, name)
                    if name in ['magic_method_codes', 'magic_method_codes++']:
                        self.drop_down_menu.add_method_drop_down(col_number, name)
                else:
                    already_present.append(name)
                    #pw.simple_warning('You are already using column header: {}'.format(name))
        return already_present


Instruction:
Can you tell what is the following Python 3 function doing
def on_remove_cols(self, event):
        # open the help message
        self.toggle_help(event=None, mode='open')
        # first unselect any selected cols/cells
        self.remove_cols_mode = True
        self.grid.ClearSelection()
        self.remove_cols_button.SetLabel("end delete column mode")
        # change button to exit the delete columns mode
        self.Unbind(wx.EVT_BUTTON, self.remove_cols_button)
        self.Bind(wx.EVT_BUTTON, self.exit_col_remove_mode, self.remove_cols_button)
        # then disable all other buttons
        for btn in [self.add_cols_button, self.remove_row_button, self.add_many_rows_button]:
            btn.Disable()
        # then make some visual changes
        self.msg_text.SetLabel("Remove grid columns: click on a column header to delete it.  Required headers for {}s may not be deleted.".format(self.grid_type))
        self.help_msg_boxsizer.Fit(self.help_msg_boxsizer.GetStaticBox())
        self.main_sizer.Fit(self)
        self.grid.SetWindowStyle(wx.DOUBLE_BORDER)
        self.grid_box.GetStaticBox().SetWindowStyle(wx.DOUBLE_BORDER)
        self.grid.Refresh()
        self.main_sizer.Fit(self) # might not need this one
        self.grid.changes = set(range(self.grid.GetNumberRows()))

Response: enter remove columns mode


Instruction:
Can you generate a brief explanation for the following Python 3 code
def on_remove_row(self, event, row_num=-1):
        if row_num == -1:
            default = (255, 255, 255, 255)
            # unhighlight any selected rows:
            for row in self.selected_rows:
                attr = wx.grid.GridCellAttr()
                attr.SetBackgroundColour(default)
                self.grid.SetRowAttr(row, attr)
            row_num = self.grid.GetNumberRows() - 1
            self.deleteRowButton.Disable()
            self.selected_rows = {row_num}

        function_mapping = {'specimen': self.er_magic.delete_specimen,
                            'sample': self.er_magic.delete_sample,
                            'site': self.er_magic.delete_site,
                            'location': self.er_magic.delete_location,
                            'result': self.er_magic.delete_result}

        names = [self.grid.GetCellValue(row, 0) for row in self.selected_rows]
        orphans = []
        for name in names:
            if name:
                try:
                    row = self.grid.row_labels.index(name)
                    function_mapping[self.grid_type](name)
                    orphans.extend([name])
                # if user entered a name, then deletes the row before saving,
                # there will be a ValueError
                except ValueError:
                    pass
            self.grid.remove_row(row)
        self.selected_rows = set()
        self.deleteRowButton.Disable()
        self.grid.Refresh()
        self.main_sizer.Fit(self)

Response: Remove specified grid row.


Instruction:
How would you implement a function in Python 3 that
exits col remove mode

Response:
def exit_col_remove_mode(self, event):
        """
        go back from 'remove cols' mode to normal
        """
        # close help messge
        self.toggle_help(event=None, mode='close')
        # update mode
        self.remove_cols_mode = False
        # re-enable all buttons
        for btn in [self.add_cols_button, self.remove_row_button, self.add_many_rows_button]:
            btn.Enable()

        # unbind grid click for deletion
        self.Unbind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK)
        # undo visual cues
        self.grid.SetWindowStyle(wx.DEFAULT)
        self.grid_box.GetStaticBox().SetWindowStyle(wx.DEFAULT)
        self.msg_text.SetLabel(self.default_msg_text)
        self.help_msg_boxsizer.Fit(self.help_msg_boxsizer.GetStaticBox())
        self.main_sizer.Fit(self)
        # re-bind self.remove_cols_button
        self.Bind(wx.EVT_BUTTON, self.on_remove_cols, self.remove_cols_button)
        self.remove_cols_button.SetLabel("Remove columns")


Instruction:
Make a summary of the following Python 3 code
def make_grid(self, incl_pmag=True):
        if incl_pmag and self.grid_type in self.er_magic.incl_pmag_data:
            incl_pmag = True
        else:
            incl_pmag = False
        er_header = self.grid_headers[self.grid_type]['er'][0]
        if incl_pmag:
            pmag_header = self.grid_headers[self.grid_type]['pmag'][0]
        else:
            pmag_header = []
        # if we need to use '++' to distinguish pmag magic_method_codes from er
        if incl_pmag and self.grid_type in ('specimen', 'sample', 'site'):
            for double_header in self.er_magic.double:
                try:
                    pmag_header.remove(double_header)
                    pmag_header.append(double_header + '++')
                except ValueError:
                    pass
        header = sorted(list(set(er_header).union(pmag_header)))

        first_headers = []
        for string in ['citation', '{}_class'.format(self.grid_type),
                       '{}_lithology'.format(self.grid_type), '{}_type'.format(self.grid_type),
                      'site_definition']:
            for head in header[:]:
                if string in head:
                    header.remove(head)
                    first_headers.append(head)

        # the way we work it, each specimen is assigned to a sample
        # each sample is assigned to a site
        # specimens can not be added en masse to a site object, for example
        # this data will be written in
        for string in ['er_specimen_names', 'er_sample_names', 'er_site_names']:
            for head in header[:]:
                if string in head:
                    header.remove(head)

        # do headers for results type grid
        if self.grid_type == 'result':
            #header.remove('pmag_result_name')
            header[:0] = ['pmag_result_name', 'er_citation_names', 'er_specimen_names',
                          'er_sample_names', 'er_site_names', 'er_location_names']

        elif self.grid_type == 'age':
            for header_type in self.er_magic.first_age_headers:
                if header_type in header:
                    header.remove(header_type)
            lst = ['er_' + self.grid_type + '_name']
            lst.extend(self.er_magic.first_age_headers)
            header[:0] = lst

        # do headers for all other data types without parents
        elif not self.parent_type:
            lst = ['er_' + self.grid_type + '_name']
            lst.extend(first_headers)
            header[:0] = lst
        # do headers for all data types with parents
        else:
            lst = ['er_' + self.grid_type + '_name', 'er_' + self.parent_type + '_name']
            lst.extend(first_headers)
            header[:0] = lst

        grid = magic_grid.MagicGrid(parent=self.panel, name=self.grid_type,
                                    row_labels=[], col_labels=header,
                                    double=self.er_magic.double)
        grid.do_event_bindings()

        self.grid = grid
        return grid

Response: make a new grid of pmag_magic_data


Instruction:
Can you implement a function in Python 3 that
saves the grid data in the data object

Response:
def save_grid_data(self):
        """
        Save grid data in the data object
        """
        if not self.grid.changes:
            print('-I- No changes to save')
            return

        if self.grid_type == 'age':
            age_data_type = self.er_magic.age_type
            self.er_magic.write_ages = True

        starred_cols = self.grid.remove_starred_labels()

        self.grid.SaveEditControlValue() # locks in value in cell currently edited

        if self.grid.changes:
            num_cols = self.grid.GetNumberCols()

            for change in self.grid.changes:
                if change == -1:
                    continue
                else:
                    old_item = self.grid.row_items[change]
                    new_item_name = self.grid.GetCellValue(change, 0)
                    new_er_data = {}
                    new_pmag_data = {}
                    er_header = self.grid_headers[self.grid_type]['er'][0]
                    pmag_header = self.grid_headers[self.grid_type]['pmag'][0]
                    start_num = 2 if self.parent_type else 1
                    result_data = {}

                    for col in range(start_num, num_cols):
                        col_label = str(self.grid.GetColLabelValue(col))
                        value = str(self.grid.GetCellValue(change, col))
                        #new_data[col_label] = value
                        if value == '\t':
                            value = ''

                        if '++' in col_label:
                            col_name = col_label[:-2]
                            new_pmag_data[col_name] = value
                            continue

                        # pmag_* files are new interpretations, so should only have "This study"
                        # er_* files can have multiple citations
                        if col_label == 'er_citation_names':
                            new_pmag_data[col_label] = 'This study'
                            new_er_data[col_label] = value
                            continue

                        if er_header and (col_label in er_header):
                            new_er_data[col_label] = value

                        if self.grid_type in ('specimen', 'sample', 'site'):
                            if pmag_header and (col_label in pmag_header) and (col_label not in self.er_magic.double):
                                new_pmag_data[col_label] = value
                        else:
                            if pmag_header and (col_label in pmag_header):
                                new_pmag_data[col_label] = value

                        if col_label in ('er_specimen_names', 'er_sample_names',
                                         'er_site_names', 'er_location_names'):
                            result_data[col_label] = value

                    # if there is an item in the data, get its name
                    if isinstance(old_item, str):
                        old_item_name = None
                    else:
                        old_item_name = self.grid.row_items[change].name

                    if self.parent_type:
                        new_parent_name = self.grid.GetCellValue(change, 1)
                    else:
                        new_parent_name = ''

                    # create a new item
                    if new_item_name and not old_item_name:
                        print('-I- make new item named', new_item_name)
                        if self.grid_type == 'result':
                            specs, samps, sites, locs = self.get_result_children(result_data)
                            item = self.er_magic.add_result(new_item_name, specs, samps, sites,
                                                            locs, new_pmag_data)
                        else:
                            item = self.er_magic.add_methods[self.grid_type](new_item_name, new_parent_name,
                                                                             new_er_data, new_pmag_data)

                    # update an existing item
                    elif new_item_name and old_item_name:
                        print('-I- update existing {} formerly named {} to {}'.format(self.grid_type,
                                                                                old_item_name,
                                                                                new_item_name))
                        if self.grid_type == 'result':
                            specs, samps, sites, locs = self.get_result_children(result_data)
                            item = self.er_magic.update_methods['result'](old_item_name, new_item_name,
                                                                          new_er_data=None,
                                                                          new_pmag_data=new_pmag_data,
                                                                          spec_names=specs,
                                                                          samp_names=samps,
                                                                          site_names=sites,
                                                                          loc_names=locs,
                                                                          replace_data=True)
                        elif self.grid_type == 'age':
                            item_type = age_data_type
                            item = self.er_magic.update_methods['age'](old_item_name, new_er_data,
                                                                       item_type, replace_data=True)

                        else:
                            item = self.er_magic.update_methods[self.grid_type](old_item_name, new_item_name,
                                                                                new_parent_name, new_er_data,
                                                                                new_pmag_data, replace_data=True)


Instruction:
Can you write a function in Python 3 where it
names hysteresis_magic.py DESCRIPTION calculates hystereis parameters and saves them in rmag_hystereis format file makes plots if option selected SYNTAX hysteresis_magic.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is agm_measurements.txt -fh: specify rmag_hysteresis.txt input file -F: specify output file, default is rmag_hysteresis.txt -P: do not make the plots -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg]

Response:
def main():
    """
    NAME
        hysteresis_magic.py

    DESCRIPTION
        calculates hystereis parameters and saves them in rmag_hystereis format file
        makes plots if option selected

    SYNTAX
        hysteresis_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is agm_measurements.txt
        -fh: specify rmag_hysteresis.txt input file
        -F: specify output file, default is rmag_hysteresis.txt
        -P: do not make the plots
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    PLT = 1
    plots = 0
    user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", ""
    pltspec = ""
    dir_path = '.'
    fmt = 'svg'
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    if '-WD' in args:
        ind = args.index('-WD')
        dir_path = args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind+1]
    if '-f' in args:
        ind = args.index("-f")
        meas_file = args[ind+1]
    if '-F' in args:
        ind = args.index("-F")
        rmag_out = args[ind+1]
    if '-fh' in args:
        ind = args.index("-fh")
        rmag_file = args[ind+1]
        rmag_file = dir_path+'/'+rmag_file
    if '-P' in args:
        PLT = 0
        irm_init, imag_init = -1, -1
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind+1]
        verbose = 0
        plots = 1
    if '-fmt' in args:
        ind = args.index("-fmt")
        fmt = args[ind+1]
    rmag_out = dir_path+'/'+rmag_out
    meas_file = dir_path+'/'+meas_file
    rmag_rem = dir_path+"/rmag_remanence.txt"
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    if verbose:
        if verbose and PLT:
            print("Plots may be on top of each other - use mouse to place ")
    if PLT:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3
        pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['deltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['hyst'], 5, 5)
        imag_init = 0
        irm_init = 0
    else:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD['imag'] = 0, 0, 0, 0, 0
    #
    if rmag_file != "":
        hyst_data, file_type = pmag.magic_read(rmag_file)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names, sids = [], []
    for rec in meas_data:
        meths = rec['magic_method_codes'].split(':')
        methods = []
        for meth in meths:
            methods.append(meth.strip())
        if 'LP-HYS' in methods:
            if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name'] != "":
                rec['er_specimen_name'] = rec['er_synthetic_name']
            if rec['magic_experiment_name'] not in experiment_names:
                experiment_names.append(rec['magic_experiment_name'])
            if rec['er_specimen_name'] not in sids:
                sids.append(rec['er_specimen_name'])
    #
    k = 0
    locname = ''
    if pltspec != "":
        k = sids.index(pltspec)
        print(sids[k])
    while k < len(sids):
        s = sids[k]
        if verbose and PLT:
            print(s, k+1, 'out of ', len(sids))
    #
    #
        # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M, Bdcd, Mdcd = [], [], [], []
        Bimag, Mimag = [], []  # Bimag,Mimag for initial magnetization curves
        first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1
        for rec in meas_data:
            methcodes = rec['magic_method_codes'].split(':')
            meths = []
            for meth in methcodes:
                meths.append(meth.strip())
            if rec['er_specimen_name'] == s and "LP-HYS" in meths:
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec['measurement_magn_moment']))
                if first_rec == 1:
                    e = rec['magic_experiment_name']
                    HystRec = {}
                    first_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        HystRec["er_location_name"] = rec["er_location_name"]
                        locname = rec['er_location_name'].replace('/', '-')
                    if "er_sample_name" in list(rec.keys()):
                        HystRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        HystRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        HystRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        HystRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == s and "LP-IRM-DCD" in meths:
                Bdcd.append(float(rec['treatment_dc_field']))
                Mdcd.append(float(rec['measurement_magn_moment']))
                if first_dcd_rec == 1:
                    RemRec = {}
                    irm_exp = rec['magic_experiment_name']
                    first_dcd_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        RemRec["er_location_name"] = rec["er_location_name"]
                    if "er_sample_name" in list(rec.keys()):
                        RemRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        RemRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        RemRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        RemRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == s and "LP-IMAG" in meths:
                if first_imag_rec == 1:
                    imag_exp = rec['magic_experiment_name']
                    first_imag_rec = 0
                Bimag.append(float(rec['measurement_lab_field_dc']))
                Mimag.append(float(rec['measurement_magn_moment']))
    #
    # now plot the hysteresis curve
    #
        if len(B) > 0:
            hmeths = []
            for meth in meths:
                hmeths.append(meth)
            hpars = pmagplotlib.plot_hdd(HDD, B, M, e)
            if verbose and PLT:
                pmagplotlib.draw_figs(HDD)
    #
    # get prior interpretations from hyst_data
            if rmag_file != "":
                hpars_prior = {}
                for rec in hyst_data:
                    if rec['magic_experiment_names'] == e:
                        if rec['hysteresis_bcr'] != "" and rec['hysteresis_mr_moment'] != "":
                            hpars_prior['hysteresis_mr_moment'] = rec['hysteresis_mr_moment']
                            hpars_prior['hysteresis_ms_moment'] = rec['hysteresis_ms_moment']
                            hpars_prior['hysteresis_bc'] = rec['hysteresis_bc']
                            hpars_prior['hysteresis_bcr'] = rec['hysteresis_bcr']
                            break
                if verbose:
                    pmagplotlib.plot_hpars(HDD, hpars_prior, 'ro')
            else:
                if verbose:
                    pmagplotlib.plot_hpars(HDD, hpars, 'bs')
                HystRec['hysteresis_mr_moment'] = hpars['hysteresis_mr_moment']
                HystRec['hysteresis_ms_moment'] = hpars['hysteresis_ms_moment']
                HystRec['hysteresis_bc'] = hpars['hysteresis_bc']
                HystRec['hysteresis_bcr'] = hpars['hysteresis_bcr']
                HystRec['hysteresis_xhf'] = hpars['hysteresis_xhf']
                HystRec['magic_experiment_names'] = e
                HystRec['magic_software_packages'] = version_num
                if hpars["magic_method_codes"] not in hmeths:
                    hmeths.append(hpars["magic_method_codes"])
                methods = ""
                for meth in hmeths:
                    methods = methods+meth.strip()+":"
                HystRec["magic_method_codes"] = methods[:-1]
                HystRec["er_citation_names"] = "This study"
                HystRecs.append(HystRec)
    #
        if len(Bdcd) > 0:
            rmeths = []
            for meth in meths:
                rmeths.append(meth)
            if verbose and PLT:
                print('plotting IRM')
            if irm_init == 0:
                HDD['irm'] = 5
                pmagplotlib.plot_init(HDD['irm'], 5, 5)
                irm_init = 1
            rpars = pmagplotlib.plot_irm(HDD['irm'], Bdcd, Mdcd, irm_exp)
            RemRec['remanence_mr_moment'] = rpars['remanence_mr_moment']
            RemRec['remanence_bcr'] = rpars['remanence_bcr']
            RemRec['magic_experiment_names'] = irm_exp
            if rpars["magic_method_codes"] not in meths:
                meths.append(rpars["magic_method_codes"])
            methods = ""
            for meth in rmeths:
                methods = methods+meth.strip()+":"
            RemRec["magic_method_codes"] = methods[:-1]
            RemRec["er_citation_names"] = "This study"
            RemRecs.append(RemRec)
        else:
            if irm_init:
                pmagplotlib.clearFIG(HDD['irm'])
        if len(Bimag) > 0:
            if verbose:
                print('plotting initial magnetization curve')
# first normalize by Ms
            Mnorm = []
            for m in Mimag:
                Mnorm.append(m / float(hpars['hysteresis_ms_moment']))
            if imag_init == 0:
                HDD['imag'] = 4
                pmagplotlib.plot_init(HDD['imag'], 5, 5)
                imag_init = 1
            pmagplotlib.plot_imag(HDD['imag'], Bimag, Mnorm, imag_exp)
        else:
            if imag_init:
                pmagplotlib.clearFIG(HDD['imag'])
    #
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            files = {}
            for key in list(HDD.keys()):
                files[key] = locname+'_'+s+'_'+key+'.'+fmt
            pmagplotlib.save_plots(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose and PLT:
            pmagplotlib.draw_figs(HDD)
            ans = input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans == "a":
                files = {}
                for key in list(HDD.keys()):
                    files[key] = locname+'_'+s+'_'+key+'.'+fmt
                pmagplotlib.save_plots(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0 and len(Bdcd) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1
    if rmag_out == "" and ans == 's' and verbose:
        really = input(
            " Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] ")
        if really == "":
            print('i thought not - goodbye')
            sys.exit()
        rmag_out = "rmag_hysteresis.txt"
    if len(HystRecs) > 0:
        pmag.magic_write(rmag_out, HystRecs, "rmag_hysteresis")
        if verbose:
            print("hysteresis parameters saved in ", rmag_out)
    if len(RemRecs) > 0:
        pmag.magic_write(rmag_rem, RemRecs, "rmag_remanence")
        if verbose:
            print("remanence parameters saved in ", rmag_rem)


Instruction:
Can you generate the documentation for the following Python 3 function
def main():
#
# get command line arguments
#

    args = sys.argv
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    user = pmag.get_named_arg("-usr", "")
    labfield = pmag.get_named_arg("-dc", '0.5')
    meas_file = pmag.get_named_arg("-F", "measurements.txt")
    samp_file = pmag.get_named_arg("-fsa", "samples.txt")
    try:
        infile = pmag.get_named_arg("-f", reqd=True)
    except pmag.MissingCommandLineArgException:
        print(main.__doc__)
        print("-f  is required option")
        sys.exit()
    specnum = int(pmag.get_named_arg("-spc", 0))
    location = pmag.get_named_arg("-loc", "")
    specimen_name = pmag.get_named_arg("-spn", reqd=True)
    syn = 0
    if "-syn" in args:
        syn = 1
    samp_con = pmag.get_named_arg("-ncn", "1")
    if "-ncn" in args:
        ind = args.index("-ncn")
        samp_con = sys.argv[ind+1]
    data_model_num = int(pmag.get_named_arg("-DM", 3))
    convert.mst(infile, specimen_name, dir_path, "", meas_file, samp_file,
        user, specnum, samp_con, labfield, location, syn, data_model_num)

Response: This function is the main entry point for the magic command line tool. It is used to convert MsT data to measurements format files and print help message and quits.


Instruction:
Create a Python 3 function for
naming parse_measurements.py DESCRIPTION takes measurments file and creates specimen and instrument files SYNTAX parse_measurements.py [command line options] OPTIONS -h prints help message and quits -f FILE magic_measurements input file, default is "magic_measurements.txt" -fsi FILE er_sites input file, default is none -Fsp FILE specimen output er_specimens format file, default is "er_specimens.txt" -Fin FILE instrument output magic_instruments format file, default is "magic_instruments.txt" OUPUT writes er_specimens and magic_instruments formatted files

Response:
def main():
    """
    NAME
        parse_measurements.py

    DESCRIPTION
        takes measurments file and creates specimen and instrument files

    SYNTAX
        parse_measurements.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE magic_measurements input file, default is "magic_measurements.txt"
        -fsi FILE er_sites input file, default is none
        -Fsp  FILE specimen output er_specimens format file, default is "er_specimens.txt"
        -Fin FILE instrument output  magic_instruments format file, default is "magic_instruments.txt"
    OUPUT
        writes er_specimens and magic_instruments formatted files

    """
    infile = 'magic_measurements.txt'
    sitefile = ""
    specout = "er_specimens.txt"
    instout = "magic_instruments.txt"
# get command line stuff
    if "-h" in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        infile = sys.argv[ind + 1]
    if '-fsi' in sys.argv:
        ind = sys.argv.index("-fsi")
        sitefile = sys.argv[ind + 1]
    if '-Fsp' in sys.argv:
        ind = sys.argv.index("-Fsp")
        specout = sys.argv[ind + 1]
    if '-Fin' in sys.argv:
        ind = sys.argv.index("-Fin")
        instout = sys.argv[ind + 1]
    if '-WD' in sys.argv:
        ind = sys.argv.index("-WD")
        dir_path = sys.argv[ind + 1]
        infile = dir_path + '/' + infile
        if sitefile != "":
            sitefile = dir_path + '/' + sitefile
        specout = dir_path + '/' + specout
        instout = dir_path + '/' + instout
# now do re-ordering
    pmag.ParseMeasFile(infile, sitefile, instout, specout)


Instruction:
Write a Python 3 function that can
name utrecht_magic.py DESCRIPTION converts Utrecht magnetometer data files to magic_measurements files SYNTAX utrecht_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify output file, default is magic_measurements.txt -Fsa: specify er_samples format file for appending, default is new er_samples.txt (Not working yet) -WD: output directory for MagIC files -ncn: Site Naming Convention Site to Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2: default] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name = sample name [6] site name entered in site_name column in the orient.txt format input file -- NOT CURRENTLY SUPPORTED [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY -spc: number of characters to remove to generate sample names from specimen names -dmy: European date format -loc LOCNAME : specify location/study name -lat latitude of samples -lon longitude of samples -A: don't average replicate measurements -mcd: [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented -dc: B PHI THETA: dc lab field (in microTesla), phi,and theta must be input as a tuple "(DC,PHI,THETA)". If not input user will be asked for values, this is advantagious if there are differing dc fields between steps or specimens. Note: this currently only works with the decimal IZZI naming convetion (XXX.0,1,2,3 where XXX is the treatment temperature and 0 is a zero field step, 1 is in field, and 2 is a pTRM check, 3 is a tail check). All other steps are hardcoded dc_field = 0. INPUT Utrecht magnetometer data file

Response:
def main(command_line=True, **kwargs):
    """
    NAME
        utrecht_magic.py

    DESCRIPTION
        converts Utrecht magnetometer data files to magic_measurements files

    SYNTAX
        utrecht_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -f FILE: specify  input file, or
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsa: specify er_samples format file for appending, default is new er_samples.txt (Not working yet)
        -WD: output directory for MagIC files
        -ncn: Site Naming Convention
         Site to Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2: default] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name = sample name
            [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
            [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY
        -spc: number of characters to remove to generate sample names from specimen names
        -dmy: European date format
        -loc LOCNAME : specify location/study name
        -lat latitude of samples
        -lon longitude of samples
        -A: don't average replicate measurements
        -mcd: [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented
        -dc: B PHI THETA: dc lab field (in microTesla), phi,and theta must be input as a tuple "(DC,PHI,THETA)". If not input user will be asked for values, this is advantagious if there are differing dc fields between steps or specimens. Note: this currently only works with the decimal IZZI naming convetion (XXX.0,1,2,3 where XXX is the treatment temperature and 0 is a zero field step, 1 is in field, and 2 is a pTRM check, 3 is a tail check). All other steps are hardcoded dc_field = 0.

    INPUT
        Utrecht magnetometer data file
    """
# initialize some stuff
    sample_lat = 0.0
    sample_lon = 0.0
    noave = 0
    er_location_name = "unknown"
    args = sys.argv
    meth_code = "LP-NO"
    version_num = pmag.get_version()
    site_num = 1

    mag_file = ""
    dir_path = '.'
    MagRecs = []
    SpecOuts = []
    SampOuts = []
    SiteOuts = []

    meas_file='magic_measurements.txt'
    spec_file='er_specimens.txt'
    samp_file='er_samples.txt'
    site_file='er_sites.txt'
    meth_code = ""
    #
    # get command line arguments
    #
    if command_line:
        if '-WD' in sys.argv:
            ind = sys.argv.index('-WD')
            dir_path = sys.argv[ind+1]
        if '-ID' in sys.argv:
            ind = sys.argv.index('-ID')
            input_dir_path = sys.argv[ind+1]
        else:
            input_dir_path = dir_path
        output_dir_path = dir_path
        if "-h" in args:
            print(main.__doc__)
            return False
        if '-F' in args:
            ind = args.index("-F")
            meas_file = args[ind+1]
        if '-Fsp' in args:
            ind=args.index("-Fsp")
            spec_file=args[ind+1]
        if '-Fsa' in args:
            ind = args.index("-Fsa")
            samp_file = args[ind+1]
        if '-Fsi' in args:   # LORI addition
            ind=args.index("-Fsi")
            site_file=args[ind+1]
            #try:
            #    open(samp_file,'r')
            #    ErSamps,file_type=pmag.magic_read(samp_file)
            #    print 'sample information will be appended to ', samp_file
            #except:
            #    print samp_file,' not found: sample information will be stored in new er_samples.txt file'
            #    samp_file = output_dir_path+'/er_samples.txt'
        if '-f' in args:
            ind = args.index("-f")
            mag_file = args[ind+1]
        if "-loc" in args:
            ind = args.index("-loc")
            er_location_name = args[ind+1]
        if "-lat" in args:
            ind = args.index("-lat")
            site_lat = args[ind+1]
        if "-lon" in args:
            ind = args.index("-lon")
            site_lon = args[ind+1]
        if "-A" in args:
            noave = 1
        if "-mcd" in args:
            ind = args.index("-mcd")
            meth_code = args[ind+1]
            #samp_con='5'
        if "-ncn" in args:
            ind=args.index("-ncn")
            samp_con=sys.argv[ind+1]
            if "4" in samp_con:
                if "-" not in samp_con:
                    print("option [4] must be in form 4-Z where Z is an integer")
                    return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
                else:
                    site_num=samp_con.split("-")[1]
                    samp_con="4"
            elif "7" in samp_con:
                if "-" not in samp_con:
                    print("option [7] must be in form 7-Z where Z is an integer")
                    return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
                else:
                    site_num=samp_con.split("-")[1]
                    samp_con="7"
        else: samp_con="1"
        if '-dc' in args:
            ind=args.index('-dc')
            DC_FIELD,DC_PHI,DC_THETA=list(map(float,args[ind+1].strip('( ) [ ]').split(',')))
            DC_FIELD *= 1e-6
            yn=''
            GET_DC_PARAMS=False
        else: DC_FIELD,DC_PHI,DC_THETA=0,0,-90
        if '-spc' in args:
            ind=args.index("-spc")
            specnum=-int(args[ind+1])
        else: specnum = 0
        if '-dmy' in args:
            ind=args.index("-dmy")
            dmy_flag=True
        else: dmy_flag=False

    if not command_line:
        dir_path = kwargs.get('dir_path', '.')
        input_dir_path = kwargs.get('input_dir_path', dir_path)
        output_dir_path = dir_path
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
        mag_file = kwargs.get('mag_file')
        spec_file = kwargs.get('spec_file', 'er_specimens.txt') # specimen outfile
        samp_file = kwargs.get('samp_file', 'er_samples.txt')
        site_file = kwargs.get('site_file', 'er_sites.txt') # site outfile
        er_location_name = kwargs.get('location_name', '')
        site_lat = kwargs.get('site_lat', '')
        site_lon = kwargs.get('site_lon', '')
        #oave = kwargs.get('noave', 0) # default (0) means DO average
        meth_code = kwargs.get('meth_code', "LP-NO")
        specnum = -int(kwargs.get('specnum', 0))
        samp_con = kwargs.get('samp_con', '2')
        if "4" in samp_con:
            if "-" not in samp_con:
                print("option [4] must be in form 4-Z where Z is an integer")
                return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
            else:
                site_num=samp_con.split("-")[1]
                samp_con="4"
        elif "7" in samp_con:
            if "-" not in samp_con:
                print("option [7] must be in form 7-Z where Z is an integer")
                return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
            else:
                site_num=samp_con.split("-")[1]
                samp_con="7"
        DC_FIELD,DC_PHI,DC_THETA = list(map(float, kwargs.get('dc_params', (0,0,-90))))
        DC_FIELD *= 1e-6
        noave = kwargs.get('avg', True)
        dmy_flag = kwargs.get('dmy_flag', False)

    # format variables
    if not mag_file:
        return False, 'You must provide a Utrecht formated file'
    mag_file = os.path.join(input_dir_path, mag_file)
    meas_file = os.path.join(output_dir_path, meas_file)
    spec_file = os.path.join(output_dir_path, spec_file)
    samp_file = os.path.join(output_dir_path, samp_file)
    site_file = os.path.join(output_dir_path, site_file)

    # parse data

    # Open up the Utrecht file and read the header information
    print('mag_file in utrecht_file', mag_file)
    AF_or_T = mag_file.split('.')[-1]
    data = open(mag_file, 'r')
    line = data.readline()
    line_items = line.split(',')
    operator=line_items[0]
    operator=operator.replace("\"","")
    machine=line_items[1]
    machine=machine.replace("\"","")
    machine=machine.rstrip('\n')
    print("operator=", operator)
    print("machine=", machine)

    #read in measurement data
    line = data.readline()
    while line != "END" and line != '"END"':
        ErSpecRec,ErSampRec,ErSiteRec = {},{},{}
        line_items = line.split(',')
        spec_name=line_items[0]
        spec_name=spec_name.replace("\"","")
        print("spec_name=", spec_name)
        free_string=line_items[1]
        free_string=free_string.replace("\"","")
        print("free_string=", free_string)
        dec=line_items[2]
        print("dec=", dec)
        inc=line_items[3]
        print("inc=", inc)
        volume=float(line_items[4])
        volume=volume * 1e-6 # enter volume in cm^3, convert to m^3
        print("volume=", volume)
        bed_plane=line_items[5]
        print("bed_plane=", bed_plane)
        bed_tilt=line_items[6]
        print("bed_tilt=", bed_tilt)

        # Configure et er_ tables
        ErSpecRec['er_specimen_name'] = spec_name
        if specnum==0: sample_name = spec_name
        else: sample_name = spec_name[:specnum]
        ErSampRec['er_sample_name'] = sample_name
        ErSpecRec['er_sample_name'] = sample_name
        er_site_name = pmag.parse_site(sample_name,samp_con,site_num)
        ErSpecRec['er_site_name']=er_site_name
        ErSpecRec['er_location_name']=er_location_name
        ErSampRec['sample_azimuth'] = dec
        ErSampRec['sample_dip'] = str(float(inc)-90)
        ErSampRec['sample_bed_dip_direction'] = bed_plane
        ErSampRec['sample_bed_tilt'] = bed_tilt
        ErSiteRec['site_lat'] = site_lat
        ErSiteRec['site_lon'] = site_lon
        ErSpecRec['magic_method_codes'] = meth_code
        ErSampRec['er_location_name'] = er_location_name
        ErSiteRec['er_location_name'] = er_location_name
        ErSiteRec['er_site_name'] = er_site_name
        ErSampRec['er_site_name'] = er_site_name
        ErSampRec['er_citation_names'] = 'This study'
        SpecOuts.append(ErSpecRec)
        SampOuts.append(ErSampRec)
        SiteOuts.append(ErSiteRec)

        #measurement data
        line = data.readline()
        line = line.rstrip("\n")
        items = line.split(",")
        while line != '9999':
            print(line)
            step=items[0]
            step=step.split('.')
            step_value=step[0]
            step_type = ""
            if len(step) == 2:
                step_type=step[1]
            if step_type=='5':
                step_value = items[0]
            A=float(items[1])
            B=float(items[2])
            C=float(items[3])
#  convert to MagIC coordinates
            Z=-A
            X=-B
            Y=C
            cart = np.array([X, Y, Z]).transpose()
            direction = pmag.cart2dir(cart).transpose()
            measurement_dec = direction[0]
            measurement_inc = direction[1]
            measurement_magn_moment = direction[2] * 1.0e-12 # the data are in pico-Am^2 - this converts to Am^2
            measurement_magn_volume = direction[2] * 1.0e-12 / volume # data volume normalized - converted to A/m
            print("measurement_magn_moment=", measurement_magn_moment)
            print("measurement_magn_volume=", measurement_magn_volume)
            error = items[4]
            date=items[5]
            date=date.strip('"')
            if date.count("-") > 0:
                date=date.split("-")
            elif date.count("/") > 0:
                date=date.split("/")
            else: print("date format seperator cannot be identified")
            print(date)
            time=items[6]
            time=time.strip('"')
            time=time.split(":")
            print(time)
            if dmy_flag:
                date_time = date[1] + ":" + date[0] + ":" + date[2] + ":" + time[0] + ":" + time[1] + ":" + "0.0"
            else:
                date_time = date[0] + ":" + date[1] + ":" + date[2] + ":" + time[0] + ":" + time[1] + ":" + "0.0"
            print(date_time)

            MagRec = {}
            MagRec["er_analyst_mail_names"] = operator
            MagRec["magic_instrument_codes"] = "Utrecht_" + machine
            MagRec["measurement_description"] = "free string = " + free_string
            MagRec["measurement_date"] = date_time
            MagRec["er_citation_names"] = "This study"
            MagRec['er_location_name'] = er_location_name
            MagRec['er_site_name'] = er_site_name
            MagRec['er_sample_name'] = sample_name
            MagRec['magic_software_packages'] = version_num
            MagRec["measurement_temp"] = '%8.3e' % (273) # room temp in kelvin
            MagRec["measurement_flag"] = 'g'
            MagRec["measurement_standard"] = 'u'
            MagRec["magic_experiment_name"] = er_location_name + er_site_name + spec_name
            MagRec["measurement_number"] = er_location_name + er_site_name + spec_name + items[0]
            MagRec["er_specimen_name"] = spec_name
            # MagRec["treatment_ac_field"] = '0'
            if AF_or_T.lower() == "th":
                MagRec["treatment_temp"] = '%8.3e' % (float(step_value)+273.) # temp in kelvin
                MagRec['treatment_ac_field']='0'
                meas_type = "LP-DIR-T:LT-T-Z"
            else:
                MagRec['treatment_temp']='273'
                MagRec['treatment_ac_field']='%10.3e'%(float(step_value)*1e-3)
                meas_type = "LP-DIR-AF:LT-AF-Z"
            MagRec['treatment_dc_field']='0'
            if step_value == '0':
                meas_type = "LT-NO"
            print("step_type=", step_type)
            if step_type == '0' and AF_or_T.lower() == 'th':
                if meas_type == "":
                    meas_type = "LT-T-Z"
                else:
                    meas_type = meas_type + ":" + "LT-T-Z"
            elif step_type == '1':
                if meas_type == "":
                    meas_type = "LT-T-I"
                else:
                    meas_type = meas_type + ":" + "LT-T-I"
                MagRec['treatment_dc_field']='%1.2e'%DC_FIELD
            elif step_type == '2':
                if meas_type == "":
                    meas_type = "LT-PTRM-I"
                else:
                    meas_type = meas_type + ":" + "LT-PTRM-I"
                MagRec['treatment_dc_field']='%1.2e'%DC_FIELD
            elif step_type == '3':
                if meas_type == "" :
                    meas_type = "LT-PTRM-Z"
                else:
                    meas_type = meas_type + ":" + "LT-PTRM-Z"
            print("meas_type=", meas_type)
            MagRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
            MagRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
            MagRec['magic_method_codes'] = meas_type
            MagRec["measurement_magn_moment"] = measurement_magn_moment
            MagRec["measurement_magn_volume"] = measurement_magn_volume
            MagRec["measurement_dec"] = measurement_dec
            MagRec["measurement_inc"] = measurement_inc
            MagRec['measurement_csd'] = error
#           MagRec['measurement_positions'] = '1'
            MagRecs.append(MagRec)

            line = data.readline()
            line = line.rstrip("\n")
            items = line.split(",")
        line = data.readline()
        line = line.rstrip("\n")
        items = line.split(",")

# write out the data to MagIC data files
    pmag.magic_write(spec_file, SpecOuts, 'er_specimens')
    pmag.magic_write(samp_file, SampOuts, 'er_samples')
    pmag.magic_write(site_file, SiteOuts, 'er_sites')
#    MagOuts = pmag.measurements_methods(MagRecs, noave)
#    pmag.magic_write(meas_file, MagOuts, 'magic_measurements')
    pmag.magic_write(meas_file, MagRecs, 'magic_measurements')
    print("results put in ", meas_file)
    print("exit!")
    return True, meas_file


Instruction:
Can you generate a brief explanation for the following Python 3 code
def on_okButton(self, event):
        os.chdir(self.WD)
        options = {}
        HUJI_file = self.bSizer0.return_value()
        if not HUJI_file:
            pw.simple_warning("You must select a HUJI format file")
            return False
        options['magfile'] = HUJI_file
        magicoutfile=os.path.split(HUJI_file)[1]+".magic"
        outfile=os.path.join(self.WD, magicoutfile)
        options['meas_file'] = outfile
        user = self.bSizer1.return_value()
        options['user'] = user
        if user:
            user = '-usr ' + user
        experiment_type = self.bSizer2.return_value()
        options['codelist'] = experiment_type
        if not experiment_type:
            pw.simple_warning("You must select an experiment type")
            return False
        cooling_rate = self.cooling_rate.GetValue() or 0
        if cooling_rate:
            experiment_type = experiment_type + " " + cooling_rate
        lab_field = self.bSizer3.return_value()
        if not lab_field:
            lab_field = "0 0 0"
        lab_field_list = lab_field.split()
        options['labfield'] = lab_field_list[0]
        options['phi'] = lab_field_list[1]
        options['theta'] = lab_field_list[2]
        lab_field = '-dc ' + lab_field
        spc = self.bSizer4.return_value()
        options['specnum'] = spc or 0
        if not spc:
            spc = '-spc 0'
        else:
            spc = '-spc ' + spc
        ncn = self.bSizer5.return_value()
        options['samp_con'] = ncn
        loc_name = self.bSizer6.return_value()
        options['er_location_name'] = loc_name
        if loc_name:
            loc_name = '-loc ' + loc_name
        peak_AF = self.bSizer7.return_value()
        options['peakfield'] = peak_AF

        replicate = self.bSizer8.return_value()
        if replicate:
            options['noave'] = 0
            replicate = ''
        else:
            options['noave'] = 1
            replicate = '-A'

        old_format= self.bSizer0a.return_value()

        if old_format:
            COMMAND = "huji_magic.py -f {} -F {} {} -LP {} {} -ncn {} {} {} {} {}".format(HUJI_file, outfile, user, experiment_type, loc_name, ncn, lab_field, spc, peak_AF, replicate)
            program_ran, error_message = huji_magic.main(False, **options)
            if program_ran:
                pw.close_window(self, COMMAND, outfile)
            else:
                pw.simple_warning(error_message)

        else: # new format
            COMMAND = "huji_magic_new.py -f {} -F {} {} -LP {} {} -ncn {} {} {} {}".format(HUJI_file, outfile, user, experiment_type, loc_name, ncn, lab_field, spc, peak_AF)
            program_ran, error_message = huji_magic_new.main(False, **options)
            if program_ran:
                pw.close_window(self, COMMAND, outfile)
            else:
                pw.simple_warning(error_message)

Response: This method is called when the user selects a new entry in the HUJI file and runs huji_magic. py with the appropriate flags.


Instruction:
Can you tell what is the following Python 3 function doing
def on_okButton(self, event):
        os.chdir(self.WD)
        options_dict = {}
        wd = self.WD
        options_dict['dir_path'] = wd
        full_file = self.bSizer0.return_value()
        if not full_file:
            pw.simple_warning('You must provide a Utrecht format file')
            return False
        input_directory, Utrecht_file = os.path.split(full_file)
        options_dict['mag_file'] = Utrecht_file
        options_dict['input_dir_path'] = input_directory
        if input_directory:
            ID = "-ID " + input_directory
        else:
            ID = ''
        outfile = Utrecht_file + ".magic"
        options_dict['meas_file'] = outfile
        samp_outfile = Utrecht_file[:Utrecht_file.find('.')] + "_er_samples.txt"
        options_dict['samp_file'] = samp_outfile
        spec_outfile = Utrecht_file[:Utrecht_file.find('.')] + "_er_specimens.txt"
        options_dict['spec_file'] = spec_outfile
        site_outfile = Utrecht_file[:Utrecht_file.find('.')] + "_er_sites.txt"
        options_dict['site_file'] = site_outfile
        dc_flag,dc_params = '',''
        if self.bSizer6.return_value() != '':
            dc_params = list(map(float,self.bSizer6.return_value().split()))
            options_dict['dc_params'] = dc_params
            dc_flag = '-dc'
        spec_num = self.bSizer3.return_value()
        options_dict['specnum'] = spec_num
        if spec_num:
            spec_num = "-spc " + str(spec_num)
        else:
            spec_num = "-spc 0" # defaults to 0 if user doesn't choose number
        loc_name = self.bSizer4.return_value()
        options_dict['location_name'] = loc_name
        if loc_name:
            loc_name = "-loc " + loc_name
        ncn = self.bSizer2.return_value()
        options_dict['samp_con'] = ncn
        particulars = self.bSizer1.return_value()
        options_dict['meth_code'] = particulars
        if particulars:
            particulars = "-mcd " + particulars
        euro_date = self.bSizer7.return_value()
        if euro_date: options_dict['dmy_flag'] = True; dmy_flag='-dmy'
        else: options_dict['dmy_flag'] = False; dmy_flag=''
        try: site_lat,site_lon = self.bSizer8.return_value().split()
        except ValueError: site_lat,site_lon = '',''
        options_dict['site_lat'] = site_lat
        options_dict['site_lon'] = site_lon
        replicate = self.bSizer5.return_value()
        if replicate:
            options_dict['avg'] = False
            replicate = ''
        else:
            options_dict['avg'] = True
            replicate = '-A'

        COMMAND = "cit_magic.py -WD {} -f {} -F {} {} {} {} -ncn {} {} -Fsp {} -Fsi {} -Fsa {} {} {} {} {} -lat {} -lon {}".format(wd, Utrecht_file, outfile, particulars, spec_num, loc_name, ncn, ID, spec_outfile, site_outfile, samp_outfile, replicate, dc_flag, dc_params, dmy_flag, site_lon, site_lat)
        # to run as module:
        program_ran, error_message = utrecht_magic.main(command_line=False, **options_dict)
        if program_ran:
            pw.close_window(self, COMMAND, outfile)
        else:
            pw.simple_warning(error_message)

Response: Function that is called when the user selects a new entry in the utrecht_magic script and runs the appropriate command line options.


Instruction:
Make a summary of the following Python 3 code
def on_m_calc_orient(self,event):
        '''
        This fucntion does exactly what the 'import orientation' fuction does in MagIC.py
        after some dialog boxes the function calls orientation_magic.py
        '''
        # first see if demag_orient.txt
        self.on_m_save_file(None)
        orient_convention_dia = orient_convention(None)
        orient_convention_dia.Center()
        #orient_convention_dia.ShowModal()
        if orient_convention_dia.ShowModal() == wx.ID_OK:
            ocn_flag = orient_convention_dia.ocn_flag
            dcn_flag = orient_convention_dia.dcn_flag
            gmt_flags = orient_convention_dia.gmt_flags
            orient_convention_dia.Destroy()
        else:
            return

        or_con = orient_convention_dia.ocn
        dec_correction_con = int(orient_convention_dia.dcn)
        try:
            hours_from_gmt = float(orient_convention_dia.gmt)
        except:
            hours_from_gmt = 0
        try:
            dec_correction = float(orient_convention_dia.correct_dec)
        except:
            dec_correction = 0

        method_code_dia=method_code_dialog(None)
        method_code_dia.Center()
        if method_code_dia.ShowModal() == wx.ID_OK:
            bedding_codes_flags=method_code_dia.bedding_codes_flags
            methodcodes_flags=method_code_dia.methodcodes_flags
            method_code_dia.Destroy()
        else:
            print("-I- Canceling calculation")
            return

        method_codes = method_code_dia.methodcodes
        average_bedding = method_code_dia.average_bedding
        bed_correction = method_code_dia.bed_correction

        command_args=['orientation_magic.py']
        command_args.append("-WD %s"%self.WD)
        command_args.append("-Fsa er_samples_orient.txt")
        command_args.append("-Fsi er_sites_orient.txt ")
        command_args.append("-f %s"%"demag_orient.txt")
        command_args.append(ocn_flag)
        command_args.append(dcn_flag)
        command_args.append(gmt_flags)
        command_args.append(bedding_codes_flags)
        command_args.append(methodcodes_flags)
        commandline = " ".join(command_args)

        print("-I- executing command: %s" %commandline)
        os.chdir(self.WD)
        if os.path.exists(os.path.join(self.WD, 'er_samples.txt')) or os.path.exists(os.path.join(self.WD, 'er_sites.txt')):
            append = True
        else:
            append = False
        samp_file = "er_samples.txt"
        site_file = "er_sites.txt"
        success, error_message = ipmag.orientation_magic(or_con, dec_correction_con, dec_correction,
                                                         bed_correction, hours_from_gmt=hours_from_gmt,
                                                         method_codes=method_codes, average_bedding=average_bedding,
                                                         orient_file='demag_orient.txt', samp_file=samp_file,
                                                         site_file=site_file, input_dir_path=self.WD,
                                                         output_dir_path=self.WD, append=append, data_model=3)

        if not success:
            dlg1 = wx.MessageDialog(None,caption="Message:", message="-E- ERROR: Error in running orientation_magic.py\n{}".format(error_message) ,style=wx.OK|wx.ICON_INFORMATION)
            dlg1.ShowModal()
            dlg1.Destroy()

            print("-E- ERROR: Error in running orientation_magic.py")
            return
        else:
            dlg2 = wx.MessageDialog(None,caption="Message:", message="-I- Successfully ran orientation_magic", style=wx.OK|wx.ICON_INFORMATION)
            dlg2.ShowModal()
            dlg2.Destroy()
            self.Parent.Show()
            self.Parent.Raise()
            self.Destroy()
            self.contribution.add_magic_table('samples')
            return

Response: This function is called when the user hits the orientation_magic. txt file.


Instruction:
Can you generate the documentation for the following Python 3 function
def main():
   file=""
   if '-h' in sys.argv:
       print(main.__doc__)
       sys.exit()
   elif '-i' in sys.argv:
       file=input("Enter eigenparameters data file name: ")

   elif '-f' in sys.argv:
       ind=sys.argv.index('-f')
       file=sys.argv[ind+1]
   if file!="":
       f=open(file,'r')
       data=f.readlines()
       f.close()
   else:
       data=sys.stdin.readlines()
   ofile=""
   if '-F' in sys.argv:
      ind = sys.argv.index('-F')
      ofile= sys.argv[ind+1]
      out = open(ofile, 'w + a')
   file_outstring = ""
   for line in data:
       tau,Vdirs=[],[]
       rec=line.split()
       for k in range(0,9,3):
           tau.append(float(rec[k]))
           Vdirs.append((float(rec[k+1]),float(rec[k+2])))
       srot=pmag.doeigs_s(tau,Vdirs)
       outstring=""
       for s in srot:outstring+='%10.8f '%(s)
       if ofile=="":
           print(outstring)
       else:
           out.write(outstring+'\n')

Response: A function that takes input file and converts it to s format and prints out a string of the output file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def main():

    args = sys.argv
    if '-h' in args:
        print(main.__doc__)
        sys.exit()
    dataframe = extractor.command_line_dataframe([['f', False, 'rmag_anisotropy.txt'],
                                                  ['fb', False, 'magic_measurements.txt'],
                                                  ['fsa', False, 'er_samples.txt'],
                                                  ['fa', False, None], ['fsum', False, None],
                                                  ['fmt', False, 'svg'], ['ds', False, 'mbsf'],
                                                  ['d', False, '-1 -1'], ['sav', False, False],
                                                  ['WD', False, '.' ], ['DM', False, 3],
                                                  ['fsp', False, 'specimens.txt']])
        #args = sys.argv
    checked_args = extractor.extract_and_check_args(args, dataframe)
    ani_file, meas_file, samp_file, age_file, sum_file, fmt, depth_scale, depth, save_quietly, dir_path, data_model, spec_file = extractor.get_vars(['f', 'fb', 'fsa', 'fa', 'fsum', 'fmt', 'ds', 'd', 'sav', 'WD', 'DM', 'fsp'], checked_args)

    # format min/max depth
    try:
        dmin, dmax = depth.split()
        dmin, dmax = float(dmin), float(dmax)
    except:
        print('you must provide depth in this format: -d dmin dmax')
        print('could not parse "{}", defaulting to plotting all depths'.format('-d ' + str(depth)))
        dmin, dmax = -1, -1

    if depth_scale:
        if depth_scale not in ['age', 'mbsf', 'mcd']:
            print('-W- Unrecognized option "{}" provided for depth scale.\n    Options for depth scale are mbsf (meters below sea floor) or mcd (meters composite depth).\n    Alternatively, if you provide an age file the depth scale will be automatically set to plot by age instead.\n    Using default "mbsf"'.format(depth_scale))
            depth_scale = 'sample_core_depth'
        if age_file:
            depth_scale = 'age'
        elif 'mbsf' in depth_scale:
            depth_scale = 'sample_core_depth'
        elif 'mcd' in depth_scale:
            depth_scale = 'sample_composite_depth'

    data_model = int(float(data_model))
    # MagIC 2
    if data_model == 2:
        fig, figname = ipmag.ani_depthplot2(ani_file, meas_file, samp_file, age_file, sum_file, fmt, dmin, dmax, depth_scale, dir_path)
    # MagIC 3
    else:
        if meas_file == "magic_measurements.txt":
            meas_file = 'measurements.txt'
        if samp_file in ['er_samples.txt', 'pmag_samples.txt']:
            samp_file = "samples.txt"
        site_file = 'sites.txt'
        fig, fignames = ipmag.ani_depthplot(spec_file, samp_file, meas_file, site_file, age_file, sum_file, fmt, dmin, dmax, depth_scale, dir_path)
        figname = fignames[0]
    if save_quietly:
        if dir_path == '.':
            dir_path = os.getcwd()
        plt.savefig(figname)
        plt.clf()
        print('Saved file: {}'.format(figname))
        return False

    app = wx.App(redirect=False)
    if not fig:
        pw.simple_warning('No plot was able to be created with the data you provided.\nMake sure you have given all the required information and try again')
        return False

    dpi = fig.get_dpi()
    pixel_width = dpi * fig.get_figwidth()
    pixel_height = dpi * fig.get_figheight()
    figname = os.path.join(dir_path, figname)
    plot_frame = pmag_menu_dialogs.PlotFrame((int(pixel_width), int(pixel_height + 50)),
                                             fig, figname, standalone=True)

    app.MainLoop()

Response: This function is the main entry point for the animal depth plot. It is the main function for the animal depth plot.


Instruction:
Implement a function in Python 3 to
return object address as a string

Response:
def address(obj):
    """Return object address as a string: '<classname @ address>'"""
    return "<%s @ %s>" % (obj.__class__.__name__,
                          hex(id(obj)).upper().replace('X', 'x'))


Instruction:
Can you create a Python 3 function that
returns the size of an arbitrary type of item

Response:
def get_size(item):
    """Return size of an item of arbitrary type"""
    if isinstance(item, (list, set, tuple, dict)):
        return len(item)
    elif isinstance(item, (ndarray, MaskedArray)):
        return item.shape
    elif isinstance(item, Image):
        return item.size
    if isinstance(item, (DataFrame, Index, Series)):
        return item.shape
    else:
        return 1


Instruction:
Write a Python 3 function for
getting the attributes of an object using dir.

Response:
def get_object_attrs(obj):
    """
    Get the attributes of an object using dir.

    This filters protected attributes
    """
    attrs = [k for k in dir(obj) if not k.startswith('__')]
    if not attrs:
        attrs = dir(obj)
    return attrs


Instruction:
Write a Python 3 script to
convert a string to a datetime. timedelta value.

Response:
def str_to_timedelta(value):
    """Convert a string to a datetime.timedelta value.

    The following strings are accepted:

        - 'datetime.timedelta(1, 5, 12345)'
        - 'timedelta(1, 5, 12345)'
        - '(1, 5, 12345)'
        - '1, 5, 12345'
        - '1'

    if there are less then three parameters, the missing parameters are
    assumed to be 0. Variations in the spacing of the parameters are allowed.

    Raises:
        ValueError for strings not matching the above criterion.

    """
    m = re.match(r'^(?:(?:datetime\.)?timedelta)?'
                 r'\(?'
                 r'([^)]*)'
                 r'\)?$', value)
    if not m:
        raise ValueError('Invalid string for datetime.timedelta')
    args = [int(a.strip()) for a in m.group(1).split(',')]
    return datetime.timedelta(*args)


Instruction:
Can you tell what is the following Python 3 function doing
def get_color_name(value):
    if not is_known_type(value):
        return CUSTOM_TYPE_COLOR
    for typ, name in list(COLORS.items()):
        if isinstance(value, typ):
            return name
    else:
        np_dtype = get_numpy_dtype(value)
        if np_dtype is None or not hasattr(value, 'size'):
            return UNSUPPORTED_COLOR
        elif value.size == 1:
            return SCALAR_COLOR
        else:
            return ARRAY_COLOR

Response: Return color name depending on value type


Instruction:
Can you generate the documentation for the following Python 3 function
def sort_against(list1, list2, reverse=False):
    try:
        return [item for _, item in
                sorted(zip(list2, list1), key=lambda x: x[0], reverse=reverse)]
    except:
        return list1

Response:
Sorts list1 by list2 by permutation which takes list2
    to sorted list1.


Instruction:
How would you code a function in Python 3 to
default display for unknown objects.

Response:
def default_display(value, with_module=True):
    """Default display for unknown objects."""
    object_type = type(value)
    try:
        name = object_type.__name__
        module = object_type.__module__
        if with_module:
            return name + ' object of ' + module + ' module'
        else:
            return name
    except:
        type_str = to_text_string(object_type)
        return type_str[1:-1]


Instruction:
Can you tell what is the following Python 3 function doing
def collections_display(value, level):
    is_dict = isinstance(value, dict)
    is_set = isinstance(value, set)

    # Get elements
    if is_dict:
        elements = iteritems(value)
    else:
        elements = value

    # Truncate values
    truncate = False
    if level == 1 and len(value) > 10:
        elements = islice(elements, 10) if is_dict or is_set else value[:10]
        truncate = True
    elif level == 2 and len(value) > 5:
        elements = islice(elements, 5) if is_dict or is_set else value[:5]
        truncate = True

    # Get display of each element
    if level <= 2:
        if is_dict:
            displays = [value_to_display(k, level=level) + ':' +
                        value_to_display(v, level=level)
                        for (k, v) in list(elements)]
        else:
            displays = [value_to_display(e, level=level)
                        for e in elements]
        if truncate:
            displays.append('...')
        display = ', '.join(displays)
    else:
        display = '...'

    # Return display
    if is_dict:
        display = '{' + display + '}'
    elif isinstance(value, list):
        display = '[' + display + ']'
    elif isinstance(value, set):
        display = '{' + display + '}'
    else:
        display = '(' + display + ')'

    return display

Response: Display for collections i. e. list set tuple and dict.