├── LICENSE
├── README.md
├── TODO.txt
└── linkedin
├── d3js-linkedin.js
├── sna-js.js
└── socilab-linkedin.js
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | sna-js
2 | ======
3 |
4 | This repository contains javascript code that interact with social network APIs, generate D3.js visualizations, and calculate relevant metrics for **social network analysis**.
5 |
6 | You can see it in use at: http://socilab.com. Socilab is a social network utility that allows users to visualize, analyze, and download data on their LinkedIn network. It has been used for in class tutorials at a number of universities - including Carnegie Mellon, Cornell, Dartmouth, London Business School, University of Sydney, among others, and is featured on datasciencemasters.org.
7 |
8 | I am actively developing this as users request more features and look forward to collaborating to anyone who shares an interest in **making network data and analysis more accessible to end users**.
9 |
10 | LinkedIn
11 | ------
12 | ###sna-js.js:
13 | Takes in 2D adjacency matrix from socilab-linkedin.js and performs egocentric network calculations for social network analysis.
14 |
15 | ###d3js-linkedin.js:
16 | A dynamic and interactive visualization of a user's LinkedIn network using the d3js library, with options to enable/disable connections to ego and color nodes by industry.
17 |
18 | ###socilab-linkedin.js:
19 | Methods for interacting with LinkedIn API to gather network data for display, analysis, and download by user.
20 |
21 | **Note on LinkedIn API functionality**: LinkedIn's public API no longer supports the related-connections request that this script relies on. LinkedIn was courteous enough to extend socilab's access to the prior functionality while our partnership application is pending review. I do not have a timeline for when the application will be processed, but any contributions made here in the meantime can be implemented on the public site so long as they comply with the terms.
22 |
23 | ----
24 | **Author**: *Craig Tutterow*, [@craigtutterow](https://github.com/craigtutterow)
25 |
26 | Contributors: *Lars Juel Nielsen* ([@LJNielsenDk](https://github.com/LJNielsenDk)), *Kushal Likhi* ([@kushal-likhi](https://github.com/kushal-likhi))
27 |
--------------------------------------------------------------------------------
/TODO.txt:
--------------------------------------------------------------------------------
1 | Features to add to network analysis:
2 |
3 | 1. Industry diversity index
4 | 2. Ordered list of top 5 contacts in eigenvector centrality
5 | 3. Add sharing feature for social media integration.
6 | 4. Add pdf download feature.
7 | 5. Error message once throttled.
8 | 6. Format download according to visualization option (connections to self included/excluded).
9 | 7. Add attributes file.
10 |
11 | Features to add to visualization:
12 |
13 | 1. Node sizing by ego's dependence (proportional tie strength or eigenvector centrality of a given node)
14 | 2. Coloring by community detection algorithm (detect clusters of contacts with high density - e.g. colleagues at different companies, classmates, friends from civic organization, etc.)
15 | 3. Add static sharing feature for social media integration.
16 | 4. Add option to remove names.
17 |
18 | Site functionality:
19 | 1. Prevent page from reloading after clicking tab to home page (jquery).
20 | 2. Add facebook support
21 |
--------------------------------------------------------------------------------
/linkedin/d3js-linkedin.js:
--------------------------------------------------------------------------------
1 | /*D3.js code to visualize a user's LinkedIn network from 2d array. Adjacency matrix of user's contacts
2 | is received after being parsed from LinkedIn API.*/
3 | function visualizeConnections(data, enableConnectionsToSelf, colorization) {
4 | var matrix = enableConnectionsToSelf ? data.matrix : data.reducedMatrix;
5 | var connections = data.publicConnections;
6 | var me = { firstName: "Me", lastName: "" };
7 | var ggraph = d3.graph();
8 | ggraph.matrix(matrix);
9 | var nodes = enableConnectionsToSelf ? [ me ].concat(connections) : connections;
10 | ggraph.nodes(nodes);
11 | var glinks = ggraph.links().filter(function(d) {return d.value > 0;});
12 | var gnodes = ggraph.nodes();
13 | var radius = 5;
14 | var defaultLinkStrength = 1;
15 | var myLinkStrength = 0.2;
16 | var showText = true;
17 |
18 | //console.log('nodes', ggraph.nodes());
19 | //console.log('links', JSON.stringify(ggraph.links());
20 | //console.log('description', ggraph.description());
21 |
22 | var color = d3.scale.category20();
23 |
24 | var width = 960,
25 | height = 800;
26 |
27 |
28 |
29 | var linkDistance = function(link) {
30 | var len1 = glinks.filter(function(d) {return (d.source.id == link.source.id);}).length;
31 | var len2 = glinks.filter(function(d) {return d.target.id == link.target.id;}).length;
32 | //console.log(len1, len2);
33 | return 160;
34 | };
35 |
36 | var force = d3.layout.force()
37 | .nodes(gnodes)
38 | .links(glinks)
39 | .size([width, height])
40 | //.linkDistance(linkDistance)
41 | .linkStrength(function(d) { return (d.source.id && d.target.id) ? d.value * defaultLinkStrength : d.value * myLinkStrength; } )
42 | .charge(-900)
43 | .gravity(.8)
44 | //.on("tick", tick)
45 | .start();
46 |
47 | d3.select("body").selectAll("svg").remove();
48 | var svg = d3.select("div#d3_viewport").append("svg")
49 | .attr("width", width)
50 | .attr("height", height)
51 | .call(d3.behavior.zoom()
52 | .on("zoom", redraw))
53 | .append("g");
54 |
55 | function redraw() {
56 | svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
57 | }
58 |
59 | // add the links and the arrows
60 | var glink = svg.selectAll(".link")
61 | .data(force.links());
62 | var glinkEnter = glink
63 | .enter().append("line")
64 | .attr("class", "link")
65 | .style("stroke-width", function (d) {
66 | return Math.sqrt(d.value);
67 | });
68 | glink.exit().remove();
69 |
70 |
71 | // define the nodes
72 | var gnode = svg.selectAll(".node")
73 | .data(force.nodes());
74 | var gnodeEnter = gnode
75 | .enter()
76 | .append("g");
77 | gnodeEnter
78 | .append("circle")
79 | .attr("class", "node")
80 | .attr("r", radius)
81 | .call(force.drag);
82 |
83 | console.log("Colorization now: " + colorization);
84 | gnode.selectAll(".node")
85 | .style("fill", function (d) { return color(colorization(d)); });
86 |
87 | gnodeEnter.append("text")
88 | .text(function (d) { return d.firstName + " " + d.lastName; })
89 | .attr("transform", "translate(7, 0)")
90 | .style("pointer-events", "none")
91 | .style("cursor", "default")
92 | .style("display", showText ? "block" : "none")
93 | .style("font-size", 8)
94 | ;
95 | glink.exit().remove();
96 |
97 |
98 | force.on("tick", function () {
99 | glink.attr("x1", function (d) {
100 | return d.source.x;
101 | })
102 | .attr("y1", function (d) {
103 | return d.source.y;
104 | })
105 | .attr("x2", function (d) {
106 | return d.target.x;
107 | })
108 | .attr("y2", function (d) {
109 | return d.target.y;
110 | });
111 |
112 | gnode.select("circle").attr("cx", function(d) {return d.x;});
113 | gnode.select("circle").attr("cy", function(d) {return d.y;});
114 | gnode.select("text").attr("transform", function (d) {
115 | return "translate(" + (d.x + 6) + "," + (d.y + 4) + ")";
116 | });
117 | });
118 |
119 | //add curvy lines?
120 | /*function tick() {
121 | glink.attr("d", function (d) {
122 | var dx = d.target.x - d.source.x,
123 | dy = d.target.y - d.source.y,
124 | dr = Math.sqrt(dx * dx + dy * dy);
125 | return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
126 | });
127 |
128 | gnode.attr("transform", function (d) {
129 | return "translate(" + d.x + "," + d.y + ")";
130 | });
131 | } */
132 | }
--------------------------------------------------------------------------------
/linkedin/sna-js.js:
--------------------------------------------------------------------------------
1 | var num = [
2 | /* data is parsed from LinkedIn's API to take in a 2d array like this:
3 |
4 | [0, 1, 1, 1, 1, 1, 1, 1, 1, 1],
5 | [1, 0, 1, 1, 0, 0, 0, 0, 0, 1],
6 | [1, 1, 0, 1, 0, 0, 1, 0, 0, 0],
7 | [1, 1, 1, 0, 1, 1, 0, 0, 0, 0],
8 | [1, 0, 0, 1, 0, 1, 1, 0, 0, 0],
9 | [1, 0, 0, 1, 1, 0, 1, 1, 0, 0],
10 | [1, 0, 1, 0, 1, 1, 0, 1, 1, 0],
11 | [1, 0, 0, 0, 0, 1, 1, 0, 1, 1],
12 | [1, 0, 0, 0, 0, 0, 1, 1, 0, 1],
13 | [1, 1, 0, 0, 0, 0, 0, 1, 1, 0]
14 |
15 | rows and columns representing an ordered list of one's contacts, producing
16 | an adjacency matrix. A 1 at the intersection of 2 contacts representing a
17 | mutual connection between x and y. Note that the matrix is symmetric by definition
18 | and that the diagonal is set to 0, as no ego can be connected to themselves)
19 | */
20 | ];
21 |
22 | /*transpose function for matrix operations*/
23 | Array.prototype.transpose = function () {
24 | var a = this,
25 | w = a.length ? a.length : 0,
26 | h = a[0] instanceof Array ? a[0].length : 0;
27 | if (h === 0 || w === 0) {
28 | return [];
29 | }
30 | var i, j, t = [];
31 | for (i = 0; i < h; i++) {
32 | t[i] = [];
33 | for (j = 0; j < w; j++) {
34 | t[i][j] = a[j][i];
35 | }
36 | }
37 | return t;
38 | };
39 |
40 | var totedges = 0;
41 |
42 | /*row sum operation for matrix operations*/
43 | function rowsums(mm) {
44 | var mmlen = mm.length;
45 | sumOfRows = new Array(mmlen);
46 | var sumR = 0;
47 | for (var row = 0; row < mmlen; row++) {
48 | for (var col = 0; col < mmlen; col++) {
49 | sumR += mm[row][col];
50 | totedges = totedges + (mm[row][col] / 2);
51 | }
52 | sumOfRows[row] = sumR;
53 | sumR = 0;
54 | }
55 | totedges = totedges - (2 * (mmlen - 1));
56 | return sumOfRows;
57 | }
58 |
59 | /*calculate the proportional strength of network edges (input for structural holes calculation)*/
60 | function ptiestrength(Z) {
61 | Ztrans = Z.transpose();
62 | zlen = Z.length;
63 | znum = new Array(zlen);
64 | for (var l = 0; l < zlen; l++) {
65 | znum[l] = new Array(zlen);
66 | }
67 | for (var x = 0; x < zlen; x++) {
68 | for (var y = 0; y < zlen; y++) {
69 | znum[x][y] = Z[x][y] + Ztrans[x][y];
70 | }
71 | }
72 | dtemp = rowsums(znum);
73 | P = new Array(zlen);
74 | for (var k = 0; k < zlen; k++) {
75 | P[k] = new Array(zlen);
76 | }
77 | for (var i = 0; i < zlen; i++) {
78 | for (var j = 0; j < zlen; j++) {
79 | if (dtemp[i] > 0) {
80 | P[i][j] = znum[i][j] / dtemp[i];
81 | }
82 | if (dtemp[i] <= 0) {
83 | P[i][j] = 0;
84 | }
85 | }
86 | }
87 | return P;
88 | }
89 |
90 | /*calculate the structural holes index and its components*/
91 | function structuralholes(Z) {
92 | aa = Z;
93 | var aalen = aa.length;
94 | var i = 0;
95 | P = ptiestrength(Z);
96 | var constraint = 0;
97 | var esize = 0;
98 | var csize = 0;
99 | var density = 0;
100 | var pubdensity = 0;
101 | var hierarchy = 0;
102 | var maxedges = (aalen - 1) * (aalen - 2) * 2;
103 | for (var j = 1; j < aalen; j++) {
104 | Pij = P[i][j];
105 | csize = csize + Math.pow(Pij, 2)
106 | var innersum = 0;
107 | for (var q = 1; q < aalen; q++) {
108 | if (q != j & q != i) {
109 | innersum = innersum + (P[i][q] * P[q][j])
110 | }
111 | }
112 | density = density + (2 * Pij * innersum)
113 | hierarchy = hierarchy + Math.pow(innersum, 2);
114 | esize = (aalen - 1) - ((totedges * 2) / (aalen - 1));
115 | asize = aalen - 1;
116 | }
117 | var betweenness=((aalen-1)*(aalen-2))/2;
118 | for(var i=1; i0)
142 | {
143 | betweenness=betweenness-(shared/(shared+1));
144 | }
145 | }
146 | }
147 | }
148 | csize = csize * 100;
149 | density = density * 100;
150 | pubdensity=totedges/((aalen-1)*(aalen-2))/2*100;
151 | hierarchy = hierarchy * 100;
152 | constraint = csize + density + hierarchy;
153 | var asize = aalen - 1;
154 | var Csdhe = { constraint: constraint, csize: csize, density:density, hierarchy: hierarchy, esize: esize, asize: asize, pubdensity: pubdensity, betweenness: betweenness};
155 | return Csdhe;
156 | }
157 |
158 | /*processes user's sociomatrix and presents results*/
159 | function processMatrix(matrix) {
160 | num = matrix;
161 | var ntr = num.transpose();
162 | var rsum = rowsums(num);
163 | var z = ptiestrength(num);
164 | var holes = structuralholes(num);
165 | document.getElementById('Instructions').innerHTML =
166 | ""
167 | ;
168 | document.getElementById('asize_output').innerHTML =
169 | "" + holes.asize.toString() + "" +
170 | "; This is the total number of contacts you have. It is not as informative as your unique (or 'effective') ties. The quality of your network isn't just about the total number of people you know, but the information, opportunities, and social support they provide. These factors are correlated with the structure of the ties between your contacts, not just their raw number.
"
171 | + "
"
172 | ;
173 | document.getElementById('esize_output').innerHTML =
174 | "" + holes.esize.toFixed(1) + "" +
175 | "; This is the 'effective size' of your network. Not every contact counts the same or adds the same value to your network. Some ties are 'redundant' because you both know all of the same people. They are not necessarily giving you unique information. This measure controls for that fact and gives an estimate of the unique number of clusters you are connected to.
"
176 | + "
"
177 | ;
178 | document.getElementById('constraint_output').innerHTML =
179 | "" + holes.constraint.toFixed(2) + "" +
180 | "/100; This is an index measure that describes the extent to which your network spans different groups (i.e. bridging structural holes) or is concentrated in one or two areas. As the number approaches 100, you are in a closed, or focused network. As it approaches 0, your network is more open/dispersed, indicating that you have more vision across social groups. Disconnected contacts may expose you to new information, but closure is required to develop a reputation or generate trust, among other things.
"
181 | + "
"
182 | ;
183 | document.getElementById('density_output').innerHTML =
184 | "" + holes.pubdensity.toFixed(2) + "" +
185 | "/100; This is a percentage that represents the number of ties between your contacts divided by the total number of possible ties (i.e. how 'dense' or closed your network is). As the number approaches 100, it means that all of your contacts know each other. As it approaches 0, it means all of your contacts are disconnected from each other. Having a closed network can be good or bad depending on the task and social environment.
"
186 | + "
"
187 | ;
188 | document.getElementById('hierarchy_output').innerHTML =
189 | "" + holes.hierarchy.toFixed(2) + "" +
190 | "/100; This number is a concentration index that represents how dependent you are on a few focal contacts. If all of your contacts know you through your boss or parent, then you have a 'hierarchical' network, and are dependent on them. This can work well in situations where you are considered an 'outsider' and need a strategic partner to get in the door, but is generally considered a handicap.
"
191 | + "
"
192 | ;
193 | document.getElementById('betweenness_output').innerHTML =
194 | "" + holes.betweenness.toFixed(1) + "" +
195 | "; This number represents the number of structural holes, or bridging opportunities, to which you have exclusive access. You have exclusive access to a structural hole if you lie on the shortest path between two contacts in your network. If others in your network lie on an equidistant path between the two contacts, then you each own a proportional amount. This number is typically quite large, and is presented in raw form in order to emphasize the opportunities you have to move information between people in your network who don't know each other.
"
196 | + "
"
197 | ;
198 | console.log("JSON: " + JSON.stringify(holes));
199 | new socilabAnalysisReport(holes).save().getPercentile(function (data) {
200 | $("#percentiles").show();
201 | $("#p_constraint span").text(data.constraint.toFixed(2) + "%");
202 | $("#p_hierarchy span").text(data.hierarchy.toFixed(2) + "%");
203 | $("#p_asize span").text(data.asize.toFixed(2) + "%");
204 | $("#p_esize span").text(data.esize.toFixed(2) + "%");
205 | $("#p_density span").text(data.density.toFixed(2) + "%");
206 | $("#p_csize span").text(data.csize.toFixed(2) + "%");
207 | $("#p_betweenness span").text(data.betweenness.toFixed(2) + "%");
208 |
209 | $("#p_constraint div.bar").css({width: data.constraint.toFixed(2) + "%"});
210 | $("#p_hierarchy div.bar").css({width: data.hierarchy.toFixed(2) + "%"});
211 | $("#p_asize div.bar").css({width: data.asize.toFixed(2) + "%"});
212 | $("#p_esize div.bar").css({width: data.esize.toFixed(2) + "%"});
213 | $("#p_density div.bar").css({width: data.density.toFixed(2) + "%"});
214 | $("#p_csize div.bar").css({width: data.csize.toFixed(2) + "%"});
215 | $("#p_betweenness div.bar").css({width: data.betweenness.toFixed(2) + "%"});
216 | });
217 | try {
218 | loader.hide();
219 | } catch (c) {
220 | }
221 | }
222 |
223 | /*database functionality to post metrics and receive percentiles*/
224 | var socilab = {
225 | config: {
226 | urls: {
227 | saveReport: "/service/analysis/report/save",
228 | getPercentile: "/service/analysis/report/percentile"
229 | }
230 | },
231 | constructors: {
232 | UserDataProvider: function () {
233 | var username = $("meta[name='user-name']").attr("content");
234 | var userID = $("meta[name='user-id']").attr("content");
235 | this.getID = function () {
236 | return userID;
237 | };
238 | this.getUsername = function () {
239 | return username;
240 | };
241 | },
242 | socilabDataTransport: function (url) {
243 | this.post = function (data, callback) {
244 | $.post(url, data, callback);
245 | };
246 | },
247 | socilabAnalysisReport: function (holes) {
248 | var _this = this;
249 | var userDataProvider = new socilab.constructors.UserDataProvider();
250 | var data = $.extend(holes, {
251 | user_id: userDataProvider.getID(),
252 | user_login: userDataProvider.getUsername()
253 | });
254 | this.save = function (callback) {
255 | new socilab.constructors.socilabDataTransport(socilab.config.urls.saveReport).post(data, function () {
256 | try {
257 | console.log("Data Saved!");
258 | if (typeof(callback) != 'undefined') callback();
259 | } catch (c) {
260 | }
261 | });
262 | return _this;
263 | };
264 | this.getPercentile = function (callback) {
265 | new socilab.constructors.socilabDataTransport(socilab.config.urls.getPercentile).post(data, function (data) {
266 | callback(data);
267 | });
268 | return _this;
269 | };
270 | }
271 | },
272 | init: new function () {
273 | $(function () {
274 | socilab.constructor();
275 | });
276 | },
277 | constructor: function () {
278 | window.socilabAnalysisReport = socilab.constructors.socilabAnalysisReport;
279 | }
280 | };
--------------------------------------------------------------------------------
/linkedin/socilab-linkedin.js:
--------------------------------------------------------------------------------
1 | //d3js option
2 | var enableConnectionsToSelf = false;
3 | var currentData;
4 |
5 | //utilities for d3js visualization options
6 | var byName = function (d) {
7 | return d.firstName + " " + d.lastName;
8 | };
9 | var byIndustry = function (d) {
10 | return d.industry;
11 | };
12 | var byCountryCode = function (d) {
13 | return d.location.country.code;
14 | };
15 | var byLocation = function (d) {
16 | var result = "";
17 | if (d.location.country.code !== 'undefined') {
18 | result = d.location.name + ", " + d.location.country.code;
19 | } else {
20 | result = d.location.name;
21 | }
22 | return result;
23 | };
24 | var colorization = byIndustry;
25 |
26 | //test data can be uploaded for debugging
27 | var testMode = false;
28 | if (window.location.search.indexOf("test") >= 0) {
29 | testMode = true;
30 | }
31 |
32 | Object.size = function (obj) {
33 | var size = 0, key;
34 | for (key in obj) {
35 | if (obj.hasOwnProperty(key)) size++;
36 | }
37 | return size;
38 | };
39 |
40 | //linkedin authorization for api access
41 | function onLinkedInLoad() {
42 | if (testMode) {
43 | setConnections(sampleData.connections);
44 | dataReady(sampleData);
45 | } else {
46 | IN.Event.on(IN, "auth", function () {
47 | onLinkedInLogin();
48 | });
49 | IN.Event.on(IN, "logout", function () {
50 | onLinkedInLogout();
51 | });
52 | }
53 | }
54 |
55 | function onLinkedInLogout() {
56 | setConnections({}, {total: 0});
57 | }
58 |
59 | function onLinkedInLogin() {
60 | //Get my info and also set the meta tags
61 | try{
62 | loader.show();
63 | }catch(c){}
64 | IN.API.Profile("me").result(function (result) {
65 | if(result.values.length){
66 | $("meta[name='user-name']").attr("content", result.values[0].firstName + " " +result.values[0].lastName);
67 | $("meta[name='user-id']").attr("content", result.values[0].id);
68 | }
69 | // pass the fields as individual string parameters
70 | IN.API.Connections("me")
71 | .fields("id", "firstName", "lastName", "pictureUrl", "publicProfileUrl", "industry")
72 | .result(function (result, metadata) {
73 | setConnections(result.values, metadata);
74 | });
75 | });
76 | }
77 |
78 | //process data and produce csv file of adjacency matrix for user download
79 | function dataReady(resultData) {
80 | console.log(JSON.stringify(resultData));
81 | console.log(JSON.stringify(resultData.connections[2].firstName + " " + resultData.connections[2].lastName));
82 | var myData='"",'+ '"Me",';
83 | console.log(resultData.connections.length);
84 | var nverts=resultData.connections.length+1;
85 | var myPajData='*Vertices '+ nverts.toString() + "\n" + '1 "Me"' + "\n";
86 | for (var i=0; i";
113 | var csvContent = myData;
114 | var encodedUri = encodeURI(csvContent);
115 | var csvlink = document.createElement("a");
116 | csvlink.setAttribute("href", "data:text/csv;charset=utf-8,\uFEFF" + encodedUri);
117 | csvlink.setAttribute("download","li-data.csv");
118 | csvlink.textContent = '[CSV adjacency matrix]';
119 | document.getElementById('download').appendChild(csvlink);
120 | var pajData = myPajData;
121 | var encodedUri2 = encodeURI(pajData);
122 | var pajlink = document.createElement("a");
123 | pajlink.setAttribute("href", "data:text/net;charset=utf-8,\uFEFF" + encodedUri2);
124 | pajlink.setAttribute("download","li-data.net");
125 | pajlink.textContent = ' [Pajek .net edge list]';
126 | document.getElementById('download').appendChild(pajlink);
127 |
128 | currentData = resultData;
129 | processMatrix(resultData.matrix);
130 | visualizeConnections(resultData, enableConnectionsToSelf, colorization);
131 | }
132 |
133 |
134 | //interface with linkedin api to pull mutual connections data of contacts for ego network
135 | function setConnections(connections) {
136 | var publicConnections = connections.filter(function (d) {
137 | return d.id != "private";
138 | });
139 |
140 | if (testMode) {
141 | return;
142 | }
143 |
144 | var connectionLimit = 499; //this is the max, as per linkedin api - after this many calls that user gets throttled/capped for the day until midnight UTC time
145 |
146 | var connectsLength = Math.min(publicConnections.length, connectionLimit);
147 | $("#message").text((connectsLength < publicConnections.length) ? "Due to LinkedIn API limitations - we can only use " + connectionLimit + " of your contacts" : "");
148 |
149 | var mutualconnects;
150 | var connectionIdIndexMap = {};
151 | publicConnections.forEach(function (connection, connectionIndex) {
152 | connectionIdIndexMap[connection.id] = connectionIndex;
153 | });
154 | var getConnectionIndexById = function (d) {
155 | return connectionIdIndexMap[d.id];
156 | };
157 |
158 | var errorCount = 0;
159 | var callsMade = 0;
160 |
161 | async.map(publicConnections.slice(0, connectsLength), function (connection, callback) {
162 | var arr = [];
163 |
164 | function fetch(offset, callback) {
165 | callsMade++;
166 | console.log("[Paginated] Making call #" + callsMade);
167 | IN.API.Raw(
168 | "/people/" + connection.id +
169 | "/relation-to-viewer/related-connections" +
170 | "?format=json" +
171 | "&start=" + offset +
172 | '&count=' + 99
173 | )
174 | .result(function (result) {
175 | arr.push.apply(arr, (result.values ? result.values.map(getConnectionIndexById).
176 | filter(function (d) {
177 | return d != null && d <= connectsLength;
178 | }) : []) || []);
179 | if (result.values && result.values.length) fetch(offset + result.values.length + 1, callback);
180 | else callback(null, arr);
181 | })
182 | .error(function (error) {
183 | console.log(error);
184 | errorCount++;
185 | callback(null, arr);
186 | });
187 | }
188 |
189 | fetch(0, callback);
190 |
191 | }, function (err, results) {
192 | mutualconnects = results;
193 | console.log("All results arrived");
194 | if (errorCount > 0) {
195 | console.warn("Querying contacts has produced " + errorCount + " error" + (errorCount == 1 ? "" : "s"));
196 | }
197 |
198 | var sociomat = mutualConnectsToMatrix(mutualconnects);
199 | var reducedSociomat = mutualConnectsToReducedMatrix(mutualconnects);
200 | var resultData = {
201 | connections: connections,
202 | publicConnections: publicConnections,
203 | matrix: sociomat,
204 | reducedMatrix: reducedSociomat
205 | };
206 | console.log("SOCIOMAT", sociomat);
207 | try {
208 | console.log('saving to local storage');
209 | localStorage.setItem(inId, JSON.stringify(resultData));
210 | } catch (c) {
211 |
212 | }
213 | dataReady(resultData);
214 | });
215 | }
216 |
217 | //converts mutual connections array to adjacency matrix
218 | function mutualConnectsToMatrix(mutualconnects) {
219 | var len = mutualconnects.length;
220 | var result = [];
221 |
222 | for (var i = 0; i < len + 1; i++) {
223 | result.push(new Array(len + 1));
224 | result[i][i] = 0;
225 | for (var j = 0; j < i; j++) {
226 | var value = (i == 0 || j == 0 || (mutualconnects[i - 1] && mutualconnects[i - 1].indexOf(j - 1) >= 0)) ? 1 : 0;
227 | result[i][j] = result[j][i] = value;
228 | }
229 | }
230 |
231 | return result;
232 | }
233 |
234 | //reduces network by removing ego node - used in the 'disable links to self' d3js option to
235 | //make internal structure of contacts more visible.
236 | function mutualConnectsToReducedMatrix(mutualconnects) {
237 | var len = mutualconnects.length;
238 | var result = [];
239 |
240 | for (var i = 0; i < len; i++) {
241 | result.push(new Array(len));
242 | result[i][i] = 0;
243 | for (var j = 0; j < i; j++) {
244 | var value = 0;
245 | if (mutualconnects[i] && mutualconnects[i].indexOf(j) >= 0) {
246 | value = 1;
247 | }
248 | result[i][j] = result[j][i] = value;
249 | }
250 | }
251 |
252 | return result;
253 | }
254 |
255 |
256 | $(function () {
257 | $("input[name=radio1]").click(function () {
258 | switch (this.value) {
259 | case "industry":
260 | colorization = byIndustry;
261 | break;
262 | case "name":
263 | colorization = byName;
264 | break;
265 | case "countryCode":
266 | colorization = byCountryCode;
267 | break;
268 | case "location": colorization = byLocation;
269 | break;
270 | default:
271 | colorization = byIndustry;
272 | }
273 | visualizeConnections(currentData, enableConnectionsToSelf, colorization);
274 | });
275 |
276 | $("input[name=radio2]").click(function () {
277 | enableConnectionsToSelf = (this.value == "self");
278 | visualizeConnections(currentData, enableConnectionsToSelf, colorization);
279 | });
280 | });
281 |
--------------------------------------------------------------------------------