Search in sources :

Example 6 with XYChartBuilder

use of org.knowm.xchart.XYChartBuilder in project PureEdgeSim by CharafeddineMechalikh.

the class ChartsGenerator method initChart.

private XYChart initChart(String x_series, String y_series, String y_series_label, String title) {
    XYChart chart = new XYChartBuilder().height(400).width(600).theme(ChartTheme.Matlab).xAxisTitle(x_series).yAxisTitle(y_series_label).build();
    chart.setTitle(y_series + " (" + title + ")");
    chart.getStyler().setLegendVisible(true);
    return chart;
}
Also used : XYChart(org.knowm.xchart.XYChart) XYChartBuilder(org.knowm.xchart.XYChartBuilder)

Example 7 with XYChartBuilder

use of org.knowm.xchart.XYChartBuilder in project unify-framework by tcdng.

the class AreaChartGeneratorUnit method translate.

@Override
protected Chart<?, ?> translate(AreaChart lineChart) throws UnifyException {
    // Create Chart
    XYChart xyChart = new XYChartBuilder().width(lineChart.getWidth()).height(lineChart.getHeight()).build();
    xyChart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Area);
    // Customize Chart
    xyChart.getStyler().setLegendVisible(lineChart.isShowLegend());
    xyChart.getStyler().setPlotBorderVisible(false);
    xyChart.getStyler().setPlotGridLinesVisible(false);
    xyChart.getStyler().setPlotBackgroundColor(Color.WHITE);
    xyChart.getStyler().setChartBackgroundColor(Color.WHITE);
    xyChart.getStyler().setDecimalPattern(valueFormatMapping.get(lineChart.getValueFormat()));
    xyChart.getStyler().setHasAnnotations(true);
    xyChart.getStyler().setXAxisTicksVisible(lineChart.isShowXAxisTicks());
    xyChart.getStyler().setYAxisTicksVisible(lineChart.isShowYAxisTicks());
    // Series
    List<Color> customColors = Collections.emptyList();
    boolean useCustomColors = lineChart.getColorPalette().isCustom();
    if (useCustomColors) {
        customColors = new ArrayList<Color>();
    }
    for (XYSeries series : lineChart.getSeriesList()) {
        if (useCustomColors) {
            customColors.add(series.getColor());
        }
        xyChart.addSeries(series.getName(), series.getXValueList(), series.getYValueList());
    }
    if (useCustomColors) {
        xyChart.getStyler().setSeriesColors(DataUtils.toArray(Color.class, customColors));
    } else if (!lineChart.getColorPalette().isDefault()) {
        List<Color> palette = lineChart.getColorPalette().pallete();
        xyChart.getStyler().setSeriesColors(DataUtils.toArray(Color.class, palette));
    }
    return xyChart;
}
Also used : XYSeries(com.tcdng.unify.core.chart.XYSeries) Color(java.awt.Color) XYChart(org.knowm.xchart.XYChart) ArrayList(java.util.ArrayList) List(java.util.List) XYChartBuilder(org.knowm.xchart.XYChartBuilder)

Example 8 with XYChartBuilder

use of org.knowm.xchart.XYChartBuilder in project openhab-core by openhab.

the class DefaultChartProvider method createChart.

@Override
public BufferedImage createChart(@Nullable String serviceId, @Nullable String theme, ZonedDateTime startTime, ZonedDateTime endTime, int height, int width, @Nullable String items, @Nullable String groups, @Nullable Integer dpiValue, @Nullable String yAxisDecimalPattern, @Nullable Boolean legend) throws ItemNotFoundException, IllegalArgumentException {
    logger.debug("Rendering chart: service: '{}', theme: '{}', startTime: '{}', endTime: '{}', width: '{}', height: '{}', items: '{}', groups: '{}', dpi: '{}', yAxisDecimalPattern: '{}', legend: '{}'", serviceId, theme, startTime, endTime, width, height, items, groups, dpiValue, yAxisDecimalPattern, legend);
    // If a persistence service is specified, find the provider, or use the default provider
    PersistenceService service = (serviceId == null) ? persistenceServiceRegistry.getDefault() : persistenceServiceRegistry.get(serviceId);
    // Did we find a service?
    QueryablePersistenceService persistenceService = (service instanceof QueryablePersistenceService) ? (QueryablePersistenceService) service : (QueryablePersistenceService) // 
    persistenceServiceRegistry.getAll().stream().filter(// 
    it -> it instanceof QueryablePersistenceService).findFirst().orElseThrow(() -> new IllegalArgumentException("No Persistence service found."));
    int seriesCounter = 0;
    // get theme
    ChartTheme chartTheme = theme == null ? CHART_THEME_DEFAULT : CHART_THEMES.getOrDefault(theme, CHART_THEME_DEFAULT);
    // get DPI
    int dpi = dpiValue != null && dpiValue > 0 ? dpiValue : DPI_DEFAULT;
    // Create Chart
    XYChart chart = new XYChartBuilder().width(width).height(height).build();
    // Define the time axis - the defaults are not very nice
    Duration period = Duration.between(startTime, endTime);
    String pattern;
    if (period.compareTo(TEN_MINUTES) <= 0) {
        pattern = "mm:ss";
    } else if (period.compareTo(ONE_DAY) <= 0) {
        pattern = "HH:mm";
    } else if (period.compareTo(ONE_WEEK) <= 0) {
        pattern = "EEE d";
    } else {
        pattern = "d MMM";
    }
    XYStyler styler = chart.getStyler();
    styler.setDatePattern(pattern);
    // axis
    styler.setAxisTickLabelsFont(chartTheme.getAxisTickLabelsFont(dpi));
    styler.setAxisTickLabelsColor(chartTheme.getAxisTickLabelsColor());
    styler.setXAxisMin((double) startTime.toInstant().toEpochMilli());
    styler.setXAxisMax((double) endTime.toInstant().toEpochMilli());
    int yAxisSpacing = Math.max(height / 10, chartTheme.getAxisTickLabelsFont(dpi).getSize());
    if (yAxisDecimalPattern != null) {
        styler.setYAxisDecimalPattern(yAxisDecimalPattern);
    }
    styler.setYAxisTickMarkSpacingHint(yAxisSpacing);
    styler.setYAxisLabelAlignment(Styler.TextAlignment.Right);
    // chart
    styler.setChartBackgroundColor(chartTheme.getChartBackgroundColor());
    styler.setChartFontColor(chartTheme.getChartFontColor());
    styler.setChartPadding(chartTheme.getChartPadding(dpi));
    styler.setPlotBackgroundColor(chartTheme.getPlotBackgroundColor());
    float plotGridLinesDash = (float) chartTheme.getPlotGridLinesDash(dpi);
    float[] plotGridLinesDashArray = { plotGridLinesDash, plotGridLinesDash };
    styler.setPlotGridLinesStroke(new BasicStroke((float) chartTheme.getPlotGridLinesWidth(dpi), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, plotGridLinesDashArray, 0));
    styler.setPlotGridLinesColor(chartTheme.getPlotGridLinesColor());
    // legend
    styler.setLegendBackgroundColor(chartTheme.getLegendBackgroundColor());
    styler.setLegendFont(chartTheme.getLegendFont(dpi));
    styler.setLegendSeriesLineLength(chartTheme.getLegendSeriesLineLength(dpi));
    LegendPositionDecider legendPositionDecider = new LegendPositionDecider();
    // Loop through all the items
    if (items != null) {
        String[] itemNames = items.split(",");
        for (String itemName : itemNames) {
            Item item = itemUIRegistry.getItem(itemName);
            if (addItem(chart, persistenceService, startTime, endTime, item, seriesCounter, chartTheme, dpi, legendPositionDecider)) {
                seriesCounter++;
            }
        }
    }
    // Loop through all the groups and add each item from each group
    if (groups != null) {
        String[] groupNames = groups.split(",");
        for (String groupName : groupNames) {
            Item item = itemUIRegistry.getItem(groupName);
            if (item instanceof GroupItem) {
                GroupItem groupItem = (GroupItem) item;
                for (Item member : groupItem.getMembers()) {
                    if (addItem(chart, persistenceService, startTime, endTime, member, seriesCounter, chartTheme, dpi, legendPositionDecider)) {
                        seriesCounter++;
                    }
                }
            } else {
                throw new ItemNotFoundException("Item '" + item.getName() + "' defined in groups is not a group.");
            }
        }
    }
    Boolean showLegend = null;
    // If there are no series, render a blank chart
    if (seriesCounter == 0) {
        // always hide the legend
        showLegend = false;
        List<Date> xData = new ArrayList<>();
        List<Number> yData = new ArrayList<>();
        xData.add(Date.from(startTime.toInstant()));
        yData.add(0);
        xData.add(Date.from(endTime.toInstant()));
        yData.add(0);
        XYSeries series = chart.addSeries("NONE", xData, yData);
        series.setMarker(new None());
        series.setLineStyle(new BasicStroke(0f));
    }
    // if the legend is not already hidden, check if legend parameter is supplied, or calculate a sensible value
    if (showLegend == null) {
        if (legend == null) {
            // more than one series, show the legend. otherwise hide it.
            showLegend = seriesCounter > 1;
        } else {
            // take value from supplied legend parameter
            showLegend = legend;
        }
    }
    // This won't be perfect, but it's a good compromise
    if (showLegend) {
        styler.setLegendPosition(legendPositionDecider.getLegendPosition());
    } else {
        // hide the whole legend
        styler.setLegendVisible(false);
    }
    // Write the chart as a PNG image
    BufferedImage lBufferedImage = new BufferedImage(chart.getWidth(), chart.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D lGraphics2D = lBufferedImage.createGraphics();
    chart.paint(lGraphics2D, chart.getWidth(), chart.getHeight());
    return lBufferedImage;
}
Also used : BasicStroke(java.awt.BasicStroke) XYSeries(org.knowm.xchart.XYSeries) ArrayList(java.util.ArrayList) BufferedImage(java.awt.image.BufferedImage) QueryablePersistenceService(org.openhab.core.persistence.QueryablePersistenceService) HistoricItem(org.openhab.core.persistence.HistoricItem) GroupItem(org.openhab.core.items.GroupItem) Item(org.openhab.core.items.Item) GroupItem(org.openhab.core.items.GroupItem) Duration(java.time.Duration) XYStyler(org.knowm.xchart.style.XYStyler) Date(java.util.Date) Graphics2D(java.awt.Graphics2D) QueryablePersistenceService(org.openhab.core.persistence.QueryablePersistenceService) PersistenceService(org.openhab.core.persistence.PersistenceService) XYChart(org.knowm.xchart.XYChart) XYChartBuilder(org.knowm.xchart.XYChartBuilder) None(org.knowm.xchart.style.markers.None) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException)

Example 9 with XYChartBuilder

use of org.knowm.xchart.XYChartBuilder in project 2022-RapidReact by Spartronics4915.

the class DrivetrainEstimatorTest method testEstimator.

@Test
public void testEstimator() {
    var stateStdDevs = new MatBuilder<>(Nat.N3(), Nat.N1()).fill(0.02, 0.02, 0.01);
    var measurementStdDevs = new MatBuilder<>(Nat.N6(), Nat.N1()).fill(0.1, 0.1, 0.1, 0.05, 0.05, 0.002);
    var est = new DrivetrainEstimator(stateStdDevs, measurementStdDevs, 3, new Pose2d());
    final double dt = 0.01;
    final double visionUpdateRate = 0.2;
    var traj = TrajectoryGenerator.generateTrajectory(List.of(new Pose2d(), new Pose2d(3, 3, new Rotation2d())), new TrajectoryConfig(Units.inchesToMeters(12), Units.inchesToMeters(12)));
    var kinematics = new DifferentialDriveKinematics(1);
    Pose2d lastPose = null;
    List<Double> trajXs = new ArrayList<>();
    List<Double> trajYs = new ArrayList<>();
    List<Double> observerXs = new ArrayList<>();
    List<Double> observerYs = new ArrayList<>();
    List<Double> slamXs = new ArrayList<>();
    List<Double> slamYs = new ArrayList<>();
    List<Double> visionXs = new ArrayList<>();
    List<Double> visionYs = new ArrayList<>();
    var rand = new Random();
    final double steadyStateErrorX = 1.0;
    final double steadyStateErrorY = 1.0;
    double t = 0.0;
    Pose2d lastVisionUpdate = null;
    double lastVisionUpdateT = Double.NEGATIVE_INFINITY;
    double maxError = Double.NEGATIVE_INFINITY;
    double errorSum = 0;
    while (t <= traj.getTotalTimeSeconds()) {
        t += dt;
        var groundtruthState = traj.sample(t);
        var input = kinematics.toWheelSpeeds(new ChassisSpeeds(groundtruthState.velocityMetersPerSecond, 0.0, // ds/dt * dtheta/ds = dtheta/dt
        groundtruthState.velocityMetersPerSecond * groundtruthState.curvatureRadPerMeter));
        Matrix<N3, N1> u = new MatBuilder<>(Nat.N3(), Nat.N1()).fill(input.leftMetersPerSecond * dt, input.rightMetersPerSecond * dt, 0.0);
        if (lastPose != null) {
            u.set(2, 0, groundtruthState.poseMeters.getRotation().getRadians() - lastPose.getRotation().getRadians());
        }
        u = u.plus(StateSpaceUtil.makeWhiteNoiseVector(new MatBuilder<>(Nat.N3(), Nat.N1()).fill(0.002, 0.002, 0.001)));
        lastPose = groundtruthState.poseMeters;
        Pose2d realPose = groundtruthState.poseMeters;
        if (lastVisionUpdateT + visionUpdateRate < t) {
            if (lastVisionUpdate != null) {
                est.addVisionMeasurement(lastVisionUpdate, lastVisionUpdateT);
            }
            lastVisionUpdateT = t;
            lastVisionUpdate = realPose.transformBy(new Transform2d(new Translation2d(rand.nextGaussian() * 0.05, rand.nextGaussian() * 0.05), new Rotation2d(rand.nextGaussian() * 0.002)));
            visionXs.add(lastVisionUpdate.getTranslation().getX());
            visionYs.add(lastVisionUpdate.getTranslation().getY());
        }
        double dist = realPose.getTranslation().getDistance(new Translation2d());
        Pose2d measurementVSlam = realPose.transformBy(new Transform2d(new Translation2d(steadyStateErrorX * (dist / 76.0), steadyStateErrorY * (dist / 76.0)), new Rotation2d())).transformBy(new Transform2d(new Translation2d(rand.nextGaussian() * 0.05, rand.nextGaussian() * 0.05), new Rotation2d(rand.nextGaussian() * 0.001)));
        var xHat = est.update(measurementVSlam, u.get(0, 0), u.get(1, 0), u.get(2, 0), t);
        double error = groundtruthState.poseMeters.getTranslation().getDistance(xHat.getTranslation());
        if (error > maxError) {
            maxError = error;
        }
        errorSum += error;
        trajXs.add(groundtruthState.poseMeters.getTranslation().getX());
        trajYs.add(groundtruthState.poseMeters.getTranslation().getY());
        observerXs.add(xHat.getTranslation().getX());
        observerYs.add(xHat.getTranslation().getY());
        slamXs.add(measurementVSlam.getTranslation().getX());
        slamYs.add(measurementVSlam.getTranslation().getY());
    }
    System.out.println("Mean error (meters): " + errorSum / (traj.getTotalTimeSeconds() / dt));
    System.out.println("Max error (meters):  " + maxError);
    try {
        if (true)
            throw new HeadlessException();
        var chartBuilder = new XYChartBuilder();
        chartBuilder.title = "The Magic of Sensor Fusion";
        var chart = chartBuilder.build();
        chart.addSeries("vSLAM", slamXs, slamYs);
        chart.addSeries("Vision", visionXs, visionYs);
        chart.addSeries("Trajectory", trajXs, trajYs);
        chart.addSeries("xHat", observerXs, observerYs);
        new SwingWrapper<>(chart).displayChart();
        try {
            Thread.sleep(1000000000);
        } catch (InterruptedException e) {
        }
    } catch (java.awt.HeadlessException ex) {
        System.out.println("skipping charts in headless mode");
    }
}
Also used : Transform2d(edu.wpi.first.math.geometry.Transform2d) DifferentialDriveKinematics(edu.wpi.first.math.kinematics.DifferentialDriveKinematics) ArrayList(java.util.ArrayList) Random(java.util.Random) TrajectoryConfig(edu.wpi.first.math.trajectory.TrajectoryConfig) N1(edu.wpi.first.math.numbers.N1) N3(edu.wpi.first.math.numbers.N3) ChassisSpeeds(edu.wpi.first.math.kinematics.ChassisSpeeds) MatBuilder(edu.wpi.first.math.MatBuilder) Translation2d(edu.wpi.first.math.geometry.Translation2d) Rotation2d(edu.wpi.first.math.geometry.Rotation2d) Pose2d(edu.wpi.first.math.geometry.Pose2d) XYChartBuilder(org.knowm.xchart.XYChartBuilder) java.awt(java.awt) Test(org.junit.jupiter.api.Test)

Example 10 with XYChartBuilder

use of org.knowm.xchart.XYChartBuilder in project rest.li by linkedin.

the class ConsistentHashRingSimulator method getCIRChart.

private XYChart getCIRChart(Map<String, List<Integer>> CIRTracker, String title) {
    XYChart chart = new XYChartBuilder().title(title).xAxisTitle("Time (ms)").yAxisTitle("CIR").width(600).height(400).build();
    for (Map.Entry<String, List<Integer>> entry : CIRTracker.entrySet()) {
        List<Integer> xData = IntStream.range(0, entry.getValue().size()).mapToObj(i -> i * CIR_SNAPSHOT_INTERVAL).collect(Collectors.toList());
        XYSeries series = chart.addSeries(entry.getKey(), xData, entry.getValue());
        series.setMarker(SeriesMarkers.NONE);
    }
    return chart;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IntStream(java.util.stream.IntStream) XYChartBuilder(org.knowm.xchart.XYChartBuilder) HashMap(java.util.HashMap) Random(java.util.Random) Timer(java.util.Timer) ArrayList(java.util.ArrayList) CallTracker(com.linkedin.util.degrader.CallTracker) XYSeries(org.knowm.xchart.XYSeries) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) CategoryChartBuilder(org.knowm.xchart.CategoryChartBuilder) Ring(com.linkedin.d2.balancer.util.hashing.Ring) TimerTask(java.util.TimerTask) Path(java.nio.file.Path) XYChart(org.knowm.xchart.XYChart) RingFactory(com.linkedin.d2.balancer.strategies.RingFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) SwingWrapper(org.knowm.xchart.SwingWrapper) CallTrackerImpl(com.linkedin.util.degrader.CallTrackerImpl) List(java.util.List) Paths(java.nio.file.Paths) CategoryChart(org.knowm.xchart.CategoryChart) SeriesMarkers(org.knowm.xchart.style.markers.SeriesMarkers) CallCompletion(com.linkedin.util.degrader.CallCompletion) XYSeries(org.knowm.xchart.XYSeries) XYChart(org.knowm.xchart.XYChart) ArrayList(java.util.ArrayList) List(java.util.List) XYChartBuilder(org.knowm.xchart.XYChartBuilder) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

XYChartBuilder (org.knowm.xchart.XYChartBuilder)16 XYChart (org.knowm.xchart.XYChart)13 XYSeries (org.knowm.xchart.XYSeries)12 ArrayList (java.util.ArrayList)11 SwingWrapper (org.knowm.xchart.SwingWrapper)8 Exchange (org.knowm.xchange.Exchange)7 BigDecimal (java.math.BigDecimal)5 OrderBook (org.knowm.xchange.dto.marketdata.OrderBook)5 LimitOrder (org.knowm.xchange.dto.trade.LimitOrder)5 MarketDataService (org.knowm.xchange.service.marketdata.MarketDataService)5 Date (java.util.Date)3 List (java.util.List)3 XYSeries (com.tcdng.unify.core.chart.XYSeries)2 Color (java.awt.Color)2 Random (java.util.Random)2 ExchangeSpecification (org.knowm.xchange.ExchangeSpecification)2 BitcoiniumExchange (org.knowm.xchange.bitcoinium.BitcoiniumExchange)2 BitcoiniumTicker (org.knowm.xchange.bitcoinium.dto.marketdata.BitcoiniumTicker)2 BitcoiniumTickerHistory (org.knowm.xchange.bitcoinium.dto.marketdata.BitcoiniumTickerHistory)2 BitcoiniumMarketDataServiceRaw (org.knowm.xchange.bitcoinium.service.BitcoiniumMarketDataServiceRaw)2