├── .circleci
└── config.yml
├── .gitignore
├── .pylintrc
├── LICENSE
├── Makefile
├── README.md
├── docs
├── Makefile
├── requirements.txt
└── source
│ ├── _static
│ └── img
│ │ ├── header.png
│ │ ├── heatmap_example.png
│ │ └── markov_chain.png
│ ├── api
│ ├── dummy.rst
│ ├── index.rst
│ ├── models.rst
│ ├── preprocessing.rst
│ └── viz.rst
│ ├── conf.py
│ ├── index.rst
│ └── usage.rst
├── environment.yml
├── markovclick
├── __init__.py
├── __version__.py
├── dummy.py
├── models.py
├── preprocessing.py
├── utils
│ ├── __init__.py
│ └── helpers.py
└── viz.py
├── requirements.txt
├── setup.py
├── tests
├── __init__.py
├── test_dummy.py
├── test_models.py
└── test_preprocessing.py
└── tox.ini
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | # Python CircleCI 2.0 configuration file
2 | #
3 | # Check https://circleci.com/docs/2.0/language-python/ for more details
4 | #
5 | version: 2
6 | jobs:
7 | build:
8 | docker:
9 | - image: circleci/python:3.6.1
10 |
11 | working_directory: ~/repo
12 |
13 | steps:
14 | - checkout
15 |
16 | # Download and cache dependencies
17 | - restore_cache:
18 | keys:
19 | - v1-dependencies-{{ checksum "requirements.txt" }}
20 | # fallback to using the latest cache if no exact match is found
21 | - v1-dependencies-
22 |
23 | - run:
24 | name: install dependencies
25 | command: |
26 | python3 -m venv venv
27 | . venv/bin/activate
28 | pip install -r requirements.txt
29 | pip install codecov
30 |
31 | - save_cache:
32 | paths:
33 | - ./venv
34 | key: v1-dependencies-{{ checksum "requirements.txt" }}
35 |
36 | - run:
37 | environment:
38 | CODECOV_TOKEN: 01867e2e-67ff-44e4-9ac0-1cc37a4375de
39 | name: run tests
40 | command: |
41 | . venv/bin/activate
42 | pytest
43 |
44 | - store_artifacts:
45 | path: test-reports
46 | destination: test-reports
47 |
48 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Python ###
2 | # Byte-compiled / optimized / DLL files
3 | __pycache__/
4 | *.py[cod]
5 | *$py.class
6 |
7 | # C extensions
8 | *.so
9 |
10 | # Distribution / packaging
11 | .vscode/
12 | .Python
13 | build/
14 | develop-eggs/
15 | dist/
16 | downloads/
17 | notebooks/
18 | data/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | wheels/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 | MANIFEST
31 |
32 | # PyInstaller
33 | # Usually these files are written by a python script from a template
34 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
35 | *.manifest
36 | *.spec
37 |
38 | # Installer logs
39 | pip-log.txt
40 | pip-delete-this-directory.txt
41 |
42 | # Unit test / coverage reports
43 | htmlcov/
44 | .tox/
45 | .nox/
46 | .coverage
47 | .coverage.*
48 | .cache
49 | nosetests.xml
50 | coverage.xml
51 | *.cover
52 | .hypothesis/
53 | .pytest_cache/
54 |
55 | # Translations
56 | *.mo
57 | *.pot
58 |
59 | # Django stuff:
60 | *.log
61 | local_settings.py
62 | db.sqlite3
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # R stuff
85 | .DS_Store
86 |
87 | # pyenv
88 | .python-version
89 |
90 | # celery beat schedule file
91 | celerybeat-schedule
92 |
93 | # SageMath parsed files
94 | *.sage.py
95 |
96 | # Environments
97 | .env
98 | .envrc
99 | .venv
100 | env/
101 | venv/
102 | ENV/
103 | env.bak/
104 | venv.bak/
105 |
106 | # Spyder project settings
107 | .spyderproject
108 | .spyproject
109 |
110 | # Rope project settings
111 | .ropeproject
112 |
113 | # mkdocs documentation
114 | /site
115 |
116 | # mypy
117 | .mypy_cache/
118 | .dmypy.json
119 | dmypy.json
120 |
121 | ### Python Patch ###
122 | .venv/
123 |
124 | ### Python.VirtualEnv Stack ###
125 | # Virtualenv
126 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
127 | [Bb]in
128 | [Ii]nclude
129 | [Ll]ib
130 | [Ll]ib64
131 | [Ll]ocal
132 | [Ss]cripts
133 | pyvenv.cfg
134 | pip-selfcheck.json
135 |
136 |
137 | # End of https://www.gitignore.io/api/python
138 |
--------------------------------------------------------------------------------
/.pylintrc:
--------------------------------------------------------------------------------
1 | [MASTER]
2 |
3 | # A comma-separated list of package or module names from where C extensions may
4 | # be loaded. Extensions are loading into the active Python interpreter and may
5 | # run arbitrary code.
6 | extension-pkg-whitelist=
7 |
8 | # Add files or directories to the blacklist. They should be base names, not
9 | # paths.
10 | ignore=CVS
11 |
12 | # Add files or directories matching the regex patterns to the blacklist. The
13 | # regex matches against base names, not paths.
14 | ignore-patterns=
15 |
16 | # Python code to execute, usually for sys.path manipulation such as
17 | # pygtk.require().
18 | #init-hook=
19 |
20 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
21 | # number of processors available to use.
22 | jobs=1
23 |
24 | # Control the amount of potential inferred values when inferring a single
25 | # object. This can help the performance when dealing with large functions or
26 | # complex, nested conditions.
27 | limit-inference-results=100
28 |
29 | # List of plugins (as comma separated values of python modules names) to load,
30 | # usually to register additional checkers.
31 | load-plugins=
32 |
33 | # Pickle collected data for later comparisons.
34 | persistent=yes
35 |
36 | # Specify a configuration file.
37 | #rcfile=
38 |
39 | # When enabled, pylint would attempt to guess common misconfiguration and emit
40 | # user-friendly hints instead of false-positive error messages.
41 | suggestion-mode=yes
42 |
43 | # Allow loading of arbitrary C extensions. Extensions are imported into the
44 | # active Python interpreter and may run arbitrary code.
45 | unsafe-load-any-extension=no
46 |
47 |
48 | [MESSAGES CONTROL]
49 |
50 | # Only show warnings with the listed confidence levels. Leave empty to show
51 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
52 | confidence=
53 |
54 | # Disable the message, report, category or checker with the given id(s). You
55 | # can either give multiple identifiers separated by comma (,) or put this
56 | # option multiple times (only on the command line, not in the configuration
57 | # file where it should appear only once). You can also use "--disable=all" to
58 | # disable everything first and then reenable specific checks. For example, if
59 | # you want to run only the similarities checker, you can use "--disable=all
60 | # --enable=similarities". If you want to run only the classes checker, but have
61 | # no Warning level messages displayed, use "--disable=all --enable=classes
62 | # --disable=W".
63 | disable=print-statement,
64 | parameter-unpacking,
65 | unpacking-in-except,
66 | old-raise-syntax,
67 | backtick,
68 | long-suffix,
69 | old-ne-operator,
70 | old-octal-literal,
71 | import-star-module-level,
72 | non-ascii-bytes-literal,
73 | raw-checker-failed,
74 | bad-inline-option,
75 | locally-disabled,
76 | locally-enabled,
77 | file-ignored,
78 | suppressed-message,
79 | useless-suppression,
80 | deprecated-pragma,
81 | use-symbolic-message-instead,
82 | apply-builtin,
83 | basestring-builtin,
84 | buffer-builtin,
85 | cmp-builtin,
86 | coerce-builtin,
87 | execfile-builtin,
88 | file-builtin,
89 | long-builtin,
90 | raw_input-builtin,
91 | reduce-builtin,
92 | standarderror-builtin,
93 | unicode-builtin,
94 | xrange-builtin,
95 | coerce-method,
96 | delslice-method,
97 | getslice-method,
98 | setslice-method,
99 | no-absolute-import,
100 | old-division,
101 | dict-iter-method,
102 | dict-view-method,
103 | next-method-called,
104 | metaclass-assignment,
105 | indexing-exception,
106 | raising-string,
107 | reload-builtin,
108 | oct-method,
109 | hex-method,
110 | nonzero-method,
111 | cmp-method,
112 | input-builtin,
113 | round-builtin,
114 | intern-builtin,
115 | unichr-builtin,
116 | map-builtin-not-iterating,
117 | zip-builtin-not-iterating,
118 | range-builtin-not-iterating,
119 | filter-builtin-not-iterating,
120 | using-cmp-argument,
121 | eq-without-hash,
122 | div-method,
123 | idiv-method,
124 | rdiv-method,
125 | exception-message-attribute,
126 | invalid-str-codec,
127 | sys-max-int,
128 | bad-python3-import,
129 | deprecated-string-function,
130 | deprecated-str-translate-call,
131 | deprecated-itertools-function,
132 | deprecated-types-field,
133 | next-method-defined,
134 | dict-items-not-iterating,
135 | dict-keys-not-iterating,
136 | dict-values-not-iterating,
137 | deprecated-operator-function,
138 | deprecated-urllib-function,
139 | xreadlines-attribute,
140 | deprecated-sys-function,
141 | exception-escape,
142 | comprehension-escape
143 |
144 | # Enable the message, report, category or checker with the given id(s). You can
145 | # either give multiple identifier separated by comma (,) or put this option
146 | # multiple time (only on the command line, not in the configuration file where
147 | # it should appear only once). See also the "--disable" option for examples.
148 | enable=c-extension-no-member
149 |
150 |
151 | [REPORTS]
152 |
153 | # Python expression which should return a note less than 10 (10 is the highest
154 | # note). You have access to the variables errors warning, statement which
155 | # respectively contain the number of errors / warnings messages and the total
156 | # number of statements analyzed. This is used by the global evaluation report
157 | # (RP0004).
158 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
159 |
160 | # Template used to display messages. This is a python new-style format string
161 | # used to format the message information. See doc for all details.
162 | #msg-template=
163 |
164 | # Set the output format. Available formats are text, parseable, colorized, json
165 | # and msvs (visual studio). You can also give a reporter class, e.g.
166 | # mypackage.mymodule.MyReporterClass.
167 | output-format=text
168 |
169 | # Tells whether to display a full report or only the messages.
170 | reports=no
171 |
172 | # Activate the evaluation score.
173 | score=yes
174 |
175 |
176 | [REFACTORING]
177 |
178 | # Maximum number of nested blocks for function / method body
179 | max-nested-blocks=5
180 |
181 | # Complete name of functions that never returns. When checking for
182 | # inconsistent-return-statements if a never returning function is called then
183 | # it will be considered as an explicit return statement and no message will be
184 | # printed.
185 | never-returning-functions=sys.exit
186 |
187 |
188 | [LOGGING]
189 |
190 | # Logging modules to check that the string format arguments are in logging
191 | # function parameter format.
192 | logging-modules=logging
193 |
194 |
195 | [SPELLING]
196 |
197 | # Limits count of emitted suggestions for spelling mistakes.
198 | max-spelling-suggestions=4
199 |
200 | # Spelling dictionary name. Available dictionaries: none. To make it working
201 | # install python-enchant package..
202 | spelling-dict=
203 |
204 | # List of comma separated words that should not be checked.
205 | spelling-ignore-words=
206 |
207 | # A path to a file that contains private dictionary; one word per line.
208 | spelling-private-dict-file=
209 |
210 | # Tells whether to store unknown words to indicated private dictionary in
211 | # --spelling-private-dict-file option instead of raising a message.
212 | spelling-store-unknown-words=no
213 |
214 |
215 | [MISCELLANEOUS]
216 |
217 | # List of note tags to take in consideration, separated by a comma.
218 | notes=FIXME,
219 | XXX,
220 | TODO
221 |
222 |
223 | [TYPECHECK]
224 |
225 | # List of decorators that produce context managers, such as
226 | # contextlib.contextmanager. Add to this list to register other decorators that
227 | # produce valid context managers.
228 | contextmanager-decorators=contextlib.contextmanager
229 |
230 | # List of members which are set dynamically and missed by pylint inference
231 | # system, and so shouldn't trigger E1101 when accessed. Python regular
232 | # expressions are accepted.
233 | generated-members=
234 |
235 | # Tells whether missing members accessed in mixin class should be ignored. A
236 | # mixin class is detected if its name ends with "mixin" (case insensitive).
237 | ignore-mixin-members=yes
238 |
239 | # Tells whether to warn about missing members when the owner of the attribute
240 | # is inferred to be None.
241 | ignore-none=yes
242 |
243 | # This flag controls whether pylint should warn about no-member and similar
244 | # checks whenever an opaque object is returned when inferring. The inference
245 | # can return multiple potential results while evaluating a Python object, but
246 | # some branches might not be evaluated, which results in partial inference. In
247 | # that case, it might be useful to still emit no-member and other checks for
248 | # the rest of the inferred objects.
249 | ignore-on-opaque-inference=yes
250 |
251 | # List of class names for which member attributes should not be checked (useful
252 | # for classes with dynamically set attributes). This supports the use of
253 | # qualified names.
254 | ignored-classes=optparse.Values,thread._local,_thread._local
255 |
256 | # List of module names for which member attributes should not be checked
257 | # (useful for modules/projects where namespaces are manipulated during runtime
258 | # and thus existing member attributes cannot be deduced by static analysis. It
259 | # supports qualified module names, as well as Unix pattern matching.
260 | ignored-modules=
261 |
262 | # Show a hint with possible names when a member name was not found. The aspect
263 | # of finding the hint is based on edit distance.
264 | missing-member-hint=yes
265 |
266 | # The minimum edit distance a name should have in order to be considered a
267 | # similar match for a missing member name.
268 | missing-member-hint-distance=1
269 |
270 | # The total number of similar names that should be taken in consideration when
271 | # showing a hint for a missing member.
272 | missing-member-max-choices=1
273 |
274 |
275 | [VARIABLES]
276 |
277 | # List of additional names supposed to be defined in builtins. Remember that
278 | # you should avoid to define new builtins when possible.
279 | additional-builtins=
280 |
281 | # Tells whether unused global variables should be treated as a violation.
282 | allow-global-unused-variables=yes
283 |
284 | # List of strings which can identify a callback function by name. A callback
285 | # name must start or end with one of those strings.
286 | callbacks=cb_,
287 | _cb
288 |
289 | # A regular expression matching the name of dummy variables (i.e. expected to
290 | # not be used).
291 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
292 |
293 | # Argument names that match this expression will be ignored. Default to name
294 | # with leading underscore.
295 | ignored-argument-names=_.*|^ignored_|^unused_
296 |
297 | # Tells whether we should check for unused import in __init__ files.
298 | init-import=no
299 |
300 | # List of qualified module names which can have objects that can redefine
301 | # builtins.
302 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
303 |
304 |
305 | [FORMAT]
306 |
307 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
308 | expected-line-ending-format=
309 |
310 | # Regexp for a line that is allowed to be longer than the limit.
311 | ignore-long-lines=^\s*(# )??$
312 |
313 | # Number of spaces of indent required inside a hanging or continued line.
314 | indent-after-paren=4
315 |
316 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
317 | # tab).
318 | indent-string=' '
319 |
320 | # Maximum number of characters on a single line.
321 | max-line-length=150
322 |
323 | # Maximum number of lines in a module.
324 | max-module-lines=1000
325 |
326 | # List of optional constructs for which whitespace checking is disabled. `dict-
327 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
328 | # `trailing-comma` allows a space between comma and closing bracket: (a, ).
329 | # `empty-line` allows space-only lines.
330 | no-space-check=trailing-comma,
331 | dict-separator
332 |
333 | # Allow the body of a class to be on the same line as the declaration if body
334 | # contains single statement.
335 | single-line-class-stmt=no
336 |
337 | # Allow the body of an if to be on the same line as the test if there is no
338 | # else.
339 | single-line-if-stmt=no
340 |
341 | # Good variable names which should always be accepted, separated by a comma
342 | good-names=i,j,k,ex,Run,_,pk,x,y
343 |
344 | [SIMILARITIES]
345 |
346 | # Ignore comments when computing similarities.
347 | ignore-comments=yes
348 |
349 | # Ignore docstrings when computing similarities.
350 | ignore-docstrings=yes
351 |
352 | # Ignore imports when computing similarities.
353 | ignore-imports=no
354 |
355 | # Minimum lines number of a similarity.
356 | min-similarity-lines=4
357 |
358 |
359 | [BASIC]
360 |
361 | # Naming style matching correct argument names.
362 | argument-naming-style=any
363 |
364 | # Regular expression matching correct argument names. Overrides argument-
365 | # naming-style.
366 | #argument-rgx=
367 |
368 | # Naming style matching correct attribute names.
369 | attr-naming-style=snake_case
370 |
371 | # Regular expression matching correct attribute names. Overrides attr-naming-
372 | # style.
373 | #attr-rgx=
374 |
375 | # Bad variable names which should always be refused, separated by a comma.
376 | bad-names=foo,
377 | bar,
378 | baz,
379 | toto,
380 | tutu,
381 | tata
382 |
383 | # Naming style matching correct class attribute names.
384 | class-attribute-naming-style=any
385 |
386 | # Regular expression matching correct class attribute names. Overrides class-
387 | # attribute-naming-style.
388 | #class-attribute-rgx=
389 |
390 | # Naming style matching correct class names.
391 | class-naming-style=PascalCase
392 |
393 | # Regular expression matching correct class names. Overrides class-naming-
394 | # style.
395 | #class-rgx=
396 |
397 | # Naming style matching correct constant names.
398 | const-naming-style=UPPER_CASE
399 |
400 | # Regular expression matching correct constant names. Overrides const-naming-
401 | # style.
402 | #const-rgx=
403 |
404 | # Minimum line length for functions/classes that require docstrings, shorter
405 | # ones are exempt.
406 | docstring-min-length=-1
407 |
408 | # Naming style matching correct function names.
409 | function-naming-style=snake_case
410 |
411 | # Regular expression matching correct function names. Overrides function-
412 | # naming-style.
413 | #function-rgx=
414 |
415 | # Good variable names which should always be accepted, separated by a comma.
416 | good-names=i,
417 | j,
418 | k,
419 | ex,
420 | Run,
421 | _
422 |
423 | # Include a hint for the correct naming format with invalid-name.
424 | include-naming-hint=no
425 |
426 | # Naming style matching correct inline iteration names.
427 | inlinevar-naming-style=any
428 |
429 | # Regular expression matching correct inline iteration names. Overrides
430 | # inlinevar-naming-style.
431 | #inlinevar-rgx=
432 |
433 | # Naming style matching correct method names.
434 | method-naming-style=snake_case
435 |
436 | # Regular expression matching correct method names. Overrides method-naming-
437 | # style.
438 | #method-rgx=
439 |
440 | # Naming style matching correct module names.
441 | module-naming-style=snake_case
442 |
443 | # Regular expression matching correct module names. Overrides module-naming-
444 | # style.
445 | #module-rgx=
446 |
447 | # Colon-delimited sets of names that determine each other's naming style when
448 | # the name regexes allow several styles.
449 | name-group=
450 |
451 | # Regular expression which should only match function or class names that do
452 | # not require a docstring.
453 | no-docstring-rgx=^_
454 |
455 | # List of decorators that produce properties, such as abc.abstractproperty. Add
456 | # to this list to register other decorators that produce valid properties.
457 | # These decorators are taken in consideration only for invalid-name.
458 | property-classes=abc.abstractproperty
459 |
460 | # Naming style matching correct variable names.
461 | variable-naming-style=snake_case
462 |
463 | # Regular expression matching correct variable names. Overrides variable-
464 | # naming-style.
465 | #variable-rgx=
466 |
467 |
468 | [IMPORTS]
469 |
470 | # Allow wildcard imports from modules that define __all__.
471 | allow-wildcard-with-all=no
472 |
473 | # Analyse import fallback blocks. This can be used to support both Python 2 and
474 | # 3 compatible code, which means that the block might have code that exists
475 | # only in one or another interpreter, leading to false positives when analysed.
476 | analyse-fallback-blocks=no
477 |
478 | # Deprecated modules which should not be used, separated by a comma.
479 | deprecated-modules=optparse,tkinter.tix
480 |
481 | # Create a graph of external dependencies in the given file (report RP0402 must
482 | # not be disabled).
483 | ext-import-graph=
484 |
485 | # Create a graph of every (i.e. internal and external) dependencies in the
486 | # given file (report RP0402 must not be disabled).
487 | import-graph=
488 |
489 | # Create a graph of internal dependencies in the given file (report RP0402 must
490 | # not be disabled).
491 | int-import-graph=
492 |
493 | # Force import order to recognize a module as part of the standard
494 | # compatibility libraries.
495 | known-standard-library=
496 |
497 | # Force import order to recognize a module as part of a third party library.
498 | known-third-party=enchant
499 |
500 |
501 | [CLASSES]
502 |
503 | # List of method names used to declare (i.e. assign) instance attributes.
504 | defining-attr-methods=__init__,
505 | __new__,
506 | setUp
507 |
508 | # List of member names, which should be excluded from the protected access
509 | # warning.
510 | exclude-protected=_asdict,
511 | _fields,
512 | _replace,
513 | _source,
514 | _make
515 |
516 | # List of valid names for the first argument in a class method.
517 | valid-classmethod-first-arg=cls
518 |
519 | # List of valid names for the first argument in a metaclass class method.
520 | valid-metaclass-classmethod-first-arg=cls
521 |
522 |
523 | [DESIGN]
524 |
525 | # Maximum number of arguments for function / method.
526 | max-args=5
527 |
528 | # Maximum number of attributes for a class (see R0902).
529 | max-attributes=7
530 |
531 | # Maximum number of boolean expressions in an if statement.
532 | max-bool-expr=5
533 |
534 | # Maximum number of branch for function / method body.
535 | max-branches=12
536 |
537 | # Maximum number of locals for function / method body.
538 | max-locals=15
539 |
540 | # Maximum number of parents for a class (see R0901).
541 | max-parents=7
542 |
543 | # Maximum number of public methods for a class (see R0904).
544 | max-public-methods=20
545 |
546 | # Maximum number of return / yield for function / method body.
547 | max-returns=6
548 |
549 | # Maximum number of statements in function / method body.
550 | max-statements=50
551 |
552 | # Minimum number of public methods for a class (see R0903).
553 | min-public-methods=2
554 |
555 |
556 | [EXCEPTIONS]
557 |
558 | # Exceptions that will emit a warning when being caught. Defaults to
559 | # "Exception".
560 | overgeneral-exceptions=Exception
561 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | python_version_major := $(word 1,${python_version_full})
2 |
3 | .PHONY: build_docs serve_docs
4 |
5 | init:
6 | pip install -r requirements.txt
7 | test:
8 | pytest
9 | build_docs:
10 | $(MAKE) -C docs html
11 | serve_docs:
12 | ifeq (python_version_major, 2)
13 | cd docs/_build/html && python -m SimpleHTTPServer
14 | else
15 | cd docs/_build/html && python -m http.server
16 | endif
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # markovclick
4 |
5 | [](https://circleci.com/gh/ismailuddin/markovclick/tree/master)
6 | [](https://www.gnu.org/licenses/gpl-3.0)
7 | [](https://markovclick.readthedocs.io/en/latest/?badge=latest)
8 |
9 |
10 | Python implementation of the R package [clickstream](https://cran.r-project.org/web/packages/clickstream/index.html) which models website clickstreams as Markov chains.
11 |
12 | ---
13 |
14 | `markovclick` allows you to model clickstream data from websites as Markov chains, which can then be used to predict the next likely click on a website for a user, given their history and current state.
15 |
16 | ## Requirements
17 | * Python 3.X
18 | * numpy
19 | * matplotlib
20 | * seaborn (Recommended)
21 | * pandas
22 |
23 | ## Installation
24 | ```
25 | python setup.py install
26 | ```
27 | or
28 |
29 | ```
30 | pip install markovclick
31 | ```
32 |
33 | ## Tests
34 | Tests can be run using the `pytest` command from the root directory.
35 |
36 | ## Documentation
37 | Documentation can be viewed at [https://markovclick.readthedocs.io/](https://markovclick.readthedocs.io/).
38 | To build the documentation, run `make html` inside the `/docs` directory.
39 |
40 | ## Usage
41 |
42 | ### Quick start
43 | To start using the package without any data, `markovclick` can produce dummy data for you to experiment with:
44 |
45 | ```python
46 | from markovclick import dummy
47 | clickstream = dummy.gen_random_clickstream(n_of_streams=100, n_of_pages=12)
48 | ```
49 |
50 |
51 | ### Terminology
52 | In the context of this package, streams refer to a series of clicks belonging to a given user. The time difference between clicks is defined by the user when assembling these streams, but is typically taken to be 30 minutes in the industry.
53 |
54 | The pages refer to the individual clicks of the user, and thus the pages they visit. Rather than storing the entire URL of the page the user visits, it is better to encode pages using a simple code such as `PXX` where `X` can be any number. This strategy can be used to group similar pages under the same code, as modelling them as separate pages is sometimes not useful leading to an excessively large probability matrix.
55 |
56 |
57 | #### Building Markov chains
58 | To build a Markov chain from the dummy data:
59 |
60 | ```python
61 | from markovclick.models import MarkovClickstream
62 | m = MarkovClickstream(clickstream)
63 | ```
64 |
65 | The instance `m` of the `MarkovClickstream` class provides access the class's attributes such as the probability matrix (`m.prob_matrix`) used to model the Markov chain, and the list of unique pages (`m.pages`) featuring in the clickstream.
66 |
67 | ### PageRank score
68 | The PageRank score for each page in the clickstream can also be calculated as follows:
69 |
70 | ```python
71 | digraph, pagerank = m.calculate_pagerank(max_nodes=2)
72 | ```
73 |
74 | | Argument | Type | Description |
75 | | -------- | ---- | ------------|
76 | | max_nodes | int | (Optional, defaults to 2). The number of pages to include as nodes linking to each node when generating the graph. Selected in order of most probable transition from Markov chain |
77 | pr_kwargs | dict | (Optional, defaults to `{}`). Dictionary to pass arguments to `networkx.linkanalysis.pagerank()` function. See details [here](https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.link_analysis.pagerank_alg.pagerank.html).
78 |
79 | The `digraph` object holds the `networkx` `DiGraph` class which was used to calculate the PageRank score, and the `pagerank` object is a dictionary of PageRank scores for each page in the network.
80 |
81 | ### Visualisation
82 |
83 | #### Visualising as a heatmap
84 |
85 | The probability matrix can be visualised as a heatmap as follows:
86 |
87 | ```python
88 | sns.heatmap(m.prob_matrix, xticklabels=m.pages, yticklabels=m.pages)
89 | ```
90 |
91 |
92 |
93 |
94 | #### Visualising the Markov chain
95 |
96 | A Markov chain can be thought of as a graph of nodes and edges, with the edges representing the transitions from each state. `markovclick` provides a wrapper function around the `graphviz` package to visualise the Markov chain in this manner.
97 |
98 | ```python
99 | from markovclick.viz import visualise_markov_chain
100 | graph = visualise_markov_chain(m)
101 | ```
102 |
103 | The function `visualise_markov_chain()` returns a `Digraph` object, which can be viewed directly inside a Jupyter notebook by simply calling the reference to the object returned. It can also be outputted to a PDF file by calling the `render()` function on the object.
104 |
105 |
106 |
107 | In the graph produced, the nodes representing the individual pages are shown in green, and up to 3 edges from each node are rendered. The first edge is in a thick blue arrow, depicting the most likely transition from this page / state to the next page / state. The second edge depicted by a thinner blue arrow, depicts the second most likely transition from this state. Finally, a third edge is shown that depicts the transition from this page / state back to itself (light grey). This edge is only shown if the the two most likely transitions are not already to itself. For all transitions, the probability is shown next to the edge (arrow).
108 |
109 |
110 |
111 | ### Clickstream processing with `markovclick.preprocessing`
112 |
113 | `markovclick` provides functions to process clickstream data such as server logs, which contain unique identifiers such as cookie IDs associated with each click. This allows clicks to be aggregated into groups, whereby clicks from the same browser (identified by the unique identifier) are grouped such that the difference between individual clicks does not exceed the maximum session timeout (typically taken to be 30 minutes).
114 |
115 | #### Sessionise clickstream data
116 |
117 | ##### `Sessionise`
118 |
119 | To sessionise clickstream data, the following code can be used that require a `pandas` DataFrame object.
120 |
121 | ```python
122 | from markovclick.preprocessing import Sessionise
123 | sessioniser = Sessionise(df, unique_id_col='cookie_id',
124 | datetime_col='timestamp', session_timeout=30)
125 | ```
126 |
127 | ##### Arguments
128 |
129 | | Argument | Type | Description |
130 | | ----------------- | --------- | ------------------------------------------------------------ |
131 | | `df` | DataFrame | `pandas` DataFrame object containing clickstream data. Must contain atleast a timestamp column, unique identifier column such as cookie ID. |
132 | | `unique_id_col` | String | Column name of unique identifier, e.g. `cookie_id` |
133 | | `datetime_col` | String | Column name of timestamp column. |
134 | | `session_timeout` | Integer | Maximum time in minutes after which a session is broken. |
135 |
136 | ##### `Sessionise.assign_sessions()`
137 |
138 | With a `Sessionise` object instantiated, the `assign_sessions()` function can then be called. This function supports multi-processing, enabling you the split job into multiple processes to take advantage of a multi-core CPU.
139 |
140 | ```python
141 | sessioniser.assign_sessions(n_jobs=2)
142 | ```
143 |
144 | ##### Arguments
145 |
146 | | Argument | Type | Description |
147 | | -------- | ------- | ------------------------------------------------------------ |
148 | | `n_jobs` | Integer | Number of processes to spawn to enable parallel processing. If set to `1`, no splitting occurs. |
149 |
150 | The `assign_sessions()` function returns the DataFrame, with an additional column added storing the unique identifier for the session. Rows of the DataFrame can then be grouped using this column.
151 |
152 | To use our new sessionized data frame with a Markov model, we can simply:
153 |
154 | ```python
155 | sessioniser = Sessionise(df,
156 | unique_id_col='cookie_id',
157 | datetime_col='timestamp',
158 | session_timeout=30)
159 |
160 | sess_df = sessioniser.assign_sessions(n_jobs=2)
161 |
162 | df_grouped = sess_df.groupby(['session_uuid'])['page_category'].apply(list)
163 |
164 | m = MarkovClickstream(df_grouped)
165 | ```
166 |
167 | Where `page_category` is the grouping information for your clickstream.
168 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | SPHINXPROJ = markovclick
8 | SOURCEDIR = source
9 | BUILDDIR = build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
--------------------------------------------------------------------------------
/docs/requirements.txt:
--------------------------------------------------------------------------------
1 | markovclick
2 | tqdm
3 | graphviz
4 | networkx
--------------------------------------------------------------------------------
/docs/source/_static/img/header.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ismailuddin/markovclick/48def4c0ce0ef5f8263da15e1dbbc1d2eb486e8c/docs/source/_static/img/header.png
--------------------------------------------------------------------------------
/docs/source/_static/img/heatmap_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ismailuddin/markovclick/48def4c0ce0ef5f8263da15e1dbbc1d2eb486e8c/docs/source/_static/img/heatmap_example.png
--------------------------------------------------------------------------------
/docs/source/_static/img/markov_chain.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ismailuddin/markovclick/48def4c0ce0ef5f8263da15e1dbbc1d2eb486e8c/docs/source/_static/img/markov_chain.png
--------------------------------------------------------------------------------
/docs/source/api/dummy.rst:
--------------------------------------------------------------------------------
1 | Dummy functions
2 | ================
3 |
4 | API documentation for ``markovclick.dummy``.
5 |
6 | .. automodule:: markovclick.dummy
7 | :members:
8 |
--------------------------------------------------------------------------------
/docs/source/api/index.rst:
--------------------------------------------------------------------------------
1 | API
2 | ====
3 |
4 | Documentation for ``markovclick`` API.
5 |
6 | .. toctree::
7 |
8 | dummy
9 | models
10 | preprocessing
11 | viz
12 |
13 |
14 |
--------------------------------------------------------------------------------
/docs/source/api/models.rst:
--------------------------------------------------------------------------------
1 | Models
2 | =======
3 |
4 | API documentation for ``markovclick.models``.
5 |
6 | .. automodule:: markovclick.models
7 | :members:
8 |
--------------------------------------------------------------------------------
/docs/source/api/preprocessing.rst:
--------------------------------------------------------------------------------
1 | Preprocessing
2 | ==============
3 |
4 | API documentation for ``markovclick.preprocessing``.
5 |
6 | .. automodule:: markovclick.preprocessing
7 | :members:
8 |
--------------------------------------------------------------------------------
/docs/source/api/viz.rst:
--------------------------------------------------------------------------------
1 | Visualisation
2 | ==============
3 |
4 | API documentation for ``markovclick.viz``.
5 |
6 | .. automodule:: markovclick.viz
7 | :members:
8 |
--------------------------------------------------------------------------------
/docs/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Configuration file for the Sphinx documentation builder.
4 | #
5 | # This file does only contain a selection of the most common options. For a
6 | # full list see the documentation:
7 | # http://www.sphinx-doc.org/en/master/config
8 |
9 | # -- Path setup --------------------------------------------------------------
10 |
11 | # If extensions (or modules to document with autodoc) are in another directory,
12 | # add these directories to sys.path here. If the directory is relative to the
13 | # documentation root, use os.path.abspath to make it absolute, like shown here.
14 | #
15 | import os
16 | import sys
17 | import markovclick
18 | sys.path.insert(0, os.path.abspath('../../'))
19 |
20 |
21 | # -- Project information -----------------------------------------------------
22 |
23 | project = 'markovclick'
24 | copyright = '2019, Ismail Uddin'
25 | author = 'Ismail Uddin'
26 |
27 | # The short X.Y version
28 | version = ''
29 | # The full version, including alpha/beta/rc tags
30 | release = '0.1.0'
31 |
32 |
33 | # -- General configuration ---------------------------------------------------
34 |
35 | # If your documentation needs a minimal Sphinx version, state it here.
36 | #
37 | # needs_sphinx = '1.0'
38 |
39 | # Add any Sphinx extension module names here, as strings. They can be
40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
41 | # ones.
42 | extensions = [
43 | 'sphinx.ext.autodoc',
44 | 'sphinx.ext.intersphinx',
45 | 'sphinx.ext.todo',
46 | 'sphinx.ext.coverage',
47 | 'sphinx.ext.mathjax',
48 | 'sphinx.ext.ifconfig',
49 | 'sphinx.ext.viewcode',
50 | 'sphinx.ext.napoleon'
51 | ]
52 |
53 | # Add any paths that contain templates here, relative to this directory.
54 | templates_path = ['_templates']
55 |
56 | # The suffix(es) of source filenames.
57 | # You can specify multiple suffix as a list of string:
58 | #
59 | # source_suffix = ['.rst', '.md']
60 | source_suffix = '.rst'
61 |
62 | # The master toctree document.
63 | master_doc = 'index'
64 |
65 | # The language for content autogenerated by Sphinx. Refer to documentation
66 | # for a list of supported languages.
67 | #
68 | # This is also used if you do content translation via gettext catalogs.
69 | # Usually you set "language" from the command line for these cases.
70 | language = None
71 |
72 | # List of patterns, relative to source directory, that match files and
73 | # directories to ignore when looking for source files.
74 | # This pattern also affects html_static_path and html_extra_path .
75 | exclude_patterns = []
76 |
77 | # The name of the Pygments (syntax highlighting) style to use.
78 | pygments_style = 'default'
79 |
80 |
81 | # -- Options for HTML output -------------------------------------------------
82 |
83 | # The theme to use for HTML and HTML Help pages. See the documentation for
84 | # a list of builtin themes.
85 | #
86 | html_theme = 'sphinx_rtd_theme'
87 |
88 | # Theme options are theme-specific and customize the look and feel of a theme
89 | # further. For a list of options available for each theme, see the
90 | # documentation.
91 | #
92 | # html_theme_options = {}
93 |
94 | # Add any paths that contain custom static files (such as style sheets) here,
95 | # relative to this directory. They are copied after the builtin static files,
96 | # so a file named "default.css" will overwrite the builtin "default.css".
97 | html_static_path = ['_static']
98 |
99 | # Custom sidebar templates, must be a dictionary that maps document names
100 | # to template names.
101 | #
102 | # The default sidebars (for documents that don't match any pattern) are
103 | # defined by theme itself. Builtin themes are using these templates by
104 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
105 | # 'searchbox.html']``.
106 | #
107 | # html_sidebars = {}
108 |
109 |
110 | # -- Options for HTMLHelp output ---------------------------------------------
111 |
112 | # Output file base name for HTML help builder.
113 | htmlhelp_basename = 'markovclickdoc'
114 |
115 |
116 | # -- Options for LaTeX output ------------------------------------------------
117 |
118 | latex_elements = {
119 | # The paper size ('letterpaper' or 'a4paper').
120 | #
121 | # 'papersize': 'letterpaper',
122 |
123 | # The font size ('10pt', '11pt' or '12pt').
124 | #
125 | # 'pointsize': '10pt',
126 |
127 | # Additional stuff for the LaTeX preamble.
128 | #
129 | # 'preamble': '',
130 |
131 | # Latex figure (float) alignment
132 | #
133 | # 'figure_align': 'htbp',
134 | }
135 |
136 | # Grouping the document tree into LaTeX files. List of tuples
137 | # (source start file, target name, title,
138 | # author, documentclass [howto, manual, or own class]).
139 | latex_documents = [
140 | (master_doc, 'markovclick.tex', 'markovclick Documentation',
141 | 'Ismail Uddin', 'manual'),
142 | ]
143 |
144 |
145 | # -- Options for manual page output ------------------------------------------
146 |
147 | # One entry per manual page. List of tuples
148 | # (source start file, name, description, authors, manual section).
149 | man_pages = [
150 | (master_doc, 'markovclick', 'markovclick Documentation',
151 | [author], 1)
152 | ]
153 |
154 |
155 | # -- Options for Texinfo output ----------------------------------------------
156 |
157 | # Grouping the document tree into Texinfo files. List of tuples
158 | # (source start file, target name, title, author,
159 | # dir menu entry, description, category)
160 | texinfo_documents = [
161 | (master_doc, 'markovclick', 'markovclick Documentation',
162 | author, 'markovclick', 'One line description of project.',
163 | 'Miscellaneous'),
164 | ]
165 |
166 |
167 | # -- Extension configuration -------------------------------------------------
168 |
169 | # -- Options for intersphinx extension ---------------------------------------
170 |
171 | # Example configuration for intersphinx: refer to the Python standard library.
172 | intersphinx_mapping = {'https://docs.python.org/': None}
173 |
174 | # -- Options for todo extension ----------------------------------------------
175 |
176 | # If true, `todo` and `todoList` produce output, else they produce nothing.
177 | todo_include_todos = True
--------------------------------------------------------------------------------
/docs/source/index.rst:
--------------------------------------------------------------------------------
1 | markovclick
2 | ===============
3 |
4 | .. figure:: _static/img/header.png
5 | :width: 750px
6 |
7 | .. image:: https://readthedocs.org/projects/markovclick/badge/?version=latest
8 | :target: https://markovclick.readthedocs.io/en/latest/?badge=latest
9 | :alt: Documentation Status
10 |
11 | .. image:: https://circleci.com/gh/ismailuddin/markovclick/tree/master.svg?style=svg
12 | :target: https://circleci.com/gh/ismailuddin/markovclick/tree/master
13 |
14 | .. image:: https://img.shields.io/aur/license/yaourt.svg
15 |
16 |
17 | .. toctree::
18 | :hidden:
19 | :maxdepth: 2
20 | :caption: Contents:
21 | :glob:
22 |
23 | api/index
24 | usage
25 |
26 | ``markovclick`` allows you to model clickstream data from websites as Markov
27 | chains, which can then be used to predict the next likely click on a website
28 | for a user, given their history and current state.
29 |
30 | Requirements
31 | ------------
32 |
33 | - Python 3.X
34 | - numpy
35 | - matplotlib
36 | - seaborn (Recommended)
37 | - pandas
38 |
39 | Installation
40 | -------------
41 |
42 | Install either via the ``setup.py`` file:
43 |
44 | .. code-block:: shell
45 |
46 | python setup.py install
47 |
48 | or via ``pip``:
49 |
50 | .. code-block:: shell
51 |
52 | pip install markovclick
53 |
54 |
55 | Tests
56 | ------
57 |
58 | Tests can be run using ``pytest`` command from the root directory.
59 |
60 | Documentation
61 | --------------
62 |
63 | To build the documentation, run ``make html`` inside the ``/docs`` directory,
64 | or whatever output is preferred e.g. ``make latex``.
65 |
--------------------------------------------------------------------------------
/docs/source/usage.rst:
--------------------------------------------------------------------------------
1 | Usage
2 | ==============
3 |
4 | Terminology
5 | ------------
6 |
7 | In the context of this package, streams refer to a series of
8 | clicks belonging to a given user. The time difference between clicks is defined
9 | by the user when assembling these streams, but is typically taken to be 30
10 | minutes in the industry.
11 |
12 | The pages refer to the individual clicks of the user, and thus the pages they
13 | visit. Rather than storing the entire URL of the page the user visits, it is
14 | better to encode pages using a simple code such as `PXX` where `X` can be any
15 | number. This strategy can be used to group similar pages under the same code,
16 | as modelling them as separate pages is sometimes not useful leading to an
17 | excessively large probability matrix.
18 |
19 | Build a dummy Markov chain
20 | ---------------------------
21 | To start using the package without any data, ``markovclick`` can
22 | produce dummy data for you to experiment with:
23 |
24 | .. code-block:: python
25 |
26 | from markovclick import dummy
27 | clickstream = dummy.gen_random_clickstream(nOfStreams=100, nOfPages=12)
28 |
29 |
30 | To build a Markov chain from the dummy data:
31 |
32 | .. code-block:: python
33 |
34 | from markovclick.models import MarkovClickstream
35 | m = MarkovClickstream(clickstream)
36 |
37 |
38 | The instance ``m`` of the ``MarkovClickstream`` class provides access the
39 | class's attributes such as the probability matrix (``m.prob_matrix``) used to
40 | model the Markov chain, and the list of unique pages (``m.pages``) featuring
41 | in the clickstream.
42 |
43 |
44 | Visualisation
45 | --------------
46 |
47 | Visualising as a heatmap
48 | //////////////////////////
49 |
50 | The probability matrix can be visualised as a heatmap as follows:
51 |
52 | .. code-block:: python
53 |
54 | sns.heatmap(m.prob_matrix, xticklabels=m.pages, yticklabels=m.pages)
55 |
56 |
57 | .. figure:: _static/img/heatmap_example.png
58 | :width: 450px
59 |
60 | Visualising the Markov chain
61 | //////////////////////////////
62 |
63 | A Markov chain can be thought of as a graph of nodes and edges, with the edges
64 | representing the transitions from each state. ``markovclick`` provides a
65 | wrapper function around the ``graphviz`` package to visualise the Markov chain
66 | in this manner.
67 |
68 | .. code-block:: python
69 |
70 | from markovclick.viz imoport visualise_markov_chain
71 | graph = visualise_markov_chain(m)
72 |
73 |
74 | The function ``visualise_markov_chain()`` returns a ``Digraph`` object, which
75 | can be viewed directly inside a Jupyter notebook by simply calling the
76 | reference to the object returned. It can also be outputted to a PDF file by
77 | calling the ``render()`` function on the object.
78 |
79 | .. autofunction:: markovclick.viz.visualise_markov_chain
80 |
81 | .. figure:: _static/img/markov_chain.png
82 | :width: 450px
83 |
84 | In the graph produced, the nodes representing the individual pages are shown
85 | in green, and up to 3 edges from each node are rendered. The first edge is in
86 | a thick blue arrow, depicting the most likely transition from this page /
87 | state to the next page / state. The second edge depicted by a thinner blue
88 | arrow, depicts the second most likely transition from this state. Finally, a
89 | third edge is shown that depicts the transition from this page / state back to
90 | itself (light grey). This edge is only shown if the the two most likely
91 | transitions are not already to itself. For all transitions, the probability is
92 | shown next to the edge (arrow).
93 |
94 |
95 | Clickstream processing with ``markovclick.preprocessing``
96 | ----------------------------------------------------------
97 |
98 | ``markovclick`` provides functions to process clickstream data such as server
99 | logs, which contain unique identifiers such as cookie IDs associated with each
100 | click. This allows clicks to be aggregated into groups, whereby clicks from
101 | the same browser (identified by the unique identifier) are grouped such that
102 | the difference between individual clicks does not exceed the maximum session
103 | timeout (typically taken to be 30 minutes).
104 |
105 | Sessionise clickstream data
106 | ////////////////////////////
107 |
108 | To sessionise clickstream data, the following code can be used that require a
109 | `pandas` DataFrame object.
110 |
111 | .. code-block:: python
112 |
113 | from markovclic.preprocessing import Sessionise
114 | sessioniser = Sessionise(df, unique_id_col='cookie_id',
115 | datetime_col='timestamp', session_timeout=30)
116 |
117 |
118 | .. autoclass:: markovclick.preprocessing.Sessionise
119 | :members: __init__
120 |
121 |
122 | With a ``Sessionise`` object instantiated, the ``assign_sessions()`` function
123 | can then be called. This function supports multi-processing, enabling you the
124 | split job into multiple processes to take advantage of a multi-core CPU.
125 |
126 | .. code-block:: python
127 |
128 | sessioniser.assign_sessions(n_jobs=2)
129 |
130 |
131 | .. autofunction:: markovclick.preprocessing.Sessionise.assign_sessions
132 |
133 | The ``assign_sessions()`` function returns the DataFrame, with an additional
134 | column added storing the unique identifier for the session. Rows of the
135 | DataFrame can then be grouped using this column.
136 |
--------------------------------------------------------------------------------
/environment.yml:
--------------------------------------------------------------------------------
1 | name: markovclick
2 | channels:
3 | - defaults
4 | prefix: /anaconda3/envs/markovclick
5 |
6 |
--------------------------------------------------------------------------------
/markovclick/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ismailuddin/markovclick/48def4c0ce0ef5f8263da15e1dbbc1d2eb486e8c/markovclick/__init__.py
--------------------------------------------------------------------------------
/markovclick/__version__.py:
--------------------------------------------------------------------------------
1 | """
2 | Version number of pacakge
3 | """
4 |
5 |
6 | VERSION = (0, 0, 2)
7 |
8 | __version__ = '.'.join(map(str, VERSION))
9 |
--------------------------------------------------------------------------------
/markovclick/dummy.py:
--------------------------------------------------------------------------------
1 | """
2 | Functions for generating dummy content.
3 | """
4 |
5 | import random
6 |
7 |
8 | def gen_random_clickstream(n_of_streams: int, n_of_pages: int,
9 | length: tuple = (8, 12)) -> list:
10 | """
11 | Generates a list of random clickstreams, to use in absence of real
12 | data.
13 |
14 | Args:
15 | n_of_streams (int): Number of unique clickstreams to generate
16 | n_of_pages (int): Number of unique pages, from which to use to
17 | generate clickstreams.
18 | length (tuple): Range of length for each clickstream.
19 | Returns:
20 | list: List of clickstreams, to use as dummy data.
21 | """
22 |
23 | clickstream_list = []
24 |
25 | def page(x):
26 | return random.randrange(0, x)
27 |
28 | for _ in range(n_of_streams):
29 | _length = random.randrange(length[0], length[1])
30 |
31 | clickstream = ['P{}'.format(page(n_of_pages)) for x in range(_length)]
32 | clickstream_list.append(clickstream)
33 |
34 | return clickstream_list
35 |
--------------------------------------------------------------------------------
/markovclick/models.py:
--------------------------------------------------------------------------------
1 | """
2 | Models module which holds MarkovClickstream model.
3 | """
4 |
5 | from typing import Tuple
6 | from itertools import product, chain
7 | from tqdm import tqdm
8 | import numpy as np
9 | import networkx as nx
10 |
11 |
12 | class MarkovClickstream:
13 | """
14 | Builds a Markov chain from input clickstreams.
15 |
16 | Args:
17 | clickstream_list (list): List of clickstream data. Each page should be
18 | encoded as a string, prefixed by a letter e.g. 'P1'
19 | """
20 |
21 | def __init__(self, clickstream_list: list = None, prefixed=True):
22 | self.clickstream_list = clickstream_list
23 | self.pages = []
24 | self.get_unique_pages(prefixed=prefixed)
25 |
26 | self._count_matrix = None
27 | self.initialise_count_matrix()
28 | self._prob_matrix = None
29 |
30 | self.populate_count_matrix()
31 | self.compute_prob_matrix()
32 |
33 | @property
34 | def count_matrix(self):
35 | """
36 | Sets attribute to access the count matrix
37 | """
38 | return self._count_matrix
39 |
40 | @property
41 | def prob_matrix(self):
42 | """
43 | Sets attribute to access the probability matrix
44 | """
45 | return self._prob_matrix
46 |
47 | def get_unique_pages(self, prefixed=True):
48 | """
49 | Retrieves all the unique pages within the provided list of
50 | clickstreams.
51 | """
52 |
53 | flattened_clickstream = list(chain.from_iterable(self.clickstream_list))
54 | self.pages = sorted(list(set(flattened_clickstream)))
55 | return self.pages
56 |
57 | def initialise_count_matrix(self):
58 | """
59 | Initialises an empty count matrix.
60 | """
61 | self._count_matrix = np.zeros([
62 | len(self.pages),
63 | len(self.pages)
64 | ])
65 |
66 | def populate_count_matrix(self):
67 | """
68 | Assembles a matrix of counts of transitions from each possible state,
69 | to every other possible state.
70 | """
71 |
72 | self.initialise_count_matrix()
73 | # For each session in list of sessions
74 | for session in self.clickstream_list:
75 | for j in range(0, len(session) - 1):
76 | next_state = self.pages.index(session[j+1])
77 | current_state = self.pages.index(session[j])
78 |
79 | self._count_matrix[current_state, next_state] += 1
80 |
81 | return self._count_matrix
82 |
83 | @staticmethod
84 | def normalise_row(row):
85 | """
86 | Normalises each row in count matrix, to produce a probability.
87 |
88 | To be used when iterating over rows of `self.count_matrix`. Sum of each
89 | row adds up to 1.
90 |
91 | Args:
92 | row : Each row within numpy matrix to act upon.
93 | """
94 | row_sum = np.sum(row)
95 | if row_sum == 0:
96 | return row
97 |
98 | normalised = np.nan_to_num(np.divide(row, np.sum(row)))
99 | return normalised
100 |
101 | def compute_prob_matrix(self):
102 | """
103 | Computes the probability matrix for the input clickstream.
104 | """
105 | self._prob_matrix = np.apply_along_axis(self.normalise_row, 1,
106 | self.count_matrix)
107 |
108 | def calc_prob_to_page(self, clickstream: list, verbose=True) -> float:
109 | """
110 | Calculates the probability for a sequence of clicks (clickstream)
111 | taking place.
112 |
113 | Args:
114 | clickstream (list): Sequence of clicks (pages), for which to
115 | calculate the probability of occuring.
116 | verbose (bool, optional): Defaults to True. Specifies whether the
117 | output is printed to the terminal, or simply provided back.
118 | """
119 |
120 | total_prob = 1
121 |
122 | curr_page = self.pages.index(clickstream[0])
123 |
124 | for i in range(0, len(clickstream) - 1):
125 | next_page = self.pages.index(clickstream[i + 1])
126 | total_prob = total_prob * self.prob_matrix[curr_page, next_page]
127 | curr_page = next_page
128 |
129 | if verbose:
130 | print("Probability for clickstream: \n {} \nis{}".format(
131 | ':'.join(clickstream), total_prob
132 | ))
133 |
134 | return total_prob
135 |
136 | @staticmethod
137 | def permutations(iterable, r=None):
138 | """
139 | Modification of `itertools.permutations()` function to yield a
140 | mutable list rather than an immutable tuple.
141 |
142 | Unlike the Cartesian product, this does not return a sequence
143 | with repetitions in it.
144 | """
145 | pool = tuple(iterable)
146 | n = len(pool)
147 | r = n if r is None else r
148 | for indices in product(range(n), repeat=r):
149 | if len(set(indices)) == r:
150 | yield [pool[i] for i in indices]
151 |
152 | @staticmethod
153 | def cartesian_product(iterable, repeats=1):
154 | """
155 | Modifies Python's `itertools.product()` function
156 | to return a list of lists, rather than list of
157 | tuples.
158 |
159 | Args:
160 | iterable (list): List of iterables to assemble
161 | Cartesian product from
162 | repeats (int): Number of elements in each list of
163 | the Cartesian product
164 |
165 | Returns:
166 | List of lists of Cartesian product
167 | """
168 |
169 | return list(list(p) for p in product(iterable, repeat=repeats))
170 |
171 | def calc_prob_all_routes_to(self, clickstream: list, end_page: str,
172 | clicks: int, cartesian_product=True):
173 | """
174 | Calculates the probability given an input sequence of page clicks,
175 | to reach the specified end state with the specified number of
176 | transitions before the end state.
177 |
178 | Args:
179 | clickstream (list): List (sequence) of states
180 | end_state (str): Desired end to state to calculate
181 | probability towards
182 | transitions (int): Number of transitions to make after input
183 | sequence, before reaching end state.
184 |
185 | Returns:
186 | float: Probability
187 | """
188 |
189 | if cartesian_product:
190 | potential_routes = list(self.cartesian_product(self.pages,
191 | repeats=clicks))
192 | else:
193 | potential_routes = list(self.permutations(self.pages, r=clicks))
194 |
195 | potential_routes_prob = []
196 |
197 | for route in tqdm(potential_routes):
198 | for state in clickstream[::-1]:
199 | route.insert(0, state)
200 | route.append(end_page)
201 |
202 | prob = self.calc_prob_to_page(route, verbose=False)
203 | potential_routes_prob.append(prob)
204 |
205 | return potential_routes, potential_routes_prob
206 |
207 | def calculate_pagerank(
208 | self, max_nodes: int=2, pr_kwargs: dict={}
209 | ) -> Tuple[nx.DiGraph, dict]:
210 | """
211 | Calculates the Google PageRank for each of the pages in the Markov
212 | chain.
213 |
214 | Converts the Markov chain into a directed graph using `networkx`, and
215 | uses its built in functions to calculate the PageRank score for each
216 | page represented as a node in the graph.
217 |
218 | Args:
219 | max_nodes (int): (Optional, defaults to 2). Specifies the number of
220 | edges (pages) to add to the digraph in order of most probable
221 | transition.
222 | pr_kwargs (dict): (Optional, defaults to empty dictionary.)
223 | Dictionary of arguments to provide to the `networkx` function
224 | for calculating PageRank. Refer to https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.link_analysis.pagerank_alg.pagerank.html
225 | for more details.
226 |
227 | Returns:
228 | Tuple[nx.DiGraph, dict]: networkx DiGraph object, and associated
229 | PageRank scores for each page (node in DiGraph).
230 | """
231 |
232 | digraph = nx.DiGraph()
233 | prob_matrix_sorted = np.argsort(self.prob_matrix, axis=1)
234 | nodes = self.pages
235 | for i, node in enumerate(nodes):
236 | digraph.add_node(node)
237 | for n in range(max_nodes):
238 | next_transition = nodes[prob_matrix_sorted[i, (n + 1) * -1]]
239 | digraph.add_edge(node, next_transition)
240 |
241 | pagerank_scores = nx.link_analysis.pagerank(digraph, **pr_kwargs)
242 | return digraph, pagerank_scores
243 |
--------------------------------------------------------------------------------
/markovclick/preprocessing.py:
--------------------------------------------------------------------------------
1 | """
2 | Functions for preprocessing clickstream datasets
3 | """
4 |
5 | from uuid import uuid4
6 | from multiprocessing import Process, Queue
7 | from datetime import timedelta
8 | import numpy as np
9 | import pandas as pd
10 |
11 |
12 | class Sessionise:
13 | """
14 | Class with functions to sessionise a pandas DataFrame containing
15 | clickstream data.
16 | """
17 |
18 | def __init__(self, df, unique_id_col: str, datetime_col: str,
19 | session_timeout: int = 30) -> None:
20 | """
21 | Instantiates object of ``Sessionise`` class.
22 |
23 |
24 |
25 | Args:
26 | df (pd.DataFrame): ``pandas`` DataFrame object containing
27 | clickstream data. Must contain atleast a timestamp column,
28 | unique identifier column such as cookie ID.
29 | unique_id_col (str): Column name of unique identifier, e.g.
30 | ``cookie_id``
31 | datetime_col (str): Column name of timestamp column.
32 | session_timeout (int, optional): Defaults to 30. Maximum time in
33 | minutes after which a session is broken.
34 | """
35 | self._df = df
36 | self.unique_id_col = unique_id_col
37 | self.datetime_col = datetime_col
38 | self._session_timeout = session_timeout
39 | self.curr_uniq_id = str(uuid4())
40 | self.columns = [self.unique_id_col, 'prev_uniq_id', 'session_boundary']
41 |
42 | @property
43 | def df(self):
44 | """
45 | Provides access to ``df`` attribute
46 | """
47 | return self._df
48 |
49 | @property
50 | def unique_id_col(self):
51 | """
52 | Provides access to ``unique_id_col`` attribute
53 | """
54 | return self.__unique_id_col
55 |
56 | @unique_id_col.setter
57 | def unique_id_col(self, name: str):
58 | """
59 | Sets value for ``unique_id_col`` attribute
60 | """
61 | if name not in self.df.columns:
62 | raise ValueError("Unique ID column name not in dataframe.")
63 | elif isinstance(name, str):
64 | self.__unique_id_col = name
65 | else:
66 | raise ValueError("Unique ID column name should be string.")
67 |
68 | @property
69 | def datetime_col(self):
70 | """
71 | Provides access to ``datetime_col`` attribute
72 | """
73 | return self.__datetime_col
74 |
75 | @datetime_col.setter
76 | def datetime_col(self, name: str):
77 | """
78 | Sets value for ``datetime_col`` attribute
79 | """
80 | if isinstance(name, str) and np.issubdtype(
81 | self.df[name], np.datetime64
82 | ):
83 | self.__datetime_col = name
84 | else:
85 | raise TypeError("Datetime column name should be string referring\
86 | to a datetime column.")
87 |
88 | @property
89 | def session_timeout(self):
90 | """
91 | Provides access to ``session_timeout`` attribute
92 | """
93 | return self._session_timeout
94 |
95 | def _add_session_boundaries(self):
96 | """
97 | Adds a column to denote the session boundaries in clickstream data
98 | """
99 | self._df.sort_values(by=[self.unique_id_col, self.datetime_col])
100 | self._df['prev_uniq_id'] = self._df.shift(1)[self.unique_id_col]
101 | self._df['time_diff'] = self._df[self.datetime_col].diff(1)
102 | self._df['time_diff'] = self._df['time_diff'].fillna(timedelta(0))
103 |
104 | self._df['session_boundary'] = self._df['time_diff'] - timedelta(
105 | minutes=self.session_timeout
106 | )
107 | self._df.loc[:, 'session_boundary'] = self._df[
108 | 'session_boundary'
109 | ].apply(
110 | lambda row: True if row > timedelta(0) else False
111 | )
112 |
113 | def _get_or_create_uuid(self, row) -> str:
114 | """
115 | Provides a new or returns previous session UUID depending on criteria
116 | for setting a new session boundary.
117 |
118 | Args:
119 | row: Row in DataFrame of clickstream dataset
120 |
121 | Returns:
122 | str: Unique session UUID
123 | """
124 | curr_uniq_id = row[self.unique_id_col]
125 | prev_anon_id = row['prev_uniq_id']
126 | boundary = row['session_boundary']
127 |
128 | if boundary is True or curr_uniq_id != prev_anon_id:
129 | self.curr_uniq_id = str(uuid4())
130 | return self.curr_uniq_id
131 | else:
132 | return self.curr_uniq_id
133 |
134 | def _create_partitions(self, partitions: int) -> list:
135 | """
136 | Splits clickstream dataset into specified number of partitions, based
137 | on the unique IDs (e.g. cookie ID) in the DataFrame.
138 |
139 | Args:
140 | partitions (int): Number of partitions to split into
141 |
142 | Returns:
143 | list: List of DataFrames partitioned
144 | """
145 | uniq_ids = self.df[self.unique_id_col].unique()
146 | partitions = list(
147 | filter(lambda x: x.size > 0, np.array_split(uniq_ids, partitions))
148 | )
149 | return partitions
150 |
151 | def _assign_sessions_parallel(self, df, partition: list, queue):
152 | """
153 | Assigns sessions to partition of DataFrame, created using list of
154 | unique IDs provided in partition argument.
155 |
156 | Args:
157 | df (pd.DataFrame): DataFrame containing clickstream data
158 | partition (list): List of unique IDs to subset DataFrame
159 | queue: multiprocessing.Queue object to add results to
160 | """
161 | _df = df.loc[df[self.unique_id_col].isin(partition), :]
162 | curr_session_uuid = str(uuid4())
163 |
164 | def get_or_create_uuid(row) -> str:
165 | nonlocal curr_session_uuid
166 | curr_uniq_id = row[self.unique_id_col]
167 | prev_anon_id = row['prev_uniq_id']
168 | boundary = row['session_boundary']
169 |
170 | if boundary is True or curr_uniq_id != prev_anon_id:
171 | curr_session_uuid = str(uuid4())
172 | return curr_session_uuid
173 | else:
174 | return curr_session_uuid
175 |
176 | _df.loc[:, 'session_uuid'] = _df.apply(
177 | lambda row: get_or_create_uuid(row), axis=1
178 | )
179 | queue.put(_df)
180 |
181 | def assign_sessions(self, n_jobs: int = 1):
182 | """
183 | Assigns unique session IDs to individual clicks that form the
184 | sessions. Supports parallel processing through setting ``n_jobs`` to
185 | higher than 1.
186 |
187 | Args:
188 | n_jobs (int, optional): Defaults to 1. If 2 or higher, enables
189 | parallel processing.
190 |
191 | Returns:
192 | pd.DataFrame: Returns sessionised DataFrame, with session IDs
193 | stored in ``session_UUID`` column.
194 | """
195 | self._add_session_boundaries()
196 | if n_jobs == 1:
197 | self._df.loc[:, 'session_uuid'] = self.df[self.columns].apply(
198 | lambda row: self._get_or_create_uuid(row), axis=1
199 | )
200 | return self.df
201 | if n_jobs > 1:
202 | partitions = self._create_partitions(n_jobs)
203 | queue = Queue()
204 | processes = []
205 | for partition in partitions:
206 | processes.append(Process(
207 | target=self._assign_sessions_parallel,
208 | args=(self.df, partition, queue)
209 | ))
210 | for process in processes:
211 | process.start()
212 | results = [queue.get() for process in processes]
213 | for process in processes:
214 | process.join()
215 |
216 | self._df = pd.concat(results, axis=0)
217 | self._df = self._df.sort_index()
218 | return self.df
219 |
--------------------------------------------------------------------------------
/markovclick/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ismailuddin/markovclick/48def4c0ce0ef5f8263da15e1dbbc1d2eb486e8c/markovclick/utils/__init__.py
--------------------------------------------------------------------------------
/markovclick/utils/helpers.py:
--------------------------------------------------------------------------------
1 | """
2 | Helper utility functions
3 | """
4 |
5 |
6 | def flatten_list(nested_list: [list]) -> list:
7 | """
8 | Function to flatten a two level nested lisst
9 |
10 | Args:
11 | nested_list (list): Nested list
12 |
13 | Returns:
14 | list: Flattened list
15 | """
16 | return [item for sublist in nested_list for item in sublist]
17 |
--------------------------------------------------------------------------------
/markovclick/viz.py:
--------------------------------------------------------------------------------
1 | """
2 | Functions for visualising Markov chain
3 | """
4 |
5 | from graphviz import Digraph
6 | import numpy as np
7 | from markovclick.models import MarkovClickstream
8 |
9 |
10 | def visualise_markov_chain(markov_chain: MarkovClickstream) -> Digraph:
11 | """
12 | Visualises Markov chain for clickstream as a graph, with individual pages
13 | as nodes, and edges between the first and second most likely nodes (pages).
14 | Probabilities for these transitions are annotated on the edges (arrows).
15 |
16 | Args:
17 | markov_chain (MarkovClickstream): Initialised MarkovClickstream object
18 | with probabilities computed.
19 |
20 | Returns:
21 | Digraph: Graphviz Digraph object, which can be rendered as an image or
22 | PDF, or displayed inside a Jupyter notebook.
23 | """
24 | if not isinstance(markov_chain, MarkovClickstream):
25 | raise TypeError(
26 | f'Argument `markov_chain` must be of type '
27 | f'MarkovClickstream. {type(markov_chain)} object provided '
28 | f'instead.'
29 | )
30 | graph = Digraph()
31 | prob = markov_chain.prob_matrix
32 | prob_matrix_sorted = np.argsort(markov_chain.prob_matrix, axis=1)
33 | nodes = markov_chain.pages
34 | for i, node in enumerate(nodes):
35 | graph.node(
36 | node, node, style='filled', fillcolor='#76ff03',
37 | fontname='Helvetica', penwidth='0', fontcolor='#1a237e'
38 | )
39 | first_trans = nodes[prob_matrix_sorted[i, -1]]
40 | most_prob = prob[i, prob_matrix_sorted[i, -1]]
41 | graph.edge(
42 | node, first_trans,
43 | label=f'{most_prob:.2f}',
44 | fontname='Helvetica', penwidth='1.5',
45 | color='#90caf9', arrowsize='0.75'
46 | )
47 | second_prob = prob[i, prob_matrix_sorted[i, -2]]
48 | sec_trans = nodes[prob_matrix_sorted[i, -2]]
49 | graph.edge(
50 | node, sec_trans,
51 | label=f' {second_prob:.2f}',
52 | fontname='Helvetica', penwidth='0.75',
53 | fontsize='10', color='#90caf9', arrowsize='0.5'
54 | )
55 | if node != first_trans and node != sec_trans:
56 | graph.edge(
57 | node, node,
58 | label=f' {prob[i, i]:.2f}',
59 | fontname='Helvetica', penwidth='1.8',
60 | fontsize='10', color='#cfd8dc', arrowsize='0.5'
61 | )
62 | return graph
63 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pytest
2 | pandas
3 | numpy
4 | tqdm
5 | networkx
6 | graphviz
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """
2 | Setup file for installing package.
3 | """
4 |
5 | from setuptools import setup, find_packages
6 |
7 | __version__ = '0.1.2'
8 |
9 | with open("README.md", "r") as fh:
10 | LONG_DESCRIPTION = fh.read()
11 |
12 | setup(
13 | name='markovclick',
14 | version=__version__,
15 | description='Package for modelling clickstream data using Markov chains',
16 | long_description=LONG_DESCRIPTION,
17 | url='https://github.com/ismailuddin/markovclick',
18 | download_url='https://github.com/ismailuddin/markovclick/tarball/' + __version__,
19 | license='BSD',
20 | classifiers=[
21 | 'Development Status :: 3 - Alpha',
22 | 'Intended Audience :: Developers',
23 | 'Programming Language :: Python :: 3',
24 | ],
25 | keywords='markov chain data science machine learning statistics clickstream',
26 | long_description_content_type="text/markdown",
27 | packages=find_packages(exclude=['docs', 'tests*']),
28 | include_package_data=True,
29 | author='Ismail Uddin'
30 | )
31 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ismailuddin/markovclick/48def4c0ce0ef5f8263da15e1dbbc1d2eb486e8c/tests/__init__.py
--------------------------------------------------------------------------------
/tests/test_dummy.py:
--------------------------------------------------------------------------------
1 | """
2 | Module to test markovclick.dummy functions
3 | """
4 |
5 |
6 | import unittest
7 |
8 | from markovclick.dummy import gen_random_clickstream
9 | from markovclick.utils.helpers import flatten_list
10 |
11 |
12 | class TestDummy(unittest.TestCase):
13 | """
14 | Class to test functions in markovclick.dummy
15 | """
16 |
17 | def test_gen_random_clickstream(self):
18 | """
19 | Tests `gen_random_clickstream` function to ensure it generates
20 | clickstreams with the attributes equal to what is specified in the
21 | arguments.
22 | """
23 | n_of_streams = 12
24 | n_of_pages = 14
25 | length = (15, 20)
26 | clickstream = gen_random_clickstream(n_of_streams, n_of_pages,
27 | length)
28 | self.assertEqual(len(clickstream), n_of_streams)
29 | self.assertEqual(len(set(flatten_list(clickstream))), n_of_pages)
30 | lengths = [len(stream) for stream in clickstream]
31 | self.assertGreaterEqual(min(lengths), length[0])
32 | self.assertLess(min(lengths), length[1])
33 | self.assertGreater(max(lengths), length[0])
34 | self.assertLessEqual(max(lengths), length[1])
35 |
--------------------------------------------------------------------------------
/tests/test_models.py:
--------------------------------------------------------------------------------
1 | """
2 | Module to run tests for the markovclick/models.py file
3 | """
4 |
5 |
6 | import unittest
7 | import numpy as np
8 | from markovclick.models import MarkovClickstream
9 | import networkx as nx
10 | import random
11 | from markovclick.dummy import gen_random_clickstream
12 | from markovclick.utils.helpers import flatten_list
13 |
14 |
15 | class TestModels(unittest.TestCase):
16 | """
17 | Class to test models.py
18 | """
19 |
20 | def test_get_unique_pages(self):
21 | """
22 | Tests the `get_unique_pages` function
23 | """
24 | clickstream = gen_random_clickstream(n_of_streams=100, n_of_pages=12)
25 | markov_clickstream = MarkovClickstream(
26 | clickstream_list=clickstream
27 | )
28 | pages = markov_clickstream.get_unique_pages()
29 | self.assertEqual(len(pages), len(set(pages)))
30 | clickstream_pages = flatten_list(clickstream)
31 | self.assertEqual(set(pages), set(clickstream_pages))
32 |
33 | def test_initialise_count_matrix(self):
34 | """
35 | Test `initialise_count_matrix` function
36 | """
37 | clickstream = gen_random_clickstream(n_of_streams=100, n_of_pages=12)
38 | markov_clickstream = MarkovClickstream(
39 | clickstream_list=clickstream
40 | )
41 | markov_clickstream.initialise_count_matrix()
42 | count_matrix = markov_clickstream.count_matrix
43 | pages = set(flatten_list(clickstream))
44 | expected = np.zeros((len(pages), len(pages)))
45 | self.assertTrue((count_matrix == expected).all())
46 |
47 | def test_populate_count_matrix(self):
48 | """
49 | Tests the `populate_count_matrix` function
50 | """
51 | clickstream = [
52 | ['P1', 'P2', 'P2', 'P2'],
53 | ['P3', 'P4', 'P5']
54 | ]
55 | markov_clickstream = MarkovClickstream(
56 | clickstream_list=clickstream
57 | )
58 |
59 | markov_clickstream.populate_count_matrix()
60 | expected_count_matrix = np.array([
61 | [0., 1., 0., 0., 0.],
62 | [0., 2., 0., 0., 0.],
63 | [0., 0., 0., 1., 0.],
64 | [0., 0., 0., 0., 1.],
65 | [0., 0., 0., 0., 0.]
66 | ])
67 |
68 | self.assertTrue(
69 | (expected_count_matrix == markov_clickstream.count_matrix).all()
70 | )
71 |
72 | def test_normalise_row(self):
73 | """
74 | Tests `normalise_row` function
75 | """
76 | test_cases = [
77 | (np.array([5.0, 0.0]), np.array([1.0, 0.0])),
78 | (np.array([0.0, 0.0]), np.array([0.0, 0.0])),
79 | ]
80 | for row, expected in test_cases:
81 | normalised = MarkovClickstream.normalise_row(row)
82 | print(row, expected, normalised)
83 | self.assertTrue((normalised == expected).all())
84 |
85 | def test_compute_prob_matrix(self):
86 | """
87 | Test `compute_prob_matrix` function
88 | """
89 | clickstream = gen_random_clickstream(n_of_streams=100, n_of_pages=12)
90 | markov_clickstream = MarkovClickstream(
91 | clickstream_list=clickstream
92 | )
93 | markov_clickstream.compute_prob_matrix()
94 | prob_matrix = markov_clickstream.prob_matrix
95 | for row in range(prob_matrix.shape[0]):
96 | self.assertAlmostEqual(np.sum(prob_matrix[row, :]), 1)
97 |
98 | def test_calculate_pagerank(self):
99 | """
100 | Test the 'calculate_pagerank` function.
101 | """
102 | clickstream = gen_random_clickstream(n_of_streams=100, n_of_pages=12)
103 | markov_clickstream = MarkovClickstream(
104 | clickstream_list=clickstream
105 | )
106 | n_pages = len(markov_clickstream.pages)
107 | max_edges = random.randrange(1, n_pages)
108 | digraph, pagerank_scores = markov_clickstream.calculate_pagerank(
109 | max_nodes=max_edges
110 | )
111 | self.assertIsInstance(digraph, nx.DiGraph)
112 | self.assertIsInstance(pagerank_scores, dict)
113 | self.assertEqual(
114 | digraph.number_of_nodes(), n_pages
115 | )
116 | self.assertLess(
117 | digraph.number_of_nodes(),
118 | (max_edges * n_pages) + 1
119 | )
120 | self.assertGreater(
121 | digraph.number_of_edges(),
122 | n_pages - 1
123 | )
124 | self.assertEqual(
125 | len(pagerank_scores.values()),
126 | n_pages
127 | )
128 |
--------------------------------------------------------------------------------
/tests/test_preprocessing.py:
--------------------------------------------------------------------------------
1 | """
2 | Module to test markovclick.preprocessing functions
3 | """
4 |
5 |
6 | import unittest
7 |
8 | import pandas as pd
9 | from datetime import datetime
10 | from markovclick import preprocessing
11 |
12 |
13 | class TestSessionise(unittest.TestCase):
14 | """
15 | Class to test preprocessing.Sessionise class
16 | """
17 | def setUp(self):
18 | data = {
19 | 'date': [
20 | datetime(2018, 1, 1, 10, 10),
21 | datetime(2018, 1, 1, 10, 15),
22 | datetime(2018, 1, 1, 10, 25),
23 | datetime(2018, 1, 1, 10, 57),
24 | datetime(2018, 1, 1, 11, 2),
25 | datetime(2018, 1, 1, 11, 15),
26 | datetime(2018, 1, 1, 11, 55),
27 | ],
28 | 'unique_id': ['id1', 'id1', 'id1', 'id1', 'id2', 'id2', 'id3']
29 | }
30 | self._df = pd.DataFrame(data)
31 |
32 | def test__init__(self):
33 | """
34 | Tests the constructor function
35 | """
36 | date_col = 'date'
37 | unique_id_col = 'unique_id'
38 | session_timeout = 60
39 | sessionise = preprocessing.Sessionise(
40 | self._df,
41 | unique_id_col,
42 | date_col,
43 | session_timeout
44 | )
45 | self.assertEqual(sessionise.unique_id_col, unique_id_col)
46 | self.assertEqual(sessionise.datetime_col, date_col)
47 | self.assertEqual(sessionise.session_timeout, session_timeout)
48 | # Test for incorrect datetime column name
49 | with self.assertRaises(TypeError):
50 | preprocessing.Sessionise(self._df, unique_id_col, unique_id_col)
51 | # Test for unique ID column name which is not in DataFrame
52 | with self.assertRaises(ValueError):
53 | preprocessing.Sessionise(self._df, 'incorrect', date_col)
54 |
55 | def test__add_session_boundaries(self):
56 | """
57 | Tests the `add_session_boundaries` function.
58 | """
59 | sessionise = preprocessing.Sessionise(self._df, 'unique_id', 'date')
60 | df = sessionise.df
61 | sessionise._add_session_boundaries() # pylint: disable=W0212
62 | columns = sessionise.df.columns
63 | self.assertTrue('prev_uniq_id' in columns)
64 | self.assertTrue('session_boundary' in columns)
65 | self.assertTrue('time_diff' in columns)
66 | self.assertEqual(
67 | df[df['session_boundary'] == True].sum()['session_boundary'],
68 | 2
69 | )
70 |
71 | def test__get_or_create_uuid(self):
72 | """
73 | Tests `_get_or_create_uuid` function with known cases.
74 | """
75 | sessionise = preprocessing.Sessionise(self._df, 'unique_id', 'date')
76 | sessionise._add_session_boundaries()
77 | df = sessionise.df
78 | df.loc[:, 'session_uuid'] = df.apply(
79 | lambda row: sessionise._get_or_create_uuid(row), axis=1
80 | )
81 | self.assertEqual(df.loc[0, 'session_uuid'], df.loc[1, 'session_uuid'])
82 | self.assertNotEqual(
83 | df.loc[2, 'session_uuid'], df.loc[3, 'session_uuid']
84 | )
85 | self.assertNotEqual(
86 | df.loc[3, 'session_uuid'], df.loc[4, 'session_uuid']
87 | )
88 | self.assertEqual(df.loc[4, 'session_uuid'], df.loc[5, 'session_uuid'])
89 | self.assertNotEqual(
90 | df.loc[5, 'session_uuid'], df.loc[6, 'session_uuid']
91 | )
92 |
93 | def test__create_partitions(self):
94 | """
95 | Tests the `_create_partitions` function
96 | """
97 | sessionise = preprocessing.Sessionise(self._df, 'unique_id', 'date')
98 | df = sessionise.df
99 | _partitions = sessionise._create_partitions(4)
100 | partitions = [list(p) for p in _partitions]
101 | for partition in partitions:
102 | self.assertEqual(len(set(partition)), len(partition))
103 |
104 | def test_assign_sessions(self):
105 | """
106 | Test for `assign_sessions` function in single and multiprocessing mode
107 | """
108 | sess_single = preprocessing.Sessionise(self._df, 'unique_id', 'date')
109 | df_single = sess_single.assign_sessions(n_jobs=1)
110 | sess_parallel = preprocessing.Sessionise(self._df, 'unique_id', 'date')
111 | df_parallel = sess_parallel.assign_sessions(n_jobs=4)
112 | self.assertEqual(
113 | df_single['session_uuid'].nunique(),
114 | df_parallel['session_uuid'].nunique()
115 | )
116 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py36
3 |
4 | [testenv]
5 | deps = pytest
6 | commands =
7 | pytest
8 |
--------------------------------------------------------------------------------