Net Study Material
Net Study Material
Net Study Material
Processes
Objectives
look at how to program UNIX processes
fork( ), exec( ), wait( )
1. What is a Process?
A process is an executing program.
A process:
$ cat file1 file2 &
Two processes:
$ ls | wc - l
continued
Pointer to program code
Pointer to data Memory for global vars
Pointer to stack Memory for local vars
Pointer to heap Dynamically allocated
Execution priority
Signal information
Important System Processes
init Mother of all processes. init is started at
boot time and is responsible for starting other
processes.
init uses file inittab & directories: /etc/rc?.d
getty login process that manages login
sessions.
Unix Start Up Processes Diagram
OS kernel
Process 0
(sched)
Process 1
(init)
login login
csh bash
Pid and Parentage
A process ID or pid is a positive integer that uniquely
identifies a running process, and is stored in a variable of
type pid_t.
Parent
int main()
{
pid_t pid; /* could be int */
int i;
pid = fork();
if( pid > 0 )
{
/* parent */
for( i=0; i < 1000; i++ )
printf(\t\t\tPARENT %d\n, i);
}
else
{
/* child */
for( i=0; I < 1000; i++ )
printf( CHILD %d\n, i );
}
return 0;
}
Possible Output
CHILD 0
CHILD 1
CHILD 2
PARENT 0
PARENT 1
PARENT 2
PARENT 3
CHILD 3
CHILD 4
PARENT 4
:
Things to Note
i is copied between parent and child.
void main()
{ char *cmd[] = {who, ls, date};
int i;
printf(0=who 1=ls 2=date : );
scanf(%d, &i);
tinymenu
cmd[i]
execlp()
printf()
not executed
unless there
is a problem
with execlp()
exec(..) Family
execv() execvp()
execve()
fork() and execv()
execv(new_program, argv[ ])
Initial process
Fork
fork() returns pid=0 and runs as a
Returns a cloned parent until execv is called
new PID
Original New
process new_Program
Copy of
Continues (replacement)
Parent
execv(new_program)
4. wait()
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *statloc);
continued
if(fork() == 0)
{ /* child */
execlp( cmd[i], cmd[i], (char *)0 );
printf( execlp failed\n );
exit(1);
}
else
{ /* parent */
wait( (int *)0 );
printf( child finished\n );
}
} /* while */
} /* main */
Execution
menushell
fork() child
cmd[i]
wait() execlp()
Macros for wait (1)
WIFEXITED(status)
Returns true if the child exited normally.
WEXITSTATUS(status)
Evaluates to the least significant eight bits of the
return code of the child which terminated, which
may have been set as the argument to a call to
exit( ) or as the argument for a return.
This macro can only be evaluated if WIFEXITED
returned non-zero.
Macros for wait (2)
WIFSIGNALED(status)
Returns true if the child process exited because of
a signal which was not caught.
WTERMSIG(status)
Returns the signal number that caused the child
process to terminate.
This macro can only be evaluated if WIFSIGNALED
returned non-zero.
waitpid()
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid( pid_t pid, int *status, int opts )
int main(void)
{
pid_t pid;
int status;
int globvar = 6;
char buf[] = stdout write\n;
int main(void)
{
int w = 88;
pid_t pid;
continued
write( 1, buf, sizeof(buf)-1 );
printf( Before fork()\n );
Before fork()
pid = 430, globvar = 7, w = 89
/*child chg*/
pid = 429, globvar = 6, w = 88
/* parent no chg */
int main(void)
{ int fd; /* file descriptor */
pid_t pid;
char buf[10]; /* for file data */
:
continued
if ((fd=open(data-file, O_RDONLY)) < 0)
perror(open);
continued
else if( pid > 0 )
{ /* parent */
wait((int *)0);
printpos( Parent after wait, fd );
}
else
perror( fork );
}
continued
void printpos( char *msg, int fd )
/* Print position in file */
{
long int pos;
$ shfile
Before fork: 10
Child before read: 10
Child after read: 20
Parent after wait: 20
what's happened?
8. Special Exit Cases
Two special cases:
continued
2) A parent exits when 1 or more
children are still running
children are adopted by the systems
initialization process (/etc/init)
it can then monitor/kill them
9. I/O redirection
The trick: you can change where the standard
I/O streams are going/coming from after the
fork but before the exec
Redirection of standard output
Example implement shell: ls > x.ls
program:
Open a new file x.lis
Redirect standard output to x.lis using dup command
everything sent to standard output ends in x.lis
execute ls in the process
dup2(int fin, int fout) - copies fin to fout in the file table
File table
dup2(3,1) stdin
stdin
0
0
stdout 1
1
stderr 2
2 x.lis
x.lis 3
3
4
4
Example - implement ls > x.lis
#include <unistd.h>
int main ()
{
int fileId;
fileId = creat( "x.lis",0640 );
if( fileId < 0 )
{
printf( stderr, "error creating x.lis\n );
exit (1);
}
dup2( fileId, stdout ); /* copy fileID to stdout */
close( fileId );
execl( "/bin/ls", "ls", 0 );
}
10. User and Group ID
Group ID
Real, effective
User ID
Real user ID
Identifies the user who is responsible for the running process.
Effective user ID
Used to assign ownership of newly created files, to check file
access permissions, and to check permission to send signals to
processes.
To change euid: executes a setuid-program that has the set-uid bit
set or invokes the setuid( ) system call.
The setuid(uid) system call: if euid is not superuser, uid must be
the real uid or the saved uid (the kernel also resets euid to uid).
Real and effective uid: inherit (fork), maintain (exec).
Read IDs
pid_t getuid(void);
Returns the real user ID of the current process
pid_t geteuid(void);
Returns the effective user ID of the current process
gid_t getgid(void);
Returns the real group ID of the current process
gid_t getegid(void);
Returns the effective group ID of the current process
Change UID and GID (1)
#include <unistd.h>
#include <sys/types.h>
int setuid( uid_t uid )
Int setgid( gid_t gid )
exec setuid(uid)
ID
suid bit off suid bit on superuser other users
environ: HOME=/home/stevens\0
PATH=:/bin:/usr/bin\0
SHELL=/bin/sh\0
USER=stevens\0
LOGNAME=stevens\0
NULL
Example: environ
#include <stdio.h>
void main(void)
{
printf(Home directory is %s\n, getenv(HOME));
putenv(HOME=/);
P=Q
Q
P1 P2=Q2
Q1
O2
O1
(Camps)
So Stereo has two steps
Finding matching points in the images
Then using them to compute depth.
Epipolar Constraint
Most powerful correspondence constraint.
Simplifies discussion of depth recovery.
Stereo correspondence
Epipolar Constraint
Reduces correspondence problem to 1D
search along conjugate epipolar lines
(Seitz)
Simplest Case
Image planes of cameras are parallel.
Focal points are at same height.
Focal lengths same.
Then, epipolar lines are horizontal scan lines.
blackboard
We can always achieve this
geometry with image
rectification
Image Reprojection
reproject image planes onto common
plane parallel to line between optical
centers
Notice, only focal point of camera really matters
(Seitz)
Lets discuss reconstruction with this geometry before
correspondence, because its much easier. blackboard
P
T x x T T
Z f
r l
Z f Z x x
Z
l r
xl xr
Disparity: d x x l r
f pl pr
Ol Or
T
Then given Z, we can compute X and Y.
Most
popular
For each window, match to closest window on epipolar line in other image.
(Camps)
Window size
W=3 W = 20
(Seitz)
Stereo results
Data from University of Tsukuba
(Seitz)
Results with window correlation
(Seitz)
Ordering constraint
Usually, order of points in two images is same.
blackboard
This enables dynamic programming.
If we match pixel i in image 1 to pixel j in
image 2, no matches that follow will affect
which are the best preceding matches.
Example with pixels (a la Cox et al.).
How well does this work? See problem set.
Other constraints
Smoothness: disparity usually doesnt change
too quickly.
Unfortunately, this makes the problem 2D again.
Solved with a host of graph algorithms, Markov
Random Fields, Belief Propagation, .
Occlusion and disparity are connected.
Summary
First, we understand constraints that make the
problem solvable.
Some are hard, like epipolar constraint.
Ordering isnt a hard constraint, but most useful when treated like
one.
Some are soft, like pixel intensities are similar, disparities
usually change slowly.
Then we find optimization method.
Which ones we can use depend on which constraints we
pick.
Topic: Trees and Graphs
Graphs (roadmap)
TREES
Static Dynamic
Binary
Search 2-3 Trees Huffman Tree Other ()
Trees
Self-Balancing
Static Dynamic
Binary
Search 2-3 Trees Huffman Tree Other ()
Trees
Self-Balancing
0 1 3
1 0 2 3
2 1 3 4
3 0 1 2
4 2
Graphs
Definitions, terminology, applications
Data Structures
Traversals
Minimum Spanning Tree
Shortest Path
Reachability, Transitive closure, Directed
Acyclic Graphs
Graphs
Definitions, terminology, applications
Data Structures
Traversals
Minimum Spanning Tree
Shortest Path
Reachability, Transitive closure, Directed
Acyclic Graphs
Graphs
Definitions, terminology, applications
Data Structures
Traversals
Minimum Spanning Tree
Shortest Path
Reachability, Transitive closure, Directed
Acyclic Graphs
41 0
0
29
1
29
5 1
5 51
45 21 32 4
38
4 2 3
36 32
3 2
50
Graphs
Definitions, terminology, applications
Data Structures
Traversals
Minimum Spanning Tree
Shortest Path
Reachability, Transitive closure, Directed
Acyclic Graphs
Welcome to
CS 620
Theory of Computation
Fall 2009
Theory of Computation
September 8, 2009 109
Lecture 1: Introduction and Preliminaries
Instructor Marc Pomplun
Office: S-3-171
Lab: S-3-135
Office Hours: Tuesdays 17:30 - 19:00
Thursdays 14:30 - 16:00
Phone: 287-6443 (office)
287-6485 (lab)
E-Mail: marc@cs.umb.edu
Homepage: www.cs.umb.edu/~marc/cs620/
Theory of Computation
September 8, 2009 110
Lecture 1: Introduction and Preliminaries
Modeling of Brain Functions
layer l +1 unit and connection
in the interpretive network
unit and connection
in the gating network
layer l -1
Theory of Computation
September 8, 2009 111
Lecture 1: Introduction and Preliminaries
What is so interesting about the
Theory of Computation?
Theory of Computation is the most fundamental subject
in computer science.
What you learn in this course applies to all computers
and all programming languages that will ever exist.
You will understand the capabilities of algorithms in
general.
For example, you will learn about problems that cannot
be solved algorithmically.
Theory of Computation
September 8, 2009 112
Lecture 1: Introduction and Preliminaries
Preliminaries
Theory of Computation
September 8, 2009 113
Lecture 1: Introduction and Preliminaries
Set Theory
Union: AB = {x | xA xB}
Intersection: AB = {x | xA xB}
Theory of Computation
September 8, 2009 117
Lecture 1: Introduction and Preliminaries
Set Operations
Theory of Computation
September 8, 2009 118
Lecture 1: Introduction and Preliminaries
Set Operations
The complement of a set A contains exactly those
elements under consideration that are not in A:
-A = U-A
Theory of Computation
September 8, 2009 119
Lecture 1: Introduction and Preliminaries
Functions
A function f from a set A to a set B is an assignment of
exactly one element of B to each element of A.
We write
f(a) = b
if b is the unique element of B assigned by the function f
to the element a of A.
If f is a function from A to B, we write
f: AB
(note: Here, has nothing to do with if then)
Theory of Computation
September 8, 2009 120
Lecture 1: Introduction and Preliminaries
Functions
If f:AB, we say that A is the domain of f and B is the
codomain of f.
Theory of Computation
September 8, 2009 121
Lecture 1: Introduction and Preliminaries
Alphabets and Strings
An alphabet is a finite, nonempty set A of objects called
symbols.
A word (string) on A is an n-tuple of symbols of A.
Instead of using the notation (a1, a2, , an) we can just
write a1a2an.
The set of all words on A is written A*.
Any subset of A* is called a language on A.
Theory of Computation
September 8, 2009 122
Lecture 1: Introduction and Preliminaries
Alphabets and Strings
Concatenation of strings:
Let string u = monkey, v = business
uv = monkeybusiness
vu = businessmonkey
Theory of Computation
September 8, 2009 123
Lecture 1: Introduction and Preliminaries
Propositional Functions
Propositional function (open sentence):
statement involving one or more variables,
e.g.: x-3 > 5.
Let us call this propositional function P(x), where P is
the predicate and x is the variable.
Theory of Computation
September 8, 2009 124
Lecture 1: Introduction and Preliminaries
Propositional Functions
Let us consider the propositional function
Q(x, y, z) defined as:
x + y = z.
Here, Q is the predicate and x, y, and z are the
variables.
Theory of Computation
September 8, 2009 125
Lecture 1: Introduction and Preliminaries
Universal Quantification
Let P(x) be a propositional function.
Theory of Computation
September 8, 2009 126
Lecture 1: Introduction and Preliminaries
Universal Quantification
Example:
S(x): x is a UMB student.
G(x): x is a genius.
Theory of Computation
September 8, 2009 127
Lecture 1: Introduction and Preliminaries
Existential Quantification
Existentially quantified sentence:
There exists an x in the universe of discourse for which
P(x) is true.
Theory of Computation
September 8, 2009 128
Lecture 1: Introduction and Preliminaries
Existential Quantification
Example:
P(x): x is a UMB professor.
G(x): x is a genius.
Theory of Computation
September 8, 2009 129
Lecture 1: Introduction and Preliminaries
Disproof by Counterexample
A counterexample to x P(x) is an object c so that P(c)
is false.
Theory of Computation
September 8, 2009 130
Lecture 1: Introduction and Preliminaries
Induction
The principle of mathematical induction is a useful
tool for proving that a certain predicate is true for all
natural numbers.
Theory of Computation
September 8, 2009 131
Lecture 1: Introduction and Preliminaries
Induction
If we have a propositional function P(n), and we want
to prove that P(n) is true for any natural number n, we
do the following:
Theory of Computation
September 8, 2009 132
Lecture 1: Introduction and Preliminaries
Induction
Example (Gauss):
1 + 2 + + n = n (n + 1)/2
Theory of Computation
September 8, 2009 133
Lecture 1: Introduction and Preliminaries
Induction
2. Show that if P(n) then P(n + 1) for any nN.
(inductive step)
1+2++n = n (n + 1)/2
1 + 2 + + n + (n + 1) = n (n + 1)/2 + (n + 1)
= (n + 1) (n/2 + 1)
= (n + 1) (n + 2)/2
= (n + 1) ((n + 1) + 1)/2
Theory of Computation
September 8, 2009 134
Lecture 1: Introduction and Preliminaries
Induction
End of proof.
End of first lecture!
Theory of Computation
September 8, 2009 135
Lecture 1: Introduction and Preliminaries
Topic 11
Sorting and Searching
"There's nothing in your head the
sorting hat can't see. So try me on
and I will tell you where you ought
to be."
-The Sorting Hat, Harry Potter and
the Sorcerer's Stone
list
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53
public static int bsearch(int[] list, int target)
{ int result = -1;
int low = 0;
int high = list.length - 1;
int mid;
while( result == -1 && low <= high )
{ mid = low + ((high - low) / 2);
if( list[mid] == target )
result = mid;
else if( list[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return result;
}
// mid = ( low + high ) / 2; // may overflow!!!
// or mid = (low + high) >>> 1; using bitwise op
CS 307 Fundamentals of Computer
144
Science Sorting and Searching
Trace When Key == 3
Trace When Key == 30
Variables of Interest?
Array sorted
times in milliseconds
CS 307 Fundamentals of Computer
168
Science Sorting and Searching
Quicksort
Invented by C.A.R. (Tony) Hoare
A divide and conquer approach
that uses recursion
1. If the list has 0 or 1 elements it is sorted
2. otherwise, pick any element p in the list. This is called
the pivot value
3. Partition the list minus the pivot into two sub lists
according to values less than or greater than the pivot.
(equal values go to either)
4. return the quicksort of the first list followed by the
quicksort of the second list
CS 307 Fundamentals of Computer
169
Science Sorting and Searching
Quicksort in Action
39 23 17 90 33 72 46 79 11 52 64 5 71
Pick middle element as pivot: 46
Partition list
23 17 5 33 39 11 46 79 72 52 64 90 71
quick sort the less than list
Pick middle element as pivot: 33
23 17 5 11 33 39
quicksort the less than list, pivot now 5
{} 5 23 17 11
quicksort the less than list, base case
quicksort the greater than list
Pick middle element as pivot: 17
and so on.
Big O of Quicksort?
Why?
(and Linux)
181
Operating Systems
183
Basic commands in Unix shells
Command Short explanation
ls -l prints the content of a directory
pwd prints the name of the current
directory
cd change directory
mkdir creates a new directory
cp copies a file
mv moves a file/directory
rm removes (deletes) a file
rmdir removes an empty directory
man help (manual) on a command 184
Additional Unix commands
cat concatenate files and print to standard output
cat file1
cat file1 file2 file3
less file viewer (less is better than more)
which locate a command
groups prints the groups the user in (permission...)
grep prints lines matching to a pattern
grep i .*lib.* foo.bar
find search for a file in a directory
find . name *.txt print
find ~/ name *.o -exec rm {} \;
clear clears the terminal screen
finger prints information about a user
who shows who is logged in
whoami identifies the current user
185
File and directory permissions in
Unix
permissions group
permissions = bits 2-10 (bit 1: d=directory, - = file)
bit 1 = whether is a directory (d) or not (-)
bits 2-4: owner permissions
bits 5-7: group permissions
bits 8-10: other permissions
rwx:
r read permission
w write permission
x execute (file)/ can cd (directory)
changing permissions: chmod
chmod go+rx a.out
chmod R 755 mydir
186
Editing text files in Unix
Common text editors:
pico - simple but very basic, similar to notepad
vi, vim
emacs, xemacs (GUI) - see course webpage for a
simple tutorial
More info: man pico, man vi, man vim
man emacs
187
Pipes and redirections to/from files
Pipe: prog1 | prog2 the output of prog1 is redirected to
the input of prog2
Example: ls l | less
Output redirection to file
prog > foo.out :may cause an error if foo.out exists
prog >! foo.out :truncates foo.out if exists
prog >> foo.out :may cause error if foo.out does NOT exist
prog >>! foo.out :does not check whether foo.out exists
Input redirection (read from file)
prog < foo.in
188
Comparing files (program tests)
189
Basic tools in UNIX
190
Compiling and linking
Compiling and linking
gcc hello.c o hello
Only compiling (creating hello.o)
gcc c hello.c
Only linking
gcc hello.o o hello
Additional common flags to gcc:
-g allows debugging
-l<library-name> - linking with external libraries
191
Make and makefiles (in short)
makefile: a collection of rules to make targets
make: a utility that executes makefiles
all: hello
target name clean:
-rm hello.o hello rule
hello: hello.o
dependencies gcc -g hello.o -o hello
command hello.o: hello.c
gcc -c -g hello.c
Makefiles will be
covered later in
the course. In the
meanwhile,
makefiles will be
supplied
192
[ Section 8.3 ]
Heaps
- complete binary trees with the heap property
- complete: for every k < (depth of the tree), there are 2k (i.e. maximum possible) nodes
at depth k. For the last level (equivalent to the depth), the nodes are arranged from left
to right with no gaps
- heap property: for every non-leaf node v, the key at v is smaller than or equal to the
keys of all its children
[ Section 8.3 ]
Heaps
Height of a heap with n keys:
[ Section 8.3 ]
Heaps
Convenient array representation:
[ Section 8.3 ]
Priority queues via heaps
- used for implementation of the priority queue data type [see also Section 8.1]
- priority queue: supports insert(x), removeMin()
[ Section 8.3 ]
Priority queues via heaps
How to implement insert(x) ?
Running time:
[ Section 13.1 ]
Graphs
Generalization of trees, can include cycles. Formally,
G = (V,E) where V = set of nodes, E VV = set of edges
(undirected or directed edges)
- adjacency lists
- adjacency matrix
[ Section 13.3 ]
Graph traversals
- BFS (breadth first search)
- DFS (depth first search)
[ Section 13.3 ]
Graph traversals
BFS (breadth first search) pseudocode
Running time:
[ Section 13.3 ]
Graph traversals
DFS (breadth first search) pseudocode
Running time:
[ Section 13.4.3 ]
Topological sort
Given is a directed acyclic graph, find an order of the nodes such that every edge goes
from an earlier node to a later node.
[ Section 13.4.3 ]
Topological sort
Topological sort via DFS with time-stamps
Running time:
What is a Network?
A network consists of 2 or more computers
connected together, and they can
communicate and share resources (e.g.
information)
208
Why Networking?
Sharing information i.e. data
communication
Do you prefer these?
Or this?
209
Sharing hardware or software
E.g. print document
210
How many kinds of Networks?
Depending on ones perspective, we can
classify networks in different ways
Based on transmission media: Wired (UTP, coaxial cables, fiber-
optic cables) and Wireless
Based on network size: LAN and WAN (and MAN)
Based on management method: Peer-to-peer and Client/Server
Based on topology (connectivity): Bus, Star, Ring
:
:
211
Transmission Media
Two main categories:
Guided wires, cables
Unguided wireless transmission, e.g. radio,
microwave, infrared, sound, sonar
We will concentrate on guided media here:
Twisted-Pair cables:
Unshielded Twisted-Pair (UTP) cables
Shielded Twisted-Pair (STP) cables
Coaxial cables
Fiber-optic cables
212
Twisted-Pair Cables
If the pair of wires are not twisted, electromagnetic
noises from, e.g., motors, will affect the closer wire more
than the further one, thereby causing errors
213
Unshielded Twisted-Pair (UTP)
Typically wrapped inside a plastic cover (for mechanical
protection)
A sample UTP cable with 5 unshielded twisted pairs of wires
Insulator Metal
214
Shielded Twisted-Pair (STP)
STP cables are similar to UTP cables, except there is a
metal foil or braided-metal-mesh cover that encases each
pair of insulated wires
215
Categories of UTP Cables
EIA classifies UTP cables according to the quality:
Category 1 the lowest quality, only good for voice, mainly
found in very old buildings, not recommended now
Category 2 good for voice and low data rates (up to 4Mbps
for low-speed token ring networks)
Category 3 at least 3 twists per foot, for up to 10 Mbps
(common in phone networks in residential buildings)
Category 4 up to 16 Mbps (mainly for token rings)
Category 5 (or 5e) up to 100 Mbps (common for networks
targeted for high-speed data communications)
Category 6 more twists than Cat 5, up to 1 Gbps
216
Coaxial Cables
In general, coaxial cables, or coax, carry signals of higher freq
(100KHz500MHz) than UTP cables
Outer metallic wrapping serves both as a shield against noise
and as the second conductor that completes the circuit
217
Fiber-Optic Cables
Light travels at 3108 ms-1 in free space and is the fastest
possible speed in the Universe
Light slows down in denser media, e.g. glass
Refraction occurs at interface, with light bending away from
the normal when it enters a less dense medium
219
Advantages and Disadvantages
Noise resistance external light is blocked by outer jacket
Less signal attenuation a signal can run for miles without
regeneration (currently, the lowest measured loss is about
~4% or 0.16dB per km)
Higher bandwidth currently, limits on data rates come from
the signal generation/reception technology, not the fiber itself
Cost Optical fibers are expensive
Installation/maintenance any crack in the core will degrade
the signal, and all connections must be perfectly aligned
220
LAN and WAN
Local Area Network (LAN)
Small network, short distance
A room, a floor, a building
Limited by no. of computers and distance covered
Usually one kind of technology throughout the LAN
Serve a department within an organization
Examples:
Network inside the Student Computer Room
Network inside CF502
Network inside your home
221
Wide Area Network (WAN)
A network that uses long-range telecommunication links to connect
2 or more LANs/computers housed in different places far apart.
Towns, states, countries
Examples:
Network of our Campus Your home
Internet
USA
WAN
Student Computer
Centre
222
Example WAN technologies:
ISDN Integrated Service Digital Network
Basic rate: 192 Kbps Primary rate: 1.544Mbps
T-Carriers basically digital phone lines
T1: 1.544Mbps T3: 28T1
Frame relay
Each link offers 1.544Mbps or even higher
ATM Asynchronous Transfer Mode
Support B-ISDN: 155Mbps or 622Mbps or higher
SONET Synchronous Optical Network
Basic rate OC1: 51.84Mbps
Support OC12 and up to OC192 (9953.28Mbps) or even higher in
the future
223
Example of WAN: Broadband Cable Network
Cable TV services have been extensively developed in most modern
cities
Cable TV companies try to make use of their coaxial cable installed
(that are supposed to carry TV signals) to deliver broadband data
services
Many cable network wiring has been replaced with hybrid fiber-coax
(HFC) i.e. use of fiber-optic cable to connect to the subscribers
buildings, and then the original coaxial cable to connect to each
household
224
The connection is shared by a number of
subscribers, hence may raise
performance and security problems
PC
TV
Cable
Drop
Coaxial Cable company
Cable
225
Cable is an asymmetrical technology
Downstream: max 36 Mbps
Upstream: max 10 Mbps
Peer-to-peer
227
Advantages of peer-to-peer networks:
Low cost
Simple to configure
User has full accessibility of the computer
Network Servers
Computers that manage and provide network resources and services
to clients
Usually have more processing power, memory and hard disk
space than clients
Run Network Operating System that can manage not only data,
but also users, groups, security, and applications on the network
Servers often have a more stringent requirement on its
performance and reliability
229
Advantages of client/server networks
Facilitate resource sharing centrally administrate and control
Facilitate system backup and improve fault tolerance
Enhance security only administrator can have access to Server
Support more users difficult to achieve with peer-to-peer
networks
230
Topology 3 basic types
How so many computers are connected
together?
Bus Topology Ring
Topology
Star Topology
Hub
231
Bus Topology
Simple and low-cost
A single cable called a trunk (backbone, segment)
Only one computer can send messages at a time
Passive topology - computer only listen for, not regenerate data
Star Topology
Each computer has a cable connected to a single point
More cabling, hence higher cost
All signals transmission through the hub; if down, entire network
down
Depending on the intelligence of hub, two or more computers may
send message at the same time
232
How to construct a network
with Bus / Star Topology?
Bus Topology
Coaxia
l cable
Star Topology
BNC T-Connector
233
Network Card
Ring Topology
Every computer serves as Ack T T
a repeater to boost signals T
Typical way to send data:
T dat T dat
Token passing
a a
only the computer who
gets the token can send T
data T
T Ack
Disadvantages T Ack
dat
Difficult to add computers a
More expensive T
If one computer fails, whole network fails T Ack
234
CT
Seeram
Chapter 2:
Introduction
to Computers
Electronic Computer Technology
Vacuum tubes
Discrete Semiconductors
Integrated Circuits
Early Computers
1951-1958
Vacuum tube memory
Input / Output
Punch cards
Magnetic Tape
Electronic Computer Technology
Warm-up
Ran hot
tube filaments required
constant heating
computers required air
conditioning
Frequent failures
Computers after Vacuum Tubes
1959-1963
Transistor & magnetic
core memory
Smaller
Less power needed
Discrete Semiconductor Components
in Computers
transistors
magnetic memory cores
Space requirements
large
but
smaller than vacuum tubes
Ran much cooler than vacuum tubes
Computers: The Big Jump
Integrated Circuits
millions of semiconductor components in tiny
package
lower production costs
Extremely small
Extremely fast
Run very cool
Very reliable
Categories of Computers
Super computers
Mainframes
Minicomputers
Microcomputers
5th Generation:
Supercomputers
PC
Rapidly changing
technology
Low cost
Non-proprietary
First common in
1980s
Minicomputers
First seen in 1970s
Much less expensive than mainframes
Medium-sized
Proprietary ($$$)
parts
operating systems
Computer used for CT
Appropriate
Size
price
Applications
imaging, reconstruction
archiving
Basics
Analog
(continuously varying)
Digital
(discretely varying)
Analog to Digital Conversion
(A to D)
Many real world inputs are analog voltages
CT detector intensity
Analog values must be converted to a # to use in a
computer
0.8
0.6
Input
analog
voltage 0.4
0.2
Digital conversion to
computer 1 2 3 4
Processing
Central Processing Unit (CPU)
Arithmetic
Logic
Internal Memory
Scratchpad
Hardware Software
People
Hardware
Computer
Peripherals
keyboard Hardware Software
printer
People
Hardware
Examples
Disk Drive
Memory
Random Access
(RAM)
Read only
(ROM)
Mouse Hardware Software
Keyboard
People
Cables
Software
Instructions to computer
Operating System
Applications
Hardware Software
People
Operating System
People
Operating System
Computer face presented to users
Windows
DOS
MAC OS
Dictates how users
interact with
computer to
run application
software
Hardware Software
People
Application Software
People
Application Software
Usually a quasi-
English language Forms![FDoSurvey]![FExpsSub].Form![KVEff] = Val(Mid$(MyData, 2, 10))
Forms![FDoSurvey]![FExpsSub].Form![KVAVG] = Val(Mid$(MyData, 12, 10))
Forms![FDoSurvey]![FExpsSub].Form![MRMEAS] = Val(Mid$(MyData, 22, 10))
Basic Forms![FDoSurvey]![FExpsSub].Form![TIMEMEAS] = Val(Mid$(MyData, 32, 10))
DumText = Mid$(MyData, 42, 3)
Fortran 'MsgBox$ (DumText)
If Right$(DumText, 1) = "+" Then
COBOL DumText = Left$(DumText, 2)
Else
C DumText = Left$(DumText, 1)
End If
Telephone lines
twisted pair wires
Coaxial cable
Fiber optic cable
Microwaves
Satellites
Radio waves
Networks
LAN (Local area network)
computers connected in one area
LANs can be connected together
WAN (Wide area network)
computers connected together over large
distances
Communications protocols
Ethernet
uses bus technology
Internet
File Server
Special computer which handles functions
for connected computers
disk access
printing
Incorporates security
may limit user to selected files or directories
may limit # of connections per user
may limit times when network available
Typical Lan
Network
Gateway
Other
Networks
Radiology Computer Systems
Insurance
Hospital Carrier Voice to Text
Admission/Discharge Dictation
Billing PACS
Reports
Web
RIS Digital Spot Film
Server
Digital Dictation
Professional
Billing Angio /
Digital
CT Subtraction
Mammography MRI
CR
The Computerization of
Nuc
Radiology Digital Digital
CT CR MRI
Med Fluoro Angio
Web Browser
3D Laser
Workstation RIS PACS
Printer
Dictation Admin
ABSTRACT
noisy channels.
A code C over an alphabet S is a subset of S* - (C S*).
A q -nary code is a code over an alphabet of q -symbols.
A binary code is a code over the alphabet {0,1}.
Examples of codes C1 = {00, 01, 10, 11} C2 = {000, 010, 101, 100}
C3 = {00000, 01101, 10111, 11011}
Basics of coding theory 279
IV054
CHANNEL
0000 1 111
Binary symmetric
channel
1016
1012 5.5 10 9
7
66
1016
The two-dimensional parity code arranges the data into a two-dimensional array and
then to each row (column) parity bit is attached.
Example Binary string
10001011000100101111
is represented and encoded as follows
1 0 0 0 1 0
1 0 0 0 1
0 1 1 0 0 0
0 1 1 0 0
0 1 0 0 1 0
0 1 0 0 1
0 1 1 1 1 0
0 1 1 1 1
1 1 0 1 1 0
Example:
C1 = {00, 01, 10, 11} is a (2,4,1)-code.
C2 = {000, 011, 101, 110} is a (3,4,2)-code.
C3 = {00000, 01101, 10110, 11011} is a (5,4,3)-code.
In 1970-72 Mariners 6-8 took such photographs that each picture was
broken into 700 832 squares. Reed-Muller (32,64,16) code was used.
Transmission rate was 16200 bits per second. (Much better pictures)
In Mariner 5, 6-bit pixels were encoded using 32-bit long Hadamard code
that could correct up to 7 errors.
The code rate represents the ratio of the number of input data symbols to
the number of transmitted code symbols.
Code rate (6/12 for Hadamard code), is an important parameter for real
implementations, because it shows what fraction of the bandwidth is being
used to transmit actual data.
l p m w = x x 1 10
i
i 1 i 1
position if x10 = 10.
Basics of coding theory 293
IV054
The ISBN-code
Transposition detection
iy ix k j x j k x
i 1
i
i 1
i j k
k j x x 0 mod 11
j k if k j and x j xk .
Theorem Suppose d is odd. Then a binary (n,M,d) -code exists iff a binary (n
+1,M,d +1) -code exists.
If case: Let D be an (n +1,M,d +1) -code. Choose code words x, y of D such that d(x,y)
= d +1.
Find a position in which x, y differ and delete this position from all codewords of D.
Resulting code is an (n,M,d) -code.
Basics of coding theory 298
IV054
The main coding theory problem
Corollary:
If d is odd, then A2 (n,d) = A2 (n +1,d +1).
If d} is even, then A2 (n,d) = A2 (n -1,d -1).
00000
01101
10110 by adding check.
11011
q 1 q 1
n
0
n
1
n
2
2
... q 1
n
r
r
words.
Proof Let u be a fixed word in Fqn. The number of words that differ from u in m
position is
n
m q 1 .
m
M q 1 ... q 1 q
n
0
n
1
n
t
t n
(1)
A code which achieves the sphere-packing bound from (1), i.e. such that
equality holds in (1), is called a perfect code.
i.e. M = 16
An example of such a code:
C4 = {0000000, 1111111, 1000101, 1100010,
n
5
6
d=3
4
8
d=5
2
2
d=7
-
-
qn
and therefore Aq n, d
q 1
d 1 n j
j 0 j
information efficiently.
Let X be a random variable (source) which
takes a value x with probability p(x). The
entropy of X is defined by
SHANNON's VIEW
In the introduction to his seminal paper A mathematical theory of communication
Shannon wrote:
Harry Chen
Department of CSEE
University of MD Baltimore County
Introduction
What is File System?
The abstraction used by kernel to represent and
organize the storage resources.
UNIX File System in general
File system is organized in tree structure.
File tree can be arbitrarily deep.
File name must NOT LONGER than 256 chars.
Single path name must NOT LONGER than 1023
chars.
Creating File System
Mounting File System
File tree is composed of File System
Use mount command to map a directory within
the existing file tree (mount point) to the root of
the new file system.
mount /dev/hda2 /usr
Use umount command to detach the file system.
Detaching will fail if the file system is busy.
Organizing of The File System
The UNIX file system has never been very
well organized. -- Page 58
incompatible naming convention
e.g. ATT & BSD startup script naming
e.g. log file naming
Organizing of The File System
(cont.)
/ The root directory
/bin or /sbin Commands for basic
system operation
/dev Device entries
/etc Critical startup and
configuration files.
/lib Library for the C
compiler
/tmp Temporary files
/var/adm or /var/log Accounting file, log
files
Types of Files
Regular Files
binary
GIF, JPEG, Executable etc.
text
scripts, program source code, documentation
Supports sequential and random access
Types of Files (cont.)
Directory
Can contain ANY kind of files
what is . and ..??
Device File
Allows programs to communicate with hardware.
Kernel modules handles device management.
Types of Files (cont.)
Device Files (cont.)
Character Device
Accepts a stream of characters, without regard to any
block structure.
It is not addressable, therefore no seek operation
Block Device
Information stored in fixed-sized block
It is addressable, therefore seek operation is possible.
Types of Files (cont.)
UNIX Domain Sockets (BSD)
sockets that are local to a particular host and are
referenced through a file system object rather
than a network port.
X windows
Named Pipe
Allow processes to communicate with each other.
Types of Files (cont.)
Hard links
Linking files by reference
System maintains a count of the number of links
Does not work across file systems.
Soft links
Linking files by name
No counter is maintained
Work across file system
File Permissions
The Setuid and Setgid bits
Setuid with octal value 4000
Setgid with octal value 2000
These bits allow programs to access files that
processes that would otherwise off limits to the
user that runs them.
Types of Files (cont.)
Sticky Bit
Not very popular in todays system
If a directory has sticky bit set, then only the
owner can remove file from the directory.
/tmp is a good example.
Types of Files (cont.)
The Permission Bit
9 permission bits used to determine 3 types of
accesses, READ, WRITE, EXECUTE.
Permission can be set based on GROUP, OWNER,
ANYONE ELSE.
Use chmod command to change permission
Binary 001 for EXECUTE
Binary 010 for WRITE
Binary 100 for READ
Types of Files (cont.)
INODES
Kernel maintains file information in a structure
called inode.
Creation, modification time stamps
Ownership, file size etc.
Commonly used INODE information can be found
by using ls command
Group information and be modified by using chgrp
command.
Summary
All UNIX file system are very similar.
All file system have this concept of file tree.
Transparent to user even mount point is mapped
to a remote file system.
To communicate with devices, special device
files are used.
More information check out the man pages.
Computer Vision & Image
John Hulskamp
processing
E-mail:
john@hulskamp.com.au
Consultant
john@hulskamp.com.au 325
Introduction
Introducing the new subject 31049 Computer
Vision & Image Processing
john@hulskamp.com.au 326
Osteons
Compact bone is comprised of many units called osteons: they consist of a central canal surrounded by closely packed
concentric layers called lamallae.
This is an image of some osteons, specimen is from a 32yo male. Image is a ~2.8x3.5mm portion of a contact micro-
radiograph taken from a 100micrometre thick, un-embedded, hard-ground section. Black areas are voids, white = high
mineral density (maybe a couple of grains of carborundum can be seen).
Attribution: David Thomas, Dental Sciences, University of Melbourne
john@hulskamp.com.au 327
Near IR Imaging
Hot strip mill temperature measurement
john@hulskamp.com.au 328
Near IR Imaging (2)
Thermal Map
Attribution: C. Lampe: A Multi-Processor temperature profiling system for real time control in a hot strip
rolling mill M.Eng. Thesis RMIT 1995
john@hulskamp.com.au 329
Topics for Discussion Today
Subject objectives
Fundamental Issues
Applications
Towards image understanding
CV & IP Tools
A Simple Beginning
Conclusions
john@hulskamp.com.au 330
Subject objectives
adequate background knowledge about computer vision and image
processing
john@hulskamp.com.au 331
Fundamental Issues
An imaging system
john@hulskamp.com.au 332
Fundamental Issues (2)
Resolution - the smallest feature size on your object that the imaging system
can distinguish
Field of view - the area of inspection that the camera can acquire
Working distance - the distance from the front of the camera lens to the object
under inspection
Sensor size - the size of a sensor's active area
Depth of field - the maximum object depth that remains in focus
john@hulskamp.com.au 333
Fundamental Issues (3)
Resolution
Resolution indicates the amount of object detail that the imaging system can
reproduce. You can determine the required resolution of your imaging system by
measuring in real-world units the size of the smallest feature you need to detect in the
image.
To make accurate measurements, a minimum of two pixels should represent the
smallest feature you want to detect in the digitized image. In the picture , the
narrowest vertical bar (w) should be at least two pixels wide in the image. This
information can assist to select the appropriate camera and lens for the imaging
application.
john@hulskamp.com.au 334
Fundamental Issues (4)
Sensor resolution is the number of columns and rows of CCD pixels in the camera sensor. To compute the
sensor resolution, you need to know the field of view (FOV).
The FOV is the area under inspection that the camera can acquire. The horizontal and vertical dimensions of the
inspection area determine the FOV. Make sure the FOV encloses the object you want to inspect.
Once you know the FOV, you can use the following equation to determine your required sensor resolution:
john@hulskamp.com.au 335
Fundamental Issues (5)
Determine the focal length of your lens.
A lens is primarily defined by its focal length. This picture illustrates the relationship between the focal length of the
lens, field of view, sensor size, and working distance which is the distance from the front of the lens to the object
under inspection.
john@hulskamp.com.au 336
Fundamental Issues (6)
Lighting issues
One of the most important aspects of setting up your imaging environment is proper
illumination. Images acquired under proper lighting conditions make your image
processing software development easier and overall processing time faster. One
objective of lighting is to separate the feature or part you want to inspect from the
surrounding background by as many gray levels as possible. Another goal is to control
the light in the scene. Set up your lighting devices so that changes in ambient
illumination-such as sunlight changing with the weather or time of day-do not
compromise image analysis and processing.
john@hulskamp.com.au 337
Fundamental Issues (7)
Backlighting is another lighting technique that can help improve the performance of your vision system.
If you can solve your application by looking at only the shape of the object, you may want to create a
silhouette of the object by placing the light source behind the object you are imaging. By lighting the
object from behind, you create sharp contrasts which make finding edges and measuring distances fast
and easy. This picture shows a stamped metal part acquired in a setup using backlighting.
john@hulskamp.com.au 338
Fundamental Issues (8)
Perspective
Perspective errors occur when the camera axis is not perpendicular to the object under inspection. The figures show both an
ideal camera position (I.e. vertical) and a camera imaging an object from an angle.
john@hulskamp.com.au 339
Fundamental Issues (9)
Perspective and Distortion Errors
Try to position your camera perpendicular to the object under inspection to reduce perspective errors.
Integration constraints may prevent you from mounting the camera perpendicular to the scene. Under
these constraints, you can still take precise measurements by correcting the perspective errors with
spatial calibration techniques.
john@hulskamp.com.au 340
Examples of Vision Applications
Attribution: National Instruments IMAQ Vision Product Demonstration (www.ni.com/vision)
Examples:
Battery Clamp
Spark Plug Gap Measurement
Blister Pack Inspection
PCB Inspection
john@hulskamp.com.au 341
Examples of Vision Applications (2)
Battery Clamp
john@hulskamp.com.au 342
Examples of Vision Applications (3)
Spark Plug Gap Measurement
john@hulskamp.com.au 343
Examples of Vision Applications (4)
Blister Pack Inspection: Ensuring that blister packs contain the correct number
and type of pills before they reach pharmacies, ensuring the integrity of the product
and increase the yield of production by automating the inspection of blister pack
contents.
Acquire colour images of the blister packs. Use colour location to count the number of
green areas in the image. With colour location, you create a model or template that
represents the colours that you are searching. Then the machine vision application
searches for the model in each acquired image and calculates a score for each
match. The surface area of each pill in the pack must be at least 50% green to pass
inspection.
john@hulskamp.com.au 344
Examples of Vision Applications (5)
Blister Pack Inspection (contd)
john@hulskamp.com.au 345
Examples of Vision Applications (6)
PCB Inspection
To ensure that components are present and at the correct orientation on a PCB.
john@hulskamp.com.au 346
Examples of Vision Applications (7)
PCB Inspection (contd): Colour information simplifies a monochrome problem by improving contrast or
separation of the components from the background. Colour pattern matching can distinguish objects from the
background more efficiently than grayscale pattern matching.
This example uses rotation-invariant pattern matching because it can detect the components regardless of their
orientations. You can use the orientation information to determine the correct placement of orientation-sensitive
components, such as capacitors or diodes.
john@hulskamp.com.au 347
Towards image understanding
Computer Vision: making useful decisions about real physical objects and scenes based on sensed images
To get to that understanding we need to process images: hence Image Processing is a step towards this
understanding
john@hulskamp.com.au 348
Histograms
The cumulative histogram of a grey-level image f(w,h) is a function
H(k) which provides the total number pixels (number of
occurrences) that have grey-level less than the value k.
H (k ) card { f ( w, h) | f ( w, h) k}
k [0, k max ]
( w, h) [(0,0), (W 1, H 1)]
h(k ) H (k ) H (k 1)
john@hulskamp.com.au 349
Histograms (2)
john@hulskamp.com.au 350
Histogram Equalisation
john@hulskamp.com.au 351
CV & IP Tools
NIH Image is a public domain image processing and analysis program for the Macintosh. It was developed
at the Research Services Branch (RSB) of the National Institute of Mental Health (NIMH), part of the
National Institutes of Health (NIH). A free PC version of Image, called Scion Image for Windows, is
available from Scion Corporation. Image can acquire, display, edit, enhance, analyse and animate images.
It reads and writes TIFF, PICT, PICS and MacPaint files, providing compatibility with many other
applications, including programs for scanning, processing, editing, publishing and analysing images. It
supports many standard image processing functions, including contrast enhancement, density profiling,
smoothing, sharpening, edge detection, median filtering, and spatial convolution with user defined
kernels.
Image can be used to measure area, mean, centroid, perimeter, etc. of user defined regions of interest. It
also performs automated particle analysis and provides tools for measuring path lengths and angles.
Spatial calibration is supported to provide real world area and length measurements. Density calibration
can be done against radiation or optical density standards using user specified units. Results can be
printed, exported to text files, or copied to the Clipboard.
john@hulskamp.com.au 352
CV & IP Tools (2)
Khoral Inc:It started out as Khoros about 10 years ago, for UNIX-based X-
systems, has become available for the Windows platform as well. Costs
money today!
Their online DIP course is very good:
http://www.khoral.com/contrib/contrib/dip2001/index.html
john@hulskamp.com.au 353
CV & IP Tools (3)
UTHSCSA ImageTool
UTHSCSA ImageTool (IT) is a free image processing and analysis program for
Microsoft Windows 9x, Windows ME or Windows NT. IT can acquire, display,
edit, analyse, process, compress, save and print gray scale and colour
images.IT can read and write over 22 common file formats including BMP,
PCX, TIF, GIF and JPEG. Image analysis functions include dimensional
(distance, angle, perimeter, area) and gray scale measurements (point, line
and area histogram with statistics). ImageTool supports standard image
processing functions such as contrast manipulation, sharpening, smoothing,
edge detection, median filtering and spatial convolutions with user-defined
convolution masks.
ImageTool was designed with an open architecture that provides
extensibility via a variety of plug-ins. Support for image acquisition using
either Adobe Photoshop plug-ins or Twain scanners is built-in. Custom
analysis and processing plug-ins can be developed using the software
development kit (SDK) provided (with source code). This approach makes it
possible to solve almost any data acquisition or analysis problem with IT.
john@hulskamp.com.au 354
CV & IP Tools (4)
Intel open source computer vision library OpenCV
CVIPtools: is a UNIX/Win32-based software package developed \ under the continuing direction of Dr.
Scott E Umbaugh One of the primary purposes of the CVIPtools development is to allow students, faculty,
and other researchers to explore the power of computer processing of digital images.
CVIPtools is a collection of computer imaging tools providing services to the users at three layers. At the
bottom level are the CVIPtools libraries (the application programming interface). Based on the CVIPtools
libraries are the cviptcl and cvipwish shells. The cviptcl shell is an extension of Tcl with additional CVIP
capabilities. With cviptcl, the user can either use the command line for interactive image processing, or
write cviptcl shell scripts for batch processing. The cvipwish shell is the extension of cviptcl with the added
functionality for building a graphical user interface (GUI) which allows even the casual computer users to
experiment with many of the sophisticated tools available to computer imaging specialists without the
need for any knowledge of computer programming.
john@hulskamp.com.au 355
Topics in Course
Image formation. Human vision. Computer vision.
Image representation. Analog and digital images. Common image and video formats. Image compression.
JPEG and MPEG.
Image acquisition. Image acquisition systems. Cameras and frame grabbers.
Image processing. Image enhancement. Convolution. Filtering. Edge detection. Texture analysis. Labelling.
Contour tracing. Image morphology. Image segmentation.
Image analysis. Feature extraction. Geometrical features. Hough transform.
Image sequences. Motion detection. Optical flow. Background subtraction. Feature tracking.
Pattern recognition. Object classification. Statistical, neural networks, symbolic classifiers.
Computer Vision. Model-based vision. Applications in industrial quality inspection, video surveillance,
robotics, medicine, multimedia .
john@hulskamp.com.au 356
A Simple Beginning
Paradigm for an image processing code:
Declarations
john@hulskamp.com.au 357
Conclusions
An overview of what is ahead for you in this
exciting field.
You might like to experiment with the above
simple code to attempt to gain the histogram
for an image, and try out histogram
equalisation
john@hulskamp.com.au 358
Data Structures - Graph
Name Graph
Non-Std None
Functions
The most versatile data structure (linked lists, trees and
Notes heaps are special instances of graphs).
Standard Problems:
Graph Coloring: Coloring the nodes of a graph such that
adjacent nodes do not have the same color.
Traveling Salesman: Visiting each node in the graph exactly
once for the least cost (start and stop at the same node).
Maximum Flow: Determine the amount of flow through a
network.
Data Structures - Graph
The fact that the nodes and edges can represent anything means
that the graph structure is very versatile and virtually any problem
can be mapped to a graph problem.
Example Graph Problem - Puzzle
How does he get everything across the river and bring everything
home (uneaten)?
Build a graph:
N = the set of possible arrangements of man, wolf, goose, corn, and
river.
E = Possible transitions due to one boat trip.
Example Graph Problem - Puzzle
mwgc| wgc| m
mwg|c wg|mc
mwc| g wc| mg
mgc| w gc| mw
mc| wg c| mwg
mg| wc g| mwc
mw|gc w|mgc
m| wgc | mwgc
Example Graph Problem - Puzzle Solved
mwgc| wgc| m
mwg|c wg|mc
mwc| g wc| mg
mgc| w gc| mw
mc| wg c| mwg
mg| wc g| mwc
mw|gc w|mgc
m| wgc | mwgc
Graph Problems
There are literally thousands of graph problems, but we will focus on three
that are occur very commonly and show the diversity of the graph
structure:
The Traveling Salesman Problem.
Graph Coloring Problem.
Maximum Flow Problem.
Each problem has a decision form and an optimization form. The decision
form asks "Can we do it?" and the optimization form asks "How well can
we do it?"
At least one of these problems is solved by you every day without you
realizing it (until now).
The fact that the nodes and edges can represent anything means that the
graph structure is very versatile and virtually any problem can be mapped
to a graph problem.
Graph Problems - Traveling Salesman
Name Tree
Non-Std None
Functions
The first element in the tree is the root node, which has no
Notes parents, and from which all others can be reached.
Nodes with no children are "leaf" nodes.
If nodes a and b are connected by an edge, then:
a is a child of b if b is closer to the root than a.
a is a parent of b if a is closer to the root than b
Name Heap
Definition A tree in which a parent node has a value larger than all its
children.
Std Functions Heap(a, H) Add new node a to heap H.
Unheap(H) Remove the root element from heap H and re-
establish the heap.
Non-Std None
Functions
Flexible data structure useful for sorting elements as they
Notes arrive. This allows sorting on lists whoses size change
constantly.
Topic #11
Todays Agenda
Complete our discussion of trees
Learn about heaps
walk through the deletion algorithms for:
AVL
2-3, 2-3-4
Learn about graphs
Heaps
A heap is a data structure similar to a binary
search tree.
However, heaps are not sorted as binary
search trees are.
And, heaps are always complete binary trees.
Therefore, we always know what the
maximum size of a heap is.
Heaps
Unlike a binary search tree, the value of
each node in a heap is greater than or
equal to the value in each of its children.
In addition, there is no relationship
between the values of the children; you
don't know which child contains the
larger value.
Heaps are used to implement priority
queues.
Heaps
A priority queue is an Abstract Data Type!
Which, can be implemented using heaps.
Think of a To-Do lists; each item has a
priority value which reflects the urgency
with which each item needed to be
addressed.
Heaps
By preparing a priority queue, we can
determine which item is the next highest
priority.
A priority queue maintains items sorted in
descending order of their priority value --
so that the item with the highest priority
value is always at the beginning of the list.
Heaps
Priority Queue ADT operations can be
implemented using heaps...
which is a weaker binary tree but sufficient
for the efficient performance of priority
queue operations.
Let's look at heap: 10
9 6
3 2 5
Heaps
To remove an item from a heap, we remove the
largest item (or the item with the highest priority).
Because the value of every node is greater than or
equal to that of either of its children, the largest
value must be the root of the tree.
A remove operation is simply to remove the item
at the root and return it to the calling routine.
Heaps
Once you have removed the largest value,
you are left with two disjoint heaps:
Therefore, you need to transform the nodes
Move the last node and place it in the root
Then take that value and trickle it down the tree
until it reaches a node in which it will not be out
of place. 5 9
10
9 6 5 6
9 6
3 2 3 2
3 2 5
Step 1 Step 2
Heaps
To insert an item, we use just the opposite
strategy.
We insert at the bottom of the tree and trickle the
number upward to be in the proper place.
With insert, the number of swaps cannot exceed the
height of the tree -- so that is the worst case!
Which, since we are dealing with a binary tree, this is
always approximately log2(N) which is very efficient.
Heaps
9 9 9
5 6 5 6 5 15
3 2 3 2 15 3 2 6
Step 1:insert 15 Step 2 Step 3
15
5 9
3 2 6
Step 5
Heaps
The real advantage of a heap is that it is
always balanced.
It makes a heap more efficient for
implementing a priority queue than a binary
search tree because the operations that keep a
binary search tree balanced are far more
complex than the heap operations.
However, heaps are not useful if you want to
try to traverse a heap in sorted order -- or
retrieve a particular item.
Heapsort
A heapsort uses a heap to sort a list of
items that are not in any particular order.
The first step of the algorithm transforms
the array into a heap.
We do this by inserting the numbers into
the heap and having them trickle up...one
number at a time.
Heapsort
A better approach is to put all of the
numbers in a binary tree -- in the order you
received them.
Then, perform the algorithm we used to
adjust the heap after deleting an item.
This will cause the smaller numbers to
trickle down to the bottom.
Heapsort
6 6
3 5 3 5
9 2 10 9 2 10
Step 1 Step 2: compare 6 with 3 & 5;
no swaps
6
9 5
3 2 10
9 10
3 2 5
Step 4: compare 5 with 10; swap;
this means that 5 is now in its correct
sorted location; Level 3 is sorted.
10
9 6
3 2 5
Pass 2: start again. Compare 6 with 3 and 10; swap
6 and 10. 3 and 6 are now in the correc t sorted locations;
Level 2 is sorted.
Deletion Algorithms
In class, take 5 minutes and practice creating
the following trees:
insert: 30, 50, 70, 10, 20, 60, 15, 25, 85
create: BST, AVL, 2-3, 2-3-4, red-black
create: a heap
now, delete a leaf in each tree
now, delete an internal node
Moving from Trees to Graphs
Trees are useful when there is an inherent
hierarchical relationship between our data
sorting data by a key can build such a relationship
But, not all problems are so simple
Maybe there are complex relationships
between nodes ... not just hierarchical!
this is where graphs become important
Graphs
Graphs can be used as data structures and as
the last ADT we will learn about;
to represent how data can be related to one
another...setting up an inherent structure.
Graphs consist of vertices (nodes) and edges
which connect the vertices.
A path is a sequence of edges that can be
taken to get from one vertex to another.
Graphs
Paths may pass through the same vertex more
than once but simple paths may not.
A cycle is a path that starts and ends at the
same vertex but does not pass through other
vertices more than once.
Graphs are considered to be connected if
there is a path between every pair of vertices.
Graphs
A graph is complete if there is an edge
between every pair of vertices.
Edges can have labels - or numeric values -
which create a weighted graph.
Weights can label the distances between
cities.
5
3
1
7 2
A directed graph
Graphs
Two common operations are to find an edge
between two vertices and to find all vertices
adjacent to a given vertex.
Using an adjacency list to determine whether
there is an edge from one vertex to another,
we must traverse the linked list associated
with one of the vertices to determine
whether the other vertex is present.
Graphs
To determine all vertices adjacent to a given
vertex, we only need to traverse the linked
list associated with the specified vertex.
What about traversing a graph?
Graph-traversal starts at a specified vertex and
does not stop until it has visited all of the vertices
that it can reach.
It visits all vertices that have a path between the
specified vertex and the next.
Graphs
Notice how different this is than tree
traversal.
with tree traversal, we always visit all of the nodes
in the tree
with graph traversal we do not necessarily visit all
of the vertices in the graph unless the graph is
connected.
If a graph is not connected, then a graph traversal
that begins at a vertex will only visit a subset of the
graphs vertices.
Graphs
There are two basic graph-traversal
algorithms that we will discuss.
These algorithms visit the vertices in
different orders,
but if they both start at the same vertex,
they will visit the same set of vertices.
Depth first search
Breadth first search
Graphs
Depth-First Search
This algorithm starts at a specified vertex and
goes as deep into the graph as it can before
backtracking.
This means that after visiting the starting vertex,
it goes to an unvisited vertex that is adjacent to
the one just visited.
The algorithm continues from this way until it
has gotten as far as possible before returning to
visit the next unvisited vertex adjacent to the
starting place.
Graphs
Depth-First Search
This traversal algorithm does not completely
specify the order in which you should visit the
vertices adjacent to a particular vertex.
One possibility is to visit the vertices in sorted
order.
This only works - of course - when our nodes in
each linked list of an adjacency list are in sorted
order.
Graphs
b
c
Depth-First Search a
e
h
i g
f
Because the graph is connected, DFS will visit
every vertex. In fact, the traversal could visit the
vertices in this order:
a bcdgefhi
Notice a stack of vertices can be used to
implement this approach -- where the last one
visited is
Graphs
Breadth-First Search
This starts at a specified vertex and visits every vertex
adjacent to that vertex before embarking from any of
those vertices to the next set.
It does not embark from any of these vertices adjacent
to the starting vertex until it has visited all possible
vertices adjacent.
Notice that this is a first visited -- first explored strategy.
Therefore, it should be obvious that a queue of vertices
can be used
Graphs
b
c
Breadth-First Search a
e
h
i g
Future
WHAT IS FUZZY LOGIC?
Definition of fuzzy
Fuzzy not clear, distinct, or precise; blurred
Slow Fast
Speed = 0 Speed = 1
bool speed;
get the speed
if ( speed == 0) {
// speed is slow
}
else {
// speed is fast
}
FUZZY LOGIC REPRESENTATION
Slowest
For every problem
[ 0.0 0.25 ]
must represent in
terms of fuzzy sets.
Slow
What are fuzzy sets? [ 0.25 0.50 ]
Fast
[ 0.50 0.75 ]
Fastest
[ 0.75 1.00 ]
FUZZY LOGIC REPRESENTATION
CONT.
Neural Networks
systems.
FUZZY LOGIC IN CONTROL SYSTEMS
Some Examples
Temperature Controller
Business
Hybrid Modeling
Expert Systems
CONCLUSION
Insertion sort
another simple, but inefficient, sorting algorithm
The first iteration takes the second element in
the array and, if its less than the first element,
swaps it with the first element.
The second iteration looks at the third element
and inserts it into the correct position with
respect to the first two, so all three elements
are in order.
At the ith iteration of this algorithm, the first i
elements in the original array will be sorted.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
19.3.3 Merge Sort
Merge sort
efficient sorting algorithm
conceptually more complex than selection sort and insertion sort
Sorts an array by splitting it into two equal-sized subarrays,
sorting each subarray, then merging them into one larger
array.
The implementation of merge sort in this example is
recursive.
The base case is an array with one element, which is, of course,
sorted, so the merge sort immediately returns in this case.
The recursion step splits the array into two approximately equal
pieces, recursively sorts them, then merges the two sorted arrays
into one larger, sorted array.
Merge sort has an efficiency of O(n log n).
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
CS6382 Theory of Computation
Ding-Zhu Du
Office: ECSS 3-611, M 3:15-4:30
Lecture: ECSS 2.311, MW 12:30-1:45
Part I
Theory of Deterministic
Computation
Lecture 1
Deterministic Turing Machine (DTM)
tape
head
Finite Control
a l p h a B e
q p
q p
V = Q (s = ,h= )
0 1 B
s (p, 0, R) (s, 1, R) -
p (q, 0, R) (s, 1, R) -
q (q, 0, R) (q, 1, R) (h, B, R)
L(M) = (0+1)*00(0+1)*.
Theorem. Every regular set can be
accepted by a DTM.
Proof.
Every regular set can be accepted a
deterministic finite automata (DFA).
Every DFA can be simulated by a DTM.
Review on Regular Set
Regular sets on an alphabet is defined
recursively as follows
(1) The empty set is a regular set.
(2) For every symbol a in , {a} is a
regular set.
(3) If A and B are regular sets, then
A B, A U B, and A* are all regular
sets.
Review on DFA
tape
a b c d e f
head
finite control
The tape is divided into cells. Each cell contains
a symbol in an alphabet .
Q = Q U {h}, = U {B},
1 0, 1
0 0
s p q
1
L(M) = (0+1)*00(0+1)*.
Turing acceptable languages
Regular
languages
Why DTM can accept more languages than
DFA?
Because
The head can move in two directions. (No!)
The head can erase. (No!)
The head can write and move in two directions.
(Yes!)
Examples of DTM
L( M ) { x | x is accepted by M }
{ww R| w (0+1)*} is Turing-acceptable.
1, if x A
(x) = {
A 0, otherwise
{ ww R| w (0+1)*} is Turing-decidable.
(recursive)
Turing-acceptable
(r.e.)
regular
Various TMs
Allow the head not move
Theorem. If the head is allowed to stay at the
cell in each move, then every function
computed by the DTM is still Turing-
computable.
Proof. Consider DTM M=(Q,,,,s) where
: Q x Q x x {R, L, H} and H means
that the head stays at the current cell. We
construct M=(Q U Q, , , ,s) as follows:
Q = {q | q Q}
For q Q,
(q, a) = (p, b, R) if (q, a) = (p, b, R)
(q, a) = (p, b, L) if (q, a) = (p, b, L)
(q, a) = (p, b, R) if (q, a) = (p, b, H)
For p Q,
(p, a) = (p, a, L).
$
Consider a two-way DTM M=(Q, , , ,s).
Construct a DTM M = (Q U Q,,,,s) to
simulate M as follows:
Q={q | q Q}
={(a, b) | a, b } U { (B, $) }
={(a, B) | a }
For q Q,
(q, $) = (q,$,R)
(q, (a, c)) = (p,(b,c),D) if (q,a)=(p,b,D)
For q Q,
(q, $) = (q, $, R)
(q,(c,a)) = (p,(c,b),R) if (q,a)=(p,b,L)
(q,(c,a)) = (p,(c,b),L) if (q,a)=(p,b,R)
(q,(c,a)) = (p,(c,b),H) if (q,a)=(p,b,H)
Multi-tape DTM
Input tape
(read only)
Storage
tapes
Output tape
X head
tape
X head
tape
X head
To simulate a move of the multitape DTM, the one-tape
DTM needs two trips:
Trip 1: read all symbols at heads.
Trip 2: erase and write at cells scaned by heads.
Questions:
How many moves does one-tape DTM needs to
simulate t moves of a multitape DTM?
How many states does one-tape DTM needs to
simulate a multitape DTM?
Church-Turing Thesis
Any reasonably computable function
is a Turing-computable function.
Theorem. A language A is Turing-decidable iff both A
and its complement A are Turing-acceptable.
Proof. The forward direction is easy.
For the backward direction, suppose one-tape DTMs
M and M accept A and A respectively. Construct 4-
tape DTM M* as follows:
Use a storage tape to simulate M
and another storage tape to simulate M.
M* halts iff M or M halts.
If M halts, then M* outputs 1.
If M halts, then M* outputs 0.
School of Continuing Studies
CS 351: Introduction to
Computer Graphics
CS 351
What is Computer Graphics?
Creation, Manipulation, and Storage of
geometric objects (modeling) and their
images (rendering)
Display those images on screens or
hardcopy devices
Image processing
Others: GUI, Haptics, Displays (VR)...
What drives computer graphics?
Movie Industry
Leaders in quality and artistry
Not slaves to conceptual purity
Big budgets and tight schedules
Reminder that there is more to
CG than technology
Hey, How'd they do that?
Defines our expectations
Nanomanipulator, UNC
Joe Kniss, Utah Gordon Kindelman, Ut
What drives computer graphics?
Computer Aided Design
Mechanical, Electronic, Architecture,...
Drives the high end of the hardware market
Integration of computing and display resources
Reduced design cyles == faster systems, sooner
ProEngineer, www.ptc.com
What drives computer graphics?
Graphic User Interfaces (GUI)
www.webpagesthatsuck.com
Morning Evening
a preetham, e
Rendering Realism
Real Synthetic
m fajaro, usc
Terrain Modeling:
Snow and Trees Added
o deusson,
Rendering/Modeling Hair
http://www.rhythm.com/~ivan/hairRender.html
Humans
Faugeras et. al
360o Scan
View plane
P(xe, ye, ze)
P'(xs,ys, D)
C
(0,0,D)
D
Screen Space
Screen space is defined to act within a closed
volume called the viewing frustum that
delineates the volume of space which is to be
rendered
Objects that lie outside the viewing frustum
are not rendered
View Frustum
Homogeneous Coordinates
A point in three dimensional space requires 3 coordinates
- x, y and z - to describe its location
In homoegeneous coordinates, an extra coordinate (which
can be thought of as a scaling term) is added
By using homogeneous coordinates, we are able to
represent transformations as matrix multiplications
Then in order to compute the transformation of some
object, we need only perform matrix multiplications for
the vertices of the polygons making up the objects
representation
Homogeneous Coordinates
The transformations we are most interested in
are scaling, translation and rotation
These can be defined as follows
Scaling Transformation
Scaling Transformation
Translation Transformation
Translation Transformation
Rotation About the X-Axis
Rotation About the X-Axis
Homogeneous Coordinates
Rotations about the y and z axis are similar
A series of operations can be combined by
performing a series of multiplications
If the scaling factor is greater than one, the
resulting coordinates must be divided by that
number at the end of the operation
Perspective Transformation
The near plane is the view plane at distance D. The far
plane is at distance F
If the height of the view plane is 2h, then the perspective
transformation can be given by the following matrix:
1 0 0 0
0 1 0 1
0 0 hF/(D(F-D)) h/D
0 0 -hF/(F-D) 0
Perspective Transformation
This transformation can simply be
concatenated with all of the other
transformations in the rendering pipeline
Clipping is performed against the viewing
frustum
Objects lying completely outside the frustum are
discarded
Objects inside the frustum are transformed into
screen space and then rendered
Objects intersecting the frustum are clipped and
then transformed into screen space
Pixel-Level Processes
Once the objects in a scene have been
translated into screen space, the processing is
oriented towards pixels rather than polygons
Rasterization, hidden-surface removal and
shading are all pixel-level processes
Rasterization
Rasterization is the process of finding out which pixels a
polygon projects onto in screen space
Calculate, for each scan line within a polygon, by linear
interpolation, the x values of the edge pixels, xstart and xend
This results in a span of pixels between two edges that
have to be rendered
Care must be taken in these calculations, otherwise we
will have aliasing problems (e.g. a straight line may
appear to be a series of steps)
Most of these problems are caused by rounding errors in the interpolation of
polygon edges
Hidden Surface Removal
We now know which pixels contain which
objects, however since some pixels may
contain two or more objects we must calculate
which of these objects is visible and which are
hidden
Hidden surface removal is generally
accomplished using the Z-buffer algorithm
Hidden Surface Removal
In this algorithm, we set aside a two-dimensional array of
memory (the Z-buffer) of the same size as the screen (#rows x
#columns)
This is in addition to the buffer we will use to store the values
of pixels which will be displayed (color values)
The Z-buffer will hold values which are depths (or z-values)
The buffer is initialized so that each element has the value of
the far clipping plane (the largest possible z-value after
clipping has been performed)
The other buffer is initialized so that each element contains a
value which is the background color
Hidden Surface Removal
Now for each polygon we have a set of pixel values
which that polygon covers
For each one of these pixels, we compare its interpolated
depth (z-value) with the value of the corresponding
element already stored in the Z-buffer
If this value is less than the previously stored value, the pixel is nearer the
viewer than previously encountered pixels
Replace the old value of the Z- buffer with the new, interpolated value and
replace the old value of the other buffer with the value (color) of the pixel
Repeat for all polygons in the image
Interpolative or Incremental Shading
Interpolative or Incremental Shading
A major reason for the growth of popularity of
polygon-based renderers is the existence of
two interpolative or incremental shading
algorithms usually known as Gouraud shading
and Phong shading
Gouraud shading is faster than the other
method, but cannot produce accurate
highlights. It is usually used in applications
where speed is important
Interpolative or Incremental Shading
Phong shading gives higher quality images,
but is more expensive
Gouraud shading calculates intensities at
polygon vertices only, using a local reflection
model, and interpolates these for pixels within
the polygon
Phong shading interpolates vertex normals and
applies a local reflection model at each pixel
Interpolative or Incremental Shading
The motivation of both schemes is efficiency
and the convincing rendering of polygonal
objects
This means that as well as giving an
impression of solidity or three-dimensionality
to the model, the shared edges in adjacent
polygons that approximate a curved surface,
are made invisible
Gouraud Shading
Generally, the intensity of light at a polygon vertex is
described as a function of the orientation of vertex
normals with respect to both the light source and the eye
This function is called a reflection model
Gouraud shading applies a local reflection model at each
vertex of a polygon to calculate a set of vertex intensities
These intensities are linearly interpolated across the
polygon interior on a scan line basis
Phong Shading
In Phong shading, the vertex normals
(calculated exactly as in Gouraud shading) are
linearly interpolated
The local reflection model is then applied at
each pixel using the interpolated normal
This solves the highlight problem and Mach
banding, but is more computationally
expensive