예제 #1
0
def main():
    #argparser = argparse.ArgumentParser(description="Compares two csv files and produces a result file.")
    #argparser.add_argument("files", metavar="F", type=open, nargs="+", help="files to process")
    #args = argparser.parse_args()
    #print(args)

    print(sys.argv)

    if len(sys.argv) < 5:
        print("Usage: main.py <first_file> <second_file> <output_file> <second_file_format> [-e]")
        print("       Use a -e parameter to print errors during parsing.")
        sys.exit(1)

    second_file_parser = get_parser(sys.argv[4])

    print("The '{0}' parser has been selected for the second file by format '{1}'".
          format(second_file_parser.type, sys.argv[4]))

    print_errors = len(sys.argv) > 5 and sys.argv[5] == '-e'

    first_list = common.parse_file(sys.argv[1], rigla.Parser(), print_errors)
    second_list = common.parse_file(sys.argv[2], second_file_parser, print_errors)

    list_of_compared_results = comparer.Comparer(first_list, second_list).compare()

    common.write_file(sys.argv[3], list_of_compared_results.not_in_first_list,
                      list_of_compared_results.not_in_second_list, list_of_compared_results.in_both_lists)
예제 #2
0
def main():
    if len(sys.argv) == 1:
        # no arguments, open file picker
        import tkinter.filedialog, tkinter
        tkinter.Tk().withdraw()
        fname = Path(tkinter.filedialog.askopenfilename())
    else:
        # pathname as argument
        fname = Path(sys.argv[1])
    if fname.is_dir():
        # if directory, find last result and plot that
        fname = find_last_result(fname)
    print(f"Plotting {fname}")
    options, data = parse_file(fname)

    # only use abs value since that is whats plotted by Zheng2013 too
    data = np.abs(data)

    interpolate = False
    scale_factor = 5
    if interpolate:
        y = np.arange(0, data.shape[0])
        x = np.arange(0, data.shape[1])
        interpolator = interp2d(x, y, data)
        x_dense = np.linspace(0, x[-1], int(len(x)*scale_factor))
        y_dense = np.linspace(0, y[-1], int(len(y)*scale_factor))
        data = interpolator(x_dense, y_dense)
        
    plot_scattering_coefficient(data, options, fname)
예제 #3
0
 def load_target(self):
     '''
     Allows user to select an FRD file to set the target.
     '''
     parsers = {'frd': self.__parse_frd, 'txt': self.__parse_frd}
     _, data = parse_file('FRD (*.frd *.txt)', 'Load Target', parsers)
     self.__new_target = data
     self.targetSet.setChecked(data is not None)
예제 #4
0
 def __load_signal(self):
     '''
     Loads a new signal (replacing any current data if required).
     '''
     parsers = {'qvibe': self.__parse_qvibe}
     name, data = parse_file('Signal (*.qvibe)', 'Load Signal', parsers)
     if name is not None:
         self.statusbar.showMessage(f"Loaded {name}")
         for d in data:
             self.__measurement_store.append(name, *d)
예제 #5
0
def process_file(filename_in, filename_out):
    sequences = parse_file(filename_in)
    result = []
    for name, sequence, structure in sequences:
        result.append(name)
        result.append(sequence)
        if '[' in structure:
            new_structure = representation_to_structure(
                structure, structure_to_representation(structure))
            result.append(new_structure)
        else:
            result.append(structure)
    with open(filename_out, 'w') as f_out:
        f_out.write('\n'.join(result))
예제 #6
0
파일: __main__.py 프로젝트: cdv04/SSWD
def main():
    """Main."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--save",
                        help="Save intermediate operations",
                        action="store_true")
    parser.add_argument("--emp",
                        help="Enable empirical law",
                        action="store_true")
    parser.add_argument("--normal",
                        help="Enable normal law",
                        action="store_true")
    parser.add_argument("--triang",
                        help="Enable triangular law",
                        action="store_true")
    parser.add_argument("--iproc", help="iproc value", default=1, type=int)
    parser.add_argument("--hazen",
                        help="Hazen parameter a",
                        default=.5,
                        type=restricted_float)
    parser.add_argument("-f", "--file", help="filename")
    parser.add_argument("--pcat", help="pcat values or colonne", type=str)
    parser.add_argument("--bootstrap",
                        help="bootstrap n times",
                        default=1000,
                        type=int)
    parser.add_argument("--nbvar", help="enable nbvar", action="store_true")
    parser.add_argument("--adjustq",
                        help="adjust q for triangular law",
                        action="store_true")
    parser.add_argument("--isp",
                        help="poderation type",
                        default=1,
                        type=isp_type)
    parser.add_argument("--lbl_liste", help="weight of each taxonomic group")
    args = parser.parse_args()
    # columns_name = get_columns(args.file)
    columns_name = ["Species", "PhylumSup", "ED"]
    espece, taxo, concentration, test = parse_file(args.file, columns_name)
    charger_parametres(args.file, args.iproc, espece, taxo, concentration,
                       test, args.pcat, args.pcat is None, args.pcat
                       is not None, args.emp, args.normal, args.triang,
                       args.bootstrap, args.hazen, args.nbvar, args.save,
                       args.lbl_liste, args.triang and args.adjustq, args.isp,
                       columns_name)
    return 0
예제 #7
0
def solve(filename):
  """
  solve prints out solutions to each of the fields described in <filename>.
  """
  tstart = time.time()
  count, total = 0, 0
  for puzzle in common.parse_file(filename):
    pstart = time.time()
    max, field = variant_reduction(s0.join_vertically(s0.join_horizontally(s0.identify(puzzle))))

    count += 1
    total += common.cost(field)
    print "cost:", common.cost(field), "time:", time.strftime("%H:%M:%S", time.gmtime(time.time() - pstart))
    print common.format(field)

  print "%s field(s). Total cost is $%s" % (count, total)
  print time.strftime("Total time is %H:%M:%S", time.gmtime(time.time() - tstart))
예제 #8
0
 def update_taxo(self, event, onload=False):
     """Update taxo list."""
     try:
         columns_name = [
             self.choice_specie.GetString(
                 self.choice_specie.GetSelection()),
             self.choice_taxo.GetString(self.choice_taxo.GetSelection()),
             self.choice_ed.GetString(self.choice_ed.GetSelection())
         ]
     except (AssertionError, wx._core.wxAssertionError) as e:
         if onload:
             e = e
         else:
             wx.MessageBox(str(e), 'Warning', wx.OK | wx.ICON_WARNING)
         return
     species, taxon, concentration, test = parse_file(
         self.filename, columns_name,
         self.choice_sheet_name.GetStringSelection())
     self.taxo_list = sorted(list(set(taxon.split('!')[1].split(';'))))[1:]
     if 'nan' in [x.lower() for x in self.taxo_list]:
         dlg = wx.MessageBox(
             "There is an incorrect name for a taxonomic/genus group."
             "\nContinue? (it will be named 'NaN')", "Warning", wx.YES_NO
             | wx.ICON_WARNING)
         if dlg == wx.YES:
             n = len(self.taxo_list) - self.grid_taxo.GetNumberRows()
             if n > 0:
                 self.grid_taxo.InsertRows(numRows=n)
             elif n < 0:
                 self.grid_taxo.DeleteRows(numRows=abs(n))
             for x in range(0, len(self.taxo_list)):
                 self.grid_taxo.SetRowLabelValue(x, self.taxo_list[x])
         else:
             self.grid_taxo.Hide()
             self.radiobox_taxo.SetSelection(0)
             wx.MessageBox('Canceled', 'Warning', wx.OK | wx.ICON_WARNING)
             return False
     return True

def get_max_x_parallel_result(data: np.array):
    """
    Get max value from left and right side of array.
    """
    return max(np.max(np.abs(data[:, 0:15])), np.max(np.abs(data[:, 45:])))


for ix, x in enumerate(x_values):
    for iy, y in enumerate(y_values):
        subprocess.call(args=(str(PROGRAM_PATH), str(OPTIONS_PATH),
                              f"--target.x={x}", f"--target.y={y}"))
        _, result = read_last_result(PROGRAM_PATH.parent)
        _, result = parse_file(
            Path(
                f"/home/darius/git/doublebeam/grid/result{ix * num_x + iy}.txt"
            ))
        # first axis of result contains num spacings (41), second axis contains orientation
        max_result_x_parallel[ix, iy] = get_max_x_parallel_result(result)
        max_result_y_parallel[ix, iy] = get_max_y_parallel_result(result)

np.save("result_grid_x", max_result_x_parallel)
np.save("result_grid_y", max_result_y_parallel)

im = plt.imshow(np.abs(max_result_x_parallel).T,
                extent=(target_x0, target_x1, target_y0, target_y1),
                origin="lower")
plt.xlabel("x axis (m)")
plt.ylabel("y axis (m)")
cb = plt.colorbar(im, format="%.2e")
cb.set_label(r"$|\sigma|$")
예제 #10
0
    This function should return number of inversions of input list

    >>> sort_and_count([1, 2, 3, 4, 5, 6])
    (0, [1, 2, 3, 4, 5, 6])
    >>> sort_and_count([1, 3, 5, 2, 4, 6])
    (3, [1, 2, 3, 4, 5, 6])
    >>> sort_and_count([6, 5, 4, 3, 2, 1])
    (15, [1, 2, 3, 4, 5, 6])
    """
    left, right = lst[:len(lst) / 2], lst[len(lst) / 2:]
    # Trivial case
    if len(lst) <= 2:
        if not right or left < right:
            return 0, lst
        else:
            return 1, right + left
    # Recursive case
    inv_left, sorted_left = sort_and_count(left)
    inv_right, sorted_right = sort_and_count(right)
    split_inversions, sorted_list = merge_and_count(sorted_left, sorted_right)
    return inv_left + inv_right + split_inversions, sorted_list

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-f", type="string", dest="file", default="IntegerArray.txt")
    (options, args) = parser.parse_args()

    inversions, _ = sort_and_count(list(parse_file(options.file)))
    print inversions
예제 #11
0
def brute_force(data):
    """
    This function should return number of inversions of input stream

    >>> brute_force([1,2,3,4,5,6])
    0
    >>> brute_force([1,3,5,2,4,6])
    3
    >>> brute_force([6,5,4,3,2,1])
    15
    """
    global PROGRESS_BAR
    data = list(data)
    cnt = 0
    for i,a in enumerate(data):
        for j,b in enumerate(data):
            if i<j and a>b: cnt+=1
        PROGRESS_BAR.update({"PROGRESS": i, "FOUND": cnt})
    return cnt

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-f", type="string", dest="file", default="IntegerArray.txt")
    (options, args) = parser.parse_args()

    setup_signals(PROGRESS_BAR)

    print brute_force(parse_file(options.file))
예제 #12
0
 def run(self, event, onload=False):
     """Run the program."""
     try:
         columns_name = [
             self.choice_specie.GetString(
                 self.choice_specie.GetSelection()),
             self.choice_taxo.GetString(self.choice_taxo.GetSelection()),
             self.choice_ed.GetString(self.choice_ed.GetSelection())
         ]
     except (AssertionError, wx._core.wxAssertionError) as e:
         if onload:
             e = e
         else:
             wx.MessageBox(str(e), 'Warning', wx.OK | wx.ICON_WARNING)
         return
     output = join(dirname(self.filename), self.txt_output_name.GetValue())
     if exists(output):
         dlg = wx.MessageBox(
             "The file \'" + basename(output) + "\' already exist in\'" +
             dirname(output) + "\'."
             "\nContinue?"
             "\nPress \"Yes\" to override the file."
             "\nPress \"No\" to abort.", "Warning",
             wx.YES_NO | wx.ICON_WARNING)
         if dlg == wx.YES:
             pass
         else:
             wx.MessageBox('Canceled', 'Warning', wx.OK | wx.ICON_WARNING)
             return
     try:
         f = open(output, 'w')
     except IOError as e:
         wx.MessageBox(str(e), 'Warning', wx.OK | wx.ICON_WARNING)
         return
     finally:
         f.close()
     species, taxon, concentration, test = parse_file(
         self.filename, columns_name,
         self.choice_sheet_name.GetStringSelection())
     pcat = list()
     if self.radiobox_taxo.GetSelection() == 0:
         pcat = None
     else:
         for x in range(0, self.grid_taxo.GetNumberRows()):
             try:
                 if self.grid_taxo.GetCellValue(x, 0) is None:
                     pcat.append(.0)
                 else:
                     pcat.append(float(self.grid_taxo.GetCellValue(x, 0)))
             except ValueError as e:
                 wx.MessageBox(str(e), 'Warning', wx.OK | wx.ICON_WARNING)
                 return
     normal = self.checkbox_norm.IsChecked()
     emp = self.checkbox_emp.IsChecked()
     triang = self.checkbox_triang.IsChecked()
     bootstrap = int(self.txtc_bootstrap.GetLineText(0))
     hazen = float(self.txtc_hazen.GetLineText(0))
     nbvar = self.checkbox_nbvar.IsChecked()
     save = self.checkbox_save.IsChecked()
     lbl_list = self.taxo_list
     adjustq = self.radio_quant.GetValue()
     isp = self.radiobox_weight.GetSelection()
     seed = (self.radiobox_seed.GetSelection() == 0)
     p1 = Process(target=charger_parametres,
                  args=(
                      output,
                      1,
                      species,
                      taxon,
                      concentration,
                      test,
                      pcat,
                      pcat is None,
                      pcat is not None,
                      emp,
                      normal,
                      triang,
                      bootstrap,
                      hazen,
                      nbvar,
                      save,
                      lbl_list,
                      triang and adjustq,
                      isp,
                      columns_name,
                      seed,
                  ))
     dlg = wx.ProgressDialog("Calculation in progress",
                             "Processing",
                             parent=self,
                             style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL)
     dot = 1
     p1.start()
     while p1.is_alive() and not dlg.WasCancelled():
         if dot >= 4:
             dot = 1
         dlg.Pulse("Processing" + "." * dot)
         dot += 1
         wx.SafeYield()
         wx.Sleep(1)
     if dlg.WasCancelled() and p1.is_alive():
         dlg.Pulse("Canceling...")
         wx.SafeYield()
         wx.Sleep(3)
         p1.terminate()
     else:
         dlg.Pulse('Finished.')
         wx.SafeYield()
         wx.Sleep(2)
     dlg.Destroy()