Skip to content

Commit

Permalink
some console.log and import clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
jaelafield committed Jan 24, 2025
1 parent cd6f3d1 commit a311912
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 81 deletions.
23 changes: 10 additions & 13 deletions src/herbie/ErrorPlot.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
// Also want to fix build -- maybe switch to vite, but most important is to move webview to subfolder
import {useState, useEffect} from "react";
import { SelectedExprIdContext, ExpressionsContext, AnalysesContext, SpecContext, CompareExprIdsContext } from './HerbieContext'
import * as HerbieContext from './HerbieContext'
import { Tooltip } from "react-tooltip";

import * as HerbieContext from './HerbieContext' // ??
import * as contexts from './HerbieContext' // >>
import { SelectedExprIdContext, ExpressionsContext,
AnalysesContext, SpecContext, CompareExprIdsContext } from './HerbieContext'

import * as HerbieTypes from './HerbieTypes'
import { Expression, ordinal, expressionError } from './HerbieTypes'

import * as fpcorejs from './lib/fpcore'
import * as ordinals from './lib/ordinals'
import * as herbiejs from './lib/herbiejs'
import { nextId } from "./lib/utils";

import { Expression, ordinal, expressionError } from './HerbieTypes'
import * as HerbieTypes from './HerbieTypes'
import * as contexts from './HerbieContext'
import { InputRangeEditor1 } from "./InputRangesEditor";

import './ErrorPlot.css'
import { nextId } from "./lib/utils";
import { Tooltip } from "react-tooltip";

const Plot = require('@observablehq/plot') // have to do this for ES modules for now

import { select } from 'd3-selection'; // Required for brushing
import { brushX } from 'd3-brush';
import { getApi } from "./lib/servercalls";
Expand Down Expand Up @@ -109,11 +111,8 @@ async function plotError({ varnames, varidx, ticks, splitpoints, data, bits, sty
y: points.reduce((acc, e) => e.y + acc, 0) / points.length,
x: points.reduce((acc, e) => e.x + acc, 0) / points.length
})
// console.log(data)
// console.log(slidingWindow(data, binSize))
const compressedSlidingWindow = compress(
slidingWindow(data, binSize), width, average)
//console.log(compressedSlidingWindow)

const percentageCompressedSlidingWindow = compressedSlidingWindow.map(({x,y}:{x:any,y:any})=>({x,y:(100-(y/64*100))}))
const percentageData = compress(data,width).map(({x,y,orig}:{x:any,y:any,orig:any})=>({x,y:(100-(y/64*100)),orig}))
Expand Down Expand Up @@ -210,8 +209,6 @@ function ErrorPlot() {
useEffect(() => {setMyInputRanges(inputRanges)}, [sample])

const expressions = allExpressions.filter(e => !archivedExpressions.includes(e.id))

// console.log('selectedExprId', selectedExprId)

// get the expression
const selectedExpr = expressions.find(e => e.id === selectedExprId)
Expand Down
29 changes: 8 additions & 21 deletions src/herbie/HerbieUI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,25 @@ import React, { useReducer, useState, createContext, useContext, useEffect } fro

import './HerbieUI.css';

import * as Types from './HerbieTypes'
import { Derivation, Expression, ErrorAnalysis, CostAnalysis, Sample } from './HerbieTypes';
import * as Contexts from './HerbieContext';

import { SpecComponent, SpecConfigComponent } from './SpecComponent';
import { ServerStatusComponent } from './ServerStatus';
import { SerializeStateComponent } from './SerializeStateComponent';
import { ExpressionTable } from './ExpressionTable';
import * as Contexts from './HerbieContext';
import { Derivation, Expression, ErrorAnalysis, CostAnalysis, SpecRange, Spec, Sample } from './HerbieTypes';
import * as Types from './HerbieTypes'
import { nextId } from './lib/utils';
import * as utils from './lib/utils';
import { SelectableVisualization } from './SelectableVisualization';
import { ErrorPlot } from './ErrorPlot';
import { DerivationComponent } from './DerivationComponent';
import SpeedVersusAccuracyPareto from './SpeedVersusAccuracyPareto';
import { expressionToTex } from './ExpressionTable';

import * as utils from './lib/utils';
import { nextId } from './lib/utils';
import { getApi } from './lib/servercalls';
import * as fpcorejs from './lib/fpcore';
import * as herbiejsImport from './lib/herbiejs';
import { expressionToTex } from './ExpressionTable';

interface ContextProviderProps {
children: React.ReactNode;
Expand Down Expand Up @@ -198,7 +200,6 @@ function HerbieUIInner() {
// HACK to make sampling work on Herbie side
const specVars = fpcorejs.getVarnamesMathJS(spec.expression)
const analysis = await herbiejs.analyzeExpression(fpcorejs.mathjsToFPCore(expression.text, spec.expression, specVars), sample, serverUrl)
console.log('Analysis was:', analysis)
// analysis now looks like [[[x1, y1], e1], ...]. We want to average the e's

return new ErrorAnalysis(analysis, expression.id, sample.id)
Expand Down Expand Up @@ -234,21 +235,11 @@ function HerbieUIInner() {
if (sample.specId !== spec.id) {
return;
}
console.debug('Getting new cost for expression', expression, 'and sample', sample, '...')

try {
const specVars = fpcorejs.getVarnamesMathJS(spec.expression);
// const formula = fpcorejs.mathjsToFPCore(expression.text, spec.expression, specVars);
const formula = fpcorejs.mathjsToFPCore(expression.text);


// console.log("Expression is " + formula);
// console.log("sample is " + sample);

const costData = await herbiejs.getCost(formula, sample, serverUrl);

console.log("hooray the cost data is: ", costData);

return new CostAnalysis(expression.id, costData);
} catch (e) {
const throwError = (e: any) => () => {
Expand All @@ -262,10 +253,7 @@ function HerbieUIInner() {
updateCostAsync();
}



// Reactively update expression styles whenever expressions change

useEffect(updateExpressionStyles, [expressions])
function updateExpressionStyles() {
setExpressionStyles(expressions.map((expression) => {
Expand Down Expand Up @@ -533,7 +521,6 @@ function HerbieUIInner() {
{'formulas': [formula] },
true
));
console.log(fptaylorInputResponse);

const fptaylorInput = fptaylorInputResponse.stdout;

Expand Down
18 changes: 10 additions & 8 deletions src/herbie/LocalError/LocalError.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import React from 'react';
import { useEffect } from 'react';
import { Tooltip } from "react-tooltip";

import * as HerbieContext from '../HerbieContext';
import * as types from '../HerbieTypes';
import { ErrorExpressionResponse } from '../HerbieTypes';

import * as fpcore from '../lib/fpcore';
import { Tooltip } from "react-tooltip";
import Mermaid from './Mermaid';
import { Point } from './Point';
import * as herbiejs from '../lib/herbiejs'

import Mermaid from './Mermaid';

import './LocalError.css';
import { useEffect } from 'react';
import React from 'react';
import { ErrorExpressionResponse } from '../HerbieTypes';

function localErrorTreeAsMermaidGraph(tree: types.LocalErrorTree, bits: number, currentLocation: Array<number>, targetLocation: Array<number> ,explanation: string) {
// See examples + doc at https://github.com/mermaid-js/mermaid
let edges = [] as string[]
Expand Down Expand Up @@ -210,8 +214,6 @@ function LocalError({ expressionId }: { expressionId: number }) {
}
return
}

console.log('Node clicked!', event.target);
};
if (!localError) {
return (
Expand Down
35 changes: 16 additions & 19 deletions src/herbie/SpecComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import React, { useCallback, ChangeEvent, useContext, useState, useEffect } from 'react';
import { InputRange, InputRangeEditor1 } from './InputRangesEditor';
import { InputRangesTableContext, SpecContext } from './HerbieContext';
import { SpecRange, Spec } from './HerbieTypes';
import * as HerbieTypes from './HerbieTypes';
import * as utils from './lib/utils';
import * as HerbieContext from './HerbieContext';
import KaTeX from 'katex';
import React, { useState, useEffect } from 'react';
import Modal from 'react-modal';
import './sliders.css';

import { DebounceInput, DebounceTextArea } from 'react-debounce-input';
console.log("KaTeX:", KaTeX);
import { DebounceInput } from 'react-debounce-input';
import KaTeX from 'katex';

import './SpecComponent.css';
const math11 = require('mathjs11');
import * as HerbieTypes from './HerbieTypes';
import { SpecRange, Spec } from './HerbieTypes';
import * as HerbieContext from './HerbieContext';
import { InputRange, InputRangeEditor1 } from './InputRangesEditor';
import { expressionToTex } from './ExpressionTable';

import * as utils from './lib/utils';
import * as fpcorejs from './lib/fpcore';
import { fPCoreToMathJS } from './lib/herbiejs';
import { expressionToTex } from './ExpressionTable';
import { getApi } from './lib/servercalls';

import './sliders.css';
import './SpecComponent.css';

async function ensureMathJS(expression: string, serverUrl: string): Promise<string> {
if (expression.includes("FPCore")) {
return await fPCoreToMathJS(expression, serverUrl);
Expand Down Expand Up @@ -280,7 +277,7 @@ function SpecConfigComponent() {
useEffect(() => {
const vars = variables;
const newRanges = vars.map((v) => {
const range = mySpecRanges.find((r) => r.variable === v) || new HerbieTypes.SpecRange(v, -1e308, 1e308);
const range = mySpecRanges.find((r) => r.variable === v) || new SpecRange(v, -1e308, 1e308);
return range;
});
setMySpecRanges(newRanges);
Expand Down Expand Up @@ -343,7 +340,7 @@ function SpecConfigComponent() {
{variables.map((v, i) => {
const range =
mySpecRanges.find((r) => r.variable === v) ||
new HerbieTypes.SpecRange(v, -1e308, 1e308);
new SpecRange(v, -1e308, 1e308);
return (
<div className="spec-range-input" key={v}>
<div className="varname">{v}:</div>
Expand All @@ -359,7 +356,7 @@ function SpecConfigComponent() {
setMySpecRanges(
mySpecRanges.map((r) =>
r.variable === v
? new HerbieTypes.SpecRange(
? new SpecRange(
v,
parseFloat(value.lower),
parseFloat(value.upper)
Expand All @@ -370,7 +367,7 @@ function SpecConfigComponent() {
} else {
const newSpecRanges = [
...mySpecRanges,
new HerbieTypes.SpecRange(
new SpecRange(
v,
parseFloat(value.lower),
parseFloat(value.upper)
Expand Down
10 changes: 1 addition & 9 deletions src/herbie/SpeedVersusAccuracyPareto.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import React from 'react';
const Plot = require('@observablehq/plot') // have to do this for ES modules for now
import * as ordinals from './lib/ordinals'
import { ordinal } from './HerbieTypes'
import './SpeedVersusAccuracyPareto.css';

interface SpeedVersusAccuracyParetoProps {
Expand All @@ -15,19 +13,15 @@ type Point = {
}

async function plotParetoPoints (bits: number, initial_pt: Point, rest_pts: Point[], clickedExpressionId: number, expressionStyles: ExpressionStyle[]) {
// const bits = benchmark["bits"];

// The line differs from rest_pts in two ways:
// - We filter to the actual pareto frontier, in case points moved
// - We make a broken line to show the real Pareto frontier
// let line: Point[] = [];

// initialize line as empty object
let line: Point[] = [];

// create a new array with rest_pts reverse sorted from lowest to highest cost
const sorted_pts = rest_pts.slice().sort((a, b) => a.cost - b.cost);
// console.log("sorted points: ", sorted_pts);
// debugger;

let mostAccurateSoFar: Point | null = null;

Expand Down Expand Up @@ -168,9 +162,7 @@ const SpeedVersusAccuracyPareto: React.FC<SpeedVersusAccuracyParetoProps> = (pro
plot.querySelectorAll('[aria-label="dot"] circle').forEach((t: any) => {
// if a point if clicked (onclick), set its clickedExpressionID
t.onclick = async() => {
console.log('Clicked point -> Setting selected point', t.getAttribute("data-id"));
setSelectedExprId(parseInt(t.getAttribute("data-id")));
console.log('New selected point', selectedExprId);
}
});

Expand Down
14 changes: 3 additions & 11 deletions src/herbie/lib/herbiejs.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as fpcorejs from './fpcore';
import * as ordinalsjs from './ordinals';
import { ErrorExpressionResponse, Sample } from '../HerbieTypes';
import * as types from '../HerbieTypes';
import { ErrorExpressionResponse, Sample } from '../HerbieTypes';
import { getApi } from './servercalls';

interface HerbieResponse {
Expand Down Expand Up @@ -36,15 +36,15 @@ const getHerbieApiAsync = async (
var checkResponse = await fetch(statusURL, {
method: 'GET',
});
while (checkResponse.status != 201 && counter < cap) {
while (checkResponse.status !== 201 && counter < cap) {
counter += 1
checkResponse = await fetch(`${host}/check-status/${job_id}`, {
method: 'GET',
});
await new Promise(r => setTimeout(r, 100)); // ms
}
// Guard that the job is finished. If not throw an error giving up on this request.
if (checkResponse.status != 201) {
if (checkResponse.status !== 201) {
throw new Error(`Request timeout`)
}
const result = await fetch(`${host}/api/result/${job_id}`, {
Expand Down Expand Up @@ -231,19 +231,12 @@ export const analyzeExpression = async (
const pointsAndErrors = ((await getHerbieApi(host, 'analyze', { formula: fpcore, sample: sample.points, seed: 5 }, true)) as AnalyzeResponse).points;
const ordinalSample = pointsAndErrors.map(p => p[0].map((v: number) => ordinalsjs.floatToApproximateOrdinal(v)));

// console.log('first 10 pointsAndErrors', pointsAndErrors.map(([point, error]) => point).slice(0, 10));
// console.log('first 10 sample points', sample.points.map(p => p[0]).slice(0, 10));
// console.log('first 10 pointsAndErrors points (from /analyze) after sorting', pointsAndErrors.map(([point, error]) => point).sort().slice(0, 10));
// console.log('first 10 sample points (from /sample) after sorting', sample.points.map(p => p[0]).sort().slice(0, 10));

const vars = fpcorejs.getVarnamesFPCore(fpcore);
const ticksByVarIdx: [string, number][][] = vars.map((v, i) => {
const values = sample.points.map(p => p[0][i]);
return ordinalsjs.chooseTicks(fastMin(values), fastMax(values)).map(v => [displayNumber(v), ordinalsjs.floatToApproximateOrdinal(v)]);
});

// console.debug(`ticksByVarIdx`, sample, ticksByVarIdx);

const splitpointsByVarIdx = vars.map(v => []); // HACK no splitpoints for now
const errors = pointsAndErrors.map(([point, error]) => parseFloat(error));
const meanBitsError = parseFloat((errors.reduce((sum, v) => sum + v, 0) / errors.length).toFixed(2));
Expand All @@ -255,7 +248,6 @@ export const analyzeExpression = async (
vars,
errors,
meanBitsError
// pointsJson: { points: ordinalSample, ticks_by_varidx: ticksByVarIdx, splitpoints_by_varidx: splitpointsByVarIdx, bits: 64, vars, error: { target: errors } }, meanBitsError
};
};

Expand Down

0 comments on commit a311912

Please sign in to comment.