/**
   * @param wfsClient
   * @throws NoSuchAuthorityCodeException
   * @throws FactoryException
   * @throws IOException
   * @throws ParseException
   * @throws NoSuchElementException
   * @throws IndexOutOfBoundsException
   */
  public void loadFeatures(GeoFabrikWFSClient wfsClient)
      throws NoSuchAuthorityCodeException, FactoryException, IOException, IndexOutOfBoundsException,
          NoSuchElementException, ParseException {
    String typeNames[] = wfsClient.getTypeNames();

    content.layers().clear();
    selectGeomType.clear();
    selectGeomType.add(GeomType.POINT);

    ProgressMonitor monitor = new ProgressMonitor(Main.map.mapView, "Loading features", "", 0, 100);

    for (int idx = 1; idx < typeNames.length; ++idx) {
      String typeName = typeNames[idx];
      Set<FeatureId> selectedFeatures = new HashSet<>();

      monitor.setProgress(100 / typeNames.length * idx);
      FeatureCollection<SimpleFeatureType, SimpleFeature> features =
          wfsClient.getFeatures(typeName, monitor);
      setGeometry(selectGeomType, typeName);

      Main.info("Osm Inspector Features size: " + features.size());

      OSMIFeatureTracker tracker = arrFeatures.get(idx - layerOffset);
      tracker.mergeFeatures(features);

      FeatureIterator<SimpleFeature> it = tracker.getFeatures().features();

      while (it.hasNext()) {
        BugInfo theInfo = new BugInfo(it.next(), osmiBugInfo.size());
        if (!osmiBugInfo.keySet().contains(theInfo)) {
          osmiBugInfo.put(theInfo, theInfo.bugId);
        }
      }

      Style style = createDefaultStyle(idx, selectedFeatures);
      content.addLayer(new FeatureLayer(tracker.getFeatures(), style));
    }

    osmiIndex.append(osmiBugInfo);

    monitor.setProgress(100);
    monitor.close();
    bIsChanged = true;
    // dialog.updateDialog(this);
    dialog.refreshModel();
    // dialog.updateNextPrevAction(this);

    this.updateView();
  }
  public static void extract() {
    String ftlPath =
        (String)
            JOptionPane.showInputDialog(
                null,
                "What is your FTL install directory:\n",
                "Extracting Resources",
                JOptionPane.PLAIN_MESSAGE,
                null,
                null,
                "C:/Program Files (x86)/Steam/SteamApps/common/FTL Faster Than Light");

    datLib dat = new datLib(ftlPath + "/resources/resource.dat");
    int[] ids = dat.List();

    ProgressMonitor progressMonitor =
        new ProgressMonitor(null, "Extracting Resources", "", 0, ids.length);

    for (int i = 0; i < ids.length; i++) {
      String path = dat.Filename(ids[i]);
      File file = new File("resources/" + path);
      if (!file.exists()) {
        dat.Extract(ids[i], "resources/" + path);
      }
      progressMonitor.setProgress(i);
    }

    progressMonitor.close();
  }
Beispiel #3
0
  public static void randomToolActions(int numStrokes, boolean brushOnly) {
    Composition comp = ImageComponents.getActiveComp().get();
    Random random = new Random();

    if (comp != null) {
      int canvasWidth = comp.getCanvasWidth();
      int canvasHeight = comp.getCanvasHeight();

      ProgressMonitor progressMonitor = Utils.createPercentageProgressMonitor("1001 Tool Actions");

      // So far we are on the EDT
      Runnable notEDTThreadTask =
          () -> {
            assert !SwingUtilities.isEventDispatchThread();
            for (int i = 0; i < numStrokes; i++) {
              int progressPercentage = (int) ((float) i * 100 / numStrokes);
              progressMonitor.setProgress(progressPercentage);
              progressMonitor.setNote(progressPercentage + "%");

              Runnable edtRunnable =
                  () -> testToolAction(comp, random, canvasWidth, canvasHeight, brushOnly);

              try {
                SwingUtilities.invokeAndWait(edtRunnable);
              } catch (InterruptedException | InvocationTargetException e) {
                e.printStackTrace();
              }

              comp.repaint();
            }
            progressMonitor.close();
          };
      new Thread(notEDTThreadTask).start();
    }
  }
  public void showProgress() {
    for (int i = 0; i <= 100; i++) {
      try {
        Thread.sleep(100);
        pb.setValue(i);

        if (pb.getValue() == 50) // se il progresso è alla metà creiamo un progress monitor
        {
          pm = new ProgressMonitor(this, "...sto computando...", null, 0, 5);

          for (int x = 0; x <= 5; x++) {
            Thread.sleep(1000);
            pm.setProgress(x);
          }

          // crea un progress monitor per la lettura di dati da un file
          File a_f = new File(getClass().getResource("SomeText.txt").getPath());
          try (FileInputStream fileIn = new FileInputStream(a_f);
              ProgressMonitorInputStream pmis =
                  new ProgressMonitorInputStream(this, "Reading SomeText.txt", fileIn);
              Scanner in = new Scanner(pmis)) {
            while (in.hasNextLine()) {
              String line = in.nextLine();
              Thread.sleep(10);
            }
          } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, ioe.toString());
          }
        }
      } catch (InterruptedException ie) {
        JOptionPane.showMessageDialog(this, ie.toString());
      }
    }
  }
Beispiel #5
0
  /**
   * Test a synapse on the specified spiking protocol or a series of spiking protocols derived from
   * initial and final protocols by interpolation over one or two dimensions. The synapse is tested
   * over all specified parameter configurations.
   *
   * @param synapse The SynapseCollection containing the synapse to test (the first synapse is
   *     used). The first configuration (at index 0) in the collection will be replaced with each
   *     configuration specified by the <em>configurations</em> argument.
   * @param configurationLabels An array containing the labels for each parameter configuration to
   *     test on. These are used to label the data sets in the returned TestResults.
   * @param configurations An array containing the parameter configurations to test on.
   * @param timeResolution The time resolution to use in the simulation, see {@link
   *     com.ojcoleman.bain.NeuralNetwork}
   * @param period The period of the spike pattern in seconds.
   * @param repetitions The number of times to apply the spike pattern.
   * @param patterns Array containing spike patterns, in the form [initial, dim 1, dim 2][pre,
   *     post][spike number] = spike time. The [spike number] array contains the times (s) of each
   *     spike, relative to the beginning of the pattern. See {@link
   *     com.ojcoleman.bain.neuron.spiking.FixedProtocolNeuronCollection}.
   * @param refSpikeIndexes Array specifying indexes of the two spikes to use as timing variation
   *     references for each variation dimension, in the form [dim 1, dim 2][reference spike,
   *     relative spike] = spike index.
   * @param refSpikePreOrPost Array specifying whether the timing variation reference spikes
   *     specified by refSpikeIndexes belong to the pre- or post-synaptic neurons, in the form [dim
   *     1, dim 2][base spike, relative spike] = Constants.PRE or Constants.POST.
   * @param logSpikesAndStateVariables Whether to record pre- and post-synaptic spikes and any state
   *     variables exposed by the synapse model in the test results.
   * @param progressMonitor If not null, this will be updated to display the progress of the test.
   * @return For a single spike protocol, a TestResults object with type {@link TYPE#STDP}
   *     consisting of series labelled "Time" and "Efficacy" and if logSpikesAndStateVariables ==
   *     true then also "Pre-synaptic spikes", "Post-synaptic spikes" and any state variables
   *     exposed by the synapse model. For a protocol varied over one dimension, a TestResults
   *     object with type {@link TYPE#STDP_1D} consisting of series labelled "Time delta" and
   *     "Efficacy". For a protocol varied over two dimensions, a TestResults object with type
   *     {@link TYPE#STDP_2D} consisting of series labelled "Time delta 1", "Time delta 2" and
   *     "Efficacy".
   */
  public static TestResults[] testPattern(
      SynapseCollection<? extends ComponentConfiguration> synapse,
      String[] configurationLabels,
      ComponentConfiguration[] configurations,
      int timeResolution,
      double period,
      int repetitions,
      double[][][] patterns,
      int[][] refSpikeIndexes,
      int[][] refSpikePreOrPost,
      boolean logSpikesAndStateVariables,
      ProgressMonitor progressMonitor)
      throws IllegalArgumentException {
    int configCount = configurationLabels.length;
    TestResults[] results = new TestResults[configCount];

    if (synapse.getConfigurationCount() == 0) {
      synapse.addConfiguration(configurations[0]);
    }

    ProgressMonitor progressMonitorSub = null;
    if (progressMonitor != null) {
      progressMonitor.setMinimum(0);
      progressMonitor.setMaximum(configCount);
      progressMonitor.setMillisToDecideToPopup(0);
      progressMonitorSub = new ProgressMonitor(null, null, "Performing test...", 0, 0);
    }

    for (int c = 0; c < configCount; c++) {
      if (progressMonitor != null) {
        progressMonitor.setProgress(c);
        progressMonitor.setNote("Testing " + configurationLabels[c]);
      }
      synapse.setConfiguration(0, configurations[c]);
      results[c] =
          testPattern(
              synapse,
              timeResolution,
              period,
              repetitions,
              patterns,
              refSpikeIndexes,
              refSpikePreOrPost,
              logSpikesAndStateVariables,
              progressMonitorSub);
      results[c].setProperty("label", configurationLabels[c]);
    }

    if (progressMonitorSub != null) {
      progressMonitorSub.close();
    }

    return results;
  }
  /**
   * Z-Sorts and draws all 3D objects which have been added to the collection of objects to draw via
   * the add3DObject() method. The progress of the drawing is instrumented with the specified
   * progress monitor.
   *
   * @param g the Graphics on which to draw the 3D objects.
   * @param progressMonitor the progress monitor which will be updated with the progress of drawing
   *     the objects. If the progress dialog is cancelled, then the drawing stops.
   */
  public void drawObjectsOnThis(Graphics g, ProgressMonitor progressMonitor) {
    synchronized (objects) {
      progressMonitor.setProgress(1);
      progressMonitor.setNote("Calculating rotations...");
      for (Iterator<Object3D> it = objects.iterator(); it.hasNext(); ) {
        Object3D currentObject = it.next();
        // check for cancellation
        if (progressMonitor.isCanceled()) return;

        // very rarely, when the "objects" list is being modified by
        // another thread, "currentObject" here is null
        if (currentObject != null) currentObject.calculateRotation(window);
        else
          // if we are here, then that strange thread error has
          // occurred, and it causes an exception to be thrown when
          // Collections.sort() is called later, so just
          // return now to prevent further errors
          return;
      }

      progressMonitor.setNote("Z-Sorting...");
      // Z-Sort
      Collections.sort(objects, depthComparator);

      // Draw all objects
      Graphics2D g2D = (Graphics2D) g;
      double numberOfObjects = (double) objects.size();
      double currentIndex = 1;

      progressMonitor.setNote("Drawing objects...");
      int maxProgress = progressMonitor.getMaximum();
      for (Iterator<Object3D> it = objects.iterator(); it.hasNext(); ) {
        // check for cancellation
        if (progressMonitor.isCanceled()) return;
        else {
          progressMonitor.setProgress((int) (currentIndex++ / numberOfObjects * maxProgress));
          it.next().drawOnThis(g2D);
        }
      }
    }
  }
Beispiel #7
0
 public void propertyChange(PropertyChangeEvent evt) {
   if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
     int progress = (Integer) evt.getNewValue();
     progressMonitor.setProgress(progress);
     String message = String.format("%d%% complete.\n", (progress == 1) ? 0 : progress);
     progressMonitor.setNote(message);
     if (progressMonitor.isCanceled()) {
       task.cancel(true);
     } else if (progress == 100) {
       mainWin.initGUI();
     }
   }
 }
Beispiel #8
0
 void showProgressMonitor() {
   progressMonitor =
       new ProgressMonitor(DBSettings.this, "Building internal data ...", "", 0, 100);
   progressMonitor.setProgress(0);
   if (dbURL.matches("(?i:.*oracle.*)")) {
     task = QueryManager.instance().initFinder(QueryManager.SearchEngine.ORACLE, this);
   }
   if (dbURL.matches("(?i:.*mysql.*)")) {
     task = QueryManager.instance().initFinder(QueryManager.SearchEngine.MYSQL, this);
   }
   if (task != null) {
     task.addPropertyChangeListener(this);
     task.execute();
   }
 }
Beispiel #9
0
  public void compile(ZNode zNode) {
    // TODO do something with errors
    apiFactory
        .getCompiler()
        .compile(
            zNode,
            new ProgressListener() {

              @Override
              public void update(int progress) {
                mon.setProgress(progress);
              }
            });
    mon.setProgress(100);
  }
Beispiel #10
0
  /** override the readLine method, to tell us were at a new line */
  public String readLine() throws IOException {
    _counter++;
    final float prog = (_counter / _length * 100);
    _progress = (int) prog;

    if (_pm != null) {
      _pm.setProgress(_progress);
      _pm.setNote("" + _progress + "% complete");

      if (_progress >= 99) {
        _pm.close();
        _pm = null;
      }
    }

    return super.readLine();
  }
Beispiel #11
0
 public Progress() {
   setLayout(new GridLayout(2, 1));
   add(pb);
   pm.setProgress(0);
   pm.setMillisToPopup(1000);
   sb.setValue(0);
   sb.setPaintTicks(true);
   sb.setMajorTickSpacing(20);
   sb.setMinorTickSpacing(5);
   sb.setBorder(new TitledBorder("Slide Me"));
   pb.setModel(sb.getModel()); // Share model
   add(sb);
   sb.addChangeListener(
       new ChangeListener() {
         public void stateChanged(ChangeEvent e) {
           pm.setProgress(sb.getValue());
         }
       });
 }
  public void run() {
    WindowBlocker blocker = new WindowBlocker(NearInfinity.getInstance());
    blocker.setBlocked(true);
    List<ResourceEntry> creFiles = ResourceFactory.getInstance().getResources("CRE");
    creFiles.addAll(ResourceFactory.getInstance().getResources("CHR"));
    ProgressMonitor progress =
        new ProgressMonitor(
            NearInfinity.getInstance(), "Checking inventories...", null, 0, creFiles.size());
    table =
        new SortableTable(
            new String[] {"File", "Name", "Item", "Message"},
            new Class[] {Object.class, Object.class, Object.class, Object.class},
            new int[] {100, 100, 200, 200});
    for (int i = 0; i < creFiles.size(); i++) {
      ResourceEntry entry = creFiles.get(i);
      try {
        if (typeButtons[0].isSelected())
          checkCreatureInventory((CreResource) ResourceFactory.getResource(entry));
        if (typeButtons[1].isSelected())
          checkItemAttribute((CreResource) ResourceFactory.getResource(entry));
      } catch (Exception e) {
        e.printStackTrace();
      }
      progress.setProgress(i + 1);
      if (progress.isCanceled()) {
        JOptionPane.showMessageDialog(
            NearInfinity.getInstance(),
            "Operation canceled",
            "Info",
            JOptionPane.INFORMATION_MESSAGE);
        blocker.setBlocked(false);
        return;
      }
    }

    if (table.getRowCount() == 0)
      JOptionPane.showMessageDialog(
          NearInfinity.getInstance(), "No hits found", "Info", JOptionPane.INFORMATION_MESSAGE);
    else {
      resultFrame = new ChildFrame("Result of CRE inventory check", true);
      resultFrame.setIconImage(Icons.getIcon("Refresh16.gif").getImage());
      bopen = new JButton("Open", Icons.getIcon("Open16.gif"));
      bopennew = new JButton("Open in new window", Icons.getIcon("Open16.gif"));
      JLabel count = new JLabel(table.getRowCount() + " hit(s) found", JLabel.CENTER);
      count.setFont(count.getFont().deriveFont((float) count.getFont().getSize() + 2.0f));
      bopen.setMnemonic('o');
      bopennew.setMnemonic('n');
      resultFrame.getRootPane().setDefaultButton(bopennew);
      JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
      panel.add(bopen);
      panel.add(bopennew);
      JScrollPane scrollTable = new JScrollPane(table);
      scrollTable.getViewport().setBackground(table.getBackground());
      JPanel pane = (JPanel) resultFrame.getContentPane();
      pane.setLayout(new BorderLayout(0, 3));
      pane.add(count, BorderLayout.NORTH);
      pane.add(scrollTable, BorderLayout.CENTER);
      pane.add(panel, BorderLayout.SOUTH);
      bopen.setEnabled(false);
      bopennew.setEnabled(false);
      table.setFont(BrowserMenuBar.getInstance().getScriptFont());
      table.getSelectionModel().addListSelectionListener(this);
      table.addMouseListener(
          new MouseAdapter() {
            public void mouseReleased(MouseEvent event) {
              if (event.getClickCount() == 2) {
                int row = table.getSelectedRow();
                if (row != -1) {
                  ResourceEntry resourceEntry = (ResourceEntry) table.getValueAt(row, 0);
                  Resource resource = ResourceFactory.getResource(resourceEntry);
                  new ViewFrame(resultFrame, resource);
                  ((AbstractStruct) resource)
                      .getViewer()
                      .selectEntry(((Item) table.getValueAt(row, 2)).getName());
                }
              }
            }
          });
      bopen.addActionListener(this);
      bopennew.addActionListener(this);
      pane.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
      resultFrame.pack();
      Center.center(resultFrame, NearInfinity.getInstance().getBounds());
      resultFrame.setVisible(true);
    }
    blocker.setBlocked(false);
    //    for (int i = 0; i < table.getRowCount(); i++) {
    //      CreInvError error = (CreInvError)table.getTableItemAt(i);
    //      System.out.println(error.resourceEntry + " (" + error.resourceEntry.getSearchString() +
    // ") -> " + error.itemRef.getAttribute("Item"));
    //    }
  }
 public void run() {
   WindowBlocker blocker = new WindowBlocker(NearInfinity.getInstance());
   blocker.setBlocked(true);
   List<ResourceEntry> files = new ArrayList<ResourceEntry>();
   for (final String fileType : FILETYPES)
     files.addAll(ResourceFactory.getInstance().getResources(fileType));
   ProgressMonitor progress =
       new ProgressMonitor(NearInfinity.getInstance(), "Searching...", null, 0, files.size());
   table =
       new SortableTable(
           new String[] {"String", "StrRef"},
           new Class[] {Object.class, Integer.class},
           new int[] {450, 20});
   StringResource.getStringRef(0);
   strUsed = new boolean[StringResource.getMaxIndex() + 1];
   for (int i = 0; i < files.size(); i++) {
     ResourceEntry entry = files.get(i);
     Resource resource = ResourceFactory.getResource(entry);
     if (resource instanceof DlgResource) checkDialog((DlgResource) resource);
     else if (resource instanceof BcsResource) checkScript((BcsResource) resource);
     else if (resource instanceof PlainTextResource) checkTextfile((PlainTextResource) resource);
     else if (resource != null) checkStruct((AbstractStruct) resource);
     progress.setProgress(i + 1);
     if (progress.isCanceled()) {
       JOptionPane.showMessageDialog(
           NearInfinity.getInstance(),
           "Operation canceled",
           "Info",
           JOptionPane.INFORMATION_MESSAGE);
       blocker.setBlocked(false);
       return;
     }
   }
   for (int i = 0; i < strUsed.length; i++)
     if (!strUsed[i]) table.addTableItem(new UnusedStringTableItem(new Integer(i)));
   if (table.getRowCount() == 0)
     JOptionPane.showMessageDialog(
         NearInfinity.getInstance(),
         "No unused strings found",
         "Info",
         JOptionPane.INFORMATION_MESSAGE);
   else {
     table.tableComplete(1);
     textArea = new JTextArea(10, 40);
     textArea.setEditable(false);
     textArea.setWrapStyleWord(true);
     textArea.setLineWrap(true);
     JScrollPane scrollText = new JScrollPane(textArea);
     resultFrame = new ChildFrame("Result", true);
     save = new JMenuItem("Save");
     save.addActionListener(this);
     JMenu fileMenu = new JMenu("File");
     fileMenu.add(save);
     JMenuBar menuBar = new JMenuBar();
     menuBar.add(fileMenu);
     resultFrame.setJMenuBar(menuBar);
     resultFrame.setIconImage(Icons.getIcon("Find16.gif").getImage());
     JLabel count = new JLabel(table.getRowCount() + " unused string(s) found", JLabel.CENTER);
     count.setFont(count.getFont().deriveFont((float) count.getFont().getSize() + 2.0f));
     JScrollPane scrollTable = new JScrollPane(table);
     scrollTable.getViewport().setBackground(table.getBackground());
     JPanel pane = (JPanel) resultFrame.getContentPane();
     pane.setLayout(new BorderLayout(0, 3));
     pane.add(count, BorderLayout.NORTH);
     pane.add(scrollTable, BorderLayout.CENTER);
     JPanel bottomPanel = new JPanel(new BorderLayout());
     JPanel searchPanel = SearchMaster.createAsPanel(this, resultFrame);
     bottomPanel.add(scrollText, BorderLayout.CENTER);
     bottomPanel.add(searchPanel, BorderLayout.EAST);
     pane.add(bottomPanel, BorderLayout.SOUTH);
     table.setFont(BrowserMenuBar.getInstance().getScriptFont());
     pane.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
     table.getSelectionModel().addListSelectionListener(this);
     resultFrame.pack();
     Center.center(resultFrame, NearInfinity.getInstance().getBounds());
     resultFrame.setVisible(true);
   }
   blocker.setBlocked(false);
 }
  public void readPlugins(String base, JFrame parent) throws Exception {
    String baseURL = base;
    ProgressMonitor monitor;

    if (base == null) {
      baseURL = TiledConfiguration.root().get("pluginsDir", "plugins");
    }

    File dir = new File(baseURL);
    if (!dir.exists() || !dir.canRead()) {
      // FIXME: removed for webstart
      // throw new Exception(
      //        "Could not open directory for reading plugins: " +
      //        baseURL);
      return;
    }

    int total = 0;
    File[] files = dir.listFiles();
    for (File file : files) {
      String aPath = file.getAbsolutePath();
      if (aPath.endsWith(".jar")) {
        total++;
      }
    }

    // Start the progress monitor
    monitor = new ProgressMonitor(parent, "Loading plugins", "", 0, total - 1);
    monitor.setProgress(0);
    monitor.setMillisToPopup(0);
    monitor.setMillisToDecideToPopup(0);

    for (int i = 0; i < files.length; i++) {
      String aPath = files[i].getAbsolutePath();
      String aName = aPath.substring(aPath.lastIndexOf(File.separatorChar) + 1);

      // Skip non-jar files.
      if (!aPath.endsWith(".jar")) {
        continue;
      }

      try {
        monitor.setNote("Reading " + aName + "...");
        JarFile jf = new JarFile(files[i]);

        monitor.setProgress(i);

        if (jf.getManifest() == null) continue;

        String readerClassName = jf.getManifest().getMainAttributes().getValue("Reader-Class");
        String writerClassName = jf.getManifest().getMainAttributes().getValue("Writer-Class");

        Class<Object> readerClass = null;
        Class<Object> writerClass = null;

        // Verify that the jar has the necessary files to be a
        // plugin
        if (readerClassName == null && writerClassName == null) {
          continue;
        }

        monitor.setNote("Loading " + aName + "...");
        addURL(new File(aPath).toURI().toURL());

        if (readerClassName != null) {
          JarEntry reader = jf.getJarEntry(readerClassName.replace('.', '/') + ".class");

          if (reader != null) {
            readerClass = loadFromJar(jf, reader, readerClassName);
          } else
            System.err.println(
                "Manifest entry " + readerClassName + " does not match any class in the jar.");
        }
        if (writerClassName != null) {
          JarEntry writer = jf.getJarEntry(writerClassName.replace('.', '/') + ".class");

          if (writer != null) {
            writerClass = loadFromJar(jf, writer, writerClassName);
          } else
            System.err.println(
                "Manifest entry " + writerClassName + " does not match any class in the jar.");
        }

        boolean bPlugin = false;
        if (isReader(readerClass)) {
          bPlugin = true;
        }
        if (isWriter(writerClass)) {
          bPlugin = true;
        }

        if (bPlugin) {
          if (readerClass != null) _add(readerClass);
          if (writerClass != null) _add(writerClass);
          // System.out.println(
          //        "Added " + files[i].getCanonicalPath());
        }

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #15
0
  /**
   * Test a synapse on the specified spiking protocol or a series of spiking protocols derived from
   * initial and final protocols by interpolation over one or two dimensions.
   *
   * @param synapse The SynapseCollection containing the synapse to test (the first synapse is
   *     used).
   * @param timeResolution The time resolution to use in the simulation, see {@link
   *     com.ojcoleman.bain.NeuralNetwork}
   * @param period The period of the spike pattern in seconds.
   * @param repetitions The number of times to apply the spike pattern.
   * @param patterns Array containing spike patterns, in the form [initial, dim 1, dim 2][pre,
   *     post][spike number] = spike time. The [spike number] array contains the times (s) of each
   *     spike, relative to the beginning of the pattern. See {@link
   *     com.ojcoleman.bain.neuron.spiking.FixedProtocolNeuronCollection}.
   * @param refSpikeIndexes Array specifying indexes of the two spikes to use as timing variation
   *     references for each variation dimension, in the form [dim 1, dim 2][reference spike,
   *     relative spike] = spike index.
   * @param refSpikePreOrPost Array specifying whether the timing variation reference spikes
   *     specified by refSpikeIndexes belong to the pre- or post-synaptic neurons, in the form [dim
   *     1, dim 2][base spike, relative spike] = Constants.PRE or Constants.POST.
   * @param logSpikesAndStateVariables Whether to record pre- and post-synaptic spikes and any state
   *     variables exposed by the synapse model in the test results.
   * @param progressMonitor If not null, this will be updated with the current progress.
   * @return For a single spike protocol, a TestResults object with type {@link TYPE#STDP}
   *     consisting of series labelled "Time" and "Efficacy" and if logSpikesAndStateVariables ==
   *     true then also "Pre-synaptic spikes", "Post-synaptic spikes" and any state variables
   *     exposed by the synapse model. For a protocol varied over one dimension, a TestResults
   *     object with type {@link TYPE#STDP_1D} consisting of series labelled "Time delta" and
   *     "Efficacy". For a protocol varied over two dimensions, a TestResults object with type
   *     {@link TYPE#STDP_2D} consisting of series labelled "Time delta 1", "Time delta 2" and
   *     "Efficacy".
   */
  public static TestResults testPattern(
      SynapseCollection<? extends ComponentConfiguration> synapse,
      int timeResolution,
      double period,
      int repetitions,
      double[][][] patterns,
      int[][] refSpikeIndexes,
      int[][] refSpikePreOrPost,
      boolean logSpikesAndStateVariables,
      ProgressMonitor progressMonitor)
      throws IllegalArgumentException {
    int variationDimsCount =
        patterns.length - 1; // Number of dimensions over which spike timing patterns vary.
    if (variationDimsCount > 2) {
      throw new IllegalArgumentException(
          "The number of variation dimensions may not exceed 2 (patterns.length must be <= 3)");
    }

    if (progressMonitor != null) {
      progressMonitor.setMinimum(0);
    }

    TestResults results = new TestResults();

    FixedProtocolNeuronCollection neurons = new FixedProtocolNeuronCollection(2);
    FixedProtocolNeuronConfiguration preConfig =
        new FixedProtocolNeuronConfiguration(period, patterns[0][0]);
    neurons.addConfiguration(preConfig);
    neurons.setComponentConfiguration(0, 0);
    FixedProtocolNeuronConfiguration postConfig =
        new FixedProtocolNeuronConfiguration(period, patterns[0][1]);
    neurons.addConfiguration(postConfig);
    neurons.setComponentConfiguration(1, 1);

    synapse.setPreNeuron(0, 0);
    synapse.setPostNeuron(0, 1);

    NeuralNetwork sim = new NeuralNetwork(timeResolution, neurons, synapse);

    int simSteps = (int) Math.round(period * repetitions * timeResolution);

    int displayTimeResolution = Math.min(1000, timeResolution);

    results.setProperty("simulation time resolution", timeResolution);
    results.setProperty("display time resolution", displayTimeResolution);

    // long startTime = System.currentTimeMillis();

    // If we're just testing a single spike pattern. // Handle separately as logging is quite
    // different from testing spike
    // patterns with gradually altered spike times.
    if (variationDimsCount == 0) {
      results = singleTest(sim, simSteps, logSpikesAndStateVariables, 0);
    } else { // We're testing spike patterns with gradually altered spike times over one or two
      // dimensions.

      int[] spikeCounts = {patterns[0][0].length, patterns[0][1].length};
      // The initial and final time deltas (s), given base and relative spike times in initial and
      // final spike patterns,
      // for each variation dimension.
      double[] timeDeltaInitial = new double[2], timeDeltaFinal = new double[2];
      // The time delta range(s) for each variation dimension.
      double[] timeDeltaRange = new double[2];
      int[] positionsCount = new int[2];
      int[][] variationDimForSpike =
          new int[2][Math.max(spikeCounts[0], spikeCounts[1])]; // [pre, post][spike index]

      // Set-up parameters for testing spike patterns with gradually altered spike times over one or
      // two dimensions.
      for (int d = 0; d < variationDimsCount; d++) {
        double baseRefSpikeTimeInitial =
            patterns[0][refSpikePreOrPost[d][0]][refSpikeIndexes[d][0]];
        double relativeRefSpikeTimeInitial =
            patterns[0][refSpikePreOrPost[d][1]][refSpikeIndexes[d][1]];
        double baseRefSpikeTimeFinal =
            patterns[d + 1][refSpikePreOrPost[d][0]][refSpikeIndexes[d][0]];
        double relativeRefSpikeTimeFinal =
            patterns[d + 1][refSpikePreOrPost[d][1]][refSpikeIndexes[d][1]];

        timeDeltaInitial[d] = relativeRefSpikeTimeInitial - baseRefSpikeTimeInitial;
        timeDeltaFinal[d] = relativeRefSpikeTimeFinal - baseRefSpikeTimeFinal;
        timeDeltaRange[d] = Math.abs(timeDeltaInitial[d] - timeDeltaFinal[d]);

        // From the initial and final spiking protocols we generate intermediate spiking protocols
        // by interpolation. //
        // Each position in between the initial and final protocol adjusts the time differential
        // between the base and
        // reference spikes by (1/timeResolution) seconds.
        positionsCount[d] = (int) Math.round(timeDeltaRange[d] * displayTimeResolution) + 1;

        // Determine which dimension, if any, a spikes timing varies over (and ensure that a spikes
        // timing only varies
        // over at most one dimension).
        // If the spikes time in variation dimension d is different to the initial spike time.
        for (int p = 0; p < 2; p++) {
          for (int si = 0; si < spikeCounts[p]; si++) {
            // If it also differs in another dimension.
            if (patterns[0][p][si] != patterns[d + 1][p][si]) {
              if (variationDimForSpike[p][si] != 0) {
                throw new IllegalArgumentException(
                    "A spikes timing may vary at most over one variation dimension. "
                        + (p == 0 ? "Pre" : "Post")
                        + "-synaptic spike "
                        + (si + 1)
                        + " varies over two.");
              }
              variationDimForSpike[p][si] = d + 1;
            }
          }
        }
      }

      double[][] currentSpikeTimings =
          new double[2][]; // Current pre and post spiking patterns [pre, post][spike index]
      for (int p = 0; p < 2; p++) {
        currentSpikeTimings[p] = new double[spikeCounts[p]];
        System.arraycopy(patterns[0][p], 0, currentSpikeTimings[p], 0, spikeCounts[p]);
      }

      // If we're testing spike patterns with gradually altered spike times over one dimension.
      if (variationDimsCount == 1) {
        // Arrays to record results.
        double[] time =
            new double[positionsCount[0]]; // The time delta in seconds [time delta index]
        // The change in synapse efficacy after all repetitions for each pattern [time delta index]
        double[] efficacyLog = new double[positionsCount[0]];

        if (progressMonitor != null) {
          progressMonitor.setMaximum(positionsCount[0]);
        }

        for (int timeDeltaIndex = 0; timeDeltaIndex < positionsCount[0]; timeDeltaIndex++) {
          if (progressMonitor != null) {
            progressMonitor.setProgress(timeDeltaIndex);
          }

          double position =
              (double) timeDeltaIndex
                  / (positionsCount[0] - 1); // Position in variation dimension 1

          // Generate pre and post spike timing patterns for this position.
          for (int p = 0; p < 2; p++) {
            for (int si = 0; si < spikeCounts[p]; si++) { // If this spikes timing varies.
              int variationDim = variationDimForSpike[p][si];
              if (variationDim != 0) {
                currentSpikeTimings[p][si] =
                    position * patterns[0][p][si] + (1 - position) * patterns[variationDim][p][si];
              }
            }
          }

          preConfig.spikeTimings = currentSpikeTimings[0];
          postConfig.spikeTimings = currentSpikeTimings[1];
          preConfig.fireChangeEvent();
          postConfig.fireChangeEvent();

          sim.reset();
          sim.run(simSteps);

          time[timeDeltaIndex] =
              position * timeDeltaInitial[0] + (1 - position) * timeDeltaFinal[0];
          efficacyLog[timeDeltaIndex] = synapse.getEfficacy(0);
        }

        results.setProperty("type", TYPE.STDP_1D);
        results.addResult("Efficacy", efficacyLog);
        results.addResult("Time delta", time);

        // We're testing spike patterns with gradually altered spike times over two dimensions.
      } else {
        // The change in synapse efficacy after all repetitions for each pattern
        // [time delta for var dim 1, time delta for var dim 2, synapse efficacy][result index]
        double[][] efficacyLog = new double[3][(positionsCount[0]) * (positionsCount[1])];

        if (progressMonitor != null) {
          progressMonitor.setMaximum(efficacyLog[0].length);
        }

        double[] position = new double[2]; // Position in variation dimensions 1 and 2
        for (int timeDeltaIndex1 = 0, resultIndex = 0;
            timeDeltaIndex1 < positionsCount[0];
            timeDeltaIndex1++) {
          position[0] = (double) timeDeltaIndex1 / (positionsCount[0] - 1);

          for (int timeDeltaIndex2 = 0;
              timeDeltaIndex2 < positionsCount[1];
              timeDeltaIndex2++, resultIndex++) {
            if (progressMonitor != null) {
              progressMonitor.setProgress(resultIndex);
            }

            position[1] = (double) timeDeltaIndex2 / (positionsCount[1] - 1);

            // Generate pre and post spike timing patterns for this position.
            for (int p = 0; p < 2; p++) {
              for (int si = 0; si < spikeCounts[p]; si++) { // If this spikes timing varies.
                int variationDim = variationDimForSpike[p][si];
                if (variationDim != 0) {
                  currentSpikeTimings[p][si] =
                      (1 - position[variationDim - 1]) * patterns[0][p][si]
                          + position[variationDim - 1] * patterns[variationDim][p][si];
                }
              }
            }

            preConfig.spikeTimings = currentSpikeTimings[0];
            postConfig.spikeTimings = currentSpikeTimings[1];
            preConfig.fireChangeEvent();
            postConfig.fireChangeEvent();

            sim.reset();
            sim.run(simSteps);

            efficacyLog[0][resultIndex] =
                (1 - position[0]) * timeDeltaInitial[0] + position[0] * timeDeltaFinal[0];
            efficacyLog[1][resultIndex] =
                (1 - position[1]) * timeDeltaInitial[1] + position[1] * timeDeltaFinal[1];
            efficacyLog[2][resultIndex] = synapse.getEfficacy(0);
          }
        }

        results.setProperty("type", TYPE.STDP_2D);
        results.addResult("Time delta 1", "Time delta 2", "Efficacy", efficacyLog);
      }
    }

    return results;
  }
Beispiel #16
0
  public void run() {
    WindowBlocker blocker = new WindowBlocker(NearInfinity.getInstance());
    blocker.setBlocked(true);
    BmpResource searchMap = null;
    List<ResourceEntry> files = ResourceFactory.getInstance().getResources("ARE");
    ProgressMonitor progress =
        new ProgressMonitor(NearInfinity.getInstance(), "Checking areas...", null, 0, files.size());
    errorTable =
        new SortableTable(
            new String[] {"Area", "Object", "Message"},
            new Class[] {Object.class, Object.class, Object.class},
            new int[] {100, 200, 200});
    long startTime = System.currentTimeMillis();

    exclude.clear();
    exclude.add("BIRD");
    exclude.add("EAGLE");
    exclude.add("SEAGULL");
    exclude.add("VULTURE");
    exclude.add("DOOM_GUARD");
    exclude.add("DOOM_GUARD_LARGER");
    exclude.add("BAT_INSIDE");
    exclude.add("BAT_OUTSIDE");

    //		exclude.add("CAT");
    //		exclude.add("MOOSE");
    //		exclude.add("RABBIT");
    exclude.add("SQUIRREL");
    exclude.add("RAT");
    //		exclude.add("STATIC_PEASANT_MAN_MATTE");
    //		exclude.add("STATIC_PEASANT_WOMAN_MATTE");

    for (int i = 0; i < files.size(); i++) {
      try {
        ResourceEntry entry = files.get(i);
        Resource area = ResourceFactory.getResource(entry);

        if (typeButtons[3].isSelected()) checkAreasConnectivity(entry, area);

        if (typeButtons[1].isSelected()) {
          String[] name = ((AreResource) area).getAttribute("WED resource").toString().split("\\.");
          ResourceEntry searchEntry =
              ResourceFactory.getInstance().getResourceEntry(name[0] + "SR.BMP");

          if (searchEntry == null) {
            searchMap = null;
            errorTable.addTableItem(
                new AreaTableLine(
                    entry,
                    ((AreResource) area).getAttribute("WED resource"),
                    "Area don't have search map"));
          } else {
            searchMap = (BmpResource) ResourceFactory.getResource(searchEntry);
          }
        }

        List<StructEntry> list = ((AreResource) area).getList();
        for (int j = 0; j < list.size(); j++) {
          if (list.get(j) instanceof Actor) {
            Actor actor = (Actor) list.get(j);
            StructEntry time = actor.getAttribute("Expiry time");
            if (typeButtons[0].isSelected() && ((DecNumber) time).getValue() != -1)
              errorTable.addTableItem(
                  new AreaTableLine(
                      entry, actor, "Actor expiry time is: " + ((DecNumber) time).getValue()));

            if (searchMap != null) checkActorPosition(entry, actor, searchMap);
          }

          if (typeButtons[2].isSelected() && list.get(j) instanceof Container) {
            ResourceRef keyRes = (ResourceRef) ((AbstractStruct) list.get(j)).getAttribute("Key");
            if (!keyRes.getResourceName().equalsIgnoreCase("None.ITM")
                && !ResourceFactory.getInstance().resourceExists(keyRes.getResourceName())) {
              errorTable.addTableItem(
                  new AreaTableLine(
                      entry,
                      list.get(j),
                      "Non existent key item for container: " + keyRes.getResourceName()));
            }
            checkContainedItem(entry, list.get(j));
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      progress.setProgress(i + 1);
      if (progress.isCanceled()) {
        JOptionPane.showMessageDialog(
            NearInfinity.getInstance(),
            "Operation canceled",
            "Info",
            JOptionPane.INFORMATION_MESSAGE);
        blocker.setBlocked(false);
        return;
      }
    }
    System.out.println("Check took " + (System.currentTimeMillis() - startTime) + "ms");
    if (errorTable.getRowCount() == 0)
      JOptionPane.showMessageDialog(
          NearInfinity.getInstance(), "No errors found", "Info", JOptionPane.INFORMATION_MESSAGE);
    else {
      errorTable.tableComplete();
      resultFrame = new ChildFrame("Result", true);
      resultFrame.setIconImage(Icons.getIcon("Find16.gif").getImage());
      bopen = new JButton("Open", Icons.getIcon("Open16.gif"));
      bopennew = new JButton("Open in new window", Icons.getIcon("Open16.gif"));
      bopen.setMnemonic('o');
      bopennew.setMnemonic('n');
      resultFrame.getRootPane().setDefaultButton(bopennew);
      JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
      panel.add(bopen);
      panel.add(bopennew);
      JLabel count = new JLabel(errorTable.getRowCount() + " errors found", JLabel.CENTER);
      count.setFont(count.getFont().deriveFont((float) count.getFont().getSize() + 2.0f));
      JScrollPane scrollTable = new JScrollPane(errorTable);
      scrollTable.getViewport().setBackground(errorTable.getBackground());
      JPanel pane = (JPanel) resultFrame.getContentPane();
      pane.setLayout(new BorderLayout(0, 3));
      pane.add(count, BorderLayout.NORTH);
      pane.add(scrollTable, BorderLayout.CENTER);
      pane.add(panel, BorderLayout.SOUTH);
      bopen.setEnabled(false);
      bopennew.setEnabled(false);
      errorTable.setFont(BrowserMenuBar.getInstance().getScriptFont());
      errorTable.addMouseListener(
          new MouseAdapter() {
            public void mouseReleased(MouseEvent event) {
              if (event.getClickCount() == 2) {
                int row = errorTable.getSelectedRow();
                if (row != -1) {
                  ResourceEntry resourceEntry = (ResourceEntry) errorTable.getValueAt(row, 0);
                  Resource resource = ResourceFactory.getResource(resourceEntry);
                  new ViewFrame(resultFrame, resource);
                  ((AbstractStruct) resource)
                      .getViewer()
                      .selectEntry((String) errorTable.getValueAt(row, 1));
                }
              }
            }
          });
      bopen.addActionListener(this);
      bopennew.addActionListener(this);
      pane.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
      errorTable.getSelectionModel().addListSelectionListener(this);
      resultFrame.pack();
      Center.center(resultFrame, NearInfinity.getInstance().getBounds());
      resultFrame.setVisible(true);
    }
    blocker.setBlocked(false);
  }