Search in sources :

Example 11 with Frequency

use of org.apache.commons.math3.stat.Frequency in project GDSC-SMLM by aherbert.

the class BenchmarkFilterAnalysis method depthAnalysis.

/**
	 * Depth analysis.
	 *
	 * @param allAssignments
	 *            The assignments generated from running the filter (or null)
	 * @param filter
	 *            the filter
	 * @return the assignments
	 */
private ArrayList<FractionalAssignment[]> depthAnalysis(ArrayList<FractionalAssignment[]> allAssignments, DirectFilter filter) {
    if (!depthRecallAnalysis || simulationParameters.fixedDepth)
        return null;
    // Build a histogram of the number of spots at different depths
    final double[] depths = depthStats.getValues();
    double[] limits = Maths.limits(depths);
    //final int bins = Math.max(10, nActual / 100);
    //final int bins = Utils.getBinsSturges(depths.length);
    final int bins = Utils.getBinsSqrt(depths.length);
    double[][] h1 = Utils.calcHistogram(depths, limits[0], limits[1], bins);
    double[][] h2 = Utils.calcHistogram(depthFitStats.getValues(), limits[0], limits[1], bins);
    // manually to get the results that pass.
    if (allAssignments == null)
        allAssignments = getAssignments(filter);
    double[] depths2 = new double[results.size()];
    int count = 0;
    for (FractionalAssignment[] assignments : allAssignments) {
        if (assignments == null)
            continue;
        for (int i = 0; i < assignments.length; i++) {
            final CustomFractionalAssignment c = (CustomFractionalAssignment) assignments[i];
            depths2[count++] = c.peak.error;
        }
    }
    depths2 = Arrays.copyOf(depths2, count);
    // Build a histogram using the same limits
    double[][] h3 = Utils.calcHistogram(depths2, limits[0], limits[1], bins);
    // Convert pixel depth to nm
    for (int i = 0; i < h1[0].length; i++) h1[0][i] *= simulationParameters.a;
    limits[0] *= simulationParameters.a;
    limits[1] *= simulationParameters.a;
    // Produce a histogram of the number of spots at each depth
    String title1 = TITLE + " Depth Histogram";
    Plot2 plot1 = new Plot2(title1, "Depth (nm)", "Frequency");
    plot1.setLimits(limits[0], limits[1], 0, Maths.max(h1[1]));
    plot1.setColor(Color.black);
    plot1.addPoints(h1[0], h1[1], Plot2.BAR);
    plot1.addLabel(0, 0, "Black = Spots; Blue = Fitted; Red = Filtered");
    plot1.setColor(Color.blue);
    plot1.addPoints(h1[0], h2[1], Plot2.BAR);
    plot1.setColor(Color.red);
    plot1.addPoints(h1[0], h3[1], Plot2.BAR);
    plot1.setColor(Color.magenta);
    PlotWindow pw1 = Utils.display(title1, plot1);
    if (Utils.isNewWindow())
        wo.add(pw1);
    // Interpolate
    final double halfBinWidth = (h1[0][1] - h1[0][0]) * 0.5;
    // Remove final value of the histogram as this is at the upper limit of the range (i.e. count zero)
    h1[0] = Arrays.copyOf(h1[0], h1[0].length - 1);
    h1[1] = Arrays.copyOf(h1[1], h1[0].length);
    h2[1] = Arrays.copyOf(h2[1], h1[0].length);
    h3[1] = Arrays.copyOf(h3[1], h1[0].length);
    // TODO : Fix the smoothing since LOESS sometimes does not work.
    // Perhaps allow configuration of the number of histogram bins and the smoothing bandwidth.
    // Use minimum of 3 points for smoothing
    // Ensure we use at least x% of data
    double bandwidth = Math.max(3.0 / h1[0].length, 0.15);
    LoessInterpolator loess = new LoessInterpolator(bandwidth, 1);
    PolynomialSplineFunction spline1 = loess.interpolate(h1[0], h1[1]);
    PolynomialSplineFunction spline2 = loess.interpolate(h1[0], h2[1]);
    PolynomialSplineFunction spline3 = loess.interpolate(h1[0], h3[1]);
    // Use a second interpolator in case the LOESS fails
    LinearInterpolator lin = new LinearInterpolator();
    PolynomialSplineFunction spline1b = lin.interpolate(h1[0], h1[1]);
    PolynomialSplineFunction spline2b = lin.interpolate(h1[0], h2[1]);
    PolynomialSplineFunction spline3b = lin.interpolate(h1[0], h3[1]);
    // Increase the number of points to show a smooth curve
    double[] points = new double[bins * 5];
    limits = Maths.limits(h1[0]);
    final double interval = (limits[1] - limits[0]) / (points.length - 1);
    double[] v = new double[points.length];
    double[] v2 = new double[points.length];
    double[] v3 = new double[points.length];
    for (int i = 0; i < points.length - 1; i++) {
        points[i] = limits[0] + i * interval;
        v[i] = getSplineValue(spline1, spline1b, points[i]);
        v2[i] = getSplineValue(spline2, spline2b, points[i]);
        v3[i] = getSplineValue(spline3, spline3b, points[i]);
        points[i] += halfBinWidth;
    }
    // Final point on the limit of the spline range
    int ii = points.length - 1;
    v[ii] = getSplineValue(spline1, spline1b, limits[1]);
    v2[ii] = getSplineValue(spline2, spline2b, limits[1]);
    v3[ii] = getSplineValue(spline3, spline3b, limits[1]);
    points[ii] = limits[1] + halfBinWidth;
    // Calculate recall
    for (int i = 0; i < v.length; i++) {
        v2[i] = v2[i] / v[i];
        v3[i] = v3[i] / v[i];
    }
    final double halfSummaryDepth = summaryDepth * 0.5;
    String title2 = TITLE + " Depth Histogram (normalised)";
    Plot2 plot2 = new Plot2(title2, "Depth (nm)", "Recall");
    plot2.setLimits(limits[0] + halfBinWidth, limits[1] + halfBinWidth, 0, Maths.min(1, Maths.max(v2)));
    plot2.setColor(Color.black);
    plot2.addLabel(0, 0, "Blue = Fitted; Red = Filtered");
    plot2.setColor(Color.blue);
    plot2.addPoints(points, v2, Plot2.LINE);
    plot2.setColor(Color.red);
    plot2.addPoints(points, v3, Plot2.LINE);
    plot2.setColor(Color.magenta);
    if (-halfSummaryDepth - halfBinWidth >= limits[0]) {
        plot2.drawLine(-halfSummaryDepth, 0, -halfSummaryDepth, getSplineValue(spline3, spline3b, -halfSummaryDepth - halfBinWidth) / getSplineValue(spline1, spline1b, -halfSummaryDepth - halfBinWidth));
    }
    if (halfSummaryDepth - halfBinWidth <= limits[1]) {
        plot2.drawLine(halfSummaryDepth, 0, halfSummaryDepth, getSplineValue(spline3, spline3b, halfSummaryDepth - halfBinWidth) / getSplineValue(spline1, spline1b, halfSummaryDepth - halfBinWidth));
    }
    PlotWindow pw2 = Utils.display(title2, plot2);
    if (Utils.isNewWindow())
        wo.add(pw2);
    return allAssignments;
}
Also used : PlotWindow(ij.gui.PlotWindow) Plot2(ij.gui.Plot2) PolynomialSplineFunction(org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction) LoessInterpolator(org.apache.commons.math3.analysis.interpolation.LoessInterpolator) FractionalAssignment(gdsc.core.match.FractionalAssignment) PeakFractionalAssignment(gdsc.smlm.results.filter.PeakFractionalAssignment) LinearInterpolator(org.apache.commons.math3.analysis.interpolation.LinearInterpolator)

Example 12 with Frequency

use of org.apache.commons.math3.stat.Frequency in project knime-core by knime.

the class WorkflowCoachView method updateFrequencyColumnHeadersAndToolTips.

/**
 * Updates the names and tooltips of the frequency column headers.
 */
private void updateFrequencyColumnHeadersAndToolTips() {
    m_namesAndToolTips = NodeRecommendationManager.getInstance().getNodeTripleProviders().stream().filter(p -> p.isEnabled()).map(p -> new Pair<>(p.getName(), p.getDescription())).collect(Collectors.toList());
    if (m_namesAndToolTips == null || m_namesAndToolTips.isEmpty()) {
        updateInputNoProvider();
        return;
    }
    // reset table sorter
    IElementComparer sorter = m_viewer.getComparer();
    if (sorter != null && sorter instanceof TableColumnSorter) {
        ((TableColumnSorter) sorter).setColumn(null);
    }
    // enforce to change the viewer state to update the headers
    m_viewerState = null;
    m_lastSelection = "";
    changeViewerStateTo(ViewerState.RECOMMENDATIONS);
    // get current selection from the workbench and update the recommendation list
    IEditorPart activeEditor = getViewSite().getPage().getActiveEditor();
    if (activeEditor == null) {
        // if no workflow is opened
        updateInput(NO_WORKFLOW_OPENED_MESSAGE);
    } else {
        IWorkbenchPartSite site = activeEditor.getSite();
        if (site != null) {
            ISelectionProvider selectionProvider = site.getSelectionProvider();
            if (selectionProvider != null) {
                ISelection selection = selectionProvider.getSelection();
                if (selection != null && selection instanceof IStructuredSelection) {
                    updateInput(selection);
                    return;
                }
            }
        }
        updateInput(StructuredSelection.EMPTY);
    }
}
Also used : Arrays(java.util.Arrays) IUpdateListener(org.knime.workbench.workflowcoach.NodeRecommendationManager.IUpdateListener) TableViewer(org.eclipse.jface.viewers.TableViewer) IWorkbenchPartSite(org.eclipse.ui.IWorkbenchPartSite) NodeContainerUI(org.knime.core.ui.node.workflow.NodeContainerUI) DND(org.eclipse.swt.dnd.DND) TableColumn(org.eclipse.swt.widgets.TableColumn) IToolBarManager(org.eclipse.jface.action.IToolBarManager) LocalSelectionTransfer(org.eclipse.jface.util.LocalSelectionTransfer) NodeContainer(org.knime.core.node.workflow.NodeContainer) IStatus(org.eclipse.core.runtime.IStatus) ISelectionListener(org.eclipse.ui.ISelectionListener) Composite(org.eclipse.swt.widgets.Composite) ISelectionProvider(org.eclipse.jface.viewers.ISelectionProvider) Cursor(org.eclipse.swt.graphics.Cursor) IEditorPart(org.eclipse.ui.IEditorPart) NodeProvider(org.knime.workbench.core.nodeprovider.NodeProvider) KNIMEJob(org.knime.core.util.KNIMEJob) CommunityTripleProvider(org.knime.workbench.workflowcoach.data.CommunityTripleProvider) PlatformUI(org.eclipse.ui.PlatformUI) Set(java.util.Set) Status(org.eclipse.core.runtime.Status) Display(org.eclipse.swt.widgets.Display) ScopedPreferenceStore(org.eclipse.ui.preferences.ScopedPreferenceStore) NodeModel(org.knime.core.node.NodeModel) Collectors(java.util.stream.Collectors) WorkflowCoachPreferenceInitializer(org.knime.workbench.workflowcoach.prefs.WorkflowCoachPreferenceInitializer) RepositoryManager(org.knime.workbench.repository.RepositoryManager) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Transfer(org.eclipse.swt.dnd.Transfer) IElementComparer(org.eclipse.jface.viewers.IElementComparer) MouseEvent(org.eclipse.swt.events.MouseEvent) List(java.util.List) MouseListener(org.eclipse.swt.events.MouseListener) InstanceScope(org.eclipse.core.runtime.preferences.InstanceScope) Wrapper(org.knime.core.ui.wrapper.Wrapper) SWT(org.eclipse.swt.SWT) Optional(java.util.Optional) ISelection(org.eclipse.jface.viewers.ISelection) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) MouseAdapter(org.eclipse.swt.events.MouseAdapter) NativeNodeContainer(org.knime.core.node.workflow.NativeNodeContainer) ViewPart(org.eclipse.ui.part.ViewPart) WorkflowEditor(org.knime.workbench.editor2.WorkflowEditor) LocalDateTime(java.time.LocalDateTime) Table(org.eclipse.swt.widgets.Table) AtomicReference(java.util.concurrent.atomic.AtomicReference) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) ArrayList(java.util.ArrayList) Pair(org.knime.core.util.Pair) HashSet(java.util.HashSet) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) UpdateJob(org.knime.workbench.workflowcoach.prefs.UpdateJob) UpdatableNodeTripleProvider(org.knime.workbench.workflowcoach.data.UpdatableNodeTripleProvider) NodeLogger(org.knime.core.node.NodeLogger) GridData(org.eclipse.swt.layout.GridData) NodeRecommendationManager(org.knime.workbench.workflowcoach.NodeRecommendationManager) HeadlessPreferencesConstants(org.knime.workbench.core.preferences.HeadlessPreferencesConstants) NodeFactory(org.knime.core.node.NodeFactory) CombinatoricsUtils(org.apache.commons.math3.util.CombinatoricsUtils) Iterator(java.util.Iterator) Job(org.eclipse.core.runtime.jobs.Job) KNIMECorePlugin(org.knime.workbench.core.KNIMECorePlugin) NodeTemplate(org.knime.workbench.repository.model.NodeTemplate) ChronoUnit(java.time.temporal.ChronoUnit) UpdateListener(org.knime.workbench.workflowcoach.prefs.UpdateJob.UpdateListener) NodeContainerEditPart(org.knime.workbench.editor2.editparts.NodeContainerEditPart) NodeRecommendation(org.knime.workbench.workflowcoach.NodeRecommendationManager.NodeRecommendation) Comparator(java.util.Comparator) Collections(java.util.Collections) FrameworkUtil(org.osgi.framework.FrameworkUtil) IWorkbenchPartSite(org.eclipse.ui.IWorkbenchPartSite) ISelectionProvider(org.eclipse.jface.viewers.ISelectionProvider) IElementComparer(org.eclipse.jface.viewers.IElementComparer) ISelection(org.eclipse.jface.viewers.ISelection) IEditorPart(org.eclipse.ui.IEditorPart) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection)

Example 13 with Frequency

use of org.apache.commons.math3.stat.Frequency in project narchy by automenta.

the class BagTest method samplingPriDist.

public static Tensor samplingPriDist(@NotNull Bag<PLink<String>, PLink<String>> b, int batches, int batchSize, int bins) {
    assert (bins > 1);
    Set<String> hit = new TreeSet();
    Frequency hits = new Frequency();
    ArrayTensor f = new ArrayTensor(bins);
    assertFalse(b.isEmpty());
    Random rng = new XoRoShiRo128PlusRandom(1);
    for (int i = 0; i < batches; i++) {
        b.sample(rng, batchSize, x -> {
            f.data[Util.bin(b.pri(x), bins)]++;
            String s = x.get();
            hits.addValue(s);
            hit.add(s);
        });
    }
    int total = batches * batchSize;
    assertEquals(total, Util.sum(f.data), 0.001f);
    if (hits.getUniqueCount() != b.size()) {
        System.out.println(hits.getUniqueCount() + " != " + b.size());
        Set<String> items = b.stream().map(PLink::get).collect(Collectors.toSet());
        items.removeAll(hit);
        System.out.println("not hit: " + items);
        System.out.println(hits);
        fail("all elements must have been sampled at least once");
    }
    return f.scale(1f / total);
}
Also used : XoRoShiRo128PlusRandom(jcog.math.random.XoRoShiRo128PlusRandom) XorShift128PlusRandom(jcog.math.random.XorShift128PlusRandom) XoRoShiRo128PlusRandom(jcog.math.random.XoRoShiRo128PlusRandom) Frequency(org.apache.commons.math3.stat.Frequency) ArrayTensor(jcog.math.tensor.ArrayTensor)

Example 14 with Frequency

use of org.apache.commons.math3.stat.Frequency in project ma-modules-public by infiniteautomation.

the class PointValueFftCalculator method streamData.

/* (non-Javadoc)
	 * @see com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeStream#streamData(java.io.Writer)
	 */
@Override
public void streamData(JsonGenerator jgen) {
    this.setupDates();
    DateTime startTime = new DateTime(from);
    DateTime endTime = new DateTime(to);
    FftGenerator generator = this.calculate(startTime, endTime);
    double[] fftData = generator.getValues();
    double sampleRateHz = 1000d / generator.getAverageSamplePeriodMs();
    double dataLength = (double) fftData.length;
    // Output The Real Steady State Mangitude
    try {
        jgen.writeStartObject();
        // Amplitude
        jgen.writeNumberField("value", fftData[0]);
        double frequency = 0;
        jgen.writeNumberField("frequency", frequency);
        jgen.writeEndObject();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    double realComponent, imaginaryComponent, frequency;
    if (fftData.length % 2 == 0) {
        for (int i = 2; i < fftData.length / 2; i++) {
            try {
                realComponent = fftData[i * 2];
                imaginaryComponent = fftData[2 * i + 1];
                Complex c = new Complex(realComponent, imaginaryComponent);
                jgen.writeStartObject();
                // Amplitude
                jgen.writeNumberField("value", c.abs());
                if (this.returnFrequency)
                    frequency = (double) i * sampleRateHz / dataLength;
                else
                    frequency = 1d / ((double) i * sampleRateHz / dataLength);
                jgen.writeNumberField("frequency", frequency);
                jgen.writeEndObject();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        for (int i = 2; i < (fftData.length - 1) / 2; i++) {
            try {
                realComponent = fftData[i * 2];
                imaginaryComponent = fftData[2 * i + 1];
                Complex c = new Complex(realComponent, imaginaryComponent);
                jgen.writeStartObject();
                // Amplitude
                jgen.writeNumberField("value", c.abs());
                if (this.returnFrequency)
                    frequency = (double) i * sampleRateHz / dataLength;
                else
                    frequency = 1d / ((double) i * sampleRateHz / dataLength);
                jgen.writeNumberField("frequency", frequency);
                jgen.writeEndObject();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // Write the last value out as it isn't in order in the array
        try {
            realComponent = fftData[fftData.length / 2];
            imaginaryComponent = fftData[1];
            Complex c = new Complex(realComponent, imaginaryComponent);
            jgen.writeStartObject();
            // Amplitude
            jgen.writeNumberField("value", c.abs());
            if (this.returnFrequency)
                frequency = (double) (((fftData.length - 1) / 2) - 1) * sampleRateHz / dataLength;
            else
                frequency = 1d / ((double) (((fftData.length - 1) / 2) - 1) * sampleRateHz / dataLength);
            jgen.writeNumberField("frequency", frequency);
            jgen.writeEndObject();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Also used : FftGenerator(com.serotonin.m2m2.view.quantize2.FftGenerator) IOException(java.io.IOException) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) Complex(org.apache.commons.math3.complex.Complex)

Aggregations

Plot2 (ij.gui.Plot2)7 XorShift128PlusRandom (jcog.math.random.XorShift128PlusRandom)4 ClusterPoint (gdsc.core.clustering.ClusterPoint)3 WeightedObservedPoint (org.apache.commons.math3.fitting.WeightedObservedPoint)3 Frequency (org.apache.commons.math3.stat.Frequency)3 Test (org.junit.jupiter.api.Test)3 StoredDataStatistics (gdsc.core.utils.StoredDataStatistics)2 PlotWindow (ij.gui.PlotWindow)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 LinearInterpolator (org.apache.commons.math3.analysis.interpolation.LinearInterpolator)2 LoessInterpolator (org.apache.commons.math3.analysis.interpolation.LoessInterpolator)2 PolynomialSplineFunction (org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction)2 DescriptiveStatistics (org.apache.commons.math3.stat.descriptive.DescriptiveStatistics)2 Joiner (com.google.common.base.Joiner)1 FftGenerator (com.serotonin.m2m2.view.quantize2.FftGenerator)1 Cluster (gdsc.core.clustering.Cluster)1 ClusteringEngine (gdsc.core.clustering.ClusteringEngine)1