<?xml version="1.0" encoding="UTF-16"?>
<!-- This XML file has been created by WebEJS 1.0. Visit http://t.um.es/webejs -->
<!-- Please, open it with WebEJS or save the file to your hard disk on your EJS' user directory and open it with Desktop Ejs 6.01 or later. -->
<Osejs version="7.0" password="">
<Osejs.Information>
<Title><![CDATA[Linear_Best_Fit_using_Plotly]]></Title>
<Copyright><![CDATA[]]></Copyright>
<Keywords><![CDATA[]]></Keywords>
<Password><![CDATA[unused]]></Password>
<Level><![CDATA[]]></Level>
<Language><![CDATA[]]></Language>
<Abstract><![CDATA[]]></Abstract>
<FixedNavigationBar>false</FixedNavigationBar>
<RunAlways>true</RunAlways>
<UseInterpreter>true</UseInterpreter>
<UseDeltaForODE>false</UseDeltaForODE>
<PreviewFullModel>false</PreviewFullModel>
<ModelTab></ModelTab>
<ModelTabTitle><![CDATA[]]></ModelTabTitle>
<ModelName><![CDATA[]]></ModelName>
<CSSFile></CSSFile>
<HTMLHead><![CDATA[               <script src="./library/plotly-2.35.2.min.js" charset="utf-8"></script>
<script src="./library/math.js" ></script>

]]></HTMLHead>
<SaveInXMLFormat>true</SaveInXMLFormat>
<IncludeSource>true</IncludeSource>
<IncludeLibrary>true</IncludeLibrary>
<UglifyJS>false</UglifyJS>
<Logo>./linear_logo.png</Logo>
<Author><![CDATA[lookang;kangrui]]></Author>
<AuthorLogo>;</AuthorLogo>
<DetectedFiles><![CDATA[./linear_logo.png]]></DetectedFiles>
<AuxiliaryFiles><![CDATA[;./data.csv;./Market.png;./library/plotly-2.35.2.min.js;./library/math.js]]></AuxiliaryFiles>
</Osejs.Information>
<Osejs.Description>
</Osejs.Description>
<Osejs.Model>
<Osejs.Model.FramesPerSecond>20</Osejs.Model.FramesPerSecond>
<Osejs.Model.StepsPerDisplay>1</Osejs.Model.StepsPerDisplay>
<Osejs.Model.RealTimeVariable></Osejs.Model.RealTimeVariable>
<Osejs.Model.Autostart>true</Osejs.Model.Autostart>
<Osejs.Model.Variables>
<Osejs.Model.Variables.Page>
<Type>undefined</Type>
<Name>Var Table 1</Name>
<Active>true</Active>
<Internal>false</Internal>
<Content>
<PageComment><![CDATA[]]></PageComment>
<Variable>
<Name><![CDATA[xTable]]></Name>
<Value><![CDATA[[0,1,2,6,7,10,20]]]></Value>
<Type><![CDATA[double]]></Type>
<Dimension><![CDATA[]]></Dimension>
<Domain><![CDATA[]]></Domain>
<Comment><![CDATA[]]></Comment>
</Variable>
<Variable>
<Name><![CDATA[yTable]]></Name>
<Value><![CDATA[[0 ,1,3,6,7,10,-20]]]></Value>
<Type><![CDATA[double]]></Type>
<Dimension><![CDATA[]]></Dimension>
<Domain><![CDATA[]]></Domain>
<Comment><![CDATA[]]></Comment>
</Variable>
<Variable>
<Name><![CDATA[]]></Name>
<Value><![CDATA[]]></Value>
<Type><![CDATA[double]]></Type>
<Dimension><![CDATA[]]></Dimension>
<Domain><![CDATA[]]></Domain>
<Comment><![CDATA[]]></Comment>
</Variable>
</Content>
</Osejs.Model.Variables.Page>
</Osejs.Model.Variables>
<Osejs.Model.Initialization>
<Osejs.Model.Initialization.Page>
<Type>undefined</Type>
<Name>Init Page 1</Name>
<Active>true</Active>
<Internal>false</Internal>
<Content>
<Comment><![CDATA[]]></Comment>
<Code><![CDATA[

    // Scatter data (your provided data)
    const scatterData = {
        x: xTable,
        y: yTable,
        mode: 'markers',
        type: 'scatter',
        name: 'Scatter Data',
        marker: { color: 'blue' }
    };

    // Perform linear regression to get the best-fit line
    const { slope, intercept } = linearRegression(scatterData.x, scatterData.y);

    // Generate y-values for the best fit line using the linear equation: y = mx + b
    const bestFitY = scatterData.x.map(xi => slope * xi + intercept);
    
    const bestFitLine = {
        x: scatterData.x,
        y: bestFitY,
        mode: 'lines',
        type: 'scatter',
        name: 'Best Fit Line',
        line: { color: 'red' }
    };

    const layout = {
        title: 'Linear Best Fit Line',
        margin: { t: 30 },
        xaxis: { title: 'X-axis' },
        yaxis: { title: 'Y-axis' }
    };

    // Plot the scatter data and the best-fit line
    Plotly.newPlot("plot", [scatterData, bestFitLine], layout);
    
//readCSVFromPath()
]]></Code>
</Content>
</Osejs.Model.Initialization.Page>
</Osejs.Model.Initialization>
<Osejs.Model.Evolution>
</Osejs.Model.Evolution>
<Osejs.Model.Constraints>
</Osejs.Model.Constraints>
<Osejs.Model.Library>
<Osejs.Model.Library.Page>
<Type>undefined</Type>
<Name>Custom Page 1</Name>
<Active>true</Active>
<Internal>false</Internal>
<Content>
<Comment><![CDATA[]]></Comment>
<Code><![CDATA[
// Function to perform linear regression
    function linearRegression(x, y) {
        const n = x.length;
        const sumX = x.reduce((a, b) => a + b, 0);
        const sumY = y.reduce((a, b) => a + b, 0);
        const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
        const sumXX = x.reduce((sum, xi) => sum + xi * xi, 0);

        const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
        const intercept = (sumY - slope * sumX) / n;

        return { slope, intercept };
    }
function readCSVFromPath() {
    //fetch('https://webejs.iwant2study.org:8000/static/sessions/317ea4eb-99af-4d88-a13a-06f65fd35ac8/source/data.csv')  // Replace 'yourfile.csv' with the actual file name
   fetch('./data.csv')  // Replace 'yourfile.csv' with the actual file name
        .then(response => {
            if (!response.ok) {
                throw new Error("Failed to fetch the CSV file");
            }
            return response.text();  // Return the CSV content as plain text
        })
        .then(data => {
            const parsedData = parseCSV(data);  // Parse the CSV data
            console.log("Parsed CSV Data:", parsedData);  // Log the parsed data for debugging
            // You can now use the parsedData for further processing in your simulation
        })
        .catch(error => {
            console.error("Error reading the CSV file:", error);
        });
}

// Function to parse the CSV data
function parseCSV(csvText) {
    const rows = csvText.split("\n").filter(row => row.trim() !== "");  // Split by new lines and filter empty rows
    const result = rows.map(row => row.split(","));  // Split each row by commas
    return result;
}

// Call the function to read the CSV file


    function polynomialRegression(x, y, degree) {
        const X = x.map(xi => Array.from({length: degree + 1}, (_, i) => Math.pow(xi, i)));
        const Xt = math.transpose(X);
        const XtX = math.multiply(Xt, X);
        const XtY = math.multiply(Xt, y);
        const coefficients = math.lusolve(XtX, XtY).flat();
        return coefficients;
    }

    // Function to generate a line of best fit
    function generateBestFitLine(xData, yData) {
        // Dynamically determine the degree of polynomial (start with quadratic)
        const degree = 2; // Adjust based on data complexity
        const coefficients = polynomialRegression(xData, yData, degree);

        // Generate y-values for the best fit line
        const bestFitY = xData.map(xi => 
            coefficients.reduce((acc, coef, i) => acc + coef * Math.pow(xi, i), 0)
        );

        return bestFitY;
    }
]]></Code>
</Content>
</Osejs.Model.Library.Page>
</Osejs.Model.Library>
<Osejs.Model.Elements>
</Osejs.Model.Elements>
</Osejs.Model>
<Osejs.HtmlView>
<Osejs.HtmlView.Page>
<Type>HTML_VIEW_EDITOR</Type>
<Name>HtmlView</Name>
<Active>true</Active>
<Internal>false</Internal>
<Content>
<SizeOption>0</SizeOption>
<X>0</X>
<Y>0</Y>
<Width>800</Width>
<Height>600</Height>
<KeepHidden>true</KeepHidden>
<RootProperties>
</RootProperties>
<Tree>
<HtmlView.Element>
<Expanded>true</Expanded>
<Type>Elements.Panel</Type>
<Name><![CDATA[panel]]></Name>
<Property name="Width"><![CDATA["100%"]]></Property>
<Property name="Display"><![CDATA["inline-flex"]]></Property>
</HtmlView.Element>
<HtmlView.Element>
<Type>Elements.Panel</Type>
<Name><![CDATA[plot]]></Name>
<Parent><![CDATA[panel]]></Parent>
<Property name="ClassName"><![CDATA["plot"]]></Property>
<Property name="Height"><![CDATA["80vh"]]></Property>
<Property name="Width"><![CDATA["80%"]]></Property>
</HtmlView.Element>
<HtmlView.Element>
<Type>Elements.ArrayPanel</Type>
<Name><![CDATA[arrayPanel]]></Name>
<Parent><![CDATA[panel]]></Parent>
<Property name="DataArray"><![CDATA[[xTable,yTable]]]></Property>
<Property name="Editable"><![CDATA[true]]></Property>
<Property name="HeadersText"><![CDATA[["x","y"]]]></Property>
<Property name="OnChange"><![CDATA[_initialize()]]></Property>
<Property name="Transpose"><![CDATA[true]]></Property>
<Property name="Width"><![CDATA["20%"]]></Property>
<Property name="Height"><![CDATA["80vh"]]></Property>
</HtmlView.Element>
</Tree>
</Content>
</Osejs.HtmlView.Page>
</Osejs.HtmlView>
</Osejs>