My favorites | Sign in
Project Home Downloads Wiki Issues Source
Repository:
Checkout   Browse   Changes   Clones    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main

import (
"bytes";
"os";
"io";
"fmt";
"strings";
"strconv";
"container/vector";
"math";
"http";
"flag";
"expvar";
"json";
. "./constants";
_ "./httplog"
)

type Point struct {
x float;
y float;
}

type Config struct {
Address string;
CustomLog string;
LogFormat []string;
}

func (pt *Point) String() string { return fmt.Sprintf("(%f,%f)", pt.x, pt.y) }

func (pt *Point) ServeHTTP(c *http.Conn, req *http.Request) {
switch req.Method {
case "GET":
pt.x++
case "POST":
pt.x, _ = strconv.Atof(req.FormValue("x"));
pt.y, _ = strconv.Atof(req.FormValue("y"));
}
fmt.Fprintf(c, "point is (%f,%f)\n", pt.x, pt.y);
}

var configFlag = flag.String("c", "server.conf", "Config file name");
var helpFlag = flag.Bool("h", false, "This help");

// next variables are also available in server config file
var addressFlag = flag.String("l", "0.0.0.0:6060", "Address and port to listen on (ex. 127.0.0.1:1234");

func main() {
// todo: config file overrides command line flags, this feels incorrect
flag.Parse();

if *helpFlag {
flag.PrintDefaults();
os.Exit(EXIT_SUCCESS);
}

configJsonBytes, err := io.ReadFile(*configFlag);
if err != nil {
fmt.Fprintf(os.Stderr, "failed to read %s: %s\n", *configFlag, err.String());
os.Exit(EXIT_NO_CONFIG);
}
// split the buffer into an array of strings, one per source line
configJson := bytes.NewBuffer(configJsonBytes).String();

var config = Config{ *addressFlag, "nolog", nil };
ok, errtok := json.Unmarshal(configJson, &config);
if !ok {
fmt.Fprintf(os.Stderr, "Config error at %s (while reading %s)\n", strconv.Quote(errtok), *configFlag);
os.Exit(EXIT_CONFIG_PARSE);
}

fmt.Printf("%s\n",config.Address);
fmt.Printf("%s\n",config.CustomLog);

demoPoint := new(Point);
demoPoint.x = 0.0;
demoPoint.y = 0.0;

http.Handle("/point", demoPoint);
expvar.Publish("point", demoPoint);

http.Handle("/goplot/viz", http.HandlerFunc(dataSampleServer));
// serve our own files instead of using http.FileServer for very tight access control
http.Handle("/goplot/graph.js", http.HandlerFunc(fileServe));
// in order
err = http.ListenAndServe(config.Address, nil);
if err != nil {
fmt.Fprintf(os.Stderr, "ListenAndServe on %s got: %s\n", config.Address, err.String());
os.Exit(EXIT_CANT_LISTEN);
}
}

// serve static files as appropriate
func fileServe(c *http.Conn, req *http.Request) {
cwd, err := os.Getwd();
if err==nil {
http.ServeFile(c, req, cwd + "/client/graph.js");
} else {
serveError(c, req, http.StatusInternalServerError); // 500
}
}

// Send the given error code.
func serveError(c *http.Conn, req *http.Request, code int) {
c.SetHeader("Content-Type", "text/plain; charset=utf-8");
c.WriteHeader(code);
io.WriteString(c, fmt.Sprintf("%d\n",code));
}

// processes data samples, sends back data to plot along with regression lines
func dataSampleServer(c *http.Conn, req *http.Request) {
switch req.Method {
case "GET":
cwd, err := os.Getwd();
if err==nil {
http.ServeFile(c, req, cwd + "/client/viz.html");
} else {
serveError(c, req, http.StatusInternalServerError); // 500
}
case "POST":
src := req.FormValue("dataseries");
result := dataSampleProcess(src);
// send the response
_,_=io.WriteString(c, result);
default :
serveError(c, req, http.StatusMethodNotAllowed);
}
}

// processes data samples, sends back data to plot along with regression lines
func dataSampleProcess(src string) (results string) {
const MAXLINES = 1000000;

// split the buffer into an array of strings, one per source line
srcLines := strings.Split(src,"\n",MAXLINES);

lineCount := len(srcLines);
series := vector.New(0);

for ix:=0; ix < lineCount; ix++ {
stmp , err := parseLine(srcLines[ix]);
if err == nil {
series.Push(stmp);
}
}
jsonStr:="{series:[";
for ix:=0; ix < series.Len(); ix++ {
jsonStr += "{x:" + strconv.Ftoa(series.At(ix).(Point).x,'f',3) + ",y:" + strconv.Ftoa(series.At(ix).(Point).y,'f',3) + "},";
}
jsonStr += "],\n";

slope, intercept, stdError, correlation := linearRegression(series);
jsonStr += fmt.Sprintf("regressionLine:{slope:%f,intercept:%f,stdError:%f,correlation:%f},",slope, intercept, stdError, correlation);
jsonStr += "}";

return jsonStr;
}

func parseLine(coords string) (p Point, err os.Error) {
if len(coords) > 0 {
coordsAr := strings.Split(strings.TrimSpace(coords), ",", 3);
if len(coordsAr) > 1 {
// ignore conversion errors
p.x, err = strconv.Atof(coordsAr[0]);
if err == nil {
p.y, err = strconv.Atof(coordsAr[1]);
}
}
} else {
err = os.NewError("parseLine: No data");
}
return p, err;
}

// perform linear regression on the data series
// based on Numerical Methods for Engineers, 2nd ed. by Chapra & Canal
func linearRegression(series *vector.Vector) (slope float, intercept float, stdError float, correlation float) {
len := series.Len();
flen := float(len); // convenience
sumx := 0.0;
sumy := 0.0;
sumxy := 0.0;
sumx2 := 0.0;
for ix:=0; ix < len; ix++ {
x := series.At(ix).(Point).x;
y := series.At(ix).(Point).y;
sumx += x;
sumy += y;
sumxy += x*y;
sumx2 += x*x;
}
xmean := sumx / flen;
ymean := sumy / flen;
slope = (flen*sumxy - sumx*sumy) / (flen*sumx2 - sumx*sumx);
intercept = ymean - slope * xmean;

st := 0.0;
sr := 0.0;
for ix:=0; ix < len; ix++ {
x := series.At(ix).(Point).x;
y := series.At(ix).(Point).y;
st += (y-ymean)*(y-ymean);
// guessing the compiler sees this is constant & does sth faster than exponentiation
sr += (y - (slope*x - intercept)) * (y - (slope*x - intercept));
}
stdError = (float)(math.Sqrt((float64)(sr/(flen-2.0)))); // todo: must check that min 2 points are supplied
correlation = (float)(math.Sqrt((float64)((st-sr)/st)));
return slope, intercept, stdError, correlation;
}

Change log

b27580e53091 by metaphorically on Nov 19, 2009   Diff
Command line options working, allows ip
address and port specification. Config
file (in JSON format) does the same. The
config file takes precedence at the
moment.
Go to: 
Project members, sign in to write a code review

Older revisions

32fb56efd88a by metaphorically on Nov 18, 2009   Diff
Added l parameter for address:port to
listen on.
1cd28351e5bf by metaphorically on Nov 14, 2009   Diff
Cleanup.
452693c7c9e7 by metaphorically on Nov 14, 2009   Diff
Now runs as a webserver. No longer
works with input & output files
though. That could be added back in
later if needed. So far the IP address
is hardcoded and so is the port
...
All revisions of this file

File info

Size: 6053 bytes, 211 lines
Powered by Google Project Hosting